text
stringlengths
54
60.6k
<commit_before>// arithmetic_multiply.cpp: functional tests for multiplication // // Copyright (C) 2017 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "stdafx.h" // when you define POSIT_VERBOSE_OUTPUT executing an MUL the code will print intermediate results //#define POSIT_VERBOSE_OUTPUT #define POSIT_TRACE_MUL // minimum set of include files to reflect source code dependencies #include "../../posit/posit.hpp" #include "../../posit/posit_manipulators.hpp" #include "../tests/test_helpers.hpp" #include "../tests/posit_test_helpers.hpp" using namespace std; using namespace sw::unum; // generate specific test case that you can trace with the trace conditions in posit.h // for most bugs they are traceable with _trace_conversion and _trace_mul template<size_t nbits, size_t es, typename Ty> void GenerateTestCase(Ty a, Ty b) { Ty ref; posit<nbits, es> pa, pb, pref, pmul; pa = a; pb = b; ref = a * b; pref = ref; pmul = pa * pb; std::cout << std::setprecision(nbits - 2); std::cout << std::setw(nbits) << a << " * " << std::setw(nbits) << b << " = " << std::setw(nbits) << ref << std::endl; std::cout << pa.get() << " * " << pb.get() << " = " << pmul.get() << " (reference: " << pref.get() << ") "; std::cout << (pref == pmul ? "PASS" : "FAIL") << std::endl << std::endl; std::cout << std::setprecision(5); } #define MANUAL_TESTING 0 #define STRESS_TESTING 0 int main(int argc, char** argv) try { bool bReportIndividualTestCases = true; int nrOfFailedTestCases = 0; cout << "Posit multiplication validation" << endl; std::string tag = "Multiplication failed: "; #if MANUAL_TESTING // generate individual testcases to hand trace/debug float fa, fb; fa = 0.0f; fb = INFINITY; std::cout << fa << " " << fb << std::endl; GenerateTestCase<4,0, float>(fa, fb); GenerateTestCase<16, 1, float>(float(minpos_value<16, 1>()), float(maxpos_value<16, 1>())); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<3, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<3,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<4,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<5,0>", "multiplication"); #else nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 0>(tag, bReportIndividualTestCases), "posit<7,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 1>(tag, bReportIndividualTestCases), "posit<7,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 2>(tag, bReportIndividualTestCases), "posit<7,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 3>(tag, bReportIndividualTestCases), "posit<7,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<16, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<16,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<24, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<24,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<32, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<32,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<32, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<32,2>", "multiplication"); #if STRESS_TESTING // nbits=48 is also showing failures nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<48, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<48,2>", "multiplication"); // disabled until we can get long doubles to work: -> test is 64bit_posits.cpp // nbits=64 requires long double compiler support //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,2>", "multiplication"); //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 3>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,3>", "multiplication"); // posit<64,4> is hitting subnormal numbers //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 4>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 0>(tag, bReportIndividualTestCases), "posit<10,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 1>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 2>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 3>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<12, 1>(tag, bReportIndividualTestCases), "posit<12,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<14, 1>(tag, bReportIndividualTestCases), "posit<14,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "multiplication"); #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { cerr << msg << endl; return EXIT_FAILURE; } catch (...) { cerr << "Caught unknown exception" << endl; return EXIT_FAILURE; } <commit_msg>Adding a set of tough testcases<commit_after>// arithmetic_multiply.cpp: functional tests for multiplication // // Copyright (C) 2017 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include "stdafx.h" // when you define POSIT_VERBOSE_OUTPUT executing an MUL the code will print intermediate results #define POSIT_VERBOSE_OUTPUT //#define POSIT_TRACE_MUL #define POSIT_TRACE_CONVERSION // minimum set of include files to reflect source code dependencies #include "../../posit/posit.hpp" #include "../../posit/posit_manipulators.hpp" #include "../tests/test_helpers.hpp" #include "../tests/posit_test_helpers.hpp" using namespace std; using namespace sw::unum; // generate specific test case that you can trace with the trace conditions in posit.h // for most bugs they are traceable with _trace_conversion and _trace_mul template<size_t nbits, size_t es, typename Ty> void GenerateTestCase(Ty a, Ty b) { Ty ref; posit<nbits, es> pa, pb, pref, pmul; pa = a; pb = b; ref = a * b; pref = ref; pmul = pa * pb; std::cout << std::setprecision(nbits - 2); std::cout << std::setw(nbits) << a << " * " << std::setw(nbits) << b << " = " << std::setw(nbits) << ref << std::endl; std::cout << pa.get() << " * " << pb.get() << " = " << pmul.get() << " (reference: " << pref.get() << ") "; std::cout << (pref == pmul ? "PASS" : "FAIL") << std::endl << std::endl; std::cout << std::setprecision(5); } template<size_t nbits, size_t es> void GenerateTestCase( posit<nbits,es> pa, posit<nbits,es> pb, posit<nbits, es> pref) { double a = double(pa); double b = double(pb); double ref = a * b; //posit<nbits, es> pref = ref; posit<nbits, es> pmul = pa * pb; std::cout << std::setprecision(nbits - 2); std::cout << std::setw(nbits) << a << " * " << std::setw(nbits) << b << " = " << std::setw(nbits) << ref << std::endl; std::cout << pa.get() << " * " << pb.get() << " = " << pmul.get() << " (reference: " << pref.get() << ") "; std::cout << (pref == pmul ? "PASS" : "FAIL") << std::endl << std::endl; std::cout << std::setprecision(5); } /* Operand1 Operand2 bad golden ======== ======== ======== ======== 00000002 93ff6977 fffffffa fffffff9 00000002 b61e2f1f fffffffe fffffffd 308566ef 7fffffff 7ffffffe 7fffffff 308566ef 80000001 80000002 80000001 503f248b 7ffffffe 7ffffffe 7fffffff 503f248b 80000002 80000002 80000001 7ffffffe 503f248b 7ffffffe 7fffffff 7fffffff 308566ef 7ffffffe 7fffffff 80000001 308566ef 80000002 80000001 80000002 503f248b 80000002 80000001 93ff6977 00000002 fffffffa fffffff9 b61e2f1f 00000002 fffffffe fffffffd b61e2f1f fffffffe 00000002 00000003 fffffffe b61e2f1f 00000002 00000003 */ void DifficultRoundingCases() { posit<32, 2> a, b, bad, pref; std::vector<uint32_t> cases = { 0x00000002, 0x93ff6977, 0xfffffffa, 0xfffffff9, 0x00000002, 0xb61e2f1f, 0xfffffffe, 0xfffffffd, 0x308566ef, 0x7fffffff, 0x7ffffffe, 0x7fffffff, 0x308566ef, 0x80000001, 0x80000002, 0x80000001, 0x503f248b, 0x7ffffffe, 0x7ffffffe, 0x7fffffff, 0x503f248b, 0x80000002, 0x80000002, 0x80000001, 0x7ffffffe, 0x503f248b, 0x7ffffffe, 0x7fffffff, 0x7fffffff, 0x308566ef, 0x7ffffffe, 0x7fffffff, 0x80000001, 0x308566ef, 0x80000002, 0x80000001, 0x80000002, 0x503f248b, 0x80000002, 0x80000001, 0x93ff6977, 0x00000002, 0xfffffffa, 0xfffffff9, 0xb61e2f1f, 0x00000002, 0xfffffffe, 0xfffffffd, 0xb61e2f1f, 0xfffffffe, 0x00000002, 0x00000003, 0xfffffffe, 0xb61e2f1f, 0x00000002, 0x00000003, }; unsigned nrOfTests = cases.size() / 4; for (unsigned i = 0; i < cases.size(); i+= 4) { a.set_raw_bits(cases[i]); b.set_raw_bits(cases[i + 1]); pref.set_raw_bits(cases[i + 3]); //cout << a.get() << " * " << b.get() << " = " << pref.get() << endl; GenerateTestCase(a, b, pref); } } #define MANUAL_TESTING 0 #define STRESS_TESTING 0 int main(int argc, char** argv) try { bool bReportIndividualTestCases = true; int nrOfFailedTestCases = 0; cout << "Posit multiplication validation" << endl; std::string tag = "Multiplication failed: "; #if MANUAL_TESTING // generate individual testcases to hand trace/debug /* float fa, fb; fa = 0.0f; fb = INFINITY; std::cout << fa << " " << fb << std::endl; GenerateTestCase<4,0, float>(fa, fb); GenerateTestCase<16, 1, float>(float(minpos_value<16, 1>()), float(maxpos_value<16, 1>())); */ DifficultRoundingCases(); return 0; nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<3, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<3,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<4,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 0>("Manual Testing: ", bReportIndividualTestCases), "posit<5,0>", "multiplication"); #else nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<3, 0>(tag, bReportIndividualTestCases), "posit<3,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 0>(tag, bReportIndividualTestCases), "posit<4,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<4, 1>(tag, bReportIndividualTestCases), "posit<4,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 0>(tag, bReportIndividualTestCases), "posit<5,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 1>(tag, bReportIndividualTestCases), "posit<5,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<5, 2>(tag, bReportIndividualTestCases), "posit<5,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 0>(tag, bReportIndividualTestCases), "posit<6,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 1>(tag, bReportIndividualTestCases), "posit<6,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 2>(tag, bReportIndividualTestCases), "posit<6,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<6, 3>(tag, bReportIndividualTestCases), "posit<6,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 0>(tag, bReportIndividualTestCases), "posit<7,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 1>(tag, bReportIndividualTestCases), "posit<7,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 2>(tag, bReportIndividualTestCases), "posit<7,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 3>(tag, bReportIndividualTestCases), "posit<7,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<7, 4>(tag, bReportIndividualTestCases), "posit<7,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 0>(tag, bReportIndividualTestCases), "posit<8,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 1>(tag, bReportIndividualTestCases), "posit<8,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 2>(tag, bReportIndividualTestCases), "posit<8,2>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 3>(tag, bReportIndividualTestCases), "posit<8,3>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 4>(tag, bReportIndividualTestCases), "posit<8,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<8, 5>(tag, bReportIndividualTestCases), "posit<8,5>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<16, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<16,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<24, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<24,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<32, 1>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<32,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<32, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<32,2>", "multiplication"); #if STRESS_TESTING // nbits=48 is also showing failures nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<48, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<48,2>", "multiplication"); // disabled until we can get long doubles to work: -> test is 64bit_posits.cpp // nbits=64 requires long double compiler support //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 2>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,2>", "multiplication"); //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 3>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,3>", "multiplication"); // posit<64,4> is hitting subnormal numbers //nrOfFailedTestCases += ReportTestResult(ValidateThroughRandoms<64, 4>(tag, bReportIndividualTestCases, OPCODE_MUL, 1000), "posit<64,4>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 0>(tag, bReportIndividualTestCases), "posit<10,0>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 1>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 2>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<10, 3>(tag, bReportIndividualTestCases), "posit<10,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<12, 1>(tag, bReportIndividualTestCases), "posit<12,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<14, 1>(tag, bReportIndividualTestCases), "posit<14,1>", "multiplication"); nrOfFailedTestCases += ReportTestResult(ValidateMultiplication<16, 1>(tag, bReportIndividualTestCases), "posit<16,1>", "multiplication"); #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { cerr << msg << endl; return EXIT_FAILURE; } catch (...) { cerr << "Caught unknown exception" << endl; return EXIT_FAILURE; } <|endoftext|>
<commit_before>#include <smartref/smartref.h> REFLECTABLE(member); namespace tests { using smartref::using_; //! These tests check for existence of the member() member-function. namespace test_existence { template<typename T> constexpr auto has_member(int) -> decltype(std::declval<T>().member(), bool{}) {return true;} template<typename T> constexpr auto has_member(...) {return false;} struct EmptyClass {}; struct NonConstClass { void member() {} }; struct ConstClass { void member() const {} }; struct MixedClass { void member() {} void member() const {} }; //////////////////////////////// // non-const member functions // //////////////////////////////// static_assert(!has_member<EmptyClass>(0), "TEST FAILED: EmptyClass seems to have a member-function!"); static_assert(!has_member<using_<EmptyClass>>(0), "TEST FAILED: using_<EmptyClass> seems to have a member-function!"); static_assert(has_member<NonConstClass>(0), "TEST FAILED: NonConstClass doesn't seem to have a member-function!"); static_assert(has_member<using_<NonConstClass>>(0), "TEST FAILED: using_<NonConstClass> doesn't seem to have a member-function!"); static_assert(has_member<ConstClass>(0), "TEST FAILED: ConstClass doesn't seem to have a member-function!"); // TODO: This reifies a non-const member-function that delegates to the const member-function // It should reify a const member-function static_assert(has_member<using_<ConstClass>>(0), "TEST FAILED: using_<ConstClass> doesn't seem to have a member-function!"); static_assert(has_member<MixedClass>(0), "TEST FAILED: MixedClass doesn't seem to have a member-function!"); static_assert(has_member<using_<MixedClass>>(0), "TEST FAILED: using_<MixedClass> doesn't seem to have a member-function!"); //////////////////////////// // const member functions // //////////////////////////// static_assert(!has_member<const EmptyClass>(0), "TEST FAILED: const EmptyClass seems to have a const member-function!"); static_assert(!has_member<const using_<EmptyClass>>(0), "TEST FAILED: const using_<EmptyClass> seems to have a const member-function!"); static_assert(!has_member<const NonConstClass>(0), "TEST FAILED: const NonConstClass seems to have a const member-function!"); static_assert(!has_member<const using_<NonConstClass>>(0), "TEST FAILED: const using_<NonConstClass> seem to have a const member-function!"); } // namespace test_existence } // namespace tests <commit_msg>Renamed classes to emphasize it's about the member functions.<commit_after>#include <smartref/smartref.h> REFLECTABLE(member); namespace tests { using smartref::using_; //! These tests check for existence of the member() member-function. namespace test_existence { template<typename T> constexpr auto has_member(int) -> decltype(std::declval<T>().member(), bool{}) {return true;} template<typename T> constexpr auto has_member(...) {return false;} struct EmptyClass {}; struct NonConstMemberClass { void member() {} }; struct ConstMemberClass { void member() const {} }; struct MixedMemberClass { void member() {} void member() const {} }; //////////////////////////////// // non-const member functions // //////////////////////////////// static_assert(!has_member<EmptyClass>(0), "TEST FAILED: EmptyClass seems to have a member-function!"); static_assert(!has_member<using_<EmptyClass>>(0), "TEST FAILED: using_<EmptyClass> seems to have a member-function!"); static_assert(has_member<NonConstMemberClass>(0), "TEST FAILED: NonConstMemberClass doesn't seem to have a member-function!"); static_assert(has_member<using_<NonConstMemberClass>>(0), "TEST FAILED: using_<NonConstMemberClass> doesn't seem to have a member-function!"); static_assert(has_member<ConstMemberClass>(0), "TEST FAILED: ConstMemberClass doesn't seem to have a member-function!"); // TODO: This reifies a non-const member-function that delegates to the const member-function // It should reify a const member-function static_assert(has_member<using_<ConstMemberClass>>(0), "TEST FAILED: using_<ConstMemberClass> doesn't seem to have a member-function!"); static_assert(has_member<MixedMemberClass>(0), "TEST FAILED: MixedMemberClass doesn't seem to have a member-function!"); static_assert(has_member<using_<MixedMemberClass>>(0), "TEST FAILED: using_<MixedMemberClass> doesn't seem to have a member-function!"); //////////////////////////// // const member functions // //////////////////////////// static_assert(!has_member<const EmptyClass>(0), "TEST FAILED: const EmptyClass seems to have a const member-function!"); static_assert(!has_member<const using_<EmptyClass>>(0), "TEST FAILED: const using_<EmptyClass> seems to have a const member-function!"); static_assert(!has_member<const NonConstMemberClass>(0), "TEST FAILED: const NonConstMemberClass seems to have a const member-function!"); static_assert(!has_member<const using_<NonConstMemberClass>>(0), "TEST FAILED: const using_<NonConstMemberClass> seem to have a const member-function!"); } // namespace test_existence } // namespace tests <|endoftext|>
<commit_before>#include <clpeak.h> #include <cstring> #define MSTRINGIFY(...) #__VA_ARGS__ static const char *stringifiedKernels = #include "global_bandwidth_kernels.cl" #include "compute_sp_kernels.cl" #include "compute_hp_kernels.cl" #include "compute_dp_kernels.cl" #include "compute_integer_kernels.cl" ; static const char *stringifiedKernelsNoInt = #include "global_bandwidth_kernels.cl" #include "compute_sp_kernels.cl" #include "compute_hp_kernels.cl" #include "compute_dp_kernels.cl" ; #ifdef USE_STUB_OPENCL // Prototype extern "C" { void stubOpenclReset(); } #endif clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false), isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true), specifiedPlatform(0), specifiedDevice(0) { } clPeak::~clPeak() { if(log) delete log; } int clPeak::runAll() { try { #ifdef USE_STUB_OPENCL stubOpenclReset(); #endif vector<cl::Platform> platforms; cl::Platform::get(&platforms); log->xmlOpenTag("clpeak"); log->xmlAppendAttribs("os", OS_NAME); for(size_t p=0; p < platforms.size(); p++) { if(forcePlatform && (p != specifiedPlatform)) continue; std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>(); trimString(platformName); log->print(NEWLINE "Platform: " + platformName + NEWLINE); log->xmlOpenTag("platform"); log->xmlAppendAttribs("name", platformName); bool isApple = (platformName.find("Apple") != std::string::npos)? true: false; cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[p])(), 0 }; cl::Context ctx(CL_DEVICE_TYPE_ALL, cps); vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); cl::Program prog; // FIXME Disabling integer compute tests on apple platform // Causes Segmentation fault: 11 if(isApple) { cl::Program::Sources source(1, make_pair(stringifiedKernelsNoInt, (strlen(stringifiedKernelsNoInt)+1))); isComputeInt = false; prog = cl::Program(ctx, source); } else { cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1))); prog = cl::Program(ctx, source); } for(size_t d=0; d < devices.size(); d++) { if(forceDevice && (d != specifiedDevice)) continue; device_info_t devInfo = getDeviceInfo(devices[d]); log->print(TAB "Device: " + devInfo.deviceName + NEWLINE); log->print(TAB TAB "Driver version : "); log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE); log->print(TAB TAB "Compute units : "); log->print(devInfo.numCUs); log->print(NEWLINE); log->print(TAB TAB "Clock frequency : "); log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE); log->xmlOpenTag("device"); log->xmlAppendAttribs("name", devInfo.deviceName); log->xmlAppendAttribs("driver_version", devInfo.driverVersion); log->xmlAppendAttribs("compute_units", devInfo.numCUs); log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq); log->xmlAppendAttribs("clock_frequency_unit", "MHz"); try { vector<cl::Device> dev = {devices[d]}; prog.build(dev, BUILD_OPTIONS); } catch (cl::Error &error) { UNUSED(error); log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d]) + NEWLINE NEWLINE); continue; } cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE); runGlobalBandwidthTest(queue, prog, devInfo); runComputeSP(queue, prog, devInfo); runComputeHP(queue, prog, devInfo); runComputeDP(queue, prog, devInfo); runComputeInteger(queue, prog, devInfo); runTransferBandwidthTest(queue, prog, devInfo); runKernelLatency(queue, prog, devInfo); log->print(NEWLINE); log->xmlCloseTag(); // device } log->xmlCloseTag(); // platform } log->xmlCloseTag(); // clpeak } catch(cl::Error &error) { stringstream ss; ss << error.what() << " (" << error.err() << ")" NEWLINE; log->print(ss.str()); // skip error for no platform if(strcmp(error.what(), "clGetPlatformIDs") == 0) { log->print("no platforms found" NEWLINE); } else { return -1; } } return 0; } float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters) { float timed = 0; // Dummy calls queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.finish(); if(useEventTimer) { for(uint i=0; i<iters; i++) { cl::Event timeEvent; queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent); queue.finish(); timed += timeInUS(timeEvent); } } else // std timer { Timer timer; timer.start(); for(uint i=0; i<iters; i++) { queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.flush(); } queue.finish(); timed = timer.stopAndTime(); } return (timed / static_cast<float>(iters)); } <commit_msg>remove int kernel restriction for apple<commit_after>#include <clpeak.h> #include <cstring> #define MSTRINGIFY(...) #__VA_ARGS__ static const char *stringifiedKernels = #include "global_bandwidth_kernels.cl" #include "compute_sp_kernels.cl" #include "compute_hp_kernels.cl" #include "compute_dp_kernels.cl" #include "compute_integer_kernels.cl" ; #ifdef USE_STUB_OPENCL // Prototype extern "C" { void stubOpenclReset(); } #endif clPeak::clPeak(): forcePlatform(false), forceDevice(false), useEventTimer(false), isGlobalBW(true), isComputeSP(true), isComputeDP(true), isComputeInt(true), isTransferBW(true), isKernelLatency(true), specifiedPlatform(0), specifiedDevice(0) { } clPeak::~clPeak() { if(log) delete log; } int clPeak::runAll() { try { #ifdef USE_STUB_OPENCL stubOpenclReset(); #endif vector<cl::Platform> platforms; cl::Platform::get(&platforms); log->xmlOpenTag("clpeak"); log->xmlAppendAttribs("os", OS_NAME); for(size_t p=0; p < platforms.size(); p++) { if(forcePlatform && (p != specifiedPlatform)) continue; std::string platformName = platforms[p].getInfo<CL_PLATFORM_NAME>(); trimString(platformName); log->print(NEWLINE "Platform: " + platformName + NEWLINE); log->xmlOpenTag("platform"); log->xmlAppendAttribs("name", platformName); cl_context_properties cps[3] = { CL_CONTEXT_PLATFORM, (cl_context_properties)(platforms[p])(), 0 }; cl::Context ctx(CL_DEVICE_TYPE_ALL, cps); vector<cl::Device> devices = ctx.getInfo<CL_CONTEXT_DEVICES>(); cl::Program::Sources source(1, make_pair(stringifiedKernels, (strlen(stringifiedKernels)+1))); cl::Program prog = cl::Program(ctx, source); for(size_t d=0; d < devices.size(); d++) { if(forceDevice && (d != specifiedDevice)) continue; device_info_t devInfo = getDeviceInfo(devices[d]); log->print(TAB "Device: " + devInfo.deviceName + NEWLINE); log->print(TAB TAB "Driver version : "); log->print(devInfo.driverVersion); log->print(" (" OS_NAME ")" NEWLINE); log->print(TAB TAB "Compute units : "); log->print(devInfo.numCUs); log->print(NEWLINE); log->print(TAB TAB "Clock frequency : "); log->print(devInfo.maxClockFreq); log->print(" MHz" NEWLINE); log->xmlOpenTag("device"); log->xmlAppendAttribs("name", devInfo.deviceName); log->xmlAppendAttribs("driver_version", devInfo.driverVersion); log->xmlAppendAttribs("compute_units", devInfo.numCUs); log->xmlAppendAttribs("clock_frequency", devInfo.maxClockFreq); log->xmlAppendAttribs("clock_frequency_unit", "MHz"); try { vector<cl::Device> dev = {devices[d]}; prog.build(dev, BUILD_OPTIONS); } catch (cl::Error &error) { UNUSED(error); log->print(TAB TAB "Build Log: " + prog.getBuildInfo<CL_PROGRAM_BUILD_LOG>(devices[d]) + NEWLINE NEWLINE); continue; } cl::CommandQueue queue = cl::CommandQueue(ctx, devices[d], CL_QUEUE_PROFILING_ENABLE); runGlobalBandwidthTest(queue, prog, devInfo); runComputeSP(queue, prog, devInfo); runComputeHP(queue, prog, devInfo); runComputeDP(queue, prog, devInfo); runComputeInteger(queue, prog, devInfo); runTransferBandwidthTest(queue, prog, devInfo); runKernelLatency(queue, prog, devInfo); log->print(NEWLINE); log->xmlCloseTag(); // device } log->xmlCloseTag(); // platform } log->xmlCloseTag(); // clpeak } catch(cl::Error &error) { stringstream ss; ss << error.what() << " (" << error.err() << ")" NEWLINE; log->print(ss.str()); // skip error for no platform if(strcmp(error.what(), "clGetPlatformIDs") == 0) { log->print("no platforms found" NEWLINE); } else { return -1; } } return 0; } float clPeak::run_kernel(cl::CommandQueue &queue, cl::Kernel &kernel, cl::NDRange &globalSize, cl::NDRange &localSize, uint iters) { float timed = 0; // Dummy calls queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.finish(); if(useEventTimer) { for(uint i=0; i<iters; i++) { cl::Event timeEvent; queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize, NULL, &timeEvent); queue.finish(); timed += timeInUS(timeEvent); } } else // std timer { Timer timer; timer.start(); for(uint i=0; i<iters; i++) { queue.enqueueNDRangeKernel(kernel, cl::NullRange, globalSize, localSize); queue.flush(); } queue.finish(); timed = timer.stopAndTime(); } return (timed / static_cast<float>(iters)); } <|endoftext|>
<commit_before>/* */ #ifndef COMMON_HPP_INCLUDED #define COMMON_HPP_INCLUDED #include <iostream> #include <vector> #include <map> #include <cassert> #include <sstream> #include <memory> #define FMT(ss) (dynamic_cast< ::std::stringstream&>(::std::stringstream() << ss).str()) // XXX: Evil hack - Define 'mv$' to be ::std::move #define mv$(x) ::std::move(x) #define box$(x) ::make_unique_ptr(::std::move(x)) #define rc_new$(x) ::make_shared_ptr(::std::move(x)) #include "include/debug.hpp" #include "include/rustic.hpp" // slice and option #include "include/compile_error.hpp" template<typename T> ::std::unique_ptr<T> make_unique_ptr(T&& v) { return ::std::unique_ptr<T>(new T(mv$(v))); } template<typename T> ::std::shared_ptr<T> make_shared_ptr(T&& v) { return ::std::shared_ptr<T>(new T(mv$(v))); } template<typename T> ::std::vector<T> make_vec1(T&& v) { ::std::vector<T> rv; rv.push_back( mv$(v) ); return rv; } template<typename T> ::std::vector<T> make_vec2(T v1, T v2) { ::std::vector<T> rv; rv.reserve(2); rv.push_back( mv$(v1) ); rv.push_back( mv$(v2) ); return rv; } enum Ordering { OrdLess, OrdEqual, OrdGreater, }; static inline Ordering ord(bool l, bool r) { if(l == r) return OrdEqual; else if( l ) return OrdGreater; else return OrdLess; } static inline Ordering ord(unsigned l, unsigned r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } static inline Ordering ord(::std::uintptr_t l, ::std::uintptr_t r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } static inline Ordering ord(const ::std::string& l, const ::std::string& r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } template<typename T> Ordering ord(const T& l, const T& r) { return l.ord(r); } template<typename T, typename U> Ordering ord(const ::std::pair<T,U>& l, const ::std::pair<T,U>& r) { Ordering rv; rv = ::ord(l.first, r.first); if(rv != OrdEqual) return rv; rv = ::ord(l.second, r.second); return rv; } template<typename T> Ordering ord(const ::std::vector<T>& l, const ::std::vector<T>& r) { unsigned int i = 0; for(const auto& it : l) { if( i >= r.size() ) return OrdGreater; auto rv = ::ord( it, r[i] ); if( rv != OrdEqual ) return rv; i ++; } return OrdEqual; } template<typename T, typename U> Ordering ord(const ::std::map<T,U>& l, const ::std::map<T,U>& r) { auto r_it = r.begin(); for(const auto& le : l) { if( r_it == r.end() ) return OrdGreater; auto rv = ::ord( le, *r_it ); if( rv != OrdEqual ) return rv; ++ r_it; } return OrdEqual; } #define ORD(a,b) do { Ordering ORD_rv = ::ord(a,b); if( ORD_rv != ::OrdEqual ) return ORD_rv; } while(0) template <typename T> struct LList { const LList* m_prev; T m_item; LList(): m_prev(nullptr) {} LList(const LList* prev, T item): m_prev(prev), m_item( ::std::move(item) ) { } LList end() const { return LList(); } LList begin() const { return *this; } bool operator==(const LList& x) { return m_prev == x.m_prev; } bool operator!=(const LList& x) { return m_prev != x.m_prev; } void operator++() { assert(m_prev); *this = *m_prev; } const T& operator*() const { return m_item; } }; template<typename T> struct Join { const char *sep; const ::std::vector<T>& v; friend ::std::ostream& operator<<(::std::ostream& os, const Join& j) { if( j.v.size() > 0 ) os << j.v[0]; for( unsigned int i = 1; i < j.v.size(); i ++ ) os << j.sep << j.v[i]; return os; } }; template<typename T> inline Join<T> join(const char *sep, const ::std::vector<T> v) { return Join<T>({ sep, v }); } namespace std { template <typename T> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::vector<T*>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << *i; } } return os; } template <typename T> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::vector<T>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i; } } return os; } template <typename T, typename U> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::pair<T,U>& v) { os << "(" << v.first << ", " << v.second << ")"; return os; } template <typename T, typename U, class Cmp> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::map<T,U,Cmp>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i.first << ": " << i.second; } } return os; } template <typename T, typename U, class Cmp> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::multimap<T,U,Cmp>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i.first << ": " << i.second; } } return os; } } // ------------------------------------------------------------------- // --- Reversed iterable template <typename T> struct reversion_wrapper { T& iterable; }; template <typename T> //auto begin (reversion_wrapper<T> w) { return ::std::rbegin(w.iterable); } auto begin (reversion_wrapper<T> w) { return w.iterable.rbegin(); } template <typename T> //auto end (reversion_wrapper<T> w) { return ::std::rend(w.iterable); } auto end (reversion_wrapper<T> w) { return w.iterable.rend(); } template <typename T> reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; } #endif <commit_msg>common - Add print for std::set<commit_after>/* */ #ifndef COMMON_HPP_INCLUDED #define COMMON_HPP_INCLUDED #include <iostream> #include <vector> #include <map> #include <set> #include <cassert> #include <sstream> #include <memory> #define FMT(ss) (dynamic_cast< ::std::stringstream&>(::std::stringstream() << ss).str()) // XXX: Evil hack - Define 'mv$' to be ::std::move #define mv$(x) ::std::move(x) #define box$(x) ::make_unique_ptr(::std::move(x)) #define rc_new$(x) ::make_shared_ptr(::std::move(x)) #include "include/debug.hpp" #include "include/rustic.hpp" // slice and option #include "include/compile_error.hpp" template<typename T> ::std::unique_ptr<T> make_unique_ptr(T&& v) { return ::std::unique_ptr<T>(new T(mv$(v))); } template<typename T> ::std::shared_ptr<T> make_shared_ptr(T&& v) { return ::std::shared_ptr<T>(new T(mv$(v))); } template<typename T> ::std::vector<T> make_vec1(T&& v) { ::std::vector<T> rv; rv.push_back( mv$(v) ); return rv; } template<typename T> ::std::vector<T> make_vec2(T v1, T v2) { ::std::vector<T> rv; rv.reserve(2); rv.push_back( mv$(v1) ); rv.push_back( mv$(v2) ); return rv; } enum Ordering { OrdLess, OrdEqual, OrdGreater, }; static inline Ordering ord(bool l, bool r) { if(l == r) return OrdEqual; else if( l ) return OrdGreater; else return OrdLess; } static inline Ordering ord(unsigned l, unsigned r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } static inline Ordering ord(::std::uintptr_t l, ::std::uintptr_t r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } static inline Ordering ord(const ::std::string& l, const ::std::string& r) { if(l == r) return OrdEqual; else if( l > r ) return OrdGreater; else return OrdLess; } template<typename T> Ordering ord(const T& l, const T& r) { return l.ord(r); } template<typename T, typename U> Ordering ord(const ::std::pair<T,U>& l, const ::std::pair<T,U>& r) { Ordering rv; rv = ::ord(l.first, r.first); if(rv != OrdEqual) return rv; rv = ::ord(l.second, r.second); return rv; } template<typename T> Ordering ord(const ::std::vector<T>& l, const ::std::vector<T>& r) { unsigned int i = 0; for(const auto& it : l) { if( i >= r.size() ) return OrdGreater; auto rv = ::ord( it, r[i] ); if( rv != OrdEqual ) return rv; i ++; } return OrdEqual; } template<typename T, typename U> Ordering ord(const ::std::map<T,U>& l, const ::std::map<T,U>& r) { auto r_it = r.begin(); for(const auto& le : l) { if( r_it == r.end() ) return OrdGreater; auto rv = ::ord( le, *r_it ); if( rv != OrdEqual ) return rv; ++ r_it; } return OrdEqual; } #define ORD(a,b) do { Ordering ORD_rv = ::ord(a,b); if( ORD_rv != ::OrdEqual ) return ORD_rv; } while(0) template <typename T> struct LList { const LList* m_prev; T m_item; LList(): m_prev(nullptr) {} LList(const LList* prev, T item): m_prev(prev), m_item( ::std::move(item) ) { } LList end() const { return LList(); } LList begin() const { return *this; } bool operator==(const LList& x) { return m_prev == x.m_prev; } bool operator!=(const LList& x) { return m_prev != x.m_prev; } void operator++() { assert(m_prev); *this = *m_prev; } const T& operator*() const { return m_item; } }; template<typename T> struct Join { const char *sep; const ::std::vector<T>& v; friend ::std::ostream& operator<<(::std::ostream& os, const Join& j) { if( j.v.size() > 0 ) os << j.v[0]; for( unsigned int i = 1; i < j.v.size(); i ++ ) os << j.sep << j.v[i]; return os; } }; template<typename T> inline Join<T> join(const char *sep, const ::std::vector<T> v) { return Join<T>({ sep, v }); } namespace std { template <typename T> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::vector<T*>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << *i; } } return os; } template <typename T> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::vector<T>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i; } } return os; } template <typename T> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::set<T>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i; } } return os; } template <typename T, typename U> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::pair<T,U>& v) { os << "(" << v.first << ", " << v.second << ")"; return os; } template <typename T, typename U, class Cmp> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::map<T,U,Cmp>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i.first << ": " << i.second; } } return os; } template <typename T, typename U, class Cmp> inline ::std::ostream& operator<<(::std::ostream& os, const ::std::multimap<T,U,Cmp>& v) { if( v.size() > 0 ) { bool is_first = true; for( const auto& i : v ) { if(!is_first) os << ", "; is_first = false; os << i.first << ": " << i.second; } } return os; } } // ------------------------------------------------------------------- // --- Reversed iterable template <typename T> struct reversion_wrapper { T& iterable; }; template <typename T> //auto begin (reversion_wrapper<T> w) { return ::std::rbegin(w.iterable); } auto begin (reversion_wrapper<T> w) { return w.iterable.rbegin(); } template <typename T> //auto end (reversion_wrapper<T> w) { return ::std::rend(w.iterable); } auto end (reversion_wrapper<T> w) { return w.iterable.rend(); } template <typename T> reversion_wrapper<T> reverse (T&& iterable) { return { iterable }; } #endif <|endoftext|>
<commit_before>/* Resembla: Word-based Japanese similar sentence search library https://github.com/tuem/resembla Copyright 2017 Takashi Uemura 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. */ #ifndef __HIERARCHICAL_RESEMBLA_HPP__ #define __HIERARCHICAL_RESEMBLA_HPP__ #include <string> #include <vector> #include <memory> #include <unordered_map> #include <fstream> #include <resembla/resembla_interface.hpp> #include <resembla/reranker.hpp> namespace resembla { template<class Preprocessor, class ScoreFunction> class HierarchicalResembla: public ResemblaInterface { public: HierarchicalResembla(std::shared_ptr<ResemblaInterface> resembla, size_t max_candidate, std::shared_ptr<Preprocessor> preprocess, std::shared_ptr<ScoreFunction> score_func, std::string corpus_path = "", size_t col = 2): resembla(resembla), max_candidate(max_candidate), preprocess(preprocess), score_func(score_func), reranker(), preprocess_corpus(!corpus_path.empty()) { if(preprocess_corpus){ loadCorpusFeatures(corpus_path, col); } } std::vector<response_type> getSimilarTexts(const string_type& input, size_t max_response, double threshold) { // extract candidates using original resembla std::vector<WorkData> candidates; auto original_results = resembla->getSimilarTexts(input, max_candidate, threshold); for(const auto& r: original_results){ candidates.push_back(std::make_pair(r.text, (*preprocess)(r, preprocess_corpus ? corpus_features[r.text] : decltype((*preprocess)(r.text))()))); } // rerank by its own metric WorkData input_data = std::make_pair(input, (*preprocess)(input)); auto reranked = reranker.rerank(input_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ if(r.second < threshold || results.size() >= max_response){ break; } results.push_back({r.first, score_func->name, r.second}); } return results; } std::vector<response_type> getSimilarTexts(const string_type& query, const std::vector<string_type>& targets) { std::vector<WorkData> candidates; auto original_results = resembla->getSimilarTexts(query, targets); for(const auto& r: original_results){ candidates.push_back(std::make_pair(r.text, (*preprocess)(r, preprocess_corpus ? corpus_features[r.text] : decltype((*preprocess)(r.text))()))); } // rerank by its own metric WorkData query_data = std::make_pair(query, (*preprocess)(query)); auto reranked = reranker.rerank(query_data, std::begin(candidates), std::end(candidates), *score_func); std::vector<ResemblaInterface::response_type> results; for(const auto& r: reranked){ results.push_back({r.first, score_func->name, r.second}); } return results; } protected: using WorkData = std::pair<string_type, typename Preprocessor::return_type>; const std::shared_ptr<ResemblaInterface> resembla; const size_t max_candidate; const std::shared_ptr<Preprocessor> preprocess; const std::shared_ptr<ScoreFunction> score_func; const Reranker<string_type> reranker; const bool preprocess_corpus; void loadCorpusFeatures(const std::string& corpus_path, size_t col) { std::ifstream ifs(corpus_path); if(ifs.fail()){ throw std::runtime_error("input file is not available: " + corpus_path); } while(ifs.good()){ std::string line; std::getline(ifs, line); if(ifs.eof() || line.length() == 0){ break; } auto columns = split(line, '\t'); if(columns.size() + 1 < col){ continue; } corpus_features[cast_string<string_type>(columns[0])] = (*preprocess)(columns[0], columns[1]); } } std::unordered_map<string_type, typename Preprocessor::return_type> corpus_features; }; } #endif <commit_msg>remove obsolete class<commit_after><|endoftext|>
<commit_before>/******************************************************************************* * * BSD 2-Clause License * * Copyright (c) 2017, Sandeep Prakash * All rights reserved. * * 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. * * 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. ******************************************************************************/ /******************************************************************************* * Copyright (c) 2017, Sandeep Prakash <[email protected]> * * \file config.cpp * * \author Sandeep Prakash * * \date Nov 14, 2017 * * \brief * ******************************************************************************/ #include <fstream> #include <glog/logging.h> #include "utils.hpp" #include "config.hpp" using std::ifstream; namespace ChCppUtils { Config::Config(string etcConfig, string localConfig) { etcConfigPath = etcConfig; localConfigPath = localConfig; mDaemon = false; mLogToConsole = false; mRunFor = 30000; mRunForever = false; } Config::~Config() { LOG(INFO) << "*****************~Config"; } bool Config::selectConfigFile() { string selected = ""; if(!fileExists(etcConfigPath)) { if(!fileExists(localConfigPath)) { LOG(ERROR) << "No config file found in /etc/ch-storage-client or " << "./config. I am looking for ch-storage-client.json"; return false; } else { LOG(INFO) << "Found config file " "./config/ch-storage-client.json"; selectedConfigPath = localConfigPath; return true; } } else { LOG(INFO) << "Found config file " "/etc/ch-storage-client/ch-storage-client.json"; selectedConfigPath = etcConfigPath; return true; } } bool Config::populateConfigValues() { LOG(INFO) << "<-----------------------Config"; mDaemon = mJson["daemon"]; LOG(INFO) << "daemon: " << mDaemon; mLogToConsole = mJson["console"]; LOG(INFO) << "console: " << mLogToConsole; mRunFor = mJson["run-for"]; LOG(INFO) << "run-for: " << mRunFor; mRunForever = mJson["run-forever"]; LOG(INFO) << "run-forever: " << mRunForever; mMaxRss = mJson["max-rss"]; LOG(INFO) << "max-rss: " << mMaxRss; LOG(INFO) << "----------------------->Config"; return true; } void Config::init() { if(!selectConfigFile()) { LOG(ERROR) << "Invalid config file."; std::terminate(); } ifstream config(selectedConfigPath); config >> mJson; if(!populateConfigValues()) { LOG(ERROR) << "Invalid config file."; std::terminate(); } LOG(INFO) << "Config: " << mJson; } bool Config::isDaemon() { return mDaemon; } uint32_t Config::getRunFor() { return mRunFor; } bool Config::shouldLogToConsole() { return mLogToConsole; } bool Config::shouldRunForever() { return mRunForever; } uint64_t Config::getMaxRss() { return mMaxRss; } } // End namespace ChCppUtils. <commit_msg>Corrected log lines.<commit_after>/******************************************************************************* * * BSD 2-Clause License * * Copyright (c) 2017, Sandeep Prakash * All rights reserved. * * 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. * * 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. ******************************************************************************/ /******************************************************************************* * Copyright (c) 2017, Sandeep Prakash <[email protected]> * * \file config.cpp * * \author Sandeep Prakash * * \date Nov 14, 2017 * * \brief * ******************************************************************************/ #include <fstream> #include <glog/logging.h> #include "utils.hpp" #include "config.hpp" using std::ifstream; namespace ChCppUtils { Config::Config(string etcConfig, string localConfig) { etcConfigPath = etcConfig; localConfigPath = localConfig; mDaemon = false; mLogToConsole = false; mRunFor = 30000; mRunForever = false; } Config::~Config() { LOG(INFO) << "*****************~Config"; } bool Config::selectConfigFile() { string selected = ""; if(!fileExists(etcConfigPath)) { if(!fileExists(localConfigPath)) { LOG(ERROR) << "No config file found in " << etcConfigPath << " or " << localConfigPath << ". I am looking for " << etcConfigPath << " or " << localConfigPath; return false; } else { LOG(INFO) << "Found config file " << localConfigPath; selectedConfigPath = localConfigPath; return true; } } else { LOG(INFO) << "Found config file " << etcConfigPath; selectedConfigPath = etcConfigPath; return true; } } bool Config::populateConfigValues() { LOG(INFO) << "<-----------------------Config"; mDaemon = mJson["daemon"]; LOG(INFO) << "daemon: " << mDaemon; mLogToConsole = mJson["console"]; LOG(INFO) << "console: " << mLogToConsole; mRunFor = mJson["run-for"]; LOG(INFO) << "run-for: " << mRunFor; mRunForever = mJson["run-forever"]; LOG(INFO) << "run-forever: " << mRunForever; mMaxRss = mJson["max-rss"]; LOG(INFO) << "max-rss: " << mMaxRss; LOG(INFO) << "----------------------->Config"; return true; } void Config::init() { if(!selectConfigFile()) { LOG(ERROR) << "Invalid config file."; std::terminate(); } ifstream config(selectedConfigPath); config >> mJson; if(!populateConfigValues()) { LOG(ERROR) << "Invalid config file."; std::terminate(); } LOG(INFO) << "Config: " << mJson; } bool Config::isDaemon() { return mDaemon; } uint32_t Config::getRunFor() { return mRunFor; } bool Config::shouldLogToConsole() { return mLogToConsole; } bool Config::shouldRunForever() { return mRunForever; } uint64_t Config::getMaxRss() { return mMaxRss; } } // End namespace ChCppUtils. <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * 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. */ /** * @file * This file implements the CHIP Connection object that maintains a UDP connection. * TODO This class should be extended to support TCP as well... * */ #include <string.h> #include <support/CodeUtils.h> #include <support/logging/CHIPLogging.h> #include <transport/SecureSessionMgr.h> #include <inttypes.h> namespace chip { // Maximum length of application data that can be encrypted as one block. // The limit is derived from IPv6 MTU (1280 bytes) - expected header overheads. // This limit would need additional reviews once we have formalized Secure Transport header. static const size_t kMax_SecureSDU_Length = 1024; static const char * kManualKeyExchangeChannelInfo = "Manual Key Exchanged Channel"; SecureSessionMgr::SecureSessionMgr() : mConnectionState(Transport::PeerAddress::Uninitialized()), mState(State::kNotReady) { OnMessageReceived = NULL; } CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, Inet::InetLayer * inet, const Transport::UdpListenParameters & listenParams) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); err = mTransport.Init(inet, listenParams); SuccessOrExit(err); mTransport.SetMessageReceiveHandler(HandleDataReceived, this); mState = State::kInitialized; mLocalNodeId = localNodeId; exit: return err; } CHIP_ERROR SecureSessionMgr::Connect(NodeId peerNodeId, const Transport::PeerAddress & peerAddress) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE); mConnectionState.SetPeerNodeId(peerNodeId); mConnectionState.SetPeerAddress(peerAddress); mState = State::kConnected; exit: return err; } CHIP_ERROR SecureSessionMgr::ManualKeyExchange(const unsigned char * remote_public_key, const size_t public_key_length, const unsigned char * local_private_key, const size_t private_key_length) { CHIP_ERROR err = CHIP_NO_ERROR; size_t info_len = strlen(kManualKeyExchangeChannelInfo); VerifyOrExit(mState == State::kConnected, err = CHIP_ERROR_INCORRECT_STATE); err = mSecureChannel.Init(remote_public_key, public_key_length, local_private_key, private_key_length, NULL, 0, (const unsigned char *) kManualKeyExchangeChannelInfo, info_len); SuccessOrExit(err); mState = State::kSecureConnected; exit: return err; } CHIP_ERROR SecureSessionMgr::SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(StateAllowsSend(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(msgBuf != NULL, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(msgBuf != NULL, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(msgBuf->Next() == NULL, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); { uint8_t * plainText = msgBuf->Start(); size_t plainTextlen = msgBuf->TotalLength(); uint8_t * encryptedText = plainText - CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; size_t encryptedLen = plainTextlen + CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; err = mSecureChannel.Encrypt(plainText, plainTextlen, encryptedText, encryptedLen); SuccessOrExit(err); msgBuf->SetStart(encryptedText); ChipLogProgress(Inet, "Secure transport transmitting msg %u after encryption", mConnectionState.GetSendMessageIndex()); } { MessageHeader header; header .SetSourceNodeId(mLocalNodeId) // .SetDestinationNodeId(peerNodeId) // .SetMessageId(mConnectionState.GetSendMessageIndex()); err = mTransport.SendMessage(header, mConnectionState.GetPeerAddress(), msgBuf); msgBuf = NULL; } SuccessOrExit(err); mConnectionState.IncrementSendMessageIndex(); exit: if (msgBuf != NULL) { ChipLogProgress(Inet, "Secure transport failed to encrypt msg %u: %s", mConnectionState.GetSendMessageIndex(), ErrorStr(err)); PacketBuffer::Free(msgBuf); msgBuf = NULL; } return err; } void SecureSessionMgr::HandleDataReceived(const MessageHeader & header, const IPPacketInfo & pktInfo, System::PacketBuffer * msg, SecureSessionMgr * connection) { // TODO: actual key exchange should happen here if (!connection->StateAllowsReceive()) { if (connection->OnNewConnection) { connection->OnNewConnection(header, pktInfo, connection->mNewConnectionArgument); } } // TODO this is where messages should be decoded if (connection->StateAllowsReceive() && msg != nullptr) { uint8_t * encryptedText = msg->Start(); uint16_t encryptedLen = msg->TotalLength(); if (encryptedLen < CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE) { PacketBuffer::Free(msg); ChipLogProgress(Inet, "Secure transport received smaller than encryption header, discarding"); return; } chip::System::PacketBuffer * origMsg = nullptr; #if CHIP_SYSTEM_CONFIG_USE_LWIP /* This is a workaround for the case where PacketBuffer payload is not allocated as an inline buffer to PacketBuffer structure */ origMsg = msg; msg = PacketBuffer::NewWithAvailableSize(encryptedLen); msg->SetDataLength(encryptedLen, msg); #endif uint8_t * plainText = msg->Start() + CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; size_t plainTextlen = encryptedLen - CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; CHIP_ERROR err = connection->mSecureChannel.Decrypt(encryptedText, encryptedLen, plainText, plainTextlen); if (origMsg != nullptr) { PacketBuffer::Free(origMsg); } if (err == CHIP_NO_ERROR) { msg->Consume(CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE); if (connection->OnMessageReceived) { connection->OnMessageReceived(header, pktInfo, msg, connection->mMessageReceivedArgument); } } else { if (connection->OnReceiveError) { connection->OnReceiveError(CHIP_ERROR_UNSUPPORTED_ENCRYPTION_TYPE_FROM_PEER, pktInfo); } PacketBuffer::Free(msg); ChipLogProgress(Inet, "Secure transport failed to decrypt msg: err %d", err); } } else if (msg != nullptr) { PacketBuffer::Free(msg); ChipLogProgress(Inet, "Secure transport failed: state not allows receive"); } else { ChipLogError(Inet, "Not ready to process new messages"); } } } // namespace chip <commit_msg>Detangle HandleDataReceived code in SecureSessionMgr (#1157)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2013-2017 Nest Labs, Inc. * 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. */ /** * @file * This file implements the CHIP Connection object that maintains a UDP connection. * TODO This class should be extended to support TCP as well... * */ #include <string.h> #include <support/CodeUtils.h> #include <support/logging/CHIPLogging.h> #include <transport/SecureSessionMgr.h> #include <inttypes.h> namespace chip { // Maximum length of application data that can be encrypted as one block. // The limit is derived from IPv6 MTU (1280 bytes) - expected header overheads. // This limit would need additional reviews once we have formalized Secure Transport header. static const size_t kMax_SecureSDU_Length = 1024; static const char * kManualKeyExchangeChannelInfo = "Manual Key Exchanged Channel"; SecureSessionMgr::SecureSessionMgr() : mConnectionState(Transport::PeerAddress::Uninitialized()), mState(State::kNotReady) { OnMessageReceived = NULL; } CHIP_ERROR SecureSessionMgr::Init(NodeId localNodeId, Inet::InetLayer * inet, const Transport::UdpListenParameters & listenParams) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kNotReady, err = CHIP_ERROR_INCORRECT_STATE); err = mTransport.Init(inet, listenParams); SuccessOrExit(err); mTransport.SetMessageReceiveHandler(HandleDataReceived, this); mState = State::kInitialized; mLocalNodeId = localNodeId; exit: return err; } CHIP_ERROR SecureSessionMgr::Connect(NodeId peerNodeId, const Transport::PeerAddress & peerAddress) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(mState == State::kInitialized, err = CHIP_ERROR_INCORRECT_STATE); mConnectionState.SetPeerNodeId(peerNodeId); mConnectionState.SetPeerAddress(peerAddress); mState = State::kConnected; exit: return err; } CHIP_ERROR SecureSessionMgr::ManualKeyExchange(const unsigned char * remote_public_key, const size_t public_key_length, const unsigned char * local_private_key, const size_t private_key_length) { CHIP_ERROR err = CHIP_NO_ERROR; size_t info_len = strlen(kManualKeyExchangeChannelInfo); VerifyOrExit(mState == State::kConnected, err = CHIP_ERROR_INCORRECT_STATE); err = mSecureChannel.Init(remote_public_key, public_key_length, local_private_key, private_key_length, NULL, 0, (const unsigned char *) kManualKeyExchangeChannelInfo, info_len); SuccessOrExit(err); mState = State::kSecureConnected; exit: return err; } CHIP_ERROR SecureSessionMgr::SendMessage(NodeId peerNodeId, System::PacketBuffer * msgBuf) { CHIP_ERROR err = CHIP_NO_ERROR; VerifyOrExit(StateAllowsSend(), err = CHIP_ERROR_INCORRECT_STATE); VerifyOrExit(msgBuf != NULL, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(msgBuf != NULL, err = CHIP_ERROR_INVALID_ARGUMENT); VerifyOrExit(msgBuf->Next() == NULL, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH); { uint8_t * plainText = msgBuf->Start(); size_t plainTextlen = msgBuf->TotalLength(); uint8_t * encryptedText = plainText - CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; size_t encryptedLen = plainTextlen + CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; err = mSecureChannel.Encrypt(plainText, plainTextlen, encryptedText, encryptedLen); SuccessOrExit(err); msgBuf->SetStart(encryptedText); ChipLogProgress(Inet, "Secure transport transmitting msg %u after encryption", mConnectionState.GetSendMessageIndex()); } { MessageHeader header; header .SetSourceNodeId(mLocalNodeId) // .SetDestinationNodeId(peerNodeId) // .SetMessageId(mConnectionState.GetSendMessageIndex()); err = mTransport.SendMessage(header, mConnectionState.GetPeerAddress(), msgBuf); msgBuf = NULL; } SuccessOrExit(err); mConnectionState.IncrementSendMessageIndex(); exit: if (msgBuf != NULL) { ChipLogProgress(Inet, "Secure transport failed to encrypt msg %u: %s", mConnectionState.GetSendMessageIndex(), ErrorStr(err)); PacketBuffer::Free(msgBuf); msgBuf = NULL; } return err; } void SecureSessionMgr::HandleDataReceived(const MessageHeader & header, const IPPacketInfo & pktInfo, System::PacketBuffer * msg, SecureSessionMgr * connection) { CHIP_ERROR err = CHIP_NO_ERROR; System::PacketBuffer * origMsg = nullptr; // TODO: actual key exchange should happen here if (!connection->StateAllowsReceive()) { if (connection->OnNewConnection) { connection->OnNewConnection(header, pktInfo, connection->mNewConnectionArgument); } ExitNow(ChipLogProgress(Inet, "Secure transport failed: state does not allow receive")); } err = CHIP_ERROR_INVALID_ARGUMENT; VerifyOrExit(msg != nullptr, ChipLogError(Inet, "Secure transport received NULL packet, discarding")); // TODO this is where messages should be decoded { uint8_t * encryptedText = msg->Start(); uint16_t encryptedLen = msg->TotalLength(); uint8_t * plainText = nullptr; size_t plainTextlen = encryptedLen - CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; VerifyOrExit(encryptedLen >= CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE, ChipLogError(Inet, "Secure transport received smaller than encryption header, discarding")); #if CHIP_SYSTEM_CONFIG_USE_LWIP /* This is a workaround for the case where PacketBuffer payload is not allocated as an inline buffer to PacketBuffer structure */ origMsg = msg; msg = PacketBuffer::NewWithAvailableSize(encryptedLen); msg->SetDataLength(encryptedLen, msg); #endif plainText = msg->Start() + CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE; err = connection->mSecureChannel.Decrypt(encryptedText, encryptedLen, plainText, plainTextlen); VerifyOrExit(err == CHIP_NO_ERROR, ChipLogProgress(Inet, "Secure transport failed to decrypt msg: err %d", err)); if (connection->OnMessageReceived) { msg->Consume(CHIP_SYSTEM_CRYPTO_HEADER_RESERVE_SIZE); connection->OnMessageReceived(header, pktInfo, msg, connection->mMessageReceivedArgument); msg = nullptr; } } exit: if (origMsg != nullptr) { PacketBuffer::Free(origMsg); } if (msg != nullptr) { PacketBuffer::Free(msg); } if (err != CHIP_NO_ERROR) { if (connection->OnReceiveError) { connection->OnReceiveError(err, pktInfo); } } } } // namespace chip <|endoftext|>
<commit_before>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "device.h" #include "array.h" #include "config.h" #include "debug_line.h" #include "input_manager.h" #include "log.h" #include "lua_environment.h" #include "material_manager.h" #include "memory.h" #include "os.h" #include "resource_loader.h" #include "resource_manager.h" #include "resource_package.h" #include "types.h" #include "world.h" #include "json_parser.h" #include "filesystem.h" #include "path.h" #include "disk_filesystem.h" #include "physics.h" #include "audio.h" #include "profiler.h" #include "console_server.h" #include "input_device.h" #include "profiler.h" #if CROWN_PLATFORM_ANDROID #include "apk_filesystem.h" #endif // CROWN_PLATFORM_ANDROID #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024 namespace crown { Device::Device(DeviceOptions& opts) : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP) , _width(0) , _height(0) , _mouse_curr_x(0) , _mouse_curr_y(0) , _mouse_last_x(0) , _mouse_last_y(0) , _is_init(false) , _is_running(false) , _is_paused(false) , _frame_count(0) , _last_time(0) , _current_time(0) , _last_delta_time(0.0f) , _time_since_start(0.0) , _device_options(opts) , _bundle_filesystem(NULL) , _boot_package_id(uint64_t(0)) , _boot_script_id(uint64_t(0)) , _boot_package(NULL) , _lua_environment(NULL) , _resource_loader(NULL) , _resource_manager(NULL) , _input_manager(NULL) , _worlds(default_allocator()) , _bgfx_allocator(default_allocator()) { } void Device::init() { // Initialize CE_LOGI("Initializing Crown Engine %s...", version()); #if CROWN_PLATFORM_ANDROID _bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(_device_options.asset_manager()); #else _bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir()); #endif // CROWN_PLATFORM_ANDROID profiler_globals::init(); _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem); _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader); read_config(); audio_globals::init(); physics_globals::init(); bgfx::init(bgfx::RendererType::Count , BGFX_PCI_ID_NONE , 0 , &_bgfx_callback , &_bgfx_allocator ); CE_LOGD("Creating material manager..."); material_manager::init(); debug_line::init(); _lua_environment = CE_NEW(_allocator, LuaEnvironment)(); _lua_environment->load_libs(); _input_manager = CE_NEW(_allocator, InputManager)(); CE_LOGD("Crown Engine initialized."); CE_LOGD("Initializing Game..."); _is_init = true; _is_running = true; _last_time = os::clocktime(); _boot_package = create_resource_package(_boot_package_id); _boot_package->load(); _boot_package->flush(); _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id)); _lua_environment->call_global("init", 0); } void Device::shutdown() { CE_ASSERT(_is_init, "Engine is not initialized"); CE_DELETE(_allocator, _input_manager); // Shutdowns the game _lua_environment->call_global("shutdown", 0); _boot_package->unload(); destroy_resource_package(*_boot_package); CE_DELETE(_allocator, _lua_environment); CE_LOGD("Releasing material manager..."); debug_line::shutdown(); material_manager::shutdown(); CE_DELETE(_allocator, _resource_manager); CE_DELETE(_allocator, _resource_loader); bgfx::shutdown(); physics_globals::shutdown(); audio_globals::shutdown(); profiler_globals::shutdown(); CE_DELETE(_allocator, _bundle_filesystem); _allocator.clear(); _is_init = false; } void Device::quit() { _is_running = false; } void Device::pause() { _is_paused = true; CE_LOGI("Engine paused."); } void Device::unpause() { _is_paused = false; CE_LOGI("Engine unpaused."); } void Device::resolution(uint16_t& width, uint16_t& height) { width = _width; height = _height; } bool Device::is_running() const { return _is_running; } uint64_t Device::frame_count() const { return _frame_count; } float Device::last_delta_time() const { return _last_delta_time; } double Device::time_since_start() const { return _time_since_start; } void Device::update() { while (!process_events() && _is_running) { _current_time = os::clocktime(); const int64_t time = _current_time - _last_time; _last_time = _current_time; const double freq = (double) os::clockfrequency(); _last_delta_time = time * (1.0 / freq); _time_since_start += _last_delta_time; profiler_globals::clear(); console_server_globals::update(); RECORD_FLOAT("device.dt", _last_delta_time); RECORD_FLOAT("device.fps", 1.0f/_last_delta_time); if (!_is_paused) { _resource_manager->complete_requests(); _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time()); _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time()); } _input_manager->update(); const bgfx::Stats* stats = bgfx::getStats(); RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq); RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq); bgfx::frame(); profiler_globals::flush(); _lua_environment->clear_temporaries(); _frame_count++; } } void Device::render_world(World& world, Camera* camera) { world.render(camera); } World* Device::create_world() { World* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment); array::push_back(_worlds, w); return w; } void Device::destroy_world(World& w) { for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i) { if (&w == _worlds[i]) { CE_DELETE(default_allocator(), &w); _worlds[i] = _worlds[n - 1]; array::pop_back(_worlds); return; } } CE_ASSERT(false, "Bad world"); } ResourcePackage* Device::create_resource_package(StringId64 id) { return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager); } void Device::destroy_resource_package(ResourcePackage& package) { CE_DELETE(default_allocator(), &package); } void Device::reload(StringId64 type, StringId64 name) { const void* old_resource = _resource_manager->get(type, name); _resource_manager->reload(type, name); const void* new_resource = _resource_manager->get(type, name); if (type == SCRIPT_TYPE) { _lua_environment->execute((const LuaResource*)new_resource); } } ResourceManager* Device::resource_manager() { return _resource_manager; } LuaEnvironment* Device::lua_environment() { return _lua_environment; } InputManager* Device::input_manager() { return _input_manager; } bool Device::process_events() { OsEvent event; bool exit = false; InputManager* im = _input_manager; const int16_t dt_x = _mouse_curr_x - _mouse_last_x; const int16_t dt_y = _mouse_curr_y - _mouse_last_y; im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f)); _mouse_last_x = _mouse_curr_x; _mouse_last_y = _mouse_curr_y; while(next_event(event)) { if (event.type == OsEvent::NONE) continue; switch (event.type) { case OsEvent::TOUCH: { const OsTouchEvent& ev = event.touch; switch (ev.type) { case OsTouchEvent::POINTER: im->touch()->set_button_state(ev.pointer_id, ev.pressed); break; case OsTouchEvent::MOVE: im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f)); break; default: CE_FATAL("Unknown touch event type"); break; } break; } case OsEvent::MOUSE: { const OsMouseEvent& ev = event.mouse; switch (ev.type) { case OsMouseEvent::BUTTON: im->mouse()->set_button_state(ev.button, ev.pressed); break; case OsMouseEvent::MOVE: _mouse_curr_x = ev.x; _mouse_curr_y = ev.y; im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f)); break; case OsMouseEvent::WHEEL: im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f)); break; default: CE_FATAL("Unknown mouse event type"); break; } break; } case OsEvent::KEYBOARD: { const OsKeyboardEvent& ev = event.keyboard; im->keyboard()->set_button_state(ev.button, ev.pressed); break; } case OsEvent::JOYPAD: { const OsJoypadEvent& ev = event.joypad; switch (ev.type) { case OsJoypadEvent::CONNECTED: im->joypad(ev.index)->set_connected(ev.connected); break; case OsJoypadEvent::BUTTON: im->joypad(ev.index)->set_button_state(ev.button, ev.pressed); break; case OsJoypadEvent::AXIS: im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z)); break; default: CE_FATAL("Unknown joypad event"); break; } break; } case OsEvent::METRICS: { const OsMetricsEvent& ev = event.metrics; _width = ev.width; _height = ev.height; bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC); break; } case OsEvent::EXIT: { exit = true; break; } case OsEvent::PAUSE: { pause(); break; } case OsEvent::RESUME: { unpause(); break; } default: { CE_FATAL("Unknown Os Event"); break; } } } return exit; } void Device::read_config() { TempAllocator1024 ta; DynamicString project_path(ta); if (_device_options.project() != NULL) { project_path += _device_options.project(); project_path += '/'; } project_path += "crown"; const StringId64 config_name(project_path.c_str()); _resource_manager->load(CONFIG_TYPE, config_name); _resource_manager->flush(); const char* config_file = (const char*)_resource_manager->get(CONFIG_TYPE, config_name); JSONParser config(config_file); JSONElement root = config.root(); _boot_script_id = root.key("boot_script").to_resource_id(); _boot_package_id = root.key("boot_package").to_resource_id(); _resource_manager->unload(CONFIG_TYPE, config_name); } char _buffer[sizeof(Device)]; Device* _device = NULL; void init(DeviceOptions& opts) { CE_ASSERT(_device == NULL, "Crown already initialized"); _device = new (_buffer) Device(opts); _device->init(); } void update() { _device->update(); } void shutdown() { _device->shutdown(); _device->~Device(); _device = NULL; } Device* device() { return crown::_device; } } // namespace crown <commit_msg>Cleanup<commit_after>/* * Copyright (c) 2012-2015 Daniele Bartolini and individual contributors. * License: https://github.com/taylor001/crown/blob/master/LICENSE */ #include "device.h" #include "array.h" #include "config.h" #include "debug_line.h" #include "input_manager.h" #include "log.h" #include "lua_environment.h" #include "material_manager.h" #include "memory.h" #include "os.h" #include "resource_loader.h" #include "resource_manager.h" #include "resource_package.h" #include "types.h" #include "world.h" #include "json_parser.h" #include "filesystem.h" #include "path.h" #include "disk_filesystem.h" #include "physics.h" #include "audio.h" #include "profiler.h" #include "console_server.h" #include "input_device.h" #if CROWN_PLATFORM_ANDROID #include "apk_filesystem.h" #endif // CROWN_PLATFORM_ANDROID #define MAX_SUBSYSTEMS_HEAP 8 * 1024 * 1024 namespace crown { Device::Device(DeviceOptions& opts) : _allocator(default_allocator(), MAX_SUBSYSTEMS_HEAP) , _width(0) , _height(0) , _mouse_curr_x(0) , _mouse_curr_y(0) , _mouse_last_x(0) , _mouse_last_y(0) , _is_init(false) , _is_running(false) , _is_paused(false) , _frame_count(0) , _last_time(0) , _current_time(0) , _last_delta_time(0.0f) , _time_since_start(0.0) , _device_options(opts) , _bundle_filesystem(NULL) , _boot_package_id(uint64_t(0)) , _boot_script_id(uint64_t(0)) , _boot_package(NULL) , _lua_environment(NULL) , _resource_loader(NULL) , _resource_manager(NULL) , _input_manager(NULL) , _worlds(default_allocator()) , _bgfx_allocator(default_allocator()) { } void Device::init() { // Initialize CE_LOGI("Initializing Crown Engine %s...", version()); #if CROWN_PLATFORM_ANDROID _bundle_filesystem = CE_NEW(_allocator, ApkFilesystem)(_device_options.asset_manager()); #else _bundle_filesystem = CE_NEW(_allocator, DiskFilesystem)(_device_options.bundle_dir()); #endif // CROWN_PLATFORM_ANDROID profiler_globals::init(); _resource_loader = CE_NEW(_allocator, ResourceLoader)(*_bundle_filesystem); _resource_manager = CE_NEW(_allocator, ResourceManager)(*_resource_loader); read_config(); audio_globals::init(); physics_globals::init(); bgfx::init(bgfx::RendererType::Count , BGFX_PCI_ID_NONE , 0 , &_bgfx_callback , &_bgfx_allocator ); CE_LOGD("Creating material manager..."); material_manager::init(); debug_line::init(); _lua_environment = CE_NEW(_allocator, LuaEnvironment)(); _lua_environment->load_libs(); _input_manager = CE_NEW(_allocator, InputManager)(); CE_LOGD("Crown Engine initialized."); CE_LOGD("Initializing Game..."); _is_init = true; _is_running = true; _last_time = os::clocktime(); _boot_package = create_resource_package(_boot_package_id); _boot_package->load(); _boot_package->flush(); _lua_environment->execute((LuaResource*)_resource_manager->get(SCRIPT_TYPE, _boot_script_id)); _lua_environment->call_global("init", 0); } void Device::shutdown() { CE_ASSERT(_is_init, "Engine is not initialized"); CE_DELETE(_allocator, _input_manager); // Shutdowns the game _lua_environment->call_global("shutdown", 0); _boot_package->unload(); destroy_resource_package(*_boot_package); CE_DELETE(_allocator, _lua_environment); CE_LOGD("Releasing material manager..."); debug_line::shutdown(); material_manager::shutdown(); CE_DELETE(_allocator, _resource_manager); CE_DELETE(_allocator, _resource_loader); bgfx::shutdown(); physics_globals::shutdown(); audio_globals::shutdown(); profiler_globals::shutdown(); CE_DELETE(_allocator, _bundle_filesystem); _allocator.clear(); _is_init = false; } void Device::quit() { _is_running = false; } void Device::pause() { _is_paused = true; CE_LOGI("Engine paused."); } void Device::unpause() { _is_paused = false; CE_LOGI("Engine unpaused."); } void Device::resolution(uint16_t& width, uint16_t& height) { width = _width; height = _height; } bool Device::is_running() const { return _is_running; } uint64_t Device::frame_count() const { return _frame_count; } float Device::last_delta_time() const { return _last_delta_time; } double Device::time_since_start() const { return _time_since_start; } void Device::update() { while (!process_events() && _is_running) { _current_time = os::clocktime(); const int64_t time = _current_time - _last_time; _last_time = _current_time; const double freq = (double) os::clockfrequency(); _last_delta_time = time * (1.0 / freq); _time_since_start += _last_delta_time; profiler_globals::clear(); console_server_globals::update(); RECORD_FLOAT("device.dt", _last_delta_time); RECORD_FLOAT("device.fps", 1.0f/_last_delta_time); if (!_is_paused) { _resource_manager->complete_requests(); _lua_environment->call_global("update", 1, ARGUMENT_FLOAT, last_delta_time()); _lua_environment->call_global("render", 1, ARGUMENT_FLOAT, last_delta_time()); } _input_manager->update(); const bgfx::Stats* stats = bgfx::getStats(); RECORD_FLOAT("bgfx.gpu_time", double(stats->gpuTimeEnd - stats->gpuTimeBegin)*1000.0/stats->gpuTimerFreq); RECORD_FLOAT("bgfx.cpu_time", double(stats->cpuTimeEnd - stats->cpuTimeBegin)*1000.0/stats->cpuTimerFreq); bgfx::frame(); profiler_globals::flush(); _lua_environment->clear_temporaries(); _frame_count++; } } void Device::render_world(World& world, Camera* camera) { world.render(camera); } World* Device::create_world() { World* w = CE_NEW(default_allocator(), World)(*_resource_manager, *_lua_environment); array::push_back(_worlds, w); return w; } void Device::destroy_world(World& w) { for (uint32_t i = 0, n = array::size(_worlds); i < n; ++i) { if (&w == _worlds[i]) { CE_DELETE(default_allocator(), &w); _worlds[i] = _worlds[n - 1]; array::pop_back(_worlds); return; } } CE_ASSERT(false, "Bad world"); } ResourcePackage* Device::create_resource_package(StringId64 id) { return CE_NEW(default_allocator(), ResourcePackage)(id, *_resource_manager); } void Device::destroy_resource_package(ResourcePackage& package) { CE_DELETE(default_allocator(), &package); } void Device::reload(StringId64 type, StringId64 name) { const void* old_resource = _resource_manager->get(type, name); _resource_manager->reload(type, name); const void* new_resource = _resource_manager->get(type, name); if (type == SCRIPT_TYPE) { _lua_environment->execute((const LuaResource*)new_resource); } } ResourceManager* Device::resource_manager() { return _resource_manager; } LuaEnvironment* Device::lua_environment() { return _lua_environment; } InputManager* Device::input_manager() { return _input_manager; } bool Device::process_events() { OsEvent event; bool exit = false; InputManager* im = _input_manager; const int16_t dt_x = _mouse_curr_x - _mouse_last_x; const int16_t dt_y = _mouse_curr_y - _mouse_last_y; im->mouse()->set_axis(MouseAxis::CURSOR_DELTA, vector3(dt_x, dt_y, 0.0f)); _mouse_last_x = _mouse_curr_x; _mouse_last_y = _mouse_curr_y; while(next_event(event)) { if (event.type == OsEvent::NONE) continue; switch (event.type) { case OsEvent::TOUCH: { const OsTouchEvent& ev = event.touch; switch (ev.type) { case OsTouchEvent::POINTER: im->touch()->set_button_state(ev.pointer_id, ev.pressed); break; case OsTouchEvent::MOVE: im->touch()->set_axis(ev.pointer_id, vector3(ev.x, ev.y, 0.0f)); break; default: CE_FATAL("Unknown touch event type"); break; } break; } case OsEvent::MOUSE: { const OsMouseEvent& ev = event.mouse; switch (ev.type) { case OsMouseEvent::BUTTON: im->mouse()->set_button_state(ev.button, ev.pressed); break; case OsMouseEvent::MOVE: _mouse_curr_x = ev.x; _mouse_curr_y = ev.y; im->mouse()->set_axis(MouseAxis::CURSOR, vector3(ev.x, ev.y, 0.0f)); break; case OsMouseEvent::WHEEL: im->mouse()->set_axis(MouseAxis::WHEEL, vector3(0.0f, ev.wheel, 0.0f)); break; default: CE_FATAL("Unknown mouse event type"); break; } break; } case OsEvent::KEYBOARD: { const OsKeyboardEvent& ev = event.keyboard; im->keyboard()->set_button_state(ev.button, ev.pressed); break; } case OsEvent::JOYPAD: { const OsJoypadEvent& ev = event.joypad; switch (ev.type) { case OsJoypadEvent::CONNECTED: im->joypad(ev.index)->set_connected(ev.connected); break; case OsJoypadEvent::BUTTON: im->joypad(ev.index)->set_button_state(ev.button, ev.pressed); break; case OsJoypadEvent::AXIS: im->joypad(ev.index)->set_axis(ev.button, vector3(ev.x, ev.y, ev.z)); break; default: CE_FATAL("Unknown joypad event"); break; } break; } case OsEvent::METRICS: { const OsMetricsEvent& ev = event.metrics; _width = ev.width; _height = ev.height; bgfx::reset(ev.width, ev.height, BGFX_RESET_VSYNC); break; } case OsEvent::EXIT: { exit = true; break; } case OsEvent::PAUSE: { pause(); break; } case OsEvent::RESUME: { unpause(); break; } default: { CE_FATAL("Unknown Os Event"); break; } } } return exit; } void Device::read_config() { TempAllocator1024 ta; DynamicString project_path(ta); if (_device_options.project() != NULL) { project_path += _device_options.project(); project_path += '/'; } project_path += "crown"; const StringId64 config_name(project_path.c_str()); _resource_manager->load(CONFIG_TYPE, config_name); _resource_manager->flush(); const char* config_file = (const char*)_resource_manager->get(CONFIG_TYPE, config_name); JSONParser config(config_file); JSONElement root = config.root(); _boot_script_id = root.key("boot_script").to_resource_id(); _boot_package_id = root.key("boot_package").to_resource_id(); _resource_manager->unload(CONFIG_TYPE, config_name); } char _buffer[sizeof(Device)]; Device* _device = NULL; void init(DeviceOptions& opts) { CE_ASSERT(_device == NULL, "Crown already initialized"); _device = new (_buffer) Device(opts); _device->init(); } void update() { _device->update(); } void shutdown() { _device->shutdown(); _device->~Device(); _device = NULL; } Device* device() { return crown::_device; } } // namespace crown <|endoftext|>
<commit_before>#include <element.h> /* Copyright (c) 2011, Wesley Moore http://www.wezm.net/ All rights reserved. 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 node-genx Project, Wesley Moore, 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. */ Persistent<FunctionTemplate> Element::constructor_template; void Element::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Element")); } Element::Element(genxElement el) : element(el) { } Element::~Element() { } Handle<Value> Element::New(const Arguments& args) { HandleScope scope; REQ_EXT_ARG(0, e); Element* el = new Element((genxElement)e->Value()); el->Wrap(args.This()); return args.This(); } genxStatus Element::start() { return genxStartElement(element); } <commit_msg>Include the element header properly<commit_after>/* Copyright (c) 2011, Wesley Moore http://www.wezm.net/ All rights reserved. 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 node-genx Project, Wesley Moore, 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. */ #include "element.h" Persistent<FunctionTemplate> Element::constructor_template; void Element::Initialize(Handle<Object> target) { HandleScope scope; Local<FunctionTemplate> t = FunctionTemplate::New(New); constructor_template = Persistent<FunctionTemplate>::New(t); constructor_template->InstanceTemplate()->SetInternalFieldCount(1); constructor_template->SetClassName(String::NewSymbol("Element")); } Element::Element(genxElement el) : element(el) { } Element::~Element() { } Handle<Value> Element::New(const Arguments& args) { HandleScope scope; REQ_EXT_ARG(0, e); Element* el = new Element((genxElement)e->Value()); el->Wrap(args.This()); return args.This(); } genxStatus Element::start() { return genxStartElement(element); } <|endoftext|>
<commit_before>#include "engine.h" #include "random.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include "io/keybinding.h" #include "soundManager.h" #include "windowManager.h" #include "scriptInterface.h" #include "multiplayer_server.h" #include <thread> #include <SDL.h> #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif Engine* engine; Engine::Engine() { engine = this; #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = DynamicLibrary::open("exchndl.dll"); if (exchndl) { auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { exchndl.reset(); } } #endif // WIN32 SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); #ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1"); #elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS) SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0"); SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_ShowCursor(false); atexit(SDL_Quit); initRandom(); CollisionManager::initialize(); gameSpeed = 1.0f; running = true; elapsedTime = 0.0f; soundManager = new SoundManager(); } Engine::~Engine() { Window::all_windows.clear(); updatableList.clear(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { if (Window::all_windows.size() == 0) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } #ifdef DEBUG if (debug_output_timer.isExpired()) LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size(); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window for(auto window : Window::all_windows) window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; sp::io::Keybinding::allPostUpdate(); } soundManager->stopMusic(); sp::audio::Source::stopAudioSystem(); } } void Engine::handleEvent(SDL_Event& event) { if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif unsigned int window_id = 0; switch(event.type) { case SDL_KEYDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_KEYUP: window_id = event.key.windowID; break; case SDL_MOUSEMOTION: window_id = event.motion.windowID; break; case SDL_MOUSEBUTTONDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_MOUSEBUTTONUP: window_id = event.button.windowID; break; case SDL_MOUSEWHEEL: window_id = event.wheel.windowID; break; case SDL_WINDOWEVENT: window_id = event.window.windowID; break; case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: #if SDL_VERSION_ATLEAST(2, 0, 12) window_id = event.tfinger.windowID; #else window_id = SDL_GetWindowID(SDL_GetMouseFocus()); #endif break; case SDL_TEXTEDITING: window_id = event.edit.windowID; break; case SDL_TEXTINPUT: window_id = event.text.windowID; break; } if (window_id != 0) { foreach(Window, window, Window::all_windows) if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id) window->handleEvent(event); } sp::io::Keybinding::handleEvent(event); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <commit_msg>Stop text input at engine start so keybindings work correctly<commit_after>#include "engine.h" #include "random.h" #include "Updatable.h" #include "collisionable.h" #include "audio/source.h" #include "io/keybinding.h" #include "soundManager.h" #include "windowManager.h" #include "scriptInterface.h" #include "multiplayer_server.h" #include <thread> #include <SDL.h> #ifdef DEBUG #include <typeinfo> int DEBUG_PobjCount; PObject* DEBUG_PobjListStart; #endif Engine* engine; Engine::Engine() { engine = this; #ifdef WIN32 // Setup crash reporter (Dr. MinGW) if available. exchndl = DynamicLibrary::open("exchndl.dll"); if (exchndl) { auto pfnExcHndlInit = exchndl->getFunction<void(*)(void)>("ExcHndlInit"); if (pfnExcHndlInit) { pfnExcHndlInit(); LOG(INFO) << "Crash Reporter ON"; } else { exchndl.reset(); } } #endif // WIN32 SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0"); SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0"); #ifdef SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH SDL_SetHint(SDL_HINT_ANDROID_SEPARATE_MOUSE_AND_TOUCH, "1"); #elif defined(SDL_HINT_MOUSE_TOUCH_EVENTS) SDL_SetHint(SDL_HINT_MOUSE_TOUCH_EVENTS, "0"); SDL_SetHint(SDL_HINT_TOUCH_MOUSE_EVENTS, "0"); #endif SDL_Init(SDL_INIT_EVERYTHING); SDL_ShowCursor(false); SDL_StopTextInput(); atexit(SDL_Quit); initRandom(); CollisionManager::initialize(); gameSpeed = 1.0f; running = true; elapsedTime = 0.0f; soundManager = new SoundManager(); } Engine::~Engine() { Window::all_windows.clear(); updatableList.clear(); delete soundManager; soundManager = nullptr; } void Engine::registerObject(string name, P<PObject> obj) { objectMap[name] = obj; } P<PObject> Engine::getObject(string name) { if (!objectMap[name]) return NULL; return objectMap[name]; } void Engine::runMainLoop() { if (Window::all_windows.size() == 0) { sp::SystemStopwatch frame_timer; while(running) { float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; foreach(Updatable, u, updatableList) u->update(delta); elapsedTime += delta; CollisionManager::handleCollisions(delta); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); std::this_thread::sleep_for(std::chrono::duration<float>(1.f/60.f - delta)); } }else{ sp::audio::Source::startAudioSystem(); sp::SystemStopwatch frame_timer; #ifdef DEBUG sp::SystemTimer debug_output_timer; debug_output_timer.repeat(5); #endif while(running) { // Handle events SDL_Event event; while (SDL_PollEvent(&event)) { handleEvent(event); } #ifdef DEBUG if (debug_output_timer.isExpired()) LOG(DEBUG) << "Object count: " << DEBUG_PobjCount << " " << updatableList.size(); #endif float delta = frame_timer.restart(); if (delta > 0.5f) delta = 0.5f; if (delta < 0.001f) delta = 0.001f; delta *= gameSpeed; EngineTiming engine_timing; sp::SystemStopwatch engine_timing_stopwatch; foreach(Updatable, u, updatableList) { u->update(delta); } elapsedTime += delta; engine_timing.update = engine_timing_stopwatch.restart(); CollisionManager::handleCollisions(delta); engine_timing.collision = engine_timing_stopwatch.restart(); ScriptObject::clearDestroyedObjects(); soundManager->updateTick(); // Clear the window for(auto window : Window::all_windows) window->render(); engine_timing.render = engine_timing_stopwatch.restart(); engine_timing.server_update = 0.0f; if (game_server) engine_timing.server_update = game_server->getUpdateTime(); last_engine_timing = engine_timing; sp::io::Keybinding::allPostUpdate(); } soundManager->stopMusic(); sp::audio::Source::stopAudioSystem(); } } void Engine::handleEvent(SDL_Event& event) { if (event.type == SDL_QUIT) running = false; #ifdef DEBUG if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE) running = false; if (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_l) { int n = 0; printf("------------------------\n"); std::unordered_map<string,int> totals; for(PObject* obj = DEBUG_PobjListStart; obj; obj = obj->DEBUG_PobjListNext) { printf("%c%4d: %4d: %s\n", obj->isDestroyed() ? '>' : ' ', n++, obj->getRefCount(), typeid(*obj).name()); if (!obj->isDestroyed()) { totals[typeid(*obj).name()]=totals[typeid(*obj).name()]+1; } } printf("--non-destroyed totals--\n"); int grand_total=0; for (auto entry : totals) { printf("%4d %s\n", entry.second, entry.first.c_str()); grand_total+=entry.second; } printf("%4d %s\n",grand_total,"All PObjects"); printf("------------------------\n"); } #endif unsigned int window_id = 0; switch(event.type) { case SDL_KEYDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_KEYUP: window_id = event.key.windowID; break; case SDL_MOUSEMOTION: window_id = event.motion.windowID; break; case SDL_MOUSEBUTTONDOWN: #ifdef __EMSCRIPTEN__ if (!audio_started) { audio::AudioSource::startAudioSystem(); audio_started = true; } #endif case SDL_MOUSEBUTTONUP: window_id = event.button.windowID; break; case SDL_MOUSEWHEEL: window_id = event.wheel.windowID; break; case SDL_WINDOWEVENT: window_id = event.window.windowID; break; case SDL_FINGERDOWN: case SDL_FINGERUP: case SDL_FINGERMOTION: #if SDL_VERSION_ATLEAST(2, 0, 12) window_id = event.tfinger.windowID; #else window_id = SDL_GetWindowID(SDL_GetMouseFocus()); #endif break; case SDL_TEXTEDITING: window_id = event.edit.windowID; break; case SDL_TEXTINPUT: window_id = event.text.windowID; break; } if (window_id != 0) { foreach(Window, window, Window::all_windows) if (window->window && SDL_GetWindowID(static_cast<SDL_Window*>(window->window)) == window_id) window->handleEvent(event); } sp::io::Keybinding::handleEvent(event); } void Engine::setGameSpeed(float speed) { gameSpeed = speed; } float Engine::getGameSpeed() { return gameSpeed; } float Engine::getElapsedTime() { return elapsedTime; } Engine::EngineTiming Engine::getEngineTiming() { return last_engine_timing; } void Engine::shutdown() { running = false; } <|endoftext|>
<commit_before>#include "boost_test.h" #include "ComplexFixedPoint.h" #include <complex> using namespace std; BOOST_AUTO_TEST_CASE( CFxpConstructors ) { /* Values too large for width */ BOOST_CHECK_THROW(CFxp(128, 0, 8), range_error); BOOST_CHECK_THROW(CFxp(0, -129, 8), range_error); /* Width larger than max allowed width */ BOOST_CHECK_THROW(CFxp(0, 0, CFxp::MAX_WIDTH + 1), range_error); } BOOST_AUTO_TEST_CASE( CFxpAccessors ) { CFxp a(1, 2, 8); BOOST_CHECK_EQUAL(a.real(), 1); BOOST_CHECK_EQUAL(a.imag(), 2); BOOST_CHECK_EQUAL(a.width(), 8); BOOST_CHECK_EQUAL(a.minVal(), -128); BOOST_CHECK_EQUAL(a.maxVal(), 127); } BOOST_AUTO_TEST_CASE( CFxpAssignment ) { CFxp a(1, 2, 8); CFxp b(1, 2, 10); CFxp c; CFxp d(1, 2, 8, true); CFxp e(1, 2, 8, false); BOOST_CHECK_THROW(a = b, SizeMismatchException); BOOST_CHECK_NO_THROW(c = a); BOOST_CHECK_EQUAL(c, a); BOOST_CHECK_NO_THROW(d = b); BOOST_CHECK_EQUAL(d, b); BOOST_CHECK_THROW(e = b, SizeMismatchException); } BOOST_AUTO_TEST_CASE( CFxpEquality ) { CFxp a(1, 2, 8); CFxp b(1, 2, 8); CFxp c(1, 2, 10); CFxp d(13, 2, 8); CFxp e(1, 13, 8); CFxp f(24, 38, 21); /* same object as lhs and rhs */ BOOST_CHECK_EQUAL(a == a, true); BOOST_CHECK_EQUAL(a != a, false); /* different equal objects */ BOOST_CHECK_EQUAL(a == b, true); BOOST_CHECK_EQUAL(a != b, false); /* same value, different widths */ BOOST_CHECK_EQUAL(a == c, false); BOOST_CHECK_EQUAL(a != c, true); /* different values, same widths */ BOOST_CHECK_EQUAL(a == d, false); BOOST_CHECK_EQUAL(a != d, true); BOOST_CHECK_EQUAL(a == e, false); BOOST_CHECK_EQUAL(a != e, true); /* everything different */ BOOST_CHECK_EQUAL(a == f, false); BOOST_CHECK_EQUAL(a != f, true); } BOOST_AUTO_TEST_CASE( CFxpScalarMultiplication ) { CFxp a(1, 2, 8); Fxp b(2, 5); /* multiplication by scalar is commutative */ BOOST_CHECK_EQUAL(a * b, b * a); /* width after multiplication by scalar */ BOOST_CHECK_EQUAL((a * b).width(), 13); /* result check */ BOOST_CHECK_EQUAL(a * b, CFxp(2, 4, 13)); } BOOST_AUTO_TEST_CASE( CFxpMultiplication ) { CFxp a(1, 2, 8); CFxp b(2, 5, 5); /* complex multiplication is commutative */ BOOST_CHECK_EQUAL(a * b, b * a); /* chaining works */ BOOST_CHECK_EQUAL(a * a * a, a * a * a); /* width after multiplication */ BOOST_CHECK_EQUAL((a * b).width(), 14); /* result check */ BOOST_CHECK_EQUAL(a * b, CFxp(-8, 9, 14)); } BOOST_AUTO_TEST_CASE( CFxpAddition ) { CFxp a(1, 2, 8); CFxp b(2, 5, 5); /* addition is commutative */ BOOST_CHECK_EQUAL(a + b, b + a); /* chaining works */ BOOST_CHECK_EQUAL(a + a + a, a + a + a); /* width after addition */ BOOST_CHECK_EQUAL((a + b).width(), 9); /* result check */ BOOST_CHECK_EQUAL(a + b, CFxp(3, 7, 9)); } <commit_msg>CFxp: Added more constructor unit tests<commit_after>#include "boost_test.h" #include "ComplexFixedPoint.h" #include <complex> using namespace std; BOOST_AUTO_TEST_CASE( CFxpConstructors ) { /* Check default constructor */ CFxp a; const unsigned int D_WIDTH = CFxp::DEFAULT_WIDTH; BOOST_CHECK_EQUAL(a.width(), D_WIDTH); BOOST_CHECK_EQUAL(a.real(), 0); BOOST_CHECK_EQUAL(a.imag(), 0); /* Check non-default constructors */ CFxp b(1, -3, 4); BOOST_CHECK_EQUAL(b.width(), 4); BOOST_CHECK_EQUAL(b.real(), 1); BOOST_CHECK_EQUAL(b.imag(), -3); CFxp c(complex<int64_t>(5, -13), 6); BOOST_CHECK_EQUAL(c.width(), 6); BOOST_CHECK_EQUAL(c.real(), 5); BOOST_CHECK_EQUAL(c.imag(), -13); /* Values too large for width */ BOOST_CHECK_THROW(CFxp(128, 0, 8), range_error); BOOST_CHECK_THROW(CFxp(0, -129, 8), range_error); /* Width larger than max allowed width */ BOOST_CHECK_THROW(CFxp(0, 0, CFxp::MAX_WIDTH + 1), range_error); } BOOST_AUTO_TEST_CASE( CFxpAccessors ) { CFxp a(1, 2, 8); BOOST_CHECK_EQUAL(a.real(), 1); BOOST_CHECK_EQUAL(a.imag(), 2); BOOST_CHECK_EQUAL(a.width(), 8); BOOST_CHECK_EQUAL(a.minVal(), -128); BOOST_CHECK_EQUAL(a.maxVal(), 127); } BOOST_AUTO_TEST_CASE( CFxpAssignment ) { CFxp a(1, 2, 8); CFxp b(1, 2, 10); CFxp c; CFxp d(1, 2, 8, true); CFxp e(1, 2, 8, false); BOOST_CHECK_THROW(a = b, SizeMismatchException); BOOST_CHECK_NO_THROW(c = a); BOOST_CHECK_EQUAL(c, a); BOOST_CHECK_NO_THROW(d = b); BOOST_CHECK_EQUAL(d, b); BOOST_CHECK_THROW(e = b, SizeMismatchException); } BOOST_AUTO_TEST_CASE( CFxpEquality ) { CFxp a(1, 2, 8); CFxp b(1, 2, 8); CFxp c(1, 2, 10); CFxp d(13, 2, 8); CFxp e(1, 13, 8); CFxp f(24, 38, 21); /* same object as lhs and rhs */ BOOST_CHECK_EQUAL(a == a, true); BOOST_CHECK_EQUAL(a != a, false); /* different equal objects */ BOOST_CHECK_EQUAL(a == b, true); BOOST_CHECK_EQUAL(a != b, false); /* same value, different widths */ BOOST_CHECK_EQUAL(a == c, false); BOOST_CHECK_EQUAL(a != c, true); /* different values, same widths */ BOOST_CHECK_EQUAL(a == d, false); BOOST_CHECK_EQUAL(a != d, true); BOOST_CHECK_EQUAL(a == e, false); BOOST_CHECK_EQUAL(a != e, true); /* everything different */ BOOST_CHECK_EQUAL(a == f, false); BOOST_CHECK_EQUAL(a != f, true); } BOOST_AUTO_TEST_CASE( CFxpScalarMultiplication ) { CFxp a(1, 2, 8); Fxp b(2, 5); /* multiplication by scalar is commutative */ BOOST_CHECK_EQUAL(a * b, b * a); /* width after multiplication by scalar */ BOOST_CHECK_EQUAL((a * b).width(), 13); /* result check */ BOOST_CHECK_EQUAL(a * b, CFxp(2, 4, 13)); } BOOST_AUTO_TEST_CASE( CFxpMultiplication ) { CFxp a(1, 2, 8); CFxp b(2, 5, 5); /* complex multiplication is commutative */ BOOST_CHECK_EQUAL(a * b, b * a); /* chaining works */ BOOST_CHECK_EQUAL(a * a * a, a * a * a); /* width after multiplication */ BOOST_CHECK_EQUAL((a * b).width(), 14); /* result check */ BOOST_CHECK_EQUAL(a * b, CFxp(-8, 9, 14)); } BOOST_AUTO_TEST_CASE( CFxpAddition ) { CFxp a(1, 2, 8); CFxp b(2, 5, 5); /* addition is commutative */ BOOST_CHECK_EQUAL(a + b, b + a); /* chaining works */ BOOST_CHECK_EQUAL(a + a + a, a + a + a); /* width after addition */ BOOST_CHECK_EQUAL((a + b).width(), 9); /* result check */ BOOST_CHECK_EQUAL(a + b, CFxp(3, 7, 9)); } <|endoftext|>
<commit_before>#include "KVUtil.h" #include <QRegExp> #include <QChar> // // Taken from http://stackoverflow.com/a/7047000 // TODO: Change the QRegExp (which is bad) to a QRegularExpression (good). // QString unescape(QString str) { QRegExp rx("(\\\\u[0-9a-fA-F]{4})"); int pos = 0; while ((pos = rx.indexIn(str, pos)) != -1) str.replace(pos++, 6, QChar(rx.cap(1).right(4).toUShort(0, 16))); return str; } <commit_msg>use QRegularExpression instead of QRegExp<commit_after>#include "KVUtil.h" #include <QRegularExpression> #include <QChar> // // Taken from http://stackoverflow.com/a/7047000 // QString unescape(QString str) { QRegularExpression re("(\\\\u[0-9a-fA-F]{4})"); QRegularExpressionMatchIterator it = re.globalMatch(str); while (it.hasNext()) { QRegularExpressionMatch match = it.next(); str.replace(match.capturedStart(), match.capturedLength(), QChar(match.captured(1).right(4).toUShort(0, 16))); } return str; } <|endoftext|>
<commit_before>#include "viewer.hpp" #include <SDL_ttf.h> #include <SDL_image.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/intersect.hpp> #include <glm/gtc/random.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtx/rotate_vector.hpp> #include <algorithm> #include <iostream> Viewer::~Viewer() { TTF_Quit(); SDL_DestroyTexture(m_render_tex); SDL_DestroyRenderer(m_render); SDL_DestroyWindow(m_window); IMG_Quit(); SDL_Quit(); } int Viewer::init() { std::cout << "Start init" << std::endl; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) { std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return 1; } int width = 600; int height = 400; m_window = SDL_CreateWindow("trac0r", 100, 100, width, height, SDL_WINDOW_SHOWN); if (m_window == nullptr) { std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } // m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | // SDL_RENDERER_PRESENTVSYNC); m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED); m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height); m_pixels.resize(width * height, 0); if (m_render == nullptr) { SDL_DestroyWindow(m_window); std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } if (TTF_Init() != 0) { std::cerr << "SDL_ttf could not initialize! SDL_ttf error: " << SDL_GetError() << std::endl; return 1; } // Setup scene SDL_SetRelativeMouseMode(SDL_TRUE); setup_scene(); std::cout << "Finish init" << std::endl; return 0; } void Viewer::setup_scene() { auto triangle = std::make_unique<Triangle>(glm::vec3{0.f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.5f}, glm::vec3{0.3, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.2}); m_scene.push_back(std::move(triangle)); // for (auto i = 0; i < 2; i++) { // auto triangle = std::make_unique<Triangle>(glm::ballRand(5.f), glm::ballRand(5.f), // glm::ballRand(5.f), glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5}); // m_scene.push_back(std::move(triangle)); // } m_camera.pos = {0, 0, 0}; m_camera.dir = {0, 1, 0}; m_camera.up = {0, 0, 1}; m_camera.fov = 90.f; m_camera.near_plane_dist = 0.1f; m_camera.far_plane_dist = 100.f; } glm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) { const auto MAX_DEPTH = 5; if (depth == MAX_DEPTH) return {0, 0, 0}; // check all triangles for collision bool collided = false; glm::vec3 ret_color; for (const auto &tri : m_scene) { glm::vec3 bary_pos; collided = glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos); if (collided) { glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z; auto new_ray_dir = tri->m_normal; new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f)); new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f)); float cos_theta = glm::dot(new_ray_dir, tri->m_normal); glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta; glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1); ret_color = tri->m_emittance + (brdf * reflected); break; } } if (collided) { return ret_color; } else { return {0, 0, 0}; } } void Viewer::mainloop() { // Input SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { shutdown(); } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) { shutdown(); } } } glm::vec3 cam_velocity{0}; const uint8_t *keystates = SDL_GetKeyboardState(0); if (keystates[SDL_SCANCODE_A]) cam_velocity.x += -0.2f; else if (keystates[SDL_SCANCODE_D]) cam_velocity.x += 0.2f; if (keystates[SDL_SCANCODE_W]) cam_velocity.y += 0.2f; else if (keystates[SDL_SCANCODE_S]) cam_velocity.y += -0.2f; m_camera.pos += cam_velocity; // Rendering here int width; int height; SDL_GetWindowSize(m_window, &width, &height); auto aspect_ratio = (float)width / (float)height; int mouse_x; int mouse_y; SDL_GetRelativeMouseState(&mouse_x, &mouse_y); m_camera.dir = glm::rotateX(m_camera.dir, mouse_y * 0.001f); m_camera.dir = glm::rotateZ(m_camera.dir, mouse_x * -0.001f); std::cout << glm::to_string(m_camera.pos) << std::endl; std::cout << glm::to_string(m_camera.dir) << std::endl; glm::mat4 projection_matrix = glm::perspective( m_camera.fov, aspect_ratio, m_camera.near_plane_dist, m_camera.far_plane_dist); glm::mat4 view_matrix = glm::lookAt(m_camera.pos, m_camera.pos + m_camera.dir, m_camera.up); // Sort by distance to camera std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) { return glm::distance(m_camera.pos, tri1->m_centroid) < glm::distance(m_camera.pos, tri2->m_centroid); }); for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) { for (auto x = 0; x < width; x++) { for (auto y = 0; y < height; y++) { glm::vec3 win_coords{x, y, 0}; glm::mat4 model{1.0f}; glm::vec4 viewport{0, 0, width, height}; glm::vec3 object_coords = glm::unProject(win_coords, model * view_matrix, projection_matrix, viewport); glm::vec3 color = intersect_scene(object_coords, m_camera.dir, 0); // std::cout << "r: " << color.r << " g: " << color.g << " b: " << color.b << // std::endl; m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 | int(color.g * 255) << 8 | int(color.b * 255); } } } SDL_SetRenderDrawColor(m_render, glm::linearRand(0, 255), glm::linearRand(0, 255), glm::linearRand(0, 255), 255); SDL_RenderClear(m_render); SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t)); SDL_RenderCopy(m_render, m_render_tex, 0, 0); SDL_RenderPresent(m_render); int current_time = SDL_GetTicks(); double dt = (current_time - m_last_frame_time) / 1000.0; (void)dt; m_last_frame_time = current_time; std::cout << "FPS: " << 1. / dt << std::endl; } SDL_Renderer *Viewer::renderer() { return m_render; } SDL_Window *Viewer::window() { return m_window; } bool Viewer::is_running() { return m_running; } void Viewer::shutdown() { m_running = false; } <commit_msg>More clean up<commit_after>#include "viewer.hpp" #include <SDL_ttf.h> #include <SDL_image.h> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/intersect.hpp> #include <glm/gtc/random.hpp> #include <glm/gtx/string_cast.hpp> #include <glm/gtx/rotate_vector.hpp> #include <algorithm> #include <iostream> Viewer::~Viewer() { TTF_Quit(); SDL_DestroyTexture(m_render_tex); SDL_DestroyRenderer(m_render); SDL_DestroyWindow(m_window); IMG_Quit(); SDL_Quit(); } int Viewer::init() { std::cout << "Start init" << std::endl; if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) != 0) { std::cerr << "SDL_Init error: " << SDL_GetError() << std::endl; return 1; } int width = 600; int height = 400; m_window = SDL_CreateWindow("trac0r", 100, 100, width, height, SDL_WINDOW_SHOWN); if (m_window == nullptr) { std::cerr << "SDL_CreateWindow error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } // m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED | // SDL_RENDERER_PRESENTVSYNC); m_render = SDL_CreateRenderer(m_window, -1, SDL_RENDERER_ACCELERATED); m_render_tex = SDL_CreateTexture(m_render, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, width, height); m_pixels.resize(width * height, 0); if (m_render == nullptr) { SDL_DestroyWindow(m_window); std::cerr << "SDL_CreateRenderer error: " << SDL_GetError() << std::endl; SDL_Quit(); return 1; } if (TTF_Init() != 0) { std::cerr << "SDL_ttf could not initialize! SDL_ttf error: " << SDL_GetError() << std::endl; return 1; } // Setup scene SDL_SetRelativeMouseMode(SDL_TRUE); setup_scene(); std::cout << "Finish init" << std::endl; return 0; } void Viewer::setup_scene() { auto triangle = std::make_unique<Triangle>(glm::vec3{0.f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.f}, glm::vec3{0.5f, 5.f, 0.5f}, glm::vec3{0.3, 0.3, 0.3}, glm::vec3{0.2, 0.2, 0.2}); m_scene.push_back(std::move(triangle)); // for (auto i = 0; i < 2; i++) { // auto triangle = std::make_unique<Triangle>(glm::ballRand(5.f), glm::ballRand(5.f), // glm::ballRand(5.f), glm::vec3{0.8, 0.3, 0.3}, glm::vec3{0.5, 0.5, 0.5}); // m_scene.push_back(std::move(triangle)); // } m_camera.pos = {0, 0, 0}; m_camera.dir = {0, 1, 0}; m_camera.up = {0, 0, 1}; m_camera.fov = glm::radians(90.f); m_camera.near_plane_dist = 0.1f; m_camera.far_plane_dist = 100.f; } glm::vec3 Viewer::intersect_scene(glm::vec3 &ray_pos, glm::vec3 &ray_dir, int depth) { const auto MAX_DEPTH = 5; if (depth == MAX_DEPTH) return {0, 0, 0}; // check all triangles for collision bool collided = false; glm::vec3 ret_color; for (const auto &tri : m_scene) { glm::vec3 bary_pos; collided = glm::intersectRayTriangle(ray_pos, ray_dir, tri->m_v1, tri->m_v2, tri->m_v3, bary_pos); if (collided) { glm::vec3 new_ray_pos = ray_pos + ray_dir * bary_pos.z; auto new_ray_dir = tri->m_normal; new_ray_dir = glm::rotateX(tri->m_normal, glm::linearRand(-90.f, 90.f)); new_ray_dir = glm::rotateY(tri->m_normal, glm::linearRand(-90.f, 90.f)); float cos_theta = glm::dot(new_ray_dir, tri->m_normal); glm::vec3 brdf = 2.f * tri->m_reflectance * cos_theta; glm::vec3 reflected = intersect_scene(new_ray_pos, new_ray_dir, depth + 1); ret_color = tri->m_emittance + (brdf * reflected); break; } } if (collided) { return ret_color; } else { return {0, 0, 0}; } } void Viewer::mainloop() { // Input SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { shutdown(); } if (e.type == SDL_KEYDOWN) { if (e.key.keysym.sym == SDLK_ESCAPE) { shutdown(); } } } glm::vec3 cam_velocity{0}; const uint8_t *keystates = SDL_GetKeyboardState(0); if (keystates[SDL_SCANCODE_A]) cam_velocity.x += -0.2f; else if (keystates[SDL_SCANCODE_D]) cam_velocity.x += 0.2f; if (keystates[SDL_SCANCODE_W]) cam_velocity.y += 0.2f; else if (keystates[SDL_SCANCODE_S]) cam_velocity.y += -0.2f; m_camera.pos += cam_velocity; // Rendering here int width; int height; SDL_GetWindowSize(m_window, &width, &height); auto aspect_ratio = (float)width / (float)height; int mouse_x; int mouse_y; SDL_GetRelativeMouseState(&mouse_x, &mouse_y); m_camera.dir = glm::rotateX(m_camera.dir, mouse_y * 0.001f); m_camera.dir = glm::rotateZ(m_camera.dir, mouse_x * -0.001f); std::cout << glm::to_string(m_camera.pos) << std::endl; std::cout << glm::to_string(m_camera.dir) << std::endl; glm::mat4 projection = glm::perspective(m_camera.fov, aspect_ratio, m_camera.near_plane_dist, m_camera.far_plane_dist); glm::mat4 view = glm::lookAt(m_camera.pos, m_camera.pos + m_camera.dir, m_camera.up); // Sort by distance to camera std::sort(m_scene.begin(), m_scene.end(), [this](const auto &tri1, const auto &tri2) { return glm::distance(m_camera.pos, tri1->m_centroid) < glm::distance(m_camera.pos, tri2->m_centroid); }); for (auto sample_cnt = 0; sample_cnt < 2; sample_cnt++) { for (auto x = 0; x < width; x++) { for (auto y = 0; y < height; y++) { glm::vec3 win_coords{x, y, 0}; glm::mat4 model{1.0f}; glm::vec4 viewport{0, 0, width, height}; glm::vec3 object_coords = glm::unProject(win_coords, model * view, projection, viewport); glm::vec3 color = intersect_scene(object_coords, m_camera.dir, 0); m_pixels[y * width + x] = 0xff << 24 | int(color.r * 255) << 16 | int(color.g * 255) << 8 | int(color.b * 255); } } } SDL_SetRenderDrawColor(m_render, glm::linearRand(0, 255), glm::linearRand(0, 255), glm::linearRand(0, 255), 255); SDL_RenderClear(m_render); SDL_UpdateTexture(m_render_tex, 0, m_pixels.data(), width * sizeof(uint32_t)); SDL_RenderCopy(m_render, m_render_tex, 0, 0); SDL_RenderPresent(m_render); int current_time = SDL_GetTicks(); double dt = (current_time - m_last_frame_time) / 1000.0; (void)dt; m_last_frame_time = current_time; std::cout << "FPS: " << 1. / dt << std::endl; } SDL_Renderer *Viewer::renderer() { return m_render; } SDL_Window *Viewer::window() { return m_window; } bool Viewer::is_running() { return m_running; } void Viewer::shutdown() { m_running = false; } <|endoftext|>
<commit_before>TCanvas *vC1; TGraph *grxy, *grin, *grout; void approx() { /****************************************************************************** * Author: Christian Stratowa, Vienna, Austria. * * Created: 26 Aug 2001 Last modified: 29 Sep 2001 * ******************************************************************************/ // Macro to test interpolation function Approx() // test data (square) Int_t n = 11; Double_t x[] = {1,2,3,4,5,6,6,6,8,9,10}; Double_t y[] = {1,4,9,16,25,25,36,49,64,81,100}; grxy = new TGraph(n,x,y); // x values, for which y values should be interpolated Int_t nout = 14; Double_t xout[] = {1.2,1.7,2.5,3.2,4.4,5.2,5.7,6.5,7.6,8.3,9.7,10.4,11.3,13}; // create Canvas vC1 = new TCanvas("vC1","square",200,10,700,700); vC1->Divide(2,2); // initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use mean for tied x-values) TGraphSmooth *gs = new TGraphSmooth("normal"); grout = gs->Approx(grin,"linear"); DrawSmooth(1,"Approx: ties = mean","X-axis","Y-axis"); // re-initialize graph with data (since graph points were set to unique vales) grin = new TGraph(n,x,y); // interpolate at given points xout grout = gs->Approx(grin,"linear", 14, xout, 0, 130); DrawSmooth(2,"Approx: ties = mean","",""); // print output variables for given values xout Int_t vNout = grout->GetN(); Double_t vXout, vYout; for (Int_t k=0;k<vNout;k++) { grout->GetPoint(k, vXout, vYout); cout << "k= " << k << " vXout[k]= " << vXout << " vYout[k]= " << vYout << endl; } // re-initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use min for tied x-values) // grout = gs->Approx(grin,"linear", 50, 0, 0, 0, 1, 0, "min"); grout = gs->Approx(grin,"constant", 50, 0, 0, 0, 1, 0.5, "min"); DrawSmooth(3,"Approx: ties = min","",""); // re-initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use max for tied x-values) grout = gs->Approx(grin,"linear", 14, xout, 0, 0, 2, 0, "max"); DrawSmooth(4,"Approx: ties = max","",""); // cleanup delete gs; } void DrawSmooth(Int_t pad, const char *title, const char *xt, const char *yt) { vC1->cd(pad); TH1F *vFrame = vC1->DrawFrame(0,0,15,150); vFrame->SetTitle(title); vFrame->SetTitleSize(0.2); vFrame->SetXTitle(xt); vFrame->SetYTitle(yt); grxy->SetMarkerColor(kBlue); grxy->SetMarkerStyle(21); grxy->SetMarkerSize(0.5); grxy->Draw("P"); grin->SetMarkerColor(kRed); grin->SetMarkerStyle(5); grin->SetMarkerSize(0.7); grin->Draw("P"); grout->DrawClone("LP"); } <commit_msg>Use gPad->DrawFrame instead of VC1->DrawFrame<commit_after>TCanvas *vC1; TGraph *grxy, *grin, *grout; void approx() { /****************************************************************************** * Author: Christian Stratowa, Vienna, Austria. * * Created: 26 Aug 2001 Last modified: 29 Sep 2001 * ******************************************************************************/ // Macro to test interpolation function Approx() // test data (square) Int_t n = 11; Double_t x[] = {1,2,3,4,5,6,6,6,8,9,10}; Double_t y[] = {1,4,9,16,25,25,36,49,64,81,100}; grxy = new TGraph(n,x,y); // x values, for which y values should be interpolated Int_t nout = 14; Double_t xout[] = {1.2,1.7,2.5,3.2,4.4,5.2,5.7,6.5,7.6,8.3,9.7,10.4,11.3,13}; // create Canvas vC1 = new TCanvas("vC1","square",200,10,700,700); vC1->Divide(2,2); // initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use mean for tied x-values) TGraphSmooth *gs = new TGraphSmooth("normal"); grout = gs->Approx(grin,"linear"); DrawSmooth(1,"Approx: ties = mean","X-axis","Y-axis"); // re-initialize graph with data (since graph points were set to unique vales) grin = new TGraph(n,x,y); // interpolate at given points xout grout = gs->Approx(grin,"linear", 14, xout, 0, 130); DrawSmooth(2,"Approx: ties = mean","",""); // print output variables for given values xout Int_t vNout = grout->GetN(); Double_t vXout, vYout; for (Int_t k=0;k<vNout;k++) { grout->GetPoint(k, vXout, vYout); cout << "k= " << k << " vXout[k]= " << vXout << " vYout[k]= " << vYout << endl; } // re-initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use min for tied x-values) // grout = gs->Approx(grin,"linear", 50, 0, 0, 0, 1, 0, "min"); grout = gs->Approx(grin,"constant", 50, 0, 0, 0, 1, 0.5, "min"); DrawSmooth(3,"Approx: ties = min","",""); // re-initialize graph with data grin = new TGraph(n,x,y); // interpolate at equidistant points (use max for tied x-values) grout = gs->Approx(grin,"linear", 14, xout, 0, 0, 2, 0, "max"); DrawSmooth(4,"Approx: ties = max","",""); // cleanup delete gs; } void DrawSmooth(Int_t pad, const char *title, const char *xt, const char *yt) { vC1->cd(pad); TH1F *vFrame = gPad->DrawFrame(0,0,15,150); vFrame->SetTitle(title); vFrame->SetTitleSize(0.2); vFrame->SetXTitle(xt); vFrame->SetYTitle(yt); grxy->SetMarkerColor(kBlue); grxy->SetMarkerStyle(21); grxy->SetMarkerSize(0.5); grxy->Draw("P"); grin->SetMarkerColor(kRed); grin->SetMarkerStyle(5); grin->SetMarkerSize(0.7); grin->Draw("P"); grout->DrawClone("LP"); } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2003 by krecipes.sourceforge.net authors * * * * * * 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 "kreimporter.h" #include <klocale.h> #include <qfile.h> #include <qstringlist.h> #include "recipe.h" KreImporter::KreImporter(const QString& filename) { QFile* file = 0; bool unlink = false; qDebug("loading file: %s",filename.latin1()); if(filename.right(6) == ".kreml"){ file = new QFile( filename ); } else if(filename.right(4) == ".kre"){ qDebug("file is an archive"); KTar* kre = new KTar(filename, "application/x-gzip"); kre->open( IO_ReadOnly ); const KArchiveDirectory* dir = kre->directory(); QString name; QStringList fileList = dir->entries(); for ( QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it ) { if( (*it).right(6) == ".kreml" ){ name = *it; } } if(name == QString::null){ qDebug("error: Archive doesn't contain a valid krecipes file"); setErrorMsg( i18n("error: Archive doesn't contain a valid krecipes file") ); return; } dir->copyTo("/tmp/"); file = new QFile( "/tmp/"+name ); kre->close(); unlink = true; //remove file after import } if ( file->open( IO_ReadOnly ) ) { qDebug("file opened"); QDomDocument doc; QString error; int line; int column; if (!doc.setContent(file,&error,&line,&column)) { qDebug("error: \"%s\" at line %d, column %d",error.latin1(),line,column); setErrorMsg( QString( i18n("\"%1\" at line %2, column %3") ).arg(error).arg(line).arg(column) ); return; } QDomElement kreml = doc.documentElement(); if (kreml.tagName() != "krecipes") { setErrorMsg( i18n("This file doesn't appear to be a *.kreml file") ); return; } // TODO Check if there are changes between versions QString kreVersion = kreml.attribute("version"); qDebug(QString( i18n("KreML version %1") ).arg(kreVersion)); QDomNodeList r = kreml.childNodes(); QDomElement krecipe; for (unsigned z = 0; z < r.count(); z++) { krecipe = r.item(z).toElement(); QDomNodeList l = krecipe.childNodes(); QDomElement el; if(krecipe.tagName() == "krecipes-recipe"){ Recipe *recipe = new Recipe; for (unsigned i = 0; i < l.count(); i++) { el = l.item(i).toElement(); if (el.tagName() == "krecipes-description"){ readDescription(el.childNodes(), recipe); } if (el.tagName() == "krecipes-ingredients"){ readIngredients(el.childNodes(), recipe); } if (el.tagName() == "krecipes-instructions"){ recipe->instructions = el.text(); } } add(recipe); } } } if(unlink){ file->remove(); } } KreImporter::~KreImporter() { } void KreImporter::readDescription(const QDomNodeList& l, Recipe *recipe) { ElementList authors; ElementList categoryList; for (unsigned i = 0; i < l.count(); i++) { QDomElement el = l.item(i).toElement(); if (el.tagName() == "title"){ recipe->title = el.text(); qDebug("Found title: %s",recipe->title.latin1()); } else if (el.tagName() == "author"){ Element author; author.name = el.text(); qDebug("Found author: %s",author.name.latin1()); authors.add(author); } else if (el.tagName() == "serving"){ recipe->persons = el.text().toInt(); } else if (el.tagName() == "category"){ QDomNodeList categories = el.childNodes(); for (unsigned j=0; j < categories.count(); j++) { QDomElement c = categories.item(j).toElement(); if (c.tagName() == "cat"){ Element new_cat; new_cat.name = QString(c.text()).stripWhiteSpace(); qDebug("Found category: %s", new_cat.name.latin1() ); categoryList.add( new_cat ); } } } else if (el.tagName() == "pictures"){ if (el.hasChildNodes()) { QDomNodeList pictures = el.childNodes(); for (unsigned j=0; j < pictures.count(); j++){ QDomElement pic = pictures.item(j).toElement(); QCString decodedPic; if (pic.tagName() == "pic") qDebug("Found photo"); QPixmap pix; KCodecs::base64Decode(QCString(pic.text()), decodedPic); int len = decodedPic.size(); QByteArray picData(len); memcpy(picData.data(),decodedPic.data(),len); bool ok = pix.loadFromData(picData, "JPEG"); if(ok){ recipe->photo = pix; } } } } } recipe->categoryList = categoryList; recipe->authorList = authors; } void KreImporter::readIngredients(const QDomNodeList& l, Recipe *recipe) { IngredientList ingredientList; for (unsigned i=0; i < l.count(); i++){ QDomElement el = l.item(i).toElement(); if (el.tagName() == "ingredient"){ QDomNodeList ingredient = el.childNodes(); Ingredient new_ing; for (unsigned j=0; j < ingredient.count(); j++){ QDomElement ing = ingredient.item(j).toElement(); if (ing.tagName() == "name"){ new_ing.name = QString(ing.text()).stripWhiteSpace(); qDebug("Found ingredient: %s", new_ing.name.latin1() ); } else if (ing.tagName() == "amount"){ new_ing.amount = (QString(ing.text()).stripWhiteSpace()).toDouble(); } else if (ing.tagName() == "unit"){ new_ing.units = QString(ing.text()).stripWhiteSpace(); } } ingredientList.add( new_ing ); } } recipe->ingList = ingredientList; } <commit_msg>Fix crash when loading file without valid extention; display error message<commit_after>/*************************************************************************** * Copyright (C) 2003 by krecipes.sourceforge.net authors * * * * * * 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 "kreimporter.h" #include <klocale.h> #include <qfile.h> #include <qstringlist.h> #include "recipe.h" KreImporter::KreImporter(const QString& filename) { QFile* file = 0; bool unlink = false; qDebug("loading file: %s",filename.latin1()); if(filename.right(6) == ".kreml"){ file = new QFile( filename ); } else if(filename.right(4) == ".kre"){ qDebug("file is an archive"); KTar* kre = new KTar(filename, "application/x-gzip"); kre->open( IO_ReadOnly ); const KArchiveDirectory* dir = kre->directory(); QString name; QStringList fileList = dir->entries(); for ( QStringList::Iterator it = fileList.begin(); it != fileList.end(); ++it ) { if( (*it).right(6) == ".kreml" ){ name = *it; } } if(name == QString::null){ qDebug("error: Archive doesn't contain a valid krecipes file"); setErrorMsg( i18n("Archive doesn't contain a valid krecipes file") ); return; } dir->copyTo("/tmp/"); file = new QFile( "/tmp/"+name ); kre->close(); unlink = true; //remove file after import } else { setErrorMsg( i18n("File extention doesn't match that of a valid Krecipes file.") ); return; } if ( file->open( IO_ReadOnly ) ) { qDebug("file opened"); QDomDocument doc; QString error; int line; int column; if (!doc.setContent(file,&error,&line,&column)) { qDebug("error: \"%s\" at line %d, column %d",error.latin1(),line,column); setErrorMsg( QString( i18n("\"%1\" at line %2, column %3") ).arg(error).arg(line).arg(column) ); return; } QDomElement kreml = doc.documentElement(); if (kreml.tagName() != "krecipes") { setErrorMsg( i18n("This file doesn't appear to be a *.kreml file") ); return; } // TODO Check if there are changes between versions QString kreVersion = kreml.attribute("version"); qDebug(QString( i18n("KreML version %1") ).arg(kreVersion)); QDomNodeList r = kreml.childNodes(); QDomElement krecipe; for (unsigned z = 0; z < r.count(); z++) { krecipe = r.item(z).toElement(); QDomNodeList l = krecipe.childNodes(); QDomElement el; if(krecipe.tagName() == "krecipes-recipe"){ Recipe *recipe = new Recipe; for (unsigned i = 0; i < l.count(); i++) { el = l.item(i).toElement(); if (el.tagName() == "krecipes-description"){ readDescription(el.childNodes(), recipe); } if (el.tagName() == "krecipes-ingredients"){ readIngredients(el.childNodes(), recipe); } if (el.tagName() == "krecipes-instructions"){ recipe->instructions = el.text(); } } add(recipe); } } } if(unlink){ file->remove(); } } KreImporter::~KreImporter() { } void KreImporter::readDescription(const QDomNodeList& l, Recipe *recipe) { ElementList authors; ElementList categoryList; for (unsigned i = 0; i < l.count(); i++) { QDomElement el = l.item(i).toElement(); if (el.tagName() == "title"){ recipe->title = el.text(); qDebug("Found title: %s",recipe->title.latin1()); } else if (el.tagName() == "author"){ Element author; author.name = el.text(); qDebug("Found author: %s",author.name.latin1()); authors.add(author); } else if (el.tagName() == "serving"){ recipe->persons = el.text().toInt(); } else if (el.tagName() == "category"){ QDomNodeList categories = el.childNodes(); for (unsigned j=0; j < categories.count(); j++) { QDomElement c = categories.item(j).toElement(); if (c.tagName() == "cat"){ Element new_cat; new_cat.name = QString(c.text()).stripWhiteSpace(); qDebug("Found category: %s", new_cat.name.latin1() ); categoryList.add( new_cat ); } } } else if (el.tagName() == "pictures"){ if (el.hasChildNodes()) { QDomNodeList pictures = el.childNodes(); for (unsigned j=0; j < pictures.count(); j++){ QDomElement pic = pictures.item(j).toElement(); QCString decodedPic; if (pic.tagName() == "pic") qDebug("Found photo"); QPixmap pix; KCodecs::base64Decode(QCString(pic.text()), decodedPic); int len = decodedPic.size(); QByteArray picData(len); memcpy(picData.data(),decodedPic.data(),len); bool ok = pix.loadFromData(picData, "JPEG"); if(ok){ recipe->photo = pix; } } } } } recipe->categoryList = categoryList; recipe->authorList = authors; } void KreImporter::readIngredients(const QDomNodeList& l, Recipe *recipe) { IngredientList ingredientList; for (unsigned i=0; i < l.count(); i++){ QDomElement el = l.item(i).toElement(); if (el.tagName() == "ingredient"){ QDomNodeList ingredient = el.childNodes(); Ingredient new_ing; for (unsigned j=0; j < ingredient.count(); j++){ QDomElement ing = ingredient.item(j).toElement(); if (ing.tagName() == "name"){ new_ing.name = QString(ing.text()).stripWhiteSpace(); qDebug("Found ingredient: %s", new_ing.name.latin1() ); } else if (ing.tagName() == "amount"){ new_ing.amount = (QString(ing.text()).stripWhiteSpace()).toDouble(); } else if (ing.tagName() == "unit"){ new_ing.units = QString(ing.text()).stripWhiteSpace(); } } ingredientList.add( new_ing ); } } recipe->ingList = ingredientList; } <|endoftext|>
<commit_before>#include "config.h" #include "ylib.h" #include "ylocale.h" #include "yapp.h" #include "yxtray.h" extern void logEvent(const XEvent &xev); char const *ApplicationName = "icewmtray"; YColor *taskBarBg; class SysTray: public YWindow, public YXTrayNotifier { public: SysTray(); bool checkMessageEvent(const XClientMessageEvent &message); void requestDock(); void handleUnmap(const XUnmapEvent &) { puts("hidexxx"); if (visible()) hide(); } void trayChanged(); private: Atom icewm_internal_tray; Atom _NET_SYSTEM_TRAY_OPCODE; YXTray *fTray2; }; class SysTrayApp: public YApplication { public: SysTrayApp(int *argc, char ***argv, const char *displayName = 0); ~SysTrayApp(); bool filterEvent(const XEvent &xev); private: SysTray *tray; }; SysTrayApp::SysTrayApp(int *argc, char ***argv, const char *displayName): YApplication(argc, argv, displayName) { desktop->setStyle(YWindow::wsDesktopAware); tray = new SysTray(); } SysTrayApp::~SysTrayApp() { } bool SysTrayApp::filterEvent(const XEvent &xev) { logEvent(xev); if (xev.type == ClientMessage) { tray->checkMessageEvent(xev.xclient); return false; } else if (xev.type == MappingNotify) { puts("tray mapping1"); if (xev.xmapping.window == tray->handle()) { puts("tray mapping"); } } return false; } SysTray::SysTray(): YWindow(0) { desktop->setStyle(YWindow::wsDesktopAware); fTray2 = new YXTray(this, "_NET_SYSTEM_TRAY_S0", this); icewm_internal_tray = XInternAtom(app->display(), "_ICEWM_INTTRAY", False); _NET_SYSTEM_TRAY_OPCODE = XInternAtom(app->display(), "_NET_SYSTEM_TRAY_OPCODE", False); fTray2->relayout(); setSize(fTray2->width(), fTray2->height()); fTray2->show(); requestDock(); } void SysTray::trayChanged() { fTray2->relayout(); setSize(fTray2->width(), fTray2->height()); } void SysTray::requestDock() { Window w = XGetSelectionOwner(app->display(), icewm_internal_tray); if (w && w != handle()) { XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = w; xev.message_type = _NET_SYSTEM_TRAY_OPCODE; xev.format = 32; xev.data.l[0] = CurrentTime; xev.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK; xev.data.l[2] = handle(); //fTray2->handle(); XSendEvent(app->display(), w, False, StructureNotifyMask, (XEvent *) &xev); } } bool SysTray::checkMessageEvent(const XClientMessageEvent &message) { if (message.message_type == icewm_internal_tray) { puts("requestDock"); requestDock(); } return true; } int main(int argc, char **argv) { YLocale locale; SysTrayApp app(&argc, &argv); taskBarBg = new YColor("#C0C0C0"); /// FIXME return app.mainLoop(); } <commit_msg>build fix<commit_after>#include "config.h" #include "ylib.h" #include "ylocale.h" #include "yapp.h" #include "yxtray.h" extern void logEvent(const XEvent &xev); char const *ApplicationName = "icewmtray"; YColor *taskBarBg; class SysTray: public YWindow, public YXTrayNotifier { public: SysTray(); bool checkMessageEvent(const XClientMessageEvent &message); void requestDock(); void handleUnmap(const XUnmapEvent &) { puts("hidexxx"); if (visible()) hide(); } void trayChanged(); private: Atom icewm_internal_tray; Atom _NET_SYSTEM_TRAY_OPCODE; YXTray *fTray2; }; class SysTrayApp: public YApplication { public: SysTrayApp(int *argc, char ***argv, const char *displayName = 0); ~SysTrayApp(); bool filterEvent(const XEvent &xev); private: SysTray *tray; }; SysTrayApp::SysTrayApp(int *argc, char ***argv, const char *displayName): YApplication(argc, argv, displayName) { desktop->setStyle(YWindow::wsDesktopAware); tray = new SysTray(); } SysTrayApp::~SysTrayApp() { } bool SysTrayApp::filterEvent(const XEvent &xev) { #ifdef DEBUG logEvent(xev); #endif if (xev.type == ClientMessage) { tray->checkMessageEvent(xev.xclient); return false; } else if (xev.type == MappingNotify) { puts("tray mapping1"); if (xev.xmapping.window == tray->handle()) { puts("tray mapping"); } } return false; } SysTray::SysTray(): YWindow(0) { desktop->setStyle(YWindow::wsDesktopAware); fTray2 = new YXTray(this, "_NET_SYSTEM_TRAY_S0", this); icewm_internal_tray = XInternAtom(app->display(), "_ICEWM_INTTRAY", False); _NET_SYSTEM_TRAY_OPCODE = XInternAtom(app->display(), "_NET_SYSTEM_TRAY_OPCODE", False); fTray2->relayout(); setSize(fTray2->width(), fTray2->height()); fTray2->show(); requestDock(); } void SysTray::trayChanged() { fTray2->relayout(); setSize(fTray2->width(), fTray2->height()); } void SysTray::requestDock() { Window w = XGetSelectionOwner(app->display(), icewm_internal_tray); if (w && w != handle()) { XClientMessageEvent xev; memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.window = w; xev.message_type = _NET_SYSTEM_TRAY_OPCODE; xev.format = 32; xev.data.l[0] = CurrentTime; xev.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK; xev.data.l[2] = handle(); //fTray2->handle(); XSendEvent(app->display(), w, False, StructureNotifyMask, (XEvent *) &xev); } } bool SysTray::checkMessageEvent(const XClientMessageEvent &message) { if (message.message_type == icewm_internal_tray) { puts("requestDock"); requestDock(); } return true; } int main(int argc, char **argv) { YLocale locale; SysTrayApp app(&argc, &argv); taskBarBg = new YColor("#C0C0C0"); /// FIXME return app.mainLoop(); } <|endoftext|>
<commit_before>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using namespace random_generator; // Default Size struct constructor. Size::Size(): internals{0}, leaves{0} {} // Available methods for tree creation. enum class Method {grow, full}; // List of valid functions for an expression. enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward}; using F = Function; // Vectors of same-arity function enums. vector<F> nullaries {F::left, F::right, F::forward}; vector<F> binaries {F::prog2, F::iffoodahead}; vector<F> trinaries {F::prog3}; /* Vectors of available function enums. Should be moved into Options struct. */ vector<F> leaves = nullaries; vector<F> internals {F::prog2, F::prog3, F::iffoodahead}; // Returns a random function from a given set of functions. Function get_function(const vector <Function>& functions) { int_dist dist{0, static_cast<int>(functions.size()) - 1}; // closed interval return functions[dist(rg.engine)]; } // Returns bool of whether or not the item is in the set. template<typename I, typename S> bool contains(const I& item, const S& set) { return std::find(set.begin(), set.end(), item) != set.end(); } // Returns the appropriate arity for a given function. unsigned int get_arity(const Function& function) { if (contains(function, nullaries)) return 0; else if (contains(function, binaries)) return 2; else if (contains(function, trinaries)) return 3; assert(false); } // Default constructor for "empty" node Node::Node(): function{Function::nil}, arity{0} {} /* Recursively constructs a parse tree using the given method (either GROW or FULL). */ Node::Node(const Method& method, const unsigned int& max_depth) { // Create terminal node if at the max depth or randomly (if growing). real_dist dist{0, 1}; float grow_chance = static_cast<float>(leaves.size()) / (leaves.size() + internals.size()); if (max_depth == 0 or (method == Method::grow and dist(rg.engine) < grow_chance)) { function = get_function(leaves); arity = get_arity(function); } // Otherwise choose a non-terminal node. else { function = get_function(internals); arity = get_arity(function); // Recursively create subtrees. for (unsigned int i = 0; i < arity; ++i) children.emplace_back(Node{method, max_depth - 1}); } assert(function != Function::nil); // do not create null types assert(children.size() == arity); // ensure arity } // Returns a string visually representing a particular node. string Node::represent() const { switch (function) { case F::nil: assert(false); // Never represent empty node. case F::prog2: return "prog-2"; case F::prog3: return "prog-3"; case F::iffoodahead: return "if-food-ahead"; case F::left: return "left"; case F::right: return "right"; case F::forward: return "forward"; } assert(false); // Every node should have been matched. } /* Returns string representation of expression in Polish/prefix notation using a pre-order traversal. */ string Node::print() const { if (children.size() == 0) return represent(); string formula = "(" + represent(); for (const Node& child : children) formula += " " + child.print(); return formula + ")"; } /* Evaluates an ant over a given map using a depth-first post-order recursive continuous evaluation of a decision tree. */ void Node::evaluate(options::Map& map) const { if (not map.active()) return; switch (function) { case F::nil: assert(false); // Never evaluate empty node case F::left: map.left(); // Terminal case break; case F::right: map.right(); // Terminal case break; case F::forward: map.forward(); // Terminal case break; case F::prog2: // Falls through case F::prog3: for (const Node& child : children) child.evaluate(map); break; case F::iffoodahead: if (map.look()) // Do left or right depending on if food ahead children[0].evaluate(map); else children[1].evaluate(map); break; } } /* Recursively count children via post-order traversal. Keep track of internals and leaves via Size struct */ const Size Node::size() const { Size size; for (const Node& child : children) { Size temp = child.size(); size.internals += temp.internals; size.leaves += temp.leaves; } if (children.size() == 0) ++size.leaves; else ++size.internals; return size; } // Used to represent "not-found" (similar to a NULL pointer). Node empty; /* Depth-first search for taget node. Must be seeking either internal or leaf, cannot be both. */ Node& Node::visit(const Size& i, Size& visiting) { for (Node& child : children) { // Increase relevant count. if (child.children.size() == 0) ++visiting.leaves; else ++visiting.internals; // Return node reference if found. if (visiting.internals == i.internals or visiting.leaves == i.leaves) return child; else { Node& temp = child.visit(i, visiting); // Recursive search. if (temp.function != Function::nil) return temp; } } return empty; } // TODO: implement mutations of individual nodes void Node::mutate_self() { if (arity == 0) { const Function old = function; while (function == old) function = get_function(leaves); } else { const Function old = function; while (function == old) function = get_function(internals); arity = get_arity(function); // Fix arity mismatches caused by mutation if (arity == 2 and children.size() == 3) children.pop_back(); else if (arity == 3 and children.size() == 2) { int_dist depth_dist{0, 4}; real_dist dist{0, 1}; unsigned int depth = depth_dist(rg.engine); Method method = (dist(rg.engine) < 0.5) ? Method::grow : Method::full; children.emplace_back(Node{method, depth}); } } assert(arity == children.size()); assert(function != Function::nil); } // Recursively mutate nodes with given probability. void Node::mutate_tree(const float& chance) { real_dist dist{0, 1}; for (Node& child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } // Default constructor for Individual Individual::Individual() {} /* Create an Individual tree by having a root node (to which the actual construction is delegated). The depth is passed by value as its creation elsewhere is temporary. */ Individual::Individual(const unsigned int depth, const float& chance, options::Map map): fitness{0}, adjusted{0} { // 50/50 chance to choose grow or full real_dist dist{0, 1}; Method method = (dist(rg.engine) < chance) ? Method::grow : Method::full; root = Node{method, depth}; /* The evaluate method updates the size and both raw and adjusted fitnesses. */ evaluate(map); } // Return string representation of a tree's size and fitness. string Individual::print() const { using std::to_string; string info = "# Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leaves()) + " leaves.\n" + "# Raw fitness: " + to_string(score) + ", and adjusted: " + to_string(adjusted) + ".\n"; return info; } // Return string represenation of tree's expression (delegated). string Individual::print_formula() const { return "# Formula: " + root.print() + "\n"; } // Read-only "getters" for private data unsigned int Individual::get_internals() const { return size.internals; } unsigned int Individual::get_leaves() const { return size.leaves; } unsigned int Individual::get_total() const { return size.internals + size.leaves; } unsigned int Individual::get_score() const { return score; } float Individual::get_fitness() const { return fitness; } float Individual::get_adjusted() const { return adjusted; } /* Evaluate Individual for given values and calculate size. Update Individual's size and fitness accordingly. Return non-empty string if printing. */ string Individual::evaluate(options::Map map, const float& penalty, const bool& print) { // Update size on evaluation because it's incredibly convenient. size = root.size(); while (map.active()) root.evaluate(map); score = map.fitness(); // Adjusted fitness does not have size penalty. adjusted = static_cast<float>(score) / map.max(); // Apply size penalty if not printing. fitness = score - penalty * get_total(); string evaluation; if (print) evaluation = map.print(); return evaluation; } // Mutate each node with given probability. void Individual::mutate(const float& chance) { root.mutate_tree(chance); } // Safely return reference to desired node. Node& Individual::operator[](const Size& i) { assert(i.internals <= get_internals()); assert(i.leaves <= get_leaves()); Size visiting; // Return root node if that's what we're seeking. if (i.internals == 0 and i.leaves == 0) return root; else return root.visit(i, visiting); } /* Swap two random subtrees between Individuals "a" and "b", selecting an internal node with chance probability. TODO: DRY */ void crossover(const float& chance, Individual& a, Individual& b) { real_dist probability{0, 1}; Size target_a, target_b; // Guaranteed to have at least 1 leaf, but may have 0 internals. if (a.get_internals() != 0 and probability(rg.engine) < chance) { // Choose an internal node. int_dist dist{0, static_cast<int>(a.get_internals()) - 1}; target_a.internals = dist(rg.engine); } else { // Otherwise choose a leaf node. int_dist dist{0, static_cast<int>(a.get_leaves()) - 1}; target_a.leaves = dist(rg.engine); } // Totally repeating myself here for "b". if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, static_cast<int>(b.get_internals()) - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, static_cast<int>(b.get_leaves()) - 1}; target_b.leaves = dist(rg.engine); } std::swap(a[target_a], b[target_b]); } } <commit_msg>Reserving children vector memory for arity<commit_after>/* indivudal.cpp - CS 472 Project #2: Genetic Programming * Copyright 2014 Andrew Schwartzmeyer * * Source file for individual namespace */ #include <algorithm> #include <cassert> #include <cmath> #include <iostream> #include <memory> #include <tuple> #include <vector> #include "individual.hpp" #include "../options/options.hpp" #include "../random_generator/random_generator.hpp" namespace individual { using std::vector; using std::string; using namespace random_generator; // Default Size struct constructor. Size::Size(): internals{0}, leaves{0} {} // Available methods for tree creation. enum class Method {grow, full}; // List of valid functions for an expression. enum class Function {nil, prog2, prog3, iffoodahead, left, right, forward}; using F = Function; // Vectors of same-arity function enums. vector<F> nullaries {F::left, F::right, F::forward}; vector<F> binaries {F::prog2, F::iffoodahead}; vector<F> trinaries {F::prog3}; /* Vectors of available function enums. Should be moved into Options struct. */ vector<F> leaves = nullaries; vector<F> internals {F::prog2, F::prog3, F::iffoodahead}; // Returns a random function from a given set of functions. Function get_function(const vector <Function>& functions) { int_dist dist{0, static_cast<int>(functions.size()) - 1}; // closed interval return functions[dist(rg.engine)]; } // Returns bool of whether or not the item is in the set. template<typename I, typename S> bool contains(const I& item, const S& set) { return std::find(set.begin(), set.end(), item) != set.end(); } // Returns the appropriate arity for a given function. unsigned int get_arity(const Function& function) { if (contains(function, nullaries)) return 0; else if (contains(function, binaries)) return 2; else if (contains(function, trinaries)) return 3; assert(false); } // Default constructor for "empty" node Node::Node(): function{Function::nil}, arity{0} {} /* Recursively constructs a parse tree using the given method (either GROW or FULL). */ Node::Node(const Method& method, const unsigned int& max_depth) { // Create terminal node if at the max depth or randomly (if growing). real_dist dist{0, 1}; float grow_chance = static_cast<float>(leaves.size()) / (leaves.size() + internals.size()); if (max_depth == 0 or (method == Method::grow and dist(rg.engine) < grow_chance)) { function = get_function(leaves); arity = get_arity(function); } // Otherwise choose a non-terminal node. else { function = get_function(internals); arity = get_arity(function); // Recursively create subtrees. children.reserve(arity); for (unsigned int i = 0; i < arity; ++i) children.emplace_back(Node{method, max_depth - 1}); } assert(function != Function::nil); // do not create null types assert(children.size() == arity); // ensure arity } // Returns a string visually representing a particular node. string Node::represent() const { switch (function) { case F::nil: assert(false); // Never represent empty node. case F::prog2: return "prog-2"; case F::prog3: return "prog-3"; case F::iffoodahead: return "if-food-ahead"; case F::left: return "left"; case F::right: return "right"; case F::forward: return "forward"; } assert(false); // Every node should have been matched. } /* Returns string representation of expression in Polish/prefix notation using a pre-order traversal. */ string Node::print() const { if (children.size() == 0) return represent(); string formula = "(" + represent(); for (const Node& child : children) formula += " " + child.print(); return formula + ")"; } /* Evaluates an ant over a given map using a depth-first post-order recursive continuous evaluation of a decision tree. */ void Node::evaluate(options::Map& map) const { if (not map.active()) return; switch (function) { case F::nil: assert(false); // Never evaluate empty node case F::left: map.left(); // Terminal case break; case F::right: map.right(); // Terminal case break; case F::forward: map.forward(); // Terminal case break; case F::prog2: // Falls through case F::prog3: for (const Node& child : children) child.evaluate(map); break; case F::iffoodahead: if (map.look()) // Do left or right depending on if food ahead children[0].evaluate(map); else children[1].evaluate(map); break; } } /* Recursively count children via post-order traversal. Keep track of internals and leaves via Size struct */ const Size Node::size() const { Size size; for (const Node& child : children) { Size temp = child.size(); size.internals += temp.internals; size.leaves += temp.leaves; } if (children.size() == 0) ++size.leaves; else ++size.internals; return size; } // Used to represent "not-found" (similar to a NULL pointer). Node empty; /* Depth-first search for taget node. Must be seeking either internal or leaf, cannot be both. */ Node& Node::visit(const Size& i, Size& visiting) { for (Node& child : children) { // Increase relevant count. if (child.children.size() == 0) ++visiting.leaves; else ++visiting.internals; // Return node reference if found. if (visiting.internals == i.internals or visiting.leaves == i.leaves) return child; else { Node& temp = child.visit(i, visiting); // Recursive search. if (temp.function != Function::nil) return temp; } } return empty; } // TODO: implement mutations of individual nodes void Node::mutate_self() { if (arity == 0) { const Function old = function; while (function == old) function = get_function(leaves); } else { const Function old = function; while (function == old) function = get_function(internals); arity = get_arity(function); // Fix arity mismatches caused by mutation if (arity == 2 and children.size() == 3) children.pop_back(); else if (arity == 3 and children.size() == 2) { int_dist depth_dist{0, 4}; real_dist dist{0, 1}; unsigned int depth = depth_dist(rg.engine); Method method = (dist(rg.engine) < 0.5) ? Method::grow : Method::full; children.emplace_back(Node{method, depth}); } } assert(arity == children.size()); assert(function != Function::nil); } // Recursively mutate nodes with given probability. void Node::mutate_tree(const float& chance) { real_dist dist{0, 1}; for (Node& child : children) { if (dist(rg.engine) < chance) child.mutate_self(); child.mutate_tree(chance); } } // Default constructor for Individual Individual::Individual() {} /* Create an Individual tree by having a root node (to which the actual construction is delegated). The depth is passed by value as its creation elsewhere is temporary. */ Individual::Individual(const unsigned int depth, const float& chance, options::Map map): fitness{0}, adjusted{0} { // 50/50 chance to choose grow or full real_dist dist{0, 1}; Method method = (dist(rg.engine) < chance) ? Method::grow : Method::full; root = Node{method, depth}; /* The evaluate method updates the size and both raw and adjusted fitnesses. */ evaluate(map); } // Return string representation of a tree's size and fitness. string Individual::print() const { using std::to_string; string info = "# Size " + to_string(get_total()) + ", with " + to_string(get_internals()) + " internals, and " + to_string(get_leaves()) + " leaves.\n" + "# Raw fitness: " + to_string(score) + ", and adjusted: " + to_string(adjusted) + ".\n"; return info; } // Return string represenation of tree's expression (delegated). string Individual::print_formula() const { return "# Formula: " + root.print() + "\n"; } // Read-only "getters" for private data unsigned int Individual::get_internals() const { return size.internals; } unsigned int Individual::get_leaves() const { return size.leaves; } unsigned int Individual::get_total() const { return size.internals + size.leaves; } unsigned int Individual::get_score() const { return score; } float Individual::get_fitness() const { return fitness; } float Individual::get_adjusted() const { return adjusted; } /* Evaluate Individual for given values and calculate size. Update Individual's size and fitness accordingly. Return non-empty string if printing. */ string Individual::evaluate(options::Map map, const float& penalty, const bool& print) { // Update size on evaluation because it's incredibly convenient. size = root.size(); while (map.active()) root.evaluate(map); score = map.fitness(); // Adjusted fitness does not have size penalty. adjusted = static_cast<float>(score) / map.max(); // Apply size penalty if not printing. fitness = score - penalty * get_total(); string evaluation; if (print) evaluation = map.print(); return evaluation; } // Mutate each node with given probability. void Individual::mutate(const float& chance) { root.mutate_tree(chance); } // Safely return reference to desired node. Node& Individual::operator[](const Size& i) { assert(i.internals <= get_internals()); assert(i.leaves <= get_leaves()); Size visiting; // Return root node if that's what we're seeking. if (i.internals == 0 and i.leaves == 0) return root; else return root.visit(i, visiting); } /* Swap two random subtrees between Individuals "a" and "b", selecting an internal node with chance probability. TODO: DRY */ void crossover(const float& chance, Individual& a, Individual& b) { real_dist probability{0, 1}; Size target_a, target_b; // Guaranteed to have at least 1 leaf, but may have 0 internals. if (a.get_internals() != 0 and probability(rg.engine) < chance) { // Choose an internal node. int_dist dist{0, static_cast<int>(a.get_internals()) - 1}; target_a.internals = dist(rg.engine); } else { // Otherwise choose a leaf node. int_dist dist{0, static_cast<int>(a.get_leaves()) - 1}; target_a.leaves = dist(rg.engine); } // Totally repeating myself here for "b". if (b.get_internals() != 0 and probability(rg.engine) < chance) { int_dist dist{0, static_cast<int>(b.get_internals()) - 1}; target_b.internals = dist(rg.engine); } else { int_dist dist{0, static_cast<int>(b.get_leaves()) - 1}; target_b.leaves = dist(rg.engine); } std::swap(a[target_a], b[target_b]); } } <|endoftext|>
<commit_before>#pragma once #include <tuple> #include <array> #include <algorithm> #include <utility> #include <type_traits> namespace gcl::ctc::algorithms::tuple { #if not defined(__clang__) and defined(__GNUC__) // Works only on GCC // Currently not supported by : // - MSVC/CL : Request non-variable parameters capture, which is non-legal // - Clang : compiler crash, need to investigate // Shorter crash case sample : https://godbolt.org/z/ovW7b6 template <typename PredicateType, auto... arguments> constexpr auto tuple_erase_if(const PredicateType predicate) { constexpr auto element_if_predicate = [predicate]<auto argument>() consteval { if constexpr (predicate(argument)) return std::tuple<>{}; else return std::tuple{argument}; }; return std::tuple_cat(element_if_predicate.template operator()<arguments>()...); } template <typename TupleType, std::size_t N> using tuple_type_at = typename std::tuple_element_t<N, TupleType>; template <auto... values> constexpr auto tuple_erase_duplicate_values() { constexpr auto arguments = std::tuple{values...}; constexpr auto element_if_predicate = [arguments]<auto argument, std::size_t argument_index>() consteval { if constexpr (argument_index == 0) return std::tuple{argument}; else { constexpr auto has_previous_position = [&arguments]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return (((std::get<indexes>(arguments) == argument) || ...)); } (std::make_index_sequence<argument_index>{}); if constexpr (has_previous_position) return std::tuple{}; else return std::tuple{argument}; } }; return [&arguments, element_if_predicate ]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return std::tuple_cat(element_if_predicate.template operator()<std::get<indexes>(arguments), indexes>()...); } (std::make_index_sequence<std::tuple_size_v<decltype(arguments)>>{}); } template <auto... values> constexpr auto tuple_erase_duplicate_types() { using values_as_tuple_type = std::tuple<decltype(values)...>; constexpr auto element_if_predicate = []<auto argument, std::size_t argument_index>() consteval { constexpr auto has_previous_position = []<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return ( (std::is_same_v<std::tuple_element_t<indexes, values_as_tuple_type>, decltype(argument)> || ...)); } (std::make_index_sequence<argument_index>{}); if constexpr (has_previous_position) return std::tuple<>{}; else return std::tuple{argument}; }; return [element_if_predicate]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return std::tuple_cat(element_if_predicate.template operator()<values, indexes>()...); } (std::make_index_sequence<sizeof...(values)>{}); } template <auto... values> using tuple_erase_duplicate_types_t = std::decay_t<decltype(tuple_erase_duplicate_types<values...>())>; #endif template <typename TupleType> constexpr auto tuple_to_std_array(TupleType tuple_value) { return [&tuple_value]<std::size_t... indexes>(std::index_sequence<indexes...>) { using element_type = std::common_type_t<decltype(std::get<indexes>(tuple_value))...>; return std::array<element_type, sizeof...(indexes)>{std::get<indexes>(tuple_value)...}; } (std::make_index_sequence<std::tuple_size_v<TupleType>>{}); } } namespace gcl::ctc::tests::algorithms::tuple { namespace ctc_tuple_algorithms = gcl::ctc::algorithms::tuple; #if not defined(__clang__) and defined(__GNUC__) static_assert( ctc_tuple_algorithms::tuple_erase_duplicate_values<'a', 'a', 42, 'b', 42, 'a', 13>() == std::tuple{'a', 42, 'b', 13}); static_assert(std::is_same_v< std::tuple<char, int>, ctc_tuple_algorithms::tuple_erase_duplicate_types_t<'a', 'a', 'b', 42, 'c', 13>>); #endif static_assert(ctc_tuple_algorithms::tuple_to_std_array(std::tuple{'a', 98, 'c'}) == std::array<int, 3>{'a', 'b', 'c'}); }<commit_msg>[gcl::ctc] add tuple_shrink<size><commit_after>#pragma once #include <tuple> #include <array> #include <algorithm> #include <utility> #include <type_traits> namespace gcl::ctc::algorithms::tuple { #if not defined(__clang__) and defined(__GNUC__) // Works only on GCC // Currently not supported by : // - MSVC/CL : Request non-variable parameters capture, which is non-legal // - Clang : compiler crash, need to investigate // Shorter crash case sample : https://godbolt.org/z/ovW7b6 template <typename PredicateType, auto... arguments> constexpr auto tuple_erase_if(const PredicateType predicate) { constexpr auto element_if_predicate = [predicate]<auto argument>() consteval { if constexpr (predicate(argument)) return std::tuple<>{}; else return std::tuple{argument}; }; return std::tuple_cat(element_if_predicate.template operator()<arguments>()...); } template <typename TupleType, std::size_t N> using tuple_type_at = typename std::tuple_element_t<N, TupleType>; template <auto... values> constexpr auto tuple_erase_duplicate_values() { constexpr auto arguments = std::tuple{values...}; constexpr auto element_if_predicate = [arguments]<auto argument, std::size_t argument_index>() consteval { if constexpr (argument_index == 0) return std::tuple{argument}; else { constexpr auto has_previous_position = [&arguments]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return (((std::get<indexes>(arguments) == argument) || ...)); } (std::make_index_sequence<argument_index>{}); if constexpr (has_previous_position) return std::tuple{}; else return std::tuple{argument}; } }; return [&arguments, element_if_predicate ]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return std::tuple_cat(element_if_predicate.template operator()<std::get<indexes>(arguments), indexes>()...); } (std::make_index_sequence<std::tuple_size_v<decltype(arguments)>>{}); } template <auto... values> constexpr auto tuple_erase_duplicate_types() { using values_as_tuple_type = std::tuple<decltype(values)...>; constexpr auto element_if_predicate = []<auto argument, std::size_t argument_index>() consteval { constexpr auto has_previous_position = []<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return ( (std::is_same_v<std::tuple_element_t<indexes, values_as_tuple_type>, decltype(argument)> || ...)); } (std::make_index_sequence<argument_index>{}); if constexpr (has_previous_position) return std::tuple<>{}; else return std::tuple{argument}; }; return [element_if_predicate]<std::size_t... indexes>(std::index_sequence<indexes...>) consteval { return std::tuple_cat(element_if_predicate.template operator()<values, indexes>()...); } (std::make_index_sequence<sizeof...(values)>{}); } template <auto... values> using tuple_erase_duplicate_types_t = std::decay_t<decltype(tuple_erase_duplicate_types<values...>())>; #endif template <typename TupleType> constexpr auto tuple_to_std_array(TupleType tuple_value) { return [&tuple_value]<std::size_t... indexes>(std::index_sequence<indexes...>) { using element_type = std::common_type_t<decltype(std::get<indexes>(tuple_value))...>; return std::array<element_type, sizeof...(indexes)>{std::get<indexes>(tuple_value)...}; } (std::make_index_sequence<std::tuple_size_v<TupleType>>{}); } template <std::size_t N, template <typename...> typename TupleType, typename... TupleElementsTypes> constexpr auto tuple_shrink(TupleType<TupleElementsTypes...> tuple_value) { using tuple_t = TupleType<TupleElementsTypes...>; static_assert(std::tuple_size_v<tuple_t> >= N); return [&tuple_value]<std::size_t... indexes>(std::index_sequence<indexes...>) { return TupleType{std::get<indexes>(tuple_value)...}; } (std::make_index_sequence<N>{}); } template <std::size_t N, typename ElementType, auto size> constexpr auto tuple_shrink(std::array<ElementType, size> tuple_value) { using tuple_t = std::array<ElementType, size>; static_assert(std::tuple_size_v<tuple_t> >= N); return [&tuple_value]<std::size_t... indexes>(std::index_sequence<indexes...>) { return std::array{std::get<indexes>(tuple_value)...}; } (std::make_index_sequence<N>{}); } } namespace gcl::ctc::tests::algorithms::tuple { namespace ctc_tuple_algorithms = gcl::ctc::algorithms::tuple; #if not defined(__clang__) and defined(__GNUC__) static_assert( ctc_tuple_algorithms::tuple_erase_duplicate_values<'a', 'a', 42, 'b', 42, 'a', 13>() == std::tuple{'a', 42, 'b', 13}); static_assert(std::is_same_v< std::tuple<char, int>, ctc_tuple_algorithms::tuple_erase_duplicate_types_t<'a', 'a', 'b', 42, 'c', 13>>); #endif static_assert(ctc_tuple_algorithms::tuple_to_std_array(std::tuple{'a', 98, 'c'}) == std::array<int, 3>{'a', 'b', 'c'}); static_assert(ctc_tuple_algorithms::tuple_shrink<2>(std::tuple{'a', 42, 'b', 43}) == std::tuple{'a', 42}); static_assert(ctc_tuple_algorithms::tuple_shrink<2>(std::array{'a', 'b', 'c'}) == std::array{'a', 'b'}); }<|endoftext|>
<commit_before>#include <cassert> #include "ZigZagConnectorProcessor.h" using namespace cura; void ZigzagConnectorProcessor::registerVertex(const Point& vertex) { if (this->is_first_connector) { this->first_connector.push_back(vertex); } else { // it's yet unclear whether the line segment should be included, so we store it until we know this->current_connector.push_back(vertex); } } bool ZigzagConnectorProcessor::shouldAddThisConnector(int start_scanline_idx, int end_scanline_idx, int direction) const { assert((direction != 1 || direction != -1) && "direction should be either +1 or -1"); // // Decide whether we should add this connection or not. // Add this zag connection is the following cases: // - if this zag lays in an even-numbered scanline segment // - if this zag is an end piece (check if the previous and the current scanlines are the same) // and "use end piece" is enabled // Don't add a zag if: // - this zag is NOT an end piece, "skip some zags" is enabled, and this zag lays in a segment // which needs to be skipped. // Moreover: // - if a "connected end pieces" is not enabled and this is an end piece, the last line // of this end piece will not be added. // // The rules above also apply to how the last part is processed (in polygon finishes) // const bool is_this_endpiece = start_scanline_idx == end_scanline_idx; const bool is_this_connection_even = start_scanline_idx % 2 == 0; bool should_skip_this_connection = false; if (this->skip_some_zags && this->zag_skip_count > 0) { // // Skipping some zags is done in the following way: // > direction: negative number means from <right> -> <left> // positive number means from <left> -> <right> // > for a connection: // - if it comes from <left> -> <right> (direction >= 0), we skip connections that // lay in segments which mean the condition: "index mod skip_count = 0" // - for connections that come from the other direction, we skip on // "(index - 1) mod skip_count = 0" // if (direction > 0) { should_skip_this_connection = start_scanline_idx % this->zag_skip_count == 0; } else { should_skip_this_connection = (start_scanline_idx - 1) % this->zag_skip_count == 0; } } const bool should_add = (is_this_connection_even && !is_this_endpiece && !should_skip_this_connection) // normal connections that should be added || (this->use_endpieces && is_this_endpiece); // end piece if it is enabled; return should_add; } void ZigzagConnectorProcessor::registerScanlineSegmentIntersection(const Point& intersection, int scanline_index, int direction) { if (this->is_first_connector) { // process as the first connector if we haven't found one yet // this will be processed with the last remaining piece at the end (when the polygon finishes) this->first_connector.push_back(intersection); this->first_connector_index = scanline_index; this->first_connector_direction = direction; this->is_first_connector = false; } else { // add this connector if needed if (this->shouldAddThisConnector(this->last_connector_index, scanline_index, direction)) { for (unsigned int point_idx = 1; point_idx < this->current_connector.size(); ++point_idx) { addLine(this->current_connector[point_idx - 1], this->current_connector[point_idx]); } // only add the last line if: // - it is not an end piece, or // - it is an end piece and "connected end pieces" is enabled const bool is_this_endpiece = scanline_index == this->last_connector_index; if (!is_this_endpiece || (is_this_endpiece && this->connected_endpieces)) { addLine(this->current_connector.back(), intersection); } } } // update state this->current_connector.clear(); // we're starting a new (odd) zigzag connector, so clear the old one this->current_connector.push_back(intersection); this->last_connector_index = scanline_index; this->last_connector_direction = direction; } void ZigzagConnectorProcessor::registerPolyFinished() { int scanline_start_index = this->last_connector_index; int scanline_end_index = this->first_connector_index; int direction = scanline_end_index > scanline_start_index ? 1 : -1; const bool is_endpiece = this->is_first_connector || (!this->is_first_connector && scanline_start_index == scanline_end_index); // decides whether to add this zag according to the following rules if ((is_endpiece && this->use_endpieces) || (!is_endpiece && this->shouldAddThisConnector(scanline_start_index, scanline_end_index, direction))) { // for convenience, put every point in one vector for (const Point& point : this->first_connector) { this->current_connector.push_back(point); } this->first_connector.clear(); for (unsigned int point_idx = 1; point_idx < this->current_connector.size() - 1; ++point_idx) { addLine(this->current_connector[point_idx - 1], this->current_connector[point_idx]); } // only add the last line if: // - it is not an end piece, or // - it is an end piece and "connected end pieces" is enabled if (!is_endpiece || (is_endpiece && this->connected_endpieces && this->current_connector.size() >= 2)) { addLine(this->current_connector[current_connector.size() - 2], this->current_connector[current_connector.size() - 1]); } } // reset member variables this->reset(); } <commit_msg>include typo<commit_after>#include <cassert> #include "ZigzagConnectorProcessor.h" using namespace cura; void ZigzagConnectorProcessor::registerVertex(const Point& vertex) { if (this->is_first_connector) { this->first_connector.push_back(vertex); } else { // it's yet unclear whether the line segment should be included, so we store it until we know this->current_connector.push_back(vertex); } } bool ZigzagConnectorProcessor::shouldAddThisConnector(int start_scanline_idx, int end_scanline_idx, int direction) const { assert((direction != 1 || direction != -1) && "direction should be either +1 or -1"); // // Decide whether we should add this connection or not. // Add this zag connection is the following cases: // - if this zag lays in an even-numbered scanline segment // - if this zag is an end piece (check if the previous and the current scanlines are the same) // and "use end piece" is enabled // Don't add a zag if: // - this zag is NOT an end piece, "skip some zags" is enabled, and this zag lays in a segment // which needs to be skipped. // Moreover: // - if a "connected end pieces" is not enabled and this is an end piece, the last line // of this end piece will not be added. // // The rules above also apply to how the last part is processed (in polygon finishes) // const bool is_this_endpiece = start_scanline_idx == end_scanline_idx; const bool is_this_connection_even = start_scanline_idx % 2 == 0; bool should_skip_this_connection = false; if (this->skip_some_zags && this->zag_skip_count > 0) { // // Skipping some zags is done in the following way: // > direction: negative number means from <right> -> <left> // positive number means from <left> -> <right> // > for a connection: // - if it comes from <left> -> <right> (direction >= 0), we skip connections that // lay in segments which mean the condition: "index mod skip_count = 0" // - for connections that come from the other direction, we skip on // "(index - 1) mod skip_count = 0" // if (direction > 0) { should_skip_this_connection = start_scanline_idx % this->zag_skip_count == 0; } else { should_skip_this_connection = (start_scanline_idx - 1) % this->zag_skip_count == 0; } } const bool should_add = (is_this_connection_even && !is_this_endpiece && !should_skip_this_connection) // normal connections that should be added || (this->use_endpieces && is_this_endpiece); // end piece if it is enabled; return should_add; } void ZigzagConnectorProcessor::registerScanlineSegmentIntersection(const Point& intersection, int scanline_index, int direction) { if (this->is_first_connector) { // process as the first connector if we haven't found one yet // this will be processed with the last remaining piece at the end (when the polygon finishes) this->first_connector.push_back(intersection); this->first_connector_index = scanline_index; this->first_connector_direction = direction; this->is_first_connector = false; } else { // add this connector if needed if (this->shouldAddThisConnector(this->last_connector_index, scanline_index, direction)) { for (unsigned int point_idx = 1; point_idx < this->current_connector.size(); ++point_idx) { addLine(this->current_connector[point_idx - 1], this->current_connector[point_idx]); } // only add the last line if: // - it is not an end piece, or // - it is an end piece and "connected end pieces" is enabled const bool is_this_endpiece = scanline_index == this->last_connector_index; if (!is_this_endpiece || (is_this_endpiece && this->connected_endpieces)) { addLine(this->current_connector.back(), intersection); } } } // update state this->current_connector.clear(); // we're starting a new (odd) zigzag connector, so clear the old one this->current_connector.push_back(intersection); this->last_connector_index = scanline_index; this->last_connector_direction = direction; } void ZigzagConnectorProcessor::registerPolyFinished() { int scanline_start_index = this->last_connector_index; int scanline_end_index = this->first_connector_index; int direction = scanline_end_index > scanline_start_index ? 1 : -1; const bool is_endpiece = this->is_first_connector || (!this->is_first_connector && scanline_start_index == scanline_end_index); // decides whether to add this zag according to the following rules if ((is_endpiece && this->use_endpieces) || (!is_endpiece && this->shouldAddThisConnector(scanline_start_index, scanline_end_index, direction))) { // for convenience, put every point in one vector for (const Point& point : this->first_connector) { this->current_connector.push_back(point); } this->first_connector.clear(); for (unsigned int point_idx = 1; point_idx < this->current_connector.size() - 1; ++point_idx) { addLine(this->current_connector[point_idx - 1], this->current_connector[point_idx]); } // only add the last line if: // - it is not an end piece, or // - it is an end piece and "connected end pieces" is enabled if (!is_endpiece || (is_endpiece && this->connected_endpieces && this->current_connector.size() >= 2)) { addLine(this->current_connector[current_connector.size() - 2], this->current_connector[current_connector.size() - 1]); } } // reset member variables this->reset(); } <|endoftext|>
<commit_before>#include "maxxx.h" MXX_CLASS(Lms100) { int sock; void connect(const char * host, long port) { post("connect %s:%d\n", host, port); } void disconnect() { post("disconnect\n"); } void send(const char * _send_, long argc, t_atom * argv) { printGimme(argc, argv); } }; int main() { MXX_REGISTER_CLASS( Lms100, "lms100", (("connect", connect)) (("disconnect", disconnect)) (("send", send)) ); } <commit_msg>ported connect<commit_after>#include "maxxx.h" // BSD sockets #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> MXX_CLASS(Lms100) { int sock; Lms100() : sock(-1) {} ~Lms100() { if (sock>-1) disconnect(); } void connect(const char * host, long port) { struct hostent * host_ent; struct sockaddr_in addr; if ((host_ent = gethostbyname(host)) == NULL) { postError("can't resolve net address '%s'", host); postOSError(); return; } if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { postError("can't create socket"); postOSError(); return; } memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = *((in_addr_t*)host_ent->h_addr_list[0]); addr.sin_port = htons(port); if (::connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { postError("error connecting to %s:%d", host, port); postOSError(); // this cleans the socket up even though we haven't connected disconnect(); return; } if (fcntl(sock, F_SETFL, O_NONBLOCK) < 0) { postError("couldn't make socket non blocking\n"); postOSError(); disconnect(); return; } // qelem_set(self->recvQueue); postMessage("connected to %s:%d", host, port); } void disconnect() { post("disconnect\n"); } void send(const char * _send_, long argc, t_atom * argv) { printGimme(argc, argv); } }; int main() { MXX_REGISTER_CLASS( Lms100, "lms100", (("connect", connect)) (("disconnect", disconnect)) (("send", send)) ); } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2016 Jan Kelling * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ ///\file ///\brief Includes the unspecialized Simplex template class with operations and typedefs. #pragma once #include <nytl/vec.hpp> #include <nytl/mat.hpp> #include <nytl/scalar.hpp> #include <nytl/linearSolver.hpp> #include <nytl/bits/tmpUtil.inl> #include <vector> #include <type_traits> #include <utility> #include <cmath> #include <stdexcept> #include <string> #include <cassert> namespace nytl { ///Short enable-if typedef template<std::size_t D, std::size_t A> using DimMatch = typename std::enable_if<D >= A>::type; ///\ingroup math ///\brief Templated abstraction of the Simplex concept. ///\details The Simplex<D, P, A> template class defines an unique area with \c A dimensions ///of \c P precision in an \c D dimensional space. ///So e.g. Simplex<3, float, 2> describes a Triangle in a 3-dimensional space. ///This template class does only works if D >= A, since the dimension of the area ///can not be higher than the dimension of the space that contains this area. ///The area is called unique, since it does have a variable number of points defining it; always ///enough to describe exactly one, unambigous area with the given dimension and precision in ///the given space. template<std::size_t D, typename P = float, std::size_t A = D> class Simplex : public DeriveDummy<DimMatch<D, A>> { public: static constexpr std::size_t dim = D; static constexpr std::size_t simplexDim = A; using Precision = P; using VecType = Vec<D, P>; using Size = std::size_t; //stl using value_type = Precision; using size_type = Size; public: Vec<A + 1, VecType> points_ {}; public: template<typename... Args, typename = typename std::enable_if_t< std::is_convertible< std::tuple<Args...>, TypeTuple<VecType, A + 1> >::value >> Simplex(Args&&... args) noexcept : points_{std::forward<Args>(args)...} {} Simplex() noexcept = default; ///Returns the size of the area (e.g. for a 3-dimensional Simplex this would be the volume) double size() const; ///Returns the center point of the area. VecType center() const; ///Returns whether the defined Simplex is valid (i.e. size > 0). bool valid() const; ///Converts the object into a Vec of points. ///Can be used to acces (read/change/manipulate) the points. Vec<A + 1, VecType>& points(){ return points_; } ///Converts the object into a const Vec of poitns. ///Can be used to const_iterate/read the points. const Vec<A + 1, VecType>& points() const { return points_; } ///Converts the object to a Simplex with a different dimension or precision. ///Note that the area dimension A cannot be changed, only the space dimension D. ///Works only if the new D is still greater equal A. template<std::size_t OD, typename OP> operator Simplex<OD, OP, A>() const; }; ///\ingroup math ///Describes a RectRegion of multiple Simplexes. template<std::size_t D, typename P = float, std::size_t A = D> class SimplexRegion : public DeriveDummy<DimMatch<D, A>> { public: static constexpr std::size_t dim = D; static constexpr std::size_t simplexDim = A; using SimplexType = Simplex<D, P, A>; using SimplexRegionType = SimplexRegion<D, P, A>; using VectorType = std::vector<SimplexType>; using Size = typename VectorType::size_type; //stl using value_type = SimplexType; using size_type = Size; public: VectorType simplices_; public: ///Adds a Simplex to this RectRegion. Effectively only adds the part of the Simplex that ///is not already part of the RectRegion. void add(const SimplexType& simplex); ///Makes this RectRegion object the union of itself and the argument-given RectRegion. void add(const SimplexRegionType& simplexRegion); ///Adds a Simplex without checking for intersection void addNoCheck(const SimplexType& simplex) { simplices_.push_back(simplex); } ///Adds a SimplexRegion without checking for intersection void addNoCheck(const SimplexRegionType& simplexRegion) { simplices_.insert(simplices_.cend(), simplexRegion.cbegin(), simplexRegion.cend()); } ///Subtracts a Simplex from this SimplexRegion. ///Effectively checks every Simplex of this SimplexRegio for intersection and resizes ///it if needed. void subtract(const SimplexType& simplex); ///Subtracts the given simplexRegion from this object. void subtract(const SimplexRegionType& simplexregion); ///Returns the total size of the region. double size() const; ///Returns the number of simplexes this SimplexRegion contains. Size count() const { return simplices().size(); } ///Returns a Vector with the given Simplexes. const VectorType& simplices() const { return simplices_; } ///Returns a Vector with the given Simplexes. VectorType& simplices() { return simplices_; } ///Converts this object to a SimplexRegion object of different precision and/or space dimension. template<std::size_t OD, typename OP> operator SimplexRegion<OD, OP, A>() const; }; //To get the additional features for each specialization, include the corresponding headers: //#include <nytl/line.hpp> template<std::size_t D, typename P = float> using Line = Simplex<D, P, 1>; //#include <nytl/triangle.hpp> template<std::size_t D, typename P = float> using Triangle = Simplex<D, P, 2>; //#include <nytl/tetrahedron.hpp> template<std::size_t D, typename P = float> using Tetrahedron = Simplex<D, P, 3>; //operators/utility #include <nytl/bits/simplexRegion.inl> #include <nytl/bits/simplex.inl> } <commit_msg>removed bad implemented SimplexRegion<commit_after>/* The MIT License (MIT) * * Copyright (c) 2016 Jan Kelling * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ ///\file ///\brief Includes the unspecialized Simplex template class with operations and typedefs. #pragma once #include <nytl/vec.hpp> #include <nytl/mat.hpp> #include <nytl/scalar.hpp> #include <nytl/linearSolver.hpp> #include <nytl/bits/tmpUtil.inl> #include <vector> #include <type_traits> #include <utility> #include <cmath> #include <stdexcept> #include <string> #include <cassert> namespace nytl { ///Short enable-if typedef template<std::size_t D, std::size_t A> using DimMatch = typename std::enable_if<D >= A>::type; ///\ingroup math ///\brief Templated abstraction of the Simplex concept. ///\details The Simplex<D, P, A> template class defines an unique area with \c A dimensions ///of \c P precision in an \c D dimensional space. ///So e.g. Simplex<3, float, 2> describes a Triangle in a 3-dimensional space. ///This template class does only works if D >= A, since the dimension of the area ///can not be higher than the dimension of the space that contains this area. ///The area is called unique, since it does have a variable number of points defining it; always ///enough to describe exactly one, unambigous area with the given dimension and precision in ///the given space. template<std::size_t D, typename P = float, std::size_t A = D> class Simplex : public DeriveDummy<DimMatch<D, A>> { public: static constexpr std::size_t dim = D; static constexpr std::size_t simplexDim = A; using Precision = P; using VecType = Vec<D, P>; using Size = std::size_t; //stl using value_type = Precision; using size_type = Size; public: Vec<A + 1, VecType> points_ {}; public: template<typename... Args, typename = typename std::enable_if_t< std::is_convertible< std::tuple<Args...>, TypeTuple<VecType, A + 1> >::value >> Simplex(Args&&... args) noexcept : points_{std::forward<Args>(args)...} {} Simplex() noexcept = default; ///Returns the size of the area (e.g. for a 3-dimensional Simplex this would be the volume) double size() const; ///Returns the center point of the area. VecType center() const; ///Converts the object into a Vec of points. ///Can be used to acces (read/change/manipulate) the points. Vec<A + 1, VecType>& points(){ return points_; } ///Converts the object into a const Vec of poitns. ///Can be used to const_iterate/read the points. const Vec<A + 1, VecType>& points() const { return points_; } ///Converts the object to a Simplex with a different dimension or precision. ///Note that the area dimension A cannot be changed, only the space dimension D. ///This means simply that e.g. a Triangle cannot be converted into a line, but a triangle ///in 3 dimensional space can be converted to a triangle in 2 dimensional space (by simply ///stripping the 3rd dimension). ///Works only if the new D is still greater equal A. template<std::size_t OD, typename OP> operator Simplex<OD, OP, A>() const; }; //To get the additional features for each specialization, include the corresponding headers: //#include <nytl/line.hpp> template<std::size_t D, typename P = float> using Line = Simplex<D, P, 1>; //#include <nytl/triangle.hpp> template<std::size_t D, typename P = float> using Triangle = Simplex<D, P, 2>; //#include <nytl/tetrahedron.hpp> template<std::size_t D, typename P = float> using Tetrahedron = Simplex<D, P, 3>; //operators/utility #include <nytl/bits/simplex.inl> } <|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_surface.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "third_party/mesa/MesaLib/include/GL/osmesa.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/gl_surface_glx.h" #include "ui/gl/gl_surface_osmesa.h" #include "ui/gl/gl_surface_stub.h" namespace gfx { namespace { Display* g_osmesa_display; } // namespace // This OSMesa GL surface can use XLib to swap the contents of the buffer to a // view. class NativeViewGLSurfaceOSMesa : public GLSurfaceOSMesa { public: explicit NativeViewGLSurfaceOSMesa(gfx::AcceleratedWidget window); static bool InitializeOneOff(); // Implement a subset of GLSurface. virtual bool Initialize() OVERRIDE; virtual void Destroy() OVERRIDE; virtual bool Resize(const gfx::Size& new_size) OVERRIDE; virtual bool IsOffscreen() OVERRIDE; virtual bool SwapBuffers() OVERRIDE; virtual std::string GetExtensions() OVERRIDE; virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE; protected: virtual ~NativeViewGLSurfaceOSMesa(); private: GC window_graphics_context_; gfx::AcceleratedWidget window_; GC pixmap_graphics_context_; Pixmap pixmap_; DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceOSMesa); }; bool GLSurface::InitializeOneOffInternal() { switch (GetGLImplementation()) { case kGLImplementationDesktopGL: if (!GLSurfaceGLX::InitializeOneOff()) { LOG(ERROR) << "GLSurfaceGLX::InitializeOneOff failed."; return false; } break; case kGLImplementationOSMesaGL: if (!NativeViewGLSurfaceOSMesa::InitializeOneOff()) { LOG(ERROR) << "NativeViewGLSurfaceOSMesa::InitializeOneOff failed."; return false; } break; case kGLImplementationEGLGLES2: if (!GLSurfaceEGL::InitializeOneOff()) { LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed."; return false; } break; default: break; } return true; } NativeViewGLSurfaceOSMesa::NativeViewGLSurfaceOSMesa( gfx::AcceleratedWidget window) : GLSurfaceOSMesa(OSMESA_BGRA, gfx::Size(1, 1)), window_graphics_context_(0), window_(window), pixmap_graphics_context_(0), pixmap_(0) { DCHECK(window); } bool NativeViewGLSurfaceOSMesa::InitializeOneOff() { static bool initialized = false; if (initialized) return true; g_osmesa_display = base::MessagePumpForUI::GetDefaultXDisplay(); if (!g_osmesa_display) { LOG(ERROR) << "XOpenDisplay failed."; return false; } initialized = true; return true; } bool NativeViewGLSurfaceOSMesa::Initialize() { if (!GLSurfaceOSMesa::Initialize()) return false; window_graphics_context_ = XCreateGC(g_osmesa_display, window_, 0, NULL); if (!window_graphics_context_) { LOG(ERROR) << "XCreateGC failed."; Destroy(); return false; } return true; } void NativeViewGLSurfaceOSMesa::Destroy() { if (pixmap_graphics_context_) { XFreeGC(g_osmesa_display, pixmap_graphics_context_); pixmap_graphics_context_ = NULL; } if (pixmap_) { XFreePixmap(g_osmesa_display, pixmap_); pixmap_ = 0; } if (window_graphics_context_) { XFreeGC(g_osmesa_display, window_graphics_context_); window_graphics_context_ = NULL; } } bool NativeViewGLSurfaceOSMesa::Resize(const gfx::Size& new_size) { if (!GLSurfaceOSMesa::Resize(new_size)) return false; XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Destroy the previous pixmap and graphics context. if (pixmap_graphics_context_) { XFreeGC(g_osmesa_display, pixmap_graphics_context_); pixmap_graphics_context_ = NULL; } if (pixmap_) { XFreePixmap(g_osmesa_display, pixmap_); pixmap_ = 0; } // Recreate a pixmap to hold the frame. pixmap_ = XCreatePixmap(g_osmesa_display, window_, new_size.width(), new_size.height(), attributes.depth); if (!pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } // Recreate a graphics context for the pixmap. pixmap_graphics_context_ = XCreateGC(g_osmesa_display, pixmap_, 0, NULL); if (!pixmap_graphics_context_) { LOG(ERROR) << "XCreateGC failed"; return false; } return true; } bool NativeViewGLSurfaceOSMesa::IsOffscreen() { return false; } bool NativeViewGLSurfaceOSMesa::SwapBuffers() { gfx::Size size = GetSize(); XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Copy the frame into the pixmap. ui::PutARGBImage(g_osmesa_display, attributes.visual, attributes.depth, pixmap_, pixmap_graphics_context_, static_cast<const uint8*>(GetHandle()), size.width(), size.height()); // Copy the pixmap to the window. XCopyArea(g_osmesa_display, pixmap_, window_, window_graphics_context_, 0, 0, size.width(), size.height(), 0, 0); return true; } std::string NativeViewGLSurfaceOSMesa::GetExtensions() { std::string extensions = gfx::GLSurfaceOSMesa::GetExtensions(); extensions += extensions.empty() ? "" : " "; extensions += "GL_CHROMIUM_post_sub_buffer"; return extensions; } bool NativeViewGLSurfaceOSMesa::PostSubBuffer( int x, int y, int width, int height) { gfx::Size size = GetSize(); // Move (0,0) from lower-left to upper-left y = size.height() - y - height; XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Copy the frame into the pixmap. ui::PutARGBImage(g_osmesa_display, attributes.visual, attributes.depth, pixmap_, pixmap_graphics_context_, static_cast<const uint8*>(GetHandle()), size.width(), size.height(), x, y, x, y, width, height); // Copy the pixmap to the window. XCopyArea(g_osmesa_display, pixmap_, window_, window_graphics_context_, x, y, width, height, x, y); return true; } NativeViewGLSurfaceOSMesa::~NativeViewGLSurfaceOSMesa() { Destroy(); } scoped_refptr<GLSurface> GLSurface::CreateViewGLSurface( bool software, gfx::AcceleratedWidget window) { TRACE_EVENT0("gpu", "GLSurface::CreateViewGLSurface"); if (software) return NULL; switch (GetGLImplementation()) { case kGLImplementationOSMesaGL: { scoped_refptr<GLSurface> surface( new NativeViewGLSurfaceOSMesa(window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationDesktopGL: { scoped_refptr<GLSurface> surface(new NativeViewGLSurfaceGLX( window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationEGLGLES2: { scoped_refptr<GLSurface> surface(new NativeViewGLSurfaceEGL( false, window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationMockGL: return new GLSurfaceStub; default: NOTREACHED(); return NULL; } } scoped_refptr<GLSurface> GLSurface::CreateOffscreenGLSurface( bool software, const gfx::Size& size) { TRACE_EVENT0("gpu", "GLSurface::CreateOffscreenGLSurface"); if (software) return NULL; switch (GetGLImplementation()) { case kGLImplementationOSMesaGL: { scoped_refptr<GLSurface> surface(new GLSurfaceOSMesa(OSMESA_RGBA, size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationDesktopGL: { scoped_refptr<GLSurface> surface(new PbufferGLSurfaceGLX(size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationEGLGLES2: { scoped_refptr<GLSurface> surface(new PbufferGLSurfaceEGL(false, size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationMockGL: return new GLSurfaceStub; default: NOTREACHED(); return NULL; } } } // namespace gfx <commit_msg>Explicitly empty the pipes on teardown to prevent cross process races.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_surface.h" #include "base/debug/trace_event.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/message_loop.h" #include "third_party/mesa/MesaLib/include/GL/osmesa.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface_egl.h" #include "ui/gl/gl_surface_glx.h" #include "ui/gl/gl_surface_osmesa.h" #include "ui/gl/gl_surface_stub.h" namespace gfx { namespace { Display* g_osmesa_display; } // namespace // This OSMesa GL surface can use XLib to swap the contents of the buffer to a // view. class NativeViewGLSurfaceOSMesa : public GLSurfaceOSMesa { public: explicit NativeViewGLSurfaceOSMesa(gfx::AcceleratedWidget window); static bool InitializeOneOff(); // Implement a subset of GLSurface. virtual bool Initialize() OVERRIDE; virtual void Destroy() OVERRIDE; virtual bool Resize(const gfx::Size& new_size) OVERRIDE; virtual bool IsOffscreen() OVERRIDE; virtual bool SwapBuffers() OVERRIDE; virtual std::string GetExtensions() OVERRIDE; virtual bool PostSubBuffer(int x, int y, int width, int height) OVERRIDE; protected: virtual ~NativeViewGLSurfaceOSMesa(); private: GC window_graphics_context_; gfx::AcceleratedWidget window_; GC pixmap_graphics_context_; Pixmap pixmap_; DISALLOW_COPY_AND_ASSIGN(NativeViewGLSurfaceOSMesa); }; bool GLSurface::InitializeOneOffInternal() { switch (GetGLImplementation()) { case kGLImplementationDesktopGL: if (!GLSurfaceGLX::InitializeOneOff()) { LOG(ERROR) << "GLSurfaceGLX::InitializeOneOff failed."; return false; } break; case kGLImplementationOSMesaGL: if (!NativeViewGLSurfaceOSMesa::InitializeOneOff()) { LOG(ERROR) << "NativeViewGLSurfaceOSMesa::InitializeOneOff failed."; return false; } break; case kGLImplementationEGLGLES2: if (!GLSurfaceEGL::InitializeOneOff()) { LOG(ERROR) << "GLSurfaceEGL::InitializeOneOff failed."; return false; } break; default: break; } return true; } NativeViewGLSurfaceOSMesa::NativeViewGLSurfaceOSMesa( gfx::AcceleratedWidget window) : GLSurfaceOSMesa(OSMESA_BGRA, gfx::Size(1, 1)), window_graphics_context_(0), window_(window), pixmap_graphics_context_(0), pixmap_(0) { DCHECK(window); } bool NativeViewGLSurfaceOSMesa::InitializeOneOff() { static bool initialized = false; if (initialized) return true; g_osmesa_display = base::MessagePumpForUI::GetDefaultXDisplay(); if (!g_osmesa_display) { LOG(ERROR) << "XOpenDisplay failed."; return false; } initialized = true; return true; } bool NativeViewGLSurfaceOSMesa::Initialize() { if (!GLSurfaceOSMesa::Initialize()) return false; window_graphics_context_ = XCreateGC(g_osmesa_display, window_, 0, NULL); if (!window_graphics_context_) { LOG(ERROR) << "XCreateGC failed."; Destroy(); return false; } return true; } void NativeViewGLSurfaceOSMesa::Destroy() { if (pixmap_graphics_context_) { XFreeGC(g_osmesa_display, pixmap_graphics_context_); pixmap_graphics_context_ = NULL; } if (pixmap_) { XFreePixmap(g_osmesa_display, pixmap_); pixmap_ = 0; } if (window_graphics_context_) { XFreeGC(g_osmesa_display, window_graphics_context_); window_graphics_context_ = NULL; } XSync(g_osmesa_display, False); } bool NativeViewGLSurfaceOSMesa::Resize(const gfx::Size& new_size) { if (!GLSurfaceOSMesa::Resize(new_size)) return false; XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Destroy the previous pixmap and graphics context. if (pixmap_graphics_context_) { XFreeGC(g_osmesa_display, pixmap_graphics_context_); pixmap_graphics_context_ = NULL; } if (pixmap_) { XFreePixmap(g_osmesa_display, pixmap_); pixmap_ = 0; } // Recreate a pixmap to hold the frame. pixmap_ = XCreatePixmap(g_osmesa_display, window_, new_size.width(), new_size.height(), attributes.depth); if (!pixmap_) { LOG(ERROR) << "XCreatePixmap failed."; return false; } // Recreate a graphics context for the pixmap. pixmap_graphics_context_ = XCreateGC(g_osmesa_display, pixmap_, 0, NULL); if (!pixmap_graphics_context_) { LOG(ERROR) << "XCreateGC failed"; return false; } return true; } bool NativeViewGLSurfaceOSMesa::IsOffscreen() { return false; } bool NativeViewGLSurfaceOSMesa::SwapBuffers() { gfx::Size size = GetSize(); XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Copy the frame into the pixmap. ui::PutARGBImage(g_osmesa_display, attributes.visual, attributes.depth, pixmap_, pixmap_graphics_context_, static_cast<const uint8*>(GetHandle()), size.width(), size.height()); // Copy the pixmap to the window. XCopyArea(g_osmesa_display, pixmap_, window_, window_graphics_context_, 0, 0, size.width(), size.height(), 0, 0); return true; } std::string NativeViewGLSurfaceOSMesa::GetExtensions() { std::string extensions = gfx::GLSurfaceOSMesa::GetExtensions(); extensions += extensions.empty() ? "" : " "; extensions += "GL_CHROMIUM_post_sub_buffer"; return extensions; } bool NativeViewGLSurfaceOSMesa::PostSubBuffer( int x, int y, int width, int height) { gfx::Size size = GetSize(); // Move (0,0) from lower-left to upper-left y = size.height() - y - height; XWindowAttributes attributes; if (!XGetWindowAttributes(g_osmesa_display, window_, &attributes)) { LOG(ERROR) << "XGetWindowAttributes failed for window " << window_ << "."; return false; } // Copy the frame into the pixmap. ui::PutARGBImage(g_osmesa_display, attributes.visual, attributes.depth, pixmap_, pixmap_graphics_context_, static_cast<const uint8*>(GetHandle()), size.width(), size.height(), x, y, x, y, width, height); // Copy the pixmap to the window. XCopyArea(g_osmesa_display, pixmap_, window_, window_graphics_context_, x, y, width, height, x, y); return true; } NativeViewGLSurfaceOSMesa::~NativeViewGLSurfaceOSMesa() { Destroy(); } scoped_refptr<GLSurface> GLSurface::CreateViewGLSurface( bool software, gfx::AcceleratedWidget window) { TRACE_EVENT0("gpu", "GLSurface::CreateViewGLSurface"); if (software) return NULL; switch (GetGLImplementation()) { case kGLImplementationOSMesaGL: { scoped_refptr<GLSurface> surface( new NativeViewGLSurfaceOSMesa(window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationDesktopGL: { scoped_refptr<GLSurface> surface(new NativeViewGLSurfaceGLX( window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationEGLGLES2: { scoped_refptr<GLSurface> surface(new NativeViewGLSurfaceEGL( false, window)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationMockGL: return new GLSurfaceStub; default: NOTREACHED(); return NULL; } } scoped_refptr<GLSurface> GLSurface::CreateOffscreenGLSurface( bool software, const gfx::Size& size) { TRACE_EVENT0("gpu", "GLSurface::CreateOffscreenGLSurface"); if (software) return NULL; switch (GetGLImplementation()) { case kGLImplementationOSMesaGL: { scoped_refptr<GLSurface> surface(new GLSurfaceOSMesa(OSMESA_RGBA, size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationDesktopGL: { scoped_refptr<GLSurface> surface(new PbufferGLSurfaceGLX(size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationEGLGLES2: { scoped_refptr<GLSurface> surface(new PbufferGLSurfaceEGL(false, size)); if (!surface->Initialize()) return NULL; return surface; } case kGLImplementationMockGL: return new GLSurfaceStub; default: NOTREACHED(); return NULL; } } } // namespace gfx <|endoftext|>
<commit_before>/*! \file * * \brief Storage of generic data via (key, value) pair (source) * \author Benjamin Pritchard ([email protected]) */ #include <boost/python.hpp> #include "bpmodule/options/OptionHolder.hpp" #include "bpmodule/options/OptionTypes.hpp" #include "bpmodule/output/Output.hpp" #include "bpmodule/python_helper/Convert.hpp" #include "bpmodule/exception/OptionException.hpp" #include "bpmodule/output/FormatStr.hpp" using bpmodule::python_helper::PythonType; using bpmodule::python_helper::StrToPythonType; using bpmodule::python_helper::GetPyClass; using bpmodule::python_helper::DeterminePyType; using bpmodule::python_helper::ConvertToPy; using bpmodule::python_helper::ConvertToCpp; using bpmodule::exception::OptionException; using bpmodule::exception::PythonConvertException; namespace bpmodule { namespace options { namespace detail { /////////////////////////////////////////////////// // These are the allowed types of OptionHolder /////////////////////////////////////////////////// template class OptionHolder<OptionInt>; template class OptionHolder<OptionFloat>; template class OptionHolder<bool>; template class OptionHolder<std::string>; template class OptionHolder<std::vector<OptionInt>>; template class OptionHolder<std::vector<OptionFloat>>; template class OptionHolder<std::vector<bool>>; template class OptionHolder<std::vector<std::string>>; /////////////////////////////////////////// // Forward declarations of free functions /////////////////////////////////////////// template<typename T> static void PrintOption_(const OptionHolder<T> & oph); template<typename T> static void PrintOption_(const OptionHolder<std::vector<T>> & oph); /////////////////////////////////////////////////// // OptionHolder members /////////////////////////////////////////////////// template<typename T> OptionHolder<T>::OptionHolder(const std::string & key, T * def, ValidatorFunc validator, bool required, python_helper::PythonType pytype, const std::string & help) : OptionBase(key, required, pytype, help), default_(def), validator_(validator) { // check the default using the validator if(def != nullptr) ValidateOrThrow_(*default_, "initial default"); if(def != nullptr && required) throw OptionException("Default value supplied for required option", Key()); } template<typename T> OptionHolder<T>::OptionHolder(const OptionHolder & oph) : OptionBase(oph), validator_(oph.validator_) { if(oph.value_) value_ = std::unique_ptr<T>(new T(*oph.value_)); if(oph.default_) default_ = std::unique_ptr<T>(new T(*oph.default_)); } template<typename T> void OptionHolder<T>::Change(const T & value) { ValidateOrThrow_(value, "new value"); value_ = std::unique_ptr<T>(new T(value)); } template<typename T> const T & OptionHolder<T>::Get(void) const { if(value_) return *value_; else if(default_) return *default_; else throw OptionException("Option does not have a value", Key()); } template<typename T> const T & OptionHolder<T>::GetDefault(void) const { if(default_) return *default_; else throw OptionException("Option does not have a default", Key()); } template<typename T> OptionBase * OptionHolder<T>::Clone(void) const { return new OptionHolder<T>(*this); } template<typename T> constexpr const char * OptionHolder<T>::Type(void) const noexcept { return typeid(T).name(); } template<typename T> bool OptionHolder<T>::HasValue(void) const noexcept { return bool(value_) || bool(default_); } template<typename T> bool OptionHolder<T>::HasDefault(void) const noexcept { return bool(default_); } template<typename T> bool OptionHolder<T>::IsDefault(void) const { if(!value_ && default_) return true; else return value_ && default_ && (*value_ == *default_); } template<typename T> void OptionHolder<T>::ResetToDefault(void) noexcept { value_.reset(); } template<typename T> void OptionHolder<T>::Print(void) const { PrintOption_(*this); } template<typename T> void OptionHolder<T>::ValidateOrThrow_(const T & value, const std::string & desc) const { if(!validator_(value)) { //! \todo add exception info from validator? if(!OptionBase::IsExpert()) throw OptionException("Value is not valid for this option", Key()); else output::Warning("Value for option %1% \"%2\" is invalid. Ignoring\n", desc, Key()); } } ///////////////////////////////////////// // Python-related functions ///////////////////////////////////////// template<typename T> boost::python::object OptionHolder<T>::GetPy(void) const { try { return ConvertToPy(Get()); } catch(exception::GeneralException & ex) { throw OptionException(ex, Key(), "valuetype", Type()); } } template<typename T> void OptionHolder<T>::ChangePy(const boost::python::object & obj) { T val; try { val = ConvertToCpp<T>(obj); } catch(exception::GeneralException & ex) { throw OptionException(ex, Key(), "valuetype", Type()); } // will validate inside Change() Change(val); } ///////////////////////////////////////// // Printing functions (free functions) ///////////////////////////////////////// ////////////////// // Helpers ////////////////// template<typename T> static std::string OptToString_(const T & opt) { return std::to_string(opt); } static std::string OptToString_(const std::string & opt) { return opt; } static std::string OptToString_(const bool & opt) { return (opt ? "True" : "False"); } template<typename T> static void PrintOption_(const OptionHolder<T> & oph) { std::string optline = FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", oph.Key(), // name/key PythonTypeToStr(oph.PyType()), // type (oph.HasValue() ? OptToString_(oph.Get()) : "(none)"), // value (oph.HasDefault() ? OptToString_(oph.GetDefault()) : "(none)"), // default (oph.IsRequired() ? "True" : "False"), // required oph.Help()); // help/description if(!oph.IsValid()) output::Error(optline); if(!oph.IsDefault()) output::Changed(optline); else output::Output(optline); } template<typename T> static void PrintOption_(const OptionHolder<std::vector<T>> & oph) { size_t nrows = 0; std::string valstr, defstr; if(oph.HasValue()) { auto valuevec = oph.Get(); nrows = valuevec.size(); if(valuevec.size() == 0) valstr = "(empty)"; else valstr = OptToString_(valuevec[0]); } else valstr = "(none)"; if(oph.HasDefault()) { auto defvec = oph.GetDefault(); nrows = std::max(nrows, defvec.size()); if(defvec.size() == 0) defstr = "(empty)"; else defstr = OptToString_(defvec[0]); } else defstr = "(none)"; std::vector<std::string> optlines; optlines.push_back(FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", oph.Key(), // name/key PythonTypeToStr(oph.PyType()), // type valstr, // value defstr, // default (oph.IsRequired() ? "True" : "False"), // required oph.Help())); // help/description // start at 1 since we did the first separately for(size_t i = 1; i < nrows; i++) { std::string valstr, defstr; if(oph.HasValue()) { auto valuevec = oph.Get(); if(valuevec.size() > i) valstr = OptToString_(valuevec[i]); } if(oph.HasDefault()) { auto defvec = oph.GetDefault(); if(defvec.size() > i) defstr = OptToString_(defvec[i]); } optlines.push_back(FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", "", // name/key "", // type valstr, // value defstr, // default "", // required "")); // help/description } for(const auto & it : optlines) { if(!oph.IsValid()) output::Error(it); else if(!oph.IsDefault()) output::Changed(it); else output::Output(it); } } //////////////////////////////////////////////////////// // CreateOptionHolder & helper functions //////////////////////////////////////////////////////// template<typename T> static bool ValidateWrapper(const boost::python::object & val, T arg) { return boost::python::extract<bool>(val.attr("Validate")(arg)); } template<typename T> static bool EmptyValidator(T arg) { return true; } template<typename T> static OptionBasePtr CreateOptionHolder(const std::string & key, const boost::python::tuple & tup) { PythonType ptype_default = DeterminePyType(tup[1]); T * def = nullptr; if(ptype_default != PythonType::None) { try { def = new T(ConvertToCpp<T>(tup[1])); } catch(const PythonConvertException & ex) { throw OptionException(ex, key); } } // Already checked /* PythonType ptype_type = DeterminePyType(tup[0]); if(ptype_type != PythonType::String) throw OptionException("\"Type\" element of tuple is not a bool", key, "type", GetPyClass(tup[0])); */ if(DeterminePyType(tup[2]) != PythonType::Bool) throw OptionException("\"Required\" element of tuple is not a bool", key, "type", GetPyClass(tup[2])); if(DeterminePyType(tup[4]) != PythonType::String) throw OptionException("\"Help\" element of tuple is not a string", key, "type", GetPyClass(tup[4])); bool req = boost::python::extract<bool>(tup[2]); std::string help = boost::python::extract<std::string>(tup[4]); PythonType pytype = StrToPythonType(boost::python::extract<std::string>(tup[0])); //! \todo Check to make sure validator object is callable // Check if validator is given. If not, use EmptyValidator typename OptionHolder<T>::ValidatorFunc validator = EmptyValidator<T>; if(DeterminePyType(tup[3]) != PythonType::None) validator = std::bind(ValidateWrapper<T>, tup[3], std::placeholders::_1); return OptionBasePtr(new OptionHolder<T>(key, def, validator, req, pytype, help)); } OptionBasePtr OptionHolderFactory(const std::string & key, const boost::python::object & obj) { PythonType ptype = DeterminePyType(obj); if(ptype != PythonType::Tuple) throw OptionException("Object for option is not a tuple", key, "pythontype", GetPyClass(obj)); boost::python::tuple tup = boost::python::extract<boost::python::tuple>(obj); int length = boost::python::extract<int>(tup.attr("__len__")()); if(length != 5) throw OptionException("Python options tuple does not have 5 elements", key, "length", std::to_string(length)); if(DeterminePyType(tup[0]) != PythonType::String) throw OptionException("\"Type\" element of tuple is not a string", key, "type", GetPyClass(tup[0])); std::string type = ConvertToCpp<std::string>(tup[0]); switch(StrToPythonType(type)) { case PythonType::Bool: return CreateOptionHolder<bool>(key, tup); case PythonType::Int: return CreateOptionHolder<OptionInt>(key, tup); case PythonType::Float: return CreateOptionHolder<OptionFloat>(key, tup); case PythonType::String: return CreateOptionHolder<std::string>(key, tup); case PythonType::ListBool: return CreateOptionHolder<std::vector<bool>>(key, tup); case PythonType::ListInt: return CreateOptionHolder<std::vector<OptionInt>>(key, tup); case PythonType::ListFloat: return CreateOptionHolder<std::vector<OptionFloat>>(key, tup); case PythonType::ListString: return CreateOptionHolder<std::vector<std::string>>(key, tup); default: throw OptionException("Cannot convert python type to option", key, "type", type); } } } // close namespace detail } // close namespace options } // close namespace bpmodule <commit_msg>Fix exception message<commit_after>/*! \file * * \brief Storage of generic data via (key, value) pair (source) * \author Benjamin Pritchard ([email protected]) */ #include <boost/python.hpp> #include "bpmodule/options/OptionHolder.hpp" #include "bpmodule/options/OptionTypes.hpp" #include "bpmodule/output/Output.hpp" #include "bpmodule/python_helper/Convert.hpp" #include "bpmodule/exception/OptionException.hpp" #include "bpmodule/output/FormatStr.hpp" using bpmodule::python_helper::PythonType; using bpmodule::python_helper::StrToPythonType; using bpmodule::python_helper::GetPyClass; using bpmodule::python_helper::DeterminePyType; using bpmodule::python_helper::ConvertToPy; using bpmodule::python_helper::ConvertToCpp; using bpmodule::exception::OptionException; using bpmodule::exception::PythonConvertException; namespace bpmodule { namespace options { namespace detail { /////////////////////////////////////////////////// // These are the allowed types of OptionHolder /////////////////////////////////////////////////// template class OptionHolder<OptionInt>; template class OptionHolder<OptionFloat>; template class OptionHolder<bool>; template class OptionHolder<std::string>; template class OptionHolder<std::vector<OptionInt>>; template class OptionHolder<std::vector<OptionFloat>>; template class OptionHolder<std::vector<bool>>; template class OptionHolder<std::vector<std::string>>; /////////////////////////////////////////// // Forward declarations of free functions /////////////////////////////////////////// template<typename T> static void PrintOption_(const OptionHolder<T> & oph); template<typename T> static void PrintOption_(const OptionHolder<std::vector<T>> & oph); /////////////////////////////////////////////////// // OptionHolder members /////////////////////////////////////////////////// template<typename T> OptionHolder<T>::OptionHolder(const std::string & key, T * def, ValidatorFunc validator, bool required, python_helper::PythonType pytype, const std::string & help) : OptionBase(key, required, pytype, help), default_(def), validator_(validator) { // check the default using the validator if(def != nullptr) ValidateOrThrow_(*default_, "initial default"); if(def != nullptr && required) throw OptionException("Default value supplied for required option", Key()); } template<typename T> OptionHolder<T>::OptionHolder(const OptionHolder & oph) : OptionBase(oph), validator_(oph.validator_) { if(oph.value_) value_ = std::unique_ptr<T>(new T(*oph.value_)); if(oph.default_) default_ = std::unique_ptr<T>(new T(*oph.default_)); } template<typename T> void OptionHolder<T>::Change(const T & value) { ValidateOrThrow_(value, "new value"); value_ = std::unique_ptr<T>(new T(value)); } template<typename T> const T & OptionHolder<T>::Get(void) const { if(value_) return *value_; else if(default_) return *default_; else throw OptionException("Option does not have a value", Key()); } template<typename T> const T & OptionHolder<T>::GetDefault(void) const { if(default_) return *default_; else throw OptionException("Option does not have a default", Key()); } template<typename T> OptionBase * OptionHolder<T>::Clone(void) const { return new OptionHolder<T>(*this); } template<typename T> constexpr const char * OptionHolder<T>::Type(void) const noexcept { return typeid(T).name(); } template<typename T> bool OptionHolder<T>::HasValue(void) const noexcept { return bool(value_) || bool(default_); } template<typename T> bool OptionHolder<T>::HasDefault(void) const noexcept { return bool(default_); } template<typename T> bool OptionHolder<T>::IsDefault(void) const { if(!value_ && default_) return true; else return value_ && default_ && (*value_ == *default_); } template<typename T> void OptionHolder<T>::ResetToDefault(void) noexcept { value_.reset(); } template<typename T> void OptionHolder<T>::Print(void) const { PrintOption_(*this); } template<typename T> void OptionHolder<T>::ValidateOrThrow_(const T & value, const std::string & desc) const { if(!validator_(value)) { //! \todo add exception info from validator? if(!OptionBase::IsExpert()) throw OptionException("Value is not valid for this option", Key()); else output::Warning("Value for option %1% \"%2\" is invalid. Ignoring\n", desc, Key()); } } ///////////////////////////////////////// // Python-related functions ///////////////////////////////////////// template<typename T> boost::python::object OptionHolder<T>::GetPy(void) const { try { return ConvertToPy(Get()); } catch(exception::GeneralException & ex) { throw OptionException(ex, Key(), "valuetype", Type()); } } template<typename T> void OptionHolder<T>::ChangePy(const boost::python::object & obj) { T val; try { val = ConvertToCpp<T>(obj); } catch(exception::GeneralException & ex) { throw OptionException(ex, Key(), "valuetype", Type()); } // will validate inside Change() Change(val); } ///////////////////////////////////////// // Printing functions (free functions) ///////////////////////////////////////// ////////////////// // Helpers ////////////////// template<typename T> static std::string OptToString_(const T & opt) { return std::to_string(opt); } static std::string OptToString_(const std::string & opt) { return opt; } static std::string OptToString_(const bool & opt) { return (opt ? "True" : "False"); } template<typename T> static void PrintOption_(const OptionHolder<T> & oph) { std::string optline = FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", oph.Key(), // name/key PythonTypeToStr(oph.PyType()), // type (oph.HasValue() ? OptToString_(oph.Get()) : "(none)"), // value (oph.HasDefault() ? OptToString_(oph.GetDefault()) : "(none)"), // default (oph.IsRequired() ? "True" : "False"), // required oph.Help()); // help/description if(!oph.IsValid()) output::Error(optline); if(!oph.IsDefault()) output::Changed(optline); else output::Output(optline); } template<typename T> static void PrintOption_(const OptionHolder<std::vector<T>> & oph) { size_t nrows = 0; std::string valstr, defstr; if(oph.HasValue()) { auto valuevec = oph.Get(); nrows = valuevec.size(); if(valuevec.size() == 0) valstr = "(empty)"; else valstr = OptToString_(valuevec[0]); } else valstr = "(none)"; if(oph.HasDefault()) { auto defvec = oph.GetDefault(); nrows = std::max(nrows, defvec.size()); if(defvec.size() == 0) defstr = "(empty)"; else defstr = OptToString_(defvec[0]); } else defstr = "(none)"; std::vector<std::string> optlines; optlines.push_back(FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", oph.Key(), // name/key PythonTypeToStr(oph.PyType()), // type valstr, // value defstr, // default (oph.IsRequired() ? "True" : "False"), // required oph.Help())); // help/description // start at 1 since we did the first separately for(size_t i = 1; i < nrows; i++) { std::string valstr, defstr; if(oph.HasValue()) { auto valuevec = oph.Get(); if(valuevec.size() > i) valstr = OptToString_(valuevec[i]); } if(oph.HasDefault()) { auto defvec = oph.GetDefault(); if(defvec.size() > i) defstr = OptToString_(defvec[i]); } optlines.push_back(FormatStr(" %|1$-20| %|2$-20| %|3$-20| %|4$-20| %|5$-10| %6%\n", "", // name/key "", // type valstr, // value defstr, // default "", // required "")); // help/description } for(const auto & it : optlines) { if(!oph.IsValid()) output::Error(it); else if(!oph.IsDefault()) output::Changed(it); else output::Output(it); } } //////////////////////////////////////////////////////// // CreateOptionHolder & helper functions //////////////////////////////////////////////////////// template<typename T> static bool ValidateWrapper(const boost::python::object & val, T arg) { return boost::python::extract<bool>(val.attr("Validate")(arg)); } template<typename T> static bool EmptyValidator(T arg) { return true; } template<typename T> static OptionBasePtr CreateOptionHolder(const std::string & key, const boost::python::tuple & tup) { PythonType ptype_default = DeterminePyType(tup[1]); T * def = nullptr; if(ptype_default != PythonType::None) { try { def = new T(ConvertToCpp<T>(tup[1])); } catch(const PythonConvertException & ex) { throw OptionException(ex, key, "desc", "Default could not be converted"); } } // Already checked /* PythonType ptype_type = DeterminePyType(tup[0]); if(ptype_type != PythonType::String) throw OptionException("\"Type\" element of tuple is not a bool", key, "type", GetPyClass(tup[0])); */ if(DeterminePyType(tup[2]) != PythonType::Bool) throw OptionException("\"Required\" element of tuple is not a bool", key, "type", GetPyClass(tup[2])); if(DeterminePyType(tup[4]) != PythonType::String) throw OptionException("\"Help\" element of tuple is not a string", key, "type", GetPyClass(tup[4])); bool req = boost::python::extract<bool>(tup[2]); std::string help = boost::python::extract<std::string>(tup[4]); PythonType pytype = StrToPythonType(boost::python::extract<std::string>(tup[0])); //! \todo Check to make sure validator object is callable // Check if validator is given. If not, use EmptyValidator typename OptionHolder<T>::ValidatorFunc validator = EmptyValidator<T>; if(DeterminePyType(tup[3]) != PythonType::None) validator = std::bind(ValidateWrapper<T>, tup[3], std::placeholders::_1); return OptionBasePtr(new OptionHolder<T>(key, def, validator, req, pytype, help)); } OptionBasePtr OptionHolderFactory(const std::string & key, const boost::python::object & obj) { PythonType ptype = DeterminePyType(obj); if(ptype != PythonType::Tuple) throw OptionException("Object for option is not a tuple", key, "pythontype", GetPyClass(obj)); boost::python::tuple tup = boost::python::extract<boost::python::tuple>(obj); int length = boost::python::extract<int>(tup.attr("__len__")()); if(length != 5) throw OptionException("Python options tuple does not have 5 elements", key, "length", std::to_string(length)); if(DeterminePyType(tup[0]) != PythonType::String) throw OptionException("\"Type\" element of tuple is not a string", key, "type", GetPyClass(tup[0])); std::string type = ConvertToCpp<std::string>(tup[0]); switch(StrToPythonType(type)) { case PythonType::Bool: return CreateOptionHolder<bool>(key, tup); case PythonType::Int: return CreateOptionHolder<OptionInt>(key, tup); case PythonType::Float: return CreateOptionHolder<OptionFloat>(key, tup); case PythonType::String: return CreateOptionHolder<std::string>(key, tup); case PythonType::ListBool: return CreateOptionHolder<std::vector<bool>>(key, tup); case PythonType::ListInt: return CreateOptionHolder<std::vector<OptionInt>>(key, tup); case PythonType::ListFloat: return CreateOptionHolder<std::vector<OptionFloat>>(key, tup); case PythonType::ListString: return CreateOptionHolder<std::vector<std::string>>(key, tup); default: throw OptionException("Cannot convert python type to option", key, "type", type); } } } // close namespace detail } // close namespace options } // close namespace bpmodule <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {StereoFixed.png}, {StereoMoving.png} // OUTPUTS: {deformationFieldOutput-horizontal.png}, {deformationFieldOutput-vertical.png}, {resampledOutput2.png} // 5 1.0 2 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example demonstrates the use of the \doxygen{otb}{NCCRegistrationFilter}. This filter performs deformation estimation // by optimising a PDE based on correlation. This use the finite difference solver hierarchy. // // The first step toward the use of these filters is to include the proper header files. // // Software Guide : EndLatex #include "otbImage.h" #include "otbStreamingImageFileWriter.h" #include "otbImageFileReader.h" #include "otbCommandLineArgumentParser.h" // Software Guide : BeginCodeSnippet #include "otbNCCRegistrationFilter.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkWarpImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImageOfVectorsToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" #include "itkCastImageFilter.h" #include <iostream> int main(int argc, char** argv ) { if(argc!= 9) { std::cerr <<"Usage: "<<argv[0]; std::cerr<<" fixedFileName movingFileName fieldOutNameHorizontal fieldOutNameVertical imageOutName "; std::cerr<<"explorationSize bluringSigma nbIterations "; return EXIT_FAILURE; } const unsigned int ImageDimension = 2; typedef double PixelType; typedef itk::Vector<double,ImageDimension> DeformationPixelType; typedef double CoordinateRepresentationType; typedef unsigned char OutputPixelType; typedef otb::Image<OutputPixelType,ImageDimension> OutputImageType; // Software Guide : BeginLatex // // Several type of \doxygen{otb}{Image} are required to represent the reference image (fixed) // the image we want to register (moving) and the deformation field. // // Software Guide : EndLatex //Allocate Images // Software Guide : BeginCodeSnippet typedef otb::Image<PixelType,ImageDimension> MovingImageType; typedef otb::Image<PixelType,ImageDimension> FixedImageType; typedef otb::Image<DeformationPixelType, ImageDimension> DeformationFieldType; // Software Guide : EndCodeSnippet typedef otb::ImageFileReader< FixedImageType > FixedReaderType; FixedReaderType::Pointer fReader = FixedReaderType::New(); fReader->SetFileName(argv[1]); typedef otb::ImageFileReader< MovingImageType > MovingReaderType; MovingReaderType::Pointer mReader = MovingReaderType::New(); mReader->SetFileName(argv[2]); // Software Guide : BeginLatex // // To make the correlation possible and to avoid some local minima the first required step is // to blur the input images. This is done using the \doxygen{itk}{RecursiveGaussianImageFilter}: // // Software Guide : EndLatex //Blur input images // Software Guide : BeginCodeSnippet typedef itk::RecursiveGaussianImageFilter< FixedImageType, FixedImageType > FixedBlurType; FixedBlurType::Pointer fBlur = FixedBlurType::New(); fBlur->SetInput( fReader->GetOutput() ); fBlur->SetSigma( atof(argv[7]) ); typedef itk::RecursiveGaussianImageFilter< MovingImageType, MovingImageType > MovingBlurType; MovingBlurType::Pointer mBlur = MovingBlurType::New(); mBlur->SetInput( mReader->GetOutput() ); mBlur->SetSigma(atof(argv[7]) ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now, we need to instanciate the NCCRegistrationFilter which is going to perform the registration: // // Software Guide : EndLatex //Create the filter // Software Guide : BeginCodeSnippet typedef otb::NCCRegistrationFilter< FixedImageType, MovingImageType, DeformationFieldType > RegistrationFilterType; RegistrationFilterType::Pointer registrator = RegistrationFilterType::New(); registrator->SetMovingImage( mBlur->GetOutput() ); registrator->SetFixedImage( fBlur->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Few parameters need to be specified to the NCCRegistrationFilter: // \begin{itemize} // \item The area where the search is performed. This area is defined by its radius: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef RegistrationFilterType::RadiusType RadiusType; RadiusType radius; radius[0] = atoi(argv[6]); radius[1] = atoi(argv[6]); registrator->SetNCCRadius( radius ); // Software Guide : EndCodeSnippet std::cout << "NCC radius " << registrator->GetNCCRadius() << std::endl; // Software Guide : BeginLatex // // \item The number of iteration for the PDE resolution: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet registrator->SetNumberOfIterations( atoi(argv[8]) ); // Software Guide : EndCodeSnippet // registrator->GetDeformationField(); // Software Guide : BeginLatex // // \end{itemize} // The execution of the NCCRegistrationFilter will be triggered by the \code{Update()} // call on the writer at the end of the pipeline. Make sure to use a // \doxygen{otb}{StreamingImageFileWriter} if you want to benefit from the streaming features. // // Software Guide : EndLatex typedef otb::ImageOfVectorsToMonoChannelExtractROI<DeformationFieldType, MovingImageType> ChannelExtractionFilterType; ChannelExtractionFilterType::Pointer channelExtractor = ChannelExtractionFilterType::New(); channelExtractor->SetInput(registrator->GetOutput()); channelExtractor->SetChannel(1); typedef itk::RescaleIntensityImageFilter<MovingImageType, OutputImageType> RescalerType; RescalerType::Pointer fieldRescaler = RescalerType::New(); fieldRescaler->SetInput(channelExtractor->GetOutput()); fieldRescaler->SetOutputMaximum(255); fieldRescaler->SetOutputMinimum(0); typedef otb::StreamingImageFileWriter< OutputImageType > DFWriterType; DFWriterType::Pointer dfWriter = DFWriterType::New(); dfWriter->SetFileName(argv[3]); dfWriter->SetInput( fieldRescaler->GetOutput() ); dfWriter->Update(); channelExtractor->SetChannel(2); dfWriter->SetFileName(argv[4]); dfWriter->Update(); typedef itk::WarpImageFilter<MovingImageType, MovingImageType, DeformationFieldType> WarperType; WarperType::Pointer warper = WarperType::New(); MovingImageType::PixelType padValue = 4.0; warper->SetInput( mReader->GetOutput() ); warper->SetDeformationField( registrator->GetOutput() ); warper->SetEdgePaddingValue( padValue ); typedef itk::CastImageFilter< MovingImageType, OutputImageType > CastFilterType; CastFilterType::Pointer caster = CastFilterType::New(); caster->SetInput( warper->GetOutput() ); typedef otb::StreamingImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[5]); writer->SetInput( caster->GetOutput() ); writer->Update(); // Software Guide : BeginLatex // // Figure~\ref{fig:NCCRegistrationFilterOUTPUT} shows the result of // applying the disparity map estimation. // // \begin{figure} // \center // \includegraphics[width=0.40\textwidth]{StereoFixed.eps} // \includegraphics[width=0.40\textwidth]{StereoMoving.eps} // \includegraphics[width=0.40\textwidth]{deformationFieldOutput-horizontal.eps} // \includegraphics[width=0.40\textwidth]{deformationFieldOutput-vertical.eps} // \itkcaption[Deformation field and resampling from NCC registration]{From left // to right and top to bottom: fixed input image, moving image with a low stereo angle, // estimated deformation field in the horizontal direction, estimated deformation field in the vertical direction.} // \label{fig:NCCRegistrationFilterOUTPUT} // \end{figure} // // Software Guide : EndLatex return EXIT_SUCCESS; } <commit_msg>STYLE: few corrections on the example<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #ifdef __BORLANDC__ #define ITK_LEAN_AND_MEAN #endif // Software Guide : BeginCommandLineArgs // INPUTS: {StereoFixed.png}, {StereoMoving.png} // OUTPUTS: {deformationFieldOutput-horizontal.png}, {deformationFieldOutput-vertical.png}, {resampledOutput2.png} // 5 1.0 2 // Software Guide : EndCommandLineArgs // Software Guide : BeginLatex // // This example demonstrates the use of the \doxygen{otb}{NCCRegistrationFilter}. This filter performs deformation estimation // by optimising a PDE based on the normalized correlation coefficient. It uses the finite difference solver hierarchy. // // The first step toward the use of these filters is to include the proper header files. // // Software Guide : EndLatex #include "otbImage.h" #include "otbStreamingImageFileWriter.h" #include "otbImageFileReader.h" #include "otbCommandLineArgumentParser.h" // Software Guide : BeginCodeSnippet #include "otbNCCRegistrationFilter.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkWarpImageFilter.h" // Software Guide : EndCodeSnippet #include "otbImageOfVectorsToMonoChannelExtractROI.h" #include "itkRescaleIntensityImageFilter.h" #include "itkCastImageFilter.h" #include <iostream> int main(int argc, char** argv ) { if(argc!= 9) { std::cerr <<"Usage: "<<argv[0]; std::cerr<<" fixedFileName movingFileName fieldOutNameHorizontal fieldOutNameVertical imageOutName "; std::cerr<<"explorationSize bluringSigma nbIterations "; return EXIT_FAILURE; } const unsigned int ImageDimension = 2; typedef double PixelType; typedef itk::Vector<double,ImageDimension> DeformationPixelType; typedef double CoordinateRepresentationType; typedef unsigned char OutputPixelType; typedef otb::Image<OutputPixelType,ImageDimension> OutputImageType; // Software Guide : BeginLatex // // Several type of \doxygen{otb}{Image} are required to represent the reference image (fixed) // the image we want to register (moving) and the deformation field. // // Software Guide : EndLatex //Allocate Images // Software Guide : BeginCodeSnippet typedef otb::Image<PixelType,ImageDimension> MovingImageType; typedef otb::Image<PixelType,ImageDimension> FixedImageType; typedef otb::Image<DeformationPixelType, ImageDimension> DeformationFieldType; // Software Guide : EndCodeSnippet typedef otb::ImageFileReader< FixedImageType > FixedReaderType; FixedReaderType::Pointer fReader = FixedReaderType::New(); fReader->SetFileName(argv[1]); typedef otb::ImageFileReader< MovingImageType > MovingReaderType; MovingReaderType::Pointer mReader = MovingReaderType::New(); mReader->SetFileName(argv[2]); // Software Guide : BeginLatex // // To make the correlation estimation more robust, the first // required step is to blur the input images. This is done using the // \doxygen{itk}{RecursiveGaussianImageFilter}: // // Software Guide : EndLatex //Blur input images // Software Guide : BeginCodeSnippet typedef itk::RecursiveGaussianImageFilter< FixedImageType, FixedImageType > FixedBlurType; FixedBlurType::Pointer fBlur = FixedBlurType::New(); fBlur->SetInput( fReader->GetOutput() ); fBlur->SetSigma( atof(argv[7]) ); typedef itk::RecursiveGaussianImageFilter< MovingImageType, MovingImageType > MovingBlurType; MovingBlurType::Pointer mBlur = MovingBlurType::New(); mBlur->SetInput( mReader->GetOutput() ); mBlur->SetSigma(atof(argv[7]) ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Now, we need to instanciate the NCCRegistrationFilter which is going to perform the registration: // // Software Guide : EndLatex //Create the filter // Software Guide : BeginCodeSnippet typedef otb::NCCRegistrationFilter< FixedImageType, MovingImageType, DeformationFieldType > RegistrationFilterType; RegistrationFilterType::Pointer registrator = RegistrationFilterType::New(); registrator->SetMovingImage( mBlur->GetOutput() ); registrator->SetFixedImage( fBlur->GetOutput() ); // Software Guide : EndCodeSnippet // Software Guide : BeginLatex // // Some parameters need to be specified to the NCCRegistrationFilter: // \begin{itemize} // \item The area where the search is performed. This area is defined by its radius: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet typedef RegistrationFilterType::RadiusType RadiusType; RadiusType radius; radius[0] = atoi(argv[6]); radius[1] = atoi(argv[6]); registrator->SetNCCRadius( radius ); // Software Guide : EndCodeSnippet std::cout << "NCC radius " << registrator->GetNCCRadius() << std::endl; // Software Guide : BeginLatex // // \item The number of iterations for the PDE resolution: // // Software Guide : EndLatex // Software Guide : BeginCodeSnippet registrator->SetNumberOfIterations( atoi(argv[8]) ); // Software Guide : EndCodeSnippet // registrator->GetDeformationField(); // Software Guide : BeginLatex // // \end{itemize} // The execution of the NCCRegistrationFilter will be triggered by // the \code{Update()} call on the writer at the end of the // pipeline. Make sure to use a // \doxygen{otb}{StreamingImageFileWriter} if you want to benefit // from the streaming features. // // Software Guide : EndLatex typedef otb::ImageOfVectorsToMonoChannelExtractROI<DeformationFieldType, MovingImageType> ChannelExtractionFilterType; ChannelExtractionFilterType::Pointer channelExtractor = ChannelExtractionFilterType::New(); channelExtractor->SetInput(registrator->GetOutput()); channelExtractor->SetChannel(1); typedef itk::RescaleIntensityImageFilter<MovingImageType, OutputImageType> RescalerType; RescalerType::Pointer fieldRescaler = RescalerType::New(); fieldRescaler->SetInput(channelExtractor->GetOutput()); fieldRescaler->SetOutputMaximum(255); fieldRescaler->SetOutputMinimum(0); typedef otb::StreamingImageFileWriter< OutputImageType > DFWriterType; DFWriterType::Pointer dfWriter = DFWriterType::New(); dfWriter->SetFileName(argv[3]); dfWriter->SetInput( fieldRescaler->GetOutput() ); dfWriter->Update(); channelExtractor->SetChannel(2); dfWriter->SetFileName(argv[4]); dfWriter->Update(); typedef itk::WarpImageFilter<MovingImageType, MovingImageType, DeformationFieldType> WarperType; WarperType::Pointer warper = WarperType::New(); MovingImageType::PixelType padValue = 4.0; warper->SetInput( mReader->GetOutput() ); warper->SetDeformationField( registrator->GetOutput() ); warper->SetEdgePaddingValue( padValue ); typedef itk::CastImageFilter< MovingImageType, OutputImageType > CastFilterType; CastFilterType::Pointer caster = CastFilterType::New(); caster->SetInput( warper->GetOutput() ); typedef otb::StreamingImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName(argv[5]); writer->SetInput( caster->GetOutput() ); writer->Update(); // Software Guide : BeginLatex // // Figure~\ref{fig:NCCRegistrationFilterOUTPUT} shows the result of // applying the disparity map estimation. // // \begin{figure} // \center // \includegraphics[width=0.40\textwidth]{StereoFixed.eps} // \includegraphics[width=0.40\textwidth]{StereoMoving.eps} // \includegraphics[width=0.40\textwidth]{deformationFieldOutput-horizontal.eps} // \includegraphics[width=0.40\textwidth]{deformationFieldOutput-vertical.eps} // \itkcaption[Deformation field and resampling from NCC registration]{From left // to right and top to bottom: fixed input image, moving image with a low stereo angle, // estimated deformation field in the horizontal direction, estimated deformation field in the vertical direction.} // \label{fig:NCCRegistrationFilterOUTPUT} // \end{figure} // // Software Guide : EndLatex return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright © 2005 Jason Kivlighn <[email protected]> * * * * 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 "prepmethodcombobox.h" #include <q3listbox.h> #include <QLineEdit> #include <kdebug.h> #include "backends/recipedb.h" #include "datablocks/elementlist.h" /** Completion object which allows completing completing items * the last item in a comma-separated list */ class PrepMethodCompletion : public KCompletion { public: PrepMethodCompletion() : KCompletion() {} virtual QString makeCompletion( const QString &string ) { kDebug()<<"original makeCompletion( "<<string<<" )"; int comma_index = string.lastIndexOf(","); QString completion_txt = string; if ( comma_index != -1 ) completion_txt = completion_txt.right( completion_txt.length() - comma_index - 1 ).trimmed(); if ( completion_txt.isEmpty() ) return string; kDebug()<<"altered makeCompletion( "<<completion_txt<<" )"; completion_txt = KCompletion::makeCompletion(completion_txt); kDebug()<<"got: "<<completion_txt; if ( completion_txt.isEmpty() ) completion_txt = string; else if ( comma_index != -1 ) completion_txt = string.left( comma_index ) + "," + completion_txt; kDebug()<<"returning: "<<completion_txt; return completion_txt; } }; PrepMethodComboBox::PrepMethodComboBox( bool b, QWidget *parent, RecipeDB *db, const QString &specialItem ): KComboBox( b, parent ), database( db ), m_specialItem(specialItem) { setAutoDeleteCompletionObject(true); setCompletionObject(new PrepMethodCompletion()); } void PrepMethodComboBox::reload() { QString remember_text; if ( isEditable() ) remember_text = lineEdit()->text(); ElementList prepMethodList; database->loadPrepMethods( &prepMethodList ); clear(); prepMethodComboRows.clear(); int row = 0; if ( !m_specialItem.isNull() ) { insertItem( count(), m_specialItem ); prepMethodComboRows.insert( row, -1 ); row++; } for ( ElementList::const_iterator it = prepMethodList.begin(); it != prepMethodList.end(); ++it, ++row ) { insertItem( count(), (*it).name ); completionObject()->addItem((*it).name); prepMethodComboRows.insert( row,(*it).id ); } if ( isEditable() ) lineEdit()->setText( remember_text ); database->disconnect( this ); connect( database, SIGNAL( prepMethodCreated( const Element & ) ), SLOT( createPrepMethod( const Element & ) ) ); connect( database, SIGNAL( prepMethodRemoved( int ) ), SLOT( removePrepMethod( int ) ) ); } int PrepMethodComboBox::id( int row ) { return prepMethodComboRows[ row ]; } int PrepMethodComboBox::id( const QString &ing ) { for ( int i = 0; i < count(); i++ ) { if ( ing == itemText( i ) ) return id(i); } kDebug()<<"Warning: couldn't find the ID for "<<ing; return -1; } void PrepMethodComboBox::createPrepMethod( const Element &element ) { int row = findInsertionPoint( element.name ); QString remember_text; if ( isEditable() ) remember_text = lineEdit()->text(); insertItem( row, element.name ); completionObject()->addItem(element.name); if ( isEditable() ) lineEdit()->setText( remember_text ); //now update the map by pushing everything after this item down QMap<int, int> new_map; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.key() >= row ) { new_map.insert( it.key() + 1, it.value() ); } else new_map.insert( it.key(), it.value() ); } prepMethodComboRows = new_map; prepMethodComboRows.insert( row, element.id ); } void PrepMethodComboBox::removePrepMethod( int id ) { int row = -1; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.value() == id ) { row = it.key(); completionObject()->removeItem( itemText(row) ); removeItem( row ); prepMethodComboRows.erase( it ); break; } } if ( row == -1 ) return ; //now update the map by pushing everything after this item up QMap<int, int> new_map; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.key() > row ) { new_map.insert( it.key() - 1, it.value() ); } else new_map.insert( it.key(), it.value() ); } prepMethodComboRows = new_map; } int PrepMethodComboBox::findInsertionPoint( const QString &name ) { for ( int i = 0; i < count(); i++ ) { if ( QString::localeAwareCompare( name, itemText( i ) ) < 0 ) return i; } return count(); } void PrepMethodComboBox::setSelected( int prepID ) { //do a reverse lookup on the row->id map QMap<int, int>::const_iterator it; for ( it = prepMethodComboRows.constBegin(); it != prepMethodComboRows.constEnd(); ++it ) { if ( it.value() == prepID ) { setCurrentIndex(it.key()); break; } } } #include "prepmethodcombobox.moc" <commit_msg>Fix Krazy warnings: doublequote_chars - src/widgets/prepmethodcombobox.cpp<commit_after>/*************************************************************************** * Copyright © 2005 Jason Kivlighn <[email protected]> * * * * 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 "prepmethodcombobox.h" #include <q3listbox.h> #include <QLineEdit> #include <kdebug.h> #include "backends/recipedb.h" #include "datablocks/elementlist.h" /** Completion object which allows completing completing items * the last item in a comma-separated list */ class PrepMethodCompletion : public KCompletion { public: PrepMethodCompletion() : KCompletion() {} virtual QString makeCompletion( const QString &string ) { kDebug()<<"original makeCompletion( "<<string<<" )"; int comma_index = string.lastIndexOf(","); QString completion_txt = string; if ( comma_index != -1 ) completion_txt = completion_txt.right( completion_txt.length() - comma_index - 1 ).trimmed(); if ( completion_txt.isEmpty() ) return string; kDebug()<<"altered makeCompletion( "<<completion_txt<<" )"; completion_txt = KCompletion::makeCompletion(completion_txt); kDebug()<<"got: "<<completion_txt; if ( completion_txt.isEmpty() ) completion_txt = string; else if ( comma_index != -1 ) completion_txt = string.left( comma_index ) + ',' + completion_txt; kDebug()<<"returning: "<<completion_txt; return completion_txt; } }; PrepMethodComboBox::PrepMethodComboBox( bool b, QWidget *parent, RecipeDB *db, const QString &specialItem ): KComboBox( b, parent ), database( db ), m_specialItem(specialItem) { setAutoDeleteCompletionObject(true); setCompletionObject(new PrepMethodCompletion()); } void PrepMethodComboBox::reload() { QString remember_text; if ( isEditable() ) remember_text = lineEdit()->text(); ElementList prepMethodList; database->loadPrepMethods( &prepMethodList ); clear(); prepMethodComboRows.clear(); int row = 0; if ( !m_specialItem.isNull() ) { insertItem( count(), m_specialItem ); prepMethodComboRows.insert( row, -1 ); row++; } for ( ElementList::const_iterator it = prepMethodList.begin(); it != prepMethodList.end(); ++it, ++row ) { insertItem( count(), (*it).name ); completionObject()->addItem((*it).name); prepMethodComboRows.insert( row,(*it).id ); } if ( isEditable() ) lineEdit()->setText( remember_text ); database->disconnect( this ); connect( database, SIGNAL( prepMethodCreated( const Element & ) ), SLOT( createPrepMethod( const Element & ) ) ); connect( database, SIGNAL( prepMethodRemoved( int ) ), SLOT( removePrepMethod( int ) ) ); } int PrepMethodComboBox::id( int row ) { return prepMethodComboRows[ row ]; } int PrepMethodComboBox::id( const QString &ing ) { for ( int i = 0; i < count(); i++ ) { if ( ing == itemText( i ) ) return id(i); } kDebug()<<"Warning: couldn't find the ID for "<<ing; return -1; } void PrepMethodComboBox::createPrepMethod( const Element &element ) { int row = findInsertionPoint( element.name ); QString remember_text; if ( isEditable() ) remember_text = lineEdit()->text(); insertItem( row, element.name ); completionObject()->addItem(element.name); if ( isEditable() ) lineEdit()->setText( remember_text ); //now update the map by pushing everything after this item down QMap<int, int> new_map; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.key() >= row ) { new_map.insert( it.key() + 1, it.value() ); } else new_map.insert( it.key(), it.value() ); } prepMethodComboRows = new_map; prepMethodComboRows.insert( row, element.id ); } void PrepMethodComboBox::removePrepMethod( int id ) { int row = -1; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.value() == id ) { row = it.key(); completionObject()->removeItem( itemText(row) ); removeItem( row ); prepMethodComboRows.erase( it ); break; } } if ( row == -1 ) return ; //now update the map by pushing everything after this item up QMap<int, int> new_map; for ( QMap<int, int>::iterator it = prepMethodComboRows.begin(); it != prepMethodComboRows.end(); ++it ) { if ( it.key() > row ) { new_map.insert( it.key() - 1, it.value() ); } else new_map.insert( it.key(), it.value() ); } prepMethodComboRows = new_map; } int PrepMethodComboBox::findInsertionPoint( const QString &name ) { for ( int i = 0; i < count(); i++ ) { if ( QString::localeAwareCompare( name, itemText( i ) ) < 0 ) return i; } return count(); } void PrepMethodComboBox::setSelected( int prepID ) { //do a reverse lookup on the row->id map QMap<int, int>::const_iterator it; for ( it = prepMethodComboRows.constBegin(); it != prepMethodComboRows.constEnd(); ++it ) { if ( it.value() == prepID ) { setCurrentIndex(it.key()); break; } } } #include "prepmethodcombobox.moc" <|endoftext|>
<commit_before>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/xbdm/xbdm_private.h" #include "xenia/kernel/xthread.h" #include "xenia/xbox.h" namespace xe { namespace kernel { namespace xbdm { #define MAKE_DUMMY_STUB_PTR(x) \ dword_result_t x() { return 0; } \ DECLARE_XBDM_EXPORT1(x, kDebug, kStub) #define MAKE_DUMMY_STUB_STATUS(x) \ dword_result_t x() { return X_STATUS_INVALID_PARAMETER; } \ DECLARE_XBDM_EXPORT1(x, kDebug, kStub) MAKE_DUMMY_STUB_PTR(DmAllocatePool); void DmCloseLoadedModules(lpdword_t unk0_ptr) {} DECLARE_XBDM_EXPORT1(DmCloseLoadedModules, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmFreePool); dword_result_t DmGetXbeInfo() { // TODO(gibbed): Crackdown appears to expect this as success? // Unknown arguments -- let's hope things don't explode. return 0x02DA0000; } DECLARE_XBDM_EXPORT1(DmGetXbeInfo, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmGetXboxName); dword_result_t DmIsDebuggerPresent() { return 0; } DECLARE_XBDM_EXPORT1(DmIsDebuggerPresent, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmRegisterCommandProcessor); void DmSendNotificationString(lpdword_t unk0_ptr) {} DECLARE_XBDM_EXPORT1(DmSendNotificationString, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmRegisterCommandProcessorEx); MAKE_DUMMY_STUB_STATUS(DmStartProfiling); MAKE_DUMMY_STUB_STATUS(DmStopProfiling); dword_result_t DmCaptureStackBackTrace(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { return X_STATUS_INVALID_PARAMETER; } DECLARE_XBDM_EXPORT1(DmCaptureStackBackTrace, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmGetThreadInfoEx); MAKE_DUMMY_STUB_STATUS(DmSetProfilingOptions); dword_result_t DmWalkLoadedModules(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { return X_STATUS_INVALID_PARAMETER; } DECLARE_XBDM_EXPORT1(DmWalkLoadedModules, kDebug, kStub); void DmMapDevkitDrive() {} DECLARE_XBDM_EXPORT1(DmMapDevkitDrive, kDebug, kStub); dword_result_t DmFindPdbSignature(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { return X_STATUS_INVALID_PARAMETER; } DECLARE_XBDM_EXPORT1(DmFindPdbSignature, kDebug, kStub); void RegisterMiscExports(xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {} } // namespace xbdm } // namespace kernel } // namespace xe <commit_msg>[Kernel/XBDM] Change return values of RegisterCommandProcessorEx & DmWalkLoadedModules<commit_after>/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2020 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include "xenia/base/logging.h" #include "xenia/kernel/kernel_state.h" #include "xenia/kernel/util/shim_utils.h" #include "xenia/kernel/xbdm/xbdm_private.h" #include "xenia/kernel/xthread.h" #include "xenia/xbox.h" namespace xe { namespace kernel { namespace xbdm { #define MAKE_DUMMY_STUB_PTR(x) \ dword_result_t x() { return 0; } \ DECLARE_XBDM_EXPORT1(x, kDebug, kStub) #define MAKE_DUMMY_STUB_STATUS(x) \ dword_result_t x() { return X_STATUS_INVALID_PARAMETER; } \ DECLARE_XBDM_EXPORT1(x, kDebug, kStub) MAKE_DUMMY_STUB_PTR(DmAllocatePool); void DmCloseLoadedModules(lpdword_t unk0_ptr) {} DECLARE_XBDM_EXPORT1(DmCloseLoadedModules, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmFreePool); dword_result_t DmGetXbeInfo() { // TODO(gibbed): Crackdown appears to expect this as success? // Unknown arguments -- let's hope things don't explode. return 0x02DA0000; } DECLARE_XBDM_EXPORT1(DmGetXbeInfo, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmGetXboxName); dword_result_t DmIsDebuggerPresent() { return 0; } DECLARE_XBDM_EXPORT1(DmIsDebuggerPresent, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmRegisterCommandProcessor); void DmSendNotificationString(lpdword_t unk0_ptr) {} DECLARE_XBDM_EXPORT1(DmSendNotificationString, kDebug, kStub); dword_result_t DmRegisterCommandProcessorEx(lpdword_t name_ptr, lpdword_t handler_fn, dword_t unk3) { // Return success to prevent some games from stalling return X_STATUS_SUCCESS; } DECLARE_XBDM_EXPORT1(DmRegisterCommandProcessorEx, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmStartProfiling); MAKE_DUMMY_STUB_STATUS(DmStopProfiling); dword_result_t DmCaptureStackBackTrace(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { return X_STATUS_INVALID_PARAMETER; } DECLARE_XBDM_EXPORT1(DmCaptureStackBackTrace, kDebug, kStub); MAKE_DUMMY_STUB_STATUS(DmGetThreadInfoEx); MAKE_DUMMY_STUB_STATUS(DmSetProfilingOptions); dword_result_t DmWalkLoadedModules(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { // Some games will loop forever unless this code is returned return 0x82DA0104; } DECLARE_XBDM_EXPORT1(DmWalkLoadedModules, kDebug, kStub); void DmMapDevkitDrive() {} DECLARE_XBDM_EXPORT1(DmMapDevkitDrive, kDebug, kStub); dword_result_t DmFindPdbSignature(lpdword_t unk0_ptr, lpdword_t unk1_ptr) { return X_STATUS_INVALID_PARAMETER; } DECLARE_XBDM_EXPORT1(DmFindPdbSignature, kDebug, kStub); void RegisterMiscExports(xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {} } // namespace xbdm } // namespace kernel } // namespace xe <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ReturnSynthesizer.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { ReturnSynthesizer::ReturnSynthesizer(clang::Sema* S) : TransactionTransformer(S), m_Context(&S->getASTContext()) { } // pin the vtable here. ReturnSynthesizer::~ReturnSynthesizer() { } void ReturnSynthesizer::Transform() { if (!getTransaction()->getCompilationOpts().ResultEvaluation) return; FunctionDecl* FD = getTransaction()->getWrapperFD(); int foundAtPos = -1; Expr* lastExpr = utils::Analyze::GetOrCreateLastExpr(FD, &foundAtPos, /*omitDS*/false, m_Sema); if (lastExpr) { QualType RetTy = lastExpr->getType(); if (!RetTy->isVoidType() && RetTy.isTriviallyCopyableType(*m_Context)) { // Change the void function's return type // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); FunctionProtoType::ExtProtoInfo EPI; QualType FnTy = m_Context->getFunctionType(RetTy, llvm::ArrayRef<QualType>(), EPI); FD->setType(FnTy); CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); assert(CS && "Missing body?"); // Change it to a return stmt (Avoid dealloc/alloc of all el.) *(CS->body_begin() + foundAtPos) = m_Sema->ActOnReturnStmt(lastExpr->getExprLoc(), lastExpr).take(); } } else if (foundAtPos >= 0) { // check for non-void return statement CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); Stmt* CSS = *(CS->body_begin() + foundAtPos); if (ReturnStmt* RS = dyn_cast<ReturnStmt>(CSS)) { if (Expr* RetV = RS->getRetValue()) { QualType RetTy = RetV->getType(); // Any return statement will have been "healed" by Sema // to correspond to the original void return type of the // wrapper, using a ImplicitCastExpr 'void' <ToVoid>. // Remove that. if (RetTy->isVoidType()) { ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(RetV); if (VoidCast) { RS->setRetValue(VoidCast->getSubExpr()); RetTy = VoidCast->getSubExpr()->getType(); } } if (!RetTy->isVoidType() && RetTy.isTriviallyCopyableType(*m_Context)) { Sema::ContextRAII pushedDC(*m_Sema, FD); FunctionProtoType::ExtProtoInfo EPI; QualType FnTy = m_Context->getFunctionType(RetTy, llvm::ArrayRef<QualType>(), EPI); FD->setType(FnTy); } // not returning void } // have return value } // is a return statement } // have a statement } } // end namespace cling <commit_msg>Don't return array types; functions cannot do that. Decay to pointer instead.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "ReturnSynthesizer.h" #include "cling/Interpreter/Transaction.h" #include "cling/Utils/AST.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclGroup.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { ReturnSynthesizer::ReturnSynthesizer(clang::Sema* S) : TransactionTransformer(S), m_Context(&S->getASTContext()) { } // pin the vtable here. ReturnSynthesizer::~ReturnSynthesizer() { } void ReturnSynthesizer::Transform() { if (!getTransaction()->getCompilationOpts().ResultEvaluation) return; FunctionDecl* FD = getTransaction()->getWrapperFD(); int foundAtPos = -1; Expr* lastExpr = utils::Analyze::GetOrCreateLastExpr(FD, &foundAtPos, /*omitDS*/false, m_Sema); if (lastExpr) { QualType RetTy = lastExpr->getType(); if (!RetTy->isVoidType() && RetTy.isTriviallyCopyableType(*m_Context)) { // Change the void function's return type // We can't PushDeclContext, because we don't have scope. Sema::ContextRAII pushedDC(*m_Sema, FD); if (RetTy->isArrayType()) { // Functions cannot return arrays; decay to pointer instead. // Array lifetime should be fine; if it's a definition it will be // extracted. RetTy = FD->getASTContext().getArrayDecayedType(RetTy); lastExpr = m_Sema->ImpCastExprToType(lastExpr, RetTy, CK_ArrayToPointerDecay, VK_RValue).take(); } FunctionProtoType::ExtProtoInfo EPI; QualType FnTy = m_Context->getFunctionType(RetTy, llvm::ArrayRef<QualType>(), EPI); FD->setType(FnTy); CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); assert(CS && "Missing body?"); // Change it to a return stmt (Avoid dealloc/alloc of all el.) *(CS->body_begin() + foundAtPos) = m_Sema->ActOnReturnStmt(lastExpr->getExprLoc(), lastExpr).take(); } } else if (foundAtPos >= 0) { // check for non-void return statement CompoundStmt* CS = cast<CompoundStmt>(FD->getBody()); Stmt* CSS = *(CS->body_begin() + foundAtPos); if (ReturnStmt* RS = dyn_cast<ReturnStmt>(CSS)) { if (Expr* RetV = RS->getRetValue()) { QualType RetTy = RetV->getType(); // Any return statement will have been "healed" by Sema // to correspond to the original void return type of the // wrapper, using a ImplicitCastExpr 'void' <ToVoid>. // Remove that. if (RetTy->isVoidType()) { ImplicitCastExpr* VoidCast = dyn_cast<ImplicitCastExpr>(RetV); if (VoidCast) { RS->setRetValue(VoidCast->getSubExpr()); RetTy = VoidCast->getSubExpr()->getType(); } } if (!RetTy->isVoidType() && RetTy.isTriviallyCopyableType(*m_Context)) { Sema::ContextRAII pushedDC(*m_Sema, FD); FunctionProtoType::ExtProtoInfo EPI; QualType FnTy = m_Context->getFunctionType(RetTy, llvm::ArrayRef<QualType>(), EPI); FD->setType(FnTy); } // not returning void } // have return value } // is a return statement } // have a statement } } // end namespace cling <|endoftext|>
<commit_before>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #include "mkldnn.hpp" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/mkl_types.h" #include "tensorflow/core/util/mkl_util.h" #include "tensorflow/core/util/tensor_format.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { class MklSoftmaxParams { public: memory::dims src_dims; MKL_TENSOR_FORMAT src_fmt; int axis; MklSoftmaxParams(memory::dims src_dims, MKL_TENSOR_FORMAT src_fmt, int axis) : src_dims(src_dims), src_fmt(src_fmt), axis(axis) {} }; template <typename T> class MklSoftmaxPrimitive : public MklPrimitive { public: explicit MklSoftmaxPrimitive(const MklSoftmaxParams& fwdParams) : cpu_engine_(ENGINE_CPU, 0) { context_.fwd_stream.reset(new CPU_STREAM(cpu_engine_)); Setup(fwdParams); } ~MklSoftmaxPrimitive() {} // Softmax forward execute // src_data: input data buffer of src // dst_data: output data buffer of dst void Execute(const T* src_data, T* dst_data) { context_.src_mem->set_data_handle( static_cast<void*>(const_cast<T*>(src_data))); context_.dst_mem->set_data_handle(static_cast<void*>(dst_data)); #ifdef ENABLE_MKLDNN_V1 DCHECK_EQ(context_.fwd_primitives.size(), context_.fwd_net_args.size()); for (size_t i = 0; i < context_.fwd_primitives.size(); ++i) { context_.fwd_primitives.at(i).execute(*context_.fwd_stream, context_.fwd_net_args.at(i)); } #else context_.fwd_stream->submit(context_.fwd_primitives); #endif // After execution, set data handle back. context_.src_mem->set_data_handle(DummyData); context_.dst_mem->set_data_handle(DummyData); } std::shared_ptr<mkldnn::softmax_forward::primitive_desc> GetSoftmaxFwdPd() { return context_.fwd_pd; } private: struct SoftmaxFwdContext { // MKL-DNN memory. std::shared_ptr<memory> src_mem; std::shared_ptr<memory> dst_mem; // Primitive descriptor. std::shared_ptr<mkldnn::softmax_forward::desc> fwd_desc; // Memory descriptor. std::shared_ptr<memory::desc> src_md; // Softmax primitive. std::shared_ptr<mkldnn::softmax_forward::primitive_desc> fwd_pd; std::shared_ptr<mkldnn::primitive> softmax_fwd; std::shared_ptr<stream> fwd_stream; std::vector<mkldnn::primitive> fwd_primitives; std::vector<MemoryArgsMap> fwd_net_args; SoftmaxFwdContext() : src_mem(nullptr), dst_mem(nullptr), fwd_desc(nullptr), src_md(nullptr), fwd_pd(nullptr), softmax_fwd(nullptr), fwd_stream(nullptr) {} }; // Softmax forward primitive setup void Setup(const MklSoftmaxParams& fwdParams) { // Create memory descriptors for softmax data with specified format. auto src_format = GET_TENSOR_FORMAT(fwdParams.src_fmt); context_.src_md.reset( new memory::desc({fwdParams.src_dims}, MklDnnType<T>(), src_format)); // Create softmax decriptor and primitive descriptor. context_.fwd_desc.reset(new mkldnn::softmax_forward::desc( prop_kind::forward_scoring, *context_.src_md, fwdParams.axis)); context_.fwd_pd.reset(new mkldnn::softmax_forward::primitive_desc( *context_.fwd_desc, cpu_engine_)); // Create memory primitive based on dummy data. context_.src_mem.reset(new MEMORY_CONSTRUCTOR_USING_MD( *context_.src_md, cpu_engine_, DummyData)); context_.dst_mem.reset(new MEMORY_CONSTRUCTOR_PD( context_.fwd_pd.get()->PRIMITIVE_DESC_DST, cpu_engine_, DummyData)); #ifdef ENABLE_MKLDNN_V1 // Create softmax primitive and add it to net context_.softmax_fwd.reset(new mkldnn::softmax_forward(*context_.fwd_pd)); context_.fwd_net_args.push_back({{MKLDNN_ARG_SRC, *context_.src_mem}, { MKLDNN_ARG_DST, *context_.dst_mem }}); #else context_.softmax_fwd.reset(new mkldnn::softmax_forward( *context_.fwd_pd, *context_.src_mem, *context_.dst_mem)); #endif // ENABLE_MKLDNN_V1 context_.fwd_primitives.push_back(*context_.softmax_fwd); } struct SoftmaxFwdContext context_; engine cpu_engine_; }; template <typename T> class MklSoftmaxPrimitiveFactory : public MklPrimitiveFactory<T> { public: static MklSoftmaxPrimitive<T>* Get(const MklSoftmaxParams& fwdParams) { // Get a softmax fwd primitive from the cached pool. MklSoftmaxPrimitive<T>* softmax_forward = static_cast<MklSoftmaxPrimitive<T>*>( MklSoftmaxPrimitiveFactory<T>::GetInstance().GetSoftmaxFwd( fwdParams)); if (softmax_forward == nullptr) { softmax_forward = new MklSoftmaxPrimitive<T>(fwdParams); MklSoftmaxPrimitiveFactory<T>::GetInstance().SetSoftmaxFwd( fwdParams, softmax_forward); } return softmax_forward; } static MklSoftmaxPrimitiveFactory& GetInstance() { static MklSoftmaxPrimitiveFactory instance_; return instance_; } private: MklSoftmaxPrimitiveFactory() {} ~MklSoftmaxPrimitiveFactory() {} static string CreateKey(const MklSoftmaxParams& fwdParams) { string prefix = "softmax_fwd"; FactoryKeyCreator key_creator; key_creator.AddAsKey(prefix); key_creator.AddAsKey(fwdParams.src_dims); key_creator.AddAsKey<int>(static_cast<int>(fwdParams.src_fmt)); key_creator.AddAsKey<int>(fwdParams.axis); return key_creator.GetKey(); } MklPrimitive* GetSoftmaxFwd(const MklSoftmaxParams& fwdParams) { string key = CreateKey(fwdParams); return this->GetOp(key); } void SetSoftmaxFwd(const MklSoftmaxParams& fwdParams, MklPrimitive* op) { string key = CreateKey(fwdParams); this->SetOp(key, op); } }; typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(ENGINE_CPU, 0); // src_tensor points to the 0-th input of global data struct "context". size_t src_idx = 0; const Tensor& src_tensor = MklGetInput(context, src_idx); MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimension of src_tensor. // Dim of the dst will also be same as src_dims. auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); memory::dims src_dims; int axis; if (src_mkl_shape.IsMklTensor()) { src_dims = src_mkl_shape.GetSizesAsMklDnnDims(); axis = 1; } else { src_dims = TFShapeToMklDnnDims(src_tf_shape); axis = input_dims - 1; } MKL_TENSOR_FORMAT layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of // the input tensor. Here "x" data format in MKL is used for 1 dim tensor, // "nc" for 2 dim tensor, "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, // and "ncdhw" for 5 dim tensor. Each of the symbols has the following // meaning: n = batch, c = channels, t = sequence length, h = height, w = // width, d = depth. When src tensor is MKL, layout_type here is only used // for setting TF layout type of output tensor. When input is TF Tensor, // layout here is no special sense. We use axis to define on which // dimension to do softmax. switch (input_dims) { case 1: layout_type = MKL_TENSOR_FORMAT_X; break; case 2: layout_type = MKL_TENSOR_FORMAT_NC; break; case 3: layout_type = MKL_TENSOR_FORMAT_TNC; break; case 4: if (src_mkl_shape.IsMklTensor()) { layout_type = MKL_TENSOR_FORMAT_NHWC; } else { layout_type = MKL_TENSOR_FORMAT_NCHW; } break; case 5: if (src_mkl_shape.IsMklTensor()) { layout_type = MKL_TENSOR_FORMAT_NDHWC; } else { layout_type = MKL_TENSOR_FORMAT_NCDHW; } break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // If input is in MKL layout, then simply get the format from input; // otherwise, use TF layout defined before. auto src_fmt = src_mkl_shape.IsMklTensor() ? GET_FORMAT_FROM_SHAPE(src_mkl_shape) : layout_type; // Get a softmax fwd primitive from primitive pool. MklSoftmaxParams fwdParams(src_dims, src_fmt, axis); MklSoftmaxPrimitive<T>* softmax_fwd = MklSoftmaxPrimitiveFactory<T>::Get(fwdParams); // Prepare for creating output tensor. Tensor* output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. auto dst_pd = softmax_fwd->GetSoftmaxFwdPd()->PRIMITIVE_DESC_DST; // If input is MKL shape, output is also MKL shape. // If input is TF shape, output is also TF shape. if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(src_dims.size(), src_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(src_dims); } // Allocate output tensor. AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); const T* src_data = src_tensor.flat<T>().data(); T* dst_data = reinterpret_cast<T*>(output_tensor->flat<T>().data()); // Execute softmax primitive. softmax_fwd->Execute(src_data, dst_data); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER( \ Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); TF_CALL_bfloat16(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL <commit_msg>Used the refactored method and fixed the typo in the comment<commit_after>/* Copyright 2015 The TensorFlow Authors. 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. ==============================================================================*/ // See docs in ../ops/nn_ops.cc. #ifdef INTEL_MKL #include "mkldnn.hpp" #include "tensorflow/core/framework/numeric_op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/util/mkl_types.h" #include "tensorflow/core/util/mkl_util.h" #include "tensorflow/core/util/tensor_format.h" #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" using mkldnn::prop_kind; using mkldnn::softmax_forward; using mkldnn::stream; namespace tensorflow { class MklSoftmaxParams { public: memory::dims src_dims; MKL_TENSOR_FORMAT src_fmt; int axis; MklSoftmaxParams(memory::dims src_dims, MKL_TENSOR_FORMAT src_fmt, int axis) : src_dims(src_dims), src_fmt(src_fmt), axis(axis) {} }; template <typename T> class MklSoftmaxPrimitive : public MklPrimitive { public: explicit MklSoftmaxPrimitive(const MklSoftmaxParams& fwdParams) : cpu_engine_(ENGINE_CPU, 0) { context_.fwd_stream.reset(new CPU_STREAM(cpu_engine_)); Setup(fwdParams); } ~MklSoftmaxPrimitive() {} // Softmax forward execute // src_data: input data buffer of src // dst_data: output data buffer of dst void Execute(const T* src_data, T* dst_data) { context_.src_mem->set_data_handle( static_cast<void*>(const_cast<T*>(src_data))); context_.dst_mem->set_data_handle(static_cast<void*>(dst_data)); #ifdef ENABLE_MKLDNN_V1 execute_primitives(context_.fwd_primitives, context_.fwd_stream, context_.net_args); #else context_.fwd_stream->submit(context_.fwd_primitives); #endif // After execution, set data handle back. context_.src_mem->set_data_handle(DummyData); context_.dst_mem->set_data_handle(DummyData); } std::shared_ptr<mkldnn::softmax_forward::primitive_desc> GetSoftmaxFwdPd() { return context_.fwd_pd; } private: struct SoftmaxFwdContext { // MKL-DNN memory. std::shared_ptr<memory> src_mem; std::shared_ptr<memory> dst_mem; // Primitive descriptor. std::shared_ptr<mkldnn::softmax_forward::desc> fwd_desc; // Memory descriptor. std::shared_ptr<memory::desc> src_md; // Softmax primitive. std::shared_ptr<mkldnn::softmax_forward::primitive_desc> fwd_pd; std::shared_ptr<mkldnn::primitive> softmax_fwd; std::shared_ptr<stream> fwd_stream; std::vector<mkldnn::primitive> fwd_primitives; std::vector<MemoryArgsMap> fwd_net_args; SoftmaxFwdContext() : src_mem(nullptr), dst_mem(nullptr), fwd_desc(nullptr), src_md(nullptr), fwd_pd(nullptr), softmax_fwd(nullptr), fwd_stream(nullptr) {} }; // Softmax forward primitive setup void Setup(const MklSoftmaxParams& fwdParams) { // Create memory descriptors for softmax data with specified format. auto src_format = GET_TENSOR_FORMAT(fwdParams.src_fmt); context_.src_md.reset( new memory::desc({fwdParams.src_dims}, MklDnnType<T>(), src_format)); // Create softmax descriptor and primitive descriptor. context_.fwd_desc.reset(new mkldnn::softmax_forward::desc( prop_kind::forward_scoring, *context_.src_md, fwdParams.axis)); context_.fwd_pd.reset(new mkldnn::softmax_forward::primitive_desc( *context_.fwd_desc, cpu_engine_)); // Create memory primitive based on dummy data. context_.src_mem.reset(new MEMORY_CONSTRUCTOR_USING_MD( *context_.src_md, cpu_engine_, DummyData)); context_.dst_mem.reset(new MEMORY_CONSTRUCTOR_PD( context_.fwd_pd.get()->PRIMITIVE_DESC_DST, cpu_engine_, DummyData)); #ifdef ENABLE_MKLDNN_V1 // Create softmax primitive and add it to net context_.softmax_fwd.reset(new mkldnn::softmax_forward(*context_.fwd_pd)); context_.fwd_net_args.push_back({{MKLDNN_ARG_SRC, *context_.src_mem}, { MKLDNN_ARG_DST, *context_.dst_mem }}); #else context_.softmax_fwd.reset(new mkldnn::softmax_forward( *context_.fwd_pd, *context_.src_mem, *context_.dst_mem)); #endif // ENABLE_MKLDNN_V1 context_.fwd_primitives.push_back(*context_.softmax_fwd); } struct SoftmaxFwdContext context_; engine cpu_engine_; }; template <typename T> class MklSoftmaxPrimitiveFactory : public MklPrimitiveFactory<T> { public: static MklSoftmaxPrimitive<T>* Get(const MklSoftmaxParams& fwdParams) { // Get a softmax fwd primitive from the cached pool. MklSoftmaxPrimitive<T>* softmax_forward = static_cast<MklSoftmaxPrimitive<T>*>( MklSoftmaxPrimitiveFactory<T>::GetInstance().GetSoftmaxFwd( fwdParams)); if (softmax_forward == nullptr) { softmax_forward = new MklSoftmaxPrimitive<T>(fwdParams); MklSoftmaxPrimitiveFactory<T>::GetInstance().SetSoftmaxFwd( fwdParams, softmax_forward); } return softmax_forward; } static MklSoftmaxPrimitiveFactory& GetInstance() { static MklSoftmaxPrimitiveFactory instance_; return instance_; } private: MklSoftmaxPrimitiveFactory() {} ~MklSoftmaxPrimitiveFactory() {} static string CreateKey(const MklSoftmaxParams& fwdParams) { string prefix = "softmax_fwd"; FactoryKeyCreator key_creator; key_creator.AddAsKey(prefix); key_creator.AddAsKey(fwdParams.src_dims); key_creator.AddAsKey<int>(static_cast<int>(fwdParams.src_fmt)); key_creator.AddAsKey<int>(fwdParams.axis); return key_creator.GetKey(); } MklPrimitive* GetSoftmaxFwd(const MklSoftmaxParams& fwdParams) { string key = CreateKey(fwdParams); return this->GetOp(key); } void SetSoftmaxFwd(const MklSoftmaxParams& fwdParams, MklPrimitive* op) { string key = CreateKey(fwdParams); this->SetOp(key, op); } }; typedef Eigen::ThreadPoolDevice CPUDevice; template <typename Device, typename T> class MklSoftmaxOp : public OpKernel { public: ~MklSoftmaxOp() {} explicit MklSoftmaxOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { try { auto cpu_engine = engine(ENGINE_CPU, 0); // src_tensor points to the 0-th input of global data struct "context". size_t src_idx = 0; const Tensor& src_tensor = MklGetInput(context, src_idx); MklDnnShape src_mkl_shape; GetMklShape(context, src_idx, &src_mkl_shape); // src_dims is the dimension of src_tensor. // Dim of the dst will also be same as src_dims. auto src_tf_shape = src_mkl_shape.IsMklTensor() ? src_mkl_shape.GetTfShape() : src_tensor.shape(); const int input_dims = src_tf_shape.dims(); memory::dims src_dims; int axis; if (src_mkl_shape.IsMklTensor()) { src_dims = src_mkl_shape.GetSizesAsMklDnnDims(); axis = 1; } else { src_dims = TFShapeToMklDnnDims(src_tf_shape); axis = input_dims - 1; } MKL_TENSOR_FORMAT layout_type; // In MKL, data format passed to mkl softmax op depends on dimension of // the input tensor. Here "x" data format in MKL is used for 1 dim tensor, // "nc" for 2 dim tensor, "tnc" for 3 dim tensor, "nchw" for 4 dim tensor, // and "ncdhw" for 5 dim tensor. Each of the symbols has the following // meaning: n = batch, c = channels, t = sequence length, h = height, w = // width, d = depth. When src tensor is MKL, layout_type here is only used // for setting TF layout type of output tensor. When input is TF Tensor, // layout here is no special sense. We use axis to define on which // dimension to do softmax. switch (input_dims) { case 1: layout_type = MKL_TENSOR_FORMAT_X; break; case 2: layout_type = MKL_TENSOR_FORMAT_NC; break; case 3: layout_type = MKL_TENSOR_FORMAT_TNC; break; case 4: if (src_mkl_shape.IsMklTensor()) { layout_type = MKL_TENSOR_FORMAT_NHWC; } else { layout_type = MKL_TENSOR_FORMAT_NCHW; } break; case 5: if (src_mkl_shape.IsMklTensor()) { layout_type = MKL_TENSOR_FORMAT_NDHWC; } else { layout_type = MKL_TENSOR_FORMAT_NCDHW; } break; default: OP_REQUIRES_OK(context, errors::Aborted("Input dims must be <= 5 and >=1")); return; } // If input is in MKL layout, then simply get the format from input; // otherwise, use TF layout defined before. auto src_fmt = src_mkl_shape.IsMklTensor() ? GET_FORMAT_FROM_SHAPE(src_mkl_shape) : layout_type; // Get a softmax fwd primitive from primitive pool. MklSoftmaxParams fwdParams(src_dims, src_fmt, axis); MklSoftmaxPrimitive<T>* softmax_fwd = MklSoftmaxPrimitiveFactory<T>::Get(fwdParams); // Prepare for creating output tensor. Tensor* output_tensor = nullptr; MklDnnShape output_mkl_shape; TensorShape output_tf_shape; // shape of output TF tensor. auto dst_pd = softmax_fwd->GetSoftmaxFwdPd()->PRIMITIVE_DESC_DST; // If input is MKL shape, output is also MKL shape. // If input is TF shape, output is also TF shape. if (src_mkl_shape.IsMklTensor()) { output_mkl_shape.SetMklTensor(true); output_mkl_shape.SetMklLayout(&dst_pd); output_mkl_shape.SetElemType(MklDnnType<T>()); output_mkl_shape.SetTfLayout(src_dims.size(), src_dims, layout_type); output_tf_shape.AddDim((dst_pd.get_size() / sizeof(T))); } else { output_mkl_shape.SetMklTensor(false); output_tf_shape = MklDnnDimsToTFShape(src_dims); } // Allocate output tensor. AllocateOutputSetMklShape(context, 0, &output_tensor, output_tf_shape, output_mkl_shape); const T* src_data = src_tensor.flat<T>().data(); T* dst_data = reinterpret_cast<T*>(output_tensor->flat<T>().data()); // Execute softmax primitive. softmax_fwd->Execute(src_data, dst_data); } catch (mkldnn::error& e) { string error_msg = "Status: " + std::to_string(e.status) + ", message: " + string(e.message) + ", in file " + string(__FILE__) + ":" + std::to_string(__LINE__); OP_REQUIRES_OK( context, errors::Aborted("Operation received an exception:", error_msg)); } } }; /* Register DNN kernels for supported operations and supported types - right now * it is only Softmax and f32 */ #define REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES(type) \ REGISTER_KERNEL_BUILDER( \ Name("_MklSoftmax") \ .Device(DEVICE_CPU) \ .TypeConstraint<type>("T") \ .Label(mkl_op_registry::kMklLayoutDependentOpLabel), \ MklSoftmaxOp<CPUDevice, type>); TF_CALL_float(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); TF_CALL_bfloat16(REGISTER_SOFTMAX_MKL_SUPPORTED_KERNELS_TYPES); } // namespace tensorflow #endif // INTEL_MKL <|endoftext|>
<commit_before>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "xmlstream.h" #include <stack> #include <libxml/parser.h> using namespace std; class SimpleNodeParser { int depth; stack<SimpleNode*> nodes; xmlSAXHandler handler; static void charactersSAXFunc(void* ctx, const xmlChar * ch, int len); static void errorSAXFunc(void* /*ctx*/, const char * /*msg*/, ...) {} static void startElementSAXFunc(void * ctx, const xmlChar * name, const xmlChar ** atts); static void endElementSAXFunc(void * ctx, const xmlChar * name); public: SimpleNodeParser() { memset(&handler, 0, sizeof(xmlSAXHandler)); handler.characters = charactersSAXFunc; handler.error = errorSAXFunc; handler.startElement = startElementSAXFunc; handler.endElement = endElementSAXFunc; } ~SimpleNodeParser() { } void parse(const string& xml, SimpleNode& node); }; void SimpleNodeParser::parse(const string& xml, SimpleNode& node) { depth = 0; nodes.push(&node); if (xmlSAXUserParseMemory(&handler, this, xml.c_str(), xml.length())) { printf("parsing error: %s\n", ""); // handle the error unless it is a tag mismatch in html // errorstring = XML_ErrorString(e); // error = stop = true; // wellformed = false; } } void SimpleNodeParser::charactersSAXFunc(void* ctx, const xmlChar* ch, int len) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); p->nodes.top()->text.append((const char*)ch, len); } void SimpleNodeParser::startElementSAXFunc(void* ctx, const xmlChar* name, const xmlChar** atts) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); SimpleNode* node = p->nodes.top(); //printf("%s %i\n", name, node->nodes.size()); // if this is not the root node, add it to the stack and to the parent node if (p->depth > 0) { SimpleNode emptynode; SimpleNode* prev = 0; if (!node->nodes.empty()) { prev = &node->nodes.back(); } node->nodes.push_back(emptynode); SimpleNode* cnode = &*(node->nodes.rbegin()); cnode->parent = node; if (prev) { prev->next = cnode; } node = cnode; p->nodes.push(node); } node->tagname = (const char*)name; while (*atts) { node->atts[(const char*)*atts] = (const char*)*(atts+1); atts += 2; } p->depth++; } void SimpleNodeParser::endElementSAXFunc(void* ctx, const xmlChar* name) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); p->nodes.pop(); p->depth--; } SimpleNode::SimpleNode(const string& xml) :parent(0), next(0) { SimpleNodeParser parser; parser.parse(xml, *this); } <commit_msg>fixed SimpleNodeParser null pointer error<commit_after>/* This file is part of Strigi Desktop Search * * Copyright (C) 2006 Jos van den Oever <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "xmlstream.h" #include <stack> #include <libxml/parser.h> using namespace std; class SimpleNodeParser { int depth; stack<SimpleNode*> nodes; xmlSAXHandler handler; static void charactersSAXFunc(void* ctx, const xmlChar * ch, int len); static void errorSAXFunc(void* /*ctx*/, const char * /*msg*/, ...) {} static void startElementSAXFunc(void * ctx, const xmlChar * name, const xmlChar ** atts); static void endElementSAXFunc(void * ctx, const xmlChar * name); public: SimpleNodeParser() { memset(&handler, 0, sizeof(xmlSAXHandler)); handler.characters = charactersSAXFunc; handler.error = errorSAXFunc; handler.startElement = startElementSAXFunc; handler.endElement = endElementSAXFunc; } ~SimpleNodeParser() { } void parse(const string& xml, SimpleNode& node); }; void SimpleNodeParser::parse(const string& xml, SimpleNode& node) { depth = 0; nodes.push(&node); if (xmlSAXUserParseMemory(&handler, this, xml.c_str(), xml.length())) { printf("parsing error: %s\n", ""); // handle the error unless it is a tag mismatch in html // errorstring = XML_ErrorString(e); // error = stop = true; // wellformed = false; } } void SimpleNodeParser::charactersSAXFunc(void* ctx, const xmlChar* ch, int len) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); p->nodes.top()->text.append((const char*)ch, len); } void SimpleNodeParser::startElementSAXFunc(void* ctx, const xmlChar* name, const xmlChar** atts) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); SimpleNode* node = p->nodes.top(); //printf("%s %i\n", name, node->nodes.size()); // if this is not the root node, add it to the stack and to the parent node if (p->depth > 0) { SimpleNode emptynode; SimpleNode* prev = 0; if (!node->nodes.empty()) { prev = &node->nodes.back(); } node->nodes.push_back(emptynode); SimpleNode* cnode = &*(node->nodes.rbegin()); cnode->parent = node; if (prev) { prev->next = cnode; } node = cnode; p->nodes.push(node); } node->tagname = (const char*)name; while ((atts != NULL) && (*atts)) { node->atts[(const char*)*atts] = (const char*)*(atts+1); atts += 2; } p->depth++; } void SimpleNodeParser::endElementSAXFunc(void* ctx, const xmlChar* name) { SimpleNodeParser* p = static_cast<SimpleNodeParser*>(ctx); p->nodes.pop(); p->depth--; } SimpleNode::SimpleNode(const string& xml) :parent(0), next(0) { SimpleNodeParser parser; parser.parse(xml, *this); } <|endoftext|>
<commit_before>/* Copyright 2018 The TensorFlow Authors. 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 "tensorflow/lite/micro/all_ops_resolver.h" #include "tensorflow/lite/micro/kernels/micro_ops.h" namespace tflite { AllOpsResolver::AllOpsResolver() { // Please keep this list of Builtin Operators in alphabetical order. AddAbs(); AddAdd(); AddAddN(); AddArgMax(); AddArgMin(); AddAveragePool2D(); AddBatchToSpaceNd(); AddCeil(); AddConcatenation(); AddConv2D(); AddCos(); AddCumSum(); AddDepthToSpace(); AddDepthwiseConv2D(); AddDequantize(); AddDetectionPostprocess(); AddElu(); AddEqual(); AddEthosU(); AddFloor(); AddFloorDiv(); AddFloorMod(); AddFullyConnected(); AddGreater(); AddGreaterEqual(); AddHardSwish(); AddL2Normalization(); AddL2Pool2D(); AddLeakyRelu(); AddLess(); AddLessEqual(); AddLog(); AddLogicalAnd(); AddLogicalNot(); AddLogicalOr(); AddLogistic(); AddMaxPool2D(); AddMaximum(); AddMean(); AddMinimum(); AddMul(); AddNeg(); AddNotEqual(); AddPack(); AddPad(); AddPadV2(); AddPrelu(); AddQuantize(); AddReduceMax(); AddRelu(); AddRelu6(); AddReshape(); AddResizeBilinear(); AddResizeNearestNeighbor(); AddRound(); AddRsqrt(); AddShape(); AddSin(); AddSoftmax(); AddSpaceToBatchNd(); AddSpaceToDepth(); AddSplit(); AddSplitV(); AddSqrt(); AddSquare(); AddSqueeze(); AddStridedSlice(); AddSub(); AddSvdf(); AddTanh(); AddTransposeConv(); AddTranspose(); AddUnpack(); } } // namespace tflite <commit_msg>Add Expand Dims to AllOpsResolver. (#259)<commit_after>/* Copyright 2018 The TensorFlow Authors. 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 "tensorflow/lite/micro/all_ops_resolver.h" #include "tensorflow/lite/micro/kernels/micro_ops.h" namespace tflite { AllOpsResolver::AllOpsResolver() { // Please keep this list of Builtin Operators in alphabetical order. AddAbs(); AddAdd(); AddAddN(); AddArgMax(); AddArgMin(); AddAveragePool2D(); AddBatchToSpaceNd(); AddCeil(); AddConcatenation(); AddConv2D(); AddCos(); AddCumSum(); AddDepthToSpace(); AddDepthwiseConv2D(); AddDequantize(); AddDetectionPostprocess(); AddElu(); AddEqual(); AddEthosU(); AddExpandDims(); AddFloor(); AddFloorDiv(); AddFloorMod(); AddFullyConnected(); AddGreater(); AddGreaterEqual(); AddHardSwish(); AddL2Normalization(); AddL2Pool2D(); AddLeakyRelu(); AddLess(); AddLessEqual(); AddLog(); AddLogicalAnd(); AddLogicalNot(); AddLogicalOr(); AddLogistic(); AddMaxPool2D(); AddMaximum(); AddMean(); AddMinimum(); AddMul(); AddNeg(); AddNotEqual(); AddPack(); AddPad(); AddPadV2(); AddPrelu(); AddQuantize(); AddReduceMax(); AddRelu(); AddRelu6(); AddReshape(); AddResizeBilinear(); AddResizeNearestNeighbor(); AddRound(); AddRsqrt(); AddShape(); AddSin(); AddSoftmax(); AddSpaceToBatchNd(); AddSpaceToDepth(); AddSplit(); AddSplitV(); AddSqrt(); AddSquare(); AddSqueeze(); AddStridedSlice(); AddSub(); AddSvdf(); AddTanh(); AddTransposeConv(); AddTranspose(); AddUnpack(); } } // namespace tflite <|endoftext|>
<commit_before>#include <itomp_cio_planner/visualization/new_viz_manager.h> #include <itomp_cio_planner/util/planning_parameters.h> #include <itomp_cio_planner/contact/ground_manager.h> #include <ros/node_handle.h> #include <boost/lexical_cast.hpp> using namespace std; namespace itomp_cio_planner { NewVizManager::NewVizManager() { } NewVizManager::~NewVizManager() { } void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model) { ros::NodeHandle node_handle; vis_marker_array_publisher_ = node_handle.advertise< visualization_msgs::MarkerArray>( "itomp_planner/visualization_marker_array", 10); vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>( "itomp_planner/visualization_marker", 10); robot_model_ = robot_model; reference_frame_ = robot_model->getReferenceFrame(); colors_.resize(8); for (int i = 0; i < 8; ++i) { colors_[i].a = 1.0; colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0; colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0; colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0; } } void NewVizManager::setPlanningGroup( const ItompPlanningGroupConstPtr& planning_group) { planning_group_ = planning_group; const multimap<string, string>& endeffector_names = PlanningParameters::getInstance()->getAnimateEndeffectorSegment(); std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> ret = endeffector_names.equal_range(planning_group_->name_); endeffector_rbdl_indices_.clear(); for (multimap<string, string>::const_iterator it = ret.first; it != ret.second; ++it) { string endeffector_name = it->second; unsigned int rbdl_link_index = robot_model_->getRBDLRobotModel().GetBodyId( endeffector_name.c_str()); endeffector_rbdl_indices_.push_back(rbdl_link_index); } } void NewVizManager::renderOneTime() { //renderGround(); //renderEnvironment(); // rendered in move_itomp } void NewVizManager::renderEnvironment() { string environment_file = PlanningParameters::getInstance()->getEnvironmentModel(); if (environment_file.empty()) return; vector<double> environment_position = PlanningParameters::getInstance()->getEnvironmentModelPosition(); double scale = PlanningParameters::getInstance()->getEnvironmentModelScale(); environment_position.resize(3, 0); visualization_msgs::MarkerArray ma; visualization_msgs::Marker msg; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = "environment"; msg.type = visualization_msgs::Marker::MESH_RESOURCE; msg.action = visualization_msgs::Marker::ADD; msg.scale.x = scale; msg.scale.y = scale; msg.scale.z = scale; msg.id = 0; msg.pose.position.x = environment_position[0]; msg.pose.position.y = environment_position[1]; msg.pose.position.z = environment_position[2]; /* msg.pose.orientation.x = sqrt(0.5); msg.pose.orientation.y = 0.0; msg.pose.orientation.z = 0.0; msg.pose.orientation.w = sqrt(0.5); */ msg.pose.orientation.x = 0.0; msg.pose.orientation.y = 0.0; msg.pose.orientation.z = 0.0; msg.pose.orientation.w = 1.0; msg.color.a = 1.0; msg.color.r = 0.5; msg.color.g = 0.5; msg.color.b = 0.5; msg.mesh_resource = environment_file; ma.markers.push_back(msg); vis_marker_array_publisher_.publish(ma); } void NewVizManager::renderGround() { } void NewVizManager::animateEndeffectors( const FullTrajectoryConstPtr& full_trajectory, const std::vector<RigidBodyDynamics::Model>& models, bool is_best) { const double scale_keyframe = 0.03; const double scale_line = 0.01; geometry_msgs::Point point; visualization_msgs::Marker msg; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = is_best ? "itomp_best_ee" : "itomp_ee"; msg.action = visualization_msgs::Marker::ADD; msg.pose.orientation.w = 1.0; // render keyframe endeffectors msg.type = visualization_msgs::Marker::SPHERE_LIST; msg.scale.x = scale_keyframe; msg.scale.y = scale_keyframe; msg.scale.z = scale_keyframe; msg.points.resize(0); msg.color = is_best ? colors_[GREEN] : colors_[BLUE]; msg.id = 0; for (int i = full_trajectory->getKeyframeStartIndex(); i < full_trajectory->getNumPoints(); i += full_trajectory->getNumKeyframeIntervalPoints()) { for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j) { int rbdl_index = endeffector_rbdl_indices_[j]; Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r; point.x = endeffector_pos(0); point.y = endeffector_pos(1); point.z = endeffector_pos(2); msg.points.push_back(point); } } vis_marker_publisher_.publish(msg); // render endeffector path msg.type = visualization_msgs::Marker::LINE_STRIP; msg.scale.x = scale_line; msg.scale.y = scale_line; msg.scale.z = scale_line; msg.color = is_best ? colors_[GREEN] : colors_[BLUE]; for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j) { ++msg.id; msg.points.resize(0); int rbdl_index = endeffector_rbdl_indices_[j]; for (int i = 0; i < full_trajectory->getNumPoints(); ++i) { Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r; point.x = endeffector_pos(0); point.y = endeffector_pos(1); point.z = endeffector_pos(2); msg.points.push_back(point); } vis_marker_publisher_.publish(msg); } } void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory, robot_state::RobotStatePtr& robot_state, bool is_best) { if (!is_best) return; geometry_msgs::Point point; visualization_msgs::MarkerArray ma; std::vector<std::string> link_names = robot_model_->getMoveitRobotModel()->getLinkModelNames(); std_msgs::ColorRGBA color = colors_[WHITE]; color.a = 0.1; ros::Duration dur(100.0); for (int point = full_trajectory->getKeyframeStartIndex(); point < full_trajectory->getNumPoints(); point += full_trajectory->getNumKeyframeIntervalPoints()) { ma.markers.clear(); const Eigen::MatrixXd mat = full_trajectory->getTrajectory( Trajectory::TRAJECTORY_TYPE_POSITION).row(point); robot_state->setVariablePositions(mat.data()); std::string ns = "kf_" + boost::lexical_cast<std::string>(point); robot_state->getRobotMarkers(ma, link_names, color, ns, dur); vis_marker_array_publisher_.publish(ma); } } void NewVizManager::animateContactForces( const FullTrajectoryConstPtr& full_trajectory, bool is_best) { const double scale_line = 0.01; const double scale_keyframe = 0.03; geometry_msgs::Point point_from, point_to; const Eigen::MatrixXd& contact_positions = full_trajectory->getComponentTrajectory( FullTrajectory::TRAJECTORY_COMPONENT_CONTACT_POSITION); const Eigen::MatrixXd& contact_forces = full_trajectory->getComponentTrajectory( FullTrajectory::TRAJECTORY_COMPONENT_CONTACT_FORCE); int num_contacts = contact_positions.cols() / 3; visualization_msgs::Marker msg, msg2; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = is_best ? "itomp_best_cf" : "itomp_cf"; msg.action = visualization_msgs::Marker::ADD; msg.pose.orientation.w = 1.0; msg.type = visualization_msgs::Marker::LINE_LIST; msg.scale.x = scale_line; msg.scale.y = scale_line; msg.scale.z = scale_line; msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA]; msg.id = 0; msg.points.resize(0); msg2 = msg; msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp"; msg2.type = visualization_msgs::Marker::SPHERE_LIST; msg2.scale.x = scale_keyframe; msg2.scale.y = scale_keyframe; msg2.scale.z = scale_keyframe; for (int point = full_trajectory->getKeyframeStartIndex(); point < full_trajectory->getNumPoints(); point += full_trajectory->getNumKeyframeIntervalPoints()) { for (int contact_index = 0; contact_index < num_contacts * 3; contact_index += 3) { Eigen::Vector3d p = contact_positions.block(point, contact_index, 1, 3).transpose(); Eigen::Vector3d contact_pos, contact_normal; GroundManager::getInstance()->getNearestGroundPosition(p, contact_pos, contact_normal); point_from.x = contact_pos(0); point_from.y = contact_pos(1); point_from.z = contact_pos(2); point_to.x = contact_forces(point, contact_index) * 0.001 + point_from.x; point_to.y = contact_forces(point, contact_index + 1) * 0.001 + point_from.y; point_to.z = contact_forces(point, contact_index + 2) * 0.001 + point_from.z; msg.points.push_back(point_from); msg.points.push_back(point_to); msg2.points.push_back(point_from); } } vis_marker_publisher_.publish(msg); vis_marker_publisher_.publish(msg2); } } <commit_msg>contact position formulation changed<commit_after>#include <itomp_cio_planner/visualization/new_viz_manager.h> #include <itomp_cio_planner/util/planning_parameters.h> #include <itomp_cio_planner/contact/ground_manager.h> #include <ros/node_handle.h> #include <boost/lexical_cast.hpp> using namespace std; namespace itomp_cio_planner { NewVizManager::NewVizManager() { } NewVizManager::~NewVizManager() { } void NewVizManager::initialize(const ItompRobotModelConstPtr& robot_model) { ros::NodeHandle node_handle; vis_marker_array_publisher_ = node_handle.advertise< visualization_msgs::MarkerArray>( "itomp_planner/visualization_marker_array", 10); vis_marker_publisher_ = node_handle.advertise<visualization_msgs::Marker>( "itomp_planner/visualization_marker", 10); robot_model_ = robot_model; reference_frame_ = robot_model->getReferenceFrame(); colors_.resize(8); for (int i = 0; i < 8; ++i) { colors_[i].a = 1.0; colors_[i].b = (i % 2 == 0) ? 0.0 : 1.0; colors_[i].g = ((i / 2) % 2 == 0) ? 0.0 : 1.0; colors_[i].r = ((i / 4) % 2 == 0) ? 0.0 : 1.0; } } void NewVizManager::setPlanningGroup( const ItompPlanningGroupConstPtr& planning_group) { planning_group_ = planning_group; const multimap<string, string>& endeffector_names = PlanningParameters::getInstance()->getAnimateEndeffectorSegment(); std::pair<multimap<string, string>::const_iterator, multimap<string, string>::const_iterator> ret = endeffector_names.equal_range(planning_group_->name_); endeffector_rbdl_indices_.clear(); for (multimap<string, string>::const_iterator it = ret.first; it != ret.second; ++it) { string endeffector_name = it->second; unsigned int rbdl_link_index = robot_model_->getRBDLRobotModel().GetBodyId( endeffector_name.c_str()); endeffector_rbdl_indices_.push_back(rbdl_link_index); } } void NewVizManager::renderOneTime() { //renderGround(); //renderEnvironment(); // rendered in move_itomp } void NewVizManager::renderEnvironment() { string environment_file = PlanningParameters::getInstance()->getEnvironmentModel(); if (environment_file.empty()) return; vector<double> environment_position = PlanningParameters::getInstance()->getEnvironmentModelPosition(); double scale = PlanningParameters::getInstance()->getEnvironmentModelScale(); environment_position.resize(3, 0); visualization_msgs::MarkerArray ma; visualization_msgs::Marker msg; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = "environment"; msg.type = visualization_msgs::Marker::MESH_RESOURCE; msg.action = visualization_msgs::Marker::ADD; msg.scale.x = scale; msg.scale.y = scale; msg.scale.z = scale; msg.id = 0; msg.pose.position.x = environment_position[0]; msg.pose.position.y = environment_position[1]; msg.pose.position.z = environment_position[2]; /* msg.pose.orientation.x = sqrt(0.5); msg.pose.orientation.y = 0.0; msg.pose.orientation.z = 0.0; msg.pose.orientation.w = sqrt(0.5); */ msg.pose.orientation.x = 0.0; msg.pose.orientation.y = 0.0; msg.pose.orientation.z = 0.0; msg.pose.orientation.w = 1.0; msg.color.a = 1.0; msg.color.r = 0.5; msg.color.g = 0.5; msg.color.b = 0.5; msg.mesh_resource = environment_file; ma.markers.push_back(msg); vis_marker_array_publisher_.publish(ma); } void NewVizManager::renderGround() { } void NewVizManager::animateEndeffectors( const FullTrajectoryConstPtr& full_trajectory, const std::vector<RigidBodyDynamics::Model>& models, bool is_best) { const double scale_keyframe = 0.03; const double scale_line = 0.01; geometry_msgs::Point point; visualization_msgs::Marker msg; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = is_best ? "itomp_best_ee" : "itomp_ee"; msg.action = visualization_msgs::Marker::ADD; msg.pose.orientation.w = 1.0; // render keyframe endeffectors msg.type = visualization_msgs::Marker::SPHERE_LIST; msg.scale.x = scale_keyframe; msg.scale.y = scale_keyframe; msg.scale.z = scale_keyframe; msg.points.resize(0); msg.color = is_best ? colors_[GREEN] : colors_[BLUE]; msg.id = 0; for (int i = full_trajectory->getKeyframeStartIndex(); i < full_trajectory->getNumPoints(); i += full_trajectory->getNumKeyframeIntervalPoints()) { for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j) { int rbdl_index = endeffector_rbdl_indices_[j]; Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r; point.x = endeffector_pos(0); point.y = endeffector_pos(1); point.z = endeffector_pos(2); msg.points.push_back(point); } } vis_marker_publisher_.publish(msg); // render endeffector path msg.type = visualization_msgs::Marker::LINE_STRIP; msg.scale.x = scale_line; msg.scale.y = scale_line; msg.scale.z = scale_line; msg.color = is_best ? colors_[GREEN] : colors_[BLUE]; for (int j = 0; j < endeffector_rbdl_indices_.size(); ++j) { ++msg.id; msg.points.resize(0); int rbdl_index = endeffector_rbdl_indices_[j]; for (int i = 0; i < full_trajectory->getNumPoints(); ++i) { Eigen::Vector3d endeffector_pos = models[i].X_base[rbdl_index].r; point.x = endeffector_pos(0); point.y = endeffector_pos(1); point.z = endeffector_pos(2); msg.points.push_back(point); } vis_marker_publisher_.publish(msg); } } void NewVizManager::animatePath(const FullTrajectoryConstPtr& full_trajectory, robot_state::RobotStatePtr& robot_state, bool is_best) { if (!is_best) return; geometry_msgs::Point point; visualization_msgs::MarkerArray ma; std::vector<std::string> link_names = robot_model_->getMoveitRobotModel()->getLinkModelNames(); std_msgs::ColorRGBA color = colors_[WHITE]; color.a = 0.1; ros::Duration dur(100.0); for (int point = full_trajectory->getKeyframeStartIndex(); point < full_trajectory->getNumPoints(); point += full_trajectory->getNumKeyframeIntervalPoints()) { ma.markers.clear(); const Eigen::MatrixXd mat = full_trajectory->getTrajectory( Trajectory::TRAJECTORY_TYPE_POSITION).row(point); robot_state->setVariablePositions(mat.data()); std::string ns = "kf_" + boost::lexical_cast<std::string>(point); robot_state->getRobotMarkers(ma, link_names, color, ns, dur); vis_marker_array_publisher_.publish(ma); } } void NewVizManager::animateContactForces( const FullTrajectoryConstPtr& full_trajectory, bool is_best) { const double scale_line = 0.01; const double scale_keyframe = 0.03; geometry_msgs::Point point_from, point_to; visualization_msgs::Marker msg, msg2; msg.header.frame_id = reference_frame_; msg.header.stamp = ros::Time::now(); msg.ns = is_best ? "itomp_best_cf" : "itomp_cf"; msg.action = visualization_msgs::Marker::ADD; msg.pose.orientation.w = 1.0; msg.type = visualization_msgs::Marker::LINE_LIST; msg.scale.x = scale_line; msg.scale.y = scale_line; msg.scale.z = scale_line; msg.color = is_best ? colors_[YELLOW] : colors_[MAGENTA]; msg.id = 0; msg.points.resize(0); msg2 = msg; msg2.ns = is_best ? "itomp_best_cp" : "itomp_cp"; msg2.type = visualization_msgs::Marker::SPHERE_LIST; msg2.scale.x = scale_keyframe; msg2.scale.y = scale_keyframe; msg2.scale.z = scale_keyframe; for (int point = full_trajectory->getKeyframeStartIndex(); point < full_trajectory->getNumPoints(); point += full_trajectory->getNumKeyframeIntervalPoints()) { const Eigen::VectorXd& r = full_trajectory->getComponentTrajectory( FullTrajectory::TRAJECTORY_COMPONENT_CONTACT_POSITION, Trajectory::TRAJECTORY_TYPE_POSITION).row(point); const Eigen::VectorXd& f = full_trajectory->getComponentTrajectory( FullTrajectory::TRAJECTORY_COMPONENT_CONTACT_FORCE, Trajectory::TRAJECTORY_TYPE_POSITION).row(point); int num_contacts = r.rows() / 3; for (int i = 0; i < num_contacts; ++i) { Eigen::Vector3d contact_position; Eigen::Vector3d contact_normal; GroundManager::getInstance()->getNearestGroundPosition( r.block(3 * i, 0, 3, 1), contact_position, contact_normal); Eigen::Vector3d contact_force = f.block(3 * i, 0, 3, 1); // test int foot_index = i / 4 * 4; int ee_index = i % 4; contact_position = r.block(3 * foot_index, 0, 3, 1); contact_position(2) = 0; switch (ee_index) { case 0: contact_position(0) -= 0.05; contact_position(1) -= 0.05; break; case 1: contact_position(0) += 0.05; contact_position(1) -= 0.05; break; case 2: contact_position(0) += 0.05; contact_position(1) += 0.2; break; case 3: contact_position(0) -= 0.05; contact_position(1) += 0.2; break; } point_from.x = contact_position(0); point_from.y = contact_position(1); point_from.z = contact_position(2); point_to.x = contact_force(0) * 0.1 + point_from.x; point_to.y = contact_force(1) * 0.1 + point_from.y; point_to.z = contact_force(2) * 0.1 + point_from.z; msg.points.push_back(point_from); msg.points.push_back(point_to); msg2.points.push_back(point_from); } } vis_marker_publisher_.publish(msg); vis_marker_publisher_.publish(msg2); } } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** 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 ETH Zurich 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. ** ***********************************************************************************************************************/ #include "QueryBuilder.h" #include "../nodes/CommandNode.h" #include "../nodes/CompositeQueryNode.h" #include "../nodes/OperatorQueryNode.h" #include "../queries/CompositeQuery.h" #include "../queries/QueryRegistry.h" #include "../queries/UnionOperator.h" #include "../parsing/QueryParsingException.h" namespace InformationScripting { QueryBuilder::QueryBuilder(Model::Node* target, QueryExecutor* executor) : executor_{executor}, target_{target} {} void QueryBuilder::init() { addType<CommandNode>(visitCommand); addType<CompositeQueryNode>(visitList); addType<OperatorQueryNode>(visitOperator); } std::unique_ptr<Query> QueryBuilder::visitCommand(QueryBuilder* self, CommandNode* command) { auto text = command->name(); if (text.isEmpty()) throw QueryParsingException("Empty command is not allowed"); auto parts = text.split(" ", QString::SplitBehavior::SkipEmptyParts); auto cmd = parts.takeFirst(); if (auto q = QueryRegistry::instance().buildQuery(cmd, self->target_, parts, self->executor_)) return q; throw QueryParsingException(QString("%1 is not a valid command").arg(cmd)); } std::unique_ptr<Query> QueryBuilder::visitList(QueryBuilder* self, CompositeQueryNode* list) { auto composite = std::make_unique<CompositeQuery>(); for (int i = 0; i < list->queries()->size(); ++i) { auto query = composite->addQuery(self->visit(list->queries()->at(i))); composite->connectInput(i, query); composite->connectToOutput(query, i); } return std::unique_ptr<Query>(composite.release()); } std::unique_ptr<Query> QueryBuilder::visitOperator(QueryBuilder* self, OperatorQueryNode* op) { Q_ASSERT(op->op() == OperatorQueryNode::OperatorTypes::Pipe); auto composite = std::make_unique<CompositeQuery>(); auto left = composite->addQuery(self->visit(op->left())); auto leftComposite = dynamic_cast<CompositeQuery*>(left); auto right = composite->addQuery(self->visit(op->right())); auto rightComposite = dynamic_cast<CompositeQuery*>(right); if (leftComposite && rightComposite) { Q_ASSERT(leftComposite->outputCount() == rightComposite->inputCount()); for (int i = 0; i < leftComposite->outputCount(); ++i) composite->connectQuery(leftComposite, i, rightComposite, i); } else if (leftComposite) { // union connectQueriesWith(composite.get(), leftComposite, new UnionOperator(), right); } else if (rightComposite) { // split for (int i = 0; i < rightComposite->inputCount(); ++i) composite->connectQuery(left, 0, rightComposite, i); } else { composite->connectQuery(left, right); } int inputCount = leftComposite ? leftComposite->inputCount() : 1; int outputCount = rightComposite ? rightComposite->outputCount() : 1; for (int i = 0; i < inputCount; ++i) composite->connectInput(i, left, i); for (int o = 0; o < outputCount; ++o) composite->connectToOutput(right, o); return std::unique_ptr<Query>(composite.release()); } void QueryBuilder::connectQueriesWith(CompositeQuery* composite, CompositeQuery* queries, Query* connectionQuery, Query* outputQuery) { for (int i = 0; i < queries->outputCount(); ++i) composite->connectQuery(queries, i, connectionQuery, i); if (outputQuery) composite->connectQuery(connectionQuery, outputQuery); } } /* namespace InformationScripting */ <commit_msg>Fix: Make UnionQuery owned by the composite it belongs to<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2015 ETH Zurich ** All rights reserved. ** ** 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 ETH Zurich 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. ** ***********************************************************************************************************************/ #include "QueryBuilder.h" #include "../nodes/CommandNode.h" #include "../nodes/CompositeQueryNode.h" #include "../nodes/OperatorQueryNode.h" #include "../queries/CompositeQuery.h" #include "../queries/QueryRegistry.h" #include "../queries/UnionOperator.h" #include "../parsing/QueryParsingException.h" namespace InformationScripting { QueryBuilder::QueryBuilder(Model::Node* target, QueryExecutor* executor) : executor_{executor}, target_{target} {} void QueryBuilder::init() { addType<CommandNode>(visitCommand); addType<CompositeQueryNode>(visitList); addType<OperatorQueryNode>(visitOperator); } std::unique_ptr<Query> QueryBuilder::visitCommand(QueryBuilder* self, CommandNode* command) { auto text = command->name(); if (text.isEmpty()) throw QueryParsingException("Empty command is not allowed"); auto parts = text.split(" ", QString::SplitBehavior::SkipEmptyParts); auto cmd = parts.takeFirst(); if (auto q = QueryRegistry::instance().buildQuery(cmd, self->target_, parts, self->executor_)) return q; throw QueryParsingException(QString("%1 is not a valid command").arg(cmd)); } std::unique_ptr<Query> QueryBuilder::visitList(QueryBuilder* self, CompositeQueryNode* list) { auto composite = std::make_unique<CompositeQuery>(); for (int i = 0; i < list->queries()->size(); ++i) { auto query = composite->addQuery(self->visit(list->queries()->at(i))); composite->connectInput(i, query); composite->connectToOutput(query, i); } return std::unique_ptr<Query>(composite.release()); } std::unique_ptr<Query> QueryBuilder::visitOperator(QueryBuilder* self, OperatorQueryNode* op) { Q_ASSERT(op->op() == OperatorQueryNode::OperatorTypes::Pipe); auto composite = std::make_unique<CompositeQuery>(); auto left = composite->addQuery(self->visit(op->left())); auto leftComposite = dynamic_cast<CompositeQuery*>(left); auto right = composite->addQuery(self->visit(op->right())); auto rightComposite = dynamic_cast<CompositeQuery*>(right); if (leftComposite && rightComposite) { Q_ASSERT(leftComposite->outputCount() == rightComposite->inputCount()); for (int i = 0; i < leftComposite->outputCount(); ++i) composite->connectQuery(leftComposite, i, rightComposite, i); } else if (leftComposite) { // union auto unionQuery = composite->addQuery(std::unique_ptr<Query>(new UnionOperator())); connectQueriesWith(composite.get(), leftComposite, unionQuery, right); } else if (rightComposite) { // split for (int i = 0; i < rightComposite->inputCount(); ++i) composite->connectQuery(left, 0, rightComposite, i); } else { composite->connectQuery(left, right); } int inputCount = leftComposite ? leftComposite->inputCount() : 1; int outputCount = rightComposite ? rightComposite->outputCount() : 1; for (int i = 0; i < inputCount; ++i) composite->connectInput(i, left, i); for (int o = 0; o < outputCount; ++o) composite->connectToOutput(right, o); return std::unique_ptr<Query>(composite.release()); } void QueryBuilder::connectQueriesWith(CompositeQuery* composite, CompositeQuery* queries, Query* connectionQuery, Query* outputQuery) { for (int i = 0; i < queries->outputCount(); ++i) composite->connectQuery(queries, i, connectionQuery, i); if (outputQuery) composite->connectQuery(connectionQuery, outputQuery); } } /* namespace InformationScripting */ <|endoftext|>
<commit_before>#ifndef STAN_MATH_PRIM_FUN_DIAG_MATRIX_HPP #define STAN_MATH_PRIM_FUN_DIAG_MATRIX_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/Eigen.hpp> namespace stan { namespace math { /** * Return a square diagonal matrix with the specified vector of * coefficients as the diagonal values. * * @tparam EigVec type of the vector (must be derived from \c Eigen::MatrixBase * and have one compile time dimmension equal to 1) * @param[in] v Specified vector. * @return Diagonal matrix with vector as diagonal values. */ template <typename EigVec, require_eigen_vector_t<EigVec>* = nullptr> inline auto diag_matrix(const EigVec& v) { return v.asDiagonal(); } } // namespace math } // namespace stan #endif <commit_msg>revert diag_matrix<commit_after>#ifndef STAN_MATH_PRIM_FUN_DIAG_MATRIX_HPP #define STAN_MATH_PRIM_FUN_DIAG_MATRIX_HPP #include <stan/math/prim/meta.hpp> #include <stan/math/prim/fun/Eigen.hpp> namespace stan { namespace math { /** * Return a square diagonal matrix with the specified vector of * coefficients as the diagonal values. * * @tparam EigVec type of the vector (must be derived from \c Eigen::MatrixBase * and have one compile time dimmension equal to 1) * @param[in] v Specified vector. * @return Diagonal matrix with vector as diagonal values. */ template <typename EigVec, require_eigen_vector_t<EigVec>* = nullptr> inline Eigen::Matrix<value_type_t<EigVec>, Eigen::Dynamic, Eigen::Dynamic> diag_matrix(const EigVec& v) { return v.asDiagonal(); } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/sync.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <arch/ppc.H> #include <sys/sync.h> #include <sys/syscall.h> #include <assert.h> #include <errno.h> #include <kernel/console.H> using namespace Systemcalls; // The size of mutexes are hardcoded in xmltohb.pl script and must be that // size. const int MUTEX_SIZE = 24; //----------------------------------------------------------------------------- int futex_wait(uint64_t * i_addr, uint64_t i_val) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_WAIT, i_addr, (void *)i_val, NULL, NULL); } //----------------------------------------------------------------------------- int futex_wake(uint64_t * i_addr, uint64_t i_count) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_WAKE, i_addr, (void *)i_count, NULL, NULL); } //----------------------------------------------------------------------------- int64_t futex_requeue(uint64_t * i_addr, uint64_t i_count1, uint64_t i_count2, uint64_t * i_futex2) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_REQUEUE, i_addr, (void *)i_count1, (void *)i_count2, i_futex2); } //----------------------------------------------------------------------------- void barrier_init (barrier_t * o_barrier, uint64_t i_count) { mutex_init(&(o_barrier->iv_mutex)); o_barrier->iv_event = 0; o_barrier->iv_count = i_count; o_barrier->iv_missing = i_count; return; } //----------------------------------------------------------------------------- void barrier_destroy (barrier_t * i_barrier) { crit_assert(i_barrier->iv_missing == i_barrier->iv_count); return; } //----------------------------------------------------------------------------- void barrier_wait (barrier_t * i_barrier) { mutex_lock(&(i_barrier->iv_mutex)); --(i_barrier->iv_missing); if(i_barrier->iv_missing > 0) { uint64_t l_event = i_barrier->iv_event; mutex_unlock(&(i_barrier->iv_mutex)); do { futex_wait(&(i_barrier->iv_event), l_event); } while (i_barrier->iv_event == l_event); } else { ++(i_barrier->iv_event); i_barrier->iv_missing = i_barrier->iv_count; // Wake em all up futex_wake(&(i_barrier->iv_event), UINT64_MAX); mutex_unlock(&(i_barrier->iv_mutex)); } return; } //----------------------------------------------------------------------------- /** * @fn mutex_init * @brief Initialize a mutex object. * @param[out] o_mutex the mutex * @param[in] i_recursive indicate whether a mutex is recursive or not. * @pre an uninitialized mutex object * @post a valid mutex object */ void mutex_init(mutex_t * o_mutex, bool i_recursive) { o_mutex->iv_val = 0; o_mutex->iv_owner = 0; o_mutex->iv_ownerLockCount = 0; o_mutex->iv_recursive = i_recursive; return; } void mutex_init(mutex_t * o_mutex) { mutex_init(o_mutex, false); return; } void recursive_mutex_init(mutex_t * o_mutex) { mutex_init(o_mutex, true); return; } //----------------------------------------------------------------------------- void mutex_destroy(mutex_t * i_mutex) { crit_assert(!i_mutex->iv_recursive); i_mutex->iv_val = ~0; i_mutex->iv_owner = 0; i_mutex->iv_ownerLockCount = 0; return; } void recursive_mutex_destroy(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); i_mutex->iv_val = ~0; i_mutex->iv_owner = 0; i_mutex->iv_ownerLockCount = 0; return; } //----------------------------------------------------------------------------- void mutex_lock(mutex_t * i_mutex) { // Weak consistency notes: // Since this is a lock, we do not need to ensure that all writes // are globally visible prior to execution (lwsync) but we do need // to ensure that all instructions finish completion prior to // leaving (isync). Both __sync_val_compare_and_swap and // __sync_lock_test_and_set have an implied isync. crit_assert(!i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. crit_assert(i_mutex->iv_val <= 2); uint64_t l_lockStatus = __sync_val_compare_and_swap(&(i_mutex->iv_val),0,1); if(unlikely(l_lockStatus != 0)) { if(likely(l_lockStatus != 2)) { l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); } while(l_lockStatus != 0) { futex_wait(&(i_mutex->iv_val), 2); l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); // if more than one task gets out - one continues while // the rest get blocked again. } } return; } //----------------------------------------------------------------------------- void mutex_unlock(mutex_t * i_mutex) { // Weak consistency notes: // Since this is an unlock we need to ensure that all writes are // globally visible prior to execution (lwsync). The // __sync_fetch_and_sub has an implied lwsync. If we need to // release a task, due to a contended mutex, the write to iv_val // and futex_wake pair will appear globally ordered due to the // context synchronizing nature of the 'sc' instruction. crit_assert(!i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. crit_assert(i_mutex->iv_val <= 2); uint64_t l_lockStatus = __sync_fetch_and_sub(&(i_mutex->iv_val), 1); if(unlikely(l_lockStatus >= 2)) { // Fully release the lock and let another task grab it. i_mutex->iv_val = 0; futex_wake(&(i_mutex->iv_val), 1); // wake one task } return; } void recursive_mutex_lock(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. crit_assert(i_mutex->iv_val <= 2); // Check the contents of the mutex's iv_val and if it's equal to 0, then // assign it the value of 1. l_lockStatus is initialized with the value of // iv_val prior to the assignment. uint64_t l_lockStatus = __sync_val_compare_and_swap(&(i_mutex->iv_val),0,1); do { if(unlikely(l_lockStatus != 0)) { // There may be contention for the lock. Since this is a recursive // mutex we first need to check if the owner has called for the lock // again. if (task_gettid() == i_mutex->iv_owner) { // The owner called for the lock. There isn't contention at this // point and so subsequent calls to this function will still // initialize l_lockStatus to 1. // // Increment the owner's lock count to keep track of how much // unwinding will be necessary but the lock can be safely // released. ++i_mutex->iv_ownerLockCount; // Return now so that the owner doesn't set the lock to be // contended and enter the waiting queue, thus causing a // deadlock. break; } // By reaching this point there is certainly contention for the // lock. Ensure that the lock status reflects this if it doesn't // already. if (likely(l_lockStatus != 2)) { // mutex's iv_val will be set to 2 and the previous value will // be assigned to l_lockStatus. l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); } // Send caller to the wait queue. while( l_lockStatus != 0 ) { futex_wait( &(i_mutex->iv_val), 2); l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val),2); // if more than one task gets out - one continues while // the rest get blocked again. } } // Set the new owner of the lock and increment the lock count. i_mutex->iv_owner = task_gettid(); ++i_mutex->iv_ownerLockCount; } while(0); return; } void recursive_mutex_unlock(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. crit_assert(i_mutex->iv_val <= 2); uint64_t l_lockStatus = 0; if (i_mutex->iv_ownerLockCount <= 1) { // Owner is finished with the lock. So reset owner variables of mutex. i_mutex->iv_ownerLockCount = 0; i_mutex->iv_owner = 0; // Decrements iv_val by 1 and assigns the value prior to the operation // to l_lockStatus. l_lockStatus = __sync_fetch_and_sub(&(i_mutex->iv_val),1); if(unlikely(l_lockStatus >= 2)) { // Fully release the lock to allow the next task to grab it. i_mutex->iv_val = 0; futex_wake(&(i_mutex->iv_val), 1); // wake one task } } else { // Unwind the recursive lock one step. --i_mutex->iv_ownerLockCount; } return; } void sync_cond_init(sync_cond_t * i_cond) { i_cond->mutex = NULL; i_cond->sequence = 0; } void sync_cond_destroy(sync_cond_t * i_cond) { // don't need to do anything } int sync_cond_wait(sync_cond_t * i_cond, mutex_t * i_mutex) { uint64_t seq = i_cond->sequence; if(i_cond->mutex != i_mutex) { if(i_cond->mutex) return EINVAL; // Atomically set mutex __sync_bool_compare_and_swap(&i_cond->mutex, NULL, i_mutex); if(i_cond->mutex != i_mutex) return EINVAL; } mutex_unlock(i_mutex); futex_wait( &(i_cond->sequence), seq); // Can't continue until i_mutex lock is obtained. // Note: // mutex_lock(i_mutex); <--- This does not work // We have to mark the mutex as contended '2' because there is a race // condition between this thread (eventually) calling mutex_unlock and // the kernel moving tasks from the condition futex to the mutex futex // during a sync_condition_broadcast. By marking contended, we force the // subsequent mutex_unlock to call to the kernel which will obtain a // spinlock to ensure all tasks have been moved to the mutex_futex. while(0 != __sync_lock_test_and_set(&(i_mutex->iv_val), 2)) { futex_wait(&(i_mutex->iv_val),2); } return 0; } void sync_cond_signal(sync_cond_t * i_cond) { __sync_fetch_and_add(&(i_cond->sequence),1); // Wake up one futex_wake(&(i_cond->sequence), 1); } void sync_cond_broadcast(sync_cond_t * i_cond) { mutex_t * m = i_cond->mutex; // no mutex means no waiters if(!m) return; // wake up all __sync_fetch_and_add(&(i_cond->sequence),1); // need to wake up one on the sequence and // re-queue the rest onto the mutex m; futex_requeue(&(i_cond->sequence),1,UINT64_MAX,&(m->iv_val)); } <commit_msg>Fix intermittent CI fails regarding mutexes<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/lib/sync.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2011,2019 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #include <arch/ppc.H> #include <sys/sync.h> #include <sys/syscall.h> #include <assert.h> #include <errno.h> #include <kernel/console.H> using namespace Systemcalls; // The size of mutexes are hardcoded in xmltohb.pl script and must be that // size. const int MUTEX_SIZE = 24; //----------------------------------------------------------------------------- int futex_wait(uint64_t * i_addr, uint64_t i_val) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_WAIT, i_addr, (void *)i_val, NULL, NULL); } //----------------------------------------------------------------------------- int futex_wake(uint64_t * i_addr, uint64_t i_count) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_WAKE, i_addr, (void *)i_count, NULL, NULL); } //----------------------------------------------------------------------------- int64_t futex_requeue(uint64_t * i_addr, uint64_t i_count1, uint64_t i_count2, uint64_t * i_futex2) { return (int64_t) _syscall5(SYS_FUTEX, (void *)FUTEX_REQUEUE, i_addr, (void *)i_count1, (void *)i_count2, i_futex2); } //----------------------------------------------------------------------------- void barrier_init (barrier_t * o_barrier, uint64_t i_count) { mutex_init(&(o_barrier->iv_mutex)); o_barrier->iv_event = 0; o_barrier->iv_count = i_count; o_barrier->iv_missing = i_count; return; } //----------------------------------------------------------------------------- void barrier_destroy (barrier_t * i_barrier) { crit_assert(i_barrier->iv_missing == i_barrier->iv_count); return; } //----------------------------------------------------------------------------- void barrier_wait (barrier_t * i_barrier) { mutex_lock(&(i_barrier->iv_mutex)); --(i_barrier->iv_missing); if(i_barrier->iv_missing > 0) { uint64_t l_event = i_barrier->iv_event; mutex_unlock(&(i_barrier->iv_mutex)); do { futex_wait(&(i_barrier->iv_event), l_event); } while (i_barrier->iv_event == l_event); } else { ++(i_barrier->iv_event); i_barrier->iv_missing = i_barrier->iv_count; // Wake em all up futex_wake(&(i_barrier->iv_event), UINT64_MAX); mutex_unlock(&(i_barrier->iv_mutex)); } return; } //----------------------------------------------------------------------------- /** * @fn mutex_init * @brief Initialize a mutex object. * @param[out] o_mutex the mutex * @param[in] i_recursive indicate whether a mutex is recursive or not. * @pre an uninitialized mutex object * @post a valid mutex object */ void mutex_init(mutex_t * o_mutex, bool i_recursive) { o_mutex->iv_val = 0; o_mutex->iv_owner = 0; o_mutex->iv_ownerLockCount = 0; o_mutex->iv_recursive = i_recursive; return; } void mutex_init(mutex_t * o_mutex) { mutex_init(o_mutex, false); return; } void recursive_mutex_init(mutex_t * o_mutex) { mutex_init(o_mutex, true); return; } //----------------------------------------------------------------------------- void mutex_destroy(mutex_t * i_mutex) { crit_assert(!i_mutex->iv_recursive); i_mutex->iv_val = ~0; i_mutex->iv_owner = 0; i_mutex->iv_ownerLockCount = 0; return; } void recursive_mutex_destroy(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); i_mutex->iv_val = ~0; i_mutex->iv_owner = 0; i_mutex->iv_ownerLockCount = 0; return; } //----------------------------------------------------------------------------- void mutex_lock(mutex_t * i_mutex) { // Weak consistency notes: // Since this is a lock, we do not need to ensure that all writes // are globally visible prior to execution (lwsync) but we do need // to ensure that all instructions finish completion prior to // leaving (isync). Both __sync_val_compare_and_swap and // __sync_lock_test_and_set have an implied isync. crit_assert(!i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. uint64_t l_lockStatus = __sync_val_compare_and_swap(&(i_mutex->iv_val),0,1); if(unlikely(l_lockStatus != 0)) { if(likely(l_lockStatus != 2)) { l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); } while(l_lockStatus != 0) { futex_wait(&(i_mutex->iv_val), 2); l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); // if more than one task gets out - one continues while // the rest get blocked again. } } return; } //----------------------------------------------------------------------------- void mutex_unlock(mutex_t * i_mutex) { // Weak consistency notes: // Since this is an unlock we need to ensure that all writes are // globally visible prior to execution (lwsync). The // __sync_fetch_and_sub has an implied lwsync. If we need to // release a task, due to a contended mutex, the write to iv_val // and futex_wake pair will appear globally ordered due to the // context synchronizing nature of the 'sc' instruction. crit_assert(!i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. uint64_t l_lockStatus = __sync_fetch_and_sub(&(i_mutex->iv_val), 1); if(unlikely(l_lockStatus >= 2)) { // Fully release the lock and let another task grab it. i_mutex->iv_val = 0; futex_wake(&(i_mutex->iv_val), 1); // wake one task } return; } void recursive_mutex_lock(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. // Check the contents of the mutex's iv_val and if it's equal to 0, then // assign it the value of 1. l_lockStatus is initialized with the value of // iv_val prior to the assignment. uint64_t l_lockStatus = __sync_val_compare_and_swap(&(i_mutex->iv_val),0,1); do { if(unlikely(l_lockStatus != 0)) { // There may be contention for the lock. Since this is a recursive // mutex we first need to check if the owner has called for the lock // again. if (task_gettid() == i_mutex->iv_owner) { // The owner called for the lock. There isn't contention at this // point and so subsequent calls to this function will still // initialize l_lockStatus to 1. // // Increment the owner's lock count to keep track of how much // unwinding will be necessary but the lock can be safely // released. ++i_mutex->iv_ownerLockCount; // Return now so that the owner doesn't set the lock to be // contended and enter the waiting queue, thus causing a // deadlock. break; } // By reaching this point there is certainly contention for the // lock. Ensure that the lock status reflects this if it doesn't // already. if (likely(l_lockStatus != 2)) { // mutex's iv_val will be set to 2 and the previous value will // be assigned to l_lockStatus. l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val), 2); } // Send caller to the wait queue. while( l_lockStatus != 0 ) { futex_wait( &(i_mutex->iv_val), 2); l_lockStatus = __sync_lock_test_and_set(&(i_mutex->iv_val),2); // if more than one task gets out - one continues while // the rest get blocked again. } } // Set the new owner of the lock and increment the lock count. i_mutex->iv_owner = task_gettid(); ++i_mutex->iv_ownerLockCount; } while(0); return; } void recursive_mutex_unlock(mutex_t * i_mutex) { crit_assert(i_mutex->iv_recursive); static_assert(sizeof(mutex_t) == MUTEX_SIZE, "mutex_t must be size of 24 bytes"); // The mutex is only allowed to take on three values: 0, 1, or 2. // 0: Lock is not held. // 1: Lock is held by a task with no contention. // 2: Lock is held by a task and there is contention. // Any other values indicates that outside influences have messed with the // mutex and we shouldn't continue. uint64_t l_lockStatus = 0; if (i_mutex->iv_ownerLockCount <= 1) { // Owner is finished with the lock. So reset owner variables of mutex. i_mutex->iv_ownerLockCount = 0; i_mutex->iv_owner = 0; // Decrements iv_val by 1 and assigns the value prior to the operation // to l_lockStatus. l_lockStatus = __sync_fetch_and_sub(&(i_mutex->iv_val),1); if(unlikely(l_lockStatus >= 2)) { // Fully release the lock to allow the next task to grab it. i_mutex->iv_val = 0; futex_wake(&(i_mutex->iv_val), 1); // wake one task } } else { // Unwind the recursive lock one step. --i_mutex->iv_ownerLockCount; } return; } void sync_cond_init(sync_cond_t * i_cond) { i_cond->mutex = NULL; i_cond->sequence = 0; } void sync_cond_destroy(sync_cond_t * i_cond) { // don't need to do anything } int sync_cond_wait(sync_cond_t * i_cond, mutex_t * i_mutex) { uint64_t seq = i_cond->sequence; if(i_cond->mutex != i_mutex) { if(i_cond->mutex) return EINVAL; // Atomically set mutex __sync_bool_compare_and_swap(&i_cond->mutex, NULL, i_mutex); if(i_cond->mutex != i_mutex) return EINVAL; } mutex_unlock(i_mutex); futex_wait( &(i_cond->sequence), seq); // Can't continue until i_mutex lock is obtained. // Note: // mutex_lock(i_mutex); <--- This does not work // We have to mark the mutex as contended '2' because there is a race // condition between this thread (eventually) calling mutex_unlock and // the kernel moving tasks from the condition futex to the mutex futex // during a sync_condition_broadcast. By marking contended, we force the // subsequent mutex_unlock to call to the kernel which will obtain a // spinlock to ensure all tasks have been moved to the mutex_futex. while(0 != __sync_lock_test_and_set(&(i_mutex->iv_val), 2)) { futex_wait(&(i_mutex->iv_val),2); } return 0; } void sync_cond_signal(sync_cond_t * i_cond) { __sync_fetch_and_add(&(i_cond->sequence),1); // Wake up one futex_wake(&(i_cond->sequence), 1); } void sync_cond_broadcast(sync_cond_t * i_cond) { mutex_t * m = i_cond->mutex; // no mutex means no waiters if(!m) return; // wake up all __sync_fetch_and_add(&(i_cond->sequence),1); // need to wake up one on the sequence and // re-queue the rest onto the mutex m; futex_requeue(&(i_cond->sequence),1,UINT64_MAX,&(m->iv_val)); } <|endoftext|>
<commit_before>#include "chord.h" /* * * comm.C * * This code deals with the actual communication to nodes. * */ chord_stats stats; // creates an array of edges of a fake network // stores in int* edges // after this function numnodes holds the number // of nodes in the fake network // NOTE: may later want to change file input name void p2p::initialize_graph() { FILE *graphfp; int cur_node, to_node, length,i,j; int done = 0; graphfp = fopen("gg","r"); if(graphfp == NULL) printf("EEK-- didn't open input file correctly\n"); // first line of file is number of nodes fscanf(graphfp,"%d",&numnodes); // create space for a numnodes by numnodes edge array edges = (int *)calloc(numnodes*numnodes,sizeof(int)); // initialize edge array as -1 for all accept i,i entries for(i=0;i<numnodes;i++) for(j=0;j<numnodes;j++) if(i == j) *(edges+i*numnodes+j) = 0; else *(edges+i*numnodes+j) = -1; // more nodes to find the edges of while(fscanf(graphfp,"%d",&cur_node) != EOF && done == 0) { fscanf(graphfp,"%d%d",&to_node,&length); *(edges+cur_node*numnodes + to_node) = length; // while there are more edges for this node while(fscanf(graphfp,"%d",&to_node) != EOF && to_node != -1) { fscanf(graphfp,"%d",&length); *(edges+cur_node*numnodes + to_node) = length; } if(to_node != -1) // reached end of file done = 1; } fclose(graphfp); } void p2p::timeout(location *l) { assert(l); warn << "timeout on " << l->n << " closing socket\n"; if (l->nout == 0) l->x = NULL; else { // warn << "timeout on node " << l->n << " has overdue RPCs\n"; l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); } } void p2p::timing_cb(aclnt_cb cb, location *l, ptr<struct timeval> start, int procno, rpc_program progno, clnt_stat err) { assert(l); struct timeval now; gettimeofday(&now, NULL); long lat = ((now.tv_sec - start->tv_sec)*1000000 + (now.tv_usec - start->tv_usec))/1000; // warn << "Latency: " << lat << " type " << progno.progno << "," << procno << "\n"; l->total_latency += lat; l->num_latencies++; if (lat > l->max_latency) l->max_latency = lat; l->nout--; (*cb)(err); } // just add a time delay to represent distance void p2p::doRPC (sfs_ID &ID, rpc_program progno, int procno, const void *in, void *out, aclnt_cb cb) { rpc_args *a = new rpc_args(ID,progno,procno,in,out,cb); if (insert_or_lookup && (rpcdelay > 0)) { warn << "DELAYED \n"; delaycb (0, rpcdelay, wrap(mkref(this), &p2p::doRealRPC, a)); } else { doRealRPC (a); } } // NOTE: now passing ID by value instead of referencing it... // (getting compiler errors before). now seems ok // May want to try to change back later (to avoid passing around // sfs_ID instead of a ptr void p2p::doRealRPC (rpc_args *a) { sfs_ID ID = a->ID; rpc_program progno = a->progno; int procno = a->procno; const void *in = a->in; void *out = a->out; aclnt_cb cb = a->cb; // warnx << "doRealRPC\n"; if (lookups_outstanding > 0) lookup_RPCs++; if ((insert_or_lookup > 0) && (myID != ID)) stats.total_rpcs++; location *l = locations[ID]; if (!l) { warn << "about to trip on " << ID << "\n"; sleep(1); exit(12); } assert (l); assert (l->alive); ptr<struct timeval> start = new refcounted<struct timeval>(); gettimeofday(start, NULL); l->nout++; if (l->x) { timecb_remove(l->timeout_cb); l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); ptr<aclnt> c = aclnt::alloc(l->x, progno); c->call (procno, in, out, wrap(mkref(this), &p2p::timing_cb, cb, l, start, procno, progno)); } else { doRPC_cbstate *st = New doRPC_cbstate (progno, procno, in, out, wrap(mkref(this), &p2p::timing_cb, cb, l, start, -procno, progno)); l->connectlist.insert_tail (st); if (!l->connecting) { l->connecting = true; chord_connect(ID, wrap (mkref (this), &p2p::dorpc_connect_cb, l)); } } } void p2p::dorpc_connect_cb(location *l, ptr<axprt_stream> x) { assert(l); if (x == NULL) { warnx << "connect_cb: connect failed\n"; doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { st1 = l->connectlist.next (st); aclnt_cb cb = st->cb; (*cb) (RPC_FAILED); } l->connecting = false; return; } assert(l->alive); l->x = x; l->connecting = false; l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { ptr<aclnt> c = aclnt::alloc (x, st->progno); c->call (st->procno, st->in, st->out, st->cb); st1 = l->connectlist.next (st); l->connectlist.remove(st); } } void p2p::chord_connect(sfs_ID ID, callback<void, ptr<axprt_stream> >::ref cb) { location *l = locations[ID]; assert (l); assert (l->alive); ptr<struct timeval> start = new refcounted<struct timeval>(); gettimeofday(start, NULL); if (l->x) { timecb_remove(l->timeout_cb); l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); (*cb)(l->x); } else { tcpconnect (l->addr.hostname, l->addr.port, wrap (mkref (this), &p2p::connect_cb, cb)); } } void p2p::connect_cb (callback<void, ptr<axprt_stream> >::ref cb, int fd) { if (fd < 0) { (*cb)(NULL); } else { tcp_nodelay(fd); ptr<axprt_stream> x = axprt_stream::alloc(fd); (*cb)(x); } } void p2p::stats_cb () { warnx << "Chord Node " << myID << " status\n"; warnx << "Core layer stats\n"; warnx << " Per link avg. RPC latencies\n"; location *l = locations.first (); while (l) { warnx << " link " << l->n << "\n"; fprintf(stderr, " Average latency: %f\n", ((float)(l->total_latency))/l->num_latencies); fprintf(stderr, " Max latency: %ld\n", l->max_latency); int *nkeys = (*stats.balance)[l->n]; if (nkeys) warnx << " " << *nkeys << " keys were sent to this node\n"; else warnx << " 0 keys were sent to this node\n"; l = locations.next(l); } warnx << "DHASH layer stats\n"; #if 0 warnx << " Caching is "; if (do_caching) warnx << "on\n"; else warnx << "off\n"; #endif warnx << " " << stats.insert_ops << " insertions\n"; fprintf(stderr, " %f average hops per insert\n", ((float)(stats.insert_path_len))/stats.insert_ops); warnx << " " << stats.lookup_ops << " lookups\n"; fprintf(stderr, " %f average hops per lookup\n", ((float)(stats.lookup_path_len))/stats.lookup_ops); fprintf(stderr, " %f ms average latency per lookup operation\n", ((float)(stats.lookup_lat))/stats.lookup_ops); fprintf(stderr, " %ld ms greatest latency for a lookup\n", stats.lookup_max_lat); fprintf(stderr, " %f KB/sec avg. total bandwidth\n", ((float)(stats.lookup_bytes_fetched))/(stats.lookup_lat)); } <commit_msg>removed sim stuff<commit_after>#include "chord.h" /* * * comm.C * * This code deals with the actual communication to nodes. * */ chord_stats stats; void p2p::timeout(location *l) { assert(l); warn << "timeout on " << l->n << " closing socket\n"; if (l->nout == 0) l->x = NULL; else { warn << "timeout on node " << l->n << " has overdue RPCs\n"; l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); } } void p2p::doRPC (sfs_ID &ID, rpc_program progno, int procno, const void *in, void *out, aclnt_cb cb) { if (lookups_outstanding > 0) lookup_RPCs++; if ((insert_or_lookup > 0) && (myID != ID)) stats.total_rpcs++; location *l = locations[ID]; assert (l); assert (l->alive); l->nout++; if (l->x) { timecb_remove(l->timeout_cb); l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); ptr<aclnt> c = aclnt::alloc(l->x, progno); c->call (procno, in, out, cb); } else { doRPC_cbstate *st = New doRPC_cbstate (progno, procno, in, out, cb); l->connectlist.insert_tail (st); if (!l->connecting) { l->connecting = true; chord_connect(ID, wrap (mkref (this), &p2p::dorpc_connect_cb, l)); } } } void p2p::dorpc_connect_cb(location *l, ptr<axprt_stream> x) { assert(l); if (x == NULL) { warnx << "connect_cb: connect failed\n"; doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { st1 = l->connectlist.next (st); aclnt_cb cb = st->cb; (*cb) (RPC_FAILED); } l->connecting = false; return; } assert(l->alive); l->x = x; l->connecting = false; l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); doRPC_cbstate *st, *st1; for (st = l->connectlist.first; st; st = st1) { ptr<aclnt> c = aclnt::alloc (x, st->progno); c->call (st->procno, st->in, st->out, st->cb); st1 = l->connectlist.next (st); l->connectlist.remove(st); } } void p2p::chord_connect(sfs_ID ID, callback<void, ptr<axprt_stream> >::ref cb) { location *l = locations[ID]; assert (l); assert (l->alive); ptr<struct timeval> start = new refcounted<struct timeval>(); gettimeofday(start, NULL); if (l->x) { timecb_remove(l->timeout_cb); l->timeout_cb = delaycb(360,0,wrap(this, &p2p::timeout, l)); (*cb)(l->x); } else { tcpconnect (l->addr.hostname, l->addr.port, wrap (mkref (this), &p2p::connect_cb, cb)); } } void p2p::connect_cb (callback<void, ptr<axprt_stream> >::ref cb, int fd) { if (fd < 0) { (*cb)(NULL); } else { tcp_nodelay(fd); ptr<axprt_stream> x = axprt_stream::alloc(fd); (*cb)(x); } } void p2p::stats_cb () { warnx << "Chord Node " << myID << " status\n"; warnx << "Core layer stats\n"; warnx << " Per link avg. RPC latencies\n"; location *l = locations.first (); while (l) { warnx << " link " << l->n << "\n"; fprintf(stderr, " Average latency: %f\n", ((float)(l->total_latency))/l->num_latencies); fprintf(stderr, " Max latency: %ld\n", l->max_latency); int *nkeys = (*stats.balance)[l->n]; if (nkeys) warnx << " " << *nkeys << " keys were sent to this node\n"; else warnx << " 0 keys were sent to this node\n"; l = locations.next(l); } warnx << "DHASH layer stats\n"; #if 0 warnx << " Caching is "; if (do_caching) warnx << "on\n"; else warnx << "off\n"; #endif warnx << " " << stats.insert_ops << " insertions\n"; fprintf(stderr, " %f average hops per insert\n", ((float)(stats.insert_path_len))/stats.insert_ops); warnx << " " << stats.lookup_ops << " lookups\n"; fprintf(stderr, " %f average hops per lookup\n", ((float)(stats.lookup_path_len))/stats.lookup_ops); fprintf(stderr, " %f ms average latency per lookup operation\n", ((float)(stats.lookup_lat))/stats.lookup_ops); fprintf(stderr, " %ld ms greatest latency for a lookup\n", stats.lookup_max_lat); fprintf(stderr, " %f KB/sec avg. total bandwidth\n", ((float)(stats.lookup_bytes_fetched))/(stats.lookup_lat)); } <|endoftext|>
<commit_before>/* * Runtime CPU detection * (C) 2009,2010,2013,2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/cpuid.h> #include <botan/types.h> #include <botan/exceptn.h> #include <botan/parsing.h> #include <ostream> namespace Botan { uint64_t CPUID::g_processor_features = 0; size_t CPUID::g_cache_line_size = BOTAN_TARGET_CPU_DEFAULT_CACHE_LINE_SIZE; CPUID::Endian_status CPUID::g_endian_status = ENDIAN_UNKNOWN; bool CPUID::has_simd_32() { #if defined(BOTAN_TARGET_SUPPORTS_SSE2) return CPUID::has_sse2(); #elif defined(BOTAN_TARGET_SUPPORTS_ALTIVEC) return CPUID::has_altivec(); #elif defined(BOTAN_TARGET_SUPPORTS_NEON) return CPUID::has_neon(); #else return true; #endif } //static std::string CPUID::to_string() { std::vector<std::string> flags; #define CPUID_PRINT(flag) do { if(has_##flag()) { flags.push_back(#flag); } } while(0) #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) CPUID_PRINT(sse2); CPUID_PRINT(ssse3); CPUID_PRINT(sse41); CPUID_PRINT(sse42); CPUID_PRINT(avx2); CPUID_PRINT(avx512f); CPUID_PRINT(rdtsc); CPUID_PRINT(bmi2); CPUID_PRINT(adx); CPUID_PRINT(aes_ni); CPUID_PRINT(clmul); CPUID_PRINT(rdrand); CPUID_PRINT(rdseed); CPUID_PRINT(intel_sha); #endif #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) CPUID_PRINT(altivec); CPUID_PRINT(ppc_crypto); #endif #if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) CPUID_PRINT(neon); CPUID_PRINT(arm_sha1); CPUID_PRINT(arm_sha2); CPUID_PRINT(arm_aes); CPUID_PRINT(arm_pmull); #endif #undef CPUID_PRINT return string_join(flags, ' '); } //static void CPUID::print(std::ostream& o) { o << "CPUID flags: " << CPUID::to_string() << "\n"; } //static void CPUID::initialize() { g_processor_features = 0; #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) g_processor_features = CPUID::detect_cpu_features(&g_cache_line_size); #endif g_processor_features |= CPUID::CPUID_INITIALIZED_BIT; } //static CPUID::Endian_status CPUID::runtime_check_endian() { // Check runtime endian const uint32_t endian32 = 0x01234567; const uint8_t* e8 = reinterpret_cast<const uint8_t*>(&endian32); Endian_status endian = ENDIAN_UNKNOWN; if(e8[0] == 0x01 && e8[1] == 0x23 && e8[2] == 0x45 && e8[3] == 0x67) { endian = ENDIAN_BIG; } else if(e8[0] == 0x67 && e8[1] == 0x45 && e8[2] == 0x23 && e8[3] == 0x01) { endian = ENDIAN_LITTLE; } else { throw Internal_Error("Unexpected endian at runtime, neither big nor little"); } // If we were compiled with a known endian, verify it matches at runtime #if defined(BOTAN_TARGET_CPU_IS_LITTLE_ENDIAN) BOTAN_ASSERT(endian == ENDIAN_LITTLE, "Build and runtime endian match"); #elif defined(BOTAN_TARGET_CPU_IS_BIG_ENDIAN) BOTAN_ASSERT(endian == ENDIAN_BIG, "Build and runtime endian match"); #endif return endian; } std::vector<Botan::CPUID::CPUID_bits> CPUID::bit_from_string(const std::string& tok) { #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) if(tok == "sse2" || tok == "simd") return {Botan::CPUID::CPUID_SSE2_BIT}; if(tok == "ssse3") return {Botan::CPUID::CPUID_SSSE3_BIT}; if(tok == "aesni") return {Botan::CPUID::CPUID_AESNI_BIT}; if(tok == "clmul") return {Botan::CPUID::CPUID_CLMUL_BIT}; if(tok == "avx2") return {Botan::CPUID::CPUID_AVX2_BIT}; if(tok == "sha") return {Botan::CPUID::CPUID_SHA_BIT}; #elif defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) if(tok == "altivec" || tok == "simd") return {Botan::CPUID::CPUID_ALTIVEC_BIT}; #elif defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) if(tok == "neon" || tok == "simd") return {Botan::CPUID::CPUID_ARM_NEON_BIT}; if(tok == "armv8sha1") return {Botan::CPUID::CPUID_ARM_SHA1_BIT}; if(tok == "armv8sha2") return {Botan::CPUID::CPUID_ARM_SHA2_BIT}; if(tok == "armv8aes") return {Botan::CPUID::CPUID_ARM_AES_BIT}; if(tok == "armv8pmull") return {Botan::CPUID::CPUID_ARM_PMULL_BIT}; #else BOTAN_UNUSED(tok); #endif return {}; } } <commit_msg>Do runtime endian check when CPUID is initialized<commit_after>/* * Runtime CPU detection * (C) 2009,2010,2013,2017 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/cpuid.h> #include <botan/types.h> #include <botan/exceptn.h> #include <botan/parsing.h> #include <ostream> namespace Botan { uint64_t CPUID::g_processor_features = 0; size_t CPUID::g_cache_line_size = BOTAN_TARGET_CPU_DEFAULT_CACHE_LINE_SIZE; CPUID::Endian_status CPUID::g_endian_status = ENDIAN_UNKNOWN; bool CPUID::has_simd_32() { #if defined(BOTAN_TARGET_SUPPORTS_SSE2) return CPUID::has_sse2(); #elif defined(BOTAN_TARGET_SUPPORTS_ALTIVEC) return CPUID::has_altivec(); #elif defined(BOTAN_TARGET_SUPPORTS_NEON) return CPUID::has_neon(); #else return true; #endif } //static std::string CPUID::to_string() { std::vector<std::string> flags; #define CPUID_PRINT(flag) do { if(has_##flag()) { flags.push_back(#flag); } } while(0) #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) CPUID_PRINT(sse2); CPUID_PRINT(ssse3); CPUID_PRINT(sse41); CPUID_PRINT(sse42); CPUID_PRINT(avx2); CPUID_PRINT(avx512f); CPUID_PRINT(rdtsc); CPUID_PRINT(bmi2); CPUID_PRINT(adx); CPUID_PRINT(aes_ni); CPUID_PRINT(clmul); CPUID_PRINT(rdrand); CPUID_PRINT(rdseed); CPUID_PRINT(intel_sha); #endif #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) CPUID_PRINT(altivec); CPUID_PRINT(ppc_crypto); #endif #if defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) CPUID_PRINT(neon); CPUID_PRINT(arm_sha1); CPUID_PRINT(arm_sha2); CPUID_PRINT(arm_aes); CPUID_PRINT(arm_pmull); #endif #undef CPUID_PRINT return string_join(flags, ' '); } //static void CPUID::print(std::ostream& o) { o << "CPUID flags: " << CPUID::to_string() << "\n"; } //static void CPUID::initialize() { g_processor_features = 0; #if defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) || \ defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) g_processor_features = CPUID::detect_cpu_features(&g_cache_line_size); #endif g_endian_status = runtime_check_endian(); g_processor_features |= CPUID::CPUID_INITIALIZED_BIT; } //static CPUID::Endian_status CPUID::runtime_check_endian() { // Check runtime endian const uint32_t endian32 = 0x01234567; const uint8_t* e8 = reinterpret_cast<const uint8_t*>(&endian32); Endian_status endian = ENDIAN_UNKNOWN; if(e8[0] == 0x01 && e8[1] == 0x23 && e8[2] == 0x45 && e8[3] == 0x67) { endian = ENDIAN_BIG; } else if(e8[0] == 0x67 && e8[1] == 0x45 && e8[2] == 0x23 && e8[3] == 0x01) { endian = ENDIAN_LITTLE; } else { throw Internal_Error("Unexpected endian at runtime, neither big nor little"); } // If we were compiled with a known endian, verify it matches at runtime #if defined(BOTAN_TARGET_CPU_IS_LITTLE_ENDIAN) BOTAN_ASSERT(endian == ENDIAN_LITTLE, "Build and runtime endian match"); #elif defined(BOTAN_TARGET_CPU_IS_BIG_ENDIAN) BOTAN_ASSERT(endian == ENDIAN_BIG, "Build and runtime endian match"); #endif return endian; } std::vector<Botan::CPUID::CPUID_bits> CPUID::bit_from_string(const std::string& tok) { #if defined(BOTAN_TARGET_CPU_IS_X86_FAMILY) if(tok == "sse2" || tok == "simd") return {Botan::CPUID::CPUID_SSE2_BIT}; if(tok == "ssse3") return {Botan::CPUID::CPUID_SSSE3_BIT}; if(tok == "aesni") return {Botan::CPUID::CPUID_AESNI_BIT}; if(tok == "clmul") return {Botan::CPUID::CPUID_CLMUL_BIT}; if(tok == "avx2") return {Botan::CPUID::CPUID_AVX2_BIT}; if(tok == "sha") return {Botan::CPUID::CPUID_SHA_BIT}; #elif defined(BOTAN_TARGET_CPU_IS_PPC_FAMILY) if(tok == "altivec" || tok == "simd") return {Botan::CPUID::CPUID_ALTIVEC_BIT}; #elif defined(BOTAN_TARGET_CPU_IS_ARM_FAMILY) if(tok == "neon" || tok == "simd") return {Botan::CPUID::CPUID_ARM_NEON_BIT}; if(tok == "armv8sha1") return {Botan::CPUID::CPUID_ARM_SHA1_BIT}; if(tok == "armv8sha2") return {Botan::CPUID::CPUID_ARM_SHA2_BIT}; if(tok == "armv8aes") return {Botan::CPUID::CPUID_ARM_AES_BIT}; if(tok == "armv8pmull") return {Botan::CPUID::CPUID_ARM_PMULL_BIT}; #else BOTAN_UNUSED(tok); #endif return {}; } } <|endoftext|>
<commit_before>#ifndef POWERUP_HPP_ #define POWERUP_HPP_ #include "GraphMap.hpp" #include "vertex.hpp" #include "Actor.hpp" #include <unordered_set> #include <unordered_map> using namespace std; class Powerup : public Actor { private: unordered_set< Vertex, hash_vertex > v_set; unordered_map< Vertex, int, hash_vertex > distances; bool visited( const Vertex& v ) const; int& dist( const Vertex& v ); public: Powerup( int type ); int selectNeighbor( GraphMap* map, int x, int y ); Powerup* duplicate(); const char* getActorId(); const char* getNetId(); }; #endif<commit_msg>removed dist()<commit_after>#ifndef POWERUP_HPP_ #define POWERUP_HPP_ #include "GraphMap.hpp" #include "vertex.hpp" #include "Actor.hpp" #include <unordered_set> #include <unordered_map> #include <queue> #include <vector> using namespace std; class Powerup : public Actor { private: GraphMap* map; unordered_set< Vertex, hash_vertex > v_set; unordered_map< Vertex, int, hash_vertex > dist; bool visited( const Vertex& v ) const; int& dist( const Vertex& v ); public: Powerup( int type ); int selectNeighbor( GraphMap* map, int x, int y ); Powerup* duplicate(); const char* getActorId(); const char* getNetId(); void rank_nodes( int x, int y ); }; #endif<|endoftext|>
<commit_before>#ifdef __SSE2__ #include <emmintrin.h> #endif #ifdef __SSE4_1__ #include <smmintrin.h> #endif #include "m_half.h" #include "m_const.h" namespace m { static struct halfData { halfData(); // 1536 bytes uint32_t baseTable[512]; uint8_t shiftTable[512]; } gHalf; halfData::halfData() { for (int i = 0, e = 0; i < 256; ++i) { e = i - 127; if (e < -24) { // When magnitude of the number is really small (2^-24 or smaller), // there is no possible half-float representation for the number, so // it must be mapped to zero (or negative zero). Setting the shift // table entries to 24 will shift all mantissa bits, leaving just zero. // Base tables store zero otherwise (0x8000 for negative zero case.) baseTable[i|0x000] = 0x0000; baseTable[i|0x100] = 0x8000; shiftTable[i|0x000] = 24; shiftTable[i|0x100] = 24; } else if (e < -14) { // When the number is small (< 2^-14), the value can only be // represented using a subnormal half-float. This is the most // complex case: first, the leading 1-bit, implicitly represented // in the normalized representation, must be explicitly added, then // the resulting mantissa must be shifted rightward, or over a number // of bit-positions as determined by the exponent. Here we prefer to // shift the original mantissa bits, and add the pre-shifted 1-bit to // it. // // Note: Shifting by -e-14 will never be negative, thus ensuring // proper conversion, an alternative method is to shift by 18-e, which // depends on implementation-defined behavior of unsigned shift. baseTable[i|0x000] = (0x0400 >> (-e-14)); baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000; shiftTable[i|0x000] = -e-1; shiftTable[i|0x100] = -e-1; } else if (e <= 15) { // Normal numbers (smaller than 2^15), can be represented using half // floats, albeit with slightly less precision. The entries in the // base table are simply set to the bias-adjust exponent value, shifted // into the right position. A sign bit is added for the negative case. baseTable[i|0x000] = ((e+15) << 10); baseTable[i|0x100] = ((e+15) << 10) | 0x8000; shiftTable[i|0x000] = 13; shiftTable[i|0x100] = 13; } else if (e < 128) { // Large values (numbers less than 2^128) must be mapped to half-float // Infinity, They are too large to be represented as half-floats. In // this case the base table is set to 0x&c00 (with sign if negative) // and the mantissa is zeroed out, which is accomplished by shifting // out all mantissa bits. baseTable[i|0x000] = 0x7C00; baseTable[i|0x100] = 0xFC00; shiftTable[i|0x000] = 24; shiftTable[i|0x100] = 24; } else { // Remaining float numbers such as Infs and NaNs should stay Infs and // NaNs after conversion. The base table entries is exactly the same // as the previous case, except the mantissa-bits are to be preserved // as much as possible, thus ensuring Infs and NaNs preserve as well. baseTable[i|0x000] = 0x7C00; baseTable[i|0x100] = 0xFC00; shiftTable[i|0x000] = 13; shiftTable[i|0x100] = 13; } } } half convertToHalf(float in) { floatShape shape; shape.asFloat = in; return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] + ((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]); } #ifdef __SSE2__ union vectorShape { __m128i asVector; alignas(16) uint32_t asInt[4]; }; template <unsigned int I> static inline int extractScalar(__m128i v) { #ifdef __SSE4_1__ return _mm_extract_epi32(v, I); #else // Not pretty vectorShape shape; shape.asVector = v; return shape.asInt[I]; #endif } static __m128i convertToHalfSSE2(__m128 f) { // ~15 SSE2 ops alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu }; alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 }; alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 }; alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 }; alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 }; const __m128 maskAbsolute = *(const __m128 *)&kMaskAbsolute; const __m128 absolute = _mm_and_ps(maskAbsolute, f); const __m128 justSign = _mm_xor_ps(f, absolute); const __m128 max = *(const __m128 *)&kMax; const __m128 expInf = *(const __m128 *)&kExpInf; const __m128 infNanCase = _mm_xor_ps(expInf, absolute); const __m128 clamped = _mm_min_ps(max, absolute); const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *)&kInf32); const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *)&kMagic); const __m128 merge1 = _mm_and_ps(infNanCase, notNormal); const __m128 merge2 = _mm_andnot_ps(notNormal, scaled); const __m128 merged = _mm_or_ps(merge1, merge2); const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13); const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16); const __m128i value = _mm_or_si128(shifted, signShifted); return value; } #endif u::vector<half> convertToHalf(const float *in, size_t length) { u::vector<half> result(length); #ifdef __SSE2__ const int blocks = int(length) / 4; const int remainder = int(length) % 4; int where = 0; for (int i = 0; i < blocks; i++) { const __m128 value = _mm_load_ps(&in[where]); const __m128i convert = convertToHalfSSE2(value); result[where++] = extractScalar<0>(convert); result[where++] = extractScalar<1>(convert); result[where++] = extractScalar<2>(convert); result[where++] = extractScalar<3>(convert); } for (int i = 0; i < remainder; i++) { result[where+i] = convertToHalf(in[where+i]); where++; } #else for (size_t i = 0; i < length; i++) result[i] = convertToHalf(in[i]); #endif return result; } } <commit_msg>Documentation<commit_after>#ifdef __SSE2__ #include <emmintrin.h> #endif #ifdef __SSE4_1__ #include <smmintrin.h> #endif #include "m_half.h" #include "m_const.h" namespace m { static struct halfData { halfData(); // 1536 bytes uint32_t baseTable[512]; uint8_t shiftTable[512]; } gHalf; halfData::halfData() { for (int i = 0, e = 0; i < 256; ++i) { e = i - 127; if (e < -24) { // When magnitude of the number is really small (2^-24 or smaller), // there is no possible half-float representation for the number, so // it must be mapped to zero (or negative zero). Setting the shift // table entries to 24 will shift all mantissa bits, leaving just zero. // Base tables store zero otherwise (0x8000 for negative zero case.) baseTable[i|0x000] = 0x0000; baseTable[i|0x100] = 0x8000; shiftTable[i|0x000] = 24; shiftTable[i|0x100] = 24; } else if (e < -14) { // When the number is small (< 2^-14), the value can only be // represented using a subnormal half-float. This is the most // complex case: first, the leading 1-bit, implicitly represented // in the normalized representation, must be explicitly added, then // the resulting mantissa must be shifted rightward, or over a number // of bit-positions as determined by the exponent. Here we prefer to // shift the original mantissa bits, and add the pre-shifted 1-bit to // it. // // Note: Shifting by -e-14 will never be negative, thus ensuring // proper conversion, an alternative method is to shift by 18-e, which // depends on implementation-defined behavior of unsigned shift. baseTable[i|0x000] = (0x0400 >> (-e-14)); baseTable[i|0x100] = (0x0400 >> (-e-14)) | 0x8000; shiftTable[i|0x000] = -e-1; shiftTable[i|0x100] = -e-1; } else if (e <= 15) { // Normal numbers (smaller than 2^15), can be represented using half // floats, albeit with slightly less precision. The entries in the // base table are simply set to the bias-adjust exponent value, shifted // into the right position. A sign bit is added for the negative case. baseTable[i|0x000] = ((e+15) << 10); baseTable[i|0x100] = ((e+15) << 10) | 0x8000; shiftTable[i|0x000] = 13; shiftTable[i|0x100] = 13; } else if (e < 128) { // Large values (numbers less than 2^128) must be mapped to half-float // Infinity, They are too large to be represented as half-floats. In // this case the base table is set to 0x7C00 (with sign if negative) // and the mantissa is zeroed out, which is accomplished by shifting // out all mantissa bits. baseTable[i|0x000] = 0x7C00; baseTable[i|0x100] = 0xFC00; shiftTable[i|0x000] = 24; shiftTable[i|0x100] = 24; } else { // Remaining float numbers such as Infs and NaNs should stay Infs and // NaNs after conversion. The base table entries are exactly the same // as the previous case, except the mantissa-bits are to be preserved // as much as possible. baseTable[i|0x000] = 0x7C00; baseTable[i|0x100] = 0xFC00; shiftTable[i|0x000] = 13; shiftTable[i|0x100] = 13; } } } half convertToHalf(float in) { floatShape shape; shape.asFloat = in; return gHalf.baseTable[(shape.asInt >> 23) & 0x1FF] + ((shape.asInt & 0x007FFFFF) >> gHalf.shiftTable[(shape.asInt >> 23) & 0x1FF]); } #ifdef __SSE2__ union vectorShape { __m128i asVector; alignas(16) uint32_t asInt[4]; }; template <unsigned int I> static inline int extractScalar(__m128i v) { #ifdef __SSE4_1__ return _mm_extract_epi32(v, I); #else // Not pretty vectorShape shape; shape.asVector = v; return shape.asInt[I]; #endif } static __m128i convertToHalfSSE2(__m128 f) { // ~15 SSE2 ops alignas(16) static const uint32_t kMaskAbsolute[4] = { 0x7fffffffu, 0x7fffffffu, 0x7fffffffu, 0x7fffffffu }; alignas(16) static const uint32_t kInf32[4] = { 255 << 23, 255 << 23, 255 << 23, 255 << 23 }; alignas(16) static const uint32_t kExpInf[4] = { (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23, (255 ^ 31) << 23 }; alignas(16) static const uint32_t kMax[4] = { (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23, (127 + 16) << 23 }; alignas(16) static const uint32_t kMagic[4] = { 15 << 23, 15 << 23, 15 << 23, 15 << 23 }; const __m128 maskAbsolute = *(const __m128 *)&kMaskAbsolute; const __m128 absolute = _mm_and_ps(maskAbsolute, f); const __m128 justSign = _mm_xor_ps(f, absolute); const __m128 max = *(const __m128 *)&kMax; const __m128 expInf = *(const __m128 *)&kExpInf; const __m128 infNanCase = _mm_xor_ps(expInf, absolute); const __m128 clamped = _mm_min_ps(max, absolute); const __m128 notNormal = _mm_cmpnlt_ps(absolute, *(const __m128 *)&kInf32); const __m128 scaled = _mm_mul_ps(clamped, *(const __m128 *)&kMagic); const __m128 merge1 = _mm_and_ps(infNanCase, notNormal); const __m128 merge2 = _mm_andnot_ps(notNormal, scaled); const __m128 merged = _mm_or_ps(merge1, merge2); const __m128i shifted = _mm_srli_epi32(_mm_castps_si128(merged), 13); const __m128i signShifted = _mm_srli_epi32(_mm_castps_si128(justSign), 16); const __m128i value = _mm_or_si128(shifted, signShifted); return value; } #endif u::vector<half> convertToHalf(const float *in, size_t length) { u::vector<half> result(length); #ifdef __SSE2__ const int blocks = int(length) / 4; const int remainder = int(length) % 4; int where = 0; for (int i = 0; i < blocks; i++) { const __m128 value = _mm_load_ps(&in[where]); const __m128i convert = convertToHalfSSE2(value); result[where++] = extractScalar<0>(convert); result[where++] = extractScalar<1>(convert); result[where++] = extractScalar<2>(convert); result[where++] = extractScalar<3>(convert); } for (int i = 0; i < remainder; i++) { result[where+i] = convertToHalf(in[where+i]); where++; } #else for (size_t i = 0; i < length; i++) result[i] = convertToHalf(in[i]); #endif return result; } } <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCvRTreesWrapper.h" #include <algorithm> #include <functional> namespace otb { void dont_delete_me(void *){} CvRTreesWrapper::CvRTreesWrapper() { #ifdef OTB_OPENCV_3 m_Impl = cv::ml::RTrees::create(); #endif } CvRTreesWrapper::~CvRTreesWrapper() { } void CvRTreesWrapper::get_votes(const cv::Mat& sample, const cv::Mat& missing, CvRTreesWrapper::VotesVectorType& vote_count) const { #ifdef OTB_OPENCV_3 // TODO #else vote_count.resize(nclasses); for( int k = 0; k < ntrees; k++ ) { CvDTreeNode* predicted_node = trees[k]->predict( sample, missing ); int class_idx = predicted_node->class_idx; CV_Assert( 0 <= class_idx && class_idx < nclasses ); ++vote_count[class_idx]; } #endif } float CvRTreesWrapper::predict_margin(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); // We only sort the 2 greatest elements std::nth_element(classVotes.begin(), classVotes.begin()+1, classVotes.end(), std::greater<unsigned int>()); float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees; return margin; #endif } float CvRTreesWrapper::predict_confidence(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); unsigned int max_votes = *(std::max_element(classVotes.begin(), classVotes.end())); float confidence = static_cast<float>(max_votes)/ntrees; return confidence; #endif } #ifdef OTB_OPENCV_3 #define OTB_CV_WRAP_IMPL(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(type val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_REF(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(const type &val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \ const type& CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } // TODO : wrap all method used OTB_CV_WRAP_IMPL(int, MaxCategories) OTB_CV_WRAP_IMPL(int, MaxDepth) OTB_CV_WRAP_IMPL(int, MinSampleCount) OTB_CV_WRAP_IMPL(bool, UseSurrogates) OTB_CV_WRAP_IMPL(int, CVFolds) OTB_CV_WRAP_IMPL(bool, Use1SERule) OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree) OTB_CV_WRAP_IMPL(float, RegressionAccuracy) OTB_CV_WRAP_IMPL(bool, CalculateVarImportance) OTB_CV_WRAP_IMPL(int, ActiveVarCount) OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors) OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets) int CvRTreesWrapper::getVarCount() const { return m_Impl->getVarCount(); } bool CvRTreesWrapper::isTrained() const { return m_Impl->isTrained(); } bool CvRTreesWrapper::isClassifier() const { return m_Impl->isClassifier(); } cv::Mat CvRTreesWrapper::getVarImportance() const { return m_Impl->getVarImportance(); } cv::String CvRTreesWrapper::getDefaultName () const { return m_Impl->getDefaultName(); } void CvRTreesWrapper::read (const cv::FileNode &fn) { m_Impl->read(fn); } void CvRTreesWrapper::write (cv::FileStorage &fs) const { m_Impl->write(fs); } void CvRTreesWrapper::save (const cv::String &filename) const { m_Impl->save(filename); } bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses) { return m_Impl->train(samples,layout, responses); } bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags ) { return m_Impl->train(trainData, flags); } float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const { return m_Impl->predict(samples, results, flags); } cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create() { return cv::makePtr<CvRTreesWrapper>(); } #undef OTB_CV_WRAP_IMPL #undef OTB_CV_WRAP_IMPL_REF #undef OTB_CV_WRAP_IMPL_CSTREF_GET #endif } <commit_msg>WRG: unused variables<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbCvRTreesWrapper.h" #include <algorithm> #include <functional> namespace otb { void dont_delete_me(void *){} CvRTreesWrapper::CvRTreesWrapper() { #ifdef OTB_OPENCV_3 m_Impl = cv::ml::RTrees::create(); #endif } CvRTreesWrapper::~CvRTreesWrapper() { } void CvRTreesWrapper::get_votes(const cv::Mat& sample, const cv::Mat& missing, CvRTreesWrapper::VotesVectorType& vote_count) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; (void) vote_count; // TODO #else vote_count.resize(nclasses); for( int k = 0; k < ntrees; k++ ) { CvDTreeNode* predicted_node = trees[k]->predict( sample, missing ); int class_idx = predicted_node->class_idx; CV_Assert( 0 <= class_idx && class_idx < nclasses ); ++vote_count[class_idx]; } #endif } float CvRTreesWrapper::predict_margin(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); // We only sort the 2 greatest elements std::nth_element(classVotes.begin(), classVotes.begin()+1, classVotes.end(), std::greater<unsigned int>()); float margin = static_cast<float>(classVotes[0]-classVotes[1])/ntrees; return margin; #endif } float CvRTreesWrapper::predict_confidence(const cv::Mat& sample, const cv::Mat& missing) const { #ifdef OTB_OPENCV_3 (void) sample; (void) missing; // TODO return 0.; #else // Sanity check (division by ntrees later on) if(ntrees == 0) { return 0.; } std::vector<unsigned int> classVotes; this->get_votes(sample, missing, classVotes); unsigned int max_votes = *(std::max_element(classVotes.begin(), classVotes.end())); float confidence = static_cast<float>(max_votes)/ntrees; return confidence; #endif } #ifdef OTB_OPENCV_3 #define OTB_CV_WRAP_IMPL(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(type val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_REF(type,name) \ type CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } \ void CvRTreesWrapper::set##name(const type &val) \ { m_Impl->set##name(val); } #define OTB_CV_WRAP_IMPL_CSTREF_GET(type, name) \ const type& CvRTreesWrapper::get##name() const \ { return m_Impl->get##name(); } // TODO : wrap all method used OTB_CV_WRAP_IMPL(int, MaxCategories) OTB_CV_WRAP_IMPL(int, MaxDepth) OTB_CV_WRAP_IMPL(int, MinSampleCount) OTB_CV_WRAP_IMPL(bool, UseSurrogates) OTB_CV_WRAP_IMPL(int, CVFolds) OTB_CV_WRAP_IMPL(bool, Use1SERule) OTB_CV_WRAP_IMPL(bool,TruncatePrunedTree) OTB_CV_WRAP_IMPL(float, RegressionAccuracy) OTB_CV_WRAP_IMPL(bool, CalculateVarImportance) OTB_CV_WRAP_IMPL(int, ActiveVarCount) OTB_CV_WRAP_IMPL_REF(cv::Mat, Priors) OTB_CV_WRAP_IMPL_REF(cv::TermCriteria, TermCriteria) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Roots) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Node>, Nodes) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<cv::ml::DTrees::Split>, Splits) OTB_CV_WRAP_IMPL_CSTREF_GET(std::vector<int>, Subsets) int CvRTreesWrapper::getVarCount() const { return m_Impl->getVarCount(); } bool CvRTreesWrapper::isTrained() const { return m_Impl->isTrained(); } bool CvRTreesWrapper::isClassifier() const { return m_Impl->isClassifier(); } cv::Mat CvRTreesWrapper::getVarImportance() const { return m_Impl->getVarImportance(); } cv::String CvRTreesWrapper::getDefaultName () const { return m_Impl->getDefaultName(); } void CvRTreesWrapper::read (const cv::FileNode &fn) { m_Impl->read(fn); } void CvRTreesWrapper::write (cv::FileStorage &fs) const { m_Impl->write(fs); } void CvRTreesWrapper::save (const cv::String &filename) const { m_Impl->save(filename); } bool CvRTreesWrapper::train(cv::InputArray samples, int layout, cv::InputArray responses) { return m_Impl->train(samples,layout, responses); } bool CvRTreesWrapper::train( const cv::Ptr<cv::ml::TrainData>& trainData, int flags ) { return m_Impl->train(trainData, flags); } float CvRTreesWrapper::predict (cv::InputArray samples, cv::OutputArray results, int flags) const { return m_Impl->predict(samples, results, flags); } cv::Ptr<CvRTreesWrapper> CvRTreesWrapper::create() { return cv::makePtr<CvRTreesWrapper>(); } #undef OTB_CV_WRAP_IMPL #undef OTB_CV_WRAP_IMPL_REF #undef OTB_CV_WRAP_IMPL_CSTREF_GET #endif } <|endoftext|>
<commit_before> //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <string> #include <sstream> #include <list> #include <map> #include <set> #include "DayTime.hpp" #include "GPSWeekSecond.hpp" #include "TimeConstants.hpp" #include "Exception.hpp" #include "CommandOption.hpp" #include "CommandOptionParser.hpp" #include "DeviceStream.hpp" #include "StringUtils.hpp" #include "InOutFramework.hpp" #include "ObsUtils.hpp" #include "MDPStream.hpp" #include "MDPNavSubframe.hpp" #include "MDPObsEpoch.hpp" #include "MDPSelftestStatus.hpp" using namespace std; using namespace gpstk; using namespace gpstk::StringUtils; class MDPEdit : public InOutFramework<MDPStream, MDPStream> { public: MDPEdit(const string& applName) throw() : InOutFramework<MDPStream, MDPStream>( applName, "Edits a MDP file based on various criteria.") {} bool initialize(int argc, char *argv[]) throw() { // set up options. note that nothing is required CommandOptionWithAnyArg startOpt('s',"start","Throw out data before" " this time. Format as string: \"yyyy ddd HH:MM:SS\" "); CommandOptionWithAnyArg endOpt('e',"end","Throw out data after this" " time. Format as string: \"yyyy ddd HH:MM:SS\" "); CommandOptionWithNumberArg prnOpt('p',"PRN","Throw out obs data from" " this PRN. Repeat option for mutiple SVs."); CommandOptionWithNumberArg recordStartOpt('\0',"record-start","Throw" " out data before this record number."); CommandOptionWithNumberArg recordEndOpt('\0',"record-end","Throw out" " data after this record number."); CommandOptionNoArg obsOpt('O',"no-obs","Remove all obs messages."); CommandOptionNoArg navOpt('N',"no-nav","Remove all nav messages."); CommandOptionNoArg pvtOpt('P',"no-pvt","Remove all pvt messages."); CommandOptionNoArg stsOpt('S',"no-sts","Remove all self test " "status messages."); if (!InOutFramework<MDPStream, MDPStream>::initialize(argc,argv)) return false; // get any PRNs to toss for (int index = 0; index < prnOpt.getCount(); index++ ) { int prn = asInt(prnOpt.getValue()[index]); if ((prn < 1)||(prn > gpstk::MAX_PRN)) { cout << "\n You entered an invalid PRN." << "\n Exiting.\n\n"; return false; } else { prnSetToToss.insert(prn); if (debugLevel || verboseLevel) cout << "Throwing out data from PRN " << prn << endl; } } // get any time limits if (startOpt.getCount()) { tStart.setToString(startOpt.getValue().front().c_str(), "%Y %j %H:%M:%S"); if (debugLevel) cout << "Throwing out data before " << tStart << endl; } else { tStart = DayTime::BEGINNING_OF_TIME; if (debugLevel || verboseLevel) cout << "No start time given.\n"; } if (endOpt.getCount()) { tEnd.setToString(endOpt.getValue().front().c_str(),"%Y %j %H:%M:%S"); if (debugLevel || verboseLevel) cout << "Throwing out data after " << tEnd << endl; } else { tEnd = DayTime::END_OF_TIME; if (debugLevel || verboseLevel) cout << "No end time given.\n"; } if (recordStartOpt.getCount()) { recordStart = asInt(recordStartOpt.getValue().front()); if (debugLevel || verboseLevel) cout << "Throwing out data before record number " << recordStart << endl; } if (recordEndOpt.getCount()) { recordEnd = asInt(recordEndOpt.getValue().front()); if (debugLevel || verboseLevel) cout << "Throwing out data after record number " << recordStart << endl; } // see if any message types should be removed noObs = noNav = noPvt = noSts = false; if (obsOpt.getCount()) { noObs = true; if (debugLevel || verboseLevel) cout << "Removing obs messages.\n"; } if (navOpt.getCount()) { noNav = true; if (debugLevel || verboseLevel) cout << "Removing nav messages.\n"; } if (pvtOpt.getCount()) { noPvt = true; if (debugLevel || verboseLevel) cout << "Removing pvt messages.\n"; } if (stsOpt.getCount()) { noSts = true; if (debugLevel || verboseLevel) cout << "Removing self test status messages.\n"; } return true; } protected: virtual void spinUp() {} virtual void process() { msgCount=0; die = false; while (!input.eof()) { input >> header; if (!input) break; else if (header.time > tEnd) return; else if (header.time < tStart) continue; msgCount++; if (msgCount == 1 && debugLevel) cout << "First message at " << header.time << endl; if (verboseLevel > 4 || debugLevel > 3) cout << "Record: " << input.recordNumber << ", message: " << msgCount << ":" << endl; switch (input.header.id) { case gpstk::MDPObsEpoch::myId: if (!noObs) { MDPObsEpoch obs; input >> obs; if (obs) { if (prnSetToToss.size()) { unsigned thisPRN = obs.prn; if (!prnSetToToss.count(thisPRN)) { output << obs; if (debugLevel > 2) { cout << " Writing obs message:\n"; obs.dump(cout); } } else if (debugLevel > 2) cout << " Not writing obs message for PRN " << thisPRN << endl; } else { if (debugLevel > 2) { cout << " Writing obs message:\n"; obs.dump(cout); } output << obs; } } else if (debugLevel > 2) { cout << " Tossing obs message:\n"; obs.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring obs message from record " << input.recordNumber << endl; } break; case gpstk::MDPPVTSolution::myId: if (!noPvt) { MDPPVTSolution pvt; input >> pvt; if (pvt) output << pvt; if (debugLevel > 2) { cout << " Writing pvt message:\n"; pvt.dump(cout); } else if (debugLevel > 2) { cout << " Tossing pvt message:\n"; pvt.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring pvt message from record " << input.recordNumber << endl; } break; case gpstk::MDPNavSubframe::myId: if (!noNav) { MDPNavSubframe nav; input >> nav; if (nav) output << nav; if (debugLevel > 2) { cout << " Writing nav message:\n"; nav.dump(cout); } else if (debugLevel > 2) { cout << " Tossing nav message:\n"; nav.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring nav message from record " << input.recordNumber << endl; } break; case gpstk::MDPSelftestStatus::myId: if (!noSts) { gpstk::MDPSelftestStatus sts; input >> sts; if (sts) output << sts; if (debugLevel > 2) { cout << " Writing self test status message:\n"; sts.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring status message from record " << input.recordNumber << endl; } break; } // switch (input.header.id) } // while (!input.eof()) timeToDie = true; } // virtual void process() virtual void shutDown() { if (verboseLevel) cout << "Doneskies.\n"; } private: bool noObs, noNav, noPvt, noSts, die; DayTime tStart, tEnd; set<int> prnSetToToss; unsigned int recordStart, recordEnd; unsigned long msgCount, fcErrorCount; unsigned short firstFC, lastFC; MDPHeader header; }; int main(int argc, char *argv[]) { MDPEdit crap(argv[0]); if (!crap.initialize(argc, argv)) exit(0); crap.run(); } <commit_msg>Now filters messages based on record number.<commit_after> //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include <string> #include <sstream> #include <list> #include <map> #include <set> #include "DayTime.hpp" #include "GPSWeekSecond.hpp" #include "TimeConstants.hpp" #include "Exception.hpp" #include "CommandOption.hpp" #include "CommandOptionParser.hpp" #include "DeviceStream.hpp" #include "StringUtils.hpp" #include "InOutFramework.hpp" #include "ObsUtils.hpp" #include "MDPStream.hpp" #include "MDPNavSubframe.hpp" #include "MDPObsEpoch.hpp" #include "MDPSelftestStatus.hpp" using namespace std; using namespace gpstk; using namespace gpstk::StringUtils; class MDPEdit : public InOutFramework<MDPStream, MDPStream> { public: MDPEdit(const string& applName) throw() : InOutFramework<MDPStream, MDPStream>( applName, "Edits a MDP file based on various criteria.") {} bool initialize(int argc, char *argv[]) throw() { // set up options. note that nothing is required CommandOptionWithAnyArg startOpt('s',"start","Throw out data before" " this time. Format as string: \"yyyy ddd HH:MM:SS\" "); CommandOptionWithAnyArg endOpt('e',"end","Throw out data after this" " time. Format as string: \"yyyy ddd HH:MM:SS\" "); CommandOptionWithNumberArg prnOpt('p',"PRN","Throw out obs data from" " this PRN. Repeat option for mutiple SVs."); CommandOptionWithNumberArg recordStartOpt('\0',"record-start","Throw" " out data before this record number."); CommandOptionWithNumberArg recordEndOpt('\0',"record-end","Throw out" " data after this record number."); CommandOptionNoArg obsOpt('O',"no-obs","Remove all obs messages."); CommandOptionNoArg navOpt('N',"no-nav","Remove all nav messages."); CommandOptionNoArg pvtOpt('P',"no-pvt","Remove all pvt messages."); CommandOptionNoArg stsOpt('S',"no-sts","Remove all self test " "status messages."); if (!InOutFramework<MDPStream, MDPStream>::initialize(argc,argv)) return false; // get any PRNs to toss for (int index = 0; index < prnOpt.getCount(); index++ ) { int prn = asInt(prnOpt.getValue()[index]); if ((prn < 1)||(prn > gpstk::MAX_PRN)) { cout << "\n You entered an invalid PRN." << "\n Exiting.\n\n"; return false; } else { prnSetToToss.insert(prn); if (debugLevel || verboseLevel) cout << "Throwing out data from PRN " << prn << endl; } } // get any time limits if (startOpt.getCount()) { tStart.setToString(startOpt.getValue().front().c_str(), "%Y %j %H:%M:%S"); if (debugLevel) cout << "Throwing out data before " << tStart << endl; } else { tStart = DayTime::BEGINNING_OF_TIME; if (debugLevel || verboseLevel) cout << "No start time given.\n"; } if (endOpt.getCount()) { tEnd.setToString(endOpt.getValue().front().c_str(),"%Y %j %H:%M:%S"); if (debugLevel || verboseLevel) cout << "Throwing out data after " << tEnd << endl; } else { tEnd = DayTime::END_OF_TIME; if (debugLevel || verboseLevel) cout << "No end time given.\n"; } recordStart = recordEnd = 0; if (recordStartOpt.getCount()) { recordStart = asInt(recordStartOpt.getValue().front()); if (debugLevel || verboseLevel) cout << "Throwing out data before record number " << recordStart << endl; } if (recordEndOpt.getCount()) { recordEnd = asInt(recordEndOpt.getValue().front()); if (debugLevel || verboseLevel) cout << "Throwing out data after record number " << recordEnd << endl; } // see if any message types should be removed noObs = noNav = noPvt = noSts = false; if (obsOpt.getCount()) { noObs = true; if (debugLevel || verboseLevel) cout << "Removing obs messages.\n"; } if (navOpt.getCount()) { noNav = true; if (debugLevel || verboseLevel) cout << "Removing nav messages.\n"; } if (pvtOpt.getCount()) { noPvt = true; if (debugLevel || verboseLevel) cout << "Removing pvt messages.\n"; } if (stsOpt.getCount()) { noSts = true; if (debugLevel || verboseLevel) cout << "Removing self test status messages.\n"; } return true; } protected: virtual void spinUp() {} virtual void process() { msgCount=0; die = false; while (!input.eof()) { input >> header; if (!input) break; else if (header.time > tEnd) return; else if (recordEnd && (input.recordNumber > recordEnd)) return; else if (header.time < tStart) continue; else if (recordStart && (input.recordNumber < recordStart)) continue; msgCount++; if (msgCount == 1 && debugLevel) cout << "First message at " << header.time << endl; if (verboseLevel > 4 || debugLevel > 3) cout << "Record: " << input.recordNumber << ", message: " << msgCount << ":" << endl; switch (input.header.id) { case gpstk::MDPObsEpoch::myId: if (!noObs) { MDPObsEpoch obs; input >> obs; if (obs) { if (prnSetToToss.size()) { unsigned thisPRN = obs.prn; if (!prnSetToToss.count(thisPRN)) { output << obs; if (debugLevel > 2) { cout << " Writing obs message:\n"; obs.dump(cout); } } else if (debugLevel > 2) cout << " Not writing obs message for PRN " << thisPRN << endl; } else { if (debugLevel > 2) { cout << " Writing obs message:\n"; obs.dump(cout); } output << obs; } } else if (debugLevel > 2) { cout << " Tossing obs message:\n"; obs.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring obs message from record " << input.recordNumber << endl; } break; case gpstk::MDPPVTSolution::myId: if (!noPvt) { MDPPVTSolution pvt; input >> pvt; if (pvt) output << pvt; if (debugLevel > 2) { cout << " Writing pvt message:\n"; pvt.dump(cout); } else if (debugLevel > 2) { cout << " Tossing pvt message:\n"; pvt.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring pvt message from record " << input.recordNumber << endl; } break; case gpstk::MDPNavSubframe::myId: if (!noNav) { MDPNavSubframe nav; input >> nav; if (nav) output << nav; if (debugLevel > 2) { cout << " Writing nav message:\n"; nav.dump(cout); } else if (debugLevel > 2) { cout << " Tossing nav message:\n"; nav.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring nav message from record " << input.recordNumber << endl; } break; case gpstk::MDPSelftestStatus::myId: if (!noSts) { gpstk::MDPSelftestStatus sts; input >> sts; if (sts) output << sts; if (debugLevel > 2) { cout << " Writing self test status message:\n"; sts.dump(cout); } } else if (debugLevel > 3) { cout << " Ignoring status message from record " << input.recordNumber << endl; } break; } // switch (input.header.id) } // while (!input.eof()) timeToDie = true; } // virtual void process() virtual void shutDown() { if (verboseLevel) cout << "Doneskies.\n"; } private: bool noObs, noNav, noPvt, noSts, die; DayTime tStart, tEnd; set<int> prnSetToToss; unsigned int recordStart, recordEnd; unsigned long msgCount, fcErrorCount; unsigned short firstFC, lastFC; MDPHeader header; }; int main(int argc, char *argv[]) { MDPEdit crap(argv[0]); if (!crap.initialize(argc, argv)) exit(0); crap.run(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestingConfig.h" #include "mitkSceneIO.h" #include "mitkStandaloneDataStorage.h" #include "mitkStandardFileLocations.h" #include "mitkDataNodeFactory.h" #include "mitkCoreObjectFactory.h" #include "mitkBaseData.h" #include "mitkImage.h" #include "mitkSurface.h" #include "mitkPointSet.h" #include "Poco/File.h" #include "Poco/TemporaryFile.h" #ifndef WIN32 #include <ulimit.h> #include <errno.h> #endif class SceneIOTestClass { public: static mitk::BaseData::Pointer LoadBaseData(const std::string& filename) { mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { factory->SetFileName( filename ); factory->Update(); if(factory->GetNumberOfOutputs()<1) { MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'"); } mitk::DataNode::Pointer node = factory->GetOutput( 0 ); return node->GetData(); } catch ( itk::ExceptionObject & e ) { MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what()); } } static mitk::Image::Pointer LoadImage(const std::string& filename) { mitk::BaseData::Pointer basedata = LoadBaseData( filename ); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(basedata.GetPointer()); if(image.IsNull()) { MITK_TEST_FAILED_MSG(<< "Test image '" << filename << "' was not loaded as an mitk::Image"); } return image; } static mitk::Surface::Pointer LoadSurface(const std::string& filename) { mitk::BaseData::Pointer basedata = LoadBaseData( filename ); mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(basedata.GetPointer()); if(surface.IsNull()) { MITK_TEST_FAILED_MSG(<< "Test surface '" << filename << "' was not loaded as an mitk::Surface"); } return surface; } static mitk::PointSet::Pointer CreatePointSet() { mitk::PointSet::Pointer ps = mitk::PointSet::New(); mitk::PointSet::PointType p; mitk::FillVector3D(p, 1.0, -2.0, 33.0); ps->SetPoint(0, p); mitk::FillVector3D(p, 100.0, -200.0, 3300.0); ps->SetPoint(1, p); mitk::FillVector3D(p, 2.0, -3.0, 22.0); ps->SetPoint(2, p, mitk::PTCORNER); // add point spec //mitk::FillVector3D(p, -2.0, -2.0, -2.22); //ps->SetPoint(0, p, 1); // ID 0 in timestep 1 //mitk::FillVector3D(p, -1.0, -1.0, -11.22); //ps->SetPoint(1, p, 1); // ID 1 in timestep 1 //mitk::FillVector3D(p, 1000.0, 1000.0, 1122.22); //ps->SetPoint(11, p, mitk::PTCORNER, 2); // ID 11, point spec, timestep 2 return ps; } static void FillStorage(mitk::DataStorage* storage, std::string imageName, std::string surfaceName) { mitk::Image::Pointer image = LoadImage(imageName); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image Pic3D.pic.gz"); image->SetProperty("image type", mitk::StringProperty::New("test image") ); image->SetProperty("greetings", mitk::StringProperty::New("to mom") ); mitk::DataNode::Pointer imagenode = mitk::DataNode::New(); imagenode->SetData( image ); imagenode->SetName( "Pic3D" ); storage->Add( imagenode ); mitk::DataNode::Pointer imagechildnode = mitk::DataNode::New(); imagechildnode->SetData( image ); imagechildnode->SetName( "Pic3D again" ); storage->Add( imagechildnode, imagenode ); mitk::Surface::Pointer surface = LoadSurface(surfaceName ); MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface binary.stl"); surface->SetProperty("surface type", mitk::StringProperty::New("test surface") ); surface->SetProperty("greetings", mitk::StringProperty::New("to dad") ); mitk::DataNode::Pointer surfacenode = mitk::DataNode::New(); surfacenode->SetData( surface ); surfacenode->SetName( "binary" ); storage->Add( surfacenode ); mitk::PointSet::Pointer ps = CreatePointSet(); mitk::DataNode::Pointer psenode = mitk::DataNode::New(); psenode->SetData( ps ); psenode->SetName( "points" ); storage->Add( psenode ); } static void VerifyStorage(mitk::DataStorage* storage) { //TODO the Surface and PointSet are uncommented until the material property is saved properly mitk::DataNode::Pointer imagenode = storage->GetNamedNode("Pic3D"); MITK_TEST_CONDITION_REQUIRED(imagenode.IsNotNull(),"Get previously stored image node"); //Image std::string testString(""); imagenode->GetStringProperty("image type", testString); MITK_TEST_CONDITION_REQUIRED(!(testString == "test image") ,"Get StringProperty from previously stored image node"); imagenode->GetStringProperty("greetings", testString); MITK_TEST_CONDITION_REQUIRED(!(testString == "to mom") ,"Get another StringProperty from previously stored image node"); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(imagenode->GetData()); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image from Datastorage"); //Get Image child node mitk::DataNode::Pointer imagechildnode = storage->GetNamedNode("Pic3D again"); mitk::DataStorage::SetOfObjects::ConstPointer objects = storage->GetSources(imagechildnode); MITK_TEST_CONDITION_REQUIRED(objects->Size() == 1,"Check size of image child nodes source list"); MITK_TEST_CONDITION_REQUIRED(objects->ElementAt(0) == imagenode,"Check for right parent node"); mitk::Image::Pointer imagechild = dynamic_cast<mitk::Image*>(imagechildnode->GetData()); MITK_TEST_CONDITION_REQUIRED(imagechild.IsNotNull(),"Loading child test image from Datastorage"); //Surface mitk::DataNode::Pointer surfacenode = storage->GetNamedNode("binary"); MITK_TEST_CONDITION_REQUIRED(surfacenode.IsNotNull(),"Get previously stored surface node"); surfacenode->GetStringProperty("surface type", testString); MITK_TEST_CONDITION_REQUIRED(!(testString.compare("test surface") == 0) ,"Get StringProperty from previously stored surface node"); surfacenode->GetStringProperty("greetings", testString); MITK_TEST_CONDITION_REQUIRED(!(testString.compare("to dad") == 0) ,"Get another StringProperty from previously stored surface node"); mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(surfacenode->GetData()); MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface from Datastorage"); //PointSet mitk::DataNode::Pointer pointsnode = storage->GetNamedNode("points"); MITK_TEST_CONDITION_REQUIRED(pointsnode.IsNotNull(),"Get previously stored PointSet node"); mitk::PointSet::Pointer pointset = dynamic_cast<mitk::PointSet*>(pointsnode->GetData()); MITK_TEST_CONDITION_REQUIRED(pointset.IsNotNull(),"Loading test PointSet from Datastorage"); mitk::PointSet::PointType p = pointset->GetPoint(0); MITK_TEST_CONDITION_REQUIRED(p[0] == 1.0 && p[1] == -2.0 && p[2] == 33.0, "Test Pointset entry 0 after loading"); p = pointset->GetPoint(1); MITK_TEST_CONDITION_REQUIRED(p[0] == 100.0 && p[1] == -200.0 && p[2] == 3300.0, "Test Pointset entry 1 after loading"); p = pointset->GetPoint(2); MITK_TEST_CONDITION_REQUIRED(p[0] == 2.0 && p[1] == -3.0 && p[2] == 22.0, "Test Pointset entry 2 after loading"); } }; // end test helper class int mitkSceneIOTest(int argc, char* argv[]) { MITK_TEST_BEGIN("SceneIO") std::string sceneFileName; for (unsigned int i = 0; i < 1; ++i) // TODO change to " < 2" to check cases where file system would be full { if (i == 1) { // call ulimit and restrict maximum file size to something small #ifndef WIN32 errno = 0; long int value = ulimit(UL_SETFSIZE, 1); MITK_TEST_CONDITION_REQUIRED( value != -1, "ulimit() returned with errno = " << errno ); #else continue; #endif } // create a data storage and fill it with some test data mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); MITK_TEST_CONDITION_REQUIRED(sceneIO.IsNotNull(),"SceneIO instantiation") mitk::DataStorage::Pointer storage = mitk::StandaloneDataStorage::New().GetPointer(); MITK_TEST_CONDITION_REQUIRED(storage.IsNotNull(),"StandaloneDataStorage instantiation"); std::cout << "ImageName: " << argv[1] << std::endl; std::cout << "SurfaceName: " << argv[2] << std::endl; SceneIOTestClass::FillStorage(storage, argv[1], argv[2]); // attempt to save it Poco::Path newname( Poco::TemporaryFile::tempName() ); sceneFileName = std::string( MITK_TEST_OUTPUT_DIR ) + Poco::Path::separator() + newname.getFileName() + ".zip"; MITK_TEST_CONDITION_REQUIRED( sceneIO->SaveScene( storage->GetAll(), storage, sceneFileName), "Saving scene file '" << sceneFileName << "'"); // test if no errors were reported mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (failedNodes.IsNotNull() && !failedNodes->empty()) { MITK_TEST_OUTPUT( << "The following nodes could not be serialized:"); for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { MITK_TEST_OUTPUT_NO_ENDL( << " - "); if ( mitk::BaseData* data =(*iter)->GetData() ) { MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass()); } else { MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)"); } MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'"); // \TODO: should we fail the test case if failed properties exist? } } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (failedProperties.IsNotNull() && !failedProperties->IsEmpty()) { MITK_TEST_OUTPUT( << "The following properties could not be serialized:"); const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { MITK_TEST_OUTPUT( << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'"); // \TODO: should we fail the test case if failed properties exist? } } MITK_TEST_CONDITION_REQUIRED(failedProperties.IsNotNull() && failedProperties->IsEmpty(), "Checking if all properties have been saved.") MITK_TEST_CONDITION_REQUIRED(failedNodes.IsNotNull() && failedNodes->empty(), "Checking if all nodes have been saved.") //Now do the loading part sceneIO = mitk::SceneIO::New(); //Load scene into the datastorage and clean the DS first MITK_TEST_OUTPUT(<< "Loading scene again"); storage = sceneIO->LoadScene(sceneFileName,storage,true); // test if no errors were reported failedNodes = sceneIO->GetFailedNodes(); if (failedNodes.IsNotNull() && !failedNodes->empty()) { MITK_TEST_OUTPUT( << "The following nodes could not be serialized:"); for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { MITK_TEST_OUTPUT_NO_ENDL( << " - "); if ( mitk::BaseData* data =(*iter)->GetData() ) { MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass()); } else { MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)"); } MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'"); // \TODO: should we fail the test case if failed properties exist? } } failedProperties = sceneIO->GetFailedProperties(); if (failedProperties.IsNotNull() && !failedProperties->IsEmpty()) { MITK_TEST_OUTPUT( << "The following properties could not be serialized:"); const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { MITK_TEST_OUTPUT( << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'"); // \TODO: should we fail the test case if failed properties exist? } } // check if data storage content has been restored correctly SceneIOTestClass::VerifyStorage(storage); } // if no sub-test failed remove the scene file, otherwise it is kept for debugging purposes if ( mitk::TestManager::GetInstance()->NumberOfFailedTests() == 0 ) { Poco::File pocoSceneFile( sceneFileName ); MITK_TEST_CONDITION_REQUIRED( pocoSceneFile.exists(), "Checking if scene file still exists before cleaning up." ) pocoSceneFile.remove(); } MITK_TEST_END(); } <commit_msg>Enhancing mitkSceneIOTest<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision: 1.12 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkTestingMacros.h" #include "mitkTestingConfig.h" #include "mitkSceneIO.h" #include "mitkStandaloneDataStorage.h" #include "mitkStandardFileLocations.h" #include "mitkDataNodeFactory.h" #include "mitkCoreObjectFactory.h" #include "mitkBaseData.h" #include "mitkImage.h" #include "mitkSurface.h" #include "mitkPointSet.h" #include "Poco/File.h" #include "Poco/TemporaryFile.h" #ifndef WIN32 #include <ulimit.h> #include <errno.h> #endif class SceneIOTestClass { public: static mitk::BaseData::Pointer LoadBaseData(const std::string& filename) { mitk::DataNodeFactory::Pointer factory = mitk::DataNodeFactory::New(); try { factory->SetFileName( filename ); factory->Update(); if(factory->GetNumberOfOutputs()<1) { MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'"); } mitk::DataNode::Pointer node = factory->GetOutput( 0 ); return node->GetData(); } catch ( itk::ExceptionObject & e ) { MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what()); } } static mitk::Image::Pointer LoadImage(const std::string& filename) { mitk::BaseData::Pointer basedata = LoadBaseData( filename ); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(basedata.GetPointer()); if(image.IsNull()) { MITK_TEST_FAILED_MSG(<< "Test image '" << filename << "' was not loaded as an mitk::Image"); } return image; } static mitk::Surface::Pointer LoadSurface(const std::string& filename) { mitk::BaseData::Pointer basedata = LoadBaseData( filename ); mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(basedata.GetPointer()); if(surface.IsNull()) { MITK_TEST_FAILED_MSG(<< "Test surface '" << filename << "' was not loaded as an mitk::Surface"); } return surface; } static mitk::PointSet::Pointer CreatePointSet() { mitk::PointSet::Pointer ps = mitk::PointSet::New(); mitk::PointSet::PointType p; mitk::FillVector3D(p, 1.0, -2.0, 33.0); ps->SetPoint(0, p); mitk::FillVector3D(p, 100.0, -200.0, 3300.0); ps->SetPoint(1, p); mitk::FillVector3D(p, 2.0, -3.0, 22.0); ps->SetPoint(2, p, mitk::PTCORNER); // add point spec //mitk::FillVector3D(p, -2.0, -2.0, -2.22); //ps->SetPoint(0, p, 1); // ID 0 in timestep 1 //mitk::FillVector3D(p, -1.0, -1.0, -11.22); //ps->SetPoint(1, p, 1); // ID 1 in timestep 1 //mitk::FillVector3D(p, 1000.0, 1000.0, 1122.22); //ps->SetPoint(11, p, mitk::PTCORNER, 2); // ID 11, point spec, timestep 2 return ps; } static void FillStorage(mitk::DataStorage* storage, std::string imageName, std::string surfaceName) { mitk::Image::Pointer image = LoadImage(imageName); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image Pic3D.pic.gz"); image->SetProperty("image type", mitk::StringProperty::New("test image") ); image->SetProperty("greetings", mitk::StringProperty::New("to mom") ); image->SetProperty("test_float_property", mitk::FloatProperty::New(-2.57f)); mitk::DataNode::Pointer imagenode = mitk::DataNode::New(); imagenode->SetData( image ); imagenode->SetName( "Pic3D" ); storage->Add( imagenode ); mitk::DataNode::Pointer imagechildnode = mitk::DataNode::New(); imagechildnode->SetData( image ); imagechildnode->SetName( "Pic3D again" ); storage->Add( imagechildnode, imagenode ); mitk::Surface::Pointer surface = LoadSurface(surfaceName ); MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface binary.stl"); surface->SetProperty("surface type", mitk::StringProperty::New("test surface") ); surface->SetProperty("greetings", mitk::StringProperty::New("to dad") ); mitk::DataNode::Pointer surfacenode = mitk::DataNode::New(); surfacenode->SetData( surface ); surfacenode->SetName( "binary" ); storage->Add( surfacenode ); mitk::PointSet::Pointer ps = CreatePointSet(); mitk::DataNode::Pointer psenode = mitk::DataNode::New(); psenode->SetData( ps ); psenode->SetName( "points" ); storage->Add( psenode ); } static void VerifyStorage(mitk::DataStorage* storage) { //TODO the Surface and PointSet are uncommented until the material property is saved properly mitk::DataNode::Pointer imagenode = storage->GetNamedNode("Pic3D"); MITK_TEST_CONDITION_REQUIRED(imagenode.IsNotNull(),"Get previously stored image node"); mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(imagenode->GetData()); MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image from Datastorage"); //Image std::string testString(""); float testFloatValue = 0.0f; mitk::PropertyList::Pointer imagePropList = image->GetPropertyList(); imagePropList->GetStringProperty("image type", testString); MITK_TEST_CONDITION(testString == "test image" ,"Get StringProperty from previously stored image"); imagePropList->GetStringProperty("greetings", testString); MITK_TEST_CONDITION(testString == "to mom" ,"Get another StringProperty from previously stored image"); imagePropList->GetFloatProperty("test_float_property", testFloatValue); MITK_TEST_CONDITION(testFloatValue == -2.57f, "Get FloatProperty from previously stored image.") //Get Image child node mitk::DataNode::Pointer imagechildnode = storage->GetNamedNode("Pic3D again"); mitk::DataStorage::SetOfObjects::ConstPointer objects = storage->GetSources(imagechildnode); MITK_TEST_CONDITION_REQUIRED(objects->Size() == 1,"Check size of image child nodes source list"); MITK_TEST_CONDITION_REQUIRED(objects->ElementAt(0) == imagenode,"Check for right parent node"); mitk::Image::Pointer imagechild = dynamic_cast<mitk::Image*>(imagechildnode->GetData()); MITK_TEST_CONDITION_REQUIRED(imagechild.IsNotNull(),"Loading child test image from Datastorage"); //Surface mitk::DataNode::Pointer surfacenode = storage->GetNamedNode("binary"); MITK_TEST_CONDITION_REQUIRED(surfacenode.IsNotNull(),"Get previously stored surface node"); mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(surfacenode->GetData()); MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface from Datastorage"); // Get the property list and test the properties mitk::PropertyList::Pointer surfacePropList = surface->GetPropertyList(); surfacePropList->GetStringProperty("surface type", testString); MITK_TEST_CONDITION((testString.compare("test surface") == 0) ,"Get StringProperty from previously stored surface node"); surfacePropList->GetStringProperty("greetings", testString); MITK_TEST_CONDITION((testString.compare("to dad") == 0) ,"Get another StringProperty from previously stored surface node"); //PointSet mitk::DataNode::Pointer pointsnode = storage->GetNamedNode("points"); MITK_TEST_CONDITION_REQUIRED(pointsnode.IsNotNull(),"Get previously stored PointSet node"); mitk::PointSet::Pointer pointset = dynamic_cast<mitk::PointSet*>(pointsnode->GetData()); MITK_TEST_CONDITION_REQUIRED(pointset.IsNotNull(),"Loading test PointSet from Datastorage"); mitk::PointSet::PointType p = pointset->GetPoint(0); MITK_TEST_CONDITION_REQUIRED(p[0] == 1.0 && p[1] == -2.0 && p[2] == 33.0, "Test Pointset entry 0 after loading"); p = pointset->GetPoint(1); MITK_TEST_CONDITION_REQUIRED(p[0] == 100.0 && p[1] == -200.0 && p[2] == 3300.0, "Test Pointset entry 1 after loading"); p = pointset->GetPoint(2); MITK_TEST_CONDITION_REQUIRED(p[0] == 2.0 && p[1] == -3.0 && p[2] == 22.0, "Test Pointset entry 2 after loading"); } }; // end test helper class int mitkSceneIOTest(int argc, char* argv[]) { MITK_TEST_BEGIN("SceneIO") std::string sceneFileName; for (unsigned int i = 0; i < 1; ++i) // TODO change to " < 2" to check cases where file system would be full { if (i == 1) { // call ulimit and restrict maximum file size to something small #ifndef WIN32 errno = 0; long int value = ulimit(UL_SETFSIZE, 1); MITK_TEST_CONDITION_REQUIRED( value != -1, "ulimit() returned with errno = " << errno ); #else continue; #endif } // create a data storage and fill it with some test data mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New(); MITK_TEST_CONDITION_REQUIRED(sceneIO.IsNotNull(),"SceneIO instantiation") mitk::DataStorage::Pointer storage = mitk::StandaloneDataStorage::New().GetPointer(); MITK_TEST_CONDITION_REQUIRED(storage.IsNotNull(),"StandaloneDataStorage instantiation"); std::cout << "ImageName: " << argv[1] << std::endl; std::cout << "SurfaceName: " << argv[2] << std::endl; SceneIOTestClass::FillStorage(storage, argv[1], argv[2]); // attempt to save it Poco::Path newname( Poco::TemporaryFile::tempName() ); sceneFileName = std::string( MITK_TEST_OUTPUT_DIR ) + Poco::Path::separator() + newname.getFileName() + ".zip"; MITK_TEST_CONDITION_REQUIRED( sceneIO->SaveScene( storage->GetAll(), storage, sceneFileName), "Saving scene file '" << sceneFileName << "'"); // test if no errors were reported mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes(); if (failedNodes.IsNotNull() && !failedNodes->empty()) { MITK_TEST_OUTPUT( << "The following nodes could not be serialized:"); for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { MITK_TEST_OUTPUT_NO_ENDL( << " - "); if ( mitk::BaseData* data =(*iter)->GetData() ) { MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass()); } else { MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)"); } MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'"); // \TODO: should we fail the test case if failed properties exist? } } mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties(); if (failedProperties.IsNotNull() && !failedProperties->IsEmpty()) { MITK_TEST_OUTPUT( << "The following properties could not be serialized:"); const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { MITK_TEST_OUTPUT( << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'"); // \TODO: should we fail the test case if failed properties exist? } } MITK_TEST_CONDITION_REQUIRED(failedProperties.IsNotNull() && failedProperties->IsEmpty(), "Checking if all properties have been saved.") MITK_TEST_CONDITION_REQUIRED(failedNodes.IsNotNull() && failedNodes->empty(), "Checking if all nodes have been saved.") //Now do the loading part sceneIO = mitk::SceneIO::New(); //Load scene into the datastorage and clean the DS first MITK_TEST_OUTPUT(<< "Loading scene again"); storage = sceneIO->LoadScene(sceneFileName,storage,true); // test if no errors were reported failedNodes = sceneIO->GetFailedNodes(); if (failedNodes.IsNotNull() && !failedNodes->empty()) { MITK_TEST_OUTPUT( << "The following nodes could not be serialized:"); for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin(); iter != failedNodes->end(); ++iter ) { MITK_TEST_OUTPUT_NO_ENDL( << " - "); if ( mitk::BaseData* data =(*iter)->GetData() ) { MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass()); } else { MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)"); } MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'"); // \TODO: should we fail the test case if failed properties exist? } } failedProperties = sceneIO->GetFailedProperties(); if (failedProperties.IsNotNull() && !failedProperties->IsEmpty()) { MITK_TEST_OUTPUT( << "The following properties could not be serialized:"); const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap(); for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin(); iter != propmap->end(); ++iter ) { MITK_TEST_OUTPUT( << " - " << iter->second->GetNameOfClass() << " associated to key '" << iter->first << "'"); // \TODO: should we fail the test case if failed properties exist? } } // check if data storage content has been restored correctly SceneIOTestClass::VerifyStorage(storage); } // if no sub-test failed remove the scene file, otherwise it is kept for debugging purposes if ( mitk::TestManager::GetInstance()->NumberOfFailedTests() == 0 ) { Poco::File pocoSceneFile( sceneFileName ); MITK_TEST_CONDITION_REQUIRED( pocoSceneFile.exists(), "Checking if scene file still exists before cleaning up." ) pocoSceneFile.remove(); } MITK_TEST_END(); } <|endoftext|>
<commit_before>/* Copyright 2016 Nervana Systems Inc. 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 <vector> #include <cstdio> #include <iostream> #include <chrono> #include <utility> #include <algorithm> #include <sox.h> #include <memory> #include "loader.hpp" #include "log.hpp" #include "web_app.hpp" #include "manifest_nds.hpp" using namespace std; using namespace nervana; loader_config::loader_config(nlohmann::json js) { if (js.is_null()) { throw std::runtime_error("missing loader config in json config"); } for (auto& info : config_list) { info->parse(js); } verify_config("loader", config_list, js); if (block_size == 0) { block_size = 2 * batch_size; } validate(); } void loader_config::validate() { if (iteration_mode == "ONCE") { } else if (iteration_mode == "INFINITE") { } else if (iteration_mode == "COUNT") { if (iteration_mode_count <= 0) { throw invalid_argument("iteration_mode_count must be a positive integer"); } } else { throw invalid_argument("iteration_mode must be one of ONCE, COUNT, or INFINITE"); } } loader::loader(const std::string& config_string) : m_current_iter(*this, false) , m_end_iter(*this, true) { auto tmp = nlohmann::json::parse(config_string); initialize(tmp); } loader::loader(nlohmann::json& config_json) : m_current_iter(*this, false) , m_end_iter(*this, true) { initialize(config_json); } loader::~loader() { if (m_debug_web_app) { m_debug_web_app->deregister_loader(this); } } void loader::initialize(nlohmann::json& config_json) { string config_string = config_json.dump(); m_current_config = config_json; loader_config lcfg(config_json); m_batch_size = lcfg.batch_size; // shared_ptr<manifest> base_manifest; sox_format_init(); if (nervana::manifest_nds::is_likely_json(lcfg.manifest_filename)) { m_manifest_nds = nervana::manifest_nds_builder() .filename(lcfg.manifest_filename) .block_size(lcfg.block_size) .elements_per_record(2) .seed(lcfg.random_seed) .make_shared(); m_block_loader = std::make_shared<block_loader_nds>(m_manifest_nds.get(), lcfg.block_size); } else { // the manifest defines which data should be included in the dataset m_manifest_file = make_shared<manifest_file>(lcfg.manifest_filename, lcfg.shuffle_manifest, lcfg.manifest_root, lcfg.subset_fraction, lcfg.block_size, lcfg.random_seed); // TODO: make the constructor throw this error if (record_count() == 0) { throw std::runtime_error("manifest file is empty"); } m_block_loader = make_shared<block_loader_file>(m_manifest_file.get(), lcfg.block_size); } m_block_manager = make_shared<block_manager>(m_block_loader.get(), lcfg.block_size, lcfg.cache_directory, lcfg.shuffle_enable, lcfg.random_seed); // Default ceil div to get number of batches m_batch_count_value = (record_count() + m_batch_size - 1) / m_batch_size; if (lcfg.iteration_mode == "ONCE") { m_batch_mode = BatchMode::ONCE; } else if (lcfg.iteration_mode == "INFINITE") { m_batch_mode = BatchMode::INFINITE; } else if (lcfg.iteration_mode == "COUNT") { m_batch_mode = BatchMode::COUNT; m_batch_count_value = lcfg.iteration_mode_count; } m_provider = provider_factory::create(config_json); unsigned int threads_num = lcfg.decode_thread_count != 0 ? lcfg.decode_thread_count : std::thread::hardware_concurrency(); const int decode_size = lcfg.batch_size * ((threads_num * m_input_multiplier - 1) / lcfg.batch_size + 1); m_batch_iterator = make_shared<batch_iterator>(m_block_manager.get(), decode_size); m_decoder = make_shared<batch_decoder>(m_batch_iterator.get(), decode_size, lcfg.decode_thread_count, lcfg.pinned, m_provider, lcfg.random_seed); m_final_stage = make_shared<batch_iterator_fbm>( m_decoder.get(), lcfg.batch_size, m_provider, !lcfg.batch_major); m_output_buffer_ptr = m_final_stage->next(); if (lcfg.web_server_port != 0) { m_debug_web_app = make_shared<web_app>(lcfg.web_server_port); m_debug_web_app->register_loader(this); } m_current_iter.m_empty_buffer.add_items(get_names_and_shapes(), (size_t)batch_size()); } const vector<string>& loader::get_buffer_names() const { return m_provider->get_buffer_names(); } const vector<pair<string, shape_type>>& loader::get_names_and_shapes() const { return m_provider->get_output_shapes(); } const shape_t& loader::get_shape(const string& name) const { return m_provider->get_output_shape(name).get_shape(); } loader::iterator::iterator(loader& ld, bool is_end) : m_current_loader(ld) , m_is_end{is_end} { } loader::iterator::iterator(const iterator& other) : m_current_loader{other.m_current_loader} , m_is_end{other.m_is_end} { } loader::iterator& loader::iterator::operator++() { m_current_loader.increment_position(); return *this; } loader::iterator& loader::iterator::operator++(int) { iterator& rc = *this; ++rc; return rc; } bool loader::iterator::operator==(const iterator& other) const { bool res = &m_current_loader == &other.m_current_loader; res &= (other.m_is_end && positional_end()) || (m_is_end && other.positional_end()); return res; } bool loader::iterator::operator!=(const iterator& other) const { return !(*this == other); } // Whether or not this strictly positional iterator has reached the end bool loader::iterator::positional_end() const { return !m_is_end && (position() >= m_current_loader.m_batch_count_value); } const fixed_buffer_map& loader::iterator::operator*() const { return m_current_loader.m_output_buffer_ptr ? *m_current_loader.m_output_buffer_ptr : m_empty_buffer; } void loader::increment_position() { m_output_buffer_ptr = m_final_stage->next(); m_position++; // Wrap around if this is an infinite iterator if (m_batch_mode == BatchMode::INFINITE && m_position == m_batch_count_value) { m_position = 0; } } <commit_msg>Enabling shuffling in manifest_nds file<commit_after>/* Copyright 2016 Nervana Systems Inc. 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 <vector> #include <cstdio> #include <iostream> #include <chrono> #include <utility> #include <algorithm> #include <sox.h> #include <memory> #include "loader.hpp" #include "log.hpp" #include "web_app.hpp" #include "manifest_nds.hpp" using namespace std; using namespace nervana; loader_config::loader_config(nlohmann::json js) { if (js.is_null()) { throw std::runtime_error("missing loader config in json config"); } for (auto& info : config_list) { info->parse(js); } verify_config("loader", config_list, js); if (block_size == 0) { block_size = 2 * batch_size; } validate(); } void loader_config::validate() { if (iteration_mode == "ONCE") { } else if (iteration_mode == "INFINITE") { } else if (iteration_mode == "COUNT") { if (iteration_mode_count <= 0) { throw invalid_argument("iteration_mode_count must be a positive integer"); } } else { throw invalid_argument("iteration_mode must be one of ONCE, COUNT, or INFINITE"); } } loader::loader(const std::string& config_string) : m_current_iter(*this, false) , m_end_iter(*this, true) { auto tmp = nlohmann::json::parse(config_string); initialize(tmp); } loader::loader(nlohmann::json& config_json) : m_current_iter(*this, false) , m_end_iter(*this, true) { initialize(config_json); } loader::~loader() { if (m_debug_web_app) { m_debug_web_app->deregister_loader(this); } } void loader::initialize(nlohmann::json& config_json) { string config_string = config_json.dump(); m_current_config = config_json; loader_config lcfg(config_json); m_batch_size = lcfg.batch_size; // shared_ptr<manifest> base_manifest; sox_format_init(); if (nervana::manifest_nds::is_likely_json(lcfg.manifest_filename)) { m_manifest_nds = nervana::manifest_nds_builder() .filename(lcfg.manifest_filename) .block_size(lcfg.block_size) .elements_per_record(2) .shuffle(lcfg.shuffle_manifest) .seed(lcfg.random_seed) .make_shared(); m_block_loader = std::make_shared<block_loader_nds>(m_manifest_nds.get(), lcfg.block_size); } else { // the manifest defines which data should be included in the dataset m_manifest_file = make_shared<manifest_file>(lcfg.manifest_filename, lcfg.shuffle_manifest, lcfg.manifest_root, lcfg.subset_fraction, lcfg.block_size, lcfg.random_seed); // TODO: make the constructor throw this error if (record_count() == 0) { throw std::runtime_error("manifest file is empty"); } m_block_loader = make_shared<block_loader_file>(m_manifest_file.get(), lcfg.block_size); } m_block_manager = make_shared<block_manager>(m_block_loader.get(), lcfg.block_size, lcfg.cache_directory, lcfg.shuffle_enable, lcfg.random_seed); // Default ceil div to get number of batches m_batch_count_value = (record_count() + m_batch_size - 1) / m_batch_size; if (lcfg.iteration_mode == "ONCE") { m_batch_mode = BatchMode::ONCE; } else if (lcfg.iteration_mode == "INFINITE") { m_batch_mode = BatchMode::INFINITE; } else if (lcfg.iteration_mode == "COUNT") { m_batch_mode = BatchMode::COUNT; m_batch_count_value = lcfg.iteration_mode_count; } m_provider = provider_factory::create(config_json); unsigned int threads_num = lcfg.decode_thread_count != 0 ? lcfg.decode_thread_count : std::thread::hardware_concurrency(); const int decode_size = lcfg.batch_size * ((threads_num * m_input_multiplier - 1) / lcfg.batch_size + 1); m_batch_iterator = make_shared<batch_iterator>(m_block_manager.get(), decode_size); m_decoder = make_shared<batch_decoder>(m_batch_iterator.get(), decode_size, lcfg.decode_thread_count, lcfg.pinned, m_provider, lcfg.random_seed); m_final_stage = make_shared<batch_iterator_fbm>( m_decoder.get(), lcfg.batch_size, m_provider, !lcfg.batch_major); m_output_buffer_ptr = m_final_stage->next(); if (lcfg.web_server_port != 0) { m_debug_web_app = make_shared<web_app>(lcfg.web_server_port); m_debug_web_app->register_loader(this); } m_current_iter.m_empty_buffer.add_items(get_names_and_shapes(), (size_t)batch_size()); } const vector<string>& loader::get_buffer_names() const { return m_provider->get_buffer_names(); } const vector<pair<string, shape_type>>& loader::get_names_and_shapes() const { return m_provider->get_output_shapes(); } const shape_t& loader::get_shape(const string& name) const { return m_provider->get_output_shape(name).get_shape(); } loader::iterator::iterator(loader& ld, bool is_end) : m_current_loader(ld) , m_is_end{is_end} { } loader::iterator::iterator(const iterator& other) : m_current_loader{other.m_current_loader} , m_is_end{other.m_is_end} { } loader::iterator& loader::iterator::operator++() { m_current_loader.increment_position(); return *this; } loader::iterator& loader::iterator::operator++(int) { iterator& rc = *this; ++rc; return rc; } bool loader::iterator::operator==(const iterator& other) const { bool res = &m_current_loader == &other.m_current_loader; res &= (other.m_is_end && positional_end()) || (m_is_end && other.positional_end()); return res; } bool loader::iterator::operator!=(const iterator& other) const { return !(*this == other); } // Whether or not this strictly positional iterator has reached the end bool loader::iterator::positional_end() const { return !m_is_end && (position() >= m_current_loader.m_batch_count_value); } const fixed_buffer_map& loader::iterator::operator*() const { return m_current_loader.m_output_buffer_ptr ? *m_current_loader.m_output_buffer_ptr : m_empty_buffer; } void loader::increment_position() { m_output_buffer_ptr = m_final_stage->next(); m_position++; // Wrap around if this is an infinite iterator if (m_batch_mode == BatchMode::INFINITE && m_position == m_batch_count_value) { m_position = 0; } } <|endoftext|>
<commit_before>#pragma ident "$Id: //depot/msn/prototype/brent/IGEB_Demo/EphSum.cpp#1 $" /** * Given a PRN ID and a date (DOY, Year), read the appropriate FIC data file(s) * and assemble a summary of all ephemerides relevant to the day for the PRN. * */ // System #include <stdio.h> // gpstk #include "FileFilterFrame.hpp" #include "BasicFramework.hpp" #include "StringUtils.hpp" #include "GPSEphemerisStore.hpp" // fic #include "FICStream.hpp" #include "FICHeader.hpp" #include "FICData.hpp" #include "FICFilterOperators.hpp" #include "RinexNavStream.hpp" #include "RinexNavData.hpp" #include "RinexNavHeader.hpp" #include "RinexNavFilterOperators.hpp" using namespace std; using namespace gpstk; class EphSum : public gpstk::BasicFramework { public: EphSum(const std::string& applName, const std::string& applDesc) throw(); ~EphSum() {} virtual bool initialize(int argc, char *argv[]) throw(); bool checkIOD( const gpstk::EngEphemeris ee, FILE* logfp ); protected: virtual void process(); gpstk::CommandOptionWithAnyArg inputOption; gpstk::CommandOptionWithAnyArg outputOption; gpstk::CommandOptionWithAnyArg prnOption; gpstk::CommandOptionNoArg FICOption; std::list<long> blocklist; std::list<long> prnlist; FILE *logfp; GPSEphemerisStore ges; int numFICErrors; }; int main( int argc, char*argv[] ) { try { EphSum fc("EphSum", "Summarize contents of a navigation message file."); if (!fc.initialize(argc, argv)) return(false); fc.run(); } catch(gpstk::Exception& exc) { cout << exc << endl; return 1; } catch(...) { cout << "Caught an unnamed exception. Exiting." << endl; return 1; } return 0; } EphSum::EphSum(const std::string& applName, const std::string& applDesc) throw() :BasicFramework(applName, applDesc), inputOption('i', "input-file", "The name of the navigation message file(s) to read.", true), outputOption('o', "output-file", "The name of the output file to write.", true), FICOption('f', "FIC","Assuming FIC input rather than Rinex(default).",false), prnOption('p', "PRNID","The PRN ID of the SV to process",false) { inputOption.setMaxCount(2); outputOption.setMaxCount(1); prnOption.setMaxCount(1); FICOption.setMaxCount(1); numFICErrors = 0; } bool EphSum::initialize(int argc, char *argv[]) throw() { if (!BasicFramework::initialize(argc, argv)) return false; if (debugLevel) { cout << "Input File(s): " << inputOption.getValue().front() << endl; cout << "Output File: " << outputOption.getValue().front() << endl; cout << "PRN ID : "; if (prnOption.getCount()==0) { cout << "all" << endl; } else { cout << "PRN ID : " << prnOption.getValue().front() << endl; } if (FICOption.getCount()==0) cout << "Processing FIC input" << endl; } // Open the output file logfp = fopen( outputOption.getValue().front().c_str(),"wt"); if (logfp==0) { cout << "Failed to open output file. Exiting." << endl; return 1; } fprintf(logfp,"# Output file from EphSum\n"); return true; } void EphSum::process() { int countByPRN[gpstk::MAX_PRN+1]; for (int i1=0;i1<=gpstk::MAX_PRN+1;++i1) countByPRN[i1] = 0; vector<string> values; values = inputOption.getValue(); if (FICOption.getCount()>0) { FileFilterFrame<FICStream, FICData> input(values); for (int it=0;it<values.size();++it) { fprintf(logfp,"# Processing FIC input specification: %s\n", values[it].c_str()); } if(debugLevel) { cout << " input.getDataCount() after init: " << input.getDataCount() << endl; cout << "Setting up output file: " << outputOption.getValue().front() << endl; } // filter the FIC data for the requested block(s) std::list<long> blockList; blockList.push_back(9); input.filter(FICDataFilterBlock(blockList)); //some hand waving for the data conversion if(debugLevel) cout << "Reading the input data." << endl; list<FICData>& ficList = input.getData(); list<FICData>::iterator itr = ficList.begin(); int count9 = 0; while (itr != ficList.end()) { count9++; FICData& r = *itr; if ( r.blockNum == 9) { EngEphemeris ee(r); ges.addEphemeris(ee); } itr++; } } else { FileFilterFrame<RinexNavStream, RinexNavData> data(values); for (int it=0;it<values.size();++it) { fprintf(logfp,"# Processing Rinex input specification: %s\n", values[it].c_str()); } list<RinexNavData>& rnavlist = data.getData(); list<RinexNavData>::iterator itr = rnavlist.begin(); while (itr!=rnavlist.end()) { RinexNavData& r = *itr; EngEphemeris ee(r); ges.addEphemeris(ee); itr++; } } string tform = "%04F %6.0g %02m/%02d/%02y %03j %02H:%02M:%02S"; GPSEphemerisStore::EngEphMap eemap; long prnid=1; long maxprn = gpstk::MAX_PRN; if (prnOption.getCount()>0) { prnid = StringUtils::asInt(prnOption.getValue().front()); maxprn = prnid; } for (int i=prnid;i<=maxprn;++i) { SatID sat = SatID( i, SatID::systemGPS); try { eemap = ges.getEphMap( sat ); } catch(InvalidRequest) { // simply go on to the next PRN fprintf(logfp,"#\n"); fprintf(logfp,"#PRN: %02d, # of eph: NONE\n",i); continue; } // Header fprintf(logfp,"#\n"); fprintf(logfp,"#PRN: %02d, # of eph: %02d\n",i,eemap.size()); fprintf(logfp,"#PRN ! Xmit ! Toe/Toc ! End of Eff ! IODC Health\n"); countByPRN[i] = eemap.size(); GPSEphemerisStore::EngEphMap::const_iterator ci; for (ci=eemap.begin(); ci!=eemap.end(); ++ci) { EngEphemeris ee = ci->second; DayTime endEff = ee.getEphemerisEpoch(); endEff += 7200; fprintf(logfp," %02d ! %s ! %s ! %s ! 0x%03X 0x%02X %02d \n", i, ee.getTransmitTime().printf(tform).c_str(), ee.getEphemerisEpoch().printf(tform).c_str(), endEff.printf(tform).c_str(), ee.getIODC(), ee.getHealth(), ee.getHealth()); //fprintf(logfp," | | %s |\n", // ee.getEpochTime().printf(tform).c_str()); } } fprintf(logfp,"#\n#Summary of Counts by PRN\n"); fprintf(logfp,"# PRN Count\n"); for (int i2=1;i2<=gpstk::MAX_PRN;++i2) { fprintf(logfp,"# %02d %5d\n",i2,countByPRN[i2]); } if (debugLevel) cout << "done." << endl; } <commit_msg><commit_after>#pragma ident "$Id: //depot/msn/prototype/brent/IGEB_Demo/EphSum.cpp#3 $" /** * Given a PRN ID and a date (DOY, Year), one or more navigation * message data file(s) and assemble a summary of all ephemerides relevant * to the day for the PRN. Display the summary as a one-line-per-ephemeris * data set that shows the transmit time, the time of effectivity, the end * of effectivity, the IODC, and the health. * */ //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Copyright 2009, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= // System #include <stdio.h> // gpstk #include "FileFilterFrame.hpp" #include "BasicFramework.hpp" #include "StringUtils.hpp" #include "GPSEphemerisStore.hpp" // fic #include "FICStream.hpp" #include "FICHeader.hpp" #include "FICData.hpp" #include "RinexNavStream.hpp" #include "RinexNavData.hpp" #include "RinexNavHeader.hpp" using namespace std; using namespace gpstk; class EphSum : public gpstk::BasicFramework { public: EphSum(const std::string& applName, const std::string& applDesc) throw(); ~EphSum() {} virtual bool initialize(int argc, char *argv[]) throw(); bool checkIOD( const gpstk::EngEphemeris ee, FILE* logfp ); protected: virtual void process(); gpstk::CommandOptionWithAnyArg inputOption; gpstk::CommandOptionWithAnyArg outputOption; gpstk::CommandOptionWithAnyArg prnOption; FILE *logfp; FILE *out2fp; GPSEphemerisStore ges; int numFICErrors; }; int main( int argc, char*argv[] ) { try { string applDesc = "\nSummarize contents of a navigation message file. " "EphSum works on either RINEX navigation message files or FIC files. " "The summary is in a text output file. The summary contains the transmit " "time, time of effectivity, end of effectivity, IODC, and health as a " "one-line-per ephemeris summary. The number of ephemerides found per SV " "is also provided. The number of ephemerides per SV is also summarized at the end. " "The default is to summarize all SVs found. If a specific PRN ID is provided, " "only data for that PRN ID will be sumarized."; EphSum fc("EphSum", applDesc); if (!fc.initialize(argc, argv)) return(false); fc.run(); } catch(gpstk::Exception& exc) { cout << exc << endl; return 1; } catch(...) { cout << "Caught an unnamed exception. Exiting." << endl; return 1; } return 0; } EphSum::EphSum(const std::string& applName, const std::string& applDesc) throw() :BasicFramework(applName, applDesc), inputOption('i', "input-file", "The name of the navigation message file(s) to read.", true), outputOption('o', "output-file", "The name of the output file to write.", true), prnOption('p', "PRNID","The PRN ID of the SV to process (default is all SVs)",false) { inputOption.setMaxCount(8); outputOption.setMaxCount(1); prnOption.setMaxCount(1); numFICErrors = 0; } bool EphSum::initialize(int argc, char *argv[]) throw() { if (!BasicFramework::initialize(argc, argv)) return false; if (debugLevel) { cout << "Input File(s): " << inputOption.getValue().front() << endl; cout << "Output File: " << outputOption.getValue().front() << endl; cout << "PRN ID : "; if (prnOption.getCount()==0) { cout << "all" << endl; } else { cout << "PRN ID : " << prnOption.getValue().front() << endl; } } // Open the output file logfp = fopen( outputOption.getValue().front().c_str(),"wt"); if (logfp==0) { cout << "Failed to open output file. Exiting." << endl; return 1; } fprintf(logfp,"# Output file from EphSum\n"); return true; } void EphSum::process() { int countByPRN[gpstk::MAX_PRN+1]; for (int i1=0;i1<=gpstk::MAX_PRN+1;++i1) countByPRN[i1] = 0; bool successAtLeastOnce = false; vector<string> values; values = inputOption.getValue(); for (int it=0;it<values.size();++it) { bool successOnThisFile = false; // Leave a record in the output file so we can verify what // ephemeris files were processed. fprintf(logfp,"# Processing input specification: %s", values[it].c_str()); // // Try processing as a RINEX file try { RinexNavHeader rnh; RinexNavData rnd; RinexNavStream RNFileIn( values[it].c_str() ); if (RNFileIn) { RNFileIn.exceptions(fstream::failbit); RNFileIn >> rnh; while (RNFileIn >> rnd) { EngEphemeris ee(rnd); ges.addEphemeris(ee); } successOnThisFile = true; fprintf(logfp," - Success(RINEX)\n"); } } catch(gpstk::Exception& exc) { // do nothing } //if (successOnThisFile) cout << "Succeeded reading RINEX" << endl; // If RINEX failed, try as FIC input file if (!successOnThisFile) { try { FICHeader fich; FICData ficd; FICStream FICFileIn( values[it].c_str() ); if (FICFileIn) { FICFileIn.exceptions(fstream::failbit); FICFileIn >> fich; int recNum = 0; int recNum9 = 0; while (FICFileIn >> ficd) { if (ficd.blockNum==9) { EngEphemeris ee(ficd); ges.addEphemeris(ee); recNum9++; } recNum++; //cout << "Processed rec#, rec9# " << recNum << ", " << recNum9 << ", " << endl; } } successOnThisFile = true; fprintf(logfp," - Success(FIC)\n"); //if (successOnThisFile) cout << "Succeeded reading FIC" << endl; } catch(gpstk::Exception& exc) { //cout << "Caught exception during FIC read." << endl; //cout << "Exception: " << exc << endl; // do nothing } } if (successOnThisFile) successAtLeastOnce = true; else fprintf(logfp," - FAILURE\n"); } if (!successAtLeastOnce) { cout << "Read no ephemeris data." << endl; cout << "EphSum will terminate." << endl; exit(1); } string tform = "%04F %6.0g %02m/%02d/%02y %03j %02H:%02M:%02S"; GPSEphemerisStore::EngEphMap eemap; long maxprn = gpstk::MAX_PRN; bool singleSV = false; int singlePRNID = 0; if (prnOption.getCount()>0) { singlePRNID = StringUtils::asInt(prnOption.getValue().front()); singleSV = true; } for (int i=1;i<=maxprn;++i) { GPSEphemerisStore::EngEphMap::const_iterator ci; SatID sat = SatID( i, SatID::systemGPS); try { eemap = ges.getEphMap( sat ); } catch(InvalidRequest) { // simply go on to the next PRN if (!singleSV || (singleSV && i==singlePRNID)) { fprintf(logfp,"#\n"); fprintf(logfp,"#PRN: %02d, # of eph: NONE\n",i); } continue; } countByPRN[i] = eemap.size(); if (singleSV && singlePRNID!=i) continue; // Header fprintf(logfp,"#\n"); fprintf(logfp,"#PRN: %02d, # of eph: %02d\n",i,eemap.size()); fprintf(logfp,"#PRN ! Xmit ! Toe/Toc ! End of Eff ! IODC Health\n"); for (ci=eemap.begin(); ci!=eemap.end(); ++ci) { EngEphemeris ee = ci->second; DayTime endEff = ee.getEphemerisEpoch(); endEff += 7200; fprintf(logfp," %02d ! %s ! %s ! %s ! 0x%03X 0x%02X %02d \n", i, ee.getTransmitTime().printf(tform).c_str(), ee.getEphemerisEpoch().printf(tform).c_str(), endEff.printf(tform).c_str(), ee.getIODC(), ee.getHealth(), ee.getHealth()); //fprintf(logfp," | | %s |\n", // ee.getEpochTime().printf(tform).c_str()); } } fprintf(logfp,"#\n#Summary of Counts by PRN\n"); fprintf(logfp,"# PRN Count\n"); for (int i2=1;i2<=gpstk::MAX_PRN;++i2) { fprintf(logfp,"# %02d %5d\n",i2,countByPRN[i2]); } if (debugLevel) cout << "done." << endl; } <|endoftext|>
<commit_before>#include "NFCUUIDModule.h" #include "NFComm/NFPluginModule/NFIKernelModule.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" namespace UUIDModule { #ifndef _MSC_VER #include <sys/time.h> #include <unistd.h> #define EPOCHFILETIME 11644473600000000ULL #else #include <windows.h> #include <time.h> #define EPOCHFILETIME 11644473600000000Ui64 #endif uint64_t get_time() { #ifndef _MSC_VER struct timeval tv; gettimeofday(&tv, NULL); int time = tv.tv_usec; time /= 1000; time += (tv.tv_sec * 1000); return time; #else FILETIME filetime; uint64_t time = 0; GetSystemTimeAsFileTime(&filetime); time |= filetime.dwHighDateTime; time <<= 32; time |= filetime.dwLowDateTime; time /= 10; time -= EPOCHFILETIME; return time / 1000; #endif } class UUID { public: UUID() : epoch_(0), time_(0), machine_(0), sequence_(0) { } ~UUID() {} void set_epoch(uint64_t epoch) { epoch_ = epoch; } void set_machine(int32_t machine) { machine_ = machine; } int64_t generate() { int64_t value = 0; uint64_t time = UUIDModule::get_time() - epoch_; // 保留后48位时间 value = time << 16; // 最后16位是sequenceID value |= sequence_++ & 0xFFFF; if (sequence_ == 0xFFFF) { sequence_ = 0; } return value; } private: uint64_t epoch_; uint64_t time_; int32_t machine_; int32_t sequence_; }; } NFCUUIDModule::NFCUUIDModule(NFIPluginManager* p) { mnIdent = 0; m_pKernelModule = NULL; pPluginManager = p; } bool NFCUUIDModule::Init() { m_pUUID = NF_NEW UUIDModule::UUID; assert(NULL != m_pUUID); return true; } bool NFCUUIDModule::Shut() { return true; } bool NFCUUIDModule::BeforeShut() { if (NULL != m_pUUID) { delete m_pUUID; m_pUUID = NULL; } return true; } bool NFCUUIDModule::AfterInit() { m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); assert(NULL != m_pKernelModule); // 初始化uuid NFINT32 nID = GetIdentID(); m_pUUID->set_machine(nID); m_pUUID->set_epoch(uint64_t(1367505795100)); return true; } bool NFCUUIDModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; } NFIDENTID NFCUUIDModule::CreateGUID() { NFIDENTID xID; xID.nSvrID = GetIdentID(); xID.nData64 = m_pUUID->generate(); return xID; } NFINT64 NFCUUIDModule::GetIdentID() { return mnIdent; } void NFCUUIDModule::SetIdentID( NFINT64 nID ) { mnIdent = nID; } <commit_msg>modify uuid generate<commit_after>#include "NFCUUIDModule.h" #include "NFComm/NFPluginModule/NFIKernelModule.h" #include "NFComm/NFPluginModule/NFIPluginManager.h" namespace UUIDModule { #ifndef _MSC_VER #include <sys/time.h> #include <unistd.h> #define EPOCHFILETIME 11644473600000000ULL #else #include <windows.h> #include <time.h> #define EPOCHFILETIME 11644473600000000Ui64 #endif uint64_t get_time() { #ifndef _MSC_VER struct timeval tv; gettimeofday(&tv, NULL); int time = tv.tv_usec; time /= 1000; time += (tv.tv_sec * 1000); return time; #else FILETIME filetime; uint64_t time = 0; GetSystemTimeAsFileTime(&filetime); time |= filetime.dwHighDateTime; time <<= 32; time |= filetime.dwLowDateTime; time /= 10; time -= EPOCHFILETIME; return time / 1000; #endif } class UUID { public: UUID() : epoch_(0), time_(0), machine_(0), sequence_(0) { } ~UUID() {} void set_epoch(uint64_t epoch) { epoch_ = epoch; } void set_machine(int32_t machine) { machine_ = machine; } int64_t generate() { int64_t value = 0; uint64_t time = UUIDModule::get_time() - epoch_; // 保留后48位时间 value = time << 16; // 最后16位是sequenceID //value |= sequence_++ & 0xFFFF; if (sequence_ == 0x7FFF) { sequence_ = 0; } return value + sequence_; } private: uint64_t epoch_; uint64_t time_; int32_t machine_; int32_t sequence_; }; } NFCUUIDModule::NFCUUIDModule(NFIPluginManager* p) { mnIdent = 0; m_pKernelModule = NULL; pPluginManager = p; } bool NFCUUIDModule::Init() { m_pUUID = NF_NEW UUIDModule::UUID; assert(NULL != m_pUUID); return true; } bool NFCUUIDModule::Shut() { return true; } bool NFCUUIDModule::BeforeShut() { if (NULL != m_pUUID) { delete m_pUUID; m_pUUID = NULL; } return true; } bool NFCUUIDModule::AfterInit() { m_pKernelModule = dynamic_cast<NFIKernelModule*>(pPluginManager->FindModule("NFCKernelModule")); assert(NULL != m_pKernelModule); // 初始化uuid NFINT32 nID = GetIdentID(); m_pUUID->set_machine(nID); m_pUUID->set_epoch(uint64_t(1367505795100)); return true; } bool NFCUUIDModule::Execute(const float fLasFrametime, const float fStartedTime) { return true; } NFIDENTID NFCUUIDModule::CreateGUID() { NFIDENTID xID; xID.nSvrID = GetIdentID(); xID.nData64 = m_pUUID->generate(); return xID; } NFINT64 NFCUUIDModule::GetIdentID() { return mnIdent; } void NFCUUIDModule::SetIdentID( NFINT64 nID ) { mnIdent = nID; } <|endoftext|>
<commit_before>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/type_checker.h" #include "library/tc_multigraph.h" namespace lean { pair<environment, list<name>> tc_multigraph::add(environment const & env, name const & /* e */, unsigned /* num_args */) { // TODO(Leo) return mk_pair(env, list<name>()); } pair<environment, list<name>> tc_multigraph::add(environment const & env, name const & e) { declaration const & d = env.get(e); return add(env, e, get_arity(d.get_type())); } void tc_multigraph::erase(name const & e) { auto src = m_edges.find(e); if (!src) return; auto succ_lst = m_successors.find(*src); lean_assert(it); name tgt; list<pair<name, name>> new_succ_lst = filter(*succ_lst, [&](pair<name, name> const & p) { if (p.first == e) { lean_assert(tgt.is_anonymous()); tgt = p.second; return false; } else { return true; } }); lean_assert(!tgt.is_anonymous()); m_successors.insert(*src, new_succ_lst); if (std::all_of(new_succ_lst.begin(), new_succ_lst.end(), [&](pair<name, name> const & p) { return p.second != tgt; })) { // e is the last edge from src to tgt auto pred_lst = m_predecessors.find(tgt); lean_assert(pred_list); list<name> new_pred_lst = filter(*pred_lst, [&](name const & n) { return n != *src; }); m_predecessors.insert(tgt, new_pred_lst); } m_edges.erase(e); } bool tc_multigraph::is_edge(name const & e) const { return m_edges.contains(e); } bool tc_multigraph::is_node(name const & c) const { return m_successors.contains(c) || m_predecessors.contains(c); } list<pair<name, name>> tc_multigraph::get_successors(name const & c) const { if (auto r = m_successors.find(c)) return *r; else return list<pair<name, name>>(); } list<name> tc_multigraph::get_predecessors(name const & c) const { if (auto r = m_predecessors.find(c)) return *r; else return list<name>(); } } <commit_msg>chore(src/library/tc_multigraph): fix typo<commit_after>/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include "kernel/type_checker.h" #include "library/tc_multigraph.h" namespace lean { pair<environment, list<name>> tc_multigraph::add(environment const & env, name const & /* e */, unsigned /* num_args */) { // TODO(Leo) return mk_pair(env, list<name>()); } pair<environment, list<name>> tc_multigraph::add(environment const & env, name const & e) { declaration const & d = env.get(e); return add(env, e, get_arity(d.get_type())); } void tc_multigraph::erase(name const & e) { auto src = m_edges.find(e); if (!src) return; auto succ_lst = m_successors.find(*src); lean_assert(succ_lst); name tgt; list<pair<name, name>> new_succ_lst = filter(*succ_lst, [&](pair<name, name> const & p) { if (p.first == e) { lean_assert(tgt.is_anonymous()); tgt = p.second; return false; } else { return true; } }); lean_assert(!tgt.is_anonymous()); m_successors.insert(*src, new_succ_lst); if (std::all_of(new_succ_lst.begin(), new_succ_lst.end(), [&](pair<name, name> const & p) { return p.second != tgt; })) { // e is the last edge from src to tgt auto pred_lst = m_predecessors.find(tgt); lean_assert(pred_lst); list<name> new_pred_lst = filter(*pred_lst, [&](name const & n) { return n != *src; }); m_predecessors.insert(tgt, new_pred_lst); } m_edges.erase(e); } bool tc_multigraph::is_edge(name const & e) const { return m_edges.contains(e); } bool tc_multigraph::is_node(name const & c) const { return m_successors.contains(c) || m_predecessors.contains(c); } list<pair<name, name>> tc_multigraph::get_successors(name const & c) const { if (auto r = m_successors.find(c)) return *r; else return list<pair<name, name>>(); } list<name> tc_multigraph::get_predecessors(name const & c) const { if (auto r = m_predecessors.find(c)) return *r; else return list<name>(); } } <|endoftext|>
<commit_before>#include "logger.hpp" #include <iostream> #include <iomanip> //for std::put_time #include <ctime> #include "platform.hpp" //Default to flow-logging Log Logger::level = Logger::INFO; //Disabled by default bool Logger::enabled = false; std::ofstream Logger::logfile; void Logger::openLogfile(const std::string path = "logs.txt") { logfile.open(path, std::ios_base::app); auto t = std::time(nullptr); auto tm = *std::localtime(&t); logfile << "\n--** NEW SESSION " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << " **--\n"; } void Logger::closeLogfile() { if(logfile.is_open()) { logfile.close(); } } void Logger::log(const std::string& str, const Log level) { if(level >= Logger::level && Logger::enabled) { switch(level) { case Logger::VERBOSE: { verbose(str); } break; case Logger::INFO: { info(str); } break; case Logger::WARNING: { warning(str); } break; case Logger::ERROR: { error(str); } break; case Logger::UNDEFINED: { /*Disable logging by doing nothing */ } break; } } if(logfile.is_open()) { logfile << str << "\n"; logfile.flush(); } } void Logger::log(std::ostringstream& oss, const Log level) { Logger::log(oss.str(), level); } void Logger::verbose(const std::string& str) { #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;36mVERBOSE\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(VERBOSE):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(VERBOSE):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::verbose(std::ostringstream& oss) { Logger::verbose(oss.str()); } void Logger::info(const std::string& str) { #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;32mINFO\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(INFO):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(INFO):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::info(std::ostringstream& oss) { Logger::info(oss.str()); } void Logger::warning(const std::string& str) { #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;33mWARNING\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(WARNING):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(WARNING):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::warning(std::ostringstream& oss) { Logger::warning(oss.str()); } void Logger::error(const std::string& str) { #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;31mERROR\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(ERROR):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(ERROR):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::error(std::ostringstream& oss) { Logger::error(oss.str()); } void Logger::disable() { Logger::enabled = false; } void Logger::enable() { Logger::enabled = true; }<commit_msg>fixed bug in logger where logs were displayed no matter the log level<commit_after>#include "logger.hpp" #include <iostream> #include <iomanip> //for std::put_time #include <ctime> #include "platform.hpp" //Default to flow-logging Log Logger::level = Logger::INFO; //Disabled by default bool Logger::enabled = false; std::ofstream Logger::logfile; void Logger::openLogfile(const std::string path = "logs.txt") { logfile.open(path, std::ios_base::app); auto t = std::time(nullptr); auto tm = *std::localtime(&t); logfile << "\n--** NEW SESSION " << std::put_time(&tm, "%Y-%m-%d %H:%M:%S") << " **--\n"; } void Logger::closeLogfile() { if(logfile.is_open()) { logfile.close(); } } void Logger::log(const std::string& str, const Log level) { if(level >= Logger::level && Logger::enabled) { switch(level) { case Logger::VERBOSE: { verbose(str); } break; case Logger::INFO: { info(str); } break; case Logger::WARNING: { warning(str); } break; case Logger::ERROR: { error(str); } break; case Logger::UNDEFINED: { /*Disable logging by doing nothing */ } break; } } if(logfile.is_open()) { logfile << str << "\n"; logfile.flush(); } } void Logger::log(std::ostringstream& oss, const Log level) { Logger::log(oss.str(), level); } void Logger::verbose(const std::string& str) { if(Logger::VERBOSE < Logger::level || !Logger::enabled) return; #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;36mVERBOSE\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(VERBOSE):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(VERBOSE):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::verbose(std::ostringstream& oss) { Logger::verbose(oss.str()); } void Logger::info(const std::string& str) { if(Logger::INFO < Logger::level || !Logger::enabled) return; #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;32mINFO\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(INFO):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(INFO):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::info(std::ostringstream& oss) { Logger::info(oss.str()); } void Logger::warning(const std::string& str) { if(Logger::WARNING < Logger::level || !Logger::enabled) return; #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;33mWARNING\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(WARNING):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(WARNING):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::warning(std::ostringstream& oss) { Logger::warning(oss.str()); } void Logger::error(const std::string& str) { if(Logger::ERROR < Logger::level || !Logger::enabled) return; #if PLATFORM == PLATFORM_LINUX std::cout << "\033[1;31mERROR\033[0m: " << str << std::endl; #elif PLATFORM == PLATFORM_APPLE std::cout << "Log(ERROR):\t" << str << std::endl; #elif PLATFORM == PLATFORM_WINDOWS std::cout << "Log(ERROR):\t" << str << std::endl; #elif PLATFORM == UNKNOWN //Disable logging by doing nothing #endif } void Logger::error(std::ostringstream& oss) { Logger::error(oss.str()); } void Logger::disable() { Logger::enabled = false; } void Logger::enable() { Logger::enabled = true; }<|endoftext|>
<commit_before> #include "libcef/browser/CefContext.h" #include <process.h> #include "third_party/WebKit/Source/wtf/Functional.h" #include "third_party/WebKit/public/platform/WebTraceLocation.h" #include "include/internal/cef_win.h" #include "libcef/browser/CefBrowserHostImpl.h" #include "libcef/common/MainDelegate.h" #include "libcef/common/CefContentClient.h" #include "libcef/common/CefCommandLineImpl.h" #include "libcef/common/CefTaskImpl.h" #include "libcef/renderer/CefV8Impl.h" #include "content/browser/WebPage.h" #include "content/web_impl_win/BlinkPlatformImpl.h" #include "content/web_impl_win/WebThreadImpl.h" static CefContext* g_context = nullptr; struct WebkitThreadInitArgs { WebkitThreadInitArgs(CefContext* context, const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, bool* initialized) : m_context(context) , m_args(&args) , m_settings(settings) , m_application(application) , m_initialized(initialized) { } CefContext* context() { return m_context; } const CefMainArgs* args() { return m_args; } CefSettings settings() { return m_settings; } CefRefPtr<CefApp> application() { return m_application; } bool* initialized() { return m_initialized; } private: CefContext* m_context; const CefMainArgs* m_args; CefSettings m_settings; CefRefPtr<CefApp> m_application; bool* m_initialized; }; unsigned CefContext::WebkitThreadEntryPoint(void* param) { content::WebThreadImpl::setThreadName(GetCurrentThreadId(), "uiThread"); WebkitThreadInitArgs* webkitInitArgs = (WebkitThreadInitArgs*)param; webkitInitArgs->context()->InitializeOnWebkitThread( *webkitInitArgs->args(), webkitInitArgs->settings(), webkitInitArgs->application(), webkitInitArgs->initialized()); webkitInitArgs->context()->RunMessageLoop(); webkitInitArgs->context()->FinalizeShutdownOnWebkitThread(); delete webkitInitArgs; return 0; } int CefExecuteProcess(const CefMainArgs& args, CefRefPtr<CefApp> application, void* windows_sandbox_info) { OutputDebugStringW(L"libcef.CefExecuteProcess \n"); if (CefContentClient::Get() && CefContentClient::Get()->application()) CefContentClient::Get()->SetRendererApplication(application); return -1; } bool CefInitialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { OutputDebugStringW(L"libcef.CefInitialize \n"); // Return true if the global context already exists. if (g_context) return true; if (settings.size != sizeof(cef_settings_t)) { NOTREACHED() << "invalid CefSettings structure size"; return false; } g_context = new CefContext(); // Initialize the global context. return g_context->Initialize(args, settings, application, windows_sandbox_info); } void CefDoMessageLoopWork() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } //CefBrowserMessageLoop::current()->DoMessageLoopIteration(); } void CefRunMessageLoop() { CefContext::Get()->RunMessageLoop(); } void CefQuitMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } CefContext::Get()->Quit(); } void CefSetOSModalLoop(bool osModalLoop) { #if defined(OS_WIN) // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } if (CEF_CURRENTLY_ON_UIT()) CefContext::Get()->SetOsModalLoop(osModalLoop); else CEF_POST_BLINK_TASK(TID_UI, WTF::bind(CefSetOSModalLoop, osModalLoop)); #endif // defined(OS_WIN) } void CefShutdown() { CefContext::Get()->FinalizeShutdown(); } void CefEnableHighDPISupport() {} // CefContext CefContext::CefContext() : m_initialized(false) , m_bShuttingDown(false) , m_osModalLoop(false) , m_needHeartbeat(false) , m_appThreadId(0) , m_uiThreadId(0) , m_webkitThreadHandle(NULL) , m_webkitShutdown(false) { } CefContext::~CefContext() { delete m_mainDelegate; } // static CefContext* CefContext::Get() { return g_context; } const CefContext::BrowserList& CefContext::GetBrowserList() { ASSERT(IsUIThread()); return m_browserList; } void CefContext::SetNeedHeartbeat() { if (m_needHeartbeat) return; m_needHeartbeat = true; ::PostThreadMessage(m_uiThreadId, WM_NULL, 0, 0); } void CefContext::ClearNeedHeartbeat() { m_needHeartbeat = false; } void CefContext::FireHeartBeat() { ::EnterCriticalSection(&m_browserListMutex); for (auto it = m_browserList.begin(); it != m_browserList.end(); ++it) { CefBrowserHostImpl* browser = *it; browser->FireHeartbeat(); } ::LeaveCriticalSection(&m_browserListMutex); } void CefContext::FinalizeShutdownOnWebkitThread() { ASSERT(IsUIThread()); CefCommandLine::GetGlobalCommandLine()->Release(); CefRequestContext::GetGlobalContext()->Release(); CefV8IsolateDestroyed(); ASSERT(0 == m_browserList.size()); ::DeleteCriticalSection(&m_browserListMutex); content::BlinkPlatformImpl* platform = (content::BlinkPlatformImpl*)blink::Platform::current(); platform->shutdown(); m_webkitShutdown = true; } void CefContext::FinalizeShutdown() { if (!IsUIThread()) Quit(); else FinalizeShutdownOnWebkitThread(); while (!m_webkitShutdown) { ::Sleep(20); } if (m_webkitThreadHandle) ::CloseHandle(m_webkitThreadHandle); m_webkitThreadHandle = NULL; } void CefContext::RunMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } MSG msg = { 0 }; BOOL bRet = FALSE; LARGE_INTEGER lastFrequency = {0}; while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) { if (WM_QUIT == msg.message) { //ExitMessageLoop(); return; } while (true) { LARGE_INTEGER qpcFrequency; BOOL b = QueryPerformanceCounter(&qpcFrequency); //if (qpcFrequency.LowPart - lastFrequency.LowPart > 15217) { FireHeartBeat(); ClearNeedHeartbeat(); lastFrequency = qpcFrequency; //} do { if (!TranslateAccelerator(msg.hwnd, NULL, &msg)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) msg.hwnd = NULL; if (WM_QUIT == msg.message) { //ExitMessageLoop(); return; } //::Sleep(10); } while (INVALID_HANDLE_VALUE != msg.hwnd && NULL != msg.hwnd); if (NULL == msg.hwnd && !g_context->IsNeedHeartbeat()) { //OutputDebugStringW(L"CefContext::FireHeartBeat break\n"); break; } //::Sleep(10); } } } void CefContext::Quit() { ::PostThreadMessage(m_uiThreadId, WM_QUIT, 0, 0); } bool CefContext::IsUIThread() const { return m_uiThreadId == GetCurrentThreadId(); } bool CefContext::CurrentlyOn(CefThreadId threadId) const { content::BlinkPlatformImpl* platform = (content::BlinkPlatformImpl*)blink::Platform::current(); blink::WebThread* webThread = platform->currentThread(); if (!webThread) return false; bool result = false; switch (threadId) { case TID_RENDERER: case TID_UI: result = (webThread == platform->mainThread()); break; case TID_DB: result = false; break; case TID_FILE: result = false; break; case TID_FILE_USER_BLOCKING: result = false; break; case TID_PROCESS_LAUNCHER: result = false; break; case TID_CACHE: result = false; break; case TID_IO: if (!platform->tryGetIoThread()) result = false; else result = (webThread == platform->tryGetIoThread()); break; default: break; }; return result; } bool CefContext::InitializeOnWebkitThread(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, bool* initialized) { m_uiThreadId = GetCurrentThreadId(); content::WebPage::initBlink(); m_mainDelegate = new CefMainDelegate(application); m_initialized = true; SetNeedHeartbeat(); OnContextInitialized(); *initialized = true; return true; } bool CefContext::Initialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { m_appThreadId = GetCurrentThreadId(); ::InitializeCriticalSection(&m_browserListMutex); base::CommandLine::Init(0, nullptr); m_settings = settings; bool initialized = false; if (settings.multi_threaded_message_loop) { //NOTIMPLEMENTED() << "multi_threaded_message_loop is not supported."; unsigned threadIdentifier = 0; WebkitThreadInitArgs* webkitInitArgs = new WebkitThreadInitArgs(this, args, settings, application, &initialized); m_webkitThreadHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, WebkitThreadEntryPoint, webkitInitArgs, 0, &threadIdentifier)); } else InitializeOnWebkitThread(args, settings, application, &initialized); while (!m_initialized) { Sleep(20); } return true; } void CefContext::OnContextInitialized() { CEF_REQUIRE_UIT(); // Notify the handler. CefRefPtr<CefApp> app = CefContentClient::Get()->application(); if (!app.get()) return; CefRefPtr<CefBrowserProcessHandler> handler = app->GetBrowserProcessHandler(); if (!handler.get()) return; handler->OnContextInitialized(); base::CommandLine* baseCommandLine = base::CommandLine::ForCurrentProcess(); CefRefPtr<CefCommandLineImpl> commandLine = new CefCommandLineImpl(baseCommandLine, false, false); String out = String::format("CefContext::OnContextInitialized 1: %d\n", (unsigned int)commandLine.get()); OutputDebugStringA(out.utf8().data()); commandLine->AppendSwitchWithValue(CefString("type"), CefString("mbrenderer")); handler->OnBeforeChildProcessLaunch(commandLine); out = String::format("CefContext::OnContextInitialized 2: %d\n", (unsigned int)commandLine.get()); OutputDebugStringA(out.utf8().data()); } void CefContext::RegisterBrowser(CefBrowserHostImpl* browser) { ASSERT(IsUIThread()); ASSERT(!m_browserList.contains(browser)); m_browserList.add(browser); } void CefContext::UnregisterBrowser(CefBrowserHostImpl* browser) { ::EnterCriticalSection(&m_browserListMutex); ASSERT(m_browserList.contains(browser)); m_browserList.remove(browser); ::LeaveCriticalSection(&m_browserListMutex); }<commit_msg>* 把线程相关函数单独挪出<commit_after> #include "libcef/browser/CefContext.h" #include <process.h> #include "third_party/WebKit/Source/wtf/Functional.h" #include "third_party/WebKit/public/platform/WebTraceLocation.h" #include "include/internal/cef_win.h" #include "libcef/browser/CefBrowserHostImpl.h" #include "libcef/common/MainDelegate.h" #include "libcef/common/CefContentClient.h" #include "libcef/common/CefCommandLineImpl.h" #include "libcef/common/CefTaskImpl.h" #include "libcef/renderer/CefV8Impl.h" #include "content/browser/WebPage.h" #include "content/web_impl_win/BlinkPlatformImpl.h" #include "content/web_impl_win/WebThreadImpl.h" #include "base/thread.h" static CefContext* g_context = nullptr; struct WebkitThreadInitArgs { WebkitThreadInitArgs(CefContext* context, const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, bool* initialized) : m_context(context) , m_args(&args) , m_settings(settings) , m_application(application) , m_initialized(initialized) { } CefContext* context() { return m_context; } const CefMainArgs* args() { return m_args; } CefSettings settings() { return m_settings; } CefRefPtr<CefApp> application() { return m_application; } bool* initialized() { return m_initialized; } private: CefContext* m_context; const CefMainArgs* m_args; CefSettings m_settings; CefRefPtr<CefApp> m_application; bool* m_initialized; }; unsigned CefContext::WebkitThreadEntryPoint(void* param) { base::SetThreadName("UiThread"); WebkitThreadInitArgs* webkitInitArgs = (WebkitThreadInitArgs*)param; webkitInitArgs->context()->InitializeOnWebkitThread( *webkitInitArgs->args(), webkitInitArgs->settings(), webkitInitArgs->application(), webkitInitArgs->initialized()); webkitInitArgs->context()->RunMessageLoop(); webkitInitArgs->context()->FinalizeShutdownOnWebkitThread(); delete webkitInitArgs; return 0; } int CefExecuteProcess(const CefMainArgs& args, CefRefPtr<CefApp> application, void* windows_sandbox_info) { OutputDebugStringW(L"libcef.CefExecuteProcess \n"); if (CefContentClient::Get() && CefContentClient::Get()->application()) CefContentClient::Get()->SetRendererApplication(application); return -1; } bool CefInitialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { OutputDebugStringW(L"libcef.CefInitialize \n"); // Return true if the global context already exists. if (g_context) return true; if (settings.size != sizeof(cef_settings_t)) { NOTREACHED() << "invalid CefSettings structure size"; return false; } g_context = new CefContext(); // Initialize the global context. return g_context->Initialize(args, settings, application, windows_sandbox_info); } void CefDoMessageLoopWork() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } //CefBrowserMessageLoop::current()->DoMessageLoopIteration(); } void CefRunMessageLoop() { CefContext::Get()->RunMessageLoop(); } void CefQuitMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!g_context->IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } CefContext::Get()->Quit(); } void CefSetOSModalLoop(bool osModalLoop) { #if defined(OS_WIN) // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } if (CEF_CURRENTLY_ON_UIT()) CefContext::Get()->SetOsModalLoop(osModalLoop); else CEF_POST_BLINK_TASK(TID_UI, WTF::bind(CefSetOSModalLoop, osModalLoop)); #endif // defined(OS_WIN) } void CefShutdown() { CefContext::Get()->FinalizeShutdown(); } void CefEnableHighDPISupport() {} // CefContext CefContext::CefContext() : m_initialized(false) , m_bShuttingDown(false) , m_osModalLoop(false) , m_needHeartbeat(false) , m_appThreadId(0) , m_uiThreadId(0) , m_webkitThreadHandle(NULL) , m_webkitShutdown(false) { } CefContext::~CefContext() { delete m_mainDelegate; } // static CefContext* CefContext::Get() { return g_context; } const CefContext::BrowserList& CefContext::GetBrowserList() { ASSERT(IsUIThread()); return m_browserList; } void CefContext::SetNeedHeartbeat() { if (m_needHeartbeat) return; m_needHeartbeat = true; ::PostThreadMessage(m_uiThreadId, WM_NULL, 0, 0); } void CefContext::ClearNeedHeartbeat() { m_needHeartbeat = false; } void CefContext::FireHeartBeat() { ::EnterCriticalSection(&m_browserListMutex); for (auto it = m_browserList.begin(); it != m_browserList.end(); ++it) { CefBrowserHostImpl* browser = *it; browser->FireHeartbeat(); } ::LeaveCriticalSection(&m_browserListMutex); } void CefContext::FinalizeShutdownOnWebkitThread() { ASSERT(IsUIThread()); CefCommandLine::GetGlobalCommandLine()->Release(); CefRequestContext::GetGlobalContext()->Release(); CefV8IsolateDestroyed(); ASSERT(0 == m_browserList.size()); ::DeleteCriticalSection(&m_browserListMutex); content::BlinkPlatformImpl* platform = (content::BlinkPlatformImpl*)blink::Platform::current(); platform->shutdown(); m_webkitShutdown = true; } void CefContext::FinalizeShutdown() { if (!IsUIThread()) Quit(); else FinalizeShutdownOnWebkitThread(); while (!m_webkitShutdown) { ::Sleep(20); } if (m_webkitThreadHandle) ::CloseHandle(m_webkitThreadHandle); m_webkitThreadHandle = NULL; } void CefContext::RunMessageLoop() { // Verify that the context is in a valid state. if (!CONTEXT_STATE_VALID()) { NOTREACHED() << "context not valid"; return; } // Must always be called on the same thread as Initialize. if (!IsUIThread()) { NOTREACHED() << "called on invalid thread"; return; } MSG msg = { 0 }; BOOL bRet = FALSE; LARGE_INTEGER lastFrequency = {0}; while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) { if (WM_QUIT == msg.message) { //ExitMessageLoop(); return; } while (true) { LARGE_INTEGER qpcFrequency; BOOL b = QueryPerformanceCounter(&qpcFrequency); //if (qpcFrequency.LowPart - lastFrequency.LowPart > 15217) { FireHeartBeat(); ClearNeedHeartbeat(); lastFrequency = qpcFrequency; //} do { if (!TranslateAccelerator(msg.hwnd, NULL, &msg)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if (!::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) msg.hwnd = NULL; if (WM_QUIT == msg.message) { //ExitMessageLoop(); return; } //::Sleep(10); } while (INVALID_HANDLE_VALUE != msg.hwnd && NULL != msg.hwnd); if (NULL == msg.hwnd && !g_context->IsNeedHeartbeat()) { //OutputDebugStringW(L"CefContext::FireHeartBeat break\n"); break; } //::Sleep(10); } } } void CefContext::Quit() { ::PostThreadMessage(m_uiThreadId, WM_QUIT, 0, 0); } bool CefContext::IsUIThread() const { return m_uiThreadId == GetCurrentThreadId(); } bool CefContext::CurrentlyOn(CefThreadId threadId) const { content::BlinkPlatformImpl* platform = (content::BlinkPlatformImpl*)blink::Platform::current(); blink::WebThread* webThread = platform->currentThread(); if (!webThread) return false; bool result = false; switch (threadId) { case TID_RENDERER: case TID_UI: result = (webThread == platform->mainThread()); break; case TID_DB: result = false; break; case TID_FILE: result = false; break; case TID_FILE_USER_BLOCKING: result = false; break; case TID_PROCESS_LAUNCHER: result = false; break; case TID_CACHE: result = false; break; case TID_IO: if (!platform->tryGetIoThread()) result = false; else result = (webThread == platform->tryGetIoThread()); break; default: break; }; return result; } bool CefContext::InitializeOnWebkitThread(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, bool* initialized) { m_uiThreadId = GetCurrentThreadId(); content::WebPage::initBlink(); m_mainDelegate = new CefMainDelegate(application); m_initialized = true; SetNeedHeartbeat(); OnContextInitialized(); *initialized = true; return true; } bool CefContext::Initialize(const CefMainArgs& args, const CefSettings& settings, CefRefPtr<CefApp> application, void* windows_sandbox_info) { m_appThreadId = GetCurrentThreadId(); ::InitializeCriticalSection(&m_browserListMutex); base::CommandLine::Init(0, nullptr); m_settings = settings; bool initialized = false; if (settings.multi_threaded_message_loop) { //NOTIMPLEMENTED() << "multi_threaded_message_loop is not supported."; unsigned threadIdentifier = 0; WebkitThreadInitArgs* webkitInitArgs = new WebkitThreadInitArgs(this, args, settings, application, &initialized); m_webkitThreadHandle = reinterpret_cast<HANDLE>(_beginthreadex(0, 0, WebkitThreadEntryPoint, webkitInitArgs, 0, &threadIdentifier)); } else InitializeOnWebkitThread(args, settings, application, &initialized); while (!m_initialized) { Sleep(20); } return true; } void CefContext::OnContextInitialized() { CEF_REQUIRE_UIT(); // Notify the handler. CefRefPtr<CefApp> app = CefContentClient::Get()->application(); if (!app.get()) return; CefRefPtr<CefBrowserProcessHandler> handler = app->GetBrowserProcessHandler(); if (!handler.get()) return; handler->OnContextInitialized(); base::CommandLine* baseCommandLine = base::CommandLine::ForCurrentProcess(); CefRefPtr<CefCommandLineImpl> commandLine = new CefCommandLineImpl(baseCommandLine, false, false); String out = String::format("CefContext::OnContextInitialized 1: %d\n", (unsigned int)commandLine.get()); OutputDebugStringA(out.utf8().data()); commandLine->AppendSwitchWithValue(CefString("type"), CefString("mbrenderer")); handler->OnBeforeChildProcessLaunch(commandLine); out = String::format("CefContext::OnContextInitialized 2: %d\n", (unsigned int)commandLine.get()); OutputDebugStringA(out.utf8().data()); } void CefContext::RegisterBrowser(CefBrowserHostImpl* browser) { ASSERT(IsUIThread()); ASSERT(!m_browserList.contains(browser)); m_browserList.add(browser); } void CefContext::UnregisterBrowser(CefBrowserHostImpl* browser) { ::EnterCriticalSection(&m_browserListMutex); ASSERT(m_browserList.contains(browser)); m_browserList.remove(browser); ::LeaveCriticalSection(&m_browserListMutex); }<|endoftext|>
<commit_before>/* * * Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <map> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "common/tag.h" #include "ngsi/Request.h" #include "rest/ConnectionInfo.h" #include "orionTypes/TypeEntity.h" #include "orionTypes/TypeEntityVector.h" /* **************************************************************************** * * TypeEntityVector::TypeEntityVector - */ TypeEntityVector::TypeEntityVector() { vec.clear(); } /* **************************************************************************** * * TypeEntityVector::render - */ std::string TypeEntityVector::render ( ConnectionInfo* ciP, const std::string& indent, bool comma ) { std::string out = ""; std::string xmlTag = "typeEntities"; std::string jsonTag = "types"; if (vec.size() > 0) { out += startTag(indent, xmlTag, jsonTag, ciP->outFormat, true, true); for (unsigned int ix = 0; ix < vec.size(); ++ix) { out += vec[ix]->render(ciP, indent + " ", ix != vec.size() - 1); } out += endTag(indent, xmlTag, ciP->outFormat, comma, true); } return out; } /* **************************************************************************** * * TypeEntityVector::check - */ std::string TypeEntityVector::check ( ConnectionInfo* ciP, const std::string& indent, const std::string& predetectedError ) { for (unsigned int ix = 0; ix < vec.size(); ++ix) { std::string res; if ((res = vec[ix]->check(ciP, indent, predetectedError)) != "OK") { return res; } } return "OK"; } /* **************************************************************************** * * TypeEntityVector::present - */ void TypeEntityVector::present(const std::string& indent) { PRINTF("%lu TypeEntitys", (uint64_t) vec.size()); for (unsigned int ix = 0; ix < vec.size(); ++ix) { vec[ix]->present(indent); } } /* **************************************************************************** * * TypeEntityVector::push_back - */ void TypeEntityVector::push_back(TypeEntity* item) { vec.push_back(item); } /* **************************************************************************** * * TypeEntityVector::get - */ TypeEntity* TypeEntityVector::get(unsigned int ix) { if (ix < vec.size()) return vec[ix]; return NULL; } /* **************************************************************************** * * TypeEntityVector::size - */ unsigned int TypeEntityVector::size(void) { return vec.size(); } /* **************************************************************************** * * TypeEntityVector::release - */ void TypeEntityVector::release(void) { for (unsigned int ix = 0; ix < vec.size(); ++ix) { vec[ix]->release(); delete vec[ix]; } vec.clear(); } <commit_msg>Remove PRINTF macro<commit_after>/* * * Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U * * This file is part of Orion Context Broker. * * Orion Context Broker is free software: you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Orion Context Broker 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 Affero * General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with Orion Context Broker. If not, see http://www.gnu.org/licenses/. * * For those usages not covered by this license please contact with * iot_support at tid dot es * * Author: Ken Zangelin */ #include <stdio.h> #include <map> #include <string> #include <vector> #include "logMsg/logMsg.h" #include "logMsg/traceLevels.h" #include "common/globals.h" #include "common/tag.h" #include "ngsi/Request.h" #include "rest/ConnectionInfo.h" #include "orionTypes/TypeEntity.h" #include "orionTypes/TypeEntityVector.h" /* **************************************************************************** * * TypeEntityVector::TypeEntityVector - */ TypeEntityVector::TypeEntityVector() { vec.clear(); } /* **************************************************************************** * * TypeEntityVector::render - */ std::string TypeEntityVector::render ( ConnectionInfo* ciP, const std::string& indent, bool comma ) { std::string out = ""; std::string xmlTag = "typeEntities"; std::string jsonTag = "types"; if (vec.size() > 0) { out += startTag(indent, xmlTag, jsonTag, ciP->outFormat, true, true); for (unsigned int ix = 0; ix < vec.size(); ++ix) { out += vec[ix]->render(ciP, indent + " ", ix != vec.size() - 1); } out += endTag(indent, xmlTag, ciP->outFormat, comma, true); } return out; } /* **************************************************************************** * * TypeEntityVector::check - */ std::string TypeEntityVector::check ( ConnectionInfo* ciP, const std::string& indent, const std::string& predetectedError ) { for (unsigned int ix = 0; ix < vec.size(); ++ix) { std::string res; if ((res = vec[ix]->check(ciP, indent, predetectedError)) != "OK") { return res; } } return "OK"; } /* **************************************************************************** * * TypeEntityVector::present - */ void TypeEntityVector::present(const std::string& indent) { LM_F(("%lu TypeEntitys", (uint64_t) vec.size())); for (unsigned int ix = 0; ix < vec.size(); ++ix) { vec[ix]->present(indent); } } /* **************************************************************************** * * TypeEntityVector::push_back - */ void TypeEntityVector::push_back(TypeEntity* item) { vec.push_back(item); } /* **************************************************************************** * * TypeEntityVector::get - */ TypeEntity* TypeEntityVector::get(unsigned int ix) { if (ix < vec.size()) return vec[ix]; return NULL; } /* **************************************************************************** * * TypeEntityVector::size - */ unsigned int TypeEntityVector::size(void) { return vec.size(); } /* **************************************************************************** * * TypeEntityVector::release - */ void TypeEntityVector::release(void) { for (unsigned int ix = 0; ix < vec.size(); ++ix) { vec[ix]->release(); delete vec[ix]; } vec.clear(); } <|endoftext|>
<commit_before>//! @file followSymLink.cpp //! @author George FLeming <[email protected]> //! @brief returns whether a path is a symbolic link #include <errno.h> #include <unistd.h> #include <string> #include <iostream> #include "followsymlink.h" #include "issymlink.h" //! @brief Followsymlink determines target path of a sym link //! //! Followsymlink //! //! @param[in] fileName //! @parblock //! A pointer to the buffer that contains the file name //! //! char* is marshaled as an LPStr, which on Linux is UTF-8. //! @endparblock //! //! @exception errno Passes these errors via errno to GetLastError: //! - ERROR_INVALID_PARAMETER: parameter is not valid //! - ERROR_FILE_NOT_FOUND: file does not exist //! - ERROR_ACCESS_DENIED: access is denied //! - ERROR_INVALID_ADDRESS: attempt to access invalid address //! - ERROR_STOPPED_ON_SYMLINK: too many symbolic links //! - ERROR_GEN_FAILURE: I/O error occurred //! - ERROR_INVALID_NAME: file provided is not a symbolic link //! - ERROR_INVALID_FUNCTION: incorrect function //! - ERROR_BAD_PATH_NAME: pathname is too long //! - ERROR_OUTOFMEMORY insufficient kernal memory //! //! @retval target path, or NULL if unsuccessful //! char* FollowSymLink(const char* fileName) { errno = 0; // if filename is null, return null value if (!fileName) { errno = ERROR_INVALID_PARAMETER; return NULL; } //if lstat in IsSymLink returns -1, path does not exist if (IsSymLink(fileName) == -1) { return NULL; } /*If the path is a symlink, the function return the absolute filepath if valid. if not valid, return null*/ if (IsSymLink(fileName) == 0) { //Attempt to resolve with the absolute filepath char actualpath[PATH_MAX+1]; char* realPath = realpath(fileName, actualpath); if (sizeof(realPath) == -1) { switch(errno) { case EACCES: errno = ERROR_ACCESS_DENIED; break; case EFAULT: errno = ERROR_INVALID_ADDRESS; break; case EINVAL: errno = ERROR_INVALID_NAME; break; case EIO: errno = ERROR_GEN_FAILURE; break; case ELOOP: errno = ERROR_STOPPED_ON_SYMLINK; break; case ENAMETOOLONG: errno = ERROR_BAD_PATH_NAME; break; case ENOENT: errno = ERROR_FILE_NOT_FOUND; break; case ENOMEM: errno = ERROR_OUTOFMEMORY; break; case ENOTDIR: errno = ERROR_BAD_PATH_NAME; break; default: errno = ERROR_INVALID_FUNCTION; } return NULL; } return strndup(realPath, strlen(realPath) + 1 ); } /*else the path is not a symlink - but attempt to resolve*/ else { char buffer[PATH_MAX]; ssize_t sz = readlink(fileName, buffer, PATH_MAX); if (sz == -1) { switch(errno) { case EACCES: errno = ERROR_ACCESS_DENIED; break; case EFAULT: errno = ERROR_INVALID_ADDRESS; break; case EINVAL: errno = ERROR_INVALID_NAME; case EIO: errno = ERROR_GEN_FAILURE; break; case ELOOP: errno = ERROR_STOPPED_ON_SYMLINK; break; case ENAMETOOLONG: errno = ERROR_BAD_PATH_NAME; break; case ENOENT: errno = ERROR_FILE_NOT_FOUND; break; case ENOMEM: errno = ERROR_OUTOFMEMORY; break; case ENOTDIR: errno = ERROR_BAD_PATH_NAME; break; default: errno = ERROR_INVALID_FUNCTION; } return NULL; } buffer[sz] = '\0'; return strndup(buffer, sz + 1); } } <commit_msg>changing logic around realpath in followsymlink<commit_after>//! @file followSymLink.cpp //! @author George FLeming <[email protected]> //! @brief returns whether a path is a symbolic link #include <errno.h> #include <unistd.h> #include <string> #include <iostream> #include "followsymlink.h" #include "issymlink.h" //! @brief Followsymlink determines target path of a sym link //! //! Followsymlink //! //! @param[in] fileName //! @parblock //! A pointer to the buffer that contains the file name //! //! char* is marshaled as an LPStr, which on Linux is UTF-8. //! @endparblock //! //! @exception errno Passes these errors via errno to GetLastError: //! - ERROR_INVALID_PARAMETER: parameter is not valid //! - ERROR_FILE_NOT_FOUND: file does not exist //! - ERROR_ACCESS_DENIED: access is denied //! - ERROR_INVALID_ADDRESS: attempt to access invalid address //! - ERROR_STOPPED_ON_SYMLINK: too many symbolic links //! - ERROR_GEN_FAILURE: I/O error occurred //! - ERROR_INVALID_NAME: file provided is not a symbolic link //! - ERROR_INVALID_FUNCTION: incorrect function //! - ERROR_BAD_PATH_NAME: pathname is too long //! - ERROR_OUTOFMEMORY insufficient kernal memory //! //! @retval target path, or NULL if unsuccessful //! char* FollowSymLink(const char* fileName) { errno = 0; // if filename is null, return null value if (!fileName) { errno = ERROR_INVALID_PARAMETER; return NULL; } //if lstat in IsSymLink returns -1, path does not exist if (IsSymLink(fileName) == -1) { return NULL; } /*If the path is a symlink, the function return the absolute filepath if valid. if not valid, return null*/ if (IsSymLink(fileName)) { //Attempt to resolve with the absolute filepath char actualpath[PATH_MAX+1]; char* realPath = realpath(fileName, actualpath); //if realPath is null, go onto the readlink implementation if (realPath == NULL) { char buffer[PATH_MAX]; ssize_t sz = readlink(fileName, buffer, PATH_MAX); if (sz == -1) { switch(errno) { case EACCES: errno = ERROR_ACCESS_DENIED; break; case EFAULT: errno = ERROR_INVALID_ADDRESS; /*If the path is a symlink, the function return the absolute filepath if valid. if not valid, return null*/ break; case EINVAL: errno = ERROR_INVALID_NAME; case EIO: errno = ERROR_GEN_FAILURE; break; case ELOOP: errno = ERROR_STOPPED_ON_SYMLINK; break; case ENAMETOOLONG: errno = ERROR_BAD_PATH_NAME; break; case ENOENT: errno = ERROR_FILE_NOT_FOUND; break; case ENOMEM: errno = ERROR_OUTOFMEMORY; break; case ENOTDIR: errno = ERROR_BAD_PATH_NAME; break; default: errno = ERROR_INVALID_FUNCTION; } return NULL; } buffer[sz] = '\0'; return strndup(buffer, sz + 1); } else { return strndup(realPath, strlen(realPath) + 1 ); } } else { char buffer[PATH_MAX]; ssize_t sz = readlink(fileName, buffer, PATH_MAX); if (sz == -1) { switch(errno) { case EACCES: errno = ERROR_ACCESS_DENIED; break; case EFAULT: errno = ERROR_INVALID_ADDRESS; /*If the path is a symlink, the function return the absolute filepath if valid. if not valid, return null*/ break; case EINVAL: errno = ERROR_INVALID_NAME; case EIO: errno = ERROR_GEN_FAILURE; break; case ELOOP: errno = ERROR_STOPPED_ON_SYMLINK; break; case ENAMETOOLONG: errno = ERROR_BAD_PATH_NAME; break; case ENOENT: errno = ERROR_FILE_NOT_FOUND; break; case ENOMEM: errno = ERROR_OUTOFMEMORY; break; case ENOTDIR: errno = ERROR_BAD_PATH_NAME; break; default: errno = ERROR_INVALID_FUNCTION; } return NULL; } buffer[sz] = '\0'; return strndup(buffer, sz + 1); } } <|endoftext|>
<commit_before>/* messagebox.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "messagebox.h" #include "kleo/job.h" #include <gpgmepp/signingresult.h> #include <gpgmepp/encryptionresult.h> #include <kfiledialog.h> #include <kdialogbase.h> #include <klocale.h> #include <ksavefile.h> #include <kguiitem.h> #include <kdebug.h> #include <qtextedit.h> #include <qtextstream.h> #include <qvbox.h> #include <gpg-error.h> using namespace Kleo; using namespace GpgME; namespace { static KGuiItem KGuiItem_save() { return KGuiItem( i18n("&Save to Disk..."), "filesaveas" ); } static KGuiItem KGuiItem_copy() { return KGuiItem( i18n("&Copy to Clipboard"), "editcopy", i18n("Copy Audit Log to Clipboard") ); } static KGuiItem KGuiItem_showAuditLog() { return KGuiItem( i18n("&Show Audit Log") ); // "view_log"? } class AuditLogViewer : public KDialogBase { // Q_OBJECT public: explicit AuditLogViewer( const QString & log, QWidget * parent=0, const char * name=0, WFlags f=0 ) : KDialogBase( parent, name, false, i18n("View GnuPG Audit Log"), Close|User1|User2, Close, false, KGuiItem_save(), KGuiItem_copy() ), m_textEdit( new QTextEdit( this, "m_textEdit" ) ) { setWFlags( f ); setMainWidget( m_textEdit ); m_textEdit->setTextFormat( QTextEdit::RichText ); m_textEdit->setReadOnly( true ); setAuditLog( log ); } ~AuditLogViewer() {} void setAuditLog( const QString & log ) { m_textEdit->setText( log ); } private: void slotUser1() { const QString fileName = KFileDialog::getSaveFileName( QString(), QString(), this, i18n("Choose File to Save GnuPG Audit Log to") ); if ( fileName.isEmpty() ) return; KSaveFile file( fileName ); if ( QTextStream * const s = file.textStream() ) { *s << m_textEdit->text() << endl; file.close(); } if ( const int err = file.status() ) KMessageBox::error( this, i18n("Couldn't save to file \"%1\": %2") .arg( file.name(), QString::fromLocal8Bit( strerror( err ) ) ), i18n("File Save Error") ); } void slotUser2() { m_textEdit->selectAll(); m_textEdit->copy(); m_textEdit->selectAll( false ); } private: QTextEdit * m_textEdit; }; } // anon namespace // static void MessageBox::auditLog( QWidget * parent, const Job * job, const QString & caption ) { if ( !job ) return; if ( !GpgME::hasFeature( AuditLogFeature ) || !job->isAuditLogSupported() ) { KMessageBox::information( parent, i18n("Your system does not have support for GnuPG Audit Logs"), i18n("System Error") ); return; } const GpgME::Error err = job->auditLogError(); if ( err.code() != GPG_ERR_NO_DATA ) { KMessageBox::information( parent, i18n("An error occurred while trying to retrieve the GnuPG Audit Log:\n%1") .arg( QString::fromLocal8Bit( err.asString() ) ), i18n("GnuPG Audit Log Error") ); return; } const QString log = job->auditLogAsHtml(); if ( log.isEmpty() ) { KMessageBox::information( parent, i18n("No GnuPG Audit Log available for this operation."), i18n("No GnuPG Audit Log") ); return; } auditLog( parent, log, caption ); } // static void MessageBox::auditLog( QWidget * parent, const QString & log, const QString & caption ) { AuditLogViewer * const alv = new AuditLogViewer( "<qt>" + log + "</qt>", parent, "alv", Qt::WDestructiveClose ); alv->setCaption( caption ); alv->show(); } // static void MessageBox::auditLog( QWidget * parent, const Job * job ) { auditLog( parent, job, i18n("GnuPG Audit Log Viewer") ); } // static void MessageBox::auditLog( QWidget * parent, const QString & log ) { auditLog( parent, log, i18n("GnuPG Audit Log Viewer") ); } static QString to_information_string( const SigningResult & result ) { return result.error() ? i18n("Signing failed: %1").arg( QString::fromLocal8Bit( result.error().asString() ) ) : i18n("Signing successful") ; } static QString to_error_string( const SigningResult & result ) { return to_information_string( result ); } static QString to_information_string( const EncryptionResult & result ) { return result.error() ? i18n("Encryption failed: %1").arg( QString::fromLocal8Bit( result.error().asString() ) ) : i18n("Encryption successful") ; } static QString to_error_string( const EncryptionResult & result ) { return to_information_string( result ); } static QString to_information_string( const SigningResult & sresult, const EncryptionResult & eresult ) { return to_information_string( sresult ) + '\n' + to_information_string( eresult ); } static QString to_error_string( const SigningResult & sresult, const EncryptionResult & eresult ) { return to_information_string( sresult, eresult ); } // static void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, int options ) { information( parent, result, job, i18n("Signing Result"), options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, int options ) { error( parent, result, job, i18n("Signing Error"), options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options ); } // static void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, int options ) { information( parent, result, job, i18n("Encryption Result"), options ); } // static void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, int options ) { error( parent, result, job, i18n("Encryption Error"), options ); } // static void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, int options ) { information( parent, sresult, eresult, job, i18n("Encryption Result"), options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( sresult, eresult ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, int options ) { error( parent, sresult, eresult, job, i18n("Encryption Error"), options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( sresult, eresult ), job, caption, options ); } // static bool MessageBox::showAuditLogButton( const Kleo::Job * job ) { if ( !job ) { kdDebug() << "not showing audit log button (no job instance)" << endl; return false; } if ( !GpgME::hasFeature( GpgME::AuditLogFeature ) ) { kdDebug() << "not showing audit log button (gpgme too old)" << endl; return false; } if ( !job->isAuditLogSupported() ) { kdDebug() << "not showing audit log button (not supported)" << endl; return false; } if ( job->auditLogError().code() == GPG_ERR_NO_DATA ) { kdDebug() << "not showing audit log button (GPG_ERR_NO_DATA)" << endl; return false; } if ( !job->auditLogError() && job->auditLogAsHtml().isEmpty() ) { kdDebug() << "not showing audit log button (success, but result empty)" << endl; return false; } return true; } // static void MessageBox::make( QWidget * parent, QMessageBox::Icon icon, const QString & text, const Job * job, const QString & caption, int options ) { KDialogBase * dialog = showAuditLogButton( job ) ? new KDialogBase( caption, KDialogBase::Yes | KDialogBase::No, KDialogBase::Yes, KDialogBase::Yes, parent, "error", true, true, KStdGuiItem::ok(), KGuiItem_showAuditLog() ) : new KDialogBase( caption, KDialogBase::Yes, KDialogBase::Yes, KDialogBase::Yes, parent, "error", true, true, KStdGuiItem::ok() ) ; if ( options & KMessageBox::PlainCaption ) dialog->setPlainCaption( caption ); if ( KDialogBase::No == KMessageBox::createKMessageBox( dialog, icon, text, QStringList(), QString::null, 0, options ) ) auditLog( 0, job ); } <commit_msg>Size the audit log window better (ask the text edit for the first paragraph's size, but limit to 2/3 of screen size)<commit_after>/* messagebox.cpp This file is part of libkleopatra, the KDE keymanagement library Copyright (c) 2004 Klarlvdalens Datakonsult AB Libkleopatra 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. Libkleopatra 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA In addition, as a special exception, the copyright holders give permission to link the code of this program with any edition of the Qt library by Trolltech AS, Norway (or with modified versions of Qt that use the same license as Qt), and distribute linked combinations including the two. You must obey the GNU General Public License in all respects for all of the code used other than Qt. If you modify this file, you may extend this exception to your version of the file, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "messagebox.h" #include "kleo/job.h" #include <gpgmepp/signingresult.h> #include <gpgmepp/encryptionresult.h> #include <kfiledialog.h> #include <kdialogbase.h> #include <klocale.h> #include <ksavefile.h> #include <kguiitem.h> #include <kdebug.h> #include <qtextedit.h> #include <qtextstream.h> #include <qvbox.h> #include <qapplication.h> #include <gpg-error.h> using namespace Kleo; using namespace GpgME; namespace { static KGuiItem KGuiItem_save() { return KGuiItem( i18n("&Save to Disk..."), "filesaveas" ); } static KGuiItem KGuiItem_copy() { return KGuiItem( i18n("&Copy to Clipboard"), "editcopy", i18n("Copy Audit Log to Clipboard") ); } static KGuiItem KGuiItem_showAuditLog() { return KGuiItem( i18n("&Show Audit Log") ); // "view_log"? } class AuditLogViewer : public KDialogBase { // Q_OBJECT public: explicit AuditLogViewer( const QString & log, QWidget * parent=0, const char * name=0, WFlags f=0 ) : KDialogBase( parent, name, false, i18n("View GnuPG Audit Log"), Close|User1|User2, Close, false, KGuiItem_save(), KGuiItem_copy() ), m_textEdit( new QTextEdit( this, "m_textEdit" ) ) { setWFlags( f ); setMainWidget( m_textEdit ); m_textEdit->setTextFormat( QTextEdit::RichText ); m_textEdit->setReadOnly( true ); setAuditLog( log ); } ~AuditLogViewer() {} void setAuditLog( const QString & log ) { m_textEdit->setText( log ); const QRect rect = m_textEdit->paragraphRect( 0 ); kdDebug() << "setAuditLog: rect = " << rect; if ( !rect.isValid() ) return; QSize maxSize = qApp->desktop()->screenGeometry( this ).size() * 2 / 3 ; if ( !maxSize.isValid() ) maxSize = QSize( 640, 480 ); m_textEdit->setMinimumSize( rect.size().boundedTo( maxSize ) ); } private: void slotUser1() { const QString fileName = KFileDialog::getSaveFileName( QString(), QString(), this, i18n("Choose File to Save GnuPG Audit Log to") ); if ( fileName.isEmpty() ) return; KSaveFile file( fileName ); if ( QTextStream * const s = file.textStream() ) { *s << m_textEdit->text() << endl; file.close(); } if ( const int err = file.status() ) KMessageBox::error( this, i18n("Couldn't save to file \"%1\": %2") .arg( file.name(), QString::fromLocal8Bit( strerror( err ) ) ), i18n("File Save Error") ); } void slotUser2() { m_textEdit->selectAll(); m_textEdit->copy(); m_textEdit->selectAll( false ); } private: QTextEdit * m_textEdit; }; } // anon namespace // static void MessageBox::auditLog( QWidget * parent, const Job * job, const QString & caption ) { if ( !job ) return; if ( !GpgME::hasFeature( AuditLogFeature ) || !job->isAuditLogSupported() ) { KMessageBox::information( parent, i18n("Your system does not have support for GnuPG Audit Logs"), i18n("System Error") ); return; } const GpgME::Error err = job->auditLogError(); if ( err.code() != GPG_ERR_NO_DATA ) { KMessageBox::information( parent, i18n("An error occurred while trying to retrieve the GnuPG Audit Log:\n%1") .arg( QString::fromLocal8Bit( err.asString() ) ), i18n("GnuPG Audit Log Error") ); return; } const QString log = job->auditLogAsHtml(); if ( log.isEmpty() ) { KMessageBox::information( parent, i18n("No GnuPG Audit Log available for this operation."), i18n("No GnuPG Audit Log") ); return; } auditLog( parent, log, caption ); } // static void MessageBox::auditLog( QWidget * parent, const QString & log, const QString & caption ) { AuditLogViewer * const alv = new AuditLogViewer( "<qt>" + log + "</qt>", parent, "alv", Qt::WDestructiveClose ); alv->setCaption( caption ); alv->show(); } // static void MessageBox::auditLog( QWidget * parent, const Job * job ) { auditLog( parent, job, i18n("GnuPG Audit Log Viewer") ); } // static void MessageBox::auditLog( QWidget * parent, const QString & log ) { auditLog( parent, log, i18n("GnuPG Audit Log Viewer") ); } static QString to_information_string( const SigningResult & result ) { return result.error() ? i18n("Signing failed: %1").arg( QString::fromLocal8Bit( result.error().asString() ) ) : i18n("Signing successful") ; } static QString to_error_string( const SigningResult & result ) { return to_information_string( result ); } static QString to_information_string( const EncryptionResult & result ) { return result.error() ? i18n("Encryption failed: %1").arg( QString::fromLocal8Bit( result.error().asString() ) ) : i18n("Encryption successful") ; } static QString to_error_string( const EncryptionResult & result ) { return to_information_string( result ); } static QString to_information_string( const SigningResult & sresult, const EncryptionResult & eresult ) { return to_information_string( sresult ) + '\n' + to_information_string( eresult ); } static QString to_error_string( const SigningResult & sresult, const EncryptionResult & eresult ) { return to_information_string( sresult, eresult ); } // static void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, int options ) { information( parent, result, job, i18n("Signing Result"), options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, int options ) { error( parent, result, job, i18n("Signing Error"), options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options ); } // static void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, int options ) { information( parent, result, job, i18n("Encryption Result"), options ); } // static void MessageBox::information( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( result ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, int options ) { error( parent, result, job, i18n("Encryption Error"), options ); } // static void MessageBox::error( QWidget * parent, const EncryptionResult & result, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( result ), job, caption, options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, int options ) { information( parent, sresult, eresult, job, i18n("Encryption Result"), options ); } // static void MessageBox::information( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Information, to_information_string( sresult, eresult ), job, caption, options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, int options ) { error( parent, sresult, eresult, job, i18n("Encryption Error"), options ); } // static void MessageBox::error( QWidget * parent, const SigningResult & sresult, const EncryptionResult & eresult, const Job * job, const QString & caption, int options ) { make( parent, QMessageBox::Critical, to_error_string( sresult, eresult ), job, caption, options ); } // static bool MessageBox::showAuditLogButton( const Kleo::Job * job ) { if ( !job ) { kdDebug() << "not showing audit log button (no job instance)" << endl; return false; } if ( !GpgME::hasFeature( GpgME::AuditLogFeature ) ) { kdDebug() << "not showing audit log button (gpgme too old)" << endl; return false; } if ( !job->isAuditLogSupported() ) { kdDebug() << "not showing audit log button (not supported)" << endl; return false; } if ( job->auditLogError().code() == GPG_ERR_NO_DATA ) { kdDebug() << "not showing audit log button (GPG_ERR_NO_DATA)" << endl; return false; } if ( !job->auditLogError() && job->auditLogAsHtml().isEmpty() ) { kdDebug() << "not showing audit log button (success, but result empty)" << endl; return false; } return true; } // static void MessageBox::make( QWidget * parent, QMessageBox::Icon icon, const QString & text, const Job * job, const QString & caption, int options ) { KDialogBase * dialog = showAuditLogButton( job ) ? new KDialogBase( caption, KDialogBase::Yes | KDialogBase::No, KDialogBase::Yes, KDialogBase::Yes, parent, "error", true, true, KStdGuiItem::ok(), KGuiItem_showAuditLog() ) : new KDialogBase( caption, KDialogBase::Yes, KDialogBase::Yes, KDialogBase::Yes, parent, "error", true, true, KStdGuiItem::ok() ) ; if ( options & KMessageBox::PlainCaption ) dialog->setPlainCaption( caption ); if ( KDialogBase::No == KMessageBox::createKMessageBox( dialog, icon, text, QStringList(), QString::null, 0, options ) ) auditLog( 0, job ); } <|endoftext|>
<commit_before>/*---------------------------------------------------------------------\ | | | _ _ _ _ __ _ | | | | | | | \_/ | / \ | | | | | | | | | |_| | / /\ \ | | | | | |__ | | | | | | / ____ \ | |__ | | |____||_| |_| |_|/ / \ \|____| | | | | ca-mgm library | | | | (C) SUSE Linux Products GmbH | \----------------------------------------------------------------------/ File: DNObject.hpp Author: <Michael Calmer> <[email protected]> Maintainer: <Michael Calmer> <[email protected]> Purpose: /-*/ #ifndef LIMAL_CA_MGM_DN_OBJECT_HPP #define LIMAL_CA_MGM_DN_OBJECT_HPP #include <limal/ca-mgm/config.h> #include <limal/ca-mgm/CommonData.hpp> namespace LIMAL_NAMESPACE { namespace CA_MGM_NAMESPACE { class CAConfig; class RDNObject { public: RDNObject(); RDNObject(const RDNObject& rdn); virtual ~RDNObject(); RDNObject& operator=(const RDNObject& rdn); void setRDNValue(const String& value); String getType() const; String getValue() const; String getOpenSSLValue() const; virtual bool valid() const; virtual blocxx::StringArray verify() const; virtual blocxx::StringArray dump() const; friend bool operator==(const RDNObject &l, const RDNObject &r); friend bool operator<(const RDNObject &l, const RDNObject &r); protected: String type; String value; String prompt; blocxx::UInt32 min; blocxx::UInt32 max; }; class DNObject { public: DNObject(); DNObject(CAConfig* caConfig, Type type); DNObject(const blocxx::List<RDNObject> &dn); DNObject(const DNObject& dn); virtual ~DNObject(); DNObject& operator=(const DNObject& dn); void setDN(const blocxx::List<RDNObject> &dn); blocxx::List<RDNObject> getDN() const; String getOpenSSLString() const; virtual bool valid() const; virtual blocxx::StringArray verify() const; virtual blocxx::StringArray dump() const; private: blocxx::List<RDNObject> dn; blocxx::StringArray checkRDNList(const blocxx::List<RDNObject>& list) const; }; } } #endif // LIMAL_CA_MGM_DN_OBJECT_HPP <commit_msg>make member dn protected<commit_after>/*---------------------------------------------------------------------\ | | | _ _ _ _ __ _ | | | | | | | \_/ | / \ | | | | | | | | | |_| | / /\ \ | | | | | |__ | | | | | | / ____ \ | |__ | | |____||_| |_| |_|/ / \ \|____| | | | | ca-mgm library | | | | (C) SUSE Linux Products GmbH | \----------------------------------------------------------------------/ File: DNObject.hpp Author: <Michael Calmer> <[email protected]> Maintainer: <Michael Calmer> <[email protected]> Purpose: /-*/ #ifndef LIMAL_CA_MGM_DN_OBJECT_HPP #define LIMAL_CA_MGM_DN_OBJECT_HPP #include <limal/ca-mgm/config.h> #include <limal/ca-mgm/CommonData.hpp> namespace LIMAL_NAMESPACE { namespace CA_MGM_NAMESPACE { class CAConfig; class RDNObject { public: RDNObject(); RDNObject(const RDNObject& rdn); virtual ~RDNObject(); RDNObject& operator=(const RDNObject& rdn); void setRDNValue(const String& value); String getType() const; String getValue() const; String getOpenSSLValue() const; virtual bool valid() const; virtual blocxx::StringArray verify() const; virtual blocxx::StringArray dump() const; friend bool operator==(const RDNObject &l, const RDNObject &r); friend bool operator<(const RDNObject &l, const RDNObject &r); protected: String type; String value; String prompt; blocxx::UInt32 min; blocxx::UInt32 max; }; class DNObject { public: DNObject(); DNObject(CAConfig* caConfig, Type type); DNObject(const blocxx::List<RDNObject> &dn); DNObject(const DNObject& dn); virtual ~DNObject(); DNObject& operator=(const DNObject& dn); void setDN(const blocxx::List<RDNObject> &dn); blocxx::List<RDNObject> getDN() const; String getOpenSSLString() const; virtual bool valid() const; virtual blocxx::StringArray verify() const; virtual blocxx::StringArray dump() const; protected: blocxx::List<RDNObject> dn; private: blocxx::StringArray checkRDNList(const blocxx::List<RDNObject>& list) const; }; } } #endif // LIMAL_CA_MGM_DN_OBJECT_HPP <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeolocation.h" #include "qgeolocation_p.h" QT_USE_NAMESPACE QGeoLocationPrivate::QGeoLocationPrivate() : QSharedData() { } QGeoLocationPrivate::QGeoLocationPrivate(const QGeoLocationPrivate &other) : QSharedData() { this->address = other.address; this->coordinate = other.coordinate; this->viewport = other.viewport; } QGeoLocationPrivate::~QGeoLocationPrivate() { } bool QGeoLocationPrivate::operator==(const QGeoLocationPrivate &other) const { return (this->address == other.address && this->coordinate == other.coordinate && this->viewport == other.viewport); } /*! \class QGeoLocation \inmodule QtLocation \ingroup QtLocation-positioning \ingroup QtLocation-places \ingroup QtLocation-places-data \since QtLocation 5.0 \brief The QGeoLocation class represents basic information about a location. A QGeoLocation consists of a coordinate and corresponding address, along with an optional bounding box which is the recommended region to be displayed when viewing the location. */ /*! Constructs an new location object. */ QGeoLocation::QGeoLocation() : d(new QGeoLocationPrivate) { } /*! Constructs a copy of \a other */ QGeoLocation::QGeoLocation(const QGeoLocation &other) :d(other.d) { } /*! Destroys the location object. */ QGeoLocation::~QGeoLocation() { } /*! Assigns \a other to this location and returns a reference to this location. */ QGeoLocation &QGeoLocation::operator =(const QGeoLocation &other) { d = other.d; return *this; } /*! Returns true if this location is equal to \a other, otherwise returns false. */ bool QGeoLocation::operator==(const QGeoLocation &other) const { return (*(d.constData()) == *(other.d.constData())); } /*! Returns the address of the location. */ QGeoAddress QGeoLocation::address() const { return d->address; } /*! Sets the \a address of the location. */ void QGeoLocation::setAddress(const QGeoAddress &address) { d->address = address; } /*! Returns the coordinate of the location. */ QGeoCoordinate QGeoLocation::coordinate() const { return d->coordinate; } /*! Sets the \a coordinate of the location. */ void QGeoLocation::setCoordinate(const QGeoCoordinate &coordinate) { d->coordinate = coordinate; } /*! Returns a bounding box which represents the recommended region to display when viewing this location. */ QGeoBoundingBox QGeoLocation::boundingBox() const { return d->viewport; } /*! Sets the \a boundingBox of the location. */ void QGeoLocation::setBoundingBox(const QGeoBoundingBox &boundingBox) { d->viewport = boundingBox; } <commit_msg>Document QGeoLocation::operator!=().<commit_after>/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtLocation module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qgeolocation.h" #include "qgeolocation_p.h" QT_USE_NAMESPACE QGeoLocationPrivate::QGeoLocationPrivate() : QSharedData() { } QGeoLocationPrivate::QGeoLocationPrivate(const QGeoLocationPrivate &other) : QSharedData() { this->address = other.address; this->coordinate = other.coordinate; this->viewport = other.viewport; } QGeoLocationPrivate::~QGeoLocationPrivate() { } bool QGeoLocationPrivate::operator==(const QGeoLocationPrivate &other) const { return (this->address == other.address && this->coordinate == other.coordinate && this->viewport == other.viewport); } /*! \class QGeoLocation \inmodule QtLocation \ingroup QtLocation-positioning \ingroup QtLocation-places \ingroup QtLocation-places-data \since QtLocation 5.0 \brief The QGeoLocation class represents basic information about a location. A QGeoLocation consists of a coordinate and corresponding address, along with an optional bounding box which is the recommended region to be displayed when viewing the location. */ /*! \fn bool QGeoLocation::operator!=(const QGeoLocation &other) const Returns true if this location is not equal to \a other, otherwise returns false. */ /*! Constructs an new location object. */ QGeoLocation::QGeoLocation() : d(new QGeoLocationPrivate) { } /*! Constructs a copy of \a other */ QGeoLocation::QGeoLocation(const QGeoLocation &other) :d(other.d) { } /*! Destroys the location object. */ QGeoLocation::~QGeoLocation() { } /*! Assigns \a other to this location and returns a reference to this location. */ QGeoLocation &QGeoLocation::operator =(const QGeoLocation &other) { d = other.d; return *this; } /*! Returns true if this location is equal to \a other, otherwise returns false. */ bool QGeoLocation::operator==(const QGeoLocation &other) const { return (*(d.constData()) == *(other.d.constData())); } /*! Returns the address of the location. */ QGeoAddress QGeoLocation::address() const { return d->address; } /*! Sets the \a address of the location. */ void QGeoLocation::setAddress(const QGeoAddress &address) { d->address = address; } /*! Returns the coordinate of the location. */ QGeoCoordinate QGeoLocation::coordinate() const { return d->coordinate; } /*! Sets the \a coordinate of the location. */ void QGeoLocation::setCoordinate(const QGeoCoordinate &coordinate) { d->coordinate = coordinate; } /*! Returns a bounding box which represents the recommended region to display when viewing this location. */ QGeoBoundingBox QGeoLocation::boundingBox() const { return d->viewport; } /*! Sets the \a boundingBox of the location. */ void QGeoLocation::setBoundingBox(const QGeoBoundingBox &boundingBox) { d->viewport = boundingBox; } <|endoftext|>
<commit_before>#include "material.h" #include "simconf.h" #include "functions.h" #include <cmath> #include <iostream> using namespace MyTRIM_NS; MaterialBase::MaterialBase(SimconfType * simconf, Real rho) : _rho(rho), tag(-1), _dirty(true), _simconf(simconf) { } void MaterialBase::prepare() { Real tt = 0.0; // get total stoichiometry for (unsigned int i = 0; i < _element.size(); ++i) { if (_element[i]->_t < 0.0) _element[i]->_t = 0.0; tt += _element[i]->_t; } // normalize relative probabilities to 1 for (unsigned int i = 0; i < _element.size(); ++i) _element[i]->_t /= tt; // average _am = 0.0; _az = 0.0; for (unsigned int i = 0; i < _element.size(); ++i) { _am += _element[i]->_m * _element[i]->_t; _az += Real(_element[i]->_Z) * _element[i]->_t; } _arho = _rho * 0.6022 / _am; //[TRI00310] atoms/Ang^3 } // make sure layers are prepare'd first! void MaterialBase::average(const IonBase * pka) { mu = pka->_m / _am; // universal or firsov screening length a = .5292 * .8853 / (std::pow(Real(pka->_Z), 0.23) + std::pow(_az, 0.23)); //a = .5292 * .8853 / std::pow(pow(Real(pka._Z), 0.5) + std::pow(_az, 0.5), 2.0/3.0); // mean flight path0 f = a * _am / (_az * Real(pka->_Z) * 14.4 * (pka->_m + _am)); //eps0 = e0 * f; epsdg = _simconf->tmin * f * std::pow(1.0 + mu, 2.0) / (4.0 * mu); // fd and kd determine how much recoil energy goes into el. loss and vaccancies fd = std::pow(0.01 * _az, -7.0 / 3.0); kd = std::pow(0.1334 * _az, 2.0 / 3.0) / std::sqrt(_am); for (unsigned int i = 0; i < _element.size(); ++i) { _element[i]->my = pka->_m / _element[i]->_m; _element[i]->ec = 4.0 * _element[i]->my / std::pow(1.0 + _element[i]->my, 2.0); _element[i]->ai = .5292 * .8853 / (std::pow(Real(pka->_Z), 0.23) + std::pow(_element[i]->_Z, 0.23)); //ai = .5292 * .8853 / std::pow(pow(Real(pka._Z), 0.5) + std::pow(_element[i].z, 0.5), 2.0/3.0); _element[i]->fi = _element[i]->ai * _element[i]->_m / (Real(pka->_Z) * Real(_element[i]->_Z) * 14.4 * (pka->_m + _element[i]->_m)); } _dirty = false; } // make sure layers are prepare'd and averaged first! Real MaterialBase::getrstop(const IonBase * pka) { Real se = 0.0; for (unsigned int i = 0; i < _element.size(); ++i) se += rstop(pka, _element[i]->_Z) * _element[i]->_t * _arho; return se; } Real MaterialBase::rpstop(int z2p, Real e) { Real pe, sl, sh, sp, velpwr; const int z2 = z2p - 1; // velocity proportional stopping below pe0 const Real pe0 = 25.0; pe = std::max(pe0, e); // pcoef indices are one less than in the fortran version! sl = (_simconf->pcoef[z2][0] * std::pow(pe, _simconf->pcoef[z2][1])) + (_simconf->pcoef[z2][2] * std::pow(pe, _simconf->pcoef[z2][3])); sh = _simconf->pcoef[z2][4] / std::pow(pe, _simconf->pcoef[z2][5]) * std::log(_simconf->pcoef[z2][6] / pe + _simconf->pcoef[z2][7] * pe); sp = sl * sh / (sl + sh); if (e <= pe0) { // velpwr is the power of velocity stopping below pe0 if (z2p <= 6) velpwr = 0.25; else velpwr = 0.45; sp *= std::pow(e / pe0, velpwr); } return sp; } Real MaterialBase::rstop(const IonBase * ion, int z2) { Real e, vrmin, yrmin, v, vr, yr, vmin, m1; Real a, b, q, /*q1,*/ l, l0, l1; Real zeta; const int z1 = ion->_Z; const Real fz1 = Real(z1); const Real fz2 = Real(z2); Real eee, sp, power; Real se; // scoeff const Real lfctr = _simconf->scoef[z1-1].lfctr; const Real mm1 = _simconf->scoef[z1-1].mm1; const Real vfermi = _simconf->scoef[z2-1].vfermi; //Real atrho = _simconf->scoef[z2-1].atrho; if (ion->_m == 0.0) m1 = mm1; else m1 = ion->_m; // we store ion energy in eV but ee is needed in keV const Real ee = 0.001 * ion->_E; e = ee / m1; if (z1 == 1) { // Hydrogen electronic stopping powers [RST0640] se = rpstop(z2, e); } else if (z1 == 2) { // Helium electronic stopping powers [RST0820] const Real he0 = 1.0; Real he = std::max(he0, e); b = std::log(he); a = 0.2865 + 0.1266 * b - 0.001429 * b*b + 0.02402 * b*b*b - 0.01135 * std::pow(b, 4.0) + 0.001475 * std::pow(b, 5.0); Real heh = 1.0 - std::exp(-std::min(30.0, a)); he = std::max(he, 1.0); a = 1.0 + (0.007 + 0.00005 * fz2) * std::exp(-sqr(7.6 - std::log(he))); heh *= a * a; sp = rpstop(z2, he); se = sp * heh * 4.0; if (e <= he0) se *= std::sqrt(e / he0); } else { // Heavy ion electronic stopping powers [RST0990] yrmin = 0.13; vrmin = 1.0; v = std::sqrt(e / 25.0) / vfermi; if (v >= 1.0) vr = v * vfermi * (1.0 + 1.0 / (5.0 * v*v)); else vr = (3.0 * vfermi / 4.0) * (1.0 + (2.0 * v*v / 3.0) - std::pow(v, 4.0) / 15.0); yr = std::max(yrmin, vr / std::pow(fz1, 0.6667)); yr = std::max(yr, vrmin / std::pow(fz1, 0.6667)); a = -0.803 * std::pow(yr, 0.3) + 1.3167 * std::pow(yr, 0.6) + 0.38157 * yr + 0.008983 * yr*yr; // ionization level of the ion at velocity yr q = std::min(1.0, std::max(0.0, 1.0 - std::exp(-std::min(a, 50.0)))); b = (std::min(0.43, std::max(0.32, 0.12 + 0.025 * fz1))) / std::pow(fz1, 0.3333); l0 = (0.8 - q * std::min(1.2, 0.6 + fz1 / 30.0)) / std::pow(fz1, 0.3333); if (q < 0.2) l1 = 0.0; else if (q < std::max(0.0, 0.9 - 0.025 * fz1)) {//210 // q1 = 0.2; in the original code, but never used l1 = b * (q - 0.2) / std::abs(std::max(0.0, 0.9 - 0.025 * fz1) - 0.2000001); } else if (q < std::max(0.0, 1.0 - 0.025 * std::min(16.0, fz1))) l1 = b; else l1 = b * (1.0 - q) / (0.025 * std::min(16.0, fz1)); l = std::max(l1, l0 * lfctr); zeta = q + (1.0 / (2.0 * vfermi*vfermi)) * (1.0 - q) * std::log(1.0 + sqr(4.0 * l * vfermi / 1.919 )); // add z1^3 effect a = -sqr(7.6 - std::max(0.0, std::log(e))); zeta *= 1.0 + (1.0 / (fz1*fz1)) * (0.18 + 0.0015 * fz2) * std::exp(a); if (yr <= std::max(yrmin, vrmin / std::pow(fz1, 0.6667))) { // calculate velocity stopping for yr < yrmin vrmin = std::max(vrmin, yrmin * std::pow(fz1, 0.6667)); vmin = 0.5 * (vrmin + std::sqrt(std::max(0.0, vrmin*vrmin - 0.8 * vfermi*vfermi))); eee = 25.0 * vmin*vmin; sp = rpstop(z2, eee); if (z2 == 6 || ((z2 == 14 || z2 == 32) && z1 <= 19)) power = 0.375; else power = 0.5; se = sp * sqr(zeta * fz1) * std::pow(e/eee, power); } else { sp = rpstop(z2, e); se = sp * sqr(zeta * fz1); } } // END: heavy-ions return se * 10.0; } <commit_msg>Error out on invalid stoichiometry (#39)<commit_after>#include "material.h" #include "simconf.h" #include "functions.h" #include <cmath> #include <iostream> using namespace MyTRIM_NS; MaterialBase::MaterialBase(SimconfType * simconf, Real rho) : _rho(rho), tag(-1), _dirty(true), _simconf(simconf) { } void MaterialBase::prepare() { Real tt = 0.0; // get total stoichiometry for (unsigned int i = 0; i < _element.size(); ++i) { if (_element[i]->_t < 0.0) _element[i]->_t = 0.0; tt += _element[i]->_t; } #ifdef MYTRIM_ENABLED if (tt == 0.0) mooseError("Stoichiometry invalid, all elements zero."); #endif // normalize relative probabilities to 1 for (unsigned int i = 0; i < _element.size(); ++i) _element[i]->_t /= tt; // average _am = 0.0; _az = 0.0; for (unsigned int i = 0; i < _element.size(); ++i) { _am += _element[i]->_m * _element[i]->_t; _az += Real(_element[i]->_Z) * _element[i]->_t; } _arho = _rho * 0.6022 / _am; //[TRI00310] atoms/Ang^3 } // make sure layers are prepare'd first! void MaterialBase::average(const IonBase * pka) { mu = pka->_m / _am; // universal or firsov screening length a = .5292 * .8853 / (std::pow(Real(pka->_Z), 0.23) + std::pow(_az, 0.23)); //a = .5292 * .8853 / std::pow(pow(Real(pka._Z), 0.5) + std::pow(_az, 0.5), 2.0/3.0); // mean flight path0 f = a * _am / (_az * Real(pka->_Z) * 14.4 * (pka->_m + _am)); //eps0 = e0 * f; epsdg = _simconf->tmin * f * std::pow(1.0 + mu, 2.0) / (4.0 * mu); // fd and kd determine how much recoil energy goes into el. loss and vaccancies fd = std::pow(0.01 * _az, -7.0 / 3.0); kd = std::pow(0.1334 * _az, 2.0 / 3.0) / std::sqrt(_am); for (unsigned int i = 0; i < _element.size(); ++i) { _element[i]->my = pka->_m / _element[i]->_m; _element[i]->ec = 4.0 * _element[i]->my / std::pow(1.0 + _element[i]->my, 2.0); _element[i]->ai = .5292 * .8853 / (std::pow(Real(pka->_Z), 0.23) + std::pow(_element[i]->_Z, 0.23)); //ai = .5292 * .8853 / std::pow(pow(Real(pka._Z), 0.5) + std::pow(_element[i].z, 0.5), 2.0/3.0); _element[i]->fi = _element[i]->ai * _element[i]->_m / (Real(pka->_Z) * Real(_element[i]->_Z) * 14.4 * (pka->_m + _element[i]->_m)); } _dirty = false; } // make sure layers are prepare'd and averaged first! Real MaterialBase::getrstop(const IonBase * pka) { Real se = 0.0; for (unsigned int i = 0; i < _element.size(); ++i) se += rstop(pka, _element[i]->_Z) * _element[i]->_t * _arho; return se; } Real MaterialBase::rpstop(int z2p, Real e) { Real pe, sl, sh, sp, velpwr; const int z2 = z2p - 1; // velocity proportional stopping below pe0 const Real pe0 = 25.0; pe = std::max(pe0, e); // pcoef indices are one less than in the fortran version! sl = (_simconf->pcoef[z2][0] * std::pow(pe, _simconf->pcoef[z2][1])) + (_simconf->pcoef[z2][2] * std::pow(pe, _simconf->pcoef[z2][3])); sh = _simconf->pcoef[z2][4] / std::pow(pe, _simconf->pcoef[z2][5]) * std::log(_simconf->pcoef[z2][6] / pe + _simconf->pcoef[z2][7] * pe); sp = sl * sh / (sl + sh); if (e <= pe0) { // velpwr is the power of velocity stopping below pe0 if (z2p <= 6) velpwr = 0.25; else velpwr = 0.45; sp *= std::pow(e / pe0, velpwr); } return sp; } Real MaterialBase::rstop(const IonBase * ion, int z2) { Real e, vrmin, yrmin, v, vr, yr, vmin, m1; Real a, b, q, /*q1,*/ l, l0, l1; Real zeta; const int z1 = ion->_Z; const Real fz1 = Real(z1); const Real fz2 = Real(z2); Real eee, sp, power; Real se; // scoeff const Real lfctr = _simconf->scoef[z1-1].lfctr; const Real mm1 = _simconf->scoef[z1-1].mm1; const Real vfermi = _simconf->scoef[z2-1].vfermi; //Real atrho = _simconf->scoef[z2-1].atrho; if (ion->_m == 0.0) m1 = mm1; else m1 = ion->_m; // we store ion energy in eV but ee is needed in keV const Real ee = 0.001 * ion->_E; e = ee / m1; if (z1 == 1) { // Hydrogen electronic stopping powers [RST0640] se = rpstop(z2, e); } else if (z1 == 2) { // Helium electronic stopping powers [RST0820] const Real he0 = 1.0; Real he = std::max(he0, e); b = std::log(he); a = 0.2865 + 0.1266 * b - 0.001429 * b*b + 0.02402 * b*b*b - 0.01135 * std::pow(b, 4.0) + 0.001475 * std::pow(b, 5.0); Real heh = 1.0 - std::exp(-std::min(30.0, a)); he = std::max(he, 1.0); a = 1.0 + (0.007 + 0.00005 * fz2) * std::exp(-sqr(7.6 - std::log(he))); heh *= a * a; sp = rpstop(z2, he); se = sp * heh * 4.0; if (e <= he0) se *= std::sqrt(e / he0); } else { // Heavy ion electronic stopping powers [RST0990] yrmin = 0.13; vrmin = 1.0; v = std::sqrt(e / 25.0) / vfermi; if (v >= 1.0) vr = v * vfermi * (1.0 + 1.0 / (5.0 * v*v)); else vr = (3.0 * vfermi / 4.0) * (1.0 + (2.0 * v*v / 3.0) - std::pow(v, 4.0) / 15.0); yr = std::max(yrmin, vr / std::pow(fz1, 0.6667)); yr = std::max(yr, vrmin / std::pow(fz1, 0.6667)); a = -0.803 * std::pow(yr, 0.3) + 1.3167 * std::pow(yr, 0.6) + 0.38157 * yr + 0.008983 * yr*yr; // ionization level of the ion at velocity yr q = std::min(1.0, std::max(0.0, 1.0 - std::exp(-std::min(a, 50.0)))); b = (std::min(0.43, std::max(0.32, 0.12 + 0.025 * fz1))) / std::pow(fz1, 0.3333); l0 = (0.8 - q * std::min(1.2, 0.6 + fz1 / 30.0)) / std::pow(fz1, 0.3333); if (q < 0.2) l1 = 0.0; else if (q < std::max(0.0, 0.9 - 0.025 * fz1)) {//210 // q1 = 0.2; in the original code, but never used l1 = b * (q - 0.2) / std::abs(std::max(0.0, 0.9 - 0.025 * fz1) - 0.2000001); } else if (q < std::max(0.0, 1.0 - 0.025 * std::min(16.0, fz1))) l1 = b; else l1 = b * (1.0 - q) / (0.025 * std::min(16.0, fz1)); l = std::max(l1, l0 * lfctr); zeta = q + (1.0 / (2.0 * vfermi*vfermi)) * (1.0 - q) * std::log(1.0 + sqr(4.0 * l * vfermi / 1.919 )); // add z1^3 effect a = -sqr(7.6 - std::max(0.0, std::log(e))); zeta *= 1.0 + (1.0 / (fz1*fz1)) * (0.18 + 0.0015 * fz2) * std::exp(a); if (yr <= std::max(yrmin, vrmin / std::pow(fz1, 0.6667))) { // calculate velocity stopping for yr < yrmin vrmin = std::max(vrmin, yrmin * std::pow(fz1, 0.6667)); vmin = 0.5 * (vrmin + std::sqrt(std::max(0.0, vrmin*vrmin - 0.8 * vfermi*vfermi))); eee = 25.0 * vmin*vmin; sp = rpstop(z2, eee); if (z2 == 6 || ((z2 == 14 || z2 == 32) && z1 <= 19)) power = 0.375; else power = 0.5; se = sp * sqr(zeta * fz1) * std::pow(e/eee, power); } else { sp = rpstop(z2, e); se = sp * sqr(zeta * fz1); } } // END: heavy-ions return se * 10.0; } <|endoftext|>
<commit_before><commit_msg>add test to make sure only one x axis is non-deleted in exported doc<commit_after><|endoftext|>
<commit_before><commit_msg>Paint infobar background as gradient.<commit_after><|endoftext|>
<commit_before><commit_msg>Fixed on official app name used for unittests that I missed before. Review URL: http://codereview.chromium.org/115637<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/webdriver/dispatch.h" #include <sstream> #include <string> #include <vector> #include "base/format_macros.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/test/webdriver/http_response.h" #include "chrome/test/webdriver/commands/command.h" #include "chrome/test/webdriver/session_manager.h" #include "chrome/test/webdriver/utility_functions.h" namespace webdriver { namespace { bool ForbidsMessageBody(const std::string& request_method, const HttpResponse& response) { return request_method == "HEAD" || response.status() == HttpResponse::kNoContent || response.status() == HttpResponse::kNotModified || (response.status() >= 100 && response.status() < 200); } void DispatchCommand(Command* const command, const std::string& method, Response* response) { if (!command->Init(response)) return; if (method == "POST") { command->ExecutePost(response); } else if (method == "GET") { command->ExecuteGet(response); } else if (method == "DELETE") { command->ExecuteDelete(response); } else { NOTREACHED(); } } void Shutdown(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { base::WaitableEvent* shutdown_event = reinterpret_cast<base::WaitableEvent*>(user_data); mg_printf(connection, "HTTP/1.1 200 OK\r\n\r\n"); shutdown_event->Signal(); } void SendNotImplementedError(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { // Send a well-formed WebDriver JSON error response to ensure clients // handle it correctly. std::string body = base::StringPrintf( "{\"status\":%d,\"value\":{\"message\":" "\"Command has not been implemented yet: %s %s\"}}", kUnknownCommand, request_info->request_method, request_info->uri); std::string header = base::StringPrintf( "HTTP/1.1 501 Not Implemented\r\n" "Content-Type:application/json\r\n" "Content-Length:%" PRIuS "\r\n" "\r\n", body.length()); LOG(ERROR) << header << body; mg_write(connection, header.data(), header.length()); mg_write(connection, body.data(), body.length()); } } // namespace namespace internal { void PrepareHttpResponse(const Response& command_response, HttpResponse* const http_response) { ErrorCode status = command_response.GetStatus(); switch (status) { case kSuccess: http_response->set_status(HttpResponse::kOk); break; // TODO(jleyba): kSeeOther, kBadRequest, kSessionNotFound, // and kMethodNotAllowed should be detected before creating // a command_response, and should thus not need conversion. case kSeeOther: { const Value* const value = command_response.GetValue(); std::string location; if (!value->GetAsString(&location)) { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody("Unable to set 'Location' header: response " "value is not a string: " + command_response.ToJSON()); return; } http_response->AddHeader("Location", location); http_response->set_status(HttpResponse::kSeeOther); break; } case kBadRequest: case kSessionNotFound: http_response->set_status(status); break; case kMethodNotAllowed: { const Value* const value = command_response.GetValue(); if (!value->IsType(Value::TYPE_LIST)) { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody( "Unable to set 'Allow' header: response value was " "not a list of strings: " + command_response.ToJSON()); return; } const ListValue* const list_value = static_cast<const ListValue* const>(value); std::vector<std::string> allowed_methods; for (size_t i = 0; i < list_value->GetSize(); ++i) { std::string method; if (list_value->GetString(i, &method)) { allowed_methods.push_back(method); } else { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody( "Unable to set 'Allow' header: response value was " "not a list of strings: " + command_response.ToJSON()); return; } } http_response->AddHeader("Allow", JoinString(allowed_methods, ',')); http_response->set_status(HttpResponse::kMethodNotAllowed); break; } // All other errors should be treated as generic 500s. The client // will be responsible for inspecting the message body for details. case kInternalServerError: default: http_response->set_status(HttpResponse::kInternalServerError); break; } http_response->SetMimeType("application/json; charset=utf-8"); http_response->SetBody(command_response.ToJSON()); } void SendResponse(struct mg_connection* const connection, const std::string& request_method, const Response& response) { HttpResponse http_response; PrepareHttpResponse(response, &http_response); std::string message_header = base::StringPrintf("HTTP/1.1 %d %s\r\n", http_response.status(), http_response.GetReasonPhrase().c_str()); typedef HttpResponse::HeaderMap::const_iterator HeaderIter; for (HeaderIter header = http_response.headers()->begin(); header != http_response.headers()->end(); ++header) { message_header.append(base::StringPrintf("%s:%s\r\n", header->first.c_str(), header->second.c_str())); } message_header.append("\r\n"); mg_write(connection, message_header.data(), message_header.length()); if (!ForbidsMessageBody(request_method, http_response)) mg_write(connection, http_response.data(), http_response.length()); } bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { VLOG(1) << "...parsing request body"; std::string json(request_info->post_data, request_info->post_data_len); std::string error; if (!ParseJSONDictionary(json, parameters, &error)) { SET_WEBDRIVER_ERROR(response, "Failed to parse command data: " + error + "\n Data: " + json, kBadRequest); return false; } } VLOG(1) << "Parsed " << method << " " << uri << std::string(request_info->post_data, request_info->post_data_len); return true; } void DispatchHelper(Command* command_ptr, const std::string& method, Response* response) { CHECK(method == "GET" || method == "POST" || method == "DELETE"); scoped_ptr<Command> command(command_ptr); if ((method == "GET" && !command->DoesGet()) || (method == "POST" && !command->DoesPost()) || (method == "DELETE" && !command->DoesDelete())) { ListValue* methods = new ListValue; if (command->DoesPost()) methods->Append(Value::CreateStringValue("POST")); if (command->DoesGet()) { methods->Append(Value::CreateStringValue("GET")); methods->Append(Value::CreateStringValue("HEAD")); } if (command->DoesDelete()) methods->Append(Value::CreateStringValue("DELETE")); response->SetStatus(kMethodNotAllowed); response->SetValue(methods); return; } DispatchCommand(command.get(), method, response); } } // namespace internal Dispatcher::Dispatcher(struct mg_context* context, const std::string& root) : context_(context), root_(root) {} Dispatcher::~Dispatcher() {} void Dispatcher::AddShutdown(const std::string& pattern, base::WaitableEvent* shutdown_event) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &Shutdown, NULL); } void Dispatcher::SetNotImplemented(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendNotImplementedError, NULL); } } // namespace webdriver <commit_msg>Fix ChromeDriver shutdown due to regression in 76517. BUG=none TEST=none Review URL: http://codereview.chromium.org/6610004<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/webdriver/dispatch.h" #include <sstream> #include <string> #include <vector> #include "base/format_macros.h" #include "base/logging.h" #include "base/message_loop_proxy.h" #include "base/string_split.h" #include "base/string_util.h" #include "base/stringprintf.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread.h" #include "chrome/test/webdriver/http_response.h" #include "chrome/test/webdriver/commands/command.h" #include "chrome/test/webdriver/session_manager.h" #include "chrome/test/webdriver/utility_functions.h" namespace webdriver { namespace { bool ForbidsMessageBody(const std::string& request_method, const HttpResponse& response) { return request_method == "HEAD" || response.status() == HttpResponse::kNoContent || response.status() == HttpResponse::kNotModified || (response.status() >= 100 && response.status() < 200); } void DispatchCommand(Command* const command, const std::string& method, Response* response) { if (!command->Init(response)) return; if (method == "POST") { command->ExecutePost(response); } else if (method == "GET") { command->ExecuteGet(response); } else if (method == "DELETE") { command->ExecuteDelete(response); } else { NOTREACHED(); } } void Shutdown(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { base::WaitableEvent* shutdown_event = reinterpret_cast<base::WaitableEvent*>(user_data); mg_printf(connection, "HTTP/1.1 200 OK\r\n\r\n"); shutdown_event->Signal(); } void SendNotImplementedError(struct mg_connection* connection, const struct mg_request_info* request_info, void* user_data) { // Send a well-formed WebDriver JSON error response to ensure clients // handle it correctly. std::string body = base::StringPrintf( "{\"status\":%d,\"value\":{\"message\":" "\"Command has not been implemented yet: %s %s\"}}", kUnknownCommand, request_info->request_method, request_info->uri); std::string header = base::StringPrintf( "HTTP/1.1 501 Not Implemented\r\n" "Content-Type:application/json\r\n" "Content-Length:%" PRIuS "\r\n" "\r\n", body.length()); LOG(ERROR) << header << body; mg_write(connection, header.data(), header.length()); mg_write(connection, body.data(), body.length()); } } // namespace namespace internal { void PrepareHttpResponse(const Response& command_response, HttpResponse* const http_response) { ErrorCode status = command_response.GetStatus(); switch (status) { case kSuccess: http_response->set_status(HttpResponse::kOk); break; // TODO(jleyba): kSeeOther, kBadRequest, kSessionNotFound, // and kMethodNotAllowed should be detected before creating // a command_response, and should thus not need conversion. case kSeeOther: { const Value* const value = command_response.GetValue(); std::string location; if (!value->GetAsString(&location)) { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody("Unable to set 'Location' header: response " "value is not a string: " + command_response.ToJSON()); return; } http_response->AddHeader("Location", location); http_response->set_status(HttpResponse::kSeeOther); break; } case kBadRequest: case kSessionNotFound: http_response->set_status(status); break; case kMethodNotAllowed: { const Value* const value = command_response.GetValue(); if (!value->IsType(Value::TYPE_LIST)) { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody( "Unable to set 'Allow' header: response value was " "not a list of strings: " + command_response.ToJSON()); return; } const ListValue* const list_value = static_cast<const ListValue* const>(value); std::vector<std::string> allowed_methods; for (size_t i = 0; i < list_value->GetSize(); ++i) { std::string method; if (list_value->GetString(i, &method)) { allowed_methods.push_back(method); } else { // This should never happen. http_response->set_status(HttpResponse::kInternalServerError); http_response->SetBody( "Unable to set 'Allow' header: response value was " "not a list of strings: " + command_response.ToJSON()); return; } } http_response->AddHeader("Allow", JoinString(allowed_methods, ',')); http_response->set_status(HttpResponse::kMethodNotAllowed); break; } // All other errors should be treated as generic 500s. The client // will be responsible for inspecting the message body for details. case kInternalServerError: default: http_response->set_status(HttpResponse::kInternalServerError); break; } http_response->SetMimeType("application/json; charset=utf-8"); http_response->SetBody(command_response.ToJSON()); } void SendResponse(struct mg_connection* const connection, const std::string& request_method, const Response& response) { HttpResponse http_response; PrepareHttpResponse(response, &http_response); std::string message_header = base::StringPrintf("HTTP/1.1 %d %s\r\n", http_response.status(), http_response.GetReasonPhrase().c_str()); typedef HttpResponse::HeaderMap::const_iterator HeaderIter; for (HeaderIter header = http_response.headers()->begin(); header != http_response.headers()->end(); ++header) { message_header.append(base::StringPrintf("%s:%s\r\n", header->first.c_str(), header->second.c_str())); } message_header.append("\r\n"); mg_write(connection, message_header.data(), message_header.length()); if (!ForbidsMessageBody(request_method, http_response)) mg_write(connection, http_response.data(), http_response.length()); } bool ParseRequestInfo(const struct mg_request_info* const request_info, std::string* method, std::vector<std::string>* path_segments, DictionaryValue** parameters, Response* const response) { *method = request_info->request_method; if (*method == "HEAD") *method = "GET"; else if (*method == "PUT") *method = "POST"; std::string uri(request_info->uri); SessionManager* manager = SessionManager::GetInstance(); uri = uri.substr(manager->url_base().length()); base::SplitString(uri, '/', path_segments); if (*method == "POST" && request_info->post_data_len > 0) { VLOG(1) << "...parsing request body"; std::string json(request_info->post_data, request_info->post_data_len); std::string error; if (!ParseJSONDictionary(json, parameters, &error)) { SET_WEBDRIVER_ERROR(response, "Failed to parse command data: " + error + "\n Data: " + json, kBadRequest); return false; } } VLOG(1) << "Parsed " << method << " " << uri << std::string(request_info->post_data, request_info->post_data_len); return true; } void DispatchHelper(Command* command_ptr, const std::string& method, Response* response) { CHECK(method == "GET" || method == "POST" || method == "DELETE"); scoped_ptr<Command> command(command_ptr); if ((method == "GET" && !command->DoesGet()) || (method == "POST" && !command->DoesPost()) || (method == "DELETE" && !command->DoesDelete())) { ListValue* methods = new ListValue; if (command->DoesPost()) methods->Append(Value::CreateStringValue("POST")); if (command->DoesGet()) { methods->Append(Value::CreateStringValue("GET")); methods->Append(Value::CreateStringValue("HEAD")); } if (command->DoesDelete()) methods->Append(Value::CreateStringValue("DELETE")); response->SetStatus(kMethodNotAllowed); response->SetValue(methods); return; } DispatchCommand(command.get(), method, response); } } // namespace internal Dispatcher::Dispatcher(struct mg_context* context, const std::string& root) : context_(context), root_(root) {} Dispatcher::~Dispatcher() {} void Dispatcher::AddShutdown(const std::string& pattern, base::WaitableEvent* shutdown_event) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &Shutdown, shutdown_event); } void Dispatcher::SetNotImplemented(const std::string& pattern) { mg_set_uri_callback(context_, (root_ + pattern).c_str(), &SendNotImplementedError, NULL); } } // namespace webdriver <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBoxSpatialObjectTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif /** * This is a test file for the itkBoxSpatialObject class. */ #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectToImageFilter.h" #include "itkBoxSpatialObject.h" int itkBoxSpatialObjectTest( int argc, char *argv[] ) { if (argc < 2) { std::cerr << "Missing Parameters: Usage " << argv[0] << "OutputImageFile" << std::endl; } const unsigned int Dimension = 2; typedef itk::GroupSpatialObject< Dimension > SceneType; typedef itk::BoxSpatialObject< Dimension > BoxType; typedef itk::Image< unsigned char, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; typedef itk::SpatialObjectToImageFilter< SceneType, OutputImageType > SpatialObjectToImageFilterType; SceneType::Pointer scene = SceneType::New(); BoxType::Pointer box1 = BoxType::New(); BoxType::Pointer box2 = BoxType::New(); box1->SetId(1); scene->AddSpatialObject(box1); scene->AddSpatialObject(box2); BoxType::SizeType boxsize1; BoxType::SizeType boxsize2; boxsize1[0] = 30; boxsize1[1] = 30; box1->SetSize( boxsize1 ); boxsize2[0] = 30; boxsize2[1] = 30; box2->SetSize( boxsize2 ); BoxType::TransformType::OffsetType offset1; BoxType::TransformType::OffsetType offset2; offset1[0] = 29.0; offset1[1] = 29.0; box1->GetObjectToParentTransform()->SetOffset( offset1 ); box1->ComputeObjectToWorldTransform(); offset2[0] = 50.0; offset2[1] = 50.0; box2->GetObjectToParentTransform()->SetOffset( offset2 ); box2->ComputeObjectToWorldTransform(); box1->ComputeBoundingBox(); box2->ComputeBoundingBox(); std::cout <<"Test ComputeBoundingBox: " << std::endl; std::cout << box1->GetBoundingBox()->GetBounds() << std::endl; std::cout << box2->GetBoundingBox()->GetBounds() << std::endl; BoxType::BoundingBoxType * boundingBox = box1->GetBoundingBox(); if( (boundingBox->GetBounds()[0]!= 29) || (boundingBox->GetBounds()[1]!= 59) || (boundingBox->GetBounds()[2]!= 29) || (boundingBox->GetBounds()[3]!= 59) ) { std::cout << "[FAILED] Test returned" << std::endl; std::cout << box1->GetBoundingBox()->GetBounds() << std::endl; std::cout << "Instead of [29 59 29 59]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // Point consistency std::cout << "Test Is Inside: "; itk::Point<double,2> in; in[0]=30.0;in[1]=30.0; itk::Point<double,2> out; out[0]=0;out[1]=4; if(!box1->IsInside(in)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } if(box1->IsInside(out)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Test ObjectToWorldTransform " << std::endl; BoxType::TransformType::OffsetType translation; translation[0] = 5.0; translation[1] = 5.0; box1->GetObjectToParentTransform()->Translate( translation ); box1->GetObjectToParentTransform()->SetOffset( offset1 ); box1->ComputeObjectToWorldTransform(); box2->GetObjectToParentTransform()->Translate( translation ); box2->GetObjectToParentTransform()->SetOffset( offset2 ); box2->ComputeObjectToWorldTransform(); SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New(); imageFilter->SetInput( scene ); OutputImageType::SizeType size; size[ 0 ] = 100; size[ 1 ] = 100; imageFilter->SetSize( size ); SpatialObjectToImageFilterType::PointType origin; origin[0]=0; origin[1]=0; imageFilter->SetOrigin( origin ); imageFilter->SetInsideValue( 255 ); imageFilter->SetOutsideValue( 0 ); imageFilter->Update(); const char * outputFilename = argv[1]; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFilename ); writer->SetInput( imageFilter->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } return EXIT_SUCCESS; } <commit_msg>ENH: Now testing the SetProperty()<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkBoxSpatialObjectTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif /** * This is a test file for the itkBoxSpatialObject class. */ #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkGroupSpatialObject.h" #include "itkSpatialObjectToImageFilter.h" #include "itkBoxSpatialObject.h" int itkBoxSpatialObjectTest( int argc, char *argv[] ) { if (argc < 2) { std::cerr << "Missing Parameters: Usage " << argv[0] << "OutputImageFile" << std::endl; } const unsigned int Dimension = 2; typedef itk::GroupSpatialObject< Dimension > SceneType; typedef itk::BoxSpatialObject< Dimension > BoxType; typedef itk::Image< unsigned char, Dimension > OutputImageType; typedef itk::ImageFileWriter< OutputImageType > WriterType; typedef itk::SpatialObjectToImageFilter< SceneType, OutputImageType > SpatialObjectToImageFilterType; SceneType::Pointer scene = SceneType::New(); BoxType::Pointer box1 = BoxType::New(); BoxType::Pointer box2 = BoxType::New(); box1->SetId(1); // Test the SetProperty() typedef BoxType::PropertyType PropertyType; PropertyType::Pointer prop = PropertyType::New(); box1->SetProperty(prop); scene->AddSpatialObject(box1); scene->AddSpatialObject(box2); BoxType::SizeType boxsize1; BoxType::SizeType boxsize2; boxsize1[0] = 30; boxsize1[1] = 30; box1->SetSize( boxsize1 ); boxsize2[0] = 30; boxsize2[1] = 30; box2->SetSize( boxsize2 ); BoxType::TransformType::OffsetType offset1; BoxType::TransformType::OffsetType offset2; offset1[0] = 29.0; offset1[1] = 29.0; box1->GetObjectToParentTransform()->SetOffset( offset1 ); box1->ComputeObjectToWorldTransform(); offset2[0] = 50.0; offset2[1] = 50.0; box2->GetObjectToParentTransform()->SetOffset( offset2 ); box2->ComputeObjectToWorldTransform(); box1->ComputeBoundingBox(); box2->ComputeBoundingBox(); std::cout <<"Test ComputeBoundingBox: " << std::endl; std::cout << box1->GetBoundingBox()->GetBounds() << std::endl; std::cout << box2->GetBoundingBox()->GetBounds() << std::endl; BoxType::BoundingBoxType * boundingBox = box1->GetBoundingBox(); if( (boundingBox->GetBounds()[0]!= 29) || (boundingBox->GetBounds()[1]!= 59) || (boundingBox->GetBounds()[2]!= 29) || (boundingBox->GetBounds()[3]!= 59) ) { std::cout << "[FAILED] Test returned" << std::endl; std::cout << box1->GetBoundingBox()->GetBounds() << std::endl; std::cout << "Instead of [29 59 29 59]" << std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; // Point consistency std::cout << "Test Is Inside: "; itk::Point<double,2> in; in[0]=30.0;in[1]=30.0; itk::Point<double,2> out; out[0]=0;out[1]=4; if(!box1->IsInside(in)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } if(box1->IsInside(out)) { std::cout<<"[FAILED]"<<std::endl; return EXIT_FAILURE; } std::cout << "[PASSED]" << std::endl; std::cout << "Test ObjectToWorldTransform " << std::endl; BoxType::TransformType::OffsetType translation; translation[0] = 5.0; translation[1] = 5.0; box1->GetObjectToParentTransform()->Translate( translation ); box1->GetObjectToParentTransform()->SetOffset( offset1 ); box1->ComputeObjectToWorldTransform(); box2->GetObjectToParentTransform()->Translate( translation ); box2->GetObjectToParentTransform()->SetOffset( offset2 ); box2->ComputeObjectToWorldTransform(); SpatialObjectToImageFilterType::Pointer imageFilter = SpatialObjectToImageFilterType::New(); imageFilter->SetInput( scene ); OutputImageType::SizeType size; size[ 0 ] = 100; size[ 1 ] = 100; imageFilter->SetSize( size ); SpatialObjectToImageFilterType::PointType origin; origin[0]=0; origin[1]=0; imageFilter->SetOrigin( origin ); imageFilter->SetInsideValue( 255 ); imageFilter->SetOutsideValue( 0 ); imageFilter->Update(); const char * outputFilename = argv[1]; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputFilename ); writer->SetInput( imageFilter->GetOutput() ); try { writer->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return -1; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OConnectionPointHelper.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2005-09-09 09:17:39 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ //______________________________________________________________________________________________________________ // my own include //______________________________________________________________________________________________________________ #ifndef _OCONNECTIONPOINTHELPER_HXX #include "OConnectionPointHelper.hxx" #endif //______________________________________________________________________________________________________________ // includes of other projects //______________________________________________________________________________________________________________ //______________________________________________________________________________________________________________ // include of my own project //______________________________________________________________________________________________________________ #ifndef _OCONNECTIONPOINTCONTAINERHELPER_HXX #include "OConnectionPointContainerHelper.hxx" #endif //______________________________________________________________________________________________________________ // namespaces //______________________________________________________________________________________________________________ using namespace ::rtl ; using namespace ::osl ; using namespace ::cppu ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::lang ; namespace unocontrols{ //______________________________________________________________________________________________________________ // construct/destruct //______________________________________________________________________________________________________________ OConnectionPointHelper::OConnectionPointHelper( Mutex& aMutex , OConnectionPointContainerHelper* pContainerImplementation , UNO3_TYPE aType ) : m_aSharedMutex ( aMutex ) , m_oContainerWeakReference ( pContainerImplementation ) , m_pContainerImplementation ( pContainerImplementation ) , m_aInterfaceType ( aType ) { } OConnectionPointHelper::~OConnectionPointHelper() { } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ Any SAL_CALL OConnectionPointHelper::queryInterface( const Type& aType ) throw( RuntimeException ) { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Ask for my own supported interfaces ... Any aReturn ( ::cppu::queryInterface( aType , static_cast< XConnectionPoint* > ( this ) ) ); // If searched interface not supported by this class ... if ( aReturn.hasValue() == sal_False ) { // ... ask baseclasses. aReturn = OWeakObject::queryInterface( aType ); } return aReturn ; } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::acquire() throw() { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Forward to baseclass OWeakObject::acquire(); } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::release() throw() { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Forward to baseclass OWeakObject::release(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Type SAL_CALL OConnectionPointHelper::getConnectionType() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Set default return value, if method failed. if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // If container reference valid, return right type of supported interfaces of THIS connectionpoint. Type aReturnType = m_aInterfaceType ; // Don't forget this! impl_UnlockContainer(); return aReturnType; } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Reference< XConnectionPointContainer > SAL_CALL OConnectionPointHelper::getConnectionPointContainer() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Convert weakreference to correct uno3-reference and return value. It can be NULL, if container destroyed! return Reference< XConnectionPointContainer >( m_oContainerWeakReference.get(), UNO_QUERY ); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::advise( const Reference< XInterface >& xListener ) throw( ListenerExistException , InvalidListenerException , RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // If type of listener not the same for this special container ... Any aCheckType = xListener->queryInterface( m_aInterfaceType ); if ( aCheckType.hasValue() ) { // ... throw an exception. throw InvalidListenerException(); } // ListenerExistException is obsolete!? // Its the same container for XConnectionPointContainer and XConnectionPoint. But only here we must control, if a listener already exist!? // You can add a listener more then one time at XConnectionPointContainer, but here only one ... // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Forward it to OConnectionPointHelperContainer! m_pContainerImplementation->advise( m_aInterfaceType, xListener ); // Don't forget this! impl_UnlockContainer(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::unadvise( const Reference< XInterface >& xListener ) throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Forward it to OConnectionPointHelperContainer! m_pContainerImplementation->unadvise( m_aInterfaceType, xListener ); // Don't forget this! impl_UnlockContainer(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Sequence< Reference< XInterface > > SAL_CALL OConnectionPointHelper::getConnections() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Set default return value, if method failed. Sequence< Reference< XInterface > > seqReturnConnections = Sequence< Reference< XInterface > >(); // Get reference to private member of OConnectionPointHelperContainer! OMultiTypeInterfaceContainerHelper& aSharedContainer = m_pContainerImplementation->impl_getMultiTypeContainer(); // Get pointer to specialized container which hold all interfaces of searched type. OInterfaceContainerHelper* pSpecialContainer = aSharedContainer.getContainer( m_aInterfaceType ); // Get elements of searched type, if somelse exist. if ( pSpecialContainer != NULL ) { seqReturnConnections = pSpecialContainer->getElements(); } // Don't forget this! impl_UnlockContainer(); return seqReturnConnections; } //______________________________________________________________________________________________________________ // private method //______________________________________________________________________________________________________________ sal_Bool OConnectionPointHelper::impl_LockContainer() { // Convert weakreference to hard uno3-reference and return state. // If this reference different from NULL, there exist a hard reference to container. Container-instance can't be destroyed. // Don't forget to "unlock" this reference! m_xLock = m_oContainerWeakReference.get(); return m_xLock.is(); } //______________________________________________________________________________________________________________ // private method //______________________________________________________________________________________________________________ void OConnectionPointHelper::impl_UnlockContainer() { // Free hard uno3-reference to container. // see also "impl_LockContainer()" m_xLock = Reference< XInterface >(); } } // namespace unocontrols <commit_msg>INTEGRATION: CWS changefileheader (1.3.42); FILE MERGED 2008/04/01 12:59:01 thb 1.3.42.2: #i85898# Stripping all external header guards 2008/03/31 13:07:32 rt 1.3.42.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OConnectionPointHelper.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ //______________________________________________________________________________________________________________ // my own include //______________________________________________________________________________________________________________ #include "OConnectionPointHelper.hxx" //______________________________________________________________________________________________________________ // includes of other projects //______________________________________________________________________________________________________________ //______________________________________________________________________________________________________________ // include of my own project //______________________________________________________________________________________________________________ #include "OConnectionPointContainerHelper.hxx" //______________________________________________________________________________________________________________ // namespaces //______________________________________________________________________________________________________________ using namespace ::rtl ; using namespace ::osl ; using namespace ::cppu ; using namespace ::com::sun::star::uno ; using namespace ::com::sun::star::lang ; namespace unocontrols{ //______________________________________________________________________________________________________________ // construct/destruct //______________________________________________________________________________________________________________ OConnectionPointHelper::OConnectionPointHelper( Mutex& aMutex , OConnectionPointContainerHelper* pContainerImplementation , UNO3_TYPE aType ) : m_aSharedMutex ( aMutex ) , m_oContainerWeakReference ( pContainerImplementation ) , m_pContainerImplementation ( pContainerImplementation ) , m_aInterfaceType ( aType ) { } OConnectionPointHelper::~OConnectionPointHelper() { } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ Any SAL_CALL OConnectionPointHelper::queryInterface( const Type& aType ) throw( RuntimeException ) { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Ask for my own supported interfaces ... Any aReturn ( ::cppu::queryInterface( aType , static_cast< XConnectionPoint* > ( this ) ) ); // If searched interface not supported by this class ... if ( aReturn.hasValue() == sal_False ) { // ... ask baseclasses. aReturn = OWeakObject::queryInterface( aType ); } return aReturn ; } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::acquire() throw() { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Forward to baseclass OWeakObject::acquire(); } //____________________________________________________________________________________________________________ // XInterface //____________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::release() throw() { // Attention: // Don't use mutex or guard in this method!!! Is a method of XInterface. // Forward to baseclass OWeakObject::release(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Type SAL_CALL OConnectionPointHelper::getConnectionType() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Set default return value, if method failed. if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // If container reference valid, return right type of supported interfaces of THIS connectionpoint. Type aReturnType = m_aInterfaceType ; // Don't forget this! impl_UnlockContainer(); return aReturnType; } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Reference< XConnectionPointContainer > SAL_CALL OConnectionPointHelper::getConnectionPointContainer() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Convert weakreference to correct uno3-reference and return value. It can be NULL, if container destroyed! return Reference< XConnectionPointContainer >( m_oContainerWeakReference.get(), UNO_QUERY ); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::advise( const Reference< XInterface >& xListener ) throw( ListenerExistException , InvalidListenerException , RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // If type of listener not the same for this special container ... Any aCheckType = xListener->queryInterface( m_aInterfaceType ); if ( aCheckType.hasValue() ) { // ... throw an exception. throw InvalidListenerException(); } // ListenerExistException is obsolete!? // Its the same container for XConnectionPointContainer and XConnectionPoint. But only here we must control, if a listener already exist!? // You can add a listener more then one time at XConnectionPointContainer, but here only one ... // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Forward it to OConnectionPointHelperContainer! m_pContainerImplementation->advise( m_aInterfaceType, xListener ); // Don't forget this! impl_UnlockContainer(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ void SAL_CALL OConnectionPointHelper::unadvise( const Reference< XInterface >& xListener ) throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Forward it to OConnectionPointHelperContainer! m_pContainerImplementation->unadvise( m_aInterfaceType, xListener ); // Don't forget this! impl_UnlockContainer(); } //______________________________________________________________________________________________________________ // XConnectionPoint //______________________________________________________________________________________________________________ Sequence< Reference< XInterface > > SAL_CALL OConnectionPointHelper::getConnections() throw( RuntimeException ) { // Ready for multithreading MutexGuard aGuard( m_aSharedMutex ); // Operation is permitted only, if reference to container is valid! if ( impl_LockContainer() == sal_False ) { // Container not exist! Its an runtime error. throw RuntimeException(); } // Set default return value, if method failed. Sequence< Reference< XInterface > > seqReturnConnections = Sequence< Reference< XInterface > >(); // Get reference to private member of OConnectionPointHelperContainer! OMultiTypeInterfaceContainerHelper& aSharedContainer = m_pContainerImplementation->impl_getMultiTypeContainer(); // Get pointer to specialized container which hold all interfaces of searched type. OInterfaceContainerHelper* pSpecialContainer = aSharedContainer.getContainer( m_aInterfaceType ); // Get elements of searched type, if somelse exist. if ( pSpecialContainer != NULL ) { seqReturnConnections = pSpecialContainer->getElements(); } // Don't forget this! impl_UnlockContainer(); return seqReturnConnections; } //______________________________________________________________________________________________________________ // private method //______________________________________________________________________________________________________________ sal_Bool OConnectionPointHelper::impl_LockContainer() { // Convert weakreference to hard uno3-reference and return state. // If this reference different from NULL, there exist a hard reference to container. Container-instance can't be destroyed. // Don't forget to "unlock" this reference! m_xLock = m_oContainerWeakReference.get(); return m_xLock.is(); } //______________________________________________________________________________________________________________ // private method //______________________________________________________________________________________________________________ void OConnectionPointHelper::impl_UnlockContainer() { // Free hard uno3-reference to container. // see also "impl_LockContainer()" m_xLock = Reference< XInterface >(); } } // namespace unocontrols <|endoftext|>
<commit_before>/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * 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 copyright holders 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 * OWNER 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. */ #include <string> #include "arch/alpha/pseudo_inst.hh" #include "cpu/exec_context.hh" #include "sim/param.hh" #include "sim/serialize.hh" #include "sim/sim_exit.hh" #include "sim/sim_stats.hh" using namespace std; using namespace Statistics; namespace AlphaPseudo { bool doStatisticsInsts; bool doCheckpointInsts; void m5exit_old(ExecContext *xc) { SimExit(curTick, "m5_exit_old instruction encountered"); } void m5exit(ExecContext *xc) { Tick delay = xc->regs.intRegFile[16]; Tick when = curTick + NS2Ticks(delay); SimExit(when, "m5_exit instruction encountered"); } void resetstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Reset, when, repeat); } void dumpstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Dump, when, repeat); } void dumpresetstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Dump|Reset, when, repeat); } void m5checkpoint(ExecContext *xc) { if (!doCheckpointInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupCheckpoint(when, repeat); } class Context : public ParamContext { public: Context(const string &section) : ParamContext(section) {} void checkParams(); }; Context context("PseudoInsts"); Param<bool> __statistics(&context, "statistics", "yes"); Param<bool> __checkpoint(&context, "checkpoint", "yes"); void Context::checkParams() { doStatisticsInsts = __statistics; doCheckpointInsts = __checkpoint; } } <commit_msg>Fix a bug in the pseudo instruction context<commit_after>/* * Copyright (c) 2003 The Regents of The University of Michigan * All rights reserved. * * 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 copyright holders 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 * OWNER 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. */ #include <string> #include "arch/alpha/pseudo_inst.hh" #include "cpu/exec_context.hh" #include "sim/param.hh" #include "sim/serialize.hh" #include "sim/sim_exit.hh" #include "sim/sim_stats.hh" using namespace std; using namespace Statistics; namespace AlphaPseudo { bool doStatisticsInsts; bool doCheckpointInsts; void m5exit_old(ExecContext *xc) { SimExit(curTick, "m5_exit_old instruction encountered"); } void m5exit(ExecContext *xc) { Tick delay = xc->regs.intRegFile[16]; Tick when = curTick + NS2Ticks(delay); SimExit(when, "m5_exit instruction encountered"); } void resetstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Reset, when, repeat); } void dumpstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Dump, when, repeat); } void dumpresetstats(ExecContext *xc) { if (!doStatisticsInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupEvent(Dump|Reset, when, repeat); } void m5checkpoint(ExecContext *xc) { if (!doCheckpointInsts) return; Tick delay = xc->regs.intRegFile[16]; Tick period = xc->regs.intRegFile[17]; Tick when = curTick + NS2Ticks(delay); Tick repeat = NS2Ticks(period); SetupCheckpoint(when, repeat); } class Context : public ParamContext { public: Context(const string &section) : ParamContext(section) {} void checkParams(); }; Context context("PseudoInsts"); Param<bool> __statistics(&context, "statistics", "enable the statistics pseudo instructions", yes); Param<bool> __checkpoint(&context, "checkpoint", "enable the checkpoint pseudo instructions", yes); void Context::checkParams() { doStatisticsInsts = __statistics; doCheckpointInsts = __checkpoint; } } <|endoftext|>
<commit_before>//===- ELFObjHandler.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===-----------------------------------------------------------------------===/ #include "ELFObjHandler.h" #include "llvm/Object/Binary.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ELFTypes.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/TextAPI/ELF/ELFStub.h" using llvm::MemoryBufferRef; using llvm::object::ELFObjectFile; using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; namespace llvm { namespace elfabi { // Simple struct to hold relevant .dynamic entries. struct DynamicEntries { uint64_t StrTabAddr = 0; uint64_t StrSize = 0; Optional<uint64_t> SONameOffset; std::vector<uint64_t> NeededLibNames; // Symbol table: uint64_t DynSymAddr = 0; // Hash tables: Optional<uint64_t> ElfHash; Optional<uint64_t> GnuHash; }; /// This function behaves similarly to StringRef::substr(), but attempts to /// terminate the returned StringRef at the first null terminator. If no null /// terminator is found, an error is returned. /// /// @param Str Source string to create a substring from. /// @param Offset The start index of the desired substring. static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) { size_t StrEnd = Str.find('\0', Offset); if (StrEnd == StringLiteral::npos) { return createError( "String overran bounds of string table (no null terminator)"); } size_t StrLen = StrEnd - Offset; return Str.substr(Offset, StrLen); } /// This function takes an error, and appends a string of text to the end of /// that error. Since "appending" to an Error isn't supported behavior of an /// Error, this function technically creates a new error with the combined /// message and consumes the old error. /// /// @param Err Source error. /// @param After Text to append at the end of Err's error message. Error appendToError(Error Err, StringRef After) { std::string Message; raw_string_ostream Stream(Message); Stream << Err; Stream << " " << After; consumeError(std::move(Err)); return createError(Stream.str().c_str()); } /// This function populates a DynamicEntries struct using an ELFT::DynRange. /// After populating the struct, the members are validated with /// some basic sanity checks. /// /// @param Dyn Target DynamicEntries struct to populate. /// @param DynTable Source dynamic table. template <class ELFT> static Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable) { if (DynTable.empty()) return createError("No .dynamic section found"); // Search .dynamic for relevant entries. bool FoundDynStr = false; bool FoundDynStrSz = false; bool FoundDynSym = false; for (auto &Entry : DynTable) { switch (Entry.d_tag) { case DT_SONAME: Dyn.SONameOffset = Entry.d_un.d_val; break; case DT_STRTAB: Dyn.StrTabAddr = Entry.d_un.d_ptr; FoundDynStr = true; break; case DT_STRSZ: Dyn.StrSize = Entry.d_un.d_val; FoundDynStrSz = true; break; case DT_NEEDED: Dyn.NeededLibNames.push_back(Entry.d_un.d_val); break; case DT_SYMTAB: Dyn.DynSymAddr = Entry.d_un.d_ptr; FoundDynSym = true; break; case DT_HASH: Dyn.ElfHash = Entry.d_un.d_ptr; break; case DT_GNU_HASH: Dyn.GnuHash = Entry.d_un.d_ptr; } } if (!FoundDynStr) { return createError( "Couldn't locate dynamic string table (no DT_STRTAB entry)"); } if (!FoundDynStrSz) { return createError( "Couldn't determine dynamic string table size (no DT_STRSZ entry)"); } if (!FoundDynSym) { return createError( "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)"); } if (Dyn.SONameOffset.hasValue() && *Dyn.SONameOffset >= Dyn.StrSize) { return createStringError( object_error::parse_failed, "DT_SONAME string offset (0x%016x) outside of dynamic string table", *Dyn.SONameOffset); } for (uint64_t Offset : Dyn.NeededLibNames) { if (Offset >= Dyn.StrSize) { return createStringError( object_error::parse_failed, "DT_NEEDED string offset (0x%016x) outside of dynamic string table", Offset); } } return Error::success(); } /// This function finds the number of dynamic symbols using a GNU hash table. /// /// @param Table The GNU hash table for .dynsym. template <class ELFT> static uint64_t getDynSymtabSize(const typename ELFT::GnuHash &Table) { using Elf_Word = typename ELFT::Word; if (Table.nbuckets == 0) return Table.symndx + 1; uint64_t LastSymIdx = 0; uint64_t BucketVal = 0; // Find the index of the first symbol in the last chain. for (Elf_Word Val : Table.buckets()) { BucketVal = std::max(BucketVal, (uint64_t)Val); } LastSymIdx += BucketVal; const Elf_Word *It = reinterpret_cast<const Elf_Word *>(Table.values(BucketVal).end()); // Locate the end of the chain to find the last symbol index. while ((*It & 1) == 0) { LastSymIdx++; It++; } return LastSymIdx + 1; } /// This function determines the number of dynamic symbols. /// Without access to section headers, the number of symbols must be determined /// by parsing dynamic hash tables. /// /// @param Dyn Entries with the locations of hash tables. /// @param ElfFile The ElfFile that the section contents reside in. template <class ELFT> static Expected<uint64_t> getNumSyms(DynamicEntries &Dyn, const ELFFile<ELFT> &ElfFile) { using Elf_Hash = typename ELFT::Hash; using Elf_GnuHash = typename ELFT::GnuHash; // Search GNU hash table to try to find the upper bound of dynsym. if (Dyn.GnuHash.hasValue()) { Expected<const uint8_t *> TablePtr = ElfFile.toMappedAddr(*Dyn.GnuHash); if (!TablePtr) return TablePtr.takeError(); const Elf_GnuHash *Table = reinterpret_cast<const Elf_GnuHash *>(TablePtr.get()); return getDynSymtabSize<ELFT>(*Table); } // Search SYSV hash table to try to find the upper bound of dynsym. if (Dyn.ElfHash.hasValue()) { Expected<const uint8_t *> TablePtr = ElfFile.toMappedAddr(*Dyn.ElfHash); if (!TablePtr) return TablePtr.takeError(); const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get()); return Table->nchain; } return 0; } /// This function extracts symbol type from a symbol's st_info member and /// maps it to an ELFSymbolType enum. /// Currently, STT_NOTYPE, STT_OBJECT, STT_FUNC, and STT_TLS are supported. /// Other symbol types are mapped to ELFSymbolType::Unknown. /// /// @param Info Binary symbol st_info to extract symbol type from. static ELFSymbolType convertInfoToType(uint8_t Info) { Info = Info & 0xf; switch (Info) { case ELF::STT_NOTYPE: return ELFSymbolType::NoType; case ELF::STT_OBJECT: return ELFSymbolType::Object; case ELF::STT_FUNC: return ELFSymbolType::Func; case ELF::STT_TLS: return ELFSymbolType::TLS; default: return ELFSymbolType::Unknown; } } /// This function creates an ELFSymbol and populates all members using /// information from a binary ELFT::Sym. /// /// @param SymName The desired name of the ELFSymbol. /// @param RawSym ELFT::Sym to extract symbol information from. template <class ELFT> static ELFSymbol createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym) { ELFSymbol TargetSym(SymName); uint8_t Binding = RawSym.getBinding(); if (Binding == STB_WEAK) TargetSym.Weak = true; else TargetSym.Weak = false; TargetSym.Undefined = RawSym.isUndefined(); TargetSym.Type = convertInfoToType(RawSym.st_info); if (TargetSym.Type == ELFSymbolType::Func) { TargetSym.Size = 0; } else { TargetSym.Size = RawSym.st_size; } return TargetSym; } /// This function populates an ELFStub with symbols using information read /// from an ELF binary. /// /// @param TargetStub ELFStub to add symbols to. /// @param DynSym Range of dynamic symbols to add to TargetStub. /// @param DynStr StringRef to the dynamic string table. template <class ELFT> static Error populateSymbols(ELFStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr) { // Skips the first symbol since it's the NULL symbol. for (auto RawSym : DynSym.drop_front(1)) { // If a symbol does not have global or weak binding, ignore it. uint8_t Binding = RawSym.getBinding(); if (!(Binding == STB_GLOBAL || Binding == STB_WEAK)) continue; // If a symbol doesn't have default or protected visibility, ignore it. uint8_t Visibility = RawSym.getVisibility(); if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED)) continue; // Create an ELFSymbol and populate it with information from the symbol // table entry. Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name); if (!SymName) return SymName.takeError(); ELFSymbol Sym = createELFSym<ELFT>(*SymName, RawSym); TargetStub.Symbols.insert(std::move(Sym)); // TODO: Populate symbol warning. } return Error::success(); } /// Returns a new ELFStub with all members populated from an ELFObjectFile. /// @param ElfObj Source ELFObjectFile. template <class ELFT> static Expected<std::unique_ptr<ELFStub>> buildStub(const ELFObjectFile<ELFT> &ElfObj) { using Elf_Dyn_Range = typename ELFT::DynRange; using Elf_Phdr_Range = typename ELFT::PhdrRange; using Elf_Sym_Range = typename ELFT::SymRange; using Elf_Sym = typename ELFT::Sym; std::unique_ptr<ELFStub> DestStub = make_unique<ELFStub>(); const ELFFile<ELFT> *ElfFile = ElfObj.getELFFile(); // Fetch .dynamic table. Expected<Elf_Dyn_Range> DynTable = ElfFile->dynamicEntries(); if (!DynTable) { return DynTable.takeError(); } // Fetch program headers. Expected<Elf_Phdr_Range> PHdrs = ElfFile->program_headers(); if (!PHdrs) { return PHdrs.takeError(); } // Collect relevant .dynamic entries. DynamicEntries DynEnt; if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable)) return std::move(Err); // Get pointer to in-memory location of .dynstr section. Expected<const uint8_t *> DynStrPtr = ElfFile->toMappedAddr(DynEnt.StrTabAddr); if (!DynStrPtr) return appendToError(DynStrPtr.takeError(), "when locating .dynstr section contents"); StringRef DynStr(reinterpret_cast<const char *>(DynStrPtr.get()), DynEnt.StrSize); // Populate Arch from ELF header. DestStub->Arch = ElfFile->getHeader()->e_machine; // Populate SoName from .dynamic entries and dynamic string table. if (DynEnt.SONameOffset.hasValue()) { Expected<StringRef> NameOrErr = terminatedSubstr(DynStr, *DynEnt.SONameOffset); if (!NameOrErr) { return appendToError(NameOrErr.takeError(), "when reading DT_SONAME"); } DestStub->SoName = *NameOrErr; } // Populate NeededLibs from .dynamic entries and dynamic string table. for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) { Expected<StringRef> LibNameOrErr = terminatedSubstr(DynStr, NeededStrOffset); if (!LibNameOrErr) { return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED"); } DestStub->NeededLibs.push_back(*LibNameOrErr); } // Populate Symbols from .dynsym table and dynamic string table. Expected<uint64_t> SymCount = getNumSyms(DynEnt, *ElfFile); if (!SymCount) return SymCount.takeError(); if (*SymCount > 0) { // Get pointer to in-memory location of .dynsym section. Expected<const uint8_t *> DynSymPtr = ElfFile->toMappedAddr(DynEnt.DynSymAddr); if (!DynSymPtr) return appendToError(DynSymPtr.takeError(), "when locating .dynsym section contents"); Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount); Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr); if (SymReadError) return appendToError(std::move(SymReadError), "when reading dynamic symbols"); } return std::move(DestStub); } Expected<std::unique_ptr<ELFStub>> readELFFile(MemoryBufferRef Buf) { Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf); if (!BinOrErr) { return BinOrErr.takeError(); } Binary *Bin = BinOrErr->get(); if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) { return buildStub(*Obj); } return createStringError(errc::not_supported, "Unsupported binary format"); } } // end namespace elfabi } // end namespace llvm <commit_msg>[elfabi] Fix the type of the variable formated for error output<commit_after>//===- ELFObjHandler.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===-----------------------------------------------------------------------===/ #include "ELFObjHandler.h" #include "llvm/Object/Binary.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/ELFTypes.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/TextAPI/ELF/ELFStub.h" using llvm::MemoryBufferRef; using llvm::object::ELFObjectFile; using namespace llvm; using namespace llvm::object; using namespace llvm::ELF; namespace llvm { namespace elfabi { // Simple struct to hold relevant .dynamic entries. struct DynamicEntries { uint64_t StrTabAddr = 0; uint64_t StrSize = 0; Optional<uint64_t> SONameOffset; std::vector<uint64_t> NeededLibNames; // Symbol table: uint64_t DynSymAddr = 0; // Hash tables: Optional<uint64_t> ElfHash; Optional<uint64_t> GnuHash; }; /// This function behaves similarly to StringRef::substr(), but attempts to /// terminate the returned StringRef at the first null terminator. If no null /// terminator is found, an error is returned. /// /// @param Str Source string to create a substring from. /// @param Offset The start index of the desired substring. static Expected<StringRef> terminatedSubstr(StringRef Str, size_t Offset) { size_t StrEnd = Str.find('\0', Offset); if (StrEnd == StringLiteral::npos) { return createError( "String overran bounds of string table (no null terminator)"); } size_t StrLen = StrEnd - Offset; return Str.substr(Offset, StrLen); } /// This function takes an error, and appends a string of text to the end of /// that error. Since "appending" to an Error isn't supported behavior of an /// Error, this function technically creates a new error with the combined /// message and consumes the old error. /// /// @param Err Source error. /// @param After Text to append at the end of Err's error message. Error appendToError(Error Err, StringRef After) { std::string Message; raw_string_ostream Stream(Message); Stream << Err; Stream << " " << After; consumeError(std::move(Err)); return createError(Stream.str().c_str()); } /// This function populates a DynamicEntries struct using an ELFT::DynRange. /// After populating the struct, the members are validated with /// some basic sanity checks. /// /// @param Dyn Target DynamicEntries struct to populate. /// @param DynTable Source dynamic table. template <class ELFT> static Error populateDynamic(DynamicEntries &Dyn, typename ELFT::DynRange DynTable) { if (DynTable.empty()) return createError("No .dynamic section found"); // Search .dynamic for relevant entries. bool FoundDynStr = false; bool FoundDynStrSz = false; bool FoundDynSym = false; for (auto &Entry : DynTable) { switch (Entry.d_tag) { case DT_SONAME: Dyn.SONameOffset = Entry.d_un.d_val; break; case DT_STRTAB: Dyn.StrTabAddr = Entry.d_un.d_ptr; FoundDynStr = true; break; case DT_STRSZ: Dyn.StrSize = Entry.d_un.d_val; FoundDynStrSz = true; break; case DT_NEEDED: Dyn.NeededLibNames.push_back(Entry.d_un.d_val); break; case DT_SYMTAB: Dyn.DynSymAddr = Entry.d_un.d_ptr; FoundDynSym = true; break; case DT_HASH: Dyn.ElfHash = Entry.d_un.d_ptr; break; case DT_GNU_HASH: Dyn.GnuHash = Entry.d_un.d_ptr; } } if (!FoundDynStr) { return createError( "Couldn't locate dynamic string table (no DT_STRTAB entry)"); } if (!FoundDynStrSz) { return createError( "Couldn't determine dynamic string table size (no DT_STRSZ entry)"); } if (!FoundDynSym) { return createError( "Couldn't locate dynamic symbol table (no DT_SYMTAB entry)"); } if (Dyn.SONameOffset.hasValue() && *Dyn.SONameOffset >= Dyn.StrSize) { return createStringError( object_error::parse_failed, "DT_SONAME string offset (0x%016" PRIx64 ") outside of dynamic string table", *Dyn.SONameOffset); } for (uint64_t Offset : Dyn.NeededLibNames) { if (Offset >= Dyn.StrSize) { return createStringError( object_error::parse_failed, "DT_NEEDED string offset (0x%016" PRIx64 ") outside of dynamic string table", Offset); } } return Error::success(); } /// This function finds the number of dynamic symbols using a GNU hash table. /// /// @param Table The GNU hash table for .dynsym. template <class ELFT> static uint64_t getDynSymtabSize(const typename ELFT::GnuHash &Table) { using Elf_Word = typename ELFT::Word; if (Table.nbuckets == 0) return Table.symndx + 1; uint64_t LastSymIdx = 0; uint64_t BucketVal = 0; // Find the index of the first symbol in the last chain. for (Elf_Word Val : Table.buckets()) { BucketVal = std::max(BucketVal, (uint64_t)Val); } LastSymIdx += BucketVal; const Elf_Word *It = reinterpret_cast<const Elf_Word *>(Table.values(BucketVal).end()); // Locate the end of the chain to find the last symbol index. while ((*It & 1) == 0) { LastSymIdx++; It++; } return LastSymIdx + 1; } /// This function determines the number of dynamic symbols. /// Without access to section headers, the number of symbols must be determined /// by parsing dynamic hash tables. /// /// @param Dyn Entries with the locations of hash tables. /// @param ElfFile The ElfFile that the section contents reside in. template <class ELFT> static Expected<uint64_t> getNumSyms(DynamicEntries &Dyn, const ELFFile<ELFT> &ElfFile) { using Elf_Hash = typename ELFT::Hash; using Elf_GnuHash = typename ELFT::GnuHash; // Search GNU hash table to try to find the upper bound of dynsym. if (Dyn.GnuHash.hasValue()) { Expected<const uint8_t *> TablePtr = ElfFile.toMappedAddr(*Dyn.GnuHash); if (!TablePtr) return TablePtr.takeError(); const Elf_GnuHash *Table = reinterpret_cast<const Elf_GnuHash *>(TablePtr.get()); return getDynSymtabSize<ELFT>(*Table); } // Search SYSV hash table to try to find the upper bound of dynsym. if (Dyn.ElfHash.hasValue()) { Expected<const uint8_t *> TablePtr = ElfFile.toMappedAddr(*Dyn.ElfHash); if (!TablePtr) return TablePtr.takeError(); const Elf_Hash *Table = reinterpret_cast<const Elf_Hash *>(TablePtr.get()); return Table->nchain; } return 0; } /// This function extracts symbol type from a symbol's st_info member and /// maps it to an ELFSymbolType enum. /// Currently, STT_NOTYPE, STT_OBJECT, STT_FUNC, and STT_TLS are supported. /// Other symbol types are mapped to ELFSymbolType::Unknown. /// /// @param Info Binary symbol st_info to extract symbol type from. static ELFSymbolType convertInfoToType(uint8_t Info) { Info = Info & 0xf; switch (Info) { case ELF::STT_NOTYPE: return ELFSymbolType::NoType; case ELF::STT_OBJECT: return ELFSymbolType::Object; case ELF::STT_FUNC: return ELFSymbolType::Func; case ELF::STT_TLS: return ELFSymbolType::TLS; default: return ELFSymbolType::Unknown; } } /// This function creates an ELFSymbol and populates all members using /// information from a binary ELFT::Sym. /// /// @param SymName The desired name of the ELFSymbol. /// @param RawSym ELFT::Sym to extract symbol information from. template <class ELFT> static ELFSymbol createELFSym(StringRef SymName, const typename ELFT::Sym &RawSym) { ELFSymbol TargetSym(SymName); uint8_t Binding = RawSym.getBinding(); if (Binding == STB_WEAK) TargetSym.Weak = true; else TargetSym.Weak = false; TargetSym.Undefined = RawSym.isUndefined(); TargetSym.Type = convertInfoToType(RawSym.st_info); if (TargetSym.Type == ELFSymbolType::Func) { TargetSym.Size = 0; } else { TargetSym.Size = RawSym.st_size; } return TargetSym; } /// This function populates an ELFStub with symbols using information read /// from an ELF binary. /// /// @param TargetStub ELFStub to add symbols to. /// @param DynSym Range of dynamic symbols to add to TargetStub. /// @param DynStr StringRef to the dynamic string table. template <class ELFT> static Error populateSymbols(ELFStub &TargetStub, const typename ELFT::SymRange DynSym, StringRef DynStr) { // Skips the first symbol since it's the NULL symbol. for (auto RawSym : DynSym.drop_front(1)) { // If a symbol does not have global or weak binding, ignore it. uint8_t Binding = RawSym.getBinding(); if (!(Binding == STB_GLOBAL || Binding == STB_WEAK)) continue; // If a symbol doesn't have default or protected visibility, ignore it. uint8_t Visibility = RawSym.getVisibility(); if (!(Visibility == STV_DEFAULT || Visibility == STV_PROTECTED)) continue; // Create an ELFSymbol and populate it with information from the symbol // table entry. Expected<StringRef> SymName = terminatedSubstr(DynStr, RawSym.st_name); if (!SymName) return SymName.takeError(); ELFSymbol Sym = createELFSym<ELFT>(*SymName, RawSym); TargetStub.Symbols.insert(std::move(Sym)); // TODO: Populate symbol warning. } return Error::success(); } /// Returns a new ELFStub with all members populated from an ELFObjectFile. /// @param ElfObj Source ELFObjectFile. template <class ELFT> static Expected<std::unique_ptr<ELFStub>> buildStub(const ELFObjectFile<ELFT> &ElfObj) { using Elf_Dyn_Range = typename ELFT::DynRange; using Elf_Phdr_Range = typename ELFT::PhdrRange; using Elf_Sym_Range = typename ELFT::SymRange; using Elf_Sym = typename ELFT::Sym; std::unique_ptr<ELFStub> DestStub = make_unique<ELFStub>(); const ELFFile<ELFT> *ElfFile = ElfObj.getELFFile(); // Fetch .dynamic table. Expected<Elf_Dyn_Range> DynTable = ElfFile->dynamicEntries(); if (!DynTable) { return DynTable.takeError(); } // Fetch program headers. Expected<Elf_Phdr_Range> PHdrs = ElfFile->program_headers(); if (!PHdrs) { return PHdrs.takeError(); } // Collect relevant .dynamic entries. DynamicEntries DynEnt; if (Error Err = populateDynamic<ELFT>(DynEnt, *DynTable)) return std::move(Err); // Get pointer to in-memory location of .dynstr section. Expected<const uint8_t *> DynStrPtr = ElfFile->toMappedAddr(DynEnt.StrTabAddr); if (!DynStrPtr) return appendToError(DynStrPtr.takeError(), "when locating .dynstr section contents"); StringRef DynStr(reinterpret_cast<const char *>(DynStrPtr.get()), DynEnt.StrSize); // Populate Arch from ELF header. DestStub->Arch = ElfFile->getHeader()->e_machine; // Populate SoName from .dynamic entries and dynamic string table. if (DynEnt.SONameOffset.hasValue()) { Expected<StringRef> NameOrErr = terminatedSubstr(DynStr, *DynEnt.SONameOffset); if (!NameOrErr) { return appendToError(NameOrErr.takeError(), "when reading DT_SONAME"); } DestStub->SoName = *NameOrErr; } // Populate NeededLibs from .dynamic entries and dynamic string table. for (uint64_t NeededStrOffset : DynEnt.NeededLibNames) { Expected<StringRef> LibNameOrErr = terminatedSubstr(DynStr, NeededStrOffset); if (!LibNameOrErr) { return appendToError(LibNameOrErr.takeError(), "when reading DT_NEEDED"); } DestStub->NeededLibs.push_back(*LibNameOrErr); } // Populate Symbols from .dynsym table and dynamic string table. Expected<uint64_t> SymCount = getNumSyms(DynEnt, *ElfFile); if (!SymCount) return SymCount.takeError(); if (*SymCount > 0) { // Get pointer to in-memory location of .dynsym section. Expected<const uint8_t *> DynSymPtr = ElfFile->toMappedAddr(DynEnt.DynSymAddr); if (!DynSymPtr) return appendToError(DynSymPtr.takeError(), "when locating .dynsym section contents"); Elf_Sym_Range DynSyms = ArrayRef<Elf_Sym>(reinterpret_cast<const Elf_Sym *>(*DynSymPtr), *SymCount); Error SymReadError = populateSymbols<ELFT>(*DestStub, DynSyms, DynStr); if (SymReadError) return appendToError(std::move(SymReadError), "when reading dynamic symbols"); } return std::move(DestStub); } Expected<std::unique_ptr<ELFStub>> readELFFile(MemoryBufferRef Buf) { Expected<std::unique_ptr<Binary>> BinOrErr = createBinary(Buf); if (!BinOrErr) { return BinOrErr.takeError(); } Binary *Bin = BinOrErr->get(); if (auto Obj = dyn_cast<ELFObjectFile<ELF32LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64LE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF32BE>>(Bin)) { return buildStub(*Obj); } else if (auto Obj = dyn_cast<ELFObjectFile<ELF64BE>>(Bin)) { return buildStub(*Obj); } return createStringError(errc::not_supported, "Unsupported binary format"); } } // end namespace elfabi } // end namespace llvm <|endoftext|>
<commit_before>/* exception_handler.cc Jeremy Barnes, 26 February 2008 Copyright (c) 2009 Jeremy Barnes. All rights reserved. */ #include <cxxabi.h> #include <cstring> #include <fstream> #include "jml/compiler/compiler.h" #include "jml/utils/environment.h" #include "backtrace.h" #include "demangle.h" #include "exception.h" #include "exception_hook.h" #include "format.h" #include "threads.h" using namespace std; namespace ML { Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true); __thread bool trace_exceptions = false; __thread bool trace_exceptions_initialized = false; void set_default_trace_exceptions(bool val) { TRACE_EXCEPTIONS.set(val); } bool get_default_trace_exceptions() { return TRACE_EXCEPTIONS; } void set_trace_exceptions(bool trace) { //cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions // << endl; trace_exceptions = trace; trace_exceptions_initialized = true; } bool get_trace_exceptions() { if (!trace_exceptions_initialized) { //cerr << "trace_exceptions initialized to = " // << trace_exceptions << " at " << &trace_exceptions << endl; set_trace_exceptions(TRACE_EXCEPTIONS); trace_exceptions_initialized = true; } //cerr << "get_trace_exceptions returned " << trace_exceptions // << " at " << &trace_exceptions << endl; return trace_exceptions; } static const std::exception * to_std_exception(void* object, const std::type_info * tinfo) { /* Check if its a class. If not, we can't see if it's a std::exception. The abi::__class_type_info is the base class of all types of type info for types that are classes (of which std::exception is one). */ const abi::__class_type_info * ctinfo = dynamic_cast<const abi::__class_type_info *>(tinfo); if (!ctinfo) return 0; /* The thing thrown was an object. Now, check if it is derived from std::exception. */ const std::type_info * etinfo = &typeid(std::exception); /* See if the exception could catch this. This is the mechanism used internally by the compiler in catch {} blocks to see if the exception matches the catch type. In the case of success, the object will be adjusted to point to the start of the std::exception object. */ void * obj_ptr = object; bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0); if (!can_catch) return 0; /* obj_ptr points to a std::exception; extract it and get the exception message. */ return (const std::exception *)obj_ptr; } /** We install this handler for when an exception is thrown. */ void default_exception_tracer(void * object, const std::type_info * tinfo) { //cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions() // << " at " << &trace_exceptions << endl; if (!get_trace_exceptions()) return; const std::exception * exc = to_std_exception(object, tinfo); // We don't want these exceptions to be printed out. if (dynamic_cast<const ML::SilentException *>(exc)) return; /* avoid allocations when std::bad_alloc is thrown */ bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc); size_t bufferSize(1024*1024); char buffer[bufferSize]; char datetime[128]; size_t totalWritten(0), written, remaining(bufferSize); time_t now; time(&now); struct tm lt_tm; strftime(datetime, sizeof(datetime), "%FT%H:%M:%SZ", gmtime_r(&now, &lt_tm)); const char * demangled; char * heapDemangled; if (noAlloc) { heapDemangled = nullptr; demangled = "std::bad_alloc"; } else { heapDemangled = char_demangle(tinfo->name()); demangled = heapDemangled; } auto pid = getpid(); auto tid = gettid(); written = ::snprintf(buffer, remaining, "\n" "--------------------------[Exception thrown]" "---------------------------\n" "time: %s\n" "type: %s\n" "pid: %d; tid: %d\n", datetime, demangled, pid, tid); if (heapDemangled) { free(heapDemangled); } if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; if (exc) { written = snprintf(buffer + totalWritten, remaining, "what: %s\n", exc->what()); if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; } if (noAlloc) { goto end; } written = snprintf(buffer + totalWritten, remaining, "stack:\n"); if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; written = backtrace(buffer + totalWritten, remaining, 3); if (written >= remaining) { goto end; } totalWritten += written; if (totalWritten < bufferSize - 1) { strcpy(buffer + totalWritten, "\n"); } end: cerr << buffer; char const * reports = getenv("ENABLE_EXCEPTION_REPORTS"); if (!noAlloc && reports) { std::string path = ML::format("%s/exception-report-%s-%d-%d.log", reports, datetime, pid, tid); std::ofstream file(path, std::ios_base::app); if(file) { file << getenv("_") << endl; backtrace(file, 3); file.close(); } } } } // namespace ML <commit_msg>PLAT-887: include node name in exception message<commit_after>/* exception_handler.cc Jeremy Barnes, 26 February 2008 Copyright (c) 2009 Jeremy Barnes. All rights reserved. */ #include <sys/utsname.h> #include <cxxabi.h> #include <cstring> #include <fstream> #include "jml/compiler/compiler.h" #include "jml/utils/environment.h" #include "backtrace.h" #include "demangle.h" #include "exception.h" #include "exception_hook.h" #include "format.h" #include "threads.h" using namespace std; namespace ML { Env_Option<bool> TRACE_EXCEPTIONS("JML_TRACE_EXCEPTIONS", true); __thread bool trace_exceptions = false; __thread bool trace_exceptions_initialized = false; void set_default_trace_exceptions(bool val) { TRACE_EXCEPTIONS.set(val); } bool get_default_trace_exceptions() { return TRACE_EXCEPTIONS; } void set_trace_exceptions(bool trace) { //cerr << "set_trace_exceptions to " << trace << " at " << &trace_exceptions // << endl; trace_exceptions = trace; trace_exceptions_initialized = true; } bool get_trace_exceptions() { if (!trace_exceptions_initialized) { //cerr << "trace_exceptions initialized to = " // << trace_exceptions << " at " << &trace_exceptions << endl; set_trace_exceptions(TRACE_EXCEPTIONS); trace_exceptions_initialized = true; } //cerr << "get_trace_exceptions returned " << trace_exceptions // << " at " << &trace_exceptions << endl; return trace_exceptions; } static const std::exception * to_std_exception(void* object, const std::type_info * tinfo) { /* Check if its a class. If not, we can't see if it's a std::exception. The abi::__class_type_info is the base class of all types of type info for types that are classes (of which std::exception is one). */ const abi::__class_type_info * ctinfo = dynamic_cast<const abi::__class_type_info *>(tinfo); if (!ctinfo) return 0; /* The thing thrown was an object. Now, check if it is derived from std::exception. */ const std::type_info * etinfo = &typeid(std::exception); /* See if the exception could catch this. This is the mechanism used internally by the compiler in catch {} blocks to see if the exception matches the catch type. In the case of success, the object will be adjusted to point to the start of the std::exception object. */ void * obj_ptr = object; bool can_catch = etinfo->__do_catch(tinfo, &obj_ptr, 0); if (!can_catch) return 0; /* obj_ptr points to a std::exception; extract it and get the exception message. */ return (const std::exception *)obj_ptr; } /** We install this handler for when an exception is thrown. */ void default_exception_tracer(void * object, const std::type_info * tinfo) { //cerr << "trace_exception: trace_exceptions = " << get_trace_exceptions() // << " at " << &trace_exceptions << endl; if (!get_trace_exceptions()) return; const std::exception * exc = to_std_exception(object, tinfo); // We don't want these exceptions to be printed out. if (dynamic_cast<const ML::SilentException *>(exc)) return; /* avoid allocations when std::bad_alloc is thrown */ bool noAlloc = dynamic_cast<const std::bad_alloc *>(exc); size_t bufferSize(1024*1024); char buffer[bufferSize]; char datetime[128]; size_t totalWritten(0), written, remaining(bufferSize); time_t now; time(&now); struct tm lt_tm; strftime(datetime, sizeof(datetime), "%FT%H:%M:%SZ", gmtime_r(&now, &lt_tm)); const char * demangled; char * heapDemangled; if (noAlloc) { heapDemangled = nullptr; demangled = "std::bad_alloc"; } else { heapDemangled = char_demangle(tinfo->name()); demangled = heapDemangled; } const char *nodeName = "<unknown>"; struct utsname utsName; if (::uname(&utsName) == 0) { nodeName = utsName.nodename; } else { cerr << "error calling uname\n"; } auto pid = getpid(); auto tid = gettid(); written = ::snprintf(buffer, remaining, "\n" "--------------------------[Exception thrown]" "---------------------------\n" "time: %s\n" "type: %s\n" "node: %s\n" "pid: %d; tid: %d\n", datetime, demangled, nodeName, pid, tid); if (heapDemangled) { free(heapDemangled); } if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; if (exc) { written = snprintf(buffer + totalWritten, remaining, "what: %s\n", exc->what()); if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; } if (noAlloc) { goto end; } written = snprintf(buffer + totalWritten, remaining, "stack:\n"); if (written >= remaining) { goto end; } totalWritten += written; remaining -= written; written = backtrace(buffer + totalWritten, remaining, 3); if (written >= remaining) { goto end; } totalWritten += written; if (totalWritten < bufferSize - 1) { strcpy(buffer + totalWritten, "\n"); } end: cerr << buffer; char const * reports = getenv("ENABLE_EXCEPTION_REPORTS"); if (!noAlloc && reports) { std::string path = ML::format("%s/exception-report-%s-%d-%d.log", reports, datetime, pid, tid); std::ofstream file(path, std::ios_base::app); if(file) { file << getenv("_") << endl; backtrace(file, 3); file.close(); } } } } // namespace ML <|endoftext|>
<commit_before>#pragma once #include "loop_awaitable.hpp" BEGIN_ASYNCIO_NAMESPACE; class Sleep : public LoopAWaitable<void> { public: Sleep(EventLoop *loop, uint64_t ms) : LoopAWaitable(loop), _ms(ms) {} void run() override; private: uint64_t _ms; }; using sleep = Sleep; END_ASYNCIO_NAMESPACE;<commit_msg>make sleep loop shedulable<commit_after>#pragma once #include "loop_awaitable.hpp" #include "../coro/coro.hpp" BEGIN_ASYNCIO_NAMESPACE; class Sleep : public LoopAWaitable<void> { public: Sleep(EventLoop *loop, uint64_t ms) : LoopAWaitable(loop), _ms(ms) {} void run() override; private: uint64_t _ms; }; template<class A=DefaultAllocator> coro<void, A> sleep(EventLoop *loop, uint64_t ms) { co_await Sleep(loop, ms); co_return; } END_ASYNCIO_NAMESPACE;<|endoftext|>
<commit_before>#include "tangram.h" #include "platform.h" #include "gl.h" // Input handling // ============== const double double_tap_time = 0.5; // seconds const double scroll_multiplier = 0.05; // scaling for zoom bool was_panning = false; bool rotating = false; bool shoving = false; double last_mouse_up = -double_tap_time; // First click should never trigger a double tap double last_x_down = 0.0; double last_y_down = 0.0; void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button != GLFW_MOUSE_BUTTON_1) { return; // This event is for a mouse button that we don't care about } if (was_panning) { was_panning = false; return; // Clicks with movement don't count as taps } double x, y; glfwGetCursorPos(window, &x, &y); double time = glfwGetTime(); if (action == GLFW_PRESS) { last_x_down = x; last_y_down = y; return; } if (time - last_mouse_up < double_tap_time) { Tangram::handleDoubleTapGesture(x, y); } else { Tangram::handleTapGesture(x, y); } last_mouse_up = time; } void cursor_pos_callback(GLFWwindow* window, double x, double y) { int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1); if (action == GLFW_PRESS) { if (was_panning) { Tangram::handlePanGesture(x - last_x_down, y - last_y_down); } was_panning = true; last_x_down = x; last_y_down = y; } } void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) { double x, y; glfwGetCursorPos(window, &x, &y); if (shoving) { Tangram::handleShoveGesture(scroll_multiplier * scrolly); } else if (rotating) { Tangram::handleRotateGesture(scroll_multiplier * scrolly); } else { Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly); } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { rotating = (mods & GLFW_MOD_SHIFT) != 0; // Whether one or more shift keys is down shoving = (mods & GLFW_MOD_CONTROL) != 0; // Whether one or more control keys is down } // Window handling // =============== void window_size_callback(GLFWwindow* window, int width, int height) { Tangram::resize(width, height); } // Main program // ============ int main(void) { GLFWwindow* window; int width = 800; int height = 600; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ glfwWindowHint(GLFW_SAMPLES, 2); window = glfwCreateWindow(width, height, "GLFW Window", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); Tangram::initialize(); Tangram::resize(width, height); glfwSetWindowSizeCallback(window, window_size_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_pos_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetKeyCallback(window, key_callback); glfwSwapInterval(1); double lastTime = glfwGetTime(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { double currentTime = glfwGetTime(); double delta = currentTime - lastTime; lastTime = currentTime; /* Render here */ Tangram::update(delta); Tangram::render(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } Tangram::teardown(); glfwTerminate(); return 0; } <commit_msg>Update GLFW panning to match new View functionality<commit_after>#include "tangram.h" #include "platform.h" #include "gl.h" // Input handling // ============== const double double_tap_time = 0.5; // seconds const double scroll_multiplier = 0.05; // scaling for zoom bool was_panning = false; bool rotating = false; bool shoving = false; double last_mouse_up = -double_tap_time; // First click should never trigger a double tap double last_x_down = 0.0; double last_y_down = 0.0; void mouse_button_callback(GLFWwindow* window, int button, int action, int mods) { if (button != GLFW_MOUSE_BUTTON_1) { return; // This event is for a mouse button that we don't care about } if (was_panning) { was_panning = false; return; // Clicks with movement don't count as taps } double x, y; glfwGetCursorPos(window, &x, &y); double time = glfwGetTime(); if (action == GLFW_PRESS) { last_x_down = x; last_y_down = y; return; } if (time - last_mouse_up < double_tap_time) { Tangram::handleDoubleTapGesture(x, y); } else { Tangram::handleTapGesture(x, y); } last_mouse_up = time; } void cursor_pos_callback(GLFWwindow* window, double x, double y) { int action = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_1); if (action == GLFW_PRESS) { if (was_panning) { Tangram::handlePanGesture(last_x_down, last_y_down, x, y); } was_panning = true; last_x_down = x; last_y_down = y; } } void scroll_callback(GLFWwindow* window, double scrollx, double scrolly) { double x, y; glfwGetCursorPos(window, &x, &y); if (shoving) { Tangram::handleShoveGesture(scroll_multiplier * scrolly); } else if (rotating) { Tangram::handleRotateGesture(scroll_multiplier * scrolly); } else { Tangram::handlePinchGesture(x, y, 1.0 + scroll_multiplier * scrolly); } } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { rotating = (mods & GLFW_MOD_SHIFT) != 0; // Whether one or more shift keys is down shoving = (mods & GLFW_MOD_CONTROL) != 0; // Whether one or more control keys is down } // Window handling // =============== void window_size_callback(GLFWwindow* window, int width, int height) { Tangram::resize(width, height); } // Main program // ============ int main(void) { GLFWwindow* window; int width = 800; int height = 600; /* Initialize the library */ if (!glfwInit()) return -1; /* Create a windowed mode window and its OpenGL context */ glfwWindowHint(GLFW_SAMPLES, 2); window = glfwCreateWindow(width, height, "GLFW Window", NULL, NULL); if (!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); Tangram::initialize(); Tangram::resize(width, height); glfwSetWindowSizeCallback(window, window_size_callback); glfwSetMouseButtonCallback(window, mouse_button_callback); glfwSetCursorPosCallback(window, cursor_pos_callback); glfwSetScrollCallback(window, scroll_callback); glfwSetKeyCallback(window, key_callback); glfwSwapInterval(1); double lastTime = glfwGetTime(); /* Loop until the user closes the window */ while (!glfwWindowShouldClose(window)) { double currentTime = glfwGetTime(); double delta = currentTime - lastTime; lastTime = currentTime; /* Render here */ Tangram::update(delta); Tangram::render(); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } Tangram::teardown(); glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "com/sun/star/security/CertificateValidity.hpp" #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/task/XInteractionApprove.hpp" #include "com/sun/star/task/XInteractionRequest.hpp" #include "com/sun/star/ucb/CertificateValidationRequest.hpp" #include "vos/mutex.hxx" #include "tools/datetime.hxx" #include "svl/zforlist.hxx" #include "vcl/svapp.hxx" #include "ids.hrc" #include "getcontinuations.hxx" #include "sslwarndlg.hxx" #include "unknownauthdlg.hxx" #include "iahndl.hxx" #define DESCRIPTION_1 1 #define DESCRIPTION_2 2 #define TITLE 3 using namespace com::sun::star; namespace { String getContentPart( const String& _rRawString ) { // search over some parts to find a string //static char* aIDs[] = { "CN", "OU", "O", "E", NULL }; static char const * aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP String sPart; int i = 0; while ( aIDs[i] ) { String sPartId = String::CreateFromAscii( aIDs[i++] ); xub_StrLen nContStart = _rRawString.Search( sPartId ); if ( nContStart != STRING_NOTFOUND ) { nContStart = nContStart + sPartId.Len(); xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart ); sPart = String( _rRawString, nContStart, nContEnd - nContStart ); break; } } return sPart; } bool isDomainMatch( rtl::OUString hostName, rtl::OUString certHostName) { if (hostName.equalsIgnoreAsciiCase( certHostName )) return true; if ( 0 == certHostName.indexOf( rtl::OUString::createFromAscii( "*" ) ) && hostName.getLength() >= certHostName.getLength() ) { rtl::OUString cmpStr = certHostName.copy( 1 ); if ( hostName.matchIgnoreAsciiCase( cmpStr, hostName.getLength() - cmpStr.getLength()) ) return true; } return false; } rtl::OUString getLocalizedDatTimeStr( uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, util::DateTime const & rDateTime ) { rtl::OUString aDateTimeStr; Date aDate; Time aTime; aDate = Date( rDateTime.Day, rDateTime.Month, rDateTime.Year ); aTime = Time( rDateTime.Hours, rDateTime.Minutes, rDateTime.Seconds ); LanguageType eUILang = Application::GetSettings().GetUILanguage(); SvNumberFormatter *pNumberFormatter = new SvNumberFormatter( xServiceFactory, eUILang ); String aTmpStr; Color* pColor = NULL; Date* pNullDate = pNumberFormatter->GetNullDate(); sal_uInt32 nFormat = pNumberFormatter->GetStandardFormat( NUMBERFORMAT_DATE, eUILang ); pNumberFormatter->GetOutputString( aDate - *pNullDate, nFormat, aTmpStr, &pColor ); aDateTimeStr = aTmpStr + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); nFormat = pNumberFormatter->GetStandardFormat( NUMBERFORMAT_TIME, eUILang ); pNumberFormatter->GetOutputString( aTime.GetTimeInDays(), nFormat, aTmpStr, &pColor ); aDateTimeStr += aTmpStr; return aDateTimeStr; } sal_Bool executeUnknownAuthDialog( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, const uno::Reference< security::XCertificate >& rXCert) SAL_THROW((uno::RuntimeException)) { try { vos::OGuard aGuard(Application::GetSolarMutex()); std::auto_ptr< ResMgr > xManager( ResMgr::CreateResMgr(CREATEVERSIONRESMGR_NAME(uui))); std::auto_ptr< UnknownAuthDialog > xDialog( new UnknownAuthDialog( pParent, rXCert, xServiceFactory, xManager.get())); // Get correct ressource string rtl::OUString aMessage; std::vector< rtl::OUString > aArguments; aArguments.push_back( getContentPart( rXCert->getSubjectName()) ); if (xManager.get()) { ResId aResId(RID_UUI_ERRHDL, *xManager.get()); if (ErrorResource(aResId).getString( ERRCODE_UUI_UNKNOWNAUTH_UNTRUSTED, &aMessage)) { aMessage = UUIInteractionHelper::replaceMessageWithArguments( aMessage, aArguments ); xDialog->setDescriptionText( aMessage ); } } return static_cast<sal_Bool> (xDialog->Execute()); } catch (std::bad_alloc const &) { throw uno::RuntimeException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")), uno::Reference< uno::XInterface >()); } } sal_Bool executeSSLWarnDialog( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, const uno::Reference< security::XCertificate >& rXCert, sal_Int32 const & failure, const rtl::OUString & hostName ) SAL_THROW((uno::RuntimeException)) { try { vos::OGuard aGuard(Application::GetSolarMutex()); std::auto_ptr< ResMgr > xManager( ResMgr::CreateResMgr(CREATEVERSIONRESMGR_NAME(uui))); std::auto_ptr< SSLWarnDialog > xDialog( new SSLWarnDialog( pParent, rXCert, xServiceFactory, xManager.get())); // Get correct ressource string rtl::OUString aMessage_1; std::vector< rtl::OUString > aArguments_1; switch( failure ) { case SSLWARN_TYPE_DOMAINMISMATCH: aArguments_1.push_back( hostName ); aArguments_1.push_back( getContentPart( rXCert->getSubjectName()) ); aArguments_1.push_back( hostName ); break; case SSLWARN_TYPE_EXPIRED: aArguments_1.push_back( getContentPart( rXCert->getSubjectName()) ); aArguments_1.push_back( getLocalizedDatTimeStr( xServiceFactory, rXCert->getNotValidAfter() ) ); aArguments_1.push_back( getLocalizedDatTimeStr( xServiceFactory, rXCert->getNotValidAfter() ) ); break; case SSLWARN_TYPE_INVALID: break; } if (xManager.get()) { ResId aResId(RID_UUI_ERRHDL, *xManager.get()); if (ErrorResource(aResId).getString( ERRCODE_AREA_UUI_UNKNOWNAUTH + failure + DESCRIPTION_1, &aMessage_1)) { aMessage_1 = UUIInteractionHelper::replaceMessageWithArguments( aMessage_1, aArguments_1 ); xDialog->setDescription1Text( aMessage_1 ); } rtl::OUString aTitle; ErrorResource(aResId).getString( ERRCODE_AREA_UUI_UNKNOWNAUTH + failure + TITLE, &aTitle); xDialog->SetText( aTitle ); } return static_cast<sal_Bool> (xDialog->Execute()); } catch (std::bad_alloc const &) { throw uno::RuntimeException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")), uno::Reference< uno::XInterface >()); } } void handleCertificateValidationRequest_( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, ucb::CertificateValidationRequest const & rRequest, uno::Sequence< uno::Reference< task::XInteractionContinuation > > const & rContinuations) SAL_THROW((uno::RuntimeException)) { uno::Reference< task::XInteractionApprove > xApprove; uno::Reference< task::XInteractionAbort > xAbort; getContinuations(rContinuations, &xApprove, &xAbort); sal_Int32 failures = rRequest.CertificateValidity; sal_Bool trustCert = sal_True; if ( ((failures & security::CertificateValidity::UNTRUSTED) == security::CertificateValidity::UNTRUSTED ) || ((failures & security::CertificateValidity::ISSUER_UNTRUSTED) == security::CertificateValidity::ISSUER_UNTRUSTED) || ((failures & security::CertificateValidity::ROOT_UNTRUSTED) == security::CertificateValidity::ROOT_UNTRUSTED) ) { trustCert = executeUnknownAuthDialog( pParent, xServiceFactory, rRequest.Certificate ); } if ( (!isDomainMatch( rRequest.HostName, getContentPart( rRequest.Certificate->getSubjectName()) )) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_DOMAINMISMATCH, rRequest.HostName ); } if ( (((failures & security::CertificateValidity::TIME_INVALID) == security::CertificateValidity::TIME_INVALID) || ((failures & security::CertificateValidity::NOT_TIME_NESTED) == security::CertificateValidity::NOT_TIME_NESTED)) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_EXPIRED, rRequest.HostName ); } if ( (((failures & security::CertificateValidity::REVOKED) == security::CertificateValidity::REVOKED) || ((failures & security::CertificateValidity::SIGNATURE_INVALID) == security::CertificateValidity::SIGNATURE_INVALID) || ((failures & security::CertificateValidity::EXTENSION_INVALID) == security::CertificateValidity::EXTENSION_INVALID) || ((failures & security::CertificateValidity::INVALID) == security::CertificateValidity::INVALID)) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_INVALID, rRequest.HostName ); } if ( trustCert ) { if (xApprove.is()) xApprove->select(); } else { if (xAbort.is()) xAbort->select(); } } } // namespace bool UUIInteractionHelper::handleCertificateValidationRequest( uno::Reference< task::XInteractionRequest > const & rRequest) SAL_THROW((uno::RuntimeException)) { uno::Any aAnyRequest(rRequest->getRequest()); ucb::CertificateValidationRequest aCertificateValidationRequest; if (aAnyRequest >>= aCertificateValidationRequest) { handleCertificateValidationRequest_(getParentProperty(), m_xServiceFactory, aCertificateValidationRequest, rRequest->getContinuations()); return true; } return false; } <commit_msg>tkr38: #i112307# Support for x509 v3 Subject Alternative Name extension added<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "com/sun/star/security/CertificateValidity.hpp" #include "com/sun/star/security/XCertificateExtension.hpp" #include "com/sun/star/security/XSanExtension.hpp" #include <com/sun/star/security/ExtAltNameType.hpp> #include "com/sun/star/task/XInteractionAbort.hpp" #include "com/sun/star/task/XInteractionApprove.hpp" #include "com/sun/star/task/XInteractionRequest.hpp" #include "com/sun/star/ucb/CertificateValidationRequest.hpp" #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include "vos/mutex.hxx" #include "tools/datetime.hxx" #include "svl/zforlist.hxx" #include "vcl/svapp.hxx" #include "ids.hrc" #include "getcontinuations.hxx" #include "sslwarndlg.hxx" #include "unknownauthdlg.hxx" #include "iahndl.hxx" #define DESCRIPTION_1 1 #define DESCRIPTION_2 2 #define TITLE 3 #define OID_SUBJECT_ALTERNATIVE_NAME "2.5.29.17" using namespace com::sun::star; namespace { String getContentPart( const String& _rRawString ) { // search over some parts to find a string //static char* aIDs[] = { "CN", "OU", "O", "E", NULL }; static char const * aIDs[] = { "CN=", "OU=", "O=", "E=", NULL };// By CP String sPart; int i = 0; while ( aIDs[i] ) { String sPartId = String::CreateFromAscii( aIDs[i++] ); xub_StrLen nContStart = _rRawString.Search( sPartId ); if ( nContStart != STRING_NOTFOUND ) { nContStart = nContStart + sPartId.Len(); xub_StrLen nContEnd = _rRawString.Search( sal_Unicode( ',' ), nContStart ); sPart = String( _rRawString, nContStart, nContEnd - nContStart ); break; } } return sPart; } bool isDomainMatch( rtl::OUString hostName, uno::Sequence< ::rtl::OUString > certHostNames) { for ( int i = 0; i < certHostNames.getLength(); i++){ ::rtl::OUString element = certHostNames[i]; if (element.getLength() == 0) continue; if (hostName.equalsIgnoreAsciiCase( element )) return true; if ( 0 == element.indexOf( rtl::OUString::createFromAscii( "*" ) ) && hostName.getLength() >= element.getLength() ) { rtl::OUString cmpStr = element.copy( 1 ); if ( hostName.matchIgnoreAsciiCase( cmpStr, hostName.getLength() - cmpStr.getLength()) ) return true; } } return false; } rtl::OUString getLocalizedDatTimeStr( uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, util::DateTime const & rDateTime ) { rtl::OUString aDateTimeStr; Date aDate; Time aTime; aDate = Date( rDateTime.Day, rDateTime.Month, rDateTime.Year ); aTime = Time( rDateTime.Hours, rDateTime.Minutes, rDateTime.Seconds ); LanguageType eUILang = Application::GetSettings().GetUILanguage(); SvNumberFormatter *pNumberFormatter = new SvNumberFormatter( xServiceFactory, eUILang ); String aTmpStr; Color* pColor = NULL; Date* pNullDate = pNumberFormatter->GetNullDate(); sal_uInt32 nFormat = pNumberFormatter->GetStandardFormat( NUMBERFORMAT_DATE, eUILang ); pNumberFormatter->GetOutputString( aDate - *pNullDate, nFormat, aTmpStr, &pColor ); aDateTimeStr = aTmpStr + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM(" ")); nFormat = pNumberFormatter->GetStandardFormat( NUMBERFORMAT_TIME, eUILang ); pNumberFormatter->GetOutputString( aTime.GetTimeInDays(), nFormat, aTmpStr, &pColor ); aDateTimeStr += aTmpStr; return aDateTimeStr; } sal_Bool executeUnknownAuthDialog( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, const uno::Reference< security::XCertificate >& rXCert) SAL_THROW((uno::RuntimeException)) { try { vos::OGuard aGuard(Application::GetSolarMutex()); std::auto_ptr< ResMgr > xManager( ResMgr::CreateResMgr(CREATEVERSIONRESMGR_NAME(uui))); std::auto_ptr< UnknownAuthDialog > xDialog( new UnknownAuthDialog( pParent, rXCert, xServiceFactory, xManager.get())); // Get correct ressource string rtl::OUString aMessage; std::vector< rtl::OUString > aArguments; aArguments.push_back( getContentPart( rXCert->getSubjectName()) ); if (xManager.get()) { ResId aResId(RID_UUI_ERRHDL, *xManager.get()); if (ErrorResource(aResId).getString( ERRCODE_UUI_UNKNOWNAUTH_UNTRUSTED, &aMessage)) { aMessage = UUIInteractionHelper::replaceMessageWithArguments( aMessage, aArguments ); xDialog->setDescriptionText( aMessage ); } } return static_cast<sal_Bool> (xDialog->Execute()); } catch (std::bad_alloc const &) { throw uno::RuntimeException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")), uno::Reference< uno::XInterface >()); } } sal_Bool executeSSLWarnDialog( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, const uno::Reference< security::XCertificate >& rXCert, sal_Int32 const & failure, const rtl::OUString & hostName ) SAL_THROW((uno::RuntimeException)) { try { vos::OGuard aGuard(Application::GetSolarMutex()); std::auto_ptr< ResMgr > xManager( ResMgr::CreateResMgr(CREATEVERSIONRESMGR_NAME(uui))); std::auto_ptr< SSLWarnDialog > xDialog( new SSLWarnDialog( pParent, rXCert, xServiceFactory, xManager.get())); // Get correct ressource string rtl::OUString aMessage_1; std::vector< rtl::OUString > aArguments_1; switch( failure ) { case SSLWARN_TYPE_DOMAINMISMATCH: aArguments_1.push_back( hostName ); aArguments_1.push_back( getContentPart( rXCert->getSubjectName()) ); aArguments_1.push_back( hostName ); break; case SSLWARN_TYPE_EXPIRED: aArguments_1.push_back( getContentPart( rXCert->getSubjectName()) ); aArguments_1.push_back( getLocalizedDatTimeStr( xServiceFactory, rXCert->getNotValidAfter() ) ); aArguments_1.push_back( getLocalizedDatTimeStr( xServiceFactory, rXCert->getNotValidAfter() ) ); break; case SSLWARN_TYPE_INVALID: break; } if (xManager.get()) { ResId aResId(RID_UUI_ERRHDL, *xManager.get()); if (ErrorResource(aResId).getString( ERRCODE_AREA_UUI_UNKNOWNAUTH + failure + DESCRIPTION_1, &aMessage_1)) { aMessage_1 = UUIInteractionHelper::replaceMessageWithArguments( aMessage_1, aArguments_1 ); xDialog->setDescription1Text( aMessage_1 ); } rtl::OUString aTitle; ErrorResource(aResId).getString( ERRCODE_AREA_UUI_UNKNOWNAUTH + failure + TITLE, &aTitle); xDialog->SetText( aTitle ); } return static_cast<sal_Bool> (xDialog->Execute()); } catch (std::bad_alloc const &) { throw uno::RuntimeException( rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("out of memory")), uno::Reference< uno::XInterface >()); } } void handleCertificateValidationRequest_( Window * pParent, uno::Reference< lang::XMultiServiceFactory > const & xServiceFactory, ucb::CertificateValidationRequest const & rRequest, uno::Sequence< uno::Reference< task::XInteractionContinuation > > const & rContinuations) SAL_THROW((uno::RuntimeException)) { uno::Reference< task::XInteractionApprove > xApprove; uno::Reference< task::XInteractionAbort > xAbort; getContinuations(rContinuations, &xApprove, &xAbort); sal_Int32 failures = rRequest.CertificateValidity; sal_Bool trustCert = sal_True; if ( ((failures & security::CertificateValidity::UNTRUSTED) == security::CertificateValidity::UNTRUSTED ) || ((failures & security::CertificateValidity::ISSUER_UNTRUSTED) == security::CertificateValidity::ISSUER_UNTRUSTED) || ((failures & security::CertificateValidity::ROOT_UNTRUSTED) == security::CertificateValidity::ROOT_UNTRUSTED) ) { trustCert = executeUnknownAuthDialog( pParent, xServiceFactory, rRequest.Certificate ); } uno::Sequence< uno::Reference< security::XCertificateExtension > > extensions = rRequest.Certificate->getExtensions(); uno::Sequence< security::CertAltNameEntry > altNames; for (sal_Int32 i = 0 ; i < extensions.getLength(); i++){ uno::Reference< security::XCertificateExtension >element = extensions[i]; rtl::OString aId ( (const sal_Char *)element->getExtensionId().getArray(), element->getExtensionId().getLength()); if (aId.equals(OID_SUBJECT_ALTERNATIVE_NAME)) { uno::Reference< security::XSanExtension > sanExtension ( element, uno::UNO_QUERY ); altNames = sanExtension->getAlternativeNames(); break; } } ::rtl::OUString certHostName = getContentPart( rRequest.Certificate->getSubjectName() ); uno::Sequence< ::rtl::OUString > certHostNames(altNames.getLength() + 1); certHostNames[0] = certHostName; for(int n = 1; n < altNames.getLength(); n++){ if (altNames[n].Type == security::ExtAltNameType_DNS_NAME){ altNames[n].Value >>= certHostNames[n]; } } if ( (!isDomainMatch( rRequest.HostName, certHostNames )) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_DOMAINMISMATCH, rRequest.HostName ); } if ( (((failures & security::CertificateValidity::TIME_INVALID) == security::CertificateValidity::TIME_INVALID) || ((failures & security::CertificateValidity::NOT_TIME_NESTED) == security::CertificateValidity::NOT_TIME_NESTED)) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_EXPIRED, rRequest.HostName ); } if ( (((failures & security::CertificateValidity::REVOKED) == security::CertificateValidity::REVOKED) || ((failures & security::CertificateValidity::SIGNATURE_INVALID) == security::CertificateValidity::SIGNATURE_INVALID) || ((failures & security::CertificateValidity::EXTENSION_INVALID) == security::CertificateValidity::EXTENSION_INVALID) || ((failures & security::CertificateValidity::INVALID) == security::CertificateValidity::INVALID)) && trustCert ) { trustCert = executeSSLWarnDialog( pParent, xServiceFactory, rRequest.Certificate, SSLWARN_TYPE_INVALID, rRequest.HostName ); } if ( trustCert ) { if (xApprove.is()) xApprove->select(); } else { if (xAbort.is()) xAbort->select(); } } } // namespace bool UUIInteractionHelper::handleCertificateValidationRequest( uno::Reference< task::XInteractionRequest > const & rRequest) SAL_THROW((uno::RuntimeException)) { uno::Any aAnyRequest(rRequest->getRequest()); ucb::CertificateValidationRequest aCertificateValidationRequest; if (aAnyRequest >>= aCertificateValidationRequest) { handleCertificateValidationRequest_(getParentProperty(), m_xServiceFactory, aCertificateValidationRequest, rRequest->getContinuations()); return true; } return false; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: metric.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hdu $ $Date: 2001-07-06 12:33:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <metric.hxx> // ======================================================================= FontInfo::FontInfo() { mpImplMetric = new ImplFontMetric; mpImplMetric->mnRefCount = 1; mpImplMetric->meType = TYPE_DONTKNOW; mpImplMetric->mbDevice = FALSE; mpImplMetric->mnAscent = 0; mpImplMetric->mnDescent = 0; mpImplMetric->mnLeading = 0; mpImplMetric->mnLineHeight = 0; mpImplMetric->mnSlant = 0; mpImplMetric->mnFirstChar = 0; mpImplMetric->mnLastChar = 0; } // ----------------------------------------------------------------------- FontInfo::FontInfo( const FontInfo& rInfo ) : Font( rInfo ) { mpImplMetric = rInfo.mpImplMetric; mpImplMetric->mnRefCount++; } // ----------------------------------------------------------------------- FontInfo::~FontInfo() { // Eventuell Metric loeschen if ( mpImplMetric->mnRefCount > 1 ) mpImplMetric->mnRefCount--; else delete mpImplMetric; } // ----------------------------------------------------------------------- FontInfo& FontInfo::operator=( const FontInfo& rInfo ) { Font::operator=( rInfo ); // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann rInfo.mpImplMetric->mnRefCount++; // Sind wir nicht die letzten ? if ( mpImplMetric->mnRefCount > 1 ) mpImplMetric->mnRefCount--; else delete mpImplMetric; mpImplMetric = rInfo.mpImplMetric; return *this; } // ----------------------------------------------------------------------- BOOL FontInfo::operator==( const FontInfo& rInfo ) const { if ( !Font::operator==( rInfo ) ) return FALSE; if ( mpImplMetric == rInfo.mpImplMetric ) return TRUE; if ( (mpImplMetric->meType == rInfo.mpImplMetric->meType ) && (mpImplMetric->mbDevice == rInfo.mpImplMetric->mbDevice ) && (mpImplMetric->mnAscent == rInfo.mpImplMetric->mnAscent ) && (mpImplMetric->mnDescent == rInfo.mpImplMetric->mnDescent ) && (mpImplMetric->mnLeading == rInfo.mpImplMetric->mnLeading ) && (mpImplMetric->mnSlant == rInfo.mpImplMetric->mnSlant ) && (mpImplMetric->mnFirstChar == rInfo.mpImplMetric->mnFirstChar ) && (mpImplMetric->mnLastChar == rInfo.mpImplMetric->mnLastChar ) ) return TRUE; else return FALSE; } // ======================================================================= static const sal_UCS4 pDefaultRangeCodes[] = {0x0020,0xD800, 0xE000,0xFFF0}; FontCharMap::FontCharMap() : mpRangeCodes( NULL ) { ImplSetDefaultRanges(); } // ----------------------------------------------------------------------- FontCharMap::~FontCharMap() { ImplSetRanges( 0, NULL ); } // ----------------------------------------------------------------------- void FontCharMap::ImplSetRanges( ULONG nPairs, const sal_UCS4* pCodes ) { if( mpRangeCodes && mpRangeCodes != pDefaultRangeCodes ) delete[] const_cast<ULONG*>( mpRangeCodes ); mnRangeCount = nPairs; mpRangeCodes = pCodes; mnCharCount = 0; for( int i = 0; i < nPairs; ++i ) mnCharCount += mpRangeCodes[ 2*i+1 ] - mpRangeCodes[ 2*i ]; } // ----------------------------------------------------------------------- void FontCharMap::ImplSetDefaultRanges() { int nCodes = sizeof(pDefaultRangeCodes) / sizeof(*pDefaultRangeCodes); ImplSetRanges( nCodes/2, pDefaultRangeCodes ); } // ----------------------------------------------------------------------- BOOL FontCharMap::IsDefaultMap() const { return (mpRangeCodes == pDefaultRangeCodes); } // ----------------------------------------------------------------------- void FontCharMap::GetRange( ULONG i, sal_UCS4& cBegin, sal_UCS4& cEnd ) const { if( i < 0 || i >= mnRangeCount ) { cBegin = pDefaultRangeCodes[ 0 ]; cEnd = pDefaultRangeCodes[ 1 ]; } else { cBegin = mpRangeCodes[ 2*i ]; cEnd = mpRangeCodes[ 2*i+1 ]; } } // ----------------------------------------------------------------------- int FontCharMap::ImplFindRange( sal_UCS4 cChar ) const { int nLower = 0; int nMid = mnRangeCount; int nUpper = 2 * mnRangeCount; while( nLower < nUpper ) { if( cChar >= mpRangeCodes[ nMid ] ) nLower = nMid; else nUpper = nMid - 1; nMid = (nLower + nUpper + 1) / 2; } return nMid; } // ----------------------------------------------------------------------- BOOL FontCharMap::HasChar( sal_UCS4 cChar ) const { int nRange = ImplFindRange( cChar ); if( nRange==0 && cChar<mpRangeCodes[0] ) return FALSE; return (nRange & 1) ? FALSE: TRUE; } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetFirstChar() const { return mpRangeCodes[0]; } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetLastChar() const { return (mpRangeCodes[ 2*mnRangeCount-1 ] - 1); } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetNextChar( sal_UCS4 cChar ) const { if( cChar < GetFirstChar() ) return GetFirstChar(); if( cChar >= GetLastChar() ) return GetLastChar(); int nRange = ImplFindRange( cChar ); if( nRange & 1 ) // inbetween ranges? return mpRangeCodes[ nRange + 1 ]; // first in next range return (cChar + 1); } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetPrevChar( sal_UCS4 cChar ) const { if( cChar <= GetFirstChar() ) return GetFirstChar(); if( cChar > GetLastChar() ) return GetLastChar(); int nRange = ImplFindRange( cChar ); // inbetween ranges or first in range? if( (nRange & 1) || (cChar == mpRangeCodes[ nRange ]) ) return (mpRangeCodes[ nRange ] - 1); // last in prev range return (cChar - 1); } // ======================================================================= <commit_msg>#94375# implement FontCharMap::op=<commit_after>/************************************************************************* * * $RCSfile: metric.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hdu $ $Date: 2001-11-19 16:38:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <metric.hxx> // ======================================================================= FontInfo::FontInfo() { mpImplMetric = new ImplFontMetric; mpImplMetric->mnRefCount = 1; mpImplMetric->meType = TYPE_DONTKNOW; mpImplMetric->mbDevice = FALSE; mpImplMetric->mnAscent = 0; mpImplMetric->mnDescent = 0; mpImplMetric->mnLeading = 0; mpImplMetric->mnLineHeight = 0; mpImplMetric->mnSlant = 0; mpImplMetric->mnFirstChar = 0; mpImplMetric->mnLastChar = 0; } // ----------------------------------------------------------------------- FontInfo::FontInfo( const FontInfo& rInfo ) : Font( rInfo ) { mpImplMetric = rInfo.mpImplMetric; mpImplMetric->mnRefCount++; } // ----------------------------------------------------------------------- FontInfo::~FontInfo() { // Eventuell Metric loeschen if ( mpImplMetric->mnRefCount > 1 ) mpImplMetric->mnRefCount--; else delete mpImplMetric; } // ----------------------------------------------------------------------- FontInfo& FontInfo::operator=( const FontInfo& rInfo ) { Font::operator=( rInfo ); // Zuerst Referenzcounter erhoehen, damit man sich selbst zuweisen kann rInfo.mpImplMetric->mnRefCount++; // Sind wir nicht die letzten ? if ( mpImplMetric->mnRefCount > 1 ) mpImplMetric->mnRefCount--; else delete mpImplMetric; mpImplMetric = rInfo.mpImplMetric; return *this; } // ----------------------------------------------------------------------- BOOL FontInfo::operator==( const FontInfo& rInfo ) const { if ( !Font::operator==( rInfo ) ) return FALSE; if ( mpImplMetric == rInfo.mpImplMetric ) return TRUE; if ( (mpImplMetric->meType == rInfo.mpImplMetric->meType ) && (mpImplMetric->mbDevice == rInfo.mpImplMetric->mbDevice ) && (mpImplMetric->mnAscent == rInfo.mpImplMetric->mnAscent ) && (mpImplMetric->mnDescent == rInfo.mpImplMetric->mnDescent ) && (mpImplMetric->mnLeading == rInfo.mpImplMetric->mnLeading ) && (mpImplMetric->mnSlant == rInfo.mpImplMetric->mnSlant ) && (mpImplMetric->mnFirstChar == rInfo.mpImplMetric->mnFirstChar ) && (mpImplMetric->mnLastChar == rInfo.mpImplMetric->mnLastChar ) ) return TRUE; else return FALSE; } // ======================================================================= static const sal_UCS4 pDefaultRangeCodes[] = {0x0020,0xD800, 0xE000,0xFFF0}; FontCharMap::FontCharMap() : mpRangeCodes( NULL ) { ImplSetDefaultRanges(); } // ----------------------------------------------------------------------- FontCharMap::~FontCharMap() { ImplSetRanges( 0, NULL ); } // ----------------------------------------------------------------------- FontCharMap& FontCharMap::operator=( const FontCharMap& rMap ) { if( rMap.mpRangeCodes == pDefaultRangeCodes ) { ImplSetDefaultRanges(); } else { ULONG nPairs = rMap.mnRangeCount; sal_UCS4* pCodes = new sal_UCS4[ 2 * nPairs ]; for( ULONG i = 0; i < 2*nPairs; ++i ) pCodes[ i ] = rMap.mpRangeCodes[ i ]; ImplSetRanges( nPairs, pCodes ); } return *this; } // ----------------------------------------------------------------------- void FontCharMap::ImplSetRanges( ULONG nPairs, const sal_UCS4* pCodes ) { if( mpRangeCodes && mpRangeCodes != pDefaultRangeCodes ) delete[] const_cast<ULONG*>( mpRangeCodes ); mnRangeCount = nPairs; mpRangeCodes = pCodes; mnCharCount = 0; for( int i = 0; i < nPairs; ++i ) mnCharCount += mpRangeCodes[ 2*i+1 ] - mpRangeCodes[ 2*i ]; } // ----------------------------------------------------------------------- void FontCharMap::ImplSetDefaultRanges() { int nCodes = sizeof(pDefaultRangeCodes) / sizeof(*pDefaultRangeCodes); ImplSetRanges( nCodes/2, pDefaultRangeCodes ); } // ----------------------------------------------------------------------- BOOL FontCharMap::IsDefaultMap() const { return (mpRangeCodes == pDefaultRangeCodes); } // ----------------------------------------------------------------------- void FontCharMap::GetRange( ULONG i, sal_UCS4& cBegin, sal_UCS4& cEnd ) const { if( i < 0 || i >= mnRangeCount ) { cBegin = pDefaultRangeCodes[ 0 ]; cEnd = pDefaultRangeCodes[ 1 ]; } else { cBegin = mpRangeCodes[ 2*i ]; cEnd = mpRangeCodes[ 2*i+1 ]; } } // ----------------------------------------------------------------------- int FontCharMap::ImplFindRange( sal_UCS4 cChar ) const { int nLower = 0; int nMid = mnRangeCount; int nUpper = 2 * mnRangeCount; while( nLower < nUpper ) { if( cChar >= mpRangeCodes[ nMid ] ) nLower = nMid; else nUpper = nMid - 1; nMid = (nLower + nUpper + 1) / 2; } return nMid; } // ----------------------------------------------------------------------- BOOL FontCharMap::HasChar( sal_UCS4 cChar ) const { int nRange = ImplFindRange( cChar ); if( nRange==0 && cChar<mpRangeCodes[0] ) return FALSE; return (nRange & 1) ? FALSE: TRUE; } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetFirstChar() const { return mpRangeCodes[0]; } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetLastChar() const { return (mpRangeCodes[ 2*mnRangeCount-1 ] - 1); } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetNextChar( sal_UCS4 cChar ) const { if( cChar < GetFirstChar() ) return GetFirstChar(); if( cChar >= GetLastChar() ) return GetLastChar(); int nRange = ImplFindRange( cChar ); if( nRange & 1 ) // inbetween ranges? return mpRangeCodes[ nRange + 1 ]; // first in next range return (cChar + 1); } // ----------------------------------------------------------------------- sal_UCS4 FontCharMap::GetPrevChar( sal_UCS4 cChar ) const { if( cChar <= GetFirstChar() ) return GetFirstChar(); if( cChar > GetLastChar() ) return GetLastChar(); int nRange = ImplFindRange( cChar ); // inbetween ranges or first in range? if( (nRange & 1) || (cChar == mpRangeCodes[ nRange ]) ) return (mpRangeCodes[ nRange ] - 1); // last in prev range return (cChar - 1); } // ======================================================================= <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK(set_on_ == PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base <commit_msg>Replace a DCHECK with DCHECK_EQ.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/cancellation_flag.h" #include "base/logging.h" namespace base { void CancellationFlag::Set() { #if !defined(NDEBUG) DCHECK_EQ(set_on_, PlatformThread::CurrentId()); #endif base::subtle::Release_Store(&flag_, 1); } bool CancellationFlag::IsSet() const { return base::subtle::Acquire_Load(&flag_) != 0; } } // namespace base <|endoftext|>
<commit_before><commit_msg>fix mac bustage by adding NL to end of file<commit_after><|endoftext|>
<commit_before>// @(#)root/base:$Name: $:$Id: TQConnection.cxx,v 1.9 2002/12/02 18:50:01 rdm Exp $ // Author: Valeriy Onuchin & Fons Rademakers 15/10/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TQConnection class is an internal class, used in the object // // communication mechanism. // // // // TQConnection: // // - is a list of signal_lists containing pointers // // to this connection // // - receiver is the object to which slot-method is applied // // // // This implementation is provided by // // Valeriy Onuchin ([email protected]). // // // ////////////////////////////////////////////////////////////////////////// #include "TQConnection.h" #include "TRefCnt.h" #include "TClass.h" #include "Api.h" #include "G__ci.h" #include "Riostream.h" ClassImpQ(TQConnection) char *gTQSlotParams; // used to pass string parameter ////////////////////////////////////////////////////////////////////////// // // // TQSlot = slightly modified TMethodCall class // // used in the object communication mechanism // // // ////////////////////////////////////////////////////////////////////////// class TQSlot : public TObject, public TRefCnt { protected: G__CallFunc *fFunc; // CINT method invocation environment Long_t fOffset; // offset added to object pointer TString fName; // full name of method Int_t fExecuting; // true if one of this slot's ExecuteMethod methods is being called public: TQSlot(TClass *cl, const char *method, const char *funcname); TQSlot(const char *class_name, const char *funcname); virtual ~TQSlot(); const char *GetName() const { return fName.Data(); } void ExecuteMethod(void *object); void ExecuteMethod(void *object, Long_t param); void ExecuteMethod(void *object, Double_t param); void ExecuteMethod(void *object, const char *params); void ExecuteMethod(void *object, Long_t *paramArr); void Print(Option_t *opt= "") const; void ls(Option_t *opt= "") const { Print(opt); } }; //______________________________________________________________________________ TQSlot::TQSlot(TClass *cl, const char *method_name, const char *funcname) : TObject(), TRefCnt() { // Create the method invocation environment. Necessary input // information: the class, full method name with prototype // string of the form: method(char*,int,float). // To initialize class method with default arguments, method // string with default parameters should be of the form: // method(=\"ABC\",1234,3.14) (!! parameter string should // consists of '='). // To execute the method call TQSlot::ExecuteMethod(object,...). fFunc = 0; fOffset = 0; fName = ""; fExecuting = 0; // cl==0, is the case of interpreted function. fName = method_name; char *method = new char[strlen(method_name)+1]; if (method) strcpy(method, method_name); char *proto; char *tmp; char *params = 0; // separate method and protoype strings if ((proto = strchr(method,'('))) { // substitute first '(' symbol with '\0' *proto++ = '\0'; // last ')' symbol with '\0' if ((tmp = strrchr(proto,')'))) *tmp = '\0'; if ((params = strchr(proto,'='))) *params = ' '; } fFunc = new G__CallFunc; // initiate class method (function) with proto // or with default params if (cl) { params ? fFunc->SetFunc(cl->GetClassInfo(), method, params, &fOffset) : fFunc->SetFuncProto(cl->GetClassInfo(), method, proto, &fOffset); } else { G__ClassInfo gcl; params ? fFunc->SetFunc(&gcl, (char*)funcname, params, &fOffset) : fFunc->SetFuncProto(&gcl, (char*)funcname, proto, &fOffset); } // cleaning delete [] method; } //______________________________________________________________________________ TQSlot::TQSlot(const char *class_name, const char *funcname) : TObject(), TRefCnt() { // Create the method invocation environment. Necessary input // information: the name of class (could be interpreted class), // full method name with prototype or parameter string // of the form: method(char*,int,float). // To initialize class method with default arguments, method // string with default parameters should be of the form: // method(=\"ABC\",1234,3.14) (!! parameter string should // consists of '='). // To execute the method call TQSlot::ExecuteMethod(object,...). fFunc = 0; fOffset = 0; fName = funcname; fExecuting = 0; char *method = new char[strlen(funcname)+1]; if (method) strcpy(method, funcname); char *proto; char *tmp; char *params = 0; // separate method and protoype strings if ((proto = strchr(method,'('))) { *proto++ = '\0'; if ((tmp = strrchr(proto,')'))) *tmp = '\0'; if ((params = strchr(proto,'='))) *params = ' '; } fFunc = new G__CallFunc; G__ClassInfo gcl; if (!class_name) ; // function else gcl.Init(class_name); // class if (params) fFunc->SetFunc(&gcl, method, params, &fOffset); else fFunc->SetFuncProto(&gcl, method, proto , &fOffset); delete [] method; return; } //______________________________________________________________________________ TQSlot::~TQSlot() { // TQSlot dtor. // don't delete executing environment of a slot that is being executed if (!fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object) { // ExecuteMethod the method (with preset arguments) for // the specified object. void *address = 0; if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Long_t param) { // ExecuteMethod the method for the specified object and // with single argument value. void *address = 0; fFunc->ResetArg(); fFunc->SetArg(param); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Double_t param) { // ExecuteMethod the method for the specified object and // with single argument value. void *address = 0; fFunc->ResetArg(); fFunc->SetArg(param); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, const char *param) { // ExecuteMethod the method for the specified object and text param. void *address = 0; gTQSlotParams = (char*)param; fFunc->SetArgs("gTQSlotParams"); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Long_t *paramArr) { // ExecuteMethod the method for the specified object and with // several argument values. // paramArr is an array containing the addresses // where to take the function parameters. // At least as many pointers should be present in the array as // there are required arguments (all arguments - default args). void *address = 0; fFunc->SetArgArray(paramArr); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ void TQSlot::Print(Option_t *) const { // Print info about slot. cout <<IsA()->GetName() << "\t" << GetName() << "\t" << "Number of Connections = " << References() << endl; } //______________________________________________________________________________ TQConnection::TQConnection() : TList(), TQObject() { // Default constructor. fReceiver = 0; fSlot = 0; } //______________________________________________________________________________ TQConnection::TQConnection(TClass *cl, void *receiver, const char *method_name) : TList(), TQObject() { // TQConnection ctor. // cl != 0 - connection to object == receiver of class == cl // and method == method_name // cl == 0 - connection to function with name == method_name char *funcname = 0; fReceiver = receiver; // fReceiver is pointer to receiver if (!cl) { funcname = G__p2f2funcname(fReceiver); if (!funcname) Warning("TQConnection", "%s cannot be compiled", method_name); } fSlot = new TQSlot(cl, method_name, funcname); fSlot->AddReference(); //update counter of references to slot } //______________________________________________________________________________ TQConnection::TQConnection(const char *class_name, void *receiver, const char *funcname) : TList(), TQObject() { // TQConnection ctor. // Creates connection to method of class specified by name, // it could be interpreted class and with method == funcname. fSlot = new TQSlot(class_name, funcname); // new slot-method fSlot->AddReference(); // update counter of references to slot fReceiver = receiver; // fReceiver is pointer to receiver } //______________________________________________________________________________ TQConnection::~TQConnection() { // TQConnection dtor. // - remove this connection from all signal lists // - we do not delete fSlot if it has other connections, // TQSlot::fCounter > 0 . TIter next(this); register TList *list; while ((list = (TList*)next())) { list->Remove(this); if (list->IsEmpty()) SafeDelete(list); // delete empty list } if (!fSlot) return; fSlot->RemoveReference(); // decrease references to slot if (fSlot->References() <=0) { SafeDelete(fSlot); } } //______________________________________________________________________________ const char *TQConnection::GetName() const { // Returns name of connection return fSlot->GetName(); } //______________________________________________________________________________ void TQConnection::Destroyed() { // Signal Destroyed tells that connection is destroyed. MakeZombie(); Emit("Destroyed()"); } //______________________________________________________________________________ void TQConnection::ls(Option_t *option) const { // List TQConnection full method name and list all signals // connected to this connection. cout << "\t" << IsA()->GetName() << "\t" << GetName() << endl; ((TQConnection*)this)->ForEach(TList,ls)(option); } //______________________________________________________________________________ void TQConnection::Print(Option_t *) const { // Print TQConnection full method name and print all // signals connected to this connection. cout << "\t\t\t" << IsA()->GetName() << "\t" << fReceiver << "\t" << GetName() << endl; } //______________________________________________________________________________ void TQConnection::ExecuteMethod() { // Apply slot-method to the fReceiver object without arguments. fSlot->ExecuteMethod(fReceiver); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Long_t param) { // Apply slot-method to the fReceiver object with // single argument value. fSlot->ExecuteMethod(fReceiver, param); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Double_t param) { // Apply slot-method to the fReceiver object with // single argument value. fSlot->ExecuteMethod(fReceiver, param); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Long_t *params) { // Apply slot-method to the fReceiver object with variable // number of argument values. fSlot->ExecuteMethod(fReceiver, params); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(const char *param) { // Apply slot-method to the fReceiver object and // with string parameter. fSlot->ExecuteMethod(fReceiver, param); } <commit_msg>The class TQConnection uses CINT and is not protected for multi-threading. This patch from Mathieu de Naurois adds R__LOCKGUARD(gCINTMutex) at several places in the code.<commit_after>// @(#)root/base:$Name: $:$Id: TQConnection.cxx,v 1.10 2003/01/20 08:44:46 brun Exp $ // Author: Valeriy Onuchin & Fons Rademakers 15/10/2000 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TQConnection class is an internal class, used in the object // // communication mechanism. // // // // TQConnection: // // - is a list of signal_lists containing pointers // // to this connection // // - receiver is the object to which slot-method is applied // // // // This implementation is provided by // // Valeriy Onuchin ([email protected]). // // // ////////////////////////////////////////////////////////////////////////// #include "TQConnection.h" #include "TRefCnt.h" #include "TClass.h" #include "Api.h" #include "G__ci.h" #include "Riostream.h" #include "TVirtualMutex.h" ClassImpQ(TQConnection) char *gTQSlotParams; // used to pass string parameter ////////////////////////////////////////////////////////////////////////// // // // TQSlot = slightly modified TMethodCall class // // used in the object communication mechanism // // // ////////////////////////////////////////////////////////////////////////// class TQSlot : public TObject, public TRefCnt { protected: G__CallFunc *fFunc; // CINT method invocation environment Long_t fOffset; // offset added to object pointer TString fName; // full name of method Int_t fExecuting; // true if one of this slot's ExecuteMethod methods is being called public: TQSlot(TClass *cl, const char *method, const char *funcname); TQSlot(const char *class_name, const char *funcname); virtual ~TQSlot(); const char *GetName() const { return fName.Data(); } void ExecuteMethod(void *object); void ExecuteMethod(void *object, Long_t param); void ExecuteMethod(void *object, Double_t param); void ExecuteMethod(void *object, const char *params); void ExecuteMethod(void *object, Long_t *paramArr); void Print(Option_t *opt= "") const; void ls(Option_t *opt= "") const { Print(opt); } }; //______________________________________________________________________________ TQSlot::TQSlot(TClass *cl, const char *method_name, const char *funcname) : TObject(), TRefCnt() { // Create the method invocation environment. Necessary input // information: the class, full method name with prototype // string of the form: method(char*,int,float). // To initialize class method with default arguments, method // string with default parameters should be of the form: // method(=\"ABC\",1234,3.14) (!! parameter string should // consists of '='). // To execute the method call TQSlot::ExecuteMethod(object,...). fFunc = 0; fOffset = 0; fName = ""; fExecuting = 0; // cl==0, is the case of interpreted function. fName = method_name; char *method = new char[strlen(method_name)+1]; if (method) strcpy(method, method_name); char *proto; char *tmp; char *params = 0; // separate method and protoype strings if ((proto = strchr(method,'('))) { // substitute first '(' symbol with '\0' *proto++ = '\0'; // last ')' symbol with '\0' if ((tmp = strrchr(proto,')'))) *tmp = '\0'; if ((params = strchr(proto,'='))) *params = ' '; } R__LOCKGUARD(gCINTMutex); fFunc = new G__CallFunc; // initiate class method (function) with proto // or with default params if (cl) { params ? fFunc->SetFunc(cl->GetClassInfo(), method, params, &fOffset) : fFunc->SetFuncProto(cl->GetClassInfo(), method, proto, &fOffset); } else { G__ClassInfo gcl; params ? fFunc->SetFunc(&gcl, (char*)funcname, params, &fOffset) : fFunc->SetFuncProto(&gcl, (char*)funcname, proto, &fOffset); } // cleaning delete [] method; } //______________________________________________________________________________ TQSlot::TQSlot(const char *class_name, const char *funcname) : TObject(), TRefCnt() { // Create the method invocation environment. Necessary input // information: the name of class (could be interpreted class), // full method name with prototype or parameter string // of the form: method(char*,int,float). // To initialize class method with default arguments, method // string with default parameters should be of the form: // method(=\"ABC\",1234,3.14) (!! parameter string should // consists of '='). // To execute the method call TQSlot::ExecuteMethod(object,...). fFunc = 0; fOffset = 0; fName = funcname; fExecuting = 0; char *method = new char[strlen(funcname)+1]; if (method) strcpy(method, funcname); char *proto; char *tmp; char *params = 0; // separate method and protoype strings if ((proto = strchr(method,'('))) { *proto++ = '\0'; if ((tmp = strrchr(proto,')'))) *tmp = '\0'; if ((params = strchr(proto,'='))) *params = ' '; } R__LOCKGUARD(gCINTMutex); fFunc = new G__CallFunc; G__ClassInfo gcl; if (!class_name) ; // function else gcl.Init(class_name); // class if (params) fFunc->SetFunc(&gcl, method, params, &fOffset); else fFunc->SetFuncProto(&gcl, method, proto , &fOffset); delete [] method; return; } //______________________________________________________________________________ TQSlot::~TQSlot() { // TQSlot dtor. // don't delete executing environment of a slot that is being executed if (!fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object) { // ExecuteMethod the method (with preset arguments) for // the specified object. void *address = 0; if (object) address = (void*)((Long_t)object + fOffset); R__LOCKGUARD(gCINTMutex); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Long_t param) { // ExecuteMethod the method for the specified object and // with single argument value. void *address = 0; R__LOCKGUARD(gCINTMutex); fFunc->ResetArg(); fFunc->SetArg(param); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Double_t param) { // ExecuteMethod the method for the specified object and // with single argument value. void *address = 0; R__LOCKGUARD(gCINTMutex); fFunc->ResetArg(); fFunc->SetArg(param); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, const char *param) { // ExecuteMethod the method for the specified object and text param. void *address = 0; gTQSlotParams = (char*)param; R__LOCKGUARD(gCINTMutex); fFunc->SetArgs("gTQSlotParams"); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ inline void TQSlot::ExecuteMethod(void *object, Long_t *paramArr) { // ExecuteMethod the method for the specified object and with // several argument values. // paramArr is an array containing the addresses // where to take the function parameters. // At least as many pointers should be present in the array as // there are required arguments (all arguments - default args). void *address = 0; R__LOCKGUARD(gCINTMutex); fFunc->SetArgArray(paramArr); if (object) address = (void*)((Long_t)object + fOffset); fExecuting++; fFunc->Exec(address); fExecuting--; if (!TestBit(kNotDeleted) && !fExecuting) delete fFunc; } //______________________________________________________________________________ void TQSlot::Print(Option_t *) const { // Print info about slot. cout <<IsA()->GetName() << "\t" << GetName() << "\t" << "Number of Connections = " << References() << endl; } //______________________________________________________________________________ TQConnection::TQConnection() : TList(), TQObject() { // Default constructor. fReceiver = 0; fSlot = 0; } //______________________________________________________________________________ TQConnection::TQConnection(TClass *cl, void *receiver, const char *method_name) : TList(), TQObject() { // TQConnection ctor. // cl != 0 - connection to object == receiver of class == cl // and method == method_name // cl == 0 - connection to function with name == method_name char *funcname = 0; fReceiver = receiver; // fReceiver is pointer to receiver if (!cl) { funcname = G__p2f2funcname(fReceiver); if (!funcname) Warning("TQConnection", "%s cannot be compiled", method_name); } fSlot = new TQSlot(cl, method_name, funcname); fSlot->AddReference(); //update counter of references to slot } //______________________________________________________________________________ TQConnection::TQConnection(const char *class_name, void *receiver, const char *funcname) : TList(), TQObject() { // TQConnection ctor. // Creates connection to method of class specified by name, // it could be interpreted class and with method == funcname. fSlot = new TQSlot(class_name, funcname); // new slot-method fSlot->AddReference(); // update counter of references to slot fReceiver = receiver; // fReceiver is pointer to receiver } //______________________________________________________________________________ TQConnection::~TQConnection() { // TQConnection dtor. // - remove this connection from all signal lists // - we do not delete fSlot if it has other connections, // TQSlot::fCounter > 0 . TIter next(this); register TList *list; while ((list = (TList*)next())) { list->Remove(this); if (list->IsEmpty()) SafeDelete(list); // delete empty list } if (!fSlot) return; fSlot->RemoveReference(); // decrease references to slot if (fSlot->References() <=0) { SafeDelete(fSlot); } } //______________________________________________________________________________ const char *TQConnection::GetName() const { // Returns name of connection return fSlot->GetName(); } //______________________________________________________________________________ void TQConnection::Destroyed() { // Signal Destroyed tells that connection is destroyed. MakeZombie(); Emit("Destroyed()"); } //______________________________________________________________________________ void TQConnection::ls(Option_t *option) const { // List TQConnection full method name and list all signals // connected to this connection. cout << "\t" << IsA()->GetName() << "\t" << GetName() << endl; ((TQConnection*)this)->ForEach(TList,ls)(option); } //______________________________________________________________________________ void TQConnection::Print(Option_t *) const { // Print TQConnection full method name and print all // signals connected to this connection. cout << "\t\t\t" << IsA()->GetName() << "\t" << fReceiver << "\t" << GetName() << endl; } //______________________________________________________________________________ void TQConnection::ExecuteMethod() { // Apply slot-method to the fReceiver object without arguments. fSlot->ExecuteMethod(fReceiver); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Long_t param) { // Apply slot-method to the fReceiver object with // single argument value. fSlot->ExecuteMethod(fReceiver, param); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Double_t param) { // Apply slot-method to the fReceiver object with // single argument value. fSlot->ExecuteMethod(fReceiver, param); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(Long_t *params) { // Apply slot-method to the fReceiver object with variable // number of argument values. fSlot->ExecuteMethod(fReceiver, params); } //______________________________________________________________________________ void TQConnection::ExecuteMethod(const char *param) { // Apply slot-method to the fReceiver object and // with string parameter. fSlot->ExecuteMethod(fReceiver, param); } <|endoftext|>
<commit_before>#ifndef PARAMS_HPP #define PARAMS_HPP #include <map> #include <sstream> #include <string> #include <vector> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "foreach.hpp" namespace nexus { namespace internal { using std::map; using std::ostringstream; using std::string; using std::vector; using std::pair; using std::make_pair; using boost::lexical_cast; struct ParseException : std::exception { const char* message; ParseException(const char* msg): message(msg) {} const char* what() const throw () { return message; } }; /** * Stores a set of key-value pairs that can be accessed as strings, ints, etc */ class Params { private: map<string, string> params; public: Params() {} Params(const map<string, string>& params_): params(params_) {} Params(const string& str) { loadString(str); } /** * Load key-value pairs from a map into this Params object. */ void loadMap(const map<string, string>& params_) { foreachpair(const string& k, const string& v, params_) { params[k] = v; } } /** * Load key-value pairs from a string into this Params object. * The string should contain pairs of the form key=value, one per line. */ void loadString(const string& str) { vector<string> lines; split(str, "\n\r", lines); foreach (string& line, lines) { vector<string> parts; split(line, "=", parts); if (parts.size() != 2) { ostringstream oss; oss << "Malformed line in params: '" << line << "'"; throw ParseException(oss.str().c_str()); } params[parts[0]] = parts[1]; } } string& operator[] (const string& key) { return params[key]; } const string& get(const string& key, const string& defaultValue) const { map<string, string>::const_iterator it = params.find(key); return (it != params.end()) ? it->second : defaultValue; } int getInt(const string& key, int defaultValue) const { map<string, string>::const_iterator it = params.find(key); if (it != params.end()) return lexical_cast<int>(it->second); else return defaultValue; } int32_t getInt32(const string& key, int32_t defaultValue) const { map<string, string>::const_iterator it = params.find(key); if (it != params.end()) return lexical_cast<int32_t>(it->second); else return defaultValue; } int64_t getInt64(const string& key, int64_t defaultValue) const { map<string, string>::const_iterator it = params.find(key); if (it != params.end()) return lexical_cast<int64_t>(it->second); else return defaultValue; } template <typename T> T get(const string& key, const T& defaultValue) const { map<string, string>::const_iterator it = params.find(key); if (it != params.end()) return lexical_cast<T>(it->second); else return defaultValue; } template <typename T> void set(const string& key, T value) { params[key] = lexical_cast<string>(value); } string str() const { ostringstream oss; foreachpair (const string& key, const string& value, params) { oss << key << "=" << value << "\n"; } return oss.str(); } map<string, string>& getMap() { return params; } const map<string, string>& getMap() const { return params; } bool contains(const string& key) const { return params.find(key) != params.end(); } private: void split(const string& str, const string& delims, vector<string>& tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens.push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } }; }} #endif /* PARAMS_HPP */ <commit_msg>Simplified some Params methods now that templated get() is available<commit_after>#ifndef PARAMS_HPP #define PARAMS_HPP #include <map> #include <sstream> #include <string> #include <vector> #include <boost/lexical_cast.hpp> #include <boost/foreach.hpp> #include "foreach.hpp" namespace nexus { namespace internal { using std::map; using std::ostringstream; using std::string; using std::vector; using std::pair; using std::make_pair; using boost::lexical_cast; struct ParseException : std::exception { const char* message; ParseException(const char* msg): message(msg) {} const char* what() const throw () { return message; } }; /** * Stores a set of key-value pairs that can be accessed as strings, ints, etc */ class Params { private: map<string, string> params; public: Params() {} Params(const map<string, string>& params_): params(params_) {} Params(const string& str) { loadString(str); } /** * Load key-value pairs from a map into this Params object. */ void loadMap(const map<string, string>& params_) { foreachpair(const string& k, const string& v, params_) { params[k] = v; } } /** * Load key-value pairs from a string into this Params object. * The string should contain pairs of the form key=value, one per line. */ void loadString(const string& str) { vector<string> lines; split(str, "\n\r", lines); foreach (string& line, lines) { vector<string> parts; split(line, "=", parts); if (parts.size() != 2) { ostringstream oss; oss << "Malformed line in params: '" << line << "'"; throw ParseException(oss.str().c_str()); } params[parts[0]] = parts[1]; } } string& operator[] (const string& key) { return params[key]; } const string& get(const string& key, const string& defaultValue) const { map<string, string>::const_iterator it = params.find(key); return (it != params.end()) ? it->second : defaultValue; } int getInt(const string& key, int defaultValue) const { return get<int>(key, defaultValue); } int32_t getInt32(const string& key, int32_t defaultValue) const { return get<int32_t>(key, defaultValue); } int64_t getInt64(const string& key, int64_t defaultValue) const { return get<int64_t>(key, defaultValue); } template <typename T> T get(const string& key, const T& defaultValue) const { map<string, string>::const_iterator it = params.find(key); if (it != params.end()) return lexical_cast<T>(it->second); else return defaultValue; } template <typename T> void set(const string& key, T value) { params[key] = lexical_cast<string>(value); } string str() const { ostringstream oss; foreachpair (const string& key, const string& value, params) { oss << key << "=" << value << "\n"; } return oss.str(); } map<string, string>& getMap() { return params; } const map<string, string>& getMap() const { return params; } bool contains(const string& key) const { return params.find(key) != params.end(); } private: void split(const string& str, const string& delims, vector<string>& tokens) { // Start and end of current token; initialize these to the first token in // the string, skipping any leading delimiters size_t start = str.find_first_not_of(delims, 0); size_t end = str.find_first_of(delims, start); while (start != string::npos || end != string::npos) { // Add current token to the vector tokens.push_back(str.substr(start, end-start)); // Advance start to first non-delimiter past the current end start = str.find_first_not_of(delims, end); // Advance end to the next delimiter after the new start end = str.find_first_of(delims, start); } } }; }} #endif /* PARAMS_HPP */ <|endoftext|>
<commit_before>// // C++ Implementation: pntmap // // Description: // // // Author: Torsten Rahn <[email protected]>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #include <stdlib.h> #include <fcntl.h> #include <cmath> #include <unistd.h> #include <QtCore/QFile> #include <QtCore/QDataStream> #include <QtCore/QDebug> #include <QtCore/QTime> #ifdef Q_OS_UNIX # include <sys/types.h> # include <sys/stat.h> # include <sys/mman.h> /* mmap() is defined in this header */ #endif #include "pntmap.h" PntPolyLine::PntPolyLine(){ m_Crossed = false; m_closed = false; m_Num = 0; m_x0 = m_y0 = m_x1 = m_y1 = 0; } PntPolyLine::~PntPolyLine(){ } void PntPolyLine::setBoundary(int x0, int y0, int x1, int y1){ m_x0 = x0; m_y0 = y0; m_x1 = x1; m_y1 = y1; m_boundary.clear(); if (getDateLine()) { int xcenter = (x0 + (21600+x1))/2; if (xcenter > 10800) xcenter -= 21600; if (xcenter < -10800) xcenter += 21600; m_boundary.append(GeoPoint( 1, xcenter, (y0 + y1)/2 )); } else m_boundary.append(GeoPoint( 1, (x0 + x1)/2, (y0 + y1)/2 )); m_boundary.append(GeoPoint( 1, x0, y0)); m_boundary.append(GeoPoint( 1, x1, y1)); m_boundary.append(GeoPoint( 1, x1, y0)); m_boundary.append(GeoPoint( 1, x0, y1)); } PntMap::PntMap(){ } PntMap::~PntMap(){ qDeleteAll(begin(), end()); } void PntMap::load(const QString &filename){ QTime *timer = new QTime(); timer->restart(); #ifdef Q_OS_UNIX // MMAP Start int fd; short* src; struct stat statbuf; if ((fd = open (filename.toLatin1(), O_RDONLY)) < 0) qDebug() << "can't open" << filename << " for reading"; if (fstat (fd,&statbuf) < 0) qDebug() << "fstat error"; int filelength = statbuf.st_size; if ((src = (short*) mmap (0, filelength, PROT_READ, MAP_SHARED, fd, 0)) == (short*) (caddr_t) -1) qDebug() << "mmap error for input"; short header, lat, lng; int count = 0; for (int i=0; i < (filelength >> 1); i+=3){ header = src[i]; lat = src[i+1]; lng = src[i+2]; // Transforming Range of Coordinates to lat [0,10800] , lng [0,21600] lat = -lat; /* 90 00N = -5400 90 00S = 5400 180 00W = -10800 180 00E = 10800 */ if (header > 5){ // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); PntPolyLine *polyline = new PntPolyLine(); append( polyline ); polyline->setNum(header); // Find out whether the Polyline is a river or a closed polygon if ((header >= 7000 && header < 8000) || (header >= 9000 && header < 20000) ) polyline->setClosed(false); else polyline->setClosed(true); polyline->append(GeoPoint(5, (int)(lng), (int)(lat))); } else { // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); last()->append(GeoPoint((int)(header), (int)(lng), (int)(lat))); } ++count; } munmap(0,filelength); close(fd); // qDebug(QString("Opened %1 with %2 Polylines and %3 Points").arg(filename).arg(this->count()).arg(count).toLatin1()); // MMAP End // qDebug() << "Loading Time:" << timer->elapsed(); #else # ifdef Q_OS_WIN int count = 0; // qDebug("Loading PntMap ..."); QFile file( filename ); file.open( QIODevice::ReadOnly ); QDataStream stream( &file ); // read the data serialized from the file stream.setByteOrder( QDataStream::LittleEndian ); short header, lat, lng; // Iterator that points to current PolyLine in PntMap // QList<PntPolyLine*>::iterator it = begin(); // int count = 0; while(!stream.atEnd()){ stream >> header >> lat >> lng; // Transforming Range of Coordinates to lat [0,10800] , lng [0,21600] lat = -lat; if (header > 5){ // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); PntPolyLine *polyline = new PntPolyLine(); append( polyline ); polyline->setNum(header); // Find out whether the Polyline is a river or a closed polygon if ((header >= 7000 && header < 8000)) polyline->setClosed(false); else polyline->setClosed(true); polyline->append(GeoPoint(5, (int)(lng), (int)(lat))); } else { // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); last()->append(GeoPoint((int)(header), (int)(lng), (int)(lat))); } ++count; } file.close(); qDebug() << "Loading Time:" << timer->elapsed(); // qDebug(QString("Opened %1 with %2 Polylines and %3 Points").arg(filename).arg(this->count()).arg(count).toLatin1()); # else # warning Your OS is not supported! # endif #endif // To optimize performance we compute the boundaries of the polygons // To detect inside/outside we need to detect the dateline first // We probably won't need this for spherical projection but for flat projection float x = 0.0, lastx = 0.0; PntPolyLine::PtrVector::Iterator itPolyLine; PntPolyLine::PtrVector::ConstIterator itEndPolyLine = end(); GeoPoint::Vector::ConstIterator itPoint; for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ GeoPoint::Vector::Iterator itEndPoint = (*itPolyLine)->end(); for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if (lastx != 0) if ((x/lastx < 0.0) && ((abs((int)x)+abs((int)lastx)) > 10800.0)) { (*itPolyLine)->setDateLine(true); // qDebug() << "DateLine: " << lastx << x; itPoint = itEndPoint-1; } lastx = x; } } /* // QTime *timer = new QTime(); timer->restart(); for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ const QVector<GeoPoint*>::const_iterator itEndPoint = (*itPolyLine)->end(); for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ (*itPoint)->setMul(6.0f); } } qDebug() << "Curious: " << timer->elapsed(); */ // Now we calculate the boundaries float y = 0; for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ float x0 = 10800.0, x1 = -10800.0; float y0 = 5400.0, y1 = -5400.0; GeoPoint::Vector::ConstIterator itEndPoint = (*itPolyLine)->end(); if ((*itPolyLine)->getDateLine()){ for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if ((x < x0) && (x > -5400)) x0 = x; if ((x > x1) && (x < -5400)) x1 = x; y = (*itPoint).getLat(); if (y < y0) y0 = y; if (y > y1) y1 = y; } (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } else { for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if (x < x0) x0 = x; if (x > x1) x1 = x; y = (*itPoint).getLat(); if (y < y0) y0 = y; if (y > y1) y1 = y; } (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } // qDebug() << "Test" << (int)(x0) << (int)(y0) << (int)(x1) << (int)(y1); // (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } delete timer; // Done } <commit_msg><commit_after>// // C++ Implementation: pntmap // // Description: // // // Author: Torsten Rahn <[email protected]>, (C) 2004 // // Copyright: See COPYING file that comes with this distribution // // #include <stdlib.h> #include <fcntl.h> #include <cmath> #include <unistd.h> #include <QtCore/QFile> #include <QtCore/QDataStream> #include <QtCore/QDebug> #include <QtCore/QTime> #ifdef Q_OS_UNIX # include <sys/types.h> # include <sys/stat.h> # include <sys/mman.h> /* mmap() is defined in this header */ #endif #include "pntmap.h" PntPolyLine::PntPolyLine(){ m_Crossed = false; m_closed = false; m_Num = 0; m_x0 = m_y0 = m_x1 = m_y1 = 0; } PntPolyLine::~PntPolyLine(){ } void PntPolyLine::setBoundary(int x0, int y0, int x1, int y1){ m_x0 = x0; m_y0 = y0; m_x1 = x1; m_y1 = y1; m_boundary.clear(); if (getDateLine()) { int xcenter = (x0 + (21600+x1))/2; if (xcenter > 10800) xcenter -= 21600; if (xcenter < -10800) xcenter += 21600; m_boundary.append(GeoPoint( 1, xcenter, (y0 + y1)/2 )); } else m_boundary.append(GeoPoint( 1, (x0 + x1)/2, (y0 + y1)/2 )); m_boundary.append(GeoPoint( 1, x0, y0)); m_boundary.append(GeoPoint( 1, x1, y1)); m_boundary.append(GeoPoint( 1, x1, y0)); m_boundary.append(GeoPoint( 1, x0, y1)); } PntMap::PntMap(){ } PntMap::~PntMap(){ qDeleteAll(begin(), end()); } void PntMap::load(const QString &filename){ QTime *timer = new QTime(); timer->restart(); #ifdef Q_OS_UNIX // MMAP Start int fd; short* src; struct stat statbuf; if ((fd = open (filename.toLatin1(), O_RDONLY)) < 0) qDebug() << "can't open" << filename << " for reading"; if (fstat (fd,&statbuf) < 0) qDebug() << "fstat error"; int filelength = statbuf.st_size; if ((src = (short*) mmap (0, filelength, PROT_READ, MAP_SHARED, fd, 0)) == (short*) (caddr_t) -1) qDebug() << "mmap error for input"; short header, lat, lng; int count = 0; for (int i=0; i < (filelength >> 1); i+=3){ header = src[i]; lat = src[i+1]; lng = src[i+2]; // Transforming Range of Coordinates to lat [0,10800] , lng [0,21600] lat = -lat; /* 90 00N = -5400 90 00S = 5400 180 00W = -10800 180 00E = 10800 */ if (header > 5){ // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); PntPolyLine *polyline = new PntPolyLine(); append( polyline ); polyline->setNum(header); // Find out whether the Polyline is a river or a closed polygon if ((header >= 7000 && header < 8000) || (header >= 9000 && header < 20000) ) polyline->setClosed(false); else polyline->setClosed(true); polyline->append(GeoPoint(5, (int)(lng), (int)(lat))); } else { // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); last()->append(GeoPoint((int)(header), (int)(lng), (int)(lat))); } ++count; } munmap(src,filelength); close(fd); // qDebug(QString("Opened %1 with %2 Polylines and %3 Points").arg(filename).arg(this->count()).arg(count).toLatin1()); // MMAP End // qDebug() << "Loading Time:" << timer->elapsed(); #else # ifdef Q_OS_WIN int count = 0; // qDebug("Loading PntMap ..."); QFile file( filename ); file.open( QIODevice::ReadOnly ); QDataStream stream( &file ); // read the data serialized from the file stream.setByteOrder( QDataStream::LittleEndian ); short header, lat, lng; // Iterator that points to current PolyLine in PntMap // QList<PntPolyLine*>::iterator it = begin(); // int count = 0; while(!stream.atEnd()){ stream >> header >> lat >> lng; // Transforming Range of Coordinates to lat [0,10800] , lng [0,21600] lat = -lat; if (header > 5){ // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); PntPolyLine *polyline = new PntPolyLine(); append( polyline ); polyline->setNum(header); // Find out whether the Polyline is a river or a closed polygon if ((header >= 7000 && header < 8000)) polyline->setClosed(false); else polyline->setClosed(true); polyline->append(GeoPoint(5, (int)(lng), (int)(lat))); } else { // qDebug(QString("header: %1 lat: %2 lng: %3").arg(header).arg(lat).arg(lng).toLatin1()); last()->append(GeoPoint((int)(header), (int)(lng), (int)(lat))); } ++count; } file.close(); qDebug() << "Loading Time:" << timer->elapsed(); // qDebug(QString("Opened %1 with %2 Polylines and %3 Points").arg(filename).arg(this->count()).arg(count).toLatin1()); # else # warning Your OS is not supported! # endif #endif // To optimize performance we compute the boundaries of the polygons // To detect inside/outside we need to detect the dateline first // We probably won't need this for spherical projection but for flat projection float x = 0.0, lastx = 0.0; PntPolyLine::PtrVector::Iterator itPolyLine; PntPolyLine::PtrVector::ConstIterator itEndPolyLine = end(); GeoPoint::Vector::ConstIterator itPoint; for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ GeoPoint::Vector::Iterator itEndPoint = (*itPolyLine)->end(); for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if (lastx != 0) if ((x/lastx < 0.0) && ((abs((int)x)+abs((int)lastx)) > 10800.0)) { (*itPolyLine)->setDateLine(true); // qDebug() << "DateLine: " << lastx << x; itPoint = itEndPoint-1; } lastx = x; } } /* // QTime *timer = new QTime(); timer->restart(); for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ const QVector<GeoPoint*>::const_iterator itEndPoint = (*itPolyLine)->end(); for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ (*itPoint)->setMul(6.0f); } } qDebug() << "Curious: " << timer->elapsed(); */ // Now we calculate the boundaries float y = 0; for ( itPolyLine = begin(); itPolyLine != itEndPolyLine; ++itPolyLine ){ float x0 = 10800.0, x1 = -10800.0; float y0 = 5400.0, y1 = -5400.0; GeoPoint::Vector::ConstIterator itEndPoint = (*itPolyLine)->end(); if ((*itPolyLine)->getDateLine()){ for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if ((x < x0) && (x > -5400)) x0 = x; if ((x > x1) && (x < -5400)) x1 = x; y = (*itPoint).getLat(); if (y < y0) y0 = y; if (y > y1) y1 = y; } (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } else { for ( itPoint = (*itPolyLine)->begin(); itPoint != itEndPoint; itPoint++ ){ x = (*itPoint).getLng(); if (x < x0) x0 = x; if (x > x1) x1 = x; y = (*itPoint).getLat(); if (y < y0) y0 = y; if (y > y1) y1 = y; } (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } // qDebug() << "Test" << (int)(x0) << (int)(y0) << (int)(x1) << (int)(y1); // (*itPolyLine)->setBoundary((int)(x0),(int)(y0),(int)(x1),(int)(y1)); // (*itPolyLine)->displayBoundary(); } delete timer; // Done } <|endoftext|>
<commit_before>#include <iostream> #include <boost/asio.hpp> #include <google/protobuf/descriptor.h> #include <google/protobuf/service.h> #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-protocol-layer.h" #include "vtrc-client-base/vtrc-client.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "protocol/vtrc-service.pb.h" #include "protocol/vtrc-errors.pb.h" #include <boost/random.hpp> #include <boost/random/random_device.hpp> #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc; void on_connect( const boost::system::error_code &err ) { std::cout << "connected " << err.value( ) << " " << err.message( ) << "\n"; } struct work_time { typedef boost::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(boost::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point stop(boost::chrono::high_resolution_clock::now( )); std::cout << "call time: " << stop - start_ << "\n"; } }; class ping_impl: public vtrc_service::internal { client::vtrc_client *c_; public: ping_impl( client::vtrc_client *c ) :c_( c ) {} void ping(::google::protobuf::RpcController* controller, const ::vtrc_service::ping_req* request, ::vtrc_service::pong_res* response, ::google::protobuf::Closure* done) { common::closure_holder chold(done); std::cout << "ping event rcvd " << c_->connection( ) ->get_protocol( ).get_call_context( ) ->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " //<< vtrc::chrono::high_resolution_clock::now( ) << "\n"; //return; const vtrc::common::call_context *cc = vtrc::common::call_context::get( c_->connection( ) ); vtrc::shared_ptr<google::protobuf::RpcChannel> ch(c_->create_channel( false, true )); vtrc_rpc_lowlevel::message_info mi; vtrc_service::test_rpc::Stub s( ch.get( ) ); s.test2( NULL, &mi, &mi, NULL ); //if( done ) done->Run( ); } }; class test_ev: public vtrc_service::test_events { vtrc::common::connection_iface *c_; public: test_ev( vtrc::common::connection_iface *c ) :c_( c ) {} void test(::google::protobuf::RpcController* controller, const ::vtrc_rpc_lowlevel::message_info* request, ::vtrc_rpc_lowlevel::message_info* response, ::google::protobuf::Closure* done) { common::closure_holder ch(done); std::cout << "test event rcvd " << c_->get_protocol( ).get_call_context( )->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " << "\n"; } }; void run_client( vtrc::shared_ptr<client::vtrc_client> cl, bool wait) { vtrc::shared_ptr<google::protobuf::RpcChannel> ch(cl->create_channel( wait, false )); vtrc_service::test_rpc::Stub s( ch.get( ) ); vtrc_rpc_lowlevel::message_info mi; size_t last = 0; std::cout << "this thread: " << vtrc::this_thread::get_id( ) << " " << "\n"; for( int i=0; i<29999999999; ++i ) { try { if( wait ) vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(1) ); work_time wt; s.test( NULL, &mi, &mi, NULL ); last = mi.message_type( ); std::cout << "response: " << last << "\n"; //cl.reset( ); } catch( const vtrc::common::exception &ex ) { std::cout << "call error: " << " code (" << ex.code( ) << ")" << " category (" << ex.category( ) << ")" << " what: " << ex.what( ) << " (" << ex.additional( ) << ")" << "\n"; //if( i % 100 == 0 ) std::cout << i << "\n"; if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break; if( ex.code( ) == vtrc_errors::ERR_COMM ) break; } catch( const std::exception &ex ) { //std::cout << "call error: " << ex.what( ) << "\n"; } } } int main( ) { common::pool_pair pp(2, 2); vtrc::shared_ptr<client::vtrc_client> cl(client::vtrc_client::create(pp)); //cl->connect( "/tmp/test" ); //cl->connect( "192.168.56.101", "44667" ); cl->connect( "127.0.0.1", "44667" ); //cl->connect( "::1", "44668" ); ///cl->async_connect( "127.0.0.1", "44667", on_connect ); cl->advise_handler( vtrc::shared_ptr<test_ev>(new test_ev(cl->connection( ).get( ))) ); cl->advise_handler( vtrc::shared_ptr<ping_impl>(new ping_impl(cl.get( ))) ); vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(2000) ); vtrc::thread( run_client, cl, true ).detach( ); vtrc::thread( run_client, cl, false ).detach( ); vtrc::thread( run_client, cl, false ).join( ); pp.stop_all( ); pp.join_all( ); return 0; } <commit_msg>protocol<commit_after>#include <iostream> #include <boost/asio.hpp> #include <google/protobuf/descriptor.h> #include <google/protobuf/service.h> #include "vtrc-common/vtrc-pool-pair.h" #include "vtrc-common/vtrc-connection-iface.h" #include "vtrc-common/vtrc-call-context.h" #include "vtrc-common/vtrc-exception.h" #include "vtrc-common/vtrc-protocol-layer.h" #include "vtrc-client-base/vtrc-client.h" #include "protocol/vtrc-rpc-lowlevel.pb.h" #include "protocol/vtrc-service.pb.h" #include "protocol/vtrc-errors.pb.h" #include <boost/random.hpp> #include <boost/random/random_device.hpp> #include "vtrc-thread.h" #include "vtrc-chrono.h" using namespace vtrc; void on_connect( const boost::system::error_code &err ) { std::cout << "connected " << err.value( ) << " " << err.message( ) << "\n"; } struct work_time { typedef boost::chrono::high_resolution_clock::time_point time_point; time_point start_; work_time( ) :start_(boost::chrono::high_resolution_clock::now( )) {} ~work_time( ) { time_point stop(boost::chrono::high_resolution_clock::now( )); std::cout << "call time: " << stop - start_ << "\n"; } }; class ping_impl: public vtrc_service::internal { client::vtrc_client *c_; public: ping_impl( client::vtrc_client *c ) :c_( c ) {} void ping(::google::protobuf::RpcController* controller, const ::vtrc_service::ping_req* request, ::vtrc_service::pong_res* response, ::google::protobuf::Closure* done) { common::closure_holder chold(done); std::cout << "ping event rcvd " << c_->connection( ) ->get_protocol( ).get_call_context( ) ->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " //<< vtrc::chrono::high_resolution_clock::now( ) << "\n"; //return; const vtrc::common::call_context *cc = vtrc::common::call_context::get( c_->connection( ) ); vtrc::shared_ptr<google::protobuf::RpcChannel> ch(c_->create_channel( false, true )); vtrc_rpc_lowlevel::message_info mi; vtrc_service::test_rpc::Stub s( ch.get( ) ); s.test2( NULL, &mi, &mi, NULL ); //if( done ) done->Run( ); } }; class test_ev: public vtrc_service::test_events { vtrc::common::connection_iface *c_; public: test_ev( vtrc::common::connection_iface *c ) :c_( c ) {} void test(::google::protobuf::RpcController* controller, const ::vtrc_rpc_lowlevel::message_info* request, ::vtrc_rpc_lowlevel::message_info* response, ::google::protobuf::Closure* done) { common::closure_holder ch(done); std::cout << "test event rcvd " << c_->get_protocol( ).get_call_context( )->get_lowlevel_message( )->id( ) << " " << vtrc::this_thread::get_id( ) << " " << "\n"; } }; void run_client( vtrc::shared_ptr<client::vtrc_client> cl, bool wait) { vtrc::shared_ptr<google::protobuf::RpcChannel> ch(cl->create_channel( wait, false )); vtrc_service::test_rpc::Stub s( ch.get( ) ); vtrc_rpc_lowlevel::message_info mi; size_t last = 0; std::cout << "this thread: " << vtrc::this_thread::get_id( ) << " " << "\n"; for( int i=0; i<29999999999; ++i ) { try { if( wait ) vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(1) ); work_time wt; s.test( NULL, &mi, &mi, NULL ); last = mi.message_type( ); std::cout << "response: " << last << "\n"; //cl.reset( ); } catch( const vtrc::common::exception &ex ) { std::cout << "call error: " << " code (" << ex.code( ) << ")" << " category (" << ex.category( ) << ")" << " what: " << ex.what( ) << " (" << ex.additional( ) << ")" << "\n"; //if( i % 100 == 0 ) std::cout << i << "\n"; if( ex.category( ) == vtrc_errors::CATEGORY_SYSTEM ) break; if( ex.code( ) == vtrc_errors::ERR_COMM ) break; } catch( const std::exception &ex ) { //std::cout << "call error: " << ex.what( ) << "\n"; } } } int main( ) { common::pool_pair pp(2, 2); vtrc::shared_ptr<client::vtrc_client> cl(client::vtrc_client::create(pp)); cl->connect( "/tmp/test" ); //cl->connect( "192.168.56.101", "44667" ); cl->connect( "127.0.0.1", "44667" ); //cl->connect( "::1", "44668" ); ///cl->async_connect( "127.0.0.1", "44667", on_connect ); cl->advise_handler( vtrc::shared_ptr<test_ev>(new test_ev(cl->connection( ).get( ))) ); cl->advise_handler( vtrc::shared_ptr<ping_impl>(new ping_impl(cl.get( ))) ); vtrc::this_thread::sleep_for( vtrc::chrono::milliseconds(2000) ); //vtrc::thread( run_client, cl, true ).detach( ); vtrc::thread( run_client, cl, false ).detach( ); vtrc::thread( run_client, cl, false ).join( ); pp.stop_all( ); pp.join_all( ); return 0; } <|endoftext|>
<commit_before>// // Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS // Authors: Florent Lamiraux // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. 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. // // 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. #include <hpp/core/problem.hh> #include <iostream> #include <hpp/util/debug.hh> #include <hpp/pinocchio/device.hh> #include <hpp/core/collision-validation.hh> #include <hpp/core/joint-bound-validation.hh> #include <hpp/core/config-validations.hh> #include <hpp/core/problem-target/goal-configurations.hh> #include <hpp/core/configuration-shooter/uniform.hh> #include <hpp/core/steering-method/straight.hh> #include <hpp/core/weighed-distance.hh> #include <hpp/core/path-validation/discretized-collision-checking.hh> #include <hpp/core/continuous-validation/dichotomy.hh> #include <hpp/core/continuous-validation/progressive.hh> #include <hpp/core/configuration-shooter/uniform.hh> namespace hpp { namespace core { Container <ParameterDescription>& pds () { static Container <ParameterDescription> _parameterDescriptions; return _parameterDescriptions; } // ====================================================================== void Problem::declareParameter (const ParameterDescription& desc) { typedef Container<ParameterDescription> CPD_t; std::pair<CPD_t::iterator, bool> ret = pds().map.insert( CPD_t::value_type (desc.name(), desc)); if (!ret.second) ret.first->second = desc; } // ====================================================================== const Container<ParameterDescription>& Problem::parameterDescriptions () { return pds(); } // ====================================================================== const ParameterDescription& Problem::parameterDescription (const std::string& name) { if (pds().has(name)) return pds().get(name); throw std::invalid_argument ("No parameter description with name " + name); } // ====================================================================== ProblemPtr_t Problem::create (DevicePtr_t robot) { ProblemPtr_t p (new Problem (robot)); p->init (p); return p; } ProblemPtr_t Problem::createCopy(const ProblemConstPtr_t& other) { ProblemPtr_t p(new Problem(*other)); p->init(p); return p; } // ====================================================================== Problem::Problem (DevicePtr_t robot) : robot_ (robot), configValidations_ (ConfigValidations::create ()) { } // ====================================================================== void Problem::init (ProblemWkPtr_t wkPtr) { wkPtr_ = wkPtr; distance_ = WeighedDistance::create (robot_); target_ = problemTarget::GoalConfigurations::create (wkPtr_.lock()); steeringMethod_ = steeringMethod::Straight::create (wkPtr_.lock()); pathValidation_ = pathValidation::createDiscretizedCollisionChecking (robot_, 0.05); configurationShooter_ = configurationShooter::Uniform::create (robot_); } // ====================================================================== Problem::Problem () : robot_ (), distance_ (), initConf_ (), target_ (), steeringMethod_ (), configValidations_ (), pathValidation_ (), collisionObstacles_ (), constraints_ (), configurationShooter_() { assert (false && "This constructor should not be used."); } Problem::~Problem () { } // ====================================================================== void Problem::initConfig (const ConfigurationPtr_t& config) { initConf_ = config; } // ====================================================================== const Configurations_t Problem::goalConfigs () const { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); if (gc) { return gc->configurations(); } return Configurations_t(); } // ====================================================================== void Problem::addGoalConfig (const ConfigurationPtr_t& config) { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); // If target is not an instance of GoalConfigurations, create new // instance if (!gc){ gc = problemTarget::GoalConfigurations::create(wkPtr_.lock()); target_ = gc; } gc->addConfiguration(config); } // ====================================================================== void Problem::resetGoalConfigs () { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); // If target is not an instance of GoalConfigurations, create new // instance if (!gc){ gc = problemTarget::GoalConfigurations::create(wkPtr_.lock()); target_ = gc; } gc->resetConfigurations(); } // ====================================================================== void Problem::resetConfigValidations () { configValidations_ = ConfigValidations::create (); } // ====================================================================== void Problem::clearConfigValidations () { configValidations_->clear (); } // ====================================================================== const ObjectStdVector_t& Problem::collisionObstacles () const { return collisionObstacles_; } // ====================================================================== void Problem::collisionObstacles (const ObjectStdVector_t& collisionObstacles) { collisionObstacles_.clear (); // pass the local vector of collisions object to the problem for (ObjectStdVector_t::const_iterator itObj = collisionObstacles.begin(); itObj != collisionObstacles.end(); ++itObj) { addObstacle (*itObj); } } // ====================================================================== void Problem::addObstacle (const CollisionObjectPtr_t& object) { // Add object in local list collisionObstacles_.push_back (object); // Add obstacle to path validation method shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->addObstacle (object); assert(configValidations_); if (configValidations_) { configValidations_->addObstacle (object); } } // ====================================================================== void Problem::removeObstacleFromJoint (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle) { shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->addObstacle (obstacle); assert(configValidations_); if (configValidations_) { configValidations_->removeObstacleFromJoint (joint, obstacle); } } // ====================================================================== void Problem::filterCollisionPairs () { RelativeMotion::matrix_type matrix = RelativeMotion::matrix (robot_); RelativeMotion::fromConstraint (matrix, robot_, constraints_); hppDout (info, "RelativeMotion matrix:\n" << matrix); shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->filterCollisionPairs (matrix); assert(configValidations_); if (configValidations_) { configValidations_->filterCollisionPairs (matrix); } } // ====================================================================== void Problem::setSecurityMargins(const matrix_t& securityMatrix) { shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->setSecurityMargins (securityMatrix); assert(configValidations_); if (configValidations_) { configValidations_->setSecurityMargins (securityMatrix); } } // ====================================================================== void Problem::pathValidation (const PathValidationPtr_t& pathValidation) { pathValidation_ = pathValidation; } // ====================================================================== void Problem::addConfigValidation (const ConfigValidationPtr_t& configValidation) { configValidations_->add ( configValidation ); } // ====================================================================== void Problem::configurationShooter (const ConfigurationShooterPtr_t& configurationShooter) { configurationShooter_ = configurationShooter; } // ====================================================================== void Problem::checkProblem () const { if (!robot ()) { std::string msg ("No device in problem."); hppDout (error, msg); throw std::runtime_error (msg); } if (!initConfig ()) { std::string msg ("No init config in problem."); hppDout (error, msg); throw std::runtime_error (msg); } ValidationReportPtr_t report; if (!configValidations_->validate (*initConf_, report)) { std::ostringstream oss; oss <<"init config invalid : "<< *report; throw std::runtime_error (oss.str ()); } problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); if (gc) { const Configurations_t goals (gc->configurations ()); for (auto config : gc->configurations ()) { if (!configValidations_->validate (*config, report)) { std::ostringstream oss; oss << *report; throw std::runtime_error (oss.str ()); } } } } // ====================================================================== void Problem::setParameter (const std::string& name, const Parameter& value) { const ParameterDescription& desc = parameterDescription(name); if (desc.type() != value.type()) throw std::invalid_argument ("value is not a " + Parameter::typeName (desc.type())); parameters.add (name, value); } // ====================================================================== } // namespace core } // namespace hpp <commit_msg>[Problem] Check that initial and goal configurations satisfy the constraints.<commit_after>// // Copyright (c) 2005, 2006, 2007, 2008, 2009, 2010, 2011 CNRS // Authors: Florent Lamiraux // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. 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. // // 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. #include <hpp/core/problem.hh> #include <iostream> #include <hpp/util/debug.hh> #include <hpp/pinocchio/configuration.hh> #include <hpp/pinocchio/device.hh> #include <hpp/core/collision-validation.hh> #include <hpp/core/joint-bound-validation.hh> #include <hpp/core/config-validations.hh> #include <hpp/core/problem-target/goal-configurations.hh> #include <hpp/core/configuration-shooter/uniform.hh> #include <hpp/core/steering-method/straight.hh> #include <hpp/core/weighed-distance.hh> #include <hpp/core/path-validation/discretized-collision-checking.hh> #include <hpp/core/continuous-validation/dichotomy.hh> #include <hpp/core/continuous-validation/progressive.hh> #include <hpp/core/configuration-shooter/uniform.hh> namespace hpp { namespace core { Container <ParameterDescription>& pds () { static Container <ParameterDescription> _parameterDescriptions; return _parameterDescriptions; } // ====================================================================== void Problem::declareParameter (const ParameterDescription& desc) { typedef Container<ParameterDescription> CPD_t; std::pair<CPD_t::iterator, bool> ret = pds().map.insert( CPD_t::value_type (desc.name(), desc)); if (!ret.second) ret.first->second = desc; } // ====================================================================== const Container<ParameterDescription>& Problem::parameterDescriptions () { return pds(); } // ====================================================================== const ParameterDescription& Problem::parameterDescription (const std::string& name) { if (pds().has(name)) return pds().get(name); throw std::invalid_argument ("No parameter description with name " + name); } // ====================================================================== ProblemPtr_t Problem::create (DevicePtr_t robot) { ProblemPtr_t p (new Problem (robot)); p->init (p); return p; } ProblemPtr_t Problem::createCopy(const ProblemConstPtr_t& other) { ProblemPtr_t p(new Problem(*other)); p->init(p); return p; } // ====================================================================== Problem::Problem (DevicePtr_t robot) : robot_ (robot), configValidations_ (ConfigValidations::create ()) { } // ====================================================================== void Problem::init (ProblemWkPtr_t wkPtr) { wkPtr_ = wkPtr; distance_ = WeighedDistance::create (robot_); target_ = problemTarget::GoalConfigurations::create (wkPtr_.lock()); steeringMethod_ = steeringMethod::Straight::create (wkPtr_.lock()); pathValidation_ = pathValidation::createDiscretizedCollisionChecking (robot_, 0.05); configurationShooter_ = configurationShooter::Uniform::create (robot_); } // ====================================================================== Problem::Problem () : robot_ (), distance_ (), initConf_ (), target_ (), steeringMethod_ (), configValidations_ (), pathValidation_ (), collisionObstacles_ (), constraints_ (), configurationShooter_() { assert (false && "This constructor should not be used."); } Problem::~Problem () { } // ====================================================================== void Problem::initConfig (const ConfigurationPtr_t& config) { initConf_ = config; } // ====================================================================== const Configurations_t Problem::goalConfigs () const { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); if (gc) { return gc->configurations(); } return Configurations_t(); } // ====================================================================== void Problem::addGoalConfig (const ConfigurationPtr_t& config) { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); // If target is not an instance of GoalConfigurations, create new // instance if (!gc){ gc = problemTarget::GoalConfigurations::create(wkPtr_.lock()); target_ = gc; } gc->addConfiguration(config); } // ====================================================================== void Problem::resetGoalConfigs () { problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); // If target is not an instance of GoalConfigurations, create new // instance if (!gc){ gc = problemTarget::GoalConfigurations::create(wkPtr_.lock()); target_ = gc; } gc->resetConfigurations(); } // ====================================================================== void Problem::resetConfigValidations () { configValidations_ = ConfigValidations::create (); } // ====================================================================== void Problem::clearConfigValidations () { configValidations_->clear (); } // ====================================================================== const ObjectStdVector_t& Problem::collisionObstacles () const { return collisionObstacles_; } // ====================================================================== void Problem::collisionObstacles (const ObjectStdVector_t& collisionObstacles) { collisionObstacles_.clear (); // pass the local vector of collisions object to the problem for (ObjectStdVector_t::const_iterator itObj = collisionObstacles.begin(); itObj != collisionObstacles.end(); ++itObj) { addObstacle (*itObj); } } // ====================================================================== void Problem::addObstacle (const CollisionObjectPtr_t& object) { // Add object in local list collisionObstacles_.push_back (object); // Add obstacle to path validation method shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->addObstacle (object); assert(configValidations_); if (configValidations_) { configValidations_->addObstacle (object); } } // ====================================================================== void Problem::removeObstacleFromJoint (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle) { shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->addObstacle (obstacle); assert(configValidations_); if (configValidations_) { configValidations_->removeObstacleFromJoint (joint, obstacle); } } // ====================================================================== void Problem::filterCollisionPairs () { RelativeMotion::matrix_type matrix = RelativeMotion::matrix (robot_); RelativeMotion::fromConstraint (matrix, robot_, constraints_); hppDout (info, "RelativeMotion matrix:\n" << matrix); shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->filterCollisionPairs (matrix); assert(configValidations_); if (configValidations_) { configValidations_->filterCollisionPairs (matrix); } } // ====================================================================== void Problem::setSecurityMargins(const matrix_t& securityMatrix) { shared_ptr<ObstacleUserInterface> oui = HPP_DYNAMIC_PTR_CAST(ObstacleUserInterface, pathValidation_); if (oui) oui->setSecurityMargins (securityMatrix); assert(configValidations_); if (configValidations_) { configValidations_->setSecurityMargins (securityMatrix); } } // ====================================================================== void Problem::pathValidation (const PathValidationPtr_t& pathValidation) { pathValidation_ = pathValidation; } // ====================================================================== void Problem::addConfigValidation (const ConfigValidationPtr_t& configValidation) { configValidations_->add ( configValidation ); } // ====================================================================== void Problem::configurationShooter (const ConfigurationShooterPtr_t& configurationShooter) { configurationShooter_ = configurationShooter; } // ====================================================================== void Problem::checkProblem () const { if (!robot ()) { std::string msg ("No device in problem."); hppDout (error, msg); throw std::runtime_error (msg); } if (!initConfig ()) { std::string msg ("No init config in problem."); hppDout (error, msg); throw std::runtime_error (msg); } // Check that initial configuration is valid ValidationReportPtr_t report; if (!configValidations_->validate (*initConf_, report)) { std::ostringstream oss; oss <<"init config invalid : "<< *report; throw std::runtime_error (oss.str ()); } // Check that initial configuration sarisfies the constraints of the // problem if (!constraints_->isSatisfied(*initConf_)){ std::ostringstream os; os << "Initial configuration " << pinocchio::displayConfig(*initConf_) << " does not satisfy the constraints of the problem."; throw std::logic_error(os.str().c_str()); } // check that goal configurations satisfy are valid problemTarget::GoalConfigurationsPtr_t gc (HPP_DYNAMIC_PTR_CAST(problemTarget::GoalConfigurations, target_)); if (gc) { const Configurations_t goals (gc->configurations ()); for (auto config : gc->configurations ()) { if (!configValidations_->validate (*config, report)) { std::ostringstream oss; oss << *report; throw std::runtime_error (oss.str ()); } // Check that goal configurations sarisfy the constraints of the // problem if (!constraints_->isSatisfied(*config)){ std::ostringstream os; os << "Goal configuration " << pinocchio::displayConfig(*config) << " does not satisfy the constraints of the problem."; throw std::logic_error(os.str().c_str()); } } } } // ====================================================================== void Problem::setParameter (const std::string& name, const Parameter& value) { const ParameterDescription& desc = parameterDescription(name); if (desc.type() != value.type()) throw std::invalid_argument ("value is not a " + Parameter::typeName (desc.type())); parameters.add (name, value); } // ====================================================================== } // namespace core } // namespace hpp <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include "../../include/boids2D/BoidsManager.hpp" BoidsManager::BoidsManager(MapGenerator& map) : m_map(map), m_updateCoeff(0), m_updatePeriod(10) { m_movableBoids = std::make_shared<Matrix<MovableBoidPtr> >(25, 25); m_rootedBoids = std::make_shared<Matrix<RootedBoidPtr> >(25, 25); } BoidsManager::~BoidsManager() { } MovableBoidPtr BoidsManager::addMovableBoid(BoidType boidType, glm::vec3 location, glm::vec3 velocity) { MovableBoidPtr movableBoid; MovableParametersPtr parameters = std::make_shared<MovableParameters>(boidType); switch(boidType) { case WOLF: movableBoid = std::make_shared<MovableBoid>(location, velocity, WOLF, parameters); break; case RABBIT: movableBoid = std::make_shared<MovableBoid>(location, velocity, RABBIT, parameters); break; default: throw std::invalid_argument("valid boidType required"); break; } unsigned int i; unsigned int j; coordToBox(location, i, j); m_movableBoids->add(i, j, movableBoid); m_movableBoidsVec.push_back(movableBoid); return movableBoid; } RootedBoidPtr BoidsManager::addRootedBoid(BoidType boidType, glm::vec3 location) { RootedBoidPtr rootedBoid; switch(boidType) { case CARROT: rootedBoid = std::make_shared<RootedBoid>(location, CARROT); break; case TREE: rootedBoid = std::make_shared<RootedBoid>(location, TREE); break; default: throw std::invalid_argument("valid boidType required"); break; } unsigned int i; unsigned int j; coordToBox(location, i, j); m_rootedBoids->add(i, j, rootedBoid); return rootedBoid; } const std::vector<MovableBoidPtr> & BoidsManager::getMovableBoids() const { return m_movableBoidsVec; } const MatrixMovableBoidPtr & BoidsManager::getMovableBoidsMatrix() const { return m_movableBoids; } const std::list<RootedBoidPtr> BoidsManager::getRootedBoids(const int & i, const int & j) const { return m_rootedBoids->merge(i,j); } const std::vector<RootedBoidPtr> BoidsManager::getAllRootedBoids() const { std::vector<RootedBoidPtr> v; for (unsigned int i = 0; i < m_rootedBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_rootedBoids->getNumCol(); ++j) { for (std::list<RootedBoidPtr>::const_iterator it = m_rootedBoids->at(i,j).begin(); it != m_rootedBoids->at(i,j).end(); ++it) { v.push_back( *it ); } } } return v; } bool BoidsManager::isNight() const { return isNightTime; } void BoidsManager::setTimeDay(bool state) { isNightTime = state; } const std::list<MovableBoidPtr> BoidsManager::getNeighbour(const int & i, const int & j) const { return m_movableBoids->merge(i,j); } Biome BoidsManager::getBiome(const float& x, const float& y) const { return m_map.getBiome(x, y); } float BoidsManager::getHeight(const float& x, const float& y) const { return m_map.getHeight(x, y); } MapGenerator& BoidsManager::getMap() const { return m_map; } void BoidsManager::removeDead() { std::list<MovableBoidPtr>::iterator itm; for (unsigned int i = 0; i < m_movableBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_movableBoids->getNumCol(); ++j) { itm = m_movableBoids->at(i,j).begin(); while ( itm != m_movableBoids->at(i,j).end()) { if (!((*itm)->isFoodRemaining()) || (*itm)->isDecomposed()) { (*itm)->disapear(); itm = m_movableBoids->at(i,j).erase(itm); } else { itm++; } } } } for (std::vector<MovableBoidPtr>::iterator i = m_movableBoidsVec.begin(); i != m_movableBoidsVec.end(); ++i) { if(!((*i)->isFoodRemaining())) { (*i)->disapear(); iter_swap(i, m_movableBoidsVec.end() - 1); m_movableBoidsVec.pop_back(); } } std::list<RootedBoidPtr>::iterator itr; for (unsigned int i = 0; i < m_rootedBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_rootedBoids->getNumCol(); ++j) { itr = m_rootedBoids->at(i,j).begin(); while ( itr != m_rootedBoids->at(i,j).end()) { if (!((*itr)->isFoodRemaining())) { (*itr)->disapear(); itr = m_rootedBoids->at(i,j).erase(itr); } else { itr++; } } } } } bool BoidsManager::getNearestLake(const MovableBoidPtr & boid, glm::vec2 & result) const { return getNearestLake(glm::vec2(boid->getLocation().x, boid->getLocation().y), result); } bool BoidsManager::getNearestLake(const glm::vec2 & position, glm::vec2 & result) const { return m_map.getClosestLake(position.x, position.y, result.x, result.y); } void BoidsManager::coordToBox(const glm::vec3 & location, unsigned int & i, unsigned int & j) const { ///< @todo : Mistake ? i = (unsigned int) floor(location.x / 20.0f); j = (unsigned int) floor(location.y / 20.0f); } void BoidsManager::updateBoidInGrid(MovableBoidPtr mvB, const unsigned int & iprev, const unsigned int & jprev) { unsigned int inext = 0; unsigned int jnext = 0; coordToBox(mvB->getLocation(), inext, jnext); if (iprev != inext || jprev != jnext) { m_movableBoids->move(mvB, iprev, jprev, inext, jnext); } } void BoidsManager::updateTick() { m_updateCoeff++; } bool BoidsManager::isUpdateTick() const { return m_updateCoeff == m_updatePeriod; } void BoidsManager::resetTick() { m_updateCoeff = 0; } <commit_msg>Fix of a segfault.<commit_after>#include <algorithm> #include <iostream> #include "../../include/boids2D/BoidsManager.hpp" BoidsManager::BoidsManager(MapGenerator& map) : m_map(map), m_updateCoeff(0), m_updatePeriod(10) { m_movableBoids = std::make_shared<Matrix<MovableBoidPtr> >(25, 25); m_rootedBoids = std::make_shared<Matrix<RootedBoidPtr> >(25, 25); } BoidsManager::~BoidsManager() { } MovableBoidPtr BoidsManager::addMovableBoid(BoidType boidType, glm::vec3 location, glm::vec3 velocity) { MovableBoidPtr movableBoid; MovableParametersPtr parameters = std::make_shared<MovableParameters>(boidType); switch(boidType) { case WOLF: movableBoid = std::make_shared<MovableBoid>(location, velocity, WOLF, parameters); break; case RABBIT: movableBoid = std::make_shared<MovableBoid>(location, velocity, RABBIT, parameters); break; default: throw std::invalid_argument("valid boidType required"); break; } unsigned int i; unsigned int j; coordToBox(location, i, j); m_movableBoids->add(i, j, movableBoid); m_movableBoidsVec.push_back(movableBoid); return movableBoid; } RootedBoidPtr BoidsManager::addRootedBoid(BoidType boidType, glm::vec3 location) { RootedBoidPtr rootedBoid; switch(boidType) { case CARROT: rootedBoid = std::make_shared<RootedBoid>(location, CARROT); break; case TREE: rootedBoid = std::make_shared<RootedBoid>(location, TREE); break; default: throw std::invalid_argument("valid boidType required"); break; } unsigned int i; unsigned int j; coordToBox(location, i, j); m_rootedBoids->add(i, j, rootedBoid); return rootedBoid; } const std::vector<MovableBoidPtr> & BoidsManager::getMovableBoids() const { return m_movableBoidsVec; } const MatrixMovableBoidPtr & BoidsManager::getMovableBoidsMatrix() const { return m_movableBoids; } const std::list<RootedBoidPtr> BoidsManager::getRootedBoids(const int & i, const int & j) const { return m_rootedBoids->merge(i,j); } const std::vector<RootedBoidPtr> BoidsManager::getAllRootedBoids() const { std::vector<RootedBoidPtr> v; for (unsigned int i = 0; i < m_rootedBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_rootedBoids->getNumCol(); ++j) { for (std::list<RootedBoidPtr>::const_iterator it = m_rootedBoids->at(i,j).begin(); it != m_rootedBoids->at(i,j).end(); ++it) { v.push_back( *it ); } } } return v; } bool BoidsManager::isNight() const { return isNightTime; } void BoidsManager::setTimeDay(bool state) { isNightTime = state; } const std::list<MovableBoidPtr> BoidsManager::getNeighbour(const int & i, const int & j) const { return m_movableBoids->merge(i,j); } Biome BoidsManager::getBiome(const float& x, const float& y) const { return m_map.getBiome(x, y); } float BoidsManager::getHeight(const float& x, const float& y) const { return m_map.getHeight(x, y); } MapGenerator& BoidsManager::getMap() const { return m_map; } void BoidsManager::removeDead() { std::list<MovableBoidPtr>::iterator itm; for (unsigned int i = 0; i < m_movableBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_movableBoids->getNumCol(); ++j) { itm = m_movableBoids->at(i,j).begin(); while ( itm != m_movableBoids->at(i,j).end()) { if (!((*itm)->isFoodRemaining()) || (*itm)->isDecomposed()) { (*itm)->disapear(); itm = m_movableBoids->at(i,j).erase(itm); } else { itm++; } } } } std::vector<std::vector<MovableBoidPtr>::iterator> toDelete; for (std::vector<MovableBoidPtr>::iterator i = m_movableBoidsVec.begin(); i != m_movableBoidsVec.end(); ++i) { if(!((*i)->isFoodRemaining()) || (*i)->isDecomposed()) { (*i)->disapear(); toDelete.push_back(i); } } for (std::vector<std::vector<MovableBoidPtr>::iterator >::iterator it = toDelete.begin(); it != toDelete.end(); ++it) { m_movableBoidsVec.erase(*it); } toDelete.clear(); std::list<RootedBoidPtr>::iterator itr; for (unsigned int i = 0; i < m_rootedBoids->getNumLine(); ++i) { for (unsigned int j = 0; j < m_rootedBoids->getNumCol(); ++j) { itr = m_rootedBoids->at(i,j).begin(); while ( itr != m_rootedBoids->at(i,j).end()) { if (!((*itr)->isFoodRemaining())) { (*itr)->disapear(); itr = m_rootedBoids->at(i,j).erase(itr); } else { itr++; } } } } } bool BoidsManager::getNearestLake(const MovableBoidPtr & boid, glm::vec2 & result) const { return getNearestLake(glm::vec2(boid->getLocation().x, boid->getLocation().y), result); } bool BoidsManager::getNearestLake(const glm::vec2 & position, glm::vec2 & result) const { return m_map.getClosestLake(position.x, position.y, result.x, result.y); } void BoidsManager::coordToBox(const glm::vec3 & location, unsigned int & i, unsigned int & j) const { ///< @todo : Mistake ? i = (unsigned int) floor(location.x / 20.0f); j = (unsigned int) floor(location.y / 20.0f); } void BoidsManager::updateBoidInGrid(MovableBoidPtr mvB, const unsigned int & iprev, const unsigned int & jprev) { unsigned int inext = 0; unsigned int jnext = 0; coordToBox(mvB->getLocation(), inext, jnext); if (iprev != inext || jprev != jnext) { m_movableBoids->move(mvB, iprev, jprev, inext, jnext); } } void BoidsManager::updateTick() { m_updateCoeff++; } bool BoidsManager::isUpdateTick() const { return m_updateCoeff == m_updatePeriod; } void BoidsManager::resetTick() { m_updateCoeff = 0; } <|endoftext|>
<commit_before><commit_msg>Cleaning up code.<commit_after><|endoftext|>
<commit_before>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API 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 Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "web_output.h" #include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace std; void Web_Output::add_encoding_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"encoding error: "<<error; display_error(out.str(), 400); } encoding_errors = true; } void Web_Output::add_parse_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": parse error: "<<error; display_error(out.str(), 400); } parse_errors = true; } void Web_Output::add_static_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": static error: "<<error; display_error(out.str(), 400); } static_errors = true; } void Web_Output::add_encoding_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"encoding remark: "<<error; display_remark(out.str()); } } void Web_Output::add_parse_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": parse remark: "<<error; display_remark(out.str()); } } void Web_Output::add_static_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": static remark: "<<error; display_remark(out.str()); } } void Web_Output::runtime_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"runtime error: "<<error; display_error(out.str(), 200); } } void Web_Output::runtime_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"runtime remark: "<<error; display_remark(out.str()); } } void Web_Output::enforce_header(uint write_mime) { if (header_written == not_yet) write_html_header("", "", write_mime); } void Web_Output::write_html_header (const string& timestamp, const string& area_timestamp, uint write_mime, bool write_js_init, bool write_remarks) { if (header_written != not_yet) return; header_written = html; if (write_mime > 0) { if (write_mime != 200) { if (write_mime == 504) cout<<"Status: "<<write_mime<<" Gateway Timeout\n"; else if (write_mime == 400) cout<<"Status: "<<write_mime<<" Bad Request\n"; else cout<<"Status: "<<write_mime<<"\n"; } if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) { cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; return; } cout<<"Content-type: text/html; charset=utf-8\n\n"; } cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n"; cout<<(write_js_init ? "<body onload=\"init()\">\n\n" : "<body>\n\n"); if (write_remarks) { cout<< "<p>The data included in this document is from www.openstreetmap.org. " "The data is made available under ODbL.</p>\n"; if (timestamp != "") { cout<<"<p>Data included until: "<<timestamp; if (area_timestamp != "") cout<<"<br/>Areas based on data until: "<<area_timestamp; cout<<"</p>\n"; } } } void Web_Output::write_xml_header (const string& timestamp, const string& area_timestamp, bool write_mime) { if (header_written != not_yet) return; header_written = xml; if (write_mime) { if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) { cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; return; } cout<<"Content-type: application/osm3s+xml\n\n"; } cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n" "<note>The data included in this document is from www.openstreetmap.org. " "The data is made available under ODbL.</note>\n"; cout<<"<meta osm_base=\""<<timestamp<<'\"'; if (area_timestamp != "") cout<<" areas=\""<<area_timestamp<<"\""; cout<<"/>\n\n"; } void Web_Output::write_json_header (const string& timestamp, const string& area_timestamp, bool write_mime) { if (header_written != not_yet) return; header_written = json; if (write_mime) { if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) { cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; return; } cout<<"Content-type: application/json\n\n"; } if (padding != "") cout<<padding<<"("; cout<<"{\n" " \"version\": 0.6,\n" " \"generator\": \"Overpass API\",\n" " \"osm3s\": {\n" " \"timestamp_osm_base\": \""<<timestamp<<"\",\n"; if (area_timestamp != "") cout<<" \"timestamp_areas_base\": \""<<area_timestamp<<"\",\n"; cout<<" \"copyright\": \"The data included in this document is from www.openstreetmap.org." " The data is made available under ODbL.\"\n" " },\n" " \"elements\": [\n\n"; } void Web_Output::write_footer() { if (is_options_request) return; if (header_written == xml) cout<<"\n</osm>\n"; else if (header_written == html) cout<<"\n</body>\n</html>\n"; else if (header_written == json) cout<<"\n\n ]\n}"<<(padding != "" ? ");\n" : "\n"); header_written = final; } void Web_Output::display_remark(const string& text) { enforce_header(200); if (is_options_request) return; if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: " <<text<<" </p>\n"; } void Web_Output::display_error(const string& text, uint write_mime) { enforce_header(write_mime); if (is_options_request) return; if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: " <<text<<" </p>\n"; } <commit_msg>Enhanced HTTP header management to cope with HTTP OPTIONS.<commit_after>/** Copyright 2008, 2009, 2010, 2011, 2012 Roland Olbricht * * This file is part of Overpass_API. * * Overpass_API is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Overpass_API 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 Affero General Public License * along with Overpass_API. If not, see <http://www.gnu.org/licenses/>. */ #include "web_output.h" #include <iomanip> #include <iostream> #include <sstream> #include <string> using namespace std; void Web_Output::add_encoding_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"encoding error: "<<error; display_error(out.str(), 400); } encoding_errors = true; } void Web_Output::add_parse_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": parse error: "<<error; display_error(out.str(), 400); } parse_errors = true; } void Web_Output::add_static_error(const string& error, int line_number) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"line "<<line_number<<": static error: "<<error; display_error(out.str(), 400); } static_errors = true; } void Web_Output::add_encoding_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"encoding remark: "<<error; display_remark(out.str()); } } void Web_Output::add_parse_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": parse remark: "<<error; display_remark(out.str()); } } void Web_Output::add_static_remark(const string& error, int line_number) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"line "<<line_number<<": static remark: "<<error; display_remark(out.str()); } } void Web_Output::runtime_error(const string& error) { if (log_level != Error_Output::QUIET) { ostringstream out; out<<"runtime error: "<<error; display_error(out.str(), 200); } } void Web_Output::runtime_remark(const string& error) { if (log_level == Error_Output::VERBOSE) { ostringstream out; out<<"runtime remark: "<<error; display_remark(out.str()); } } void Web_Output::enforce_header(uint write_mime) { if (header_written == not_yet) write_html_header("", "", write_mime); } void Web_Output::write_html_header (const string& timestamp, const string& area_timestamp, uint write_mime, bool write_js_init, bool write_remarks) { if (header_written != not_yet) return; header_written = html; if (write_mime > 0) { if (write_mime != 200) { if (write_mime == 504) cout<<"Status: "<<write_mime<<" Gateway Timeout\n"; else if (write_mime == 400) cout<<"Status: "<<write_mime<<" Bad Request\n"; else cout<<"Status: "<<write_mime<<"\n"; } if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; cout<<"Content-type: text/html; charset=utf-8\n\n"; if (is_options_request) return; } cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n" " \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n" "<head>\n" " <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" lang=\"en\"/>\n" " <title>OSM3S Response</title>\n" "</head>\n"; cout<<(write_js_init ? "<body onload=\"init()\">\n\n" : "<body>\n\n"); if (write_remarks) { cout<< "<p>The data included in this document is from www.openstreetmap.org. " "The data is made available under ODbL.</p>\n"; if (timestamp != "") { cout<<"<p>Data included until: "<<timestamp; if (area_timestamp != "") cout<<"<br/>Areas based on data until: "<<area_timestamp; cout<<"</p>\n"; } } } void Web_Output::write_xml_header (const string& timestamp, const string& area_timestamp, bool write_mime) { if (header_written != not_yet) return; header_written = xml; if (write_mime) { if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; cout<<"Content-type: application/osm3s+xml\n\n"; if (is_options_request) return; } cout<< "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<osm version=\"0.6\" generator=\"Overpass API\">\n" "<note>The data included in this document is from www.openstreetmap.org. " "The data is made available under ODbL.</note>\n"; cout<<"<meta osm_base=\""<<timestamp<<'\"'; if (area_timestamp != "") cout<<" areas=\""<<area_timestamp<<"\""; cout<<"/>\n\n"; } void Web_Output::write_json_header (const string& timestamp, const string& area_timestamp, bool write_mime) { if (header_written != not_yet) return; header_written = json; if (write_mime) { if (allow_headers != "") cout<<"Access-Control-Allow-Headers: "<<allow_headers<<'\n'; if (has_origin) cout<<"Access-Control-Allow-Origin: *\n"; if (is_options_request) cout<<"Access-Control-Allow-Methods: GET, POST, OPTIONS\n" "Content-Length: 0\n"; cout<<"Content-type: application/json\n\n"; if (is_options_request) return; } if (padding != "") cout<<padding<<"("; cout<<"{\n" " \"version\": 0.6,\n" " \"generator\": \"Overpass API\",\n" " \"osm3s\": {\n" " \"timestamp_osm_base\": \""<<timestamp<<"\",\n"; if (area_timestamp != "") cout<<" \"timestamp_areas_base\": \""<<area_timestamp<<"\",\n"; cout<<" \"copyright\": \"The data included in this document is from www.openstreetmap.org." " The data is made available under ODbL.\"\n" " },\n" " \"elements\": [\n\n"; } void Web_Output::write_footer() { if (is_options_request) return; if (header_written == xml) cout<<"\n</osm>\n"; else if (header_written == html) cout<<"\n</body>\n</html>\n"; else if (header_written == json) cout<<"\n\n ]\n}"<<(padding != "" ? ");\n" : "\n"); header_written = final; } void Web_Output::display_remark(const string& text) { enforce_header(200); if (is_options_request) return; if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#00BB00\">Remark</strong>: " <<text<<" </p>\n"; } void Web_Output::display_error(const string& text, uint write_mime) { enforce_header(write_mime); if (is_options_request) return; if (header_written == xml) cout<<"<remark> "<<text<<" </remark>\n"; else if (header_written == html) cout<<"<p><strong style=\"color:#FF0000\">Error</strong>: " <<text<<" </p>\n"; } <|endoftext|>
<commit_before>// Copyright 2014 Vinzenz Feenstra // // 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. #ifndef GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED #define GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED #include <pypa/parser/symbol_table.hh> #include <pypa/ast/tree_walker.hh> namespace pypa { #define PYPA_ADD_SYMBOL_ERR(MSG, AST) add_error(MSG, AST, __LINE__, __FILE__, __PRETTY_FUNCTION__) #define PYPA_ADD_SYMBOL_WARN(MSG, AST) add_warn(MSG, AST, __LINE__, __FILE__, __PRETTY_FUNCTION__) struct symbol_table_visitor { SymbolTablePtr table; SymbolErrorReportFun push_error; void add_error(char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { add_error(ErrorType::SyntaxError, message, o, line, file, function); } void add_warn(char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { add_error(ErrorType::SyntaxWarning, message, o, line, file, function); } void add_error(ErrorType type, char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { if(push_error) { assert(message); push_error({ type, message, {{}, o.line, o.column, {}}, {}, {}, line, file ? file : "", function ? function : "" }); } } uint32_t lookup(String const & name) { String mangled = mangle(name); uint32_t result = 0; if(table->current->symbols.count(name)) { result = table->current->symbols[name]; } return result; } void implicit_arg(uint32_t pos, Ast & a) { char buffer[32]{}; if(::snprintf(buffer, sizeof(buffer), ".%u", pos) > 0) { add_def(buffer, SymbolFlag_Param, a); } } void params_nested(AstExprList & args) { for(AstExpr & e : args) { assert(e && "Expected valid AstExpr instance"); if(e->type == AstType::Tuple) { AstTuple & t = *std::static_pointer_cast<AstTuple>(e); params(t.elements, false); } } } void params(AstExprList & args, bool toplevel) { for(size_t i = 0; i < args.size(); ++i) { AstExpr & e = args[i]; assert(e && "Expected valid AstExpr instance"); switch(e->type) { case AstType::Name: { AstName & n = *std::static_pointer_cast<AstName>(e); assert(n.context == AstContext::Param || (n.context == AstContext::Store && !toplevel)); add_def(n.id, SymbolFlag_Param, n); break; } case AstType::Tuple: { AstTuple & t = *std::static_pointer_cast<AstTuple>(e); assert(t.context == AstContext::Store); if(toplevel) { implicit_arg(uint32_t(i), t); } break; } default: PYPA_ADD_SYMBOL_ERR("Invalid expression in parameter list", *e); break; } } if(toplevel) { params_nested(args); } } void arguments(AstArguments & args) { params(args.arguments, true); if(args.args) { add_def(get_name(args.args), SymbolFlag_Param, *args.args); table->current->has_varargs = true; } if(args.kwargs) { add_def(get_name(args.kwargs), SymbolFlag_Param, *args.kwargs); table->current->has_varkw = true; } assert(args.keywords.empty() && "There must be no keyword items in a lambda or function definition"); } String const & get_name(AstExpr const & expr) { assert(expr && expr->type == AstType::Name); return std::static_pointer_cast<AstName>(expr)->id; } String mangle(String name) { // No class no private variable if(!table->current_class.empty()) { return name; } // Must start with 2 underscores if(name.find_first_not_of('_') != 2) { return name; } // NO items in __<SOMETHING>__ form should be mangled if(name.size() > 2 && name.find_last_not_of('_', 2) != name.size() - 2) { return name; } // Don't mangle names with dots if(name.find_first_of('.') != String::npos) { return name; } char const * classname = table->current_class.c_str(); // strip leading _ from the classname while(*classname == '_') { ++classname; } // Don't mangle just underscore classes if(!*classname) { return name; } name = "_" + (classname + name); return name; } void add_def(String name, uint32_t flags, Ast & a) { String mangled = mangle(name); uint32_t symflags = 0; if(table->current->symbols.count(name)) { symflags = table->current->symbols[name]; if((flags & SymbolFlag_Param) && (flags & SymbolFlag_Param)) { String errmsg = "Duplicated argument '" + name + "'in function definition"; PYPA_ADD_SYMBOL_ERR(errmsg.c_str(), a); return; } symflags |= flags; } else { symflags = flags; } table->current->symbols[mangled] = symflags; if(flags & SymbolFlag_Param) { table->current->variables.insert(mangled); } else if(flags & SymbolFlag_Global) { if(table->module) { table->module->symbols[mangled] |= flags; } } } bool operator() (AstFunctionDef & f) { String const & name = get_name(f.name); // We can keep the ref add_def(name, SymbolFlag_Local, f); walk_tree(f.args.defaults, *this); walk_tree(f.decorators, *this); table->enter_block(BlockType::Function, name, f); // TODO: Special arguments handling arguments(f.args); walk_tree(*f.body, *this); table->leave_block(); return false; } bool operator() (AstGlobal & g) { for(auto name : g.names) { assert(name); AstName & n = *name; uint32_t flags = lookup(n.id); if(flags & (SymbolFlag_Local | SymbolFlag_Used)) { String errmsg = "Name '" + n.id + "' is "; if(flags & SymbolFlag_Local) { errmsg += "is assigned to before global declaration"; PYPA_ADD_SYMBOL_WARN(errmsg.c_str(), n); } else { errmsg += "is used prior to global declaration"; PYPA_ADD_SYMBOL_WARN(errmsg.c_str(), n); } } add_def(n.id, SymbolFlag_Global, n); } return false; } bool operator() (AstClassDef & c) { String const & name = get_name(c.name); // We can keep the ref add_def(name, SymbolFlag_Local, c); walk_tree(c.bases, *this); walk_tree(c.decorators, *this); table->enter_block(BlockType::Class, name, c); String current_class; current_class.swap(table->current_class); table->current_class = name; walk_tree(*c.body, *this); table->leave_block(); current_class.swap(table->current_class); return false; } bool operator() (AstLambda & l) { walk_tree(l.arguments.defaults, *this); table->enter_block(BlockType::Function, "<lambda>", l); arguments(l.arguments); walk_tree(l.body, *this); table->leave_block(); return false; } bool operator() (AstReturn & r) { if(r.value) { if(table->current->is_generator) { PYPA_ADD_SYMBOL_ERR("Return value in generator", r); } } return true; } bool operator() (AstModule & m) { table->enter_block(BlockType::Module, table->file_name, m); return true; } bool operator() (AstYieldExpr & y) { table->current->is_generator = true; if(table->current->returns_value) { PYPA_ADD_SYMBOL_ERR("Return value in generator", y); } return true; } bool operator() (AstImportFrom & i) { if(i.names) visit(*this, *i.names); return true; } bool operator() (AstImport & i) { if(i.names) visit(*this, *i.names); return false; } bool operator() (AstAlias & a) { AstName & n = *std::static_pointer_cast<AstName>(a.as_name ? a.as_name : a.name); String name = n.id; if(n.dotted) { size_t pos = name.find_first_of('.'); assert(String::npos != pos); name.erase(pos); } if(name == "*") { if(table->current->type != BlockType::Module) { PYPA_ADD_SYMBOL_WARN("Import * only allowed at module level", n); } table->current->unoptimized |= OptimizeFlag_ImportStar; } else { add_def(name, SymbolFlag_Import, a); } return false; } bool operator() (AstName & n) { add_def(n.id, n.context == AstContext::Load ? SymbolFlag_Used : SymbolFlag_Local, n); return false; } template< typename T > bool operator ()(T) { return true; } }; } #endif // GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED <commit_msg>Last bits of the SymbolTable implementation<commit_after>// Copyright 2014 Vinzenz Feenstra // // 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. #ifndef GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED #define GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED #include <pypa/parser/symbol_table.hh> #include <pypa/ast/tree_walker.hh> namespace pypa { #define PYPA_ADD_SYMBOL_ERR(MSG, AST) add_error(MSG, AST, __LINE__, __FILE__, __PRETTY_FUNCTION__) #define PYPA_ADD_SYMBOL_WARN(MSG, AST) add_warn(MSG, AST, __LINE__, __FILE__, __PRETTY_FUNCTION__) struct symbol_table_visitor { SymbolTablePtr table; SymbolErrorReportFun push_error; void add_error(char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { add_error(ErrorType::SyntaxError, message, o, line, file, function); } void add_warn(char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { add_error(ErrorType::SyntaxWarning, message, o, line, file, function); } void add_error(ErrorType type, char const * message, Ast & o, int line = -1, char const * file = 0, char const * function = 0) { if(push_error) { assert(message); push_error({ type, message, {{}, o.line, o.column, {}}, {}, {}, line, file ? file : "", function ? function : "" }); } } uint32_t lookup(String const & name) { String mangled = mangle(name); uint32_t result = 0; if(table->current->symbols.count(name)) { result = table->current->symbols[name]; } return result; } void implicit_arg(uint32_t pos, Ast & a) { char buffer[32]{}; if(::snprintf(buffer, sizeof(buffer), ".%u", pos) > 0) { add_def(buffer, SymbolFlag_Param, a); } } void params_nested(AstExprList & args) { for(AstExpr & e : args) { assert(e && "Expected valid AstExpr instance"); if(e->type == AstType::Tuple) { AstTuple & t = *std::static_pointer_cast<AstTuple>(e); params(t.elements, false); } } } void params(AstExprList & args, bool toplevel) { for(size_t i = 0; i < args.size(); ++i) { AstExpr & e = args[i]; assert(e && "Expected valid AstExpr instance"); switch(e->type) { case AstType::Name: { AstName & n = *std::static_pointer_cast<AstName>(e); assert(n.context == AstContext::Param || (n.context == AstContext::Store && !toplevel)); add_def(n.id, SymbolFlag_Param, n); break; } case AstType::Tuple: { AstTuple & t = *std::static_pointer_cast<AstTuple>(e); assert(t.context == AstContext::Store); if(toplevel) { implicit_arg(uint32_t(i), t); } break; } default: PYPA_ADD_SYMBOL_ERR("Invalid expression in parameter list", *e); break; } } if(toplevel) { params_nested(args); } } void arguments(AstArguments & args) { params(args.arguments, true); if(args.args) { add_def(get_name(args.args), SymbolFlag_Param, *args.args); table->current->has_varargs = true; } if(args.kwargs) { add_def(get_name(args.kwargs), SymbolFlag_Param, *args.kwargs); table->current->has_varkw = true; } assert(args.keywords.empty() && "There must be no keyword items in a lambda or function definition"); } String const & get_name(AstExpr const & expr) { assert(expr && expr->type == AstType::Name); return std::static_pointer_cast<AstName>(expr)->id; } String mangle(String name) { // No class no private variable if(!table->current_class.empty()) { return name; } // Must start with 2 underscores if(name.find_first_not_of('_') != 2) { return name; } // NO items in __<SOMETHING>__ form should be mangled if(name.size() > 2 && name.find_last_not_of('_', 2) != name.size() - 2) { return name; } // Don't mangle names with dots if(name.find_first_of('.') != String::npos) { return name; } char const * classname = table->current_class.c_str(); // strip leading _ from the classname while(*classname == '_') { ++classname; } // Don't mangle just underscore classes if(!*classname) { return name; } name = "_" + (classname + name); return name; } void add_def(String name, uint32_t flags, Ast & a) { String mangled = mangle(name); uint32_t symflags = 0; if(table->current->symbols.count(name)) { symflags = table->current->symbols[name]; if((flags & SymbolFlag_Param) && (flags & SymbolFlag_Param)) { String errmsg = "Duplicated argument '" + name + "'in function definition"; PYPA_ADD_SYMBOL_ERR(errmsg.c_str(), a); return; } symflags |= flags; } else { symflags = flags; } table->current->symbols[mangled] = symflags; if(flags & SymbolFlag_Param) { table->current->variables.insert(mangled); } else if(flags & SymbolFlag_Global) { if(table->module) { table->module->symbols[mangled] |= flags; } } } bool operator() (AstFunctionDef & f) { String const & name = get_name(f.name); // We can keep the ref add_def(name, SymbolFlag_Local, f); walk_tree(f.args.defaults, *this); walk_tree(f.decorators, *this); table->enter_block(BlockType::Function, name, f); // TODO: Special arguments handling arguments(f.args); walk_tree(*f.body, *this); table->leave_block(); return false; } bool operator() (AstGlobal & g) { for(auto name : g.names) { assert(name); AstName & n = *name; uint32_t flags = lookup(n.id); if(flags & (SymbolFlag_Local | SymbolFlag_Used)) { String errmsg = "Name '" + n.id + "' is "; if(flags & SymbolFlag_Local) { errmsg += "is assigned to before global declaration"; PYPA_ADD_SYMBOL_WARN(errmsg.c_str(), n); } else { errmsg += "is used prior to global declaration"; PYPA_ADD_SYMBOL_WARN(errmsg.c_str(), n); } } add_def(n.id, SymbolFlag_Global, n); } return false; } void handle_comprehension(bool generator, String const & scope_name, Ast & e, AstExprList & generators, AstExpr element, AstExpr value) { bool needs_tmp = !generator; assert(!generators.empty() && generators.front()); AstComprehension & outermost = *std::static_pointer_cast<AstComprehension>(generators.front()); walk_tree(*outermost.iter, *this); table->enter_block(BlockType::Function, scope_name, e); table->current->is_generator = generator; implicit_arg(0, e); if(needs_tmp) { char tmpname[32]{}; snprintf(tmpname, sizeof(tmpname), "_[%d]", ++table->current->temp_name_count); add_def(tmpname, SymbolFlag_Local, e); } walk_tree(outermost.target, *this); walk_tree(outermost.ifs, *this); for(size_t i = 1; i < generators.size(); ++i) { walk_tree(*generators[i], *this); } if(value) { walk_tree(*value, *this); } walk_tree(*element, *this); table->leave_block(); } bool operator() (AstDictComp & d) { handle_comprehension(false, "dictcomp", d, d.generators, d.key, d.value); return false; } bool operator() (AstSetComp & s) { handle_comprehension(false, "setcomp", s, s.generators, s.element, {}); return false; } bool operator() (AstGenerator & g) { handle_comprehension(false, "genexpr", g, g.generators, g.element, {}); return false; } bool operator() (AstClassDef & c) { String const & name = get_name(c.name); // We can keep the ref add_def(name, SymbolFlag_Local, c); walk_tree(c.bases, *this); walk_tree(c.decorators, *this); table->enter_block(BlockType::Class, name, c); String current_class; current_class.swap(table->current_class); table->current_class = name; walk_tree(*c.body, *this); table->leave_block(); current_class.swap(table->current_class); return false; } bool operator() (AstLambda & l) { walk_tree(l.arguments.defaults, *this); table->enter_block(BlockType::Function, "<lambda>", l); arguments(l.arguments); walk_tree(l.body, *this); table->leave_block(); return false; } bool operator() (AstReturn & r) { if(r.value) { if(table->current->is_generator) { PYPA_ADD_SYMBOL_ERR("Return value in generator", r); } } return true; } bool operator() (AstModule & m) { table->enter_block(BlockType::Module, table->file_name, m); return true; } bool operator() (AstYieldExpr & y) { table->current->is_generator = true; if(table->current->returns_value) { PYPA_ADD_SYMBOL_ERR("Return value in generator", y); } return true; } bool operator() (AstImportFrom & i) { if(i.names) visit(*this, *i.names); return true; } bool operator() (AstImport & i) { if(i.names) visit(*this, *i.names); return false; } bool operator() (AstAlias & a) { AstName & n = *std::static_pointer_cast<AstName>(a.as_name ? a.as_name : a.name); String name = n.id; if(n.dotted) { size_t pos = name.find_first_of('.'); assert(String::npos != pos); name.erase(pos); } if(name == "*") { if(table->current->type != BlockType::Module) { PYPA_ADD_SYMBOL_WARN("Import * only allowed at module level", n); } table->current->unoptimized |= OptimizeFlag_ImportStar; table->current->opt_last_line = n.line; } else { add_def(name, SymbolFlag_Import, a); } return false; } bool operator() (AstExec & e) { table->current->opt_last_line = e.line; if(e.globals) { table->current->unoptimized |= OptimizeFlag_Exec; } else { table->current->unoptimized |= OptimizeFlag_BareExec; } return true; } bool operator() (AstName & n) { add_def(n.id, n.context == AstContext::Load ? SymbolFlag_Used : SymbolFlag_Local, n); return false; } template< typename T > bool operator ()(T) { return true; } }; } #endif // GUARD_PYPA_PARSER_SYMBOL_TABLE_VISITOR_HH_INCLUDED <|endoftext|>
<commit_before>// Copyright (c) 2015 GitHub Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "scrollbar-style-observer.h" using namespace v8; // NOLINT void ScrollbarStyleObserver::Init(Local<Object> target) { Nan::HandleScope scope; Local<FunctionTemplate> newTemplate = Nan::New<FunctionTemplate>(ScrollbarStyleObserver::New); newTemplate->SetClassName(Nan::New<String>("ScrollbarStyleObserver").ToLocalChecked()); newTemplate->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate(); Nan::SetMethod(proto, "getPreferredScrollbarStyle", ScrollbarStyleObserver::GetPreferredScrollbarStyle); target->Set(Nan::New<String>("ScrollbarStyleObserver").ToLocalChecked(), Nan::GetFunction(newTemplate).ToLocalChecked()); } NODE_MODULE(scrollbar_style_observer, ScrollbarStyleObserver::Init) NAN_METHOD(ScrollbarStyleObserver::New) { Nan::HandleScope scope; Local<Function> callbackHandle = info[0].As<Function>(); Nan::Callback *callback = new Nan::Callback(callbackHandle); ScrollbarStyleObserver *observer = new ScrollbarStyleObserver(callback); observer->Wrap(info.This()); return; } ScrollbarStyleObserver::ScrollbarStyleObserver(Nan::Callback *callback) : callback(callback) { } ScrollbarStyleObserver::~ScrollbarStyleObserver() { delete callback; } void ScrollbarStyleObserver::HandleScrollbarStyleChanged() { } NAN_METHOD(ScrollbarStyleObserver::GetPreferredScrollbarStyle) { Nan::HandleScope scope; info.GetReturnValue().Set(Nan::New<String>("legacy").ToLocalChecked()); } <commit_msg>fix lint<commit_after>// Copyright (c) 2015 GitHub Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "scrollbar-style-observer.h" using namespace v8; // NOLINT void ScrollbarStyleObserver::Init(Local<Object> target) { Nan::HandleScope scope; Local<FunctionTemplate> newTemplate = Nan::New<FunctionTemplate>(ScrollbarStyleObserver::New); newTemplate->SetClassName(Nan::New<String>("ScrollbarStyleObserver").ToLocalChecked()); newTemplate->InstanceTemplate()->SetInternalFieldCount(1); Local<ObjectTemplate> proto = newTemplate->PrototypeTemplate(); Nan::SetMethod(proto, "getPreferredScrollbarStyle", ScrollbarStyleObserver::GetPreferredScrollbarStyle); target->Set( Nan::New<String>("ScrollbarStyleObserver").ToLocalChecked(), Nan::GetFunction(newTemplate).ToLocalChecked()); } NODE_MODULE(scrollbar_style_observer, ScrollbarStyleObserver::Init) NAN_METHOD(ScrollbarStyleObserver::New) { Nan::HandleScope scope; Local<Function> callbackHandle = info[0].As<Function>(); Nan::Callback *callback = new Nan::Callback(callbackHandle); ScrollbarStyleObserver *observer = new ScrollbarStyleObserver(callback); observer->Wrap(info.This()); return; } ScrollbarStyleObserver::ScrollbarStyleObserver(Nan::Callback *callback) : callback(callback) { } ScrollbarStyleObserver::~ScrollbarStyleObserver() { delete callback; } void ScrollbarStyleObserver::HandleScrollbarStyleChanged() { } NAN_METHOD(ScrollbarStyleObserver::GetPreferredScrollbarStyle) { Nan::HandleScope scope; info.GetReturnValue().Set(Nan::New<String>("legacy").ToLocalChecked()); } <|endoftext|>
<commit_before>#include "SlitherlinkDatabase.h" #include "SlitherlinkDatabaseMethod.hpp" #include "../common/SolverConstant.h" namespace Penciloid { int *SlitherlinkDatabase::database = nullptr; const int SlitherlinkDatabase::DATABASE_DX[] = { -2, -2, -1, -1, -1, 0, 0, 1, 1, 1, 2, 2 }; const int SlitherlinkDatabase::DATABASE_DY[] = { -1, 1, -2, 0, 2, -1, 1, -2, 0, 2, -1, 1 }; void SlitherlinkDatabase::CreateDatabase() { const int pow3[] = { 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441 }; ReleaseDatabase(); database = new int[pow3[12] * 4]; int styles[12]; for (int hint = 0; hint <= 3; ++hint) { for (int id = pow3[12] - 1; id >= 0; --id) { int tmp = id; int undecided_pos = -1; for (int i = 0; i < 12; ++i) { styles[i] = tmp % 3; tmp /= 3; if (styles[i] == 0) undecided_pos = i; } if (undecided_pos == -1) { bool consistency = true; if (8 - (styles[3] + styles[5] + styles[6] + styles[8]) != hint) { consistency = false; } tmp = 8 - (styles[0] + styles[2] + styles[3] + styles[5]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[1] + styles[3] + styles[4] + styles[6]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[5] + styles[7] + styles[8] + styles[10]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[6] + styles[8] + styles[9] + styles[11]); if (tmp != 0 && tmp != 2) consistency = false; if (consistency) { int tmp = 0; for (int i = 0; i < 12; ++i) tmp |= styles[i] << (2 * i); database[hint * pow3[12] + id] = tmp; } else { database[hint * pow3[12] + id] = -1; } } else { int base1 = database[hint * pow3[12] + id + pow3[undecided_pos]]; int base2 = database[hint * pow3[12] + id + pow3[undecided_pos] * 2]; database[hint * pow3[12] + id] = base1 & base2; } } } } void SlitherlinkDatabase::CreateReducedDatabase(SlitherlinkDatabaseMethod &method) { const int pow3[] = { 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441 }; ReleaseDatabase(); database = new int[pow3[12] * 4]; int styles[12]; for (int hint = 0; hint <= 3; ++hint) { for (int id = pow3[12] - 1; id >= 0; --id) { int tmp = id; for (int i = 0; i < 12; ++i) { styles[i] = tmp % 3; tmp /= 3; } database[hint * pow3[12] + id] = SolveLocal(hint, styles, method); } } } void SlitherlinkDatabase::ReleaseDatabase() { if (database) { delete[] database; database = nullptr; } } int SlitherlinkDatabase::SolveLocal(int clue, int styles[12], SlitherlinkDatabaseMethod &method) { const int UNDECIDED = 0, LINE = 1, BLANK = 2; int segments[5][5]; for (int i = 0; i < 12; ++i) segments[2 + DATABASE_DY[i]][2 + DATABASE_DX[i]] = styles[i]; if (method.adjacent_lines) { int n_lines = (segments[2][1] == LINE ? 1 : 0) + (segments[2][3] == LINE ? 1 : 0) + (segments[1][2] == LINE ? 1 : 0) + (segments[3][2] == LINE ? 1 : 0); int n_blanks = (segments[2][1] == BLANK ? 1 : 0) + (segments[2][3] == BLANK ? 1 : 0) + (segments[1][2] == BLANK ? 1 : 0) + (segments[3][2] == BLANK ? 1 : 0); if (n_lines > clue || 4 - n_blanks < clue) return -1; if (n_lines == clue) { if (segments[2][1] == UNDECIDED) segments[2][1] = BLANK; if (segments[2][3] == UNDECIDED) segments[2][3] = BLANK; if (segments[1][2] == UNDECIDED) segments[1][2] = BLANK; if (segments[3][2] == UNDECIDED) segments[3][2] = BLANK; } if (4 - n_blanks == clue) { if (segments[2][1] == UNDECIDED) segments[2][1] = LINE; if (segments[2][3] == UNDECIDED) segments[2][3] = LINE; if (segments[1][2] == UNDECIDED) segments[1][2] = LINE; if (segments[3][2] == UNDECIDED) segments[3][2] = LINE; } } for (int dir = 0; dir < 4; ++dir) { int dy1 = GridConstant::GRID_DY[dir], dx1 = GridConstant::GRID_DX[dir]; int dy2 = GridConstant::GRID_DY[(dir + 1) % 4], dx2 = GridConstant::GRID_DX[(dir + 1) % 4]; if (segments[2 + dy1 * 2 + dy2][2 + dx1 * 2 + dx2] == BLANK && segments[2 + dy1 + dy2 * 2][2 + dx1 + dx2 * 2] == BLANK) { // this cell is corner if (clue == 1 && method.corner_1) { segments[2 + dy1][2 + dx1] = segments[2 + dy2][2 + dx2] = BLANK; } if (clue == 2 && method.corner_2) { int out_y1, out_x1, out_y2, out_x2; out_y1 = 2 + dy1 * 2 - dy2, out_x1 = 2 + dx1 * 2 - dx2; out_y2 = 2 + dy1 - dy2 * 2, out_x2 = 2 + dx1 - dx2 * 2; if (segments[out_y1][out_x1] == LINE) segments[out_y2][out_x2] |= BLANK; if (segments[out_y1][out_x1] == BLANK) segments[out_y2][out_x2] |= LINE; if (segments[out_y2][out_x2] == LINE) segments[out_y1][out_x1] |= BLANK; if (segments[out_y2][out_x2] == BLANK) segments[out_y1][out_x1] |= LINE; out_y1 = 2 - dy1 * 2 + dy2, out_x1 = 2 - dx1 * 2 + dx2; out_y2 = 2 - dy1 + dy2 * 2, out_x2 = 2 - dx1 + dx2 * 2; if (segments[out_y1][out_x1] == LINE) segments[out_y2][out_x2] |= BLANK; if (segments[out_y1][out_x1] == BLANK) segments[out_y2][out_x2] |= LINE; if (segments[out_y2][out_x2] == LINE) segments[out_y1][out_x1] |= BLANK; if (segments[out_y2][out_x2] == BLANK) segments[out_y1][out_x1] |= LINE; } if (clue == 3 && method.corner_3) { segments[2 + dy1][2 + dx1] = segments[2 + dy2][2 + dx2] = LINE; } } } // TODO: support other methods int ret = 0; for (int i = 0; i < 12; ++i) { int y = 2 + DATABASE_DY[i], x = 2 + DATABASE_DX[i]; if (segments[y][x] == 3) return -1; ret |= segments[y][x] << (2 * i); } return ret; } } <commit_msg>Support 'line to 3'<commit_after>#include "SlitherlinkDatabase.h" #include "SlitherlinkDatabaseMethod.hpp" #include "../common/SolverConstant.h" namespace Penciloid { int *SlitherlinkDatabase::database = nullptr; const int SlitherlinkDatabase::DATABASE_DX[] = { -2, -2, -1, -1, -1, 0, 0, 1, 1, 1, 2, 2 }; const int SlitherlinkDatabase::DATABASE_DY[] = { -1, 1, -2, 0, 2, -1, 1, -2, 0, 2, -1, 1 }; void SlitherlinkDatabase::CreateDatabase() { const int pow3[] = { 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441 }; ReleaseDatabase(); database = new int[pow3[12] * 4]; int styles[12]; for (int hint = 0; hint <= 3; ++hint) { for (int id = pow3[12] - 1; id >= 0; --id) { int tmp = id; int undecided_pos = -1; for (int i = 0; i < 12; ++i) { styles[i] = tmp % 3; tmp /= 3; if (styles[i] == 0) undecided_pos = i; } if (undecided_pos == -1) { bool consistency = true; if (8 - (styles[3] + styles[5] + styles[6] + styles[8]) != hint) { consistency = false; } tmp = 8 - (styles[0] + styles[2] + styles[3] + styles[5]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[1] + styles[3] + styles[4] + styles[6]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[5] + styles[7] + styles[8] + styles[10]); if (tmp != 0 && tmp != 2) consistency = false; tmp = 8 - (styles[6] + styles[8] + styles[9] + styles[11]); if (tmp != 0 && tmp != 2) consistency = false; if (consistency) { int tmp = 0; for (int i = 0; i < 12; ++i) tmp |= styles[i] << (2 * i); database[hint * pow3[12] + id] = tmp; } else { database[hint * pow3[12] + id] = -1; } } else { int base1 = database[hint * pow3[12] + id + pow3[undecided_pos]]; int base2 = database[hint * pow3[12] + id + pow3[undecided_pos] * 2]; database[hint * pow3[12] + id] = base1 & base2; } } } } void SlitherlinkDatabase::CreateReducedDatabase(SlitherlinkDatabaseMethod &method) { const int pow3[] = { 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147, 531441 }; ReleaseDatabase(); database = new int[pow3[12] * 4]; int styles[12]; for (int hint = 0; hint <= 3; ++hint) { for (int id = pow3[12] - 1; id >= 0; --id) { int tmp = id; for (int i = 0; i < 12; ++i) { styles[i] = tmp % 3; tmp /= 3; } database[hint * pow3[12] + id] = SolveLocal(hint, styles, method); } } } void SlitherlinkDatabase::ReleaseDatabase() { if (database) { delete[] database; database = nullptr; } } int SlitherlinkDatabase::SolveLocal(int clue, int styles[12], SlitherlinkDatabaseMethod &method) { const int UNDECIDED = 0, LINE = 1, BLANK = 2; int segments[5][5]; for (int i = 0; i < 12; ++i) segments[2 + DATABASE_DY[i]][2 + DATABASE_DX[i]] = styles[i]; if (method.adjacent_lines) { int n_lines = (segments[2][1] == LINE ? 1 : 0) + (segments[2][3] == LINE ? 1 : 0) + (segments[1][2] == LINE ? 1 : 0) + (segments[3][2] == LINE ? 1 : 0); int n_blanks = (segments[2][1] == BLANK ? 1 : 0) + (segments[2][3] == BLANK ? 1 : 0) + (segments[1][2] == BLANK ? 1 : 0) + (segments[3][2] == BLANK ? 1 : 0); if (n_lines > clue || 4 - n_blanks < clue) return -1; if (n_lines == clue) { if (segments[2][1] == UNDECIDED) segments[2][1] = BLANK; if (segments[2][3] == UNDECIDED) segments[2][3] = BLANK; if (segments[1][2] == UNDECIDED) segments[1][2] = BLANK; if (segments[3][2] == UNDECIDED) segments[3][2] = BLANK; } if (4 - n_blanks == clue) { if (segments[2][1] == UNDECIDED) segments[2][1] = LINE; if (segments[2][3] == UNDECIDED) segments[2][3] = LINE; if (segments[1][2] == UNDECIDED) segments[1][2] = LINE; if (segments[3][2] == UNDECIDED) segments[3][2] = LINE; } } for (int dir = 0; dir < 4; ++dir) { int dy1 = GridConstant::GRID_DY[dir], dx1 = GridConstant::GRID_DX[dir]; int dy2 = GridConstant::GRID_DY[(dir + 1) % 4], dx2 = GridConstant::GRID_DX[(dir + 1) % 4]; if (segments[2 + dy1 * 2 + dy2][2 + dx1 * 2 + dx2] == BLANK && segments[2 + dy1 + dy2 * 2][2 + dx1 + dx2 * 2] == BLANK) { // this cell is corner if (clue == 1 && method.corner_1) { segments[2 + dy1][2 + dx1] = segments[2 + dy2][2 + dx2] = BLANK; } if (clue == 2 && method.corner_2) { int out_y1, out_x1, out_y2, out_x2; out_y1 = 2 + dy1 * 2 - dy2, out_x1 = 2 + dx1 * 2 - dx2; out_y2 = 2 + dy1 - dy2 * 2, out_x2 = 2 + dx1 - dx2 * 2; if (segments[out_y1][out_x1] == LINE) segments[out_y2][out_x2] |= BLANK; if (segments[out_y1][out_x1] == BLANK) segments[out_y2][out_x2] |= LINE; if (segments[out_y2][out_x2] == LINE) segments[out_y1][out_x1] |= BLANK; if (segments[out_y2][out_x2] == BLANK) segments[out_y1][out_x1] |= LINE; out_y1 = 2 - dy1 * 2 + dy2, out_x1 = 2 - dx1 * 2 + dx2; out_y2 = 2 - dy1 + dy2 * 2, out_x2 = 2 - dx1 + dx2 * 2; if (segments[out_y1][out_x1] == LINE) segments[out_y2][out_x2] |= BLANK; if (segments[out_y1][out_x1] == BLANK) segments[out_y2][out_x2] |= LINE; if (segments[out_y2][out_x2] == LINE) segments[out_y1][out_x1] |= BLANK; if (segments[out_y2][out_x2] == BLANK) segments[out_y1][out_x1] |= LINE; } if (clue == 3 && method.corner_3) { segments[2 + dy1][2 + dx1] = segments[2 + dy2][2 + dx2] = LINE; } } int in_y1, in_x1, in_y2, in_x2; in_y1 = 2 + dy1 * 2 + dy2, in_x1 = 2 + dx1 * 2 + dx2; in_y2 = 2 + dy1 + dy2 * 2, in_x2 = 2 + dx1 + dx2 * 2; if (clue == 3 && method.line_to_3) { if (segments[in_y1][in_x1] == LINE || segments[in_y2][in_x2] == LINE) { segments[2 - dy1][2 - dx1] |= LINE; segments[2 - dy2][2 - dx2] |= LINE; if (segments[in_y1][in_x1] == LINE) segments[in_y2][in_x2] |= BLANK; if (segments[in_y2][in_x2] == LINE) segments[in_y1][in_x1] |= BLANK; } } } // TODO: support other methods int ret = 0; for (int i = 0; i < 12; ++i) { int y = 2 + DATABASE_DY[i], x = 2 + DATABASE_DX[i]; if (segments[y][x] == 3) return -1; ret |= segments[y][x] << (2 * i); } return ret; } } <|endoftext|>
<commit_before>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Implementation for Path test */ #include <nta/os/Path.hpp> #include <nta/os/OS.hpp> #include <nta/os/FStream.hpp> #include <nta/utils/Log.hpp> #include "PathTest.hpp" using namespace std; using namespace nta; void PathTest::RunTests() { std::string sep(Path::sep); // test static exists() { } // test static getParent() { #ifdef WIN32 // no tests defined #else std::string g = "/a/b/c/g.ext"; g = Path::getParent(g); TESTEQUAL2_STR("getParent1", "/a/b/c", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent2", "/a/b", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent3", "/a", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent4", "/", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent5", "/", g); // Parent should normalize first, to avoid parent(a/b/..)->(a/b) g = "/a/b/.."; TESTEQUAL2_STR("getParent6", "/", Path::getParent(g)); // getParent() of a relative directory may be a bit non-intuitive g = "a/b"; TESTEQUAL2_STR("getParent7", "a", Path::getParent(g)); g = "a"; TESTEQUAL2_STR("getParent8", ".", Path::getParent(g)); // getParent() of a relative directory above us should work g = "../../a"; TESTEQUAL2_STR("getParent9", "../..", Path::getParent(g)); g = "."; TESTEQUAL2_STR("getParent10", "..", Path::getParent(g)); #endif std::string x = Path::join("someDir", "X"); x = Path::makeAbsolute(x); std::string y = Path::join(x, "Y"); std::string parent = Path::getParent(y); TEST(x == parent); } // test static getFilename() { } // test static getBasename() { #ifdef WIN32 // no tests defined #else TESTEQUAL2_STR("basename1", "bar", Path::getBasename("/foo/bar")); TESTEQUAL2_STR("basename2", "", Path::getBasename("/foo/bar/")); TESTEQUAL2_STR("basename3", "bar.ext", Path::getBasename("/this is a long dir / foo$/bar.ext")); #endif } // test static getExtension() { std::string ext = Path::getExtension("abc" + sep + "def.ext"); TEST(ext == "ext"); } // test static normalize() { #ifdef WIN32 // no tests defined #else TESTEQUAL2_STR("normalize1", "/foo/bar", Path::normalize("//foo/quux/..//bar")); TESTEQUAL2_STR("normalize2", "/foo/contains a lot of spaces", Path::normalize("///foo/a/b/c/../../d/../../contains a lot of spaces/g.tgz/..")); TESTEQUAL2_STR("normalize3", "../..", Path::normalize("../foo/../..")); TESTEQUAL2_STR("normalize4", "/", Path::normalize("/../..")); #endif } // test static makeAbsolute() { } // test static split() { #ifdef WIN32 // no tests defined #else Path::StringVec sv; sv = Path::split("/foo/bar"); TESTEQUAL2("split1 size", 3U, sv.size()); if (sv.size() == 3) { TESTEQUAL2("split1.1", sv[0], "/"); TESTEQUAL2("split1.2", sv[1], "foo"); TESTEQUAL2("split1.3", sv[2], "bar"); } TESTEQUAL2_STR("split1.4", "/foo/bar", Path::join(sv.begin(), sv.end())); sv = Path::split("foo/bar"); TESTEQUAL2("split2 size", 2U, sv.size()); if (sv.size() == 2) { TESTEQUAL2("split2.2", sv[0], "foo"); TESTEQUAL2("split2.3", sv[1], "bar"); } TESTEQUAL2_STR("split2.3", "foo/bar", Path::join(sv.begin(), sv.end())); sv = Path::split("foo//bar/"); TESTEQUAL2("split3 size", 2U, sv.size()); if (sv.size() == 2) { TESTEQUAL2("split3.2", sv[0], "foo"); TESTEQUAL2("split3.3", sv[1], "bar"); } TESTEQUAL2_STR("split3.4", "foo/bar", Path::join(sv.begin(), sv.end())); #endif } // test static join() { } // test static remove() { } // test static rename() { } // test static copy() { { OFStream f("a.txt"); f << "12345"; } { std::string s; IFStream f("a.txt"); f >> s; TEST(s == "12345"); } { if (Path::exists("b.txt")) Path::remove("b.txt"); TEST(!Path::exists("b.txt")); Path::copy("a.txt", "b.txt"); TEST(Path::exists("b.txt")); std::string s; IFStream f("b.txt"); f >> s; TEST(s == "12345"); } Path::remove("a.txt"); Path::remove("b.txt"); TEST(!Path::exists("a.txt")); TEST(!Path::exists("b.txt")); } // test static copy() in temp directory { { OFStream f("a.txt"); f << "12345"; } { std::string s; IFStream f("a.txt"); f >> s; TEST(s == "12345"); } string destination = fromTestOutputDir("pathtest_dir"); { destination += "b.txt"; if (Path::exists(destination)) Path::remove(destination); TEST(!Path::exists(destination)); Path::copy("a.txt", destination); TEST(Path::exists(destination)); std::string s; IFStream f(destination.c_str()); f >> s; TEST(s == "12345"); } Path::remove("a.txt"); Path::remove(destination); TEST(!Path::exists("a.txt")); TEST(!Path::exists(destination)); } //test static isRootdir() { } //test static isAbsolute() { #ifdef WIN32 TEST(Path::isAbsolute("c:")); TEST(Path::isAbsolute("c:\\")); TEST(Path::isAbsolute("c:\\foo\\")); TEST(Path::isAbsolute("c:\\foo\\bar")); TEST(Path::isAbsolute("\\\\foo")); TEST(Path::isAbsolute("\\\\foo\\")); TEST(Path::isAbsolute("\\\\foo\\bar")); TEST(Path::isAbsolute("\\\\foo\\bar\\baz")); TEST(!Path::isAbsolute("foo")); TEST(!Path::isAbsolute("foo\\bar")); TEST(!Path::isAbsolute("\\")); TEST(!Path::isAbsolute("\\\\")); TEST(!Path::isAbsolute("\\foo")); #else TEST(Path::isAbsolute("/")); TEST(Path::isAbsolute("/foo")); TEST(Path::isAbsolute("/foo/")); TEST(Path::isAbsolute("/foo/bar")); TEST(!Path::isAbsolute("foo")); TEST(!Path::isAbsolute("foo/bar")); #endif } { // test static getExecutablePath std::string path = Path::getExecutablePath(); std::cout << "Executable path: '" << path << "'\n"; TEST(Path::exists(path)); std::string basename = Path::getBasename(path); #ifdef NTA_PLATFORM_win32 TESTEQUAL2("basename should be testeverything", basename, "testeverything.exe"); #else TESTEQUAL2("basename should be testeverything", basename, "testeverything"); #endif } } <commit_msg>Now basename is googletests<commit_after>/* --------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement * with Numenta, Inc., for a separate license for this software code, the * following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 3 as * published by the Free Software Foundation. * * 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. * * http://numenta.org/licenses/ * --------------------------------------------------------------------- */ /** @file * Implementation for Path test */ #include <nta/os/Path.hpp> #include <nta/os/OS.hpp> #include <nta/os/FStream.hpp> #include <nta/utils/Log.hpp> #include "PathTest.hpp" using namespace std; using namespace nta; void PathTest::RunTests() { std::string sep(Path::sep); // test static exists() { } // test static getParent() { #ifdef WIN32 // no tests defined #else std::string g = "/a/b/c/g.ext"; g = Path::getParent(g); TESTEQUAL2_STR("getParent1", "/a/b/c", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent2", "/a/b", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent3", "/a", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent4", "/", g); g = Path::getParent(g); TESTEQUAL2_STR("getParent5", "/", g); // Parent should normalize first, to avoid parent(a/b/..)->(a/b) g = "/a/b/.."; TESTEQUAL2_STR("getParent6", "/", Path::getParent(g)); // getParent() of a relative directory may be a bit non-intuitive g = "a/b"; TESTEQUAL2_STR("getParent7", "a", Path::getParent(g)); g = "a"; TESTEQUAL2_STR("getParent8", ".", Path::getParent(g)); // getParent() of a relative directory above us should work g = "../../a"; TESTEQUAL2_STR("getParent9", "../..", Path::getParent(g)); g = "."; TESTEQUAL2_STR("getParent10", "..", Path::getParent(g)); #endif std::string x = Path::join("someDir", "X"); x = Path::makeAbsolute(x); std::string y = Path::join(x, "Y"); std::string parent = Path::getParent(y); TEST(x == parent); } // test static getFilename() { } // test static getBasename() { #ifdef WIN32 // no tests defined #else TESTEQUAL2_STR("basename1", "bar", Path::getBasename("/foo/bar")); TESTEQUAL2_STR("basename2", "", Path::getBasename("/foo/bar/")); TESTEQUAL2_STR("basename3", "bar.ext", Path::getBasename("/this is a long dir / foo$/bar.ext")); #endif } // test static getExtension() { std::string ext = Path::getExtension("abc" + sep + "def.ext"); TEST(ext == "ext"); } // test static normalize() { #ifdef WIN32 // no tests defined #else TESTEQUAL2_STR("normalize1", "/foo/bar", Path::normalize("//foo/quux/..//bar")); TESTEQUAL2_STR("normalize2", "/foo/contains a lot of spaces", Path::normalize("///foo/a/b/c/../../d/../../contains a lot of spaces/g.tgz/..")); TESTEQUAL2_STR("normalize3", "../..", Path::normalize("../foo/../..")); TESTEQUAL2_STR("normalize4", "/", Path::normalize("/../..")); #endif } // test static makeAbsolute() { } // test static split() { #ifdef WIN32 // no tests defined #else Path::StringVec sv; sv = Path::split("/foo/bar"); TESTEQUAL2("split1 size", 3U, sv.size()); if (sv.size() == 3) { TESTEQUAL2("split1.1", sv[0], "/"); TESTEQUAL2("split1.2", sv[1], "foo"); TESTEQUAL2("split1.3", sv[2], "bar"); } TESTEQUAL2_STR("split1.4", "/foo/bar", Path::join(sv.begin(), sv.end())); sv = Path::split("foo/bar"); TESTEQUAL2("split2 size", 2U, sv.size()); if (sv.size() == 2) { TESTEQUAL2("split2.2", sv[0], "foo"); TESTEQUAL2("split2.3", sv[1], "bar"); } TESTEQUAL2_STR("split2.3", "foo/bar", Path::join(sv.begin(), sv.end())); sv = Path::split("foo//bar/"); TESTEQUAL2("split3 size", 2U, sv.size()); if (sv.size() == 2) { TESTEQUAL2("split3.2", sv[0], "foo"); TESTEQUAL2("split3.3", sv[1], "bar"); } TESTEQUAL2_STR("split3.4", "foo/bar", Path::join(sv.begin(), sv.end())); #endif } // test static join() { } // test static remove() { } // test static rename() { } // test static copy() { { OFStream f("a.txt"); f << "12345"; } { std::string s; IFStream f("a.txt"); f >> s; TEST(s == "12345"); } { if (Path::exists("b.txt")) Path::remove("b.txt"); TEST(!Path::exists("b.txt")); Path::copy("a.txt", "b.txt"); TEST(Path::exists("b.txt")); std::string s; IFStream f("b.txt"); f >> s; TEST(s == "12345"); } Path::remove("a.txt"); Path::remove("b.txt"); TEST(!Path::exists("a.txt")); TEST(!Path::exists("b.txt")); } // test static copy() in temp directory { { OFStream f("a.txt"); f << "12345"; } { std::string s; IFStream f("a.txt"); f >> s; TEST(s == "12345"); } string destination = fromTestOutputDir("pathtest_dir"); { destination += "b.txt"; if (Path::exists(destination)) Path::remove(destination); TEST(!Path::exists(destination)); Path::copy("a.txt", destination); TEST(Path::exists(destination)); std::string s; IFStream f(destination.c_str()); f >> s; TEST(s == "12345"); } Path::remove("a.txt"); Path::remove(destination); TEST(!Path::exists("a.txt")); TEST(!Path::exists(destination)); } //test static isRootdir() { } //test static isAbsolute() { #ifdef WIN32 TEST(Path::isAbsolute("c:")); TEST(Path::isAbsolute("c:\\")); TEST(Path::isAbsolute("c:\\foo\\")); TEST(Path::isAbsolute("c:\\foo\\bar")); TEST(Path::isAbsolute("\\\\foo")); TEST(Path::isAbsolute("\\\\foo\\")); TEST(Path::isAbsolute("\\\\foo\\bar")); TEST(Path::isAbsolute("\\\\foo\\bar\\baz")); TEST(!Path::isAbsolute("foo")); TEST(!Path::isAbsolute("foo\\bar")); TEST(!Path::isAbsolute("\\")); TEST(!Path::isAbsolute("\\\\")); TEST(!Path::isAbsolute("\\foo")); #else TEST(Path::isAbsolute("/")); TEST(Path::isAbsolute("/foo")); TEST(Path::isAbsolute("/foo/")); TEST(Path::isAbsolute("/foo/bar")); TEST(!Path::isAbsolute("foo")); TEST(!Path::isAbsolute("foo/bar")); #endif } { // test static getExecutablePath std::string path = Path::getExecutablePath(); std::cout << "Executable path: '" << path << "'\n"; TEST(Path::exists(path)); std::string basename = Path::getBasename(path); #ifdef NTA_PLATFORM_win32 TESTEQUAL2("basename should be googletests", basename, "googletests.exe"); #else TESTEQUAL2("basename should be googletests", basename, "googletests"); #endif } } <|endoftext|>
<commit_before>/****************************************************************************** * include files *****************************************************************************/ #include <stdio.h> #include <assert.h> #include <string> extern "C" { #include "xed-interface.h" }; #include "code-ranges.h" #include "function-entries.h" #include "process-ranges.h" /****************************************************************************** * macros *****************************************************************************/ #define is_aligned(addr) ((((unsigned long) (addr)) & 0x3) == 0) #define is_call_iclass(x) \ ((x == XED_ICLASS_CALL_FAR) || (x == XED_ICLASS_CALL_NEAR)) /****************************************************************************** * forward declarations *****************************************************************************/ static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr, void *start, void *end); static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr); static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr); static bool invalid_routine_start(unsigned char *ins); /****************************************************************************** * local variables *****************************************************************************/ static xed_state_t xed_machine_state_x86_64 = { XED_MACHINE_MODE_LONG_64, XED_ADDRESS_WIDTH_64b, XED_ADDRESS_WIDTH_64b }; /****************************************************************************** * interface operations *****************************************************************************/ void process_range_init() { xed_tables_init(); } void process_range(long offset, void *vstart, void *vend, bool fn_discovery) { xed_decoded_inst_t xedd; xed_decoded_inst_t *xptr = &xedd; xed_error_enum_t xed_error; int error_count = 0; char *ins = (char *) vstart; char *end = (char *) vend; xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64); xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID; while (ins < end) { xed_decoded_inst_zero_keep_mode(xptr); xed_error = xed_decode(xptr, (uint8_t*) ins, 15); if (xed_error != XED_ERROR_NONE) { error_count++; /* note the error */ ins++; /* skip this byte */ continue; /* continue onward ... */ } xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr); switch(xiclass) { case XED_ICLASS_CALL_FAR: case XED_ICLASS_CALL_NEAR: /* if (fn_discovery) */ process_call(ins, offset, xptr, vstart, vend); break; case XED_ICLASS_JMP: case XED_ICLASS_JMP_FAR: if (fn_discovery && !is_call_iclass(prev_xiclass)) { // regarding use of !is_call above: don't infer function start // if we run into code from C++ that consists of a call followed // by an unconditional jump after_unconditional(ins, offset, xptr); } break; case XED_ICLASS_RET_FAR: case XED_ICLASS_RET_NEAR: if (fn_discovery) after_unconditional(ins, offset, xptr); break; case XED_ICLASS_JB: case XED_ICLASS_JBE: case XED_ICLASS_JL: case XED_ICLASS_JLE: case XED_ICLASS_JNB: case XED_ICLASS_JNBE: case XED_ICLASS_JNL: case XED_ICLASS_JNLE: case XED_ICLASS_JNO: case XED_ICLASS_JNP: case XED_ICLASS_JNS: case XED_ICLASS_JNZ: case XED_ICLASS_JO: case XED_ICLASS_JP: case XED_ICLASS_JRCXZ: case XED_ICLASS_JS: case XED_ICLASS_JZ: if (fn_discovery) process_branch(ins, offset , xptr); break; default: break; } prev_xiclass = xiclass; ins += xed_decoded_inst_get_length(xptr); } } /****************************************************************************** * private operations *****************************************************************************/ static int is_padding(int c) { return (c == 0x66) || (c == 0x90); } static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr) { ins += xed_decoded_inst_get_length(xptr); unsigned char *uins = (unsigned char *) ins; unsigned char *potential_function_addr = uins + offset; for (; is_padding(*uins); uins++); // skip remaining padding // only infer a function entry before padding bytes if there isn't already one after padding bytes if (contains_function_entry(uins + offset) == false) { if (is_aligned(uins + offset) && !invalid_routine_start(uins)) { add_stripped_function_entry(potential_function_addr); // potential function entry point } } } static void * get_branch_target(char *ins, xed_decoded_inst_t *xptr, xed_operand_values_t *vals) { int bytes = xed_operand_values_get_branch_displacement_length(vals); int offset = 0; switch(bytes) { case 1: offset = (signed char) xed_operand_values_get_branch_displacement_byte(vals,0); break; case 4: offset = xed_operand_values_get_branch_displacement_int32(vals); break; default: assert(0); } char *end_of_call_inst = ins + xed_decoded_inst_get_length(xptr); char *target = end_of_call_inst + offset; return target; } static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr, void *start, void *end) { const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op0 = xed_inst_operand(xi, 0); xed_operand_enum_t op0_name = xed_operand_name(op0); xed_operand_type_enum_t op0_type = xed_operand_type(op0); if (op0_name == XED_OPERAND_RELBR && op0_type == XED_OPERAND_TYPE_IMM_CONST) { xed_operand_values_t *vals = xed_decoded_inst_operands(xptr); if (xed_operand_values_has_branch_displacement(vals)) { void *vaddr = get_branch_target(ins + offset,xptr,vals); if (consider_possible_fn_address(vaddr)) add_stripped_function_entry(vaddr); } } } static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr) { char *relocated_ins = ins + offset; const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op0 = xed_inst_operand(xi, 0); xed_operand_enum_t op0_name = xed_operand_name(op0); xed_operand_type_enum_t op0_type = xed_operand_type(op0); if (op0_name == XED_OPERAND_RELBR && op0_type == XED_OPERAND_TYPE_IMM_CONST) { xed_operand_values_t *vals = xed_decoded_inst_operands(xptr); if (xed_operand_values_has_branch_displacement(vals)) { char *target = (char *) get_branch_target(relocated_ins, xptr, vals); void *start, *end; if (target < relocated_ins) { unsigned char *tloc = (unsigned char *) target - offset; for (; is_padding(*(tloc-1)); tloc--) { // extend branch range to before padding target--; } start = target; end = relocated_ins; } else { start = relocated_ins; end = ((char *) target) + 1; // add one to ensure that the branch target is part of the "covered" range } add_branch_range(start, end); } } } static int mem_below_rsp_or_rbp(xed_decoded_inst_t *xptr, int oindex) { xed_reg_enum_t basereg = xed_decoded_inst_get_base_reg(xptr, oindex); if (basereg == XED_REG_RSP || basereg == XED_REG_RBP) { int64_t offset = xed_decoded_inst_get_memory_displacement(xptr, oindex); #if 0 if (offset > 0) { #endif return 1; #if 0 } #endif } else if (basereg == XED_REG_RAX) { return 1; } return 0; } static bool inst_accesses_callers_mem(xed_decoded_inst_t *xptr) { // if the instruction accesses memory below the rsp or rbp, this is // not a valid first instruction for a routine. if this is the first // instruction in a routine, this must be manipulating values in the // caller's frame, not its own. int noperands = xed_decoded_inst_number_of_memory_operands(xptr); int not_my_mem = 0; switch (noperands) { case 2: not_my_mem |= mem_below_rsp_or_rbp(xptr, 1); case 1: not_my_mem |= mem_below_rsp_or_rbp(xptr, 0); case 0: break; default: assert(0 && "unexpected number of memory operands"); } if (not_my_mem) return true; return false; } static bool from_rax_eax(xed_decoded_inst_t *xptr) { int noperands = xed_decoded_inst_noperands(xptr); if (noperands == 2) { const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op1 = xed_inst_operand(xi, 1); xed_operand_enum_t op1_name = xed_operand_name(op1); #if 0 if ((xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOV) || (xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOVSXD)) { #endif if ((op1_name == XED_OPERAND_REG1) && ((xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_RAX) || (xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_EAX))) { return true; } #if 0 } #endif } return false; } // prefetches are commonly outlined from loops. don't infer them as function starts // after unconditional control flow static bool is_prefetch(xed_decoded_inst_t *xptr) { switch(xed_decoded_inst_get_iclass(xptr)) { case XED_ICLASS_PREFETCHNTA: case XED_ICLASS_PREFETCHT0: case XED_ICLASS_PREFETCHT1: case XED_ICLASS_PREFETCHT2: case XED_ICLASS_PREFETCH_EXCLUSIVE: case XED_ICLASS_PREFETCH_MODIFIED: case XED_ICLASS_PREFETCH_RESERVED: return true; default: return false; } } static bool invalid_routine_start(unsigned char *ins) { xed_decoded_inst_t xdi; xed_decoded_inst_zero_set_mode(&xdi, &xed_machine_state_x86_64); xed_error_enum_t xed_error = xed_decode(&xdi, (uint8_t*) ins, 15); if (xed_error == XED_ERROR_NONE) { if (inst_accesses_callers_mem(&xdi)) return true; if (from_rax_eax(&xdi)) return true; if (is_prefetch(&xdi)) return true; } return false; } void x86_dump_ins(void *ins) { xed_decoded_inst_t xedd; xed_decoded_inst_t *xptr = &xedd; xed_error_enum_t xed_error; char inst_buf[1024]; xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64); xed_error = xed_decode(xptr, (uint8_t*) ins, 15); xed_format_xed(xptr, inst_buf, sizeof(inst_buf), (uint64_t) ins); printf("(%p, %d bytes, %s) %s \n" , ins, xed_decoded_inst_get_length(xptr), xed_iclass_enum_t2str(xed_decoded_inst_get_iclass(xptr)), inst_buf); } <commit_msg>when processing jump instructions, don't infer the start of a new function after instructions that look like jmp *r11 A register-indirect jump is the idiom for switch tables. Inferring that the instruction following such a jump was potentially the start of a new function caused us to infer spurious function starts in many places. This problem was particularly manifest in the PGI-compiled code for the go benchmark where it caused spurious functions to be inferred in the middle of some of the key routines for game tree exploration. A consequence of the spurious functions for the PGI-compiled go benchmark was that the binary analyzer in hpcrun didn't have the proper function bounds. This resulted in incorrect unwind recipes. Bad unwind recipes resulted in about 25% dropped samples for the SPEC go benchmark using the train input size. This change reduces the sample drops for the train size of the go benchmark to a single digit.<commit_after>/****************************************************************************** * include files *****************************************************************************/ #include <stdio.h> #include <assert.h> #include <string> extern "C" { #include "xed-interface.h" }; #include "code-ranges.h" #include "function-entries.h" #include "process-ranges.h" /****************************************************************************** * macros *****************************************************************************/ #define is_aligned(addr) ((((unsigned long) (addr)) & 0x3) == 0) #define is_call_iclass(x) \ ((x == XED_ICLASS_CALL_FAR) || (x == XED_ICLASS_CALL_NEAR)) /****************************************************************************** * forward declarations *****************************************************************************/ static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr, void *start, void *end); static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr); static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr); static bool invalid_routine_start(unsigned char *ins); /****************************************************************************** * local variables *****************************************************************************/ static xed_state_t xed_machine_state_x86_64 = { XED_MACHINE_MODE_LONG_64, XED_ADDRESS_WIDTH_64b, XED_ADDRESS_WIDTH_64b }; /****************************************************************************** * interface operations *****************************************************************************/ void process_range_init() { xed_tables_init(); } void process_range(long offset, void *vstart, void *vend, bool fn_discovery) { xed_decoded_inst_t xedd; xed_decoded_inst_t *xptr = &xedd; xed_error_enum_t xed_error; int error_count = 0; char *ins = (char *) vstart; char *end = (char *) vend; xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64); xed_iclass_enum_t prev_xiclass = XED_ICLASS_INVALID; while (ins < end) { xed_decoded_inst_zero_keep_mode(xptr); xed_error = xed_decode(xptr, (uint8_t*) ins, 15); if (xed_error != XED_ERROR_NONE) { error_count++; /* note the error */ ins++; /* skip this byte */ continue; /* continue onward ... */ } xed_iclass_enum_t xiclass = xed_decoded_inst_get_iclass(xptr); switch(xiclass) { case XED_ICLASS_CALL_FAR: case XED_ICLASS_CALL_NEAR: /* if (fn_discovery) */ process_call(ins, offset, xptr, vstart, vend); break; case XED_ICLASS_JMP: case XED_ICLASS_JMP_FAR: if (xed_decoded_inst_noperands(xptr) == 2) { const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op0 = xed_inst_operand(xi, 0); const xed_operand_t *op1 = xed_inst_operand(xi, 1); xed_operand_type_enum_t op0_type = xed_operand_type(op0); xed_operand_type_enum_t op1_type = xed_operand_type(op1); if ((op0_type == XED_OPERAND_TYPE_NT_LOOKUP_FN) && (op1_type == XED_OPERAND_TYPE_NT_LOOKUP_FN)) { // idiom for a switch using a jump table: // don't consider the instruction afterward a potential function start break; } } if (fn_discovery && !is_call_iclass(prev_xiclass)) { // regarding use of !is_call above: don't infer function start // if we run into code from C++ that consists of a call followed // by an unconditional jump after_unconditional(ins, offset, xptr); } break; case XED_ICLASS_RET_FAR: case XED_ICLASS_RET_NEAR: if (fn_discovery) after_unconditional(ins, offset, xptr); break; case XED_ICLASS_JB: case XED_ICLASS_JBE: case XED_ICLASS_JL: case XED_ICLASS_JLE: case XED_ICLASS_JNB: case XED_ICLASS_JNBE: case XED_ICLASS_JNL: case XED_ICLASS_JNLE: case XED_ICLASS_JNO: case XED_ICLASS_JNP: case XED_ICLASS_JNS: case XED_ICLASS_JNZ: case XED_ICLASS_JO: case XED_ICLASS_JP: case XED_ICLASS_JRCXZ: case XED_ICLASS_JS: case XED_ICLASS_JZ: if (fn_discovery) process_branch(ins, offset , xptr); break; default: break; } prev_xiclass = xiclass; ins += xed_decoded_inst_get_length(xptr); } } /****************************************************************************** * private operations *****************************************************************************/ static int is_padding(int c) { return (c == 0x66) || (c == 0x90); } static void after_unconditional(char *ins, long offset, xed_decoded_inst_t *xptr) { ins += xed_decoded_inst_get_length(xptr); unsigned char *uins = (unsigned char *) ins; unsigned char *potential_function_addr = uins + offset; for (; is_padding(*uins); uins++); // skip remaining padding // only infer a function entry before padding bytes if there isn't already one after padding bytes if (contains_function_entry(uins + offset) == false) { if (is_aligned(uins + offset) && !invalid_routine_start(uins)) { add_stripped_function_entry(potential_function_addr); // potential function entry point } } } static void * get_branch_target(char *ins, xed_decoded_inst_t *xptr, xed_operand_values_t *vals) { int bytes = xed_operand_values_get_branch_displacement_length(vals); int offset = 0; switch(bytes) { case 1: offset = (signed char) xed_operand_values_get_branch_displacement_byte(vals,0); break; case 4: offset = xed_operand_values_get_branch_displacement_int32(vals); break; default: assert(0); } char *end_of_call_inst = ins + xed_decoded_inst_get_length(xptr); char *target = end_of_call_inst + offset; return target; } static void process_call(char *ins, long offset, xed_decoded_inst_t *xptr, void *start, void *end) { const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op0 = xed_inst_operand(xi, 0); xed_operand_enum_t op0_name = xed_operand_name(op0); xed_operand_type_enum_t op0_type = xed_operand_type(op0); if (op0_name == XED_OPERAND_RELBR && op0_type == XED_OPERAND_TYPE_IMM_CONST) { xed_operand_values_t *vals = xed_decoded_inst_operands(xptr); if (xed_operand_values_has_branch_displacement(vals)) { void *vaddr = get_branch_target(ins + offset,xptr,vals); if (consider_possible_fn_address(vaddr)) add_stripped_function_entry(vaddr); } } } static void process_branch(char *ins, long offset, xed_decoded_inst_t *xptr) { char *relocated_ins = ins + offset; const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op0 = xed_inst_operand(xi, 0); xed_operand_enum_t op0_name = xed_operand_name(op0); xed_operand_type_enum_t op0_type = xed_operand_type(op0); if (op0_name == XED_OPERAND_RELBR && op0_type == XED_OPERAND_TYPE_IMM_CONST) { xed_operand_values_t *vals = xed_decoded_inst_operands(xptr); if (xed_operand_values_has_branch_displacement(vals)) { char *target = (char *) get_branch_target(relocated_ins, xptr, vals); void *start, *end; if (target < relocated_ins) { unsigned char *tloc = (unsigned char *) target - offset; for (; is_padding(*(tloc-1)); tloc--) { // extend branch range to before padding target--; } start = target; end = relocated_ins; } else { start = relocated_ins; end = ((char *) target) + 1; // add one to ensure that the branch target is part of the "covered" range } add_branch_range(start, end); } } } static int mem_below_rsp_or_rbp(xed_decoded_inst_t *xptr, int oindex) { xed_reg_enum_t basereg = xed_decoded_inst_get_base_reg(xptr, oindex); if (basereg == XED_REG_RSP || basereg == XED_REG_RBP) { int64_t offset = xed_decoded_inst_get_memory_displacement(xptr, oindex); #if 0 if (offset > 0) { #endif return 1; #if 0 } #endif } else if (basereg == XED_REG_RAX) { return 1; } return 0; } static bool inst_accesses_callers_mem(xed_decoded_inst_t *xptr) { // if the instruction accesses memory below the rsp or rbp, this is // not a valid first instruction for a routine. if this is the first // instruction in a routine, this must be manipulating values in the // caller's frame, not its own. int noperands = xed_decoded_inst_number_of_memory_operands(xptr); int not_my_mem = 0; switch (noperands) { case 2: not_my_mem |= mem_below_rsp_or_rbp(xptr, 1); case 1: not_my_mem |= mem_below_rsp_or_rbp(xptr, 0); case 0: break; default: assert(0 && "unexpected number of memory operands"); } if (not_my_mem) return true; return false; } static bool from_rax_eax(xed_decoded_inst_t *xptr) { int noperands = xed_decoded_inst_noperands(xptr); if (noperands == 2) { const xed_inst_t *xi = xed_decoded_inst_inst(xptr); const xed_operand_t *op1 = xed_inst_operand(xi, 1); xed_operand_enum_t op1_name = xed_operand_name(op1); #if 0 if ((xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOV) || (xed_decoded_inst_get_iclass(xptr) == XED_ICLASS_MOVSXD)) { #endif if ((op1_name == XED_OPERAND_REG1) && ((xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_RAX) || (xed_decoded_inst_get_reg(xptr, op1_name) == XED_REG_EAX))) { return true; } #if 0 } #endif } return false; } // prefetches are commonly outlined from loops. don't infer them as function starts // after unconditional control flow static bool is_prefetch(xed_decoded_inst_t *xptr) { switch(xed_decoded_inst_get_iclass(xptr)) { case XED_ICLASS_PREFETCHNTA: case XED_ICLASS_PREFETCHT0: case XED_ICLASS_PREFETCHT1: case XED_ICLASS_PREFETCHT2: case XED_ICLASS_PREFETCH_EXCLUSIVE: case XED_ICLASS_PREFETCH_MODIFIED: case XED_ICLASS_PREFETCH_RESERVED: return true; default: return false; } } static bool invalid_routine_start(unsigned char *ins) { xed_decoded_inst_t xdi; xed_decoded_inst_zero_set_mode(&xdi, &xed_machine_state_x86_64); xed_error_enum_t xed_error = xed_decode(&xdi, (uint8_t*) ins, 15); if (xed_error == XED_ERROR_NONE) { if (inst_accesses_callers_mem(&xdi)) return true; if (from_rax_eax(&xdi)) return true; if (is_prefetch(&xdi)) return true; } return false; } void x86_dump_ins(void *ins) { xed_decoded_inst_t xedd; xed_decoded_inst_t *xptr = &xedd; xed_error_enum_t xed_error; char inst_buf[1024]; xed_decoded_inst_zero_set_mode(xptr, &xed_machine_state_x86_64); xed_error = xed_decode(xptr, (uint8_t*) ins, 15); xed_format_xed(xptr, inst_buf, sizeof(inst_buf), (uint64_t) ins); printf("(%p, %d bytes, %s) %s \n" , ins, xed_decoded_inst_get_length(xptr), xed_iclass_enum_t2str(xed_decoded_inst_get_iclass(xptr)), inst_buf); } <|endoftext|>
<commit_before>#include "../../testing/testing.hpp" #include "../storage.hpp" using namespace storage; UNIT_TEST(StorageTest_Smoke) { Storage st; TIndex const i1 = st.FindIndexByFile("USA_Georgia"); TEST(i1.IsValid(), ()); TIndex const i2 = st.FindIndexByFile("Georgia"); TEST(i2.IsValid(), ()); TEST_NOT_EQUAL(i1, i2, ()); } <commit_msg>[core] country file name tests added<commit_after>#include "../../testing/testing.hpp" #include "../storage.hpp" using namespace storage; UNIT_TEST(StorageTest_Smoke) { Storage st; TIndex const i1 = st.FindIndexByFile("USA_Georgia"); TEST(i1.IsValid(), ()); TEST_EQUAL(st.CountryFileName(i1), "USA_Georgia", ()); TIndex const i2 = st.FindIndexByFile("Georgia"); TEST(i2.IsValid(), ()); TEST_EQUAL(st.CountryFileName(i2), "Georgia", ()); TEST_NOT_EQUAL(i1, i2, ()); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swframeposstrings.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 04:41:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _SVXSWFRAMEPOSSTRINGS_HXX #include <swframeposstrings.hxx> #endif #ifndef _TOOLS_RC_HXX #include <tools/rc.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SVX_DIALMGR_HXX #include <dialmgr.hxx> #endif #include <dialogs.hrc> class SvxSwFramePosString_Impl : public Resource { friend class SvxSwFramePosString; String aStrings[SvxSwFramePosString::STR_MAX]; public: SvxSwFramePosString_Impl(); }; SvxSwFramePosString_Impl::SvxSwFramePosString_Impl() : Resource(SVX_RES(RID_SVXSW_FRAMEPOSITIONS)) { for(USHORT i = 0; i < SvxSwFramePosString::STR_MAX; i++) { //string ids have to start at 1 aStrings[i] = String(ResId(i + 1)); } FreeResource(); } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ SvxSwFramePosString::SvxSwFramePosString() : pImpl(new SvxSwFramePosString_Impl) { } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ SvxSwFramePosString::~SvxSwFramePosString() { delete pImpl; } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ const String& SvxSwFramePosString::GetString(StringId eId) { DBG_ASSERT(eId >= 0 && eId < STR_MAX, "invalid StringId") if(!(eId >= 0 && eId < STR_MAX)) eId = LEFT; return pImpl->aStrings[eId]; } <commit_msg>INTEGRATION: CWS residcleanup (1.5.262); FILE MERGED 2007/02/21 22:04:12 pl 1.5.262.1: #i74635# get rid of global ResMgr<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: swframeposstrings.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2007-04-26 07:43:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * 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. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef _SVXSWFRAMEPOSSTRINGS_HXX #include <swframeposstrings.hxx> #endif #ifndef _TOOLS_RC_HXX #include <tools/rc.hxx> #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef _SVX_DIALMGR_HXX #include <dialmgr.hxx> #endif #include <dialogs.hrc> class SvxSwFramePosString_Impl : public Resource { friend class SvxSwFramePosString; String aStrings[SvxSwFramePosString::STR_MAX]; public: SvxSwFramePosString_Impl(); }; SvxSwFramePosString_Impl::SvxSwFramePosString_Impl() : Resource(SVX_RES(RID_SVXSW_FRAMEPOSITIONS)) { for(USHORT i = 0; i < SvxSwFramePosString::STR_MAX; i++) { //string ids have to start at 1 aStrings[i] = String(SVX_RES(i + 1)); } FreeResource(); } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ SvxSwFramePosString::SvxSwFramePosString() : pImpl(new SvxSwFramePosString_Impl) { } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ SvxSwFramePosString::~SvxSwFramePosString() { delete pImpl; } /*-- 04.03.2004 13:14:48--------------------------------------------------- -----------------------------------------------------------------------*/ const String& SvxSwFramePosString::GetString(StringId eId) { DBG_ASSERT(eId >= 0 && eId < STR_MAX, "invalid StringId") if(!(eId >= 0 && eId < STR_MAX)) eId = LEFT; return pImpl->aStrings[eId]; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: Medical3.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // // This example reads a volume dataset, extracts two isosurfaces that // represent the skin and bone, creates three orthogonal planes // (sagittal, axial, coronal), and displays them. // #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkVolume16Reader.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkOutlineFilter.h> #include <vtkCamera.h> #include <vtkStripper.h> #include <vtkLookupTable.h> #include <vtkImageDataGeometryFilter.h> #include <vtkProperty.h> #include <vtkPolyDataNormals.h> #include <vtkContourFilter.h> #include <vtkImageData.h> #include <vtkImageMapToColors.h> #include <vtkImageActor.h> #include <vtkSmartPointer.h> int main (int argc, char *argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " DATADIR/headsq/quarter" << endl; return 1; } // Create the renderer, the render window, and the interactor. The // renderer draws into the render window, the interactor enables // mouse- and keyboard-based interaction with the data within the // render window. // vtkSmartPointer<vtkRenderer> aRenderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer(aRenderer); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); // The following reader is used to read a series of 2D slices (images) // that compose the volume. The slice dimensions are set, and the // pixel spacing. The data Endianness must also be specified. The // reader usese the FilePrefix in combination with the slice number to // construct filenames using the format FilePrefix.%d. (In this case // the FilePrefix is the root name of the file: quarter.) vtkSmartPointer<vtkVolume16Reader> v16 = vtkSmartPointer<vtkVolume16Reader>::New(); v16->SetDataDimensions(64,64); v16->SetDataByteOrderToLittleEndian(); v16->SetFilePrefix (argv[1]); v16->SetImageRange(1, 93); v16->SetDataSpacing (3.2, 3.2, 1.5); // An isosurface, or contour value of 500 is known to correspond to // the skin of the patient. Once generated, a vtkPolyDataNormals // filter is is used to create normals for smooth surface shading // during rendering. The triangle stripper is used to create triangle // strips from the isosurface; these render much faster on may // systems. vtkSmartPointer<vtkContourFilter> skinExtractor = vtkSmartPointer<vtkContourFilter>::New(); skinExtractor->SetInputConnection( v16->GetOutputPort()); skinExtractor->SetValue(0, 500); vtkSmartPointer<vtkPolyDataNormals> skinNormals = vtkSmartPointer<vtkPolyDataNormals>::New(); skinNormals->SetInputConnection(skinExtractor->GetOutputPort()); skinNormals->SetFeatureAngle(60.0); vtkSmartPointer<vtkStripper> skinStripper = vtkSmartPointer<vtkStripper>::New(); skinStripper->SetInputConnection(skinNormals->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> skinMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); skinMapper->SetInputConnection(skinStripper->GetOutputPort()); skinMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> skin = vtkSmartPointer<vtkActor>::New(); skin->SetMapper(skinMapper); skin->GetProperty()->SetDiffuseColor(1, .49, .25); skin->GetProperty()->SetSpecular(.3); skin->GetProperty()->SetSpecularPower(20); // An isosurface, or contour value of 1150 is known to correspond to // the skin of the patient. Once generated, a vtkPolyDataNormals // filter is is used to create normals for smooth surface shading // during rendering. The triangle stripper is used to create triangle // strips from the isosurface; these render much faster on may // systems. vtkSmartPointer<vtkContourFilter> boneExtractor = vtkSmartPointer<vtkContourFilter>::New(); boneExtractor->SetInputConnection(v16->GetOutputPort()); boneExtractor->SetValue(0, 1150); vtkSmartPointer<vtkPolyDataNormals> boneNormals = vtkSmartPointer<vtkPolyDataNormals>::New(); boneNormals->SetInputConnection(boneExtractor->GetOutputPort()); boneNormals->SetFeatureAngle(60.0); vtkSmartPointer<vtkStripper> boneStripper = vtkSmartPointer<vtkStripper>::New(); boneStripper->SetInputConnection(boneNormals->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> boneMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); boneMapper->SetInputConnection(boneStripper->GetOutputPort()); boneMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> bone = vtkSmartPointer<vtkActor>::New(); bone->SetMapper(boneMapper); bone->GetProperty()->SetDiffuseColor(1, 1, .9412); // An outline provides context around the data. // vtkSmartPointer<vtkOutlineFilter> outlineData = vtkSmartPointer<vtkOutlineFilter>::New(); outlineData->SetInputConnection(v16->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> mapOutline = vtkSmartPointer<vtkPolyDataMapper>::New(); mapOutline->SetInputConnection(outlineData->GetOutputPort()); vtkSmartPointer<vtkActor> outline = vtkSmartPointer<vtkActor>::New(); outline->SetMapper(mapOutline); outline->GetProperty()->SetColor(0,0,0); // Now we are creating three orthogonal planes passing through the // volume. Each plane uses a different texture map and therefore has // different coloration. // Start by creatin a black/white lookup table. vtkSmartPointer<vtkLookupTable> bwLut = vtkSmartPointer<vtkLookupTable>::New(); bwLut->SetTableRange (0, 2000); bwLut->SetSaturationRange (0, 0); bwLut->SetHueRange (0, 0); bwLut->SetValueRange (0, 1); bwLut->Build(); //effective built // Now create a lookup table that consists of the full hue circle // (from HSV). vtkSmartPointer<vtkLookupTable> hueLut = vtkSmartPointer<vtkLookupTable>::New(); hueLut->SetTableRange (0, 2000); hueLut->SetHueRange (0, 1); hueLut->SetSaturationRange (1, 1); hueLut->SetValueRange (1, 1); hueLut->Build(); //effective built // Finally, create a lookup table with a single hue but having a range // in the saturation of the hue. vtkSmartPointer<vtkLookupTable> satLut = vtkSmartPointer<vtkLookupTable>::New(); satLut->SetTableRange (0, 2000); satLut->SetHueRange (.6, .6); satLut->SetSaturationRange (0, 1); satLut->SetValueRange (1, 1); satLut->Build(); //effective built // Create the first of the three planes. The filter vtkImageMapToColors // maps the data through the corresponding lookup table created above. The // vtkImageActor is a type of vtkProp and conveniently displays an image on // a single quadrilateral plane. It does this using texture mapping and as // a result is quite fast. (Note: the input image has to be unsigned char // values, which the vtkImageMapToColors produces.) Note also that by // specifying the DisplayExtent, the pipeline requests data of this extent // and the vtkImageMapToColors only processes a slice of data. vtkSmartPointer<vtkImageMapToColors> sagittalColors = vtkSmartPointer<vtkImageMapToColors>::New(); sagittalColors->SetInputConnection(v16->GetOutputPort()); sagittalColors->SetLookupTable(bwLut); vtkSmartPointer<vtkImageActor> sagittal = vtkSmartPointer<vtkImageActor>::New(); sagittal->SetInput(sagittalColors->GetOutput()); sagittal->SetDisplayExtent(32,32, 0,63, 0,92); // Create the second (axial) plane of the three planes. We use the // same approach as before except that the extent differs. vtkSmartPointer<vtkImageMapToColors> axialColors = vtkSmartPointer<vtkImageMapToColors>::New(); axialColors->SetInputConnection(v16->GetOutputPort()); axialColors->SetLookupTable(hueLut); vtkSmartPointer<vtkImageActor> axial = vtkSmartPointer<vtkImageActor>::New(); axial->SetInput(axialColors->GetOutput()); axial->SetDisplayExtent(0,63, 0,63, 46,46); // Create the third (coronal) plane of the three planes. We use // the same approach as before except that the extent differs. vtkSmartPointer<vtkImageMapToColors> coronalColors = vtkSmartPointer<vtkImageMapToColors>::New(); coronalColors->SetInputConnection(v16->GetOutputPort()); coronalColors->SetLookupTable(satLut); vtkSmartPointer<vtkImageActor> coronal = vtkSmartPointer<vtkImageActor>::New(); coronal->SetInput(coronalColors->GetOutput()); coronal->SetDisplayExtent(0,63, 32,32, 0,92); // It is convenient to create an initial view of the data. The // FocalPoint and Position form a vector direction. Later on // (ResetCamera() method) this vector is used to position the camera // to look at the data in this direction. vtkSmartPointer<vtkCamera> aCamera = vtkSmartPointer<vtkCamera>::New(); aCamera->SetViewUp (0, 0, -1); aCamera->SetPosition (0, 1, 0); aCamera->SetFocalPoint (0, 0, 0); aCamera->ComputeViewPlaneNormal(); aCamera->Azimuth(30.0); aCamera->Elevation(30.0); // Actors are added to the renderer. aRenderer->AddActor(outline); aRenderer->AddActor(sagittal); aRenderer->AddActor(axial); aRenderer->AddActor(coronal); aRenderer->AddActor(axial); aRenderer->AddActor(coronal); aRenderer->AddActor(skin); aRenderer->AddActor(bone); // Turn off bone for this example. bone->VisibilityOff(); // Set skin to semi-transparent. skin->GetProperty()->SetOpacity(0.5); // An initial camera view is created. The Dolly() method moves // the camera towards the FocalPoint, thereby enlarging the image. aRenderer->SetActiveCamera(aCamera); aRenderer->Render(); aRenderer->ResetCamera (); aCamera->Dolly(1.5); // Set a background color for the renderer and set the size of the // render window (expressed in pixels). aRenderer->SetBackground(.2, .3, .4); renWin->SetSize(640, 480); // Note that when camera movement occurs (as it does in the Dolly() // method), the clipping planes often need adjusting. Clipping planes // consist of two planes: near and far along the view direction. The // near plane clips out objects in front of the plane; the far plane // clips out objects behind the plane. This way only what is drawn // between the planes is actually rendered. aRenderer->ResetCameraClippingRange (); // interact with data iren->Initialize(); iren->Start(); return 0; } <commit_msg>BUG: axial and coronal actors were added twice. See if this fixes crashes on Mac's.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: Medical3.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // // This example reads a volume dataset, extracts two isosurfaces that // represent the skin and bone, creates three orthogonal planes // (sagittal, axial, coronal), and displays them. // #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkVolume16Reader.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkOutlineFilter.h> #include <vtkCamera.h> #include <vtkStripper.h> #include <vtkLookupTable.h> #include <vtkImageDataGeometryFilter.h> #include <vtkProperty.h> #include <vtkPolyDataNormals.h> #include <vtkContourFilter.h> #include <vtkImageData.h> #include <vtkImageMapToColors.h> #include <vtkImageActor.h> #include <vtkSmartPointer.h> int main (int argc, char *argv[]) { if (argc < 2) { cout << "Usage: " << argv[0] << " DATADIR/headsq/quarter" << endl; return EXIT_FAILURE; } // Create the renderer, the render window, and the interactor. The // renderer draws into the render window, the interactor enables // mouse- and keyboard-based interaction with the data within the // render window. // vtkSmartPointer<vtkRenderer> aRenderer = vtkSmartPointer<vtkRenderer>::New(); vtkSmartPointer<vtkRenderWindow> renWin = vtkSmartPointer<vtkRenderWindow>::New(); renWin->AddRenderer(aRenderer); vtkSmartPointer<vtkRenderWindowInteractor> iren = vtkSmartPointer<vtkRenderWindowInteractor>::New(); iren->SetRenderWindow(renWin); // The following reader is used to read a series of 2D slices (images) // that compose the volume. The slice dimensions are set, and the // pixel spacing. The data Endianness must also be specified. The // reader uses the FilePrefix in combination with the slice number to // construct filenames using the format FilePrefix.%d. (In this case // the FilePrefix is the root name of the file: quarter.) vtkSmartPointer<vtkVolume16Reader> v16 = vtkSmartPointer<vtkVolume16Reader>::New(); v16->SetDataDimensions(64,64); v16->SetDataByteOrderToLittleEndian(); v16->SetFilePrefix (argv[1]); v16->SetImageRange(1, 93); v16->SetDataSpacing (3.2, 3.2, 1.5); // An isosurface, or contour value of 500 is known to correspond to // the skin of the patient. Once generated, a vtkPolyDataNormals // filter is is used to create normals for smooth surface shading // during rendering. The triangle stripper is used to create triangle // strips from the isosurface; these render much faster on may // systems. vtkSmartPointer<vtkContourFilter> skinExtractor = vtkSmartPointer<vtkContourFilter>::New(); skinExtractor->SetInputConnection( v16->GetOutputPort()); skinExtractor->SetValue(0, 500); vtkSmartPointer<vtkPolyDataNormals> skinNormals = vtkSmartPointer<vtkPolyDataNormals>::New(); skinNormals->SetInputConnection(skinExtractor->GetOutputPort()); skinNormals->SetFeatureAngle(60.0); vtkSmartPointer<vtkStripper> skinStripper = vtkSmartPointer<vtkStripper>::New(); skinStripper->SetInputConnection(skinNormals->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> skinMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); skinMapper->SetInputConnection(skinStripper->GetOutputPort()); skinMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> skin = vtkSmartPointer<vtkActor>::New(); skin->SetMapper(skinMapper); skin->GetProperty()->SetDiffuseColor(1, .49, .25); skin->GetProperty()->SetSpecular(.3); skin->GetProperty()->SetSpecularPower(20); // An isosurface, or contour value of 1150 is known to correspond to // the skin of the patient. Once generated, a vtkPolyDataNormals // filter is is used to create normals for smooth surface shading // during rendering. The triangle stripper is used to create triangle // strips from the isosurface; these render much faster on may // systems. vtkSmartPointer<vtkContourFilter> boneExtractor = vtkSmartPointer<vtkContourFilter>::New(); boneExtractor->SetInputConnection(v16->GetOutputPort()); boneExtractor->SetValue(0, 1150); vtkSmartPointer<vtkPolyDataNormals> boneNormals = vtkSmartPointer<vtkPolyDataNormals>::New(); boneNormals->SetInputConnection(boneExtractor->GetOutputPort()); boneNormals->SetFeatureAngle(60.0); vtkSmartPointer<vtkStripper> boneStripper = vtkSmartPointer<vtkStripper>::New(); boneStripper->SetInputConnection(boneNormals->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> boneMapper = vtkSmartPointer<vtkPolyDataMapper>::New(); boneMapper->SetInputConnection(boneStripper->GetOutputPort()); boneMapper->ScalarVisibilityOff(); vtkSmartPointer<vtkActor> bone = vtkSmartPointer<vtkActor>::New(); bone->SetMapper(boneMapper); bone->GetProperty()->SetDiffuseColor(1, 1, .9412); // An outline provides context around the data. // vtkSmartPointer<vtkOutlineFilter> outlineData = vtkSmartPointer<vtkOutlineFilter>::New(); outlineData->SetInputConnection(v16->GetOutputPort()); vtkSmartPointer<vtkPolyDataMapper> mapOutline = vtkSmartPointer<vtkPolyDataMapper>::New(); mapOutline->SetInputConnection(outlineData->GetOutputPort()); vtkSmartPointer<vtkActor> outline = vtkSmartPointer<vtkActor>::New(); outline->SetMapper(mapOutline); outline->GetProperty()->SetColor(0,0,0); // Now we are creating three orthogonal planes passing through the // volume. Each plane uses a different texture map and therefore has // different coloration. // Start by creatin a black/white lookup table. vtkSmartPointer<vtkLookupTable> bwLut = vtkSmartPointer<vtkLookupTable>::New(); bwLut->SetTableRange (0, 2000); bwLut->SetSaturationRange (0, 0); bwLut->SetHueRange (0, 0); bwLut->SetValueRange (0, 1); bwLut->Build(); //effective built // Now create a lookup table that consists of the full hue circle // (from HSV). vtkSmartPointer<vtkLookupTable> hueLut = vtkSmartPointer<vtkLookupTable>::New(); hueLut->SetTableRange (0, 2000); hueLut->SetHueRange (0, 1); hueLut->SetSaturationRange (1, 1); hueLut->SetValueRange (1, 1); hueLut->Build(); //effective built // Finally, create a lookup table with a single hue but having a range // in the saturation of the hue. vtkSmartPointer<vtkLookupTable> satLut = vtkSmartPointer<vtkLookupTable>::New(); satLut->SetTableRange (0, 2000); satLut->SetHueRange (.6, .6); satLut->SetSaturationRange (0, 1); satLut->SetValueRange (1, 1); satLut->Build(); //effective built // Create the first of the three planes. The filter vtkImageMapToColors // maps the data through the corresponding lookup table created above. The // vtkImageActor is a type of vtkProp and conveniently displays an image on // a single quadrilateral plane. It does this using texture mapping and as // a result is quite fast. (Note: the input image has to be unsigned char // values, which the vtkImageMapToColors produces.) Note also that by // specifying the DisplayExtent, the pipeline requests data of this extent // and the vtkImageMapToColors only processes a slice of data. vtkSmartPointer<vtkImageMapToColors> sagittalColors = vtkSmartPointer<vtkImageMapToColors>::New(); sagittalColors->SetInputConnection(v16->GetOutputPort()); sagittalColors->SetLookupTable(bwLut); vtkSmartPointer<vtkImageActor> sagittal = vtkSmartPointer<vtkImageActor>::New(); sagittal->SetInput(sagittalColors->GetOutput()); sagittal->SetDisplayExtent(32,32, 0,63, 0,92); // Create the second (axial) plane of the three planes. We use the // same approach as before except that the extent differs. vtkSmartPointer<vtkImageMapToColors> axialColors = vtkSmartPointer<vtkImageMapToColors>::New(); axialColors->SetInputConnection(v16->GetOutputPort()); axialColors->SetLookupTable(hueLut); vtkSmartPointer<vtkImageActor> axial = vtkSmartPointer<vtkImageActor>::New(); axial->SetInput(axialColors->GetOutput()); axial->SetDisplayExtent(0,63, 0,63, 46,46); // Create the third (coronal) plane of the three planes. We use // the same approach as before except that the extent differs. vtkSmartPointer<vtkImageMapToColors> coronalColors = vtkSmartPointer<vtkImageMapToColors>::New(); coronalColors->SetInputConnection(v16->GetOutputPort()); coronalColors->SetLookupTable(satLut); vtkSmartPointer<vtkImageActor> coronal = vtkSmartPointer<vtkImageActor>::New(); coronal->SetInput(coronalColors->GetOutput()); coronal->SetDisplayExtent(0,63, 32,32, 0,92); // It is convenient to create an initial view of the data. The // FocalPoint and Position form a vector direction. Later on // (ResetCamera() method) this vector is used to position the camera // to look at the data in this direction. vtkSmartPointer<vtkCamera> aCamera = vtkSmartPointer<vtkCamera>::New(); aCamera->SetViewUp (0, 0, -1); aCamera->SetPosition (0, 1, 0); aCamera->SetFocalPoint (0, 0, 0); aCamera->ComputeViewPlaneNormal(); aCamera->Azimuth(30.0); aCamera->Elevation(30.0); // Actors are added to the renderer. aRenderer->AddActor(outline); aRenderer->AddActor(sagittal); aRenderer->AddActor(axial); aRenderer->AddActor(coronal); aRenderer->AddActor(skin); aRenderer->AddActor(bone); // Turn off bone for this example. bone->VisibilityOff(); // Set skin to semi-transparent. skin->GetProperty()->SetOpacity(0.5); // An initial camera view is created. The Dolly() method moves // the camera towards the FocalPoint, thereby enlarging the image. aRenderer->SetActiveCamera(aCamera); aRenderer->Render(); aRenderer->ResetCamera (); aCamera->Dolly(1.5); // Set a background color for the renderer and set the size of the // render window (expressed in pixels). aRenderer->SetBackground(.2, .3, .4); renWin->SetSize(640, 480); // Note that when camera movement occurs (as it does in the Dolly() // method), the clipping planes often need adjusting. Clipping planes // consist of two planes: near and far along the view direction. The // near plane clips out objects in front of the plane; the far plane // clips out objects behind the plane. This way only what is drawn // between the planes is actually rendered. aRenderer->ResetCameraClippingRange (); // interact with data iren->Initialize(); iren->Start(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/component_updater_service.h" #include <algorithm> #include <string> #include <vector> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "net/url_request/url_request_context_getter.h" namespace { // Default time constants. const int kDelayOneMinute = 60; const int kDelayOneHour = kDelayOneMinute * 60; // Debug values you can pass to --component-updater-debug=value1,value2. // Speed up component checking. const char kDebugFastUpdate[] = "fast-update"; // Force out-of-process-xml parsing. const char kDebugOutOfProcess[] = "out-of-process"; // Add "testrequest=1" parameter to the update check query. const char kDebugRequestParam[] = "test-request"; bool HasDebugValue(const std::vector<std::string>& vec, const char* test) { if (vec.empty()) return 0; return (std::find(vec.begin(), vec.end(), test) != vec.end()); } // The request extra information is the OS and architecture, this helps // the server select the right package to be delivered. const char kExtraInfo[] = #if defined(OS_MACOSX) #if defined(__amd64__) "os=mac&arch=x64&prod=chrome&prodversion="; #elif defined(__i386__) "os=mac&arch=x86&prod=chrome&prodversion="; #else #error "unknown mac architecture" #endif #elif defined(OS_WIN) #if defined(_WIN64) "os=win&arch=x64&prod=chrome&prodversion="; #elif defined(_WIN32) "os=win&arch=x86&prod=chrome&prodversion="; #else #error "unknown windows architecture" #endif #elif defined(OS_CHROMEOS) #if defined(__i386__) "os=cros&arch=x86&prod=chrome&prodversion="; #elif defined(__arm__) "os=cros&arch=arm&prod=chrome&prodversion="; #else "os=cros&arch=unknown&prod=chrome&prodversion="; #endif #elif defined(OS_LINUX) #if defined(__amd64__) "os=linux&arch=x64&prod=chrome&prodversion="; #elif defined(__i386__) "os=linux&arch=x86&prod=chrome&prodversion="; #elif defined(__arm__) "os=linux&arch=arm&prod=chrome&prodversion="; #else "os=linux&arch=unknown&prod=chrome&prodversion="; #endif #elif defined(OS_OPENBSD) #if defined(__amd64__) "os=openbsd&arch=x64"; #elif defined(__i386__) "os=openbsd&arch=x86"; #else "os=openbsd&arch=unknown"; #endif #else #error "unknown os or architecture" #endif } // namespace class ChromeConfigurator : public ComponentUpdateService::Configurator { public: ChromeConfigurator(const CommandLine* cmdline, net::URLRequestContextGetter* url_request_getter); virtual ~ChromeConfigurator() {} virtual int InitialDelay() OVERRIDE; virtual int NextCheckDelay() OVERRIDE; virtual int StepDelay() OVERRIDE; virtual int MinimumReCheckWait() OVERRIDE; virtual GURL UpdateUrl() OVERRIDE; virtual const char* ExtraRequestParams() OVERRIDE; virtual size_t UrlSizeLimit() OVERRIDE; virtual net::URLRequestContextGetter* RequestContext() OVERRIDE; virtual bool InProcess() OVERRIDE; virtual void OnEvent(Events event, int val) OVERRIDE; private: net::URLRequestContextGetter* url_request_getter_; std::string extra_info_; bool fast_update_; bool out_of_process_; GURL app_update_url_; }; ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline, net::URLRequestContextGetter* url_request_getter) : url_request_getter_(url_request_getter), extra_info_(kExtraInfo) { // Parse comma-delimited debug flags. std::vector<std::string> debug_values; Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug), ",", &debug_values); fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate); out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess); // Allow switch to override update URL (piggyback on AppsGalleryUpdateURL). if (cmdline->HasSwitch(switches::kAppsGalleryUpdateURL)) { app_update_url_ = GURL(cmdline->GetSwitchValueASCII(switches::kAppsGalleryUpdateURL)); } else { app_update_url_ = GURL("http://clients2.google.com/service/update2/crx"); } // Make the extra request params, they are necessary so omaha does // not deliver components that are going to be rejected at install time. extra_info_ += chrome::VersionInfo().Version(); if (HasDebugValue(debug_values, kDebugRequestParam)) extra_info_ += "&testrequest=1"; } int ChromeConfigurator::InitialDelay() { return fast_update_ ? 1 : (6 * kDelayOneMinute); } int ChromeConfigurator::NextCheckDelay() { return fast_update_ ? 3 : (4 * kDelayOneHour); } int ChromeConfigurator::StepDelay() { return fast_update_ ? 1 : 4; } int ChromeConfigurator::MinimumReCheckWait() { return fast_update_ ? 30 : (6 * kDelayOneHour); } GURL ChromeConfigurator::UpdateUrl() { return app_update_url_; } const char* ChromeConfigurator::ExtraRequestParams() { return extra_info_.c_str(); } size_t ChromeConfigurator::UrlSizeLimit() { return 1024ul; } net::URLRequestContextGetter* ChromeConfigurator::RequestContext() { return url_request_getter_; } bool ChromeConfigurator::InProcess() { return !out_of_process_; } void ChromeConfigurator::OnEvent(Events event, int val) { switch (event) { case kManifestCheck: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100); break; case kComponentUpdated: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100); break; case kManifestError: UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val); break; case kNetworkError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100); break; case kUnpackError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100); break; case kInstallerError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100); break; default: NOTREACHED(); break; } } ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator( const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) { return new ChromeConfigurator(cmdline, context_getter); } <commit_msg>Add android component updater configuration.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/component_updater_service.h" #include <algorithm> #include <string> #include <vector> #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/metrics/histogram.h" #include "base/string_util.h" #include "build/build_config.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/chrome_version_info.h" #include "net/url_request/url_request_context_getter.h" namespace { // Default time constants. const int kDelayOneMinute = 60; const int kDelayOneHour = kDelayOneMinute * 60; // Debug values you can pass to --component-updater-debug=value1,value2. // Speed up component checking. const char kDebugFastUpdate[] = "fast-update"; // Force out-of-process-xml parsing. const char kDebugOutOfProcess[] = "out-of-process"; // Add "testrequest=1" parameter to the update check query. const char kDebugRequestParam[] = "test-request"; bool HasDebugValue(const std::vector<std::string>& vec, const char* test) { if (vec.empty()) return 0; return (std::find(vec.begin(), vec.end(), test) != vec.end()); } // The request extra information is the OS and architecture, this helps // the server select the right package to be delivered. const char kExtraInfo[] = #if defined(OS_MACOSX) #if defined(__amd64__) "os=mac&arch=x64&prod=chrome&prodversion="; #elif defined(__i386__) "os=mac&arch=x86&prod=chrome&prodversion="; #else #error "unknown mac architecture" #endif #elif defined(OS_WIN) #if defined(_WIN64) "os=win&arch=x64&prod=chrome&prodversion="; #elif defined(_WIN32) "os=win&arch=x86&prod=chrome&prodversion="; #else #error "unknown windows architecture" #endif #elif defined(OS_ANDROID) #if defined(__i386__) "os=android&arch=x86&prod=chrome&prodversion="; #elif defined(__arm__) "os=android&arch=arm&prod=chrome&prodversion="; #else "os=android&arch=unknown&prod=chrome&prodversion="; #endif #elif defined(OS_CHROMEOS) #if defined(__i386__) "os=cros&arch=x86&prod=chrome&prodversion="; #elif defined(__arm__) "os=cros&arch=arm&prod=chrome&prodversion="; #else "os=cros&arch=unknown&prod=chrome&prodversion="; #endif #elif defined(OS_LINUX) #if defined(__amd64__) "os=linux&arch=x64&prod=chrome&prodversion="; #elif defined(__i386__) "os=linux&arch=x86&prod=chrome&prodversion="; #elif defined(__arm__) "os=linux&arch=arm&prod=chrome&prodversion="; #else "os=linux&arch=unknown&prod=chrome&prodversion="; #endif #elif defined(OS_OPENBSD) #if defined(__amd64__) "os=openbsd&arch=x64"; #elif defined(__i386__) "os=openbsd&arch=x86"; #else "os=openbsd&arch=unknown"; #endif #else #error "unknown os or architecture" #endif } // namespace class ChromeConfigurator : public ComponentUpdateService::Configurator { public: ChromeConfigurator(const CommandLine* cmdline, net::URLRequestContextGetter* url_request_getter); virtual ~ChromeConfigurator() {} virtual int InitialDelay() OVERRIDE; virtual int NextCheckDelay() OVERRIDE; virtual int StepDelay() OVERRIDE; virtual int MinimumReCheckWait() OVERRIDE; virtual GURL UpdateUrl() OVERRIDE; virtual const char* ExtraRequestParams() OVERRIDE; virtual size_t UrlSizeLimit() OVERRIDE; virtual net::URLRequestContextGetter* RequestContext() OVERRIDE; virtual bool InProcess() OVERRIDE; virtual void OnEvent(Events event, int val) OVERRIDE; private: net::URLRequestContextGetter* url_request_getter_; std::string extra_info_; bool fast_update_; bool out_of_process_; GURL app_update_url_; }; ChromeConfigurator::ChromeConfigurator(const CommandLine* cmdline, net::URLRequestContextGetter* url_request_getter) : url_request_getter_(url_request_getter), extra_info_(kExtraInfo) { // Parse comma-delimited debug flags. std::vector<std::string> debug_values; Tokenize(cmdline->GetSwitchValueASCII(switches::kComponentUpdaterDebug), ",", &debug_values); fast_update_ = HasDebugValue(debug_values, kDebugFastUpdate); out_of_process_ = HasDebugValue(debug_values, kDebugOutOfProcess); // Allow switch to override update URL (piggyback on AppsGalleryUpdateURL). if (cmdline->HasSwitch(switches::kAppsGalleryUpdateURL)) { app_update_url_ = GURL(cmdline->GetSwitchValueASCII(switches::kAppsGalleryUpdateURL)); } else { app_update_url_ = GURL("http://clients2.google.com/service/update2/crx"); } // Make the extra request params, they are necessary so omaha does // not deliver components that are going to be rejected at install time. extra_info_ += chrome::VersionInfo().Version(); if (HasDebugValue(debug_values, kDebugRequestParam)) extra_info_ += "&testrequest=1"; } int ChromeConfigurator::InitialDelay() { return fast_update_ ? 1 : (6 * kDelayOneMinute); } int ChromeConfigurator::NextCheckDelay() { return fast_update_ ? 3 : (4 * kDelayOneHour); } int ChromeConfigurator::StepDelay() { return fast_update_ ? 1 : 4; } int ChromeConfigurator::MinimumReCheckWait() { return fast_update_ ? 30 : (6 * kDelayOneHour); } GURL ChromeConfigurator::UpdateUrl() { return app_update_url_; } const char* ChromeConfigurator::ExtraRequestParams() { return extra_info_.c_str(); } size_t ChromeConfigurator::UrlSizeLimit() { return 1024ul; } net::URLRequestContextGetter* ChromeConfigurator::RequestContext() { return url_request_getter_; } bool ChromeConfigurator::InProcess() { return !out_of_process_; } void ChromeConfigurator::OnEvent(Events event, int val) { switch (event) { case kManifestCheck: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ManifestCheck", val, 100); break; case kComponentUpdated: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.ComponentUpdated", val, 100); break; case kManifestError: UMA_HISTOGRAM_COUNTS_100("ComponentUpdater.ManifestError", val); break; case kNetworkError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.NetworkError", val, 100); break; case kUnpackError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.UnpackError", val, 100); break; case kInstallerError: UMA_HISTOGRAM_ENUMERATION("ComponentUpdater.InstallError", val, 100); break; default: NOTREACHED(); break; } } ComponentUpdateService::Configurator* MakeChromeComponentUpdaterConfigurator( const CommandLine* cmdline, net::URLRequestContextGetter* context_getter) { return new ChromeConfigurator(cmdline, context_getter); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QApplication> #include <QDesktopServices> #include <QFile> #include <QDir> #include <QString> #include <QProcess> #include "de_web_plugin.h" #include "de_web_plugin_private.h" #define FW_IDLE_TIMEOUT (10 * 1000) #define FW_WAIT_UPDATE_READY (2) //s #define FW_IDLE_TIMEOUT_LONG (240 * 1000) #define FW_WAIT_USER_TIMEOUT (120 * 1000) /*! Inits the firmware update manager. */ void DeRestPluginPrivate::initFirmwareUpdate() { fwProcess = 0; fwUpdateState = FW_Idle; Q_ASSERT(apsCtrl); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle); fwUpdateStartedByUser = false; fwUpdateTimer = new QTimer(this); fwUpdateTimer->setSingleShot(true); connect(fwUpdateTimer, SIGNAL(timeout()), this, SLOT(firmwareUpdateTimerFired())); fwUpdateTimer->start(5000); } /*! Starts the actual firmware update process. */ void DeRestPluginPrivate::updateFirmware() { if (gwFirmwareNeedUpdate) { gwFirmwareNeedUpdate = false; } Q_ASSERT(apsCtrl); if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle || apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) { DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n"); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); updateEtag(gwConfigEtag); return; } QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher"; #ifdef Q_OS_WIN gcfFlasherBin.append(".exe"); QString bin = gcfFlasherBin; #elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there QString bin = "pkexec"; gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; fwProcessArgs.prepend(gcfFlasherBin); #elif defined(Q_OS_OSX) // TODO // /usr/bin/osascript -e 'do shell script "make install" with administrator privileges' QString bin = "sudo"; fwProcessArgs.prepend(gcfFlasherBin); #else QString bin = "sudo"; gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; fwProcessArgs.prepend(gcfFlasherBin); #endif if (!fwProcess) { fwProcess = new QProcess(this); } fwProcessArgs << "-f" << fwUpdateFile; fwUpdateState = FW_UpdateWaitFinished; updateEtag(gwConfigEtag); fwUpdateTimer->start(250); fwProcess->start(bin, fwProcessArgs); } /*! Observes the firmware update process. */ void DeRestPluginPrivate::updateFirmwareWaitFinished() { if (fwProcess) { if (fwProcess->bytesAvailable()) { QByteArray data = fwProcess->readAllStandardOutput(); DBG_Printf(DBG_INFO, "%s", qPrintable(data)); if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning) { if (data.contains("flashing")) { apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning); } } } if (fwProcess->state() == QProcess::Starting) { DBG_Printf(DBG_INFO, "GW firmware update starting ..\n"); } else if (fwProcess->state() == QProcess::Running) { DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n"); } else if (fwProcess->state() == QProcess::NotRunning) { if (fwProcess->exitStatus() == QProcess::NormalExit) { DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode()); } else if (fwProcess->exitStatus() == QProcess::CrashExit) { DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString())); } fwProcess->deleteLater(); fwProcess = 0; } } // done if (fwProcess == 0) { fwUpdateStartedByUser = false; gwFirmwareNeedUpdate = false; updateEtag(gwConfigEtag); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); } else // recheck { fwUpdateTimer->start(250); } } /*! Starts the device disconnect so that the serial port is released. */ void DeRestPluginPrivate::updateFirmwareDisconnectDevice() { Q_ASSERT(apsCtrl); // if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle) // { // if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) // { // DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n"); // } // } if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) { fwUpdateTimer->start(100); // recheck } else { DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n"); fwUpdateState = FW_Update; fwUpdateTimer->start(0); updateEtag(gwConfigEtag); } } /*! Starts the firmware update. */ bool DeRestPluginPrivate::startUpdateFirmware() { fwUpdateStartedByUser = true; if (fwUpdateState == FW_WaitUserConfirm) { apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning); updateEtag(gwConfigEtag); fwUpdateState = FW_DisconnectDevice; fwUpdateTimer->start(100); return true; } return false; } /*! Delayed trigger to update the firmware. */ void DeRestPluginPrivate::firmwareUpdateTimerFired() { if (otauLastBusyTimeDelta() < OTA_LOW_PRIORITY_TIME) { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } else if (fwUpdateState == FW_Idle) { if (gwFirmwareNeedUpdate) { gwFirmwareNeedUpdate = false; updateEtag(gwConfigEtag); } fwUpdateState = FW_CheckDevices; fwUpdateTimer->start(0); } else if (fwUpdateState == FW_CheckDevices) { checkFirmwareDevices(); } else if (fwUpdateState == FW_CheckVersion) { queryFirmwareVersion(); } else if (fwUpdateState == FW_DisconnectDevice) { updateFirmwareDisconnectDevice(); } else if (fwUpdateState == FW_Update) { updateFirmware(); } else if (fwUpdateState == FW_UpdateWaitFinished) { updateFirmwareWaitFinished(); } else if (fwUpdateState == FW_WaitUserConfirm) { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } else { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } } /*! Lazy query of firmware version. Because the device might not be connected at first optaining the firmware version must be delayed. If the firmware is older then the min required firmware for the platform and a proper firmware update file exists, the API will announce that a firmware update is available. */ void DeRestPluginPrivate::queryFirmwareVersion() { Q_ASSERT(apsCtrl); if (!apsCtrl) { return; } { // check for GCFFlasher binary QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher"; #ifdef Q_OS_WIN gcfFlasherBin.append(".exe"); #elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; #elif defined(Q_OS_OSX) // TODO #else gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; #endif if (!QFile::exists(gcfFlasherBin)) { DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin)); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); return; } } // does the update file exist? if (fwUpdateFile.isEmpty()) { QString fileName; fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION); // search in different locations std::vector<QString> paths; #ifdef Q_OS_LINUX paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/")); #endif paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/")); paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/")); #ifdef Q_OS_OSX QDir dir(qApp->applicationDirPath()); dir.cdUp(); dir.cd("Resources"); paths.push_back(dir.path() + "/"); #endif std::vector<QString>::const_iterator i = paths.begin(); std::vector<QString>::const_iterator end = paths.end(); for (; i != end; ++i) { if (QFile::exists(*i + fileName)) { fwUpdateFile = *i + fileName; DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile)); break; } } } if (fwUpdateFile.isEmpty()) { DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fwUpdateFile)); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); return; } uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected); uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion); Q_ASSERT(!gwFirmwareNeedUpdate); if (devConnected == 0 || fwVersion == 0) { // if even after some time no firmware was detected // ASSUME that a device is present and reachable but might not have firmware installed // if (getUptime() >= FW_WAIT_UPDATE_READY) { QString str; str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION); gwFirmwareVersion = "0x00000000"; // unknown gwFirmwareVersionUpdate = str; gwConfig["fwversion"] = gwFirmwareVersion; gwFirmwareNeedUpdate = true; updateEtag(gwConfigEtag); fwUpdateState = FW_WaitUserConfirm; fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart); if (fwUpdateStartedByUser) { startUpdateFirmware(); } } return; } else if (devConnected) { QString str; str.sprintf("0x%08x", fwVersion); if (gwFirmwareVersion != str) { gwFirmwareVersion = str; gwConfig["fwversion"] = str; updateEtag(gwConfigEtag); } DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion)); // if the device is detected check that the firmware version is >= min version if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI) { if (fwVersion < GW_MIN_RPI_FW_VERSION) { gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION); gwFirmwareNeedUpdate = true; updateEtag(gwConfigEtag); DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION); fwUpdateState = FW_WaitUserConfirm; fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart); return; } else { DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); return; } } if (!gwFirmwareVersionUpdate.isEmpty()) { gwFirmwareVersionUpdate.clear(); updateEtag(gwConfigEtag); } } fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } /*! Checks if devices for firmware update are present. */ void DeRestPluginPrivate::checkFirmwareDevices() { deCONZ::DeviceEnumerator devEnumerator; fwProcessArgs.clear(); devEnumerator.listSerialPorts(); const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList(); std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin(); std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end(); int raspBeeCount = 0; int usbDongleCount = 0; QString ttyPath; for (; i != end; ++i) { if (i->friendlyName.contains(QLatin1String("ConBee"))) { usbDongleCount++; } else if (i->friendlyName.contains(QLatin1String("RaspBee"))) { raspBeeCount = 1; ttyPath = i->path; } } if (usbDongleCount > 1) { DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n"); } else if (usbDongleCount == 1) { DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n"); fwProcessArgs << "-d" << "0"; } else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty()) { DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath)); fwProcessArgs << "-d" << "RaspBee"; } if (!fwProcessArgs.isEmpty()) { fwUpdateState = FW_CheckVersion; fwUpdateTimer->start(0); return; } fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } <commit_msg>Fix retreive of firmware version on desktop<commit_after>/* * Copyright (c) 2016 dresden elektronik ingenieurtechnik gmbh. * All rights reserved. * * The software in this package is published under the terms of the BSD * style license a copy of which has been included with this distribution in * the LICENSE.txt file. * */ #include <QApplication> #include <QDesktopServices> #include <QFile> #include <QDir> #include <QString> #include <QProcess> #include "de_web_plugin.h" #include "de_web_plugin_private.h" #define FW_IDLE_TIMEOUT (10 * 1000) #define FW_WAIT_UPDATE_READY (2) //s #define FW_IDLE_TIMEOUT_LONG (240 * 1000) #define FW_WAIT_USER_TIMEOUT (120 * 1000) /*! Inits the firmware update manager. */ void DeRestPluginPrivate::initFirmwareUpdate() { fwProcess = 0; fwUpdateState = FW_Idle; Q_ASSERT(apsCtrl); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle); fwUpdateStartedByUser = false; fwUpdateTimer = new QTimer(this); fwUpdateTimer->setSingleShot(true); connect(fwUpdateTimer, SIGNAL(timeout()), this, SLOT(firmwareUpdateTimerFired())); fwUpdateTimer->start(5000); } /*! Starts the actual firmware update process. */ void DeRestPluginPrivate::updateFirmware() { if (gwFirmwareNeedUpdate) { gwFirmwareNeedUpdate = false; } Q_ASSERT(apsCtrl); if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle || apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) { DBG_Printf(DBG_INFO, "GW firmware update conditions not met, abort\n"); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); updateEtag(gwConfigEtag); return; } QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher"; #ifdef Q_OS_WIN gcfFlasherBin.append(".exe"); QString bin = gcfFlasherBin; #elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there QString bin = "pkexec"; gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; fwProcessArgs.prepend(gcfFlasherBin); #elif defined(Q_OS_OSX) // TODO // /usr/bin/osascript -e 'do shell script "make install" with administrator privileges' QString bin = "sudo"; fwProcessArgs.prepend(gcfFlasherBin); #else QString bin = "sudo"; gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; fwProcessArgs.prepend(gcfFlasherBin); #endif if (!fwProcess) { fwProcess = new QProcess(this); } fwProcessArgs << "-f" << fwUpdateFile; fwUpdateState = FW_UpdateWaitFinished; updateEtag(gwConfigEtag); fwUpdateTimer->start(250); fwProcess->start(bin, fwProcessArgs); } /*! Observes the firmware update process. */ void DeRestPluginPrivate::updateFirmwareWaitFinished() { if (fwProcess) { if (fwProcess->bytesAvailable()) { QByteArray data = fwProcess->readAllStandardOutput(); DBG_Printf(DBG_INFO, "%s", qPrintable(data)); if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) != deCONZ::FirmwareUpdateRunning) { if (data.contains("flashing")) { apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning); } } } if (fwProcess->state() == QProcess::Starting) { DBG_Printf(DBG_INFO, "GW firmware update starting ..\n"); } else if (fwProcess->state() == QProcess::Running) { DBG_Printf(DBG_INFO_L2, "GW firmware update running ..\n"); } else if (fwProcess->state() == QProcess::NotRunning) { if (fwProcess->exitStatus() == QProcess::NormalExit) { DBG_Printf(DBG_INFO, "GW firmware update exit code %d\n", fwProcess->exitCode()); } else if (fwProcess->exitStatus() == QProcess::CrashExit) { DBG_Printf(DBG_INFO, "GW firmware update crashed %s\n", qPrintable(fwProcess->errorString())); } fwProcess->deleteLater(); fwProcess = 0; } } // done if (fwProcess == 0) { fwUpdateStartedByUser = false; gwFirmwareNeedUpdate = false; updateEtag(gwConfigEtag); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateIdle); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); } else // recheck { fwUpdateTimer->start(250); } } /*! Starts the device disconnect so that the serial port is released. */ void DeRestPluginPrivate::updateFirmwareDisconnectDevice() { Q_ASSERT(apsCtrl); // if (apsCtrl->getParameter(deCONZ::ParamFirmwareUpdateActive) == deCONZ::FirmwareUpdateIdle) // { // if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) // { // DBG_Printf(DBG_INFO, "GW firmware disconnect device before update\n"); // } // } if (apsCtrl->getParameter(deCONZ::ParamDeviceConnected) == 1) { fwUpdateTimer->start(100); // recheck } else { DBG_Printf(DBG_INFO, "GW firmware start update (device not connected)\n"); fwUpdateState = FW_Update; fwUpdateTimer->start(0); updateEtag(gwConfigEtag); } } /*! Starts the firmware update. */ bool DeRestPluginPrivate::startUpdateFirmware() { fwUpdateStartedByUser = true; if (fwUpdateState == FW_WaitUserConfirm) { apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateRunning); updateEtag(gwConfigEtag); fwUpdateState = FW_DisconnectDevice; fwUpdateTimer->start(100); return true; } return false; } /*! Delayed trigger to update the firmware. */ void DeRestPluginPrivate::firmwareUpdateTimerFired() { if (otauLastBusyTimeDelta() < OTA_LOW_PRIORITY_TIME) { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } else if (fwUpdateState == FW_Idle) { if (gwFirmwareNeedUpdate) { gwFirmwareNeedUpdate = false; updateEtag(gwConfigEtag); } if (gwFirmwareVersion == QLatin1String("0x00000000")) { uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected); uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion); if (devConnected && fwVersion) { gwFirmwareVersion.sprintf("0x%08x", fwVersion); gwConfig["fwversion"] = gwFirmwareVersion; updateEtag(gwConfigEtag); } } fwUpdateState = FW_CheckDevices; fwUpdateTimer->start(0); } else if (fwUpdateState == FW_CheckDevices) { checkFirmwareDevices(); } else if (fwUpdateState == FW_CheckVersion) { queryFirmwareVersion(); } else if (fwUpdateState == FW_DisconnectDevice) { updateFirmwareDisconnectDevice(); } else if (fwUpdateState == FW_Update) { updateFirmware(); } else if (fwUpdateState == FW_UpdateWaitFinished) { updateFirmwareWaitFinished(); } else if (fwUpdateState == FW_WaitUserConfirm) { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } else { fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } } /*! Lazy query of firmware version. Because the device might not be connected at first optaining the firmware version must be delayed. If the firmware is older then the min required firmware for the platform and a proper firmware update file exists, the API will announce that a firmware update is available. */ void DeRestPluginPrivate::queryFirmwareVersion() { Q_ASSERT(apsCtrl); if (!apsCtrl) { return; } { // check for GCFFlasher binary QString gcfFlasherBin = qApp->applicationDirPath() + "/GCFFlasher"; #ifdef Q_OS_WIN gcfFlasherBin.append(".exe"); #elif defined(Q_OS_LINUX) && !defined(ARCH_ARM) // on RPi a normal sudo is ok since we don't need password there gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; #elif defined(Q_OS_OSX) // TODO #else gcfFlasherBin = "/usr/bin/GCFFlasher_internal"; #endif if (!QFile::exists(gcfFlasherBin)) { DBG_Printf(DBG_INFO, "GW update firmware failed, %s doesn't exist\n", qPrintable(gcfFlasherBin)); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); return; } } // does the update file exist? QString fileName; if (fwUpdateFile.isEmpty()) { fileName.sprintf("deCONZ_Rpi_0x%08x.bin.GCF", GW_MIN_RPI_FW_VERSION); // search in different locations std::vector<QString> paths; #ifdef Q_OS_LINUX paths.push_back(QLatin1String("/usr/share/deCONZ/firmware/")); #endif paths.push_back(deCONZ::getStorageLocation(deCONZ::ApplicationsDataLocation) + QLatin1String("/firmware/")); paths.push_back(deCONZ::getStorageLocation(deCONZ::HomeLocation) + QLatin1String("/raspbee_firmware/")); #ifdef Q_OS_OSX QDir dir(qApp->applicationDirPath()); dir.cdUp(); dir.cd("Resources"); paths.push_back(dir.path() + "/"); #endif std::vector<QString>::const_iterator i = paths.begin(); std::vector<QString>::const_iterator end = paths.end(); for (; i != end; ++i) { if (QFile::exists(*i + fileName)) { fwUpdateFile = *i + fileName; DBG_Printf(DBG_INFO, "GW update firmware found: %s\n", qPrintable(fwUpdateFile)); break; } } } if (fwUpdateFile.isEmpty()) { DBG_Printf(DBG_ERROR, "GW update firmware not found: %s\n", qPrintable(fileName)); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); return; } uint8_t devConnected = apsCtrl->getParameter(deCONZ::ParamDeviceConnected); uint32_t fwVersion = apsCtrl->getParameter(deCONZ::ParamFirmwareVersion); Q_ASSERT(!gwFirmwareNeedUpdate); if (devConnected == 0 || fwVersion == 0) { // if even after some time no firmware was detected // ASSUME that a device is present and reachable but might not have firmware installed // if (getUptime() >= FW_WAIT_UPDATE_READY) { QString str; str.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION); gwFirmwareVersion = "0x00000000"; // unknown gwFirmwareVersionUpdate = str; gwConfig["fwversion"] = gwFirmwareVersion; gwFirmwareNeedUpdate = true; updateEtag(gwConfigEtag); fwUpdateState = FW_WaitUserConfirm; fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart); if (fwUpdateStartedByUser) { startUpdateFirmware(); } } return; } else if (devConnected) { QString str; str.sprintf("0x%08x", fwVersion); if (gwFirmwareVersion != str) { gwFirmwareVersion = str; gwConfig["fwversion"] = str; updateEtag(gwConfigEtag); } DBG_Printf(DBG_INFO, "GW firmware version: %s\n", qPrintable(gwFirmwareVersion)); // if the device is detected check that the firmware version is >= min version if ((fwVersion & FW_PLATFORM_MASK) == FW_PLATFORM_RPI) { if (fwVersion < GW_MIN_RPI_FW_VERSION) { gwFirmwareVersionUpdate.sprintf("0x%08x", GW_MIN_RPI_FW_VERSION); gwFirmwareNeedUpdate = true; updateEtag(gwConfigEtag); DBG_Printf(DBG_INFO, "GW firmware version shall be updated to: 0x%08x\n", GW_MIN_RPI_FW_VERSION); fwUpdateState = FW_WaitUserConfirm; fwUpdateTimer->start(FW_WAIT_USER_TIMEOUT); apsCtrl->setParameter(deCONZ::ParamFirmwareUpdateActive, deCONZ::FirmwareUpdateReadyToStart); return; } else { DBG_Printf(DBG_INFO, "GW firmware version is up to date: 0x%08x\n", fwVersion); fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT_LONG); return; } } if (!gwFirmwareVersionUpdate.isEmpty()) { gwFirmwareVersionUpdate.clear(); updateEtag(gwConfigEtag); } } fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } /*! Checks if devices for firmware update are present. */ void DeRestPluginPrivate::checkFirmwareDevices() { deCONZ::DeviceEnumerator devEnumerator; fwProcessArgs.clear(); devEnumerator.listSerialPorts(); const std::vector<deCONZ::DeviceEntry> &availPorts = devEnumerator.getList(); std::vector<deCONZ::DeviceEntry>::const_iterator i = availPorts.begin(); std::vector<deCONZ::DeviceEntry>::const_iterator end = availPorts.end(); int raspBeeCount = 0; int usbDongleCount = 0; QString ttyPath; for (; i != end; ++i) { if (i->friendlyName.contains(QLatin1String("ConBee"))) { usbDongleCount++; } else if (i->friendlyName.contains(QLatin1String("RaspBee"))) { raspBeeCount = 1; ttyPath = i->path; } } if (usbDongleCount > 1) { DBG_Printf(DBG_INFO_L2, "GW firmware update too many USB devices connected, abort\n"); } else if (usbDongleCount == 1) { DBG_Printf(DBG_INFO_L2, "GW firmware update select USB device\n"); fwProcessArgs << "-d" << "0"; } else if (raspBeeCount > 0 && usbDongleCount == 0 && !ttyPath.isEmpty()) { DBG_Printf(DBG_INFO_L2, "GW firmware update select %s device\n", qPrintable(ttyPath)); fwProcessArgs << "-d" << "RaspBee"; } if (!fwProcessArgs.isEmpty()) { fwUpdateState = FW_CheckVersion; fwUpdateTimer->start(0); return; } fwUpdateState = FW_Idle; fwUpdateTimer->start(FW_IDLE_TIMEOUT); } <|endoftext|>
<commit_before>/** * \file dcs/testbed/detail/application_experiment.hpp * * \brief Represents an experiment for a single application. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2012 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-testbed (below referred to as "this program"). * * 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/>. */ #ifndef DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP #define DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP #include <boost/chrono.hpp> #include <boost/smart_ptr.hpp> #include <boost/thread.hpp> #include <dcs/assert.hpp> #include <dcs/debug.hpp> #include <dcs/exception.hpp> #include <dcs/testbed/base_application_manager.hpp> #include <dcs/testbed/detail/runnable.hpp> #include <stdexcept> namespace dcs { namespace testbed { namespace detail { template <typename T, typename MT> struct sampler_runnable { sampler_runnable(::boost::weak_ptr<T> const& ptr, MT& mutex) : wp_(ptr), mtx_(mutex) { } void operator()() { ::boost::shared_ptr<T> sp(wp_.lock()); typename T::traits_type::uint_type ts = sp->sampling_time(); while (true) { { ::boost::lock_guard< ::boost::mutex > lock(mtx_); sp->sample(); } ::boost::this_thread::sleep_for(::boost::chrono::seconds(ts)); } } ::boost::weak_ptr<T> wp_; MT& mtx_; }; // sampler_runnable template <typename T, typename MT> struct controller_runnable { controller_runnable(::boost::weak_ptr<T> const& ptr, MT& mutex) : wp_(ptr), mtx_(mutex) { } void operator()() { ::boost::shared_ptr<T> sp(wp_.lock()); typename T::traits_type::uint_type ts = sp->control_time(); while (true) { { ::boost::lock_guard< ::boost::mutex > lock(mtx_); sp->control(); } ::boost::this_thread::sleep_for(::boost::chrono::seconds(ts)); } } ::boost::weak_ptr<T> wp_; MT& mtx_; }; // controller_runnable template <typename TraitsT> class application_experiment { public: typedef TraitsT traits_type; public: typedef typename traits_type::real_type real_type; private: typedef base_application<traits_type> app_type; public: typedef ::boost::shared_ptr<app_type> app_pointer; private: typedef base_workload_driver<traits_type> driver_type; public: typedef ::boost::shared_ptr<driver_type> driver_pointer; private: typedef base_application_manager<traits_type> manager_type; public: typedef ::boost::shared_ptr<manager_type> manager_pointer; public: application_experiment(app_pointer const& p_app, driver_pointer const& p_drv, manager_pointer const& p_mgr) : p_app_(p_app), p_drv_(p_drv), p_mgr_(p_mgr) { } public: void app(app_pointer const& p_app) { p_app_ = p_app; } public: void driver(driver_pointer const& p_drv) { p_drv_ = p_drv; } public: void manager(manager_pointer const& p_mgr) { p_mgr_ = p_mgr; } public: void run() { DCS_ASSERT(p_app_, DCS_EXCEPTION_THROW(::std::runtime_error, "Application not set")); DCS_ASSERT(p_drv_, DCS_EXCEPTION_THROW(::std::runtime_error, "Driver not set")); DCS_ASSERT(p_mgr_, DCS_EXCEPTION_THROW(::std::runtime_error, "Manager not set")); const unsigned long zzz_time(5); p_mgr_->app(p_app_); p_mgr_->reset(); //p_drv_->app(p_app_); //TODO p_drv_->reset(); p_drv_->start(); ::boost::thread_group mgr_thd_grp; ::boost::mutex mgr_mtx; bool mgr_run(false); while (!p_drv_->done()) { if (!mgr_run && p_drv_->ready()) { sampler_runnable<manager_type,::boost::mutex> mgr_smp_runner(p_mgr_, mgr_mtx); mgr_thd_grp.create_thread(mgr_smp_runner); controller_runnable<manager_type,::boost::mutex> mgr_ctl_runner(p_mgr_, mgr_mtx); mgr_thd_grp.create_thread(mgr_ctl_runner); mgr_run = true; } ::boost::this_thread::sleep_for(::boost::chrono::seconds(zzz_time)); } mgr_thd_grp.interrupt_all(); mgr_thd_grp.join_all(); } private: app_pointer p_app_; ///< Pointer to the application private: driver_pointer p_drv_; ///< Pointer to the application driver private: manager_pointer p_mgr_; ///< Pointer to the application manager }; // application_experiment }}} // Namespace dcs::testbed::detail #endif // DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP <commit_msg>(new:minor) In dcs::testbed::detail::application_experiment class, set the application pointer to the application driver<commit_after>/** * \file dcs/testbed/detail/application_experiment.hpp * * \brief Represents an experiment for a single application. * * \author Marco Guazzone ([email protected]) * * <hr/> * * Copyright (C) 2012 Marco Guazzone ([email protected]) * [Distributed Computing System (DCS) Group, * Computer Science Institute, * Department of Science and Technological Innovation, * University of Piemonte Orientale, * Alessandria (Italy)] * * This file is part of dcsxx-testbed (below referred to as "this program"). * * 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/>. */ #ifndef DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP #define DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP #include <boost/chrono.hpp> #include <boost/smart_ptr.hpp> #include <boost/thread.hpp> #include <dcs/assert.hpp> #include <dcs/debug.hpp> #include <dcs/exception.hpp> #include <dcs/testbed/base_application_manager.hpp> #include <dcs/testbed/detail/runnable.hpp> #include <stdexcept> namespace dcs { namespace testbed { namespace detail { template <typename T, typename MT> struct sampler_runnable { sampler_runnable(::boost::weak_ptr<T> const& ptr, MT& mutex) : wp_(ptr), mtx_(mutex) { } void operator()() { ::boost::shared_ptr<T> sp(wp_.lock()); typename T::traits_type::uint_type ts = sp->sampling_time(); while (true) { { ::boost::lock_guard< ::boost::mutex > lock(mtx_); sp->sample(); } ::boost::this_thread::sleep_for(::boost::chrono::seconds(ts)); } } ::boost::weak_ptr<T> wp_; MT& mtx_; }; // sampler_runnable template <typename T, typename MT> struct controller_runnable { controller_runnable(::boost::weak_ptr<T> const& ptr, MT& mutex) : wp_(ptr), mtx_(mutex) { } void operator()() { ::boost::shared_ptr<T> sp(wp_.lock()); typename T::traits_type::uint_type ts = sp->control_time(); while (true) { { ::boost::lock_guard< ::boost::mutex > lock(mtx_); sp->control(); } ::boost::this_thread::sleep_for(::boost::chrono::seconds(ts)); } } ::boost::weak_ptr<T> wp_; MT& mtx_; }; // controller_runnable template <typename TraitsT> class application_experiment { public: typedef TraitsT traits_type; public: typedef typename traits_type::real_type real_type; private: typedef base_application<traits_type> app_type; public: typedef ::boost::shared_ptr<app_type> app_pointer; private: typedef base_workload_driver<traits_type> driver_type; public: typedef ::boost::shared_ptr<driver_type> driver_pointer; private: typedef base_application_manager<traits_type> manager_type; public: typedef ::boost::shared_ptr<manager_type> manager_pointer; public: application_experiment(app_pointer const& p_app, driver_pointer const& p_drv, manager_pointer const& p_mgr) : p_app_(p_app), p_drv_(p_drv), p_mgr_(p_mgr) { } public: void app(app_pointer const& p_app) { p_app_ = p_app; } public: void driver(driver_pointer const& p_drv) { p_drv_ = p_drv; } public: void manager(manager_pointer const& p_mgr) { p_mgr_ = p_mgr; } public: void run() { DCS_ASSERT(p_app_, DCS_EXCEPTION_THROW(::std::runtime_error, "Application not set")); DCS_ASSERT(p_drv_, DCS_EXCEPTION_THROW(::std::runtime_error, "Driver not set")); DCS_ASSERT(p_mgr_, DCS_EXCEPTION_THROW(::std::runtime_error, "Manager not set")); const unsigned long zzz_time(5); p_mgr_->app(p_app_); p_mgr_->reset(); p_drv_->app(p_app_); p_drv_->reset(); p_drv_->start(); ::boost::thread_group mgr_thd_grp; ::boost::mutex mgr_mtx; bool mgr_run(false); while (!p_drv_->done()) { if (!mgr_run && p_drv_->ready()) { sampler_runnable<manager_type,::boost::mutex> mgr_smp_runner(p_mgr_, mgr_mtx); mgr_thd_grp.create_thread(mgr_smp_runner); controller_runnable<manager_type,::boost::mutex> mgr_ctl_runner(p_mgr_, mgr_mtx); mgr_thd_grp.create_thread(mgr_ctl_runner); mgr_run = true; } ::boost::this_thread::sleep_for(::boost::chrono::seconds(zzz_time)); } mgr_thd_grp.interrupt_all(); mgr_thd_grp.join_all(); } private: app_pointer p_app_; ///< Pointer to the application private: driver_pointer p_drv_; ///< Pointer to the application driver private: manager_pointer p_mgr_; ///< Pointer to the application manager }; // application_experiment }}} // Namespace dcs::testbed::detail #endif // DCS_TESTBED_DETAIL_APPLICATION_EXPERIMENT_HPP <|endoftext|>
<commit_before>#ifndef QTL_REGION_CLASSIFIER_HPP_ #define QTL_REGION_CLASSIFIER_HPP_ #include "qtl_allele.h" #include "clotho/utility/random_generator.hpp" #include "clotho/classifiers/region_classifier.hpp" #include <boost/random/poisson_distribution.hpp> namespace clotho { namespace utility { template < class URNG, class Result, class Tag > class random_generator< URNG, clotho::classifiers::region_classifier< qtl_allele, Result, Tag > > { public: typedef random_generator< URNG, clotho::classifiers::region_classifier< qtl_allele, Result, Tag > > self_type; typedef clotho::classifiers::region_classifier< qtl_allele, Result, Tag > result_type; typedef boost::random::uniform_01< double > uniform_type; // key distribution typedef boost::random::poisson_distribution< unsigned int, double > dist_type; // region distribution random_generator( URNG & rng, boost::property_tree::ptree & config ) : m_rng( &rng ) , m_dist( DEFAULT_RECOMB_RATE ) , m_bSkip(false) { parseConfig( config ); } random_generator( URNG & rng, double mu = DEFAULT_RECOMB_RATE ) : m_rng( &rng ), m_dist( mu ) { } result_type operator()() { typename result_type::param_type p; unsigned int n = ((m_bSkip)? 0 : m_dist( *m_rng )); for( unsigned int i = 0; i < n; ++i ) { double k = m_uniform( *m_rng ); qtl_allele::trait_weights coeff; p.push_back( qtl_allele( k, DEFAULT_SELECTION, DEFAULT_DOMINANCE, DEFAULT_NEUTRAL, coeff) ); } std::sort( p.begin(), p.end() ); return result_type( p ); } protected: void parseConfig( boost::property_tree::ptree & config ) { std::ostringstream oss; oss /*<< CONFIG_BLOCK_K << "."*/ << REC_BLOCK_K << "." << RATE_PER_REGION_K; if( config.get_child_optional( oss.str() ) == boost::none ) { config.put( oss.str(), m_dist.mean() ); } else { double m = config.get< double >( oss.str() ); m_bSkip = (m == 0.0); if( m_bSkip ) { m = 0.00000000001; } else if( m < 0.0 ) { m = std::abs( m ); } typename dist_type::param_type p( m ); m_dist.param( p ); } } URNG * m_rng; uniform_type m_uniform; dist_type m_dist; bool m_bSkip; }; } // namespace utility { } // namespace clotho { #endif // QTL_REGION_CLASSIFIER_HPP_ <commit_msg>Added age property<commit_after>#ifndef QTL_REGION_CLASSIFIER_HPP_ #define QTL_REGION_CLASSIFIER_HPP_ #include "qtl_allele.h" #include "clotho/utility/random_generator.hpp" #include "clotho/classifiers/region_classifier.hpp" #include <boost/random/poisson_distribution.hpp> namespace clotho { namespace utility { template < class URNG, class Result, class Tag > class random_generator< URNG, clotho::classifiers::region_classifier< qtl_allele, Result, Tag > > { public: typedef random_generator< URNG, clotho::classifiers::region_classifier< qtl_allele, Result, Tag > > self_type; typedef clotho::classifiers::region_classifier< qtl_allele, Result, Tag > result_type; typedef boost::random::uniform_01< double > uniform_type; // key distribution typedef boost::random::poisson_distribution< unsigned int, double > dist_type; // region distribution random_generator( URNG & rng, boost::property_tree::ptree & config ) : m_rng( &rng ) , m_dist( DEFAULT_RECOMB_RATE ) , m_bSkip(false) { parseConfig( config ); } random_generator( URNG & rng, double mu = DEFAULT_RECOMB_RATE ) : m_rng( &rng ), m_dist( mu ) { } result_type operator()() { typename result_type::param_type p; unsigned int n = ((m_bSkip)? 0 : m_dist( *m_rng )); for( unsigned int i = 0; i < n; ++i ) { double k = m_uniform( *m_rng ); qtl_allele::trait_weights coeff; p.push_back( qtl_allele( k, DEFAULT_SELECTION, DEFAULT_DOMINANCE, DEFAULT_NEUTRAL, 0, coeff) ); } std::sort( p.begin(), p.end() ); return result_type( p ); } protected: void parseConfig( boost::property_tree::ptree & config ) { std::ostringstream oss; oss /*<< CONFIG_BLOCK_K << "."*/ << REC_BLOCK_K << "." << RATE_PER_REGION_K; if( config.get_child_optional( oss.str() ) == boost::none ) { config.put( oss.str(), m_dist.mean() ); } else { double m = config.get< double >( oss.str() ); m_bSkip = (m == 0.0); if( m_bSkip ) { m = 0.00000000001; } else if( m < 0.0 ) { m = std::abs( m ); } typename dist_type::param_type p( m ); m_dist.param( p ); } } URNG * m_rng; uniform_type m_uniform; dist_type m_dist; bool m_bSkip; }; } // namespace utility { } // namespace clotho { #endif // QTL_REGION_CLASSIFIER_HPP_ <|endoftext|>
<commit_before>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf.hpp * \date October 2014 * \author Jan Issac ([email protected]) */ #ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP #define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP #include <utility> #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/exception/exception.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/model/process/linear_process_model.hpp> #include <fl/model/observation/linear_observation_model.hpp> namespace fl { template <typename...> class GaussianFilter; /** * \defgroup kalman_filter KalmanFilter * \ingroup filters */ /** * \ingroup kalman_filter * * Traits of the Linear GaussianFilter (KalmanFilter) */ template <typename State_,typename Input_,typename Obsrv_> struct Traits< GaussianFilter< LinearGaussianProcessModel<State_, Input_>, LinearGaussianObservationModel<Obsrv_, State_>>> { /** * \brief Process model definition. * The process model of the KalmanFilter is always the * \c LinearGaussianProcessModel taking a \c State and an \c Input type as * the only parameter types. */ typedef LinearGaussianProcessModel<State_, Input_> ProcessModel; /** * \brief Observation model definition. * The observation model of the KalmanFilter is always the * \c LinearGaussianObservationModel taking an \c Obsrv and a * \c State type as the only parameters. */ typedef LinearGaussianObservationModel< Obsrv_, State_ > ObservationModel; /** * \brief Represents KalmanFilter definition. * The KalmanFilter type is represented by the GaussianFilter using * the linear Gaussian Models. */ typedef GaussianFilter< LinearGaussianProcessModel<State_, Input_>, LinearGaussianObservationModel<Obsrv_, State_> > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ObservationModel>::Obsrv Obsrv; /** * \brief Represents the underlying distribution of the estimated state. * In the case of the Kalman filter, the distribution is a simple Gaussian * with the dimension of the \c State */ typedef Gaussian<State> StateDistribution; }; /** * \ingroup kalman_filter * * \brief GaussianFilter resembles the Kalman filter. * * \tparam State State type defining the state space * \tparam Input Process model input type * \tparam Obsrv Observation type of the linear observation Gaussian model * * The KalmanFilter type is represented by the GaussianFilter using * the linear Gaussian Models. * */ template <typename State, typename Input, typename Obsrv> class GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State>> : /* Implement the conceptual filter interface */ public FilterInterface< GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State>>> { protected: /** \cond INTERNAL */ typedef GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State> > This; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::ObservationModel ObservationModel; typedef typename Traits<This>::ProcessModel ProcessModel; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a linear Gaussian filter (a KalmanFilter) * * \param process_model Process model instance * \param obsrv_model Obsrv model instance */ template < typename ProcessModel, // deduce model type for perfect forwarding typename ObsrvModel // deduce model type for perfect forwarding > GaussianFilter(ProcessModel&& process_model, ObsrvModel&& obsrv_model) : process_model_(std::forward<ProcessModel>(process_model)), obsrv_model_(std::forward<ObservationModel>(obsrv_model)) { } /** * \copydoc FilterInterface::predict * * KalmanFilter prediction step * * Given the following matrices * * - \f$ A \f$: Dynamics Matrix * - \f$ B \f$: Dynamics Noise Covariance * * and the current state distribution * \f$ {\cal N}(x_t\mid \hat{x}_t, \hat{\Sigma}_{t}) \f$, * * the prediction steps is the discrete linear mapping * * \f$ \bar{x}_{t} = A \hat{x}_t\f$ and * * \f$ \bar{\Sigma}_{t} = A\hat{\Sigma}_{t}A^T + Q \f$ */ virtual void predict(double delta_time, const Input& input, const StateDistribution& prior_dist, StateDistribution& predicted_dist) { auto&& A = (process_model_.A() * delta_time).eval(); auto&& Q = (process_model_.covariance() * delta_time).eval(); predicted_dist.mean( A * prior_dist.mean()); predicted_dist.covariance( A * prior_dist.covariance() * A.transpose() + Q); } /** * \copydoc FilterInterface::update * * Given the following matrices * * - \f$ H \f$: Sensor Matrix * - \f$ R \f$: Sensor Noise Covariance * * and the current predicted state distribution * \f$ {\cal N}(x_t\mid \bar{x}_t, \bar{\Sigma}_{t}) \f$, * * the update steps is the discrete linear mapping * * \f$ \hat{x}_{t+1} = \bar{x}_t + K (y - H\bar{x}_t)\f$ and * * \f$ \hat{\Sigma}_{t} = (I - KH) \bar{\Sigma}_{t}\f$ * * with the KalmanGain * * \f$ K = \bar{\Sigma}_{t}H^T (H\bar{\Sigma}_{t}H^T+R)^{-1}\f$. */ virtual void update(const Obsrv& y, const StateDistribution& predicted_dist, StateDistribution& posterior_dist) { auto&& H = obsrv_model_.H(); auto&& R = obsrv_model_.covariance(); auto&& mean = predicted_dist.mean(); auto&& cov_xx = predicted_dist.covariance(); auto&& S = (H * cov_xx * H.transpose() + R).eval(); auto&& K = (cov_xx * H.transpose() * S.inverse()).eval(); posterior_dist.mean(mean + K * (y - H * mean)); posterior_dist.covariance(cov_xx - K * H * cov_xx); } /** * \copydoc FilterInterface::predict_and_update */ virtual void predict_and_update(double delta_time, const Input& input, const Obsrv& observation, const StateDistribution& prior_dist, StateDistribution& posterior_dist) { predict(delta_time, input, prior_dist, posterior_dist); update(observation, posterior_dist, posterior_dist); } protected: ProcessModel process_model_; ObservationModel obsrv_model_; }; } #endif <commit_msg>added model accessors<commit_after>/* * This is part of the FL library, a C++ Bayesian filtering library * (https://github.com/filtering-library) * * Copyright (c) 2014 Jan Issac ([email protected]) * Copyright (c) 2014 Manuel Wuthrich ([email protected]) * * Max-Planck Institute for Intelligent Systems, AMD Lab * University of Southern California, CLMC Lab * * This Source Code Form is subject to the terms of the MIT License (MIT). * A copy of the license can be found in the LICENSE file distributed with this * source code. */ /** * \file gaussian_filter_kf.hpp * \date October 2014 * \author Jan Issac ([email protected]) */ #ifndef FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP #define FL__FILTER__GAUSSIAN__GAUSSIAN_FILTER_KF_HPP #include <utility> #include <fl/util/meta.hpp> #include <fl/util/traits.hpp> #include <fl/exception/exception.hpp> #include <fl/filter/filter_interface.hpp> #include <fl/model/process/linear_process_model.hpp> #include <fl/model/observation/linear_observation_model.hpp> namespace fl { template <typename...> class GaussianFilter; /** * \defgroup kalman_filter KalmanFilter * \ingroup filters */ /** * \ingroup kalman_filter * * Traits of the Linear GaussianFilter (KalmanFilter) */ template <typename State_,typename Input_,typename Obsrv_> struct Traits< GaussianFilter< LinearGaussianProcessModel<State_, Input_>, LinearGaussianObservationModel<Obsrv_, State_>>> { /** * \brief Process model definition. * The process model of the KalmanFilter is always the * \c LinearGaussianProcessModel taking a \c State and an \c Input type as * the only parameter types. */ typedef LinearGaussianProcessModel<State_, Input_> ProcessModel; /** * \brief Observation model definition. * The observation model of the KalmanFilter is always the * \c LinearGaussianObservationModel taking an \c Obsrv and a * \c State type as the only parameters. */ typedef LinearGaussianObservationModel< Obsrv_, State_ > ObservationModel; /** * \brief Represents KalmanFilter definition. * The KalmanFilter type is represented by the GaussianFilter using * the linear Gaussian Models. */ typedef GaussianFilter< LinearGaussianProcessModel<State_, Input_>, LinearGaussianObservationModel<Obsrv_, State_> > Filter; /* * Required concept (interface) types * * - Ptr * - State * - Input * - Observation * - StateDistribution */ //typedef std::shared_ptr<Filter> Ptr; typedef typename Traits<ProcessModel>::State State; typedef typename Traits<ProcessModel>::Input Input; typedef typename Traits<ObservationModel>::Obsrv Obsrv; /** * \brief Represents the underlying distribution of the estimated state. * In the case of the Kalman filter, the distribution is a simple Gaussian * with the dimension of the \c State */ typedef Gaussian<State> StateDistribution; }; /** * \ingroup kalman_filter * * \brief GaussianFilter resembles the Kalman filter. * * \tparam State State type defining the state space * \tparam Input Process model input type * \tparam Obsrv Observation type of the linear observation Gaussian model * * The KalmanFilter type is represented by the GaussianFilter using * the linear Gaussian Models. * */ template <typename State, typename Input, typename Obsrv> class GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State>> : /* Implement the conceptual filter interface */ public FilterInterface< GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State>>> { protected: /** \cond INTERNAL */ typedef GaussianFilter< LinearGaussianProcessModel<State, Input>, LinearGaussianObservationModel<Obsrv, State> > This; /** \endcond */ public: /* public concept interface types */ typedef typename Traits<This>::ObservationModel ObservationModel; typedef typename Traits<This>::ProcessModel ProcessModel; typedef typename Traits<This>::StateDistribution StateDistribution; public: /** * Creates a linear Gaussian filter (a KalmanFilter) * * \param process_model Process model instance * \param obsrv_model Obsrv model instance */ // template < // typename ProcessModel, // deduce model type for perfect forwarding // typename ObsrvModel // deduce model type for perfect forwarding // > GaussianFilter(const ProcessModel& process_model, const ObservationModel& obsrv_model) : process_model_(process_model), obsrv_model_(obsrv_model) { } /** * \copydoc FilterInterface::predict * * KalmanFilter prediction step * * Given the following matrices * * - \f$ A \f$: Dynamics Matrix * - \f$ B \f$: Dynamics Noise Covariance * * and the current state distribution * \f$ {\cal N}(x_t\mid \hat{x}_t, \hat{\Sigma}_{t}) \f$, * * the prediction steps is the discrete linear mapping * * \f$ \bar{x}_{t} = A \hat{x}_t\f$ and * * \f$ \bar{\Sigma}_{t} = A\hat{\Sigma}_{t}A^T + Q \f$ */ virtual void predict(double delta_time, const Input& input, const StateDistribution& prior_dist, StateDistribution& predicted_dist) { auto&& A = (process_model_.A() * delta_time).eval(); auto&& Q = (process_model_.covariance() * delta_time).eval(); predicted_dist.mean( A * prior_dist.mean()); predicted_dist.covariance( A * prior_dist.covariance() * A.transpose() + Q); } /** * \copydoc FilterInterface::update * * Given the following matrices * * - \f$ H \f$: Sensor Matrix * - \f$ R \f$: Sensor Noise Covariance * * and the current predicted state distribution * \f$ {\cal N}(x_t\mid \bar{x}_t, \bar{\Sigma}_{t}) \f$, * * the update steps is the discrete linear mapping * * \f$ \hat{x}_{t+1} = \bar{x}_t + K (y - H\bar{x}_t)\f$ and * * \f$ \hat{\Sigma}_{t} = (I - KH) \bar{\Sigma}_{t}\f$ * * with the KalmanGain * * \f$ K = \bar{\Sigma}_{t}H^T (H\bar{\Sigma}_{t}H^T+R)^{-1}\f$. */ virtual void update(const Obsrv& y, const StateDistribution& predicted_dist, StateDistribution& posterior_dist) { auto&& H = obsrv_model_.H(); auto&& R = obsrv_model_.covariance(); auto&& mean = predicted_dist.mean(); auto&& cov_xx = predicted_dist.covariance(); auto&& S = (H * cov_xx * H.transpose() + R).eval(); auto&& K = (cov_xx * H.transpose() * S.inverse()).eval(); posterior_dist.mean(mean + K * (y - H * mean)); posterior_dist.covariance(cov_xx - K * H * cov_xx); } /** * \copydoc FilterInterface::predict_and_update */ virtual void predict_and_update(double delta_time, const Input& input, const Obsrv& observation, const StateDistribution& prior_dist, StateDistribution& posterior_dist) { predict(delta_time, input, prior_dist, posterior_dist); update(observation, posterior_dist, posterior_dist); } ProcessModel& process_model() { return process_model_; } ObservationModel& obsrv_model() { return obsrv_model_; } const ProcessModel& process_model() const { return process_model_; } const ObservationModel& obsrv_model() const { return obsrv_model_; } protected: ProcessModel process_model_; ObservationModel obsrv_model_; }; } #endif <|endoftext|>
<commit_before>#include "BarcodeFormat.h" // Reader #include "DecodeHints.h" #include "GenericLuminanceSource.h" #include "HybridBinarizer.h" #include "MultiFormatReader.h" #include "Result.h" // Writer #include "BitMatrix.h" #include "MultiFormatWriter.h" #include "TextUtfEncoding.h" #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <memory> #include <vector> using namespace ZXing; namespace py = pybind11; // Numpy array wrapper class for images (either BGR or GRAYSCALE) using Image = py::array_t<uint8_t, py::array::c_style>; template<typename OUT, typename IN> OUT narrow(IN in) { return static_cast<OUT>(in); } // The intension was to use the flag based BarcodeFormats here but that failed due to a pybind11 bug: // https://github.com/pybind/pybind11/issues/2221 using FormatList = std::vector<BarcodeFormat>; FormatList barcode_formats_from_str(const std::string& str) { auto formats = BarcodeFormatsFromString(str); return FormatList(formats.begin(), formats.end()); }; Result read_barcode(const Image& image, const FormatList& formats, bool fastMode, bool tryRotate, bool hybridBinarizer) { DecodeHints hints; hints.setTryHarder(!fastMode); hints.setTryRotate(tryRotate); hints.setPossibleFormats(formats); MultiFormatReader reader(hints); const auto height = narrow<int>(image.shape(0)); const auto width = narrow<int>(image.shape(1)); const auto bytes = image.data(); std::shared_ptr<LuminanceSource> source; if (image.ndim() == 2) { // Grayscale image source = std::make_shared<GenericLuminanceSource>(width, height, bytes, width); } else { // BGR image const auto channels = image.shape(2); source = std::make_shared<GenericLuminanceSource>(width, height, bytes, width * channels, channels, 2, 1, 0); } if (hybridBinarizer) { return reader.read(HybridBinarizer(source)); } else { return reader.read(GlobalHistogramBinarizer(source)); } } Image write_barcode(BarcodeFormat format, std::string text, int width, int height, int margin, int eccLevel) { auto writer = MultiFormatWriter(format).setMargin(margin).setEccLevel(eccLevel); auto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height); auto result = Image({bitmap.width(), bitmap.height()}); auto r = result.mutable_unchecked<2>(); for (ssize_t y = 0; y < r.shape(0); y++) for (ssize_t x = 0; x < r.shape(1); x++) r(y, x) = bitmap.get(narrow<int>(x), narrow<int>(y)) ? 0 : 255; return result; } PYBIND11_MODULE(zxing, m) { m.doc() = "python bindings for zxing-cpp"; py::enum_<BarcodeFormat>(m, "BarcodeFormat") .value("AZTEC", BarcodeFormat::AZTEC) .value("CODABAR", BarcodeFormat::CODABAR) .value("CODE_39", BarcodeFormat::CODE_39) .value("CODE_93", BarcodeFormat::CODE_93) .value("CODE_128", BarcodeFormat::CODE_128) .value("DATA_MATRIX", BarcodeFormat::DATA_MATRIX) .value("EAN_8", BarcodeFormat::EAN_8) .value("EAN_13", BarcodeFormat::EAN_13) .value("ITF", BarcodeFormat::ITF) .value("MAXICODE", BarcodeFormat::MAXICODE) .value("PDF_417", BarcodeFormat::PDF_417) .value("QR_CODE", BarcodeFormat::QR_CODE) .value("RSS_14", BarcodeFormat::RSS_14) .value("RSS_EXPANDED", BarcodeFormat::RSS_EXPANDED) .value("UPC_A", BarcodeFormat::UPC_A) .value("UPC_E", BarcodeFormat::UPC_E) .value("UPC_EAN_EXTENSION", BarcodeFormat::UPC_EAN_EXTENSION) .value("FORMAT_COUNT", BarcodeFormat::FORMAT_COUNT) .value("INVALID", BarcodeFormat::INVALID) .export_values(); py::class_<ResultPoint>(m, "ResultPoint") .def_property_readonly("x", &ResultPoint::x) .def_property_readonly("y", &ResultPoint::y); py::class_<Result>(m, "Result") .def_property_readonly("valid", &Result::isValid) .def_property_readonly("text", &Result::text) .def_property_readonly("format", &Result::format) .def_property_readonly("points", &Result::resultPoints); m.def("barcode_format_from_str", &BarcodeFormatFromString, "Convert string to BarcodeFormat", py::arg("str")); m.def("barcode_formats_from_str", &barcode_formats_from_str, "Convert string to BarcodeFormats", py::arg("str")); m.def("read_barcode", &read_barcode, "Read (decode) a barcode from a numpy BGR or grayscale image array", py::arg("image"), py::arg("formats") = FormatList{}, py::arg("fastMode") = false, py::arg("tryRotate") = true, py::arg("hybridBinarizer") = true ); m.def("write_barcode", &write_barcode, "Write (encode) a text into a barcode and return numpy image array", py::arg("format"), py::arg("text"), py::arg("width") = 0, py::arg("height") = 0, py::arg("margin") = -1, py::arg("eccLevel") = -1 ); } <commit_msg>python: switch to new ReadBarcode API<commit_after>#include "BarcodeFormat.h" // Reader #include "ReadBarcode.h" // Writer #include "BitMatrix.h" #include "MultiFormatWriter.h" #include "TextUtfEncoding.h" #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <memory> #include <vector> using namespace ZXing; namespace py = pybind11; // Numpy array wrapper class for images (either BGR or GRAYSCALE) using Image = py::array_t<uint8_t, py::array::c_style>; template<typename OUT, typename IN> OUT narrow(IN in) { return static_cast<OUT>(in); } // The intension was to use the flag based BarcodeFormats here but that failed due to a pybind11 bug: // https://github.com/pybind/pybind11/issues/2221 using FormatList = std::vector<BarcodeFormat>; FormatList barcode_formats_from_str(const std::string& str) { auto formats = BarcodeFormatsFromString(str); return FormatList(formats.begin(), formats.end()); }; Result read_barcode(const Image& image, const FormatList& formats, bool fastMode, bool tryRotate, bool hybridBinarizer) { DecodeHints hints; hints.setTryHarder(!fastMode); hints.setTryRotate(tryRotate); hints.setPossibleFormats(formats); hints.setBinarizer(hybridBinarizer ? Binarizer::LocalAverage : Binarizer::GlobalHistogram); const auto height = narrow<int>(image.shape(0)); const auto width = narrow<int>(image.shape(1)); const auto channels = image.ndim() == 2 ? 1 : narrow<int>(image.shape(2)); const auto bytes = image.data(); const auto imgfmt = channels == 1 ? ImageFormat::Lum : ImageFormat::BGR; return ReadBarcode({bytes, width, height, imgfmt, width * channels, channels}, hints); } Image write_barcode(BarcodeFormat format, std::string text, int width, int height, int margin, int eccLevel) { auto writer = MultiFormatWriter(format).setMargin(margin).setEccLevel(eccLevel); auto bitmap = writer.encode(TextUtfEncoding::FromUtf8(text), width, height); auto result = Image({bitmap.width(), bitmap.height()}); auto r = result.mutable_unchecked<2>(); for (ssize_t y = 0; y < r.shape(0); y++) for (ssize_t x = 0; x < r.shape(1); x++) r(y, x) = bitmap.get(narrow<int>(x), narrow<int>(y)) ? 0 : 255; return result; } PYBIND11_MODULE(zxing, m) { m.doc() = "python bindings for zxing-cpp"; py::enum_<BarcodeFormat>(m, "BarcodeFormat") .value("AZTEC", BarcodeFormat::AZTEC) .value("CODABAR", BarcodeFormat::CODABAR) .value("CODE_39", BarcodeFormat::CODE_39) .value("CODE_93", BarcodeFormat::CODE_93) .value("CODE_128", BarcodeFormat::CODE_128) .value("DATA_MATRIX", BarcodeFormat::DATA_MATRIX) .value("EAN_8", BarcodeFormat::EAN_8) .value("EAN_13", BarcodeFormat::EAN_13) .value("ITF", BarcodeFormat::ITF) .value("MAXICODE", BarcodeFormat::MAXICODE) .value("PDF_417", BarcodeFormat::PDF_417) .value("QR_CODE", BarcodeFormat::QR_CODE) .value("RSS_14", BarcodeFormat::RSS_14) .value("RSS_EXPANDED", BarcodeFormat::RSS_EXPANDED) .value("UPC_A", BarcodeFormat::UPC_A) .value("UPC_E", BarcodeFormat::UPC_E) .value("UPC_EAN_EXTENSION", BarcodeFormat::UPC_EAN_EXTENSION) .value("FORMAT_COUNT", BarcodeFormat::FORMAT_COUNT) .value("INVALID", BarcodeFormat::INVALID) .export_values(); py::class_<ResultPoint>(m, "ResultPoint") .def_property_readonly("x", &ResultPoint::x) .def_property_readonly("y", &ResultPoint::y); py::class_<Result>(m, "Result") .def_property_readonly("valid", &Result::isValid) .def_property_readonly("text", &Result::text) .def_property_readonly("format", &Result::format) .def_property_readonly("points", &Result::resultPoints); m.def("barcode_format_from_str", &BarcodeFormatFromString, "Convert string to BarcodeFormat", py::arg("str")); m.def("barcode_formats_from_str", &barcode_formats_from_str, "Convert string to BarcodeFormats", py::arg("str")); m.def("read_barcode", &read_barcode, "Read (decode) a barcode from a numpy BGR or grayscale image array", py::arg("image"), py::arg("formats") = FormatList{}, py::arg("fastMode") = false, py::arg("tryRotate") = true, py::arg("hybridBinarizer") = true ); m.def("write_barcode", &write_barcode, "Write (encode) a text into a barcode and return numpy image array", py::arg("format"), py::arg("text"), py::arg("width") = 0, py::arg("height") = 0, py::arg("margin") = -1, py::arg("eccLevel") = -1 ); } <|endoftext|>
<commit_before>#ifndef TUDOCOMP_DRIVER_ALGORITHM_PARSER #define TUDOCOMP_DRIVER_ALGORITHM_PARSER #include <cstddef> #include <cstdint> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <istream> #include <map> #include <sstream> #include <streambuf> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <vector> #include <memory> #include <boost/utility/string_ref.hpp> #include <glog/logging.h> #include <tudocomp/Env.hpp> #include <tudocomp/Compressor.hpp> #include <tudocomp/util.h> namespace tudocomp_driver { using namespace tudocomp; /* AlgorithmSpec ::= IDENT '(' [AlgorithmArg,]* [AlgorithmArg] ')' AlgorithmArg ::= IDENT '=' string | string */ struct AlgorithmArg; struct AlgorithmSpec { std::string name; std::vector<AlgorithmArg> args; }; struct AlgorithmArg { std::string keyword; boost::variant<std::string, AlgorithmSpec> arg; }; class Err { std::string m_reason; std::shared_ptr<Err> m_prev; public: inline Err(std::string reason): m_reason(reason) { } inline Err(const Err& prev, std::string reason): Err(reason) { m_prev = std::make_shared<Err>(prev); } inline std::string reason() { return m_reason; } }; class Parser; template<class T> class Result { Parser* trail; boost::variant<T, Err> data; public: Result(Parser& parser, boost::variant<T, Err> data_): trail(&parser), data(data_) {} template<class U> using Fun = std::function<Result<U> (T)>; template<class U> inline Result<U> and_then(Fun<U> f); inline Result<T> or_else(Fun<Err> f); inline T unwrap(); inline Result<T> end_parse(); }; class Parser { boost::string_ref m_input; size_t m_current_pos; public: inline Parser(boost::string_ref input): m_input(input), m_current_pos(0) {} inline Parser(const Parser& other) = delete; inline Parser(Parser&& other) = delete; inline boost::string_ref cursor() const { return m_input.substr(m_current_pos); } //inline void end_parse_or_error() inline void skip_whitespace() { for (; m_current_pos < m_input.size(); m_current_pos++) { if (m_input[m_current_pos] != ' ') { return; } } return; } inline void skip(size_t i) { m_current_pos += i; } inline size_t cursor_pos() const { return m_current_pos; } inline boost::string_ref input() const { return m_input; } inline Result<boost::string_ref> parse_ident() { Parser& s = *this; s.skip_whitespace(); auto valid_first = [](uint8_t c) { return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }; auto valid_middle = [=](uint8_t c) { return valid_first(c) || (c >= '0' && c <= '9'); }; size_t i = 0; if (i < s.cursor().size() && valid_first(s.cursor()[i])) { for (i = 1; i < s.cursor().size() && valid_middle(s.cursor()[i]); i++) { } s.skip(i); auto r = s.cursor().substr(0, i); return ok<boost::string_ref>(r); } else { return err<boost::string_ref>("Expected an identifier"); } } inline Result<uint8_t> parse_char(uint8_t chr) { Parser& s = *this; s.skip_whitespace(); if (s.cursor().size() > 0 && uint8_t(s.cursor()[0]) == chr) { s.skip(1); return ok<uint8_t>(chr); } else { return err<uint8_t>(std::string("Expected char '") + char(chr) + "'" + ", found '" + s.cursor()[0] + "'"); } } template<class T> inline Result<T> ok(T t) { return Result<T> { *this, t, }; } template<class T> inline Result<T> err(std::string msg) { return Result<T> { *this, Err { msg }, }; } template<class T> inline Result<T> err(Err msg) { return Result<T> { *this, msg, }; } inline Result<std::vector<AlgorithmArg>> parse_args() { Parser& p = *this; return p.parse_char('(').and_then<std::vector<AlgorithmArg>>([&](uint8_t chr) { // Parse arguments here std::vector<AlgorithmArg> args; /*p.parse_ident().and_then<AlgorithmArg>([&](boost::string_ref arg_ident) { }).or_else<AlgorithmArg>([&](Err err) { });*/ return p.parse_char(')').and_then<std::vector<AlgorithmArg>>([&](uint8_t chr) { return p.ok(args); }); }); } inline Result<AlgorithmSpec> parse() { Parser& p = *this; return p.parse_ident().and_then<AlgorithmSpec>([&](boost::string_ref ident) { return p.parse_args().and_then<AlgorithmSpec>([&](std::vector<AlgorithmArg> args) { return p.ok(AlgorithmSpec { std::string(ident), args }); }); }).end_parse(); } }; template<class T> inline T Result<T>::unwrap() { struct visitor: public boost::static_visitor<T> { const Parser* m_trail; visitor(Parser* trail): m_trail(trail) { } T operator()(T& ok) const { return ok; } T operator()(Err& err) const { std::stringstream ss; ss << "\nParse error at #" << int(m_trail->cursor_pos()) << ":\n"; ss << m_trail->input() << "\n"; ss << std::setw(m_trail->cursor_pos()) << ""; ss << "^\n"; ss << err.reason() << "\n"; throw std::runtime_error(ss.str()); } }; return boost::apply_visitor(visitor(trail), data); } template<class T> template<class U> inline Result<U> Result<T>::and_then(Fun<U> f) { struct visitor: public boost::static_visitor<Result<U>> { // insert constructor here Fun<U> m_f; Parser* m_trail; visitor(Fun<U> f, Parser* trail): m_f(f), m_trail(trail) { } Result<U> operator()(T& ok) const { return m_f(ok); } Result<U> operator()(Err& err) const { return m_trail->err<U>(err); } }; return boost::apply_visitor(visitor(f, trail), data); } template<class T> inline Result<T> Result<T>::or_else(Fun<Err> f) { struct visitor: public boost::static_visitor<Result<T>> { // insert constructor here Fun<Err> m_f; Parser* m_trail; visitor(Fun<Err> f, Parser* trail): m_f(f), m_trail(trail) { } Result<T> operator()(T& ok) const { return m_trail->ok<T>(ok); } Result<T> operator()(Err& err) const { return m_f(err); } }; return boost::apply_visitor(visitor(f, trail), data); } template<class T> inline Result<T> Result<T>::end_parse() { return this->and_then<T>([&](T _t) { Parser& p = *trail; p.skip_whitespace(); if (p.cursor() == "") { return *this; } else { return p.err<T>("Expected end of input"); } }); } } #endif <commit_msg>More work on parser<commit_after>#ifndef TUDOCOMP_DRIVER_ALGORITHM_PARSER #define TUDOCOMP_DRIVER_ALGORITHM_PARSER #include <cstddef> #include <cstdint> #include <fstream> #include <functional> #include <iomanip> #include <iostream> #include <istream> #include <map> #include <sstream> #include <streambuf> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <vector> #include <memory> #include <boost/utility/string_ref.hpp> #include <glog/logging.h> #include <tudocomp/Env.hpp> #include <tudocomp/Compressor.hpp> #include <tudocomp/util.h> namespace tudocomp_driver { using namespace tudocomp; /* AlgorithmSpec ::= IDENT '(' [AlgorithmArg,]* [AlgorithmArg] ')' AlgorithmArg ::= IDENT '=' string | string */ struct AlgorithmArg; struct AlgorithmSpec { std::string name; std::vector<AlgorithmArg> args; }; struct AlgorithmArg { std::string keyword; boost::variant<std::string, AlgorithmSpec> arg; }; class Err { std::string m_reason; std::shared_ptr<Err> m_prev; public: inline Err(std::string reason): m_reason(reason) { } inline Err(const Err& prev, std::string reason): Err(reason) { m_prev = std::make_shared<Err>(prev); } inline std::string reason() { return m_reason; } }; class Parser; template<class T> class Result { Parser* trail; boost::variant<T, Err> data; public: Result(Parser& parser, boost::variant<T, Err> data_): trail(&parser), data(data_) {} template<class A, class R> using Fun = std::function<Result<R> (A)>; template<class U> inline Result<U> and_then(Fun<T, U> f); inline Result<T> or_else(Fun<Err, T> f); inline T unwrap(); inline Result<T> end_parse(); inline bool is_ok() { struct visitor: public boost::static_visitor<bool> { bool operator()(T& ok) const { return true; } bool operator()(Err& err) const { return false; } }; return boost::apply_visitor(visitor(), data); } inline bool is_err() { return !is_ok(); } }; class Parser { boost::string_ref m_input; size_t m_current_pos; public: inline Parser(boost::string_ref input): m_input(input), m_current_pos(0) {} inline Parser(const Parser& other) = delete; inline Parser(Parser&& other) = delete; inline boost::string_ref cursor() const { return m_input.substr(m_current_pos); } //inline void end_parse_or_error() inline void skip_whitespace() { for (; m_current_pos < m_input.size(); m_current_pos++) { if (m_input[m_current_pos] != ' ') { return; } } return; } inline void skip(size_t i) { m_current_pos += i; } inline size_t cursor_pos() const { return m_current_pos; } inline boost::string_ref input() const { return m_input; } inline Result<boost::string_ref> parse_ident() { Parser& s = *this; s.skip_whitespace(); auto valid_first = [](uint8_t c) { return (c == '_') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); }; auto valid_middle = [=](uint8_t c) { return valid_first(c) || (c >= '0' && c <= '9'); }; size_t i = 0; if (i < s.cursor().size() && valid_first(s.cursor()[i])) { for (i = 1; i < s.cursor().size() && valid_middle(s.cursor()[i]); i++) { } s.skip(i); auto r = s.cursor().substr(0, i); return ok<boost::string_ref>(r); } else { return err<boost::string_ref>("Expected an identifier"); } } inline Result<uint8_t> parse_char(uint8_t chr) { Parser& s = *this; s.skip_whitespace(); if (s.cursor().size() > 0 && uint8_t(s.cursor()[0]) == chr) { s.skip(1); return ok<uint8_t>(chr); } else { return err<uint8_t>(std::string("Expected char '") + char(chr) + "'" + ", found '" + s.cursor()[0] + "'"); } } template<class T> inline Result<T> ok(T t) { return Result<T> { *this, t, }; } template<class T> inline Result<T> err(std::string msg) { return Result<T> { *this, Err { msg }, }; } template<class T> inline Result<T> err(Err msg) { return Result<T> { *this, msg, }; } inline Result<AlgorithmArg> parse_arg(boost::string_ref keyword = "") { Parser& p = *this; return p.parse_ident().and_then<AlgorithmArg>([&](boost::string_ref arg_ident) { // "ident ..." case if (keyword == "") { auto r = p.parse_char('=').and_then<AlgorithmArg>([&](uint8_t chr) { // "ident = ..." case return p.parse_arg(arg_ident); }); if (r.is_ok()) { return r; } } return p.parse_args().and_then<AlgorithmArg>([&](std::vector<AlgorithmArg> args) { // "ident(...) ..." case return p.ok(AlgorithmArg { std::string(keyword), AlgorithmSpec { std::string(arg_ident), args } }); }).or_else([&](Err err) { // "ident ..." fallback case return p.ok<AlgorithmArg>(AlgorithmArg { std::string(keyword), std::string(arg_ident) }); }); });//.or_else<AlgorithmArg>([&](Err err) {}); } inline Result<std::vector<AlgorithmArg>> parse_args() { Parser& p = *this; return p.parse_char('(').and_then<std::vector<AlgorithmArg>>([&](uint8_t chr) { // Parse arguments here std::vector<AlgorithmArg> args; p.parse_arg(); return p.parse_char(')').and_then<std::vector<AlgorithmArg>>([&](uint8_t chr) { return p.ok(args); }); }); } inline Result<AlgorithmSpec> parse() { Parser& p = *this; return p.parse_ident().and_then<AlgorithmSpec>([&](boost::string_ref ident) { return p.parse_args().and_then<AlgorithmSpec>([&](std::vector<AlgorithmArg> args) { return p.ok(AlgorithmSpec { std::string(ident), args }); }); }).end_parse(); } }; template<class T> inline T Result<T>::unwrap() { struct visitor: public boost::static_visitor<T> { const Parser* m_trail; visitor(Parser* trail): m_trail(trail) { } T operator()(T& ok) const { return ok; } T operator()(Err& err) const { std::stringstream ss; ss << "\nParse error at #" << int(m_trail->cursor_pos()) << ":\n"; ss << m_trail->input() << "\n"; ss << std::setw(m_trail->cursor_pos()) << ""; ss << "^\n"; ss << err.reason() << "\n"; throw std::runtime_error(ss.str()); } }; return boost::apply_visitor(visitor(trail), data); } template<class T> template<class U> inline Result<U> Result<T>::and_then(Fun<T, U> f) { struct visitor: public boost::static_visitor<Result<U>> { // insert constructor here Fun<T, U> m_f; Parser* m_trail; visitor(Fun<T, U> f, Parser* trail): m_f(f), m_trail(trail) { } Result<U> operator()(T& ok) const { return m_f(ok); } Result<U> operator()(Err& err) const { return m_trail->err<U>(err); } }; return boost::apply_visitor(visitor(f, trail), data); } template<class T> inline Result<T> Result<T>::or_else(Fun<Err, T> f) { struct visitor: public boost::static_visitor<Result<T>> { // insert constructor here Fun<Err, T> m_f; Parser* m_trail; visitor(Fun<Err, T> f, Parser* trail): m_f(f), m_trail(trail) { } Result<T> operator()(T& ok) const { return m_trail->ok<T>(ok); } Result<T> operator()(Err& err) const { return m_f(err); } }; return boost::apply_visitor(visitor(f, trail), data); } template<class T> inline Result<T> Result<T>::end_parse() { return this->and_then<T>([&](T _t) { Parser& p = *trail; p.skip_whitespace(); if (p.cursor() == "") { return *this; } else { return p.err<T>("Expected end of input"); } }); } } #endif <|endoftext|>
<commit_before>// // invite.hpp // ********* // // Copyright (c) 2020 Sharon Fox (sharon at xandium dot io) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #include "aegis/config.hpp" #include "aegis/snowflake.hpp" #include <nlohmann/json.hpp> namespace aegis { namespace gateway { namespace objects { enum target_user_type { STREAM = 1 }; struct invite_metadata_t { int32_t uses; /**< # of times this invite has been used */ int32_t max_uses; /**< Max # of times this invite can be used */ int32_t max_age; /**< Duration (in seconds) after which the invite expires */ bool temporary = false; /**< Whether this invite only grants temporary membership */ std::string created_at; /**< ISO8601 timestamp of when this invite was created */ }; struct invite; /// \cond TEMPLATES void from_json(const nlohmann::json& j, invite& m); void to_json(nlohmann::json& j, const invite& m); /// \endcond /// Discord Invite Object struct invite { invite(const std::string& _json, aegis::core* bot) noexcept { from_json(nlohmann::json::parse(_json), *this); } invite(const nlohmann::json& _json, aegis::core* bot) noexcept { from_json(_json, *this); } invite(aegis::core* bot) noexcept {} invite() noexcept {} std::string code; /**< Invite code (unique ID) */ snowflake _guild; /**< Guild this invite is for */ snowflake _channel; /**< Channel this invite is for */ snowflake inviter; /**< User that created the invite */ snowflake target_user; /**< Target user for this invite */ target_user_type target_type = STREAM; /**< Type of user target for this invite */ int32_t approximate_presence_count = 0; /**< Approximate count of online members of guild, requires target_user be set */ int32_t approximate_member_count = 0; /**< Approximate count of total members of guild */ invite_metadata_t metadata; /**< Extra information about invite */ }; /// \cond TEMPLATES inline void from_json(const nlohmann::json& j, invite& m) { m.code = j["code"]; if (j.count("guild") && !j["guild"].is_null()) m._guild = j["guild"]["id"]; if (j.count("channel") && !j["channel"].is_null()) m._channel = j["channel"]["id"]; if (j.count("inviter") && !j["inviter"].is_null()) m.inviter = j["inviter"]["id"]; if (j.count("target_user") && !j["target_user"].is_null()) m.target_user = j["target_user"]["id"]; if (j.count("target_user_type") && !j["target_user_type"].is_null()) m.target_user_type = j["target_user_type"]; if (j.count("approximate_presence_count") && !j["approximate_presence_count"].is_null()) m.approximate_presence_count = j["approximate_presence_count"]; if (j.count("approximate_member_count") && !j["approximate_member_count"].is_null()) m.approximate_member_count = j["approximate_member_count"]; // Metadata if (j.count("uses") && !j["uses"].is_null()) m.metadata.uses = j["uses"]; if (j.count("max_uses") && !j["max_uses"].is_null()) m.metadata.max_uses = j["max_uses"]; if (j.count("max_age") && !j["max_age"].is_null()) m.metadata.max_age = j["max_age"]; if (j.count("temporary") && !j["temporary"].is_null()) m.metadata.temporary = j["temporary"]; if (j.count("created_at") && !j["created_at"].is_null()) m.metadata.created_at = j["created_at"]; } inline void to_json(nlohmann::json& j, const invite& m) { j["code"] = m.code; j["guild"] = m._guild; j["channel"] = m._channel; j["inviter"] = m.inviter; j["target_user"] = m.target_user; j["target_user_type"] = m.target_user_type; j["approximate_presence_count"] = m.approximate_presence_count; j["approximate_member_count"] = m.approximate_member_count; // Metadata j["uses"] = m.metadata.uses; j["max_uses"] = m.metadata.max_uses; j["max_age"] = m.metadata.max_age; j["temporary"] = m.metadata.temporary; j["created_at"] = m.metadata.created_at; } /// \endcond } } } <commit_msg>Further fix dumb mistakes<commit_after>// // invite.hpp // ********* // // Copyright (c) 2020 Sharon Fox (sharon at xandium dot io) // // Distributed under the MIT License. (See accompanying file LICENSE) // #pragma once #include "aegis/config.hpp" #include "aegis/snowflake.hpp" #include <nlohmann/json.hpp> namespace aegis { namespace gateway { namespace objects { enum target_user_type { STREAM = 1 }; struct invite_metadata_t { int32_t uses; /**< # of times this invite has been used */ int32_t max_uses; /**< Max # of times this invite can be used */ int32_t max_age; /**< Duration (in seconds) after which the invite expires */ bool temporary = false; /**< Whether this invite only grants temporary membership */ std::string created_at; /**< ISO8601 timestamp of when this invite was created */ }; struct invite; /// \cond TEMPLATES void from_json(const nlohmann::json& j, invite& m); void to_json(nlohmann::json& j, const invite& m); /// \endcond /// Discord Invite Object struct invite { invite(const std::string& _json, aegis::core* bot) noexcept { from_json(nlohmann::json::parse(_json), *this); } invite(const nlohmann::json& _json, aegis::core* bot) noexcept { from_json(_json, *this); } invite(aegis::core* bot) noexcept {} invite() noexcept {} std::string code; /**< Invite code (unique ID) */ snowflake _guild; /**< Guild this invite is for */ snowflake _channel; /**< Channel this invite is for */ snowflake inviter; /**< User that created the invite */ snowflake target_user; /**< Target user for this invite */ target_user_type target_type = STREAM; /**< Type of user target for this invite */ int32_t approximate_presence_count = 0; /**< Approximate count of online members of guild, requires target_user be set */ int32_t approximate_member_count = 0; /**< Approximate count of total members of guild */ invite_metadata_t metadata; /**< Extra information about invite */ }; /// \cond TEMPLATES inline void from_json(const nlohmann::json& j, invite& m) { m.code = j["code"]; if (j.count("guild") && !j["guild"].is_null()) m._guild = j["guild"]["id"]; if (j.count("channel") && !j["channel"].is_null()) m._channel = j["channel"]["id"]; if (j.count("inviter") && !j["inviter"].is_null()) m.inviter = j["inviter"]["id"]; if (j.count("target_user") && !j["target_user"].is_null()) m.target_user = j["target_user"]["id"]; if (j.count("target_user_type") && !j["target_user_type"].is_null()) m.target_type = j["target_user_type"]; if (j.count("approximate_presence_count") && !j["approximate_presence_count"].is_null()) m.approximate_presence_count = j["approximate_presence_count"]; if (j.count("approximate_member_count") && !j["approximate_member_count"].is_null()) m.approximate_member_count = j["approximate_member_count"]; // Metadata if (j.count("uses") && !j["uses"].is_null()) m.metadata.uses = j["uses"]; if (j.count("max_uses") && !j["max_uses"].is_null()) m.metadata.max_uses = j["max_uses"]; if (j.count("max_age") && !j["max_age"].is_null()) m.metadata.max_age = j["max_age"]; if (j.count("temporary") && !j["temporary"].is_null()) m.metadata.temporary = j["temporary"]; if (j.count("created_at") && !j["created_at"].is_null()) m.metadata.created_at = j["created_at"]; } inline void to_json(nlohmann::json& j, const invite& m) { j["code"] = m.code; j["guild"] = m._guild; j["channel"] = m._channel; j["inviter"] = m.inviter; j["target_user"] = m.target_user; j["target_user_type"] = m.target_type; j["approximate_presence_count"] = m.approximate_presence_count; j["approximate_member_count"] = m.approximate_member_count; // Metadata j["uses"] = m.metadata.uses; j["max_uses"] = m.metadata.max_uses; j["max_age"] = m.metadata.max_age; j["temporary"] = m.metadata.temporary; j["created_at"] = m.metadata.created_at; } /// \endcond } } } <|endoftext|>
<commit_before><commit_msg>Fixed incorrect packet buffer sizes<commit_after><|endoftext|>
<commit_before>/*! \file static_object.hpp \brief Internal polymorphism static object support \ingroup Internal */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant All rights reserved. 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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 CEREAL_DETAILS_STATIC_OBJECT_HPP_ #define CEREAL_DETAILS_STATIC_OBJECT_HPP_ #include "cereal/macros.hpp" #if CEREAL_THREAD_SAFE #include <mutex> #endif //! Prevent link optimization from removing non-referenced static objects /*! Especially for polymorphic support, we create static objects which may not ever be explicitly referenced. Most linkers will detect this and remove the code causing various unpleasant runtime errors. These macros, adopted from Boost (see force_include.hpp) prevent this (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . 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) */ #ifdef _MSC_VER # define CEREAL_DLL_EXPORT __declspec(dllexport) # define CEREAL_USED #else // clang or gcc # define CEREAL_DLL_EXPORT # define CEREAL_USED __attribute__ ((__used__)) #endif namespace cereal { namespace detail { //! A static, pre-execution object /*! This class will create a single copy (singleton) of some type and ensures that merely referencing this type will cause it to be instantiated and initialized pre-execution. For example, this is used heavily in the polymorphic pointer serialization mechanisms to bind various archive types with different polymorphic classes */ template <class T> class CEREAL_DLL_EXPORT StaticObject { private: static T & create() { static T t; //! Forces instantiation at pre-execution time (void)instance; return t; } StaticObject( StaticObject const & /*other*/ ) {} public: static T & getInstance() { return create(); } //! A class that acts like std::lock_guard class LockGuard { #if CEREAL_THREAD_SAFE public: LockGuard(std::mutex & m) : lock(m) {} private: std::unique_lock<std::mutex> lock; #else public: LockGuard(LockGuard const &) = default; // prevents implicit copy ctor warning ~LockGuard() CEREAL_NOEXCEPT {} // prevents variable not used #endif }; //! Attempts to lock this static object for the current scope /*! @note This function is a no-op if cereal is not compiled with thread safety enabled (CEREAL_THREAD_SAFE = 1). This function returns an object that holds a lock for this StaticObject that will release its lock upon destruction. This call will block until the lock is available. */ static LockGuard lock() { #if CEREAL_THREAD_SAFE static std::mutex instanceMutex; return LockGuard{instanceMutex}; #else return LockGuard{}; #endif } private: static T & instance; }; template <class T> T & StaticObject<T>::instance = StaticObject<T>::create(); } // namespace detail } // namespace cereal #endif // CEREAL_DETAILS_STATIC_OBJECT_HPP_ <commit_msg>Fix spacing #470<commit_after>/*! \file static_object.hpp \brief Internal polymorphism static object support \ingroup Internal */ /* Copyright (c) 2014, Randolph Voorhies, Shane Grant All rights reserved. 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 cereal 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 RANDOLPH VOORHIES OR SHANE GRANT 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 CEREAL_DETAILS_STATIC_OBJECT_HPP_ #define CEREAL_DETAILS_STATIC_OBJECT_HPP_ #include "cereal/macros.hpp" #if CEREAL_THREAD_SAFE #include <mutex> #endif //! Prevent link optimization from removing non-referenced static objects /*! Especially for polymorphic support, we create static objects which may not ever be explicitly referenced. Most linkers will detect this and remove the code causing various unpleasant runtime errors. These macros, adopted from Boost (see force_include.hpp) prevent this (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . 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) */ #ifdef _MSC_VER # define CEREAL_DLL_EXPORT __declspec(dllexport) # define CEREAL_USED #else // clang or gcc # define CEREAL_DLL_EXPORT # define CEREAL_USED __attribute__ ((__used__)) #endif namespace cereal { namespace detail { //! A static, pre-execution object /*! This class will create a single copy (singleton) of some type and ensures that merely referencing this type will cause it to be instantiated and initialized pre-execution. For example, this is used heavily in the polymorphic pointer serialization mechanisms to bind various archive types with different polymorphic classes */ template <class T> class CEREAL_DLL_EXPORT StaticObject { private: static T & create() { static T t; //! Forces instantiation at pre-execution time (void)instance; return t; } StaticObject( StaticObject const & /*other*/ ) {} public: static T & getInstance() { return create(); } //! A class that acts like std::lock_guard class LockGuard { #if CEREAL_THREAD_SAFE public: LockGuard(std::mutex & m) : lock(m) {} private: std::unique_lock<std::mutex> lock; #else public: LockGuard(LockGuard const &) = default; // prevents implicit copy ctor warning ~LockGuard() CEREAL_NOEXCEPT {} // prevents variable not used #endif }; //! Attempts to lock this static object for the current scope /*! @note This function is a no-op if cereal is not compiled with thread safety enabled (CEREAL_THREAD_SAFE = 1). This function returns an object that holds a lock for this StaticObject that will release its lock upon destruction. This call will block until the lock is available. */ static LockGuard lock() { #if CEREAL_THREAD_SAFE static std::mutex instanceMutex; return LockGuard{instanceMutex}; #else return LockGuard{}; #endif } private: static T & instance; }; template <class T> T & StaticObject<T>::instance = StaticObject<T>::create(); } // namespace detail } // namespace cereal #endif // CEREAL_DETAILS_STATIC_OBJECT_HPP_ <|endoftext|>
<commit_before>#ifndef COMBINATION_KERNEL_CONTAINER_HPP_ #define COMBINATION_KERNEL_CONTAINER_HPP_ #include "linalg.hpp" #include <algorithm> #include <vector> /** * @brief A combination container for incremental kernel updates * */ template <typename NT> struct Combination_kernel_container { /** * The generators of the zonotope */ const std::vector<std::vector<NT> >& generators; /** * An integer in 1..n */ const int MAX_SIZE; /** * A sorted stack of up to MAX_SIZE integers in 0..n-1, that * can still be extended to include MAX_SIZE integers. */ std::vector<int> elements; /** * The kernel of generators[combination] */ std::vector<std::vector<NT> > kernel; /** * @brief Construct an empty combination with room for up to * MAX_SIZE elements. */ Combination_kernel_container( const std::vector<std::vector<NT> >& generators, const int MAX_SIZE ) : generators( generators ), MAX_SIZE( MAX_SIZE ) { using std::vector; const int d = generators[0].size(); kernel = vector<vector<NT> > ( d, vector<NT>( d, 0 ) ); for ( int i = 0; i < d; ++i ) { kernel[i][i] = 1; } } /** * @brief Extend the combination to include i * * @param i an integer in (top() + 1) .. neighbor_upper_bound() */ void extend(const int i) { elements.push_back(i); kernel = update_kernel<NT> ( kernel, generators[i] ); } /** * @brief The largest value in the combination, or -1 if empty */ int back() const { if (!elements.size()) { return -1; } return elements.back(); } std::vector<int>::size_type size() const { return elements.size(); } int neighbor_upper_bound() const { const int n = generators.size(); const int k = elements.size(); return (n - (MAX_SIZE - k) + 1); } /** * @brief true iff i is in the combination * * Performs an O(log(k)) search for i in a combination of size k. */ bool find(int i) const { return std::binary_search(elements.begin(), elements.end(), i); } /** * @brief true iff the combination is independent */ bool is_valid() const { const int d = generators[0].size(); return ( size() + kernel.size() == d ); } }; #endif <commit_msg>disable a small optimization to match my thesis<commit_after>#ifndef COMBINATION_KERNEL_CONTAINER_HPP_ #define COMBINATION_KERNEL_CONTAINER_HPP_ #include "linalg.hpp" #include <algorithm> #include <vector> /** * @brief A combination container for incremental kernel updates * */ template <typename NT> struct Combination_kernel_container { /** * The generators of the zonotope */ const std::vector<std::vector<NT> >& generators; /** * An integer in 1..n */ const int MAX_SIZE; /** * A sorted stack of up to MAX_SIZE integers in 0..n-1, that * can still be extended to include MAX_SIZE integers. */ std::vector<int> elements; /** * The kernel of generators[combination] */ std::vector<std::vector<NT> > kernel; /** * @brief Construct an empty combination with room for up to * MAX_SIZE elements. */ Combination_kernel_container( const std::vector<std::vector<NT> >& generators, const int MAX_SIZE ) : generators( generators ), MAX_SIZE( MAX_SIZE ) { using std::vector; const int d = generators[0].size(); kernel = vector<vector<NT> > ( d, vector<NT>( d, 0 ) ); for ( int i = 0; i < d; ++i ) { kernel[i][i] = 1; } } /** * @brief Extend the combination to include i * * @param i an integer in (top() + 1) .. neighbor_upper_bound() */ void extend(const int i) { elements.push_back(i); kernel = update_kernel<NT> ( kernel, generators[i] ); } /** * @brief The largest value in the combination, or -1 if empty */ int back() const { if (!elements.size()) { return -1; } return elements.back(); } std::vector<int>::size_type size() const { return elements.size(); } int neighbor_upper_bound() const { const int n = generators.size(); const int k = elements.size(); return n; // return (n - (MAX_SIZE - k) + 1); } /** * @brief true iff i is in the combination * * Performs an O(log(k)) search for i in a combination of size k. */ bool find(int i) const { return std::binary_search(elements.begin(), elements.end(), i); } /** * @brief true iff the combination is independent */ bool is_valid() const { const int d = generators[0].size(); return ( size() + kernel.size() == d ); } }; #endif <|endoftext|>
<commit_before>// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "orient_outward_ao.h" #include "../per_face_normals.h" #include "../doublearea.h" #include "../random_dir.h" #include "EmbreeIntersector.h" #include <iostream> #include <random> #include <ctime> #include <limits> template < typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedFF, typename DerivedI> IGL_INLINE void igl::orient_outward_ao( const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, const Eigen::PlainObjectBase<DerivedC> & C, const int min_num_rays_per_component, const int total_num_rays, Eigen::PlainObjectBase<DerivedFF> & FF, Eigen::PlainObjectBase<DerivedI> & I) { using namespace Eigen; using namespace std; assert(C.rows() == F.rows()); assert(F.cols() == 3); assert(V.cols() == 3); EmbreeIntersector ei; ei.init(V.template cast<float>(),F); // number of faces const int m = F.rows(); // number of patches const int num_cc = C.maxCoeff()+1; I.resize(num_cc); if(&FF != &F) { FF = F; } // face normal MatrixXd N; per_face_normals(V,F,N); // face area Matrix<typename DerivedV::Scalar,Dynamic,1> A; doublearea(V,F,A); double area_min = numeric_limits<double>::max(); for (int f = 0; f < m; ++f) { area_min = A(f) != 0 && A(f) < area_min ? A(f) : area_min; } double area_total = A.sum(); // determine number of rays per component according to its area VectorXd area_per_component; area_per_component.setZero(num_cc); for (int f = 0; f < m; ++f) { area_per_component(C(f)) += A(f); } VectorXi num_rays_per_component; num_rays_per_component.setZero(num_cc); for (int c = 0; c < num_cc; ++c) { num_rays_per_component(c) = max<int>(min_num_rays_per_component, static_cast<int>(total_num_rays * area_per_component(c) / area_total)); } // generate all the rays //cout << "generating rays... "; uniform_real_distribution<float> rdist; mt19937 prng; prng.seed(time(nullptr)); vector<int > ray_face; vector<Vector3f> ray_ori; vector<Vector3f> ray_dir; ray_face.reserve(total_num_rays); ray_ori .reserve(total_num_rays); ray_dir .reserve(total_num_rays); for (int c = 0; c < num_cc; ++c) { if (area_per_component[c] == 0) { continue; } vector<int> CF; // set of faces per component vector<int> CF_area; for (int f = 0; f < m; ++f) { if (C(f)==c) { CF.push_back(f); CF_area.push_back(static_cast<int>(100 * A(f) / area_min)); } } // discrete distribution for random selection of faces with probability proportional to their areas auto ddist_func = [&] (double i) { return CF_area[static_cast<int>(i)]; }; discrete_distribution<int> ddist(CF.size(), 0, CF.size(), ddist_func); // simple ctor of (Iter, Iter) not provided by the stupid VC11 impl... for (int i = 0; i < num_rays_per_component[c]; ++i) { int f = CF[ddist(prng)]; // select face with probability proportional to face area float t0 = rdist(prng); // random barycentric coordinate float t1 = rdist(prng); float t2 = rdist(prng); float t_sum = t0 + t1 + t2; t0 /= t_sum; t1 /= t_sum; t2 /= t_sum; Vector3f p = t0 * V.row(F(f,0)).template cast<float>().eval() // be careful with the index!!! + t1 * V.row(F(f,1)).template cast<float>().eval() + t2 * V.row(F(f,2)).template cast<float>().eval(); Vector3f n = N.row(f).cast<float>(); // random direction in hemisphere around n (avoid too grazing angle) Vector3f d; while (true) { d = random_dir().cast<float>(); float ndotd = n.dot(d); if (fabsf(ndotd) < 0.1f) { continue; } if (ndotd < 0) { d *= -1.0f; } break; } ray_face.push_back(f); ray_ori .push_back(p); ray_dir .push_back(d); } } // per component voting: first=front, second=back vector<pair<float, float>> C_vote_distance(num_cc, make_pair(0, 0)); // sum of distance between ray origin and intersection vector<pair<int , int >> C_vote_infinity(num_cc, make_pair(0, 0)); // number of rays reaching infinity //cout << "shooting rays... "; #pragma omp parallel for for (int i = 0; i < (int)ray_face.size(); ++i) { int f = ray_face[i]; Vector3f o = ray_ori [i]; Vector3f d = ray_dir [i]; int c = C(f); // shoot ray toward front & back vector<Hit> hits_front; vector<Hit> hits_back; int num_rays_front; int num_rays_back; ei.intersectRay(o, d, hits_front, num_rays_front); ei.intersectRay(o, -d, hits_back , num_rays_back ); if (!hits_front.empty() && hits_front[0].id == f) hits_front.erase(hits_front.begin()); if (!hits_back .empty() && hits_back [0].id == f) hits_back .erase(hits_back .begin()); if (hits_front.empty()) { #pragma omp atomic C_vote_infinity[c].first++; } else { #pragma omp atomic C_vote_distance[c].first += hits_front[0].t; } if (hits_back.empty()) { #pragma omp atomic C_vote_infinity[c].second++; } else { #pragma omp atomic C_vote_distance[c].second += hits_back[0].t; } } for(int c = 0;c<num_cc;c++) { I(c) = C_vote_infinity[c].first == C_vote_infinity[c].second && C_vote_distance[c].first < C_vote_distance[c].second || C_vote_infinity[c].first < C_vote_infinity[c].second; } // flip according to I for(int f = 0;f<m;f++) { if(I(C(f))) { FF.row(f) = FF.row(f).reverse().eval(); } } //cout << "done!\n"; } // Call with default parameters template < typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedFF, typename DerivedI> IGL_INLINE void igl::orient_outward_ao( const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, const Eigen::PlainObjectBase<DerivedC> & C, Eigen::PlainObjectBase<DerivedFF> & FF, Eigen::PlainObjectBase<DerivedI> & I) { return orient_outward_ao(V, F, C, 100, F.rows() * 100, FF, I); } #ifndef IGL_HEADER_ONLY // Explicit template specialization template void igl::orient_outward_ao<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif <commit_msg>parentheses added to improve clarity<commit_after>// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "orient_outward_ao.h" #include "../per_face_normals.h" #include "../doublearea.h" #include "../random_dir.h" #include "EmbreeIntersector.h" #include <iostream> #include <random> #include <ctime> #include <limits> template < typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedFF, typename DerivedI> IGL_INLINE void igl::orient_outward_ao( const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, const Eigen::PlainObjectBase<DerivedC> & C, const int min_num_rays_per_component, const int total_num_rays, Eigen::PlainObjectBase<DerivedFF> & FF, Eigen::PlainObjectBase<DerivedI> & I) { using namespace Eigen; using namespace std; assert(C.rows() == F.rows()); assert(F.cols() == 3); assert(V.cols() == 3); EmbreeIntersector ei; ei.init(V.template cast<float>(),F); // number of faces const int m = F.rows(); // number of patches const int num_cc = C.maxCoeff()+1; I.resize(num_cc); if(&FF != &F) { FF = F; } // face normal MatrixXd N; per_face_normals(V,F,N); // face area Matrix<typename DerivedV::Scalar,Dynamic,1> A; doublearea(V,F,A); double area_min = numeric_limits<double>::max(); for (int f = 0; f < m; ++f) { area_min = A(f) != 0 && A(f) < area_min ? A(f) : area_min; } double area_total = A.sum(); // determine number of rays per component according to its area VectorXd area_per_component; area_per_component.setZero(num_cc); for (int f = 0; f < m; ++f) { area_per_component(C(f)) += A(f); } VectorXi num_rays_per_component; num_rays_per_component.setZero(num_cc); for (int c = 0; c < num_cc; ++c) { num_rays_per_component(c) = max<int>(min_num_rays_per_component, static_cast<int>(total_num_rays * area_per_component(c) / area_total)); } // generate all the rays //cout << "generating rays... "; uniform_real_distribution<float> rdist; mt19937 prng; prng.seed(time(nullptr)); vector<int > ray_face; vector<Vector3f> ray_ori; vector<Vector3f> ray_dir; ray_face.reserve(total_num_rays); ray_ori .reserve(total_num_rays); ray_dir .reserve(total_num_rays); for (int c = 0; c < num_cc; ++c) { if (area_per_component[c] == 0) { continue; } vector<int> CF; // set of faces per component vector<int> CF_area; for (int f = 0; f < m; ++f) { if (C(f)==c) { CF.push_back(f); CF_area.push_back(static_cast<int>(100 * A(f) / area_min)); } } // discrete distribution for random selection of faces with probability proportional to their areas auto ddist_func = [&] (double i) { return CF_area[static_cast<int>(i)]; }; discrete_distribution<int> ddist(CF.size(), 0, CF.size(), ddist_func); // simple ctor of (Iter, Iter) not provided by the stupid VC11 impl... for (int i = 0; i < num_rays_per_component[c]; ++i) { int f = CF[ddist(prng)]; // select face with probability proportional to face area float t0 = rdist(prng); // random barycentric coordinate float t1 = rdist(prng); float t2 = rdist(prng); float t_sum = t0 + t1 + t2; t0 /= t_sum; t1 /= t_sum; t2 /= t_sum; Vector3f p = t0 * V.row(F(f,0)).template cast<float>().eval() // be careful with the index!!! + t1 * V.row(F(f,1)).template cast<float>().eval() + t2 * V.row(F(f,2)).template cast<float>().eval(); Vector3f n = N.row(f).cast<float>(); // random direction in hemisphere around n (avoid too grazing angle) Vector3f d; while (true) { d = random_dir().cast<float>(); float ndotd = n.dot(d); if (fabsf(ndotd) < 0.1f) { continue; } if (ndotd < 0) { d *= -1.0f; } break; } ray_face.push_back(f); ray_ori .push_back(p); ray_dir .push_back(d); } } // per component voting: first=front, second=back vector<pair<float, float>> C_vote_distance(num_cc, make_pair(0, 0)); // sum of distance between ray origin and intersection vector<pair<int , int >> C_vote_infinity(num_cc, make_pair(0, 0)); // number of rays reaching infinity //cout << "shooting rays... "; #pragma omp parallel for for (int i = 0; i < (int)ray_face.size(); ++i) { int f = ray_face[i]; Vector3f o = ray_ori [i]; Vector3f d = ray_dir [i]; int c = C(f); // shoot ray toward front & back vector<Hit> hits_front; vector<Hit> hits_back; int num_rays_front; int num_rays_back; ei.intersectRay(o, d, hits_front, num_rays_front); ei.intersectRay(o, -d, hits_back , num_rays_back ); if (!hits_front.empty() && hits_front[0].id == f) hits_front.erase(hits_front.begin()); if (!hits_back .empty() && hits_back [0].id == f) hits_back .erase(hits_back .begin()); if (hits_front.empty()) { #pragma omp atomic C_vote_infinity[c].first++; } else { #pragma omp atomic C_vote_distance[c].first += hits_front[0].t; } if (hits_back.empty()) { #pragma omp atomic C_vote_infinity[c].second++; } else { #pragma omp atomic C_vote_distance[c].second += hits_back[0].t; } } for(int c = 0;c<num_cc;c++) { I(c) = (C_vote_infinity[c].first == C_vote_infinity[c].second && C_vote_distance[c].first < C_vote_distance[c].second) || C_vote_infinity[c].first < C_vote_infinity[c].second; } // flip according to I for(int f = 0;f<m;f++) { if(I(C(f))) { FF.row(f) = FF.row(f).reverse().eval(); } } //cout << "done!\n"; } // Call with default parameters template < typename DerivedV, typename DerivedF, typename DerivedC, typename DerivedFF, typename DerivedI> IGL_INLINE void igl::orient_outward_ao( const Eigen::PlainObjectBase<DerivedV> & V, const Eigen::PlainObjectBase<DerivedF> & F, const Eigen::PlainObjectBase<DerivedC> & C, Eigen::PlainObjectBase<DerivedFF> & FF, Eigen::PlainObjectBase<DerivedI> & I) { return orient_outward_ao(V, F, C, 100, F.rows() * 100, FF, I); } #ifndef IGL_HEADER_ONLY // Explicit template specialization template void igl::orient_outward_ao<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, 1, 0, -1, 1> >(Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> > const&, int, int, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 1, 0, -1, 1> >&); #endif <|endoftext|>
<commit_before>#include "CubemapFace.h" boost::interprocess::offset_ptr<Cubemap> cubemap; CubemapFace::CubemapFace(boost::uint32_t width, boost::uint32_t height, int index, AVPixelFormat format, boost::chrono::system_clock::time_point presentationTime, void* pixels, Allocator& allocator) : allocator(allocator), width(width), height(height), index(index), format(format), presentationTime(presentationTime), pixels(pixels) { } CubemapFace::~CubemapFace() { allocator.deallocate(pixels.get(), width * height * 4); } boost::uint32_t CubemapFace::getWidth() { return width; } boost::uint32_t CubemapFace::getHeight() { return height; } int CubemapFace::getIndex() { return index; } AVPixelFormat CubemapFace::getFormat() { return format; } boost::chrono::system_clock::time_point CubemapFace::getPresentationTime() { return presentationTime; } void* CubemapFace::getPixels() { return pixels.get(); } boost::interprocess::interprocess_mutex& CubemapFace::getMutex() { return mutex; } boost::interprocess::interprocess_condition& CubemapFace::getNewPixelsCondition() { return newPixelsCondition; } void CubemapFace::setPresentationTime(boost::chrono::system_clock::time_point presentationTime) { this->presentationTime = presentationTime; } CubemapFace* CubemapFace::create(boost::uint32_t width, boost::uint32_t height, int index, AVPixelFormat format, boost::chrono::system_clock::time_point presentationTime, Allocator& allocator) { void* addr = allocator.allocate(sizeof(CubemapFace)); void* pixels = allocator.allocate(width * height * 4); return new (addr) CubemapFace(width, height, index, format, presentationTime, pixels, allocator); } void CubemapFace::destroy(CubemapFace* cubemapFace) { cubemapFace->~CubemapFace(); cubemapFace->allocator.deallocate(cubemapFace, sizeof(CubemapFace)); } Cubemap::Cubemap(std::vector<CubemapFace*>& faces, Allocator& allocator) : allocator(allocator) { for (int i = 0; i < faces.size(); i++) { this->faces[i] = faces[i]; } } Cubemap::~Cubemap() { for (int i = 0; i < getFacesCount(); i++) { CubemapFace::destroy(faces[i].get()); } } CubemapFace* Cubemap::getFace(int index) { return faces[index].get(); } int Cubemap::getFacesCount() { int count = 0; while (count < MAX_FACES_COUNT && faces[count].get() != nullptr) { count++; } return count; } Cubemap* Cubemap::create(std::vector<CubemapFace*> faces, Allocator& allocator) { void* addr = allocator.allocate(sizeof(Cubemap)); return new (addr) Cubemap(faces, allocator); } void Cubemap::destroy(Cubemap* cubemap) { cubemap->~Cubemap(); cubemap->allocator.deallocate(cubemap, sizeof(Cubemap)); } StereoCubemap::StereoCubemap(std::vector<Cubemap*>& eyes, Allocator& allocator) : allocator(allocator) { for (int i = 0; i < eyes.size(); i++) { this->eyes[i] = eyes[i]; } } StereoCubemap::~StereoCubemap() { for (int i = 0; i < getEyesCount(); i++) { Cubemap::destroy(eyes[i].get()); } } Cubemap* StereoCubemap::getEye(int index) { return eyes[index].get(); } int StereoCubemap::getEyesCount() { int count = 0; while (count < MAX_EYES_COUNT && eyes[count].get() != nullptr) { count++; } return count; } StereoCubemap* StereoCubemap::create(std::vector<Cubemap*>& eyes, Allocator& allocator) { void* addr = allocator.allocate(sizeof(StereoCubemap)); return new (addr) StereoCubemap(eyes, allocator); } void StereoCubemap::destroy(StereoCubemap* stereoCubemap) { stereoCubemap->~StereoCubemap(); stereoCubemap->allocator.deallocate(stereoCubemap, sizeof(StereoCubemap)); }<commit_msg>Bugfix<commit_after>#include "CubemapFace.h" boost::interprocess::offset_ptr<Cubemap> cubemap; CubemapFace::CubemapFace(boost::uint32_t width, boost::uint32_t height, int index, AVPixelFormat format, boost::chrono::system_clock::time_point presentationTime, void* pixels, Allocator& allocator) : allocator(allocator), width(width), height(height), index(index), format(format), presentationTime(presentationTime), pixels(pixels) { } CubemapFace::~CubemapFace() { } boost::uint32_t CubemapFace::getWidth() { return width; } boost::uint32_t CubemapFace::getHeight() { return height; } int CubemapFace::getIndex() { return index; } AVPixelFormat CubemapFace::getFormat() { return format; } boost::chrono::system_clock::time_point CubemapFace::getPresentationTime() { return presentationTime; } void* CubemapFace::getPixels() { return pixels.get(); } boost::interprocess::interprocess_mutex& CubemapFace::getMutex() { return mutex; } boost::interprocess::interprocess_condition& CubemapFace::getNewPixelsCondition() { return newPixelsCondition; } void CubemapFace::setPresentationTime(boost::chrono::system_clock::time_point presentationTime) { this->presentationTime = presentationTime; } CubemapFace* CubemapFace::create(boost::uint32_t width, boost::uint32_t height, int index, AVPixelFormat format, boost::chrono::system_clock::time_point presentationTime, Allocator& allocator) { void* addr = allocator.allocate(sizeof(CubemapFace)); void* pixels = allocator.allocate(width * height * 4); return new (addr) CubemapFace(width, height, index, format, presentationTime, pixels, allocator); } void CubemapFace::destroy(CubemapFace* cubemapFace) { cubemapFace->~CubemapFace(); cubemapFace->allocator.deallocate(cubemapFace->pixels.get(), cubemapFace->width * cubemapFace->height * 4); cubemapFace->allocator.deallocate(cubemapFace, sizeof(CubemapFace)); } Cubemap::Cubemap(std::vector<CubemapFace*>& faces, Allocator& allocator) : allocator(allocator) { for (int i = 0; i < faces.size(); i++) { this->faces[i] = faces[i]; } } Cubemap::~Cubemap() { for (int i = 0; i < getFacesCount(); i++) { CubemapFace::destroy(faces[i].get()); } } CubemapFace* Cubemap::getFace(int index) { return faces[index].get(); } int Cubemap::getFacesCount() { int count = 0; while (count < MAX_FACES_COUNT && faces[count].get() != nullptr) { count++; } return count; } Cubemap* Cubemap::create(std::vector<CubemapFace*> faces, Allocator& allocator) { void* addr = allocator.allocate(sizeof(Cubemap)); return new (addr) Cubemap(faces, allocator); } void Cubemap::destroy(Cubemap* cubemap) { cubemap->~Cubemap(); cubemap->allocator.deallocate(cubemap, sizeof(Cubemap)); } StereoCubemap::StereoCubemap(std::vector<Cubemap*>& eyes, Allocator& allocator) : allocator(allocator) { for (int i = 0; i < eyes.size(); i++) { this->eyes[i] = eyes[i]; } } StereoCubemap::~StereoCubemap() { for (int i = 0; i < getEyesCount(); i++) { Cubemap::destroy(eyes[i].get()); } } Cubemap* StereoCubemap::getEye(int index) { return eyes[index].get(); } int StereoCubemap::getEyesCount() { int count = 0; while (count < MAX_EYES_COUNT && eyes[count].get() != nullptr) { count++; } return count; } StereoCubemap* StereoCubemap::create(std::vector<Cubemap*>& eyes, Allocator& allocator) { void* addr = allocator.allocate(sizeof(StereoCubemap)); return new (addr) StereoCubemap(eyes, allocator); } void StereoCubemap::destroy(StereoCubemap* stereoCubemap) { stereoCubemap->~StereoCubemap(); stereoCubemap->allocator.deallocate(stereoCubemap, sizeof(StereoCubemap)); }<|endoftext|>
<commit_before>/********************************************************************* ** Author: Zach Colbert ** Date: 30 November 2017 ** Description: Patron class *********************************************************************/ /********************************************************************* ** Includes *********************************************************************/ #include "Patron.hpp" /********************************************************************* ** Description: *********************************************************************/ Patron::Patron(std::string idn, std::string n) { // Set patron ID number (manually, because we don't have a set function) idNum = idn; // Set patron name name = n; // Initialize fine amount to zero for new patrons fineAmount = 0.0; } // Description std::string Patron::getIdNum() { return idNum; } // Description std::string Patron::getName() { return name; } // Description std::vector<Book*> Patron::getCheckedOutBooks() { return checkedOutBooks; } /********************************************************************* ** Description: *********************************************************************/ void Patron::addBook(Book* b) { // Add (Book pointer) b to the end of the list of checkedOutBooks checkedOutBooks.push_back(b); } /********************************************************************* ** Description: *********************************************************************/ void Patron::removeBook(Book* b) { // Remove (Book pointer) b from the list of checkedOutBooks // Use vector::erase() for any element in the vector // vector::pop_back() only works for the last element checkedOutBooks.erase(b); } // Description double Patron::getFineAmount() { return fineAmount; } /********************************************************************* ** Description: *********************************************************************/ void Patron::amendFine(double amount) { // Add (or subtract, if it's negative) the given amount to the existing fine fineAmount += amount; }<commit_msg>First draft<commit_after>/********************************************************************* ** Author: Zach Colbert ** Date: 30 November 2017 ** Description: Patron class *********************************************************************/ /********************************************************************* ** Includes *********************************************************************/ #include "Patron.hpp" /********************************************************************* ** Description: *********************************************************************/ Patron::Patron(std::string idn, std::string n) { // Set patron ID number (manually, because we don't have a set function) idNum = idn; // Set patron name name = n; // Initialize fine amount to zero for new patrons fineAmount = 0.0; } // Description std::string Patron::getIdNum() { return idNum; } // Description std::string Patron::getName() { return name; } // Description std::vector<Book*> Patron::getCheckedOutBooks() { return checkedOutBooks; } /********************************************************************* ** Description: *********************************************************************/ void Patron::addBook(Book* b) { // Add (Book pointer) b to the end of the list of checkedOutBooks checkedOutBooks.push_back(b); } /********************************************************************* ** Description: *********************************************************************/ void Patron::removeBook(Book* b) { // Remove (Book pointer) b from the list of checkedOutBooks // Use vector::erase() for any element in the vector // vector::pop_back() only works for the last element int bookIndex = -1; for (Book* chkBook : checkedOutBooks) { bookIndex++; if (chkBook == b) { break; } } checkedOutBooks.erase(checkedOutBooks.begin() + bookIndex); } // Description double Patron::getFineAmount() { return fineAmount; } /********************************************************************* ** Description: *********************************************************************/ void Patron::amendFine(double amount) { // Add (or subtract, if it's negative) the given amount to the existing fine fineAmount += amount; }<|endoftext|>
<commit_before>/* * Copyright 2018 The Cartographer Authors * * 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 "cartographer/mapping/internal/3d/pose_graph_3d.h" #include "cartographer/mapping/internal/test_helpers.h" #include "cartographer/mapping/proto/serialization.pb.h" #include "cartographer/transform/rigid_transform.h" #include "cartographer/transform/rigid_transform_test_helpers.h" #include "cartographer/transform/transform.h" #include "gmock/gmock.h" #include "google/protobuf/util/message_differencer.h" namespace cartographer { namespace mapping { namespace pose_graph { class FakeOptimizationProblem3D : public OptimizationProblem3D { public: FakeOptimizationProblem3D() : OptimizationProblem3D(proto::OptimizationProblemOptions{}) {} ~FakeOptimizationProblem3D() override = default; void Solve( const std::vector<Constraint>& constraints, const std::set<int>& frozen_trajectories, const std::map<std::string, LandmarkNode>& landmark_nodes) override {} }; } // namespace pose_graph namespace { class PoseGraph3DForTesting : public PoseGraph3D { public: PoseGraph3DForTesting( const proto::PoseGraphOptions& options, std::unique_ptr<pose_graph::OptimizationProblem3D> optimization_problem, common::ThreadPool* thread_pool) : PoseGraph3D(options, std::move(optimization_problem), thread_pool) {} void WaitForAllComputations() { PoseGraph3D::WaitForAllComputations(); } }; class PoseGraph3DTest : public ::testing::Test { protected: PoseGraph3DTest() : thread_pool_(common::make_unique<common::ThreadPool>(1)) {} void SetUp() override { const std::string kPoseGraphLua = R"text( include "pose_graph.lua" return POSE_GRAPH)text"; auto pose_graph_parameters = test::ResolveLuaParameters(kPoseGraphLua); pose_graph_options_ = CreatePoseGraphOptions(pose_graph_parameters.get()); } void BuildPoseGraph() { auto optimization_problem = common::make_unique<pose_graph::OptimizationProblem3D>( pose_graph_options_.optimization_problem_options()); pose_graph_ = common::make_unique<PoseGraph3DForTesting>( pose_graph_options_, std::move(optimization_problem), thread_pool_.get()); } void BuildPoseGraphWithFakeOptimization() { auto optimization_problem = common::make_unique<pose_graph::FakeOptimizationProblem3D>(); pose_graph_ = common::make_unique<PoseGraph3DForTesting>( pose_graph_options_, std::move(optimization_problem), thread_pool_.get()); } proto::PoseGraphOptions pose_graph_options_; std::unique_ptr<common::ThreadPool> thread_pool_; std::unique_ptr<PoseGraph3DForTesting> pose_graph_; }; TEST_F(PoseGraph3DTest, Empty) { BuildPoseGraph(); pose_graph_->WaitForAllComputations(); EXPECT_TRUE(pose_graph_->GetAllSubmapData().empty()); EXPECT_TRUE(pose_graph_->constraints().empty()); EXPECT_TRUE(pose_graph_->GetConnectedTrajectories().empty()); EXPECT_TRUE(pose_graph_->GetAllSubmapPoses().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryNodes().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryNodePoses().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryData().empty()); proto::PoseGraph empty_proto; EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( pose_graph_->ToProto(), empty_proto)); } TEST_F(PoseGraph3DTest, BasicSerialization) { BuildPoseGraph(); proto::PoseGraph proto; auto fake_node = test::CreateFakeNode(); test::AddToProtoGraph(fake_node, &proto); pose_graph_->AddNodeFromProto(transform::Rigid3d::Identity(), fake_node); auto fake_submap = test::CreateFakeSubmap3D(); test::AddToProtoGraph(fake_submap, &proto); pose_graph_->AddSubmapFromProto(transform::Rigid3d::Identity(), fake_submap); test::AddToProtoGraph(test::CreateFakeConstraint(fake_node, fake_submap), &proto); pose_graph_->AddSerializedConstraints(FromProto(proto.constraint())); pose_graph_->WaitForAllComputations(); proto::PoseGraph actual_proto = pose_graph_->ToProto(); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.constraint(0), actual_proto.constraint(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0).node(0), actual_proto.trajectory(0).node(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0).submap(0), actual_proto.trajectory(0).submap(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0), actual_proto.trajectory(0))); EXPECT_TRUE( google::protobuf::util::MessageDifferencer::Equals(proto, actual_proto)); } TEST_F(PoseGraph3DTest, PureLocalizationTrimmer) { BuildPoseGraphWithFakeOptimization(); const int trajectory_id = 2; const int num_submaps_to_create = 5; const int num_submaps_to_keep = 3; const int num_nodes_per_submap = 2; for (int i = 0; i < num_submaps_to_create; ++i) { int submap_index = 42 + i; auto submap = test::CreateFakeSubmap3D(trajectory_id, submap_index); pose_graph_->AddSubmapFromProto(transform::Rigid3d::Identity(), submap); for (int j = 0; j < num_nodes_per_submap; ++j) { int node_index = 7 + num_nodes_per_submap * i + j; auto node = test::CreateFakeNode(trajectory_id, node_index); pose_graph_->AddNodeFromProto(transform::Rigid3d::Identity(), node); proto::PoseGraph proto; auto constraint = test::CreateFakeConstraint(node, submap); // TODO(gaschler): Also remove inter constraints when all references are // gone. constraint.set_tag(proto::PoseGraph::Constraint::INTRA_SUBMAP); test::AddToProtoGraph(constraint, &proto); pose_graph_->AddSerializedConstraints(FromProto(proto.constraint())); } } pose_graph_->AddTrimmer(common::make_unique<PureLocalizationTrimmer>( trajectory_id, num_submaps_to_keep)); pose_graph_->WaitForAllComputations(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_create); for (int i = 0; i < 2; ++i) { pose_graph_->RunFinalOptimization(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_keep); } } } // namespace } // namespace mapping } // namespace cartographer <commit_msg>Test trimming within trajectory (#1020)<commit_after>/* * Copyright 2018 The Cartographer Authors * * 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 "cartographer/mapping/internal/3d/pose_graph_3d.h" #include "cartographer/mapping/internal/test_helpers.h" #include "cartographer/mapping/proto/serialization.pb.h" #include "cartographer/transform/rigid_transform.h" #include "cartographer/transform/rigid_transform_test_helpers.h" #include "cartographer/transform/transform.h" #include "gmock/gmock.h" #include "google/protobuf/util/message_differencer.h" namespace cartographer { namespace mapping { namespace pose_graph { class FakeOptimizationProblem3D : public OptimizationProblem3D { public: FakeOptimizationProblem3D() : OptimizationProblem3D(proto::OptimizationProblemOptions{}) {} ~FakeOptimizationProblem3D() override = default; void Solve( const std::vector<Constraint>& constraints, const std::set<int>& frozen_trajectories, const std::map<std::string, LandmarkNode>& landmark_nodes) override {} }; } // namespace pose_graph namespace { class PoseGraph3DForTesting : public PoseGraph3D { public: PoseGraph3DForTesting( const proto::PoseGraphOptions& options, std::unique_ptr<pose_graph::OptimizationProblem3D> optimization_problem, common::ThreadPool* thread_pool) : PoseGraph3D(options, std::move(optimization_problem), thread_pool) {} void WaitForAllComputations() { PoseGraph3D::WaitForAllComputations(); } }; class PoseGraph3DTest : public ::testing::Test { protected: PoseGraph3DTest() : thread_pool_(common::make_unique<common::ThreadPool>(1)) {} void SetUp() override { const std::string kPoseGraphLua = R"text( include "pose_graph.lua" return POSE_GRAPH)text"; auto pose_graph_parameters = test::ResolveLuaParameters(kPoseGraphLua); pose_graph_options_ = CreatePoseGraphOptions(pose_graph_parameters.get()); } void BuildPoseGraph() { auto optimization_problem = common::make_unique<pose_graph::OptimizationProblem3D>( pose_graph_options_.optimization_problem_options()); pose_graph_ = common::make_unique<PoseGraph3DForTesting>( pose_graph_options_, std::move(optimization_problem), thread_pool_.get()); } void BuildPoseGraphWithFakeOptimization() { auto optimization_problem = common::make_unique<pose_graph::FakeOptimizationProblem3D>(); pose_graph_ = common::make_unique<PoseGraph3DForTesting>( pose_graph_options_, std::move(optimization_problem), thread_pool_.get()); } proto::PoseGraphOptions pose_graph_options_; std::unique_ptr<common::ThreadPool> thread_pool_; std::unique_ptr<PoseGraph3DForTesting> pose_graph_; }; TEST_F(PoseGraph3DTest, Empty) { BuildPoseGraph(); pose_graph_->WaitForAllComputations(); EXPECT_TRUE(pose_graph_->GetAllSubmapData().empty()); EXPECT_TRUE(pose_graph_->constraints().empty()); EXPECT_TRUE(pose_graph_->GetConnectedTrajectories().empty()); EXPECT_TRUE(pose_graph_->GetAllSubmapPoses().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryNodes().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryNodePoses().empty()); EXPECT_TRUE(pose_graph_->GetTrajectoryData().empty()); proto::PoseGraph empty_proto; EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( pose_graph_->ToProto(), empty_proto)); } TEST_F(PoseGraph3DTest, BasicSerialization) { BuildPoseGraph(); proto::PoseGraph proto; auto fake_node = test::CreateFakeNode(); test::AddToProtoGraph(fake_node, &proto); pose_graph_->AddNodeFromProto(transform::Rigid3d::Identity(), fake_node); auto fake_submap = test::CreateFakeSubmap3D(); test::AddToProtoGraph(fake_submap, &proto); pose_graph_->AddSubmapFromProto(transform::Rigid3d::Identity(), fake_submap); test::AddToProtoGraph(test::CreateFakeConstraint(fake_node, fake_submap), &proto); pose_graph_->AddSerializedConstraints(FromProto(proto.constraint())); pose_graph_->WaitForAllComputations(); proto::PoseGraph actual_proto = pose_graph_->ToProto(); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.constraint(0), actual_proto.constraint(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0).node(0), actual_proto.trajectory(0).node(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0).submap(0), actual_proto.trajectory(0).submap(0))); EXPECT_TRUE(google::protobuf::util::MessageDifferencer::Equals( proto.trajectory(0), actual_proto.trajectory(0))); EXPECT_TRUE( google::protobuf::util::MessageDifferencer::Equals(proto, actual_proto)); } TEST_F(PoseGraph3DTest, PureLocalizationTrimmer) { BuildPoseGraphWithFakeOptimization(); const int trajectory_id = 2; const int num_submaps_to_create = 5; const int num_submaps_to_keep = 3; const int num_nodes_per_submap = 2; for (int i = 0; i < num_submaps_to_create; ++i) { int submap_index = (i < 3) ? 42 + i : 100 + i; auto submap = test::CreateFakeSubmap3D(trajectory_id, submap_index); pose_graph_->AddSubmapFromProto(transform::Rigid3d::Identity(), submap); for (int j = 0; j < num_nodes_per_submap; ++j) { int node_index = 7 + num_nodes_per_submap * submap_index + j; auto node = test::CreateFakeNode(trajectory_id, node_index); pose_graph_->AddNodeFromProto(transform::Rigid3d::Identity(), node); proto::PoseGraph proto; auto constraint = test::CreateFakeConstraint(node, submap); // TODO(gaschler): Also remove inter constraints when all references are // gone. constraint.set_tag(proto::PoseGraph::Constraint::INTRA_SUBMAP); test::AddToProtoGraph(constraint, &proto); pose_graph_->AddSerializedConstraints(FromProto(proto.constraint())); } } pose_graph_->AddTrimmer(common::make_unique<PureLocalizationTrimmer>( trajectory_id, num_submaps_to_keep)); pose_graph_->WaitForAllComputations(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_create); for (int i = 0; i < 2; ++i) { pose_graph_->RunFinalOptimization(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_keep); } } class EvenSubmapTrimmer : public PoseGraphTrimmer { public: explicit EvenSubmapTrimmer(int trajectory_id) : trajectory_id_(trajectory_id) {} void Trim(Trimmable* pose_graph) override { auto submap_ids = pose_graph->GetSubmapIds(trajectory_id_); for (const auto submap_id : submap_ids) { if (submap_id.submap_index % 2 == 0) { pose_graph->MarkSubmapAsTrimmed(submap_id); } } } bool IsFinished() override { return false; } private: int trajectory_id_; }; TEST_F(PoseGraph3DTest, EvenSubmapTrimmer) { BuildPoseGraphWithFakeOptimization(); const int trajectory_id = 2; const int num_submaps_to_keep = 10; const int num_submaps_to_create = 2 * num_submaps_to_keep; const int num_nodes_per_submap = 3; for (int i = 0; i < num_submaps_to_create; ++i) { int submap_index = 42 + i; auto submap = test::CreateFakeSubmap3D(trajectory_id, submap_index); pose_graph_->AddSubmapFromProto(transform::Rigid3d::Identity(), submap); for (int j = 0; j < num_nodes_per_submap; ++j) { int node_index = 7 + num_nodes_per_submap * i + j; auto node = test::CreateFakeNode(trajectory_id, node_index); pose_graph_->AddNodeFromProto(transform::Rigid3d::Identity(), node); proto::PoseGraph proto; auto constraint = test::CreateFakeConstraint(node, submap); constraint.set_tag(proto::PoseGraph::Constraint::INTRA_SUBMAP); test::AddToProtoGraph(constraint, &proto); pose_graph_->AddSerializedConstraints(FromProto(proto.constraint())); } } pose_graph_->AddTrimmer( common::make_unique<EvenSubmapTrimmer>(trajectory_id)); pose_graph_->WaitForAllComputations(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_create); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_create); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_create); for (int i = 0; i < 2; ++i) { pose_graph_->RunFinalOptimization(); EXPECT_EQ( pose_graph_->GetAllSubmapPoses().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetAllSubmapData().SizeOfTrajectoryOrZero(trajectory_id), num_submaps_to_keep); EXPECT_EQ( pose_graph_->GetTrajectoryNodes().SizeOfTrajectoryOrZero(trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->GetTrajectoryNodePoses().SizeOfTrajectoryOrZero( trajectory_id), num_nodes_per_submap * num_submaps_to_keep); EXPECT_EQ(pose_graph_->constraints().size(), num_nodes_per_submap * num_submaps_to_keep); } } } // namespace } // namespace mapping } // namespace cartographer <|endoftext|>
<commit_before>// Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #include <cassert> #include <memory> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> #include "../config.hpp" #include "../normal.hpp" #include "../nothing.hpp" #include "../parse.hpp" #include "../internal/iterator.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace parse_tree { struct node { std::vector< std::unique_ptr< node > > children; const std::type_info* id = nullptr; internal::iterator begin; internal::iterator end; std::string source; }; namespace internal { struct state { std::vector< std::unique_ptr< node > > stack; state() { emplace_back(); } void emplace_back() { stack.emplace_back( std::unique_ptr< node >( new node ) ); // NOLINT: std::make_unique requires C++14 } std::unique_ptr< node >& back() noexcept { return stack.back(); } void pop_back() noexcept { return stack.pop_back(); } }; template< typename T, typename = void > struct transform { static void call( std::unique_ptr< node >& /*unused*/ ) noexcept { } }; template< typename T > struct transform< T, decltype( T::transform( std::declval< std::unique_ptr< node >& >() ), void() ) > { static void call( std::unique_ptr< node >& n ) noexcept( noexcept( T::transform( n ) ) ) { T::transform( n ); } }; template< template< typename > class S > struct parse_tree { template< typename Rule, bool = S< Rule >::value > struct builder; template< typename Rule > using type = builder< Rule >; }; template< template< typename > class S > template< typename Rule > struct parse_tree< S >::builder< Rule, false > : normal< Rule > { }; template< template< typename > class S > template< typename Rule > struct parse_tree< S >::builder< Rule, true > : normal< Rule > { template< typename Input > static void start( const Input& in, state& st ) { st.emplace_back(); st.back()->id = &typeid( Rule ); st.back()->begin = in.iterator(); st.back()->source = in.source(); } template< typename Input > static void success( const Input& in, state& st ) { auto n = std::move( st.back() ); n->end = in.iterator(); st.pop_back(); transform< S< Rule > >::call( n ); if( n ) { st.back()->children.emplace_back( std::move( n ) ); } } template< typename Input > static void failure( const Input& /*unused*/, state& st ) noexcept { st.pop_back(); } }; template< typename > struct store_all : std::true_type { }; } // namespace internal template< typename Rule, template< typename > class S = internal::store_all, typename Input > std::unique_ptr< node > parse( Input& in ) { internal::state st; if( !TAO_PEGTL_NAMESPACE::parse< Rule, nothing, internal::parse_tree< S >::template type >( in, st ) ) { return nullptr; } assert( st.stack.size() == 1 ); return std::move( st.back() ); } } // namespace parse_tree } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif <commit_msg>Refactored to allow user-defined node type<commit_after>// Copyright (c) 2017-2018 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #define TAO_PEGTL_CONTRIB_PARSE_TREE_HPP #include <cassert> #include <memory> #include <type_traits> #include <typeinfo> #include <utility> #include <vector> #include "../config.hpp" #include "../normal.hpp" #include "../nothing.hpp" #include "../parse.hpp" #include "../internal/iterator.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace parse_tree { struct node { std::vector< std::unique_ptr< node > > children; const std::type_info* id = nullptr; internal::iterator begin; internal::iterator end; std::string source; node() = default; node( const node& ) = delete; node( node&& ) = default; ~node() = default; node& operator=( const node& ) = delete; node& operator=( node&& ) = delete; template< typename Rule, typename Input > void initialize( const Input& in ) { id = &typeid( Rule ); begin = in.iterator(); source = in.source(); } template< typename Rule, typename Input > void finalize( const Input& in ) { end = in.iterator(); } void append( std::unique_ptr< node > child ) { children.emplace_back( std::move( child ) ); } }; namespace internal { template< typename Node > struct state { std::vector< std::unique_ptr< Node > > stack; state() { emplace_back(); } void emplace_back() { stack.emplace_back( std::unique_ptr< Node >( new Node ) ); // NOLINT: std::make_unique requires C++14 } std::unique_ptr< Node >& back() noexcept { return stack.back(); } void pop_back() noexcept { return stack.pop_back(); } }; template< typename Node, typename S, typename = void > struct transform { static void call( std::unique_ptr< Node >& /*unused*/ ) noexcept { } }; template< typename Node, typename S > struct transform< Node, S, decltype( S::transform( std::declval< std::unique_ptr< Node >& >() ), void() ) > { static void call( std::unique_ptr< Node >& n ) noexcept( noexcept( S::transform( n ) ) ) { S::transform( n ); } }; template< template< typename > class S > struct make_control { template< typename Rule, bool = S< Rule >::value > struct control; template< typename Rule > using type = control< Rule >; }; template< template< typename > class S > template< typename Rule > struct make_control< S >::control< Rule, false > : normal< Rule > { }; template< template< typename > class S > template< typename Rule > struct make_control< S >::control< Rule, true > : normal< Rule > { template< typename Input, typename Node > static void start( const Input& in, state< Node >& st ) { st.emplace_back(); st.back()->template initialize< Rule >( in ); } template< typename Input, typename Node > static void success( const Input& in, state< Node >& st ) { auto n = std::move( st.back() ); st.pop_back(); n->template finalize< Rule >( in ); transform< Node, S< Rule > >::call( n ); if( n ) { st.back()->append( std::move( n ) ); } } template< typename Input, typename Node > static void failure( const Input& /*unused*/, state< Node >& st ) noexcept { st.pop_back(); } }; template< typename > struct store_all : std::true_type { }; } // namespace internal template< typename Rule, typename Node, template< typename > class S = internal::store_all, typename Input > std::unique_ptr< Node > parse( Input& in ) { internal::state< Node > st; if( !TAO_PEGTL_NAMESPACE::parse< Rule, nothing, internal::make_control< S >::template type >( in, st ) ) { return nullptr; } assert( st.stack.size() == 1 ); return std::move( st.back() ); } template< typename Rule, template< typename > class S = internal::store_all, typename Input > std::unique_ptr< node > parse( Input& in ) { return parse< Rule, node, S >( in ); } } // namespace parse_tree } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif <|endoftext|>