text
stringlengths
8
6.88M
#include <pybind11/pybind11.h> #include <pybind11/eigen.h> #include <pybind11/stl.h> #include <rmf_traffic/agv/VehicleTraits.hpp> #include <rmf_traffic/Profile.hpp> namespace py = pybind11; using VehicleTraits = rmf_traffic::agv::VehicleTraits; using Profile = rmf_traffic::Profile; using ConstFinalConvexShapePtr = rmf_traffic::geometry::ConstFinalConvexShapePtr; void bind_vehicletraits(py::module &m) { auto m_vehicletraits = m.def_submodule("vehicletraits"); // LIMITS ==================================================================== py::class_<VehicleTraits::Limits>(m_vehicletraits, "Limits") .def(py::init<double, double>(), py::arg("velocity") = 0.0, py::arg("acceleration") = 0.0) .def_property("nominal_velocity", &VehicleTraits::Limits::get_nominal_velocity, &VehicleTraits::Limits::set_nominal_velocity) .def_property("nominal_acceleration", &VehicleTraits::Limits::get_nominal_acceleration, &VehicleTraits::Limits::set_nominal_acceleration) .def_property_readonly("valid", &VehicleTraits::Limits::valid); // STEERING ================================================================== py::enum_<VehicleTraits::Steering>(m_vehicletraits, "Steering") .value("Differential", VehicleTraits::Steering::Differential) .value("Holonomic", VehicleTraits::Steering::Holonomic); // DIFFERENTIAL ============================================================== py::class_<VehicleTraits::Differential>(m_vehicletraits, "Differential") .def(py::init<Eigen::Vector2d, bool>(), py::arg("forward") = Eigen::Vector2d::UnitX(), py::arg("reversible") = true) .def_property("forward", &VehicleTraits::Differential::get_forward, &VehicleTraits::Differential::set_forward) .def_property("reversible", &VehicleTraits::Differential::is_reversible, &VehicleTraits::Differential::set_reversible) .def_property_readonly("valid", &VehicleTraits::Differential::valid); // HOLONOMIC ================================================================= py::class_<VehicleTraits::Holonomic>(m_vehicletraits, "Holonomic") .def(py::init<>()); // PROFILE =================================================================== py::class_<Profile>(m_vehicletraits, "Profile") .def(py::init<ConstFinalConvexShapePtr, ConstFinalConvexShapePtr>(), py::arg("footprint"), py::arg("vicinity") = ( ConstFinalConvexShapePtr) nullptr) .def_property("footprint", py::overload_cast<>(&Profile::footprint, py::const_), py::overload_cast<ConstFinalConvexShapePtr>( &Profile::footprint)) .def_property("vicinity", py::overload_cast<>(&Profile::vicinity, py::const_), py::overload_cast<ConstFinalConvexShapePtr>( &Profile::vicinity)); // VEHICLETRAITS ============================================================= py::class_<VehicleTraits>(m_vehicletraits, "VehicleTraits") .def(py::init<VehicleTraits::Limits, VehicleTraits::Limits, Profile, VehicleTraits::Differential >(), py::arg("linear"), py::arg("angular"), py::arg("profile"), py::arg("steering") = VehicleTraits::Differential()) .def_property("linear", py::overload_cast<>(&VehicleTraits::linear, py::const_), py::overload_cast<>(&VehicleTraits::linear)) .def_property("rotational", py::overload_cast<>(&VehicleTraits::rotational, py::const_), py::overload_cast<>(&VehicleTraits::rotational)) .def_property("profile", py::overload_cast<>(&VehicleTraits::profile, py::const_), py::overload_cast<>(&VehicleTraits::profile)) .def_property_readonly("steering", &VehicleTraits::get_steering) .def_property("differential", py::overload_cast<>(&VehicleTraits::get_differential), &VehicleTraits::set_differential) .def_property_readonly("const_differential", py::overload_cast<>(&VehicleTraits::get_differential, py::const_)) .def_property("holonomic", py::overload_cast<>(&VehicleTraits::get_holonomic), &VehicleTraits::set_holonomic) .def_property_readonly("const_holonomic", py::overload_cast<>(&VehicleTraits::get_holonomic, py::const_)) .def_property_readonly("valid", &VehicleTraits::valid); }
/** * AddressBookType.h * [Insert Description of File] * * Written by: Mathew Larribas * Date: 11/13/2013 ******************************************************************************/ #include <iostream> #include <fstream> #include "orderedlinkedlist.h" #include "ExtPersonType.h" using namespace std; class AddressBookType : public orderedLinkedList<ExtPersonType> { public: void print(); void printNameInTheMonth(int); int search(string); void printInfoOf(string); void printNamesWithStatus(string); void printAt(int); void printNamesBetweenLastNames(string, string); void saveData(ofstream&); bool lexicalCompare(string, string); void AddressBookType::deletePerson(const string firstName, const string lastName); nodeType<ExtPersonType>* firstNode(); AddressBookType(); }; // ========================================================================== // // Constructor - Default AddressBookType::AddressBookType() { // Intentionally left blank } // ========================================================================== // // Print - Default void AddressBookType::print() { nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return; } while (currentNode != NULL) { currentNode->info.printInfo(); cout << endl; currentNode = currentNode->link; } } // -------------------------------------------------------------- // Print - Name In The Month void AddressBookType::printNameInTheMonth(int month) { nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return; } while (currentNode != NULL) { if (currentNode->info.getDate().getMonth() == month) currentNode->info.print(); currentNode = currentNode->link; } } // -------------------------------------------------------------- // Print - Info Of void AddressBookType::printInfoOf(string lastName) { nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return; } int index = search(lastName); if (index != -1) { for (int i = 0; i < index; i++) currentNode = currentNode->link; currentNode->info.printInfo(); } else { cout << "Person not found!" << endl << endl; } } // -------------------------------------------------------------- // Print - Names with Status void AddressBookType::printNamesWithStatus(string status) { nodeType<ExtPersonType> *currentNode = first; while (currentNode != NULL) { if (currentNode->info.getStatus() == status) currentNode->info.print(); currentNode = currentNode->link; } } // -------------------------------------------------------------- // Print - Print At void AddressBookType::printAt(int index) { nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return; } // Progress the node to the correct index for (int i = 0; i < index; i++) { currentNode = currentNode->link; // Check to see if the index is out of bounds if (currentNode == NULL) { cout << "Index out of bounds!" << endl << endl; return; } } // Print the information of the node currentNode->info.printInfo(); } nodeType<ExtPersonType>* AddressBookType::firstNode() { if (first != NULL) return first; else { cout << "No list is present!" << endl << endl; return NULL; } } // -------------------------------------------------------------- // Print - Print Names Between Last Names void AddressBookType::printNamesBetweenLastNames(string s1, string s2) { nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return; } while (currentNode != NULL) { string lastName = currentNode->info.getLastName(); if (lexicalCompare(lastName, s1) && lexicalCompare(s2, lastName)) currentNode->info.print(); currentNode = currentNode->link; } } bool AddressBookType::lexicalCompare(string s1, string s2) { if (s1 == s2) return true; int i = 0; for (;;) { if (NULL == s1[i]) return false; if (NULL == s2[i]) return true; char a, b; a = tolower(s1[i]); b = tolower(s2[i]); if (a < b) return false; if (b < a) return true; i++; } } // ========================================================================== // // Search int AddressBookType::search(string lastName) { int index = 0; nodeType<ExtPersonType> *currentNode; if (!(currentNode = firstNode())) { return -1; } while (currentNode != NULL) { if (currentNode->info.getLastName() == lastName) return index; currentNode = currentNode->link; index++; } return -1; } // ========================================================================== // // Save Data void AddressBookType::saveData(ofstream& outFile) { nodeType<ExtPersonType> *currentNode; currentNode = firstNode(); int entryCount = 0; while (currentNode != NULL) { DateType d = currentNode->info.getDate(); AddressType a = currentNode->info.getAddress(); string aMembers[4]; a.getAddress(aMembers[0], aMembers[1], aMembers[2], aMembers[3]); outFile << currentNode->info.getFirstName() << " " << currentNode->info.getLastName() << endl; outFile << d.getMonth() << " " << d.getDay() << " " << d.getYear() << endl; outFile << aMembers[0] << endl; outFile << aMembers[1] << endl; outFile << aMembers[2] << endl; outFile << aMembers[3] << endl; outFile << currentNode->info.getPhoneNumber() << endl; outFile << currentNode->info.getStatus(); if (entryCount++ + 1 != this->count) outFile << endl; currentNode = currentNode->link; } } //==========================================================================================// //DeletingPerson void AddressBookType::deletePerson(const string firstName, const string lastName) { ExtPersonType personInList; nodeType<ExtPersonType> *currentNode; currentNode = firstNode(); while (currentNode != NULL) { if (currentNode->info.getFirstName() == firstName && currentNode->info.getLastName() == lastName) { personInList = currentNode->info; this->deleteNode(personInList); cout << firstName << " " << lastName << " has been deleted. " << endl << endl; return; } currentNode = currentNode->link; } cout << firstName << " " << lastName << " was not found. " << endl << endl; }
//Inline function /* C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality. To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function. The compiler can ignore the inline qualifier in case defined function is more than a line. */ #include<iostream> using namespace std; inline int max(int x,int y) { return (x>y) ? x:y; } int main() { cout<<"Max(20,10) is : "<<max(20,10)<<endl; cout<<"Max(1000,10) is : "<<max(100,10)<<endl; cout<<"Max(20,1000) is : "<<max(20,1000)<<endl; return 0; }
#ifndef ROSE_JAVA_SUPPORT #define ROSE_JAVA_SUPPORT // Remove this !! //extern SgGlobal *getGlobalScope(); extern SgGlobal *globalScope; extern SgClassType *ObjectClassType; extern SgClassDefinition *ObjectClassDefinition; // This is used for both Fortran and Java support to point to the current SgSourceFile. extern SgSourceFile *OpenFortranParser_globalFilePointer; #include "jni_JavaSourceCodePosition.h" #include "token.h" // Control output from Fortran parser #define DEBUG_JAVA_SUPPORT true #define DEBUG_RULE_COMMENT_LEVEL 1 #define DEBUG_COMMENT_LEVEL 2 // Global stack of expressions, types and statements class ComponentStack : private std::list<SgNode *> { public: void push(SgNode *n) { if (SgProject::get_verbose() > 0) { std::cerr << "***Pushing node " << n -> class_name() << std::endl; std::cerr.flush(); } push_front(n); } SgNode *pop() { ROSE_ASSERT(size() > 0); SgNode *n = front(); if (SgProject::get_verbose() > 0) { std::cerr << "***Popping node " << n -> class_name() << std::endl; std::cerr.flush(); } pop_front(); return n; } SgNode *top() { ROSE_ASSERT(size() > 0); return front(); } bool empty() { return (size() == 0); } size_type size() { return std::list<SgNode*>::size(); } std::list<SgNode *>::iterator begin() { return std::list<SgNode *>::begin(); } std::list<SgNode *>::iterator end() { return std::list<SgNode *>::end(); } std::list<SgNode *>::reverse_iterator rbegin() { return std::list<SgNode *>::rbegin(); } std::list<SgNode *>::reverse_iterator rend() { return std::list<SgNode *>::rend(); } SgExpression *popExpression() { SgNode *n = pop(); if (! isSgExpression(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgExpression" << std::endl; ROSE_ASSERT(false); } return (SgExpression *) n; } SgStatement *popStatement() { SgNode *n = pop(); if (isSgExpression(n)) { if (SgProject::get_verbose() > 0) { std::cerr << "***Turning node " << n -> class_name() << " into a SgExprStatement" << std::endl; } // TODO: set source position for expr statement !!!? n = SageBuilder::buildExprStatement((SgExpression *) n); } else if (! isSgStatement(n)) { std::cerr << "Invalid attemtp to pop a node of type " << n -> class_name() << " as an SgStatement" << std::endl; ROSE_ASSERT(false); } return (SgStatement *) n; } SgType *popType() { SgNode *n = pop(); if (! isSgType(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgType" << std::endl; ROSE_ASSERT(false); } return (SgType *) n; } }; // Global stack of scope elements. class ScopeStack : private std::list<SgScopeStatement *> { public: void push(SgScopeStatement *n) { if (SgProject::get_verbose() > 0) { std::cerr << "***Pushing node " << n -> class_name() << std::endl; std::cerr.flush(); } push_front(n); } SgScopeStatement *pop() { ROSE_ASSERT(size() > 0); SgScopeStatement *n = front(); if (SgProject::get_verbose() > 0) { std::cerr << "***Popping node " << n -> class_name() << std::endl; std::cerr.flush(); } pop_front(); return n; } SgGlobal *popGlobal() { SgScopeStatement *n = pop(); if (! isSgGlobal(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgGlobal" << std::endl; ROSE_ASSERT(false); } return (SgGlobal *) n; } SgNamespaceDefinitionStatement *popNamespaceDefinitionStatement() { SgScopeStatement *n = pop(); if (! isSgNamespaceDefinitionStatement(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgNamespaceDefinitionStatement" << std::endl; ROSE_ASSERT(false); } return (SgNamespaceDefinitionStatement *) n; } SgClassDefinition *popClassDefinition() { SgScopeStatement *n = pop(); if (! isSgClassDefinition(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgClassDefinition" << std::endl; ROSE_ASSERT(false); } return (SgClassDefinition *) n; } SgBasicBlock *popBasicBlock() { SgScopeStatement *n = pop(); if (! isSgBasicBlock(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgBasicBlock" << std::endl; ROSE_ASSERT(false); } return (SgBasicBlock *) n; } SgIfStmt *popIfStmt() { SgScopeStatement *n = pop(); if (! isSgIfStmt(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgIfStmt" << std::endl; ROSE_ASSERT(false); } return (SgIfStmt *) n; } SgSwitchStatement *popSwitchStatement() { SgScopeStatement *n = pop(); if (! isSgSwitchStatement(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgSwitchStatement" << std::endl; ROSE_ASSERT(false); } return (SgSwitchStatement *) n; } SgCatchOptionStmt *popCatchOptionStmt() { SgScopeStatement *n = pop(); if (! isSgCatchOptionStmt(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgCatchOptionStmt" << std::endl; ROSE_ASSERT(false); } return (SgCatchOptionStmt *) n; } SgWhileStmt *popWhileStmt() { SgScopeStatement *n = pop(); if (! isSgWhileStmt(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgWhileStmt" << std::endl; ROSE_ASSERT(false); } return (SgWhileStmt *) n; } SgDoWhileStmt *popDoWhileStmt() { SgScopeStatement *n = pop(); if (! isSgDoWhileStmt(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgDoWhileStmt" << std::endl; ROSE_ASSERT(false); } return (SgDoWhileStmt *) n; } SgForStatement *popForStatement() { SgScopeStatement *n = pop(); if (! isSgForStatement(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgForStatement" << std::endl; ROSE_ASSERT(false); } return (SgForStatement *) n; } SgJavaForEachStatement *popJavaForEachStatement() { SgScopeStatement *n = pop(); if (! isSgJavaForEachStatement(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgJavaForEachStatement" << std::endl; ROSE_ASSERT(false); } return (SgJavaForEachStatement *) n; } SgJavaLabelStatement *popJavaLabelStatement() { SgScopeStatement *n = pop(); if (! isSgJavaLabelStatement(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgJavaLabelStatement" << std::endl; ROSE_ASSERT(false); } return (SgJavaLabelStatement *) n; } SgFunctionDefinition *popFunctionDefinition() { SgScopeStatement *n = pop(); if (! isSgFunctionDefinition(n)) { std::cerr << "Invalid attempt to pop a node of type " << n -> class_name() << " as an SgFunctionDefinition" << std::endl; ROSE_ASSERT(false); } return (SgFunctionDefinition *) n; } SgScopeStatement *top() { ROSE_ASSERT(size() > 0); return (SgScopeStatement *) front(); } bool empty() { return (size() == 0); } size_type size() { return std::list<SgScopeStatement *>::size(); } std::list<SgScopeStatement *>::iterator begin() { return std::list<SgScopeStatement *>::begin(); } std::list<SgScopeStatement *>::iterator end() { return std::list<SgScopeStatement *>::end(); } std::list<SgScopeStatement *>::reverse_iterator rbegin() { return std::list<SgScopeStatement *>::rbegin(); } std::list<SgScopeStatement *>::reverse_iterator rend() { return std::list<SgScopeStatement *>::rend(); } }; // Global stack of AST components: Expressions, statements, types, etc... extern ComponentStack astJavaComponentStack; // Global stack of scopes extern ScopeStack /* std::list<SgScopeStatement*> */ astJavaScopeStack; // Global list of implicit classes extern std::list<SgName> astJavaImplicitClassList; std::list<SgStatement*> pop_from_stack_and_reverse(std::list<SgStatement*> &l, int nb_pop); /* Create a token from a JavaToken jni object. Also converts JavaSourceCodeInformation to C */ Token_t *create_token(JNIEnv *env, jobject jToken); void pushAndSetSourceCodePosition(JavaSourceCodePosition *pos, SgLocatedNode *sgnode); // Duplicated setJavaSourcePosition signature. // Not sure why but JNI wasn't happy if posInfo was assigned to a default value void setJavaSourcePosition(SgLocatedNode *locatedNode); void setJavaSourcePosition(SgLocatedNode *locatedNode, JavaSourceCodePosition *posInfo); // DQ (8/16/2011): Added support using the jToken object. void setJavaSourcePosition(SgLocatedNode *locatedNode, JNIEnv *env, jobject jToken); // DQ (8/16/2011): Added support for marking nodes as compiler generated (implicit in Java). void setJavaCompilerGenerated(SgLocatedNode *locatedNode); void setJavaSourcePositionUnavailableInFrontend(SgLocatedNode *locatedNode); //! This is how Java implicit classes are marked so that they can be avoided in output. void setJavaFrontendSpecific(SgLocatedNode *locatedNode); // ********************************************* std::string convertJavaStringToCxxString (JNIEnv *env, const jstring &java_string); int convertJavaIntegerToCxxInteger(JNIEnv *env, const jint &java_integer); bool convertJavaBooleanToCxxBoolean(JNIEnv *env, const jboolean &java_boolean); // Specify the SgClassDefinition explicitly so that implicit classes are simpler to build. // SgMemberFunctionDeclaration *buildSimpleMemberFunction(const SgName &name); // SgMemberFunctionDeclaration *buildSimpleMemberFunction(const SgName &name, SgClassDefinition *classDefinition); // DQ (3/25/2011): These will replace buildSimpleMemberFunction shortly. SgMemberFunctionDeclaration *buildNonDefiningMemberFunction(const SgName &inputName, SgClassDefinition *classDefinition, int num_arguments); SgMemberFunctionDeclaration *buildDefiningMemberFunction (const SgName &inputName, SgClassDefinition *classDefinition, int num_arguments); // Build a simple class in the current scope and set the scope to be the class definition. void buildClass (const SgName &className, Token_t *token); void buildImplicitClass (const SgName &className); void buildClassSupport (const SgName &className, bool implicitClass, Token_t *token); SgVariableDeclaration *buildSimpleVariableDeclaration(const SgName &name, SgType *type); std::list<SgName> generateQualifierList (const SgName &classNameWithQualification); SgName stripQualifiers (const SgName &classNameWithQualification); // It might be that this function should take a "const SgName &" instead of a "std::string". SgClassSymbol *lookupSymbolFromQualifiedName(std::string className); SgClassType *lookupTypeFromQualifiedName(std::string className); //! Support to get current class scope. SgClassDefinition *getCurrentClassDefinition(); //! Strips off "#RAW" suffix from raw types (support for Java 1.5 and greater). SgName processNameOfRawType(SgName name); //! Support for identification of symbols using simple names in a given scope. SgSymbol *lookupSimpleNameInClassScope(const SgName &name, SgClassDefinition *classDefinition); //! Support for identification of symbols using simple names. SgVariableSymbol *lookupVariableByName(const SgName &name); //! Support for identification of symbols using qualified names (used by the import statement). SgSymbol *lookupSymbolInParentScopesUsingQualifiedName(SgName qualifiedName, SgScopeStatement *currentScope); //! charles4: Support for identification of symbols using qualified names (used by the import statement). //SgSymbol *FindSymbolInParentScopesUsingQualifiedName(SgName qualifiedName, SgScopeStatement *currentScope); //! charles4: 02/15/2012 //SgSymbol *lookupSymbolInParentScopesUsingSimpleName(SgName name, SgScopeStatement *currentScope); //! Refactored support to extraction of associated scope from symbol (where possible, i.e. SgClassSymbol, etc.). SgScopeStatement *get_scope_from_symbol(SgSymbol *returnSymbol); // *********************************************************** // Template Definitions (required to be in the header files) // *********************************************************** template< class T > void unaryExpressionSupport() { SgExpression *operand = astJavaComponentStack.popExpression(); // Build the assignment operator and push it onto the stack. // SgExpression *assignmentExpression = SageBuilder::buildUnaryExpression<T>(operand); SgExpression *resultExpression = SageBuilder::buildUnaryExpression<T>(operand); ROSE_ASSERT(resultExpression != NULL); astJavaComponentStack.push(resultExpression); } template< class T > void binaryExpressionSupport() { SgExpression *rhs = astJavaComponentStack.popExpression(); ROSE_ASSERT(rhs != NULL); SgExpression *lhs = astJavaComponentStack.popExpression(); ROSE_ASSERT(lhs != NULL); // Build the assignment operator and push it onto the stack. // SgExpression *assignmentExpression = SageBuilder::buildBinaryExpression<T>(lhs, rhs); SgExpression *resultExpression = SageBuilder::buildBinaryExpression<T>(lhs, rhs); ROSE_ASSERT(resultExpression != NULL); astJavaComponentStack.push(resultExpression); } // endif for ROSE_JAVA_SUPPORT #endif
#ifndef PARAMEDITOUTPUT_H #define PARAMEDITOUTPUT_H #include <QWidget> #include "configparams.h" namespace Ui { class ParamEditOutput; } class ParamEditOutput : public QWidget { Q_OBJECT public: explicit ParamEditOutput(QWidget *parent = nullptr); ~ParamEditOutput(); void setConfig(ConfigParams *config); QString name() const; void setName(const QString &name); private slots: void paramChangedOutput(QObject *src, QString name, int newParam); void on_readButton_clicked(); void on_readDefaultButton_clicked(); void on_helpButton_clicked(); void on_valueBox_currentIndexChanged(int index); private: Ui::ParamEditOutput *ui; ConfigParams *mConfig; QString mName; }; #endif // PARAMEDITOUTPUT_H
#ifndef OBJECT_H #define OBJECT_H #include"TextureManager.h" class Object { private: SDL_Rect src; SDL_Rect dest; SDL_Rect* source = &src; SDL_Rect* destination = &dest; SDL_Texture* Tex; public: SDL_Texture* getTexture(); SDL_Rect* getSrc(); SDL_Rect* getDest(); void setSrc(int x, int y, int h, int w); void setDest(int x, int y, int h, int w); void SetBlendMode(SDL_BlendMode blending); void SetAlpha(Uint8 alpha); void CreateTexture(const char* address, SDL_Renderer* ren); void virtual Render(SDL_Renderer* ren)=0; }; #endif
#include <cassert> #include "TestUtils.h" #include "Utils.h" void cpp_class2_test::testAreEqualFloat() { const float mocka=100.0001f, mockb=100.f; const bool areEqual= cpp_class2::areEqual(mocka, mockb); assert(!areEqual); } void cpp_class2_test::testAreEqualDouble() { const double mocka = 100.0000001, mockb = 100.; const bool areEqual = cpp_class2::areEqual(mocka, mockb); assert(!areEqual); }
#ifndef CCONFIGMANAGER_H #define CCONFIGMANAGER_H #include "model/cdatetime.h" #include "model/cdatetimebuilder.h" class CConfigManager { public: enum DATE_DISPLAY_CONFIG { DATE_DISPLAY_CONFIG_LONG = 0, //default DATE_DISPLAY_CONFIG_SHORT, DATE_DISPLAY_CONFIG_MAX }; enum TIME_DISPLAY_CONFIG { TIME_DISPLAY_CONFIG_LONG = 0, //default TIME_DISPLAY_CONFIG_SHORT, TIME_DISPLAY_CONFIG_MAX }; public: CConfigManager(); virtual ~CConfigManager() {} virtual void updateTimeDisplayConfig(TIME_DISPLAY_CONFIG config) { this->mTimeDisplayConfig = config; } virtual void updateDateDisplayConfig(DATE_DISPLAY_CONFIG config) { this->mDateDisplayConfig = config; } virtual const CDateTimeBuilder* createDateTimeBuilder(CDateTime* dateTime); protected: protected: DATE_DISPLAY_CONFIG mDateDisplayConfig; TIME_DISPLAY_CONFIG mTimeDisplayConfig; CDateTimeBuilder* mDateTimeBuilder; }; #endif // CCONFIGMANAGER_H
#include <fstream> #include "cpu.h" #include "log.h" #include "font.h" #include "defines.h" chip8::CPU::CPU() : program_counter(START_ADDRESS) { log_subsys::Init(); for (size_t i = 0; i < 0x10; ++i) { table[i] = &CPU::OP_NOP; } for(size_t i = 0; i < 0xF; ++i) { table0[i] = &CPU::OP_NOP; } for (size_t i = 0; i < 0xF; ++i) { tableE[i] = &CPU::OP_NOP; } for (size_t i = 0; i < 0x66; ++i) { tableF[i] = &CPU::OP_NOP; } table[0x0] = &CPU::Table0; table[0x1] = &CPU::OP_1nnn; table[0x2] = &CPU::OP_2nnn; table[0x3] = &CPU::OP_3xkk; table[0x4] = &CPU::OP_4xkk; table[0x5] = &CPU::OP_5xy0; table[0x6] = &CPU::OP_6xkk; table[0x7] = &CPU::OP_7xkk; table[0x8] = &CPU::Table8; table[0x9] = &CPU::OP_9xy0; table[0xA] = &CPU::OP_Annn; table[0xB] = &CPU::OP_Bnnn; table[0xC] = &CPU::OP_Cxkk; table[0xD] = &CPU::OP_Dxyn; table[0xE] = &CPU::TableE; table[0xF] = &CPU::TableF; table0[0x0] = &CPU::OP_00E0; table0[0xE] = &CPU::OP_00EE; table8[0x0] = &CPU::OP_8xy0; table8[0x1] = &CPU::OP_8xy1; table8[0x2] = &CPU::OP_8xy2; table8[0x3] = &CPU::OP_8xy3; table8[0x4] = &CPU::OP_8xy4; table8[0x5] = &CPU::OP_8xy5; table8[0x6] = &CPU::OP_8xy6; table8[0x7] = &CPU::OP_8xy7; table8[0xE] = &CPU::OP_8xyE; tableE[0x1] = &CPU::OP_ExA1; tableE[0xE] = &CPU::OP_Ex9E; tableF[0x07] = &CPU::OP_Fx07; tableF[0x0A] = &CPU::OP_Fx0A; tableF[0x15] = &CPU::OP_Fx15; tableF[0x18] = &CPU::OP_Fx18; tableF[0x1E] = &CPU::OP_Fx1E; tableF[0x29] = &CPU::OP_Fx29; tableF[0x33] = &CPU::OP_Fx33; tableF[0x55] = &CPU::OP_Fx55; tableF[0x65] = &CPU::OP_Fx65; C8_INFO("STARTING CPU AT ADDRESS {}...", reinterpret_cast<void*>(this)); for (size_t i = 0; i < FONTSET_SZ; ++i) { memory.at(FONTSET_START + i) = fontset[i]; } } void chip8::CPU::LoadROM(const std::string& filename) { const auto buffer = new char[8192]; std::ifstream file(filename, std::ios::binary); file.rdbuf()->pubsetbuf(buffer, 8192); C8_INFO("Opening file {}", filename); if (file.is_open()) { std::string file_contents((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); for (size_t i = 0; i < file_contents.size(); ++i) { memory.at(START_ADDRESS + i) = file_contents.at(i); } file.close(); C8_INFO("File loaded sucessfully!"); } else { file.close(); C8_ERROR("FAILED TO OPEN FILE {}, BAILING OUT!", filename); delete[] buffer; exit(0); } delete[] buffer; }
#ifndef NAIMP_H #define NAIMP_H /// @file NaImp.h /// @brief NaImp のヘッダファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2012 Yusuke Matsunaga /// All rights reserved. #include "YmNetworks/bdn.h" BEGIN_NAMESPACE_YM_NETWORKS class ImpMgr; class ImpInfo; ////////////////////////////////////////////////////////////////////// /// @class NaImp NaImp.h "NaImp.h" /// @brief 構造を用いた間接含意エンジン ////////////////////////////////////////////////////////////////////// class NaImp { public: /// @brief コンストラクタ NaImp(); /// @brief デストラクタ ~NaImp(); /// @brief 直接含意を用いるかどうかのフラグをセットする. void use_di(bool use); /// @brief 対偶の関係を用いるかどうかのフラグをセットする. void use_contra(bool use); /// @brief cap_merge2 を用いるかどうかのフラグをセットする. void use_cap_merge2(bool use); public: ////////////////////////////////////////////////////////////////////// // 外部インターフェイスの宣言 ////////////////////////////////////////////////////////////////////// /// @brief ネットワーク中の間接含意を求める. /// @param[in] imp_mgr マネージャ /// @param[out] imp_info 間接含意のリスト virtual void learning(ImpMgr& imp_mgr, ImpInfo& imp_info); private: ////////////////////////////////////////////////////////////////////// // データメンバ ////////////////////////////////////////////////////////////////////// // 直接含意を用いるかどうかのフラグ bool mUseDI; // 対偶の関係を用いるかどうかのフラグ bool mUseContra; // cap_merge2 を用いるかどうかのフラグ bool mUseCapMerge2; }; END_NAMESPACE_YM_NETWORKS #endif // NAIMP_H
#pragma once #include <vector> #include "geometry/Point.hpp" class IPositionable; class IPositionableListener { public: virtual void changed(IPositionable& ipos, const Point& newPosition) = 0; }; class IPositionable { Point position; const Point* oldPosition; std::vector<IPositionableListener*> listeners; void notify(); public: IPositionable(Point initialPosition = Point()); virtual ~IPositionable(); bool move(const Point& offset, bool force = false); bool setPosition(const Point& newPosition, bool force = false); void addListener(IPositionableListener* iposListener); virtual bool consider(const Point& newPosition) = 0; /** * @brief Called after the position of the IPositionable has changed. Default * implementation does nothing. * * @param oldPosition The previous position. */ virtual void changed(const Point& oldPosition); const Point& getPosition() const; const Point& getOldPosition() const; inline friend bool operator==(const IPositionable& lhs, const IPositionable& rhs); inline friend bool operator!=(const IPositionable& lhs, const IPositionable& rhs); };
// AUTHOR: Sumit Prajapati #include <bits/stdc++.h> using namespace std; #define ull unsigned long long #define ll long long #define pii pair<int, int> #define pll pair<ll, ll> #define pb push_back #define mk make_pair #define ff first #define ss second #define all(a) a.begin(),a.end() #define trav(x,v) for(auto &x:v) #define debug(x) cerr<<#x<<" = "<<x<<'\n' #define llrand() distribution(generator) #define rep(i,n) for(int i=0;i<n;i++) #define repe(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=a;i<=b;i++) #define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n' #define endl '\n' #define curtime chrono::high_resolution_clock::now() #define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count() #define INF 1'000'000'000 #define MD 1'000'000'007 #define MDL 998244353 #define MX 30005 auto time0 = curtime; random_device rd; default_random_engine generator(rd()); uniform_int_distribution<ull> distribution(0,0xFFFFFFFFFFFFFFFF); //Is testcase present? string s[MX]; void printvec(vector<int>& v){ for(auto& el:v) cout<<el<<" "; cout<<'\n'; } ll fn(vector<int>& a,ll l,ll r){ if(l>=r) return 0; ll mid=(l+r)>>1; vector<int>Le,Ri; rep(i,mid-l+1) Le.pb(a[i]); FOR(i,mid-l+1,r-l) Ri.pb(a[i]); ll lef=fn(Le,l,mid),rig=fn(Ri,mid+1,r); int i=0,j=0; ll cnt=0; ll count=0; int szi=Le.size(),szj=Ri.size(); while(i<szi && j<szj ){ if(Le[i]<Ri[j]){ a[cnt++]=Le[i]; i++; } else{ count+=(szi-i); a[cnt++]=Ri[j]; j++; } } while(i<szi) a[cnt++]=(Le[i]),i++; while(j<szj) a[cnt++]=(Ri[j]),j++; // cout<<l<<" "<<r<<"--\n"; // printvec(a); // printvec(Le); // printvec(Ri); // cout<<"-------\n"; return lef+rig+count; } void solve(){ int n; cin>>n; rep(i,n) cin>>s[i]; string temp; map<string,int>mp; rep(i,n){ cin>>temp; mp[temp]=i; } vector<int> a(n); rep(i,n) a[i]=mp[s[i]]; // printvec(a); ll ans=fn(a,0,n-1); // printvec(a); cout<<ans<<'\n'; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); time0 = curtime; int t=1; cin>>t; repe(tt,t){ //cout<<"Case #"<<tt<<": "; solve(); } //cerr<<"Execution Time: "<<timedif(time0,curtime)*1e-9<<" sec\n"; return 0; }
// CkSFtpDir.h: interface for the CkSFtpDir class. // ////////////////////////////////////////////////////////////////////// // This header is generated. #ifndef _CkSFtpDir_H #define _CkSFtpDir_H #include "chilkatDefs.h" #include "CkString.h" #include "CkMultiByteBase.h" class CkSFtpFile; #ifndef __sun__ #pragma pack (push, 8) #endif // CLASS: CkSFtpDir class CkSFtpDir : public CkMultiByteBase { private: // Don't allow assignment or copying these objects. CkSFtpDir(const CkSFtpDir &); CkSFtpDir &operator=(const CkSFtpDir &); public: CkSFtpDir(void); virtual ~CkSFtpDir(void); static CkSFtpDir *createNew(void); void inject(void *impl); // May be called when finished with the object to free/dispose of any // internal resources held by the object. void dispose(void); // BEGIN PUBLIC INTERFACE // ---------------------- // Properties // ---------------------- int get_NumFilesAndDirs(void); void get_OriginalPath(CkString &str); const char *originalPath(void); // ---------------------- // Methods // ---------------------- CkSFtpFile *GetFileObject(int index); bool GetFilename(int index, CkString &outStr); const char *getFilename(int index); const char *filename(int index); // END PUBLIC INTERFACE }; #ifndef __sun__ #pragma pack (pop) #endif #endif
/*************************************************************************** paginafuentes.cpp - description ------------------- begin : mar 24 2004 copyright : (C) 2004 by Oscar G. Duarte email : ogduarte@ing.unal.edu.co ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "paginafuentes.h" BEGIN_EVENT_TABLE(PaginaFuentes, wxPanel) EVT_PAINT(PaginaFuentes::OnPaint) EVT_BUTTON(DLG_PAGFTE_BTN_EDITAR, PaginaFuentes::editarFte) EVT_BUTTON(DLG_PAGFTE_BTN_APLICAR, PaginaFuentes::aplicar) EVT_LISTBOX(DLG_PAGFTE_LISTBOX, PaginaFuentes::seleccionarFte) END_EVENT_TABLE() PaginaFuentes::PaginaFuentes(MiCanvas *canvas, wxWindow *parent,const wxString& title) :wxPanel(parent,-1) { Canvas=canvas; recargar(); // SetTitle(wxT("Configuración de la Interfaz")); crearPagFuentes(); } PaginaFuentes::~PaginaFuentes() { } void PaginaFuentes::crearPagFuentes() { wxPanel *PagFuentes = this; ButtonEditarFte =new wxButton (PagFuentes,DLG_PAGFTE_BTN_EDITAR, wxT("Editar")); ButtonAplicarFte =new wxButton (PagFuentes,DLG_PAGFTE_BTN_APLICAR, wxT("Aplicar")); ListBoxItemsFte =new wxListBox (PagFuentes,DLG_PAGFTE_LISTBOX); ListBoxItemsFte->SetMinSize(wxSize(200,200)); ListBoxItemsFte->Clear(); int i,tam=0; tam=ListaFte.Nombres.GetCount(); for(i=0;i<tam;i++) { ListBoxItemsFte->Append(ListaFte.Nombres.Item(i)); } if(tam>0) { ListBoxItemsFte->SetSelection(0); } sizerDibujoFte = new wxBoxSizer(wxVERTICAL); sizerDibujoFte->Add(40,20, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerButSup = new wxBoxSizer(wxVERTICAL); sizerButSup->Add(sizerDibujoFte, 0, wxALIGN_CENTER | wxALL, 5); sizerButSup->Add(ButtonEditarFte, 0, wxALIGN_CENTER | wxALL, 5); sizerButSup->Add(ButtonAplicarFte, 0, wxALIGN_CENTER | wxALL, 5); wxBoxSizer *sizerTotal = new wxBoxSizer(wxHORIZONTAL); sizerTotal->Add(ListBoxItemsFte, 0, wxALIGN_CENTER | wxALL, 5); sizerTotal->Add(sizerButSup, 0, wxALIGN_CENTER | wxALL, 5); PagFuentes->SetAutoLayout(TRUE); PagFuentes->SetSizer(sizerTotal); sizerTotal->SetSizeHints(PagFuentes); sizerTotal->Fit(PagFuentes); Refresh(); } void PaginaFuentes::recargar() { ListaTempFte=&Canvas->Fuentes; ListaFte=*ListaTempFte; } void PaginaFuentes::editarFte(wxCommandEvent&) { int item; item=ListBoxItemsFte->GetSelection(); if(item<0){return;} wxFont fnt; wxFont fntRet; wxFontData data; wxFontDialog *dialog2; fnt = ListaFte.Fuentes.Item(item); data.SetInitialFont(fnt); dialog2 = new wxFontDialog(this,data); dialog2->SetTitle(ListaFte.Nombres.Item(item)); if (dialog2->ShowModal() == wxID_OK) { wxFontData retData = dialog2->GetFontData(); fntRet = retData.GetChosenFont(); if(fntRet.Ok()) { ListaFte.Fuentes.Item(item)=fntRet; } } delete dialog2; Refresh(); } void PaginaFuentes::OnPaint(wxPaintEvent&) { pintarFte(); } void PaginaFuentes::aplicar(wxCommandEvent&) { *ListaTempFte=ListaFte; Canvas->Refresh(); } void PaginaFuentes::pintarFte() { wxPaintDC dc(this); wxPoint origen=sizerDibujoFte->GetPosition(); wxSize tamano=sizerDibujoFte->GetSize(); wxBrush Brush; wxPen Pen; int item; item=ListBoxItemsFte->GetSelection(); Brush.SetColour(*wxWHITE); dc.SetBrush (Brush); dc.DrawRectangle(origen,tamano); Pen.SetWidth(2); Pen.SetColour(*wxBLACK); dc.SetPen (Pen); dc.DrawRectangle(origen,tamano); dc.SetFont(ListaFte.Fuentes.Item(item)); wxString cad=wxT("Abc"); dc.DrawText(cad,origen); } void PaginaFuentes::seleccionarFte(wxCommandEvent&) { Refresh(); }
#ifndef _OBJECT_H_ #define _OBJECT_H_ #include<vector> #include "vertex.h" #include "box.h" #include "face.h" #include "material_lib.h" using namespace std; class Object { public: Object(std::string); void readObj(const char*filename,MaterialLib&matlib); void updateBoundingBox(); Box boundingBox()const; void Render(MaterialLib ml,bool,bool); void CalculaNormals(); void CalculaNormalsVertexs(); private: void make_face(char**words,int nwords,int material); void netejaDades(); public: vector<Vertex>vertices; vector<Face>faces; private: std::string name; Box _boundingBox; }; #endif
#pragma once #pragma execution_character_set("utf-8") #include<iostream> #include<vector> #include<string> #include<queue> #include<unordered_map> using namespace std; //C++ O(n log(n - k)) unordered_map and priority_queue solution class Solution { public: vector<int> topKFrequent(vector<int>& nums, int k) { unordered_map<int, int>map; for (int num : nums) map[num]++; vector<int>res; //pair<frequency,element> std::priority_queue<pair<int, int>>pri_queue; for (auto it = map.begin(); it != map.end(); it++) { pri_queue.push(make_pair(it->second,it->first)); if (pri_queue.size() > (int)map.size() - k) { res.push_back(pri_queue.top().second); pri_queue.pop(); }/*if */ }/*for */ return res; } }; //int main() //{ // Solution so = *(new Solution()); // vector<int>nums = {1,3,2,3,5,5}; // int k = 2; // vector<int> res = so.topKFrequent(nums,k); // for (int num : res) // cout << num << " "; // system("pause"); //}
#include<iostream> using namespace std; int main() { int iNo1=10; int &ref1=iNo1; int &ref2=iNo1; int &ref3=iNo1; cout<<iNo1<<endl<<ref1<<endl<<ref2<<endl<<ref3; cout<<&iNo1<<endl<<&ref1<<endl<<&ref2<<endl<<&ref3; }
#include "physics\Singularity.Physics.h" namespace Singularity { namespace Physics { namespace Core { class BoundingCapsule { public: #pragma region Variables Vector3 Segment[2]; float Radius; float Height; #pragma endregion #pragma region Constructors and Finalizers BoundingCapsule(Vector3 center = Vector3(0,0,0), Quaternion rotation = Quaternion(0,0,0,1), float radius = 0.5f, float height = 2.0f); #pragma endregion #pragma region Methods //Vector3 FindIntersectionPoint(BoundingSphere& sphere); #pragma endregion #pragma region Static Methods //static bool Intersects(BoundingSphere& sphere0, BoundingSphere& sphere1); #pragma endregion }; } } }
#include "IdleJoystickState.h" JoystickState * IdleJoystickState::getInstance() { if (IdleJoystickState::sInstance == NULL) { IdleJoystickState::sInstance = new IdleJoystickState(); } return IdleJoystickState::sInstance; } void IdleJoystickState::handleCoordinates(int nX, int nY, Joystick & joystick) { int8_t retVal = joystick.getZone(nX, nY); if (retVal == NOT_IN_DEADZONE) { int8_t bufferFreeIndexNum; if (nX > MAX_X_POSITION) { bufferFreeIndexNum = joystick.getStateBufferFreeIndex(); if (bufferFreeIndexNum != NOK) { joystick.changeState(RightJoystickState::getInstance()); joystick.position_states[bufferFreeIndexNum] = RightJoystickState::getInstance(); cout << "Joystick moved to Right Position!" << endl; } } else if (nX < MIN_X_POSITION) { bufferFreeIndexNum = joystick.getStateBufferFreeIndex(); if (bufferFreeIndexNum != NOK) { joystick.changeState(LeftJoystickState::getInstance()); joystick.position_states[bufferFreeIndexNum] = LeftJoystickState::getInstance(); cout << "Joystick moved to Left Position!" << endl; } } else if (nY > MAX_Y_POSITION) { bufferFreeIndexNum = joystick.getStateBufferFreeIndex(); if (bufferFreeIndexNum != NOK) { joystick.changeState(UpJoystickState::getInstance()); joystick.position_states[bufferFreeIndexNum] = UpJoystickState::getInstance(); cout << "Joystick moved to Up Position!" << endl; } } else if (nY < MIN_Y_POSITION) { bufferFreeIndexNum = joystick.getStateBufferFreeIndex(); if (bufferFreeIndexNum != NOK) { joystick.changeState(DownJoystickState::getInstance()); joystick.position_states[bufferFreeIndexNum] = DownJoystickState::getInstance(); cout << "Joystick moved to Down position!" << endl; } } } else if (retVal == IN_DEADZONE) { cout << "Joystick is in Deadzone!" << endl; } else if (retVal == INVALID_PARAMETER) { cout << "Invalid parameters!" << endl; } } JoystickState* IdleJoystickState::sInstance = NULL;
#include "pangram.h" bool pangram::is_pangram(string s) { bitset<26> data; for (const auto& i : s) { if (isalpha(i)) { int j = tolower(i) - 97; data[j] = 1; } } return data.all(); }
#include "LoadMapTest.h" #include "tinyxml2.h" #include "Util.h" USING_NS_CC; Scene* LoadMapTest::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = LoadMapTest::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } bool LoadMapTest::init() { if (!Layer::init()) { return false; } // map if (!LoadMapFromXML("map1.xml", TMXTiledMap::create("grassland.tmx"), "maze", 6, 6)) { return false; } return true; } bool LoadMapTest::LoadMapFromXML(const std::string& xmlfile, TMXTiledMap* bgmap, const std::string& layername, int tilex, int tiley) { m_Map = bgmap; this->addChild(m_Map, 0, "bgmap"); m_Layer = m_Map->getLayer(layername); tinyxml2::XMLDocument doc; if (int i = doc.LoadFile(xmlfile.c_str()) != 0) { CCLOG("Load xmlfile false:%d", i); return false; } tinyxml2::XMLElement *themap=doc.RootElement(); const char* mappic = themap->Attribute("scene"); const char* wallid = themap->Attribute("wallid"); int mapwidth = atoi(themap->Attribute("width")); int mapheight = atoi(themap->Attribute("height")); if (!mappic || !wallid) { CCLOG("map scene is null or wallid is null."); return false; } if (mapwidth == 0 || mapheight == 0) { CCLOG("map size is not valid."); return false; } tinyxml2::XMLElement* data = themap->FirstChildElement("data"); std::string encode = data->Attribute("encoding"); std::string compr = data->Attribute("compression"); CCLOG("encoding:%s, compression:%s", data->Attribute("encoding"), data->Attribute("compression")); if (encode == "base64" && compr == "zlib") { std::string mapdata = Decode(data->GetText()); CCLOG("mapdata:%s", mapdata.c_str()); std::vector<std::string> rows = SplitStr(mapdata, ";"); for (size_t i = 0; i < rows.size(); ++i) { std::vector<std::string> values = SplitStr(rows[i], ","); for (size_t j = 0; j < values.size(); ++j) { m_Layer->setTileGID(atoi(values[j].c_str()), Vec2(tilex + i, tiley + j)); } } } return true; }
#include <bits/stdc++.h> using namespace std; #define ar array #define ll long long const int MAX_N = 1e5 + 1; const ll MOD = 1e9 + 7; const ll INF = 1e9; //CF Round #721 (1527) ProgA - Practice void solve() { int n; cin>>n; if(n == 1){ cout<<0<<"\n"; return; } int i = 1; int curr = 1 << i; int res = curr; while(curr <= n){ res = curr; curr = 1 << i; i++; } cout<<res - 1<<"\n"; } //for(int i = 0; i < n; i++) int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t=1; cin>>t; while(t--) { //cout << "Case #" << t << ": "; solve(); } //cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl; }
// This file has been generated by Py++. // Copyright (c) 2004 Raoul M. Gough // // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy // at http://www.boost.org/LICENSE_1_0.txt) // // Header file methods.hpp // // Methods (and sets of methods) that containers can provide. // // History // ======= // 2004/ 1/11 rmg File creation // 2008/12/08 Roman Change indexing suite layout // // $Id: methods.hpp,v 1.1.2.1 2004/02/08 18:57:42 raoulgough Exp $ // #ifndef BOOST_PYTHON_INDEXING_METHODS_HPP #define BOOST_PYTHON_INDEXING_METHODS_HPP #include <boost/config.hpp> #include <boost/mpl/if.hpp> namespace boost { namespace python { namespace indexing { typedef unsigned long method_set_type; enum methods_enum { method_len = 1UL << 0, method_iter = 1UL << 1, method_getitem = 1UL << 2, method_getitem_slice = 1UL << 3, method_index = 1UL << 4, method_contains = 1UL << 5, method_count = 1UL << 6, method_has_key = 1UL << 7, method_setitem = 1UL << 8, method_setitem_slice = 1UL << 9, method_delitem = 1UL << 10, method_delitem_slice = 1UL << 11, method_reverse = 1UL << 12, method_append = 1UL << 13, method_insert = 1UL << 14, method_extend = 1UL << 15, method_sort = 1UL << 16 }; // Some sets of methods that could be useful for disabling expensive // features. e.g. something & ~(slice_methods | search_methods) enum { slice_methods = method_getitem_slice | method_setitem_slice | method_delitem_slice }; enum { search_methods = method_index | method_contains | method_count | method_has_key }; enum { reorder_methods = method_sort | method_reverse }; enum { insert_methods = method_append | method_insert | method_extend }; enum { all_methods = ~0UL }; namespace detail { // Compile-time constant selection: // // method_set_if<c, t, f>::value == (c ? t : f) // // where c is convertible to bool, and t and f are convertible to // method_set_type. This gives a compile-time constant reliably on // all supported compilers. template< bool Cond, method_set_type TrueValue, method_set_type FalseValue = 0> struct method_set_if { struct true_type { BOOST_STATIC_CONSTANT(method_set_type, value = TrueValue); }; struct false_type { BOOST_STATIC_CONSTANT(method_set_type, value = FalseValue); }; typedef typename mpl::if_c<Cond, true_type, false_type>::type result_type; BOOST_STATIC_CONSTANT(method_set_type, value = result_type::value); }; // Compile-time set membership test: // is_member<set, mem>::value == (bool) set & mem template<method_set_type Set, method_set_type Member> struct is_member { // Use a cast to prevent MSVC truncation warning C4305 BOOST_STATIC_CONSTANT (bool, value = (bool) (Set & Member)); }; } } } } // boost::python::indexing #endif // BOOST_PYTHON_INDEXING_METHODS_HPP
/* Project: AltaLux plugin for IrfanView Author: Stefano Tommesani Website: http://www.tommesani.com Microsoft Public License (MS-PL) [OSI Approved License] This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. */ #include "CParallelEventAltaLuxFilter.h" #include <windows.h> #include <memory> #include <ppl.h> /// <summary> /// processes incoming image /// </summary> /// <returns>error code, refer to AL_XXX codes</returns> /// <remarks> /// working parallel code with single loop, using Win32 events to protect data dependecies across vertical blocks /// [Filter processing of full resolution image] in [1.131 seconds] /// </remarks> int CParallelEventAltaLuxFilter::Run() { if (ClipLimit == 1.0) return AL_OK; //< is OK, immediately returns original image auto pImage = static_cast<PixelType *>(ImageBuffer); /// pulMapArray is pointer to mappings auto pulMapArray = std::make_unique<unsigned int[]>(NumHorRegions * NumVertRegions * NUM_GRAY_LEVELS); if (pulMapArray == nullptr) return AL_OUT_OF_MEMORY; //< not enough memory /// region pixel count auto NumPixels = static_cast<unsigned int>(RegionWidth) * static_cast<unsigned int>(RegionHeight); //< region pixel count unsigned int ulClipLimit; //< clip limit if (ClipLimit > 0.0) { /// calculate actual cliplimit ulClipLimit = static_cast<unsigned int>(ClipLimit * (RegionWidth * RegionHeight) / NUM_GRAY_LEVELS); ulClipLimit = (ulClipLimit < 1UL) ? 1UL : ulClipLimit; } else ulClipLimit = 1UL << 14; //< large value, do not clip (AHE) /// Interpolate greylevel mappings to get CLAHE image // create events for signaling that the first phase is completed HANDLE FirstPhaseCompleted[MAX_VERT_REGIONS]; for (int i = 0; i < NumVertRegions; i++) FirstPhaseCompleted[i] = CreateEvent( nullptr, // default security attributes TRUE, // manual-reset event FALSE, // initial state is nonsignaled nullptr // object name ); concurrency::parallel_for((int)0, (int)(NumVertRegions + 1), [&](int uiY) { // first half auto pImPointer = pImage; if (uiY > 0) pImPointer += ((RegionHeight >> 1) + ((uiY - 1) * RegionHeight)) * OriginalImageWidth; if (uiY < NumVertRegions) { /// calculate greylevel mappings for each contextual region for (unsigned int uiX = 0; uiX < NumHorRegions; uiX++, pImPointer += RegionWidth) { auto pHistogram = &pulMapArray[NUM_GRAY_LEVELS * (uiY * NumHorRegions + uiX)]; MakeHistogram(pImPointer, pHistogram); ClipHistogram(pHistogram, ulClipLimit); MapHistogram(pHistogram, NumPixels); } } // signal that the first phase is completed for this horizontal block if (uiY < NumVertRegions) SetEvent(FirstPhaseCompleted[uiY]); // wait for completion of first phase of the previous horizontal block if (uiY > 0) auto dwWaitResult = WaitForSingleObject(FirstPhaseCompleted[uiY - 1], INFINITE); // second half unsigned int uiSubX, uiSubY; //< size of subimages unsigned int uiXL, uiXR, uiYU, uiYB; //< auxiliary variables interpolation routine pImPointer = pImage; if (uiY > 0) pImPointer += ((RegionHeight >> 1) + ((uiY - 1) * RegionHeight)) * OriginalImageWidth; if (uiY == 0) { /// special case: top row uiSubY = RegionHeight >> 1; uiYU = 0; uiYB = 0; } else { if (uiY == NumVertRegions) { /// special case: bottom row uiSubY = (RegionHeight >> 1) + (OriginalImageHeight - ImageHeight); uiYU = NumVertRegions - 1; uiYB = uiYU; } else { /// default values uiSubY = RegionHeight; uiYU = uiY - 1; uiYB = uiY; } } for (unsigned int uiX = 0; uiX <= NumHorRegions; uiX++) { if (uiX == 0) { /// special case: left column uiSubX = RegionWidth >> 1; uiXL = 0; uiXR = 0; } else { if (uiX == NumHorRegions) { /// special case: right column uiSubX = (RegionWidth >> 1) + (OriginalImageWidth - ImageWidth); uiXL = NumHorRegions - 1; uiXR = uiXL; } else { /// default values uiSubX = RegionWidth; uiXL = uiX - 1; uiXR = uiX; } } auto pulLU = &pulMapArray[NUM_GRAY_LEVELS * (uiYU * NumHorRegions + uiXL)]; auto pulRU = &pulMapArray[NUM_GRAY_LEVELS * (uiYU * NumHorRegions + uiXR)]; auto pulLB = &pulMapArray[NUM_GRAY_LEVELS * (uiYB * NumHorRegions + uiXL)]; auto pulRB = &pulMapArray[NUM_GRAY_LEVELS * (uiYB * NumHorRegions + uiXR)]; Interpolate(pImPointer, pulLU, pulRU, pulLB, pulRB, uiSubX, uiSubY); pImPointer += uiSubX; //< set pointer on next matrix } }); for (auto i = 0; i < NumVertRegions; i++) CloseHandle(FirstPhaseCompleted[i]); return AL_OK; //< return status OK }
#pragma once //#define PAR_SORT #define INT_SORT #include <vector> #include <algorithm> #include <numeric> #ifdef PAR_SORT #include <parallel/algorithm> #define PARSEQ __gnu_parallel #else #define PARSEQ std #endif #ifdef INT_SORT #include <tudocomp/util/IntSort.hpp> #endif #include <tudocomp/def.hpp> #include <tudocomp/ds/IntVector.hpp> #include <tudocomp/Algorithm.hpp> #include <tudocomp/compressors/lcpcomp/lcpcomp.hpp> #include <tudocomp_stat/StatPhase.hpp> namespace tdc { namespace lcpcomp { namespace PointerJumpIntEM_interal { struct Factor { len_t source; len_t len; #ifdef DEBUG len_t target; #endif Factor() {} constexpr Factor(len_t source, len_t target, len_t len) : source(source), len(len) #ifdef DEBUG , target(target) #endif {} constexpr Factor(len_t source, len_t len) : Factor(source, 0, len) {} Factor(const Factor&) = default; bool operator< (const Factor& o) const {return source < o.source ; }// as_tuple() < o.as_tuple();} bool operator== (const Factor& o) const {return as_tuple() == o.as_tuple();} friend std::ostream& operator<<(std::ostream& o, const Factor& f) { o << "[src=" << f.source << ", len=" << f.len #ifdef DEBUG << ", dbg-target=" << f.target #endif << "]"; return o; } constexpr static Factor max_sentinel() { return { std::numeric_limits<decltype(Factor().source)>::max(), std::numeric_limits<decltype(Factor().len)>::max() }; } private: std::tuple<const len_t&, const len_t&> as_tuple() const { return std::tie(source, len); } }; struct Request { len_t source; len_t target; len_t len; Request() {} constexpr Request(len_t source, len_t target, len_t len) : source(source), target(target), len(len) {} Request(const Request&) = default; Request(const Factor& f) : Request(f.source, 0, f.len) {} bool operator< (const Request& o) const {return source < o.source; } //as_tuple() < o.as_tuple();} bool operator== (const Request& o) const {return as_tuple() == o.as_tuple();} constexpr static Request max_sentinel() { return { std::numeric_limits<decltype(Request().source)>::max(), std::numeric_limits<decltype(Request().target)>::max(), std::numeric_limits<decltype(Request().len)>::max() }; } private: std::tuple<const len_t&, const len_t&, const len_t&> as_tuple() const { return std::tie(source, target, len); } }; template<typename IterResolved, typename IterUnresolved> class FactorStreamMergerImpl { public: FactorStreamMergerImpl() = delete; FactorStreamMergerImpl(IterResolved res_begin, IterResolved res_end, IterUnresolved un_begin, IterUnresolved un_end, len_t size) : m_res_it(res_begin), m_res_end(res_end), m_un_it(un_begin), m_un_end(un_end), m_cursor(0), m_size(size) { next(); } FactorStreamMergerImpl(const FactorStreamMergerImpl&) = default; const Request& current() const { return m_current; } const bool resolved() const { return m_is_resolved; } const bool empty() const { const bool empty = (m_size == m_cursor); DCHECK(!empty || (std::next(m_un_it) == m_un_end)); DCHECK(!empty || (std::next(m_res_it) == m_res_end)); return empty; } const len_t cursor_begin() const { return m_begin; } const len_t cursor_end() const { return m_cursor; } void next() { //DCHECK(!empty()); // implied by next assertion DCHECK_GT(m_size, m_cursor); DCHECK(m_res_it != m_res_end); DCHECK(m_un_it != m_un_end); m_is_resolved = (m_cursor == m_res_it->source); if (m_is_resolved) { m_current = *m_res_it; DCHECK_EQ(m_cursor, m_current.source); ++m_res_it; } else { m_current = *m_un_it; IF_DEBUG(DCHECK_EQ(m_cursor, m_current.target)); ++m_un_it; } DCHECK(m_current.len); m_begin = m_cursor; m_cursor += m_current.len; } private: IterResolved m_res_it; const IterResolved m_res_end; IterUnresolved m_un_it; const IterUnresolved m_un_end; len_t m_cursor; len_t m_begin; const len_t m_size; Request m_current; bool m_is_resolved; }; using FactorVector = std::vector<Factor>; using RequestVector = std::vector<Request>; using FactorStreamMerger = FactorStreamMergerImpl<FactorVector::const_iterator, RequestVector::const_iterator>; /** * Runs a number of scans of the factors. * In each scan, it tries to decode all factors. * Factors that got fully decoded are dropped. */ class PointerJumpIntEM : public Algorithm { public: inline static Meta meta() { Meta m(dec_strategy_type(), "pjintem"); return m; } inline void decode_lazy() { if (tdc_likely(m_decode_literal_factor.len)) { m_resolved.push_back(m_decode_literal_factor); } // Put sentinels in factor streams to make merging easier m_unresolved.push_back(Request::max_sentinel()); m_resolved.push_back(Factor::max_sentinel()); bool done = false; do { StatPhase::wrap("Round", [&] () { std::cout << "Round" << std::endl; done = process_round(); }); } while(!done); } void decode_eagerly() { } PointerJumpIntEM(PointerJumpIntEM&& other) = default; inline PointerJumpIntEM(Config&& cfg) : Algorithm(std::move(cfg)) , m_cursor(0) {} inline void initialize(size_t n) { if(tdc_unlikely(n == 0)) throw std::runtime_error( "no text length provided"); m_buffer = IntVector<uliteral_t>(n); } // decoding statge inline void decode_literal(uliteral_t c) { m_buffer[m_cursor] = c; if (tdc_unlikely(m_decode_literal_factor.len == 0)) { m_decode_literal_factor.source = m_cursor; } m_decode_literal_factor.len++; m_cursor++; // we assume that the text to restore does not contain a NULL-byte but at its very end DCHECK(c != 0 || m_cursor == m_buffer.size()); } inline void decode_factor(const len_t source_position, len_t factor_length) { if (tdc_likely(m_decode_literal_factor.len)) { m_resolved.push_back(m_decode_literal_factor); m_decode_literal_factor.len = 0; } DCHECK_NE(m_cursor, source_position); DCHECK(factor_length); auto add = [&] (len_t source, len_t target, len_t len, bool print = false) { if (print) std::cout << " [" << target << ".." << (target+len) << " <- " << source << ".." << (source+len) << "]\n"; m_unresolved.emplace_back(source, target, len); m_new_requests.emplace_back(source, target, len); m_cursor += len; factor_length -= len; }; const bool overlap_at_end = (m_cursor < source_position) && (source_position < m_cursor + factor_length); if (false && tdc_unlikely(overlap_at_end)) { const len_t ov_len = source_position - m_cursor; const len_t source_end = source_position + factor_length; const len_t first_factor = factor_length % ov_len; if (first_factor) { add(source_end - first_factor, m_cursor, first_factor); } while(factor_length) { add(source_end - ov_len, m_cursor, ov_len); } } else { add(source_position, m_cursor, factor_length); } } // final touch inline void process() { } inline len_t longest_chain() const { // We would need additional data structures to compute it. so we output a dummy value. // if you need it, use a different decompressor return 0; } inline void write_to(std::ostream& out) const { for(auto c : m_buffer) out << c; } private: // literals and insertion len_t m_cursor; IntVector<uliteral_t> m_buffer; FactorVector m_resolved; RequestVector m_unresolved; RequestVector m_requests; RequestVector m_new_requests; Factor m_decode_literal_factor{0, 0}; void check_invariants() const { // Resolved DCHECK(!m_resolved.empty()); DCHECK(m_resolved.back() == Factor::max_sentinel()); DCHECK(std::is_sorted(m_resolved.cbegin(), m_resolved.cend())); // Unresolved DCHECK(!m_unresolved.empty()); DCHECK(m_unresolved.back() == Request::max_sentinel()); // Check full coverage const len_t resolved = std::accumulate( m_resolved.cbegin(), m_resolved.cbegin() + (m_resolved.size() - 1), static_cast<len_t>(0), [] (len_t x, const auto& f) {return x+f.len;} ); const len_t unresolved = std::accumulate( m_unresolved.cbegin(), m_unresolved.cbegin() + (m_unresolved.size() - 1), static_cast<len_t>(0), [] (len_t x, const auto& f) {return x+f.len;} ); DCHECK_EQ(m_buffer.size(), resolved + unresolved); // Requests DCHECK(std::is_sorted(m_requests.cbegin(), m_requests.cend())); } bool process_round() { // sort and exchange requests #ifdef INT_SORT intsort(m_new_requests, [] (const Request& r) {return r.source;}, static_cast<len_t>(m_buffer.size())); #else PARSEQ::sort(m_new_requests.begin(), m_new_requests.end()); #endif m_requests.swap(m_new_requests); m_new_requests.clear(); IF_DEBUG(check_invariants()); std::vector<Factor> new_resolved; FactorStreamMerger merger{ m_resolved.cbegin(), m_resolved.cend(), m_unresolved.cbegin(), m_unresolved.cend(), static_cast<len_t>(m_buffer.size()) }; auto process_request = [&new_resolved, &m_new_requests = this->m_new_requests, &m_buffer = this->m_buffer] (Request request, FactorStreamMerger merger /* call by value !! */) { while(true) { // check that we have an overlap with the current input token DCHECK_GE(request.source, merger.cursor_begin()); DCHECK_GT(merger.cursor_end(), request.source); const len_t token_starting_before = request.source - merger.cursor_begin(); const len_t length = std::min<len_t>( request.len, merger.current().len - token_starting_before); DCHECK(length); if (merger.resolved()) { // we found an already resolved piece, so copy the data new_resolved.emplace_back( request.target, length ); if (true) { // copy data (unfortunately this triggers unstructured I/Os); easy to replace in EM std::copy( std::next(m_buffer.cbegin(), request.source), std::next(m_buffer.cbegin(), request.source + length), std::next(m_buffer.begin(), request.target) ); // make sure we only copy initialised data for (len_t j = request.source; j < request.source + length; ++j) { DCHECK(m_buffer[j]); } } } else { // pointer jumping m_new_requests.emplace_back(merger.current().source + token_starting_before, request.target, length); } // remove process snippet from request by moving the request to the right // and shortening it accordingly request.target += length; request.source += length; request.len -= length; if (!request.len) break; merger.next(); } }; for(const auto& request : m_requests) { // skip all irrelevant tokens while(merger.cursor_end() <= request.source) { merger.next(); } process_request(request, merger); } // new requests -> new unresolved StatPhase::log("m_unresolved.size", m_unresolved.size() - 1); m_unresolved.clear(); m_unresolved.reserve(m_new_requests.size() + 1); m_unresolved.assign(m_new_requests.cbegin(), m_new_requests.cend()); #ifdef INT_SORT intsort(m_unresolved, [] (const Request& r) {return r.target;}, static_cast<len_t>(m_buffer.size())); #else PARSEQ::sort(m_unresolved.begin(), m_unresolved.end(), [] (const Request& a, const Request& b) {return a.target < b.target;}); #endif StatPhase::log("m_new_unresolved.size", m_unresolved.size()); m_unresolved.push_back(Request::max_sentinel()); // merge resolved vector { std::vector<Factor> resolved_merged; resolved_merged.reserve(new_resolved.size() + m_resolved.size()); #ifdef INT_SORT intsort(new_resolved, [] (const Factor& r) {return r.source;}, static_cast<len_t>(m_buffer.size())); #else PARSEQ::sort(new_resolved.begin(), new_resolved.end()); #endif new_resolved.emplace_back(Factor::max_sentinel()); auto it_old = m_resolved.cbegin(); auto it_new = new_resolved.cbegin(); resolved_merged.push_back(it_old->source < it_new->source ? *it_old++ : *it_new++); while(resolved_merged.back().source != Request::max_sentinel().source) { const auto token = it_old->source < it_new->source ? *it_old++ : *it_new++; if (resolved_merged.back().source + resolved_merged.back().len == token.source) { resolved_merged.back().len += token.len; } else { resolved_merged.push_back(token); } } StatPhase::log("m_resolved.size", m_resolved.size()); StatPhase::log("new_resolved.size", new_resolved.size()); StatPhase::log("resolved_merged.size", resolved_merged.size()); m_resolved.swap(resolved_merged); } return m_unresolved.size() == 1; } }; } // internal namespace using PointerJumpIntEM = PointerJumpIntEM_interal::PointerJumpIntEM; }} //ns
#include "stdafx.h" #include "ply/ply.h" #include "MxImage.h" #include "MxIsoSurface.h" #include "SurfaceRendering.h" #include "MxOpenGL.h" #include "MxImageIO.h" #include "MxFileIO.h" typedef struct Vertex { float x,y,z; float r,g,b; float nx,ny,nz; void *other_props; /* other properties */ } Vertex; typedef struct Face { unsigned char nverts; /* number of vertex indices in list */ int *verts; /* vertex index list */ void *other_props; /* other properties */ } Face; char *elem_names[] = { /* list of the elements in the object */ "vertex", "face" }; PlyProperty vert_props[] = { /* list of property information for a vertex */ {"x", Float32, Float32, offsetof(Vertex,x), 0, 0, 0, 0}, {"y", Float32, Float32, offsetof(Vertex,y), 0, 0, 0, 0}, {"z", Float32, Float32, offsetof(Vertex,z), 0, 0, 0, 0}, {"r", Float32, Float32, offsetof(Vertex,r), 0, 0, 0, 0}, {"g", Float32, Float32, offsetof(Vertex,g), 0, 0, 0, 0}, {"b", Float32, Float32, offsetof(Vertex,b), 0, 0, 0, 0}, {"nx", Float32, Float32, offsetof(Vertex,nx), 0, 0, 0, 0}, {"ny", Float32, Float32, offsetof(Vertex,ny), 0, 0, 0, 0}, {"nz", Float32, Float32, offsetof(Vertex,nz), 0, 0, 0, 0}, }; PlyProperty face_props[] = { /* list of property information for a face */ {"vertex_indices", Int32, Int32, offsetof(Face,verts), 1, Uint8, Uint8, offsetof(Face,nverts)}, }; /*** the PLY object ***/ static int nverts,nfaces; static Vertex **vlist; static Face **flist; static PlyOtherProp *vert_other,*face_other; static int per_vertex_color = 0; static int has_normals = 0; /****************************************************************************** Read in the PLY file from standard in. ******************************************************************************/ void read_file(FILE* file) { int i,j; int elem_count; char *elem_name; PlyFile *in_ply; /*** Read in the original PLY object ***/ in_ply = read_ply (file); for (i = 0; i < in_ply->num_elem_types; i++) { /* prepare to read the i'th list of elements */ elem_name = setup_element_read_ply (in_ply, i, &elem_count); if (equal_strings ("vertex", elem_name)) { /* create a vertex list to hold all the vertices */ vlist = (Vertex **) malloc (sizeof (Vertex *) * elem_count); nverts = elem_count; /* set up for getting vertex elements */ setup_property_ply (in_ply, &vert_props[0]); setup_property_ply (in_ply, &vert_props[1]); setup_property_ply (in_ply, &vert_props[2]); for (j = 0; j < in_ply->elems[i]->nprops; j++) { PlyProperty *prop; prop = in_ply->elems[i]->props[j]; if (equal_strings ("r", prop->name)) { setup_property_ply (in_ply, &vert_props[3]); per_vertex_color = 1; } if (equal_strings ("g", prop->name)) { setup_property_ply (in_ply, &vert_props[4]); per_vertex_color = 1; } if (equal_strings ("b", prop->name)) { setup_property_ply (in_ply, &vert_props[5]); per_vertex_color = 1; } if (equal_strings ("nx", prop->name)) { setup_property_ply (in_ply, &vert_props[6]); has_normals = 1; } if (equal_strings ("ny", prop->name)) { setup_property_ply (in_ply, &vert_props[7]); has_normals = 1; } if (equal_strings ("nz", prop->name)) { setup_property_ply (in_ply, &vert_props[8]); has_normals = 1; } } vert_other = get_other_properties_ply (in_ply, offsetof(Vertex,other_props)); std::cout<<"elem_count==="<<elem_count<<std::endl; /* grab all the vertex elements */ for (j = 0; j < elem_count; j++) { vlist[j] = (Vertex *) malloc (sizeof (Vertex)); vlist[j]->r = 1; vlist[j]->g = 1; vlist[j]->b = 1; get_element_ply (in_ply, (void *) vlist[j]); } } else if (equal_strings ("face", elem_name)) { /* create a list to hold all the face elements */ flist = (Face **) malloc (sizeof (Face *) * elem_count); nfaces = elem_count; /* set up for getting face elements */ setup_property_ply (in_ply, &face_props[0]); face_other = get_other_properties_ply (in_ply, offsetof(Face,other_props)); /* grab all the face elements */ for (j = 0; j < elem_count; j++) { flist[j] = (Face *) malloc (sizeof (Face)); get_element_ply (in_ply, (void *) flist[j]); } } else get_other_element_ply (in_ply); } close_ply (in_ply); free_ply (in_ply); } /****************************************************************************** Write out the PLY file to standard out. ******************************************************************************/ void write_file(FILE* file) { int i; PlyFile *ply; int num_elem_types; /*** Write out the transformed PLY object ***/ static int nelems = 2; ply = write_ply (file, nelems, elem_names, PLY_ASCII); /* describe what properties go into the vertex elements */ describe_element_ply (ply, "vertex", nverts); describe_property_ply (ply, &vert_props[0]); describe_property_ply (ply, &vert_props[1]); describe_property_ply (ply, &vert_props[2]); describe_property_ply (ply, &vert_props[3]); describe_property_ply (ply, &vert_props[4]); describe_property_ply (ply, &vert_props[5]); describe_element_ply (ply, "face", nfaces); describe_property_ply (ply, &face_props[0]); append_comment_ply (ply, "created by sphereply"); header_complete_ply (ply); /* set up and write the vertex elements */ put_element_setup_ply (ply, "vertex"); for (i = 0; i < nverts; i++) put_element_ply (ply, (void *) &vlist[i]); /* set up and write the face elements */ put_element_setup_ply (ply, "face"); for (i = 0; i < nfaces; i++) put_element_ply (ply, (void *) &flist[i]); close_ply (ply); free_ply (ply); } /* * @Time:20160917 Written By MicroPhion * @Function:Get the Bound box of the vertex, use the bound to set the resolution of the spacing * @Input: vlist, the list of vertex vVertexNum, the number of the vertex * @Output: fLeftDownPoint, the left down point of the bound box fRightUpPoint, the right up point of the bound box */ void GetBoundBox(Vertex** vlist, int nVertexNum, double *fLeftDownPoint,double *fRightUpPoint){ //1.0 Init the bound box for (int i = 0; i < 3; i ++){ fLeftDownPoint[i] = 1000000; fRightUpPoint[i] = -1000000; } //2.0 Get the bound box for (int i = 0; i < nVertexNum; i ++){ double x = vlist[i]->x; double y = vlist[i]->y; double z = vlist[i]->z; if (x < fLeftDownPoint[0]){ fLeftDownPoint[0] = x; } if (y < fLeftDownPoint[1]){ fLeftDownPoint[1] = y; } if (z < fLeftDownPoint[2]){ fLeftDownPoint[2] = z; } if (x > fRightUpPoint[0]){ fRightUpPoint[0] = x; } if (y > fRightUpPoint[1]){ fRightUpPoint[1] = y; } if (z > fRightUpPoint[2]){ fRightUpPoint[2] = z; } } //3.0 test, print the information of the volume std::cout<<"nverts==="<<nverts<<std::endl; std::cout<<"left down point==="<<fLeftDownPoint[0]<<","<<fLeftDownPoint[1]<<","<<fLeftDownPoint[2]<<std::endl;; std::cout<<"right up point==="<<fRightUpPoint[0]<<","<<fRightUpPoint[1]<<","<<fRightUpPoint[2]<<std::endl; double volume = (fRightUpPoint[0]-fLeftDownPoint[0])*(fRightUpPoint[1]-fLeftDownPoint[1])*(fRightUpPoint[2]-fLeftDownPoint[2]); std::cout<<"volume==="<<volume<<std::endl; std::cout<<"spacing==="<<volume/(nverts*10)<<std::endl; } /* * @Time: 20160917 Written By MicroPhion * @Function: build the volume data by cloud points * @Input: vlist, the list of the vertex nVertexNum, the number of the vertex fLeftDownPoint, the left down point of the bound box fRightUpPoint, the right up point of the bound box * @Output:im, volume data in 3d format * */ void BuildVolumeData(Vertex** vlist, int nVertexNum, double *fLeftDownPoint,double *fRightUpPoint,UCharImage &im){ //the spacing confirm by the number of the points and boundbox of the points double spacing[3] = {0.01,0.01,0.01}; int size[3] = {1,1,1}; for (int i = 0; i < 3;i ++){ size[i] = (fRightUpPoint[i] - fLeftDownPoint[i])/spacing[i]+10; } int nDataLength = size[0]*size[1]*size[2]; unsigned char *mask = new unsigned char[nDataLength+1]; im.Create(size); im.SetSpacing(spacing); im.Flush(0); //TODO we should save the color information here, for example ,we can create an IntImage to save the rgb //when we get the surface of the volume data, we should get the rgb from IntImage for(int i = 0; i < nVertexNum; i ++){ int x = (int)((vlist[i]->x-fLeftDownPoint[0])/spacing[0]+0.5); int y = (int)((vlist[i]->y-fLeftDownPoint[1])/spacing[1]+0.5); int z = (int)((vlist[i]->z-fLeftDownPoint[2])/spacing[2]+0.5); int nIndex = x + y * size[0] + z * size[0]*size[1]; im.SetPixelValue(nIndex,1); } //std::cout<<"size==="<<size[0]<<","<<size[1]<<","<<size[2]<<std::endl; } /* * @Time: 20160917 Written By MicroPhion * @Function:a.Render Surface and Save the Frame to Image * @Input: width, the width of the output image height, the height of the output image outputpath, the path of the output image imageNum,the number of the output image surface, the surface want to be rendered */ void Create3DImages(int width, int height, std::string outputpath, int imageNum,std::vector<MxSurface*> surface){ //1.0 Init gl context GLUtils::xInitGlut(); int id = glutCreateWindow("MicroPhion"); if(wglGetCurrentContext() == NULL)return; //2.0 Render the surface FloatPoint box[2]; int fSpaceScope = MxSurface::xGetSpaceScope(surface,box); //2.1 set the projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-fSpaceScope/2*1.1, fSpaceScope/2*1.1 , -fSpaceScope/2*1.1 , fSpaceScope/2*1.1 , -fSpaceScope , fSpaceScope ); SurfaceRendering * surfaceRender = new SurfaceRendering(); surfaceRender->xSetMxSurface(surface); for(int i = 0; i < imageNum; i ++){ //2.2 set the viewmodel matrix glPushMatrix(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glRotated(360.0*i/imageNum, 0.0f, 1.0f, 0.0f);//ÈÆYÖáÐýת glTranslated(-(box[0].x + box[1].x)/2,-(box[0].y + box[1].y)/2,-(box[0].z + box[1].z)/2); MxOpenGL::xglEnable(GL_BLEND); surfaceRender->xCreateSRViewData(512,512,1); glPopMatrix(); //2.3 Save the image to file IntImage im; surfaceRender->xGetSRViewData(&im,1); UCharImage im2; MxImageIO::Int2RGB(im,&im2); std::string path = outputpath+std::string("\\")+MxFileIO::ConvertToString(i)+std::string(".jpg"); std::cout<<"nodule path ====" <<path<<std::endl; MxImageIO::SaveRGBFile(im2,path.c_str()); } SAFEDELETEObject(surfaceRender); //3.0 release the gl context glutHideWindow(); glutDestroyWindow(id); } /* * @Time:20160917 Written by Microphion * @Function: Create the surface from volume image by MarchingCube algorithm * @Input:image, the volume data in 3d format * @Output:surface the surface of the volume data */ void CreateSurface(UCharImage& image,MxSurface &surface){ std::cout << image.GetDataLength() << std::endl; //1.0 Create the Surface by MarchingCube TriangleSurface m_triangles; MxIsoSurface<unsigned char> isos; int size = image.GetDataLength(); unsigned char* data = new unsigned char[size]; memcpy(data,image.GetData(),size); isos.SetScalarData(data,image.GetWidth()-1,image.GetHeight()-1,image.GetDepth()-1,2,2,2); isos.SetThreshold(0.5); isos.Update(); isos.GetTriangleSurface(m_triangles); isos.ClearAllData(); //2.0 Set the color of the surface surface.Copy(m_triangles); surface.color[0] = 1;surface.color[1] = 1;surface.color[2] = 0;surface.color[3] = 1; //std:;cout<<"m_surface point==="<<m_triangles.pointSize()<<std::endl; //3.0 Testing, save the surface to image2d std::vector<MxSurface*> surfaces; surfaces.push_back(&surface); Create3DImages(1024,1024,"D:\\",30,surfaces); } /* * @Time:20160917 Wirtten by MicroPhion * @Function: render the cloud points by vtk */ void ShowCloudPoints(int nverts,Vertex** vlist) { //1.0 Create the Objects vtkPoints *m_Points = vtkPoints::New(); vtkCellArray *vertices = vtkCellArray::New(); vtkPolyData *polyData = vtkPolyData::New(); vtkPolyDataMapper *pointMapper = vtkPolyDataMapper::New(); vtkActor *pointActor = vtkActor::New(); vtkRenderer *ren1= vtkRenderer::New(); vtkRenderWindow *renWin = vtkRenderWindow::New(); vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New(); vtkInteractorStyleTrackball *istyle = vtkInteractorStyleTrackball::New(); //2.0 put points to vertices for (int i = 0; i < nverts; i ++) { double x = vlist[i]->x; double y = vlist[i]->y; double z = vlist[i]->z; m_Points->InsertPoint(i,x,y,z); vertices->InsertNextCell(1); vertices->InsertCellPoint(i); } //3.0 put the data to Mapper polyData->SetPoints(m_Points); polyData->SetVerts(vertices); pointMapper->SetInputData(polyData); //4.0 Set Property of the render pointActor->SetMapper( pointMapper ); pointActor->GetProperty()->SetColor(0.0,0.1,1.0); pointActor->GetProperty()->SetAmbient(0.5); pointActor->GetProperty()->SetPointSize(2); pointActor->GetProperty()->SetRepresentationToWireframe(); //5.0 Render ren1->AddActor( pointActor ); ren1->SetBackground( 0, 0, 0); renWin->AddRenderer( ren1 ); renWin->SetSize(800,800); iren->SetInteractorStyle(istyle); iren->SetRenderWindow(renWin); renWin->Render(); iren->Start(); //6.0 Release the Objects m_Points->Delete(); vertices->Delete(); polyData->Delete(); pointMapper->Delete(); pointActor->Delete(); ren1->Delete(); renWin->Delete(); iren->Delete(); istyle->Delete(); } void main(){ //1.0 Read Ply File std::string path = "D:\\densify.ply"; FILE *file = fopen(path.c_str(), "r"); read_file(file); //2.0 Convert Cloud Points to Volume Data //2.1 Get the BoundBox from Cloud Points double fLeftDown[3],fRightUp[3]; GetBoundBox(vlist,nverts,fLeftDown,fRightUp); UCharImage image; //2.2 Set Resolution Spacings //2.3 Create the Volume Data BuildVolumeData(vlist,nverts,fLeftDown,fRightUp,image); //3.0 Build Surfaces By MarchingCube MxSurface surface; CreateSurface(image,surface); //4.0 Save the Surface to File double *sp = image.GetSpacing(); for (int i = 0; i < surface.pointSize(); i ++){ surface.points[i] = surface.points[i].Spacing(sp) + FloatPoint(fLeftDown[0],fLeftDown[1],fLeftDown[2]); } surface.Save("D:\\1.obj"); }
#pragma once #include <malloc.h> #include <iostream> template<typename T, int align = alignof(T)> struct heapAligned { void* data = malloc(sizeof(T) + alignof(T) - 1); T* val = nullptr; heapAligned<T>() { if ((uintptr_t)data % align == 0) val = (T*)data; else val = data + (align + ((uintptr_t)data % align)); printf("data at %p\nval aligned at %p\n", data, val); } };
//========================================================================== // LOGINSPECTOR.H - part of // // OMNeT++/OMNEST // Discrete System Simulation in C++ // //========================================================================== /*--------------------------------------------------------------* Copyright (C) 1992-2008 Andras Varga Copyright (C) 2006-2008 OpenSim Ltd. This file is distributed WITHOUT ANY WARRANTY. See the file `license' for details on this and other legal matters. *--------------------------------------------------------------*/ #ifndef __LOGINSPECTOR_H #define __LOGINSPECTOR_H #include <map> #include "platmisc.h" // must precede <tk.h> otherwise Visual Studio 2013 fails to compile #include <tk.h> #include "logbuffer.h" #include "componenthistory.h" #include "inspector.h" #include "cmessageprinter.h" NAMESPACE_BEGIN class TKENV_API LogInspector : public Inspector, protected ILogBufferListener { public: enum Mode {LOG, MESSAGES}; protected: LogBuffer *logBuffer; // not owned ComponentHistory *componentHistory; // not owned char textWidget[128]; Tcl_CmdInfo textWidgetCmdInfo; std::set<int> excludedModuleIds; Mode mode; // state used during incremental printing (printLastLogLine(), printLastMessageLine()): // MESSAGES mode: eventnumber_t lastMsgEventNumber; simtime_t lastMsgTime; // LOG mode: bool entryMatches; bool bannerPrinted; bool bookmarkAdded; protected: void textWidgetCommand(const char *arg1, const char *arg2=NULL, const char *arg3=NULL, const char *arg4=NULL, const char *arg5=NULL, const char *arg6=NULL); void textWidgetInsert(const char *text, const char *tags); void textWidgetSeeEnd(); void textWidgetGotoBeginning(); void textWidgetGotoEnd(); void textWidgetSetBookmark(const char *bookmark, const char *pos); void textWidgetDumpBookmarks(const char *label); virtual void logEntryAdded(); virtual void logLineAdded(); virtual void messageSendAdded(); bool isMatchingComponent(int componentId); bool isAncestorModule(int moduleId, int potentialAncestorModuleId); virtual void printLastLogLine(); virtual void printLastMessageLine(); void printBannerIfNeeded(const LogBuffer::Entry *entry); void addBookmarkIfNeeded(const LogBuffer::Entry *entry); virtual void printLogLine(const LogBuffer::Entry *entry, const LogBuffer::Line& line); virtual int findFirstRelevantHop(const LogBuffer::MessageSend& msgsend, int fromHop); virtual cMessagePrinter *chooseMessagePrinter(cMessage *msg); virtual void printMessage(const LogBuffer::Entry *entry, int msgIndex, int hopIndex, bool repeatedEvent, bool repeatedSimtime); public: LogInspector(InspectorFactory *f); virtual ~LogInspector(); virtual void createWindow(const char *window, const char *geometry); virtual void useWindow(const char *window); virtual void doSetObject(cObject *obj); virtual void refresh(); virtual void redisplay(); virtual Mode getMode() const {return mode;} virtual void setMode(Mode mode); virtual int inspectorCommand(int argc, const char **argv); }; NAMESPACE_END #endif
#include <string> #include <iostream> namespace N { class C { private: std::string& first(){ // funzione #1 std::cout<< "1\n";} public: const std::string& first() const{ // funzione #2 std::cout<< "2\n";} std::string& last(){ // funzione #3 std::cout<< "3\n";} const std::string& last() const{ // funzione #4 std::cout<<"4\n"; } C(const char*){ // funzione #5 std::cout<<"5\n";} }; // class C void print(const C&){ // funzione #6 std::cout<<"6\n";} std::string& f(int){ // funzione #7 std::cout<<"7\n";} } // namespace N class A { public: explicit A(std::string&){ // funzione #8 std::cout<<"8\n";} }; void print(const A&){ // funzione #9 std::cout<<"9\n";} void f(N::C& c) // funzione #10 { std::cout<< "10\n"; const std::string& f1 = c.first(); //chiamata A std::string& f2 = c.first(); //chiamata B const std::string& l1 = c.last(); //chiamata C std::string& l2 = c.last(); //chiamata D } void f(const N::C& c) // funzione #11 { std::cout <<"11\n"; const std::string& f1 = c.first(); //chimata E; std::string& f2 = c.first(); //chiamata F const std::string& l1 = c.last(); // chiamata G std::string& l2 = c.last(); // chiamata H } int main() { N::C c("begin"); // chimata I f(c); //chiamata L f("middle"); // chiamata M // print("end"); // chiamata N } /* svolgimento A C={1,2} U={1,2} M={1} // dato che nella funzione la "c" non ci viene passata costante vado a prendere a funzione 1 perchè e non costante B C={1,2} U={1,2} M={1} // ci viene dato errore perchè è un metodo privato C C={3,4} U={3,4} M={3} D C={3,4} U={3,4} M={3} E C={1,2} U={1,2} M={2} F C={1,2} U={1,2} M={2} G C={3,4} U={3,4} M={4} H C={3,4} U={3,4} M={4} I C={5} U={5} M={5} L C={10,11} U={10,11} M={10} M C={10,11} U={10,11} M={11} N C={9} U={9} M={9} */
//$Id$ //------------------------------------------------------------------------------ // BuiltinGmatFunction //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG04CC06P. // // Author: Linda Jun // Created: 2016.05.02 // /** * Implements BuiltinGmatFunction class. */ //------------------------------------------------------------------------------ #include "BuiltinGmatFunction.hpp" #include "Parameter.hpp" #include "MessageInterface.hpp" //#define DEBUG_FUNCTION_SET //#define DEBUG_FUNCTION_INIT //#ifndef DEBUG_MEMORY //#define DEBUG_MEMORY //#endif //#ifndef DEBUG_TRACE //#define DEBUG_TRACE //#endif #ifdef DEBUG_MEMORY #include "MemoryTracker.hpp" #endif #ifdef DEBUG_TRACE #include <ctime> // for clock() #endif //--------------------------------- // static data //--------------------------------- //------------------------------------------------------------------------------ // BuiltinGmatFunction(std::string typeStr, std::string name) //------------------------------------------------------------------------------ /** * Constructs the BuiltinGmatFunction object (default constructor). * * @param <typeStr> String text identifying the object type * @param <name> Name for the object */ //------------------------------------------------------------------------------ BuiltinGmatFunction::BuiltinGmatFunction(const std::string &typeStr, const std::string &name) : Function(typeStr, name) { objectTypeNames.push_back(typeStr); objectTypeNames.push_back("BuiltinGmatFunction"); } //------------------------------------------------------------------------------ // ~BuiltinGmatFunction(void) //------------------------------------------------------------------------------ /** * Destroys the BuiltinGmatFunction object (destructor). */ //------------------------------------------------------------------------------ BuiltinGmatFunction::~BuiltinGmatFunction() { } //------------------------------------------------------------------------------ // BuiltinGmatFunction(const BuiltinGmatFunction &f) //------------------------------------------------------------------------------ /** * Constructs the BuiltinGmatFunction object (copy constructor). * * @param <f> Object that is copied */ //------------------------------------------------------------------------------ BuiltinGmatFunction::BuiltinGmatFunction(const BuiltinGmatFunction &f) : Function(f) { } //------------------------------------------------------------------------------ // BuiltinGmatFunction& operator=(const BuiltinGmatFunction &f) //------------------------------------------------------------------------------ /** * Sets one BuiltinGmatFunction object to match another (assignment operator). * * @param <f> The object that is copied. * * @return this object, with the parameters set as needed. */ //------------------------------------------------------------------------------ BuiltinGmatFunction& BuiltinGmatFunction::operator=(const BuiltinGmatFunction &f) { if (this == &f) return *this; Function::operator=(f); return *this; } //------------------------------------------------------------------------------ // bool Initialize(ObjectInitializer *objInit, bool reinitialize = false) //------------------------------------------------------------------------------ bool BuiltinGmatFunction::Initialize(ObjectInitializer *objInit, bool reinitialize) { #ifdef DEBUG_TRACE static Integer callCount = 0; callCount++; clock_t t1 = clock(); MessageInterface::ShowMessage ("BuiltinGmatFunction::Initialize() entered, callCount=%d\n", callCount); ShowTrace(callCount, t1, "BuiltinGmatFunction::Initialize() entered"); #endif #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage ("======================================================================\n" "BuiltinGmatFunction::Initialize() entered for function '%s'\n reinitialize=%d, " "objectsInitialized=%d\n", functionName.c_str(), reinitialize, objectsInitialized); MessageInterface::ShowMessage(" FCS is %s set.\n", (fcs? "correctly" : "NOT")); MessageInterface::ShowMessage(" Pointer for FCS is %p\n", fcs); MessageInterface::ShowMessage(" First command in fcs is %s\n", fcs ? (fcs->GetTypeName()).c_str() : "NULL"); MessageInterface::ShowMessage(" internalCS is %p\n", internalCoordSys); #endif Function::Initialize(objInit); // Initialize the Validator - I think I need to do this each time - or do I? validator->SetFunction(this); validator->SetSolarSystem(solarSys); std::map<std::string, GmatBase *>::iterator omi; #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" functionObjectMap.size() = %d\n automaticObjectMap.size() = %d\n", functionObjectMap.size(), automaticObjectMap.size()); #endif // Add clones of objects created in the function to the FOS (LOJ: 2014.12.09) for (omi = functionObjectMap.begin(); omi != functionObjectMap.end(); ++omi) { std::string funcObjName = omi->first; GmatBase *funcObj = omi->second; #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" Add clone to objectStore if funcObj <%p>[%s]'%s' is not already in objectStore\n", funcObj, funcObj ? funcObj->GetTypeName().c_str() : "NULL", funcObjName.c_str()); MessageInterface::ShowMessage (" funcObj->IsGlobal=%d, funcObj->IsLocal=%d\n", funcObj->IsGlobal(), funcObj->IsLocal()); #endif // if name not found, clone it and add to map (loj: 2008.12.15) if (objectStore->find(funcObjName) == objectStore->end()) { #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" About to clone <%p>[%s]'%s'\n", (omi->second), (omi->second)->GetTypeName().c_str(), (omi->second)->GetName().c_str()); #endif GmatBase *funcObjClone = (omi->second)->Clone(); #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Add (funcObjClone, funcObjName, "BuiltinGmatFunction::Initialize()", "funcObj = (omi->second)->Clone()"); #endif #ifdef DEBUG_FUNCTION_INIT_MORE try { MessageInterface::ShowMessage (" funcObj(%s)->EvaluateReal() = %f\n", funcObjName.c_str(), funcObjClone->GetRealParameter("Value")); } catch (BaseException &e) { MessageInterface::ShowMessage("%s\n", e.GetFullMessage().c_str()); } #endif #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" ==> Adding funcObj clone <%p>'%s' to objectStore\n", funcObjClone, funcObjName.c_str()); #endif funcObjClone->SetIsLocal(true); objectStore->insert(std::make_pair(funcObjName, funcObjClone)); } else { std::map<std::string, GmatBase *>::iterator mapi; mapi = objectStore->find(funcObjName); if (mapi != objectStore->end()) { GmatBase *mapObj = (mapi->second); #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" '%s' already exist: <%p>[%s]'%s'\n", funcObjName.c_str(), mapObj, mapObj->GetTypeName().c_str(), mapObj->GetName().c_str()); MessageInterface::ShowMessage (" Now checking if input parameter is redefined to different type\n"); #endif // Check if input parameter is redefined in a function if (funcObj->GetTypeName() != mapObj->GetTypeName()) { // Check for return type if object type is Parameter? // (fix for GMT-5262 LOJ: 2015.09.04) if (funcObj->IsOfType(Gmat::PARAMETER) && mapObj->IsOfType(Gmat::PARAMETER)) { if (((Parameter*)funcObj)->GetReturnType() != ((Parameter*)mapObj)->GetReturnType()) { throw FunctionException ("Redefinition of formal input parameter '" + funcObjName + "' to different type is not allowed in GMAT function '" + functionPath + "'. It's expected type is '" + mapObj->GetTypeName() + "'.\n"); } } } } } } // add automatic objects such as sat.X to the FOS (well, actually, clones of them) for (omi = automaticObjectMap.begin(); omi != automaticObjectMap.end(); ++omi) { std::string autoObjName = omi->first; GmatBase *autoObj = omi->second; #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" Add clone to objectStore if autoObj <%p>[%s]'%s' is not already in objectStore\n", autoObj, autoObj ? autoObj->GetTypeName().c_str() : "NULL", autoObjName.c_str()); MessageInterface::ShowMessage (" autoObj->IsGlobal=%d, autoObj->IsLocal=%d\n", autoObj->IsGlobal(), autoObj->IsLocal()); #endif // If automatic object owner (i.e Parameter owner) is global, set it global GmatBase *owner = NULL; if (IsAutomaticObjectGlobal(autoObjName, &owner)) { #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" autoObj <%p>'%s' is global, so setting isGlobal to true\n", autoObj, autoObjName.c_str()); MessageInterface::ShowMessage(GmatBase::WriteObjectInfo(" owner=", owner)); #endif autoObj->SetIsGlobal(true); // Set IsLocal to false to indicate it is not created inside a function (LOJ: 2015.10.03) owner->SetIsLocal(false); autoObj->SetIsLocal(false); } // if name not found, clone it and add to map (loj: 2008.12.15) std::map<std::string, GmatBase *>::iterator foundIter = objectStore->find(autoObjName); if (foundIter == objectStore->end()) { GmatBase *clonedAutoObj = autoObj->Clone(); #ifdef DEBUG_MEMORY MemoryTracker::Instance()->Add (clonedAutoObj, autoObjName, "BuiltinGmatFunction::Initialize()", "clonedAutoObj = (omi->second)->Clone()"); #endif #ifdef DEBUG_FUNCTION_INIT_MORE try { MessageInterface::ShowMessage (" clonedAutoObj(%s)->EvaluateReal() = %f\n", autoObjName.c_str(), clonedAutoObj->GetRealParameter("Value")); } catch (BaseException &e) { MessageInterface::ShowMessage("%s\n", e.GetFullMessage().c_str()); } #endif #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" ==> Adding clonedAutoObj <%p>'%s' to objectStore, isGlobal=%d, " "isLocal=%d\n", clonedAutoObj, autoObjName.c_str(), clonedAutoObj->IsGlobal(), clonedAutoObj->IsLocal()); if (owner) { GmatBase *paramOwner = clonedAutoObj->GetRefObject(owner->GetType(), owner->GetName()); MessageInterface::ShowMessage(GmatBase::WriteObjectInfo(" paramOwner=", paramOwner)); } #endif // Do not set IsLocal to true since it is cloned above (LOJ: 2015.10.03) //clonedAutoObj->SetIsLocal(true); objectStore->insert(std::make_pair(autoObjName, clonedAutoObj)); } } #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage(" If object is global, move it to globalObjectStore\n"); #endif // If object is global, move it to globalObjectStore for (omi = objectStore->begin(); omi != objectStore->end(); ++omi) { std::string objName = omi->first; GmatBase *obj = omi->second; #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" obj<%p>'%s' IsGlobal:%s, IsLocal:%s\n", obj, objName.c_str(), obj->IsGlobal() ? "Yes" : "No", obj->IsLocal() ? "Yes" : "No"); #endif // Check if it is global but not a local (means passed or locally created object) if (obj->IsGlobal() && !obj->IsLocal()) { if (globalObjectStore->find(objName) == globalObjectStore->end()) { #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" ==> obj<%p>'%s' is global and not local, so moving it from " "objectStore to globalObjectStore\n", obj, objName.c_str()); #endif globalObjectStore->insert(std::make_pair(objName, obj)); objectStore->erase(objName); } } else { #ifdef DEBUG_FUNCTION_INIT MessageInterface::ShowMessage (" ==> obj<%p>'%s' is global and local, so it stays in objectStore\n", obj, objName.c_str()); #endif } } return true; } //------------------------------------------------------------------------------ // bool SetStringParameter(const Integer id, const Real value) //------------------------------------------------------------------------------ /** * Sets the value for a std::string parameter. * * @param <id> Integer ID of the parameter. * @param <value> New value for the parameter. * * @return If value of the parameter was set. */ //------------------------------------------------------------------------------ bool BuiltinGmatFunction::SetStringParameter(const Integer id, const std::string &value) { #ifdef DEBUG_FUNCTION_SET MessageInterface::ShowMessage ("BuiltinGmatFunction::SetStringParameter() entered, id=%d, value=%s\n", id, value.c_str()); #endif bool retval = false; switch (id) { case FUNCTION_NAME: functionName = value; retval = true; break; default: retval = Function::SetStringParameter(id, value); break; } #ifdef DEBUG_FUNCTION_SET MessageInterface::ShowMessage ("BuiltinGmatFunction::SetStringParameter() returning %d\n", retval); #endif return retval; }
#include "XLSearchTask.h" #include "XLSearchParameters.h" #include "../../EngineLayer/CommonParameters.h" #include "../DbForTask.h" #include "../FileSpecificParameters.h" #include "../MyTaskResults.h" #include "../MyFileManager.h" #include "../../EngineLayer/Ms2ScanWithSpecificMass.h" #include "../../EngineLayer/GlobalVariables.h" #include "../../EngineLayer/EventArgs/ProgressEventArgs.h" #include "../../EngineLayer/PeptideSpectralMatch.h" #include "../../EngineLayer/CrosslinkSearch/PsmCrossType.h" #include <sstream> #include "MassSpectrometry/Enums/DissociationType.h" #include "UsefulProteomicsDatabases/DecoyType.h" #include "pepXML/pepXML_v120.h" #include "stringhelper.h" #include "time.h" using namespace EngineLayer; using namespace EngineLayer::CrosslinkSearch; using namespace EngineLayer::Indexing; using namespace MassSpectrometry; using namespace Proteomics; using namespace Proteomics::ProteolyticDigestion; using namespace MzLibUtil; using namespace EngineLayer::FdrAnalysis; using namespace Proteomics::Fragmentation; //Hard coding for now the timing break down of the XLSearchTask, since this //is the main area of interest right now. //#define TIMING_INFO 1 #ifdef TIMING_INFO #include <sys/time.h> static double timediff (struct timeval t1, struct timeval t2) { double elapsedtime; elapsedtime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedtime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms return elapsedtime/1000; //ms to sec } #endif namespace TaskLayer { XLSearchTask::XLSearchTask() : MetaMorpheusTask(MyTask::XLSearch) { std::string taskDescr = ""; DissociationType dissType = DissociationType::HCD; int topNpeaks = 200; double minRatio = 0.01; bool trimMs1Peaks = false; bool trimMsMsPeaks = true; bool useDeltaScore = false; bool calculateEValue = false; auto tempVar = new EngineLayer::CommonParameters( taskDescr, dissType, true, true, 3, 12, true, false, 1, 3, topNpeaks, minRatio, trimMs1Peaks, trimMsMsPeaks, useDeltaScore, calculateEValue, nullptr, new PpmTolerance(10)); setCommonParameters(tempVar); auto tempVar2 = new TaskLayer::XlSearchParameters(); setXlSearchParameters(tempVar2); } XLSearchTask::XLSearchTask(std::string tomlFile ) : MetaMorpheusTask(MyTask::XLSearch) { //Check ending that it is a toml file. Toml trw; toml::Value toml_value = trw.tomlReadFile(tomlFile); toml::Value* fileParameters = trw.getValue(toml_value, "XlSearchParameters"); toml::Table tomlTable = fileParameters->as<toml::Table>(); auto xlParams = new TaskLayer::XlSearchParameters(); // parse toml file and set the values for (auto const& keyValuePair : tomlTable) { // we're using the name of the variable here and not a fixed string // in case the variable name changes at some point if (keyValuePair.first == "DecoyType") { auto val = keyValuePair.second.as<std::string>(); xlParams->setDecoyType(DecoyTypeFromString(val )); } else if ( keyValuePair.first == "CrosslinkerType") { auto val = keyValuePair.second.as<std::string>(); xlParams->setCrosslinkerType(CrosslinkerTypeFromString(val)); } else if ( keyValuePair.first == "CrosslinkSearchTopNum") { xlParams->setCrosslinkSearchTopNum(keyValuePair.second.as<int>() ); } else if ( keyValuePair.first == "CrosslinkerResidues" ) { xlParams->setCrosslinkerResidues(keyValuePair.second.as<std::string>() ); } else if ( keyValuePair.first == "CrosslinkerResidues2" ) { xlParams->setCrosslinkerResidues2(keyValuePair.second.as<std::string>() ); } else if ( keyValuePair.first == "IsCleavable" ) { xlParams->setIsCleavable ( keyValuePair.second.as<bool>() ); } else if ( keyValuePair.first == "RestrictToTopNHits" ) { xlParams->setRestrictToTopNHits(keyValuePair.second.as<bool>() ); } else if ( keyValuePair.first == "WriteOutputForPercolator" ) { xlParams->setWriteOutputForPercolator(keyValuePair.second.as<bool>() ) ; } else if ( keyValuePair.first == "WritePepXml") { xlParams->setWritePepXml( keyValuePair.second.as<bool>() ); } else if ( keyValuePair.first == "XlQuench_H2O") { xlParams->setXlQuench_H2O(keyValuePair.second.as<bool>() ); } else if ( keyValuePair.first == "XlQuench_Tris") { xlParams->setXlQuench_Tris(keyValuePair.second.as<bool>() ); } else if ( keyValuePair.first == "XlQuench_NH2") { xlParams->setXlQuench_NH2(keyValuePair.second.as<bool>() ); } } setXlSearchParameters(xlParams); // Do we need to read the common parameters as well? Probably yes. std::string taskDescr = ""; auto tempVar = new EngineLayer::CommonParameters( tomlFile, taskDescr ); setCommonParameters(tempVar); } void XLSearchTask::writeTomlConfig(std::string &filename, std::ofstream &tomlFd ) { if ( !tomlFd.is_open() ) { tomlFd.open(filename ); if ( !tomlFd.is_open() ) { std::cout << "XLSearchTask: Could not open file " << filename << std::endl; return; } } toml::Value v; std::string key = "TaskType", value = "XLSearch"; v.set ( key, value); tomlFd << v; XlSearchParameters *xlparams = getXlSearchParameters(); toml::Table search_params; auto tvar1 = xlparams->getDecoyType(); search_params["DecoyType"] = DecoyTypeToString(tvar1); auto tvar2 = xlparams->getCrosslinkerType(); search_params["CrosslinkerType"] = CrosslinkerTypeToString(tvar2); search_params["CrosslinkSearchTopNum"] = xlparams->getCrosslinkSearchTopNum(); //search_params[""] = xlparams->std::string getCrosslinkerName(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerTotalMass(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerShortMass(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerLongMass(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerLoopMass(); search_params["CrosslinkerResidues"] = xlparams->getCrosslinkerResidues(); search_params["CrosslinkerResidues2"] = xlparams->getCrosslinkerResidues2(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerDeadEndMassH2O(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerDeadEndMassNH2(); //search_params[""] = xlparams->std::optional<double> getCrosslinkerDeadEndMassTris(); search_params["IsCleavable"] = xlparams->getIsCleavable(); search_params["RestrictToTopNHits"] = xlparams->getRestrictToTopNHits(); search_params["WriteOutputForPercolator"] = xlparams->getWriteOutputForPercolator(); search_params["WritePepXml"] = xlparams->getWritePepXml(); search_params["XlQuench_H2O"] = xlparams->getXlQuench_H2O(); search_params["XlQuench_Tris"] = xlparams->getXlQuench_Tris(); search_params["XlQuench_NH2"] = xlparams->getXlQuench_NH2(); tomlFd << std::endl; tomlFd << "[XlSearchParameters]" << std::endl; tomlFd << search_params; // Now write the generic parameters MetaMorpheusTask::writeTomlConfig(filename, tomlFd ); if ( tomlFd.is_open() ) { tomlFd.close(); } return; } TaskLayer::XlSearchParameters *XLSearchTask::getXlSearchParameters() const { return privateXlSearchParameters; } std::vector<Protein*> XLSearchTask::getProteinList () const { return proteinList; } void XLSearchTask::setXlSearchParameters(TaskLayer::XlSearchParameters *value) { if (privateXlSearchParameters != nullptr ) { delete privateXlSearchParameters; } privateXlSearchParameters = value; } MyTaskResults *XLSearchTask::RunSpecific(const std::string &OutputFolder, std::vector<DbForTask*> &dbFilenameList, std::vector<std::string> &currentRawFileList, const std::string &taskId, std::vector<FileSpecificParameters*> &fileSettingsList) { myTaskResults = new MyTaskResults(this); std::vector<CrosslinkSpectralMatch*> allPsms; std::vector<Modification*> variableModifications; std::vector<Modification*> fixedModifications; std::vector<std::string> localizeableModificationTypes; #ifdef TIMING_INFO struct timeval t1, t1e; struct timeval t2, t2e; struct timeval t3, t3e; struct timeval t4, t4e; struct timeval t5, t5e; struct timeval t6, t6e; struct timeval t7, t7e; struct timeval t8, t8e; struct timeval t9, t9e; double t3total=0.0, t4total=0.0, t5total=0.0, t6total=0.0; gettimeofday (&t1, NULL); #endif LoadModifications(taskId, variableModifications, fixedModifications, localizeableModificationTypes); #ifdef TIMING_INFO gettimeofday (&t1e, NULL); #endif // load proteins #ifdef TIMING_INFO gettimeofday (&t2, NULL); #endif proteinList = LoadProteins(taskId, dbFilenameList, true, getXlSearchParameters()->getDecoyType(), localizeableModificationTypes, getCommonParameters()); #ifdef TIMING_INFO gettimeofday (&t2e, NULL); #endif auto crosslinker = new Crosslinker(); crosslinker = crosslinker->SelectCrosslinker(getXlSearchParameters()->getCrosslinkerType()); if (getXlSearchParameters()->getCrosslinkerType() == CrosslinkerType::UserDefined) { crosslinker = GenerateUserDefinedCrosslinker(getXlSearchParameters()); } MyFileManager *myFileManager = new MyFileManager(true); std::vector<CommonParameters *> fileSpecificCommonParams; for ( auto b : fileSettingsList ) { fileSpecificCommonParams.push_back(SetAllFileSpecificCommonParams(getCommonParameters(), b)); } std::unordered_set<DigestionParams*> ListOfDigestionParams; for ( auto p : fileSpecificCommonParams ) { ListOfDigestionParams.emplace(p->getDigestionParams()); } int completedFiles = 0; //std::any indexLock = std::any(); //std::any psmLock = std::any(); Status("Searching files...", taskId, getVerbose() ); DigestionParams *dPar = getCommonParameters()->getDigestionParams(); ProseCreatedWhileRunning->append("The following crosslink discovery were used: "); ProseCreatedWhileRunning->append("crosslinker name = " + crosslinker->getCrosslinkerName() + "; "); std::string ss = "true"; if ( !crosslinker->getCleavable() ) ss = "false"; ProseCreatedWhileRunning->append("crosslinker type = " + ss + "; "); ProseCreatedWhileRunning->append("crosslinker mass = " + std::to_string(crosslinker->getTotalMass()) + "; "); ProseCreatedWhileRunning->append("crosslinker modification site(s) = " + crosslinker->getCrosslinkerModSites() + "; "); ProseCreatedWhileRunning->append("protease = " + dPar->getProtease()->ToString() + "; "); ProseCreatedWhileRunning->append("maximum missed cleavages = " + std::to_string(dPar->getMaxMissedCleavages()) + "; "); ProseCreatedWhileRunning->append("minimum peptide length = " + std::to_string(dPar->getMinPeptideLength()) + "; "); ProseCreatedWhileRunning->append(dPar->getMaxPeptideLength() == std::numeric_limits<int>::max() ? "maximum peptide length = unspecified; " : "maximum peptide length = " + std::to_string(dPar->getMaxPeptideLength()) + "; "); ProseCreatedWhileRunning->append("initiator methionine behavior = " + ProteolyticDigestion::InitiatorMethionineBehaviorToString(dPar->getInitiatorMethionineBehavior()) + "; "); ProseCreatedWhileRunning->append("max modification isoforms = " + std::to_string(dPar->getMaxModificationIsoforms()) + "; "); std::vector<std::string> vsv; for ( auto m : fixedModifications ) { vsv.push_back(m->getIdWithMotif()); } std::string del = ", "; ProseCreatedWhileRunning->append("fixed modifications = " + StringHelper::join ( vsv, del) + "; "); vsv.clear(); for ( auto m : variableModifications ) { vsv.push_back(m->getIdWithMotif()); } ProseCreatedWhileRunning->append("variable modifications = " + StringHelper::join ( vsv, del) + "; "); ProseCreatedWhileRunning->append("parent mass tolerance(s) = ±" + std::to_string(getCommonParameters()->getPrecursorMassTolerance()->getValue()) + " PPM; "); ProseCreatedWhileRunning->append("product mass tolerance = ±" + std::to_string(getCommonParameters()->getProductMassTolerance()->getValue()) + " PPM; "); int c1 = 0; for ( auto p: proteinList ) { if (p->getIsContaminant()) { c1++; } } ProseCreatedWhileRunning->append("The combined search database contained " + std::to_string(proteinList.size()) + " total entries including " + std::to_string(c1) + " contaminant sequences. "); // The following vectors are only required for memory management at the end of the Task std::vector<CrosslinkSearchEngine *> csengines; std::vector<Ms2ScanWithSpecificMass*> Ms2Scans; std::unordered_set<PeptideWithSetModifications*> peptides; for (int spectraFileIndex = 0; spectraFileIndex < (int)currentRawFileList.size(); spectraFileIndex++) { auto origDataFile = currentRawFileList[spectraFileIndex]; EngineLayer::CommonParameters *combinedParams = SetAllFileSpecificCommonParams(getCommonParameters(), fileSettingsList[spectraFileIndex]); auto thisId = std::vector<std::string> {taskId, "Individual Spectra Files", origDataFile}; Status("Loading spectra file...", thisId, getVerbose() ); #ifdef TIMING_INFO gettimeofday (&t3, NULL); #endif MsDataFile *myMsDataFile = myFileManager->LoadFile(origDataFile, std::make_optional(combinedParams->getTopNpeaks()), std::make_optional(combinedParams->getMinRatio()), combinedParams->getTrimMs1Peaks(), combinedParams->getTrimMsMsPeaks(), combinedParams); #ifdef TIMING_INFO gettimeofday (&t3e, NULL); t3total += timediff(t3, t3e); #endif Status("Getting ms2 scans...", thisId, getVerbose()); #ifdef TIMING_INFO gettimeofday (&t4, NULL); #endif std::vector<Ms2ScanWithSpecificMass*> arrayOfMs2ScansSortedByMass= GetMs2Scans(myMsDataFile, origDataFile, combinedParams); std::sort(arrayOfMs2ScansSortedByMass.begin(), arrayOfMs2ScansSortedByMass.end(), [&] (Ms2ScanWithSpecificMass* l, Ms2ScanWithSpecificMass* r) { return l->getPrecursorMass() < r->getPrecursorMass(); }); Ms2Scans.insert(Ms2Scans.end(), arrayOfMs2ScansSortedByMass.begin(), arrayOfMs2ScansSortedByMass.end() ); #ifdef TIMING_INFO gettimeofday (&t4e, NULL); t4total += timediff (t4, t4e); #endif std::vector<CrosslinkSpectralMatch*> newPsms(arrayOfMs2ScansSortedByMass.size()); for (int currentPartition = 0; currentPartition < getCommonParameters()->getTotalPartitions(); currentPartition++) { std::vector<PeptideWithSetModifications*> peptideIndex; int start = currentPartition * proteinList.size() / combinedParams->getTotalPartitions(); int count = ((currentPartition + 1) * proteinList.size() / combinedParams->getTotalPartitions()) - (currentPartition * proteinList.size() /combinedParams->getTotalPartitions()); std::vector<Protein*> proteinListSubset; for ( auto p=0; p<count; p++ ) { proteinListSubset.push_back(proteinList[start+p]); } std::vector<std::string> vs = {taskId}; Status("Getting fragment dictionary...", vs, getVerbose()); std::vector<std::string> filenameList; for ( auto p: dbFilenameList ) { filenameList.push_back(p->getFilePath()); } std::vector<std::string> vtaskId = {"IndexingEngine", taskId}; #ifdef TIMING_INFO gettimeofday (&t5, NULL); #endif auto indexEngine = new IndexingEngine(proteinListSubset, variableModifications, fixedModifications, currentPartition, UsefulProteomicsDatabases::DecoyType::Reverse, combinedParams, 30000.0, false, filenameList, vtaskId, getVerbose() ); std::vector<std::vector<int>> fragmentIndex; std::vector<std::vector<int>> precursorIndex; auto allmods = GlobalVariables::getAllModsKnown(); GenerateIndexes(indexEngine, dbFilenameList, peptideIndex, fragmentIndex, precursorIndex, proteinList, allmods, taskId); #ifdef TIMING_INFO gettimeofday (&t5e, NULL); t5total += timediff(t5, t5e ); #endif Status("Searching files...", taskId, getVerbose()); #ifdef TIMING_INFO gettimeofday (&t6, NULL); #endif std::vector<std::string> thisId2 = {"CrosslinkSearchEngine", taskId, "Individual Spectra Files", origDataFile}; auto tempVar = new CrosslinkSearchEngine (newPsms, arrayOfMs2ScansSortedByMass, peptideIndex, fragmentIndex, currentPartition, combinedParams, crosslinker, getXlSearchParameters()->getRestrictToTopNHits(), getXlSearchParameters()->getCrosslinkSearchTopNum(), getXlSearchParameters()->getXlQuench_H2O(), getXlSearchParameters()->getXlQuench_NH2(), getXlSearchParameters()->getXlQuench_Tris(), thisId2, getVerbose()); csengines.push_back(tempVar); tempVar->Run(); #ifdef TIMING_INFO gettimeofday (&t6e, NULL); t6total += timediff (t6, t6e ); #endif std::string s1 = "Done with search " + std::to_string(currentPartition + 1) + "/" + std::to_string(getCommonParameters()->getTotalPartitions()) + "!"; ProgressEventArgs tempVar2(100, s1, thisId); ReportProgress(&tempVar2, getVerbose() ); // Store the pointers for later deletion for ( auto p = peptideIndex.begin(); p != peptideIndex.end(); p++ ){ peptides.emplace(*p); } delete indexEngine; } for ( auto p : newPsms ) { if ( p != nullptr ) { allPsms.push_back(p); } } completedFiles++; std::vector<std::string> vs2 = {taskId, "Individual Spectra Files"}; ProgressEventArgs tempVar3(completedFiles / currentRawFileList.size(), "Searching...", vs2); ReportProgress(&tempVar3, getVerbose()); } std::vector<std::string> vs3 = {taskId, "Individual Spectra Files"}; ProgressEventArgs tempVar4(100, "Done with all searches!", vs3); ReportProgress(&tempVar4, getVerbose()); std::sort(allPsms.begin(), allPsms.end(), [&] (CrosslinkSpectralMatch *l, CrosslinkSpectralMatch *r) { return l->getXLTotalScore() > r->getXLTotalScore(); }); std::vector<CrosslinkSpectralMatch *> allPsmsXL; for ( auto p : allPsms ) { if ( p->getCrossType() == PsmCrossType::Cross ){ allPsmsXL.push_back(p); } } // inter-crosslinks; different proteins are linked std::vector<CrosslinkSpectralMatch *> interCsms; for ( auto p: allPsmsXL ) { if ( p->getProteinAccession() != p->getBetaPeptide()->getProteinAccession() ) { interCsms.push_back(p); } } for (auto item : interCsms) { item->setCrossType(PsmCrossType::Inter); } // intra-crosslinks; crosslinks within a protein std::vector<CrosslinkSpectralMatch *> intraCsms; for ( auto p: allPsmsXL ) { if ( p->getProteinAccession() == p->getBetaPeptide()->getProteinAccession() ) { intraCsms.push_back(p); } } for (auto item : intraCsms) { item->setCrossType(PsmCrossType::Intra); } // calculate FDR #ifdef TIMING_INFO gettimeofday (&t7, NULL); #endif DoCrosslinkFdrAnalysis(interCsms); DoCrosslinkFdrAnalysis(intraCsms); std::vector<std::string> sv1 = {"FdrAnalysisEngine", taskId}; SingleFDRAnalysis(allPsms, sv1 ); #ifdef TIMING_INFO gettimeofday (&t7e, NULL); #endif // calculate protein crosslink residue numbers #ifdef TIMING_INFO gettimeofday (&t8, NULL); #endif for (auto csm : allPsmsXL) { // alpha peptide crosslink residue in the protein csm->setXlProteinPos(csm->getOneBasedStartResidueInProtein().value() + csm->getLinkPositions()[0] - 1); // beta crosslink residue in protein csm->getBetaPeptide()->setXlProteinPos(csm->getBetaPeptide()->getOneBasedStartResidueInProtein().value() + csm->getBetaPeptide()->getLinkPositions()[0] - 1); } #ifdef TIMING_INFO gettimeofday (&t8e, NULL); #endif // write interlink CSMs #ifdef TIMING_INFO gettimeofday (&t9, NULL); #endif if (!interCsms.empty()) { std::string file = OutputFolder + "/XL_Interlinks.tsv"; WritePsmCrossToTsv(interCsms, file, 2); std::vector<std::string> vs2 = {taskId}; FinishedWritingFile(file, vs2, getVerbose()); } int interCsms_size=0; for ( auto p: interCsms ) { if ( p->getFdrInfo()->getQValue() <= 0.01 && !p->getIsDecoy() && !p->getBetaPeptide()->getIsDecoy() ) { interCsms_size++; } } myTaskResults->AddNiceText("Target inter-crosslinks within 1% FDR: " + std::to_string(interCsms_size)); if (getXlSearchParameters()->getWriteOutputForPercolator()) { std::vector<CrosslinkSpectralMatch *> interPsmsXLPercolator ; for ( auto p: interCsms ) { if (p->getScore() >= 2 && p->getBetaPeptide()->getScore() >= 2 ) { interPsmsXLPercolator.push_back(p); } } std::sort(interPsmsXLPercolator.begin(), interPsmsXLPercolator.end(), [&] (CrosslinkSpectralMatch *l , CrosslinkSpectralMatch *r ) { return l->getScanNumber() < r->getScanNumber(); }); std::vector<std::string> vs2a = {taskId}; WriteCrosslinkToTxtForPercolator(interPsmsXLPercolator, OutputFolder, "XL_Interlinks_Percolator", crosslinker, vs2a); } // write intralink CSMs if (!intraCsms.empty()) { std::string file = OutputFolder + "/XL_Intralinks.tsv"; WritePsmCrossToTsv(intraCsms, file, 2); std::vector<std::string> vs3 = {taskId}; FinishedWritingFile(file, vs3, getVerbose()); } int intraCsms_size=0; for ( auto p: intraCsms ) { if ( p->getFdrInfo()->getQValue() <= 0.01 && !p->getIsDecoy() && !p->getBetaPeptide()->getIsDecoy() ) { intraCsms_size++; } } myTaskResults->AddNiceText("Target intra-crosslinks within 1% FDR: " +std::to_string(intraCsms_size)); if (getXlSearchParameters()->getWriteOutputForPercolator()) { std::vector<CrosslinkSpectralMatch *> intraPsmsXLPercolator ; for ( auto p: intraCsms ) { if (p->getScore() >= 2 && p->getBetaPeptide()->getScore() >= 2 ) { intraPsmsXLPercolator.push_back(p); } } std::sort(intraPsmsXLPercolator.begin(), intraPsmsXLPercolator.end(), [&] (CrosslinkSpectralMatch *l , CrosslinkSpectralMatch *r ) { return l->getScanNumber() < r->getScanNumber(); }); std::vector<std::string> vs3a = {taskId}; WriteCrosslinkToTxtForPercolator(intraPsmsXLPercolator, OutputFolder, "XL_Intralinks_Percolator", crosslinker, vs3a); } // write single peptides std::vector<CrosslinkSpectralMatch *> singlePsms; for ( auto p: allPsms ) { if ( p->getCrossType() == PsmCrossType::Single ) { singlePsms.push_back(p); } } if (!singlePsms.empty()) { std::string writtenFileSingle = OutputFolder + "/SinglePeptides" + ".tsv"; WritePsmCrossToTsv(singlePsms, writtenFileSingle, 1); std::vector<std::string> vs4 = {taskId}; FinishedWritingFile(writtenFileSingle, vs4, getVerbose()); } int singlePsms_size=0; for ( auto p: singlePsms ) { if (p->getFdrInfo()->getQValue() <= 0.01 && !p->getIsDecoy()) { singlePsms_size++; } } myTaskResults->AddNiceText("Target single peptides within 1% FDR: " + std::to_string(singlePsms_size)); // write loops std::vector<CrosslinkSpectralMatch *> loopPsms; for ( auto p : allPsms ) { if ( p->getCrossType() == PsmCrossType::Loop ) { loopPsms.push_back(p); } } if (!loopPsms.empty()) { std::string writtenFileLoop = OutputFolder + "/Looplinks" + ".tsv"; WritePsmCrossToTsv(loopPsms, writtenFileLoop, 1); std::vector<std::string> vs4a = {taskId}; FinishedWritingFile(writtenFileLoop, vs4a, getVerbose()); } int loopPsms_size =0; for ( auto p : loopPsms ) { if ( p->getFdrInfo()->getQValue() <= 0.01 && !p->getIsDecoy()) { loopPsms_size++; } } myTaskResults->AddNiceText("Target loop-linked peptides within 1% FDR: " + std::to_string(loopPsms_size)); // write deadends std::vector<CrosslinkSpectralMatch *> deadendPsms; for ( auto p : allPsms ) { if ( p->getCrossType() == PsmCrossType::DeadEnd || p->getCrossType() == PsmCrossType::DeadEndH2O || p->getCrossType() == PsmCrossType::DeadEndNH2 || p->getCrossType() == PsmCrossType::DeadEndTris) { deadendPsms.push_back(p); } } if (!deadendPsms.empty()) { std::string writtenFileDeadend = OutputFolder + "/Deadends" + ".tsv"; WritePsmCrossToTsv(deadendPsms, writtenFileDeadend, 1); std::vector<std::string> vs5a = {taskId}; FinishedWritingFile(writtenFileDeadend, vs5a, getVerbose()); } int deadendPsms_size =0; for ( auto p : deadendPsms ) { if ( p->getFdrInfo()->getQValue() <= 0.01 && !p->getIsDecoy()) { deadendPsms_size++; } } myTaskResults->AddNiceText("Target deadend peptides within 1% FDR: " + std::to_string(deadendPsms_size)); // write pepXML if (getXlSearchParameters()->getWritePepXml()) { std::vector<CrosslinkSpectralMatch*> writeToXml; for ( auto p: intraCsms ) { if ( !p->getIsDecoy() && !p->getBetaPeptide()->getIsDecoy() && p->getFdrInfo()->getQValue() <= 0.05) { writeToXml.push_back(p); } } for ( auto p: interCsms ) { if ( !p->getIsDecoy() && !p->getBetaPeptide()->getIsDecoy() && p->getFdrInfo()->getQValue() <= 0.05 ) { writeToXml.push_back(p); } } for ( auto p: singlePsms ) { if (!p->getIsDecoy() && p->getFdrInfo()->getQValue() <= 0.05) { writeToXml.push_back(p); } } for ( auto p: loopPsms ) { if ( !p->getIsDecoy() && p->getFdrInfo()->getQValue() <= 0.05 ) { writeToXml.push_back(p); } } for ( auto p: deadendPsms ) { if ( !p->getIsDecoy() && p->getFdrInfo()->getQValue() <= 0.05 ) { writeToXml.push_back(p); } } std::sort(writeToXml.begin(), writeToXml.end(), [&] (CrosslinkSpectralMatch *l, CrosslinkSpectralMatch *r ) { return l->getScanNumber() < r->getScanNumber(); }); for (auto fullFilePath : currentRawFileList) { std::string fileName = fullFilePath.substr(0, fullFilePath.find_last_of(".")); std::string fileNameNoExtension = fileName.substr(fileName.find_last_of("/")); std::vector<std::string> vs6 = {taskId}; std::vector<CrosslinkSpectralMatch*> tmpwriteToXml; for ( auto p: writeToXml ) { if ( p->getFullFilePath() == fullFilePath ) { tmpwriteToXml.push_back(p); } } WritePepXML_xl(tmpwriteToXml, proteinList, dbFilenameList[0]->getFilePath(), variableModifications, fixedModifications, localizeableModificationTypes, OutputFolder, fileNameNoExtension, vs6); } } #ifdef TIMING_INFO gettimeofday (&t9e, NULL); std::cout << "Load Modifications : " << timediff(t1, t1e ) << " sec \n"; std::cout << "Load Proteins : " << timediff(t2, t2e ) << " sec \n"; std::cout << "Load Files : " << t3total << " sec \n"; std::cout << "GetMs2Scans : " << t4total << " sec \n"; std::cout << "GenerateIndixes : " << t5total << " sec \n"; std::cout << "CrosslinkSearch : " << t6total << " sec \n"; std::cout << "FdrAnalysis : " << timediff(t7, t7e) << " sec \n"; std::cout << "Calculate Residue numbers : " << timediff(t8, t8e) << " sec \n"; std::cout << "Write results : " << timediff(t9, t9e) << " sec \n"; #endif // Memory cleanup. for ( auto p: proteinList ) { delete p; } for ( auto m : Ms2Scans ) { delete m; } for ( auto a: allPsms ) { delete a; } for (auto p = peptides.begin(); p!= peptides.end() ; p++ ) { delete (*p); } for ( auto csengine : csengines ) { delete csengine; } delete myFileManager; //C# TO C++ CONVERTER TODO TASK: A 'delete crosslinker' statement was not added since crosslinker was //passed to a method or constructor. Handle memory management manually. return myTaskResults; } void XLSearchTask::SingleFDRAnalysis(std::vector<CrosslinkSpectralMatch*> &items, std::vector<std::string> &taskIds) { // calculate single PSM FDR std::vector<PeptideSpectralMatch*> psms; for ( auto p: items ) { if ( p->getCrossType() == PsmCrossType::Single ) { psms.push_back(dynamic_cast<PeptideSpectralMatch*>(p)); } } FdrAnalysisEngine tempVar(psms, 0, getCommonParameters(), taskIds, getVerbose()); tempVar.Run(); // calculate loop PSM FDR psms.clear(); for ( auto p: items ) { if ( p->getCrossType() == PsmCrossType::Loop ) { psms.push_back(dynamic_cast<PeptideSpectralMatch*>(p)); } } FdrAnalysisEngine tempVar2(psms, 0, getCommonParameters(), taskIds, getVerbose()); tempVar2.Run(); // calculate deadend FDR psms.clear(); for ( auto p: items ) { if ( p->getCrossType() == PsmCrossType::DeadEnd || p->getCrossType() == PsmCrossType::DeadEndH2O || p->getCrossType() == PsmCrossType::DeadEndNH2 || p->getCrossType() == PsmCrossType::DeadEndTris ) { psms.push_back(dynamic_cast<PeptideSpectralMatch*>(p)); } } FdrAnalysisEngine tempVar3(psms, 0, getCommonParameters(), taskIds, getVerbose() ); tempVar3.Run(); } void XLSearchTask::DoCrosslinkFdrAnalysis(std::vector<CrosslinkSpectralMatch*> &csms) { int cumulativeTarget = 0; int cumulativeDecoy = 0; for (int i = 0; i < (int)csms.size(); i++) { auto csm = csms[i]; if (csm->getIsDecoy() || csm->getBetaPeptide()->getIsDecoy()) { cumulativeDecoy++; } else { cumulativeTarget++; } double qValue = std::min((double)1.0, static_cast<double>(cumulativeDecoy) / cumulativeTarget); csm->SetFdrValues(cumulativeTarget, cumulativeDecoy, qValue, 0, 0, 0, 0, 0, 0, false); } double qValueThreshold = 1.0; for (int i = csms.size() - 1; i >= 0; i--) { CrosslinkSpectralMatch *csm = csms[i]; // threshold q-values if (csm->getFdrInfo()->getQValue() > qValueThreshold) { csm->getFdrInfo()->setQValue(qValueThreshold); } else if (csm->getFdrInfo()->getQValue() < qValueThreshold) { qValueThreshold = csm->getFdrInfo()->getQValue(); } } } Crosslinker *XLSearchTask::GenerateUserDefinedCrosslinker(TaskLayer::XlSearchParameters *xlSearchParameters) { std::optional<double> tempVar = xlSearchParameters->getCrosslinkerTotalMass(); std::optional<double> tempVar2 = xlSearchParameters->getCrosslinkerShortMass(); std::optional<double> tempVar3 = xlSearchParameters->getCrosslinkerLongMass(); std::optional<double> tempVar4 = xlSearchParameters->getCrosslinkerLoopMass(); std::optional<double> tempVar5 = xlSearchParameters->getCrosslinkerDeadEndMassH2O(); std::optional<double> tempVar6 = xlSearchParameters->getCrosslinkerDeadEndMassNH2(); std::optional<double> tempVar7 = xlSearchParameters->getCrosslinkerDeadEndMassTris(); auto crosslinker = new Crosslinker(xlSearchParameters->getCrosslinkerResidues(), xlSearchParameters->getCrosslinkerResidues2(), xlSearchParameters->getCrosslinkerName(), xlSearchParameters->getIsCleavable(), tempVar.has_value() ? tempVar.value() : NAN, tempVar2.has_value() ? tempVar2.value() : NAN, tempVar3.has_value() ? tempVar3.value() : NAN, tempVar4.has_value() ? tempVar4.value() : NAN, tempVar5.has_value() ? tempVar5.value() : NAN, tempVar6.has_value() ? tempVar6.value() : NAN, tempVar7.has_value() ? tempVar7.value() : NAN); return crosslinker; } void XLSearchTask::WritePsmCrossToTsv(std::vector<CrosslinkSpectralMatch*> &items, const std::string &filePath, int writeType) { if (items.empty()) { return; } //StreamWriter output = StreamWriter(filePath); std::ofstream output (filePath); std::string header; switch (writeType) { case 1: header = CrosslinkSpectralMatch::GetTabSepHeaderSingle(); break; case 2: header = CrosslinkSpectralMatch::GetTabSepHeaderCross(); break; default: break; } output << header << std::endl; for (auto heh : items) { output << heh->ToString() << std::endl; } output.close(); } void XLSearchTask::WriteCrosslinkToTxtForPercolator(std::vector<CrosslinkSpectralMatch*> &items, const std::string &outputFolder, const std::string &fileName, Crosslinker *crosslinker, std::vector<std::string> &nestedIds) { if (items.empty()) { return; } std::string writtenFile = outputFolder + "/" + fileName + ".txt"; { std::ofstream output(writtenFile); std::string s = "SpecId\tLabel\tScannr\tScore\tdScore\tNormRank\tCharge\tMass\tPPM\tLenShort\tLenLong\tLenSum"; std::string s2 = "\tPeptide\tProtein"; output << s << s2 << std::endl; for (auto item : items) { if (item->getBaseSequence() != "" && item->getBetaPeptide()->getBaseSequence() != "" && item->getProteinAccession() != "" && item->getBetaPeptide()->getProteinAccession() != "") { std::string x = "T"; int label = 1; if (item->getIsDecoy() || item->getBetaPeptide()->getIsDecoy()) { x = "D"; label = -1; } output << x + "-" + std::to_string(item->getScanNumber()) + "-" + std::to_string(item->getScanRetentionTime()) + "\t" + std::to_string(label) + "\t" + std::to_string(item->getScanNumber()) + "\t" + std::to_string(item->getXLTotalScore()) + "\t" + std::to_string(item->getDeltaScore()) + "\t" + std::to_string(item->getXlRank()[0] + item->getXlRank()[1])+ "\t" + std::to_string(item->getScanPrecursorCharge()) + "\t" + std::to_string(item->getScanPrecursorMass()) + "\t" + ((item->getPeptideMonisotopicMass().has_value() && item->getBetaPeptide()->getPeptideMonisotopicMass().has_value() ) ? std::to_string((item->getScanPrecursorMass() - item->getBetaPeptide()->getPeptideMonisotopicMass().value() - item->getPeptideMonisotopicMass().value() - crosslinker->getTotalMass()) / item->getScanPrecursorMass() * 1E6) : "---") + "\t" + std::to_string(item->getBetaPeptide()->getBaseSequence().length()) + "\t" + std::to_string(item->getBaseSequence().length()) + "\t" + std::to_string(item->getBetaPeptide()->getBaseSequence().length() + item->getBaseSequence().length()) + "\t" + "-." + item->getBaseSequence() + std::to_string(item->getLinkPositions().front()) + "--" + item->getBetaPeptide()->getBaseSequence() + std::to_string(item->getBetaPeptide()->getLinkPositions().front()) + ".-" + "\t" + std::get<1>(item->getBestMatchingPeptides().front())->getProtein()->getAccession() + "(" + std::to_string(item->getXlProteinPos()) + ")" + "\t" + std::get<1>(item->getBetaPeptide()->getBestMatchingPeptides().front())->getProtein()->getAccession() + "(" + std::to_string(item->getBetaPeptide()->getXlProteinPos()) + ")" << std::endl; } } output.close(); } FinishedWritingFile(writtenFile, nestedIds, getVerbose()); } void XLSearchTask::WritePepXML_xl(std::vector<CrosslinkSpectralMatch*> &items, std::vector<Protein*> &proteinList, const std::string &databasePath, std::vector<Modification*> &variableModifications, std::vector<Modification*> &fixedModifications, std::vector<std::string> &localizeableModificationTypes, const std::string &outputFolder, const std::string &fileName, std::vector<std::string> &nestedIds) { if (items.empty()) { return; } //XmlSerializer *_indexedSerializer = new XmlSerializer(pepXML::Generated::msms_pipeline_analysis::typeid); //auto _pepxml = new pepXML::Generated::msms_pipeline_analysis(); auto _pepxml = new pepXML::msms_pipeline_analysis(); //_pepxml->date = DateTime::Now; //_pepxml->summary_xml = items[0]->getFullFilePath() + ".pep.XM"; time_t timer; time(&timer); struct tm *tmi = localtime(&timer); short zone_hours=0; short zone_minutes=0; ::xml_schema::date_time *dt = new ::xml_schema::date_time(tmi->tm_year, tmi->tm_mon, tmi->tm_mday, tmi->tm_hour, tmi->tm_min, (double)tmi->tm_sec, zone_hours, zone_minutes); _pepxml->date(*dt); _pepxml->summary_xml(items[0]->getFullFilePath() + ".pep.XML"); std::string proteaseC; std::string proteaseNC; for ( auto m : getCommonParameters()->getDigestionParams()->getProtease()->getDigestionMotifs() ) { proteaseC += m->InducingCleavage; } for ( auto m : getCommonParameters()->getDigestionParams()->getProtease()->getDigestionMotifs() ) { proteaseNC += m->PreventingCleavage; } auto tempVar = new Crosslinker(); Crosslinker *crosslinker = tempVar->SelectCrosslinker(getXlSearchParameters()->getCrosslinkerType()); if (getXlSearchParameters()->getCrosslinkerType() == CrosslinkerType::UserDefined) { crosslinker = GenerateUserDefinedCrosslinker(getXlSearchParameters()); } //std::string fileNameNoExtension = Path::GetFileNameWithoutExtension(items[0]->getFullFilePath()); std::string temps = items[0]->getFullFilePath(); std::string fileNameNoExtension = temps.substr(0, temps.find_last_of(".")); std::string filePathNoExtension = temps.substr(0, temps.find_last_of("/")); std::string s1 = crosslinker->getCrosslinkerModSites(); std::string s2 = crosslinker->getCrosslinkerModSites2(); std::vector<char> vs1 (s1.begin(), s1.end() ); std::vector<char> vs2 (s2.begin(), s2.end() ); std::vector<char> modChars = vs1; for ( auto c : vs2 ) { bool found = false; for ( auto c2: modChars ) { if ( c == c2 ) { found = true; break; } } if ( !found ) { modChars.push_back(c); } } std::string modSites(modChars.begin(), modChars.end()); //auto para = std::vector<pepXML::nameValueType*>(); auto para = new pepXML::search_summary::parameter_sequence(); { pepXML::nameValueType *tempVar2 = new pepXML::nameValueType(); tempVar2->name("threads"); tempVar2->value(std::to_string(getCommonParameters()->getMaxThreadsToUsePerFile())); para->push_back(*tempVar2); delete tempVar2; pepXML::nameValueType *tempVar3 = new pepXML::nameValueType(); tempVar3->name("database"); tempVar3->value(databasePath); para->push_back(*tempVar3); delete tempVar3; pepXML::nameValueType *tempVar4 = new pepXML::nameValueType(); tempVar4->name("MS_data_file"); tempVar4->value(items[0]->getFullFilePath()); para->push_back(*tempVar4); delete tempVar4; pepXML::nameValueType *tempVar5 = new pepXML::nameValueType(); tempVar5->name("Cross-link precursor Mass Tolerance"); tempVar5->value(std::to_string(getCommonParameters()->getPrecursorMassTolerance()->getValue())); para->push_back(*tempVar5); delete tempVar5; pepXML::nameValueType *tempVar6 = new pepXML::nameValueType(); tempVar6->name("Cross-linker type"); tempVar6->value(crosslinker->getCrosslinkerName()); para->push_back(*tempVar6); delete tempVar6; pepXML::nameValueType *tempVar7 = new pepXML::nameValueType(); tempVar7->name("Cross-linker mass"); tempVar7->value(std::to_string(crosslinker->getTotalMass())); para->push_back(*tempVar7); delete tempVar7; pepXML::nameValueType *tempVar8 = new pepXML::nameValueType(); tempVar8->name("Cross-linker cleavable"); tempVar8->value(StringHelper::toString(crosslinker->getCleavable())); para->push_back(*tempVar8); delete tempVar8; pepXML::nameValueType *tempVar9 = new pepXML::nameValueType(); tempVar9->name("Cross-linker cleavable long mass"); tempVar9->value(std::to_string(crosslinker->getCleaveMassLong())); para->push_back(*tempVar9); delete tempVar9; pepXML::nameValueType *tempVar10 = new pepXML::nameValueType(); tempVar10->name("Cross-linker cleavable short mass"); tempVar10->value(std::to_string(crosslinker->getCleaveMassShort())); para->push_back(*tempVar10); delete tempVar10; pepXML::nameValueType *tempVar11 = new pepXML::nameValueType(); tempVar11->name("Cross-linker xl site"); tempVar11->value(modSites); para->push_back(*tempVar11); delete tempVar11; pepXML::nameValueType *tempVar12 = new pepXML::nameValueType(); tempVar12->name("Generate decoy proteins"); auto tempVar12a = getXlSearchParameters()->getDecoyType(); tempVar12->value(DecoyTypeToString(tempVar12a)); para->push_back(*tempVar12); delete tempVar12; pepXML::nameValueType *tempVar13 = new pepXML::nameValueType(); tempVar13->name( "MaxMissed Cleavages"); tempVar13->value(std::to_string(getCommonParameters()->getDigestionParams()->getMaxMissedCleavages())); para->push_back(*tempVar13); delete tempVar13; pepXML::nameValueType *tempVar14 = new pepXML::nameValueType(); tempVar14->name( "Protease"); tempVar14->value(getCommonParameters()->getDigestionParams()->getProtease()->getName()); para->push_back(*tempVar14); delete tempVar14; pepXML::nameValueType *tempVar15 = new pepXML::nameValueType(); tempVar15->name( "Initiator Methionine"); auto tmpVar15a = getCommonParameters()->getDigestionParams()->getInitiatorMethionineBehavior(); tempVar15->value(InitiatorMethionineBehaviorToString(tmpVar15a)); para->push_back(*tempVar15); delete tempVar15; pepXML::nameValueType *tempVar16 = new pepXML::nameValueType(); tempVar16->name( "Max Modification Isoforms"); tempVar16->value(std::to_string(getCommonParameters()->getDigestionParams()->getMaxModificationIsoforms())); para->push_back(*tempVar16); delete tempVar16; pepXML::nameValueType *tempVar17 = new pepXML::nameValueType(); tempVar17->name( "Min Peptide Len"); tempVar17->value(std::to_string(getCommonParameters()->getDigestionParams()->getMinPeptideLength())); para->push_back(*tempVar17); delete tempVar17; pepXML::nameValueType *tempVar18 = new pepXML::nameValueType(); tempVar18->name( "Max Peptide Len"); tempVar18->value(std::to_string(getCommonParameters()->getDigestionParams()->getMaxPeptideLength())); para->push_back(*tempVar18); delete tempVar18; pepXML::nameValueType *tempVar19 = new pepXML::nameValueType(); tempVar19->name( "Product Mass Tolerance"); tempVar19->value(std::to_string(getCommonParameters()->getProductMassTolerance()->getValue())); para->push_back(*tempVar19); delete tempVar19; pepXML::nameValueType *tempVar20 = new pepXML::nameValueType(); tempVar20->name( "Ions to search"); std::vector<ProductType> tempVar20a = DissociationTypeCollection::ProductsFromDissociationType[getCommonParameters()->getDissociationType()]; std::string tempVar20s=""; for ( auto p: tempVar20a ) { tempVar20s += Proteomics::Fragmentation::ProductTypeToString(p) + ", "; } tempVar20->value(tempVar20s); para->push_back(*tempVar20); delete tempVar20; for (auto fixedMod : fixedModifications) { pepXML::nameValueType *tempVar21 = new pepXML::nameValueType(); tempVar21->name( "Fixed Modifications: " + fixedMod->getIdWithMotif()); tempVar21->value(std::to_string(fixedMod->getMonoisotopicMass().value())); para->push_back(*tempVar21); delete tempVar21; } for (auto variableMod : variableModifications) { pepXML::nameValueType *tempVar22 = new pepXML::nameValueType(); tempVar22->name( "Variable Modifications: " + variableMod->getIdWithMotif()); tempVar22->value(std::to_string(variableMod->getMonoisotopicMass().value())); para->push_back(*tempVar22); delete tempVar22; } pepXML::nameValueType *tempVar23 = new pepXML::nameValueType(); tempVar23->name( "Localize All Modifications"); tempVar23->value("true"); para->push_back(*tempVar23); delete tempVar23; } pepXML::msms_run_summary *tempVar24 = new pepXML::msms_run_summary(); tempVar24->base_name( filePathNoExtension); tempVar24->raw_data_type("raw"); tempVar24->raw_data(".mzM"); tempVar24->sample_enzyme( *(new pepXML::sample_enzyme())); tempVar24->sample_enzyme()->name(getCommonParameters()->getDigestionParams()->getProtease()->getName()); pepXML::specificity *tempVar25 = new pepXML::specificity(); //Added by Edgar tempVar25->sense("C"); //End Added by Edgar tempVar25->cut(proteaseC); tempVar25->no_cut(proteaseNC); auto t25 = new pepXML::sample_enzyme::specificity_sequence(); t25->push_back(*tempVar25); delete tempVar25; tempVar24->sample_enzyme()->specificity(*t25); delete t25; pepXML::search_summary *tempVar26 = new pepXML::search_summary(); //Added by Edgar: tempVar26->search_engine(pepXML::engineType::SEQUEST); //END added by Edgar tempVar26->base_name( filePathNoExtension); tempVar26->search_engine_version(GlobalVariables::getMetaMorpheusVersion()); tempVar26->precursor_mass_type(pepXML::massType::monoisotopic); tempVar26->fragment_mass_type(pepXML::massType::monoisotopic); tempVar26->search_id(1); tempVar26->search_database(*(new pepXML::search_database())); tempVar26->search_database()->local_path(databasePath); tempVar26->search_database()->type(pepXML::type::value::AA); tempVar26->enzymatic_search_constraint(*(new pepXML::enzymatic_search_constraint())); tempVar26->enzymatic_search_constraint()->enzyme(getCommonParameters()->getDigestionParams()->getProtease()->getName()); tempVar26->enzymatic_search_constraint()->max_num_internal_cleavages(getCommonParameters()->getDigestionParams()->getMaxMissedCleavages()); //Added by Edgar: tempVar26->enzymatic_search_constraint()->min_number_termini(1); //END added by Edgar tempVar26->parameter(*para); delete para; auto t26 = new pepXML::msms_run_summary::search_summary_sequence(); t26->push_back(*tempVar26); delete tempVar26; tempVar24->search_summary(*t26); delete t26; auto tt26 = new pepXML::msms_pipeline_analysis::msms_run_summary_sequence(); tt26->push_back(*tempVar24); delete tempVar24; _pepxml->msms_run_summary(*tt26); delete tt26; auto ttt26 = new pepXML::msms_run_summary::spectrum_query_sequence(items.size()); _pepxml->msms_run_summary()[0].spectrum_query(*ttt26); delete ttt26; auto searchHits = std::vector<pepXML::search_hit*>(); for (int i = 0; i < (int)items.size(); i++) { //auto mods = std::vector<pepXML::mod_aminoacid_mass*>(); auto mods = new pepXML::modInfoDataType::mod_aminoacid_mass_sequence(); PeptideWithSetModifications *alphaPeptide = std::get<1>(items[i]->getBestMatchingPeptides().front()); for (auto modification : alphaPeptide->getAllModsOneIsNterminus() ) { auto mod = new pepXML::mod_aminoacid_mass(); auto thismod = std::get<1>(modification); mod->mass(thismod->getMonoisotopicMass().value()); mod->position(std::get<0>(modification) - 1); mods->push_back(*mod); delete mod; } if (items[i]->getCrossType() == PsmCrossType::Single) { auto searchHit = new pepXML::search_hit(); searchHit->hit_rank(1); searchHit->peptide(alphaPeptide->getBaseSequence()); std::stringstream ss; ss << alphaPeptide->getPreviousAminoAcid(); searchHit->peptide_prev_aa(ss.str()); ss.str(""); ss << alphaPeptide->getNextAminoAcid(); searchHit->peptide_next_aa(ss.str()); searchHit->protein(alphaPeptide->getProtein()->getAccession()); searchHit->num_tot_proteins(1); searchHit->calc_neutral_pep_mass(static_cast<float>(items[i]->getScanPrecursorMass())); searchHit->massdiff((items[i]->getScanPrecursorMass() - items[i]->getPeptideMonisotopicMass().value())); //searchHit->xlink_typeSpecified(true); searchHit->xlink_type1().set(pepXML::xlink_type::na); searchHit->modification_info(*new pepXML::modInfoDataType()); searchHit->modification_info()->mod_aminoacid_mass(*mods); pepXML::nameValueType *tempVar27 = new pepXML::nameValueType(); tempVar27->name( "xlTotalScore"); tempVar27->value(std::to_string(items[i]->getXLTotalScore())); pepXML::nameValueType *tempVar28 = new pepXML::nameValueType(); tempVar28->name( "Qvalue"); tempVar28->value(std::to_string(items[i]->getFdrInfo()->getQValue())); auto t28 = new pepXML::search_hit::search_score_sequence(); t28->push_back(*tempVar27); delete tempVar27; t28->push_back(*tempVar28); delete tempVar28; searchHit->search_score(*t28); delete t28; searchHits.push_back(searchHit); //C# TO C++ CONVERTER TODO TASK: A 'delete searchHit' statement was not added since //searchHit was passed to a method or constructor. Handle memory management manually. } else if (items[i]->getCrossType() == PsmCrossType::DeadEnd || items[i]->getCrossType() == PsmCrossType::DeadEndH2O || items[i]->getCrossType() == PsmCrossType::DeadEndNH2 || items[i]->getCrossType() == PsmCrossType::DeadEndTris) { double crosslinkerDeadEndMass = 0; switch (items[i]->getCrossType()) { case PsmCrossType::DeadEndNH2: crosslinkerDeadEndMass = crosslinker->getDeadendMassNH2(); break; case PsmCrossType::DeadEndTris: crosslinkerDeadEndMass = crosslinker->getDeadendMassTris(); break; default: crosslinkerDeadEndMass = crosslinker->getDeadendMassH2O(); break; } auto mod = new pepXML::mod_aminoacid_mass(); mod->mass(crosslinkerDeadEndMass ); mod->position(items[i]->getLinkPositions().front()); mods->push_back(*mod); delete mod; auto searchHit = new pepXML::search_hit(); searchHit->hit_rank(1); searchHit->peptide(alphaPeptide->getBaseSequence()); std::stringstream ss; ss << alphaPeptide->getPreviousAminoAcid(); searchHit->peptide_prev_aa(ss.str()); ss.str(""); ss << alphaPeptide->getNextAminoAcid(); searchHit->peptide_next_aa(ss.str()); searchHit->protein(alphaPeptide->getProtein()->getAccession()); searchHit->num_tot_proteins(1); searchHit->calc_neutral_pep_mass(static_cast<float>(items[i]->getScanPrecursorMass())); searchHit->massdiff((items[i]->getScanPrecursorMass() - items[i]->getPeptideMonisotopicMass().value() - crosslinkerDeadEndMass)); //searchHit->xlink_typeSpecified = true; searchHit->xlink_type1().set(pepXML::xlink_type::na); searchHit->modification_info(*(new pepXML::modInfoDataType())); searchHit->modification_info()->mod_aminoacid_mass(*mods); pepXML::nameValueType *tempVar29 = new pepXML::nameValueType(); tempVar29->name( "xlTotalScore"); tempVar29->value(std::to_string(items[i]->getXLTotalScore())); pepXML::nameValueType *tempVar30 = new pepXML::nameValueType(); tempVar30->name( "Qvalue"); tempVar30->value(std::to_string(items[i]->getFdrInfo()->getQValue())); auto t30 = new pepXML::search_hit::search_score_sequence(); t30->push_back(*tempVar29); delete tempVar29; t30->push_back(*tempVar30); delete tempVar30; searchHit->search_score(*t30); delete t30; searchHits.push_back(searchHit); //C# TO C++ CONVERTER TODO TASK: A 'delete searchHit' statement was not added since //searchHit was passed to a method or constructor. Handle memory management manually. } else if (items[i]->getCrossType() == PsmCrossType::Inter || items[i]->getCrossType() == PsmCrossType::Intra || items[i]->getCrossType() == PsmCrossType::Cross) { auto betaPeptide = std::get<1>(items[i]->getBetaPeptide()->getBestMatchingPeptides().front()); auto modsBeta = new pepXML::modInfoDataType::mod_aminoacid_mass_sequence(); for (auto mod : betaPeptide->getAllModsOneIsNterminus()) { auto modBeta = new pepXML::mod_aminoacid_mass(); modBeta->mass(std::get<1>(mod)->getMonoisotopicMass().value()); modBeta->position(std::get<0>(mod) - 1); modsBeta->push_back(*modBeta); delete modBeta; } auto alpha = new pepXML::linked_peptide(); alpha->peptide(alphaPeptide->getBaseSequence()); std::stringstream ss; ss << alphaPeptide->getPreviousAminoAcid(); alpha->peptide_prev_aa(ss.str()); ss.str(""); ss << alphaPeptide->getNextAminoAcid(); alpha->peptide_next_aa(ss.str() ); alpha->protein(alphaPeptide->getProtein()->getAccession()); alpha->num_tot_proteins(1); alpha->calc_neutral_pep_mass(static_cast<float>(items[i]->getPeptideMonisotopicMass().value())); alpha->complement_mass(static_cast<float>(items[i]->getScanPrecursorMass() - alphaPeptide->getMonoisotopicMass())); alpha->designation("alpha"); alpha->modification_info(*new pepXML::modInfoDataType()); alpha->modification_info()->mod_aminoacid_mass(*mods); pepXML::nameValueType *tempVar31 = new pepXML::nameValueType(); tempVar31->name("xlscore"); tempVar31->value(std::to_string(items[i]->getXLTotalScore())); pepXML::nameValueType *tempVar32 = new pepXML::nameValueType(); tempVar32->name("link"); tempVar32->value(std::to_string(items[i]->getLinkPositions().front())); auto talpha = new pepXML::linked_peptide::xlink_score_sequence(); talpha->push_back(*tempVar31); delete tempVar31; talpha->push_back(*tempVar32); delete tempVar32; alpha->xlink_score(*talpha); delete talpha; auto beta = new pepXML::linked_peptide(); beta->peptide(betaPeptide->getBaseSequence()); ss.str(""); ss << betaPeptide->getPreviousAminoAcid(); beta->peptide_prev_aa(ss.str()); ss.str(""); ss << betaPeptide->getNextAminoAcid(); beta->peptide_next_aa(ss.str()); beta->protein(betaPeptide->getProtein()->getAccession()); beta->num_tot_proteins(1); beta->calc_neutral_pep_mass(static_cast<float>(betaPeptide->getMonoisotopicMass())); beta->complement_mass(static_cast<float>(items[i]->getScanPrecursorMass() - betaPeptide->getMonoisotopicMass())); beta->designation("beta"); beta->modification_info(*(new pepXML::modInfoDataType())); beta->modification_info()->mod_aminoacid_mass(*modsBeta); pepXML::nameValueType *tempVar33 = new pepXML::nameValueType(); tempVar33->name( "xlscore"); tempVar33->value(std::to_string(items[i]->getBetaPeptide()->getScore())); pepXML::nameValueType *tempVar34 = new pepXML::nameValueType(); tempVar34->name( "link"); tempVar34->value(std::to_string(items[i]->getBetaPeptide()->getLinkPositions().front())); auto tbeta = new pepXML::linked_peptide::xlink_score_sequence(); tbeta->push_back(*tempVar33); delete tempVar33; tbeta->push_back(*tempVar34); delete tempVar34; beta->xlink_score(*tbeta); delete tbeta; //auto cross = {alpha, beta}; auto cross = new pepXML::xlink::linked_peptide_sequence(); cross->push_back(*alpha); delete alpha; cross->push_back(*beta); delete beta; auto searchHit = new pepXML::search_hit(); searchHit->hit_rank(1); searchHit->peptide("-"); searchHit->peptide_prev_aa("-"); searchHit->peptide_next_aa("-"); searchHit->protein("-"); searchHit->num_tot_proteins(1); searchHit->calc_neutral_pep_mass( static_cast<float>(items[i]->getScanPrecursorMass())); searchHit->massdiff((items[i]->getScanPrecursorMass() - betaPeptide->getMonoisotopicMass() - alphaPeptide->getMonoisotopicMass() - crosslinker->getTotalMass())); //searchHit->xlink_typeSpecified = true; searchHit->xlink_type1().set(pepXML::xlink_type::xl); searchHit->xlink(*new pepXML::xlink()); searchHit->xlink()->identifier(crosslinker->getCrosslinkerName()); searchHit->xlink()->mass(static_cast<float>(crosslinker->getTotalMass())); searchHit->xlink()->linked_peptide(*cross); pepXML::nameValueType *tempVar35 = new pepXML::nameValueType(); tempVar35->name( "xlTotalScore"); tempVar35->value(std::to_string(items[i]->getXLTotalScore())); pepXML::nameValueType *tempVar36 = new pepXML::nameValueType(); tempVar36->name( "Qvalue"); tempVar36->value(std::to_string(items[i]->getFdrInfo()->getQValue())); auto t36 = new pepXML::search_hit::search_score_sequence(); t36->push_back(*tempVar35); delete tempVar35; t36->push_back(*tempVar36); delete tempVar36; searchHit->search_score(*t36); delete t36; searchHits.push_back(searchHit); //C# TO C++ CONVERTER TODO TASK: A 'delete searchHit' statement was not added since //searchHit was passed to a method or constructor. Handle memory management manually. } else if (items[i]->getCrossType() == PsmCrossType::Loop) { auto thePeptide = new pepXML::linked_peptide(); //Added by Edgar: thePeptide->peptide("-"); //thePeptide->peptide_prev_aa("-"); //thePeptide->peptide_next_aa("-"); thePeptide->protein("-"); thePeptide->num_tot_proteins(0); thePeptide->calc_neutral_pep_mass(static_cast<float>(0)); thePeptide->complement_mass(static_cast<float>(0)); //thePeptide->designation("test"); //End Added by Edgar pepXML::nameValueType *tempVar37 = new pepXML::nameValueType(); tempVar37->name( "link"); tempVar37->value(std::to_string(items[i]->getLinkPositions().front())); pepXML::nameValueType *tempVar38 = new pepXML::nameValueType(); tempVar38->name( "link"); tempVar38->value(std::to_string(items[i]->getLinkPositions()[1])); auto t38 = new pepXML::linked_peptide::xlink_score_sequence(); t38->push_back(*tempVar37); delete tempVar37; t38->push_back(*tempVar38); delete tempVar38; thePeptide->xlink_score(*t38); delete t38; //auto cross = {thePeptide}; auto cross = new pepXML::xlink::linked_peptide_sequence(); cross->push_back(*thePeptide); delete thePeptide; auto searchHit = new pepXML::search_hit(); searchHit->hit_rank(1); searchHit->peptide(alphaPeptide->getBaseSequence()); std::stringstream ss; ss << alphaPeptide->getPreviousAminoAcid(); searchHit->peptide_prev_aa(ss.str()); ss.str(""); ss << alphaPeptide->getNextAminoAcid(); searchHit->peptide_next_aa(ss.str() ); searchHit->protein(alphaPeptide->getProtein()->getAccession()); searchHit->num_tot_proteins(1); searchHit->calc_neutral_pep_mass(static_cast<float>(items[i]->getScanPrecursorMass())); searchHit->massdiff((items[i]->getScanPrecursorMass() - alphaPeptide->getMonoisotopicMass() - crosslinker->getLoopMass())); //searchHit->xlink_typeSpecified = true; searchHit->xlink_type1().set(pepXML::xlink_type::loop); searchHit->modification_info(*(new pepXML::modInfoDataType())); searchHit->modification_info()->mod_aminoacid_mass(*mods); searchHit->xlink() = *(new pepXML::xlink()); searchHit->xlink()->identifier(crosslinker->getCrosslinkerName()); searchHit->xlink()->mass(static_cast<float>(crosslinker->getTotalMass())); searchHit->xlink()->linked_peptide(*cross); delete cross; pepXML::nameValueType *tempVar39 = new pepXML::nameValueType(); tempVar39->name( "xlTotalScore"); tempVar39->value(std::to_string(items[i]->getXLTotalScore())); pepXML::nameValueType *tempVar40 = new pepXML::nameValueType(); tempVar40->name( "Qvalue"); tempVar40->value(std::to_string(items[i]->getFdrInfo()->getQValue())); auto t40 = new pepXML::search_hit::search_score_sequence(); t40->push_back(*tempVar39); delete tempVar39; t40->push_back(*tempVar40); delete tempVar40; searchHit->search_score(*t40); delete t40; searchHits.push_back(searchHit); //C# TO C++ CONVERTER TODO TASK: A 'delete searchHit' statement was not added since //searchHit was passed to a method or constructor. Handle memory management manually. } } for (int i = 0; i < (int)items.size(); i++) { auto tempVar41 = new pepXML::spectrum_query(); tempVar41->spectrum(fileNameNoExtension + "." + std::to_string(items[i]->getScanNumber())); tempVar41->start_scan(static_cast<unsigned int>(items[i]->getScanNumber())); tempVar41->end_scan(static_cast<unsigned int>(items[i]->getScanNumber())); tempVar41->precursor_neutral_mass(static_cast<float>(items[i]->getScanPrecursorMass())); tempVar41->assumed_charge(items[i]->getScanPrecursorCharge()); tempVar41->index(static_cast<unsigned int>(i + 1)); tempVar41->retention_time_sec(static_cast<float>(items[i]->getScanRetentionTime() * 60)); auto tempVar42 = new pepXML::search_result(); auto t42 = new pepXML::search_result::search_hit_sequence(); t42->push_back(*searchHits[i]); delete searchHits[i]; tempVar42->search_hit(*t42); delete t42; auto t41 = new pepXML::spectrum_query::search_result_sequence(); t41->push_back(*tempVar42); delete tempVar42; tempVar41->search_result(*t41); delete t41; _pepxml->msms_run_summary()[0].spectrum_query()[i] = *tempVar41; delete tempVar41; } // Serialize the object model to XML. // std::string outFileName = outputFolder + "/"+ fileName + ".pep.XM"; xml_schema::namespace_infomap map; map[""].name = ""; map[""].schema = "/home/gabriel/XLMS/mzlib-master/pepXML/pepXML_v120.xsd"; try{ std::ofstream ofs (outFileName); pepXML::msms_pipeline_analysis_ (ofs, *_pepxml, map); ofs.close(); } catch (const xml_schema::exception& e) { std::cerr << e << std::endl; } FinishedWritingFile( outFileName, nestedIds, getVerbose()); delete _pepxml; } }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #include "stdafx.h" #include "utils\global_defines.h" #include "utils\DigitalTrainingStudio_version.h" #include "ParameterManager.h" #include "Application\Debug\LogManager.h" #include "Application\Objects\plugin\java\JavaPluginManager.h" #define PARAM_STORE_FILE "ParamStore.dat" #include "JNIEnvHelper.h" using namespace de::freegroup::jnipp; extern CString int2string(int i); std::string ParameterManager::className = "de/freegroup/digitalsimulator/Configuration"; jclass ParameterManager::objectClass = NULL; //---------------------------------------------------------------------------- ParameterManager& ParameterManager::Instance(){ //---------------------------------------------------------------------------- // PROC_TRACE; static ParameterManager* m =new ParameterManager; if(objectClass==NULL && JavaPluginManager::isOk()) { JNIStack jniStack; objectClass = static_cast<jclass>( JNIEnvHelper::NewGlobalRef( JNIEnvHelper::FindClass( className.c_str() ) ) ); } return *m; } //---------------------------------------------------------------------------- ParameterManager::ParameterManager(){ //---------------------------------------------------------------------------- // PROC_TRACE; char lpFilename[500]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; Load(); GetModuleFileName( GetModuleHandle(NULL),(char*) lpFilename, (DWORD)sizeof(lpFilename)); _splitpath( (const char*)lpFilename, drive, dir, fname, ext ); CString applicationPath = CString(drive) + dir; Set("ApplicationPath",applicationPath); // Init the path for the object icons // Set("WMFPath",applicationPath + "WMF\\"); // Init the path for the script object bitmaps // Set("BMPPath",applicationPath + "BMP\\"); // Init the path for the palettes // Set("PalettePath",applicationPath +"palettes\\"); // Init the path for the string language catalog // Set("LanguagePath",applicationPath + "langCatalog\\"); // Init the path for the plugin // Set("PluginPath",applicationPath + "plugins\\"); // Init the path for the flags // Set("BannerPath",applicationPath + "banner\\"); // Init the path for the logfiles // Set("LoggingPath",applicationPath + "logging\\"); // Init the path for the basic circurits // Set("BasicPath",applicationPath + "basics\\"); // Init the path for the scripts // Set("ScriptPath",applicationPath + "scripts\\"); // Init the path for the plugins // Set("JavaPluginPath",applicationPath + "plugins\\"); // Init the path for the plugins // Set("TempPath",applicationPath + "temp\\"); // init the path for the JavaRuntime // Set("JREPath",applicationPath + "jdk\\jre\\"); // init the path for the JavaRuntime // Set("JAVA_HOME",applicationPath + "jdk\\"); // init the path for the java look&feel packages // Set("ThemesPath",applicationPath + "themes\\"); putenv(CString("JAVA_HOME=")+Get("JAVA_HOME")); CString path= getenv("PATH"); putenv(CString("PATH=")+path+";\""+Get("JAVA_HOME")+"\\bin\\\""); CString a= getenv("PATH"); // Set the actuall build number in the property file. The java plugins // can now read the buildId. This is userfull for the LiveUpdate tool // Set("ApplicationBuildNumber",int2string(BUILD_NUM)); Set("ApplicationVersion",PROGRAM_VERSION); // TRACE(path); // TRACE(a); } //---------------------------------------------------------------------------- ParameterManager::~ParameterManager(){ //---------------------------------------------------------------------------- // PROC_TRACE; } //---------------------------------------------------------------------------- void ParameterManager::Load(){ //---------------------------------------------------------------------------- // PROC_TRACE; char lpFilename[500]; char drive[_MAX_DRIVE]; char dir[_MAX_DIR]; char fname[_MAX_FNAME]; char ext[_MAX_EXT]; GetModuleFileName( GetModuleHandle(NULL),(char*) lpFilename, (DWORD)sizeof(lpFilename)); _splitpath( (const char*)lpFilename, drive, dir, fname, ext ); CString paramFile = CString(drive) + dir + "\\" + PARAM_STORE_FILE; std::string valueName; std::string value; std::ifstream inFile(paramFile); if(inFile.is_open()==true) { while(!inFile.eof()){ std::getline(inFile ,valueName,'\n'); std::getline(inFile ,value,'\n'); Set(valueName.c_str(),value.c_str()); } } else{ CString msg = CString("Parameterdatei [") + PARAM_STORE_FILE + "] nicht gefunden"; AfxMessageBox(msg); } } //---------------------------------------------------------------------------- void ParameterManager::Save(){ //---------------------------------------------------------------------------- // PROC_TRACE; std::ofstream outFile(APPLICATION_PATH(PARAM_STORE_FILE)); if(outFile.is_open()){ ParamMap::iterator theIterator; theIterator = m_paramMap.begin(); while(theIterator != m_paramMap.end()){ outFile <<(LPCSTR)((*theIterator).first) << std::endl; outFile <<(LPCSTR)((*theIterator).second) << std::endl; theIterator++; } } } //---------------------------------------------------------------------------- void ParameterManager::RegisterForChange( ValueChangeNotifyee* callback){ //---------------------------------------------------------------------------- // PROC_TRACE; m_callbackObjects.insert(callback); } //---------------------------------------------------------------------------- void ParameterManager::UnregisterForChange(ValueChangeNotifyee* callback){ //---------------------------------------------------------------------------- // PROC_TRACE; int i= m_callbackObjects.erase(callback); if(i !=1 ){ // ein Object welches sich nicht registriert hat will sich loeschen AfxMessageBox("Error during erase callback"); } else{ } } //---------------------------------------------------------------------------- CString ParameterManager::Get(const CString &valueName){ //---------------------------------------------------------------------------- // PROC_TRACE; return m_paramMap[valueName]; } //---------------------------------------------------------------------------- void ParameterManager::Set(const CString& valueName,const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; if(valueName != ""){ BeforeChange(valueName,value); m_paramMap[valueName]=value; DuringChange(valueName, value); AfterChange(valueName, value); // Save(); } } //---------------------------------------------------------------------------- void ParameterManager::BeforeChange(const CString& valueName, const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; NotifyeeCollection::iterator theIterator; theIterator = m_callbackObjects.begin(); while(theIterator != m_callbackObjects.end()){ if((*theIterator)->m_valueNameForNotifyee==valueName) (*theIterator)->BeforeChange(value); theIterator++; } // notify the Java part for the changes // if(objectClass!=NULL && JavaPluginManager::isOk()){ JNIStack jniStack; de::freegroup::jnipp::JStringHelper p0 = valueName; de::freegroup::jnipp::JStringHelper p1 = value; jmethodID mid = JNIEnvHelper::GetStaticMethodID( objectClass, "onBeforeChange", "(Ljava/lang/String;Ljava/lang/String;)V" ); JNIEnvHelper::CallStaticVoidMethod( objectClass, mid, static_cast<jobject>(p0),static_cast<jobject>(p1) ); } } //---------------------------------------------------------------------------- void ParameterManager::DuringChange(const CString& valueName, const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; NotifyeeCollection::iterator theIterator; theIterator = m_callbackObjects.begin(); while(theIterator != m_callbackObjects.end()){ if((*theIterator)->m_valueNameForNotifyee==valueName) (*theIterator)->DuringChange(value); theIterator++; } // notify the Java part for the changes // if(objectClass!=NULL && JavaPluginManager::isOk()){ JNIStack jniStack; de::freegroup::jnipp::JStringHelper p0 = valueName; de::freegroup::jnipp::JStringHelper p1 = value; jmethodID mid = JNIEnvHelper::GetStaticMethodID( objectClass, "onDuringChange", "(Ljava/lang/String;Ljava/lang/String;)V" ); JNIEnvHelper::CallStaticVoidMethod( objectClass, mid, static_cast<jobject>(p0),static_cast<jobject>(p1) ); } } //---------------------------------------------------------------------------- void ParameterManager::AfterChange(const CString& valueName, const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; NotifyeeCollection::iterator theIterator; theIterator = m_callbackObjects.begin(); while(theIterator != m_callbackObjects.end()){ if((*theIterator)->m_valueNameForNotifyee==valueName) (*theIterator)->AfterChange(value); theIterator++; } // notify the Java part for the changes // if(objectClass!=NULL && JavaPluginManager::isOk()){ JNIStack jniStack; de::freegroup::jnipp::JStringHelper p0 = valueName; de::freegroup::jnipp::JStringHelper p1 = value; jmethodID mid = JNIEnvHelper::GetStaticMethodID( objectClass, "onAfterChange", "(Ljava/lang/String;Ljava/lang/String;)V" ); JNIEnvHelper::CallStaticVoidMethod( objectClass, mid, static_cast<jobject>(p0),static_cast<jobject>(p1) ); } } //---------------------------------------------------------------------------- void ValueChangeNotifyee::BeforeChange(const CString &value){ //---------------------------------------------------------------------------- // PROC_TRACE; } //---------------------------------------------------------------------------- void ValueChangeNotifyee::DuringChange(const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; } //---------------------------------------------------------------------------- void ValueChangeNotifyee::AfterChange(const CString& value){ //---------------------------------------------------------------------------- // PROC_TRACE; }
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Components/ActorComponent.h" #include "PlayerWeapon.h" #include "PlayerInventory.generated.h" UENUM(BlueprintType) enum class EWeaponType : uint8 { LightWeapon UMETA(DisplayName = "Light Weapon"), MainWeapon UMETA(DisplayName = "Main Weapon"), MeleeWeapon UMETA(DisplayName = "Melee Weapon"), Num UMETA(Hidden) }; UCLASS( ClassGroup=(Custom), meta=(BlueprintSpawnableComponent) ) class FORTHGAME_API UPlayerInventory : public UActorComponent { GENERATED_BODY() public: UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Inventory) TSubclassOf<APlayerWeapon> LightWeaponSlot; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Inventory) TSubclassOf<APlayerWeapon> MainWeaponSlot; UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Inventory) TSubclassOf<APlayerWeapon> MeleeWeaponSlot; UPlayerInventory(); protected: virtual void BeginPlay() override; public: virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override; TSubclassOf<APlayerWeapon> GetWeapon(EWeaponType WeaponSlot); };
/** * Implementasi Binary Search Tree (ADT: BST) * yakni BST yang tidak menyimpan key duplikat (unique key) * * Dibuat dan ditulis oleh Bayu Laksana * -- tanggal 29 Februrari 2019 * Struktur Data 2020 * * Implementasi untuk Bahasa C */ #include <stdlib.h> #include <stdbool.h> #include <stdio.h> /** * Node structure and * uniqueBST structure */ int flag=0; typedef struct bstnode_t { long long int key; struct bstnode_t \ *left, *right; } BSTNode; typedef struct bst_t { BSTNode *_root; unsigned int _size; } BST; /** * !!! WARNING UTILITY FUNCTION !!! * Recognized by prefix "__bst__" * --------------------------------------------- * Note that you better never access these functions, * unless you need to modify or you know how these functions work. */ BSTNode* __bst__createNode(int value) { BSTNode *newNode = (BSTNode*) malloc(sizeof(BSTNode)); newNode->key = value; newNode->left = newNode->right = NULL; return newNode; } BSTNode* __bst__insert(BSTNode *root, int value) { if (root == NULL) return __bst__createNode(value); if (value < root->key) root->left = __bst__insert(root->left, value); else if (value > root->key) root->right = __bst__insert(root->right, value); return root; } BSTNode* __bst__search(BSTNode *root, int value) { while (root != NULL) { if (value < root->key) root = root->left; else if (value > root->key) root = root->right; else return root; } return root; } BSTNode* __bst__findMinNode(BSTNode *node) { BSTNode *currNode = node; while (currNode && currNode->left != NULL) currNode = currNode->left; return currNode; } BSTNode* __bst__remove(BSTNode *root, int value) { if (root == NULL) return NULL; if (value > root->key) root->right = __bst__remove(root->right, value); else if (value < root->key) root->left = __bst__remove(root->left, value); else { if (root->left == NULL) { BSTNode *rightChild = root->right; free(root); return rightChild; } else if (root->right == NULL) { BSTNode *leftChild = root->left; free(root); return leftChild; } BSTNode *temp = __bst__findMinNode(root->right); root->key = temp->key; root->right = __bst__remove(root->right, temp->key); } return root; } void __bst__inorder(BSTNode *root) { if (root) { __bst__inorder(root->left); printf("%d ", root->key); __bst__inorder(root->right); } } void __bst__postorder(BSTNode *root) { if (root) { __bst__postorder(root->left); __bst__postorder(root->right); printf("%d ", root->key); } } void __bst__preorder(BSTNode *root) { if (root) { printf("%d ", root->key); __bst__preorder(root->left); __bst__preorder(root->right); } } /** * PRIMARY FUNCTION * --------------------------- * Accessible and safe to use. */ void bst_init(BST *bst) { bst->_root = NULL; bst->_size = 0u; } bool bst_isEmpty(BST *bst) { return bst->_root == NULL; } bool bst_find(BST *bst, int value) { BSTNode *temp = __bst__search(bst->_root, value); if (temp == NULL) return false; if (temp->key == value) return true; else return false; } void bst_insert(BST *bst, int value) { if (!bst_find(bst, value)) { bst->_root = __bst__insert(bst->_root, value); bst->_size++; } else { printf("SUSAH BANGED WOI!\n"); flag=1; return; } } void bst_remove(BST *bst, int value) { if (bst_find(bst, value)) { bst->_root = __bst__remove(bst->_root, value); bst->_size--; } } void bst_inorder(BST *bst) { __bst__inorder(bst->_root); } void bst_postorder(BST *bst) { __bst__postorder(bst->_root); } void bst_preorder(BST *bst) { __bst__preorder(bst->_root); } int main() { BST bst; bst_init(&bst); long long int n; scanf("%lld",&n); for (long long int i=0;i<n;i++) { long long int in; scanf("%lld",&in); bst_insert(&bst,in); if (flag==1) break; } if (flag==1) { return 0; } else printf("NAH GITU DONG, NGEGAS!\n"); return 0; }
#include <iostream> #include <cstdlib> #include <cstdio> #include <unistd.h> #include <csignal> #define FORE_BOLD "\e[1m" #define FORE_RED "\e[31m" #define FORE_GREEN "\e[32m" #define FORE_YELLOW "\e[33m" #define FORE_BLUE "\e[34m" #define FORE_MAGENTA "\e[35m" #define FORE_CYAN "\e[36m" #define RESET "\e[0m" #define BACK_GREEN "\e[102m" #define BACK_GREY "\e[100m" #define PROGRESS_BAR_MAX_STEP (100) #define PRINT_BUFFER (1000) using namespace std; void initconsole(); void update_progress(int p); void bufferprint(char * s); void intprint(const long int offset, const long int count,FILE * out); void cprint(const long int offset, const long int count,FILE * out); void lprint(const long int offset, const long int count, FILE *out); void printhelp(); void sighandler(int s); void cleanup(); FILE *out = NULL ; int main(int argc, char * argv[]) { out = stdout; char * fname = NULL; long int ncount=250; long int ccount=0,lcount=0; bool lflag=false,cflag=false,nflag=false; long int startnumber = 0; if(argc==1) { printhelp(); return 1; } for(long int i = 1 ; i< argc; ++i ) { if(strcmp(argv[i],"-h")==0 || strcmp(argv[i],"--help")==0) { printhelp(); return 1; } else if(strcmp(argv[i],"-o")==0 || strcmp(argv[i],"--out")==0) { ++i; fname = argv[i]; } else if(strcmp(argv[i],"-n")==0) { ++i; ncount=strtol(argv[i],NULL,10); if(ncount==0) ncount = 250; nflag=true; cflag=lflag=false; } else if(strcmp(argv[i],"-c")==0) { ++i; ccount=strtol(argv[i],NULL,10); cflag=true; nflag=lflag=false; } else if(strcmp(argv[i],"-l")==0) { ++i; lcount=strtol(argv[i],NULL,10); lflag=true; nflag=cflag=false; } else if(strcmp(argv[i],"-s")==0 || strcmp(argv[i],"--offset")==0) { ++i; startnumber =strtol(argv[i],NULL,10); } else { printf(FORE_RED "Invalid Option %s\n" RESET,argv[i]); printhelp(); return -2; } } signal(SIGINT,sighandler); signal(SIGABRT,sighandler); if(fname!=NULL) out = fopen(fname,"w"); if(out!=stdout) initconsole(); if(out==NULL) { fprintf(stdout,"%s\n","Cannot open file.Abort!"); return -1; } if(nflag) intprint(startnumber,ncount,out); else if(cflag) cprint(startnumber,ccount,out); else if(lflag) lprint(startnumber,lcount,out); cleanup(); cout<<endl; } void initconsole() { printf("[%*c]0%%",PROGRESS_BAR_MAX_STEP,' '); } void update_progress(int p) { static int prevprogress=0; int back; if(prevprogress==p) { return; } int i=0; // printf("\nprevprogress:%d p:%d\n", prevprogress,p); //'%' back = 1; //1-100 if(prevprogress<10) ++back; else if(prevprogress<100) back+=2; else back+=3; //] + empty bar length back+=1+(PROGRESS_BAR_MAX_STEP-prevprogress); // printf("\nback=%d\n",back); printf("\e[%dD\e[K",back); printf(BACK_GREY); for(i=prevprogress;i<p;++i) printf(" "); printf(RESET); for(;i<PROGRESS_BAR_MAX_STEP;++i) printf(" "); printf("]"); printf(FORE_BOLD"%d%%"RESET,p); fflush(stdout); prevprogress=p; } void bufferprint(char * s) { static char buf[PRINT_BUFFER+1]; if(s==NULL && strlen(buf)!=0) { fprintf(out,"%s",buf); memset(buf,0,sizeof(buf)); return; } if(strlen(s)+strlen(buf)<sizeof(buf)) strcat(buf,s); else { fprintf(out,"%s%s",buf,s); memset(buf,0,sizeof(buf)); } } void intprint(const long int offset, const long int count,FILE * out) { // cout<<"intprint\n"; char pdata[22]; long int i = 0 ; while(i<count) { if(i!=count-1) snprintf(pdata,sizeof(pdata),"%ld ",offset+i); else snprintf(pdata,sizeof(pdata),"%ld",offset+i); bufferprint(pdata); if(out!=stdout) update_progress((i*PROGRESS_BAR_MAX_STEP)/count); ++i; } update_progress((i*PROGRESS_BAR_MAX_STEP)/count); } void cprint(const long int offset,const long int count,FILE * out) { // cout<<"cprint\n"; long int size=0; char * data; char pdata[22]; long int i = offset; int n; while(size<count) { asprintf(&data,"%lu ",i); size+=snprintf(pdata,(count-size)+1,"%s",data); if(strlen(pdata)!=strlen(data)) size=count; bufferprint(pdata); ++i; if(out!=stdout) update_progress((size*PROGRESS_BAR_MAX_STEP)/count); } update_progress((size*PROGRESS_BAR_MAX_STEP)/count); free(data); } void lprint(const long int offset,const long int count, FILE *out) { // cout<<"\nlprint\n"<<count; char pdata[22]; long int i=0; while(i<count) { snprintf(pdata,sizeof(pdata),"%ld\n",offset+i); bufferprint(pdata); if(out!=stdout) update_progress((i*PROGRESS_BAR_MAX_STEP)/count); ++i; } update_progress((i*PROGRESS_BAR_MAX_STEP)/count); } void printhelp() { printf(FORE_BOLD"Command%10cDescription\n"RESET,' '); printf("%-17s%s\n","-h/--help","print this help"); printf("%-17s%s\n","-c","print given no of characters"); printf("%-17s%s\n","-l","print given no of lines"); printf("%-17s%s\n","-n","print till n"); printf("%-17s%s\n","-o/--out","output file name"); printf("%-17s%s\n","-s/--offset","count start offset (default is 0)"); } void sighandler(int s) { cleanup(); printf(FORE_RED"\nSignal(%d)\n"RESET,s); exit(0); } void cleanup() { bufferprint(NULL); if(out!=stdout) fclose(out); }
/***************************************************************************************************** * 剑指offer第21题 * 定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。 * * Input: 数据栈 * Output: 数据栈的最小元素 * * Note: (结合例子分析比较直观) * 应用一个***辅助栈***,压的时候,如果A栈的压入比B栈压入大,B栈不压,,,,小于等于,AB栈同时压入, 出栈,如果,AB栈顶元素不等,A出,B不出。 * author: lcxanhui@163.com * time: 2019.5.5 ******************************************************************************************************/ #include <iostream> #include <stack> using namespace std; template <typename T> class StackWithMin { public: void push(const T& value); void pop(); const T& top() const; const T& min() const; private: typename stack<T> stack1; typename stack<T> stack2; // 辅助栈,该辅助栈的栈顶一直保存压栈后的最小元素 }; template <typename T> void StackWithMin<T>::push(const T& value) { stack1.push(value); if (stack2.empty() || value < stack2.top()) stack2.push(value); else stack2.push(stack2.top()); } template <typename T> void StackWithMin<T>::pop() { if (!stack1.empty() && !stack2.empty()) { stack2.pop(); stack1.pop(); } } template <typename T> const T& StackWithMin<T>::top() const { if (!stack1.empty() && !stack2.empty()) { return stack1.top(); } } template <typename T> const T& StackWithMin<T>::min() const { if (!stack1.empty() && !stack2.empty()) { return stack2.top(); } } int main(void) { StackWithMin<int> min_stack; min_stack.push(3); min_stack.push(4); min_stack.push(2); min_stack.push(1); cout << min_stack.min(); min_stack.pop(); cout << min_stack.min(); cout << min_stack.top(); return 0; }
#include<bits/stdc++.h> #include<limits.h> using namespace std; #define mod 1000000007 #define si(x) scanf("%d", &x) #define sll(x) scanf("%lld", &x) #define pi(x) printf("%d\n", x) #define pll(x) printf("%lld\n", x) #define ii pair<int, int> #define vi vector<int> #define vii vector<pair<int, int> > #define adjList vector<vector<int> > #define ll long long int #define pb push_back #define mp make_pair #define fi first #define se second #define rep(i, z, q) for(i = z; i < q; i++) #define rev(i, z, q) for(i = z; i > q; i--) ll gcd(ll a, ll b) { return b == 0 ? a : gcd(b, a % b); } ll lcm(ll a, ll b) { return a * (b / gcd(a, b)); } ll power(ll a,ll b) { ll ans = 1; while(b > 0){ if(b & 1) ans = ((ans % mod) *(a % mod)) % mod; a=((a % mod)*(a % mod)) % mod; b >>= 1; } return ans; } struct node{ int left, right, ans, left_val, right_val; }; int arr[100010]; node tree[400010]; node merge(node a, node b) { node temp; temp.ans = INT_MIN; if(a.left_val == b.right_val) { temp.left = temp.right = temp.ans = a.ans + b.ans; temp.left_val = temp.right_val = a.left_val; } else if(a.left_val == b.left_val) { temp.left = temp.ans = a.ans + b.left; temp.left_val = a.left_val; temp.right = b.right; temp.right_val = b.right_val; } else if(a.right_val == b.right_val) { temp.right = temp.ans = b.ans + a.right; temp.left_val = a.left_val; temp.right = b.right; temp.right_val = b.right_val; } else { temp.left = a.left; temp.left_val = a.left_val; temp.right = b.right; temp.right_val = b.right_val; if(a.right_val == b.left_val) temp.ans = a.right + b.left; } temp.ans = max(temp.ans, max(a.ans, b.ans)); return temp; } void build(int low, int high, int pos) { if(low == high) { tree[pos].left = tree[pos].right = tree[pos].ans = 1; tree[pos].left_val = tree[pos].right_val = arr[low]; return; } int mid = (low + high)/2; build(low, mid, 2*pos); build(mid+1, high, 2*pos+1); tree[pos] = merge(tree[2*pos], tree[2*pos+1]); return; } node query(int low, int high, int l, int r, int pos) { if(l <= low && r >= high) return tree[pos]; else if(l > high || r < low) { node temp; temp.left = temp.right = temp.ans = temp.left_val = temp.right_val = 0; return temp; } int mid = (low + high) / 2; return merge(query(low, mid, l, r, 2*pos),query(mid+1, high, l, r, 2*pos + 1)); } int main() { int n, i, l, r, q; while(1) { cin>>n; if(n == 0) break; node temp; temp.left = temp.right = temp.ans = temp.left_val = temp.right_val = 0; rep(i, 1, 4*n + 1) tree[i] = temp; cin>>q; rep(i, 1, n+1) cin>>arr[i]; build(1, n, 1); rep(i, 1, 4*n+1) cout<<tree[i].ans<<endl; while(q--) { cin>>l>>r; temp = query(1, n, l, r, 1); cout<<temp.ans<<endl; } } return 0; }
#include "gtest/gtest.h" #include "../../fff-master/fff.h" // add FFF interface dependecy DEFINE_FFF_GLOBALS // Initialize the framework // include external C-code files extern "C" { #include "drivers/hih8120.h" #include "drivers/mh_z19.h" #include "drivers/serial.h" #include "temp_hum_sensor.h" #include "co2.h" #include <stdbool.h> } /* SETUP: 1) Disable the precompiled headers 2) Add "drivers" to Include Directories in the project */ /// <summary> /// Temp_Hum SENSOR TEST SUITE /// </summary> // Fake function to create the Temp_Hum Sensor FAKE_VALUE_FUNC(hih8120_driverReturnCode_t, hih8120_create); // Fake function to wakeup the Temp_Hum Sensor FAKE_VALUE_FUNC(hih8120_driverReturnCode_t, hih8120_wakeup); // Fake function to make the Temp_Hum Sensor execute a measurement FAKE_VALUE_FUNC(hih8120_driverReturnCode_t, hih8120_measure); // Fake function to get the Humidity from the Temp_Hum Sensor FAKE_VALUE_FUNC(uint16_t, hih8120_getHumidityPercent_x10); // Fake function to get the Temperature from the Temp_Hum Sensor FAKE_VALUE_FUNC(int16_t, hih8120_getTemperature_x10); class Temp_Hum_Test : public ::testing::Test { protected: void SetUp() override { RESET_FAKE(hih8120_create); FFF_RESET_HISTORY(); } void TearDown() override { } }; /// <summary> /// CO2 SENSOR TEST SUITE /// </summary> // Fake function to take a measuring from the CO2 Sensor FAKE_VALUE_FUNC(mh_z19_returnCode_t, mh_z19_takeMeassuring); // Fake function to get the CO2 value from the CO2 Sensor FAKE_VALUE_FUNC(mh_z19_returnCode_t, mh_z19_getCo2Ppm, uint16_t*); class CO2_Test : public ::testing::Test { protected: void SetUp() override { RESET_FAKE(mh_z19_takeMeassuring); RESET_FAKE(mh_z19_getCo2Ppm); FFF_RESET_HISTORY(); } void TearDown() override { } }; TEST_F(Temp_Hum_Test, Test_initialize_Temp_Hum_driver) { // Arrange // Act temp_hum_initalizeDriver(); // Assert ASSERT_EQ(1, hih8120_create_fake.call_count); ASSERT_TRUE(HIH8120_OK == hih8120_create_fake.return_val); } TEST_F(Temp_Hum_Test, Test_get_temperature_humidity) { // Arrange // Act int16_t lastTemperature = temp_hum_getLatestTemperature(); uint16_t lastHumidity = temp_hum_getLatestHumidity(); auto wakeUp_rc = temp_hum_wake_up(); auto measure_rc = temp_hum_measure(); // Assert ASSERT_TRUE(HIH8120_OK == wakeUp_rc); ASSERT_TRUE(HIH8120_OK == measure_rc); ASSERT_FALSE(lastTemperature == temp_hum_getLatestHumidity()); ASSERT_FALSE(lastHumidity == temp_hum_getLatestTemperature()); ASSERT_TRUE(456 == temp_hum_getLatestHumidity()); ASSERT_TRUE(550 == temp_hum_getLatestTemperature()); } TEST_F(CO2_Test, Test_get_CO2_value) { // Arrange int co2ppm; // Act co2ppm = co2_getLastCO2ppm(); // Assert EXPECT_EQ(0, co2ppm); } TEST_F(CO2_Test, Test_CO2_measure_is_called_10_times) { // Arrange // Act for (int i = 0; i < 10; i++) { co2_doMeasurement(); } // Assert ASSERT_EQ(10, mh_z19_takeMeassuring_fake.call_count); ASSERT_TRUE(MHZ19_OK == mh_z19_takeMeassuring_fake.return_val); } TEST_F(CO2_Test, Test_CO2_set_data_is_called) { // Arrange uint16_t value = co2_getLastCO2ppm(); // Act co2_getLatestMeasurement(); // Assert ASSERT_TRUE(mh_z19_getCo2Ppm_fake.call_count == 1); EXPECT_TRUE(MHZ19_OK == mh_z19_getCo2Ppm_fake.return_val); ASSERT_TRUE(1500 == co2_getLastCO2ppm()); ASSERT_FALSE(value == co2_getLastCO2ppm()); }
//ÉîËÑ #include<stdio.h> #include<climits> #define MAX 201 char map[MAX][MAX]; int vis[MAX][MAX]; int n,m,ax,ay,minx; void dfs(int x,int y,int len) { if(x<0 || y<0 || x>=n || y>=m) return; if(len>=minx) return; if(map[x][y]=='#') return; if(vis[x][y]==1) return; if(map[x][y]=='r') { if(len<minx) minx=len; return; } if(map[x][y]=='x') len+=1; vis[x][y]=1; dfs(x+1,y,len+1); dfs(x-1,y,len+1); dfs(x,y+1,len+1); dfs(x,y-1,len+1); vis[x][y]=0; } int main() { int i,j,len; while(~scanf("%d %d",&n,&m)) { for(i=0; i<n; ++i) { for(j=0; j<m; ++j) { map[i][j]=getchar(); if(map[i][j]=='a') { ax = i; ay = j; } } getchar(); } len = 0; minx = INT_MAX; dfs(ax,ay,len); if(minx != INT_MAX) printf("%d\n",minx); else printf("Poor ANGEL has to stay in the prison all his life.\n"); } return 0; } //¹ã¶ÈËÑË÷ #include <iostream> #include <stdio.h> #include <string.h> #include <queue> #define N 201 using namespace std; struct Persion { int x,y; int time; friend bool operator < (const Persion &a,const Persion &b) { return a.time>b.time; } }; int dir[4][2]={{-1,0},{1,0},{0,-1},{0,1}}; char map[N][N]; int visited[N][N]; int m,n; int BFS(int x,int y) { priority_queue <Persion>q; Persion current,next; memset(visited,0,sizeof(visited)); current.x=x; current.y=y; current.time=0; visited[current.x][current.y]=1; q.push(current); while(!q.empty()) { current=q.top(); q.pop(); for(int i=0;i<4;i++) { next.x=current.x+dir[i][0]; next.y=current.y+dir[i][1]; if(next.x>=0&&next.x<n&&next.y>=0&&next.y<m&&map[next.x][next.y]!='#'&&!visited[next.x][next.y]) { if(map[next.x][next.y]=='r') return current.time+1; if(map[next.x][next.y]=='x') next.time=current.time+2; else next.time=current.time+1; visited[next.x][next.y]=1; q.push(next); } } } return -1; } int main() { int i,j; Persion angle; while(cin>>n>>m&&(m||n)) { for(i=0;i<n;i++) for(j=0;j<m;j++) { cin>>map[i][j]; if(map[i][j]=='a') { angle.x=i; angle.y=j; } } int time=BFS(angle.x,angle.y); if(time==-1) cout<<"Poor ANGEL has to stay in the prison all his life."<<endl; else cout<<time<<endl; } return 0; }
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "bullet.h" #include "cmd_specific.gen.h" //static constexpr float kDistBullet = 0.3; // 子弹的体积 static constexpr float kDistBullet = 0.01; // 子弹的体积 string Bullet::Draw() const { return make_string("u", _p, _state); } // Unlike Unit, we don't do Act then PerformAct since collision check is not needed. CmdBPtr Bullet::Forward(const RTSMap&, const Units& units) { // First check whether the attacker is dead, if so, remove _id_from to avoid issues. auto self_it = units.find(_id_from); // 这里要改 if (self_it == units.end()) _id_from = INVALID; // If it already exploded, the state changes until it goes to DONE. if (_state == BULLET_EXPLODE1) { _state = BULLET_EXPLODE2; return CmdBPtr(); } else if (_state == BULLET_EXPLODE2) { _state = BULLET_EXPLODE3; return CmdBPtr(); } else if (_state == BULLET_EXPLODE3) { _state = BULLET_DONE; return CmdBPtr(); } // Move forward with the speed provided. // Hit the target // Change its state until it is done. PointF target; if (_target_id != INVALID) { auto it = units.find(_target_id); if (it == units.end()) { // The target is destroyed, destroy itself. 目标已经被摧毁,销毁子弹 _state = BULLET_DONE; return CmdBPtr(); } target = it->second->GetPointF(); } else { if (_target_p.IsInvalid()) { _state = BULLET_DONE; return CmdBPtr(); } target = _target_p; } float dist_sqr = PointF::L2Sqr(_p, target); if (fabs(dist_sqr- kDistBullet * kDistBullet)< 4e-3 ) { // 如果子弹击中目标 // Hit the target. //cout<<"dist_sqr: "<<dist_sqr<<" 碰撞距离: "<<kDistBullet * kDistBullet<<" 两者差值: "<<fabs(dist_sqr- kDistBullet * kDistBullet)<<endl; // cout<<"bullet_p: "<<_p<<" 目标位置: "<<target<<endl; _state = BULLET_EXPLODE1; if (_target_id != INVALID) { // if(_id_from == INVALID){ // printf("[[[[[[[tower is dead!!!!!!!!!!!!\n"); // } return CmdBPtr(new CmdMeleeAttack(_id_from, _target_id, _att,_att_r,_round,_p_tower,true)); // 造成一次攻击 }else{ return CmdBPtr(); } } else { // 子弹飞向目标 // Fly // [TODO]: Randomize the flying procedure (e.g., curvy tracking). PointF diff; // 从 _p 指向 target 的方向 // Here it has to be true, otherwise there is something wrong. if (! PointF::Diff(target, _p, &diff)) { cout << "Bullet::Forward, target or _p is invalid! Target: " << target << " _p:" << _p << endl; return CmdBPtr(); } diff.Trunc(_speed); // 移动的距离 // std::cout<<"dist: "<<diff.x*diff.x + diff.y*diff.y<<std::endl; //cout<<"dist_sqr: "<<dist_sqr<<" 碰撞距离: "<<kDistBullet * kDistBullet<<" 两者差值: "<<dist_sqr - kDistBullet * kDistBullet<<" 飞行距离: "<<diff.x*diff.x + diff.y*diff.y<<endl; _p += diff; // 更新子弹位置 } return CmdBPtr(); }
#ifndef ORDERSERVICE_H #define ORDERSERVICE_H #include "../REPO/OrderRepository.h" #include "../main.h" class OrderService { public: int viewOrderList(); void service_header(); void state_header(); private: OrderRepository orderRepo; }; #endif // ORDERSERVICE_H
#ifndef DEFINES_H_ #define DEFINES_H_ #include <functional> #include <cmath> #include "Tensor.h" namespace StaticNet { namespace Defines { // ------------------------------------------------------------ // Activation functions // ------------------------------------------------------------ // Sigmoid function std::function<float(float)> Sigmoid = [](float x) { return 1.0f / (1.0f + std::exp(-x)); }; std::function<float(float)> SigmoidDerivative = [](float x) { return Sigmoid(x) * (1.0f - Sigmoid(x)); }; std::function<float(float)> SigmoidDerivative_ = [](float x) { return x * (1.0f - x); }; // Tanh function std::function<float(float)> Tanh = [](float x) { return std::tanh(x); }; std::function<float(float)> TanhDerivative = [](float x) { return 1.0f - std::pow(Tanh(x), 2); }; std::function<float(float)> TanhDerivative_ = [](float x) { return 1.0f - x * x; }; // ReLU function std::function<float(float)> ReLU = [](float x) { return x > 0.0f ? x : 0.0f; }; std::function<float(float)> ReLUDerivative = [](float x) { return x > 0.0f ? 1.0f : 0.0f; }; std::function<float(float)> Lnh = [](float x) { return x > 0.0f ? log(x+1.f) : -log(-x+1.f); }; std::function<float(float)> LnhDerivative = [](float x) { return x > 0.0f ? 1.f / (x + 1.f) : 1.f / (-x+1.f); }; // Softmax function template <size_t Input> std::function<Tensor<float, Input>(Tensor<float, Input>)> Softmax = [](Tensor<float, Input> x) { float max = x[argmax(x)]; float sum = 0.0f; for (size_t i = 0; i < Input; i++) { x[i] = std::exp(x[i] - max); sum += x[i]; } return x / sum; }; // ------------------------------------------------------------ // Loss functions // ------------------------------------------------------------ // Mean squared error template <size_t Input> std::function<float(Tensor<float, Input>, Tensor<float, Input>)> MeanSquared = [](Tensor<float, Input> y, Tensor<float, Input> y_) { float sum = 0.0f; for (size_t i = 0; i < Input; i++) sum += std::pow(y[i] - y_[i], 2); return sum / Input; }; // Cross-entropy template <size_t Input> std::function<float(Tensor<bool, Input>, Tensor<float, Input>)> CrossEntropy = [](Tensor<bool, Input> y, Tensor<float, Input> y_) { float sum = 0.0f; for (size_t i = 0; i < Input; i++) if(y[i]) sum -= std::log(y_[i]); return sum; }; } } #endif
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); using namespace std; typedef long long ll; typedef vector<int> vi; typedef pair<int, int> ii; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<bool> vb; typedef vector<vb> vvb; typedef set<int> si; typedef map<string, int> msi; typedef greater<int> gt; typedef priority_queue<int, vector<int>, gt> minq; typedef long long ll; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ int main() { ll N,K,M,R; cin >>N>>K>>M>>R; ll sum = 0; vector<ll> score(N-1); rep(i,N-1) { cin >> score[i]; }; sort(score.begin(), score.end(), [](ll a, ll b) { return a>b;}); ll topK = 0; if (K<N) { rep (i,K) topK+=score[i]; if(topK >= R*K) { cout << 0 << endl; return 0; } else { topK -= score[K-1]; } } else { rep(i,K-1) topK+=score[i]; } ll want = R*K-topK; if (want > M) want = -1; printf("%lld\n", want); return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "SensorInteraction.h" #include "Components/BoxComponent.h" #include "Components/WidgetComponent.h" #include "TempCapstoneProject/PaladinCharacter.h" #include "TempCapstoneProject/RogueCharacter.h" // Sets default values ASensorInteraction::ASensorInteraction() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; SceneRoot = CreateDefaultSubobject<USceneComponent>("Scene Root"); RootComponent = SceneRoot; SensorCollider = CreateDefaultSubobject<UBoxComponent>("Sensor Collider"); SensorCollider->SetupAttachment(RootComponent); ObjectMesh = CreateDefaultSubobject<UStaticMeshComponent>("Object Mesh"); ObjectMesh->SetupAttachment(RootComponent); InteractionWidget = CreateDefaultSubobject<UWidgetComponent>("Interaction Widget"); InteractionWidget->SetupAttachment(RootComponent); InteractionWidget->SetVisibility(false); // Register overlap events OnActorBeginOverlap.AddDynamic(this, &ASensorInteraction::OnOverlapBegin); OnActorEndOverlap.AddDynamic(this, &ASensorInteraction::OnOverlapEnd); } void ASensorInteraction::OnOverlapBegin(AActor* OverlappedActor, AActor* OtherActor) { if (OtherActor && OtherActor != this) { if (OtherActor->IsA(APaladinCharacter::StaticClass()) || OtherActor->IsA(ARogueCharacter::StaticClass())) { bIsActive = true; GEngine->AddOnScreenDebugMessage(-1, 1.5, FColor::Green, "Overlap Begin"); GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Magenta, FString::Printf(TEXT("Other Actor = %s"), *OtherActor->GetName())); } } } void ASensorInteraction::OnOverlapEnd(AActor* OverlappedActor, AActor* OtherActor) { if (OtherActor && OtherActor != nullptr) { if (OtherActor->IsA(APaladinCharacter::StaticClass()) || OtherActor->IsA(ARogueCharacter::StaticClass())) { bIsActive = false; GEngine->AddOnScreenDebugMessage(-1, 1.5, FColor::Green, "Overlap Ended"); GEngine->AddOnScreenDebugMessage(-1, 5.0f, FColor::Magenta, FString::Printf(TEXT("%s has left the Sensor"), *OtherActor->GetName())); } } } // Called when the game starts or when spawned void ASensorInteraction::BeginPlay() { Super::BeginPlay(); } // Called every frame void ASensorInteraction::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (bIsActive) { Interact(); } } void ASensorInteraction::Interact() { ReceiveInteract(); } void ASensorInteraction::ShowInteractionWidget() { } void ASensorInteraction::HideInteractionWidget() { }
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // modified by Francisco Eduardo Balart Sanchez balart40@gmail.com // Original source from: src/network/examples/main-packet-header.cc #ifndef ESSOAPACKET_H #define ESSOAPACKET_H #include "ns3/ptr.h" #include "ns3/packet.h" #include "ns3/enum.h" #include "ns3/header.h" #include <iostream> namespace ns3{ enum MessageType { ESSOATYPE_RREQ = 1, // <- ESSOA_RREQ ESSOATYPE_RREP = 2, // <- ESSOA_RREP ESSOATYPE_RERR = 3, // <- ESSOA_RERR ESSOATYPE_RREP_ACK = 4 // <- ESSOA_RREP_ACK }; enum ESSOA_MSG_TYPE { ESSOA_RRESPB, // ESSOA REQUEST RESPONSE TO BROADCAST PACKET ESSOA_RRESPANS, // ESSOA ANSWER PACKET WITH REQUEST RESPONSE ESSOA_NRESP // ESSOA NO RESPONSE PACKET }; /* A sample Header implementation */ class HelloHeader : public Header { public: HelloHeader (); virtual ~HelloHeader (); void SetSourceNodeId (uint16_t srcNodeId); void SetDestinationNodeId (uint16_t destNodeId); void SetSentHandShakeUid (uint16_t Uid); void SetReceivedHandShakeUid (uint16_t Uid); uint16_t GetSourceNodeId () const; uint16_t GetDestinationNodeId () const; uint16_t GetSentHandShakeUid () const; uint16_t GetReceivedHandShakeUid () const; // Header Serialization / De-serialization static TypeId GetTypeId (void); virtual TypeId GetInstanceTypeId (void) const; virtual void Serialize (Buffer::Iterator start) const; virtual uint32_t Deserialize (Buffer::Iterator start); virtual uint32_t GetSerializedSize (void) const; virtual void Print (std::ostream &os) const; private: // 2 bytes * 4 datas => 8 bytes uint16_t m_sourceNodeId; uint16_t m_destinationNodeId; uint16_t m_SentHandShakeUid; uint16_t m_ReceivedHandShakeUid; }; HelloHeader::HelloHeader () { // we must provide a public default constructor, // implicit or explicit, but never private. } HelloHeader::~HelloHeader () { } TypeId HelloHeader::GetTypeId (void) { static TypeId tid = TypeId ("ns3::HelloHeader") .SetParent<Header> () .AddConstructor<HelloHeader> (); return tid; } TypeId HelloHeader::GetInstanceTypeId (void) const { return GetTypeId (); } void HelloHeader::Print (std::ostream &os) const { // This method is invoked by the packet printing // routines to print the content of my header. //os << "data=" << m_data << std::endl; os << "data: \n" <<"source id: "<< m_sourceNodeId << "\n"<<"Destination Id: "<< m_destinationNodeId<<"\n"<<"Sent Uid: "<<m_SentHandShakeUid<<"\n"<<"Received Id: "<<m_ReceivedHandShakeUid; } uint32_t HelloHeader::GetSerializedSize (void) const { // we reserve 2 bytes for our header. return 8; } void HelloHeader::Serialize (Buffer::Iterator start) const { // we can serialize two bytes at the start of the buffer. // we write them in network byte order. start.WriteHtonU16 (m_sourceNodeId); start.WriteHtonU16 (m_destinationNodeId); start.WriteHtonU16 (m_SentHandShakeUid); start.WriteHtonU16 (m_ReceivedHandShakeUid); } uint32_t HelloHeader::Deserialize (Buffer::Iterator start) { // we can deserialize two bytes from the start of the buffer. // we read them in network byte order and store them // in host byte order. m_sourceNodeId = start.ReadNtohU16 (); m_destinationNodeId = start.ReadNtohU16 (); m_SentHandShakeUid = start.ReadNtohU16 (); m_ReceivedHandShakeUid = start.ReadNtohU16 (); // we return the number of bytes effectively read. return 8; } void HelloHeader::SetSourceNodeId (uint16_t srcNodeId) { m_sourceNodeId = srcNodeId; } void HelloHeader::SetDestinationNodeId (uint16_t destNodeId) { m_destinationNodeId = destNodeId; } void HelloHeader::SetSentHandShakeUid (uint16_t Uid) { m_SentHandShakeUid = Uid; } void HelloHeader::SetReceivedHandShakeUid (uint16_t Uid) { m_ReceivedHandShakeUid= Uid; } uint16_t HelloHeader::GetSourceNodeId () const { return m_sourceNodeId; } uint16_t HelloHeader::GetDestinationNodeId () const { return m_destinationNodeId; } uint16_t HelloHeader::GetSentHandShakeUid () const { return m_SentHandShakeUid; } uint16_t HelloHeader::GetReceivedHandShakeUid () const { return m_ReceivedHandShakeUid; } }// end bracket namesapce ns3 // %INFO: We removed the main function original source is at: src/network/examples/main-packet-header.cc #endif
#include "algorithm/opticalflow_slam/include/opticalflow_slam.h" namespace OpticalFlow_SLAM_algorithm_opticalflow_slam{ /** * @brief create a op_slam, load system config , camera_config and dataset, * to filling slam_config_ , camera_config_ and image_left_right * input: * @param system_config_path run parameters config * @param camera_config_path camer's internal parameters * @param dataset_path where to read images * @param save_map_path where to save the slam result * output: * @return OP_SLAM object; * @exception no * @author snowden * @date 2021-07-16 * @version 1.0 * @property no */ OP_SLAM::OP_SLAM(const std::string system_config_path, const std::string camera_config_path, const std::string dataset_path, const std::string save_map_path) : system_config_path_(system_config_path), camera_config_path_(camera_config_path), dataset_path_(dataset_path), save_map_path_(save_map_path) { // SHOW_FUNCTION_INFO is_running_.store(true); } /** * @brief release the op_slam object; * @author snowden * @date 2021-07-16 * @version 1.0 */ OP_SLAM::~OP_SLAM() { //TODO(snowden): need to release dynamic memory }; /** * @brief opticalflow_slam_loop * @author snowden * @date 2021-07-21 * @version 1.0 */ void OP_SLAM::opticalflow_slam_loop() { while (is_running_.load()) { DLOG_INFO << " slam is running " << std::endl; switch (get_status()) { case OP_SLAM_STATUS::READY: { DLOG_INFO << " OP_SLAM_STATUS::READY " << std::endl; CHECK_EQ(load_system_config(), true); CHECK_EQ(load_camera_config(), true); // CHECK_EQ(load_images(), true); set_status(OP_SLAM_STATUS::INITING); break; } case OP_SLAM_STATUS::INITING: { DLOG_INFO << " OP_SLAM_STATUS::INITING " << std::endl; CHECK_EQ(init(), true); set_status(OP_SLAM_STATUS::RUNNING); break; } case OP_SLAM_STATUS::RUNNING: { DLOG_INFO << " OP_SLAM_STATUS::RUNNING " << std::endl; CHECK_EQ(run(), true); set_status(OP_SLAM_STATUS::SAVINGMAP); break; } case OP_SLAM_STATUS::SAVINGMAP: { DLOG_INFO << " OP_SLAM_STATUS::SAVINGMAP " << std::endl; if (!save_map()) { LOG_ERROR << " save map failed , please check " << std::endl; } if(!save_trajectory()) { LOG_ERROR << "save trajectory failed , please check" << std::endl; } set_status(OP_SLAM_STATUS::FINISHED); break; } case OP_SLAM_STATUS::FINISHED: { DLOG_INFO << " OP_SLAM_STATUS::FINISHED " << std::endl; stop_slam(); break; } case OP_SLAM_STATUS::RESET: { DLOG_INFO << " OP_SLAM_STATUS::RESET " << std::endl; set_status(OP_SLAM_STATUS::INITING); break; } case OP_SLAM_STATUS::UNKNOW: { DLOG_INFO << " OP_SLAM_STATUS::UNKNOW " << std::endl; set_status(OP_SLAM_STATUS::READY); break; } default: { LOG_ERROR << "OP_SLAM_STATUS get_status error: new state is " \ << static_cast<int64_t>(get_status()) << std::endl; break; } } //switch (get_status()) } //while (is_running_.load()) DLOG_INFO << " OP slam run finished " << std::endl; } //void OP_SLAM::opticalflow_slam_loop() /** * @brief mainly init sp_map_, sp_tracker_, and sp_optimizer_ * output * @author snowden * @date 2021-07-16 * @version 1.0 */ bool OP_SLAM::init() { //init Map sp_map_ = std::shared_ptr<Map>(new Map()); //TODO(snowden): parameter need read from config file; // sp_slam_config_ = SystemConfig::getSystemConfig(); /** * @note tracker will notify viewer and optimizer, and optimizer will notify viewer ,so init order must be : * viewer -> optimizer -> tracker; tracker init will trigger slam run, so put tracker in run funciton; */ //start viewer thread; sp_viewer_ = std::shared_ptr<Viewer>(new Viewer(sp_map_, sp_tracker_, sp_optimizer_)); //start optimizer thread; sp_optimizer_ = std::shared_ptr<Optimizer>(new Optimizer(sp_map_, sp_slam_config_, sp_camera_config_)); if((nullptr != sp_map_ )&& (nullptr != sp_slam_config_) && (nullptr != sp_viewer_) && (nullptr != sp_optimizer_)) { return true; } else { return false; } } /** * @brief include a main loop to run slam system; * @author snowden * @date 2021-07-16 * @version 1.0 */ bool OP_SLAM::run() { sp_tracker_ = std::shared_ptr<Tracker>(new Tracker(sp_map_, sp_slam_config_, sp_camera_config_, dataset_path_)); sp_viewer_->sp_tracker_ = sp_tracker_; sp_viewer_->wp_optimizer_.lock() = sp_optimizer_; if(nullptr == sp_tracker_) { return false; } sp_tracker_->wp_viewer_ = sp_viewer_; sp_tracker_->wp_optimizer_ = sp_optimizer_; sp_optimizer_->wp_tracker_ = sp_tracker_; sp_optimizer_->wp_viewer_ = sp_viewer_; //warning: main thread will be blocked here ,until received tracker's finished notify; wait_notify_all_tracker_finished(); return true; } /** * @brief save map in save_map_path files; * @author snowden * @date 2021-07-16 * @version 1.0 */ bool OP_SLAM::save_map() { std::vector<std::shared_ptr<Mappoint3d>> all_mappoint { sp_map_->get_mappoints() }; std::ofstream map_file(save_map_path_ + "/map.obj"); map_file.clear(); if (!map_file.is_open()) { DLOG_ERROR << " save map file open failed " << std::endl; } DLOG_INFO << " ready to save map " << std::endl; map_file << "mtllib obj.mtl" << std::endl << std::endl; for(auto v : all_mappoint) { map_file << "v " << v->get_position3d()(0) << " " <<v->get_position3d()(1) << " " << v->get_position3d()(2) << std::endl; } map_file.close(); DLOG_INFO << " save map finished, please use meshlab to check it " << std::endl; return true; } /** * @brief save trajectory in save_map_path files; * @author snowden * @date 2021-08-09 * @version 1.0 */ bool OP_SLAM::save_trajectory() { std::vector<std::shared_ptr<Frame>> all_frame { sp_map_->get_frames() }; std::ofstream trajectory_file(save_map_path_ + "/trajectory.txt"); trajectory_file.clear(); if(!trajectory_file.is_open()) { DLOG_ERROR << " open trajecotry.txt failed " << std::endl; } DLOG_INFO << " ready to save trajectory " << std::endl; SE3 pose; for(int i { 0 }; i < all_frame.size(); i++) { pose = all_frame[i]->get_left_pose().inverse(); trajectory_file << pose.matrix()(0,0) << " " << pose.matrix()(0,1) << " " << pose.matrix()(0,2) << " " << pose.matrix()(0,3) << " " << pose.matrix()(1,0) << " " << pose.matrix()(1,1) << " " << pose.matrix()(1,2) << " " << pose.matrix()(1,3) << " " << pose.matrix()(2,0) << " " << pose.matrix()(2,1) << " " << pose.matrix()(2,2) << " " << pose.matrix()(2,3) << std::endl; } trajectory_file.close(); DLOG_INFO << " save trajectory finished , please use evo to check it" << std::endl; return true; } /** * @brief keep main thread ,keep show viewer; * @author snowden * @date 2021-07-21 * @version 1.0 * @note only tracker , optimizer, and viewer all exit, slam be allowed exit, * however, optimizer and viewer will always keep alive, so , main thread will be blocked here; */ bool OP_SLAM::stop_slam() { sp_optimizer_->is_running_.store(false); sp_viewer_->is_running_.store(false); sp_tracker_->stop(); sp_optimizer_->stop(); sp_viewer_->stop(); is_running_.store(false); } /** * @brief change slam status in some condition * @param new_status * @author sowden * @date 2021-07-16 * @version 1.0 */ bool OP_SLAM::set_status(const OP_SLAM_STATUS &new_status) { SHOW_FUNCTION_INFO bool is_allowed_change { false } ; switch(new_status) { case OP_SLAM_STATUS::READY: { if (slam_status_ == OP_SLAM_STATUS::UNKNOW) { is_allowed_change = true; } break; } case OP_SLAM_STATUS::INITING: { if ((slam_status_ == OP_SLAM_STATUS::READY) || (slam_status_ == OP_SLAM_STATUS::RESET)) { is_allowed_change = true; } break; } case OP_SLAM_STATUS::RUNNING: { if (slam_status_ == OP_SLAM_STATUS::INITING) { is_allowed_change = true; } break; } case OP_SLAM_STATUS::SAVINGMAP: { if (slam_status_ == OP_SLAM_STATUS::RUNNING) { is_allowed_change = true; } break; } case OP_SLAM_STATUS::FINISHED: { if (slam_status_ == OP_SLAM_STATUS::SAVINGMAP) { is_allowed_change = true; } break; } case OP_SLAM_STATUS::RESET: { if ((slam_status_ == OP_SLAM_STATUS::INITING) || (slam_status_ == OP_SLAM_STATUS::RUNNING) || (slam_status_ == OP_SLAM_STATUS::FINISHED) || (slam_status_ == OP_SLAM_STATUS::SAVINGMAP) || (slam_status_ == OP_SLAM_STATUS::UNKNOW) ) { is_allowed_change = true; } break; } default: { LOG_ERROR << "give OP_SLAM_STATUS is not know " << std::endl; return false; } } if (is_allowed_change) { slam_status_ = new_status; } else { LOG_ERROR << " can't change slam status from " << static_cast<int64_t>(slam_status_) << " to " << static_cast<int64_t>(new_status) << std::endl; } return is_allowed_change; } /** * @brief * @author snowden * @date 2021-07-18 * @version 1.0 */ bool OP_SLAM::load_system_config() { SHOW_FUNCTION_INFO sp_slam_config_ = SystemConfig::getSystemConfig( ); //TODO cv::FileStorage f_system_config(system_config_path_, cv::FileStorage::READ); CHECK_EQ(f_system_config.isOpened(), true); //TODO(snowden) : may exit other mothed to achieve read int type data to int64_t directly; int32_t temp_int32_data = -1; f_system_config["pyrimid.levels_num"] >>temp_int32_data; sp_slam_config_->pyrimid_levels_num = static_cast<int64_t>(temp_int32_data); f_system_config["pyrimid.scale"] >> sp_slam_config_->pyrimid_scale; f_system_config["fps"] >> temp_int32_data ; sp_slam_config_->fps = static_cast<int64_t>(temp_int32_data); f_system_config["features.expected_nums"] >> temp_int32_data; sp_slam_config_->features_expected_nums = static_cast<int64_t>(temp_int32_data); f_system_config["features.init_min_threshold"] >> temp_int32_data; sp_slam_config_->features_init_min_threshold = static_cast<int64_t>(temp_int32_data); f_system_config["features.tracking_min_threshold"] >> temp_int32_data; sp_slam_config_->features_tracking_min_threshold = static_cast<int64_t>(temp_int32_data); f_system_config["mappoint.init_min_threshold"] >> temp_int32_data; sp_slam_config_->mappoint_init_min_threshold = static_cast<int64_t>(temp_int32_data); f_system_config["mappoint.need_insert_keyframe_min_threshold"] >> temp_int32_data; sp_slam_config_->mappoint_need_insert_keyframe_min_threshold = static_cast<int64_t>(temp_int32_data); sp_slam_config_->show_system_config_info(); f_system_config.release(); return true; } /** * @brief * @author snowden * @date 2021-07-18 * @version 1.0 */ bool OP_SLAM::load_camera_config() { sp_camera_config_ = CameraConfig::getCameraConfig(); std::ifstream fin(camera_config_path_); if(!fin) { LOG_FATAL << " open " << camera_config_path_ << "failed" << std::endl; } //discard name; char camear_name; for(int k = 0; k < 3; k++) { fin >> camear_name; } //intrinsics with base line; double intrinsics_mat34[12]; for(int i = 0; i < 12; i++) { fin >> intrinsics_mat34[i]; } sp_camera_config_->K_left << intrinsics_mat34[0], intrinsics_mat34[1], intrinsics_mat34[2], intrinsics_mat34[4], intrinsics_mat34[5], intrinsics_mat34[6], intrinsics_mat34[8], intrinsics_mat34[9], intrinsics_mat34[10]; sp_camera_config_->fx_left = intrinsics_mat34[0]; sp_camera_config_->fy_left = intrinsics_mat34[5]; sp_camera_config_->cx_left = intrinsics_mat34[2]; sp_camera_config_->cy_left = intrinsics_mat34[6]; //discard name; for(int k = 0; k < 3; k++) { fin >> camear_name; } //intrinsics with base line; for(int i = 0; i < 12; i++) { fin >> intrinsics_mat34[i]; } sp_camera_config_->K_right << intrinsics_mat34[0], intrinsics_mat34[1], intrinsics_mat34[2], intrinsics_mat34[4], intrinsics_mat34[5], intrinsics_mat34[6], intrinsics_mat34[8], intrinsics_mat34[9], intrinsics_mat34[10]; Vec3 negative_fxb; negative_fxb << intrinsics_mat34[3], intrinsics_mat34[7], intrinsics_mat34[11]; sp_camera_config_->base_line = negative_fxb / intrinsics_mat34[0]; sp_camera_config_->fx_right = intrinsics_mat34[0]; sp_camera_config_->fy_right = intrinsics_mat34[5]; sp_camera_config_->cx_right = intrinsics_mat34[2]; sp_camera_config_->cy_right = intrinsics_mat34[6]; sp_camera_config_->show_camera_config_info(); return true; } // /** // * @brief // * @author snowden // * @date 2021-07-18 // * @version 1.0 // */ // bool OP_SLAM::load_images() // { // SHOW_FUNCTION_INFO // return true; // } /** * @brief wait tracker finished notify from tracker thread; * @author snowden * @date 2021-07-21 * @version 1.0 */ void OP_SLAM::wait_notify_all_tracker_finished() { sp_tracker_->condition_variable_is_tracker_finished_.wait(sp_tracker_->tracker_finished_lock); } } //OpticalFlow_SLAM_algorithm_opticalflow_slam
#include <bits/stdc++.h> using namespace std; using ll = long long int; using PLL = pair < ll, ll>; void solve(){ ll n, w; cin >> n >> w; vector < PLL > v(n); for (int i = 0; i < n; i++){ cin >> v[i].first; v[i].second = i; } sort(v.begin(), v.end()); vector < int > inds; ll sum = 0; for (int i = 0; i < n; i++){ if (v[i].first >= (w+1)/2 and v[i].first <= w) { cout << "1\n"; cout << v[i].second + 1 << '\n'; return; } } for (int i = 0; i < n; i++) { ll tmp = sum + v[i].first; if (tmp <= w) { sum += v[i].first; inds.push_back(v[i].second); } else break; } if (sum >= (w+1)/2 and sum <= w) { cout << inds.size() << '\n'; for (auto x : inds) cout << x + 1 << " "; cout << "\n"; } else { cout << "-1\n"; } } int main(){ ios::sync_with_stdio(0); cin.tie(0); int t; cin >> t; while(t--){ solve(); } }
//cv_stereo_reconstru.cpp #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/core/utility.hpp" #include <stdio.h> #include<iostream>//标准输入输出 //命名空间 using namespace cv; using namespace std; static void print_help() { printf("\nDemo stereo matching converting L and extrin_R images into disparity and point clouds\n"); printf("\nUsage: stereo_match <left_image> <right_image> [--method_algorithm=stereo_bm|stereo_sgbm|stereo_hh|stereo_sgbm3way] [--method_block_size=<size_of_block>]\n" "[--method_max_disparity=<max_disparity>] [--method_stereo_scal=stereo_scal_factor>] [-i=<name_intrin_file>] [-e=<name_extrin_file>]\n" "[--method_no_display] [-o=<method_disparity_image>] [-p=<file_cloud_point>]\n"); } //将点云数据保存到本地 static void saveXYZ(const char* file_name, const Mat& mat_xyz) { const double max_z_value = 1.0e4; FILE* fp_xyz = fopen(file_name, "wt"); for(int xyz_rows = 0; xyz_rows < mat_xyz.rows; xyz_rows++)//可以传入roi参数 减少遍历的像素点 { for(int xyz_cols = 0; xyz_cols < mat_xyz.cols; xyz_cols++) { Vec3f xyz_point = mat_xyz.at<Vec3f>(xyz_rows, xyz_cols); if(fabs(xyz_point[2] - max_z_value) < FLT_EPSILON || fabs(xyz_point[2]) > max_z_value) continue; fprintf(fp_xyz, "%f %f %f\n", xyz_point[0], xyz_point[1], xyz_point[2]); } } fclose(fp_xyz); } int main(int argc, char** argv) { std::string filename_img_l = ""; std::string filename_img_r = ""; std::string name_intrin_file = ""; std::string name_extrin_file = ""; std::string File_name_disparity = ""; std::string File_name_point_cloud = ""; std::string File_name_point_cloud_ch = "point_cloud_file_ch.txt"; std::string File_name_disparity_ch="disparity_image_ch.png"; enum { method_BM=0, method_SGBM=1, method_HH=2, method_VAR=3, method_3WAY=4 }; int method_alg = method_SGBM;//选择了SGBM算法 int stereo_sad_window_size, stereo_num_of_disparities; bool display_no; float method_stereo_scal; int i_1=16,i_2=9,j_3=0,j_4=16,j_5=3; Ptr<StereoBM> stereo_bm = StereoBM::create(i_1,i_2); Ptr<StereoSGBM> stereo_sgbm = StereoSGBM::create(j_3,j_4,j_5); /* "{@arg1|left2.jpg|}{@arg2|right2.jpg|}{help h||}{method_algorithm|stereo_sgbm|}{method_max_disparity|0|}{method_block_size|5|}{method_no_display||}{method_stereo_scal|1|}{i|intrinsics.yml|}{e|extrinsics.yml|}{o|method_disparity_image.png|}{p|file_cloud_point.txt|}"); */ cv::CommandLineParser parser(argc, argv, "{@arg1|left7.jpg|}{@arg2|right7.jpg|}{help h||}{method_algorithm|stereo_sgbm|}{method_max_disparity|160|}{method_block_size|7|}{method_no_display||}{method_stereo_scal|1|}{i|intrinsics_file.yml|}{e|extrinsics_file.yml|}{o|method_disparity_image.png|}{p|file_cloud_point.txt|}"); if(parser.has("help")) { print_help(); return 0; } filename_img_l = parser.get<std::string>(0); //printf("filename_img_l= %s\n",filename_img_l); //打印左图文件名称 cout<< filename_img_l << endl; filename_img_r = parser.get<std::string>(1); //打印右图文件名称 cout<< filename_img_r << endl; if (parser.has("method_algorithm")) { std::string _method_alg = parser.get<std::string>("method_algorithm"); method_alg = _method_alg == "stereo_bm" ? method_BM : _method_alg == "stereo_sgbm" ? method_SGBM : _method_alg == "stereo_hh" ? method_HH : _method_alg == "var" ? method_VAR : _method_alg == "stereo_sgbm3way" ? method_3WAY : -1; cout<<_method_alg<<endl;//打印调试 选取的方法 } stereo_num_of_disparities = parser.get<int>("method_max_disparity"); cout<<"method_max_disparity="<<stereo_num_of_disparities<<endl;//打印调试 最大视差 stereo_sad_window_size = parser.get<int>("method_block_size"); cout<<"method_block_size="<<stereo_sad_window_size<<endl;//打印调试 块的大小 method_stereo_scal = parser.get<float>("method_stereo_scal"); cout<<"method_stereo_scal="<<method_stereo_scal<<endl;//打印调试  display_no = parser.has("method_no_display"); cout<<display_no<<endl;//打印调试 bool 类型 if( parser.has("i") ) name_intrin_file = parser.get<std::string>("i"); cout<<"name_intrin_file="<<name_intrin_file<<endl;//打印调试 内参文件 if( parser.has("e") ) name_extrin_file = parser.get<std::string>("e"); cout<<"name_extrin_file="<<name_extrin_file<<endl;//打印调试 外参文件 if( parser.has("o") ) File_name_disparity = parser.get<std::string>("o"); cout<<"File_name_disparity="<<File_name_disparity<<endl;//打印调试 视差文件 if( parser.has("p") ) File_name_point_cloud = parser.get<std::string>("p"); cout<<"File_name_point_cloud="<<File_name_point_cloud<<endl;//打印调试 点云文件 if (!parser.check()) { parser.printErrors(); return 1; } if( method_alg < 0 ) { printf("command_line param_error: stereo method_algorithm is error\n\n"); print_help(); return -1; } if ( stereo_num_of_disparities < 1 || stereo_num_of_disparities % 16 != 0 ) { printf("command_line param_error: method_max_disparity must be a positive integer divisible by 16\n"); print_help(); return -1; } if (method_stereo_scal < 0) { printf("command_line param_error: The method_stereo_scal factor must be a positive floating point number\n"); return -1; } if (stereo_sad_window_size < 1 || stereo_sad_window_size % 2 != 1) { printf("command_line param_error: stereo_sad_window_size must be a positive odd number\n"); return -1; } if( filename_img_l.empty() || filename_img_r.empty() ) { printf("command_line param_error: filename_img_l or filename_img_r is empty\n"); return -1; } if( (!name_intrin_file.empty()) ^ (!name_extrin_file.empty()) ) { printf("command_line param_error: name_intrin_file or name_extrin_file is empty \n"); return -1; } if( name_extrin_file.empty() && !File_name_point_cloud.empty() ) { printf("command_line param_error: extrinsic or File_name_point_cloud is empty \n"); return -1; } int mode_color_method = method_alg == method_BM ? 0 : -1; Mat left_img = imread(filename_img_l, mode_color_method); Mat right_img = imread(filename_img_r, mode_color_method); if (left_img.empty()) { printf("command_line param_error: could not load left_img\n"); return -1; } if (right_img.empty()) { printf("command_line param_error: could not load right_img\n"); return -1; } if (method_stereo_scal != 1.f) { Mat scal_temp_1, scal_temp_2; int scal_method = method_stereo_scal < 1 ? INTER_AREA : INTER_CUBIC; resize(left_img, scal_temp_1, Size(), method_stereo_scal, method_stereo_scal, scal_method); left_img = scal_temp_1; resize(right_img, scal_temp_2, Size(), method_stereo_scal, method_stereo_scal, scal_method); right_img = scal_temp_2; } Size size_image = left_img.size(); Rect method_roi_1, method_roi_2; Mat remp_Q; if( !name_intrin_file.empty() ) { // reading intrinsic parameters FileStorage fs(name_intrin_file, FileStorage::READ); if(!fs.isOpened()) { printf("can't open file %s\n", name_intrin_file.c_str()); return -1; } Mat intrin_M1, intrin_D1, intrin_M2, intrin_D2; fs["intrin_M1"] >> intrin_M1; fs["intrin_D1"] >> intrin_D1; fs["intrin_M2"] >> intrin_M2; fs["intrin_D2"] >> intrin_D2; intrin_M1 *= method_stereo_scal; intrin_M2 *= method_stereo_scal; fs.open(name_extrin_file, FileStorage::READ); if(!fs.isOpened()) { printf("can't open file %s\n", name_extrin_file.c_str()); return -1; } Mat Rec,extrin_R, extrin_T, output_R_1, output_P_1, output_R_2, output_P_2; fs["extrin_R"] >> extrin_R; //似乎后面会进行Rodrigues变换 //cout<<Rec<<endl; //Rodrigues(Rec, extrin_R); //Rodrigues变换 //cout<<extrin_R<<endl; fs["extrin_T"] >> extrin_T; stereoRectify( intrin_M1, intrin_D1, intrin_M2, intrin_D2, size_image, extrin_R, extrin_T, output_R_1, output_R_2, output_P_1, output_P_2, remp_Q, CALIB_ZERO_DISPARITY, -1, size_image, &method_roi_1, &method_roi_2 ); Mat URMmap11, URMmap12, URMmap21, URMmap22; initUndistortRectifyMap(intrin_M1, intrin_D1, output_R_1, output_P_1, size_image, CV_16SC2, URMmap11, URMmap12); initUndistortRectifyMap(intrin_M2, intrin_D2, output_R_2, output_P_2, size_image, CV_16SC2, URMmap21, URMmap22); Mat left_img_rectify, right_img_rectify; remap(left_img, left_img_rectify, URMmap11, URMmap12, INTER_LINEAR); remap(right_img, right_img_rectify, URMmap21, URMmap22, INTER_LINEAR); left_img = left_img_rectify; right_img = right_img_rectify; } stereo_num_of_disparities = stereo_num_of_disparities > 0 ? stereo_num_of_disparities : ((size_image.width/8) + 15) & -16;// & -16 被16整除 //cout<<"stereo_num_of_disparities_1="<<stereo_num_of_disparities<<endl; //cout<<"(size_image.width/8) + 15)="<<(size_image.width/8) + 15<<endl; //cout<<"160 & -16="<<(160 & -16)<<endl; //cout<<"(((size_image.width/8) + 15) & -16)="<<(((size_image.width/8) + 15) & -16)<<endl; stereo_bm->setROI1(method_roi_1); stereo_bm->setROI2(method_roi_2); stereo_bm->setPreFilterCap(31); stereo_bm->setBlockSize(stereo_sad_window_size > 0 ? stereo_sad_window_size : 9); stereo_bm->setMinDisparity(0); stereo_bm->setNumDisparities(stereo_num_of_disparities); stereo_bm->setTextureThreshold(10); stereo_bm->setUniquenessRatio(15); stereo_bm->setSpeckleWindowSize(100); stereo_bm->setSpeckleRange(32); stereo_bm->setDisp12MaxDiff(1); stereo_sgbm->setPreFilterCap(63); int sgbm_winsize = stereo_sad_window_size > 0 ? stereo_sad_window_size : 3; stereo_sgbm->setBlockSize(sgbm_winsize); int _channels = left_img.channels(); stereo_sgbm->setP1(8*_channels*sgbm_winsize*sgbm_winsize); stereo_sgbm->setP2(32*_channels*sgbm_winsize*sgbm_winsize); stereo_sgbm->setMinDisparity(0); stereo_sgbm->setNumDisparities(160);//stereo_num_of_disparities 256+16+16+64 stereo_sgbm->setUniquenessRatio(10); stereo_sgbm->setSpeckleWindowSize(100); stereo_sgbm->setSpeckleRange(32); stereo_sgbm->setDisp12MaxDiff(-1); if(method_alg==method_HH) stereo_sgbm->setMode(StereoSGBM::MODE_HH); else if(method_alg==method_SGBM) stereo_sgbm->setMode(StereoSGBM::MODE_SGBM); else if(method_alg==method_3WAY) stereo_sgbm->setMode(StereoSGBM::MODE_SGBM_3WAY); Mat disparites, disparites_u8, disparites_u8_ch; //Mat img1p, img2p, dispp; //copyMakeBorder(left_img, img1p, 0, 0, stereo_num_of_disparities, 0, IPL_BORDER_REPLICATE); //copyMakeBorder(right_img, img2p, 0, 0, stereo_num_of_disparities, 0, IPL_BORDER_REPLICATE); int64 t = getTickCount(); if( method_alg == method_BM ) stereo_bm->compute(left_img, right_img, disparites); else if( method_alg == method_SGBM || method_alg == method_HH || method_alg == method_3WAY ) stereo_sgbm->compute(left_img, right_img, disparites); t = getTickCount() - t; printf("Time of used: %fms\n", t*1000/getTickFrequency()); //创建roi_rect Point pt1=Point(478,178); Point pt2=Point(783,578); Rect rect_pikachu=Rect(pt1.x,pt1.y,pt2.x-pt1.x,pt2.y-pt1.y); Point p_disp; for (int i=pt1.x;i<=pt1.x+10;i++) for(int j=pt1.y;j<=pt1.y+10;j++) { p_disp.x=i; p_disp.y=j; cout<<p_disp<<"in disparites="<<disparites.at<short>(p_disp)<<endl; } //debug cout<<"disparites.type()="<<disparites.type()<<endl<<"disparites.channels()="<<disparites.channels()<<endl;//CV_16SC1 16位有符号数单通道 cout<<"CV_16SC1="<<CV_16SC1<<endl; //创建空的disp_ch Mat disp_ch=Mat::zeros(disparites.rows,disparites.cols,disparites.type());//CV_16SC1 cout<<"disparites.rows="<<disparites.rows<<endl<<"disparites.cols="<<disparites.cols<<endl; //imshow("disp_ch",disp_ch); //创建roi Mat disp_roi=disparites(rect_pikachu); Mat disp_roi_zero=disp_ch(rect_pikachu); //深拷贝原图roi Mat disp_roi_threshold=disp_roi.clone(); Mat roi_threshold_result;//阈值结果 threshold(disp_roi_threshold,roi_threshold_result,1000,2000,THRESH_TOZERO);//去除较小值小于1000去除 imshow("disp_roi_threshold_first",roi_threshold_result);//显示阈值结果 disp_roi_threshold = roi_threshold_result.clone();//深拷贝 threshold(disp_roi_threshold, roi_threshold_result, 2000, 255, THRESH_TOZERO_INV);//去除数值较高的,大于2000去除 imshow("disp_roi_threshold_second", roi_threshold_result);//显示阈值后的效果 */ imshow("disp_roi",disp_roi);//展示原图的感兴趣区域 roi_threshold_result.copyTo(disp_roi_zero);//将16位阈值后视差原图的roi拷贝到16位空的视差图相应的Roi中 namedWindow("目标视差图"); imshow("目标视差图",disp_ch);//显示新的是视差图 imshow("disparites",disparites);//5.26 add //disparites = dispp.colRange(stereo_num_of_disparities, img1p.cols); if( method_alg != method_VAR ) {disparites.convertTo(disparites_u8, CV_8U, 255/(stereo_num_of_disparities*16.));//将原图视差图转换为8位无符号(灰度可见)的形式 cout<<"stereo_num_of_disparities="<<stereo_num_of_disparities<<endl;//打印最大视差窗口 disp_ch.convertTo(disparites_u8_ch, CV_8U, 255/(stereo_num_of_disparities*16.));//目标视差图转换为8位无符号(灰度可见)的形式 } else disparites.convertTo(disparites_u8, CV_8U);//不会执行 if( !display_no ) { namedWindow("left_image", 1); imshow("left_image", left_img); imwrite("Rectify_left_pic.png",left_img); namedWindow("right_image", 1); imshow("right_image", right_img); imwrite("Rectify_right_pic.png",right_img); namedWindow("disparity", 0); namedWindow("disparity_ch", 0); imshow("disparity", disparites_u8); imshow("disparity_ch", disparites_u8_ch); printf("press any key to continue..."); fflush(stdout); waitKey(); printf("\n"); } if(!File_name_disparity.empty())//如果存在这个文件夹 继续 imwrite(File_name_disparity, disparites_u8); if(!File_name_disparity_ch.empty())//如果存在这个文件夹 继续 imwrite(File_name_disparity_ch, disparites_u8_ch); if(!File_name_point_cloud.empty()) { printf("point cloud is storing..."); fflush(stdout); //Mat poin_cloud_xyz(disparites.rows, disparites.cols, CV_32FC3, cv::Scalar::all(0)); //Mat poin_cloud_xyz_ch(disparites.rows, disparites.cols, CV_32FC3, cv::Scalar::all(0)); Mat poin_cloud_xyz; Mat poin_cloud_xyz_ch; reprojectImageTo3D(disparites, poin_cloud_xyz, remp_Q, true);//poin_cloud_xyz.depth=CV_32F poin_cloud_xyz.type=CV_32FC3 reprojectImageTo3D(disp_ch, poin_cloud_xyz_ch, remp_Q, true); //debug cout<<"poin_cloud_xyz.type()="<<poin_cloud_xyz.type()<<endl<<"poin_cloud_xyz.channels()="<<poin_cloud_xyz.channels()<<endl<<"poin_cloud_xyz.depth="<<poin_cloud_xyz.depth()<<endl;//CV_16SC1 16位有符号数单通道 cout<<"poin_cloud_xyz_ch.type()="<<poin_cloud_xyz_ch.type()<<endl<<"poin_cloud_xyz_ch.channels()="<<poin_cloud_xyz_ch.channels()<<endl<<"poin_cloud_xyz_ch.depth="<<poin_cloud_xyz_ch.depth()<<endl;//CV_16SC1 16位有符号数单通道 rectangle(poin_cloud_xyz,rect_pikachu,Scalar(255,0,0)); imshow("poin_cloud_xyz",poin_cloud_xyz); imshow("poin_cloud_xyz_ch",poin_cloud_xyz_ch); imwrite("poin_cloud_xyz.png",poin_cloud_xyz); imwrite("poin_cloud_xyz_ch.png",poin_cloud_xyz_ch); Point xyz_p_1; xyz_p_1.x=669;//691(点1) 524(点2) 544(棋盘格) 669(picha_07) xyz_p_1.y=366;//334(点1) 140(点2) 206(棋盘格) 366(picha_07) cout<<xyz_p_1<<"in disp_ch="<<poin_cloud_xyz_ch.at<Vec3f>(xyz_p_1)*16<<endl; Point xyz_p_2; xyz_p_2.x=721;// 596(棋盘格) 721(picha_07) xyz_p_2.y=363;// 206(棋盘格) 363(picha_07) cout<<xyz_p_2<<"in disp_ch="<<poin_cloud_xyz_ch.at<Vec3f>(xyz_p_2)*16<<endl; waitKey(); saveXYZ(File_name_point_cloud.c_str(), poin_cloud_xyz); saveXYZ(File_name_point_cloud_ch.c_str(), poin_cloud_xyz_ch); printf("\n"); } return 0; }
#include "AppDelegate.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <random> #include <ctime> #include <cstdio> #include "GLProgram.h" #include "Shader.h" #include "Bitmap.h" #include "Texture2D.h" #include "Camera.h" #include "platform.hpp" using namespace std; using namespace glm; static void CHECK_GL_ERROR_DEBUG() { GLenum error = glGetError(); if (error) { printf("OpenGL error 0x%04X in %s %s %d\n", error, __FILE__, __FUNCTION__, __LINE__); } } void AppDelegate::beforeInit() { _inited = false; } void AppDelegate::prepare(float dt) { if (!_inited) { _loadShaders(); _loadTexture(); _initCamera(); _initVertexData(); _inited = true; } } void AppDelegate::render() { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _program->use(); _program->setUniform("camera", _camera->matrix()); glBindVertexArray(_vao); // method one glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _rgbTexture->id()); _program->setUniform("tex", 0); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, _alphaTexture->id()); _program->setUniform("tex2", 1); // method two /*glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, _rgbaTexture->id()); _program->setUniform("tex", 0);*/ glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (GLvoid *)0); glBindTexture(GL_TEXTURE_2D, 0); glBindVertexArray(0); _program->stop(); } AppDelegate::~AppDelegate() { if (glIsVertexArray(_vao)) { glDeleteVertexArrays(1, &_vao); } if (glIsBuffer(_vbos[0]) && glIsBuffer(_vbos[1])) { glDeleteBuffers(2, &_vbos[0]); } } void AppDelegate::_loadShaders() { std::vector<std::shared_ptr<Shader> > shaders; shared_ptr<Shader> vertShader(new Shader(::ResourcePath("etc_with_alpha.vert"), GL_VERTEX_SHADER)); shared_ptr<Shader> fragShader(new Shader(::ResourcePath("etc_with_alpha.frag"), GL_FRAGMENT_SHADER)); shaders.push_back(vertShader); shaders.push_back(fragShader); _program = shared_ptr<GLProgram>(new GLProgram(shaders)); } void AppDelegate::_loadTexture() { shared_ptr<Bitmap> rgbBmp(new Bitmap(::ResourcePath("rgb2.jpg"))); _rgbTexture = shared_ptr<Texture2D>(new Texture2D(rgbBmp.get())); shared_ptr<Bitmap> alphaBmp(new Bitmap(::ResourcePath("alpha2.jpg"))); _alphaTexture = shared_ptr<Texture2D>(new Texture2D(alphaBmp.get())); shared_ptr<Bitmap> rgbaBmp(new Bitmap(::ResourcePath("rgba.jpg"))); _rgbaTexture = shared_ptr<Texture2D>(new Texture2D(rgbaBmp.get())); } void AppDelegate::_initCamera() { _camera = shared_ptr<Camera>(new Camera()); _camera->setViewportAspectRatio(_width / _height); _camera->setPosition(vec3(0, 0, 4)); } void AppDelegate::_initVertexData() { glGenVertexArrays(1, &_vao); glGenBuffers(2, &_vbos[0]); GLfloat vertexData[] = { // X Y Z U V // bottom-left -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, // top-left -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, // top-right 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, // bottom-right 1.0f, -1.0f, 0.0f, 1.0f, 0.0f }; glBindVertexArray(_vao); glBindBuffer(GL_ARRAY_BUFFER, _vbos[0]); glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), &vertexData[0], GL_STATIC_DRAW); GLushort indices[] = { 0, 1, 3, 1, 2, 3 }; glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vbos[1]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), &indices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(_program->attribute("vert")); glVertexAttribPointer(_program->attribute("vert"), 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), nullptr); glEnableVertexAttribArray(_program->attribute("vertTexCoord")); glVertexAttribPointer(_program->attribute("vertTexCoord"), 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (const GLvoid *)(3 * sizeof(GLfloat))); glBindVertexArray(0); }
#include <bits/stdc++.h> using namespace std; bool validPos(int i){ return (i>=0 && i<9); } vector<int> getBlankSpace(vector<string> mp){ //returns vector [si,sj,ei,ej] int si=-1,sj=-1,ei=-1,ej=-1,nexti,nextj,diri=-1,dirj=-1; int dx[] = {-1,1,0,0}; int dy[] = {0,0,-1,1}; for(int i=0;i<10 && si==-1;i++){ for(int j=0;j<10 && si==-1;j++){ //for each position if(mp[i][j]!='+'){ //if not restricted location for(int k=0;k<4 && si==-1;k++){ nexti = i+dx[k]; nextj = j+dy[k]; if(validPos(nexti) && validPos(nextj) && mp[nexti][nextj]=='-'){ si = i; sj = j; diri = dx[k]; dirj = dy[k]; break; } } } } } ei = nexti; ej = nextj; while(validPos(nexti) && validPos(nextj)){ ei = nexti; ej = nextj; ei = ei+diri; ej = ej+dirj; } return vector<int>({si,sj,ei,ej,diri,dirj}); } int getLen(int si,int sj, int ei, int ej){ //either same row or same col if(ei==si){ return abs(ej-sj); }else{ return abs(ei-si); } } bool solve(vector<string> mp, vector<string> dic, int si, int sj, int ei, int ej, int diri,int dirj){ int len = getLen(si,sj,ei,ej); for(int i=0;i<dic.size();i++){ if(len==dic[i].size() && (mp[si][sj]=='-' || mp[si][sj] == dic[i][0] )){ for(int j=0;j<len;j++){ //put the word mp[si+j*diri][sj+j*dirj] = dic[i][j]; } vector<int> temp = getBlankSpace(mp); if(temp[0]==-1){ for(int i=0;i<10;i++){ cout << mp[i] << endl; } return true; } string temps = dic[i]; dic[i] = ""; return solve(mp,dic,temp[0],temp[1],temp[2],temp[3],temp[4],temp[5]); } } } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ vector<string> mp; string temp; for(int i=0;i<10;i++){ cin >> temp; mp.push_back(temp); } cin >> temp; string p = strtok(temp, ";"); while(p!=NULL){ mp.push_back(p); cout << "adding " << p; p = strtok(NULL,";"); } return 0; }
// Created on: 2015-03-15 // Created by: Danila ULYANOV // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ViewerTest_CmdParser_HeaderFile #define _ViewerTest_CmdParser_HeaderFile #include <Graphic3d_Vec3.hxx> #include <limits> #include <map> #include <vector> #include <set> #include <string> class Quantity_Color; class Quantity_ColorRGBA; class gp_Vec; class gp_Pnt; //! A key for a command line option used for a ViewerTest_CmdParser work typedef std::size_t ViewerTest_CommandOptionKey; //! A set of keys for command-line options typedef std::set<ViewerTest_CommandOptionKey> ViewerTest_CommandOptionKeySet; //! Command parser. class ViewerTest_CmdParser { public: //! The key of the unnamed command option static const std::size_t THE_UNNAMED_COMMAND_OPTION_KEY; //! The key of the help command option static const std::size_t THE_HELP_COMMAND_OPTION_KEY; //! Initializes help option. //! @param theDescription the description of the command ViewerTest_CmdParser (const std::string& theDescription = std::string()); //! Sets description for command. void SetDescription (const std::string& theDescription) { myDescription = theDescription; } //! Adds option to available option list. Several names may be provided if separated with '|'. //! @param theOptionNames the list of possible option names separated with '|' //! (the first name is main, the other names are aliases) //! @param theOptionDescription the description of the option //! @return an access key of the newly added option ViewerTest_CommandOptionKey AddOption (const std::string& theOptionNames, const std::string& theOptionDescription = std::string()); //! Prints help message based on provided command and options descriptions. void PrintHelp() const; //! Parses argument list (skips the command name); assigns local arguments to each option. void Parse (Standard_Integer theArgsNb, const char* const* theArgVec); //! Gets an option name by its access key //! @param theOptionKey the access key of the option which name is to be found //! @retuan a name of the option with the given access key std::string GetOptionNameByKey (ViewerTest_CommandOptionKey theOptionKey) const; //! Gets a set of used options //! @return a set of used options ViewerTest_CommandOptionKeySet GetUsedOptions() const; //! Tests if there were no command line options provided //! @return true if no command line options were provided, or false otherwise bool HasNoOption() const; //! Tests if the unnamed command line option was provided //! @return true if the unnamed command line option was provided, or false otherwise bool HasUnnamedOption() const; //! Tests if only unnamed command line option was provided //! @return true if only unnamed command line option was provided, or false otherwise bool HasOnlyUnnamedOption() const; //! Checks if option was used with given minimal number of arguments. //! Prints error message if isFatal flag was set. //! @param theOptionName the name of the option to be checked //! @param theMandatoryArgsNb the number of mandatory arguments //! @param isFatal the flag that controls printing of an error message //! @return true if an option was set, or false otherwise bool HasOption (const std::string& theOptionName, std::size_t theMandatoryArgsNb = 0, bool isFatal = Standard_False) const; //! Checks if option was used with given minimal number of arguments. //! Prints error message if isFatal flag was set. //! @param theOptionKey the access key of the option to be checked //! @param theMandatoryArgsNb the number of mandatory arguments //! @param isFatal the flag that controls printing of an error message //! @return true if an option was set, or false otherwise bool HasOption (ViewerTest_CommandOptionKey theOptionKey, std::size_t theMandatoryArgsNb = 0, bool isFatal = Standard_False) const; //! Gets a number of option arguments //! @param theOptionName the name of the option //! @return a number of option arguments, or 0 if option was not used Standard_Integer GetNumberOfOptionArguments (const std::string& theOptionName) const; //! Gets a number of option arguments //! @param theOptionKey the access key of the option //! @return a number of option arguments, or 0 if option was not used Standard_Integer GetNumberOfOptionArguments (ViewerTest_CommandOptionKey theOptionKey) const; //! Accesses local argument of option 'theOptionName' with index 'theArgumentIndex'. //! @param theOptionName the name of the option which argument is to be accessed //! @param theArgumentIndex the index of an accessed argument //! @param theOptionArgument an argument of the option with the given name //! @return true if an access was successful, or false otherwise bool Arg (const std::string& theOptionName, Standard_Integer theArgumentIndex, std::string& theOptionArgument) const; //! Accesses a local argument with the index 'theArgumentIndex' of the option with the key 'theOptionKey'. //! @param theOptionKey the access key of the option which argument is to be accessed //! @param theArgumentIndex the index of an accessed argument //! @param theOptionArgument an argument of the option with the given key //! @return true if an access was successful, or false otherwise bool Arg (ViewerTest_CommandOptionKey theOptionKey, Standard_Integer theArgumentIndex, std::string& theOptionArgument) const; //! Accesses local argument of option 'theOptionName' with index 'theArgumentIndex'. //! @param theOptionName the name of the option which argument is to be accessed //! @param theArgumentIndex the index of an accessed argument //! @return an argument of the option with the given name std::string Arg (const std::string& theOptionName, Standard_Integer theArgumentIndex) const; //! Accesses a local argument with the index 'theArgumentIndex' of the option with the key 'theOptionKey'. //! @param theOptionKey the access key of the option which argument is to be accessed //! @param theArgumentIndex the index of an accessed argument //! @return an argument of the option with the given key std::string Arg (ViewerTest_CommandOptionKey theOptionKey, Standard_Integer theArgumentIndex) const; // Interprets arguments of option 'theOptionName' as float vector starting with index 'theArgumentIndex'. Graphic3d_Vec3 ArgVec3f (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as double vector starting with index 'theArgumentIndex'. Graphic3d_Vec3d ArgVec3d (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as gp vector starting with index 'theArgumentIndex'. gp_Vec ArgVec (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as gp vector starting with index 'theArgumentIndex'. gp_Pnt ArgPnt (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as double at index 'theArgumentIndex'. Standard_Real ArgDouble (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as float at index 'theArgumentIndex'. Standard_ShortReal ArgFloat (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as integer at index 'theArgumentIndex'. Standard_Integer ArgInt (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; // Interprets arguments of option 'theOptionName' as boolean at index 'theArgumentIndex'. bool ArgBool (const std::string& theOptionName, const Standard_Integer theArgumentIndex = 0) const; //! Interprets arguments of the option 'theOptionName' with the index 'theArgumentIndex' as an RGB(A) color object. //! @tparam theColor the type of a resulting RGB(A) color object //! @param theOptionName the name of the option which arguments are to be interpreted //! @param theArgumentIndex the index of the first argument to be interpreted //! (will be promoted to the next argument after the block of interpreted arguments) //! @param theColor a color that is an interpretation of argument(s) of the option with the given name //! @return true if an interpretation was successful, or false otherwise template <typename TheColor> bool ArgColor (const std::string& theOptionName, Standard_Integer& theArgumentIndex, TheColor& theColor) const; //! Interprets arguments of the option with the key 'theOptionKey' as an RGB(A) color object. //! @tparam theColor the type of a resulting RGB(A) color object //! @param theOptionKey the access key of the option which arguments are to be interpreted //! @param theArgumentIndex the index of the first argument to be interpreted //! (will be promoted to the next argument after the block of interpreted arguments) //! @param theColor a color that is an interpretation of argument(s) of the option with the given name //! @return true if an interpretation was successful, or false otherwise template <typename TheColor> bool ArgColor (ViewerTest_CommandOptionKey theOptionKey, Standard_Integer& theArgumentIndex, TheColor& theColor) const; private: //! A list of aliases to a command option name typedef std::vector<std::string> OptionAliases; //! A map from all possible option names to option access keys typedef std::map<std::string, ViewerTest_CommandOptionKey> OptionMap; //! A map from keys of used options to their indices in the storage typedef std::map<ViewerTest_CommandOptionKey, std::size_t> UsedOptionMap; //! A list of command option arguments typedef std::vector<std::string> OptionArguments; //! A storage of arguments of different command options typedef std::vector<OptionArguments> OptionArgumentsStorage; //! A full description of a command option struct CommandOption { std::string Name; //!< A command option name OptionAliases Aliases; //!< A list of aliases to a command option name std::string Description; //!< A text description of a command option }; // A storage of command options descriptions typedef std::vector<CommandOption> CommandOptionStorage; // A list of raw string arguments typedef std::vector<const char*> RawStringArguments; //! Description of command. std::string myDescription; //! Container which stores option objects. std::vector<CommandOption> myOptionStorage; //! Map from all possible option names to option access keys (that are indices in myOptionStorage) OptionMap myOptionMap; //! Map from keys of used options to their indices in the option arguments storage UsedOptionMap myUsedOptionMap; //! Container which stores the arguments of all used options OptionArgumentsStorage myOptionArgumentStorage; //! Gets an access key of the option //! @param theOptionName the name of the option which key is to be found //! @param theOptionKey an access key of the option with the given name //! @return true if the given option was found, or false otherwise bool findOptionKey (const std::string& theOptionName, ViewerTest_CommandOptionKey& theOptionKey) const; //! Gets an index of an option that was used //! @param theOptionKey the access key of the used option which index is to be found //! @param theUsedOptionIndex an index of the used option with the given access key //! @return true if the given option was not found or not used, or false otherwise bool findUsedOptionIndex (ViewerTest_CommandOptionKey theOptionKey, std::size_t& theUsedOptionIndex) const; //! Gets an index of an option that was used //! @param theOptionName the name of the used option which index is to be found //! @param theUsedOptionIndex an index of the used option with the given name //! @return true if the given option was not found or not used, or false otherwise bool findUsedOptionIndex (const std::string& theOptionName, std::size_t& theUsedOptionIndex) const; //! Adds the option that is used in the passed command line parameters //! @param theNewUsedOptionKey the access key of the adding option //! @return an index of a newly added option std::size_t addUsedOption (ViewerTest_CommandOptionKey theNewUsedOptionKey); //! Gets an index of an option that was used //! @param theOptionName the name of the used option which index is to be found //! @param theUsedOptionIndex an index of the used option with the given name //! @return true if the given option was not found or not used, or false otherwise RawStringArguments getRawStringArguments (std::size_t theUsedOptionIndex) const; }; #endif // _ViewerTest_CmdParser_HeaderFile
#include <fstream> #include <iostream> #include <sstream> #include <vector> #include <string> #include "Eigen/Dense" #include "measurement_package.h" #include "tracking.h" int main() { /* We have a file with lines of data. The line could be either from RADAR or LIDAR. Consider each line a measurement package. Let's create a list (vector) of the first 4 LASER measurments and process the last 3 of it. */ /* OPEN MEASUREMENTS FILE */ // hardcoded input file with laser and radar measurements std::string in_file_name_ = "EKF_DATA/obj_pose-laser-radar-synthetic-input.txt"; std::ifstream in_file(in_file_name_.c_str()); // c_str() converts string to char*, ifstream::in is a flag to allow access to input from the stream // Check for error if (!in_file.is_open()) { std::cout << "Cannot open input file: " << in_file_name_ << std::endl; } /* READ FILE - line by line, only LASER, 4 lines */ std::vector<MeasurementPackage> measurement_pack_list; // Here is the list of measurment packages (all 3 LASER lines) MeasurementPackage meas_package; // Each line data long timestamp; // timestamp data from measurment package (line) float x; // x position data from measurment package (line) float y; // y position data from measurment package (line) std::string line; // it will hold temporary stream line information // set i to get only first 4 measurements int i = 0; // starting with zero the while will loop 0,1,2,3 (4 lines) while(std::getline(in_file, line) && (i<=3)){ /* READ LASER ONLY */ std::istringstream iss(line); // istringstream class is used to split line information into variables std::string sensor_type; iss >> sensor_type; //reads first element from the current line if(sensor_type.compare("L") == 0){ //laser measurement, string.compare method will return 0 if true //read measurements meas_package.sensor_type_ = MeasurementPackage::LASER; meas_package.raw_measurements_ = Eigen::VectorXd(2); iss >> x; iss >> y; meas_package.raw_measurements_ << x,y; iss >> timestamp; meas_package.timestamp_ = timestamp; measurement_pack_list.push_back(meas_package); } else if(sensor_type.compare("R") == 0){ //Skip Radar measurements continue; } i++; } /* PROCESS THE STORED LASER MEASUREMENTS */ //Create a Tracking instance Tracking tracking; // tracking class has the method ProcessMeasurement, used to process the data //call the ProcessingMeasurement() function for each measurement size_t N = measurement_pack_list.size(); // how many packages (lines) to loop through? size_t id used because we define a variable that takes a size for (size_t k = 0; k < N; ++k) { tracking.ProcessMeasurement(measurement_pack_list[k]); // the method will use first line (package) only to initialize // so the filtering effectivelly starts from the second frame // (the speed is also unknown in the first frame, so that is appropriate) } /* CLOSE MEASUREMENTS FILE */ if(in_file.is_open()){ in_file.close(); } return 0; }
#ifndef FUZZYCORE_REFRESHVIEWEXCEPTION_H #define FUZZYCORE_REFRESHVIEWEXCEPTION_H #include "ViewException.h" class RefreshViewException : public ViewException { public: explicit RefreshViewException(const std::string &); }; #endif
#include <bits/stdc++.h> using namespace std; int main() { int n, ans = 0; cin>>n; while(n--) { int p, q; cin>>p>>q; if(q-p>=2) ans++; } cout<<ans<<endl; }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2018 Ryo Suzuki // Copyright (c) 2016-2018 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include <Siv3D/Script.hpp> # include <Siv3D/Periodic.hpp> # include "ScriptBind.hpp" namespace s3d { using namespace AngelScript; void RegisterPeriodic(asIScriptEngine* engine) { int32 r = 0; r = engine->SetDefaultNamespace("Periodic"); assert(r >= 0); { r = engine->RegisterGlobalFunction("double Sine0_1(double, double = Time::GetMicrosec() / 1000000.0)", asFUNCTIONPR(Periodic::Sine0_1, (double, double), double), asCALL_CDECL); assert(r >= 0); r = engine->RegisterGlobalFunction("double Square0_1(double, double = Time::GetMicrosec() / 1000000.0)", asFUNCTIONPR(Periodic::Square0_1, (double, double), double), asCALL_CDECL); assert(r >= 0); r = engine->RegisterGlobalFunction("double Tringle0_1(double, double = Time::GetMicrosec() / 1000000.0)", asFUNCTIONPR(Periodic::Tringle0_1, (double, double), double), asCALL_CDECL); assert(r >= 0); r = engine->RegisterGlobalFunction("double Sawtooth0_1(double, double = Time::GetMicrosec() / 1000000.0)", asFUNCTIONPR(Periodic::Sawtooth0_1, (double, double), double), asCALL_CDECL); assert(r >= 0); } r = engine->SetDefaultNamespace(""); assert(r >= 0); } }
/usr/include/c++/4.4/./debug/safe_iterator.tcc
#include <iostream> #include "DefEnv.h" #include "AllTest.h" #if ENABLE_EXE int main() { #if ENABLE_TEST RunTest(); #endif return 0; } #endif
#include <bits/stdc++.h> using namespace std; class Solution { public: int minSteps(string s, string t) { if (s == t) return 0; map<char, int> m; for (char c : s) m[c]++; int ans = 0; for (char c : t) if (m.find(c) != m.end() && m[c] > 0) m[c]--; else ans++; return ans; } };
#pragma once #include "../MetaMorpheusEngine.h" #include <string> #include <unordered_map> #include <unordered_set> #include <vector> #include "../PeptideSpectralMatch.h" #include "../CommonParameters.h" #include "../MetaMorpheusEngineResults.h" using namespace Chemistry; namespace EngineLayer { namespace ModificationAnalysis { typedef std::tuple<std::string, std::string, int> ModTuple; struct ModTuple_hash: public std::unary_function<ModTuple, std::size_t>{ std::size_t operator() (const ModTuple& k ) const { size_t h1= std::hash<std::string>{}(std::get<0>(k)); size_t h2= std::hash<std::string>{}(std::get<1>(k)); size_t h3= std::hash<int>{}(std::get<2>(k)); return h1 ^ (h2 << 1) ^ (h3 << 2); } }; struct ModTuple_equal: public std::binary_function<ModTuple, ModTuple, bool>{ bool operator() (const ModTuple& lhs, const ModTuple& rhs) const { return std::get<0>(lhs) == std::get<0>(rhs) && std::get<1>(lhs) == std::get<1>(rhs) && std::get<2>(lhs) == std::get<2>(rhs); } }; typedef std::unordered_set<ModTuple, ModTuple_hash, ModTuple_equal> ModTuple_set; class ModificationAnalysisEngine : public MetaMorpheusEngine { private: const std::vector<PeptideSpectralMatch*> NewPsms; public: ModificationAnalysisEngine(std::vector<PeptideSpectralMatch*> &newPsms, CommonParameters *commonParameters, std::vector<std::string> nestedIds, int verbosityLevel=0); protected: MetaMorpheusEngineResults *RunSpecific() override; }; } }
#include<bits/stdc++.h> using namespace std; #define debug(x) cerr << #x << ": " << x << endl; #define iosbase ios_base::sync_with_stdio(false) #define tie cin.tie();cout.tie(); #define endl '\n' typedef pair<int, int> ii; typedef long long ll; #define T int t; cin >> t; while( t--) #define sT int t; scanf("%d", &t); while( t--) int n, m; int main(){ sT{ set<int> ans; ll n; scanf("%lld", &n); ll i = 0LL; if(n == 1LL){ printf("2\n0 1\n"); continue; } for(ll i = 1; i * i <= n; i++){ ll x = n/i; ans.insert( n / x); ans.insert(n/i); // debug(n/i); } printf("%d\n",( (int)ans.size()) + 1); printf("0"); for(auto it: ans){ printf(" %d", it); }puts(""); } }
/**************************************************************************** ** Meta object code from reading C++ file 'dialog.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../dotrgb_gui/dialog.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'dialog.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.8.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_Dialog_t { QByteArrayData data[32]; char stringdata0[649]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_Dialog_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_Dialog_t qt_meta_stringdata_Dialog = { { QT_MOC_LITERAL(0, 0, 6), // "Dialog" QT_MOC_LITERAL(1, 7, 19), // "on_RED_stateChanged" QT_MOC_LITERAL(2, 27, 0), // "" QT_MOC_LITERAL(3, 28, 4), // "arg1" QT_MOC_LITERAL(4, 33, 21), // "on_GREEN_stateChanged" QT_MOC_LITERAL(5, 55, 20), // "on_BLUE_stateChanged" QT_MOC_LITERAL(6, 76, 12), // "updateDotRGB" QT_MOC_LITERAL(7, 89, 7), // "command" QT_MOC_LITERAL(8, 97, 21), // "on_RED_2_stateChanged" QT_MOC_LITERAL(9, 119, 21), // "on_RED_3_stateChanged" QT_MOC_LITERAL(10, 141, 21), // "on_RED_4_stateChanged" QT_MOC_LITERAL(11, 163, 21), // "on_RED_5_stateChanged" QT_MOC_LITERAL(12, 185, 21), // "on_RED_6_stateChanged" QT_MOC_LITERAL(13, 207, 21), // "on_RED_7_stateChanged" QT_MOC_LITERAL(14, 229, 21), // "on_RED_8_stateChanged" QT_MOC_LITERAL(15, 251, 21), // "on_RED_9_stateChanged" QT_MOC_LITERAL(16, 273, 23), // "on_GREEN_2_stateChanged" QT_MOC_LITERAL(17, 297, 23), // "on_GREEN_3_stateChanged" QT_MOC_LITERAL(18, 321, 23), // "on_GREEN_4_stateChanged" QT_MOC_LITERAL(19, 345, 23), // "on_GREEN_5_stateChanged" QT_MOC_LITERAL(20, 369, 23), // "on_GREEN_6_stateChanged" QT_MOC_LITERAL(21, 393, 23), // "on_GREEN_7_stateChanged" QT_MOC_LITERAL(22, 417, 23), // "on_GREEN_8_stateChanged" QT_MOC_LITERAL(23, 441, 23), // "on_GREEN_9_stateChanged" QT_MOC_LITERAL(24, 465, 22), // "on_BLUE_2_stateChanged" QT_MOC_LITERAL(25, 488, 22), // "on_BLUE_3_stateChanged" QT_MOC_LITERAL(26, 511, 22), // "on_BLUE_4_stateChanged" QT_MOC_LITERAL(27, 534, 22), // "on_BLUE_5_stateChanged" QT_MOC_LITERAL(28, 557, 22), // "on_BLUE_6_stateChanged" QT_MOC_LITERAL(29, 580, 22), // "on_BLUE_7_stateChanged" QT_MOC_LITERAL(30, 603, 22), // "on_BLUE_8_stateChanged" QT_MOC_LITERAL(31, 626, 22) // "on_BLUE_9_stateChanged" }, "Dialog\0on_RED_stateChanged\0\0arg1\0" "on_GREEN_stateChanged\0on_BLUE_stateChanged\0" "updateDotRGB\0command\0on_RED_2_stateChanged\0" "on_RED_3_stateChanged\0on_RED_4_stateChanged\0" "on_RED_5_stateChanged\0on_RED_6_stateChanged\0" "on_RED_7_stateChanged\0on_RED_8_stateChanged\0" "on_RED_9_stateChanged\0on_GREEN_2_stateChanged\0" "on_GREEN_3_stateChanged\0on_GREEN_4_stateChanged\0" "on_GREEN_5_stateChanged\0on_GREEN_6_stateChanged\0" "on_GREEN_7_stateChanged\0on_GREEN_8_stateChanged\0" "on_GREEN_9_stateChanged\0on_BLUE_2_stateChanged\0" "on_BLUE_3_stateChanged\0on_BLUE_4_stateChanged\0" "on_BLUE_5_stateChanged\0on_BLUE_6_stateChanged\0" "on_BLUE_7_stateChanged\0on_BLUE_8_stateChanged\0" "on_BLUE_9_stateChanged" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_Dialog[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 28, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 154, 2, 0x08 /* Private */, 4, 1, 157, 2, 0x08 /* Private */, 5, 1, 160, 2, 0x08 /* Private */, 6, 1, 163, 2, 0x08 /* Private */, 8, 1, 166, 2, 0x08 /* Private */, 9, 1, 169, 2, 0x08 /* Private */, 10, 1, 172, 2, 0x08 /* Private */, 11, 1, 175, 2, 0x08 /* Private */, 12, 1, 178, 2, 0x08 /* Private */, 13, 1, 181, 2, 0x08 /* Private */, 14, 1, 184, 2, 0x08 /* Private */, 15, 1, 187, 2, 0x08 /* Private */, 16, 1, 190, 2, 0x08 /* Private */, 17, 1, 193, 2, 0x08 /* Private */, 18, 1, 196, 2, 0x08 /* Private */, 19, 1, 199, 2, 0x08 /* Private */, 20, 1, 202, 2, 0x08 /* Private */, 21, 1, 205, 2, 0x08 /* Private */, 22, 1, 208, 2, 0x08 /* Private */, 23, 1, 211, 2, 0x08 /* Private */, 24, 1, 214, 2, 0x08 /* Private */, 25, 1, 217, 2, 0x08 /* Private */, 26, 1, 220, 2, 0x08 /* Private */, 27, 1, 223, 2, 0x08 /* Private */, 28, 1, 226, 2, 0x08 /* Private */, 29, 1, 229, 2, 0x08 /* Private */, 30, 1, 232, 2, 0x08 /* Private */, 31, 1, 235, 2, 0x08 /* Private */, // slots: parameters QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::QString, 7, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, QMetaType::Void, QMetaType::Int, 3, 0 // eod }; void Dialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Dialog *_t = static_cast<Dialog *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->on_RED_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: _t->on_GREEN_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: _t->on_BLUE_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 3: _t->updateDotRGB((*reinterpret_cast< QString(*)>(_a[1]))); break; case 4: _t->on_RED_2_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 5: _t->on_RED_3_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 6: _t->on_RED_4_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 7: _t->on_RED_5_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 8: _t->on_RED_6_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 9: _t->on_RED_7_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 10: _t->on_RED_8_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 11: _t->on_RED_9_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 12: _t->on_GREEN_2_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 13: _t->on_GREEN_3_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 14: _t->on_GREEN_4_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 15: _t->on_GREEN_5_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 16: _t->on_GREEN_6_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 17: _t->on_GREEN_7_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 18: _t->on_GREEN_8_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 19: _t->on_GREEN_9_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 20: _t->on_BLUE_2_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 21: _t->on_BLUE_3_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 22: _t->on_BLUE_4_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 23: _t->on_BLUE_5_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 24: _t->on_BLUE_6_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 25: _t->on_BLUE_7_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 26: _t->on_BLUE_8_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 27: _t->on_BLUE_9_stateChanged((*reinterpret_cast< int(*)>(_a[1]))); break; default: ; } } } const QMetaObject Dialog::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_Dialog.data, qt_meta_data_Dialog, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *Dialog::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *Dialog::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_Dialog.stringdata0)) return static_cast<void*>(const_cast< Dialog*>(this)); return QDialog::qt_metacast(_clname); } int Dialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 28) qt_static_metacall(this, _c, _id, _a); _id -= 28; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 28) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 28; } return _id; } QT_WARNING_POP QT_END_MOC_NAMESPACE
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jwon <jwon@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/12/30 12:50:44 by jwon #+# #+# */ /* Updated: 2021/01/22 18:10:17 by jwon ### ########.fr */ /* */ /* ************************************************************************** */ #include "FragTrap.hpp" void fragtrapTest(void) { FragTrap Jwon; FragTrap Yechoi("Yechoi"); unsigned int damage; Jwon = FragTrap("Jwon"); std::cout << std::endl; Jwon.playerStatus(); Yechoi.playerStatus(); std::cout << std::endl; Jwon.takeDamage(Yechoi.rangedAttack(Jwon.m_name)); Jwon.takeDamage(Yechoi.rangedAttack(Jwon.m_name)); std::cout << std::endl; Yechoi.takeDamage(Jwon.meleeAttack(Yechoi.m_name)); Yechoi.takeDamage(Jwon.meleeAttack(Yechoi.m_name)); std::cout << std::endl; Yechoi.beRepaired(42); Yechoi.beRepaired(42); std::cout << std::endl; Jwon.beRepaired(5); Jwon.beRepaired(5); std::cout << std::endl; srand(time(NULL)); std::cout << ">>> Start random attack!!!! <<<" << std::endl; Jwon.playerStatus(); Yechoi.playerStatus(); std::cout << std::endl; for (int i = 0 ; i < 5 ; i++) { if ((damage = Yechoi.vaulthunter_dot_exe(Jwon.m_name)) == 0) break ; Jwon.takeDamage(damage); std::cout << std::endl; } std::cout << std::endl; } int main(void) { fragtrapTest(); return (EXIT_SUCCESS); }
#include "../commonunion.h" #include <iostream> using namespace std; COMMONUNION(FooUnion,,foo) template<int I> struct isval { constexpr int foo(int i) const { return i==I; } }; template<int L, int H> struct allvals { typedef FooUnion<typename allvals<L,(H+L)/2>::type, typename allvals<(H+L)/2+1,H>::type> type; }; template<int L> struct allvals<L,L> { typedef FooUnion<isval<L>> type; }; constexpr int N = 257; int main(int argc, char **argv) { typename allvals<1,N>::type x{isval<N/2>{}}; cout << "size = " << sizeof(x) << endl; cout << "size = " << sizeof(uint_least8_t) << endl; cout << "size = " << sizeof(uint_least16_t) << endl; for(int i=1;i<=N;i++) cout << x.foo(i) << (i==N/2 ? '*' : ' '); cout << endl; x = isval<1>{}; for(int i=1;i<=N;i++) cout << x.foo(i) << (i==1 ? '*' : ' '); cout << endl; x = isval<N>{}; for(int i=1;i<=N;i++) cout << x.foo(i) << (i==N ? '*' : ' '); cout << endl; }
#pragma once #include <Arcane/Graphics/Lights/DirectionalLight.h> #include <Arcane/Graphics/Lights/PointLight.h> #include <Arcane/Graphics/Lights/SpotLight.h> namespace Arcane { class Shader; class DynamicLightManager { public: DynamicLightManager(); void BindLightingUniforms(Shader *shader); void BindStaticLightingUniforms(Shader *shader); void AddDirectionalLight(DirectionalLight &directionalLight); void AddPointLight(PointLight &pointLight); void AddSpotLight(SpotLight &spotLight); // Control functions for directional lights void SetDirectionalLightDirection(unsigned int index, const glm::vec3 &dir); // Control functions for point lights void SetPointLightPosition(unsigned int index, const glm::vec3 &pos); // Control functions for spot lights void SetSpotLightPosition(unsigned int index, const glm::vec3 &pos); void SetSpotLightDirection(unsigned int index, const glm::vec3 &dir); // Getters const glm::vec3& GetDirectionalLightDirection(unsigned int index); private: void Init(); std::vector<DirectionalLight> m_DirectionalLights; std::vector<PointLight> m_PointLights; std::vector<SpotLight> m_SpotLights; }; }
vect::vect(){ x = 0.0f; y = 0.0f; z = 0.0f; } vect::vect(float ax, float ay, float az){ x = ax; y = ay; z = az; } vect::vect(const vect& a){ x = a.x; y = a.y; z = a.z; } //operations friend vect vect::operator+(vect a, vect b){ vect r; r.x = a.x + b.x; r.y = a.y + b.y; r.z = a.z + b.z; return r; } friend vect vect::operator-(vect a, vect b){ vect r; r.x = a.x - b.x; r.y = a.y - b.y; r.z = a.z - b.z; return r; } friend vect vect::operator-(vect a){ vect r; r.x = -a.x; r.y = -a.y; r.z = -a.z; return r; } friend void vect::operator+=(vect &a, vect b){ a.x += b.x; a.y += b.y; a.z += b.z; } friend void vect::operator-=(vect &a, vect b){ a.x -= b.x; a.y -= b.y; a.z -= b.z; } friend float vect::operator*(vect a, vect b){ return a.x*b.x + a.y*b.y + a.z*b.z; } friend vect vect::operator*(vect a, float b){ vect r; r.x = a.x*b; r.y = a.y*b; r.z = a.z*b; return r; } friend vect vect::operator*(float b, vect a){ vect r; r.x = a.x*b; r.y = a.y*b; r.z = a.z*b; return r; } friend vect vect::operator^(vect a, vect b){ vect r; r.x = a.y*b.z-b.y*a.z; r.y = a.z*b.x-b.z*a.x; r.z = a.x*b.y-b.x*a.y; return r; } friend vect vect::operator/(vect a, float b){ vect r; r.x = a.x/b; r.y = a.y/b; r.z = a.z/b; return r; } void vect::set(float ax, float ay, float az){ x = ax; y = ay; z = az; } void vect::add(float ax, float ay, float az){ x += ax; y += ay; z += az; } void vect::add(vect p){ x += p.x; y += p.y; z += p.z; } void vect::nul(){ x = 0.0f; y = 0.0f; z = 0.0f; } //(c)heroin
#include <bits/stdc++.h> using namespace std; int main() { int N; cin >> N; getchar(); while (N--) { vector<char> abertura; char c; bool ok = true; while (scanf("%c", &c), c != '\n') { if (c == '(' || c == '[' || c == '{') abertura.push_back(c); else if (c == ')' || c == ']' || c == '}') { if (!abertura.empty()) { if (abertura.back() == '(' && c == ')') abertura.pop_back(); else if (abertura.back() == '[' && c == ']') abertura.pop_back(); else if (abertura.back() == '{' && c == '}') abertura.pop_back(); else ok = false; } else ok = false; } } if (ok && abertura.empty()) cout << "Compilou" << endl; else cout << "Erro de compilacao" << endl; } return 0; }
#ifndef SSPEDITOR_LIGHTCONTROLLER_H #define SSPEDITOR_LIGHTCONTROLLER_H #include "Header.h" #include "GlobalIDHandler.h" class LightController { public: ~LightController(); void Initialize(); static LightController * GetInstance(); std::vector<Light*> * GetLights() { return &m_lights; }; std::vector<LIGHTING::Point>* GetPointLightData() { return &pointLightData; }; void synchData(LIGHTING::LIGHT_TYPE type); void AddLight(LIGHTING::LIGHT_TYPE type); void AddLight(Light* light, LIGHTING::Light * data, LIGHTING::LIGHT_TYPE type); void AddLight(LIGHTING::Point* light); void UpdateLights(LIGHTING::LIGHT_TYPE type); void UpdateShadows(); void RemoveLight(int index, LIGHTING::LIGHT_TYPE type); void SetAmbientR(float r); void SetAmbientG(float g); void SetAmbientB(float b); void SetAmbientIntensity(float intensity); void SetLevelAmbient(Ambient ambient); void SetGraphicsHandler(GraphicsHandler* gh) { this->gh = gh; }; const Ambient * GetLevelAmbient() { return &this->m_levelAmbience; }; void DisplayLightRadius(bool display); bool DisplayLightRadius(); std::vector<int> * GetShadowCasterIndexList(); void MakeShadowCaster(unsigned int internalID); void RemoveShadowCaster(unsigned int internalID); bool GetIsShadowCaster(unsigned int internalID); void Destroy(); private: void m_updateAmbient(); LightController(); Ambient m_levelAmbience = Ambient(); std::vector<Light*> m_lights; std::vector<LIGHTING::Point> pointLightData; std::vector<int> shadowCasterIndexes; bool m_displayLightRadius; GraphicsHandler* gh = nullptr; }; #endif
/*************************************************************************** Copyright (c) 1999-2003 Apple Computer, Inc. All Rights Reserved. 2010-2020 DADI ORISTAR TECHNOLOGY DEVELOPMENT(BEIJING)CO.,LTD FileName: QTSSStream.h Description: Abstract base class QTSSStream containing the prototypes for generalized stream functions. Any server object that wants to act as a QTSS_StreamRef should derive off of this and implement one or more of the stream APIs. Comment: copy from Darwin Streaming Server 5.5.5 Author: taoyunxing@dadimedia.com Version: v1.0.0.1 CreateDate: 2010-08-16 LastUpdate: 2010-08-16 ****************************************************************************/ #ifndef __QTSS_STREAM_H__ #define __QTSS_STREAM_H__ #include "QTSS.h" #include "Task.h" class QTSSStream { public: //constrcutor/destructor QTSSStream() : fTask(NULL) {} virtual ~QTSSStream() {} // // A stream can have a task associated with it. If this stream supports // async I/O, the task is needed to know what to wakeup when there is an event void SetTask(Task* inTask) { fTask = inTask; } Task* GetTask() { return fTask; } // declarations of stream callback routines, explicit code definitions see QTSSDictionary.cpp /* 参见QTSS API Doc */ virtual QTSS_Error Read(void* /*ioBuffer*/, UInt32 /*inLen*/, UInt32* /*outLen*/) { return QTSS_Unimplemented; } virtual QTSS_Error Write(void* /*inBuffer*/, UInt32 /*inLen*/, UInt32* /*outLenWritten*/, UInt32 /*inFlags*/) { return QTSS_Unimplemented; } virtual QTSS_Error WriteV(iovec* /*inVec*/, UInt32 /*inNumVectors*/, UInt32 /*inTotalLength*/, UInt32* /*outLenWritten*/) { return QTSS_Unimplemented; } virtual QTSS_Error Flush() { return QTSS_Unimplemented; } virtual QTSS_Error Seek(UInt64 /*inNewPosition*/) { return QTSS_Unimplemented; } virtual QTSS_Error Advise(UInt64 /*inPosition*/, UInt32 /*inAdviseSize*/) { return QTSS_Unimplemented; } /* 注册事件:可读/可写 */ virtual QTSS_Error RequestEvent(QTSS_EventType /*inEventMask*/) { return QTSS_Unimplemented; } private: Task* fTask; }; #endif //__QTSS_STREAM_H__
#ifndef __HELLOWORLD_SCENE_H__ #define __HELLOWORLD_SCENE_H__ #include "cocos2d.h" #include "cocos-ext.h" #include "SimpleAudioEngine.h" //#include <CCScrollView/CCScrollView.h> #include "Macro.h" #include "GameSprite.h" #include "GameHero.h" class GameAnimtion; class GameSprite; class TemplateScene; using namespace cocos2d::gui; class GameBattleLayer : public cocos2d::CCLayer { public: enum EBattleLayerdActionTag { EHelloWorldActionTag_FollowHero = 1, //跟随主角动作 }; GameBattleLayer(); ~GameBattleLayer(); virtual bool init(); CREATE_FUNC(GameBattleLayer); public: void scrollViewDidScroll(cocos2d::extension::CCScrollView * view); void scrollViewDidZoom(cocos2d::extension::CCScrollView * view); void onEnter(); virtual bool ccTouchBegan(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); virtual void ccTouchMoved(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); virtual void ccTouchEnded(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); virtual void ccTouchCancelled(cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent); void update(float dt); void playerAddSprite(int32t nArmSN); //技能生效,返回受攻击的精灵 vector<GameSprite*> onSkillEffect(GameSprite* pSprite, GameSkill* pSkill); //根据技能选择目标 GameSprite* selectAim(GameSprite* pSprite, GameSkill* pSkill); virtual void onExit(); public: CC_SYNTHESIZE_RETAIN(cocos2d::CCArray*, m_aEnemies, Enemies); //敌方 CC_SYNTHESIZE_RETAIN(cocos2d::CCArray*, m_aArms, Arms); //己方 CC_SYNTHESIZE_RETAIN(GameHero*, m_pHero, Hero); //英雄 public: void loadWave(); //加载一波敌对精灵 //加载核心建筑 bool loadCoreArm(ESpriteCamp eCamp, ESpriteDir eDir); //加载英雄 bool loadHero(int nSN); void onSpriteDead(GameSprite* sprite); int32t getCurrentRes() const {return m_nRes;} void incRes(float dt); // a selector callback void menuArmCallback(CCObject* pSender); void menuBuildingCallback(CCObject* pSender); private: //创建一个精灵 GameSprite* createSprite(int32t nSN, ESpriteCamp eCamp, ESpriteDir eDir, float activeTime); void changeResNum(int32t nRes); void changeMoneyNum(int32t nMoeny); void changeEneryNum(int32t nEnery); void giveDrop(int32t nArmSN); //给掉落 void onCompleteScene(ESpriteCamp eCamp, int32t nSpriteSN); private: int32t m_nRes; //当前资源数量 cocos2d::CCPoint m_ptTouch; }; #endif // __HELLOWORLD_SCENE_H__
#include<iostream> using namespace std; int main() { int i=10; try { int a=0; if(a==0) throw "division error"; i = i/a; } catch(string s) { cout << s << endl; } catch(...) { cout << "exception error" << endl; } cout << "end" << endl; return 0; }
#include <bits/stdc++.h> using namespace std; const int epsilon = 256;//空的定义 const int Accepting = 257;//结尾定义,即可接受状态的位置 const int bel = 258;//在minDFA过程中标记属于哪个集合 class NFA { public: vector<int> nf[305][260]; int NfaId; NFA() { memset(nf, -1, sizeof nf); NfaId = 2; } void link(int s, int ch, int t, int id) {//起始状态是s,当前字符为ch,下一个状态为t,id是为了标记改状态是哪个可接受状态 if(ch>=300) ch-=300;//将字符还原回ascill nf[s][ch].push_back(t); if (ch == epsilon && t == 1) nf[s][Accepting].push_back(id); } void strToNFA(string s, int id) { stack<int> s_st; stack<int> s_ed; stack<int> s_str; s_str.push('$'); s_st.push(0); s_ed.push(1); for (int i = 0; i < (int)s.size(); ++i) { int ch = s[i]; // cout << i << ' ' << ch << endl; if (ch == '\\') { ch = s[++i]; //转义字符 // cout<<ch<<endl; s_str.push(ch+300);//为了转义字符 s_st.push(NfaId++); } else if (ch == '(') {//左括号,创建新的id并入栈 s_ed.push(NfaId++); s_str.push('('); } else if (ch == ')') {//右括号,取出到左括号之间的所有字符和两个栈顶进行连接 int ed = s_ed.top(); int st = s_st.top(); link(st, epsilon, ed, id); ch = s_str.top(); while (ch != '(') { int nxt = s_st.top(); s_st.pop(); int pre = s_st.top(); if (ch != '#') link(pre, ch, nxt, id); // nf[pre][(int)ch]=nxt; s_str.pop(); ch = s_str.top(); } s_str.pop(); s_str.push('#');//为了解决括号嵌套,‘#’相当于push了括号的内容 s_st.push(s_ed.top()); s_ed.pop(); } else if (ch == '|') {//或将前面所有的连接连起来,连接在外层的st和ed上 int ed = s_ed.top(); int st = s_st.top(); // nf[st][epsilon]=ed; link(st, epsilon, ed, id); ch = s_str.top(); while (ch != '(' && ch != '$') { int nxt = s_st.top(); s_st.pop(); int pre = s_st.top(); if (ch != '#') link(pre, ch, nxt, id); // nf[pre][(int)ch]=nxt; s_str.pop(); ch = s_str.top(); } } else if (ch == '*') { //闭包运算,把外层(st和ed栈顶)的起点和终点用epsilon连接起来。 int nxt = s_st.top(); s_st.pop(); int pre = s_st.top(); link(pre, epsilon, nxt, id); link(nxt, epsilon, pre, id); // nf[pre][epsilon]=nxt; // nf[nxt][epsilon]=pre; s_st.push(nxt); } else { s_str.push(ch); s_st.push(NfaId++); } } int ch = s_str.top(); if (ch != '$') link(s_st.top(), epsilon, 1, id); while (ch != '$')//清空栈,防止出现没有比连接更低级优先级的符号出现。 { int nxt = s_st.top(); s_st.pop(); int pre = s_st.top(); if (ch != '#') link(pre, ch, nxt, id); // nf[pre][(int)ch] = nxt; s_str.pop(); ch = s_str.top(); } } void outputNFA() { cout << NfaId << endl; for (int i = 0; i < NfaId; i++) { for (int j = 0; j < 256; j++) { if (nf[i][j].size()) { for (auto x : nf[i][j]) cout << i << ' ' << char(j) << ' ' << x << endl; } } if (nf[i][256].size()) { for (auto x : nf[i][epsilon]) cout << i << ' ' << "epsilon" << ' ' << x << endl; } if (nf[i][257].size()) { for (auto x : nf[i][Accepting]) cout << i << " Accepting " << x << endl; } } } //DFA int df[305][260], DfaId; vector<int> epsilonClosure(vector<int> pre, int a) {//求一个集合经过a的epsilon闭包 vector <int> nxt; for (auto x : pre) { //把pre里的每个元素经过a的集合求出来 if (nf[x][a].size()) for (auto y : nf[x][a]) nxt.push_back(y); } sort(nxt.begin(), nxt.end()), nxt.erase(unique(nxt.begin(), nxt.end()), nxt.end()); //求nxt数组每个元素的epsilon闭包 set <int> st; queue <int> que; for (auto x : nxt) { st.insert(x); que.push(x); } while (!que.empty()) { int now = que.front(); que.pop(); for (auto x : nf[now][epsilon]) if (!st.count(x)) { st.insert(x); que.push(x); } } nxt.clear(); for (auto it = st.begin(); it != st.end(); it++) nxt.push_back(*it); return nxt; } void toDFA() { DfaId = 0; memset(df, -1, sizeof df); map <vector<int>, int> dfmp; //保存出现过的状态集 queue <vector<int>> q;//队列保证集合按出现顺序加入DFA中 vector <int> start{0};//构造开始状态集 for (auto x : nf[0][epsilon]) start.push_back(x); dfmp[start] = DfaId++; //加入开始状态集 q.push(start); while (!q.empty()) { vector <int> now = q.front(); q.pop(); int nowID = dfmp[now], AC = 0x3f3f3f3f; for (auto x : now) { if (nf[x][Accepting].size()) { AC = min(AC, nf[x][Accepting][0]); //为了保证保留字优先,取较小的Accpting(先输入的保留字,保留字id比较小,别的不会冲突) } } if (AC != 0x3f3f3f3f) df[nowID][Accepting] = AC;//更新过是有可接受状态的 for (int i = 0; i < 256; i++) { vector <int> tmp = epsilonClosure(now, i); if (tmp.size()) { // cout<<"i="<<char(i)<<endl; // for(auto x:tmp) // cout<<x<<' '; // cout<<endl; if (!dfmp.count(tmp)) { //未存在过的节点 dfmp[tmp] = DfaId++; q.push(tmp); } df[nowID][i] = dfmp[tmp]; } } } } void outputDFA() { // cout<<"DFAMap"<<endl; cout << DfaId << endl; for (int i = 0; i < DfaId; i++) { for (int j = 0; j < 256; j++) { if (df[i][j] != -1) { cout << i << ' ' << char(j) << ' ' << df[i][j] << endl; } } if (df[i][256] != -1) { cout << i << ' ' << "epsilon" << ' ' << df[i][256] << endl; } if (df[i][257] != -1) { cout << i << ' ' << "Accepting" << ' ' << df[i][257] << endl; } } } //minDFA int mdf[305][260], mDfaId; bool equalBel(int x, int y) { bool f = 1; for (int i = 0; i <= 256; i++) { if (df[x][i] != df[y][i]) { if (df[x][i] == -1 || df[y][i] == -1) f = 0; if (df[df[x][i]][bel] != df[df[y][i]][bel]) f = 0; } } if (df[x][Accepting] != df[y][Accepting]) f=0; return f; } void minDFA() { mDfaId = 1; memset(mdf, -1, sizeof mdf); for (int i = 0; i < DfaId; i++) { df[i][bel] = df[i][Accepting] + 1; if(mDfaId<=df[i][bel]) mDfaId=df[i][bel]+1; } bool f = true; while (f) { //f==fasle时,说明上次没有集合被分开 f = false; vector <int> vec[305]; for (int i = 0; i < DfaId; i++) { //将所有节点分类 vec[df[i][bel]].push_back(i); } for (int i = 0; i < mDfaId; i++) { //对每个节点集合尝试拆分 if (vec[i].size() == 1) //该集合只有一个节点,不再尝试拆分 continue; int newId = -1; for (int j = 1; j < (int)vec[i].size(); j++) { if (!equalBel(vec[i][0], vec[i][j])) { //不相等则分类 if (newId == -1) newId = mDfaId++; df[vec[i][j]][bel] = newId; vec[newId].push_back(vec[i][j]); } } if (newId != -1) f = true; } } vector <int> vec[305]; for (int i = 0; i < DfaId; i++) //将所有节点分类 vec[df[i][bel]].push_back(i); for (int i = 0; i < mDfaId; i++) { for (int j = 0; j < 257 ; j++){ int x=df[vec[i][0]][j]; if(x!=-1) mdf[i][j]=df[x][bel]; } mdf[i][Accepting]=df[vec[i][0]][Accepting]; } } void outputMinDFA() { cout << mDfaId << endl; for (int i = 0; i < mDfaId; i++) { for (int j = 0; j <= 257; j++) { if (mdf[i][j] != -1) { cout << i << ' ' << j << ' ' << mdf[i][j] << endl; } } } cout<<-1<<endl; } int analysis(string s){ int now=0; for(int i=0;i<(int)s.size();i++){ if(mdf[now][(int)s[i]]!=-1) now=mdf[now][(int)s[i]]; else return -1; } return mdf[now][Accepting]; } }; class TokenType { public: vector<string> Type; void addstr(string &s, int &id) { string tmp, new_s; int i = 0; while (s[i] != '=')tmp += s[i++]; Type.push_back(tmp); id = Type.size() - 1; for (i++; i < (int)s.size(); i++) { if (s[i] == '\\') new_s += s[i++], new_s += s[i]; else if (s[i] == '[') { for (int j = s[i + 1]; j < s[i + 3]; j++) new_s += j, new_s += '|'; new_s += s[i + 3]; i += 4; } else new_s += s[i]; } s = new_s; } void output() { cout << Type.size() << endl; for (int i = 0; i < (int)Type.size(); ++i) { cout << i << ' ' << Type[i] << endl; } } }; int main() { freopen("regular2minDFA-input.txt", "r", stdin); freopen("analysis-dfaMap-input.txt", "w", stdout); string str; NFA nfa; TokenType token; while (cin >> str) { // int n; // cin>>n; // while(n--){ // cin>>str; int id; token.addstr(str, id); nfa.strToNFA(str, id); } token.output(); // nfa.outputNFA(); nfa.toDFA(); // cout<<"DFAOk"<<endl; // nfa.outputDFA(); nfa.minDFA(); // cout<<"mDFAOk"<<endl; nfa.outputMinDFA(); return 0; }
class Solution { void DFSTraversal(unordered_map<string, multiset<string>> &table, string curr, vector<string> &result) { while(!table[curr].empty()) { string next = *table[curr].begin(); table[curr].erase(table[curr].begin()); DFSTraversal(table, next, result); } result.push_back(curr); } public: vector<string> findItinerary(vector<pair<string, string>> tickets) { unordered_map<string, multiset<string>> table; for (int i = 0; i < tickets.size(); i++) { table[tickets[i].first].insert(tickets[i].second); } vector<string> result; DFSTraversal(table, "JFK", result); reverse(result.begin(), result.end()); return result; } };
#include "Circular_SLList.h" template <typename T> Circular_SLList<T>::Node::Node(T data) { this->data = data; this->next = NULL; } //Constructor template <typename T> Circular_SLList<T>::Circular_SLList() { last = NULL; count = 0; } template <typename T> Circular_SLList<T>::Circular_SLList(initializer_list<T> l) { count = l.size(); auto it = l.begin(); last = new Node(*it); last->next = last; it++; while (it != l.end()) { Node *newNode = new Node(*it); newNode->next = last->next; last->next = newNode; last = last->next; it++; } } template <typename T> Circular_SLList<T>::Circular_SLList(const Circular_SLList<T> &csl) { if (csl.count != 0) { count = csl.count; Node *cur = csl.last->next; last = new Node(cur->data); last->next = last; cur = cur->next; while (cur != csl.last->next) { Node *newNode = new Node(cur->data); newNode->next = last->next; last->next = newNode; last = last->next; cur = cur->next; } } else { count = 0; last = NULL; } } //Destructor template <typename T> Circular_SLList<T>::~Circular_SLList() { if (last == NULL) return; while (last != last->next) { Node *temp = last->next; last->next = temp->next; delete temp; } delete last; last = NULL; count = 0; } //Assign operator template <typename T> const Circular_SLList<T> &Circular_SLList<T>::operator=(const Circular_SLList<T> &csl) { count = csl.count; Node *cur = csl.last->next; last = new Node(cur->data); last->next = last; cur = cur->next; while (cur != csl.last->next) { Node *newNode = new Node(cur->data); newNode->next = last->next; last->next = newNode; last = last->next; cur = cur->next; } return csl; } //Capacity template <typename T> int Circular_SLList<T>::size() { return count; } template <typename T> bool Circular_SLList<T>::empty() { return count == 0; } //Element access template <typename T> T &Circular_SLList<T>::at(int pos) { if (pos < 0 || pos >= count) throw out_of_range("Index is out of bound"); else { if (pos == count - 1) return last->data; Node *cur = last->next; for (int i = 0; i < pos; i++) { cur = cur->next; } return cur->data; } } template <typename T> T &Circular_SLList<T>::front() { if (last == NULL) throw out_of_range("List is empty"); return last->next->data; } template <typename T> T &Circular_SLList<T>::back() { if (last == NULL) throw out_of_range("List is empty"); return last->data; } //Modifiers template <typename T> bool Circular_SLList<T>::insert(int pos, const T &data) { if (pos < 0 || pos > count) return false; Node *newNode = new Node(data); if (last == NULL) { last = newNode; last->next = last; } else if (pos == count) { newNode->next = last->next; last->next = newNode; last = last->next; } else { Node *cur = last; for (int i = 0; i < pos; i++) { cur = cur->next; } newNode->next = cur->next; cur->next = newNode; } count++; return true; } template <typename T> bool Circular_SLList<T>::erase(int pos) { if (pos < 0 || pos >= count) return false; if (count == 1) { delete last; last = NULL; } else if (pos == count - 1) { Node *cur = last->next; while (cur->next != last) { cur = cur->next; } cur->next = last->next; delete last; last = cur; } else { Node *cur = last; for (int i = 0; i < pos; i++) { cur = cur->next; } Node *temp = cur->next; cur->next = temp->next; delete temp; } count--; return true; } template <typename T> void Circular_SLList<T>::clear() { if (last == NULL) return; while (last != last->next) { Node *temp = last->next; last->next = temp->next; delete temp; } delete last; last = NULL; count = 0; } //Operations template <typename T> bool Circular_SLList<T>::remove(const T &item) { if (last == NULL) return false; if (last->data == item) { if (count == 1) { delete last; last == NULL; } else { Node *cur = last->next; while (cur->next != last) { cur = cur->next; } cur->next = last->next; delete last; last = cur; } count--; return true; } else { Node *cur = last; while (cur->next != last) { if (cur->next->data == item) { Node *temp = cur->next; cur->next = temp->next; delete temp; count--; return true; } else cur = cur->next; } } return false; } template <typename T> void Circular_SLList<T>::reverse() { if (count > 1) { Node *prev = last; Node *cur = last->next; while (cur != last) { Node *temp = cur; cur = cur->next; temp->next = prev; prev = temp; } last = last->next; cur->next = prev; } } template <typename T> void Circular_SLList<T>::display() { if (last == NULL) cout << "List is empty" << endl; else { Node *cur = last->next; do { cout << cur->data << "->"; cur = cur->next; } while (cur != last->next); cout << "HEAD" << endl; } }
#include <RCSwitch.h> RCSwitch mySwitch = RCSwitch(); int hozdead= VALUE ; int verdead= VALUE ; int pos = 0; int oldpos=100; int val = 0; int val2 = 0; void setup() { Serial.begin(9600); mySwitch.enableTransmit(10); } void loop() { //Read JoyStick val = analogRead(0); val2 = analogRead(1); Serial.println(val); Serial.println(val2); //UP 1 if (val> verdead+30){ //move both motors forward } //DOWN 2 if (val< verdead-30){ //move both motors backwards } //RIGHT 3 if (val2> hozdead+30){pos=4; Serial.println(pos);} //LEFT 4 if (val2< hozdead-30){pos=3; Serial.println(pos);} //DEAD ZONE 5 if (val>verdead-20 && val< verdead+20 && val2>hozdead-20 && val2< hozdead+20) { pos=5; Serial.println(pos); } mySwitch.send(pos, 23); }
#ifndef HTTP_UTILS_H #define HTTP_UTILS_H #include <httpserver.hpp> #include <megaapi.h> httpserver::http_response *make_msg_response(const std::string &msg, int status_code); // str_iter not used anywhere else using str_iter = std::vector<std::string>::const_iterator; std::string path_to_string(str_iter beg, str_iter end); #endif // HTTP_UTILS_H
//二分法求根号2的近似值,利用函数f(x)=x^2 #include<stdio.h> const double eps=1e-5; //设置精度为10^-5 double function(double x); double calSqrt(double left,double right); int main() { printf("%f",calSqrt(1,2)); return 0; } double function(double x) { return x*x; } double calSqrt(double left,double right) { double mid; //区间中点 while(right-left>eps) //比eps小意味着达到了精度,注意循环的大于号 { mid=left+(right-left)/2;//求区间中点 if(function(mid)>2) //中点值大于根号2 right=mid; //在[left,mid]区间里面找 else left=mid; //在[mid,right]区间继续逼近 } return mid; //夹出来的值即为根号2的接近值 }
//Not a competition Problem just a challenge to an easier problem with harder contraints #include <bits/stdc++.h> using namespace std; vector<long long int> a; long long int conInt(string); void rec(string, int); int main() { rec("", 1); sort(a.begin(), a.end()); //for(int i=0; i<a.size(); i++) cout<<a[i]<<endl; long long int n; cin>>n; bool f = 0; for(int i=0; i<a.size() && a[i]<=n; i++) { if(n%a[i]==0) { f = 1; cout<<a[i]<<endl; break; } } if(f) cout<<"YES"<<endl; else cout<<"NO"<<endl; } void rec(string s, int l) { string c1 = s, c2 = s; c1 += '4'; c2 += '7'; a.push_back(conInt(c1)); a.push_back(conInt(c2)); if(l==18) return; rec(c1, l+1); rec(c2, l+1); } long long int conInt(string s) { long long int ret = 0; for(int i=0; i<s.length(); i++) { ret += (s[i]-'0')*(pow(10, s.length()-i-1)); } return ret; }
/************************************************************* Author : qmeng MailTo : qmeng1128@163.com QQ : 1163306125 Blog : http://blog.csdn.net/Mq_Go/ Create : 2018-03-29 19:57:11 Version: 1.0 **************************************************************/ #include <cstdio> #include <iostream> using namespace std; int main(){ cout << "Hello World\nHello New World"; return 0; }
/// /// @file list_kmers_found_in_multiple_samples.cpp /// @brief Go over a list of k-mer DBs and output only k-mers appearing in at least /// N (defined by user) DBs. Then outputing the k-mers in a binary format. /// // Read all the sorted kmers files and collect statistics on them: // 1. In how many accessions they were found // 2. In how many they apeard in canonized/non-canonized form or both // // Output the general statistics on how many times they were found in // which form. // // Filter kmers to the ones apearing at least N times and found in // every form at least in some defined percent. // // For example: a kmer K will pass the threshold if it: // 1. Found in at least 5 acessions // 2. Found at least 20% of the time in every form // * So if it apeared in 100 accessions, we should 20 accessions // with each form. // /// @author Yoav Voichek (YV), yoav.voichek@tuebingen.mpg.de /// /// Created 08/14/18 /// Compiler gcc/g++ /// Company Max Planck Institute for Developmental Biology Dep 6 /// Copyright Copyright (c) 2018, Yoav Voichek /// /// This source code is released for free distribution under the terms of the /// GNU General Public License as published by the Free Software Foundation. ///===================================================================================== /// #include "kmer_general.h" #include "kmers_single_database.h" #include <cmath> using namespace std; void output_uint64_t_matrix(const string& fn, const vector<vector<uint64_t> >& M) { ofstream fout(fn); for(size_t i=0; i<M.size(); i++) { for(size_t j=0; j<M[i].size(); j++) { if(j>0) fout << "\t"; fout << M[i][j]; } fout << endl; } fout.close(); } int main(int argc, char *argv[]) { /* Read user input */ if(argc != 7) { cerr << "usage: " << argv[0] << " <1 file with paths to kmers files> <2 output file> <3 minimum k-mer counts> <4 kmer len> <5 hash table initial size> <6 minimum strand percent>" << endl; return -1; } // Read accessions to use vector<AccessionPath> sorted_kmers_fn = read_accessions_path_list(argv[1]); vector<KmersSingleDataBaseSortedFile> list_handles; // Open all kmers files size_t N = sorted_kmers_fn.size(); for(size_t i=0; i<N; i++) list_handles.emplace_back(sorted_kmers_fn[i].path); // Read filtering parameters size_t minimum_kmer_count = atoi(argv[3]); double minimum_strand_per = atof(argv[6]); size_t kmer_len = atoi(argv[4]); // Build the hash table that will contain all the kmers counts KmerUint64Hash kmers_hash(atoi(argv[5])); // Initial hash_table_size from user kmers_hash.set_empty_key(NULL_KEY); // Defining variables to use while going over the k-mers vector<uint64_t> kmers, flags, unique_kmers; KmerUint64Hash::iterator it_hash; // statistics collection vector<uint64_t> shareness(N+1, 0); vector<vector<uint64_t> > only_canonical(N+1,vector<uint64_t>(N+1,0)); vector<vector<uint64_t> > only_non_canonical(N+1,vector<uint64_t>(N+1,0)); vector<vector<uint64_t> > both_forms(N+1,vector<uint64_t>(N+1,0)); // We want to keep track for each kmer if it apeared in canonical/non-canonical or both // as the counters have 64 bits and we assume we will have less than 1,000,000 individuals // we can put 3 counters in the same word. The following array define the constant to add. uint64_t adders[] = {1ull+(1ull<<20ull), 1ull+(1ull<<40ull), 1ull+0ull}; // Output files: ofstream file_out_kmers(argv[2], ios::binary); // kmers passing filters ofstream file_non_pass_kmers(string(argv[2]) + ".no_pass_kmers"); // kmers not passing filters file_non_pass_kmers << "kmer\tcount_all\tcanonical\tnon-canonical\tboth" << endl; uint64_t STEPS = 5000; uint64_t cnt_no_pass(0), cnt_pass(0), cnt_low_MAC; for(uint64_t step_i=1; step_i<=(STEPS+1); step_i++) { // the +1 in STEPS is for debugging kmers_hash.clear(); // Empty the hash table unique_kmers.resize(0); // Empty unique kmers collection // Set threshold until which kmer to read uint64_t current_threshold = ((((1ull << (kmer_len*2ull))-1ull) / STEPS)+1) * step_i; cerr << step_i << " / " << STEPS << "\t:\t" << bitset<WLEN>(current_threshold); // Go over all the kmers and collect information for(size_t i=0; i<N; i++) { //over individuals list_handles[i].load_kmers_upto_x(current_threshold, kmers, flags); // read kmers & flags for(size_t kmer_i=0; kmer_i < kmers.size(); kmer_i++) { uint64_t cur_adder = adders[flags[kmer_i]-1]; // Flag should never be zero! it_hash = kmers_hash.find(kmers[kmer_i]); if(it_hash == kmers_hash.end()) { // new kmer kmers_hash.insert(KmerUint64Hash::value_type(kmers[kmer_i], cur_adder)); unique_kmers.push_back(kmers[kmer_i]); } else it_hash->second += cur_adder; } } cerr << "\tunique kmers: " << unique_kmers.size() << endl; sort(unique_kmers.begin(), unique_kmers.end()); // Sort so the end list will also be sorted // output kmers that pass threshold and collect statistics for(size_t i=0; i<unique_kmers.size(); i++) { it_hash = kmers_hash.find(unique_kmers[i]); // kmers from unique_kmers have to be in hash uint64_t counts = it_hash->second; uint64_t count_all = counts & 0x00000000000FFFFF; uint64_t count_canon = (counts >> 20) & 0x00000000000FFFFF; uint64_t count_non_canon = (counts >> 40) & 0x00000000000FFFFF; uint64_t count_both = count_all - count_canon - count_non_canon; // Update general statistics only_canonical[count_all][count_canon]++; only_non_canonical[count_all][count_non_canon]++; both_forms[count_all][count_both]++; // Filter or not? if(count_all>=minimum_kmer_count) { // pass MAC if ((static_cast<double>(count_canon + count_both) >= ceil(minimum_strand_per * static_cast<double>(count_all))) && (static_cast<double>(count_non_canon + count_both) >= ceil(minimum_strand_per * static_cast<double>(count_all)))) { file_out_kmers.write(reinterpret_cast<const char *>(&unique_kmers[i]), sizeof(unique_kmers[i])); cnt_pass++; shareness[count_all]++; // This statistics only for the used k-mers } else { file_non_pass_kmers << bits2kmer31(unique_kmers[i], kmer_len) << "\t" << count_all << "\t" << count_canon << "\t" << count_non_canon << "\t" << count_both << endl; cnt_no_pass++; } } } } cerr << "kmers lower than MAC:\t" << cnt_low_MAC << endl; cerr << "Pass kmers:\t" << cnt_pass << endl; cerr << "pass MAC bot not pass strand filter:\t" << cnt_no_pass << endl; file_out_kmers.close(); file_non_pass_kmers.close(); /* Output shareness measures */ ofstream file_shareness(string(argv[2]) + ".shareness"); file_shareness << "kmer appearance\tcount" << endl; for(size_t i=0; i<shareness.size(); i++) file_shareness << i << "\t" << shareness[i] << endl; file_shareness.close(); output_uint64_t_matrix(string(argv[2]) + ".stats.only_canonical", only_canonical); output_uint64_t_matrix(string(argv[2]) + ".stats.only_non_canonical", only_non_canonical); output_uint64_t_matrix(string(argv[2]) + ".stats.both", both_forms); return 0; }
/**************************************** * * INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE * Copyright (C) 2019 Victor Tran * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * *************************************/ #include "buttondiagnostics.h" #include "ui_buttondiagnostics.h" #include "pauseoverlay.h" #include <QGamepadManager> #include "gamepadevent.h" #include "gamepadbuttons.h" #include <QQueue> #include <QGamepad> #include "musicengine.h" #include <QTimer> #include "questionoverlay.h" struct ButtonDiagnosticsPrivate { QGamepad gamepad; QQueue<QGamepadManager::GamepadButton> pressedOrder; QTimer* timer; QGamepadManager::GamepadButton timerButton; }; ButtonDiagnostics::ButtonDiagnostics(int gamepadId, QWidget *parent) : QWidget(parent), ui(new Ui::ButtonDiagnostics) { ui->setupUi(this); d = new ButtonDiagnosticsPrivate(); d->gamepad.setDeviceId(gamepadId); ui->unavailableButtonsWarning->setText(tr("Depending on your setup, the %1 button may not register here.").arg(GamepadButtons::stringForButton(QGamepadManager::ButtonGuide))); PauseOverlay::overlayForWindow(parent)->pushOverlayWidget(this); connect(&d->gamepad, &QGamepad::connectedChanged, this, [=](bool connected) { if (!connected) { d->gamepad.blockSignals(true); QuestionOverlay* question = new QuestionOverlay(this); question->setIcon(QMessageBox::Critical); question->setTitle(tr("Gamepad Disconnected")); question->setText(tr("The gamepad that you were testing was disconnected.")); question->setButtons(QMessageBox::Ok); auto after = [=] { question->deleteLater(); quit(); }; connect(question, &QuestionOverlay::accepted, this, after); connect(question, &QuestionOverlay::rejected, this, after); } }); d->timer = new QTimer(this); d->timer->setSingleShot(true); d->timer->setInterval(1000); connect(d->timer, &QTimer::timeout, this, [=] { this->quit(); }); } ButtonDiagnostics::~ButtonDiagnostics() { delete ui; delete d; } void ButtonDiagnostics::quit() { d->gamepad.blockSignals(true); PauseOverlay::overlayForWindow(this)->popOverlayWidget([=] { emit done(); }); } void ButtonDiagnostics::on_finishButton_clicked() { this->quit(); } bool ButtonDiagnostics::event(QEvent*event) { if (event->type() == GamepadEvent::type()) { GamepadEvent* e = static_cast<GamepadEvent*>(event); if (e->gamepad()->deviceId() == d->gamepad.deviceId() && e->isButtonEvent()) { if (e->buttonPressed()) { d->pressedOrder.enqueue(e->button()); if (d->pressedOrder.count() > 8) d->pressedOrder.dequeue(); updateLabel(); MusicEngine::playSoundEffect(MusicEngine::FocusChanged); d->timerButton = e->button(); d->timer->start(); } else { if (d->timerButton == e->button()) d->timer->stop(); } } e->accept(); return true; } return false; } void ButtonDiagnostics::updateLabel() { QStringList buttons; for (QGamepadManager::GamepadButton button : d->pressedOrder) { buttons.append(GamepadButtons::stringForButton(button)); } ui->buttonsLabel->setText(buttons.join(" ")); }
#include "gui.h" const int width_slider_max = 100; int width_slider; double width_ratio; const int height_slider_max = 100; int height_slider; double height_ratio; /// Matrices to store images Mat src; Mat dst; void on_trackbar_width(int, void*) { if (width_slider == 0){ width_slider = 1; } width_ratio = (double)(width_slider) / width_slider_max; // Refaire en fonction des nouveaux parametres de resize_seam_carv_random (Size) : // resize_seam_carv_random(src, width_ratio, height_ratio,20); imshow("Seam carving", src); } void on_trackbar_height(int, void*) { if (height_slider == 0){ height_slider = 1; } height_ratio = (double)(height_slider) / height_slider_max; // Refaire en fonction des nouveaux parametres de resize_seam_carv_random (Size) : // resize_seam_carv_random(src, width_ratio, height_ratio,20); imshow("Seam carving", src); } void init_gui(){ //src = imread("Broadway_tower_edit.jpg"); ////dst = imread("Broadway_tower_edit.jpg"); ///// Create Windows //namedWindow("Seam carving", 1); //width_slider = 100; //height_slider = 100; //width_ratio = 1; //height_ratio = 1; ///// Create Trackbars //char WidthTrackbarName[50]; //sprintf(WidthTrackbarName, "Width : %d", width_slider_max); //char HeightTrackbarName[50]; //sprintf(HeightTrackbarName, "Height : %d", height_slider_max); //createTrackbar(WidthTrackbarName, "Seam carving", &width_slider, width_slider_max, on_trackbar_width); //createTrackbar(HeightTrackbarName, "Seam carving", &height_slider, height_slider_max, on_trackbar_height); ///// Show some stuff //on_trackbar_width(width_slider, 0); //on_trackbar_height(height_slider, 0); //waitKey(0); }
#ifndef FASTCG_DEBUG_MENU_SYSTEM_H #define FASTCG_DEBUG_MENU_SYSTEM_H #ifdef _DEBUG #include <FastCG/Core/System.h> #include <unordered_map> #include <string> #include <functional> #include <cstdint> #include <cassert> namespace FastCG { struct DebugMenuSystemArgs { }; using DebugMenuItemCallback = std::function<void(int &)>; using DebugMenuCallback = std::function<void(int)>; class DebugMenuSystem { FASTCG_DECLARE_SYSTEM(DebugMenuSystem, DebugMenuSystemArgs); public: inline void AddCallback(const std::string &rName, const DebugMenuCallback &rCallback) { mCallbacks.emplace(std::hash<std::string>()(rName), rCallback); } inline void RemoveCallback(const std::string &rName) { auto it = mCallbacks.find(std::hash<std::string>()(rName)); assert(it != mCallbacks.end()); mCallbacks.erase(it); } inline void AddItem(const std::string &rName, const DebugMenuItemCallback &rItemCallback) { mItems.emplace(std::hash<std::string>()(rName), Item{rName, rItemCallback}); } inline void RemoveItem(const std::string &rName) { auto it = mItems.find(std::hash<std::string>()(rName)); assert(it != mItems.end()); mItems.erase(it); } private: struct Item { std::string name; DebugMenuItemCallback callback; bool enabled{false}; }; const DebugMenuSystemArgs mArgs; std::unordered_map<size_t, Item> mItems; std::unordered_map<size_t, DebugMenuCallback> mCallbacks; DebugMenuSystem(const DebugMenuSystemArgs &rArgs) : mArgs(rArgs) {} void DrawMenu(); }; } #endif #endif
#include "mainwindow.h" #include <QCoreApplication> #include <QPluginLoader> #include <QDir> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { loadPlugins(); } MainWindow::~MainWindow() { } void MainWindow::loadPlugins() { QDir dir = qApp->applicationDirPath(); qDebug() << dir.absolutePath(); qDebug() << dir.cd("plugins"); foreach (QString s, dir.entryList(QDir::Files)) { qDebug() << dir.absoluteFilePath(s); QPluginLoader loader(s); qDebug() << loader.isLoaded(); } }
class Solution { bool traverse(vector<vector<int>> &graph, int curr, vector<int> &visited, vector<int> &result) { if (visited[curr] == 0) { visited[curr] = 1; for (int i = 0, count = graph[curr].size(); i < count; i++) { int next = graph[curr][i]; if (visited[next] == 1) { return true; } else { bool cycle = traverse(graph, next, visited, result); if (cycle) return true; } } visited[curr] = 2; result.push_back(curr); } return false; } public: vector<int> findOrder(int numCourses, vector<pair<int, int>>& prerequisites) { vector<vector<int>> graph(numCourses); vector<int> isRoot(numCourses, true); for (int i = 0; i < prerequisites.size(); i++) { graph[prerequisites[i].second].push_back(prerequisites[i].first); isRoot[prerequisites[i].first] = false; } queue<int> store; for (int i = 0; i < numCourses; i++) { if (isRoot[i]) { store.push(i); } } vector<int> visited(numCourses, 0); vector<int> result; while(!store.empty()) { int root = store.front(); store.pop();a if (traverse(graph, root, visited, result)) { return {}; } } if (result.size() != numCourses) return {}; reverse(result.begin(), result.end()); return result; } };
/** * Copyright (C) 2017 Alibaba Group Holding Limited. All Rights Reserved. * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <string.h> #include "cowrecorder_wrapper.h" #include "multimedia/component.h" #include <multimedia/mm_debug.h> namespace YUNOS_MM { #define FUNC_TRACK() FuncTracker tracker("CowRecorderWrapper", __FUNCTION__, __LINE__) // #define FUNC_TRACK() DEFINE_LOGTAG(CowRecorderWrapper) DEFINE_LOGTAG(CowRecorderWrapper::CowListener) CowRecorderWrapper::CowRecorderWrapper(RecorderType type, const void * userDefinedData/* = NULL*/) : mCowListener(NULL) { FUNC_TRACK(); mRecorder = new CowRecorder(type); if ( !mRecorder ) { ERROR("failed to create recorder\n"); } } CowRecorderWrapper::~CowRecorderWrapper() { FUNC_TRACK(); if ( mRecorder ) { mRecorder->reset(); } MM_RELEASE(mRecorder); MM_RELEASE(mCowListener); } mm_status_t CowRecorderWrapper::setPipeline(PipelineSP pipeline) { FUNC_TRACK(); return mRecorder->setPipeline(pipeline); } mm_status_t CowRecorderWrapper::setListener(Listener * listener) { FUNC_TRACK(); if ( !mCowListener ) { mCowListener = new CowListener(this); if ( !mCowListener ) { ERROR("no mem\n"); return MM_ERROR_NO_MEM; } mRecorder->setListener(mCowListener); } else { MMLOGW("already set\n"); } return MediaRecorder::setListener(listener); } mm_status_t CowRecorderWrapper::setCamera(VideoCapture *camera, RecordingProxy *recordingProxy) { FUNC_TRACK(); return mRecorder->setCamera(camera, recordingProxy); } mm_status_t CowRecorderWrapper::setVideoSourceUri(const char * uri, const std::map<std::string, std::string> * headers) { FUNC_TRACK(); return mRecorder->setVideoSourceUri(uri, headers); } mm_status_t CowRecorderWrapper::setAudioSourceUri(const char * uri, const std::map<std::string, std::string> * headers) { FUNC_TRACK(); return mRecorder->setAudioSourceUri(uri, headers); } mm_status_t CowRecorderWrapper::setVideoSourceFormat(int width, int height, uint32_t format) { FUNC_TRACK(); return mRecorder->setVideoSourceFormat(width, height, format); } mm_status_t CowRecorderWrapper::setVideoEncoder(const char* mime) { FUNC_TRACK(); return mRecorder->setVideoEncoder(mime); } mm_status_t CowRecorderWrapper::setAudioEncoder(const char* mime) { FUNC_TRACK(); return mRecorder->setAudioEncoder(mime); } mm_status_t CowRecorderWrapper::setOutputFormat(const char* mime) { FUNC_TRACK(); return mRecorder->setOutputFormat(mime); } mm_status_t CowRecorderWrapper::setOutputFile(const char* filePath) { FUNC_TRACK(); return mRecorder->setOutputFile(filePath); } mm_status_t CowRecorderWrapper::setOutputFile(int fd) { FUNC_TRACK(); return mRecorder->setOutputFile(fd); } mm_status_t CowRecorderWrapper::prepare() { FUNC_TRACK(); return mRecorder->prepare(); } mm_status_t CowRecorderWrapper::prepareAsync() { FUNC_TRACK(); return mRecorder->prepareAsync(); } mm_status_t CowRecorderWrapper::setRecorderUsage(RecorderUsage usage) { FUNC_TRACK(); return mRecorder->setRecorderUsage(usage); } mm_status_t CowRecorderWrapper::getRecorderUsage(RecorderUsage &usage) { FUNC_TRACK(); return mRecorder->getRecorderUsage(usage); } mm_status_t CowRecorderWrapper::setPreviewSurface(void * handle) { FUNC_TRACK(); return mRecorder->setPreviewSurface(handle); } mm_status_t CowRecorderWrapper::reset() { FUNC_TRACK(); return mRecorder->reset(); } mm_status_t CowRecorderWrapper::start() { FUNC_TRACK(); return mRecorder->start(); } mm_status_t CowRecorderWrapper::stop() { FUNC_TRACK(); return mRecorder->stop(); } mm_status_t CowRecorderWrapper::stopSync() { FUNC_TRACK(); return mRecorder->stopSync(); } mm_status_t CowRecorderWrapper::pause() { FUNC_TRACK(); return mRecorder->pause(); } bool CowRecorderWrapper::isRecording() const { FUNC_TRACK(); return mRecorder->isRecording(); } mm_status_t CowRecorderWrapper::getVideoSize(int *width, int * height) const { FUNC_TRACK(); if (!width || !height) return MM_ERROR_INVALID_PARAM; return mRecorder->getVideoSize(*width, *height); } mm_status_t CowRecorderWrapper::getCurrentPosition(int64_t * msec) const { //FUNC_TRACK(); mm_status_t status = MM_ERROR_SUCCESS; if (!msec) return MM_ERROR_INVALID_PARAM; status = mRecorder->getCurrentPosition(*msec); return status; } mm_status_t CowRecorderWrapper::setParameter(const MediaMetaSP & meta) { FUNC_TRACK(); return mRecorder->setParameter(meta); } mm_status_t CowRecorderWrapper::getParameter(MediaMetaSP & meta) { FUNC_TRACK(); return mRecorder->getParameter(meta); } mm_status_t CowRecorderWrapper::invoke(const MMParam * request, MMParam * reply) { FUNC_TRACK(); WARNING("%s %s isn't supported yet\n", __FILE__, __FUNCTION__); return MM_ERROR_UNSUPPORTED; } mm_status_t CowRecorderWrapper::setMaxDuration(int64_t msec) { FUNC_TRACK(); return mRecorder->setMaxDuration(msec); } mm_status_t CowRecorderWrapper::setMaxFileSize(int64_t bytes) { FUNC_TRACK(); return mRecorder->setMaxFileSize(bytes); } CowRecorderWrapper::CowListener::CowListener(CowRecorderWrapper * watcher) : mWatcher(watcher) { MMASSERT(watcher != NULL); } CowRecorderWrapper::CowListener::~CowListener() { } void CowRecorderWrapper::CowListener::onMessage(int eventType, int param1, int param2, const MMParamSP meta) { MMParam param; MMLOGD("eventType: %d\n", eventType); switch ( eventType ) { case Component::kEventPrepareResult: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_PREPARED, param1, 0, NULL); break; case Component::kEventEOS: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_RECORDER_COMPLETE, 0, 0, NULL); break; case Component::kEventStartResult: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_STARTED, param1, 0, NULL); break; case Component::kEventPaused: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_PAUSED, param1, 0, NULL); break; case Component::kEventStopped: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_STOPPED, param1, 0, NULL); break; case Component::kEventError: { mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_ERROR, param1, 0, NULL); } break; case Component::kEventMediaInfo: { // FIXME // int i = convertCowInfoCode(getInfoType()); int i = -1; mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_INFO, i, 0, NULL); } break; case Component::kEventInfo: switch (param1) { case Component::kEventMaxFileSizeReached: { INFO("try to send MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED msg\n"); mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_INFO, 801/* MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED */, 0, NULL); } break; case Component::kEventMaxDurationReached: { INFO("try to send MEDIA_RECORDER_INFO_MAX_DURATION_REACHED msg\n"); mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_INFO, 800/* MEDIA_RECORDER_INFO_MAX_DURATION_REACHED */, 0, NULL); } break; default: mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_INFO, param1, 0, NULL); break; } break; case Component::kEventMusicSpectrum: { mWatcher->mListener->onMessage(MediaRecorder::Listener::MSG_MUSIC_SPECTRUM, param1, 0, NULL); } break; default: ERROR("unrecognized message: %d\n", eventType); } } mm_status_t CowRecorderWrapper::setAudioConnectionId(const char * connectionId) { FUNC_TRACK(); return mRecorder->setAudioConnectionId(connectionId); } const char * CowRecorderWrapper::getAudioConnectionId() const { FUNC_TRACK(); return mRecorder->getAudioConnectionId(); } }
#include <vector> using namespace std; long long solution(int N) { long long answer = 0; bool decimal[10000001] = { false }; for (int i = 2; i <= N; i++) { //2부터 N까지 if (!decimal[i]) //false 일때 더함 answer += i; for (int j = i; j <= N; j += i) { //N까지 i의 모든 배수 true decimal[j] = true; } } return answer; }
# define HEALBAGCONTROLLER_HPP # ifndef HEALBAG_HPP # include <healBag.hpp> # endif class healBagController : public sf::Drawable { using Map = sf::Sprite; public: healBagController(const sf::Time &, uint); uint getMaxBags() const; void setMaxBags(const uint &); void setScale(const sf::Vector2f &); void addNewOne(Entity *, Map *); void update(const sf::Time &, Entity *, Map *); Animation m_animation; private: virtual void draw(sf::RenderTarget &, sf::RenderStates) const; std::list<healBag> m_currentBags; sf::Vector2f m_scale; uint m_maxBags; sf::Time m_elapsed, m_spawnTime; };
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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. */ #ifndef ABSTRACTFEASSEMBLERINTERFACE_HPP_ #define ABSTRACTFEASSEMBLERINTERFACE_HPP_ #include <cassert> #include "UblasCustomFunctions.hpp" #include "PetscTools.hpp" /** * A common bass class for AbstractFeVolumeIntegralAssembler (the main abstract assembler class), and other assembler classes * (including continuum mechanics assemblers, which is why this class is separate to AbstractFeAssemblerInterface). * * See AbstractFeVolumeIntegralAssembler documentation for info on these assembler classes. */ template <bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX> class AbstractFeAssemblerInterface : private boost::noncopyable { protected: /** The vector to be assembled (only used if CAN_ASSEMBLE_VECTOR == true). */ Vec mVectorToAssemble; /** The matrix to be assembled (only used if CAN_ASSEMBLE_MATRIX == true). */ Mat mMatrixToAssemble; /** * Whether to assemble the matrix (an assembler may be able to assemble matrices * (CAN_ASSEMBLE_MATRIX==true), but may not want to do so each timestep, hence * this second boolean. */ bool mAssembleMatrix; /** Whether to assemble the vector. */ bool mAssembleVector; /** Whether to zero the given matrix before assembly, or just add to it. */ bool mZeroMatrixBeforeAssembly; /** Whether to zero the given vector before assembly, or just add to it. */ bool mZeroVectorBeforeAssembly; /** Ownership range of the vector/matrix - lowest component owned. */ PetscInt mOwnershipRangeLo; /** Ownership range of the vector/matrix - highest component owned +1. */ PetscInt mOwnershipRangeHi; /** * The main assembly method. Protected, should only be called through Assemble(), * AssembleMatrix() or AssembleVector() which set mAssembleMatrix, mAssembleVector * accordingly. Pure and therefore is implemented in child classes. Will involve looping * over elements (which may be volume, surface or cable elements), and computing * integrals and adding them to the vector or matrix */ virtual void DoAssemble()=0; public: /** * Constructor. */ AbstractFeAssemblerInterface(); /** * Set the matrix that needs to be assembled. Requires CAN_ASSEMBLE_MATRIX==true. * * @param rMatToAssemble Reference to the matrix * @param zeroMatrixBeforeAssembly Whether to zero the matrix before assembling * (otherwise it is just added to) */ void SetMatrixToAssemble(Mat& rMatToAssemble, bool zeroMatrixBeforeAssembly=true); /** * Set the vector that needs to be assembled. Requires CAN_ASSEMBLE_VECTOR==true. * * @param rVecToAssemble Reference to the vector * @param zeroVectorBeforeAssembly Whether to zero the vector before assembling * (otherwise it is just added to) */ void SetVectorToAssemble(Vec& rVecToAssemble, bool zeroVectorBeforeAssembly); /** * Assemble everything that the class can assemble. */ void Assemble() { mAssembleMatrix = CAN_ASSEMBLE_MATRIX; mAssembleVector = CAN_ASSEMBLE_VECTOR; DoAssemble(); } /** * Assemble the matrix. Requires CAN_ASSEMBLE_MATRIX==true */ void AssembleMatrix() { assert(CAN_ASSEMBLE_MATRIX); mAssembleMatrix = true; mAssembleVector = false; DoAssemble(); } /** * Assemble the vector. Requires CAN_ASSEMBLE_VECTOR==true */ void AssembleVector() { assert(CAN_ASSEMBLE_VECTOR); mAssembleMatrix = false; mAssembleVector = true; DoAssemble(); } /** * Destructor. */ virtual ~AbstractFeAssemblerInterface() { } }; template <bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX> AbstractFeAssemblerInterface<CAN_ASSEMBLE_VECTOR, CAN_ASSEMBLE_MATRIX>::AbstractFeAssemblerInterface() : mVectorToAssemble(nullptr), mMatrixToAssemble(nullptr), mZeroMatrixBeforeAssembly(true), mZeroVectorBeforeAssembly(true) { assert(CAN_ASSEMBLE_VECTOR || CAN_ASSEMBLE_MATRIX); } template <bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX> void AbstractFeAssemblerInterface<CAN_ASSEMBLE_VECTOR, CAN_ASSEMBLE_MATRIX>::SetMatrixToAssemble(Mat& rMatToAssemble, bool zeroMatrixBeforeAssembly) { assert(rMatToAssemble); MatGetOwnershipRange(rMatToAssemble, &mOwnershipRangeLo, &mOwnershipRangeHi); mMatrixToAssemble = rMatToAssemble; mZeroMatrixBeforeAssembly = zeroMatrixBeforeAssembly; } template <bool CAN_ASSEMBLE_VECTOR, bool CAN_ASSEMBLE_MATRIX> void AbstractFeAssemblerInterface<CAN_ASSEMBLE_VECTOR, CAN_ASSEMBLE_MATRIX>::SetVectorToAssemble(Vec& rVecToAssemble, bool zeroVectorBeforeAssembly) { assert(rVecToAssemble); VecGetOwnershipRange(rVecToAssemble, &mOwnershipRangeLo, &mOwnershipRangeHi); mVectorToAssemble = rVecToAssemble; mZeroVectorBeforeAssembly = zeroVectorBeforeAssembly; } #endif // ABSTRACTFEASSEMBLERINTERFACE_HPP_
#include <string> #include <vector> using namespace std; int solution(vector<vector<int>> board, vector<int> moves) { int answer = 0; vector<int> select; for (int j = 0; j < moves.size(); j++) { int num = moves[j] - 1; for (int i = 0; i < board.size(); i++) if (board[i][num] > 0) { if (!select.empty() && select.back() == board[i][num]) { select.pop_back(); answer += 2; } else { select.push_back(board[i][num]); } board[i][num] = 0; break; } } return answer; }
#include <stdio.h> #include <stdlib.h> #include <time.h> #include "aps.h" main(int iargc, char *argv[]){ //d=8 -> delta_chisq=15.5 //d=5 -> delta_chisq=11 int seed=99; int dim,ncenters; seed=atoi(argv[1]); dim=atoi(argv[2]); ncenters=atoi(argv[3]); char timingname[letters],outname[letters]; //what is the name of the file where APS will store its timing information sprintf(timingname,"timingFiles/ellipse_d%d_c%d_timing.sav",dim,ncenters); //what is the name of the file where APS will output the points it sampled sprintf(outname,"outputFiles/ellipse_d%d_c%d_output.sav",dim,ncenters); if(seed<0){ seed=int(time(NULL)); } printf("seed %d\n",seed); //declare the covariogram for APS's Gaussian process matern_covariance cv; //declare the chisquared function APS will be searching ellipses_integrable chisq(dim,ncenters); //declare APS //the '20' below is the number of nearest neighbors to use when seeding the //Gaussian process // //the '11.0' is the \Delta\chi^2 corresponding to a 95% confidence limit //on a 5-dimensional parameter space aps aps_test(dim,20,11.0,seed); //pass chisq to the aps object aps_test.assign_chisquared(&chisq); //pass the covariogram to the aps object aps_test.assign_covariogram(&cv); //how often will APS stop and write its output aps_test.set_write_every(1000); //set the G parameter from equation (4) in the paper aps_test.set_grat(1.0); //set the maximum and minimum values in parameter space array_1d<double> max,min; max.set_name("driver_max"); min.set_name("driver_min"); max.set_dim(dim); min.set_dim(dim); int i,j; for(i=0;i<dim;i++){ min.set(i,-200.0); max.set(i,200.0); } aps_test.set_timingname(timingname); aps_test.set_outname(outname); //initialize aps with 1000 random samples aps_test.initialize(1000,min,max); double chival,chivaltest,err; i=-1; //search parameter space until the //chisquared function has been called //10000 times while(aps_test.get_called()<50000){ aps_test.search(); } aps_test.write_pts(); array_1d<double> minpt; //what is the point in parameter space corresponding to the //minimum chisquared aps_test.get_minpt(minpt); printf("chimin %e\n",aps_test.get_chimin()); printf("ct_aps %d ct_simplex %d total %d\n", aps_test.get_ct_aps(),aps_test.get_ct_simplex(), aps_test.get_called()); }
#include "HelloWorldScene.h" #include "SimpleAudioEngine.h" #include"GameScene.h" #include"AppDelegate.h" USING_NS_CC; Scene* HelloWorld::createScene() { return HelloWorld::create(); } // Print useful error message instead of segfaulting when files are not there. static void problemLoading(const char* filename) { printf("Error while loading: %s\n", filename); printf("Depending on how you compiled you might have to add 'Resources/' in front of filenames in HelloWorldScene.cpp\n"); } // on "init" you need to initialize your instance bool HelloWorld::init() { ////////////////////////////// // 1. super init first if (!Scene::init()) { return false; } auto visibleSize = Director::getInstance()->getVisibleSize(); Vec2 origin = Director::getInstance()->getVisibleOrigin(); auto labelStart = Label::create("Start Game", "fonts/Marker Felt.ttf", 72); auto labelAI = Label::create("Automatic Path Finding", "fonts/Marker Felt.ttf", 72); auto labelExit = Label::create("ExitGame", "fonts/Marker Felt.ttf", 72); auto startItem = MenuItemLabel::create(labelStart, CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); startItem->setTag(1); startItem->setPosition(Vec2(visibleSize.width / 3 * 2, visibleSize.height / 4 * 3 - 10)); auto AIItem = MenuItemLabel::create(labelAI, CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); AIItem->setTag(2); AIItem->setPosition(Vec2(visibleSize.width / 3 * 2, visibleSize.height / 4 * 2)); auto exitItem = MenuItemLabel::create(labelExit, CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); exitItem->setTag(3); exitItem->setPosition(Vec2(visibleSize.width / 3 * 2, visibleSize.height / 4 * 1 + 10)); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setTag(4); if (closeItem == nullptr || closeItem->getContentSize().width <= 0 || closeItem->getContentSize().height <= 0) { problemLoading("'CloseNormal.png' and 'CloseSelected.png'"); } else { float x = origin.x + visibleSize.width - closeItem->getContentSize().width / 2; float y = origin.y + closeItem->getContentSize().height / 2; closeItem->setPosition(Vec2(x, y)); } // // create menu, it's an autorelease object auto menu = Menu::create(startItem, AIItem, exitItem, closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); // ///////////////////////////// // // 3. add your codes below... // // add a label shows "Hello World" // // create and initialize a label auto label = Label::createWithTTF("Snake", "fonts/Marker Felt.ttf", 96); if (label == nullptr) { problemLoading("'fonts/Marker Felt.ttf'"); } else { // position the label on the center of the screen label->setPosition(Vec2(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - label->getContentSize().height)); // add the label as a child to this layer this->addChild(label, 1); } // add "HelloWorld" splash screen" auto sprite = Sprite::create("HelloWorld.png"); if (sprite == nullptr) { problemLoading("'HelloWorld.png'"); } else { // position the sprite on the center of the screen sprite->setPosition(Vec2(visibleSize.width / 3 + origin.x, visibleSize.height / 2 + origin.y)); // add the sprite as a child to this layer this->addChild(sprite, 0); } //auto sprite1 = Sprite::create("yqh.png"); //sprite1->setPosition(Vec2(0, 0)); //sprite1->setAnchorPoint(Vec2(0, 0)); //this->addChild(sprite1); //this->removeAllChildrenWithCleanup(true); return true; } void HelloWorld::menuCloseCallback(Ref* pSender) { //Close the cocos2d-x game scene and quit the application switch (((Node*)pSender)->getTag()) { case 1: //log("go to game"); secondLayer->sceneNum = 0; Director::getInstance()->replaceScene(GameScene::createScene()); break; /*case 2: CCLOG("go to help"); Director::getInstance()->replaceScene(GameAI::createScene());*/ break; case 2: secondLayer->sceneNum = 1; Director::getInstance()->replaceScene(GameScene::createScene()); break; case 3: Director::getInstance()->end(); case 4: Director::getInstance()->end(); } #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif /*To navigate back to native iOS screen(if present) without quitting the application ,do not use Director::getInstance()->end() and exit(0) as given above,instead trigger a custom event created in RootViewController.mm as below*/ //EventCustom customEndEvent("game_scene_close_event"); //_eventDispatcher->dispatchEvent(&customEndEvent); } /*********************************************************************************************************/
#include "spis.h" consoleInput::consoleInput(int startX, int startY, string label, int maxNum) { win = newwin(maxNum + 1 + 2 + 2, INPUT_LIST_WIDTH + 3, startY, startX); mvwprintw(win, 0, 0, "%s", label.c_str()); wrefresh(win); numWin = winBorder(maxNum , INPUT_LIST_WIDTH + 1, startY + 2, startX + 1); wrefresh(numWin); inWin = winBorder(1, INPUT_LIST_WIDTH + 1, startY + maxNum + 2 + 1, startX + 1); current = 0; max = maxNum; lbl = label; mvwprintw(inWin, 0, 0, "%s", PROMPT.c_str()); wrefresh(inWin); } inputArrow *consoleInput::initArrow(int8_t nodeIndex, int8_t arrowIndex) { int y, x; getbegyx(grid[nodeIndex].w_main, y, x); if (arrowIndex == 0) inArr = new inputArrow(nodeIndex, y - ARROW_V_HEIGHT, x + floor(NODE_WIDTH / 2) - floor(ARROW_V_WIDTH / 2), arrowIndex, lbl); else if (arrowIndex == 1) inArr = new inputArrow(nodeIndex, y + floor(NODE_HEIGHT / 2) - floor(ARROW_H_HEIGHT / 2), x + NODE_WIDTH + GAP_WIDTH_H, arrowIndex, lbl); else if (arrowIndex == 2) inArr = new inputArrow(nodeIndex, y + NODE_HEIGHT + GAP_WIDTH_V, x + floor(NODE_WIDTH / 2) - floor(ARROW_V_WIDTH / 2), arrowIndex, lbl); else inArr = new inputArrow(nodeIndex, y + floor(NODE_HEIGHT / 2) - floor(ARROW_H_HEIGHT / 2), x - ARROW_H_WIDTH, arrowIndex, lbl); gridArrows.push_back(inArr); grid[nodeIndex].arrows[arrowIndex] = inArr; wrefresh(inArr->win); return inArr; } void consoleInput::loadValue() { inArr->nodeSet(INPUT_ID, inValue); inArr->updateValues(); return; } void consoleInput::inputInt(int input) { return; } void consoleInput::tickUpdate() { if (inReady && inArr->setRequest(INPUT_ID)) { loadValue(); inReady = false; } return; } void consoleInput::reset() { current = 0; werase(numWin); wrefresh(numWin); selected = false; inStr = ""; updateValues(); } bool consoleInput::processInput(int input, MEVENT event) { if ((input != KEY_MOUSE) && !selected) return false; if (input == KEY_MOUSE) { if (!pointInWindow(inWin, event.x, event.y)) return false; selected = true; cursorX = event.x - getbegx(inWin) - 1; if (cursorX < 0) cursorX = 0; else if (cursorX > inStr.length()) cursorX = inStr.length(); x = getbegx(inWin) + cursorX + 1; y = getbegy(inWin); move(y, x); setCursor(true); return true; } if (input >= 48 && input <= 57) { if (inStr.length() >= 4) return true; inStr = inStr.substr(0, cursorX) + static_cast<char>(input) + inStr.substr(cursorX); updateValues(); cursorX++; x++; move(y, x); setCursor(true); } else if (input == KEY_ENTER || input == 11 || input == 10) { if (inArr->setRequest(INPUT_ID) && !inReady && abs(stoi(inStr)) < 999) { mvwprintw(numWin, current, 0, "%s", makeThreeDigit(stoi(inStr)).c_str()); wrefresh(numWin); inReady = true; inValue = stoi(inStr); } inStr = ""; x -= cursorX; cursorX = 0; updateValues(); } else if(input == KEY_BACKSPACE || input == 127) { // BACKSPACE if (cursorX <= 0) return true; inStr = inStr.substr(0, cursorX - 1) + inStr.substr(cursorX); cursorX--; x = getbegx(inWin) + cursorX + 1; move(y, x); updateValues(); setCursor(true); } else if (input == KEY_LEFT) { if (cursorX != 0) { cursorX--; x = getbegx(inWin) + cursorX + 1; move(y, x); setCursor(true); } return true; } else if (input == KEY_RIGHT) { if (cursorX <= 4 && cursorX <= inStr.length()) { cursorX++; x = getbegx(inWin) + cursorX + 1; move(y, x); setCursor(true); } return true; } return false; } WINDOW *consoleInput::getInputWin() { return inWin; } void consoleInput::updateValues() { werase(inWin); mvwprintw(inWin, 0, 0, "%s", (">" + inStr).c_str()); wrefresh(inWin); }
#include <iostream> #include <algorithm> #include <vector> #include <map> #include <string> #include <set> #include <cmath> #include <math.h> #include <unordered_map> #include <unordered_set> #include <cstring> #include <climits> #include <queue> #include <assert.h> using namespace std; int N,K; int main(){ int T; cin>>T; for(int tt=1;tt<T+1;++tt){ cin>>N>>K; vector<double> numbers(N); for(int i=0;i<N;++i){cin>>numbers[i];} sort(numbers.begin(),numbers.end()); double result=0; for(int i=0;i<=K;++i){ vector<double>vals(numbers.begin(),numbers.begin()+i); for(int x=N-K+i;x<N;++x){vals.push_back(numbers[x]);} int j=0; int col=0; vector<vector<double>> probs(K/2+1,vector<double>(K,0.0)); while(j<K){ if(col==0){probs[1][0]=vals[j];probs[0][0]=1-vals[j];col++;j++;continue;} for(int num=0;num<=K/2;++num){ if(num==0){probs[0][col]=probs[0][col-1]*(1-vals[j]);continue;} probs[num][col]=vals[j]*probs[num-1][col-1]+probs[num][col-1]*(1-vals[j]); } j++; col++; } result=max(result,probs[K/2][K-1]); } cout.precision(6); cout<<"Case #"<<tt<<": "<<fixed<<result<<endl; } }
#ifndef __TEST_OBJECTS_H #define __TEST_OBJECTS_H class User; #include "ReplicaManager2.h" // NetworkIDManager2 is in the namespace RakNet using namespace RakNet; // Soldier is a class that a User can create class Soldier : public Replica2 { public: // All created soldiers static DataStructures::List<Soldier*> soldiers; // My soldier (client only) static Soldier *mySoldier; // The user that owns this soldier User *owner; // Name of this soldier char name[128]; // Is this soldier cloaked? While cloaked, changes will not be sent with the Serialize() function bool isCloaked; // Track this pointer, which user owns me, and the initial value for my name Soldier(); // Stop tracking this pointer virtual ~Soldier(); // Return the user that owns me (shouldn't be NULL) User* GetUser(void) const; // Set a new name for myself void SetName(char *newName); // Cloak or uncloak. Other systems won't get changes to this soldier while cloaked. void SetCloak(bool b); // Implemented member of Replica2: This function encodes the identifier for this class, so the class factory can create it virtual bool SerializeConstruction(RakNet::BitStream *bitStream, SerializationContext *serializationContext); // Implemented member of Replica2: Write the data members of this class. ReplicaManager2 works with strings as well as pointers virtual bool Serialize(RakNet::BitStream *bitStream, SerializationContext *serializationContext); // Implemented member of Replica2: Read what I wrote in Serialize() immediately above virtual void Deserialize(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); // Implemented member of Replica2: Should this object be visible to this connection? If not visible, Serialize() will not be sent to that system. virtual BooleanQueryResult QueryVisibility(Connection_RM2 *connection); // Implemented member of Replica2: Called when our visibility changes. While not visible, we will not get updates from Serialize() for affected connection(s) virtual void DeserializeVisibility(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); // Overriding so the client can delete this object. By default, only the server could virtual bool QueryIsDestructionAuthority(void) const; // Overriding so the client can control if this object is visible or not (for cloaking). By default, only the server control this // Objects that are not visible are not serialized automatically with ReplicaManager2::AutoSerialize() virtual bool QueryIsVisibilityAuthority(void) const; // Overriding so the client can send serialization changes for its own soldier. By default, only the server can send serialization changes. virtual bool QueryIsSerializationAuthority(void) const; }; // User represents a human behind a computer. One instance is created on the server per new connection. class User : public Replica2 { public: // Holds a pointer to my soldier. Soldier *soldier; // All users that have been created static DataStructures::List<User*> users; // Does this user represent me? Used on the client only. static User *myUser; // System address of this user SystemAddress systemAddress; // User starts out with no soldier. Also, track this pointer. User(); // Remove myself from the static users list virtual ~User(); // Overload QueryConstruction to test delaying construction by one tick virtual BooleanQueryResult QueryConstruction(Connection_RM2 *connection); // Helper function to free memory when someone disconnections. static void DeleteUserByAddress(SystemAddress systemAddress); // Helper function to lookup the user in users by systemAddress static User* GetUserByAddress(SystemAddress systemAddress); // Each user can have a soldier. Create my soldier if I don't have one already Soldier* CreateSoldier(void); // Return my soldier Soldier* GetMySoldier(void) const; // Implemented member of Replica2: This function encodes the identifier for this class, so the class factory can create it virtual bool SerializeConstruction(RakNet::BitStream *bitStream, SerializationContext *serializationContext); // Implemented member of Replica2: Write the data members of this class. ReplicaManager2 works with pointers as well as any other kind of data virtual bool Serialize(RakNet::BitStream *bitStream, SerializationContext *serializationContext); // Implemented member of Replica2: Read what I wrote in Serialize() immediately above virtual void Deserialize(RakNet::BitStream *bitStream, SerializationType serializationType, SystemAddress sender, RakNetTime timestamp); }; // One instance of Connection_RM2 is implicitly created per connection that uses ReplicaManager2. The most important function to implement is Construct() as this creates your game objects. // It is designed this way so you can override per-connection behavior in your own game classes class ReplicaManager2DemoConnection : public Connection_RM2 { public: ReplicaManager2DemoConnection() {constructionDelayedOneTick=false;} ~ReplicaManager2DemoConnection() {} // Callback used to create objects // See Connection_RM2::Construct in ReplicaManager2.h for a full explanation of each parameter Replica2* Construct(RakNet::BitStream *replicaData, SystemAddress sender, SerializationType type, ReplicaManager2 *replicaManager, RakNetTime timestamp, NetworkID networkId, bool networkIDCollision); // Callback when we finish downloading all objects from a new connection // See Connection_RM2::DeserializeDownloadComplete in ReplicaManager2.h for a full explanation of each parameter virtual void DeserializeDownloadComplete(RakNet::BitStream *objectData, SystemAddress sender, ReplicaManager2 *replicaManager, RakNetTime timestamp, SerializationType serializationType); bool constructionDelayedOneTick; }; // This is a required class factory, that creates and destroys instances of ReplicaManager2DemoConnection class ReplicaManager2DemoConnectionFactory : public Connection_RM2Factory { virtual Connection_RM2* AllocConnection(void) const {return new ReplicaManager2DemoConnection;} virtual void DeallocConnection(Connection_RM2* s) const {delete s;} }; #endif
// SETUP NOTES: // This test uses 4 buttons, 4 POTS, a breadboard and 10 optional LED's. // // Termainl: // - You should connect your TinyPICO to a proper ANSI terminal such as TeraTerm and set the baud rate to 115200 // - ASCII escape codes are used to control advanced debug output // // Expander Setup: // - Plug in TinyPICO // - Connect GND and 3.3V to breadboard power rails // - Connect Expander Board INTERRUPT A pin to TinyPICO Pin 27 // // Button Setup: // - Place 4 buttons on a breadboard and connect one side of each button to GND // - Connect the 4 buttons to Expander shield IO pins marked 5, 6, 7, 8 on the Expander Shield // // Potentiometer Setup // -- Place 4 pots on the breadboard. Connect them all to ground and 3.3v // -- Connect the wiper pins to A0, A1, A2 and A3 // // Optional LED Setup: // - Place 10 LED's on the Breadboard connecting the short leg / negative / cathode to GND via a relevant resitor // - Connect 8 of the LED's long leg / positive / anode to Expander Shield IO pins marked 1, 2, 3, 4, 13, 14, 15, 16 // // Optional Interrupt Pins LED // - Instead of conecting INTTERUPT A pin to TinyPICO Pin 27 tie these pins together on a spare row on the breadboard // - Plug the one of the remaining LEDs long leg / positive / anode to the same row. // - This LED will be high / ON and will go low / turn OFF when a GPIO interrupt is fired. // - Connect the remaining LEDs long leg / positive / anode to the ALERT pin. // - This LED will be high / ON and will go low / turn OFF when a comparator interrupt is fired. // // Expected Behaviour // - The first 4 LED's will cycle // - The next four LEDS will alternate a staggered pattern X 0 X 0 >> 0 X 0 X >> X 0 X 0 .... // - All four buttons will generate a callback and show a message in the serial console debug screen // - When buttons 1 & 2 are both held together, a message will be displayed in the serial console debug screen // - Only buttons 3 & 4 will generate an interrupt handle message // - Interrupts for other buttons will be blocked while holding down a button, although callbacks will continue to fire // - When in analog sinle ended mode all four pot will be shown on the debug output screen // - When in analog differential channels 0 (A0+ / A1-) & 1 (A2+ / A3-) will be shown on the debug screen output. // - To test differential mode, go to analog mode. Set channel 0 to 500 and channel 1 to 200. Go to differential mode and channel 0 should read 300; // - When in comparitor mode, the comparator value will read from channel 0 and be shown on the debug screen output. One the comparitor exceeds 500 the ALERT pin will go LOW #include "Arduino.h" #include "TinyPICOExpander.h" typedef enum { Single, Differential, Comparator } adsMode_t; TinyPICOExpander tpio = TinyPICOExpander(); volatile bool handleInterrupt = false; volatile int interruptFires = 0; // count the number of times an interrupt has been fired int callbackFires = 0; // count the number of times a callback has been called int cyclePort = 0; // current port number that is being set in togglePorts adsMode_t adsMode = Single; int gainSetting = 0x00; unsigned long lastToggle; // Routine to print int as binary with leading zeros void printBits(uint16_t b, int bits) { for (int i = bits - 1; i >= 0; i--) Serial.print(bitRead(b, i)); } // routine called as interrupt handler / ISR to flag interrupt process required // we don't read the MCP23017 ports via I2C during an interrupt as it will create watchdog & issues // we set a bool flag and process the interrupt via the main loop void InterruptFlag() { handleInterrupt = true; interruptFires++; } // code called when the interrupt flag is processed void ProcessInterrupt() { // detachInterrupt(27); Serial.printf("\033[13;0H"); Serial.printf("| Interrupt! - Pin: %03d | Value: %03d | Fires: %03d\r\n", tpio.getLastInterruptPin(), tpio.getLastInterruptPinValue(), interruptFires); Serial.printf("\033[H"); // attachInterrupt(27, InterruptFlag, FALLING); } // test code to cycle and stagger port bits for testing void togglePorts() { if (millis() - lastToggle < 1000) return; lastToggle = millis(); // cycle bits 0-3 tpio.digitalWrite(0, cyclePort == 0 ? LOW : HIGH); tpio.digitalWrite(1, cyclePort == 1 ? LOW : HIGH); tpio.digitalWrite(2, cyclePort == 2 ? LOW : HIGH); tpio.digitalWrite(3, cyclePort == 3 ? LOW : HIGH); // bits 4-7 are buttons // stagger bits 8-15 tpio.digitalWrite(8, cyclePort % 2 == 0 ? LOW : HIGH); tpio.digitalWrite(9, cyclePort % 2 != 0 ? LOW : HIGH); tpio.digitalWrite(10, cyclePort % 2 == 0 ? LOW : HIGH); tpio.digitalWrite(11, cyclePort % 2 != 0 ? LOW : HIGH); tpio.digitalWrite(12, cyclePort % 2 == 0 ? LOW : HIGH); tpio.digitalWrite(13, cyclePort % 2 != 0 ? LOW : HIGH); tpio.digitalWrite(14, cyclePort % 2 == 0 ? LOW : HIGH); tpio.digitalWrite(15, cyclePort % 2 != 0 ? LOW : HIGH); cyclePort++; if (cyclePort > 3) cyclePort = 0; } // draw initial debug screen via serial output void drawScreen() { Serial.printf("\033[2J\033[H\033[?25l"); // clear screen, home cursor, hide cursor Serial.println(".---------------------------------------------------------------------------------------------------------------------------------."); Serial.println("| \033[41mTinyPICO IO Expander Shield Test v0.1 \033[m |"); Serial.println("|---------------------------------------------------------------------------------------------------------------------------------|"); Serial.println("| \033[44mDIGITAL \033[m |"); Serial.println("|---------------------------------------------------------------.-----------------------------------------------------------------|"); Serial.println("| \033[7mCycle \033[m | \033[7mButtons \033[m |"); Serial.println("| Port00: - Port01: - Port02: - Port03: - | Port04: - Port05: - Port06: - Port07: - |"); Serial.println("|-------------------------------------------------------------- +-----------------------------------------------------------------|"); Serial.println("| \033[7mStaggered \033[m | \033[7mStaggered \033[m |"); Serial.println("| Port08: - Port09: - Port10: - Port11: - | Port12: - Port13: - Port14: - Port15: - |"); Serial.println("|---------------------------------------------------------------+-----------------------------------------------------------------|"); Serial.println("| \033[7mInterrupt \033[m | \033[7mPorts \033[m |"); Serial.println("| Interrupt! - Pin: --- | Value: --- | Fires: --- | Ports: ---------------- | PortA : -------- | PortB : -------- |"); Serial.println("|---------------------------------------------------------------+-----------------------------------------------------------------|"); Serial.println("| \033[7mCallback \033[m |"); Serial.println("| Callback! - Ports: ---------------- | Button: --- | State: ----- | Fires: --- |"); Serial.println("|---------------------------------------------------------------------------------------------------------------------------------|"); Serial.println("| \033[44mANALOG \033[m |"); Serial.println("|---------------------------------------------------------------------------------------------------------------------------------|"); switch(adsMode) { case Single: Serial.println("| \033[7mSingle Ended \033[m |"); Serial.println("| 0: ---------------- | 1: ---------------- | 2: ---------------- | 3: ---------------- |"); Serial.println("| 0: ---------------- | 1: ---------------- | 2: ---------------- | 3: ---------------- |"); break; case Differential: Serial.println("| \033[7mDifferential Inputs \033[m |"); Serial.println("| 0: ---------------- | 1: ---------------- | 2: ---------------- | 3: ---------------- |"); Serial.println("| 0: ---------------- | 1: ---------------- | 2: ---------------- | 3: ---------------- |"); break; case Comparator: Serial.println("| \033[7mComparator \033[m |"); Serial.println("| 0: ---------------- | Compare: ----- |"); Serial.println("| 0: ---------------- |"); break; default: break; } Serial.println("|---------------------------------------------------------------------------------------------------------------------------------|"); Serial.println("| \033[7mGain \033[m | \033[7mNone \033[m |"); Serial.println("| Gain: | |"); Serial.println("|---------------------------------------------------------------------------------------------------------------------------------|"); Serial.println("| \033[38;5;242mNOTES: \033[m |"); Serial.println("| \033[38;5;242mDigital: [BUTTON1-4] - Generate Callback [BUTTON3-4] - Generate Interrupt \033[m |"); Serial.println("| \033[38;5;242m Analog: [BUTTON1] - Switch Analog Mode (Single|Differential|Comparator) [BUTTON2] - Cycle Gain (2/3x|1x|2x|4x|8x|16x) \033[m |"); Serial.println("`---------------------------------------------------------------+-----------------------------------------------------------------'"); } // update only values for debug screen via serial output void updateScreen() { // GPIO Serial.printf("\033[7;11H%d", tpio.digitalRead(0)); Serial.printf("\033[7;27H%d", tpio.digitalRead(1)); Serial.printf("\033[7;43H%d", tpio.digitalRead(2)); Serial.printf("\033[7;59H%d", tpio.digitalRead(3)); Serial.printf("\033[7;75H%d", tpio.digitalRead(4)); Serial.printf("\033[7;91H%d", tpio.digitalRead(5)); Serial.printf("\033[7;107H%d", tpio.digitalRead(6)); Serial.printf("\033[7;123H%d", tpio.digitalRead(7)); Serial.printf("\033[10;11H%d", tpio.digitalRead(8)); Serial.printf("\033[10;27H%d", tpio.digitalRead(9)); Serial.printf("\033[10;43H%d", tpio.digitalRead(10)); Serial.printf("\033[10;59H%d", tpio.digitalRead(11)); Serial.printf("\033[10;75H%d", tpio.digitalRead(12)); Serial.printf("\033[10;91H%d", tpio.digitalRead(13)); Serial.printf("\033[10;107H%d", tpio.digitalRead(14)); Serial.printf("\033[10;123H%d", tpio.digitalRead(15)); Serial.print("\033[13;67HPorts: "); printBits(tpio.readPorts(), 16); Serial.print(" | PortA : "); printBits(tpio.readPorts(MCP23017_GPIOA), 8); Serial.print(" | PortB : "); printBits(tpio.readPorts(MCP23017_GPIOB), 8); Serial.print(" |\r\n"); // ADC uint16_t value; switch (adsMode) { case Single: value = tpio.analogReadSingleEnded(0); Serial.print("\033[21;6H"); printBits(value, 16); Serial.print("\033[22;6H"); Serial.printf("%16u", value); value = tpio.analogReadSingleEnded(1); Serial.print("\033[21;42H"); printBits(value, 16); Serial.print("\033[22;42H"); Serial.printf("%16u", value); value = tpio.analogReadSingleEnded(2); Serial.print("\033[21;80H"); printBits(value, 16); Serial.print("\033[22;80H"); Serial.printf("%16u", value); value = tpio.analogReadSingleEnded(3); Serial.print("\033[21;114H"); printBits(value, 16); Serial.print("\033[22;114H"); Serial.printf("%16u", value); break; case Differential: value = tpio.analogReadDifferential(0); Serial.print("\033[21;6H"); printBits(value, 16); Serial.print("\033[22;6H"); Serial.printf("%16u", value); Serial.print("\033[21;42H----------------"); Serial.print("\033[22;42H----------------"); value = tpio.analogReadDifferential(1); Serial.print("\033[21;80H"); printBits(value, 16); Serial.print("\033[22;80H"); Serial.printf("%16u", value); Serial.print("\033[21;114H----------------"); Serial.print("\033[22;114H----------------"); break; case Comparator: value = tpio.getLastConversionResults(); Serial.print("\033[21;6H"); printBits(value, 16); Serial.print("\033[22;6H"); Serial.printf("%16u", value); break; default: break; } Serial.print("\033[25;3HGain: "); switch (tpio.analogGetGain()) { case GAIN_TWOTHIRDS: Serial.print("x2/3"); break; case GAIN_ONE: Serial.print("x1 "); break; case GAIN_TWO: Serial.print("x2 "); break; case GAIN_FOUR: Serial.print("x4 "); break; case GAIN_EIGHT: Serial.print("x8 "); break; case GAIN_SIXTEEN: Serial.print("x16 "); break; default: break; } } // routine called when port changes state. This is an alternative to using interrupts // it requires update be called in the main loop and uses a polling technique generating more I2C calls // it is however more versatile than interrupts as it can detect multiple simultaneous button presses and supports callbacks void GPIOChangeCallback(uint16_t ports, uint8_t button, bool state) { callbackFires++; Serial.printf("\033[16;0H"); Serial.printf("| Callback! - Ports: "); printBits(ports, 16); Serial.printf(" | Button: %03d | State: %s | Fires: %03d | ", button, state ? "TRUE " : "FALSE", callbackFires); if (state == true) switch (button) { case 4: adsMode = adsMode_t(((int)adsMode) + 1); if (adsMode > Comparator) adsMode = Single; if (adsMode == Comparator) tpio.startComparator(0, 500); // ~1.5v drawScreen(); break; case 5: gainSetting += 0x200; if (gainSetting > 0xA00) gainSetting = 0x00; tpio.analogSetGain((adsGain_t)gainSetting); break; default: break; } // detect multiple button press // ports are pullups and will go low when pressed so we NOT (!) the bit test if (!(ports & BUTTON4) && !(ports & BUTTON5)) Serial.printf("Button 1 & 2 Pressed!"); else Serial.printf(" "); } void setup() { // Serial.begin(460800); Serial.begin(115200); tpio.begin(); gainSetting = tpio.analogGetGain(); tpio.pinMode(0, OUTPUT); tpio.pinMode(1, OUTPUT); tpio.pinMode(2, OUTPUT); tpio.pinMode(3, OUTPUT); tpio.pinMode(8, OUTPUT); tpio.pinMode(9, OUTPUT); tpio.pinMode(10, OUTPUT); tpio.pinMode(11, OUTPUT); tpio.pinMode(12, OUTPUT); tpio.pinMode(13, OUTPUT); tpio.pinMode(14, OUTPUT); tpio.pinMode(15, OUTPUT); tpio.pinMode(4, INPUT); tpio.pinMode(5, INPUT); tpio.pinMode(6, INPUT); tpio.pinMode(7, INPUT); tpio.pullUp(4, HIGH); tpio.pullUp(5, HIGH); tpio.pullUp(6, HIGH); tpio.pullUp(7, HIGH); tpio.setupInterrupts(false, false, LOW); tpio.setupInterruptPin(7, FALLING); tpio.setupInterruptPin(6, FALLING); pinMode(27, INPUT); attachInterrupt(27, InterruptFlag, FALLING); // register after pin setup. // In this example we only want to create call back events for the buttons and not for the changes made in the togglePorts function // to do this we pass in a bit mask to register callback. The value 0xF0 represents ports 4-7 / 0000 0000 1111 0000. tpio.RegisterChangeCB(GPIOChangeCallback, 0xF0); drawScreen(); } void loop() { // process interrupt if ISR handler is flagged if (handleInterrupt) { handleInterrupt = false; ProcessInterrupt(); } togglePorts(); updateScreen(); tpio.update(); }
#ifndef DATASTRUCTURE_TESTBINARYTREE_H #define DATASTRUCTURE_TESTBINARYTREE_H // 包含要测试的数据类型头文件 #include "binaryTree.h" // 设置值类型为char型 using ValueType = char; // 空字符设置为'#' const ValueType NULL_VALUE = '#'; // 测试主函数 void testBinaryTree() { constexpr int size = 100; // 选择的操作 int operation = -1; // 一个辅助变量 ValueType value = 0; // 结点类型指针 Node<ValueType> *temp_node = nullptr; // 定义一棵二叉树 BinaryTree<ValueType, NULL_VALUE> trees[size]; int tree_index = 0; int temp_tree_index = 0; // visit函数 Visit<ValueType> visit = [](const ValueType &t) {std::cout << t << std::endl; }; // 默认键为-1 int key = -1; // 左右选择 LR lr = LR::L; int position = 0; // 插入子树时的临时树 BinaryTree<ValueType, NULL_VALUE> temp_tree; // 用户选择的选项 std::string choice; while (operation != 0) { // 清屏 cls(); // 打印菜单 std::cout << ""; std::cout << " Menu for Binary Tree\n\n"; std::cout << "---------------------------------------------------\n"; std::cout << " 1.InitBiTree 2.DestroyBiTree\n"; std::cout << " 3.CreateBiTree 4.ClearBiTree\n"; std::cout << " 5.BiTreeEmpty 6.BiTreeDepth\n"; std::cout << " 7.Root 8.Value\n"; std::cout << " 9.Assign 10.Parent\n"; std::cout << " 11.LeftChild 12.RightChild\n"; std::cout << " 13.LeftSibling 14.RightSibling\n"; std::cout << " 15.InsertChild 16.DeleteChild\n"; std::cout << " 17.PreOrderTraverse 18.InOrderTraverse\n"; std::cout << " 19.PostOrderTraverse 20.LevelOrderTraverse\n"; std::cout << " 21.ChangeBiTree\n"; std::cout << " 0.Exit\n"; std::cout << "---------------------------------------------------\n"; std::cout << "Current using tree: " << tree_index << "\n\n"; std::cout << " Please select your selection: "; std::cin >> choice; // 将字符串转为数字 operation = std::stoi(choice); auto &tree = trees[tree_index]; switch (operation) { case 1: std::cout << "InitBiTree Function\n"; if (tree.InitBiTree() == OK) { std::cout << "Initalize tree succefully.\n"; } else { std::cout << "Initalize tree failed.\n"; } wait(); break; case 2: std::cout << "DestroyBiTree Function\n"; if (tree.DestroyBiTree() == OK) { std::cout << "Destroy tree successfully.\n"; } else { std::cout << "Destroy tree failed.\n"; } wait(); break; case 3: std::cout << "CreateBiTree Function\n"; if (tree.CreateBiTree() == OK) { std::cout << "Create tree successfully.\n"; } else { std::cout << "Create tree failed.\n"; } wait(); break; case 4: std::cout << "ClearBiTree Function\n"; if (tree.ClearBiTree() == OK) { std::cout << "Clear tree successfully.\n"; } else { std::cout << "Clear tree failed.\n"; } wait(); break; case 5: std::cout << "BiTreeEmpty Funtion\n"; if (tree.BiTreeEmpty()) { std::cout << "This tree is empty.\n"; } else { std::cout << "This tree is not empty.\n"; } wait(); break; case 6: std::cout << "BiTreeDepth Function\n"; key = tree.BiTreeDepth(); std::cout << "Tree's depth is: " << key << "\n"; wait(); break; case 7: std::cout << "Root Function\n"; temp_node = tree.Root(); if (temp_node != nullptr) { std::cout << "Get root from tree, value: " << temp_node->value << "\n"; } else { std::cout << "Get root from tree failed.\n"; } wait(); break; case 8: std::cout << "Value Functin\n"; tree.displsy(); std::cout << "Please input key of the node: "; std::cin >> key; value = tree.Value(key); std::cout << "Get value: " << value << "\n"; wait(); break; case 9: std::cout << "Assign Funciton\n"; tree.displsy(); std::cout << "Please input the key of node: "; std::cin >> key; std::cout << "Please input the value to assign: "; std::cin >> value; if (tree.Assign(key, value) == OK) { std::cout << "Assign value successfully.\n"; } else { std::cout << "Assign value failed.\n"; } wait(); break; case 10: std::cout << "Parent Function\n"; tree.displsy(); std::cout << "Please enter the key of node: "; std::cin >> key; temp_node = tree.Parent(key); if (temp_node == nullptr) { std::cout << "Get the parent node failed.\n"; } else { std::cout << "Get the parent node, value: " << temp_node->value << std::endl; } wait(); break; case 11: std::cout << "LeftChildren Function\n"; tree.displsy(); std::cout << "Please enter the key of node: "; std::cin >> key; temp_node = tree.LeftChildren(key); if (temp_node != nullptr) { std::cout << "Get node's left node, value: " << temp_node->value << std::endl; } else { std::cout << "Get left node failed.\n"; } wait(); break; case 12: std::cout << "RightChildren Function\n"; tree.displsy(); std::cout << "Please enter the key of node: "; std::cin >> key; temp_node = tree.RightChildren(key); if (temp_node != nullptr) { std::cout << "Get the right children, value: " << temp_node->value << std::endl; } wait(); break; case 13: std::cout << "LeftSibling Function\n"; tree.displsy(); std::cout << "Please enter the key of node: "; std::cin >> key; temp_node = tree.LeftSibling(key); if (temp_node != nullptr) { std::cout << "Get the left sibling of node, value: " << temp_node->value << "\n"; } else { std::cout << "Get the left sibling filed.\n"; } wait(); break; case 14: std::cout << "RightSibling Function\n"; tree.displsy(); std::cout << "Please enter the key of node: "; std::cin >> key; temp_node = tree.RightSibling(key); if (temp_node != nullptr) { std::cout << "Get the right sibling of node, value: " << temp_node->value << "\n"; } else { std::cout << "Get right siblling failed.\n"; } wait(); break; case 15: std::cout << "InsertChild Function\n"; tree.displsy(); std::cout << "Please enter key of node: "; std::cin >> key; std::cout << "Please enter the tree: "; std::cin >> temp_tree; std::cout << "insert into left or right(0:left, 1:right):"; std::cin >> position; lr = position == 0 ? LR::L : LR::R; if (tree.InsertChild(key, lr, temp_tree) == OK) { std::cout << "Insert child success.\n"; } else { std::cout << "Insert child failed.\n"; } wait(); break; case 16: std::cout << "DeleteChild Functin\n"; tree.displsy(); std::cout << "Please enter key of node: "; std::cin >> key; std::cout << "Delete left or right(0:left, 1:right):"; std::cin >> position; lr = position == 0 ? LR::L : LR::R; if (tree.DeleteChild(key, lr) == OK) { std::cout << "Delete child success.\n"; } else { std::cout << "Delete child failed.\n"; } wait(); break; case 17: std::cout << "PreOrderTraverse Function\n"; if (tree.PreOrderTraverse(visit) == OK) { std::cout << "PreOrderTreverse successfully.\n"; } else { std::cout << "PreOrderTreverse failed.\n"; } wait(); break; case 18: std::cout << "InOrderTraverse Function\n"; if (tree.InOrderTraverse(visit) == OK) { std::cout << "InOrderTreverse successfully.\n"; } else { std::cout << "InOrderTreverse failed.\n"; } wait(); break; case 19: std::cout << "InOrderTreverse Function\n"; if (tree.PostOrderTraverse(visit) == OK) { std::cout << "PostOrderTraverse successfully.\n"; } else { std::cout << "PostOrderTraverse failed.\n"; } wait(); break; case 20: std::cout << "LevelOrderTraverse Function\n"; if (tree.LevelOrderTraverse(visit) == OK) { std::cout << "LevelOrderTraverse successfully.\n"; } else { std::cout << "LevelOrderTraverse failed.\n"; } wait(); break; case 21: std::cout << "ChangeBiTree Function\n"; std::cout << "Please enter index of tree: "; std::cin >> temp_tree_index; if (temp_tree_index < 0 || temp_tree_index >= 100) { std::cout << "Index out of bounds.\n"; } else { tree_index = temp_tree_index; } break; case 0: break; default: break; } } std::cout << "Good Bye.\n"; } #endif // DATASTRUCTURE_TESTBINARYTREE_H
#ifndef DESTROYABLEBODY_HPP #define DESTROYABLEBODY_HPP #include "..\Box2D_v2.0.1\Box2D\Include\Box2D.h" #include <SFML/Graphics.hpp> #include <iostream> #include <sstream> #include <math.h> #include <vector> #include "Object.hpp" #include "TempObjectHandler.hpp" using namespace std; using namespace sf; struct position; class DestroyableBody : public Object{ public: struct position{ b2PolygonDef* polygon; b2Shape* shape; unsigned int positionX; unsigned int positionY; int iterI; //int iterJ; position* left; position* right; position* up; position* down; bool suspended; bool checked; position(){ polygon=0; shape=0; positionX=0; positionY=0; iterI=0; //iterJ=0; left=0; right=0; up=0; down=0; suspended=false; checked=false; } position(unsigned int posX, unsigned int posY, b2PolygonDef* poly){ polygon=poly; shape=0; iterI=0; //iterJ=0; positionX=posX; positionY=posY; left=0; right=0; up=0; down=0; suspended=false; checked=false; } ~position(){ polygon=0; shape=0; if(left){ left->right=0; left=0; } if(right){ right->left=0; right=0; } if(up){ up->down=0; up=0; } if(down){ down->up=0; down=0; } } /*position* position::GetLeft(){ if(left!=NULL)return left; } position* position::GetRight(){ if(right!=NULL)return right; } position* position::GetUp(){ if(up!=NULL)return up; } position* position::GetDown(){ if(down!=NULL)return down; }*/ }; RenderWindow* Window; b2World* world; TempObjectHandler* TOH; int number; bool deleteable; bool breaking; bool isstatic; int iter; int shapecount; int Ilimit; int Jlimit; b2BodyDef destroyablebodyDef; b2Body* destroyablebody; //b2PolygonDef dshapeDef; data destroyablebodydata; //Shape Body; //vector<Shape> Body; vector<position*> positions; vector<position> position_collector; position* first; position* bottom; Image DBodyImg; Sprite DBodySp; Image bulletholeImg1; Image bulletholeImg2; DestroyableBody(RenderWindow* window, b2World* World, TempObjectHandler* toh, float PositionX, float PositionY, float Angle, bool IsStatic); DestroyableBody(RenderWindow* window, b2World* World, TempObjectHandler* toh, float PositionX, float PositionY, float Angle, vector<position> NewPositions, Image image, int ilimit, int jlimit); void Show(); void InputHandling(); void GetNext(position* p); //void GetLeft(position* p); void GetRight(position* p); //void GetUp(position* p); void FindBottom(position* p); void UnCheck(); bool IsUnbroken(position* p); void EliminateShape(b2Shape* shape); void CollectShapes(position* p); void SetNumber(int num); int GetNumber(); }; #endif
#include<bits/stdc++.h> using namespace std; int vet[1000]; int main(){ int t; scanf("%d", &t); while(t--){ int n; scanf("%d", &n); for(int i=0; i<n*4; i++){ scanf("%d", &vet[i]); } sort(vet, vet+(4*n)); n*=4; int valor = 0; if(vet[0] != vet[1] || vet[n-1] != vet[n-2]){ puts("NO"); continue; } valor = vet[0] * vet[n-1]; // printf("valor: %d\n", valor); bool flag = false; for(int i = 0; i < n/4; i++){ if(vet[2*i]!=vet[2*i+1] || vet[n - 2*i - 1] != vet[n - 2*i - 2] || vet[2*i]*vet[n - 2*i - 1] != valor){ puts("NO"); flag = true; break; } } if(!flag){ puts("YES"); } } }
//! Bismillahi-Rahamanirahim. /** ========================================** ** @Author: Md. Abu Farhad ( RUET, CSE'15) ** @Category: /** ========================================**/ #include<bits/stdc++.h> #include<stdio.h> using namespace std; #define ll long long #define scl(n) cin>>n; #define scc(c) cin>>c; #define fr(i,n) for (ll i=0;i<n;i++) #define fr1(i,n) for(ll i=1;i<=n;i++) #define pfl(x) printf("%lld\n",x) #define pb push_back #define l(s) s.size() #define asort(a) sort(a,a+n) #define all(x) (x).begin(), (x).end() #define dsort(a) sort(a,a+n,greater<int>()) #define vasort(v) sort(v.begin(), v.end()); #define vdsort(v) sort(v.begin(), v.end(),greater<int>()); #define uniquee(x) x.erase(unique(x.begin(), x.end()),x.end()) #define pn cout<<endl; #define md 10000007 #define inf 1e18 #define debug cout<<"Monti valo nei "<<endl; #define ps cout<<" "; #define Pi acos(-1.0) #define mem(a,i) memset(a, i, sizeof(a)) #define tcas(i,t) for(ll i=1;i<=t;i++) #define pcas(i) cout<<"Case "<<i<<": "<<endl; #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL) #define conv_string(n) to_string(n) //ll x[10]= {0,-1,-1,1,1,-2,-2,2,2}; //ll y[10]= {0,-2,2,-2,2,-1,1,-1,1}; //vector<ll>cnt(26, 0); ///create fixed 26 sized vector and initialize initially all 0 // sscanf(c, "%s %s", s,s1); // take string buffer and then distribute all value , here take 2 value and distribute ///cin.ignore(); // Need when we take input as a string line before getline(cin,s) //ll bigmod(ll b, ll p, ll md){if(p==0) return 1;if(p%2==1){ return ((b%md)*bigmod(b,p-1,md))%md;} else {ll y=bigmod(b,p/2,md);return (y*y)%md;}} //ll find_all_divisor(ll n){ fr1(i,sqrt(n)){ ll x; if(n % i == 0) { x = n / i; v.pb(i); if(i != x) v.pb(x);}}} ///Every even integer greater than 2 can be represented as the sum of two primes numbers. //count item in array : count(arr,arr+n,'I'); #define N 100006 int main() { fast; ll t; cin>>t; while(t--) { ll m,n,b,c,d,i,j,k,x,y,z,l,q,r; string s1, s2, s3, s4; ll cnt=1,ans=0,sum=0, cn=0,res=0; cin>>n>>m; ll a[n], id=0; map<ll, ll> mp; fr(i, n)cin>>a[i], mp[a[i] ]=i+1; fr1(i, m) { cin>>x; b=mp[x]; if( id>b)ans++; else { ans+=2*(b-i) +1; id=max(id, b); } } cout<<ans<<endl; } return 0; } ///Before submit=> /// *check for integer overflow,array bounds /// *check for n=1
// includes #include <iostream> #include <cstdlib> #include <ctime> // using std's using std::cout; using std::cin; using std::endl; // globals bool quitGame = false; char playerChoice = ' '; int playerChips = 1000; int betAmount = 0; int reelResults[3]; // function prototypes void DisplayPlayerChips(int chips); void Menu(); void EnterBet(); int Random(int low, int high); void Reels(); // main program entry point int main() { // seed random numbers srand((unsigned int)time(NULL)); // Display the Menu Menu(); // output message cout << "Press any key key to exit"; cin.get(); cin.ignore(); return 0; } // function declarations // Display Players Chips void DisplayPlayerChips(int chips) { // assign the value of playerChips to chips chips = playerChips; // output a message cout << "Player's Chips: $" << chips << endl << endl; } // Menu void Menu() { // output message cout << "\t\t\t=================" << endl; cout << "\t\t\tSlot Machine V1.0" << endl; cout << "\t\t\t=================" << endl << endl; // Player Chips DisplayPlayerChips(playerChips); // Menu Options cout << "Press 'P' to [P]lay or 'E' to [E]xit : "; cin >> playerChoice; cout << endl << endl; // while quit game is not equal to true while (!quitGame) { // return appropriate case to players choice switch (playerChoice) { // the user chose to play the game case 'p': case 'P': // output a welcome message cout << "Welcome to your game of slots!" << endl; // Enter your bet choice EnterBet(); break; // the user chose to quit case 'e': case 'E': // exit game cout << "Exiting..." << endl; quitGame = true; break; default: // output a message if user enters an incorrect choice cout << "Sorry you have entered an invalid choice please try again.." << endl << endl; // ignore input that isn't numerical cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); break; } } } // Bet Choice void EnterBet() { // output a message cout << "Please enter your bet :"; // store the users choice cin >> betAmount; cout << endl << endl; // check amounts are valid // if bet amount is less than or equal to zero if (betAmount <= 0) { // tell the user they have entered a wrong amount cout << "Sorry you have entered an incorrect amount please try again..." << endl << endl; } // or if the bet amount is more than the player has else if (betAmount > playerChips) { // tell them they do not have enough chips cout << "Sorry you do not have enough chips..." << endl << endl; } // otherwise.. else { // continue running the program and display the slot reels to the user Reels(); } } // Return Random Numbers int Random(int low, int high) { // create variable to store randomNum int randomNum = 0; // calculate the random number randomNum = low + rand() % ((high + 1) - low); // return the random number return randomNum; } // Seed 3 Random numbers to return as a result for each reel void Reels() { // loop through the 3 reels for (int i = 0; i < 3; i++) { // assign a random number to each of the reels reelResults[i] = Random(2, 7); } // output the result of the random number on each reel cout << "["<< reelResults[0] << "] [" << reelResults[1] << "] [" << reelResults[2] << "]" << endl; // if all 3 reels return the same number if (reelResults[0] == reelResults[1] && reelResults[0] == reelResults[2]) { // pay the player 5 times the amount they have bet betAmount *= 5; // output a message to let them know they have won 5 times the amount cout << "You won 5 times your bet!" << endl << endl; // update the players chips with the new amount playerChips += betAmount; // re-display the amount of chips the player has.. DisplayPlayerChips(playerChips); } // if 2 of the reels match else if (reelResults[0] == reelResults[1] || reelResults[0] == reelResults[2] || reelResults[1] == reelResults[2]) { // pay the player 3 times the amount they have bet betAmount *= 3; // output a message to let them know they have won 3 times the amount cout << "You won 3 times your bet!" << endl << endl; // update the players chips with the new amount playerChips += betAmount; // re-display the amount of chips the player has.. DisplayPlayerChips(playerChips); } else { // output a message letting the user know they didn't win this time cout << "Sorry you didn't win!" << endl << endl; // update the players chips (subtract the bet amount) playerChips -= betAmount; // re-display the amount of chips the player has.. DisplayPlayerChips(playerChips); // additional check!! // if the player has no chips left or the player presses 'e/E' to quit if (playerChips <= 0) { // exit game (as we don't want to keep asking them to enter a bet when they can't) cout << "Exiting..." << endl; // set quit game equal to true quitGame = true; } } }