{"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2016 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \n#include \n\n#include \"list_permissions_statement.hh\"\n#include \"auth\/authorizer.hh\"\n#include \"auth\/common.hh\"\n#include \"cql3\/result_set.hh\"\n#include \"transport\/messages\/result_message.hh\"\n\ncql3::statements::list_permissions_statement::list_permissions_statement(\n auth::permission_set permissions,\n std::optional resource,\n std::optional username, bool recursive)\n : _permissions(permissions)\n , _resource(std::move(resource))\n , _username(std::move(username))\n , _recursive(recursive) {\n}\n\nvoid cql3::statements::list_permissions_statement::validate(\n distributed& proxy,\n const service::client_state& state) {\n \/\/ a check to ensure the existence of the user isn't being leaked by user existence check.\n state.ensure_not_anonymous();\n}\n\nfuture<> cql3::statements::list_permissions_statement::check_access(const service::client_state& state) {\n \/\/\n \/\/ TODO(jhaberku): The existence checks should be in `execute()`. `check_access` should be restricted to\n \/\/ authorization checking.\n \/\/\n\n auto f = make_ready_future();\n if (_username) {\n f = state.get_auth_service()->underlying_role_manager().exists(*_username).then([this](bool exists) {\n if (!exists) {\n throw exceptions::invalid_request_exception(sprint(\"User %s doesn't exist\", *_username));\n }\n });\n }\n return f.then([this, &state] {\n if (_resource) {\n maybe_correct_resource(*_resource, state);\n return state.ensure_exists(*_resource);\n }\n\n return make_ready_future<>();\n }).then([this, &state] {\n const auto& as = *state.get_auth_service();\n\n return auth::has_superuser(as, *state.user()).then([this, &state, &as](bool has_super) {\n if (has_super) {\n return make_ready_future<>();\n }\n\n if (!_username) {\n return make_exception_future<>(\n exceptions::unauthorized_exception(\"You are not authorized to view everyone's permissions\"));\n }\n\n return auth::has_role(as, *state.user(), *_username).then([this](bool has_role) {\n if (!has_role) {\n return make_exception_future<>(\n exceptions::unauthorized_exception(\n sprint(\"You are not authorized to view %s's permissions\", *_username)));\n }\n\n return make_ready_future<>();\n });\n });\n });\n}\n\n\nfuture<::shared_ptr>\ncql3::statements::list_permissions_statement::execute(\n distributed& proxy,\n service::query_state& state,\n const query_options& options) {\n static auto make_column = [](sstring name) {\n return ::make_shared(\n auth::meta::AUTH_KS,\n \"permissions\",\n ::make_shared(std::move(name), true),\n utf8_type);\n };\n\n static thread_local const std::vector<::shared_ptr> metadata({\n make_column(\"role\"), make_column(\"resource\"), make_column(\"permission\")\n });\n\n typedef std::optional opt_resource;\n\n std::vector resources;\n\n auto r = _resource;\n for (;;) {\n resources.emplace_back(r);\n if (!r || !_recursive) {\n break;\n }\n\n auto parent = r->parent();\n if (!parent) {\n break;\n }\n\n r = std::move(parent);\n }\n\n return map_reduce(\n resources,\n [&state, this](opt_resource r) {\n return do_with(std::move(r), [this, &state](const opt_resource& r) {\n auto& auth_service = *state.get_client_state().get_auth_service();\n return auth_service.underlying_authorizer().list(_permissions, r, _username, auth_service);\n });\n },\n std::vector(),\n [](std::vector details, std::vector pd) {\n details.insert(details.end(), pd.begin(), pd.end());\n return details;\n }).then([this](std::vector details) {\n std::sort(details.begin(), details.end());\n\n auto rs = std::make_unique(metadata);\n\n for (auto& v : details) {\n \/\/ Make sure names are sorted.\n auto names = auth::permissions::to_strings(v.permissions);\n for (auto& p : std::set(names.begin(), names.end())) {\n rs->add_row(\n std::vector{\n utf8_type->decompose(v.user),\n utf8_type->decompose(sstring(sprint(\"%s\", v.resource))),\n utf8_type->decompose(p)});\n }\n }\n\n auto rows = ::make_shared(std::move(rs));\n return ::shared_ptr(std::move(rows));\n });\n}\ncql3: Fix error handling in LIST PERMISSIONS\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2016 ScyllaDB\n *\n * Modified by ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#include \n#include \n\n#include \"list_permissions_statement.hh\"\n#include \"auth\/authorizer.hh\"\n#include \"auth\/common.hh\"\n#include \"cql3\/result_set.hh\"\n#include \"transport\/messages\/result_message.hh\"\n\ncql3::statements::list_permissions_statement::list_permissions_statement(\n auth::permission_set permissions,\n std::optional resource,\n std::optional username, bool recursive)\n : _permissions(permissions)\n , _resource(std::move(resource))\n , _username(std::move(username))\n , _recursive(recursive) {\n}\n\nvoid cql3::statements::list_permissions_statement::validate(\n distributed& proxy,\n const service::client_state& state) {\n \/\/ a check to ensure the existence of the user isn't being leaked by user existence check.\n state.ensure_not_anonymous();\n}\n\nfuture<> cql3::statements::list_permissions_statement::check_access(const service::client_state& state) {\n if (_resource) {\n maybe_correct_resource(*_resource, state);\n return state.ensure_exists(*_resource);\n }\n\n const auto& as = *state.get_auth_service();\n\n return auth::has_superuser(as, *state.user()).then([this, &state, &as](bool has_super) {\n if (has_super) {\n return make_ready_future<>();\n }\n\n if (!_username) {\n return make_exception_future<>(\n exceptions::unauthorized_exception(\"You are not authorized to view everyone's permissions\"));\n }\n\n return auth::has_role(as, *state.user(), *_username).then([this](bool has_role) {\n if (!has_role) {\n return make_exception_future<>(\n exceptions::unauthorized_exception(\n sprint(\"You are not authorized to view %s's permissions\", *_username)));\n }\n\n return make_ready_future<>();\n }).handle_exception_type([](const auth::nonexistant_role& e) {\n return make_exception_future<>(exceptions::invalid_request_exception(e.what()));\n });\n });\n}\n\n\nfuture<::shared_ptr>\ncql3::statements::list_permissions_statement::execute(\n distributed& proxy,\n service::query_state& state,\n const query_options& options) {\n static auto make_column = [](sstring name) {\n return ::make_shared(\n auth::meta::AUTH_KS,\n \"permissions\",\n ::make_shared(std::move(name), true),\n utf8_type);\n };\n\n static thread_local const std::vector<::shared_ptr> metadata({\n make_column(\"role\"), make_column(\"resource\"), make_column(\"permission\")\n });\n\n typedef std::optional opt_resource;\n\n std::vector resources;\n\n auto r = _resource;\n for (;;) {\n resources.emplace_back(r);\n if (!r || !_recursive) {\n break;\n }\n\n auto parent = r->parent();\n if (!parent) {\n break;\n }\n\n r = std::move(parent);\n }\n\n return map_reduce(\n resources,\n [&state, this](opt_resource r) {\n return do_with(std::move(r), [this, &state](const opt_resource& r) {\n auto& auth_service = *state.get_client_state().get_auth_service();\n return auth_service.underlying_authorizer().list(\n _permissions,\n r,\n _username,\n auth_service).handle_exception_type([](const auth::nonexistant_role& e) {\n return make_exception_future>(\n exceptions::invalid_request_exception(e.what()));\n });\n });\n },\n std::vector(),\n [](std::vector details, std::vector pd) {\n details.insert(details.end(), pd.begin(), pd.end());\n return details;\n }).then([this](std::vector details) {\n std::sort(details.begin(), details.end());\n\n auto rs = std::make_unique(metadata);\n\n for (auto& v : details) {\n \/\/ Make sure names are sorted.\n auto names = auth::permissions::to_strings(v.permissions);\n for (auto& p : std::set(names.begin(), names.end())) {\n rs->add_row(\n std::vector{\n utf8_type->decompose(v.user),\n utf8_type->decompose(sstring(sprint(\"%s\", v.resource))),\n utf8_type->decompose(p)});\n }\n }\n\n auto rows = ::make_shared(std::move(rs));\n return ::shared_ptr(std::move(rows));\n });\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace folly;\n\nclass AbstractIntException : public std::exception {\n public:\n virtual int getInt() const = 0;\n};\n\nclass IntException : public AbstractIntException {\n public:\n explicit IntException(int i) : i_(i) {}\n\n int getInt() const override { return i_; }\n const char* what() const noexcept override {\n what_ = folly::to(\"int == \", i_);\n return what_.c_str();\n }\n\n private:\n int i_;\n mutable std::string what_;\n};\n\nconst static std::string kExceptionClassName =\n demangle(typeid(std::exception)).toStdString();\nconst static std::string kRuntimeErrorClassName =\n demangle(typeid(std::runtime_error)).toStdString();\nconst static std::string kIntExceptionClassName =\n demangle(typeid(IntException)).toStdString();\nconst static std::string kIntClassName = demangle(typeid(int)).toStdString();\n\n\/\/ Tests that when we call throwException, the proper type is thrown (derived)\nTEST(ExceptionWrapper, throw_test) {\n std::runtime_error e(\"payload\");\n auto ew = make_exception_wrapper(e);\n\n std::vector container;\n container.push_back(ew);\n\n try {\n container[0].throwException();\n } catch (std::runtime_error& e) {\n std::string expected = \"payload\";\n std::string actual = e.what();\n EXPECT_EQ(expected, actual);\n }\n}\n\nTEST(ExceptionWrapper, members) {\n auto ew = exception_wrapper();\n EXPECT_FALSE(bool(ew));\n EXPECT_EQ(ew.what(), \"\");\n EXPECT_EQ(ew.class_name(), \"\");\n ew = make_exception_wrapper(\"payload\");\n EXPECT_TRUE(bool(ew));\n EXPECT_EQ(ew.what(), kRuntimeErrorClassName + \": payload\");\n EXPECT_EQ(ew.class_name(), kRuntimeErrorClassName);\n}\n\nTEST(ExceptionWrapper, equals) {\n std::runtime_error e(\"payload\");\n auto ew1 = make_exception_wrapper(e);\n auto ew2 = ew1;\n EXPECT_EQ(ew1, ew2);\n\n auto ew3 = try_and_catch([&]() {\n throw std::runtime_error(\"payload\");\n });\n auto ew4 = try_and_catch([&]() {\n ew3.throwException();\n });\n EXPECT_EQ(ew3, ew4);\n}\n\nTEST(ExceptionWrapper, not_equals) {\n std::runtime_error e1(\"payload\");\n std::runtime_error e2(\"payload\");\n auto ew1 = make_exception_wrapper(e1);\n auto ew2 = make_exception_wrapper(e2);\n EXPECT_NE(ew1, ew2);\n\n auto ew3 = make_exception_wrapper(e1);\n auto ew4 = make_exception_wrapper(e1);\n EXPECT_NE(ew3, ew4);\n\n auto ew5 = try_and_catch([&]() {\n throw e1;\n });\n auto ew6 = try_and_catch([&]() {\n throw e1;\n });\n EXPECT_NE(ew5, ew6);\n}\n\nTEST(ExceptionWrapper, try_and_catch_test) {\n std::string expected = \"payload\";\n\n \/\/ Catch rightmost matching exception type\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw std::runtime_error(expected);\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_TRUE(ew.getCopied());\n EXPECT_EQ(ew.what(), kRuntimeErrorClassName + \": payload\");\n EXPECT_EQ(ew.class_name(), kRuntimeErrorClassName);\n auto rep = ew.is_compatible_with();\n EXPECT_TRUE(rep);\n\n \/\/ Changing order is like catching in wrong order. Beware of this in your\n \/\/ code.\n auto ew2 = try_and_catch([=]() {\n throw std::runtime_error(expected);\n });\n EXPECT_TRUE(bool(ew2));\n \/\/ We are catching a std::exception, not std::runtime_error.\n EXPECT_FALSE(ew2.getCopied());\n \/\/ But, we can still get the actual type if we want it.\n rep = ew2.is_compatible_with();\n EXPECT_TRUE(rep);\n\n \/\/ Catches even if not rightmost.\n auto ew3 = try_and_catch([]() {\n throw std::exception();\n });\n EXPECT_TRUE(bool(ew3));\n EXPECT_EQ(ew3.what(), kExceptionClassName + \": std::exception\");\n EXPECT_EQ(ew3.class_name(), kExceptionClassName);\n rep = ew3.is_compatible_with();\n EXPECT_FALSE(rep);\n\n \/\/ If does not catch, throws.\n EXPECT_THROW(\n try_and_catch([]() {\n throw std::exception();\n }),\n std::exception);\n}\n\nTEST(ExceptionWrapper, with_exception_test) {\n int expected = 23;\n\n \/\/ This works, and doesn't slice.\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw IntException(expected);\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_EQ(ew.what(), kIntExceptionClassName + \": int == 23\");\n EXPECT_EQ(ew.class_name(), kIntExceptionClassName);\n EXPECT_TRUE(ew.with_exception(\n [&](const IntException& ie) { EXPECT_EQ(ie.getInt(), expected); }));\n\n \/\/ I can try_and_catch a non-copyable base class. This will use\n \/\/ std::exception_ptr internally.\n exception_wrapper ew2 = try_and_catch(\n [=]() {\n throw IntException(expected);\n });\n EXPECT_TRUE(bool(ew2));\n EXPECT_EQ(ew2.what(), kIntExceptionClassName + \": int == 23\");\n EXPECT_EQ(ew2.class_name(), kIntExceptionClassName);\n EXPECT_TRUE(ew2.with_exception([&](AbstractIntException& ie) {\n EXPECT_EQ(ie.getInt(), expected);\n EXPECT_TRUE(dynamic_cast(&ie));\n }));\n\n \/\/ Test with const this. If this compiles and does not crash due to\n \/\/ infinite loop when it runs, it succeeds.\n const exception_wrapper& cew = ew;\n EXPECT_TRUE(\n cew.with_exception([&](const IntException& \/* ie *\/) { SUCCEED(); }));\n\n \/\/ Test with empty ew.\n exception_wrapper empty_ew;\n EXPECT_FALSE(\n empty_ew.with_exception([&](const std::exception& \/* ie *\/) { FAIL(); }));\n\n \/\/ This won't even compile. You can't use a function which takes a\n \/\/ non-const reference with a const exception_wrapper.\n\/*\n cew.with_exception([&](IntException& ie) {\n SUCCEED();\n });\n*\/\n}\n\nTEST(ExceptionWrapper, getExceptionPtr_test) {\n int expected = 23;\n\n \/\/ This works, and doesn't slice.\n exception_wrapper ew = try_and_catch(\n [=]() { throw IntException(expected); });\n std::exception_ptr eptr = ew.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ I can try_and_catch a non-copyable base class. This will use\n \/\/ std::exception_ptr internally.\n exception_wrapper ew2 = try_and_catch(\n [=]() { throw IntException(expected); });\n eptr = ew2.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ Test with const this.\n const exception_wrapper& cew = ew;\n eptr = cew.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ Test with empty ew.\n\n \/\/ Disabling pending fix for fbandroid: t13822116\n \/*\n exception_wrapper empty_ew;\n eptr = empty_ew.getExceptionPtr();\n EXPECT_DEATH(std::rethrow_exception(eptr), \"exception\");\n *\/\n}\n\nTEST(ExceptionWrapper, with_exception_deduction) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](std::runtime_error&) {}));\n EXPECT_TRUE(ew.with_exception([](std::exception&) {}));\n EXPECT_FALSE(ew.with_exception([](std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_exn_const) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](const std::runtime_error&) {}));\n EXPECT_TRUE(ew.with_exception([](const std::exception&) {}));\n EXPECT_FALSE(ew.with_exception([](const std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_wrap_const_exn_const) {\n const auto cew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(cew.with_exception([](const std::runtime_error&) {}));\n EXPECT_TRUE(cew.with_exception([](const std::exception&) {}));\n EXPECT_FALSE(cew.with_exception([](const std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_returning) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](std::runtime_error&) { return 3; }));\n EXPECT_TRUE(ew.with_exception([](std::exception&) { return \"hello\"; }));\n EXPECT_FALSE(ew.with_exception([](std::logic_error&) { return nullptr; }));\n}\n\nnamespace {\ntemplate \nT& r_to_l(T v) { return std::ref(v); }\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_functor_lvalue) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception(r_to_l([](std::runtime_error&) {})));\n EXPECT_TRUE(ew.with_exception(r_to_l([](std::exception&) {})));\n EXPECT_FALSE(ew.with_exception(r_to_l([](std::logic_error&) {})));\n}\n\nTEST(ExceptionWrapper, non_std_exception_test) {\n int expected = 17;\n\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw expected;\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_FALSE(ew.is_compatible_with());\n EXPECT_EQ(ew.what(), kIntClassName);\n EXPECT_EQ(ew.class_name(), kIntClassName);\n \/\/ non-std::exception types are supported, but the only way to\n \/\/ access their value is to explicity rethrow and catch it.\n try {\n ew.throwException();\n } catch \/* nolint *\/ (int& i) {\n EXPECT_EQ(i, expected);\n }\n}\n\n\nTEST(ExceptionWrapper, exceptionStr) {\n auto ew = make_exception_wrapper(\"argh\");\n EXPECT_EQ(kRuntimeErrorClassName + \": argh\", exceptionStr(ew));\n}\n\nTEST(ExceptionWrapper, throwException_noException) {\n exception_wrapper ew;\n ASSERT_DEATH(ew.throwException(), \"empty folly::exception_wrapper\");\n}\n\nnamespace {\nclass TestException : public std::exception { };\nvoid testEW(const exception_wrapper& ew) {\n EXPECT_THROW(ew.throwException(), TestException);\n}\n} \/\/ namespace\n\nTEST(ExceptionWrapper, implicitConstruction) {\n \/\/ Try with both lvalue and rvalue references\n TestException e;\n testEW(e);\n testEW(TestException());\n}\nFix for ExceptionWrapperTest\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace folly;\n\nclass AbstractIntException : public std::exception {\n public:\n virtual int getInt() const = 0;\n};\n\nclass IntException : public AbstractIntException {\n public:\n explicit IntException(int i) : i_(i) {}\n\n int getInt() const override { return i_; }\n const char* what() const noexcept override {\n what_ = folly::to(\"int == \", i_);\n return what_.c_str();\n }\n\n private:\n int i_;\n mutable std::string what_;\n};\n\nconst static std::string kExceptionClassName =\n demangle(typeid(std::exception)).toStdString();\nconst static std::string kRuntimeErrorClassName =\n demangle(typeid(std::runtime_error)).toStdString();\nconst static std::string kIntExceptionClassName =\n demangle(typeid(IntException)).toStdString();\nconst static std::string kIntClassName = demangle(typeid(int)).toStdString();\n\n\/\/ Tests that when we call throwException, the proper type is thrown (derived)\nTEST(ExceptionWrapper, throw_test) {\n std::runtime_error e(\"payload\");\n auto ew = make_exception_wrapper(e);\n\n std::vector container;\n container.push_back(ew);\n\n try {\n container[0].throwException();\n } catch (std::runtime_error& e) {\n std::string expected = \"payload\";\n std::string actual = e.what();\n EXPECT_EQ(expected, actual);\n }\n}\n\nTEST(ExceptionWrapper, members) {\n auto ew = exception_wrapper();\n EXPECT_FALSE(bool(ew));\n EXPECT_EQ(ew.what(), \"\");\n EXPECT_EQ(ew.class_name(), \"\");\n ew = make_exception_wrapper(\"payload\");\n EXPECT_TRUE(bool(ew));\n EXPECT_EQ(ew.what(), kRuntimeErrorClassName + \": payload\");\n EXPECT_EQ(ew.class_name(), kRuntimeErrorClassName);\n}\n\nTEST(ExceptionWrapper, equals) {\n std::runtime_error e(\"payload\");\n auto ew1 = make_exception_wrapper(e);\n auto ew2 = ew1;\n EXPECT_EQ(ew1, ew2);\n\n auto ew3 = try_and_catch([&]() {\n throw std::runtime_error(\"payload\");\n });\n auto ew4 = try_and_catch([&]() {\n ew3.throwException();\n });\n EXPECT_EQ(ew3, ew4);\n}\n\nTEST(ExceptionWrapper, not_equals) {\n std::runtime_error e1(\"payload\");\n std::runtime_error e2(\"payload\");\n auto ew1 = make_exception_wrapper(e1);\n auto ew2 = make_exception_wrapper(e2);\n EXPECT_NE(ew1, ew2);\n\n auto ew3 = make_exception_wrapper(e1);\n auto ew4 = make_exception_wrapper(e1);\n EXPECT_NE(ew3, ew4);\n\n auto ew5 = try_and_catch([&]() {\n throw e1;\n });\n auto ew6 = try_and_catch([&]() {\n throw e1;\n });\n EXPECT_NE(ew5, ew6);\n}\n\nTEST(ExceptionWrapper, try_and_catch_test) {\n std::string expected = \"payload\";\n\n \/\/ Catch rightmost matching exception type\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw std::runtime_error(expected);\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_TRUE(ew.getCopied());\n EXPECT_EQ(ew.what(), kRuntimeErrorClassName + \": payload\");\n EXPECT_EQ(ew.class_name(), kRuntimeErrorClassName);\n auto rep = ew.is_compatible_with();\n EXPECT_TRUE(rep);\n\n \/\/ Changing order is like catching in wrong order. Beware of this in your\n \/\/ code.\n auto ew2 = try_and_catch([=]() {\n throw std::runtime_error(expected);\n });\n EXPECT_TRUE(bool(ew2));\n \/\/ We are catching a std::exception, not std::runtime_error.\n EXPECT_FALSE(ew2.getCopied());\n \/\/ But, we can still get the actual type if we want it.\n rep = ew2.is_compatible_with();\n EXPECT_TRUE(rep);\n\n \/\/ Catches even if not rightmost.\n auto ew3 = try_and_catch([]() {\n throw std::exception();\n });\n EXPECT_TRUE(bool(ew3));\n EXPECT_EQ(ew3.what(), kExceptionClassName + \": std::exception\");\n EXPECT_EQ(ew3.class_name(), kExceptionClassName);\n rep = ew3.is_compatible_with();\n EXPECT_FALSE(rep);\n\n \/\/ If does not catch, throws.\n EXPECT_THROW(\n try_and_catch([]() {\n throw std::exception();\n }),\n std::exception);\n}\n\nTEST(ExceptionWrapper, with_exception_test) {\n int expected = 23;\n\n \/\/ This works, and doesn't slice.\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw IntException(expected);\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_EQ(ew.what(), kIntExceptionClassName + \": int == 23\");\n EXPECT_EQ(ew.class_name(), kIntExceptionClassName);\n EXPECT_TRUE(ew.with_exception(\n [&](const IntException& ie) { EXPECT_EQ(ie.getInt(), expected); }));\n\n \/\/ I can try_and_catch a non-copyable base class. This will use\n \/\/ std::exception_ptr internally.\n exception_wrapper ew2 = try_and_catch(\n [=]() {\n throw IntException(expected);\n });\n EXPECT_TRUE(bool(ew2));\n EXPECT_EQ(ew2.what(), kIntExceptionClassName + \": int == 23\");\n EXPECT_EQ(ew2.class_name(), kIntExceptionClassName);\n EXPECT_TRUE(ew2.with_exception([&](AbstractIntException& ie) {\n EXPECT_EQ(ie.getInt(), expected);\n EXPECT_TRUE(dynamic_cast(&ie));\n }));\n\n \/\/ Test with const this. If this compiles and does not crash due to\n \/\/ infinite loop when it runs, it succeeds.\n const exception_wrapper& cew = ew;\n EXPECT_TRUE(\n cew.with_exception([&](const IntException& \/* ie *\/) { SUCCEED(); }));\n\n \/\/ Test with empty ew.\n exception_wrapper empty_ew;\n EXPECT_FALSE(\n empty_ew.with_exception([&](const std::exception& \/* ie *\/) { FAIL(); }));\n\n \/\/ This won't even compile. You can't use a function which takes a\n \/\/ non-const reference with a const exception_wrapper.\n\/*\n cew.with_exception([&](IntException& ie) {\n SUCCEED();\n });\n*\/\n}\n\nTEST(ExceptionWrapper, getExceptionPtr_test) {\n int expected = 23;\n\n \/\/ This works, and doesn't slice.\n exception_wrapper ew = try_and_catch(\n [=]() { throw IntException(expected); });\n std::exception_ptr eptr = ew.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ I can try_and_catch a non-copyable base class. This will use\n \/\/ std::exception_ptr internally.\n exception_wrapper ew2 = try_and_catch(\n [=]() { throw IntException(expected); });\n eptr = ew2.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ Test with const this.\n const exception_wrapper& cew = ew;\n eptr = cew.getExceptionPtr();\n EXPECT_THROW(std::rethrow_exception(eptr), IntException);\n\n \/\/ Test with empty ew.\n exception_wrapper empty_ew;\n eptr = empty_ew.getExceptionPtr();\n EXPECT_FALSE(eptr);\n}\n\nTEST(ExceptionWrapper, with_exception_deduction) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](std::runtime_error&) {}));\n EXPECT_TRUE(ew.with_exception([](std::exception&) {}));\n EXPECT_FALSE(ew.with_exception([](std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_exn_const) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](const std::runtime_error&) {}));\n EXPECT_TRUE(ew.with_exception([](const std::exception&) {}));\n EXPECT_FALSE(ew.with_exception([](const std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_wrap_const_exn_const) {\n const auto cew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(cew.with_exception([](const std::runtime_error&) {}));\n EXPECT_TRUE(cew.with_exception([](const std::exception&) {}));\n EXPECT_FALSE(cew.with_exception([](const std::logic_error&) {}));\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_returning) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception([](std::runtime_error&) { return 3; }));\n EXPECT_TRUE(ew.with_exception([](std::exception&) { return \"hello\"; }));\n EXPECT_FALSE(ew.with_exception([](std::logic_error&) { return nullptr; }));\n}\n\nnamespace {\ntemplate \nT& r_to_l(T v) { return std::ref(v); }\n}\n\nTEST(ExceptionWrapper, with_exception_deduction_functor_lvalue) {\n auto ew = make_exception_wrapper(\"hi\");\n EXPECT_TRUE(ew.with_exception(r_to_l([](std::runtime_error&) {})));\n EXPECT_TRUE(ew.with_exception(r_to_l([](std::exception&) {})));\n EXPECT_FALSE(ew.with_exception(r_to_l([](std::logic_error&) {})));\n}\n\nTEST(ExceptionWrapper, non_std_exception_test) {\n int expected = 17;\n\n exception_wrapper ew = try_and_catch(\n [=]() {\n throw expected;\n });\n EXPECT_TRUE(bool(ew));\n EXPECT_FALSE(ew.is_compatible_with());\n EXPECT_EQ(ew.what(), kIntClassName);\n EXPECT_EQ(ew.class_name(), kIntClassName);\n \/\/ non-std::exception types are supported, but the only way to\n \/\/ access their value is to explicity rethrow and catch it.\n try {\n ew.throwException();\n } catch \/* nolint *\/ (int& i) {\n EXPECT_EQ(i, expected);\n }\n}\n\n\nTEST(ExceptionWrapper, exceptionStr) {\n auto ew = make_exception_wrapper(\"argh\");\n EXPECT_EQ(kRuntimeErrorClassName + \": argh\", exceptionStr(ew));\n}\n\nTEST(ExceptionWrapper, throwException_noException) {\n exception_wrapper ew;\n ASSERT_DEATH(ew.throwException(), \"empty folly::exception_wrapper\");\n}\n\nnamespace {\nclass TestException : public std::exception { };\nvoid testEW(const exception_wrapper& ew) {\n EXPECT_THROW(ew.throwException(), TestException);\n}\n} \/\/ namespace\n\nTEST(ExceptionWrapper, implicitConstruction) {\n \/\/ Try with both lvalue and rvalue references\n TestException e;\n testEW(e);\n testEW(TestException());\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2008, Google Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without \n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, \n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of Google Inc. nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ The file contains the implementation of the File methods specific to\n\/\/ POSIX platforms.\n\n#include \"kml\/base\/file.h\"\n#include \n#include \n#include \n#include \n\nnamespace kmlbase {\n\n\/\/ Internal to the POSIX File class.\nstatic bool StatFile(const char* path, struct stat* stat_data) {\n struct stat tmp;\n if (stat(path, &tmp) !=0) {\n return false;\n }\n *stat_data = tmp;\n return true;\n}\n\nbool File::Exists(const string& full_path) {\n struct stat stat_data;\n if (!StatFile(full_path.c_str(), &stat_data)) {\n return false;\n }\n return S_ISREG(stat_data.st_mode);\n}\n\nbool File::Delete(const string& filepath) {\n return unlink(filepath.c_str()) == 0;\n}\n\nbool File::CreateNewTempFile(string* path) {\n if (!path) {\n return false;\n }\n char temp_path[] = \"\/tmp\/libkmlXXXXXX\";\n int fd = mkstemp(temp_path);\n if (fd == -1) {\n return false;\n }\n close(fd);\n path->assign(temp_path, strlen(temp_path));\n return true;\n}\n\n} \/\/ end namespace kmlbase\nBUG: missing include file\/\/ Copyright 2008, Google Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without \n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, \n\/\/ this list of conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/ 3. Neither the name of Google Inc. nor the names of its contributors may be\n\/\/ used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED\n\/\/ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF \n\/\/ MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO\n\/\/ EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, \n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n\/\/ OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n\/\/ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR \n\/\/ OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF \n\/\/ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ The file contains the implementation of the File methods specific to\n\/\/ POSIX platforms.\n\n#include \"kml\/base\/file.h\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace kmlbase {\n\n\/\/ Internal to the POSIX File class.\nstatic bool StatFile(const char* path, struct stat* stat_data) {\n struct stat tmp;\n if (stat(path, &tmp) !=0) {\n return false;\n }\n *stat_data = tmp;\n return true;\n}\n\nbool File::Exists(const string& full_path) {\n struct stat stat_data;\n if (!StatFile(full_path.c_str(), &stat_data)) {\n return false;\n }\n return S_ISREG(stat_data.st_mode);\n}\n\nbool File::Delete(const string& filepath) {\n return unlink(filepath.c_str()) == 0;\n}\n\nbool File::CreateNewTempFile(string* path) {\n if (!path) {\n return false;\n }\n char temp_path[] = \"\/tmp\/libkmlXXXXXX\";\n int fd = mkstemp(temp_path);\n if (fd == -1) {\n return false;\n }\n close(fd);\n path->assign(temp_path, strlen(temp_path));\n return true;\n}\n\n} \/\/ end namespace kmlbase\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/thread.h\"\n\n#include \"vm\/growable_array.h\"\n#include \"vm\/isolate.h\"\n#include \"vm\/lockers.h\"\n#include \"vm\/object.h\"\n#include \"vm\/os_thread.h\"\n#include \"vm\/profiler.h\"\n#include \"vm\/stub_code.h\"\n#include \"vm\/thread_interrupter.h\"\n#include \"vm\/thread_registry.h\"\n\nnamespace dart {\n\n\/\/ The single thread local key which stores all the thread local data\n\/\/ for a thread.\nThreadLocalKey Thread::thread_key_ = OSThread::kUnsetThreadLocalKey;\n\n\n\/\/ Remove |thread| from each isolate's thread registry.\nclass ThreadPruner : public IsolateVisitor {\n public:\n explicit ThreadPruner(Thread* thread)\n : thread_(thread) {\n ASSERT(thread_ != NULL);\n }\n\n void VisitIsolate(Isolate* isolate) {\n ThreadRegistry* registry = isolate->thread_registry();\n ASSERT(registry != NULL);\n registry->PruneThread(thread_);\n }\n private:\n Thread* thread_;\n};\n\n\nstatic void DeleteThread(void* thread) {\n delete reinterpret_cast(thread);\n}\n\n\nThread::~Thread() {\n \/\/ We should cleanly exit any isolate before destruction.\n ASSERT(isolate_ == NULL);\n \/\/ Clear |this| from all isolate's thread registry.\n ThreadPruner pruner(this);\n Isolate::VisitIsolates(&pruner);\n}\n\n\nvoid Thread::InitOnceBeforeIsolate() {\n ASSERT(thread_key_ == OSThread::kUnsetThreadLocalKey);\n thread_key_ = OSThread::CreateThreadLocal(DeleteThread);\n ASSERT(thread_key_ != OSThread::kUnsetThreadLocalKey);\n ASSERT(Thread::Current() == NULL);\n \/\/ Allocate a new Thread and postpone initialization of VM constants for\n \/\/ this first thread.\n Thread* thread = new Thread(false);\n \/\/ Verify that current thread was set.\n ASSERT(Thread::Current() == thread);\n}\n\n\nvoid Thread::InitOnceAfterObjectAndStubCode() {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == Dart::vm_isolate());\n thread->InitVMConstants();\n}\n\n\nvoid Thread::SetCurrent(Thread* current) {\n OSThread::SetThreadLocal(thread_key_, reinterpret_cast(current));\n}\n\n\nvoid Thread::EnsureInit() {\n if (Thread::Current() == NULL) {\n \/\/ Allocate a new Thread.\n Thread* thread = new Thread();\n \/\/ Verify that current thread was set.\n ASSERT(Thread::Current() == thread);\n }\n}\n\n\n#if defined(TARGET_OS_WINDOWS)\nvoid Thread::CleanUp() {\n Thread* current = Current();\n if (current != NULL) {\n delete current;\n }\n SetCurrent(NULL);\n}\n#endif\n\n\nThread::Thread(bool init_vm_constants)\n : id_(OSThread::GetCurrentThreadId()),\n isolate_(NULL),\n store_buffer_block_(NULL) {\n ClearState();\n#define DEFAULT_INIT(type_name, member_name, init_expr, default_init_value) \\\n member_name = default_init_value;\nCACHED_CONSTANTS_LIST(DEFAULT_INIT)\n#undef DEFAULT_INIT\n if (init_vm_constants) {\n InitVMConstants();\n }\n SetCurrent(this);\n}\n\n\nvoid Thread::InitVMConstants() {\n#define ASSERT_VM_HEAP(type_name, member_name, init_expr, default_init_value) \\\n ASSERT((init_expr)->IsOldObject());\nCACHED_VM_OBJECTS_LIST(ASSERT_VM_HEAP)\n#undef ASSERT_VM_HEAP\n\n#define INIT_VALUE(type_name, member_name, init_expr, default_init_value) \\\n ASSERT(member_name == default_init_value); \\\n member_name = (init_expr);\nCACHED_CONSTANTS_LIST(INIT_VALUE)\n#undef INIT_VALUE\n}\n\n\nvoid Thread::Schedule(Isolate* isolate) {\n State st;\n if (isolate->thread_registry()->RestoreStateTo(this, &st)) {\n ASSERT(isolate->thread_registry()->Contains(this));\n state_ = st;\n }\n}\n\n\nvoid Thread::Unschedule() {\n ThreadRegistry* reg = isolate_->thread_registry();\n ASSERT(reg->Contains(this));\n reg->SaveStateFrom(this, state_);\n ClearState();\n}\n\n\nvoid Thread::EnterIsolate(Isolate* isolate) {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == NULL);\n ASSERT(!isolate->HasMutatorThread());\n thread->isolate_ = isolate;\n isolate->MakeCurrentThreadMutator(thread);\n isolate->set_vm_tag(VMTag::kVMTagId);\n ASSERT(thread->store_buffer_block_ == NULL);\n thread->StoreBufferAcquire();\n ASSERT(isolate->heap() != NULL);\n thread->heap_ = isolate->heap();\n thread->Schedule(isolate);\n \/\/ TODO(koda): Migrate profiler interface to use Thread.\n Profiler::BeginExecution(isolate);\n}\n\n\nvoid Thread::ExitIsolate() {\n Thread* thread = Thread::Current();\n \/\/ TODO(koda): Audit callers; they should know whether they're in an isolate.\n if (thread == NULL || thread->isolate() == NULL) return;\n Isolate* isolate = thread->isolate();\n Profiler::EndExecution(isolate);\n thread->Unschedule();\n \/\/ TODO(koda): Move store_buffer_block_ into State.\n thread->StoreBufferRelease();\n if (isolate->is_runnable()) {\n isolate->set_vm_tag(VMTag::kIdleTagId);\n } else {\n isolate->set_vm_tag(VMTag::kLoadWaitTagId);\n }\n isolate->ClearMutatorThread();\n thread->isolate_ = NULL;\n ASSERT(Isolate::Current() == NULL);\n thread->heap_ = NULL;\n}\n\n\nvoid Thread::EnterIsolateAsHelper(Isolate* isolate) {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == NULL);\n thread->isolate_ = isolate;\n ASSERT(thread->store_buffer_block_ == NULL);\n \/\/ TODO(koda): Use StoreBufferAcquire once we properly flush before Scavenge.\n thread->store_buffer_block_ =\n thread->isolate()->store_buffer()->PopEmptyBlock();\n ASSERT(isolate->heap() != NULL);\n thread->heap_ = isolate->heap();\n ASSERT(thread->thread_state() == NULL);\n \/\/ Do not update isolate->mutator_thread, but perform sanity check:\n \/\/ this thread should not be both the main mutator and helper.\n ASSERT(!isolate->MutatorThreadIsCurrentThread());\n thread->Schedule(isolate);\n}\n\n\nvoid Thread::ExitIsolateAsHelper() {\n Thread* thread = Thread::Current();\n Isolate* isolate = thread->isolate();\n ASSERT(isolate != NULL);\n thread->Unschedule();\n \/\/ TODO(koda): Move store_buffer_block_ into State.\n thread->StoreBufferRelease();\n thread->set_thread_state(NULL);\n thread->isolate_ = NULL;\n thread->heap_ = NULL;\n ASSERT(!isolate->MutatorThreadIsCurrentThread());\n}\n\n\n\/\/ TODO(koda): Make non-static and invoke in SafepointThreads.\nvoid Thread::PrepareForGC() {\n Thread* thread = Thread::Current();\n const bool kDoNotCheckThreshold = false; \/\/ Prevent scheduling another GC.\n thread->StoreBufferRelease(kDoNotCheckThreshold);\n \/\/ Make sure to get an *empty* block; the isolate needs all entries\n \/\/ at GC time.\n \/\/ TODO(koda): Replace with an epilogue (PrepareAfterGC) that acquires.\n thread->store_buffer_block_ =\n thread->isolate()->store_buffer()->PopEmptyBlock();\n}\n\n\nvoid Thread::StoreBufferBlockProcess(bool check_threshold) {\n StoreBufferRelease(check_threshold);\n StoreBufferAcquire();\n}\n\n\nvoid Thread::StoreBufferAddObject(RawObject* obj) {\n store_buffer_block_->Push(obj);\n if (store_buffer_block_->IsFull()) {\n StoreBufferBlockProcess(true);\n }\n}\n\n\nvoid Thread::StoreBufferAddObjectGC(RawObject* obj) {\n store_buffer_block_->Push(obj);\n if (store_buffer_block_->IsFull()) {\n StoreBufferBlockProcess(false);\n }\n}\n\n\nvoid Thread::StoreBufferRelease(bool check_threshold) {\n StoreBufferBlock* block = store_buffer_block_;\n store_buffer_block_ = NULL;\n isolate_->store_buffer()->PushBlock(block, check_threshold);\n}\n\n\nvoid Thread::StoreBufferAcquire() {\n store_buffer_block_ = isolate()->store_buffer()->PopNonFullBlock();\n}\n\n\nCHA* Thread::cha() const {\n ASSERT(isolate_ != NULL);\n return isolate_->cha_;\n}\n\n\nvoid Thread::set_cha(CHA* value) {\n ASSERT(isolate_ != NULL);\n isolate_->cha_ = value;\n}\n\n\nvoid Thread::SetThreadInterrupter(ThreadInterruptCallback callback,\n void* data) {\n ASSERT(Thread::Current() == this);\n thread_interrupt_callback_ = callback;\n thread_interrupt_data_ = data;\n}\n\n\nbool Thread::IsThreadInterrupterEnabled(ThreadInterruptCallback* callback,\n void** data) const {\n#if defined(TARGET_OS_WINDOWS)\n \/\/ On Windows we expect this to be called from the thread interrupter thread.\n ASSERT(id() != OSThread::GetCurrentThreadId());\n#else\n \/\/ On posix platforms, we expect this to be called from signal handler.\n ASSERT(id() == OSThread::GetCurrentThreadId());\n#endif\n ASSERT(callback != NULL);\n ASSERT(data != NULL);\n *callback = thread_interrupt_callback_;\n *data = thread_interrupt_data_;\n return (*callback != NULL) &&\n (*data != NULL);\n}\n\n\nbool Thread::CanLoadFromThread(const Object& object) {\n#define CHECK_OBJECT(type_name, member_name, expr, default_init_value) \\\n if (object.raw() == expr) return true;\nCACHED_VM_OBJECTS_LIST(CHECK_OBJECT)\n#undef CHECK_OBJECT\n return false;\n}\n\n\nintptr_t Thread::OffsetFromThread(const Object& object) {\n#define COMPUTE_OFFSET(type_name, member_name, expr, default_init_value) \\\n ASSERT((expr)->IsVMHeapObject()); \\\n if (object.raw() == expr) return Thread::member_name##offset();\nCACHED_VM_OBJECTS_LIST(COMPUTE_OFFSET)\n#undef COMPUTE_OFFSET\n UNREACHABLE();\n return -1;\n}\n\n} \/\/ namespace dart\n- Initialize fields used in the profiler interrupts.\/\/ Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file\n\/\/ for details. All rights reserved. Use of this source code is governed by a\n\/\/ BSD-style license that can be found in the LICENSE file.\n\n#include \"vm\/thread.h\"\n\n#include \"vm\/growable_array.h\"\n#include \"vm\/isolate.h\"\n#include \"vm\/lockers.h\"\n#include \"vm\/object.h\"\n#include \"vm\/os_thread.h\"\n#include \"vm\/profiler.h\"\n#include \"vm\/stub_code.h\"\n#include \"vm\/thread_interrupter.h\"\n#include \"vm\/thread_registry.h\"\n\nnamespace dart {\n\n\/\/ The single thread local key which stores all the thread local data\n\/\/ for a thread.\nThreadLocalKey Thread::thread_key_ = OSThread::kUnsetThreadLocalKey;\n\n\n\/\/ Remove |thread| from each isolate's thread registry.\nclass ThreadPruner : public IsolateVisitor {\n public:\n explicit ThreadPruner(Thread* thread)\n : thread_(thread) {\n ASSERT(thread_ != NULL);\n }\n\n void VisitIsolate(Isolate* isolate) {\n ThreadRegistry* registry = isolate->thread_registry();\n ASSERT(registry != NULL);\n registry->PruneThread(thread_);\n }\n private:\n Thread* thread_;\n};\n\n\nstatic void DeleteThread(void* thread) {\n delete reinterpret_cast(thread);\n}\n\n\nThread::~Thread() {\n \/\/ We should cleanly exit any isolate before destruction.\n ASSERT(isolate_ == NULL);\n \/\/ Clear |this| from all isolate's thread registry.\n ThreadPruner pruner(this);\n Isolate::VisitIsolates(&pruner);\n}\n\n\nvoid Thread::InitOnceBeforeIsolate() {\n ASSERT(thread_key_ == OSThread::kUnsetThreadLocalKey);\n thread_key_ = OSThread::CreateThreadLocal(DeleteThread);\n ASSERT(thread_key_ != OSThread::kUnsetThreadLocalKey);\n ASSERT(Thread::Current() == NULL);\n \/\/ Allocate a new Thread and postpone initialization of VM constants for\n \/\/ this first thread.\n Thread* thread = new Thread(false);\n \/\/ Verify that current thread was set.\n ASSERT(Thread::Current() == thread);\n}\n\n\nvoid Thread::InitOnceAfterObjectAndStubCode() {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == Dart::vm_isolate());\n thread->InitVMConstants();\n}\n\n\nvoid Thread::SetCurrent(Thread* current) {\n OSThread::SetThreadLocal(thread_key_, reinterpret_cast(current));\n}\n\n\nvoid Thread::EnsureInit() {\n if (Thread::Current() == NULL) {\n \/\/ Allocate a new Thread.\n Thread* thread = new Thread();\n \/\/ Verify that current thread was set.\n ASSERT(Thread::Current() == thread);\n }\n}\n\n\n#if defined(TARGET_OS_WINDOWS)\nvoid Thread::CleanUp() {\n Thread* current = Current();\n if (current != NULL) {\n delete current;\n }\n SetCurrent(NULL);\n}\n#endif\n\n\nThread::Thread(bool init_vm_constants)\n : id_(OSThread::GetCurrentThreadId()),\n thread_interrupt_callback_(NULL),\n thread_interrupt_data_(NULL),\n isolate_(NULL),\n heap_(NULL),\n store_buffer_block_(NULL) {\n ClearState();\n#define DEFAULT_INIT(type_name, member_name, init_expr, default_init_value) \\\n member_name = default_init_value;\nCACHED_CONSTANTS_LIST(DEFAULT_INIT)\n#undef DEFAULT_INIT\n if (init_vm_constants) {\n InitVMConstants();\n }\n SetCurrent(this);\n}\n\n\nvoid Thread::InitVMConstants() {\n#define ASSERT_VM_HEAP(type_name, member_name, init_expr, default_init_value) \\\n ASSERT((init_expr)->IsOldObject());\nCACHED_VM_OBJECTS_LIST(ASSERT_VM_HEAP)\n#undef ASSERT_VM_HEAP\n\n#define INIT_VALUE(type_name, member_name, init_expr, default_init_value) \\\n ASSERT(member_name == default_init_value); \\\n member_name = (init_expr);\nCACHED_CONSTANTS_LIST(INIT_VALUE)\n#undef INIT_VALUE\n}\n\n\nvoid Thread::Schedule(Isolate* isolate) {\n State st;\n if (isolate->thread_registry()->RestoreStateTo(this, &st)) {\n ASSERT(isolate->thread_registry()->Contains(this));\n state_ = st;\n }\n}\n\n\nvoid Thread::Unschedule() {\n ThreadRegistry* reg = isolate_->thread_registry();\n ASSERT(reg->Contains(this));\n reg->SaveStateFrom(this, state_);\n ClearState();\n}\n\n\nvoid Thread::EnterIsolate(Isolate* isolate) {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == NULL);\n ASSERT(!isolate->HasMutatorThread());\n thread->isolate_ = isolate;\n isolate->MakeCurrentThreadMutator(thread);\n isolate->set_vm_tag(VMTag::kVMTagId);\n ASSERT(thread->store_buffer_block_ == NULL);\n thread->StoreBufferAcquire();\n ASSERT(isolate->heap() != NULL);\n thread->heap_ = isolate->heap();\n thread->Schedule(isolate);\n \/\/ TODO(koda): Migrate profiler interface to use Thread.\n Profiler::BeginExecution(isolate);\n}\n\n\nvoid Thread::ExitIsolate() {\n Thread* thread = Thread::Current();\n \/\/ TODO(koda): Audit callers; they should know whether they're in an isolate.\n if (thread == NULL || thread->isolate() == NULL) return;\n Isolate* isolate = thread->isolate();\n Profiler::EndExecution(isolate);\n thread->Unschedule();\n \/\/ TODO(koda): Move store_buffer_block_ into State.\n thread->StoreBufferRelease();\n if (isolate->is_runnable()) {\n isolate->set_vm_tag(VMTag::kIdleTagId);\n } else {\n isolate->set_vm_tag(VMTag::kLoadWaitTagId);\n }\n isolate->ClearMutatorThread();\n thread->isolate_ = NULL;\n ASSERT(Isolate::Current() == NULL);\n thread->heap_ = NULL;\n}\n\n\nvoid Thread::EnterIsolateAsHelper(Isolate* isolate) {\n Thread* thread = Thread::Current();\n ASSERT(thread != NULL);\n ASSERT(thread->isolate() == NULL);\n thread->isolate_ = isolate;\n ASSERT(thread->store_buffer_block_ == NULL);\n \/\/ TODO(koda): Use StoreBufferAcquire once we properly flush before Scavenge.\n thread->store_buffer_block_ =\n thread->isolate()->store_buffer()->PopEmptyBlock();\n ASSERT(isolate->heap() != NULL);\n thread->heap_ = isolate->heap();\n ASSERT(thread->thread_state() == NULL);\n \/\/ Do not update isolate->mutator_thread, but perform sanity check:\n \/\/ this thread should not be both the main mutator and helper.\n ASSERT(!isolate->MutatorThreadIsCurrentThread());\n thread->Schedule(isolate);\n}\n\n\nvoid Thread::ExitIsolateAsHelper() {\n Thread* thread = Thread::Current();\n Isolate* isolate = thread->isolate();\n ASSERT(isolate != NULL);\n thread->Unschedule();\n \/\/ TODO(koda): Move store_buffer_block_ into State.\n thread->StoreBufferRelease();\n thread->set_thread_state(NULL);\n thread->isolate_ = NULL;\n thread->heap_ = NULL;\n ASSERT(!isolate->MutatorThreadIsCurrentThread());\n}\n\n\n\/\/ TODO(koda): Make non-static and invoke in SafepointThreads.\nvoid Thread::PrepareForGC() {\n Thread* thread = Thread::Current();\n const bool kDoNotCheckThreshold = false; \/\/ Prevent scheduling another GC.\n thread->StoreBufferRelease(kDoNotCheckThreshold);\n \/\/ Make sure to get an *empty* block; the isolate needs all entries\n \/\/ at GC time.\n \/\/ TODO(koda): Replace with an epilogue (PrepareAfterGC) that acquires.\n thread->store_buffer_block_ =\n thread->isolate()->store_buffer()->PopEmptyBlock();\n}\n\n\nvoid Thread::StoreBufferBlockProcess(bool check_threshold) {\n StoreBufferRelease(check_threshold);\n StoreBufferAcquire();\n}\n\n\nvoid Thread::StoreBufferAddObject(RawObject* obj) {\n store_buffer_block_->Push(obj);\n if (store_buffer_block_->IsFull()) {\n StoreBufferBlockProcess(true);\n }\n}\n\n\nvoid Thread::StoreBufferAddObjectGC(RawObject* obj) {\n store_buffer_block_->Push(obj);\n if (store_buffer_block_->IsFull()) {\n StoreBufferBlockProcess(false);\n }\n}\n\n\nvoid Thread::StoreBufferRelease(bool check_threshold) {\n StoreBufferBlock* block = store_buffer_block_;\n store_buffer_block_ = NULL;\n isolate_->store_buffer()->PushBlock(block, check_threshold);\n}\n\n\nvoid Thread::StoreBufferAcquire() {\n store_buffer_block_ = isolate()->store_buffer()->PopNonFullBlock();\n}\n\n\nCHA* Thread::cha() const {\n ASSERT(isolate_ != NULL);\n return isolate_->cha_;\n}\n\n\nvoid Thread::set_cha(CHA* value) {\n ASSERT(isolate_ != NULL);\n isolate_->cha_ = value;\n}\n\n\nvoid Thread::SetThreadInterrupter(ThreadInterruptCallback callback,\n void* data) {\n ASSERT(Thread::Current() == this);\n thread_interrupt_callback_ = callback;\n thread_interrupt_data_ = data;\n}\n\n\nbool Thread::IsThreadInterrupterEnabled(ThreadInterruptCallback* callback,\n void** data) const {\n#if defined(TARGET_OS_WINDOWS)\n \/\/ On Windows we expect this to be called from the thread interrupter thread.\n ASSERT(id() != OSThread::GetCurrentThreadId());\n#else\n \/\/ On posix platforms, we expect this to be called from signal handler.\n ASSERT(id() == OSThread::GetCurrentThreadId());\n#endif\n ASSERT(callback != NULL);\n ASSERT(data != NULL);\n *callback = thread_interrupt_callback_;\n *data = thread_interrupt_data_;\n return (*callback != NULL) &&\n (*data != NULL);\n}\n\n\nbool Thread::CanLoadFromThread(const Object& object) {\n#define CHECK_OBJECT(type_name, member_name, expr, default_init_value) \\\n if (object.raw() == expr) return true;\nCACHED_VM_OBJECTS_LIST(CHECK_OBJECT)\n#undef CHECK_OBJECT\n return false;\n}\n\n\nintptr_t Thread::OffsetFromThread(const Object& object) {\n#define COMPUTE_OFFSET(type_name, member_name, expr, default_init_value) \\\n ASSERT((expr)->IsVMHeapObject()); \\\n if (object.raw() == expr) return Thread::member_name##offset();\nCACHED_VM_OBJECTS_LIST(COMPUTE_OFFSET)\n#undef COMPUTE_OFFSET\n UNREACHABLE();\n return -1;\n}\n\n} \/\/ namespace dart\n<|endoftext|>"} {"text":"\/*\n ircaccount.cpp - IRC Account\n\n Copyright (c) 2002 by Nick Betcher \n\n Kopete (c) 2002 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kopeteaway.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetemetacontact.h\"\n\n#include \"ircaccount.h\"\n#include \"ircprotocol.h\"\n#include \"irccontactmanager.h\"\n#include \"ircservercontact.h\"\n#include \"ircchannelcontact.h\"\n#include \"ircusercontact.h\"\n#include \"ksparser.h\"\n\nIRCAccount::IRCAccount(IRCProtocol *protocol, const QString &accountId)\n\t: KopeteAccount(protocol, accountId)\n{\n\tm_manager = 0L;\n\tm_protocol = protocol;\n\n\tmNickName = accountId.section('@',0,0);\n\tQString serverInfo = accountId.section('@',1);\n\tm_server = serverInfo.section(':',0,0);\n\tm_port = serverInfo.section(':',1).toUInt();\n\n\tm_engine = new KIRC( m_server, m_port );\n\tQString version=i18n(\"Kopete IRC Plugin %1 [http:\/\/kopete.kde.org]\").arg(kapp->aboutData()->version());\n\tm_engine->setVersionString( version );\n\tif( rememberPassword() )\n\t\tm_engine->setPassword( password() );\n\n\tQObject::connect(m_engine, SIGNAL(successfullyChangedNick(const QString &, const QString &)),\n\t\t\tthis, SLOT(successfullyChangedNick(const QString &, const QString &)));\n\n\tm_contactManager = new IRCContactManager(mNickName, m_server, this);\n\tm_mySelf = m_contactManager->mySelf();\n\tm_myServer = m_contactManager->myServer();\n}\n\nIRCAccount::~IRCAccount()\n{\n\/\/\tkdDebug(14120) << k_funcinfo << mServer << \" \" << engine() << endl;\n\tif ( engine()->isConnected() )\n\t\tengine()->quitIRC(i18n(\"Plugin Unloaded\"), true);\n\n\tdelete m_contactManager;\n\tdelete m_engine;\n}\n\nvoid IRCAccount::loaded()\n{\n\tm_engine->setUserName(userName());\n}\n\nQString IRCAccount::userName()\n{\n\treturn pluginData(protocol(), QString::fromLatin1(\"userName\"));\n}\n\nvoid IRCAccount::setUserName(QString userName)\n{\n\tm_engine->setUserName(userName);\n\tsetPluginData(protocol(), QString::fromLatin1( \"userName\" ), userName);\n}\n\nKActionMenu *IRCAccount::actionMenu()\n{\n\tQString menuTitle = QString::fromLatin1( \" %1 <%2> \" ).arg( accountId() ).arg( m_mySelf->onlineStatus().description() );\n\n\tKActionMenu *mActionMenu = new KActionMenu( accountId(),myself()->onlineStatus().iconFor(this), this, \"IRCAccount::mActionMenu\" );\n\tmActionMenu->popupMenu()->insertTitle( m_mySelf->onlineStatus().iconFor( m_mySelf ), menuTitle );\n\n\tmActionMenu->insert( new KAction ( i18n(\"Go Online\"), m_protocol->m_UserStatusOnline.iconFor( this ), 0, this, SLOT(connect()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Set Away\"), m_protocol->m_UserStatusAway.iconFor( this ), 0, this, SLOT(slotGoAway()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Go Offline\"), m_protocol->m_UserStatusOffline.iconFor( this ), 0, this, SLOT(disconnect()), mActionMenu ) );\n\tmActionMenu->popupMenu()->insertSeparator();\n\tmActionMenu->insert( new KAction ( i18n(\"Join Channel...\"), \"\", 0, this, SLOT(slotJoinChannel()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Show Server Window\"), \"\", 0, this, SLOT(slotShowServerWindow()), mActionMenu ) );\n\n\treturn mActionMenu;\n}\n\nvoid IRCAccount::connect()\n{\n\tif( m_engine->isConnected() )\n\t{\n\t\tif( isAway() )\n\t\t\tsetAway( false );\n\t}\n\telse if( m_engine->isDisconnected() )\n\t{\n\t\tm_engine->connectToServer( m_mySelf->nickName() );\n\t}\n}\n\nvoid IRCAccount::disconnect()\n{\n\tm_engine->quitIRC(\"Kopete IRC [http:\/\/kopete.kde.org]\");\n}\n\nvoid IRCAccount::setAway( bool isAway, const QString &awayMessage )\n{\n\tkdDebug(14120) << k_funcinfo << isAway << \" \" << awayMessage << endl;\n\tif(m_engine->isConnected())\n\t{\n\t\tm_mySelf->setAway( isAway );\n\t\tengine()->setAway( isAway, awayMessage );\n\t}\n}\n\nvoid IRCAccount::slotGoAway()\n{\n\tsetAway( true, KopeteAway::message() );\n}\n\nvoid IRCAccount::slotShowServerWindow()\n{\n\tm_myServer->startServerChat();\n}\n\nbool IRCAccount::isConnected()\n{\n\treturn (m_mySelf->onlineStatus().status() == KopeteOnlineStatus::Online);\n}\n\nvoid IRCAccount::unregister(KopeteContact *contact)\n{\n\tm_contactManager->unregister(contact);\n}\n\nIRCServerContact *IRCAccount::findServer( const QString &name, KopeteMetaContact *m )\n{\n\treturn m_contactManager->findServer(name, m);\n}\n\nvoid IRCAccount::unregisterServer( const QString &name )\n{\n\tm_contactManager->unregisterServer(name);\n}\n\nIRCChannelContact *IRCAccount::findChannel( const QString &name, KopeteMetaContact *m )\n{\n\treturn m_contactManager->findChannel(name, m);\n}\n\nvoid IRCAccount::unregisterChannel( const QString &name )\n{\n\tm_contactManager->unregisterChannel(name);\n}\n\nIRCUserContact *IRCAccount::findUser(const QString &name, KopeteMetaContact *m)\n{\n\treturn m_contactManager->findUser(name, m);\n}\n\nvoid IRCAccount::unregisterUser( const QString &name )\n{\n\tm_contactManager->unregisterUser(name);\n}\n\nvoid IRCAccount::successfullyChangedNick(const QString &\/*oldnick*\/, const QString &newnick)\n{\n\tkdDebug(14120) << k_funcinfo << \"Changing nick to \" << newnick << endl;\n\tm_mySelf->manager()->setDisplayName( m_mySelf->caption() );\n\n\tif( isConnected() )\n\t\tm_engine->changeNickname( newnick );\n}\n\nbool IRCAccount::addContactToMetaContact( const QString &contactId, const QString &displayName,\n\t KopeteMetaContact *m )\n{\n\/\/\tkdDebug(14120) << k_funcinfo << contactId << \"|\" << displayName << endl;\n\t\/\/FIXME: I think there are too many tests in this functions. This function should be called ONLY by\n\t\/\/ KopeteAccount::addContact, where all test are already done. Can a irc developer look at this? -Olivier\n\tIRCContact *c;\n\n\tif( !m )\n\t{\/\/This should NEVER happen\n\t\tm = new KopeteMetaContact();\n\t\tKopeteContactList::contactList()->addMetaContact(m);\n\t\tm->setDisplayName( displayName );\n\t}\n\n\tif ( contactId.startsWith( QString::fromLatin1(\"#\") ) )\n\t\tc = static_cast( findChannel(contactId, m) );\n\telse\n\t{\n\t\tm_contactManager->addToNotifyList( contactId );\n\t\tc = static_cast( findUser(contactId, m) );\n\t}\n\n\tif( c->metaContact() != m )\n\t{\/\/This should NEVER happen\n\t\tKopeteMetaContact *old = c->metaContact();\n\t\tc->setMetaContact( m );\n\t\tKopeteContactPtrList children = old->contacts();\n\t\tif( children.isEmpty() )\n\t\t\tKopeteContactList::contactList()->removeMetaContact( old );\n\t}\n\telse if( c->metaContact()->isTemporary() ) \/\/FIXME: if the metacontact is temporary, that mean this is a temporary contact\n\t\tm->setTemporary(false);\n\n\treturn true;\n}\n\nvoid IRCAccount::slotJoinChannel()\n{\n\tif(!isConnected())\n\t\treturn;\n\n\tQString chan = KInputDialog::getText( i18n( \"IRC Plugin\" ),\n\t\ti18n( \"Please enter name of the channel you want to join:\" ), QString::null);\n\tif( !chan.isNull() )\n\t{\n\t\tif( chan.startsWith( QString::fromLatin1(\"#\") ) )\n\t\t\tfindChannel( chan )->startChat();\n\t\telse\n\t\t\tKMessageBox::error(0l, i18n(\"\\\"%1\\\" is an invalid channel. Channels must start with '#'.<\/qt>\").arg(chan), i18n(\"IRC Plugin\"));\n\t}\n}\n\nKopeteContact *IRCAccount::myself() const\n{\n\treturn m_mySelf;\n}\n\nIRCUserContact *IRCAccount::mySelf() const\n{\n\treturn m_mySelf;\n}\n\nIRCServerContact *IRCAccount::myServer() const\n{\n\treturn m_myServer;\n}\n\n#include \"ircaccount.moc\"\nFix crash\/*\n ircaccount.cpp - IRC Account\n\n Copyright (c) 2002 by Nick Betcher \n\n Kopete (c) 2002 by the Kopete developers \n\n *************************************************************************\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU General Public License as published by *\n * the Free Software Foundation; either version 2 of the License, or *\n * (at your option) any later version. *\n * *\n *************************************************************************\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kopeteaway.h\"\n#include \"kopetecontactlist.h\"\n#include \"kopetemetacontact.h\"\n\n#include \"ircaccount.h\"\n#include \"ircprotocol.h\"\n#include \"irccontactmanager.h\"\n#include \"ircservercontact.h\"\n#include \"ircchannelcontact.h\"\n#include \"ircusercontact.h\"\n#include \"ksparser.h\"\n\nIRCAccount::IRCAccount(IRCProtocol *protocol, const QString &accountId)\n\t: KopeteAccount(protocol, accountId)\n{\n\tm_manager = 0L;\n\tm_protocol = protocol;\n\n\tmNickName = accountId.section('@',0,0);\n\tQString serverInfo = accountId.section('@',1);\n\tm_server = serverInfo.section(':',0,0);\n\tm_port = serverInfo.section(':',1).toUInt();\n\n\tm_engine = new KIRC( m_server, m_port );\n\tQString version=i18n(\"Kopete IRC Plugin %1 [http:\/\/kopete.kde.org]\").arg(kapp->aboutData()->version());\n\tm_engine->setVersionString( version );\n\n\tQObject::connect(m_engine, SIGNAL(successfullyChangedNick(const QString &, const QString &)),\n\t\t\tthis, SLOT(successfullyChangedNick(const QString &, const QString &)));\n\n\n\tm_contactManager = new IRCContactManager(mNickName, m_server, this);\n\tm_mySelf = m_contactManager->mySelf();\n\tm_myServer = m_contactManager->myServer();\n\n\t\/\/Warning: requesting the password may ask to kwallet, this will open a dcop call and call QApplication::enter_loop\n\tif( rememberPassword() )\n\t\tm_engine->setPassword( password() );\n\n\n}\n\nIRCAccount::~IRCAccount()\n{\n\/\/\tkdDebug(14120) << k_funcinfo << mServer << \" \" << engine() << endl;\n\tif ( engine()->isConnected() )\n\t\tengine()->quitIRC(i18n(\"Plugin Unloaded\"), true);\n\n\tdelete m_contactManager;\n\tdelete m_engine;\n}\n\nvoid IRCAccount::loaded()\n{\n\tm_engine->setUserName(userName());\n}\n\nQString IRCAccount::userName()\n{\n\treturn pluginData(protocol(), QString::fromLatin1(\"userName\"));\n}\n\nvoid IRCAccount::setUserName(QString userName)\n{\n\tm_engine->setUserName(userName);\n\tsetPluginData(protocol(), QString::fromLatin1( \"userName\" ), userName);\n}\n\nKActionMenu *IRCAccount::actionMenu()\n{\n\tQString menuTitle = QString::fromLatin1( \" %1 <%2> \" ).arg( accountId() ).arg( m_mySelf->onlineStatus().description() );\n\n\tKActionMenu *mActionMenu = new KActionMenu( accountId(),myself()->onlineStatus().iconFor(this), this, \"IRCAccount::mActionMenu\" );\n\tmActionMenu->popupMenu()->insertTitle( m_mySelf->onlineStatus().iconFor( m_mySelf ), menuTitle );\n\n\tmActionMenu->insert( new KAction ( i18n(\"Go Online\"), m_protocol->m_UserStatusOnline.iconFor( this ), 0, this, SLOT(connect()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Set Away\"), m_protocol->m_UserStatusAway.iconFor( this ), 0, this, SLOT(slotGoAway()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Go Offline\"), m_protocol->m_UserStatusOffline.iconFor( this ), 0, this, SLOT(disconnect()), mActionMenu ) );\n\tmActionMenu->popupMenu()->insertSeparator();\n\tmActionMenu->insert( new KAction ( i18n(\"Join Channel...\"), \"\", 0, this, SLOT(slotJoinChannel()), mActionMenu ) );\n\tmActionMenu->insert( new KAction ( i18n(\"Show Server Window\"), \"\", 0, this, SLOT(slotShowServerWindow()), mActionMenu ) );\n\n\treturn mActionMenu;\n}\n\nvoid IRCAccount::connect()\n{\n\tif( m_engine->isConnected() )\n\t{\n\t\tif( isAway() )\n\t\t\tsetAway( false );\n\t}\n\telse if( m_engine->isDisconnected() )\n\t{\n\t\tm_engine->connectToServer( m_mySelf->nickName() );\n\t}\n}\n\nvoid IRCAccount::disconnect()\n{\n\tm_engine->quitIRC(\"Kopete IRC [http:\/\/kopete.kde.org]\");\n}\n\nvoid IRCAccount::setAway( bool isAway, const QString &awayMessage )\n{\n\tkdDebug(14120) << k_funcinfo << isAway << \" \" << awayMessage << endl;\n\tif(m_engine->isConnected())\n\t{\n\t\tm_mySelf->setAway( isAway );\n\t\tengine()->setAway( isAway, awayMessage );\n\t}\n}\n\nvoid IRCAccount::slotGoAway()\n{\n\tsetAway( true, KopeteAway::message() );\n}\n\nvoid IRCAccount::slotShowServerWindow()\n{\n\tm_myServer->startServerChat();\n}\n\nbool IRCAccount::isConnected()\n{\n\treturn (m_mySelf->onlineStatus().status() == KopeteOnlineStatus::Online);\n}\n\nvoid IRCAccount::unregister(KopeteContact *contact)\n{\n\tm_contactManager->unregister(contact);\n}\n\nIRCServerContact *IRCAccount::findServer( const QString &name, KopeteMetaContact *m )\n{\n\treturn m_contactManager->findServer(name, m);\n}\n\nvoid IRCAccount::unregisterServer( const QString &name )\n{\n\tm_contactManager->unregisterServer(name);\n}\n\nIRCChannelContact *IRCAccount::findChannel( const QString &name, KopeteMetaContact *m )\n{\n\treturn m_contactManager->findChannel(name, m);\n}\n\nvoid IRCAccount::unregisterChannel( const QString &name )\n{\n\tm_contactManager->unregisterChannel(name);\n}\n\nIRCUserContact *IRCAccount::findUser(const QString &name, KopeteMetaContact *m)\n{\n\treturn m_contactManager->findUser(name, m);\n}\n\nvoid IRCAccount::unregisterUser( const QString &name )\n{\n\tm_contactManager->unregisterUser(name);\n}\n\nvoid IRCAccount::successfullyChangedNick(const QString &\/*oldnick*\/, const QString &newnick)\n{\n\tkdDebug(14120) << k_funcinfo << \"Changing nick to \" << newnick << endl;\n\tm_mySelf->manager()->setDisplayName( m_mySelf->caption() );\n\n\tif( isConnected() )\n\t\tm_engine->changeNickname( newnick );\n}\n\nbool IRCAccount::addContactToMetaContact( const QString &contactId, const QString &displayName,\n\t KopeteMetaContact *m )\n{\n\/\/\tkdDebug(14120) << k_funcinfo << contactId << \"|\" << displayName << endl;\n\t\/\/FIXME: I think there are too many tests in this functions. This function should be called ONLY by\n\t\/\/ KopeteAccount::addContact, where all test are already done. Can a irc developer look at this? -Olivier\n\tIRCContact *c;\n\n\tif( !m )\n\t{\/\/This should NEVER happen\n\t\tm = new KopeteMetaContact();\n\t\tKopeteContactList::contactList()->addMetaContact(m);\n\t\tm->setDisplayName( displayName );\n\t}\n\n\tif ( contactId.startsWith( QString::fromLatin1(\"#\") ) )\n\t\tc = static_cast( findChannel(contactId, m) );\n\telse\n\t{\n\t\tm_contactManager->addToNotifyList( contactId );\n\t\tc = static_cast( findUser(contactId, m) );\n\t}\n\n\tif( c->metaContact() != m )\n\t{\/\/This should NEVER happen\n\t\tKopeteMetaContact *old = c->metaContact();\n\t\tc->setMetaContact( m );\n\t\tKopeteContactPtrList children = old->contacts();\n\t\tif( children.isEmpty() )\n\t\t\tKopeteContactList::contactList()->removeMetaContact( old );\n\t}\n\telse if( c->metaContact()->isTemporary() ) \/\/FIXME: if the metacontact is temporary, that mean this is a temporary contact\n\t\tm->setTemporary(false);\n\n\treturn true;\n}\n\nvoid IRCAccount::slotJoinChannel()\n{\n\tif(!isConnected())\n\t\treturn;\n\n\tQString chan = KInputDialog::getText( i18n( \"IRC Plugin\" ),\n\t\ti18n( \"Please enter name of the channel you want to join:\" ), QString::null);\n\tif( !chan.isNull() )\n\t{\n\t\tif( chan.startsWith( QString::fromLatin1(\"#\") ) )\n\t\t\tfindChannel( chan )->startChat();\n\t\telse\n\t\t\tKMessageBox::error(0l, i18n(\"\\\"%1\\\" is an invalid channel. Channels must start with '#'.<\/qt>\").arg(chan), i18n(\"IRC Plugin\"));\n\t}\n}\n\nKopeteContact *IRCAccount::myself() const\n{\n\treturn m_mySelf;\n}\n\nIRCUserContact *IRCAccount::mySelf() const\n{\n\treturn m_mySelf;\n}\n\nIRCServerContact *IRCAccount::myServer() const\n{\n\treturn m_myServer;\n}\n\n#include \"ircaccount.moc\"\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mwidgetmodel.h\"\n#include \"mwidgetmodel_p.h\"\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PRIVATE CLASS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMWidgetModelPrivate::MWidgetModelPrivate() :\n transactionInProgress(false),\n referenceCount(0)\n{\n}\n\nMWidgetModelPrivate::~MWidgetModelPrivate()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PUBLIC CLASS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MWidgetModel::memberModified(const char *const member)\n{\n if (d_ptr->transactionInProgress) {\n d_ptr->modifiedMembers.enqueue(member);\n } else {\n QList list;\n list.append(member);\n emit modified(list);\n }\n}\n\nvoid MWidgetModel::beginTransaction()\n{\n if (d_ptr->transactionInProgress) {\n mWarning(\"MWidgetModel\") << \"beginTransaction() - transaction already started!\";\n return;\n }\n\n d_ptr->transactionInProgress = true;\n}\n\nvoid MWidgetModel::commitTransaction()\n{\n if (d_ptr->transactionInProgress == false) {\n mWarning(\"MWidgetModel\") << \"commitTransaction() - no transaction ongoing!\";\n return;\n }\n\n d_ptr->transactionInProgress = false;\n emit modified(d_ptr->modifiedMembers);\n d_ptr->modifiedMembers.clear();\n}\n\nvoid MWidgetModel::increaseReferenceCount()\n{\n ++d_ptr->referenceCount;\n}\n\nvoid MWidgetModel::decreaseReferenceCount()\n{\n --d_ptr->referenceCount;\n if (d_ptr->referenceCount == 0)\n delete this;\n}\n\nQDataStream &operator<<(QDataStream &stream, const MWidgetModel &model)\n{\n const QMetaObject *metaObject = model.metaObject();\n QString hashString = metaObject->className();\n\n int propertyCount = metaObject->propertyCount();\n for (int i = 0; i != propertyCount; ++i) {\n hashString += metaObject->property(i).name();\n hashString += metaObject->property(i).typeName();\n }\n\n uint hash = qHash(hashString);\n stream << hash;\n for (int i = 0; i != propertyCount; ++i) {\n stream << metaObject->property(i).read(&model);\n }\n\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, MWidgetModel &model)\n{\n const QMetaObject *metaObject = model.metaObject();\n QString hashString = metaObject->className();\n\n int propertyCount = metaObject->propertyCount();\n for (int i = 0; i != propertyCount; ++i) {\n hashString += metaObject->property(i).name();\n hashString += metaObject->property(i).typeName();\n }\n\n uint realHash = qHash(hashString);\n uint hash;\n stream >> hash;\n if (hash != realHash) {\n qFatal(\"Deserializing of %s failed from QDataStream, Q_PROPERTY table doesn't match!\", metaObject->className());\n }\n\n for (int i = 0; i != propertyCount; ++i) {\n QVariant v;\n stream >> v;\n metaObject->property(i).write(&model, v);\n }\n\n return stream;\n}\n\nRevert \"Fixes: Replace deleteLater with delete in mwidgetmodel\"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mwidgetmodel.h\"\n#include \"mwidgetmodel_p.h\"\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PRIVATE CLASS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nMWidgetModelPrivate::MWidgetModelPrivate() :\n transactionInProgress(false),\n referenceCount(0)\n{\n}\n\nMWidgetModelPrivate::~MWidgetModelPrivate()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ PUBLIC CLASS \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid MWidgetModel::memberModified(const char *const member)\n{\n if (d_ptr->transactionInProgress) {\n d_ptr->modifiedMembers.enqueue(member);\n } else {\n QList list;\n list.append(member);\n emit modified(list);\n }\n}\n\nvoid MWidgetModel::beginTransaction()\n{\n if (d_ptr->transactionInProgress) {\n mWarning(\"MWidgetModel\") << \"beginTransaction() - transaction already started!\";\n return;\n }\n\n d_ptr->transactionInProgress = true;\n}\n\nvoid MWidgetModel::commitTransaction()\n{\n if (d_ptr->transactionInProgress == false) {\n mWarning(\"MWidgetModel\") << \"commitTransaction() - no transaction ongoing!\";\n return;\n }\n\n d_ptr->transactionInProgress = false;\n emit modified(d_ptr->modifiedMembers);\n d_ptr->modifiedMembers.clear();\n}\n\nvoid MWidgetModel::increaseReferenceCount()\n{\n ++d_ptr->referenceCount;\n}\n\nvoid MWidgetModel::decreaseReferenceCount()\n{\n --d_ptr->referenceCount;\n if (d_ptr->referenceCount == 0)\n deleteLater();\n}\n\nQDataStream &operator<<(QDataStream &stream, const MWidgetModel &model)\n{\n const QMetaObject *metaObject = model.metaObject();\n QString hashString = metaObject->className();\n\n int propertyCount = metaObject->propertyCount();\n for (int i = 0; i != propertyCount; ++i) {\n hashString += metaObject->property(i).name();\n hashString += metaObject->property(i).typeName();\n }\n\n uint hash = qHash(hashString);\n stream << hash;\n for (int i = 0; i != propertyCount; ++i) {\n stream << metaObject->property(i).read(&model);\n }\n\n return stream;\n}\n\nQDataStream &operator>>(QDataStream &stream, MWidgetModel &model)\n{\n const QMetaObject *metaObject = model.metaObject();\n QString hashString = metaObject->className();\n\n int propertyCount = metaObject->propertyCount();\n for (int i = 0; i != propertyCount; ++i) {\n hashString += metaObject->property(i).name();\n hashString += metaObject->property(i).typeName();\n }\n\n uint realHash = qHash(hashString);\n uint hash;\n stream >> hash;\n if (hash != realHash) {\n qFatal(\"Deserializing of %s failed from QDataStream, Q_PROPERTY table doesn't match!\", metaObject->className());\n }\n\n for (int i = 0; i != propertyCount; ++i) {\n QVariant v;\n stream >> v;\n metaObject->property(i).write(&model, v);\n }\n\n return stream;\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/peac:$Name:$:$Id:$\n\/\/ Author: Maarten Ballintijn 21\/10\/2004\n\/\/ Author: Kris Gulbrandsen 21\/10\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TPEAC \/\/\n\/\/ \/\/\n\/\/ This class implements the setup of a PROOF session using PEAC \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TPEAC.h\"\n\n#include \"TClarens.h\"\n#include \"TDSet.h\"\n#include \"TEnv.h\"\n#include \"TGM.h\"\n#include \"TObjString.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TUrl.h\"\n#include \"TVirtualProof.h\"\n\n\nnamespace {\n\n\/\/------------------------------------------------------------------------------\n\nstruct TPEACStartup {\n TPEACStartup() {TPEAC::Init();}\n} PEACStartup;\n\n\/\/------------------------------------------------------------------------------\n\n};\n\n\nTPEAC *gPEAC = 0;\n\nClassImp(TPEAC)\n\n\n\/\/______________________________________________________________________________\nTPEAC::TPEAC()\n : fGM(0), fProof(0)\n{\n TClarens::Init();\n}\n\n\n\/\/______________________________________________________________________________\nTPEAC::~TPEAC()\n{\n if (!fSessionID.IsNull()) EndSession();\n delete fGM;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::Init()\n{\n if (gPEAC == 0) {\n gPEAC = new TPEAC;\n }\n}\n\n\n\/\/______________________________________________________________________________\nTDSet *TPEAC::StartSession(const Char_t *dataset)\n{\n if (fGM == 0) {\n\n const Char_t *gmUrl = gEnv->GetValue(\"PEAC.GmUrl\",\n \"http:\/\/localhost:8080\/clarens\/\");\n\n fGM = gClarens->CreateGM(gmUrl);\n\n if (!fGM) {\n Error(\"TPEAC\", \"Could not get Global Manager for URL: %s\", gmUrl);\n return 0;\n }\n }\n\n if (!fSessionID.IsNull()) {\n Error(\"StartSession\", \"Session associated with dataset '%s' still open\",\n fDataSet.Data());\n Error(\"StartSession\", \"That session must end before\"\n \" starting a new session\");\n return 0;\n }\n\n if (gDebug > 0) fGM->Print();\n\n TList* files = 0;\n TString sessionid;\n TUrl purl(\"\");\n if (!fGM->CreateSession(dataset, sessionid, files, purl)) {\n delete fGM;\n fGM = 0;\n return 0;\n }\n\n \/\/ session successfully created\n\n if (gDebug > 0) {\n Info(\"StartSession\", \"sessionid = %s @ %s\", sessionid.Data(), purl.GetUrl());\n files->Print();\n }\n\n \/\/ construct TDSet\n TDSet *dset = 0;\n TIter NextFile(files);\n while (TGM::TFileParams *fp = dynamic_cast(NextFile())) {\n\n if (dset == 0) dset = new TDSet(fp->fObjClass, fp->fObjName, fp->fDir);\n\n dset->Add(fp->fFileName, fp->fObjName, fp->fDir, fp->fFirst, fp->fNum);\n }\n Int_t nfiles = files->GetSize();\n delete files;\n\n \/\/ save session id\n fSessionID = sessionid;\n fDataSet = dataset;\n\n \/\/ start proof\n fProof = gROOT->Proof(TString(purl.GetUrl()), TString(\"peac:\")+sessionid);\n\n if (!fProof || !fProof->IsValid()) {\n Error(\"StartSession\", \"PROOF session could not be started\");\n EndSession();\n delete dset;\n return 0;\n }\n\n \/\/call EndSession when proof is destroyed\n fProof->Connect(\"~TVirtualProof()\", \"TPEAC\", this, \"EndSessionCallback()\");\n\n \/\/wait until data is ready\n Long64_t totalbytes, bytesready;\n Bool_t dataready = fProof->IsDataReady(totalbytes, bytesready);\n\n \/\/make a progress bar - either the user deletes it or it deletes itself\n if (!gROOT->IsBatch()) {\n if (TPluginManager *pm = gROOT->GetPluginManager()) {\n if (TPluginHandler *h = pm->FindHandler(\"TProofStartupDialog\")) {\n if(h->LoadPlugin() != -1) {\n h->ExecPlugin(4, fProof, dataset, nfiles, totalbytes);\n \/\/trigger progress atleast once\n dataready = fProof->IsDataReady(totalbytes, bytesready);\n }\n }\n }\n }\n\n if (!dataready) {\n gSystem->Sleep(500);\n while (!fProof->IsDataReady(totalbytes, bytesready)) {\n gSystem->Sleep(500);\n }\n }\n\n return dset;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::EndSessionCallback()\n{\n if (fSessionID.IsNull()) {\n Error(\"EndSession\", \"No session active. Don't call EndSessionCallback() directly\");\n return;\n }\n\n if (!fGM) {\n Error(\"EndSession\", \"Global manager does not exist\");\n return;\n }\n\n if (fProof) {\n fProof->Disconnect(\"~TVirtualProof()\", this, \"EndSessionCallback()\");\n fProof = 0;\n }\n fGM->DestroySession(fSessionID);\n fSessionID = \"\";\n fDataSet = \"\";\n\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::EndSession()\n{\n if (fSessionID.IsNull()) {\n Info(\"EndSession\", \"No session active\");\n return;\n }\n\n if (!fGM) {\n Error(\"EndSession\", \"Global manager does not exist\");\n return;\n }\n\n if (fProof) {\n fProof->Disconnect(\"~TVirtualProof()\", this, \"EndSessionCallback()\");\n delete fProof;\n fProof = 0;\n }\n fGM->DestroySession(fSessionID);\n fSessionID = \"\";\n fDataSet = \"\";\n}\nFrom Christian Holm: change gROOT->Proof() to TVirtualProof::Open().\/\/ @(#)root\/peac:$Name: $:$Id: TPEAC.cxx,v 1.1 2005\/02\/07 18:02:36 rdm Exp $\n\/\/ Author: Maarten Ballintijn 21\/10\/2004\n\/\/ Author: Kris Gulbrandsen 21\/10\/2004\n\n\/*************************************************************************\n * Copyright (C) 1995-2005, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TPEAC \/\/\n\/\/ \/\/\n\/\/ This class implements the setup of a PROOF session using PEAC \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TPEAC.h\"\n\n#include \"TClarens.h\"\n#include \"TDSet.h\"\n#include \"TEnv.h\"\n#include \"TGM.h\"\n#include \"TObjString.h\"\n#include \"TPluginManager.h\"\n#include \"TROOT.h\"\n#include \"TSystem.h\"\n#include \"TUrl.h\"\n#include \"TVirtualProof.h\"\n\n\nnamespace {\n\n\/\/------------------------------------------------------------------------------\n\nstruct TPEACStartup {\n TPEACStartup() {TPEAC::Init();}\n} PEACStartup;\n\n\/\/------------------------------------------------------------------------------\n\n};\n\n\nTPEAC *gPEAC = 0;\n\nClassImp(TPEAC)\n\n\n\/\/______________________________________________________________________________\nTPEAC::TPEAC()\n : fGM(0), fProof(0)\n{\n TClarens::Init();\n}\n\n\n\/\/______________________________________________________________________________\nTPEAC::~TPEAC()\n{\n if (!fSessionID.IsNull()) EndSession();\n delete fGM;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::Init()\n{\n if (gPEAC == 0) {\n gPEAC = new TPEAC;\n }\n}\n\n\n\/\/______________________________________________________________________________\nTDSet *TPEAC::StartSession(const Char_t *dataset)\n{\n if (fGM == 0) {\n\n const Char_t *gmUrl = gEnv->GetValue(\"PEAC.GmUrl\",\n \"http:\/\/localhost:8080\/clarens\/\");\n\n fGM = gClarens->CreateGM(gmUrl);\n\n if (!fGM) {\n Error(\"TPEAC\", \"Could not get Global Manager for URL: %s\", gmUrl);\n return 0;\n }\n }\n\n if (!fSessionID.IsNull()) {\n Error(\"StartSession\", \"Session associated with dataset '%s' still open\",\n fDataSet.Data());\n Error(\"StartSession\", \"That session must end before\"\n \" starting a new session\");\n return 0;\n }\n\n if (gDebug > 0) fGM->Print();\n\n TList* files = 0;\n TString sessionid;\n TUrl purl(\"\");\n if (!fGM->CreateSession(dataset, sessionid, files, purl)) {\n delete fGM;\n fGM = 0;\n return 0;\n }\n\n \/\/ session successfully created\n\n if (gDebug > 0) {\n Info(\"StartSession\", \"sessionid = %s @ %s\", sessionid.Data(), purl.GetUrl());\n files->Print();\n }\n\n \/\/ construct TDSet\n TDSet *dset = 0;\n TIter NextFile(files);\n while (TGM::TFileParams *fp = dynamic_cast(NextFile())) {\n\n if (dset == 0) dset = new TDSet(fp->fObjClass, fp->fObjName, fp->fDir);\n\n dset->Add(fp->fFileName, fp->fObjName, fp->fDir, fp->fFirst, fp->fNum);\n }\n Int_t nfiles = files->GetSize();\n delete files;\n\n \/\/ save session id\n fSessionID = sessionid;\n fDataSet = dataset;\n\n \/\/ start proof\n fProof = TVirtualProof::Open(purl.GetUrl(), Form(\"peac:%s\", sessionid.Data()));\n\n if (!fProof || !fProof->IsValid()) {\n Error(\"StartSession\", \"PROOF session could not be started\");\n EndSession();\n delete dset;\n return 0;\n }\n\n \/\/call EndSession when proof is destroyed\n fProof->Connect(\"~TVirtualProof()\", \"TPEAC\", this, \"EndSessionCallback()\");\n\n \/\/wait until data is ready\n Long64_t totalbytes, bytesready;\n Bool_t dataready = fProof->IsDataReady(totalbytes, bytesready);\n\n \/\/make a progress bar - either the user deletes it or it deletes itself\n if (!gROOT->IsBatch()) {\n if (TPluginManager *pm = gROOT->GetPluginManager()) {\n if (TPluginHandler *h = pm->FindHandler(\"TProofStartupDialog\")) {\n if(h->LoadPlugin() != -1) {\n h->ExecPlugin(4, fProof, dataset, nfiles, totalbytes);\n \/\/trigger progress atleast once\n dataready = fProof->IsDataReady(totalbytes, bytesready);\n }\n }\n }\n }\n\n if (!dataready) {\n gSystem->Sleep(500);\n while (!fProof->IsDataReady(totalbytes, bytesready)) {\n gSystem->Sleep(500);\n }\n }\n\n return dset;\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::EndSessionCallback()\n{\n if (fSessionID.IsNull()) {\n Error(\"EndSession\", \"No session active. Don't call EndSessionCallback() directly\");\n return;\n }\n\n if (!fGM) {\n Error(\"EndSession\", \"Global manager does not exist\");\n return;\n }\n\n if (fProof) {\n fProof->Disconnect(\"~TVirtualProof()\", this, \"EndSessionCallback()\");\n fProof = 0;\n }\n fGM->DestroySession(fSessionID);\n fSessionID = \"\";\n fDataSet = \"\";\n\n}\n\n\n\/\/______________________________________________________________________________\nvoid TPEAC::EndSession()\n{\n if (fSessionID.IsNull()) {\n Info(\"EndSession\", \"No session active\");\n return;\n }\n\n if (!fGM) {\n Error(\"EndSession\", \"Global manager does not exist\");\n return;\n }\n\n if (fProof) {\n fProof->Disconnect(\"~TVirtualProof()\", this, \"EndSessionCallback()\");\n delete fProof;\n fProof = 0;\n }\n fGM->DestroySession(fSessionID);\n fSessionID = \"\";\n fDataSet = \"\";\n}\n<|endoftext|>"} {"text":"#ifdef _WIN32\n# define NOMINMAX\n#endif\n\n#include \"dsb\/comm.hpp\"\n\n#include \n#include \n#include \n\n#include \"dsb\/config.h\"\n#include \"dsb\/error.hpp\"\n#include \"dsb\/util.hpp\"\n\n\nnamespace\n{\n void SendFrames(\n zmq::socket_t& socket,\n std::deque& message,\n bool moreComing)\n {\n assert (!message.empty());\n for (auto it = message.begin(); ; ) {\n auto m = it++;\n if (it == message.end()) {\n if (moreComing) socket.send(*m, ZMQ_SNDMORE);\n else socket.send(*m);\n break;\n } else {\n socket.send(*m, ZMQ_SNDMORE);\n }\n }\n message.clear();\n }\n}\n\nvoid dsb::comm::Send(zmq::socket_t& socket, std::deque& message)\n{\n DSB_INPUT_CHECK(!message.empty());\n SendFrames(socket, message, false);\n assert (message.empty());\n}\n\n\nvoid dsb::comm::AddressedSend(\n zmq::socket_t& socket,\n std::deque& envelope,\n std::deque& body)\n{\n DSB_INPUT_CHECK(!envelope.empty());\n DSB_INPUT_CHECK(!body.empty());\n SendFrames(socket, envelope, true);\n socket.send(\"\", 0, ZMQ_SNDMORE);\n SendFrames(socket, body, false);\n assert (envelope.empty());\n assert (body.empty());\n}\n\n\nvoid dsb::comm::Receive(\n zmq::socket_t& socket,\n std::deque& message)\n{\n message.clear();\n do {\n#if DSB_USE_MSVC_EMPLACE_WORKAROUND\n message.emplace_back(zmq::message_t());\n#else\n message.emplace_back();\n#endif\n socket.recv(&message.back());\n } while (message.back().more());\n}\n\n\nbool dsb::comm::Receive(\n zmq::socket_t& socket,\n std::deque& message,\n boost::chrono::milliseconds timeout)\n{\n zmq::pollitem_t pollItem = { socket, 0, ZMQ_POLLIN, 0 };\n if (zmq::poll(&pollItem, 1, static_cast(timeout.count())) == 0) {\n return false;\n } else {\n assert (pollItem.revents == ZMQ_POLLIN);\n dsb::comm::Receive(socket, message);\n return true;\n }\n}\n\n\nsize_t dsb::comm::PopMessageEnvelope(\n std::deque& message,\n std::deque* envelope)\n{\n auto delim = std::find_if(message.begin(), message.end(),\n [](const zmq::message_t& m) { return m.size() == 0; });\n if (delim == message.end()) {\n if (envelope) envelope->clear();\n return 0;\n }\n const auto envSize = delim - message.begin();\n if (envelope) {\n envelope->resize(envSize);\n std::move(message.begin(), delim, envelope->begin());\n }\n message.erase(message.begin(), ++delim);\n return envSize + 1;\n}\n\n\nvoid dsb::comm::CopyMessage(\n std::deque& source,\n std::deque& target)\n{\n target.resize(source.size());\n for (size_t i = 0; i < source.size(); ++i) {\n target[i].copy(&source[i]);\n }\n}\n\n\nvoid dsb::comm::CopyMessage(\n const std::deque& source,\n std::deque& target)\n{\n target.clear();\n for (auto it = source.cbegin(); it != source.cend(); ++it) {\n target.push_back(zmq::message_t(it->size()));\n std::memcpy(target.back().data(), it->data(), it->size());\n }\n}\n\n\nstd::string dsb::comm::ToString(const zmq::message_t& frame)\n{\n return std::string(static_cast(frame.data()), frame.size());\n}\n\n\nzmq::message_t dsb::comm::ToFrame(const std::string& s)\n{\n auto msg = zmq::message_t(s.size());\n std::memcpy(msg.data(), s.data(), s.size());\n return msg;\n}\n\n\nstd::string dsb::comm::LastEndpoint(zmq::socket_t& socket)\n{\n const size_t MAX_ENDPOINT_SIZE = 257; \/\/ including terminating zero\n char buffer[MAX_ENDPOINT_SIZE];\n size_t length = MAX_ENDPOINT_SIZE;\n socket.getsockopt(ZMQ_LAST_ENDPOINT, buffer, &length);\n assert (length > 0 && buffer[length-1] == '\\0');\n return std::string(buffer, length-1);\n}\n\n\nnamespace dsb { namespace comm {\n\nReactor::Reactor()\n : m_nextTimerID(0),\n m_needsRebuild(false),\n m_continuePolling(false)\n{ }\n\n\nvoid Reactor::AddSocket(zmq::socket_t& socket, SocketHandler handler)\n{\n m_sockets.push_back(std::make_pair(&socket, handler));\n m_needsRebuild = true;\n}\n\n\nvoid Reactor::RemoveSocket(zmq::socket_t& socket)\n{\n \/\/ Actual removal is deferred to the next rebuild. At this stage, we just\n \/\/ replace the socket pointer with null.\n for (auto it = m_sockets.begin(); it != m_sockets.end(); ++it) {\n if (it->first == &socket) it->first = nullptr;\n }\n m_needsRebuild = true;\n}\n\n\nnamespace\n{\n \/\/ We use templates to work around the fact that Reactor::Timer is private.\n template\n bool EventTimeGreater(const T& a, const T& b)\n {\n return a.nextEventTime > b.nextEventTime;\n }\n\n template\n void PushTimer(std::vector& v, const T& t)\n {\n v.push_back(t);\n std::push_heap(std::begin(v), std::end(v), EventTimeGreater);\n }\n\n template\n void PopTimer(std::vector& v)\n {\n std::pop_heap(std::begin(v), std::end(v), EventTimeGreater);\n v.pop_back();\n }\n}\n\n\nint Reactor::AddTimer(\n boost::chrono::milliseconds interval,\n int count,\n TimerHandler handler)\n{\n if (interval < boost::chrono::milliseconds(0)) {\n throw std::invalid_argument(\"Negative interval\");\n }\n if (count == 0) {\n throw std::invalid_argument(\"Invalid timer count\");\n }\n Timer t = {\n ++m_nextTimerID,\n boost::chrono::system_clock::now() + interval,\n interval,\n count,\n handler\n };\n PushTimer(m_timers, t);\n return t.id;\n}\n\n\nvoid Reactor::RemoveTimer(int id)\n{\n const auto it = std::find_if(m_timers.begin(), m_timers.end(),\n [id](const Timer& t){ return t.id == id; });\n if (it == m_timers.end()) {\n throw std::invalid_argument(\"Invalid timer ID\");\n }\n m_timers.erase(it);\n std::make_heap(std::begin(m_timers), std::end(m_timers), &EventTimeGreater);\n}\n\n\nvoid Reactor::Run()\n{\n m_continuePolling = true;\n do {\n if (m_needsRebuild) Rebuild();\n zmq::poll(m_pollItems.data(), m_pollItems.size(),\n m_timers.empty() ? -1 : static_cast(TimeToNextEvent().count()));\n for (size_t i = 0; i < m_pollItems.size(); ++i) {\n if ((m_pollItems[i].revents & ZMQ_POLLIN) && m_sockets[i].first != nullptr) {\n m_sockets[i].second(*this, *m_sockets[i].first);\n }\n }\n while (!m_timers.empty()\n && boost::chrono::system_clock::now() >= m_timers.front().nextEventTime) {\n PerformNextEvent();\n }\n } while (m_continuePolling);\n}\n\n\nvoid Reactor::Stop()\n{\n m_continuePolling = false;\n}\n\n\nboost::chrono::milliseconds Reactor::TimeToNextEvent() const\n{\n return std::max(\n boost::chrono::duration_cast(\n m_timers.front().nextEventTime - boost::chrono::system_clock::now()),\n boost::chrono::milliseconds(0));\n}\n\n\nvoid Reactor::PerformNextEvent()\n{\n auto t = m_timers.front();\n assert (t.nextEventTime <= boost::chrono::system_clock::now());\n assert (t.remaining != 0);\n\n \/\/ We need to update the timer queue even if the handler throws.\n auto updateTimer = dsb::util::OnScopeExit([&] () {\n \/\/ Timer may already have been removed by handler,\n \/\/ in which case we do nothing.\n if (m_timers.front().id == t.id) {\n PopTimer(m_timers);\n if (t.remaining > 0) --t.remaining;\n if (t.remaining != 0) {\n t.nextEventTime = boost::chrono::system_clock::now() + t.interval;\n PushTimer(m_timers, t);\n }\n }\n });\n t.handler(*this, t.id);\n}\n\n\nvoid Reactor::Rebuild()\n{\n \/\/ Remove null sockets from m_sockets\n auto newEnd = std::remove_if(m_sockets.begin(), m_sockets.end(),\n [](const SocketHandlerPair& a) { return a.first == nullptr; });\n m_sockets.erase(newEnd, m_sockets.end());\n\n \/\/ Rebuild m_pollItems\n m_pollItems.clear();\n for (auto it = m_sockets.begin(); it != m_sockets.end(); ++it) {\n zmq::pollitem_t pi = { *it->first, 0, ZMQ_POLLIN, 0 };\n m_pollItems.push_back(pi);\n }\n m_needsRebuild = false;\n}\n\n\n}} \/\/ namespace\nFixed \"next event time\" calculation#ifdef _WIN32\n# define NOMINMAX\n#endif\n\n#include \"dsb\/comm.hpp\"\n\n#include \n#include \n#include \n\n#include \"dsb\/config.h\"\n#include \"dsb\/error.hpp\"\n#include \"dsb\/util.hpp\"\n\n\nnamespace\n{\n void SendFrames(\n zmq::socket_t& socket,\n std::deque& message,\n bool moreComing)\n {\n assert (!message.empty());\n for (auto it = message.begin(); ; ) {\n auto m = it++;\n if (it == message.end()) {\n if (moreComing) socket.send(*m, ZMQ_SNDMORE);\n else socket.send(*m);\n break;\n } else {\n socket.send(*m, ZMQ_SNDMORE);\n }\n }\n message.clear();\n }\n}\n\nvoid dsb::comm::Send(zmq::socket_t& socket, std::deque& message)\n{\n DSB_INPUT_CHECK(!message.empty());\n SendFrames(socket, message, false);\n assert (message.empty());\n}\n\n\nvoid dsb::comm::AddressedSend(\n zmq::socket_t& socket,\n std::deque& envelope,\n std::deque& body)\n{\n DSB_INPUT_CHECK(!envelope.empty());\n DSB_INPUT_CHECK(!body.empty());\n SendFrames(socket, envelope, true);\n socket.send(\"\", 0, ZMQ_SNDMORE);\n SendFrames(socket, body, false);\n assert (envelope.empty());\n assert (body.empty());\n}\n\n\nvoid dsb::comm::Receive(\n zmq::socket_t& socket,\n std::deque& message)\n{\n message.clear();\n do {\n#if DSB_USE_MSVC_EMPLACE_WORKAROUND\n message.emplace_back(zmq::message_t());\n#else\n message.emplace_back();\n#endif\n socket.recv(&message.back());\n } while (message.back().more());\n}\n\n\nbool dsb::comm::Receive(\n zmq::socket_t& socket,\n std::deque& message,\n boost::chrono::milliseconds timeout)\n{\n zmq::pollitem_t pollItem = { socket, 0, ZMQ_POLLIN, 0 };\n if (zmq::poll(&pollItem, 1, static_cast(timeout.count())) == 0) {\n return false;\n } else {\n assert (pollItem.revents == ZMQ_POLLIN);\n dsb::comm::Receive(socket, message);\n return true;\n }\n}\n\n\nsize_t dsb::comm::PopMessageEnvelope(\n std::deque& message,\n std::deque* envelope)\n{\n auto delim = std::find_if(message.begin(), message.end(),\n [](const zmq::message_t& m) { return m.size() == 0; });\n if (delim == message.end()) {\n if (envelope) envelope->clear();\n return 0;\n }\n const auto envSize = delim - message.begin();\n if (envelope) {\n envelope->resize(envSize);\n std::move(message.begin(), delim, envelope->begin());\n }\n message.erase(message.begin(), ++delim);\n return envSize + 1;\n}\n\n\nvoid dsb::comm::CopyMessage(\n std::deque& source,\n std::deque& target)\n{\n target.resize(source.size());\n for (size_t i = 0; i < source.size(); ++i) {\n target[i].copy(&source[i]);\n }\n}\n\n\nvoid dsb::comm::CopyMessage(\n const std::deque& source,\n std::deque& target)\n{\n target.clear();\n for (auto it = source.cbegin(); it != source.cend(); ++it) {\n target.push_back(zmq::message_t(it->size()));\n std::memcpy(target.back().data(), it->data(), it->size());\n }\n}\n\n\nstd::string dsb::comm::ToString(const zmq::message_t& frame)\n{\n return std::string(static_cast(frame.data()), frame.size());\n}\n\n\nzmq::message_t dsb::comm::ToFrame(const std::string& s)\n{\n auto msg = zmq::message_t(s.size());\n std::memcpy(msg.data(), s.data(), s.size());\n return msg;\n}\n\n\nstd::string dsb::comm::LastEndpoint(zmq::socket_t& socket)\n{\n const size_t MAX_ENDPOINT_SIZE = 257; \/\/ including terminating zero\n char buffer[MAX_ENDPOINT_SIZE];\n size_t length = MAX_ENDPOINT_SIZE;\n socket.getsockopt(ZMQ_LAST_ENDPOINT, buffer, &length);\n assert (length > 0 && buffer[length-1] == '\\0');\n return std::string(buffer, length-1);\n}\n\n\nnamespace dsb { namespace comm {\n\nReactor::Reactor()\n : m_nextTimerID(0),\n m_needsRebuild(false),\n m_continuePolling(false)\n{ }\n\n\nvoid Reactor::AddSocket(zmq::socket_t& socket, SocketHandler handler)\n{\n m_sockets.push_back(std::make_pair(&socket, handler));\n m_needsRebuild = true;\n}\n\n\nvoid Reactor::RemoveSocket(zmq::socket_t& socket)\n{\n \/\/ Actual removal is deferred to the next rebuild. At this stage, we just\n \/\/ replace the socket pointer with null.\n for (auto it = m_sockets.begin(); it != m_sockets.end(); ++it) {\n if (it->first == &socket) it->first = nullptr;\n }\n m_needsRebuild = true;\n}\n\n\nnamespace\n{\n \/\/ We use templates to work around the fact that Reactor::Timer is private.\n template\n bool EventTimeGreater(const T& a, const T& b)\n {\n return a.nextEventTime > b.nextEventTime;\n }\n\n template\n void PushTimer(std::vector& v, const T& t)\n {\n v.push_back(t);\n std::push_heap(std::begin(v), std::end(v), EventTimeGreater);\n }\n\n template\n void PopTimer(std::vector& v)\n {\n std::pop_heap(std::begin(v), std::end(v), EventTimeGreater);\n v.pop_back();\n }\n}\n\n\nint Reactor::AddTimer(\n boost::chrono::milliseconds interval,\n int count,\n TimerHandler handler)\n{\n if (interval < boost::chrono::milliseconds(0)) {\n throw std::invalid_argument(\"Negative interval\");\n }\n if (count == 0) {\n throw std::invalid_argument(\"Invalid timer count\");\n }\n Timer t = {\n ++m_nextTimerID,\n boost::chrono::system_clock::now() + interval,\n interval,\n count,\n handler\n };\n PushTimer(m_timers, t);\n return t.id;\n}\n\n\nvoid Reactor::RemoveTimer(int id)\n{\n const auto it = std::find_if(m_timers.begin(), m_timers.end(),\n [id](const Timer& t){ return t.id == id; });\n if (it == m_timers.end()) {\n throw std::invalid_argument(\"Invalid timer ID\");\n }\n m_timers.erase(it);\n std::make_heap(std::begin(m_timers), std::end(m_timers), &EventTimeGreater);\n}\n\n\nvoid Reactor::Run()\n{\n m_continuePolling = true;\n do {\n if (m_needsRebuild) Rebuild();\n zmq::poll(m_pollItems.data(), m_pollItems.size(),\n m_timers.empty() ? -1 : static_cast(TimeToNextEvent().count()));\n for (size_t i = 0; i < m_pollItems.size(); ++i) {\n if ((m_pollItems[i].revents & ZMQ_POLLIN) && m_sockets[i].first != nullptr) {\n m_sockets[i].second(*this, *m_sockets[i].first);\n }\n }\n while (!m_timers.empty()\n && boost::chrono::system_clock::now() >= m_timers.front().nextEventTime) {\n PerformNextEvent();\n }\n } while (m_continuePolling);\n}\n\n\nvoid Reactor::Stop()\n{\n m_continuePolling = false;\n}\n\n\nboost::chrono::milliseconds Reactor::TimeToNextEvent() const\n{\n return std::max(\n boost::chrono::duration_cast(\n m_timers.front().nextEventTime - boost::chrono::system_clock::now()),\n boost::chrono::milliseconds(0));\n}\n\n\nvoid Reactor::PerformNextEvent()\n{\n auto t = m_timers.front();\n assert (t.nextEventTime <= boost::chrono::system_clock::now());\n assert (t.remaining != 0);\n\n \/\/ We need to update the timer queue even if the handler throws.\n auto updateTimer = dsb::util::OnScopeExit([&] () {\n \/\/ Timer may already have been removed by handler,\n \/\/ in which case we do nothing.\n if (m_timers.front().id == t.id) {\n PopTimer(m_timers);\n if (t.remaining > 0) --t.remaining;\n if (t.remaining != 0) {\n t.nextEventTime += t.interval;\n PushTimer(m_timers, t);\n }\n }\n });\n t.handler(*this, t.id);\n}\n\n\nvoid Reactor::Rebuild()\n{\n \/\/ Remove null sockets from m_sockets\n auto newEnd = std::remove_if(m_sockets.begin(), m_sockets.end(),\n [](const SocketHandlerPair& a) { return a.first == nullptr; });\n m_sockets.erase(newEnd, m_sockets.end());\n\n \/\/ Rebuild m_pollItems\n m_pollItems.clear();\n for (auto it = m_sockets.begin(); it != m_sockets.end(); ++it) {\n zmq::pollitem_t pi = { *it->first, 0, ZMQ_POLLIN, 0 };\n m_pollItems.push_back(pi);\n }\n m_needsRebuild = false;\n}\n\n\n}} \/\/ namespace\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"CCameraController.h\"\n\n#include \n#include \n\n#include \"debug\/Log.h\"\n\n#include \"graphics\/camera\/IControllableCamera.h\"\n\n#include \"input\/IInputProvider.h\"\n#include \"io\/JsonUtil.h\"\n#include \"io\/JsonDeserialize.h\"\n\nCCameraController::CCameraController() {}\n\nCCameraController::~CCameraController()\n{\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->removeInputListener(this);\n }\n}\n\nvoid CCameraController::setCamera(std::shared_ptr camera)\n{\n m_camera = camera;\n}\n\nvoid CCameraController::setInputProvider(IInputProvider* provider)\n{\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->removeInputListener(this);\n }\n\n m_inputProvider = provider;\n\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->addInputListener(this);\n }\n}\n\nbool CCameraController::loadSequence(std::string file)\n{\n m_sequenceTime = 0;\n m_sequencePoints.clear();\n\n Json::Reader reader;\n Json::Value root;\n\n \/\/ Load scene file\n std::ifstream ifs(file);\n if (!ifs.is_open())\n {\n LOG_ERROR(\"Failed to open json file %s.\", file.c_str());\n return false;\n }\n\n \/\/ Parse json data\n if (!reader.parse(ifs, root))\n {\n LOG_ERROR(\"Failed to load scene file %s with error %s.\", file.c_str(),\n reader.getFormattedErrorMessages().c_str());\n return false;\n }\n \/\/ Read done, close file\n ifs.close();\n\n Json::Value node = root[\"positions\"];\n\n \/\/ Node empty?\n if (node.empty())\n {\n LOG_INFO(\"Missing or empty 'positions' node. No scene objects are loaded.\");\n return true;\n }\n\n \/\/ Node is array type\n if (!node.isArray())\n {\n LOG_ERROR(\"The node 'positions' must be array type.\");\n return false;\n }\n\n bool success = true;\n\n for (unsigned int i = 0; i < node.size(); ++i)\n {\n glm::vec3 position;\n glm::vec3 orientation;\n float timestamp;\n bool fxaaActive;\n bool fogActive;\n\n if (!load(node[i], \"position\", position))\n {\n LOG_ERROR(\"Failed loading node 'position' for element #%i.\", i);\n success = false;\n break;\n }\n\n if (!load(node[i], \"orientation\", orientation))\n {\n LOG_ERROR(\"Failed loading node 'orientation' for element #%i.\", i);\n success = false;\n break;\n }\n\n if (!load(node[i], \"timestamp\", timestamp))\n {\n LOG_ERROR(\"Failed loading node 'timestamp' for element #%i.\", i);\n success = false;\n break;\n }\n \n if (!load(node[i], \"fxaa\", fxaaActive))\n {\n LOG_ERROR(\"Failed loading node 'fxaa' for element #%i.\", i);\n success = false;\n break;\n }\n \n if (!load(node[i], \"fog\", fogActive))\n {\n LOG_ERROR(\"Failed loading node 'fog' for element #%i.\", i);\n success = false;\n break;\n }\n\n SequencePoint sp{position, glm::normalize(orientation), timestamp, fxaaActive, fogActive};\n m_sequencePoints.push_back(sp);\n }\n\n m_isRunningSequence = success;\n return success;\n}\n\nvoid CCameraController::animate(float dt)\n{\n if (m_inputProvider != nullptr && m_camera != nullptr)\n {\n animateFeatures(dt);\n \n if (m_isRunningSequence)\n {\n animateSequence(dt);\n }\n else\n {\n animateManual(dt);\n }\n }\n}\n\nvoid CCameraController::animateFeatures(float dt) {\n \/\/ tODO\n}\n\nvoid CCameraController::animateSequence(float dt) {\n if (m_inputProvider->isKeyPressed(GLFW_KEY_C))\n {\n m_isRunningSequence = false;\n return;\n }\n \n float timeModifier = 1.0f;\n if (m_inputProvider->isKeyPressed(GLFW_KEY_B))\n {\n timeModifier = -2.0f;\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_N))\n {\n timeModifier = 4.0f;\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_M))\n {\n timeModifier = 8.0f;\n }\n \n m_sequenceTime += (dt * timeModifier);\n \n if (m_sequenceTime > m_sequencePoints.back().timestamp)\n {\n m_isRunningSequence = false;\n return;\n }\n \n auto it = std::find_if(m_sequencePoints.begin(), m_sequencePoints.end(),\n [&](const SequencePoint& s)\n {\n return s.timestamp >= m_sequenceTime;\n });\n \n if (it == m_sequencePoints.begin())\n {\n \/\/ not started yet\n return;\n }\n \n SequencePoint after = *it;\n SequencePoint before = *(--it);\n \n float ix = (m_sequenceTime - before.timestamp) \/ (after.timestamp - before.timestamp);\n glm::vec3 cameraPosition = before.position * (1.0f - ix) + after.position * ix;\n glm::vec3 cameraOrientation = before.orientation * (1.0f - ix) + after.orientation * ix;\n \n m_camera->lookAt(cameraPosition, cameraPosition + cameraOrientation, glm::vec3(0,1,0));\n m_camera->getFeatureInfoForWrite().fogType = (before.fogActive ? FogType::Exp2 : FogType::None);\n m_camera->getFeatureInfoForWrite().fxaaActive = before.fxaaActive;\n}\n\nvoid CCameraController::animateManual(float dt) {\n float walkingModifier = 1.0f;\n if (m_inputProvider->isKeyPressed(GLFW_KEY_SPACE))\n {\n walkingModifier = 6.0f;\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_W))\n {\n m_camera->moveForward(dt * 2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_S))\n {\n m_camera->moveForward(dt * -2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_A))\n {\n m_camera->moveRight(dt * 2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_D))\n {\n m_camera->moveRight(dt * -2.f * m_speed * walkingModifier);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_Q))\n {\n m_camera->moveUp(dt * -2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_E))\n {\n m_camera->moveUp(dt * 2.f * m_speed * walkingModifier);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_UP))\n {\n m_camera->pitch(-dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_DOWN))\n {\n m_camera->pitch(dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_RIGHT))\n {\n m_camera->yaw(-dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_LEFT))\n {\n m_camera->yaw(dt * m_speed);\n }\n}\n\nvoid CCameraController::handleKeyEvent(EKeyEventType type, int keyCode)\n{\n if (type != EKeyEventType::KEY_PRESSED) {\n return;\n }\n \n SFeatureInfo& info = m_camera->getFeatureInfoForWrite();\n \n\n\tif (keyCode == GLFW_KEY_R)\n\t{\n\t\tswitch (info.renderMode) {\n\t\tcase RenderMode::Final:\n\t\t\tinfo.renderMode = RenderMode::Color;\n\t\t\tbreak;\n\t\tcase RenderMode::Color:\n\t\t\tinfo.renderMode = RenderMode::Depth;\n\t\t\tbreak;\n\t\tcase RenderMode::Depth:\n\t\t\tinfo.renderMode = RenderMode::Lights;\n\t\t\tbreak;\n\t\tcase RenderMode::Lights:\n\t\t\tinfo.renderMode = RenderMode::Normals;\n\t\t\tbreak;\n\t\tcase RenderMode::Normals:\n\t\t\tinfo.renderMode = RenderMode::GodRay;\n\t\t\tbreak;\n\t\tcase RenderMode::GodRay:\n\t\t\tinfo.renderMode = RenderMode::Final;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tinfo.renderMode = RenderMode::Final;\n\t\t\tbreak;\n\t\t}\n\t}\n\n if (keyCode == GLFW_KEY_T)\n {\n switch (info.fogType) {\n case FogType::None:\n info.fogType = FogType::Linear;\n break;\n case FogType::Linear:\n info.fogType = FogType::Exp;\n break;\n case FogType::Exp:\n info.fogType = FogType::Exp2;\n break;\n case FogType::Exp2:\n info.fogType = FogType::None;\n break;\n default:\n info.fogType = FogType::None;\n break;\n }\n }\n \n if (keyCode == GLFW_KEY_Z)\n {\n info.shadowsActive = !info.shadowsActive;\n }\n \n if (keyCode == GLFW_KEY_U)\n {\n info.fxaaActive = !info.fxaaActive;\n }\n \n if (keyCode == GLFW_KEY_I)\n {\n info.dofActive = !info.dofActive;\n }\n \n if (keyCode == GLFW_KEY_O)\n {\n info.normalMappingActive = !info.normalMappingActive;\n }\n\n\tif (keyCode == GLFW_KEY_P)\n\t{\n\t\tinfo.godRayActive = !info.godRayActive;\n\t}\n}\n\nvoid CCameraController::handleMouseMovementEvent(int x, int y)\n{\n m_camera->pitch((y - m_lastY) * m_speed \/ 1000);\n m_camera->yaw(-(x - m_lastX) * m_speed \/ 1000);\n\n m_lastX = x;\n m_lastY = y;\n}\n\nvoid CCameraController::handleMouseButtonEvent(EMouseButtonEventType type, int buttonCode)\n{\n \/\/ TODO\n}\n\nvoid CCameraController::handleResizeEvent(int width, int height)\n{\n m_camera->setProjection(m_camera->getFieldOfView(), (float)width \/ height, m_camera->getZNear(),\n m_camera->getZFar());\n}\ncleanup#include \n#include \n\n#include \"CCameraController.h\"\n\n#include \n#include \n\n#include \"debug\/Log.h\"\n\n#include \"graphics\/camera\/IControllableCamera.h\"\n\n#include \"input\/IInputProvider.h\"\n#include \"io\/JsonUtil.h\"\n#include \"io\/JsonDeserialize.h\"\n\nCCameraController::CCameraController() {}\n\nCCameraController::~CCameraController()\n{\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->removeInputListener(this);\n }\n}\n\nvoid CCameraController::setCamera(std::shared_ptr camera)\n{\n m_camera = camera;\n}\n\nvoid CCameraController::setInputProvider(IInputProvider* provider)\n{\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->removeInputListener(this);\n }\n\n m_inputProvider = provider;\n\n if (m_inputProvider != nullptr)\n {\n m_inputProvider->addInputListener(this);\n }\n}\n\nbool CCameraController::loadSequence(std::string file)\n{\n m_sequenceTime = 0;\n m_sequencePoints.clear();\n\n Json::Reader reader;\n Json::Value root;\n\n \/\/ Load scene file\n std::ifstream ifs(file);\n if (!ifs.is_open())\n {\n LOG_ERROR(\"Failed to open json file %s.\", file.c_str());\n return false;\n }\n\n \/\/ Parse json data\n if (!reader.parse(ifs, root))\n {\n LOG_ERROR(\"Failed to load scene file %s with error %s.\", file.c_str(),\n reader.getFormattedErrorMessages().c_str());\n return false;\n }\n \/\/ Read done, close file\n ifs.close();\n\n Json::Value node = root[\"positions\"];\n\n \/\/ Node empty?\n if (node.empty())\n {\n LOG_INFO(\"Missing or empty 'positions' node. No scene objects are loaded.\");\n return true;\n }\n\n \/\/ Node is array type\n if (!node.isArray())\n {\n LOG_ERROR(\"The node 'positions' must be array type.\");\n return false;\n }\n\n bool success = true;\n\n for (unsigned int i = 0; i < node.size(); ++i)\n {\n glm::vec3 position;\n glm::vec3 orientation;\n float timestamp;\n bool fxaaActive;\n bool fogActive;\n\n if (!load(node[i], \"position\", position))\n {\n LOG_ERROR(\"Failed loading node 'position' for element #%i.\", i);\n success = false;\n break;\n }\n\n if (!load(node[i], \"orientation\", orientation))\n {\n LOG_ERROR(\"Failed loading node 'orientation' for element #%i.\", i);\n success = false;\n break;\n }\n\n if (!load(node[i], \"timestamp\", timestamp))\n {\n LOG_ERROR(\"Failed loading node 'timestamp' for element #%i.\", i);\n success = false;\n break;\n }\n \n if (!load(node[i], \"fxaa\", fxaaActive))\n {\n LOG_ERROR(\"Failed loading node 'fxaa' for element #%i.\", i);\n success = false;\n break;\n }\n \n if (!load(node[i], \"fog\", fogActive))\n {\n LOG_ERROR(\"Failed loading node 'fog' for element #%i.\", i);\n success = false;\n break;\n }\n\n SequencePoint sp{position, glm::normalize(orientation), timestamp, fxaaActive, fogActive};\n m_sequencePoints.push_back(sp);\n }\n\n m_isRunningSequence = success;\n return success;\n}\n\nvoid CCameraController::animate(float dt)\n{\n if (m_inputProvider != nullptr && m_camera != nullptr)\n {\n animateFeatures(dt);\n \n if (m_isRunningSequence)\n {\n animateSequence(dt);\n }\n else\n {\n animateManual(dt);\n }\n }\n}\n\nvoid CCameraController::animateFeatures(float dt) {\n \/\/ tODO\n}\n\nvoid CCameraController::animateSequence(float dt) {\n if (m_inputProvider->isKeyPressed(GLFW_KEY_C))\n {\n m_isRunningSequence = false;\n return;\n }\n \n float timeModifier = 1.0f;\n if (m_inputProvider->isKeyPressed(GLFW_KEY_B))\n {\n timeModifier = -2.0f;\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_N))\n {\n timeModifier = 4.0f;\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_M))\n {\n timeModifier = 8.0f;\n }\n \n m_sequenceTime += (dt * timeModifier);\n \n if (m_sequenceTime > m_sequencePoints.back().timestamp)\n {\n m_isRunningSequence = false;\n return;\n }\n \n auto it = std::find_if(m_sequencePoints.begin(), m_sequencePoints.end(),\n [&](const SequencePoint& s)\n {\n return s.timestamp >= m_sequenceTime;\n });\n \n if (it == m_sequencePoints.begin())\n {\n \/\/ not started yet\n return;\n }\n \n SequencePoint after = *it;\n SequencePoint before = *(--it);\n \n float ix = (m_sequenceTime - before.timestamp) \/ (after.timestamp - before.timestamp);\n glm::vec3 cameraPosition = before.position * (1.0f - ix) + after.position * ix;\n glm::vec3 cameraOrientation = before.orientation * (1.0f - ix) + after.orientation * ix;\n \n m_camera->lookAt(cameraPosition, cameraPosition + cameraOrientation, glm::vec3(0,1,0));\n m_camera->getFeatureInfoForWrite().fogType = (before.fogActive ? FogType::Exp2 : FogType::None);\n m_camera->getFeatureInfoForWrite().fxaaActive = before.fxaaActive;\n}\n\nvoid CCameraController::animateManual(float dt) {\n float walkingModifier = 1.0f;\n if (m_inputProvider->isKeyPressed(GLFW_KEY_SPACE))\n {\n walkingModifier = 6.0f;\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_W))\n {\n m_camera->moveForward(dt * 2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_S))\n {\n m_camera->moveForward(dt * -2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_A))\n {\n m_camera->moveRight(dt * 2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_D))\n {\n m_camera->moveRight(dt * -2.f * m_speed * walkingModifier);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_Q))\n {\n m_camera->moveUp(dt * -2.f * m_speed * walkingModifier);\n }\n if (m_inputProvider->isKeyPressed(GLFW_KEY_E))\n {\n m_camera->moveUp(dt * 2.f * m_speed * walkingModifier);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_UP))\n {\n m_camera->pitch(-dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_DOWN))\n {\n m_camera->pitch(dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_RIGHT))\n {\n m_camera->yaw(-dt * m_speed);\n }\n \n if (m_inputProvider->isKeyPressed(GLFW_KEY_LEFT))\n {\n m_camera->yaw(dt * m_speed);\n }\n}\n\nvoid CCameraController::handleKeyEvent(EKeyEventType type, int keyCode)\n{\n if (type != EKeyEventType::KEY_PRESSED) {\n return;\n }\n \n SFeatureInfo& info = m_camera->getFeatureInfoForWrite();\n \n\n\tif (keyCode == GLFW_KEY_R)\n\t{\n\t\tswitch (info.renderMode) {\n\t\tcase RenderMode::Final:\n\t\t\tinfo.renderMode = RenderMode::Color;\n\t\t\tbreak;\n\t\tcase RenderMode::Color:\n\t\t\tinfo.renderMode = RenderMode::Depth;\n\t\t\tbreak;\n\t\tcase RenderMode::Depth:\n\t\t\tinfo.renderMode = RenderMode::Lights;\n\t\t\tbreak;\n\t\tcase RenderMode::Lights:\n\t\t\tinfo.renderMode = RenderMode::Normals;\n\t\t\tbreak;\n\t\tcase RenderMode::Normals:\n\t\t\tinfo.renderMode = RenderMode::GodRay;\n\t\t\tbreak;\n\t\tcase RenderMode::GodRay:\n\t\t\tinfo.renderMode = RenderMode::Final;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tinfo.renderMode = RenderMode::Final;\n\t\t\tbreak;\n\t\t}\n\t}\n\n if (keyCode == GLFW_KEY_T)\n {\n switch (info.fogType) {\n case FogType::None:\n info.fogType = FogType::Linear;\n break;\n case FogType::Linear:\n info.fogType = FogType::Exp;\n break;\n case FogType::Exp:\n info.fogType = FogType::Exp2;\n break;\n case FogType::Exp2:\n info.fogType = FogType::None;\n break;\n default:\n info.fogType = FogType::None;\n break;\n }\n }\n \n if (keyCode == GLFW_KEY_Z)\n {\n info.shadowsActive = !info.shadowsActive;\n }\n \n if (keyCode == GLFW_KEY_U)\n {\n info.fxaaActive = !info.fxaaActive;\n }\n \n if (keyCode == GLFW_KEY_I)\n {\n info.dofActive = !info.dofActive;\n }\n \n if (keyCode == GLFW_KEY_O)\n {\n info.normalMappingActive = !info.normalMappingActive;\n }\n\n\tif (keyCode == GLFW_KEY_P)\n\t{\n\t\tinfo.godRayActive = !info.godRayActive;\n\t}\n}\n\nvoid CCameraController::handleMouseMovementEvent(int x, int y)\n{\n m_camera->pitch((y - m_lastY) * m_speed \/ 1000);\n m_camera->yaw(-(x - m_lastX) * m_speed \/ 1000);\n\n m_lastX = x;\n m_lastY = y;\n}\n\nvoid CCameraController::handleMouseButtonEvent(EMouseButtonEventType type, int buttonCode)\n{\n \/\/ TODO\n}\n\nvoid CCameraController::handleResizeEvent(int width, int height)\n{\n m_camera->setProjection(m_camera->getFieldOfView(), (float)width \/ height, m_camera->getZNear(), m_camera->getZFar());\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include \"Storage.h\"\n\nnamespace fblualib {\nnamespace python {\n\nint initStorage(lua_State* L) {\n PythonGuard g;\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n return 0;\n}\n\n}} \/\/ namespaces\ncomment out unused parameter in python\/Storage.cpp\/*\n * Copyright (c) 2014, Facebook, Inc.\n * All rights reserved.\n *\n * This source code is licensed under the BSD-style license found in the\n * LICENSE file in the root directory of this source tree. An additional grant\n * of patent rights can be found in the PATENTS file in the same directory.\n *\n *\/\n\n#include \"Storage.h\"\n\nnamespace fblualib {\nnamespace python {\n\nint initStorage(lua_State* \/*L*\/) {\n PythonGuard g;\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n PythonStorage::define();\n return 0;\n}\n\n}} \/\/ namespaces\n<|endoftext|>"} {"text":"Attempting to resolve AI over-spawn issue - I believe players transferring to another server would result in the server entering sleep immediately and not resolving to remove the player ship somehow, resulting in ever-increasing maxPlayerScoreAI() returns. Resulted to calculating actual connected clients.<|endoftext|>"} {"text":"#include \"outputfunction.h\"\n\nspnp::OutputFunction::OutputFunction(OutputFunction::TYPE type, std::string objId, std::string option)\n :AbstractData()\n{\n this->objId = objId;\n this->option = option;\n this->type = type;\n this->functionNumber = 0;\n\n this->vars = \"\";\n this->functionName = \"\";\n this->functionString = \"\";\n this->finalString = \"\";\n this->descriptionString = \"\";\n\n this->prepareData();\n}\n\nspnp::OutputFunction::~OutputFunction()\n{\n\n}\n\nXMLNode *spnp::OutputFunction::toXML()\n{\n XMLNode* n = AbstractData::toXML();\n n->setAttribute(\"object_id\", this->objId);\n n->setAttribute(\"option\", this->option);\n n->setAttribute(\"type\",static_cast(this->type));\n\n return n;\n}\n\nvoid spnp::OutputFunction::fromXML(XMLNode *xml)\n{\n AbstractData::fromXML(xml);\n this->objId = xml->getAttributeS(\"object_id\");\n this->option = xml->getAttributeS(\"option\");\n this->type = static_cast(xml->getAttributeI(\"type\"));\n}\n\nvoid spnp::OutputFunction::setFunctionNumber(int num)\n{\n this->functionNumber = num;\n}\n\nstd::string spnp::OutputFunction::c_str(spnp::IData *data) const\n{\n (void)data;\n\n return \"\";\n}\n\nstd::string spnp::OutputFunction::getVariables()\n{\n return this->vars;\n}\n\nstd::string spnp::OutputFunction::getFunction()\n{\n return this->functionString;\n}\n\nstd::string spnp::OutputFunction::getFinal()\n{\n return this->finalString;\n}\n\nstd::string spnp::OutputFunction::getDescription()\n{\n return this->descriptionString;\n}\n\nvoid spnp::OutputFunction::prepareFunction()\n{\n switch (this->type)\n {\n case TYPE::EXPECTED_TOKEN_PLACE_STEADY:\n this->prepareETPS();\n break;\n case TYPE::EXPECTED_TOKEN_PLACE_TIME:\n this->prepareETPT();\n break;\n case TYPE::EXPECTED_TOKEN_PLACES_STEADY:\n this->prepareETPsS();\n break;\n case TYPE::EXPECTED_TOKEN_PLACES_TIME:\n this->prepareETPsT();\n break;\n\n case TYPE::THROUGHPUT_TRANSITION_STEADY:\n this->prepareTTS();\n break;\n case TYPE::THROUGHPUT_TRANSITION_TIME:\n this->prepareTTT();\n break;\n case TYPE::THROUGHPUT_TRANSITIONS_STEADY:\n this->prepareTTsS();\n break;\n case TYPE::THROUGHPUT_TRANSITIONS_TIME:\n this->prepareTTsT();\n break;\n\n case TYPE::UTILIZATION_TRANSITION_STEADY:\n this->prepareUTS();\n break;\n case TYPE::UTILIZATION_TRANSITION_TIME:\n this->prepareUTT();\n break;\n case TYPE::UTILIZATION_TRANSITIONS_STEADY:\n this->prepareUTsS();\n break;\n case TYPE::UTILIZATION_TRANSITIONS_TIME:\n this->prepareUTsT();\n break;\n\n case TYPE::PROB_PLACE_STEADY:\n this->preparePPS();\n break;\n case TYPE::PROB_PLACE_TIME:\n this->preparePPT();\n break;\n case TYPE::PROB_PLACES_STEADY:\n this->preparePPsS();\n break;\n case TYPE::PROB_PLACES_TIME:\n this->preparePPsT();\n break;\n\n case TYPE::EXPECTED_REWARD_STEADY:\n this->prepareERS();\n break;\n case TYPE::EXPECTED_REWARD_TIME:\n this->prepareERT();\n break;\n case TYPE::EXPECTED_ACCUMULATED_ABSORTION:\n this->prepareEAA();\n break;\n case TYPE::EXPECTED_ACCUMULATED_TIME:\n this->prepareEAT();\n break;\n case TYPE::STEADY_DEFAULT:\n this->prepareSD();\n break;\n case TYPE::VARIABLE:\n this->prepareV();\n break;\n default:\n this->prepareNull();\n break;\n }\n}\n\n\nstd::string spnp::OutputFunction::getClassNodeName()\n{\n return \"output_funcion\";\n}\n\nvoid spnp::OutputFunction::prepareData()\n{\n this->functionName = \"outFunc\" + std::to_string(this->functionNumber);\n this->prepareFunction();\n}\n\nvoid spnp::OutputFunction::prepareETPS()\n{\n this->functionString = \"double \" + this->functionName + \"() {\\n\";\n this->functionString+= \"\\treturn(mark(\"+ objId +\"));\\n}\\n\";\n\n this->descriptionString = \"Expected # of tokens of the place \" + objId + \" in steady-state\";\n\n this->finalString = \"\\tsolve(INFINITY);\\n\";\n this->finalString += \"pr_expected(\\\"\"+ this->descriptionString +\"\\\",\"+ this->functionName +\")\";\n}\n\nvoid spnp::OutputFunction::prepareETPT()\n{\n this->functionString = \"double \" + this->functionName + \"() {\\n\";\n this->functionString+= \"\\treturn(mark(\"+ objId +\"));\\n}\\n\";\n\n this->descriptionString = \"Expected # of tokens of the place \" + objId + \": \" + this->option;\n\n std::vector data = this->split(this->option);\n this->finalString = \"for(loop=\" + data.at(0)+\";loop<\"+data.at(1)+\";loop+=\"+data.at(2)+\") {\\n\";\n this->finalString += \"\\tsolve((double) loop);\\n\";\n this->finalString += \"\\tpr_expected(\\\"Expected # of tokens of the place \"+objId+\"\\\",\"+this->functionName+\");\";\n}\n\nvoid spnp::OutputFunction::prepareETPsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareETPsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTsT()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPS()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPT()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPsS()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareERS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareERT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareEAA()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareEAT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareSD()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareV()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareNull()\n{\n\n}\n\nstd::vector spnp::OutputFunction::split(std::string in)\n{\n std::vector out;\n int index = -1;\n do\n {\n index = in.find(',');\n if(index>-1)\n {\n out.push_back(in.substr(0, index));\n in = in.substr(index, in.size());\n }\n } while(index > -1);\n\n return out;\n}\nCorreção na função de avaliação#include \"outputfunction.h\"\n\nspnp::OutputFunction::OutputFunction(OutputFunction::TYPE type, std::string objId, std::string option)\n :AbstractData()\n{\n this->objId = objId;\n this->option = option;\n this->type = type;\n this->functionNumber = 0;\n\n this->vars = \"\";\n this->functionName = \"\";\n this->functionString = \"\";\n this->finalString = \"\";\n this->descriptionString = \"\";\n\n this->prepareData();\n}\n\nspnp::OutputFunction::~OutputFunction()\n{\n\n}\n\nXMLNode *spnp::OutputFunction::toXML()\n{\n XMLNode* n = AbstractData::toXML();\n n->setAttribute(\"object_id\", this->objId);\n n->setAttribute(\"option\", this->option);\n n->setAttribute(\"type\",static_cast(this->type));\n\n return n;\n}\n\nvoid spnp::OutputFunction::fromXML(XMLNode *xml)\n{\n AbstractData::fromXML(xml);\n this->objId = xml->getAttributeS(\"object_id\");\n this->option = xml->getAttributeS(\"option\");\n this->type = static_cast(xml->getAttributeI(\"type\"));\n}\n\nvoid spnp::OutputFunction::setFunctionNumber(int num)\n{\n this->functionNumber = num;\n}\n\nstd::string spnp::OutputFunction::c_str(spnp::IData *data) const\n{\n (void)data;\n\n return \"\";\n}\n\nstd::string spnp::OutputFunction::getVariables()\n{\n return this->vars;\n}\n\nstd::string spnp::OutputFunction::getFunction()\n{\n return this->functionString;\n}\n\nstd::string spnp::OutputFunction::getFinal()\n{\n return this->finalString;\n}\n\nstd::string spnp::OutputFunction::getDescription()\n{\n return this->descriptionString;\n}\n\nvoid spnp::OutputFunction::prepareFunction()\n{\n switch (this->type)\n {\n case TYPE::EXPECTED_TOKEN_PLACE_STEADY:\n this->prepareETPS();\n break;\n case TYPE::EXPECTED_TOKEN_PLACE_TIME:\n this->prepareETPT();\n break;\n case TYPE::EXPECTED_TOKEN_PLACES_STEADY:\n this->prepareETPsS();\n break;\n case TYPE::EXPECTED_TOKEN_PLACES_TIME:\n this->prepareETPsT();\n break;\n\n case TYPE::THROUGHPUT_TRANSITION_STEADY:\n this->prepareTTS();\n break;\n case TYPE::THROUGHPUT_TRANSITION_TIME:\n this->prepareTTT();\n break;\n case TYPE::THROUGHPUT_TRANSITIONS_STEADY:\n this->prepareTTsS();\n break;\n case TYPE::THROUGHPUT_TRANSITIONS_TIME:\n this->prepareTTsT();\n break;\n\n case TYPE::UTILIZATION_TRANSITION_STEADY:\n this->prepareUTS();\n break;\n case TYPE::UTILIZATION_TRANSITION_TIME:\n this->prepareUTT();\n break;\n case TYPE::UTILIZATION_TRANSITIONS_STEADY:\n this->prepareUTsS();\n break;\n case TYPE::UTILIZATION_TRANSITIONS_TIME:\n this->prepareUTsT();\n break;\n\n case TYPE::PROB_PLACE_STEADY:\n this->preparePPS();\n break;\n case TYPE::PROB_PLACE_TIME:\n this->preparePPT();\n break;\n case TYPE::PROB_PLACES_STEADY:\n this->preparePPsS();\n break;\n case TYPE::PROB_PLACES_TIME:\n this->preparePPsT();\n break;\n\n case TYPE::EXPECTED_REWARD_STEADY:\n this->prepareERS();\n break;\n case TYPE::EXPECTED_REWARD_TIME:\n this->prepareERT();\n break;\n case TYPE::EXPECTED_ACCUMULATED_ABSORTION:\n this->prepareEAA();\n break;\n case TYPE::EXPECTED_ACCUMULATED_TIME:\n this->prepareEAT();\n break;\n case TYPE::STEADY_DEFAULT:\n this->prepareSD();\n break;\n case TYPE::VARIABLE:\n this->prepareV();\n break;\n default:\n this->prepareNull();\n break;\n }\n}\n\n\nstd::string spnp::OutputFunction::getClassNodeName()\n{\n return \"output_funcion\";\n}\n\nvoid spnp::OutputFunction::prepareData()\n{\n this->functionName = \"outFunc\" + std::to_string(this->functionNumber);\n this->prepareFunction();\n}\n\nvoid spnp::OutputFunction::prepareETPS()\n{\n this->functionString = \"double \" + this->functionName + \"() {\\n\";\n this->functionString+= \"\\treturn(mark(\"+ objId +\"));\\n}\\n\";\n\n this->descriptionString = \"Expected # of tokens of the place \" + objId + \" in steady-state\";\n\n this->finalString = \"\\tsolve(INFINITY);\\n\";\n this->finalString += \"pr_expected(\\\"\"+ this->descriptionString +\"\\\",\"+ this->functionName +\")\";\n}\n\nvoid spnp::OutputFunction::prepareETPT()\n{\n this->functionString = \"double \" + this->functionName + \"() {\\n\";\n this->functionString+= \"\\treturn(mark(\"+ objId +\"));\\n}\\n\";\n\n this->descriptionString = \"Expected # of tokens of the place \" + objId + \": \" + this->option;\n\n std::vector data = this->split(this->option);\n this->finalString = \"for(loop=\" + data.at(0)+\";loop<\"+data.at(1)+\";loop+=\"+data.at(2)+\") {\\n\";\n this->finalString += \"\\tsolve((double) loop);\\n\";\n this->finalString += \"\\tpr_expected(\\\"Expected # of tokens of the place \"+objId+\"\\\",\"+this->functionName+\");\";\n}\n\nvoid spnp::OutputFunction::prepareETPsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareETPsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareTTsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTsS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareUTsT()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPS()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPT()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPsS()\n{\n\n}\n\nvoid spnp::OutputFunction::preparePPsT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareERS()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareERT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareEAA()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareEAT()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareSD()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareV()\n{\n\n}\n\nvoid spnp::OutputFunction::prepareNull()\n{\n\n}\n\nstd::vector spnp::OutputFunction::split(std::string in)\n{\n std::vector out;\n int index = -1;\n do\n {\n index = in.find(',');\n if(index>-1)\n {\n out.push_back(in.substr(0, index));\n in = in.substr(index+1, in.size());\n }\n else\n {\n out.push_back(in);\n }\n } while(index > -1);\n\n return out;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bibmod.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 19:13:55 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n#ifndef _URLOBJ_HXX\n#include \n#endif\n#ifndef SVTOOLS_URIHELPER_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XLOCALIZEDALIASES_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#include \"bibmod.hxx\"\n#include \"bibresid.hxx\"\n#include \"datman.hxx\"\n#include \"bibconfig.hxx\"\nstatic PtrBibModul pBibModul=NULL;\nstatic sal_uInt32 nBibModulCount=0;\n\n#ifndef _UCBHELPER_CONTENT_HXX\n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::ucb;\n\n#define C2U(cChar) OUString::createFromAscii(cChar)\n#define C2S(cChar) String::CreateFromAscii(cChar)\n\nHdlBibModul OpenBibModul()\n{\n if(pBibModul==NULL)\n {\n pBibModul=new BibModul();\n }\n nBibModulCount++;\n return &pBibModul;\n}\n\nvoid CloseBibModul(HdlBibModul ppBibModul)\n{\n nBibModulCount--;\n if(nBibModulCount==0 && ppBibModul!=NULL)\n {\n delete pBibModul;\n pBibModul=NULL;\n }\n}\n\nBibResId::BibResId( sal_uInt16 nId ) :\n ResId( nId, pBibModul->GetResMgr() )\n{\n}\nBibConfig* BibModul::pBibConfig = 0;\nBibModul::BibModul()\n{\n pResMgr = ResMgr::CreateResMgr( \"bib\" MAKE_NUMSTR(SUPD) );\n}\n\nBibModul::~BibModul()\n{\n delete pResMgr;\n delete pBibConfig;\n pBibConfig = 0;\n}\n\nBibDataManager* BibModul::createDataManager()\n{\n return new BibDataManager();\n}\n\/\/-----------------------------------------------------------------------------\nBibConfig* BibModul::GetConfig()\n{\n if(! pBibConfig)\n pBibConfig = new BibConfig;\n return pBibConfig;\n}\n\n\n\/\/ PropertyNames\n#define STATIC_USTRING(a,b) rtl::OUString a(b)\nSTATIC_USTRING(FM_PROP_LABEL,C2U(\"Label\"));\nSTATIC_USTRING(FM_PROP_CONTROLSOURCE,C2U(\"DataField\"));\nSTATIC_USTRING(FM_PROP_NAME,C2U(\"Name\"));\nSTATIC_USTRING(FM_PROP_FORMATKEY,C2U(\"FormatKey\"));\n#ifdef TF_SDBAPI\n#else \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_EDITMODE,C2U(\"RecordMode\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCETYPE,C2U(\"DataSelectionType\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCE,C2U(\"DataSelection\"));\nSTATIC_USTRING(FM_PROP_DATASOURCE, C2U(\"DataSource\"));\n#endif \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_VALUE,C2U(\"Value\"));\nSTATIC_USTRING(FM_PROP_TEXT,C2U(\"Text\"));\nINTEGRATION: CWS pchfix02 (1.8.186); FILE MERGED 2006\/09\/01 17:26:26 kaib 1.8.186.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: bibmod.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 12:55:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_extensions.hxx\"\n\n\n#include \n#ifndef _URLOBJ_HXX\n#include \n#endif\n#ifndef SVTOOLS_URIHELPER_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_UTIL_XLOCALIZEDALIASES_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XLOCALIZABLE_HPP_\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#include \"bibmod.hxx\"\n#include \"bibresid.hxx\"\n#include \"datman.hxx\"\n#include \"bibconfig.hxx\"\nstatic PtrBibModul pBibModul=NULL;\nstatic sal_uInt32 nBibModulCount=0;\n\n#ifndef _UCBHELPER_CONTENT_HXX\n#include \n#endif\n\nusing namespace ::rtl;\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::util;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::ucb;\n\n#define C2U(cChar) OUString::createFromAscii(cChar)\n#define C2S(cChar) String::CreateFromAscii(cChar)\n\nHdlBibModul OpenBibModul()\n{\n if(pBibModul==NULL)\n {\n pBibModul=new BibModul();\n }\n nBibModulCount++;\n return &pBibModul;\n}\n\nvoid CloseBibModul(HdlBibModul ppBibModul)\n{\n nBibModulCount--;\n if(nBibModulCount==0 && ppBibModul!=NULL)\n {\n delete pBibModul;\n pBibModul=NULL;\n }\n}\n\nBibResId::BibResId( sal_uInt16 nId ) :\n ResId( nId, pBibModul->GetResMgr() )\n{\n}\nBibConfig* BibModul::pBibConfig = 0;\nBibModul::BibModul()\n{\n pResMgr = ResMgr::CreateResMgr( \"bib\" MAKE_NUMSTR(SUPD) );\n}\n\nBibModul::~BibModul()\n{\n delete pResMgr;\n delete pBibConfig;\n pBibConfig = 0;\n}\n\nBibDataManager* BibModul::createDataManager()\n{\n return new BibDataManager();\n}\n\/\/-----------------------------------------------------------------------------\nBibConfig* BibModul::GetConfig()\n{\n if(! pBibConfig)\n pBibConfig = new BibConfig;\n return pBibConfig;\n}\n\n\n\/\/ PropertyNames\n#define STATIC_USTRING(a,b) rtl::OUString a(b)\nSTATIC_USTRING(FM_PROP_LABEL,C2U(\"Label\"));\nSTATIC_USTRING(FM_PROP_CONTROLSOURCE,C2U(\"DataField\"));\nSTATIC_USTRING(FM_PROP_NAME,C2U(\"Name\"));\nSTATIC_USTRING(FM_PROP_FORMATKEY,C2U(\"FormatKey\"));\n#ifdef TF_SDBAPI\n#else \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_EDITMODE,C2U(\"RecordMode\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCETYPE,C2U(\"DataSelectionType\"));\nSTATIC_USTRING(FM_PROP_CURSORSOURCE,C2U(\"DataSelection\"));\nSTATIC_USTRING(FM_PROP_DATASOURCE, C2U(\"DataSource\"));\n#endif \/\/ !TF_SDBAPI\nSTATIC_USTRING(FM_PROP_VALUE,C2U(\"Value\"));\nSTATIC_USTRING(FM_PROP_TEXT,C2U(\"Text\"));\n<|endoftext|>"} {"text":"\/\/ This file is part of the \"kafkaping\" project\n\/\/ \n\/\/ (c) 2017 Christian Parpart \n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"LogMessage.h\"\n\nvoid dumpConfig(RdKafka::Conf* conf, const std::string& msg) {\n std::cout << \"============================== \" << msg << std::endl;\n auto d = conf->dump();\n for (auto i = d->begin(), e = d->end(); i != e;) {\n std::cout << *i++ << \" = \" << *i++ << std::endl;\n }\n std::cout << std::endl;\n}\n\nclass Kafkaping : public RdKafka::EventCb,\n public RdKafka::DeliveryReportCb,\n public RdKafka::ConsumeCb,\n public RdKafka::OffsetCommitCb {\n public:\n Kafkaping(const std::string& brokers,\n const std::string& topic,\n int count,\n int interval,\n bool debug);\n ~Kafkaping();\n\n void producerLoop();\n void consumerLoop();\n\n void event_cb(RdKafka::Event& event) override;\n void dr_cb(RdKafka::Message& message) override;\n void consume_cb(RdKafka::Message& msg, void* opaque) override;\n void offset_commit_cb(RdKafka::ErrorCode err,\n std::vector& offsets) override;\n\n LogMessage logError() {\n return LogMessage(\"[ERROR] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n }\n\n LogMessage logInfo() {\n return LogMessage(\"[INFO] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n }\n\n LogMessage logDebug() {\n if (debug_) {\n return LogMessage(\"[DEBUG] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n } else {\n return LogMessage(\"\", [](auto m) {});\n }\n }\n\n private:\n void logPrinter(const std::string& msg) {\n std::lock_guard _lk(stderrLock_);\n\n char ts[20];\n time_t t = time(nullptr);\n struct tm tm;\n localtime_r(&t, &tm);\n int timed = strftime(ts, sizeof(ts), \"%Y-%m-%d %H:%M:%S\", &tm);\n\n if (timed) {\n fprintf(stderr, \"[%s] %s\\n\", ts, msg.c_str());\n } else {\n fprintf(stderr, \"%s\\n\", msg.c_str());\n }\n }\n\n void configureGlobal(const std::string& key, const std::string& val);\n void configureTopic(const std::string& key, const std::string& val);\n\n private:\n RdKafka::Conf* confGlobal_;\n RdKafka::Conf* confTopic_;\n std::string topicStr_;\n std::atomic count_;\n int interval_;\n bool debug_;\n int64_t startOffset_;\n std::mutex stderrLock_;\n};\n\nKafkaping::Kafkaping(const std::string& brokers,\n const std::string& topic,\n int count,\n int interval,\n bool debug)\n : confGlobal_(RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL)),\n confTopic_(RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC)),\n topicStr_(topic),\n count_(count),\n interval_(interval),\n debug_(debug),\n startOffset_(RdKafka::Topic::OFFSET_END) {\n std::string errstr;\n confGlobal_->set(\"event_cb\", (RdKafka::EventCb*) this, errstr);\n confGlobal_->set(\"dr_cb\", (RdKafka::DeliveryReportCb*) this, errstr);\n confGlobal_->set(\"metadata.broker.list\", brokers, errstr);\n\n configureGlobal(\"client.id\", \"kafkaping\");\n configureGlobal(\"group.id\", \"kafkaping\");\n\n configureGlobal(\"request.timeout.ms\", \"5000\");\n configureGlobal(\"connections.max.idle.ms\", \"10000\");\n configureGlobal(\"message.send.max.retries\", \"10\");\n\n configureGlobal(\"queue.buffering.max.ms\", \"1\"); \/\/ don't buffer inflights messages\n\n \/\/ XXX only interesting if we wanna use the broker's offset store\n \/\/ configureGlobal(\"enable.auto.commit\", \"true\");\n \/\/ configureGlobal(\"auto.commit.interval.ms\", \"true\");\n \/\/ configureGlobal(\"auto.offset.reset\", \"latest\");\n\n if (debug_) {\n dumpConfig(confGlobal_, \"global\");\n dumpConfig(confTopic_, \"topic\");\n }\n}\n\nvoid Kafkaping::configureGlobal(const std::string& key, const std::string& val) {\n std::string errstr;\n confGlobal_->set(key, val, errstr);\n}\n\nvoid Kafkaping::configureTopic(const std::string& key, const std::string& val) {\n std::string errstr;\n confTopic_->set(key, val, errstr);\n}\n\nKafkaping::~Kafkaping() {\n}\n\nvoid Kafkaping::producerLoop() {\n const int32_t partition = RdKafka::Topic::PARTITION_UA;\n std::string errstr;\n\n RdKafka::Producer* producer = RdKafka::Producer::create(confGlobal_, errstr);\n if (!producer) {\n logError() << \"Failed to create producer \" << errstr;\n exit(1);\n }\n logDebug() << \"Created producer \" << producer->name();\n\n RdKafka::Topic* topic = RdKafka::Topic::create(producer, topicStr_, confTopic_, errstr);\n if (!topic) {\n logError() << \"Failed to create topic: \" << errstr;\n exit(1);\n }\n logDebug() << \"Created topic \" << topicStr_;\n\n while (count_.load() != 0) {\n timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n std::string payload = std::to_string(ts.tv_sec) + \".\" + std::to_string(ts.tv_nsec);\n\n \/\/ produce\n RdKafka::ErrorCode resp = producer->produce(\n topic, partition, RdKafka::Producer::RK_MSG_COPY \/* Copy payload *\/,\n const_cast(payload.c_str()), payload.size() + 1, nullptr, nullptr);\n if (resp != RdKafka::ERR_NO_ERROR)\n logError() << \"Produce failed. \" << RdKafka::err2str(resp);\n else\n logDebug() << \"Produced payload:\" << payload;\n\n \/\/ wait until flushed (no need to send another message if we can't even handle that)\n if (producer->outq_len()) {\n do producer->poll(1000);\n while (producer->outq_len() > 0);\n }\n if (interval_) {\n usleep(interval_ * 1000);\n }\n }\n\n while (producer->outq_len() > 0) {\n producer->poll(1000);\n }\n\n delete topic;\n \/\/FIXME(doesn't return): delete producer;\n}\n\nvoid Kafkaping::consumerLoop() {\n const int32_t partition = 0;\n\n std::string errstr;\n RdKafka::Consumer *consumer = RdKafka::Consumer::create(confGlobal_, errstr);\n if (!consumer) {\n logError() << \"Failed to create consumer: \" << errstr;\n abort();\n }\n logDebug() << \"Created consumer \" << consumer->name();\n\n RdKafka::Topic *topic = RdKafka::Topic::create(consumer, topicStr_, confTopic_, errstr);\n if (!topic) {\n logError() << \"Failed to create consumer topic: \" << errstr;\n abort();\n }\n\n RdKafka::ErrorCode resp = consumer->start(topic, partition, startOffset_);\n if (resp != RdKafka::ERR_NO_ERROR) {\n logError() << \"Failed to start consumer (\" << resp << \"): \" << RdKafka::err2str(resp);\n abort();\n }\n\n while (count_.load() != 0) {\n consumer->consume_callback(topic, partition, 1000, this, nullptr);\n consumer->poll(0);\n }\n\n logDebug() << \"Stopping consumer\";\n consumer->stop(topic, partition);\n consumer->poll(1000);\n\n delete topic;\n delete consumer;\n logDebug() << \"Stopped consumer\";\n}\n\nvoid Kafkaping::event_cb(RdKafka::Event& event) {\n switch (event.type()) {\n case RdKafka::Event::EVENT_ERROR:\n logError() << RdKafka::err2str(event.err()) << \": \" << event.str();\n \/\/ if (event.err() == RdKafka::ERR__ALL_BROKERS_DOWN)\n \/\/ abort();\n break;\n case RdKafka::Event::EVENT_STATS:\n logDebug() << \"STATS: \" << event.str();\n break;\n case RdKafka::Event::EVENT_LOG:\n logDebug() << \"LOG-\" << event.severity() << \"-\" << event.fac() << \": \" << event.str();\n break;\n default:\n logError() << \"EVENT \" << event.type() << \" (\"\n << RdKafka::err2str(event.err()) << \"): \" << event.str();\n break;\n }\n}\n\nvoid Kafkaping::dr_cb(RdKafka::Message& message) {\n if (message.err()) {\n logError() << \"Devliery Report Failure. \" << message.errstr();\n } else {\n logDebug()\n << \"Delivered offset:\" << message.offset()\n << \" payload:\" << std::string((const char*) message.payload(), message.len());\n }\n\n if (message.key())\n logDebug() << \"Key: \" << *(message.key()) << \";\";\n}\n\nvoid Kafkaping::consume_cb(RdKafka::Message& message, void* opaque) {\n switch (message.err()) {\n case RdKafka::ERR__TIMED_OUT:\n break;\n case RdKafka::ERR_NO_ERROR: {\n if (count_.load() > 0) {\n --count_;\n }\n\n timespec now;\n clock_gettime(CLOCK_MONOTONIC, &now);\n\n long secs = 0, nsecs = 0;\n std::sscanf((char*) message.payload(), \"%ld.%ld\", &secs, &nsecs);\n timespec beg{secs, nsecs};\n\n int64_t diff = (now.tv_sec * 1000 + now.tv_nsec \/ 1000000) -\n (beg.tv_sec * 1000 + beg.tv_nsec \/ 1000000);\n\n std::string broker = \"\";\n confGlobal_->get(\"metadata.broker.list\", broker);\n\n std::cout << \"Received from \" << broker << \":\"\n << \" topic=\" << message.topic_name()\n << \" partition=\" << message.partition()\n << \" offset=\" << message.offset()\n << \" time=\" << diff << \" ms\" << std::endl;\n break;\n }\n case RdKafka::ERR__PARTITION_EOF:\n \/* Last message *\/\n break;\n default:\n logError() << \"Consume failed. \" << message.errstr();\n break;\n }\n}\n\nvoid Kafkaping::offset_commit_cb(RdKafka::ErrorCode err,\n std::vector& offsets) {\n}\n\nvoid printHelp() {\n printf(\"Usage: kafkaping [-g] [-t topic] [-c count] [-i interval_ms] [broker list]\\n\");\n}\n\nint main(int argc, char* const argv[]) {\n std::string topic = \"kafkaping\";\n std::string brokers; \/\/ = \"localhost:9092\";\n int count = -1;\n int interval = 1000; \/\/ ms\n bool debug = false;\n\n for (bool done = false; !done;) {\n switch (getopt(argc, argv, \"t:c:i:hg\")) {\n case 'g':\n debug = true;\n break;\n case 't':\n topic = optarg;\n break;\n case 'c':\n count = std::atoi(optarg);\n break;\n case 'i':\n interval = std::atoi(optarg);\n break;\n case 'h':\n printHelp();\n return 0;\n case -1:\n done = true;\n break;\n default:\n printHelp();\n return 1;\n }\n }\n if (optind < argc) {\n while (optind < argc) {\n if (!brokers.empty()) {\n brokers += \",\";\n }\n brokers += argv[optind++];\n }\n }\n\n if (brokers.empty()) {\n fprintf(stderr, \"No brokers passed.\\n\");\n printHelp();\n return 1;\n }\n\n Kafkaping kafkaping(brokers, topic, count, interval, debug);\n\n std::thread producer(std::bind(&Kafkaping::producerLoop, &kafkaping));\n std::thread consumer(std::bind(&Kafkaping::consumerLoop, &kafkaping));\n\n producer.join();\n consumer.join();\n\n return 0;\n}\nabstract away the console outputter so we can support other outputs soon\/\/ This file is part of the \"kafkaping\" project\n\/\/ \n\/\/ (c) 2017 Christian Parpart \n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"LogMessage.h\"\n\nvoid dumpConfig(RdKafka::Conf* conf, const std::string& msg) {\n std::cout << \"============================== \" << msg << std::endl;\n auto d = conf->dump();\n for (auto i = d->begin(), e = d->end(); i != e;) {\n std::cout << *i++ << \" = \" << *i++ << std::endl;\n }\n std::cout << std::endl;\n}\n\nclass StatsSink {\n public:\n ~StatsSink() {}\n\n virtual void fill(const std::string& broker,\n const std::string& topic,\n int partition,\n int64_t offset,\n int64_t ts,\n unsigned latencyMs) = 0;\n};\n\nclass ConsoleSink : public StatsSink {\n public:\n void fill(const std::string& broker,\n const std::string& topic,\n int partition,\n int64_t offset,\n int64_t ts,\n unsigned latencyMs) override;\n};\n\nvoid ConsoleSink::fill(const std::string& broker,\n const std::string& topic,\n int partition,\n int64_t offset,\n int64_t ts,\n unsigned latencyMs) {\n std::cout << \"Received from \" << broker << \":\"\n << \" topic=\" << topic\n << \" partition=\" << partition\n << \" offset=\" << offset\n << \" time=\" << latencyMs << \" ms\" << std::endl;\n}\n\nclass Kafkaping : public RdKafka::EventCb,\n public RdKafka::DeliveryReportCb,\n public RdKafka::ConsumeCb,\n public RdKafka::OffsetCommitCb {\n public:\n Kafkaping(const std::string& brokers,\n const std::string& topic,\n int count,\n int interval,\n bool debug,\n StatsSink* sink);\n ~Kafkaping();\n\n void producerLoop();\n void consumerLoop();\n\n void event_cb(RdKafka::Event& event) override;\n void dr_cb(RdKafka::Message& message) override;\n void consume_cb(RdKafka::Message& msg, void* opaque) override;\n void offset_commit_cb(RdKafka::ErrorCode err,\n std::vector& offsets) override;\n\n LogMessage logError() {\n return LogMessage(\"[ERROR] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n }\n\n LogMessage logInfo() {\n return LogMessage(\"[INFO] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n }\n\n LogMessage logDebug() {\n if (debug_) {\n return LogMessage(\"[DEBUG] \", std::bind(&Kafkaping::logPrinter, this, std::placeholders::_1));\n } else {\n return LogMessage(\"\", [](auto m) {});\n }\n }\n\n private:\n void logPrinter(const std::string& msg) {\n std::lock_guard _lk(stderrLock_);\n\n char ts[20];\n time_t t = time(nullptr);\n struct tm tm;\n localtime_r(&t, &tm);\n int timed = strftime(ts, sizeof(ts), \"%Y-%m-%d %H:%M:%S\", &tm);\n\n if (timed) {\n fprintf(stderr, \"[%s] %s\\n\", ts, msg.c_str());\n } else {\n fprintf(stderr, \"%s\\n\", msg.c_str());\n }\n }\n\n void configureGlobal(const std::string& key, const std::string& val);\n void configureTopic(const std::string& key, const std::string& val);\n\n private:\n RdKafka::Conf* confGlobal_;\n RdKafka::Conf* confTopic_;\n std::string topicStr_;\n std::atomic count_;\n int interval_;\n bool debug_;\n int64_t startOffset_;\n std::mutex stderrLock_;\n StatsSink* sink_;\n};\n\nKafkaping::Kafkaping(const std::string& brokers,\n const std::string& topic,\n int count,\n int interval,\n bool debug,\n StatsSink* sink)\n : confGlobal_(RdKafka::Conf::create(RdKafka::Conf::CONF_GLOBAL)),\n confTopic_(RdKafka::Conf::create(RdKafka::Conf::CONF_TOPIC)),\n topicStr_(topic),\n count_(count),\n interval_(interval),\n debug_(debug),\n startOffset_(RdKafka::Topic::OFFSET_END),\n sink_(sink) {\n std::string errstr;\n confGlobal_->set(\"event_cb\", (RdKafka::EventCb*) this, errstr);\n confGlobal_->set(\"dr_cb\", (RdKafka::DeliveryReportCb*) this, errstr);\n confGlobal_->set(\"metadata.broker.list\", brokers, errstr);\n\n configureGlobal(\"client.id\", \"kafkaping\");\n configureGlobal(\"group.id\", \"kafkaping\");\n\n configureGlobal(\"request.timeout.ms\", \"5000\");\n configureGlobal(\"connections.max.idle.ms\", \"10000\");\n configureGlobal(\"message.send.max.retries\", \"10\");\n\n configureGlobal(\"queue.buffering.max.ms\", \"1\"); \/\/ don't buffer inflights messages\n\n \/\/ XXX only interesting if we wanna use the broker's offset store\n \/\/ configureGlobal(\"enable.auto.commit\", \"true\");\n \/\/ configureGlobal(\"auto.commit.interval.ms\", \"true\");\n \/\/ configureGlobal(\"auto.offset.reset\", \"latest\");\n\n if (debug_) {\n dumpConfig(confGlobal_, \"global\");\n dumpConfig(confTopic_, \"topic\");\n }\n}\n\nvoid Kafkaping::configureGlobal(const std::string& key, const std::string& val) {\n std::string errstr;\n confGlobal_->set(key, val, errstr);\n}\n\nvoid Kafkaping::configureTopic(const std::string& key, const std::string& val) {\n std::string errstr;\n confTopic_->set(key, val, errstr);\n}\n\nKafkaping::~Kafkaping() {\n}\n\nvoid Kafkaping::producerLoop() {\n const int32_t partition = RdKafka::Topic::PARTITION_UA;\n std::string errstr;\n\n RdKafka::Producer* producer = RdKafka::Producer::create(confGlobal_, errstr);\n if (!producer) {\n logError() << \"Failed to create producer \" << errstr;\n exit(1);\n }\n logDebug() << \"Created producer \" << producer->name();\n\n RdKafka::Topic* topic = RdKafka::Topic::create(producer, topicStr_, confTopic_, errstr);\n if (!topic) {\n logError() << \"Failed to create topic: \" << errstr;\n exit(1);\n }\n logDebug() << \"Created topic \" << topicStr_;\n\n while (count_.load() != 0) {\n timespec ts;\n clock_gettime(CLOCK_MONOTONIC, &ts);\n std::string payload = std::to_string(ts.tv_sec) + \".\" + std::to_string(ts.tv_nsec);\n\n \/\/ produce\n RdKafka::ErrorCode resp = producer->produce(\n topic, partition, RdKafka::Producer::RK_MSG_COPY \/* Copy payload *\/,\n const_cast(payload.c_str()), payload.size() + 1, nullptr, nullptr);\n if (resp != RdKafka::ERR_NO_ERROR)\n logError() << \"Produce failed. \" << RdKafka::err2str(resp);\n else\n logDebug() << \"Produced payload:\" << payload;\n\n \/\/ wait until flushed (no need to send another message if we can't even handle that)\n if (producer->outq_len()) {\n do producer->poll(1000);\n while (producer->outq_len() > 0);\n }\n if (interval_) {\n usleep(interval_ * 1000);\n }\n }\n\n while (producer->outq_len() > 0) {\n producer->poll(1000);\n }\n\n delete topic;\n \/\/FIXME(doesn't return): delete producer;\n}\n\nvoid Kafkaping::consumerLoop() {\n const int32_t partition = 0;\n\n std::string errstr;\n RdKafka::Consumer *consumer = RdKafka::Consumer::create(confGlobal_, errstr);\n if (!consumer) {\n logError() << \"Failed to create consumer: \" << errstr;\n abort();\n }\n logDebug() << \"Created consumer \" << consumer->name();\n\n RdKafka::Topic *topic = RdKafka::Topic::create(consumer, topicStr_, confTopic_, errstr);\n if (!topic) {\n logError() << \"Failed to create consumer topic: \" << errstr;\n abort();\n }\n\n RdKafka::ErrorCode resp = consumer->start(topic, partition, startOffset_);\n if (resp != RdKafka::ERR_NO_ERROR) {\n logError() << \"Failed to start consumer (\" << resp << \"): \" << RdKafka::err2str(resp);\n abort();\n }\n\n while (count_.load() != 0) {\n consumer->consume_callback(topic, partition, 1000, this, nullptr);\n consumer->poll(0);\n }\n\n logDebug() << \"Stopping consumer\";\n consumer->stop(topic, partition);\n consumer->poll(1000);\n\n delete topic;\n delete consumer;\n logDebug() << \"Stopped consumer\";\n}\n\nvoid Kafkaping::event_cb(RdKafka::Event& event) {\n switch (event.type()) {\n case RdKafka::Event::EVENT_ERROR:\n logError() << RdKafka::err2str(event.err()) << \": \" << event.str();\n \/\/ if (event.err() == RdKafka::ERR__ALL_BROKERS_DOWN)\n \/\/ abort();\n break;\n case RdKafka::Event::EVENT_STATS:\n logDebug() << \"STATS: \" << event.str();\n break;\n case RdKafka::Event::EVENT_LOG:\n logDebug() << \"LOG-\" << event.severity() << \"-\" << event.fac() << \": \" << event.str();\n break;\n default:\n logError() << \"EVENT \" << event.type() << \" (\"\n << RdKafka::err2str(event.err()) << \"): \" << event.str();\n break;\n }\n}\n\nvoid Kafkaping::dr_cb(RdKafka::Message& message) {\n if (message.err()) {\n logError() << \"Devliery Report Failure. \" << message.errstr();\n } else {\n logDebug()\n << \"Delivered offset:\" << message.offset()\n << \" payload:\" << std::string((const char*) message.payload(), message.len());\n }\n\n if (message.key())\n logDebug() << \"Key: \" << *(message.key()) << \";\";\n}\n\nvoid Kafkaping::consume_cb(RdKafka::Message& message, void* opaque) {\n switch (message.err()) {\n case RdKafka::ERR__TIMED_OUT:\n break;\n case RdKafka::ERR_NO_ERROR: {\n if (count_.load() > 0) {\n --count_;\n }\n\n timespec now;\n clock_gettime(CLOCK_MONOTONIC, &now);\n\n long secs = 0, nsecs = 0;\n std::sscanf((char*) message.payload(), \"%ld.%ld\", &secs, &nsecs);\n timespec beg{secs, nsecs};\n\n int64_t diff = (now.tv_sec * 1000 + now.tv_nsec \/ 1000000) -\n (beg.tv_sec * 1000 + beg.tv_nsec \/ 1000000);\n\n std::string broker = \"\";\n confGlobal_->get(\"metadata.broker.list\", broker);\n\n sink_->fill(broker, message.topic_name(), message.partition(),\n message.offset(), message.timestamp().timestamp, diff);\n break;\n }\n case RdKafka::ERR__PARTITION_EOF:\n \/* Last message *\/\n break;\n default:\n logError() << \"Consume failed. \" << message.errstr();\n break;\n }\n}\n\nvoid Kafkaping::offset_commit_cb(RdKafka::ErrorCode err,\n std::vector& offsets) {\n}\n\nvoid printHelp() {\n printf(\"Usage: kafkaping [-g] [-t topic] [-c count] [-i interval_ms] [broker list]\\n\");\n}\n\nint main(int argc, char* const argv[]) {\n std::string topic = \"kafkaping\";\n std::string brokers; \/\/ = \"localhost:9092\";\n int count = -1;\n int interval = 1000; \/\/ ms\n bool debug = false;\n\n for (bool done = false; !done;) {\n switch (getopt(argc, argv, \"t:c:i:hg\")) {\n case 'g':\n debug = true;\n break;\n case 't':\n topic = optarg;\n break;\n case 'c':\n count = std::atoi(optarg);\n break;\n case 'i':\n interval = std::atoi(optarg);\n break;\n case 'h':\n printHelp();\n return 0;\n case -1:\n done = true;\n break;\n default:\n printHelp();\n return 1;\n }\n }\n if (optind < argc) {\n while (optind < argc) {\n if (!brokers.empty()) {\n brokers += \",\";\n }\n brokers += argv[optind++];\n }\n }\n\n if (brokers.empty()) {\n fprintf(stderr, \"No brokers passed.\\n\");\n printHelp();\n return 1;\n }\n\n ConsoleSink consoleSink;\n Kafkaping kafkaping(brokers, topic, count, interval, debug, &consoleSink);\n\n std::thread producer(std::bind(&Kafkaping::producerLoop, &kafkaping));\n std::thread consumer(std::bind(&Kafkaping::consumerLoop, &kafkaping));\n\n producer.join();\n consumer.join();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"scientistservice.h\"\n\n\nusing namespace std;\n\n\n\/\/operator overloading functions for scientistSort.\nbool sortByNameAsc (const Scientist &a, const Scientist &b)\n{ \/\/ also makes the sort case insensitive.\n string aName = a.getName(), bName = b.getName();\n transform(aName.begin(), aName.end(), aName.begin(), ::tolower);\n transform(bName.begin(), bName.end(), bName.begin(), ::tolower);\n return aName < bName;\n}\nbool sortByNameDesc(const Scientist &a, const Scientist &b)\n{ \/\/ also makes the sort case insensitive.\n string aName = a.getName(), bName = b.getName();\n transform(aName.begin(), aName.end(), aName.begin(), ::tolower);\n transform(bName.begin(), bName.end(), bName.begin(), ::tolower);\n return aName > bName;\n}\nbool sortByGender (const Scientist &a, const Scientist &b) { return a.getGender() < b.getGender(); }\nbool sortByBirth (const Scientist &a, const Scientist &b) { return a.getBirth() < b.getBirth(); }\nbool sortByDeath (const Scientist &a, const Scientist &b) { return a.getDeath() < b.getDeath(); }\nbool sortByAge (const Scientist &a, const Scientist &b) { return a.getAge() < b.getAge(); }\n\n\nScientistService::ScientistService()\n{\n\n}\n\nvector ScientistService::getScientists()\n{ \/\/ Uploads the list of scientists from file.\n\n _scientists = _data.loadScientists();\n\n return _scientists;\n}\n\nbool ScientistService::addScientist(string name, char gender, int birth, int death, int age)\n{ \/\/ Adds a scientist to the list and updates the file.\n \/\/ Returns true if adding succeded, false otherwise.\n\n Scientist scientist(name, gender, birth, death, age);\n\n if (findScientistByName(name).size() > 0)\n {\n return false;\n }\n\n else\n {\n _scientists.push_back(scientist);\n _data.saveScientists(_scientists);\n return true;\n }\n}\nbool ScientistService::removeScientist(string name)\n{ \/\/ Removes a scientist with that name from the vector. Case insensitive.\n \/\/ Returns true if removing succeded, false otherwise.\n\n vector scientistsToRemove = findScientistByName(name);\n\n if (scientistsToRemove.size() > 0)\n {\n for (size_t i = 0; i < scientistsToRemove.size(); i++)\n {\n Scientist toRemove = scientistsToRemove.at(i);\n\n _scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());\n }\n\n _data.saveScientists(_scientists);\n\n return true;\n }\n\n return false;\n}\nvoid ScientistService::removeAllScientists()\n{ \/\/ Removes ALL scientists from the list. Be careful with this.\n\n _scientists.clear();\n\n _data.saveScientists(_scientists);\n}\n\nvoid ScientistService::scientistSort(int sortType)\n{ \/\/ Sort by parameter: 1 = name(A-Z), 2 = name(Z-A), 3 = gender\n \/\/\t\t\t\t\t\t\t4 = birth, 5 = death, 6 = age.\n\n\n if (sortType == 1)\n {\n sort(_scientists.begin(), _scientists.end(), sortByNameAsc);\n }\n else if (sortType == 2)\n {\n sort(_scientists.begin(), _scientists.end(), sortByNameDesc);\n }\n else if (sortType == 3)\n {\n sort(_scientists.begin(), _scientists.end(), sortByGender);\n }\n else if (sortType == 4)\n {\n sort(_scientists.begin(), _scientists.end(), sortByBirth);\n }\n else if (sortType == 5)\n {\n sort(_scientists.begin(), _scientists.end(), sortByDeath);\n }\n else if (sortType == 6)\n {\n sort(_scientists.begin(), _scientists.end(), sortByAge);\n }\n\n _data.saveScientists(_scientists);\n}\nvoid ScientistService::scientistSortForFind(int sortType, vector& scientists)\n{ \/\/ Sort list by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender,\n \/\/ 4 = birth, 5 = death, 6 = age.\n \/\/ Sorts the list provided by the find function without saving to file,\n \/\/ so that the search result is displayed according to the search type.\n\n if (sortType == 1)\n {\n sort(scientists.begin(), scientists.end(), sortByNameAsc);\n }\n else if (sortType == 2)\n {\n sort(scientists.begin(), scientists.end(), sortByNameDesc);\n }\n else if (sortType == 3)\n {\n sort(scientists.begin(), scientists.end(), sortByGender);\n }\n else if (sortType == 4)\n {\n sort(scientists.begin(), scientists.end(), sortByBirth);\n }\n else if (sortType == 5)\n {\n sort(scientists.begin(), scientists.end(), sortByDeath);\n }\n else if (sortType == 6)\n {\n sort(scientists.begin(), scientists.end(), sortByAge);\n }\n}\n\nvector ScientistService::findScientistByName(string name) \/\/ Search vector by name\n{ \/\/ Returns all scientists whos name includes the string entered. Case insensitive.\n\n vector scientist;\n string databaseName;\n int pos = -1;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n databaseName = _scientists[i].getName();\n transform(databaseName.begin(), databaseName.end(), databaseName.begin(), ::tolower);\n transform(name.begin(), name.end(), name.begin(), ::tolower);\n\n pos = databaseName.find(name);\n\n if (pos > -1)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(1, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByGender(char gender) \/\/ Search vector by gender\n{ \/\/ Returns all scientists of that gender.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getGender() == gender)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByBirth(int birth) \/\/ Search vector by year of birth\n{ \/\/ Returns all scientists born that year.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getBirth() == birth)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByBirthRange(int birth1, int birth2) \/\/ Search vector by range of birth\n{ \/\/ Returns all scientists born in that year range.\n\n vector scientist;\n int temp;\n if(birth1 > birth2)\n {\n temp = birth1;\n birth1 = birth2;\n birth2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getBirth() >= birth1 && _scientists[i].getBirth() <= birth2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(4, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByDeath(int death) \/\/ Search vector by year of death\n{ \/\/ Returns all scientists that died that year, or death = 0 if still alive.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getDeath() == death)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByDeathRange(int death1, int death2) \/\/ Search vector by range of death\n{ \/\/ Returns all scientists who died in that year range.\n\n vector scientist;\n int temp;\n if(death1 > death2)\n {\n temp = death1;\n death1 = death2;\n death2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getDeath() >= death1 && _scientists[i].getDeath() <= death2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(5, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByAge(int age) \/\/ Search vector by age\n{ \/\/ Returns all scientists of that age.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getAge() == age)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByAgeRange(int age1, int age2) \/\/ Search vector by range of age\n{ \/\/ Returns all scientists in that age range.\n\n vector scientist;\n int temp;\n if(age1 > age2)\n {\n temp = age1;\n age1 = age2;\n age2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getAge() >= age1 && _scientists[i].getAge() <= age2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(6, scientist);\n\n return scientist;\n}\nadd sends a single scientist instead of vector#include \"scientistservice.h\"\n\n\nusing namespace std;\n\n\n\/\/operator overloading functions for scientistSort.\nbool sortByNameAsc (const Scientist &a, const Scientist &b)\n{ \/\/ also makes the sort case insensitive.\n string aName = a.getName(), bName = b.getName();\n transform(aName.begin(), aName.end(), aName.begin(), ::tolower);\n transform(bName.begin(), bName.end(), bName.begin(), ::tolower);\n return aName < bName;\n}\nbool sortByNameDesc(const Scientist &a, const Scientist &b)\n{ \/\/ also makes the sort case insensitive.\n string aName = a.getName(), bName = b.getName();\n transform(aName.begin(), aName.end(), aName.begin(), ::tolower);\n transform(bName.begin(), bName.end(), bName.begin(), ::tolower);\n return aName > bName;\n}\nbool sortByGender (const Scientist &a, const Scientist &b) { return a.getGender() < b.getGender(); }\nbool sortByBirth (const Scientist &a, const Scientist &b) { return a.getBirth() < b.getBirth(); }\nbool sortByDeath (const Scientist &a, const Scientist &b) { return a.getDeath() < b.getDeath(); }\nbool sortByAge (const Scientist &a, const Scientist &b) { return a.getAge() < b.getAge(); }\n\n\nScientistService::ScientistService()\n{\n\n}\n\nvector ScientistService::getScientists()\n{ \/\/ Uploads the list of scientists from file.\n\n _scientists = _data.loadScientists();\n\n return _scientists;\n}\n\nbool ScientistService::addScientist(string name, char gender, int birth, int death, int age)\n{ \/\/ Adds a scientist to the list and updates the file.\n \/\/ Returns true if adding succeded, false otherwise.\n\n Scientist scientist(name, gender, birth, death, age);\n\n if (findScientistByName(name).size() > 0)\n {\n return false;\n }\n\n else\n {\n _scientists.push_back(scientist);\n _data.saveScientists(scientist);\n return true;\n }\n}\nbool ScientistService::removeScientist(string name)\n{ \/\/ Removes a scientist with that name from the vector. Case insensitive.\n \/\/ Returns true if removing succeded, false otherwise.\n\n vector scientistsToRemove = findScientistByName(name);\n\n if (scientistsToRemove.size() > 0)\n {\n for (size_t i = 0; i < scientistsToRemove.size(); i++)\n {\n Scientist toRemove = scientistsToRemove.at(i);\n\n _scientists.erase(remove(_scientists.begin(), _scientists.end(), toRemove), _scientists.end());\n }\n\n _data.saveScientists(_scientists);\n\n return true;\n }\n\n return false;\n}\nvoid ScientistService::removeAllScientists()\n{ \/\/ Removes ALL scientists from the list. Be careful with this.\n\n _scientists.clear();\n\n _data.saveScientists(_scientists);\n}\n\nvoid ScientistService::scientistSort(int sortType)\n{ \/\/ Sort by parameter: 1 = name(A-Z), 2 = name(Z-A), 3 = gender\n \/\/\t\t\t\t\t\t\t4 = birth, 5 = death, 6 = age.\n\n\n if (sortType == 1)\n {\n sort(_scientists.begin(), _scientists.end(), sortByNameAsc);\n }\n else if (sortType == 2)\n {\n sort(_scientists.begin(), _scientists.end(), sortByNameDesc);\n }\n else if (sortType == 3)\n {\n sort(_scientists.begin(), _scientists.end(), sortByGender);\n }\n else if (sortType == 4)\n {\n sort(_scientists.begin(), _scientists.end(), sortByBirth);\n }\n else if (sortType == 5)\n {\n sort(_scientists.begin(), _scientists.end(), sortByDeath);\n }\n else if (sortType == 6)\n {\n sort(_scientists.begin(), _scientists.end(), sortByAge);\n }\n\n _data.saveScientists(_scientists);\n}\nvoid ScientistService::scientistSortForFind(int sortType, vector& scientists)\n{ \/\/ Sort list by sortType: 1 = name(A-Z), 2 = name(Z-A), 3 = gender,\n \/\/ 4 = birth, 5 = death, 6 = age.\n \/\/ Sorts the list provided by the find function without saving to file,\n \/\/ so that the search result is displayed according to the search type.\n\n if (sortType == 1)\n {\n sort(scientists.begin(), scientists.end(), sortByNameAsc);\n }\n else if (sortType == 2)\n {\n sort(scientists.begin(), scientists.end(), sortByNameDesc);\n }\n else if (sortType == 3)\n {\n sort(scientists.begin(), scientists.end(), sortByGender);\n }\n else if (sortType == 4)\n {\n sort(scientists.begin(), scientists.end(), sortByBirth);\n }\n else if (sortType == 5)\n {\n sort(scientists.begin(), scientists.end(), sortByDeath);\n }\n else if (sortType == 6)\n {\n sort(scientists.begin(), scientists.end(), sortByAge);\n }\n}\n\nvector ScientistService::findScientistByName(string name) \/\/ Search vector by name\n{ \/\/ Returns all scientists whos name includes the string entered. Case insensitive.\n\n vector scientist;\n string databaseName;\n int pos = -1;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n databaseName = _scientists[i].getName();\n transform(databaseName.begin(), databaseName.end(), databaseName.begin(), ::tolower);\n transform(name.begin(), name.end(), name.begin(), ::tolower);\n\n pos = databaseName.find(name);\n\n if (pos > -1)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(1, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByGender(char gender) \/\/ Search vector by gender\n{ \/\/ Returns all scientists of that gender.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getGender() == gender)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByBirth(int birth) \/\/ Search vector by year of birth\n{ \/\/ Returns all scientists born that year.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getBirth() == birth)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByBirthRange(int birth1, int birth2) \/\/ Search vector by range of birth\n{ \/\/ Returns all scientists born in that year range.\n\n vector scientist;\n int temp;\n if(birth1 > birth2)\n {\n temp = birth1;\n birth1 = birth2;\n birth2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getBirth() >= birth1 && _scientists[i].getBirth() <= birth2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(4, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByDeath(int death) \/\/ Search vector by year of death\n{ \/\/ Returns all scientists that died that year, or death = 0 if still alive.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getDeath() == death)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByDeathRange(int death1, int death2) \/\/ Search vector by range of death\n{ \/\/ Returns all scientists who died in that year range.\n\n vector scientist;\n int temp;\n if(death1 > death2)\n {\n temp = death1;\n death1 = death2;\n death2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getDeath() >= death1 && _scientists[i].getDeath() <= death2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(5, scientist);\n\n return scientist;\n}\nvector ScientistService::findScientistByAge(int age) \/\/ Search vector by age\n{ \/\/ Returns all scientists of that age.\n\n vector scientist;\n\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getAge() == age)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n return scientist;\n}\nvector ScientistService::findScientistByAgeRange(int age1, int age2) \/\/ Search vector by range of age\n{ \/\/ Returns all scientists in that age range.\n\n vector scientist;\n int temp;\n if(age1 > age2)\n {\n temp = age1;\n age1 = age2;\n age2 = temp;\n }\n for (size_t i = 0; i < _scientists.size(); i++)\n {\n if (_scientists[i].getAge() >= age1 && _scientists[i].getAge() <= age2)\n {\n scientist.push_back(_scientists[i]);\n }\n }\n\n scientistSortForFind(6, scientist);\n\n return scientist;\n}\n<|endoftext|>"} {"text":"#include \n#include \"constants.h\"\n#include \"fork_motor_controller.h\"\n\nnamespace hardware {\n\nconst uint16_t counts_per_revolution = 20000; \/\/ Teknic M-3441E-LN-20D\nconst uint8_t ccr_channel = 0; \/\/ PWM Channel 0\nconst float max_current = 6.0; \/\/ Copley Controls ACJ-055-18\nconst float torque_constant = 106.459f * constants::Nm_per_ozfin;\n\nForkMotorController::ForkMotorController()\n : MotorController(\"Fork\"),\n e_(STM32_TIM3, counts_per_revolution),\n m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,\n STM32_TIM1, ccr_channel, max_current, torque_constant)\n{\n instances[fork] = this;\n}\n\nForkMotorController::~ForkMotorController()\n{\n instances[fork] = 0;\n}\n \nvoid ForkMotorController::set_reference(float yaw_rate)\n{\n yaw_rate_command_ = yaw_rate;\n}\n\nvoid ForkMotorController::disable()\n{\n\n}\n\nvoid ForkMotorController::enable()\n{\n\n}\n\nvoid ForkMotorController::update(Sample & s)\n{\n s.encoder.steer = e_.get_angle();\n s.set_point.psi_dot = yaw_rate_command_;\n \/\/ TODO:\n \/\/ implement rate divider\n \/\/ determine motor current command, save it in s.motor_current\n}\n\n} \/\/ namespace hardware\nAdd steer motor state logging code.#include \n#include \"constants.h\"\n#include \"fork_motor_controller.h\"\n#include \"SystemState.h\"\n\nnamespace hardware {\n\nconst uint16_t counts_per_revolution = 20000; \/\/ Teknic M-3441E-LN-20D\nconst uint8_t ccr_channel = 0; \/\/ PWM Channel 0\nconst float max_current = 6.0; \/\/ Copley Controls ACJ-055-18\nconst float torque_constant = 106.459f * constants::Nm_per_ozfin;\n\nForkMotorController::ForkMotorController()\n : MotorController(\"Fork\"),\n e_(STM32_TIM3, counts_per_revolution),\n m_(GPIOF, GPIOF_STEER_DIR, GPIOF_STEER_ENABLE, GPIOF_STEER_FAULT,\n STM32_TIM1, ccr_channel, max_current, torque_constant)\n{\n instances[fork] = this;\n}\n\nForkMotorController::~ForkMotorController()\n{\n instances[fork] = 0;\n}\n \nvoid ForkMotorController::set_reference(float yaw_rate)\n{\n yaw_rate_command_ = yaw_rate;\n}\n\nvoid ForkMotorController::disable()\n{\n\n}\n\nvoid ForkMotorController::enable()\n{\n\n}\n\nvoid ForkMotorController::update(Sample & s)\n{\n s.encoder.steer = e_.get_angle();\n s.set_point.psi_dot = yaw_rate_command_;\n\n \/\/ TODO:\n \/\/ 1) get rear wheel rate from sample\n \/\/ 2) update state estimate\n \/\/ 3) update lqr output\n \/\/ 4) update PI output\n \/\/ 5) compute & set steer torque\n \n s.motor_current.steer = m_.get_current();\n\n if (e_.rotation_direction())\n s.system_state |= systemstate::SteerEncoderDir;\n if (m_.is_enabled())\n s.system_state |= systemstate::SteerMotorEnable;\n if (m_.has_fault())\n s.system_state |= systemstate::SteerMotorFault;\n if (m_.current_direction())\n s.system_state |= systemstate::SteerMotorCurrentDir;\n}\n\n} \/\/ namespace hardware\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n\nnamespace But\n{\nnamespace Threading\n{\n\n\/** @brief class for easy making your type lockable.\n *\n * \n * class MyCollection: BasicLocable\n * {\n * \/\/ ...\n * bool empty();\n * Element& top();\n * void pop();\n * \/\/ ...\n * };\n *\n * MyCollection mc;\n *\n * \/\/ ...\n *\n * {\n * \/\/ NOTE: this whole block is locked, so sequence of operations is secure!\n * const std::lock_guard lock{mc};\n * if( not mc.empty() )\n * {\n * process( mc.top() );\n * mc.pop();\n * }\n * }\n * <\/code>\n *\n * @note each method of your type, should first do 'assert( locked() )', before proceeding.\n * 'locked()' is only available in debug mode, but can save a lot of time when looking for sync issues.\n *\/\ntemplate\nclass BasicLockable\n{\npublic:\n void lock() const\n {\n m_.lock();\n assert( not locked(true) );\n }\n\n void unlock() const\n {\n assert( locked(false) );\n m_.unlock();\n }\n\nprotected:\n BasicLockable()\n {\n \/\/ test is here, as CRTP must be defined, before it can be used... :P\n static_assert( std::is_base_of::value, \"this class is meant to be derived from, to make it work\" );\n }\n\n ~BasicLockable() = default;\n\n#ifndef NDEBUG\n \/** @brief to be used in derived classes, for checks like 'assert( locked() )' in methods.\n * @note this is for debugging purposes in derived class only!\n * @warning this method is NOT thread-safe on its own!\n * @warning this method is available only in debug mode!\n *\/\n bool locked() const { return locked_; }\n#endif\n\nprivate:\n#ifndef NDEBUG\n bool locked(const bool newState) const\n {\n const auto prev = locked_;\n locked_ = newState;\n return prev;\n }\n\n mutable bool locked_{false};\n#endif\n\n mutable std::mutex m_;\n};\n\n}\n}\nrename CRTP -> Derived, as it is easier to understand#pragma once\n#include \n#include \n#include \n\nnamespace But\n{\nnamespace Threading\n{\n\n\/** @brief class for easy making your type lockable.\n *\n * \n * class MyCollection: BasicLocable\n * {\n * \/\/ ...\n * bool empty();\n * Element& top();\n * void pop();\n * \/\/ ...\n * };\n *\n * MyCollection mc;\n *\n * \/\/ ...\n *\n * {\n * \/\/ NOTE: this whole block is locked, so sequence of operations is secure!\n * const std::lock_guard lock{mc};\n * if( not mc.empty() )\n * {\n * process( mc.top() );\n * mc.pop();\n * }\n * }\n * <\/code>\n *\n * @note each method of your type, should first do 'assert( locked() )', before proceeding.\n * 'locked()' is only available in debug mode, but can save a lot of time when looking for sync issues.\n *\/\ntemplate\nclass BasicLockable\n{\npublic:\n void lock() const\n {\n m_.lock();\n assert( not locked(true) );\n }\n\n void unlock() const\n {\n assert( locked(false) );\n m_.unlock();\n }\n\nprotected:\n BasicLockable()\n {\n \/\/ test is here, as 'Derived' must be defined, before it can be used... :P\n static_assert( std::is_base_of::value, \"this class is meant to be derived from, to make it work\" );\n }\n\n ~BasicLockable() = default;\n\n#ifndef NDEBUG\n \/** @brief to be used in derived classes, for checks like 'assert( locked() )' in methods.\n * @note this is for debugging purposes in derived class only!\n * @warning this method is NOT thread-safe on its own!\n * @warning this method is available only in debug mode!\n *\/\n bool locked() const { return locked_; }\n#endif\n\nprivate:\n#ifndef NDEBUG\n bool locked(const bool newState) const\n {\n const auto prev = locked_;\n locked_ = newState;\n return prev;\n }\n\n mutable bool locked_{false};\n#endif\n\n mutable std::mutex m_;\n};\n\n}\n}\n<|endoftext|>"} {"text":"\/\/\/A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace seqan;\r\n\r\nint main(int argc, const char *argv[])\r\n{\r\n\ttypedef FragmentStore<> TFragStore;\r\n\ttypedef TFragStore::TContigPos TContigPos;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Define options\r\n\tCommandLineParser parser;\r\n\taddUsageLine(parser, \"sam2svg [OPTION]... \");\r\n\taddUsageLine(parser, \"sam2svg [OPTION]... \");\r\n\t\r\n\taddOption(parser, CommandLineOption(\"c\", \"contig\", \"display only contig #NUM (default: show all contigs)\", OptionType::Int | OptionType::Label | OptionType::List));\r\n\taddOption(parser, CommandLineOption(\"p\", \"pos\", 2, \"set begin and end position (default: show whole strands)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"l\", \"lines\", 2, \"set first and last line of the alignment (default: show whole alignment)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"a\", \"ascii\", \"output alignment in ASCII format instead of SVG\", OptionType::Bool | OptionType::Label));\r\n\trequiredArguments(parser, 2);\r\n\r\n\tif (argc == 1)\r\n\t{\r\n\t\tshortHelp(parser, std::cerr);\t\/\/ print short help and exit\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tbool stop = !parse(parser, argc, argv, std::cerr);\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Extract and check options\r\n\r\n\tif (isSetLong(parser, \"help\") || isSetLong(parser, \"version\")) return 0;\t\/\/ print help or version and exit\r\n\t\r\n\tString contigs;\r\n\tTContigPos left = 0;\r\n\tTContigPos right = SupremumValue::VALUE;\r\n\tunsigned firstLine = 0;\r\n\tunsigned lastLine = SupremumValue::VALUE;\r\n\tbool inASCII = false;\r\n\t\r\n\tif (isSetLong(parser, \"pos\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"pos\", 0, left);\r\n\t\tgetOptionValueLong(parser, \"pos\", 1, right);\r\n\t\tif ((left >= right) && (stop = true))\r\n\t\t\tstd::cerr << \"Begin position must be less than end position.\" << std::endl;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"lines\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"lines\", 0, firstLine);\r\n\t\tgetOptionValueLong(parser, \"lines\", 1, lastLine);\r\n\t\tif ((firstLine >= lastLine) && (stop = true))\r\n\t\t\tstd::cerr << \"First line must be less or equal than last line.\" << std::endl;\r\n\t}\r\n\r\n\tTFragStore store;\r\n\tstd::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);\r\n\tstd::ofstream ascii;\r\n\tSVGFile svg;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome file\r\n\tuint outArgNo = 1;\r\n\tif (argumentCount(parser) > 2)\r\n\t{\r\n\t\tif (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))\r\n\t\t\tstd::cerr << \"Failed to load genome.\" << std::endl;\r\n\t\t++outArgNo;\r\n\t}\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Load SAM file\r\n\tif (!stop) read(samFile, store, SAM());\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Choose contigs\r\n\tif (isSetLong(parser, \"contig\"))\r\n\t{\r\n\t\tresize(contigs, length(getOptionValuesLong(parser, \"contig\")));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tgetOptionValueLong(parser, \"contig\", i, contigs[i]);\r\n\t} else {\r\n\t\tresize(contigs, length(store.contigStore));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tcontigs[i] = i;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"ascii\"))\r\n\t\tinASCII = true;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome and open SVG file for writing\r\n\tif (!stop)\r\n\t{\r\n\t\t\r\n\t\tif (!stop)\r\n\t\t{\r\n\t\t\tif (inASCII)\r\n\t\t\t{\r\n\t\t\t\tascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);\r\n\t\t\t\tif (!ascii.is_open()) stop = true;\r\n\t\t\t} else\r\n\t\t\t\tif (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;\r\n\t\t\t\r\n\t\t\tif (stop) std::cerr << \"Failed to open output file for writing.\" << std::endl;\r\n\t\t}\r\n\t}\r\n\t\r\n\t\/\/ something went wrong\r\n\tif (stop)\r\n\t{\r\n\t\tstd::cerr << \"Exiting ...\" << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tfor(unsigned o=0;o::VALUE)\r\n\t\t\t{\r\n\t\t\t\tright_ = 0;\r\n\t\t\t\tfor (unsigned j = 0; j < length(layout.contigRows[i]); ++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned id = back(layout.contigRows[i][j]);\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].beginPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].beginPos;\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].endPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].endPos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstd::cout << left<<'\\t'<\/\/\/A simple SAM viewer. Convert a SAM alignment file into a SVG vector graphic.\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace seqan;\r\n\r\nint main(int argc, const char *argv[])\r\n{\r\n\ttypedef FragmentStore<> TFragStore;\r\n\ttypedef TFragStore::TContigPos TContigPos;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Define options\r\n\tCommandLineParser parser;\r\n\taddUsageLine(parser, \"sam2svg [OPTION]... \");\r\n\taddUsageLine(parser, \"sam2svg [OPTION]... \");\r\n\t\r\n\taddOption(parser, CommandLineOption(\"c\", \"contig\", \"display only contig #NUM (default: show all contigs)\", OptionType::Int | OptionType::Label | OptionType::List));\r\n\taddOption(parser, CommandLineOption(\"p\", \"pos\", 2, \"set begin and end position (default: show whole strands)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"l\", \"lines\", 2, \"set first and last line of the alignment (default: show whole alignment)\", OptionType::Int | OptionType::Label));\r\n\taddOption(parser, CommandLineOption(\"a\", \"ascii\", \"output alignment in ASCII format instead of SVG\", OptionType::Bool | OptionType::Label));\r\n\trequiredArguments(parser, 2);\r\n\r\n\tif (argc == 1)\r\n\t{\r\n\t\tshortHelp(parser, std::cerr);\t\/\/ print short help and exit\r\n\t\treturn 0;\r\n\t}\r\n\r\n\tbool stop = !parse(parser, argc, argv, std::cerr);\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Extract and check options\r\n\r\n\tif (isSetLong(parser, \"help\") || isSetLong(parser, \"version\")) return 0;\t\/\/ print help or version and exit\r\n\t\r\n\tString contigs;\r\n\tTContigPos left = 0;\r\n\tTContigPos right = SupremumValue::VALUE;\r\n\tunsigned firstLine = 0;\r\n\tunsigned lastLine = SupremumValue::VALUE;\r\n\tbool inASCII = false;\r\n\t\r\n\tif (isSetLong(parser, \"pos\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"pos\", 0, left);\r\n\t\tgetOptionValueLong(parser, \"pos\", 1, right);\r\n\t\tif ((left >= right) && (stop = true))\r\n\t\t\tstd::cerr << \"Begin position must be less than end position.\" << std::endl;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"lines\"))\r\n\t{\r\n\t\tgetOptionValueLong(parser, \"lines\", 0, firstLine);\r\n\t\tgetOptionValueLong(parser, \"lines\", 1, lastLine);\r\n\t\tif ((firstLine >= lastLine) && (stop = true))\r\n\t\t\tstd::cerr << \"First line must be less or equal than last line.\" << std::endl;\r\n\t}\r\n\r\n\tTFragStore store;\r\n\tstd::ifstream samFile(toCString(getArgumentValue(parser, 0)), std::ios_base::in | std::ios_base::binary);\r\n\tstd::ofstream ascii;\r\n\tSVGFile svg;\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome file\r\n\tuint outArgNo = 1;\r\n\tif (argumentCount(parser) > 2)\r\n\t{\r\n\t\tif (!loadContigs(store, getArgumentValue(parser, 1)) && (stop = true))\r\n\t\t\tstd::cerr << \"Failed to load genome.\" << std::endl;\r\n\t\t++outArgNo;\r\n\t}\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Load SAM file\r\n\tif (!stop) read(samFile, store, SAM());\r\n\t\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Choose contigs\r\n\tif (isSetLong(parser, \"contig\"))\r\n\t{\r\n\t\tresize(contigs, length(getOptionValuesLong(parser, \"contig\")));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tgetOptionValueLong(parser, \"contig\", i, contigs[i]);\r\n\t} else {\r\n\t\tresize(contigs, length(store.contigStore));\r\n\t\tfor (unsigned i = 0; i < length(contigs); ++i)\r\n\t\t\tcontigs[i] = i;\r\n\t}\r\n\r\n\tif (isSetLong(parser, \"ascii\"))\r\n\t\tinASCII = true;\r\n\r\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\/\/ Optionally load genome and open SVG file for writing\r\n\tif (!stop)\r\n\t{\r\n\t\tif (inASCII)\r\n\t\t{\r\n\t\t\tascii.open(toCString(getArgumentValue(parser, outArgNo)), std::ios_base::out | std::ios_base::trunc);\r\n\t\t\tif (!ascii.is_open()) stop = true;\r\n\t\t} else\r\n\t\t\tif (!open(svg, toCString(getArgumentValue(parser, outArgNo)))) stop = true;\r\n\t\t\r\n\t\tif (stop) std::cerr << \"Failed to open output file for writing.\" << std::endl;\r\n\t}\r\n\t\r\n\t\/\/ something went wrong\r\n\tif (stop)\r\n\t{\r\n\t\tstd::cerr << \"Exiting ...\" << std::endl;\r\n\t\treturn 1;\r\n\t}\r\n\t\r\n\tfor(unsigned o=0;o::VALUE)\r\n\t\t\t{\r\n\t\t\t\tright_ = 0;\r\n\t\t\t\tfor (unsigned j = 0; j < length(layout.contigRows[i]); ++j)\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned id = back(layout.contigRows[i][j]);\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].beginPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].beginPos;\r\n\t\t\t\t\tif (right_ < store.alignedReadStore[id].endPos)\r\n\t\t\t\t\t\tright_ = store.alignedReadStore[id].endPos;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tstd::cout << left<<'\\t'<"} {"text":"Started maths::Matrix testing<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ This code exists to generate minidump files for testing.\n\n#include \n\n#include \n\n#include \"breakpad\/src\/client\/linux\/handler\/exception_handler.h\"\n#include \"breakpad\/src\/common\/linux\/linux_libc_support.h\"\n#include \"breakpad\/src\/third_party\/lss\/linux_syscall_support.h\"\n\nstatic bool DumpCallback(const char* dump_path, const char* minidump_id,\n void* context, bool success) {\n if (!success) {\n static const char msg[] = \"Failed to write minidump\\n\";\n sys_write(2, msg, sizeof(msg) - 1);\n return false;\n }\n\n static const char msg[] = \"Wrote minidump: \";\n sys_write(2, msg, sizeof(msg) - 1);\n sys_write(2, dump_path, my_strlen(dump_path));\n sys_write(2, \"\/\", 1);\n sys_write(2, minidump_id, my_strlen(minidump_id));\n sys_write(2, \".dmp\\n\", 5);\n\n return true;\n}\n\nstatic void DoSomethingWhichCrashes() {\n int local_var = 1;\n *reinterpret_cast(NULL) = 1;\n}\n\nint main() {\n google_breakpad::ExceptionHandler breakpad(\".\", NULL, DumpCallback, NULL,\n true);\n DoSomethingWhichCrashes();\n return 0;\n}\nLinux: Fix linux_syscall_support #include path for generate-test-dump.cc.\/\/ Copyright (c) 2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ This code exists to generate minidump files for testing.\n\n#include \n\n#include \n\n#include \"breakpad\/src\/client\/linux\/handler\/exception_handler.h\"\n#include \"breakpad\/src\/common\/linux\/linux_libc_support.h\"\n#include \"third_party\/lss\/linux_syscall_support.h\"\n\nstatic bool DumpCallback(const char* dump_path, const char* minidump_id,\n void* context, bool success) {\n if (!success) {\n static const char msg[] = \"Failed to write minidump\\n\";\n sys_write(2, msg, sizeof(msg) - 1);\n return false;\n }\n\n static const char msg[] = \"Wrote minidump: \";\n sys_write(2, msg, sizeof(msg) - 1);\n sys_write(2, dump_path, my_strlen(dump_path));\n sys_write(2, \"\/\", 1);\n sys_write(2, minidump_id, my_strlen(minidump_id));\n sys_write(2, \".dmp\\n\", 5);\n\n return true;\n}\n\nstatic void DoSomethingWhichCrashes() {\n int local_var = 1;\n *reinterpret_cast(NULL) = 1;\n}\n\nint main() {\n google_breakpad::ExceptionHandler breakpad(\".\", NULL, DumpCallback, NULL,\n true);\n DoSomethingWhichCrashes();\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#define FML_USED_ON_EMBEDDER\n\n#include \"flutter\/shell\/platform\/android\/android_shell_holder.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/shell\/common\/rasterizer.h\"\n#include \"flutter\/shell\/platform\/android\/platform_view_android.h\"\n#include \"lib\/fxl\/functional\/make_copyable.h\"\n\nnamespace shell {\n\nAndroidShellHolder::AndroidShellHolder(\n blink::Settings settings,\n fml::jni::JavaObjectWeakGlobalRef java_object)\n : settings_(std::move(settings)), java_object_(java_object) {\n static size_t shell_count = 1;\n auto thread_label = std::to_string(shell_count++);\n\n FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==\n 0);\n\n thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |\n ThreadHost::Type::IO};\n\n \/\/ Detach from JNI when the UI thread exits.\n thread_host_.ui_thread->GetTaskRunner()->PostTask(\n [key = thread_destruct_key_]() {\n FXL_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0);\n });\n\n fml::WeakPtr weak_platform_view;\n Shell::CreateCallback on_create_platform_view =\n [java_object, &weak_platform_view](Shell& shell) {\n auto platform_view_android = std::make_unique(\n shell, \/\/ delegate\n shell.GetTaskRunners(), \/\/ task runners\n java_object, \/\/ java object handle for JNI interop\n shell.GetSettings()\n .enable_software_rendering \/\/ use software rendering\n );\n weak_platform_view = platform_view_android->GetWeakPtr();\n return platform_view_android;\n };\n\n Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {\n return std::make_unique(shell.GetTaskRunners());\n };\n\n \/\/ The current thread will be used as the platform thread. Ensure that the\n \/\/ message loop is initialized.\n fml::MessageLoop::EnsureInitializedForCurrentThread();\n\n blink::TaskRunners task_runners(\n thread_label, \/\/ label\n fml::MessageLoop::GetCurrent().GetTaskRunner(), \/\/ platform\n thread_host_.gpu_thread->GetTaskRunner(), \/\/ gpu\n thread_host_.ui_thread->GetTaskRunner(), \/\/ ui\n thread_host_.io_thread->GetTaskRunner() \/\/ io\n );\n\n shell_ =\n Shell::Create(task_runners, \/\/ task runners\n settings_, \/\/ settings\n on_create_platform_view, \/\/ platform view create callback\n on_create_rasterizer \/\/ rasterizer create callback\n );\n\n platform_view_ = weak_platform_view;\n FXL_DCHECK(platform_view_);\n\n is_valid_ = shell_ != nullptr;\n\n if (is_valid_) {\n task_runners.GetGPUTaskRunner()->PostTask(\n []() {\n \/\/ Android describes -8 as \"most important display threads, for\n \/\/ compositing the screen and retrieving input events\". Conservatively\n \/\/ set the GPU thread to slightly lower priority than it.\n if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {\n \/\/ Defensive fallback. Depending on the OEM, it may not be possible\n \/\/ to set priority to -5.\n if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {\n FXL_LOG(ERROR) << \"Failed to set GPU task runner priority\";\n }\n }\n });\n task_runners.GetUITaskRunner()->PostTask(\n []() {\n if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {\n FXL_LOG(ERROR) << \"Failed to set UI task runner priority\";\n }\n });\n }\n}\n\nAndroidShellHolder::~AndroidShellHolder() {\n shell_.reset();\n thread_host_.Reset();\n FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0);\n}\n\nvoid AndroidShellHolder::ThreadDestructCallback(void* value) {\n fml::jni::DetachFromVM();\n}\n\nbool AndroidShellHolder::IsValid() const {\n return is_valid_;\n}\n\nconst blink::Settings& AndroidShellHolder::GetSettings() const {\n return settings_;\n}\n\nvoid AndroidShellHolder::Launch(RunConfiguration config) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n fxl::MakeCopyable([engine = shell_->GetEngine(), \/\/\n config = std::move(config) \/\/\n ]() mutable {\n if (engine) {\n if (!engine->Run(std::move(config))) {\n FXL_LOG(ERROR) << \"Could not launch engine in configuration.\";\n }\n }\n }));\n}\n\nvoid AndroidShellHolder::SetViewportMetrics(\n const blink::ViewportMetrics& metrics) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n [engine = shell_->GetEngine(), metrics]() {\n if (engine) {\n engine->SetViewportMetrics(metrics);\n }\n });\n}\n\nvoid AndroidShellHolder::DispatchPointerDataPacket(\n std::unique_ptr packet) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(fxl::MakeCopyable(\n [engine = shell_->GetEngine(), packet = std::move(packet)] {\n if (engine) {\n engine->DispatchPointerDataPacket(*packet);\n }\n }));\n}\n\nRasterizer::Screenshot AndroidShellHolder::Screenshot(\n Rasterizer::ScreenshotType type,\n bool base64_encode) {\n if (!IsValid()) {\n return {nullptr, SkISize::MakeEmpty()};\n }\n return shell_->Screenshot(type, base64_encode);\n}\n\nfml::WeakPtr AndroidShellHolder::GetPlatformView() {\n FXL_DCHECK(platform_view_);\n return platform_view_;\n}\n\nvoid AndroidShellHolder::UpdateAssetManager(\n fxl::RefPtr asset_manager) {\n if (!IsValid() || !asset_manager) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n [engine = shell_->GetEngine(),\n asset_manager = std::move(asset_manager)]() {\n if (engine) {\n if (!engine->UpdateAssetManager(std::move(asset_manager))) {\n FXL_DLOG(ERROR) << \"Could not update asset asset manager.\";\n }\n }\n });\n}\n\n} \/\/ namespace shell\nDetach from JNI before exiting the GPU thread. (#5231)\/\/ Copyright 2018 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#define FML_USED_ON_EMBEDDER\n\n#include \"flutter\/shell\/platform\/android\/android_shell_holder.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"flutter\/fml\/message_loop.h\"\n#include \"flutter\/shell\/common\/rasterizer.h\"\n#include \"flutter\/shell\/platform\/android\/platform_view_android.h\"\n#include \"lib\/fxl\/functional\/make_copyable.h\"\n\nnamespace shell {\n\nAndroidShellHolder::AndroidShellHolder(\n blink::Settings settings,\n fml::jni::JavaObjectWeakGlobalRef java_object)\n : settings_(std::move(settings)), java_object_(java_object) {\n static size_t shell_count = 1;\n auto thread_label = std::to_string(shell_count++);\n\n FXL_CHECK(pthread_key_create(&thread_destruct_key_, ThreadDestructCallback) ==\n 0);\n\n thread_host_ = {thread_label, ThreadHost::Type::UI | ThreadHost::Type::GPU |\n ThreadHost::Type::IO};\n\n \/\/ Detach from JNI when the UI and GPU threads exit.\n auto jni_exit_task([key = thread_destruct_key_]() {\n FXL_CHECK(pthread_setspecific(key, reinterpret_cast(1)) == 0);\n });\n thread_host_.ui_thread->GetTaskRunner()->PostTask(jni_exit_task);\n thread_host_.gpu_thread->GetTaskRunner()->PostTask(jni_exit_task);\n\n fml::WeakPtr weak_platform_view;\n Shell::CreateCallback on_create_platform_view =\n [java_object, &weak_platform_view](Shell& shell) {\n auto platform_view_android = std::make_unique(\n shell, \/\/ delegate\n shell.GetTaskRunners(), \/\/ task runners\n java_object, \/\/ java object handle for JNI interop\n shell.GetSettings()\n .enable_software_rendering \/\/ use software rendering\n );\n weak_platform_view = platform_view_android->GetWeakPtr();\n return platform_view_android;\n };\n\n Shell::CreateCallback on_create_rasterizer = [](Shell& shell) {\n return std::make_unique(shell.GetTaskRunners());\n };\n\n \/\/ The current thread will be used as the platform thread. Ensure that the\n \/\/ message loop is initialized.\n fml::MessageLoop::EnsureInitializedForCurrentThread();\n\n blink::TaskRunners task_runners(\n thread_label, \/\/ label\n fml::MessageLoop::GetCurrent().GetTaskRunner(), \/\/ platform\n thread_host_.gpu_thread->GetTaskRunner(), \/\/ gpu\n thread_host_.ui_thread->GetTaskRunner(), \/\/ ui\n thread_host_.io_thread->GetTaskRunner() \/\/ io\n );\n\n shell_ =\n Shell::Create(task_runners, \/\/ task runners\n settings_, \/\/ settings\n on_create_platform_view, \/\/ platform view create callback\n on_create_rasterizer \/\/ rasterizer create callback\n );\n\n platform_view_ = weak_platform_view;\n FXL_DCHECK(platform_view_);\n\n is_valid_ = shell_ != nullptr;\n\n if (is_valid_) {\n task_runners.GetGPUTaskRunner()->PostTask(\n []() {\n \/\/ Android describes -8 as \"most important display threads, for\n \/\/ compositing the screen and retrieving input events\". Conservatively\n \/\/ set the GPU thread to slightly lower priority than it.\n if (::setpriority(PRIO_PROCESS, gettid(), -5) != 0) {\n \/\/ Defensive fallback. Depending on the OEM, it may not be possible\n \/\/ to set priority to -5.\n if (::setpriority(PRIO_PROCESS, gettid(), -2) != 0) {\n FXL_LOG(ERROR) << \"Failed to set GPU task runner priority\";\n }\n }\n });\n task_runners.GetUITaskRunner()->PostTask(\n []() {\n if (::setpriority(PRIO_PROCESS, gettid(), -1) != 0) {\n FXL_LOG(ERROR) << \"Failed to set UI task runner priority\";\n }\n });\n }\n}\n\nAndroidShellHolder::~AndroidShellHolder() {\n shell_.reset();\n thread_host_.Reset();\n FXL_CHECK(pthread_key_delete(thread_destruct_key_) == 0);\n}\n\nvoid AndroidShellHolder::ThreadDestructCallback(void* value) {\n fml::jni::DetachFromVM();\n}\n\nbool AndroidShellHolder::IsValid() const {\n return is_valid_;\n}\n\nconst blink::Settings& AndroidShellHolder::GetSettings() const {\n return settings_;\n}\n\nvoid AndroidShellHolder::Launch(RunConfiguration config) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n fxl::MakeCopyable([engine = shell_->GetEngine(), \/\/\n config = std::move(config) \/\/\n ]() mutable {\n if (engine) {\n if (!engine->Run(std::move(config))) {\n FXL_LOG(ERROR) << \"Could not launch engine in configuration.\";\n }\n }\n }));\n}\n\nvoid AndroidShellHolder::SetViewportMetrics(\n const blink::ViewportMetrics& metrics) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n [engine = shell_->GetEngine(), metrics]() {\n if (engine) {\n engine->SetViewportMetrics(metrics);\n }\n });\n}\n\nvoid AndroidShellHolder::DispatchPointerDataPacket(\n std::unique_ptr packet) {\n if (!IsValid()) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(fxl::MakeCopyable(\n [engine = shell_->GetEngine(), packet = std::move(packet)] {\n if (engine) {\n engine->DispatchPointerDataPacket(*packet);\n }\n }));\n}\n\nRasterizer::Screenshot AndroidShellHolder::Screenshot(\n Rasterizer::ScreenshotType type,\n bool base64_encode) {\n if (!IsValid()) {\n return {nullptr, SkISize::MakeEmpty()};\n }\n return shell_->Screenshot(type, base64_encode);\n}\n\nfml::WeakPtr AndroidShellHolder::GetPlatformView() {\n FXL_DCHECK(platform_view_);\n return platform_view_;\n}\n\nvoid AndroidShellHolder::UpdateAssetManager(\n fxl::RefPtr asset_manager) {\n if (!IsValid() || !asset_manager) {\n return;\n }\n\n shell_->GetTaskRunners().GetUITaskRunner()->PostTask(\n [engine = shell_->GetEngine(),\n asset_manager = std::move(asset_manager)]() {\n if (engine) {\n if (!engine->UpdateAssetManager(std::move(asset_manager))) {\n FXL_DLOG(ERROR) << \"Could not update asset asset manager.\";\n }\n }\n });\n}\n\n} \/\/ namespace shell\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2004-08-24 07:20:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sdrmediawindow.hxx\"\n\nnamespace sdr { namespace contact {\n\n\/\/ ----------------------------------\n\/\/ - ViewObjectContactOfSdrMediaObj -\n\/\/ ----------------------------------\n\nViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,\n ViewContact& rViewContact,\n const ::avmedia::MediaItem& rMediaItem ) :\n ViewObjectContact( rObjectContact, rViewContact ),\n mpMediaWindow( NULL )\n{\n Window* pWindow = getWindow();\n\n if( pWindow )\n {\n mpMediaWindow = new SdrMediaWindow( pWindow, *this );\n executeMediaItem( rMediaItem );\n mpMediaWindow->show();\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj()\n{\n DBG_ASSERT( !mpMediaWindow, \"ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL\" );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::PrepareDelete()\n{\n ViewObjectContact::PrepareDelete();\n delete mpMediaWindow;\n mpMediaWindow = NULL;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo)\n{\n SdrObject* pObj = GetViewContact().TryToGetSdrObject();\n\n ViewObjectContact::PaintObject( rDisplayInfo );\n\n if( pObj )\n {\n Rectangle aPaintRect( pObj->GetCurrentBoundRect() );\n OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();\n sal_Int32 nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() );\n bool bWasPainted = false;\n\n aPaintRect.Left() += nOffset;\n aPaintRect.Top() += nOffset;\n aPaintRect.Right() -= nOffset;\n aPaintRect.Bottom() -= nOffset;\n\n if( !mpMediaWindow )\n {\n OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();\n\n if( pOutDev &&\n ( aPaintRect.Left() < aPaintRect.Right() &&\n aPaintRect.Top() < aPaintRect.Bottom() ) )\n {\n pOutDev->SetLineColor( COL_BLACK );\n pOutDev->SetFillColor( COL_BLACK );\n pOutDev->DrawRect( aPaintRect );\n bWasPainted = true;\n }\n }\n else\n {\n Rectangle aCurPaintRect( pOutDev->LogicToPixel( aPaintRect.TopLeft() ),\n pOutDev->LogicToPixel( aPaintRect.GetSize() ) );\n const bool bNewPaintRect = ( maLastPaintRect.IsEmpty() || ( maLastPaintRect != aCurPaintRect ) );\n\n if( bNewPaintRect )\n {\n mpMediaWindow->setPosSize( aCurPaintRect );\n maLastPaintRect = aCurPaintRect;\n }\n else\n {\n Window* pWindow = mpMediaWindow->getWindow();\n\n if( pWindow )\n {\n pWindow->Invalidate();\n pWindow->Update();\n }\n }\n\n bWasPainted = true;\n }\n\n if( bWasPainted )\n {\n mbIsPainted = sal_True;\n mbIsInvalidated = sal_False;\n maPaintedRectangle = pObj->GetCurrentBoundRect();\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nWindow* ViewObjectContactOfSdrMediaObj::getWindow() const\n{\n OutputDevice& rOutDev = static_cast< ObjectContactOfPageView& >( GetObjectContact() ).GetPageViewWindow().GetOutputDevice();\n\n return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nbool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const\n{\n return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSize ViewObjectContactOfSdrMediaObj::getPreferredSize() const\n{\n Size aRet;\n\n if( mpMediaWindow )\n aRet = mpMediaWindow->getPreferredSize();\n\n return aRet;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const\n{\n if( mpMediaWindow )\n mpMediaWindow->updateMediaItem( rItem );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )\n{\n if( mpMediaWindow )\n {\n ::avmedia::MediaItem aUpdatedItem;\n\n mpMediaWindow->executeMediaItem( rItem );\n\n \/\/ query new properties after trying to set the new properties\n updateMediaItem( aUpdatedItem );\n static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem );\n }\n}\n\n} }\nINTEGRATION: CWS jmf3 (1.3.68); FILE MERGED 2004\/10\/04 10:33:12 ka 1.3.68.1: watch for correct cast\/*************************************************************************\n *\n * $RCSfile: viewobjectcontactofsdrmediaobj.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-11-03 16:03:37 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sdrmediawindow.hxx\"\n\nnamespace sdr { namespace contact {\n\n\/\/ ----------------------------------\n\/\/ - ViewObjectContactOfSdrMediaObj -\n\/\/ ----------------------------------\n\nViewObjectContactOfSdrMediaObj::ViewObjectContactOfSdrMediaObj( ObjectContact& rObjectContact,\n ViewContact& rViewContact,\n const ::avmedia::MediaItem& rMediaItem ) :\n ViewObjectContact( rObjectContact, rViewContact ),\n mpMediaWindow( NULL )\n{\n Window* pWindow = getWindow();\n\n if( pWindow )\n {\n mpMediaWindow = new SdrMediaWindow( pWindow, *this );\n executeMediaItem( rMediaItem );\n mpMediaWindow->show();\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj()\n{\n DBG_ASSERT( !mpMediaWindow, \"ViewObjectContactOfSdrMediaObj::~ViewObjectContactOfSdrMediaObj(): mpMediaWindow != NULL\" );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::PrepareDelete()\n{\n ViewObjectContact::PrepareDelete();\n delete mpMediaWindow;\n mpMediaWindow = NULL;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::PaintObject(DisplayInfo& rDisplayInfo)\n{\n SdrObject* pObj = GetViewContact().TryToGetSdrObject();\n\n ViewObjectContact::PaintObject( rDisplayInfo );\n\n if( pObj )\n {\n Rectangle aPaintRect( pObj->GetCurrentBoundRect() );\n OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();\n sal_Int32 nOffset( pOutDev->PixelToLogic( Size( 4, 4 ) ).Width() );\n bool bWasPainted = false;\n\n aPaintRect.Left() += nOffset;\n aPaintRect.Top() += nOffset;\n aPaintRect.Right() -= nOffset;\n aPaintRect.Bottom() -= nOffset;\n\n if( !mpMediaWindow )\n {\n OutputDevice* pOutDev = rDisplayInfo.GetOutputDevice();\n\n if( pOutDev &&\n ( aPaintRect.Left() < aPaintRect.Right() &&\n aPaintRect.Top() < aPaintRect.Bottom() ) )\n {\n pOutDev->SetLineColor( COL_BLACK );\n pOutDev->SetFillColor( COL_BLACK );\n pOutDev->DrawRect( aPaintRect );\n bWasPainted = true;\n }\n }\n else\n {\n Rectangle aCurPaintRect( pOutDev->LogicToPixel( aPaintRect.TopLeft() ),\n pOutDev->LogicToPixel( aPaintRect.GetSize() ) );\n const bool bNewPaintRect = ( maLastPaintRect.IsEmpty() || ( maLastPaintRect != aCurPaintRect ) );\n\n if( bNewPaintRect )\n {\n mpMediaWindow->setPosSize( aCurPaintRect );\n maLastPaintRect = aCurPaintRect;\n }\n else\n {\n Window* pWindow = mpMediaWindow->getWindow();\n\n if( pWindow )\n {\n pWindow->Invalidate();\n pWindow->Update();\n }\n }\n\n bWasPainted = true;\n }\n\n if( bWasPainted )\n {\n mbIsPainted = sal_True;\n mbIsInvalidated = sal_False;\n maPaintedRectangle = pObj->GetCurrentBoundRect();\n }\n }\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nWindow* ViewObjectContactOfSdrMediaObj::getWindow() const\n{\n ObjectContactOfPageView* pOC = dynamic_cast< ObjectContactOfPageView* >( &GetObjectContact() );\n\n if( pOC)\n {\n OutputDevice& rOutDev = pOC->GetPageViewWindow().GetOutputDevice();\n return( ( rOutDev.GetOutDevType() == OUTDEV_WINDOW ) ? static_cast< Window* >( &rOutDev ) : NULL );\n }\n\n return NULL;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nbool ViewObjectContactOfSdrMediaObj::hasPreferredSize() const\n{\n return( mpMediaWindow != NULL && mpMediaWindow->hasPreferredSize() );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nSize ViewObjectContactOfSdrMediaObj::getPreferredSize() const\n{\n Size aRet;\n\n if( mpMediaWindow )\n aRet = mpMediaWindow->getPreferredSize();\n\n return aRet;\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::updateMediaItem( ::avmedia::MediaItem& rItem ) const\n{\n if( mpMediaWindow )\n mpMediaWindow->updateMediaItem( rItem );\n}\n\n\/\/ ------------------------------------------------------------------------------\n\nvoid ViewObjectContactOfSdrMediaObj::executeMediaItem( const ::avmedia::MediaItem& rItem )\n{\n if( mpMediaWindow )\n {\n ::avmedia::MediaItem aUpdatedItem;\n\n mpMediaWindow->executeMediaItem( rItem );\n\n \/\/ query new properties after trying to set the new properties\n updateMediaItem( aUpdatedItem );\n static_cast< ViewContactOfSdrMediaObj& >( GetViewContact() ).mediaPropertiesChanged( aUpdatedItem );\n }\n}\n\n} }\n<|endoftext|>"} {"text":"\/***************************************************************************\n * The Kernel-Machine Library *\n * Copyright (C) 2004, 2005 by Rutger W. ter Borg *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *\n ***************************************************************************\/\n\n\n#ifndef KRLS_HPP\n#define KRLS_HPP\n\n\/\/ #include \n\/\/ #include \"kernels.h\"\n\n\/\/ #include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace atlas = boost::numeric::bindings::atlas;\n\n\nnamespace kml {\n\n\n\/*!\n\\brief Kernel Recursive Least Squares\n \nA preprocessing step is taken to absorb the bias term into the weight vector w, by\nredefining w as (w^T, b)^T and \\f$\\phi\\f$ as (phi^T,1)^T. For details, see Engel et al,\nSparse Online Greedy Support Vector Regression, below on page 3:\n\\f$k(x,x')=k(x,x') + \\lambda^2\\f$, where \\f$\\lambda\\f$ is a small, positive constant.\n\n\\section bibliography References\n-# Engel et al., 2003. Kernel Recursive Least Squares. \n*\/\n\n\ntemplate< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>\nclass krls: public kernel_machine< Problem, Kernel, PropertyMap > {};\n\n\n\ntemplate< typename Problem, typename Kernel, typename PropertyMap >\nclass krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression >::type>:\n public kernel_machine< Problem, Kernel, PropertyMap > {\n\n\ttypedef kernel_machine< Problem, Kernel, PropertyMap > base_type;\n typedef typename base_type::kernel_type kernel_type;\n typedef double scalar_type;\n\n typedef symmetric_view< ublas::matrix > symmetric_type;\n \n typedef ublas::matrix matrix_type;\n typedef ublas::vector vector_type;\n\n typedef typename Problem::input_type input_type;\n typedef typename Problem::output_type output_type;\n\n\ttypedef typename boost::property_traits::key_type key_type;\n\ttypedef typename boost::property_traits::value_type object_type;\n\npublic:\n krls( scalar_type n, scalar_type l, \n \t\ttypename boost::call_traits::param_type k, \n \ttypename boost::call_traits::param_type map ):\n base_type(k,map), nu(n), lambda_squared(l*l) {}\n \n template< typename TokenIterator >\n krls( TokenIterator const begin, TokenIterator const end, \n typename boost::call_traits::param_type k,\n typename boost::call_traits::param_type map ):\n\t\tbase_type(k,map) {\n\t\tnu = 1e-1;\t\t\t\t\t\t\/\/ default value\n\t\tscalar_type lambda=1e-3;\t\t\/\/ default value\n\t\tTokenIterator token(begin);\n\t\tif ( token != end ) {\n\t\t\tnu = boost::lexical_cast( *token++ );\n\t\t\tif ( token != end ) lambda = boost::lexical_cast( *token );\n\t\t}\n\t\tlambda_squared=lambda*lambda;\n\t}\n \n\n output_type operator()( input_type const &x ) {\n \n\t\tvector_type temp_K( base_type::key_lookup.size() );\n\t\tbase_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );\n\t\tfor( int i=0; i < temp_K.size(); ++i )\n temp_K[i] += lambda_squared;\n return atlas::dot( base_type::weight, temp_K );\n\n }\n \n\n \/*! learn the entire range of keys indicated by this range *\/\n template\n void learn( KeyIterator begin, KeyIterator end ) {\n\t\tKeyIterator key_iterator(begin);\n\t\twhile( key_iterator != end ) {\n\t\t\tincrement( *key_iterator );\n\t\t\t++key_iterator;\n\t\t}\n }\n \n \n \/*! \\param key key of example in data *\/\n void increment( key_type const &key ) {\n\t \n\t \/\/std::cout << \"running key \" << key << \" through KRLS... \" << std::endl;\n \n\t\t\/\/ calculate the base_type::kernel function on (x_t,x_t), needed later on\n scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;\n\n \/\/ check whether dictionary is still not initialised\n if ( base_type::key_lookup.empty() ) {\n\n\t \t\/\/ there is no dictionary yet, so initialise all variables\n \/\/ resize the matrix K, its inverse R and matrix P to 1 x 1\n K.grow_row_column();\n R.grow_row_column();\n P.grow_row_column();\n\n \/\/ and use values as stated in the paper\n K.matrix(0,0) = k_tt;\n R.matrix(0,0) = 1.0 \/ k_tt;\n P.matrix(0,0) = 1.0;\n\n \/\/ add to weight vector\n\t\t base_type::weight.push_back( (*base_type::data)[key].second \/ k_tt );\n\n \/\/ add to support vector set\n base_type::key_lookup.push_back( key );\n\n } else {\n\n \/\/ KRLS already initialised, continue\n vector_type a_t( K.size1() );\n vector_type k_t( K.size1() );\n\n\t\t \/\/ fill vector k_t\n\t\t base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );\n\t\t for( int i=0; i > R_range( R.view() );\n ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix > > R_view( R_range );\n atlas::symv( R_view, k_t, a_t );\n scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );\n\n \/\/ Perform Approximate Linear Dependency (ALD) test\n if (delta_t > nu) {\n\t \n \/\/ add x_t to support vector set, adjust all needed variables\n unsigned int old_size = base_type::key_lookup.size();\n unsigned int new_size = old_size + 1;\n \n\t\t\t\t\/\/ update K (equation 14)\n \/\/ fetch a view into the last row of the matrix of the _old_ size\n\t\t\t\tK.grow_row_column();\n \t\t\t ublas::matrix_vector_slice< ublas::matrix > K_row_part( K.shrinked_row(old_size) );\n \t\t\t atlas::copy( k_t, K_row_part );\n K.matrix( old_size, old_size ) = k_tt;\n\t\t\t\t\n \/\/ update R (equation 14)\n scalar_type factor = static_cast(1) \/ delta_t;\n atlas::syr( factor, a_t, R_view );\n R.grow_row_column();\n\t\t\t ublas::matrix_vector_slice< ublas::matrix > R_row_part( R.shrinked_row(old_size) );\n atlas::scal( -factor, a_t );\n R_row_part.assign( a_t );\n R.matrix( old_size, old_size ) = factor;\n \n \/\/ update P (equation 15)\n \/\/ assign unit vector with 1 on last element.\n P.grow_row_column();\n\t\t\t\tublas::matrix_vector_slice< ublas::matrix > P_row_part( P.shrinked_row(old_size) ); \n\t\t\t\tatlas::set( 0.0, P_row_part );\n\t\t\t\tP.matrix( old_size, old_size ) = 1.0;\n\n \/\/ adjust weight vector alpha (equation 16)\n factor = (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight);\n atlas::axpy( factor, a_t, base_type::weight );\n\t\t\n\t\t\t\t\/\/ add new weight to the weight vector\n base_type::weight.push_back( factor \/ delta_t );\n\n \/\/ add support vector to the set\n\t \tbase_type::key_lookup.push_back( key );\n\n } else {\n \/\/ support vector set unchanged (see algorithmic on page 4 of paper)\n \/\/ adjust weight vector and permutation matrix P\n \/\/ P_a <- P_t-1 %*% a_t\n vector_type P_a( base_type::key_lookup.size() );\n\n \/\/ spmv(A,x,y) y <- A x\n \t ublas::matrix_range< ublas::matrix > P_range( P.view() );\n\t ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix > > P_view( P_range );\n atlas::symv( P_view, a_t, P_a );\n\n \/\/ 1 \/ (1 + a_t %*% P_(t-1) %*% a)\n scalar_type factor = 1.0 \/ (1.0 + atlas::dot( a_t, P_a ));\n\n \/\/ update weights (equation 13)\n atlas::symv( factor* (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight), \n \t\t\t R_view, P_a, static_cast(1), base_type::weight );\n\n \/\/ update permutation matrix (equation 14)\n atlas::syr( -factor, P_a, P_view );\n\t\t\t}\n }\n }\n\n\nprivate:\n\n symmetric_type K; \/\/ kernel matrix K\n symmetric_type R; \/\/ inverse of kernel matrix K\n symmetric_type P; \/\/ permutation matrix P\n scalar_type nu; \/\/ ALD parameter\n scalar_type lambda_squared; \/\/ kernel function addition\n};\n\n\n\n} \/\/ namespace kml\n\n#endif\n\nremoved an unused variable in krls.hpp\/***************************************************************************\n * The Kernel-Machine Library *\n * Copyright (C) 2004, 2005 by Rutger W. ter Borg *\n * *\n * This program is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU General Public License *\n * as published by the Free Software Foundation; either version 2 *\n * of the License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program; if not, write to the Free Software *\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307 *\n ***************************************************************************\/\n\n\n#ifndef KRLS_HPP\n#define KRLS_HPP\n\n\/\/ #include \n\/\/ #include \"kernels.h\"\n\n\/\/ #include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace atlas = boost::numeric::bindings::atlas;\n\n\nnamespace kml {\n\n\n\/*!\n\\brief Kernel Recursive Least Squares\n \nA preprocessing step is taken to absorb the bias term into the weight vector w, by\nredefining w as (w^T, b)^T and \\f$\\phi\\f$ as (phi^T,1)^T. For details, see Engel et al,\nSparse Online Greedy Support Vector Regression, below on page 3:\n\\f$k(x,x')=k(x,x') + \\lambda^2\\f$, where \\f$\\lambda\\f$ is a small, positive constant.\n\n\\section bibliography References\n-# Engel et al., 2003. Kernel Recursive Least Squares. \n*\/\n\n\ntemplate< typename Problem, typename Kernel, typename PropertyMap, class Enable = void>\nclass krls: public kernel_machine< Problem, Kernel, PropertyMap > {};\n\n\n\ntemplate< typename Problem, typename Kernel, typename PropertyMap >\nclass krls< Problem, Kernel, PropertyMap, typename boost::enable_if< is_regression >::type>:\n public kernel_machine< Problem, Kernel, PropertyMap > {\n\n\ttypedef kernel_machine< Problem, Kernel, PropertyMap > base_type;\n typedef typename base_type::kernel_type kernel_type;\n typedef double scalar_type;\n\n typedef symmetric_view< ublas::matrix > symmetric_type;\n \n typedef ublas::matrix matrix_type;\n typedef ublas::vector vector_type;\n\n typedef typename Problem::input_type input_type;\n typedef typename Problem::output_type output_type;\n\n\ttypedef typename boost::property_traits::key_type key_type;\n\ttypedef typename boost::property_traits::value_type object_type;\n\npublic:\n krls( scalar_type n, scalar_type l, \n \t\ttypename boost::call_traits::param_type k, \n \ttypename boost::call_traits::param_type map ):\n base_type(k,map), nu(n), lambda_squared(l*l) {}\n \n template< typename TokenIterator >\n krls( TokenIterator const begin, TokenIterator const end, \n typename boost::call_traits::param_type k,\n typename boost::call_traits::param_type map ):\n\t\tbase_type(k,map) {\n\t\tnu = 1e-1;\t\t\t\t\t\t\/\/ default value\n\t\tscalar_type lambda=1e-3;\t\t\/\/ default value\n\t\tTokenIterator token(begin);\n\t\tif ( token != end ) {\n\t\t\tnu = boost::lexical_cast( *token++ );\n\t\t\tif ( token != end ) lambda = boost::lexical_cast( *token );\n\t\t}\n\t\tlambda_squared=lambda*lambda;\n\t}\n \n\n output_type operator()( input_type const &x ) {\n \n\t\tvector_type temp_K( base_type::key_lookup.size() );\n\t\tbase_type::fill_kernel( x, base_type::key_lookup.begin(), base_type::key_lookup.end(), temp_K.begin() );\n\t\tfor( int i=0; i < temp_K.size(); ++i )\n temp_K[i] += lambda_squared;\n return atlas::dot( base_type::weight, temp_K );\n\n }\n \n\n \/*! learn the entire range of keys indicated by this range *\/\n template\n void learn( KeyIterator begin, KeyIterator end ) {\n\t\tKeyIterator key_iterator(begin);\n\t\twhile( key_iterator != end ) {\n\t\t\tincrement( *key_iterator );\n\t\t\t++key_iterator;\n\t\t}\n }\n \n \n \/*! \\param key key of example in data *\/\n void increment( key_type const &key ) {\n\t \n\t \/\/std::cout << \"running key \" << key << \" through KRLS... \" << std::endl;\n \n\t\t\/\/ calculate the base_type::kernel function on (x_t,x_t), needed later on\n scalar_type k_tt = base_type::kernel( key, key ) + lambda_squared;\n\n \/\/ check whether dictionary is still not initialised\n if ( base_type::key_lookup.empty() ) {\n\n\t \t\/\/ there is no dictionary yet, so initialise all variables\n \/\/ resize the matrix K, its inverse R and matrix P to 1 x 1\n K.grow_row_column();\n R.grow_row_column();\n P.grow_row_column();\n\n \/\/ and use values as stated in the paper\n K.matrix(0,0) = k_tt;\n R.matrix(0,0) = 1.0 \/ k_tt;\n P.matrix(0,0) = 1.0;\n\n \/\/ add to weight vector\n\t\t base_type::weight.push_back( (*base_type::data)[key].second \/ k_tt );\n\n \/\/ add to support vector set\n base_type::key_lookup.push_back( key );\n\n } else {\n\n \/\/ KRLS already initialised, continue\n vector_type a_t( K.size1() );\n vector_type k_t( K.size1() );\n\n\t\t \/\/ fill vector k_t\n\t\t base_type::fill_kernel( key, base_type::key_lookup.begin(), base_type::key_lookup.end(), k_t.begin() );\n\t\t for( int i=0; i > R_range( R.view() );\n ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix > > R_view( R_range );\n atlas::symv( R_view, k_t, a_t );\n scalar_type delta_t = k_tt - atlas::dot( k_t, a_t );\n\n \/\/ Perform Approximate Linear Dependency (ALD) test\n if (delta_t > nu) {\n\t \n \/\/ add x_t to support vector set, adjust all needed variables\n unsigned int old_size = base_type::key_lookup.size();\n \n\t\t\/\/ update K (equation 14)\n \/\/ fetch a view into the last row of the matrix of the _old_ size\n\t\t\t\tK.grow_row_column();\n \t\t\t ublas::matrix_vector_slice< ublas::matrix > K_row_part( K.shrinked_row(old_size) );\n \t\t\t atlas::copy( k_t, K_row_part );\n K.matrix( old_size, old_size ) = k_tt;\n\t\t\t\t\n \/\/ update R (equation 14)\n scalar_type factor = static_cast(1) \/ delta_t;\n atlas::syr( factor, a_t, R_view );\n R.grow_row_column();\n\t\t\t ublas::matrix_vector_slice< ublas::matrix > R_row_part( R.shrinked_row(old_size) );\n atlas::scal( -factor, a_t );\n R_row_part.assign( a_t );\n R.matrix( old_size, old_size ) = factor;\n \n \/\/ update P (equation 15)\n \/\/ assign unit vector with 1 on last element.\n P.grow_row_column();\n\t\t\t\tublas::matrix_vector_slice< ublas::matrix > P_row_part( P.shrinked_row(old_size) ); \n\t\t\t\tatlas::set( 0.0, P_row_part );\n\t\t\t\tP.matrix( old_size, old_size ) = 1.0;\n\n \/\/ adjust weight vector alpha (equation 16)\n factor = (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight);\n atlas::axpy( factor, a_t, base_type::weight );\n\t\t\n\t\t\t\t\/\/ add new weight to the weight vector\n base_type::weight.push_back( factor \/ delta_t );\n\n \/\/ add support vector to the set\n\t \tbase_type::key_lookup.push_back( key );\n\n } else {\n \/\/ support vector set unchanged (see algorithmic on page 4 of paper)\n \/\/ adjust weight vector and permutation matrix P\n \/\/ P_a <- P_t-1 %*% a_t\n vector_type P_a( base_type::key_lookup.size() );\n\n \/\/ spmv(A,x,y) y <- A x\n \t ublas::matrix_range< ublas::matrix > P_range( P.view() );\n\t ublas::symmetric_adaptor< ublas::matrix_range< ublas::matrix > > P_view( P_range );\n atlas::symv( P_view, a_t, P_a );\n\n \/\/ 1 \/ (1 + a_t %*% P_(t-1) %*% a)\n scalar_type factor = 1.0 \/ (1.0 + atlas::dot( a_t, P_a ));\n\n \/\/ update weights (equation 13)\n atlas::symv( factor* (*base_type::data)[key].second - atlas::dot(k_t,base_type::weight), \n \t\t\t R_view, P_a, static_cast(1), base_type::weight );\n\n \/\/ update permutation matrix (equation 14)\n atlas::syr( -factor, P_a, P_view );\n\t\t\t}\n }\n }\n\n\nprivate:\n\n symmetric_type K; \/\/ kernel matrix K\n symmetric_type R; \/\/ inverse of kernel matrix K\n symmetric_type P; \/\/ permutation matrix P\n scalar_type nu; \/\/ ALD parameter\n scalar_type lambda_squared; \/\/ kernel function addition\n};\n\n\n\n} \/\/ namespace kml\n\n#endif\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xiroot.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2003-05-21 07:59:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"filt_pch.hxx\"\n#endif\n#pragma hdrstop\n\n\/\/ ============================================================================\n\n#ifndef SC_XIROOT_HXX\n#include \"xiroot.hxx\"\n#endif\n\n#ifndef SC_ADDINCOL_HXX\n#include \"addincol.hxx\"\n#endif\n\n#ifndef SC_XILINK_HXX\n#include \"xilink.hxx\"\n#endif\n#ifndef SC_XISTYLE_HXX\n#include \"xistyle.hxx\"\n#endif\n#ifndef SC_XICONTENT_HXX\n#include \"xicontent.hxx\"\n#endif\n#ifndef SC_XIESCHER_HXX\n#include \"xiescher.hxx\"\n#endif\n\n#include \"root.hxx\"\n\n\n\/\/ Global data ================================================================\n\nXclImpRootData::XclImpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rBasePath, CharSet eCharSet ) :\n XclRootData( eBiff, rDocument, rBasePath, eCharSet )\n{\n}\n\nXclImpRootData::~XclImpRootData()\n{\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nXclImpRoot::XclImpRoot( XclImpRootData& rImpRootData ) :\n XclRoot( rImpRootData ),\n mrImpData( rImpRootData )\n{\n mrImpData.mpPalette.reset( new XclImpPalette( GetRoot() ) );\n mrImpData.mpFontBuffer.reset( new XclImpFontBuffer( GetRoot() ) );\n mrImpData.mpNumFmtBuffer.reset( new XclImpNumFmtBuffer( GetRoot() ) );\n mrImpData.mpXFBuffer.reset( new XclImpXFBuffer( GetRoot() ) );\n mrImpData.mpXFIndexBuffer.reset( new XclImpXFIndexBuffer( GetRoot() ) );\n mrImpData.mpTabIdBuffer.reset( new XclImpTabIdBuffer );\n mrImpData.mpLinkManager.reset( new XclImpLinkManager( GetRoot() ) );\n}\n\nXclImpRoot::XclImpRoot( const XclImpRoot& rRoot ) :\n XclRoot( rRoot ),\n mrImpData( rRoot.mrImpData )\n{\n}\n\nXclImpRoot& XclImpRoot::operator=( const XclImpRoot& rRoot )\n{\n XclRoot::operator=( rRoot );\n return *this;\n}\n\nvoid XclImpRoot::SetBiff( XclBiff eBiff )\n{\n XclRoot::SetBiff( eBiff );\n GetPalette().OnChangeBiff();\n}\n\nXclImpSst& XclImpRoot::GetSst() const\n{\n if( !mrImpData.mpSst.get() )\n mrImpData.mpSst.reset( new XclImpSst( GetRoot() ) );\n return *mrImpData.mpSst;\n}\n\nXclImpPalette& XclImpRoot::GetPalette() const\n{\n return *mrImpData.mpPalette;\n}\n\nXclImpFontBuffer& XclImpRoot::GetFontBuffer() const\n{\n return *mrImpData.mpFontBuffer;\n}\n\nXclImpNumFmtBuffer& XclImpRoot::GetNumFmtBuffer() const\n{\n return *mrImpData.mpNumFmtBuffer;\n}\n\nXclImpXFBuffer& XclImpRoot::GetXFBuffer() const\n{\n return *mrImpData.mpXFBuffer;\n}\n\nXclImpXFIndexBuffer& XclImpRoot::GetXFIndexBuffer() const\n{\n return *mrImpData.mpXFIndexBuffer;\n}\n\nXclImpTabIdBuffer& XclImpRoot::GetTabIdBuffer() const\n{\n return *mrImpData.mpTabIdBuffer;\n}\n\nXclImpLinkManager& XclImpRoot::GetLinkManager() const\n{\n return *mrImpData.mpLinkManager;\n}\n\nXclImpObjectManager& XclImpRoot::GetObjectManager() const\n{\n if( !mrImpData.mpObjManager.get() )\n mrImpData.mpObjManager.reset( new XclImpObjectManager( GetRoot() ) );\n return *mrImpData.mpObjManager;\n}\n\nXclImpWebQueryBuffer& XclImpRoot::GetWebQueryBuffer() const\n{\n if( !mrImpData.mpWebQBuffer.get() )\n mrImpData.mpWebQBuffer.reset( new XclImpWebQueryBuffer( GetRoot() ) );\n return *mrImpData.mpWebQBuffer;\n}\n\nExcelToSc& XclImpRoot::GetFmlaConverter() const\n{\n return *mpRD->pFmlaConverter;\n}\n\nString XclImpRoot::GetScAddInName( const String& rXclName ) const\n{\n String aScName;\n if( ScGlobal::GetAddInCollection()->GetCalcName( rXclName, aScName ) )\n return aScName;\n return rXclName;\n}\n\nbool XclImpRoot::CheckCellAddress( const ScAddress& rPos ) const\n{\n return XclRoot::CheckCellAddress( rPos, GetScMaxPos() );\n}\n\nbool XclImpRoot::CheckCellRange( ScRange& rRange ) const\n{\n return XclRoot::CheckCellRange( rRange, GetScMaxPos() );\n}\n\nvoid XclImpRoot::CheckCellRangeList( ScRangeList& rRanges ) const\n{\n XclRoot::CheckCellRangeList( rRanges, GetScMaxPos() );\n}\n\n\n\/\/ ============================================================================\n\nINTEGRATION: CWS filtertracer01 (1.4.36); FILE MERGED 2003\/07\/15 12:05:03 dr 1.4.36.1: filter tracer\/*************************************************************************\n *\n * $RCSfile: xiroot.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2003-08-07 15:29:38 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/\/ ============================================================================\n\n#ifndef SC_XIROOT_HXX\n#include \"xiroot.hxx\"\n#endif\n\n#ifndef SC_ADDINCOL_HXX\n#include \"addincol.hxx\"\n#endif\n\n#ifndef SC_XLTRACER_HXX\n#include \"xltracer.hxx\"\n#endif\n#ifndef SC_XILINK_HXX\n#include \"xilink.hxx\"\n#endif\n#ifndef SC_XISTYLE_HXX\n#include \"xistyle.hxx\"\n#endif\n#ifndef SC_XICONTENT_HXX\n#include \"xicontent.hxx\"\n#endif\n#ifndef SC_XIESCHER_HXX\n#include \"xiescher.hxx\"\n#endif\n\n#include \"root.hxx\"\n\n\n\/\/ Global data ================================================================\n\nXclImpRootData::XclImpRootData( XclBiff eBiff, ScDocument& rDocument, const String& rDocUrl, CharSet eCharSet ) :\n XclRootData( eBiff, rDocument, rDocUrl, eCharSet )\n{\n}\n\nXclImpRootData::~XclImpRootData()\n{\n}\n\n\n\/\/ ----------------------------------------------------------------------------\n\nXclImpRoot::XclImpRoot( XclImpRootData& rImpRootData ) :\n XclRoot( rImpRootData ),\n mrImpData( rImpRootData )\n{\n mrImpData.mpTracer.reset( new XclTracer( GetDocUrl(), CREATE_OUSTRING( \"Office.Tracing\/Import\/Excel\" ) ) );\n mrImpData.mpPalette.reset( new XclImpPalette( GetRoot() ) );\n mrImpData.mpFontBuffer.reset( new XclImpFontBuffer( GetRoot() ) );\n mrImpData.mpNumFmtBuffer.reset( new XclImpNumFmtBuffer( GetRoot() ) );\n mrImpData.mpXFBuffer.reset( new XclImpXFBuffer( GetRoot() ) );\n mrImpData.mpXFIndexBuffer.reset( new XclImpXFIndexBuffer( GetRoot() ) );\n mrImpData.mpTabIdBuffer.reset( new XclImpTabIdBuffer );\n mrImpData.mpLinkManager.reset( new XclImpLinkManager( GetRoot() ) );\n}\n\nXclImpRoot::XclImpRoot( const XclImpRoot& rRoot ) :\n XclRoot( rRoot ),\n mrImpData( rRoot.mrImpData )\n{\n}\n\nXclImpRoot& XclImpRoot::operator=( const XclImpRoot& rRoot )\n{\n XclRoot::operator=( rRoot );\n return *this;\n}\n\nvoid XclImpRoot::SetBiff( XclBiff eBiff )\n{\n XclRoot::SetBiff( eBiff );\n GetPalette().OnChangeBiff();\n}\n\nXclImpSst& XclImpRoot::GetSst() const\n{\n if( !mrImpData.mpSst.get() )\n mrImpData.mpSst.reset( new XclImpSst( GetRoot() ) );\n return *mrImpData.mpSst;\n}\n\nXclImpPalette& XclImpRoot::GetPalette() const\n{\n return *mrImpData.mpPalette;\n}\n\nXclImpFontBuffer& XclImpRoot::GetFontBuffer() const\n{\n return *mrImpData.mpFontBuffer;\n}\n\nXclImpNumFmtBuffer& XclImpRoot::GetNumFmtBuffer() const\n{\n return *mrImpData.mpNumFmtBuffer;\n}\n\nXclImpXFBuffer& XclImpRoot::GetXFBuffer() const\n{\n return *mrImpData.mpXFBuffer;\n}\n\nXclImpXFIndexBuffer& XclImpRoot::GetXFIndexBuffer() const\n{\n return *mrImpData.mpXFIndexBuffer;\n}\n\nXclImpTabIdBuffer& XclImpRoot::GetTabIdBuffer() const\n{\n return *mrImpData.mpTabIdBuffer;\n}\n\nXclImpLinkManager& XclImpRoot::GetLinkManager() const\n{\n return *mrImpData.mpLinkManager;\n}\n\nXclImpObjectManager& XclImpRoot::GetObjectManager() const\n{\n if( !mrImpData.mpObjManager.get() )\n mrImpData.mpObjManager.reset( new XclImpObjectManager( GetRoot() ) );\n return *mrImpData.mpObjManager;\n}\n\nXclImpWebQueryBuffer& XclImpRoot::GetWebQueryBuffer() const\n{\n if( !mrImpData.mpWebQBuffer.get() )\n mrImpData.mpWebQBuffer.reset( new XclImpWebQueryBuffer( GetRoot() ) );\n return *mrImpData.mpWebQBuffer;\n}\n\nExcelToSc& XclImpRoot::GetFmlaConverter() const\n{\n return *mpRD->pFmlaConverter;\n}\n\nString XclImpRoot::GetScAddInName( const String& rXclName ) const\n{\n String aScName;\n if( ScGlobal::GetAddInCollection()->GetCalcName( rXclName, aScName ) )\n return aScName;\n return rXclName;\n}\n\nbool XclImpRoot::CheckCellAddress( const ScAddress& rPos ) const\n{\n return XclRoot::CheckCellAddress( rPos, GetScMaxPos() );\n}\n\nbool XclImpRoot::CheckCellRange( ScRange& rRange ) const\n{\n return XclRoot::CheckCellRange( rRange, GetScMaxPos() );\n}\n\nvoid XclImpRoot::CheckCellRangeList( ScRangeList& rRanges ) const\n{\n XclRoot::CheckCellRangeList( rRanges, GetScMaxPos() );\n}\n\n\n\/\/ ============================================================================\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlbodyi.cxx,v $\n * $Revision: 1.31 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n#include \n\n#include \"document.hxx\"\n\n#include \"xmlbodyi.hxx\"\n#include \"xmltabi.hxx\"\n#include \"xmlnexpi.hxx\"\n#include \"xmldrani.hxx\"\n#include \"xmlimprt.hxx\"\n#include \"xmldpimp.hxx\"\n#include \"xmlcvali.hxx\"\n#include \"xmlstyli.hxx\"\n#include \"xmllabri.hxx\"\n#include \"XMLConsolidationContext.hxx\"\n#include \"XMLDDELinksContext.hxx\"\n#include \"XMLCalculationSettingsContext.hxx\"\n#include \"XMLTrackedChangesContext.hxx\"\n#include \"XMLEmptyContext.hxx\"\n#include \"scerrors.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\n\/\/------------------------------------------------------------------\n\nScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,\n USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const uno::Reference& xAttrList ) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n sPassword(),\n bProtected(sal_False),\n bHadCalculationSettings(sal_False),\n pChangeTrackingImportHelper(NULL)\n{\n ScDocument* pDoc = GetScImport().GetDocument();\n if (pDoc)\n {\n \/\/ ODF 1.1 and earlier => GRAM_PODF; ODF 1.2 and later => GRAM_ODFF;\n \/\/ no version => earlier than 1.2 => GRAM_PODF.\n ScGrammar::Grammar eGrammar = ScGrammar::GRAM_ODFF;\n OUString aVer( rImport.GetODFVersion());\n sal_Int32 nLen = aVer.getLength();\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr, \"\\n ScXMLBodyContext ODFVersion: nLen: %d, str: %s\\n\",\n nLen, OUStringToOString( aVer, RTL_TEXTENCODING_UTF8).getStr());\n#endif\n if (!nLen)\n eGrammar = ScGrammar::GRAM_PODF;\n else\n {\n \/\/ In case there was a micro version, e.g. \"1.2.3\", this would\n \/\/ still yield major.minor, but pParsedEnd (5th parameter, not\n \/\/ passed here) would point before string end upon return.\n double fVer = ::rtl::math::stringToDouble( aVer, '.', 0, NULL, NULL);\n if (fVer < 1.2)\n eGrammar = ScGrammar::GRAM_PODF;\n }\n pDoc->SetStorageGrammar( eGrammar);\n }\n\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n for( sal_Int16 i=0; i < nAttrCount; ++i )\n {\n const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));\n rtl::OUString aLocalName;\n USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(\n sAttrName, &aLocalName );\n const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));\n\n if (nPrefix == XML_NAMESPACE_TABLE)\n {\n if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))\n bProtected = IsXMLToken(sValue, XML_TRUE);\n else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))\n sPassword = sValue;\n }\n }\n}\n\nScXMLBodyContext::~ScXMLBodyContext()\n{\n}\n\nSvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();\n\/\/ sal_Bool bOrdered = sal_False;\n\/\/ sal_Bool bHeading = sal_False;\n switch( rTokenMap.Get( nPrefix, rLocalName ) )\n {\n\/\/ case XML_TOK_TEXT_H:\n\/\/ bHeading = TRUE;\n\/\/ case XML_TOK_TEXT_P:\n\/\/ pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,\n\/\/ xAttrList, bHeading );\n\/\/ break;\n\/\/ case XML_TOK_TEXT_ORDERED_LIST:\n\/\/ bOrdered = TRUE;\n\/\/ case XML_TOK_TEXT_UNORDERED_LIST:\n\/\/ pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,\n\/\/ xAttrList, bOrdered );\n\/\/ break;\n case XML_TOK_BODY_TRACKED_CHANGES :\n {\n pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();\n if (pChangeTrackingImportHelper)\n pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);\n }\n break;\n case XML_TOK_BODY_CALCULATION_SETTINGS :\n pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n bHadCalculationSettings = sal_True;\n break;\n case XML_TOK_BODY_CONTENT_VALIDATIONS :\n pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n break;\n case XML_TOK_BODY_LABEL_RANGES:\n pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n break;\n case XML_TOK_BODY_TABLE:\n {\n if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)\n {\n GetScImport().SetRangeOverflowType(SCWARN_IMPORT_SHEET_OVERFLOW);\n pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);\n }\n else\n {\n pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,\n xAttrList );\n }\n }\n break;\n case XML_TOK_BODY_NAMED_EXPRESSIONS:\n pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATABASE_RANGES:\n pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATABASE_RANGE:\n pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATA_PILOT_TABLES:\n pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_CONSOLIDATION:\n pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DDE_LINKS:\n pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );\n\n return pContext;\n}\n\nvoid ScXMLBodyContext::EndElement()\n{\n if (!bHadCalculationSettings)\n {\n \/\/ #111055#; set calculation settings defaults if there is no calculation settings element\n SvXMLImportContext *pContext = new ScXMLCalculationSettingsContext( GetScImport(), XML_NAMESPACE_TABLE, GetXMLToken(XML_CALCULATION_SETTINGS), NULL );\n pContext->EndElement();\n }\n GetScImport().LockSolarMutex();\n ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();\n ScDocument* pDoc = GetScImport().GetDocument();\n ScMyImpDetectiveOp aDetOp;\n\n if (pDoc && GetScImport().GetModel().is())\n {\n if (pDetOpArray)\n {\n pDetOpArray->Sort();\n while( pDetOpArray->GetFirstOp( aDetOp ) )\n {\n ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );\n pDoc->AddDetectiveOperation( aOpData );\n }\n }\n\n if (pChangeTrackingImportHelper)\n pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());\n\n#if 0\n \/\/ #i57869# table styles are applied before the contents now\n\n std::vector aTableStyleNames(GetScImport().GetTableStyle());\n uno::Reference xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );\n if ( xSpreadDoc.is() && !aTableStyleNames.empty())\n {\n uno::Reference xIndex( xSpreadDoc->getSheets(), uno::UNO_QUERY );\n if ( xIndex.is() )\n {\n sal_Int32 nTableCount = xIndex->getCount();\n sal_Int32 nSize(aTableStyleNames.size());\n DBG_ASSERT(nTableCount == nSize, \"every table should have a style name\");\n for(sal_uInt32 i = 0; i < nTableCount; i++)\n {\n if (i < nSize)\n {\n uno::Reference xProperties(xIndex->getByIndex(i), uno::UNO_QUERY);\n if (xProperties.is())\n {\n rtl::OUString sTableStyleName(aTableStyleNames[i]);\n XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();\n if ( pStyles && sTableStyleName.getLength() )\n {\n XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(\n XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);\n if (pStyle)\n pStyle->FillPropertySet(xProperties);\n }\n }\n }\n }\n }\n }\n#endif\n\n \/\/ #i37959# handle document protection after the sheet settings\n if (bProtected)\n {\n uno::Sequence aPass;\n if (sPassword.getLength())\n SvXMLUnitConverter::decodeBase64(aPass, sPassword);\n pDoc->SetDocProtection(bProtected, aPass);\n }\n }\n GetScImport().UnlockSolarMutex();\n}\n\nINTEGRATION: CWS chart29 (1.31.64); FILE MERGED 2008\/07\/10 13:59:36 dr 1.31.64.1: missing casts\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlbodyi.cxx,v $\n * $Revision: 1.32 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\/\/ INCLUDE ---------------------------------------------------------------\n#include \n\n#include \"document.hxx\"\n\n#include \"xmlbodyi.hxx\"\n#include \"xmltabi.hxx\"\n#include \"xmlnexpi.hxx\"\n#include \"xmldrani.hxx\"\n#include \"xmlimprt.hxx\"\n#include \"xmldpimp.hxx\"\n#include \"xmlcvali.hxx\"\n#include \"xmlstyli.hxx\"\n#include \"xmllabri.hxx\"\n#include \"XMLConsolidationContext.hxx\"\n#include \"XMLDDELinksContext.hxx\"\n#include \"XMLCalculationSettingsContext.hxx\"\n#include \"XMLTrackedChangesContext.hxx\"\n#include \"XMLEmptyContext.hxx\"\n#include \"scerrors.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace com::sun::star;\nusing namespace xmloff::token;\n\n\/\/------------------------------------------------------------------\n\nScXMLBodyContext::ScXMLBodyContext( ScXMLImport& rImport,\n USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const uno::Reference& xAttrList ) :\n SvXMLImportContext( rImport, nPrfx, rLName ),\n sPassword(),\n bProtected(sal_False),\n bHadCalculationSettings(sal_False),\n pChangeTrackingImportHelper(NULL)\n{\n ScDocument* pDoc = GetScImport().GetDocument();\n if (pDoc)\n {\n \/\/ ODF 1.1 and earlier => GRAM_PODF; ODF 1.2 and later => GRAM_ODFF;\n \/\/ no version => earlier than 1.2 => GRAM_PODF.\n ScGrammar::Grammar eGrammar = ScGrammar::GRAM_ODFF;\n OUString aVer( rImport.GetODFVersion());\n sal_Int32 nLen = aVer.getLength();\n#if OSL_DEBUG_LEVEL > 1\n fprintf( stderr, \"\\n ScXMLBodyContext ODFVersion: nLen: %d, str: %s\\n\",\n (int)nLen, OUStringToOString( aVer, RTL_TEXTENCODING_UTF8).getStr());\n#endif\n if (!nLen)\n eGrammar = ScGrammar::GRAM_PODF;\n else\n {\n \/\/ In case there was a micro version, e.g. \"1.2.3\", this would\n \/\/ still yield major.minor, but pParsedEnd (5th parameter, not\n \/\/ passed here) would point before string end upon return.\n double fVer = ::rtl::math::stringToDouble( aVer, '.', 0, NULL, NULL);\n if (fVer < 1.2)\n eGrammar = ScGrammar::GRAM_PODF;\n }\n pDoc->SetStorageGrammar( eGrammar);\n }\n\n sal_Int16 nAttrCount = xAttrList.is() ? xAttrList->getLength() : 0;\n for( sal_Int16 i=0; i < nAttrCount; ++i )\n {\n const rtl::OUString& sAttrName(xAttrList->getNameByIndex( i ));\n rtl::OUString aLocalName;\n USHORT nPrefix = GetScImport().GetNamespaceMap().GetKeyByAttrName(\n sAttrName, &aLocalName );\n const rtl::OUString& sValue(xAttrList->getValueByIndex( i ));\n\n if (nPrefix == XML_NAMESPACE_TABLE)\n {\n if (IsXMLToken(aLocalName, XML_STRUCTURE_PROTECTED))\n bProtected = IsXMLToken(sValue, XML_TRUE);\n else if (IsXMLToken(aLocalName, XML_PROTECTION_KEY))\n sPassword = sValue;\n }\n }\n}\n\nScXMLBodyContext::~ScXMLBodyContext()\n{\n}\n\nSvXMLImportContext *ScXMLBodyContext::CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList )\n{\n SvXMLImportContext *pContext = 0;\n\n const SvXMLTokenMap& rTokenMap = GetScImport().GetBodyElemTokenMap();\n\/\/ sal_Bool bOrdered = sal_False;\n\/\/ sal_Bool bHeading = sal_False;\n switch( rTokenMap.Get( nPrefix, rLocalName ) )\n {\n\/\/ case XML_TOK_TEXT_H:\n\/\/ bHeading = TRUE;\n\/\/ case XML_TOK_TEXT_P:\n\/\/ pContext = new SwXMLParaContext( GetSwImport(),nPrefix, rLocalName,\n\/\/ xAttrList, bHeading );\n\/\/ break;\n\/\/ case XML_TOK_TEXT_ORDERED_LIST:\n\/\/ bOrdered = TRUE;\n\/\/ case XML_TOK_TEXT_UNORDERED_LIST:\n\/\/ pContext = new SwXMLListBlockContext( GetSwImport(),nPrefix, rLocalName,\n\/\/ xAttrList, bOrdered );\n\/\/ break;\n case XML_TOK_BODY_TRACKED_CHANGES :\n {\n pChangeTrackingImportHelper = GetScImport().GetChangeTrackingImportHelper();\n if (pChangeTrackingImportHelper)\n pContext = new ScXMLTrackedChangesContext( GetScImport(), nPrefix, rLocalName, xAttrList, pChangeTrackingImportHelper);\n }\n break;\n case XML_TOK_BODY_CALCULATION_SETTINGS :\n pContext = new ScXMLCalculationSettingsContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n bHadCalculationSettings = sal_True;\n break;\n case XML_TOK_BODY_CONTENT_VALIDATIONS :\n pContext = new ScXMLContentValidationsContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n break;\n case XML_TOK_BODY_LABEL_RANGES:\n pContext = new ScXMLLabelRangesContext( GetScImport(), nPrefix, rLocalName, xAttrList );\n break;\n case XML_TOK_BODY_TABLE:\n {\n if (GetScImport().GetTables().GetCurrentSheet() >= MAXTAB)\n {\n GetScImport().SetRangeOverflowType(SCWARN_IMPORT_SHEET_OVERFLOW);\n pContext = new ScXMLEmptyContext(GetScImport(), nPrefix, rLocalName);\n }\n else\n {\n pContext = new ScXMLTableContext( GetScImport(),nPrefix, rLocalName,\n xAttrList );\n }\n }\n break;\n case XML_TOK_BODY_NAMED_EXPRESSIONS:\n pContext = new ScXMLNamedExpressionsContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATABASE_RANGES:\n pContext = new ScXMLDatabaseRangesContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATABASE_RANGE:\n pContext = new ScXMLDatabaseRangeContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DATA_PILOT_TABLES:\n pContext = new ScXMLDataPilotTablesContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_CONSOLIDATION:\n pContext = new ScXMLConsolidationContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n case XML_TOK_BODY_DDE_LINKS:\n pContext = new ScXMLDDELinksContext ( GetScImport(), nPrefix, rLocalName,\n xAttrList );\n break;\n }\n\n if( !pContext )\n pContext = new SvXMLImportContext( GetImport(), nPrefix, rLocalName );\n\n return pContext;\n}\n\nvoid ScXMLBodyContext::EndElement()\n{\n if (!bHadCalculationSettings)\n {\n \/\/ #111055#; set calculation settings defaults if there is no calculation settings element\n SvXMLImportContext *pContext = new ScXMLCalculationSettingsContext( GetScImport(), XML_NAMESPACE_TABLE, GetXMLToken(XML_CALCULATION_SETTINGS), NULL );\n pContext->EndElement();\n }\n GetScImport().LockSolarMutex();\n ScMyImpDetectiveOpArray* pDetOpArray = GetScImport().GetDetectiveOpArray();\n ScDocument* pDoc = GetScImport().GetDocument();\n ScMyImpDetectiveOp aDetOp;\n\n if (pDoc && GetScImport().GetModel().is())\n {\n if (pDetOpArray)\n {\n pDetOpArray->Sort();\n while( pDetOpArray->GetFirstOp( aDetOp ) )\n {\n ScDetOpData aOpData( aDetOp.aPosition, aDetOp.eOpType );\n pDoc->AddDetectiveOperation( aOpData );\n }\n }\n\n if (pChangeTrackingImportHelper)\n pChangeTrackingImportHelper->CreateChangeTrack(GetScImport().GetDocument());\n\n#if 0\n \/\/ #i57869# table styles are applied before the contents now\n\n std::vector aTableStyleNames(GetScImport().GetTableStyle());\n uno::Reference xSpreadDoc( GetScImport().GetModel(), uno::UNO_QUERY );\n if ( xSpreadDoc.is() && !aTableStyleNames.empty())\n {\n uno::Reference xIndex( xSpreadDoc->getSheets(), uno::UNO_QUERY );\n if ( xIndex.is() )\n {\n sal_Int32 nTableCount = xIndex->getCount();\n sal_Int32 nSize(aTableStyleNames.size());\n DBG_ASSERT(nTableCount == nSize, \"every table should have a style name\");\n for(sal_uInt32 i = 0; i < nTableCount; i++)\n {\n if (i < nSize)\n {\n uno::Reference xProperties(xIndex->getByIndex(i), uno::UNO_QUERY);\n if (xProperties.is())\n {\n rtl::OUString sTableStyleName(aTableStyleNames[i]);\n XMLTableStylesContext *pStyles = (XMLTableStylesContext *)GetScImport().GetAutoStyles();\n if ( pStyles && sTableStyleName.getLength() )\n {\n XMLTableStyleContext* pStyle = (XMLTableStyleContext *)pStyles->FindStyleChildContext(\n XML_STYLE_FAMILY_TABLE_TABLE, sTableStyleName, sal_True);\n if (pStyle)\n pStyle->FillPropertySet(xProperties);\n }\n }\n }\n }\n }\n }\n#endif\n\n \/\/ #i37959# handle document protection after the sheet settings\n if (bProtected)\n {\n uno::Sequence aPass;\n if (sPassword.getLength())\n SvXMLUnitConverter::decodeBase64(aPass, sPassword);\n pDoc->SetDocProtection(bProtected, aPass);\n }\n }\n GetScImport().UnlockSolarMutex();\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlcelli.hxx,v $\n *\n * $Revision: 1.22 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 20:04:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef SC_XMLCELLI_HXX\n#define SC_XMLCELLI_HXX\n\n#ifndef _SC_XMLDETECTIVECONTEXT_HXX\n#include \"XMLDetectiveContext.hxx\"\n#endif\n#ifndef _SC_XMLCELLRANGESOURCECONTEXT_HXX\n#include \"XMLCellRangeSourceContext.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLIMP_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_XCELL_HPP_\n#include \n#endif\n#include \n#include \n#ifndef _SAL_TYPES_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XACTIONLOCKABLE_HPP_\n#include \n#endif\n\nclass ScXMLImport;\nclass OutlinerParaObject;\n\nstruct ScMyImportAnnotation\n{\n rtl::OUString sAuthor;\n rtl::OUString sCreateDate;\n rtl::OUString sText;\n sal_Bool bDisplay;\n Rectangle* pRect;\n SfxItemSet* pItemSet;\n OutlinerParaObject* pOPO;\n\n ScMyImportAnnotation() : pItemSet(NULL), pOPO(NULL), pRect(NULL) {}\n ~ScMyImportAnnotation();\n};\n\nclass ScXMLTableRowCellContext : public SvXMLImportContext\n{\n com::sun::star::uno::Reference xBaseCell;\n com::sun::star::uno::Reference xLockable;\n rtl::OUString* pOUTextValue;\n rtl::OUString* pOUTextContent;\n rtl::OUString* pOUFormula;\n rtl::OUString* pContentValidationName;\n ScMyImportAnnotation* pMyAnnotation;\n ScMyImpDetectiveObjVec* pDetectiveObjVec;\n ScMyImpCellRangeSource* pCellRangeSource;\n double fValue;\n sal_Int32 nMergedRows, nMergedCols;\n sal_Int32 nMatrixRows, nMatrixCols;\n sal_Int32 nRepeatedRows;\n sal_Int32 nCellsRepeated;\n ScXMLImport& rXMLImport;\n sal_Int16 nCellType;\n sal_Bool bIsMerged;\n sal_Bool bIsMatrix;\n sal_Bool bHasSubTable;\n sal_Bool bIsCovered;\n sal_Bool bIsEmpty;\n sal_Bool bHasTextImport;\n sal_Bool bIsFirstTextImport;\n sal_Bool bSolarMutexLocked;\n sal_Bool bFormulaTextResult;\n\n const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }\n ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }\n\n sal_Int16 GetCellType(const rtl::OUString& sOUValue) const;\n\n sal_Bool IsMerged (const com::sun::star::uno::Reference & xCellRange,\n const sal_Int32 nCol, const sal_Int32 nRow,\n com::sun::star::table::CellRangeAddress& aCellAddress) const;\n void DoMerge(const com::sun::star::table::CellAddress& aCellPos,\n const sal_Int32 nCols, const sal_Int32 nRows);\n\n void SetContentValidation(com::sun::star::uno::Reference& xPropSet);\n void SetCellProperties(const com::sun::star::uno::Reference& xCellRange,\n const com::sun::star::table::CellAddress& aCellAddress);\n void SetCellProperties(const com::sun::star::uno::Reference& xCell);\n\n void LockSolarMutex();\n void UnlockSolarMutex();\n\n sal_Bool CellExists(const com::sun::star::table::CellAddress& aCellPos) const\n {\n return (aCellPos.Column <= MAXCOL && aCellPos.Row <= MAXROW);\n }\n\npublic:\n\n ScXMLTableRowCellContext( ScXMLImport& rImport, USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList,\n const sal_Bool bIsCovered, const sal_Int32 nRepeatedRows );\n\n virtual ~ScXMLTableRowCellContext();\n\n virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList );\n\n void SetString(const rtl::OUString& rOUTempText) {\n if (pOUTextContent)\n delete pOUTextContent;\n pOUTextContent = new ::rtl::OUString(rOUTempText); }\n void SetCursorOnTextImport(const rtl::OUString& rOUTempText);\n\n void SetAnnotation(const com::sun::star::uno::Reference& xCell);\n void SetDetectiveObj( const ::com::sun::star::table::CellAddress& rPosition );\n void SetCellRangeSource( const ::com::sun::star::table::CellAddress& rPosition );\n\n virtual void EndElement();\n\n void AddAnnotation(ScMyImportAnnotation* pValue) { pMyAnnotation = pValue; }\n};\n\n#endif\nINTEGRATION: CWS calcperf01 (1.21.56); FILE MERGED 2005\/06\/03 13:20:48 sab 1.21.56.1: #i50282#; use Core instead of API\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlcelli.hxx,v $\n *\n * $Revision: 1.23 $\n *\n * last change: $Author: hr $ $Date: 2005-09-23 12:42:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef SC_XMLCELLI_HXX\n#define SC_XMLCELLI_HXX\n\n#ifndef _SC_XMLDETECTIVECONTEXT_HXX\n#include \"XMLDetectiveContext.hxx\"\n#endif\n#ifndef _SC_XMLCELLRANGESOURCECONTEXT_HXX\n#include \"XMLCellRangeSourceContext.hxx\"\n#endif\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \n#endif\n\n#ifndef _XMLOFF_XMLIMP_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_XCELL_HPP_\n#include \n#endif\n#include \n#include \n#ifndef _SAL_TYPES_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_XCELLRANGE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_CELLRANGEADDRESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_TABLE_CELLADDRESS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SHEET_XSPREADSHEETDOCUMENT_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_DOCUMENT_XACTIONLOCKABLE_HPP_\n#include \n#endif\n\nclass ScXMLImport;\nclass OutlinerParaObject;\n\nstruct ScMyImportAnnotation\n{\n rtl::OUString sAuthor;\n rtl::OUString sCreateDate;\n rtl::OUString sText;\n sal_Bool bDisplay;\n Rectangle* pRect;\n SfxItemSet* pItemSet;\n OutlinerParaObject* pOPO;\n\n ScMyImportAnnotation() : pItemSet(NULL), pOPO(NULL), pRect(NULL) {}\n ~ScMyImportAnnotation();\n};\n\nclass ScXMLTableRowCellContext : public SvXMLImportContext\n{\n com::sun::star::uno::Reference xBaseCell;\n com::sun::star::uno::Reference xLockable;\n rtl::OUString* pOUTextValue;\n rtl::OUString* pOUTextContent;\n rtl::OUString* pOUFormula;\n rtl::OUString* pContentValidationName;\n ScMyImportAnnotation* pMyAnnotation;\n ScMyImpDetectiveObjVec* pDetectiveObjVec;\n ScMyImpCellRangeSource* pCellRangeSource;\n double fValue;\n sal_Int32 nMergedRows, nMergedCols;\n sal_Int32 nMatrixRows, nMatrixCols;\n sal_Int32 nRepeatedRows;\n sal_Int32 nCellsRepeated;\n ScXMLImport& rXMLImport;\n sal_Int16 nCellType;\n sal_Bool bIsMerged;\n sal_Bool bIsMatrix;\n sal_Bool bHasSubTable;\n sal_Bool bIsCovered;\n sal_Bool bIsEmpty;\n sal_Bool bHasTextImport;\n sal_Bool bIsFirstTextImport;\n sal_Bool bSolarMutexLocked;\n sal_Bool bFormulaTextResult;\n\n const ScXMLImport& GetScImport() const { return (const ScXMLImport&)GetImport(); }\n ScXMLImport& GetScImport() { return (ScXMLImport&)GetImport(); }\n\n sal_Int16 GetCellType(const rtl::OUString& sOUValue) const;\n\n sal_Bool IsMerged (const com::sun::star::uno::Reference & xCellRange,\n const sal_Int32 nCol, const sal_Int32 nRow,\n com::sun::star::table::CellRangeAddress& aCellAddress) const;\n void DoMerge(const com::sun::star::table::CellAddress& aCellPos,\n const sal_Int32 nCols, const sal_Int32 nRows);\n\n void SetContentValidation(com::sun::star::uno::Reference& xPropSet);\n void SetCellProperties(const com::sun::star::uno::Reference& xCellRange,\n const com::sun::star::table::CellAddress& aCellAddress);\n void SetCellProperties(const com::sun::star::uno::Reference& xCell);\n\n void LockSolarMutex();\n void UnlockSolarMutex();\n\n sal_Bool CellExists(const com::sun::star::table::CellAddress& aCellPos) const\n {\n return (aCellPos.Column <= MAXCOL && aCellPos.Row <= MAXROW);\n }\n\npublic:\n\n ScXMLTableRowCellContext( ScXMLImport& rImport, USHORT nPrfx,\n const ::rtl::OUString& rLName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList,\n const sal_Bool bIsCovered, const sal_Int32 nRepeatedRows );\n\n virtual ~ScXMLTableRowCellContext();\n\n virtual SvXMLImportContext *CreateChildContext( USHORT nPrefix,\n const ::rtl::OUString& rLocalName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::xml::sax::XAttributeList>& xAttrList );\n\n void SetString(const rtl::OUString& rOUTempText) {\n if (pOUTextContent)\n delete pOUTextContent;\n pOUTextContent = new ::rtl::OUString(rOUTempText); }\n void SetCursorOnTextImport(const rtl::OUString& rOUTempText);\n\n void SetAnnotation(const ::com::sun::star::table::CellAddress& rPosition );\n void SetDetectiveObj( const ::com::sun::star::table::CellAddress& rPosition );\n void SetCellRangeSource( const ::com::sun::star::table::CellAddress& rPosition );\n\n virtual void EndElement();\n\n void AddAnnotation(ScMyImportAnnotation* pValue) { pMyAnnotation = pValue; }\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: graphsh.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: rt $ $Date: 2006-05-02 15:49:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifdef PCH\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n\/\/------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"graphsh.hxx\"\n#include \"sc.hrc\"\n#include \"viewdata.hxx\"\n#include \"drawview.hxx\"\n#include \"scresid.hxx\"\n\n#define ScGraphicShell\n#include \"scslots.hxx\"\n\n#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()\n\n\nSFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )\n{\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,\n ScResId(RID_GRAPHIC_OBJECTBAR) );\n SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );\n}\n\nTYPEINIT1( ScGraphicShell, ScDrawShell );\n\nScGraphicShell::ScGraphicShell(ScViewData* pData) :\n ScDrawShell(pData)\n{\n SetHelpId(HID_SCSHELL_GRAPHIC);\n SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"GraphicObject\")));\n}\n\nScGraphicShell::~ScGraphicShell()\n{\n}\n\nvoid ScGraphicShell::GetAttrState( SfxItemSet& rSet )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n\n if( pView )\n SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );\n}\n\nvoid ScGraphicShell::Execute( SfxRequest& rReq )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n\n if( pView )\n {\n SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );\n Invalidate();\n }\n}\n\nvoid ScGraphicShell::GetFilterState( SfxItemSet& rSet )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n BOOL bEnable = FALSE;\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )\n bEnable = TRUE;\n }\n\n if( !bEnable )\n SvxGraphicFilter::DisableGraphicFilterSlots( rSet );\n}\n\nvoid ScGraphicShell::ExecuteFilter( SfxRequest& rReq )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )\n {\n GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );\n\n if( SVX_GRAPHICFILTER_ERRCODE_NONE ==\n SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )\n {\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView )\n {\n SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetDescriptionOfMarkedObjects() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );\n pView->BegUndo( aStr );\n pFilteredObj->SetGraphicObject( aFilterObj );\n pView->ReplaceObject( pObj, *pPageView, pFilteredObj );\n pView->EndUndo();\n }\n }\n }\n }\n\n Invalidate();\n}\n\nINTEGRATION: CWS pchfix01 (1.7.60); FILE MERGED 2006\/07\/12 10:02:40 kaib 1.7.60.1: #i67080# Converted cxx files in sc, added initial project level pch and stripped old PCH definitions.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: graphsh.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2006-07-21 13:54:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sc.hxx\"\n\n\n\n\/\/------------------------------------------------------------------\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"graphsh.hxx\"\n#include \"sc.hrc\"\n#include \"viewdata.hxx\"\n#include \"drawview.hxx\"\n#include \"scresid.hxx\"\n\n#define ScGraphicShell\n#include \"scslots.hxx\"\n\n#define ITEMVALUE(ItemSet,Id,Cast) ((const Cast&)(ItemSet).Get(Id)).GetValue()\n\n\nSFX_IMPL_INTERFACE(ScGraphicShell, ScDrawShell, ScResId(SCSTR_GRAPHICSHELL) )\n{\n SFX_OBJECTBAR_REGISTRATION( SFX_OBJECTBAR_OBJECT|SFX_VISIBILITY_STANDARD|SFX_VISIBILITY_SERVER,\n ScResId(RID_GRAPHIC_OBJECTBAR) );\n SFX_POPUPMENU_REGISTRATION( ScResId(RID_POPUP_GRAPHIC) );\n}\n\nTYPEINIT1( ScGraphicShell, ScDrawShell );\n\nScGraphicShell::ScGraphicShell(ScViewData* pData) :\n ScDrawShell(pData)\n{\n SetHelpId(HID_SCSHELL_GRAPHIC);\n SetName(String::CreateFromAscii(RTL_CONSTASCII_STRINGPARAM(\"GraphicObject\")));\n}\n\nScGraphicShell::~ScGraphicShell()\n{\n}\n\nvoid ScGraphicShell::GetAttrState( SfxItemSet& rSet )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n\n if( pView )\n SvxGrafAttrHelper::GetGrafAttrState( rSet, *pView );\n}\n\nvoid ScGraphicShell::Execute( SfxRequest& rReq )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n\n if( pView )\n {\n SvxGrafAttrHelper::ExecuteGrafAttr( rReq, *pView );\n Invalidate();\n }\n}\n\nvoid ScGraphicShell::GetFilterState( SfxItemSet& rSet )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n BOOL bEnable = FALSE;\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) && ( ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP ) )\n bEnable = TRUE;\n }\n\n if( !bEnable )\n SvxGraphicFilter::DisableGraphicFilterSlots( rSet );\n}\n\nvoid ScGraphicShell::ExecuteFilter( SfxRequest& rReq )\n{\n ScDrawView* pView = GetViewData()->GetScDrawView();\n const SdrMarkList& rMarkList = pView->GetMarkedObjectList();\n\n if( rMarkList.GetMarkCount() == 1 )\n {\n SdrObject* pObj = rMarkList.GetMark( 0 )->GetObj();\n\n if( pObj && pObj->ISA( SdrGrafObj ) && ( (SdrGrafObj*) pObj )->GetGraphicType() == GRAPHIC_BITMAP )\n {\n GraphicObject aFilterObj( ( (SdrGrafObj*) pObj )->GetGraphicObject() );\n\n if( SVX_GRAPHICFILTER_ERRCODE_NONE ==\n SvxGraphicFilter::ExecuteGrfFilterSlot( rReq, aFilterObj ) )\n {\n SdrPageView* pPageView = pView->GetPageViewPvNum( 0 );\n\n if( pPageView )\n {\n SdrGrafObj* pFilteredObj = (SdrGrafObj*) pObj->Clone();\n String aStr( pView->GetDescriptionOfMarkedObjects() );\n\n aStr.Append( sal_Unicode(' ') );\n aStr.Append( String( ScResId( SCSTR_UNDO_GRAFFILTER ) ) );\n pView->BegUndo( aStr );\n pFilteredObj->SetGraphicObject( aFilterObj );\n pView->ReplaceObject( pObj, *pPageView, pFilteredObj );\n pView->EndUndo();\n }\n }\n }\n }\n\n Invalidate();\n}\n\n<|endoftext|>"} {"text":"\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * DataManWriter.cpp\n *\n * Created on: Jan 10, 2017\n * Author: Jason Wang\n *\/\n\n#include \"DataManWriter.tcc\"\n\nnamespace adios2\n{\nnamespace core\n{\nnamespace engine\n{\n\nDataManWriter::DataManWriter(IO &io, const std::string &name,\n const Mode openMode, helper::Comm comm)\n: Engine(\"DataManWriter\", io, name, openMode, std::move(comm)),\n m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)), m_SentSteps(0),\n m_ReplyThreadActive(true), m_PublishThreadActive(true)\n{\n\n m_MpiRank = m_Comm.Rank();\n m_MpiSize = m_Comm.Size();\n\n if (m_MpiSize > 1)\n {\n std::cerr << \"DataMan does not support N-to-M decomposition!\"\n << std::endl;\n }\n\n helper::GetParameter(m_IO.m_Parameters, \"IPAddress\", m_IPAddress);\n helper::GetParameter(m_IO.m_Parameters, \"Port\", m_Port);\n helper::GetParameter(m_IO.m_Parameters, \"Timeout\", m_Timeout);\n helper::GetParameter(m_IO.m_Parameters, \"Verbose\", m_Verbosity);\n helper::GetParameter(m_IO.m_Parameters, \"RendezvousReaderCount\",\n m_RendezvousReaderCount);\n helper::GetParameter(m_IO.m_Parameters, \"Threading\", m_Threading);\n helper::GetParameter(m_IO.m_Parameters, \"TransportMode\", m_TransportMode);\n helper::GetParameter(m_IO.m_Parameters, \"Monitor\", m_MonitorActive);\n helper::GetParameter(m_IO.m_Parameters, \"CombiningSteps\", m_CombiningSteps);\n helper::GetParameter(m_IO.m_Parameters, \"FloatAccuracy\", m_FloatAccuracy);\n\n m_HandshakeJson[\"Threading\"] = m_Threading;\n m_HandshakeJson[\"Transport\"] = m_TransportMode;\n \/\/ m_HandshakeJson[\"FloatAccuracy\"] = m_FloatAccuracy;\n\n if (m_IPAddress.empty())\n {\n throw(std::invalid_argument(\"IP address not specified\"));\n }\n\n if (m_MonitorActive)\n {\n if (m_CombiningSteps < 20)\n {\n m_Monitor.SetAverageSteps(40);\n }\n else\n {\n m_Monitor.SetAverageSteps(m_CombiningSteps * 2);\n }\n }\n\n std::string replierAddress =\n \"tcp:\/\/\" + m_IPAddress + \":\" + std::to_string(m_Port);\n std::string publisherAddress =\n \"tcp:\/\/\" + m_IPAddress + \":\" + std::to_string(m_Port + 1);\n\n if (m_TransportMode == \"fast\")\n {\n m_Publisher.OpenPublisher(publisherAddress);\n }\n\n m_Replier.OpenReplier(replierAddress, m_Timeout, 64);\n\n if (m_RendezvousReaderCount == 0)\n {\n m_ReplyThreadActive = true;\n m_ReplyThread = std::thread(&DataManWriter::ReplyThread, this);\n }\n else\n {\n Handshake();\n }\n\n if (m_TransportMode == \"reliable\" && m_RendezvousReaderCount > 0)\n {\n m_ReplyThreadActive = true;\n m_ReplyThread = std::thread(&DataManWriter::ReplyThread, this);\n }\n\n if (m_TransportMode == \"fast\")\n {\n m_ReplyThreadActive = false;\n }\n\n if (m_Threading && m_TransportMode == \"fast\")\n {\n m_PublishThreadActive = true;\n m_PublishThread = std::thread(&DataManWriter::PublishThread, this);\n }\n}\n\nDataManWriter::~DataManWriter()\n{\n if (not m_IsClosed)\n {\n DoClose();\n }\n}\n\nStepStatus DataManWriter::BeginStep(StepMode mode, const float timeout_sec)\n{\n ++m_CurrentStep;\n if (m_CombinedSteps == 0)\n {\n m_Serializer.NewWriterBuffer(m_SerializerBufferSize);\n }\n\n if (m_MonitorActive)\n {\n m_Monitor.BeginStep(m_CurrentStep);\n }\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::BeginStep \" << m_CurrentStep << std::endl;\n }\n\n return StepStatus::OK;\n}\n\nsize_t DataManWriter::CurrentStep() const { return m_CurrentStep; }\n\nvoid DataManWriter::PerformPuts() {}\n\nvoid DataManWriter::EndStep()\n{\n if (m_CurrentStep == 0)\n {\n m_Serializer.PutAttributes(m_IO);\n }\n\n m_Serializer.AttachTimeStamp(\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count());\n\n ++m_CombinedSteps;\n\n if (m_CombinedSteps >= m_CombiningSteps)\n {\n m_CombinedSteps = 0;\n m_Serializer.AttachAttributesToLocalPack();\n const auto buffer = m_Serializer.GetLocalPack();\n if (buffer->size() > m_SerializerBufferSize)\n {\n m_SerializerBufferSize = buffer->size();\n }\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(buffer);\n }\n else\n {\n m_Publisher.Send(buffer);\n }\n }\n\n if (m_MonitorActive)\n {\n m_Monitor.EndStep(m_CurrentStep);\n }\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::EndStep \" << m_CurrentStep << std::endl;\n }\n}\n\nvoid DataManWriter::Flush(const int transportIndex) {}\n\n\/\/ PRIVATE functions below\n\n#define declare_type(T) \\\n void DataManWriter::DoPutSync(Variable &variable, const T *values) \\\n { \\\n PutSyncCommon(variable, values); \\\n } \\\n void DataManWriter::DoPutDeferred(Variable &variable, const T *values) \\\n { \\\n PutDeferredCommon(variable, values); \\\n }\nADIOS2_FOREACH_STDTYPE_1ARG(declare_type)\n#undef declare_type\n\nvoid DataManWriter::DoClose(const int transportIndex)\n{\n if (m_CombinedSteps < m_CombiningSteps && m_CombinedSteps > 0)\n {\n m_Serializer.AttachAttributesToLocalPack();\n const auto buffer = m_Serializer.GetLocalPack();\n if (buffer->size() > m_SerializerBufferSize)\n {\n m_SerializerBufferSize = buffer->size();\n }\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(buffer);\n }\n else\n {\n m_Publisher.Send(buffer);\n }\n }\n\n nlohmann::json endSignal;\n endSignal[\"FinalStep\"] = static_cast(m_CurrentStep);\n std::string s = endSignal.dump() + '\\0';\n auto cvp = std::make_shared>(s.size());\n std::memcpy(cvp->data(), s.c_str(), s.size());\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(cvp);\n }\n else\n {\n m_Publisher.Send(cvp);\n }\n\n m_PublishThreadActive = false;\n if (m_ReplyThreadActive)\n {\n while (m_SentSteps < m_CurrentStep + 2)\n {\n }\n m_ReplyThreadActive = false;\n }\n\n if (m_ReplyThread.joinable())\n {\n m_ReplyThread.join();\n }\n\n if (m_PublishThread.joinable())\n {\n m_PublishThread.join();\n }\n\n m_IsClosed = true;\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::DoClose \" << m_CurrentStep << std::endl;\n }\n}\n\nvoid DataManWriter::PushBufferQueue(std::shared_ptr> buffer)\n{\n std::lock_guard l(m_BufferQueueMutex);\n m_BufferQueue.push(buffer);\n}\n\nstd::shared_ptr> DataManWriter::PopBufferQueue()\n{\n std::lock_guard l(m_BufferQueueMutex);\n if (m_BufferQueue.empty())\n {\n return nullptr;\n }\n else\n {\n auto ret = m_BufferQueue.front();\n m_BufferQueue.pop();\n return ret;\n }\n}\n\nvoid DataManWriter::PublishThread()\n{\n while (m_PublishThreadActive)\n {\n auto buffer = PopBufferQueue();\n if (buffer != nullptr && buffer->size() > 0)\n {\n m_Publisher.Send(buffer);\n }\n }\n}\n\nvoid DataManWriter::Handshake()\n{\n int readerCount = 0;\n while (true)\n {\n auto request = m_Replier.ReceiveRequest();\n if (request != nullptr && request->size() > 0)\n {\n std::string r(request->begin(), request->end());\n if (r == \"Handshake\")\n {\n m_HandshakeJson[\"TimeStamp\"] =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count();\n std::string js = m_HandshakeJson.dump() + '\\0';\n m_Replier.SendReply(js.data(), js.size());\n }\n else if (r == \"Ready\")\n {\n m_Replier.SendReply(\"OK\", 2);\n ++readerCount;\n }\n\n if (readerCount >= m_RendezvousReaderCount)\n {\n break;\n }\n }\n }\n}\n\nvoid DataManWriter::ReplyThread()\n{\n int readerCount = 0;\n while (m_ReplyThreadActive)\n {\n auto request = m_Replier.ReceiveRequest();\n if (request != nullptr && request->size() > 0)\n {\n std::string r(request->begin(), request->end());\n if (r == \"Handshake\")\n {\n m_HandshakeJson[\"TimeStamp\"] =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count();\n std::string js = m_HandshakeJson.dump() + '\\0';\n m_Replier.SendReply(js.data(), js.size());\n }\n else if (r == \"Ready\")\n {\n m_Replier.SendReply(\"OK\", 2);\n ++readerCount;\n }\n else if (r == \"Step\")\n {\n auto buffer = PopBufferQueue();\n while (buffer == nullptr)\n {\n buffer = PopBufferQueue();\n }\n if (buffer->size() > 0)\n {\n m_Replier.SendReply(buffer);\n m_SentSteps = m_SentSteps + m_CombiningSteps;\n }\n }\n }\n }\n}\n\n} \/\/ end namespace engine\n} \/\/ end namespace core\n} \/\/ end namespace adios2\nslowly adding back changes and see which one CI actually hates\/*\n * Distributed under the OSI-approved Apache License, Version 2.0. See\n * accompanying file Copyright.txt for details.\n *\n * DataManWriter.cpp\n *\n * Created on: Jan 10, 2017\n * Author: Jason Wang\n *\/\n\n#include \"DataManWriter.tcc\"\n\nnamespace adios2\n{\nnamespace core\n{\nnamespace engine\n{\n\nDataManWriter::DataManWriter(IO &io, const std::string &name,\n const Mode openMode, helper::Comm comm)\n: Engine(\"DataManWriter\", io, name, openMode, std::move(comm)),\n m_Serializer(m_Comm, helper::IsRowMajor(io.m_HostLanguage)), m_SentSteps(0),\n m_ReplyThreadActive(true), m_PublishThreadActive(true)\n{\n\n m_MpiRank = m_Comm.Rank();\n m_MpiSize = m_Comm.Size();\n\n if (m_MpiSize > 1)\n {\n std::cerr << \"DataMan does not support N-to-M decomposition!\"\n << std::endl;\n }\n\n helper::GetParameter(m_IO.m_Parameters, \"IPAddress\", m_IPAddress);\n helper::GetParameter(m_IO.m_Parameters, \"Port\", m_Port);\n helper::GetParameter(m_IO.m_Parameters, \"Timeout\", m_Timeout);\n helper::GetParameter(m_IO.m_Parameters, \"Verbose\", m_Verbosity);\n helper::GetParameter(m_IO.m_Parameters, \"RendezvousReaderCount\",\n m_RendezvousReaderCount);\n helper::GetParameter(m_IO.m_Parameters, \"Threading\", m_Threading);\n helper::GetParameter(m_IO.m_Parameters, \"TransportMode\", m_TransportMode);\n helper::GetParameter(m_IO.m_Parameters, \"Monitor\", m_MonitorActive);\n helper::GetParameter(m_IO.m_Parameters, \"CombiningSteps\", m_CombiningSteps);\n helper::GetParameter(m_IO.m_Parameters, \"FloatAccuracy\", m_FloatAccuracy);\n\n m_HandshakeJson[\"Threading\"] = m_Threading;\n m_HandshakeJson[\"Transport\"] = m_TransportMode;\n m_HandshakeJson[\"FloatAccuracy\"] = m_FloatAccuracy;\n\n if (m_IPAddress.empty())\n {\n throw(std::invalid_argument(\"IP address not specified\"));\n }\n\n if (m_MonitorActive)\n {\n if (m_CombiningSteps < 20)\n {\n m_Monitor.SetAverageSteps(40);\n }\n else\n {\n m_Monitor.SetAverageSteps(m_CombiningSteps * 2);\n }\n }\n\n std::string replierAddress =\n \"tcp:\/\/\" + m_IPAddress + \":\" + std::to_string(m_Port);\n std::string publisherAddress =\n \"tcp:\/\/\" + m_IPAddress + \":\" + std::to_string(m_Port + 1);\n\n if (m_TransportMode == \"fast\")\n {\n m_Publisher.OpenPublisher(publisherAddress);\n }\n\n m_Replier.OpenReplier(replierAddress, m_Timeout, 64);\n\n if (m_RendezvousReaderCount == 0)\n {\n m_ReplyThreadActive = true;\n m_ReplyThread = std::thread(&DataManWriter::ReplyThread, this);\n }\n else\n {\n Handshake();\n }\n\n if (m_TransportMode == \"reliable\" && m_RendezvousReaderCount > 0)\n {\n m_ReplyThreadActive = true;\n m_ReplyThread = std::thread(&DataManWriter::ReplyThread, this);\n }\n\n if (m_TransportMode == \"fast\")\n {\n m_ReplyThreadActive = false;\n }\n\n if (m_Threading && m_TransportMode == \"fast\")\n {\n m_PublishThreadActive = true;\n m_PublishThread = std::thread(&DataManWriter::PublishThread, this);\n }\n}\n\nDataManWriter::~DataManWriter()\n{\n if (not m_IsClosed)\n {\n DoClose();\n }\n}\n\nStepStatus DataManWriter::BeginStep(StepMode mode, const float timeout_sec)\n{\n ++m_CurrentStep;\n if (m_CombinedSteps == 0)\n {\n m_Serializer.NewWriterBuffer(m_SerializerBufferSize);\n }\n\n if (m_MonitorActive)\n {\n m_Monitor.BeginStep(m_CurrentStep);\n }\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::BeginStep \" << m_CurrentStep << std::endl;\n }\n\n return StepStatus::OK;\n}\n\nsize_t DataManWriter::CurrentStep() const { return m_CurrentStep; }\n\nvoid DataManWriter::PerformPuts() {}\n\nvoid DataManWriter::EndStep()\n{\n if (m_CurrentStep == 0)\n {\n m_Serializer.PutAttributes(m_IO);\n }\n\n m_Serializer.AttachTimeStamp(\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count());\n\n ++m_CombinedSteps;\n\n if (m_CombinedSteps >= m_CombiningSteps)\n {\n m_CombinedSteps = 0;\n m_Serializer.AttachAttributesToLocalPack();\n const auto buffer = m_Serializer.GetLocalPack();\n if (buffer->size() > m_SerializerBufferSize)\n {\n m_SerializerBufferSize = buffer->size();\n }\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(buffer);\n }\n else\n {\n m_Publisher.Send(buffer);\n }\n }\n\n if (m_MonitorActive)\n {\n m_Monitor.EndStep(m_CurrentStep);\n }\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::EndStep \" << m_CurrentStep << std::endl;\n }\n}\n\nvoid DataManWriter::Flush(const int transportIndex) {}\n\n\/\/ PRIVATE functions below\n\n#define declare_type(T) \\\n void DataManWriter::DoPutSync(Variable &variable, const T *values) \\\n { \\\n PutSyncCommon(variable, values); \\\n } \\\n void DataManWriter::DoPutDeferred(Variable &variable, const T *values) \\\n { \\\n PutDeferredCommon(variable, values); \\\n }\nADIOS2_FOREACH_STDTYPE_1ARG(declare_type)\n#undef declare_type\n\nvoid DataManWriter::DoClose(const int transportIndex)\n{\n if (m_CombinedSteps < m_CombiningSteps && m_CombinedSteps > 0)\n {\n m_Serializer.AttachAttributesToLocalPack();\n const auto buffer = m_Serializer.GetLocalPack();\n if (buffer->size() > m_SerializerBufferSize)\n {\n m_SerializerBufferSize = buffer->size();\n }\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(buffer);\n }\n else\n {\n m_Publisher.Send(buffer);\n }\n }\n\n nlohmann::json endSignal;\n endSignal[\"FinalStep\"] = static_cast(m_CurrentStep);\n std::string s = endSignal.dump() + '\\0';\n auto cvp = std::make_shared>(s.size());\n std::memcpy(cvp->data(), s.c_str(), s.size());\n\n if (m_Threading || m_TransportMode == \"reliable\")\n {\n PushBufferQueue(cvp);\n }\n else\n {\n m_Publisher.Send(cvp);\n }\n\n m_PublishThreadActive = false;\n if (m_ReplyThreadActive)\n {\n while (m_SentSteps < m_CurrentStep + 2)\n {\n }\n m_ReplyThreadActive = false;\n }\n\n if (m_ReplyThread.joinable())\n {\n m_ReplyThread.join();\n }\n\n if (m_PublishThread.joinable())\n {\n m_PublishThread.join();\n }\n\n m_IsClosed = true;\n\n if (m_Verbosity >= 10)\n {\n std::cout << \"DataManWriter::DoClose \" << m_CurrentStep << std::endl;\n }\n}\n\nvoid DataManWriter::PushBufferQueue(std::shared_ptr> buffer)\n{\n std::lock_guard l(m_BufferQueueMutex);\n m_BufferQueue.push(buffer);\n}\n\nstd::shared_ptr> DataManWriter::PopBufferQueue()\n{\n std::lock_guard l(m_BufferQueueMutex);\n if (m_BufferQueue.empty())\n {\n return nullptr;\n }\n else\n {\n auto ret = m_BufferQueue.front();\n m_BufferQueue.pop();\n return ret;\n }\n}\n\nvoid DataManWriter::PublishThread()\n{\n while (m_PublishThreadActive)\n {\n auto buffer = PopBufferQueue();\n if (buffer != nullptr && buffer->size() > 0)\n {\n m_Publisher.Send(buffer);\n }\n }\n}\n\nvoid DataManWriter::Handshake()\n{\n int readerCount = 0;\n while (true)\n {\n auto request = m_Replier.ReceiveRequest();\n if (request != nullptr && request->size() > 0)\n {\n std::string r(request->begin(), request->end());\n if (r == \"Handshake\")\n {\n m_HandshakeJson[\"TimeStamp\"] =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count();\n std::string js = m_HandshakeJson.dump() + '\\0';\n m_Replier.SendReply(js.data(), js.size());\n }\n else if (r == \"Ready\")\n {\n m_Replier.SendReply(\"OK\", 2);\n ++readerCount;\n }\n\n if (readerCount >= m_RendezvousReaderCount)\n {\n break;\n }\n }\n }\n}\n\nvoid DataManWriter::ReplyThread()\n{\n int readerCount = 0;\n while (m_ReplyThreadActive)\n {\n auto request = m_Replier.ReceiveRequest();\n if (request != nullptr && request->size() > 0)\n {\n std::string r(request->begin(), request->end());\n if (r == \"Handshake\")\n {\n m_HandshakeJson[\"TimeStamp\"] =\n std::chrono::duration_cast(\n std::chrono::system_clock::now().time_since_epoch())\n .count();\n std::string js = m_HandshakeJson.dump() + '\\0';\n m_Replier.SendReply(js.data(), js.size());\n }\n else if (r == \"Ready\")\n {\n m_Replier.SendReply(\"OK\", 2);\n ++readerCount;\n }\n else if (r == \"Step\")\n {\n auto buffer = PopBufferQueue();\n while (buffer == nullptr)\n {\n buffer = PopBufferQueue();\n }\n if (buffer->size() > 0)\n {\n m_Replier.SendReply(buffer);\n m_SentSteps = m_SentSteps + m_CombiningSteps;\n }\n }\n }\n }\n}\n\n} \/\/ end namespace engine\n} \/\/ end namespace core\n} \/\/ end namespace adios2\n<|endoftext|>"} {"text":"\/* Copyright © 2001-2019, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE equipment_test\n\n#include \n\n#include \"ed\/build_helper.h\"\n#include \"equipment\/equipment_api.h\"\n#include \"ptreferential\/ptreferential.h\"\n#include \"utils\/logger.h\"\n#include \"type\/type.h\"\n#include \"type\/pt_data.h\"\n#include \"tests\/utils_test.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace navitia;\nusing boost::posix_time::time_period;\nusing std::map;\nusing std::multiset;\nusing std::pair;\nusing std::set;\nusing std::string;\nusing std::vector;\n\nstruct logger_initialized {\n logger_initialized() { navitia::init_logger(); }\n};\nBOOST_GLOBAL_FIXTURE(logger_initialized);\n\nnamespace {\n\nclass EquipmentTestFixture {\npublic:\n ed::builder b;\n navitia::PbCreator pb_creator;\n const type::Data& data;\n\n EquipmentTestFixture() : b(\"20190101\"), data(*b.data) {\n b.sa(\"sa1\")(\"stop1\", {{\"CodeType1\", {\"code1\", \"code2\"}}});\n b.sa(\"sa2\")(\"stop2\", {{\"CodeType3\", {\"code5\"}}});\n b.sa(\"sa3\")(\"stop3\", {{\"CodeType1\", {\"code6\"}}});\n b.sa(\"sa4\")(\"stop4\", {});\n b.sa(\"sa5\")(\"stop5\", {{\"CodeType3\", {\"code7\"}}});\n b.sa(\"sa6\")(\"stop6\", {{\"CodeType1\", {\"code8\"}}});\n\n b.vj(\"A\")(\"stop1\", 8000, 8050)(\"stop2\", 8200, 8250)(\"stop3\", 9000, 9050);\n b.vj(\"B\")(\"stop4\", 8000, 8050)(\"stop5\", 8200, 8250)(\"stop6\", 9000, 9050);\n b.make();\n\n const ptime since = \"20190101T000000\"_dt;\n const ptime until = \"21190101T000000\"_dt;\n pb_creator.init(&data, since, time_period(since, until));\n }\n};\n\nBOOST_FIXTURE_TEST_CASE(test_stop_point_codes_creation, EquipmentTestFixture) {\n type::Indexes idx = ptref::make_query(nt::Type_e::StopPoint, \"(stop_point.has_code_type(CodeType1))\", data);\n\n set stop_points_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_points_uris.size(), 3);\n BOOST_CHECK_EQUAL_RANGE(stop_points_uris, (set{\"stop1\", \"stop3\", \"stop6\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_stop_area_query, EquipmentTestFixture) {\n type::Indexes idx = ptref::make_query(nt::Type_e::StopArea, \"(stop_point.has_code_type(CodeType1))\", data);\n\n set stop_area_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_area_uris.size(), 3);\n BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set{\"sa1\", \"sa3\", \"sa6\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_stop_area_per_line_query, EquipmentTestFixture) {\n type::Indexes idx =\n ptref::make_query(nt::Type_e::StopArea, \"(line.uri=A and stop_point.has_code_type(CodeType1))\", data);\n\n set stop_area_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_area_uris.size(), 2);\n BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set{\"sa1\", \"sa3\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_get_total_lines, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n\n BOOST_CHECK_EQUAL(er.get_total_lines(), 0);\n er.get_paginated_equipment_report_list();\n BOOST_CHECK_EQUAL(er.get_total_lines(), 2);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_get_report_list_should_return_the_stop_areas_per_line, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Convert result from object pointers to uris\n map> sa_per_line_uris;\n for (const auto& report : reports) {\n type::Line* line = std::get<0>(report);\n auto stop_area_equipments = std::get<1>(report);\n set sa_uris;\n for (const auto& sa_equip : stop_area_equipments) {\n type::StopArea* sa = std::get<0>(sa_equip);\n sa_uris.insert(sa->uri);\n }\n sa_per_line_uris[line->uri] = sa_uris;\n }\n\n map> expected_uris{\n {\"A\", {\"sa1\", \"sa3\"}},\n {\"B\", {\"sa6\"}},\n };\n BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);\n}\n\nBOOST_FIXTURE_TEST_CASE(get_report_list_should_return_the_correct_stop_points, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Convert result from object pointers to uris\n multiset stop_points_with_equipment;\n for (const auto& report : reports) {\n auto stop_area_equipments = std::get<1>(report);\n for (const auto& sa_equip : stop_area_equipments) {\n auto stop_points = std::get<1>(sa_equip);\n for (const type::StopPoint* sp : stop_points) {\n stop_points_with_equipment.insert(sp->uri);\n }\n }\n }\n\n multiset expected_sp = {\"stop1\", \"stop3\", \"stop6\"};\n BOOST_CHECK_EQUAL_RANGE(stop_points_with_equipment, expected_sp);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_should_forbid_uris, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\", 10, 0, {\"A\"});\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Stop Areas \"A\" and \"B\" have cpde \"CodeType1\", but \"A\" has been forbidden,\n \/\/ Hense the fact that only \"B\" is returned\n BOOST_REQUIRE_EQUAL(reports.size(), 1);\n BOOST_CHECK_EQUAL(std::get<0>(reports[0])->uri, \"B\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_test_api, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n equipment::equipment_reports(pb_creator, filter, 10);\n\n BOOST_CHECK_EQUAL(pb_creator.equipment_reports_size(), 2);\n const auto resp = pb_creator.get_response();\n\n map> sa_per_line_uris;\n for (const auto& equip_rep : resp.equipment_reports()) {\n BOOST_REQUIRE(equip_rep.has_line());\n set stop_area_uris;\n for (const auto& sae : equip_rep.stop_area_equipments()) {\n BOOST_REQUIRE(sae.has_stop_area());\n stop_area_uris.emplace(sae.stop_area().uri());\n }\n sa_per_line_uris[equip_rep.line().uri()] = stop_area_uris;\n }\n\n map> expected_uris{\n {\"A\", {\"sa1\", \"sa3\"}},\n {\"B\", {\"sa6\"}},\n };\n BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_fail_on_bad_filter, EquipmentTestFixture) {\n const auto filter = \"this filter is just nonsense\";\n equipment::equipment_reports(pb_creator, filter, 10);\n\n BOOST_CHECK_NO_THROW();\n BOOST_CHECK(pb_creator.has_error());\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_0, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n \/\/ PAGE 0 - COUNT = 1\n equipment::equipment_reports(pb_creator, filter, 1, 0, 0);\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();\n BOOST_CHECK_EQUAL(line_A_uri, \"A\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_1, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n \/\/ PAGE 1 - COUNT = 1\n equipment::equipment_reports(pb_creator, filter, 1, 0, 1);\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();\n BOOST_CHECK_EQUAL(line_A_uri, \"B\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_have_stop_points_codes, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n equipment::equipment_reports(pb_creator, filter, 1);\n\n \/*\n * With count = 1, we'll only get stop_areas\/stop_points from the 1sr line (\"A\")\n * This means we'll only populate codes from stop1 and stop3,\n * as they both have code type \"CodeType1\"\n *\/\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n\n multiset codes;\n for (const auto& sae : pb_creator.get_response().equipment_reports(0).stop_area_equipments()) {\n for (const auto& sp : sae.stop_area().stop_points()) {\n for (const auto& c : sp.codes()) {\n codes.emplace(c.value());\n }\n }\n }\n\n multiset expected_codes = {\"code1\", \"code2\", \"code6\"};\n BOOST_CHECK_EQUAL_RANGE(codes, expected_codes);\n}\n\n} \/\/ namespace\nfix typo\/* Copyright © 2001-2019, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nIRC #navitia on freenode\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE equipment_test\n\n#include \n\n#include \"ed\/build_helper.h\"\n#include \"equipment\/equipment_api.h\"\n#include \"ptreferential\/ptreferential.h\"\n#include \"utils\/logger.h\"\n#include \"type\/type.h\"\n#include \"type\/pt_data.h\"\n#include \"tests\/utils_test.h\"\n\n#include \n#include \n#include \n#include \n\nusing namespace navitia;\nusing boost::posix_time::time_period;\nusing std::map;\nusing std::multiset;\nusing std::pair;\nusing std::set;\nusing std::string;\nusing std::vector;\n\nstruct logger_initialized {\n logger_initialized() { navitia::init_logger(); }\n};\nBOOST_GLOBAL_FIXTURE(logger_initialized);\n\nnamespace {\n\nclass EquipmentTestFixture {\npublic:\n ed::builder b;\n navitia::PbCreator pb_creator;\n const type::Data& data;\n\n EquipmentTestFixture() : b(\"20190101\"), data(*b.data) {\n b.sa(\"sa1\")(\"stop1\", {{\"CodeType1\", {\"code1\", \"code2\"}}});\n b.sa(\"sa2\")(\"stop2\", {{\"CodeType3\", {\"code5\"}}});\n b.sa(\"sa3\")(\"stop3\", {{\"CodeType1\", {\"code6\"}}});\n b.sa(\"sa4\")(\"stop4\", {});\n b.sa(\"sa5\")(\"stop5\", {{\"CodeType3\", {\"code7\"}}});\n b.sa(\"sa6\")(\"stop6\", {{\"CodeType1\", {\"code8\"}}});\n\n b.vj(\"A\")(\"stop1\", 8000, 8050)(\"stop2\", 8200, 8250)(\"stop3\", 9000, 9050);\n b.vj(\"B\")(\"stop4\", 8000, 8050)(\"stop5\", 8200, 8250)(\"stop6\", 9000, 9050);\n b.make();\n\n const ptime since = \"20190101T000000\"_dt;\n const ptime until = \"21190101T000000\"_dt;\n pb_creator.init(&data, since, time_period(since, until));\n }\n};\n\nBOOST_FIXTURE_TEST_CASE(test_stop_point_codes_creation, EquipmentTestFixture) {\n type::Indexes idx = ptref::make_query(nt::Type_e::StopPoint, \"(stop_point.has_code_type(CodeType1))\", data);\n\n set stop_points_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_points_uris.size(), 3);\n BOOST_CHECK_EQUAL_RANGE(stop_points_uris, (set{\"stop1\", \"stop3\", \"stop6\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_stop_area_query, EquipmentTestFixture) {\n type::Indexes idx = ptref::make_query(nt::Type_e::StopArea, \"(stop_point.has_code_type(CodeType1))\", data);\n\n set stop_area_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_area_uris.size(), 3);\n BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set{\"sa1\", \"sa3\", \"sa6\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(test_stop_area_per_line_query, EquipmentTestFixture) {\n type::Indexes idx =\n ptref::make_query(nt::Type_e::StopArea, \"(line.uri=A and stop_point.has_code_type(CodeType1))\", data);\n\n set stop_area_uris = get_uris(idx, data);\n\n BOOST_CHECK_EQUAL(stop_area_uris.size(), 2);\n BOOST_CHECK_EQUAL_RANGE(stop_area_uris, (set{\"sa1\", \"sa3\"}));\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_get_total_lines, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n\n BOOST_CHECK_EQUAL(er.get_total_lines(), 0);\n er.get_paginated_equipment_report_list();\n BOOST_CHECK_EQUAL(er.get_total_lines(), 2);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_get_report_list_should_return_the_stop_areas_per_line, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Convert result from object pointers to uris\n map> sa_per_line_uris;\n for (const auto& report : reports) {\n type::Line* line = std::get<0>(report);\n auto stop_area_equipments = std::get<1>(report);\n set sa_uris;\n for (const auto& sa_equip : stop_area_equipments) {\n type::StopArea* sa = std::get<0>(sa_equip);\n sa_uris.insert(sa->uri);\n }\n sa_per_line_uris[line->uri] = sa_uris;\n }\n\n map> expected_uris{\n {\"A\", {\"sa1\", \"sa3\"}},\n {\"B\", {\"sa6\"}},\n };\n BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);\n}\n\nBOOST_FIXTURE_TEST_CASE(get_report_list_should_return_the_correct_stop_points, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\");\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Convert result from object pointers to uris\n multiset stop_points_with_equipment;\n for (const auto& report : reports) {\n auto stop_area_equipments = std::get<1>(report);\n for (const auto& sa_equip : stop_area_equipments) {\n auto stop_points = std::get<1>(sa_equip);\n for (const type::StopPoint* sp : stop_points) {\n stop_points_with_equipment.insert(sp->uri);\n }\n }\n }\n\n multiset expected_sp = {\"stop1\", \"stop3\", \"stop6\"};\n BOOST_CHECK_EQUAL_RANGE(stop_points_with_equipment, expected_sp);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_report_should_forbid_uris, EquipmentTestFixture) {\n equipment::EquipmentReports er(data, \"stop_point.has_code_type(CodeType1)\", 10, 0, {\"A\"});\n auto reports = er.get_paginated_equipment_report_list();\n\n \/\/ Stop Areas \"A\" and \"B\" have cpde \"CodeType1\", but \"A\" has been forbidden,\n \/\/ Hense the fact that only \"B\" is returned\n BOOST_REQUIRE_EQUAL(reports.size(), 1);\n BOOST_CHECK_EQUAL(std::get<0>(reports[0])->uri, \"B\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_test_api, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n equipment::equipment_reports(pb_creator, filter, 10);\n\n BOOST_CHECK_EQUAL(pb_creator.equipment_reports_size(), 2);\n const auto resp = pb_creator.get_response();\n\n map> sa_per_line_uris;\n for (const auto& equip_rep : resp.equipment_reports()) {\n BOOST_REQUIRE(equip_rep.has_line());\n set stop_area_uris;\n for (const auto& sae : equip_rep.stop_area_equipments()) {\n BOOST_REQUIRE(sae.has_stop_area());\n stop_area_uris.emplace(sae.stop_area().uri());\n }\n sa_per_line_uris[equip_rep.line().uri()] = stop_area_uris;\n }\n\n map> expected_uris{\n {\"A\", {\"sa1\", \"sa3\"}},\n {\"B\", {\"sa6\"}},\n };\n BOOST_CHECK_EQUAL_RANGE(sa_per_line_uris, expected_uris);\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_fail_on_bad_filter, EquipmentTestFixture) {\n const auto filter = \"this filter is just nonsense\";\n equipment::equipment_reports(pb_creator, filter, 10);\n\n BOOST_CHECK_NO_THROW();\n BOOST_CHECK(pb_creator.has_error());\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_0, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n \/\/ PAGE 0 - COUNT = 1\n equipment::equipment_reports(pb_creator, filter, 1, 0, 0);\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();\n BOOST_CHECK_EQUAL(line_A_uri, \"A\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_paginate_page_1, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n \/\/ PAGE 1 - COUNT = 1\n equipment::equipment_reports(pb_creator, filter, 1, 0, 1);\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n auto line_A_uri = pb_creator.get_response().equipment_reports(0).line().uri();\n BOOST_CHECK_EQUAL(line_A_uri, \"B\");\n}\n\nBOOST_FIXTURE_TEST_CASE(equipment_reports_should_have_stop_points_codes, EquipmentTestFixture) {\n const auto filter = \"stop_point.has_code_type(CodeType1)\";\n equipment::equipment_reports(pb_creator, filter, 1);\n\n \/*\n * With count = 1, we'll only get stop_areas\/stop_points from the 1st line (\"A\")\n * This means we'll only populate codes from stop1 and stop3,\n * as they both have code type \"CodeType1\"\n *\/\n BOOST_REQUIRE_EQUAL(pb_creator.equipment_reports_size(), 1);\n\n multiset codes;\n for (const auto& sae : pb_creator.get_response().equipment_reports(0).stop_area_equipments()) {\n for (const auto& sp : sae.stop_area().stop_points()) {\n for (const auto& c : sp.codes()) {\n codes.emplace(c.value());\n }\n }\n }\n\n multiset expected_codes = {\"code1\", \"code2\", \"code6\"};\n BOOST_CHECK_EQUAL_RANGE(codes, expected_codes);\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nusing namespace gl;\nusing namespace gloperate;\nnamespace gloperate_osg\n{\n\n\n\/**\n* @brief\n* Constructor\n*\/\nOsgRenderStage::OsgRenderStage(const std::string & name)\n: AbstractStage(name)\n, m_viewer(nullptr)\n, m_embedded(nullptr)\n, m_scene(nullptr)\n, m_viewportX(0)\n, m_viewportY(0)\n, m_viewportWidth(800)\n, m_viewportHeight(600)\n{\n}\n\n\/**\n* @brief\n* Destructor\n*\/\nOsgRenderStage::~OsgRenderStage()\n{\n osg_cleanup();\n}\n\n\/**\n* @brief\n* Get OSG viewer\n*\/\nosgViewer::Viewer * OsgRenderStage::viewer() const\n{\n return m_viewer;\n}\n\n\/**\n* @brief\n* Get OSG scene\n*\/\nosg::Node * OsgRenderStage::scene() const\n{\n return m_scene;\n}\n\n\/**\n* @brief\n* Set OSG scene\n*\/\nvoid OsgRenderStage::setScene(osg::Node * scene)\n{\n osg_setScene(scene);\n}\n\n\/**\n* @brief\n* Set viewport\n*\/\nvoid OsgRenderStage::setViewport(int x, int y, int width, int height)\n{\n m_viewportX = x;\n m_viewportY = y;\n m_viewportWidth = width;\n m_viewportHeight = height;\n}\n\n\/**\n* @brief\n* Create keyboard handler to control the wrapped OSG scene\n*\/\nOsgKeyboardHandler * OsgRenderStage::createKeyboardHandler() const\n{\n if (m_embedded) {\n return new OsgKeyboardHandler(m_embedded);\n } else {\n return nullptr;\n }\n}\n\n\/**\n* @brief\n* Create mouse handler to control the wrapped OSG scene\n*\/\nOsgMouseHandler * OsgRenderStage::createMouseHandler() const\n{\n if (m_embedded) {\n return new OsgMouseHandler(m_embedded);\n } else {\n return nullptr;\n }\n}\n\nvoid OsgRenderStage::initialize()\n{\n osg_initialize();\n}\n\nvoid OsgRenderStage::process()\n{\n \/\/ Get framebuffer to render into\n \/\/ [TODO] How to pass this to the stage?\n \/*\n globjects::Framebuffer * fbo = m_targetFramebufferCapability->framebuffer();\n if (!fbo) {\n fbo = globjects::Framebuffer::defaultFBO();\n }\n\n \/\/ Bind framebuffer\n fbo->bind(GL_FRAMEBUFFER);\n *\/\n\n \/\/ Draw osg scene\n osg_process();\n}\n\n\n} \/\/ namespace gloperate_osg\nRemove todo regarding target FBO from OsgRenderStage, since that is the responsibility of the painter#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n\nusing namespace gl;\nusing namespace gloperate;\nnamespace gloperate_osg\n{\n\n\n\/**\n* @brief\n* Constructor\n*\/\nOsgRenderStage::OsgRenderStage(const std::string & name)\n: AbstractStage(name)\n, m_viewer(nullptr)\n, m_embedded(nullptr)\n, m_scene(nullptr)\n, m_viewportX(0)\n, m_viewportY(0)\n, m_viewportWidth(800)\n, m_viewportHeight(600)\n{\n}\n\n\/**\n* @brief\n* Destructor\n*\/\nOsgRenderStage::~OsgRenderStage()\n{\n osg_cleanup();\n}\n\n\/**\n* @brief\n* Get OSG viewer\n*\/\nosgViewer::Viewer * OsgRenderStage::viewer() const\n{\n return m_viewer;\n}\n\n\/**\n* @brief\n* Get OSG scene\n*\/\nosg::Node * OsgRenderStage::scene() const\n{\n return m_scene;\n}\n\n\/**\n* @brief\n* Set OSG scene\n*\/\nvoid OsgRenderStage::setScene(osg::Node * scene)\n{\n osg_setScene(scene);\n}\n\n\/**\n* @brief\n* Set viewport\n*\/\nvoid OsgRenderStage::setViewport(int x, int y, int width, int height)\n{\n m_viewportX = x;\n m_viewportY = y;\n m_viewportWidth = width;\n m_viewportHeight = height;\n}\n\n\/**\n* @brief\n* Create keyboard handler to control the wrapped OSG scene\n*\/\nOsgKeyboardHandler * OsgRenderStage::createKeyboardHandler() const\n{\n if (m_embedded) {\n return new OsgKeyboardHandler(m_embedded);\n } else {\n return nullptr;\n }\n}\n\n\/**\n* @brief\n* Create mouse handler to control the wrapped OSG scene\n*\/\nOsgMouseHandler * OsgRenderStage::createMouseHandler() const\n{\n if (m_embedded) {\n return new OsgMouseHandler(m_embedded);\n } else {\n return nullptr;\n }\n}\n\nvoid OsgRenderStage::initialize()\n{\n osg_initialize();\n}\n\nvoid OsgRenderStage::process()\n{\n \/\/ Draw osg scene\n osg_process();\n}\n\n\n} \/\/ namespace gloperate_osg\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/ Generator for particle pairs in a preset\n\/\/ kinematic range \n\/\/ ranges can be set for invariant mass, pair pT, pair rapidity\n\/\/ and pair azimuth\n\n\/\/\n\/\/ Comments and suggestions: markus.konrad.kohler@cern.ch\n\/\/\n\n#include \"TPDGCode.h\"\n#include \n#include \"AliGenEventHeader.h\"\n#include \"TF1.h\"\n\n#include \"AliGenPairFlat.h\"\n\nClassImp(AliGenPairFlat)\n\n\/\/_____________________________________________________________________________\nAliGenPairFlat::AliGenPairFlat()\n :AliGenerator(), \n fPairNpart(10),\n fPairYMin(-10.),\n fPairYMax(10.),\n fPairPhiMin(0.),\n fPairPhiMax(TMath::TwoPi()),\n fPairPtMin(0.001),\n fPairPtMax(50.),\n fPairMassMin(0.),\n fPairMassMax(10.),\n fLegPdg1(11),\n fLegPdg2(-11),\n fAlpha(0.),\n fDebug(0)\n{\n \/\/\n \/\/ Default constructor\n \/\/\n}\n\n\/\/_____________________________________________________________________________\nvoid AliGenPairFlat::Generate()\n{\n \/\/\n \/\/ Generate a random pair of particles\n \/\/\n \n Float_t polar[3]= {0,0,0};\n Float_t origin[3];\n Float_t time;\n\n Float_t p[3];\n Int_t i, j, nt;\n Double_t phi, y, mass, mt, e, pt;\n Float_t weight = 1.;\n Double_t pt1, pt2, y1, y2;\n\n TLorentzVector mother, dau1, dau2;\n Float_t random[6];\n\n\/\/ TF1* fPol = new TF1(\"fPol\",\"1.+[0]*x*x\",-1.,1.);\n TF1 fPol(\"fPol\",\"1.+[0]*x*x\",-1.,1.);\n fPol.SetParameter(0,fAlpha);\n\n\n for (j=0;j<3;j++) origin[j]=fOrigin[j];\n time = fTimeOrigin;\n if(fVertexSmear==kPerEvent) {\n\tVertex();\n\tfor (j=0;j<3;j++) origin[j]=fVertex[j];\n\ttime = fTime;\n }\n\n\tprintf(\"\\n\\n------------------GENERATOR SETTINGS------------------\\n\\n\");\n\tprintf(\"You choosed for the mother the Mass range %f - %f \\n\",fPairMassMin,fPairMassMax);\n\tprintf(\"You choosed for the mother the transverse Momentum range %f - %f \\n\",fPairPtMin,fPairPtMax);\n\tprintf(\"You choosed for the mother the Phi range %f - %f \\n\",fPairPhiMin,fPairPhiMax);\n\tprintf(\"The Particle will decay in (pdg) %i and %i\\n \\n\",fLegPdg1, fLegPdg2);\n\tprintf(\"The rest Mass of first daughter (%s) is %f \\n\",\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->GetTitle(),\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass());\n\tprintf(\"The rest Mass of second daughter (%s) is %f \\n\",\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->GetTitle(),\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass());\n\tprintf(\"polarization factor is alpha == %lf \\n\",fAlpha);\n\tprintf(\"vertex is at x == %f || y == %f || z == %f \\n\",origin[0],origin[1],origin[2]);\n\tprintf(\"\\n----------------------------------------------------------\\n\");\n\n\n for(i=0;iid=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\\n\",fLegPdg1,p[0],p[1],p[2],pt1,weight,e);\n\n\t\/\/second daughter\n\tp[0] = dau2.Px();\n\tp[1] = dau2.Py();\n\tp[2] = dau2.Pz();\n\te = dau2.E();\n\n\tif(fVertexSmear==kPerTrack) {\n\t Rndm(random,6);\n\t for (j=0;j<3;j++) {\n\t\torigin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*\n\t\t TMath::Sqrt(-2*TMath::Log(random[2*j+1]));\n\t }\n\n\t Rndm(random,2);\n\t time = fTimeOrigin + fOsigma[2]\/TMath::Ccgs()*\n\t TMath::Cos(2*random[0]*TMath::Pi())*\n\t TMath::Sqrt(-2*TMath::Log(random[1]));\n\t}\n\n\tPushTrack(fTrackIt,-1,fLegPdg2,p,origin,polar,time,kPPrimary,nt,weight);\n if (fDebug == 2) printf(\"dau2-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\\n\",fLegPdg2,p[0],p[1],p[2],pt2, weight,e);\n\n }\/\/particle loop\n\n}\n\n\/\/_____________________________________________________________________________\n\nvoid AliGenPairFlat::Init()\n{\n\t\/\/\n\t\/\/ Init\n\t\/\/\n\n\tprintf(\"AliGenPairFlat::Init() not implemented!!!\\n\");\n\n}\n\n\n\/\/_____________________________________________________________________________\n\n\nBool_t AliGenPairFlat::Decay(TLorentzVector mother, TLorentzVector &dau1, TLorentzVector &dau2, TF1 polfactor)\n{\n\t\/\/\n\t\/\/ decay procedure\n\t\/\/\n\n\tDouble_t mp, md1, md2, ed1, ed2, pd1, pd2;\n\tDouble_t costheta, sintheta, phi;\n\n\tmp = mother.M();\n\tmd1 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass();\n\tmd2 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass();\n\n\tif(mp < md1+md2){\n\tprintf(\"Daughters are heavier than Mother!! Check Kinematics!! \\n\");\n\treturn 0;\n\t}\n\n ed1 = (mp*mp + md1*md1 - md2*md2)\/(2.*mp);\n ed2 = mp-ed1;\n pd1 = TMath::Sqrt((ed1+md1)*(ed1-md1));\n pd2 = TMath::Sqrt((mp*mp-(md1+md2)*(md1+md2))*(mp*mp -(md1-md2)*(md1-md2)))\/(2.*mp);\n\n costheta = polfactor.GetRandom(); \/\/polarization\n sintheta = TMath::Sqrt((1.+costheta)*(1.-costheta));\n phi = 2.0*TMath::Pi()*gRandom->Rndm();\n\n\tdau1.SetPxPyPzE(pd1*sintheta*TMath::Cos(phi), \n\t\t pd1*sintheta*TMath::Sin(phi), \n\t\t pd1*costheta,\n\t\t\ted1); \n\n\tdau2.SetPxPyPzE((-1.)*pd1*sintheta*TMath::Cos(phi),\n\t\t\t(-1.)*pd1*sintheta*TMath::Sin(phi), \n\t\t\t(-1.)*pd1*costheta,\n\t\t\ted2);\n\n \tTVector3 boost = mother.BoostVector();\n\n \tdau1.Boost(boost);\n \tdau2.Boost(boost);\n\n return 1;\n\n}\n\n\n\nFix for coverity 19211\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/ Generator for particle pairs in a preset\n\/\/ kinematic range \n\/\/ ranges can be set for invariant mass, pair pT, pair rapidity\n\/\/ and pair azimuth\n\n\/\/\n\/\/ Comments and suggestions: markus.konrad.kohler@cern.ch\n\/\/\n\n#include \"TPDGCode.h\"\n#include \n#include \"AliGenEventHeader.h\"\n#include \"TF1.h\"\n\n#include \"AliGenPairFlat.h\"\n\nClassImp(AliGenPairFlat)\n\n\/\/_____________________________________________________________________________\nAliGenPairFlat::AliGenPairFlat()\n :AliGenerator(), \n fPairNpart(10),\n fPairYMin(-10.),\n fPairYMax(10.),\n fPairPhiMin(0.),\n fPairPhiMax(TMath::TwoPi()),\n fPairPtMin(0.001),\n fPairPtMax(50.),\n fPairMassMin(0.),\n fPairMassMax(10.),\n fLegPdg1(11),\n fLegPdg2(-11),\n fAlpha(0.),\n fDebug(0)\n{\n \/\/\n \/\/ Default constructor\n \/\/\n}\n\n\/\/_____________________________________________________________________________\nvoid AliGenPairFlat::Generate()\n{\n \/\/\n \/\/ Generate a random pair of particles\n \/\/\n \n Float_t polar[3]= {0,0,0};\n Float_t origin[3];\n Float_t time;\n\n Float_t p[3];\n Int_t i, j, nt;\n Double_t phi, y, mass, mt, e, pt;\n Float_t weight = 1.;\n Double_t pt1, pt2, y1, y2;\n\n TLorentzVector mother, dau1, dau2;\n Float_t random[6];\n\n TF1* pol = new TF1(\"Pol\",\"1.+[0]*x*x\",-1.,1.);\n pol->SetParameter(0, fAlpha);\n\n\n for (j=0;j<3;j++) origin[j]=fOrigin[j];\n time = fTimeOrigin;\n if(fVertexSmear==kPerEvent) {\n\tVertex();\n\tfor (j=0;j<3;j++) origin[j]=fVertex[j];\n\ttime = fTime;\n }\n\n\tprintf(\"\\n\\n------------------GENERATOR SETTINGS------------------\\n\\n\");\n\tprintf(\"You choosed for the mother the Mass range %f - %f \\n\",fPairMassMin,fPairMassMax);\n\tprintf(\"You choosed for the mother the transverse Momentum range %f - %f \\n\",fPairPtMin,fPairPtMax);\n\tprintf(\"You choosed for the mother the Phi range %f - %f \\n\",fPairPhiMin,fPairPhiMax);\n\tprintf(\"The Particle will decay in (pdg) %i and %i\\n \\n\",fLegPdg1, fLegPdg2);\n\tprintf(\"The rest Mass of first daughter (%s) is %f \\n\",\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->GetTitle(),\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass());\n\tprintf(\"The rest Mass of second daughter (%s) is %f \\n\",\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->GetTitle(),\n\tTDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass());\n\tprintf(\"polarization factor is alpha == %lf \\n\",fAlpha);\n\tprintf(\"vertex is at x == %f || y == %f || z == %f \\n\",origin[0],origin[1],origin[2]);\n\tprintf(\"\\n----------------------------------------------------------\\n\");\n\n\n for(i=0;iid=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\\n\",fLegPdg1,p[0],p[1],p[2],pt1,weight,e);\n\n\t\/\/second daughter\n\tp[0] = dau2.Px();\n\tp[1] = dau2.Py();\n\tp[2] = dau2.Pz();\n\te = dau2.E();\n\n\tif(fVertexSmear==kPerTrack) {\n\t Rndm(random,6);\n\t for (j=0;j<3;j++) {\n\t\torigin[j]=fOrigin[j]+fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())*\n\t\t TMath::Sqrt(-2*TMath::Log(random[2*j+1]));\n\t }\n\n\t Rndm(random,2);\n\t time = fTimeOrigin + fOsigma[2]\/TMath::Ccgs()*\n\t TMath::Cos(2*random[0]*TMath::Pi())*\n\t TMath::Sqrt(-2*TMath::Log(random[1]));\n\t}\n\n\tPushTrack(fTrackIt,-1,fLegPdg2,p,origin,polar,time,kPPrimary,nt,weight);\n if (fDebug == 2) printf(\"dau2-->id=%+3d, p = (%+11.4e,%+11.4e,%+11.4e) GeV || pt = %+11.4e || weight=%+11.4e || E= %+11.4e\\n\",fLegPdg2,p[0],p[1],p[2],pt2, weight,e);\n\n }\/\/particle loop\n\n}\n\n\/\/_____________________________________________________________________________\n\nvoid AliGenPairFlat::Init()\n{\n\t\/\/\n\t\/\/ Init\n\t\/\/\n\n\tprintf(\"AliGenPairFlat::Init() not implemented!!!\\n\");\n\n}\n\n\n\/\/_____________________________________________________________________________\n\n\nBool_t AliGenPairFlat::Decay(TLorentzVector mother, TLorentzVector &dau1, TLorentzVector &dau2, TF1* polfactor)\n{\n\t\/\/\n\t\/\/ decay procedure\n\t\/\/\n\n\tDouble_t mp, md1, md2, ed1, ed2, pd1, pd2;\n\tDouble_t costheta, sintheta, phi;\n\n\tmp = mother.M();\n\tmd1 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg1))->Mass();\n\tmd2 = TDatabasePDG::Instance()->GetParticle(TMath::Abs(fLegPdg2))->Mass();\n\n\tif(mp < md1+md2){\n\tprintf(\"Daughters are heavier than Mother!! Check Kinematics!! \\n\");\n\treturn 0;\n\t}\n\n ed1 = (mp*mp + md1*md1 - md2*md2)\/(2.*mp);\n ed2 = mp-ed1;\n pd1 = TMath::Sqrt((ed1+md1)*(ed1-md1));\n pd2 = TMath::Sqrt((mp*mp-(md1+md2)*(md1+md2))*(mp*mp -(md1-md2)*(md1-md2)))\/(2.*mp);\n\n costheta = polfactor->GetRandom(); \/\/polarization\n sintheta = TMath::Sqrt((1.+costheta)*(1.-costheta));\n phi = 2.0*TMath::Pi()*gRandom->Rndm();\n\n\tdau1.SetPxPyPzE(pd1*sintheta*TMath::Cos(phi), \n\t\t pd1*sintheta*TMath::Sin(phi), \n\t\t pd1*costheta,\n\t\t\ted1); \n\n\tdau2.SetPxPyPzE((-1.)*pd1*sintheta*TMath::Cos(phi),\n\t\t\t(-1.)*pd1*sintheta*TMath::Sin(phi), \n\t\t\t(-1.)*pd1*costheta,\n\t\t\ted2);\n\n \tTVector3 boost = mother.BoostVector();\n\n \tdau1.Boost(boost);\n \tdau2.Boost(boost);\n\n return 1;\n\n}\n\n\n\n<|endoftext|>"} {"text":"replace memcmp with MagicCmp that supports '.' for single character of anything and add webp BUG=67987 TEST=omnibox can show webp from filer or harddrive when mimetype or extension is wrong<|endoftext|>"} {"text":"\n#include \"test.h\"\n#include \"include\/agg_array.h\"\n#include \"src\/include\/data_vector.h\"\n#include \"timeuse.h\"\n\nusing namespace picasso;\n\nstruct data_test \n{\n int i;\n float f;\n double d;\n};\n\nvolatile int tmp;\nstatic int dummy[4096000];\nstatic void clear_cache(void)\n{\n int sum = 0;\n for(int i=0; i<4096000; i++)\n dummy[i] = 2;\n for(int i=0; i<4096000; i++)\n sum += dummy[i];\n\n tmp = sum;\n}\n\nTEST(Pod_Vector, CreateAndDestroy)\n{\n pod_vector iv;\n\n pod_vector sv = iv;\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n \n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(0, (int)sv.capacity());\n\n EXPECT_NE(&iv , &sv);\n\n pod_vector dv(10);\n\n EXPECT_EQ(0, (int)dv.size());\n EXPECT_EQ(10, (int)dv.capacity());\n}\n\nTEST(Pod_Vector, PushAndInsert)\n{\n pod_vector iv;\n pod_vector sv;\n\n iv.resize(3);\n sv.resize(5);\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(3, (int)iv.capacity());\n \n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n \n bool b;\n b = iv.push_back(10);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(11);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(12);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(13);\n EXPECT_EQ(false, b);\n\n\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"copy vector iv to sv\\n\");\n sv = iv;\n\n EXPECT_EQ(3, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n EXPECT_EQ(true, sv.is_full());\n EXPECT_EQ(true, iv.is_full());\n\n for(unsigned int i = 0; i < sv.size(); i++)\n printf(\"sv: integer vector[%d] = %d\\n\",i, sv[i]);\n\n printf(\"resize iv to 6\\n\");\n iv.resize(6);\n for(unsigned int i = 0; i < iv.size(); i++) {\n EXPECT_EQ(sv[i], iv[i]);\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n }\n\n EXPECT_EQ(false, iv.is_full());\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n\n printf(\"insert value to index 2\\n\");\n b = iv.insert_at(2, 15);\n EXPECT_EQ(true, b);\n EXPECT_EQ(4, (int)iv.size());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"insert value to index 15\\n\");\n b = iv.insert_at(15, 15);\n EXPECT_EQ(false, b);\n EXPECT_EQ(4, (int)iv.size());\n\n EXPECT_NE(iv.data(), sv.data());\n\n printf(\"reset capacity sv\\n\");\n sv.capacity(1);\n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n sv.capacity(10);\n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(10, (int)sv.capacity());\n\n printf(\"cut at index 2\\n\");\n iv.cut_at(2);\n EXPECT_EQ(2, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"set data!\\n\");\n unsigned int data[] = {100, 200, 300};\n iv.set_data(3, data);\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"set data!\\n\");\n unsigned int data2[] = {50, 150, 250, 350, 450, 550 ,650, 750};\n iv.set_data(8, data2);\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n iv.resize(8);\n iv.set_data(8, data2);\n EXPECT_EQ(8, (int)iv.size());\n EXPECT_EQ(8, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n\n printf(\"clear iv\\n\");\n iv.clear();\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(8, (int)iv.capacity());\n}\n\n\nTEST(Pod_Vector, SpeedCompareWithAgg)\n{\n clocktime_t t1, t2;\n double u1, u2;\n\n pod_vector pv;\n pod_vector pdv;\n data_test d = {1,1,1};\n\n printf(\"pod_vector speed testing...\\n\");\n clear_cache();\n \/\/ picasso data vector speed.\n t1 = get_clock();\n\n pv.resize(10000);\n for(unsigned int i = 0; i < pv.size(); i++)\n pv.push_back(i);\n pv.clear();\n\n pdv.resize(10000);\n for(unsigned int i = 0; i < pdv.size(); i++)\n pdv.push_back(d);\n pdv.clear();\n t2 = get_clock();\n u1 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"picasso pod_vector use %f ms\\n\", u1);\n\n clear_cache();\n\n agg::pod_vector av;\n agg::pod_vector adv;\n \/\/ agg data vector speed.\n t1 = get_clock();\n\n av.resize(10000);\n for(unsigned int i = 0; i < av.size(); i++)\n av.push_back(i);\n av.clear();\n\n adv.resize(10000);\n for(unsigned int i = 0; i < adv.size(); i++)\n adv.push_back(d);\n adv.clear();\n\n t2 = get_clock();\n u2 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"agg pod_vector use %f ms\\n\", u2);\n\n clear_cache();\n\n EXPECT_EQ(true, u1<=u2);\n if (u1 <= u2)\n fprintf (stderr, \"picasso is faster!\\n\");\n else\n fprintf (stderr, \"agg is faster!\\n\");\n\n}\n\n\nTEST(Pod_BVector, SpeedCompareWithAgg)\n{\n clocktime_t t1, t2;\n double u1, u2;\n\n clear_cache();\n\n pod_bvector pv;\n pod_bvector pdv;\n data_test d = {1,1,1};\n\n printf(\"pod_bvector speed testing...\\n\");\n \/\/ picasso data vector speed.\n t1 = get_clock();\n\n for(unsigned int i = 0; i < 1000; i++)\n pv.add(i);\n pv.clear();\n\n for(unsigned int i = 0; i < 1000; i++)\n pdv.add(d);\n pdv.clear();\n\n t2 = get_clock();\n u1 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"picasso pod_bvector use %f ms\\n\", u1);\n\n clear_cache();\n\n agg::pod_bvector av;\n agg::pod_bvector pav;\n \/\/ agg data vector speed.\n t1 = get_clock();\n\n for(unsigned int i = 0; i < 1000; i++)\n av.add(i);\n av.remove_all();\n\n for(unsigned int i = 0; i < 1000; i++)\n pav.add(d);\n pav.remove_all();\n\n t2 = get_clock();\n u2 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"agg pod_bvector use %f ms\\n\", u2);\n\n clear_cache();\n\n EXPECT_EQ(true, u1<=u2);\n if (u1 <= u2)\n fprintf (stderr, \"picasso is faster!\\n\");\n else\n fprintf (stderr, \"agg is faster!\\n\");\n}\n\nTEST(Pod_BVector, BlockAndAutoSizeVector)\n{\n printf(\"create bvector size 0, capacity 0\\n\");\n pod_bvector iv;\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n\n printf(\"add datas\\n\");\n iv.add(10);\n iv.add(11);\n iv.add(12);\n\n printf(\"bvector size 3, capacity 32\\n\");\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n\n printf(\"add datas\\n\");\n iv.add(13);\n iv.add(14);\n\n printf(\"bvector size 5, capacity 32\\n\");\n EXPECT_EQ(5, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"remove last \\n\");\n iv.remove_last();\n\n printf(\"bvector size 4, capacity 32\\n\");\n EXPECT_EQ(4, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"remove all \\n\");\n iv.remove_all();\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n\n}\n\nTEST(Block_Allocater, BlockBaseAllocater)\n{\n printf(\"create a block allocater\\n\");\n block_allocator alloc(16384-16);\n\n printf(\"alloc 100 elements aligment 4\\n\");\n data_test* ds = (data_test*)alloc.allocate(sizeof(data_test)*256, 4);\n EXPECT_EQ(true, ds!=0);\n\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n\n data_test* ss = (data_test*)alloc.allocate(sizeof(data_test), 8); \n EXPECT_EQ(true, ss!=0);\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n\n printf(\"free all memory\\n\");\n alloc.remove_all();\n\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n}\n\nTEST(Pod_Array, CreateAndInitialize)\n{\n pod_array iv;\n pod_array sv = iv;\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)sv.size());\n\n EXPECT_NE(&iv , &sv);\n\n pod_array dv(10);\n EXPECT_EQ(10, (int)dv.size());\n}\n\nTEST(Pod_Array, SpeedCompareWithAgg)\n{\n clocktime_t t1, t2;\n double u1, u2;\n pod_array pv;\n\n printf(\"pod_array speed testing...\\n\");\n clear_cache();\n\n t1 = get_clock();\n\n for (int i = 1; i < 10000000; i++) {\n int s = (i%10) * 1024;\n pv.resize(s);\n pv[s-1] = i;\n }\n\n t2 = get_clock();\n u1 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"picasso pod_array use %f ms\\n\", u1);\n\n\n agg::pod_array av;\n clear_cache();\n\n t1 = get_clock();\n\n for (int i = 1; i < 10000000; i++) {\n int s = (i%10) * 1024;\n av.resize(s);\n av[s-1] = i;\n }\n\n t2 = get_clock();\n u2 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"agg pod_array use %f ms\\n\", u1);\n\n\n\n clear_cache();\n\n EXPECT_EQ(true, u1<=u2);\n if (u1 <= u2)\n fprintf (stderr, \"picasso is faster!\\n\");\n else\n fprintf (stderr, \"agg is faster!\\n\");\n}\nfix code\n#include \"test.h\"\n#include \"src\/include\/data_vector.h\"\n#include \"timeuse.h\"\n\nusing namespace picasso;\n\nstruct data_test \n{\n int i;\n float f;\n double d;\n};\n\nvolatile int tmp;\nstatic int dummy[4096000];\nstatic void clear_cache(void)\n{\n int sum = 0;\n for(int i=0; i<4096000; i++)\n dummy[i] = 2;\n for(int i=0; i<4096000; i++)\n sum += dummy[i];\n\n tmp = sum;\n}\n\nTEST(Pod_Vector, CreateAndDestroy)\n{\n pod_vector iv;\n\n pod_vector sv = iv;\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n \n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(0, (int)sv.capacity());\n\n EXPECT_NE(&iv , &sv);\n\n pod_vector dv(10);\n\n EXPECT_EQ(0, (int)dv.size());\n EXPECT_EQ(10, (int)dv.capacity());\n}\n\nTEST(Pod_Vector, PushAndInsert)\n{\n pod_vector iv;\n pod_vector sv;\n\n iv.resize(3);\n sv.resize(5);\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(3, (int)iv.capacity());\n \n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n \n bool b;\n b = iv.push_back(10);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(11);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(12);\n EXPECT_EQ(true, b);\n\n b = iv.push_back(13);\n EXPECT_EQ(false, b);\n\n\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"copy vector iv to sv\\n\");\n sv = iv;\n\n EXPECT_EQ(3, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n EXPECT_EQ(true, sv.is_full());\n EXPECT_EQ(true, iv.is_full());\n\n for(unsigned int i = 0; i < sv.size(); i++)\n printf(\"sv: integer vector[%d] = %d\\n\",i, sv[i]);\n\n printf(\"resize iv to 6\\n\");\n iv.resize(6);\n for(unsigned int i = 0; i < iv.size(); i++) {\n EXPECT_EQ(sv[i], iv[i]);\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n }\n\n EXPECT_EQ(false, iv.is_full());\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n\n printf(\"insert value to index 2\\n\");\n b = iv.insert_at(2, 15);\n EXPECT_EQ(true, b);\n EXPECT_EQ(4, (int)iv.size());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"insert value to index 15\\n\");\n b = iv.insert_at(15, 15);\n EXPECT_EQ(false, b);\n EXPECT_EQ(4, (int)iv.size());\n\n EXPECT_NE(iv.data(), sv.data());\n\n printf(\"reset capacity sv\\n\");\n sv.capacity(1);\n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(5, (int)sv.capacity());\n\n sv.capacity(10);\n EXPECT_EQ(0, (int)sv.size());\n EXPECT_EQ(10, (int)sv.capacity());\n\n printf(\"cut at index 2\\n\");\n iv.cut_at(2);\n EXPECT_EQ(2, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"set data!\\n\");\n unsigned int data[] = {100, 200, 300};\n iv.set_data(3, data);\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"set data!\\n\");\n unsigned int data2[] = {50, 150, 250, 350, 450, 550 ,650, 750};\n iv.set_data(8, data2);\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(6, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n iv.resize(8);\n iv.set_data(8, data2);\n EXPECT_EQ(8, (int)iv.size());\n EXPECT_EQ(8, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n\n printf(\"clear iv\\n\");\n iv.clear();\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(8, (int)iv.capacity());\n}\n\n\nTEST(Pod_Vector, SpeedCompareWithAgg)\n{\n clocktime_t t1, t2;\n double u1, u2;\n\n pod_vector pv;\n pod_vector pdv;\n data_test d = {1,1,1};\n\n printf(\"pod_vector speed testing...\\n\");\n clear_cache();\n \/\/ picasso data vector speed.\n t1 = get_clock();\n\n pv.resize(10000);\n for(unsigned int i = 0; i < pv.size(); i++)\n pv.push_back(i);\n pv.clear();\n\n pdv.resize(10000);\n for(unsigned int i = 0; i < pdv.size(); i++)\n pdv.push_back(d);\n pdv.clear();\n t2 = get_clock();\n u1 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"picasso pod_vector use %f ms\\n\", u1);\n\n clear_cache();\n\n agg::pod_vector av;\n agg::pod_vector adv;\n \/\/ agg data vector speed.\n t1 = get_clock();\n\n av.resize(10000);\n for(unsigned int i = 0; i < av.size(); i++)\n av.push_back(i);\n av.clear();\n\n adv.resize(10000);\n for(unsigned int i = 0; i < adv.size(); i++)\n adv.push_back(d);\n adv.clear();\n\n t2 = get_clock();\n u2 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"agg pod_vector use %f ms\\n\", u2);\n\n clear_cache();\n\n EXPECT_EQ(true, u1<=u2);\n if (u1 <= u2)\n fprintf (stderr, \"picasso is faster!\\n\");\n else\n fprintf (stderr, \"agg is faster!\\n\");\n\n}\n\n\nTEST(Pod_BVector, SpeedCompareWithAgg)\n{\n clocktime_t t1, t2;\n double u1, u2;\n\n clear_cache();\n\n pod_bvector pv;\n pod_bvector pdv;\n data_test d = {1,1,1};\n\n printf(\"pod_bvector speed testing...\\n\");\n \/\/ picasso data vector speed.\n t1 = get_clock();\n\n for(unsigned int i = 0; i < 1000; i++)\n pv.add(i);\n pv.clear();\n\n for(unsigned int i = 0; i < 1000; i++)\n pdv.add(d);\n pdv.clear();\n\n t2 = get_clock();\n u1 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"picasso pod_bvector use %f ms\\n\", u1);\n\n clear_cache();\n\n agg::pod_bvector av;\n agg::pod_bvector pav;\n \/\/ agg data vector speed.\n t1 = get_clock();\n\n for(unsigned int i = 0; i < 1000; i++)\n av.add(i);\n av.remove_all();\n\n for(unsigned int i = 0; i < 1000; i++)\n pav.add(d);\n pav.remove_all();\n\n t2 = get_clock();\n u2 = get_clock_used_ms(t1, t2);\n fprintf (stderr, \"agg pod_bvector use %f ms\\n\", u2);\n\n clear_cache();\n\n EXPECT_EQ(true, u1<=u2);\n if (u1 <= u2)\n fprintf (stderr, \"picasso is faster!\\n\");\n else\n fprintf (stderr, \"agg is faster!\\n\");\n}\n\nTEST(Pod_BVector, BlockAndAutoSizeVector)\n{\n printf(\"create bvector size 0, capacity 0\\n\");\n pod_bvector iv;\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n\n printf(\"add datas\\n\");\n iv.add(10);\n iv.add(11);\n iv.add(12);\n\n printf(\"bvector size 3, capacity 32\\n\");\n EXPECT_EQ(3, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n\n printf(\"add datas\\n\");\n iv.add(13);\n iv.add(14);\n\n printf(\"bvector size 5, capacity 32\\n\");\n EXPECT_EQ(5, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"remove last \\n\");\n iv.remove_last();\n\n printf(\"bvector size 4, capacity 32\\n\");\n EXPECT_EQ(4, (int)iv.size());\n EXPECT_EQ(32, (int)iv.capacity());\n for(unsigned int i = 0; i < iv.size(); i++)\n printf(\"iv: integer vector[%d] = %d\\n\",i, iv[i]);\n\n printf(\"remove all \\n\");\n iv.remove_all();\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)iv.capacity());\n\n}\n\nTEST(Block_Allocater, BlockBaseAllocater)\n{\n printf(\"create a block allocater\\n\");\n block_allocator alloc(16384-16);\n\n printf(\"alloc 100 elements aligment 4\\n\");\n data_test* ds = (data_test*)alloc.allocate(sizeof(data_test)*256, 4);\n EXPECT_EQ(true, ds!=0);\n\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n\n data_test* ss = (data_test*)alloc.allocate(sizeof(data_test), 8); \n EXPECT_EQ(true, ss!=0);\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n\n printf(\"free all memory\\n\");\n alloc.remove_all();\n\n printf(\"block memsize %d \\n\", alloc.all_mem_used());\n}\n\nTEST(Pod_Array, CreateAndInitialize)\n{\n pod_array iv;\n pod_array sv = iv;\n\n EXPECT_EQ(0, (int)iv.size());\n EXPECT_EQ(0, (int)sv.size());\n\n EXPECT_NE(&iv , &sv);\n\n pod_array dv(10);\n EXPECT_EQ(10, (int)dv.size());\n}\n\n<|endoftext|>"} {"text":"\/* --- Unitary test symmetric.cpp This code tests and compares three ways of\n * expressing symmetric matrices. In addition to the unitary validation (test\n * of the basic operations), the code is validating the computation\n * performances of each methods.\n *\n * The three methods are:\n * - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.\n * - Metapod Symmetric with LTI factorization.\n * - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.\n *\n * Expected time scores on a I7 2.1GHz:\n * - Eigen: 2.5us\n * - Metapod: 4us\n * - Pinocchio: 6us\n *\/\n\n#include \"pinocchio\/spatial\/fwd.hpp\"\n#include \"pinocchio\/spatial\/se3.hpp\"\n#include \"pinocchio\/tools\/timer.hpp\"\n\n#include \n#include \n\n#include \"pinocchio\/spatial\/symmetric3.hpp\"\n\n#include \nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d);\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(se3::Symmetric3);\n\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\nvoid timeSym3(const se3::Symmetric3 & S,\n\t const se3::Symmetric3::Matrix3 & R,\n\t se3::Symmetric3 & res)\n{\n res = S.rotate(R);\n}\n\nvoid testSym3()\n{\n using namespace se3;\n typedef Symmetric3::Matrix3 Matrix3;\n typedef Symmetric3::Vector3 Vector3;\n \n { \n \/\/ op(Matrix3)\n {\n Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n Symmetric3 S(M);\n assert( S.matrix().isApprox(M) );\n }\n\n \/\/ S += S\n {\n Symmetric3\n\tS = Symmetric3::Random(),\n\tS2 = Symmetric3::Random();\n Symmetric3 Scopy = S;\n S+=S2;\n assert( S.matrix().isApprox( S2.matrix()+Scopy.matrix()) );\n }\n\n \/\/ S + M\n {\n Symmetric3 S = Symmetric3::Random();\n Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n\n Symmetric3 S2 = S + M;\n assert( S2.matrix().isApprox( S.matrix()+M ));\n\n S2 = S - M;\n assert( S2.matrix().isApprox( S.matrix()-M ));\n }\n\n \/\/ S*v\n {\n Symmetric3 S = Symmetric3::Random();\n Vector3 v = Vector3::Random(); \n Vector3 Sv = S*v;\n assert( Sv.isApprox( S.matrix()*v ));\n }\n\n \/\/ Random\n for(int i=0;i<100;++i )\n {\n\tMatrix3 M = Matrix3::Random(); M = M*M.transpose();\n\tSymmetric3 S = Symmetric3::RandomPositive();\n\tVector3 v = Vector3::Random();\n\tassert( (v.transpose()*(S*v))[0] > 0);\n }\n\n \/\/ Identity\n { \n assert( Symmetric3::Identity().matrix().isApprox( Matrix3::Identity() ) );\n }\n\n \/\/ Skew2\n {\n Vector3 v = Vector3::Random();\n Symmetric3 vxvx = Symmetric3::SkewSquare(v);\n\n Vector3 p = Vector3::UnitX();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n p = Vector3::UnitY();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n p = Vector3::UnitZ();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n\n Matrix3 vx = skew(v);\n Matrix3 vxvx2 = (vx*vx).eval();\n assert( vxvx.matrix().isApprox(vxvx2) );\n\n Symmetric3 S = Symmetric3::RandomPositive();\n assert( (S-Symmetric3::SkewSquare(v)).matrix()\n\t .isApprox( S.matrix()-vxvx2 ) );\n double m = Eigen::internal::random()+1;\n assert( (S-m*Symmetric3::SkewSquare(v)).matrix()\n\t .isApprox( S.matrix()-m*vxvx2 ) );\n\n Symmetric3 S2 = S;\n S -= Symmetric3::SkewSquare(v);\n assert(S.matrix().isApprox( S2.matrix()-vxvx2 ) );\n S = S2; S -= m*Symmetric3::SkewSquare(v);\n assert(S.matrix().isApprox( S2.matrix()-m*vxvx2 ) );\n\n }\n\n \/\/ (i,j)\n {\n\tMatrix3 M = Matrix3::Random(); M = M*M.transpose();\n\tSymmetric3 S(M);\n\tfor(int i=0;i<3;++i)\n\t for(int j=0;j<3;++j)\n\t assert( S(i,j) == M(i,j) );\n }\n }\n\n \/\/ SRS\n {\n Symmetric3 S = Symmetric3::RandomPositive();\n Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix::Random())).normalized().matrix();\n \n Symmetric3 RSRt = S.rotate(R);\n assert( RSRt.matrix().isApprox( R*S.matrix()*R.transpose() ));\n\n Symmetric3 RtSR = S.rotate(R.transpose());\n assert( RtSR.matrix().isApprox( R.transpose()*S.matrix()*R ));\n }\n\n \/\/ Time test \n {\n const int NBT = 100000;\n Symmetric3 S = Symmetric3::RandomPositive();\n\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i::Random())).normalized().matrix();\n\n std::cout << \"Pinocchio: \";\n StackTicToc timer(StackTicToc::US); timer.tic();\n SMOOTH(NBT)\n {\n\ttimeSym3(S,Rs[_smooth],Sres[_smooth]);\n }\n timer.toc(std::cout,NBT);\n }\n}\n\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\n#ifdef WITH_METAPOD\n\n#include \n#include \n\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI);\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl);\n\nvoid timeLTI(const metapod::Spatial::ltI& S,\n\t const metapod::Spatial::RotationMatrixTpl& R, \n\t metapod::Spatial::ltI & res)\n{\n res = R.rotTSymmetricMatrix(S);\n}\n\nvoid testLTI()\n{\n using namespace metapod::Spatial;\n\n typedef ltI Sym3;\n typedef Eigen::Matrix3d Matrix3;\n typedef RotationMatrixTpl R3;\n\n Matrix3 M = Matrix3::Random();\n Sym3 S(M),S2;\n\n R3 R; R.randomInit();\n\n R.rotTSymmetricMatrix(S);\n timeLTI(S,R,S2);\n assert( S2.toMatrix().isApprox( R.toMatrix().transpose()*S.toMatrix()*R.toMatrix()) );\n \n const int NBT = 100000;\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i Sym3;\n Sym3 S(Sdense);\n ASA.triangularView()\n = A * S * A.transpose();\n}\n\nvoid testSelfAdj()\n{\n using namespace se3;\n typedef Eigen::Matrix3d Matrix3;\n typedef Eigen::SelfAdjointView Sym3;\n\n Matrix3 M = Matrix3::Random();\n Sym3 S(M);\n {\n Matrix3 Scp = S;\n assert( Scp-Scp.transpose()==Matrix3::Zero());\n }\n\n Matrix3 M2 = Matrix3::Random();\n M.triangularView() = M2;\n\n Matrix3 A = Matrix3::Random(), ASA1, ASA2;\n ASA1.triangularView() = A * S * A.transpose();\n timeSelfAdj(A,M,ASA2);\n\n {\n Matrix3 Masa1 = ASA1.selfadjointView();\n Matrix3 Masa2 = ASA2.selfadjointView();\n assert(Masa1.isApprox(Masa2));\n }\n\n const int NBT = 100000;\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i::Random())).normalized().matrix();\n\n std::cout << \"Eigen: \";\n StackTicToc timer(StackTicToc::US); timer.tic();\n SMOOTH(NBT)\n {\n timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);\n }\n timer.toc(std::cout,NBT);\n}\n\n\nint main()\n{\n testSelfAdj();\n testLTI();\n testSym3();\n \n return 0;\n}\n[Debug] Correct bug in Symmectric test that was preventing tests to compile (at least on ubutun 14.04 LTS)\/* --- Unitary test symmetric.cpp This code tests and compares three ways of\n * expressing symmetric matrices. In addition to the unitary validation (test\n * of the basic operations), the code is validating the computation\n * performances of each methods.\n *\n * The three methods are:\n * - Eigen SelfAdjoint (a mask atop of a classical dense matrix) ==> the least efficient.\n * - Metapod Symmetric with LTI factorization.\n * - Pinocchio rewritting of Metapod code with LTI factor as well and minor improvement.\n *\n * Expected time scores on a I7 2.1GHz:\n * - Eigen: 2.5us\n * - Metapod: 4us\n * - Pinocchio: 6us\n *\/\n\n#include \"pinocchio\/spatial\/fwd.hpp\"\n#include \"pinocchio\/spatial\/se3.hpp\"\n#include \"pinocchio\/tools\/timer.hpp\"\n\n#include \n#include \n\n#include \"pinocchio\/spatial\/symmetric3.hpp\"\n\n#include \nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(Eigen::Matrix3d);\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(se3::Symmetric3);\n\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\n\/* --- PINOCCHIO ------------------------------------------------------------ *\/\nvoid timeSym3(const se3::Symmetric3 & S,\n\t const se3::Symmetric3::Matrix3 & R,\n\t se3::Symmetric3 & res)\n{\n res = S.rotate(R);\n}\n\nvoid testSym3()\n{\n using namespace se3;\n typedef Symmetric3::Matrix3 Matrix3;\n typedef Symmetric3::Vector3 Vector3;\n \n { \n \/\/ op(Matrix3)\n {\n Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n Symmetric3 S(M);\n assert( S.matrix().isApprox(M) );\n }\n\n \/\/ S += S\n {\n Symmetric3\n\tS = Symmetric3::Random(),\n\tS2 = Symmetric3::Random();\n Symmetric3 Scopy = S;\n S+=S2;\n assert( S.matrix().isApprox( S2.matrix()+Scopy.matrix()) );\n }\n\n \/\/ S + M\n {\n Symmetric3 S = Symmetric3::Random();\n Matrix3 M = Matrix3::Random(); M = M*M.transpose();\n\n Symmetric3 S2 = S + M;\n assert( S2.matrix().isApprox( S.matrix()+M ));\n\n S2 = S - M;\n assert( S2.matrix().isApprox( S.matrix()-M ));\n }\n\n \/\/ S*v\n {\n Symmetric3 S = Symmetric3::Random();\n Vector3 v = Vector3::Random(); \n Vector3 Sv = S*v;\n assert( Sv.isApprox( S.matrix()*v ));\n }\n\n \/\/ Random\n for(int i=0;i<100;++i )\n {\n\tMatrix3 M = Matrix3::Random(); M = M*M.transpose();\n\tSymmetric3 S = Symmetric3::RandomPositive();\n\tVector3 v = Vector3::Random();\n\tassert( (v.transpose()*(S*v))[0] > 0);\n }\n\n \/\/ Identity\n { \n assert( Symmetric3::Identity().matrix().isApprox( Matrix3::Identity() ) );\n }\n\n \/\/ Skew2\n {\n Vector3 v = Vector3::Random();\n Symmetric3 vxvx = Symmetric3::SkewSquare(v);\n\n Vector3 p = Vector3::UnitX();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n p = Vector3::UnitY();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n p = Vector3::UnitZ();\n assert( (vxvx*p).isApprox( v.cross(v.cross(p)) ));\n\n Matrix3 vx = skew(v);\n Matrix3 vxvx2 = (vx*vx).eval();\n assert( vxvx.matrix().isApprox(vxvx2) );\n\n Symmetric3 S = Symmetric3::RandomPositive();\n assert( (S-Symmetric3::SkewSquare(v)).matrix()\n\t .isApprox( S.matrix()-vxvx2 ) );\n double m = Eigen::internal::random()+1;\n assert( (S-m*Symmetric3::SkewSquare(v)).matrix()\n\t .isApprox( S.matrix()-m*vxvx2 ) );\n\n Symmetric3 S2 = S;\n S -= Symmetric3::SkewSquare(v);\n assert(S.matrix().isApprox( S2.matrix()-vxvx2 ) );\n S = S2; S -= m*Symmetric3::SkewSquare(v);\n assert(S.matrix().isApprox( S2.matrix()-m*vxvx2 ) );\n\n }\n\n \/\/ (i,j)\n {\n\tMatrix3 M = Matrix3::Random(); M = M*M.transpose();\n\tSymmetric3 S(M);\n\tfor(int i=0;i<3;++i)\n\t for(int j=0;j<3;++j)\n\t assert( S(i,j) == M(i,j) );\n }\n }\n\n \/\/ SRS\n {\n Symmetric3 S = Symmetric3::RandomPositive();\n Matrix3 R = (Eigen::Quaterniond(Eigen::Matrix::Random())).normalized().matrix();\n \n Symmetric3 RSRt = S.rotate(R);\n assert( RSRt.matrix().isApprox( R*S.matrix()*R.transpose() ));\n\n Symmetric3 RtSR = S.rotate(R.transpose());\n assert( RtSR.matrix().isApprox( R.transpose()*S.matrix()*R ));\n }\n\n \/\/ Time test \n {\n const int NBT = 100000;\n Symmetric3 S = Symmetric3::RandomPositive();\n\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i::Random())).normalized().matrix();\n\n std::cout << \"Pinocchio: \";\n StackTicToc timer(StackTicToc::US); timer.tic();\n SMOOTH(NBT)\n {\n\ttimeSym3(S,Rs[_smooth],Sres[_smooth]);\n }\n timer.toc(std::cout,NBT);\n }\n}\n\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\/* --- METAPOD -------------------------------------------------------------- *\/\n\n#ifdef WITH_METAPOD\n\n#include \n#include \n\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::ltI);\nEIGEN_DEFINE_STL_VECTOR_SPECIALIZATION(metapod::Spatial::RotationMatrixTpl);\n\nvoid timeLTI(const metapod::Spatial::ltI& S,\n\t const metapod::Spatial::RotationMatrixTpl& R, \n\t metapod::Spatial::ltI & res)\n{\n res = R.rotTSymmetricMatrix(S);\n}\n\nvoid testLTI()\n{\n using namespace metapod::Spatial;\n\n typedef ltI Sym3;\n typedef Eigen::Matrix3d Matrix3;\n typedef RotationMatrixTpl R3;\n\n Matrix3 M = Matrix3::Random();\n Sym3 S(M),S2;\n\n R3 R; R.randomInit();\n\n R.rotTSymmetricMatrix(S);\n timeLTI(S,R,S2);\n assert( S2.toMatrix().isApprox( R.toMatrix().transpose()*S.toMatrix()*R.toMatrix()) );\n \n const int NBT = 100000;\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i Sym3;\n Sym3 S(Sdense);\n ASA.triangularView()\n = A * S * A.transpose();\n}\n\nvoid testSelfAdj()\n{\n using namespace se3;\n typedef Eigen::Matrix3d Matrix3;\n typedef Eigen::SelfAdjointView Sym3;\n\n Matrix3 M = Matrix3::Random();\n Sym3 S(M);\n {\n Matrix3 Scp = S;\n assert( Scp-Scp.transpose()==Matrix3::Zero());\n }\n\n Matrix3 M2 = Matrix3::Random();\n M.triangularView() = M2;\n\n Matrix3 A = Matrix3::Random(), ASA1, ASA2;\n ASA1.triangularView() = A * S * A.transpose();\n timeSelfAdj(A,M,ASA2);\n\n {\n Matrix3 Masa1 = ASA1.selfadjointView();\n Matrix3 Masa2 = ASA2.selfadjointView();\n assert(Masa1.isApprox(Masa2));\n }\n\n const int NBT = 100000;\n std::vector Sres (NBT);\n std::vector Rs (NBT);\n for(int i=0;i::Random())).normalized().matrix();\n\n std::cout << \"Eigen: \";\n StackTicToc timer(StackTicToc::US); timer.tic();\n SMOOTH(NBT)\n {\n timeSelfAdj(Rs[_smooth],M,Sres[_smooth]);\n }\n timer.toc(std::cout,NBT);\n}\n\n\nint main()\n{\n testSelfAdj();\n testLTI();\n testSym3();\n \n return 0;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2014, Randolph Voorhies, Shane Grant\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and\/or other materials provided with the distribution.\n* Neither the name of cereal nor the\nnames of its contributors may be used to endorse or promote products\nderived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"common.hpp\"\n#include \n\ntemplate \nvoid test_valarray()\n{\n\tstd::random_device rd;\n\tstd::mt19937 gen(rd());\n\n\tfor (int ii = 0; ii<100; ++ii)\n\t{\n\t\tstd::valarray o_podvalarray(100);\n\t\tfor (auto & elem : o_podvalarray)\n\t\t\telem = random_value(gen);\n\n\t\tstd::valarray o_iservalarray(100);\n\t\tfor (auto & elem : o_iservalarray)\n\t\t\telem = StructInternalSerialize(random_value(gen), random_value(gen));\n\n\t\tstd::valarray o_isplvalarray(100);\n\t\tfor (auto & elem : o_isplvalarray)\n\t\t\telem = StructInternalSplit(random_value(gen), random_value(gen));\n\n\t\tstd::valarray o_eservalarray(100);\n\t\tfor (auto & elem : o_eservalarray)\n\t\t\telem = StructExternalSerialize(random_value(gen), random_value(gen));\n\n\t\tstd::valarray o_esplvalarray(100);\n\t\tfor (auto & elem : o_esplvalarray)\n\t\t\telem = StructExternalSplit(random_value(gen), random_value(gen));\n\n\t\tstd::ostringstream os;\n\t\t{\n\t\t\tOArchive oar(os);\n\n\t\t\toar(o_podvalarray);\n\t\t\toar(o_iservalarray);\n\t\t\toar(o_isplvalarray);\n\t\t\toar(o_eservalarray);\n\t\t\toar(o_esplvalarray);\n\t\t}\n\n\t\tstd::valarray i_podvalarray;\n\t\tstd::valarray i_iservalarray;\n\t\tstd::valarray i_isplvalarray;\n\t\tstd::valarray i_eservalarray;\n\t\tstd::valarray i_esplvalarray;\n\n\t\tstd::istringstream is(os.str());\n\t\t{\n\t\t\tIArchive iar(is);\n\n\t\t\tiar(i_podvalarray);\n\t\t\tiar(i_iservalarray);\n\t\t\tiar(i_isplvalarray);\n\t\t\tiar(i_eservalarray);\n\t\t\tiar(i_esplvalarray);\n\t\t}\n\n\t\tBOOST_CHECK_EQUAL(i_podvalarray.size(), o_podvalarray.size());\n\t\tBOOST_CHECK_EQUAL(i_iservalarray.size(), o_iservalarray.size());\n\t\tBOOST_CHECK_EQUAL(i_isplvalarray.size(), o_isplvalarray.size());\n\t\tBOOST_CHECK_EQUAL(i_eservalarray.size(), o_eservalarray.size());\n\t\tBOOST_CHECK_EQUAL(i_esplvalarray.size(), o_esplvalarray.size());\n\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_podvalarray), std::end(i_podvalarray), std::begin(o_podvalarray), std::end(o_podvalarray));\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_iservalarray), std::end(i_iservalarray), std::begin(o_iservalarray), std::end(o_iservalarray));\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_isplvalarray), std::end(i_isplvalarray), std::begin(o_isplvalarray), std::end(o_isplvalarray));\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_eservalarray), std::end(i_eservalarray), std::begin(o_eservalarray), std::end(o_eservalarray));\n\t\tBOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_esplvalarray), std::end(i_esplvalarray), std::begin(o_esplvalarray), std::end(o_esplvalarray));\n\t}\n}\n\nBOOST_AUTO_TEST_CASE(binary_valarray)\n{\n\ttest_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(portable_binary_valarray)\n{\n\ttest_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(xml_valarray)\n{\n\ttest_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(json_valarray)\n{\n\ttest_valarray();\n}\nmore tab spacing fixes\/*\nCopyright (c) 2014, Randolph Voorhies, Shane Grant\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n* Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\nnotice, this list of conditions and the following disclaimer in the\ndocumentation and\/or other materials provided with the distribution.\n* Neither the name of cereal nor the\nnames of its contributors may be used to endorse or promote products\nderived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL RANDOLPH VOORHIES AND SHANE GRANT BE LIABLE FOR ANY\nDIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"common.hpp\"\n#include \n\ntemplate \nvoid test_valarray()\n{\n std::random_device rd;\n std::mt19937 gen(rd());\n\n for (int ii = 0; ii<100; ++ii)\n {\n std::valarray o_podvalarray(100);\n for (auto & elem : o_podvalarray)\n elem = random_value(gen);\n\n std::valarray o_iservalarray(100);\n for (auto & elem : o_iservalarray)\n elem = StructInternalSerialize(random_value(gen), random_value(gen));\n\n std::valarray o_isplvalarray(100);\n for (auto & elem : o_isplvalarray)\n elem = StructInternalSplit(random_value(gen), random_value(gen));\n\n std::valarray o_eservalarray(100);\n for (auto & elem : o_eservalarray)\n elem = StructExternalSerialize(random_value(gen), random_value(gen));\n\n std::valarray o_esplvalarray(100);\n for (auto & elem : o_esplvalarray)\n elem = StructExternalSplit(random_value(gen), random_value(gen));\n\n std::ostringstream os;\n {\n OArchive oar(os);\n\n oar(o_podvalarray);\n oar(o_iservalarray);\n oar(o_isplvalarray);\n oar(o_eservalarray);\n oar(o_esplvalarray);\n }\n\n std::valarray i_podvalarray;\n std::valarray i_iservalarray;\n std::valarray i_isplvalarray;\n std::valarray i_eservalarray;\n std::valarray i_esplvalarray;\n\n std::istringstream is(os.str());\n {\n IArchive iar(is);\n\n iar(i_podvalarray);\n iar(i_iservalarray);\n iar(i_isplvalarray);\n iar(i_eservalarray);\n iar(i_esplvalarray);\n }\n\n BOOST_CHECK_EQUAL(i_podvalarray.size(), o_podvalarray.size());\n BOOST_CHECK_EQUAL(i_iservalarray.size(), o_iservalarray.size());\n BOOST_CHECK_EQUAL(i_isplvalarray.size(), o_isplvalarray.size());\n BOOST_CHECK_EQUAL(i_eservalarray.size(), o_eservalarray.size());\n BOOST_CHECK_EQUAL(i_esplvalarray.size(), o_esplvalarray.size());\n\n BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_podvalarray), std::end(i_podvalarray), std::begin(o_podvalarray), std::end(o_podvalarray));\n BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_iservalarray), std::end(i_iservalarray), std::begin(o_iservalarray), std::end(o_iservalarray));\n BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_isplvalarray), std::end(i_isplvalarray), std::begin(o_isplvalarray), std::end(o_isplvalarray));\n BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_eservalarray), std::end(i_eservalarray), std::begin(o_eservalarray), std::end(o_eservalarray));\n BOOST_CHECK_EQUAL_COLLECTIONS(std::begin(i_esplvalarray), std::end(i_esplvalarray), std::begin(o_esplvalarray), std::end(o_esplvalarray));\n }\n}\n\nBOOST_AUTO_TEST_CASE(binary_valarray)\n{\n test_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(portable_binary_valarray)\n{\n test_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(xml_valarray)\n{\n test_valarray();\n}\n\nBOOST_AUTO_TEST_CASE(json_valarray)\n{\n test_valarray();\n}\n<|endoftext|>"} {"text":"#pragma once\n\/**\n\t@file\n\t@brief a class to get top n score\n\t@author MITSUNARI Shigeo(@herumi)\n*\/\n#include \n\nnamespace cybozu { namespace nlp {\n\n\/*\n\tT is int, size_t or pointer to object\n*\/\ntemplate\nclass TopScore {\npublic:\n\tstruct Pair {\n\t\tDouble score;\n\t\tT idx;\n\t};\n\ttypedef std::vector Table;\nprivate:\n\tconst size_t maxSize_;\n\tsize_t size_;\n\tmutable Table tbl_;\n\tTopScore(const TopScore&);\n\tvoid operator=(const TopScore&);\npublic:\n\texplicit TopScore(size_t maxSize = 10)\n\t\t: maxSize_(maxSize)\n\t\t, size_(0)\n\t{\n\t\ttbl_.resize(maxSize_);\n\t}\n\tvoid setSize(size_t maxSize)\n\t{\n\t\tmaxSize_ = maxSize;\n\t\tsize_ = 0;\n\t\ttbl_.clear();\n\t}\n\tvoid add(Double score, T idx)\n\t{\n\t\t\/\/ short cut\n\t\tif (size_ == maxSize_ && score <= tbl_[size_ - 1].score) {\n\t\t\treturn;\n\t\t}\n\t\tint pos = -1;\n\t\tif (size_ > 0) {\n\t\t\tfor (size_t i = 0; i < size_; i++) {\n\t\t\t\tif (score > tbl_[i].score) {\n\t\t\t\t\tint end = (int)std::min(maxSize_ - 2, size_ - 1);\n\t\t\t\t\tfor (int j = end; j >= (int)i; j--) {\n\t\t\t\t\t\ttbl_[j + 1] = tbl_[j];\n\t\t\t\t\t}\n\t\t\t\t\tpos = (int)i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (size_ < maxSize_) {\n\t\t\tif (pos < 0) pos = (int)size_;\n\t\t\tsize_++;\n\t\t}\n\t\tif (pos == -1) return;\n\t\ttbl_[pos].score = score;\n\t\ttbl_[pos].idx = idx;\n\t}\n\tconst Table& getTable() const\n\t{\n\t\ttbl_.resize(size_);\n\t\treturn tbl_;\n\t}\n};\n\n} } \/\/ cybozu::nlp\nremove const#pragma once\n\/**\n\t@file\n\t@brief a class to get top n score\n\t@author MITSUNARI Shigeo(@herumi)\n*\/\n#include \n\nnamespace cybozu { namespace nlp {\n\n\/*\n\tT is int, size_t or pointer to object\n*\/\ntemplate\nclass TopScore {\npublic:\n\tstruct Pair {\n\t\tDouble score;\n\t\tT idx;\n\t};\n\ttypedef std::vector Table;\nprivate:\n\tsize_t maxSize_;\n\tsize_t size_;\n\tmutable Table tbl_;\n\tTopScore(const TopScore&);\n\tvoid operator=(const TopScore&);\npublic:\n\texplicit TopScore(size_t maxSize = 10)\n\t\t: maxSize_(maxSize)\n\t\t, size_(0)\n\t{\n\t\ttbl_.resize(maxSize_);\n\t}\n\tvoid setSize(size_t maxSize)\n\t{\n\t\tmaxSize_ = maxSize;\n\t\tsize_ = 0;\n\t\ttbl_.clear();\n\t}\n\tvoid add(Double score, T idx)\n\t{\n\t\t\/\/ short cut\n\t\tif (size_ == maxSize_ && score <= tbl_[size_ - 1].score) {\n\t\t\treturn;\n\t\t}\n\t\tint pos = -1;\n\t\tif (size_ > 0) {\n\t\t\tfor (size_t i = 0; i < size_; i++) {\n\t\t\t\tif (score > tbl_[i].score) {\n\t\t\t\t\tint end = (int)std::min(maxSize_ - 2, size_ - 1);\n\t\t\t\t\tfor (int j = end; j >= (int)i; j--) {\n\t\t\t\t\t\ttbl_[j + 1] = tbl_[j];\n\t\t\t\t\t}\n\t\t\t\t\tpos = (int)i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (size_ < maxSize_) {\n\t\t\tif (pos < 0) pos = (int)size_;\n\t\t\tsize_++;\n\t\t}\n\t\tif (pos == -1) return;\n\t\ttbl_[pos].score = score;\n\t\ttbl_[pos].idx = idx;\n\t}\n\tconst Table& getTable() const\n\t{\n\t\ttbl_.resize(size_);\n\t\treturn tbl_;\n\t}\n};\n\n} } \/\/ cybozu::nlp\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef JSON_LOGGER_HPP\n#define JSON_LOGGER_HPP\n\n#include \n\n#include \n\nnamespace osrm\n{\nnamespace json\n{\n\n\/\/ Used to append additional debugging information to the JSON response in a\n\/\/ thread safe manner.\nclass Logger\n{\n using MapT = std::unordered_map;\n\n public:\n static Logger* get()\n {\n static Logger logger;\n\n bool return_logger = true;\n#ifdef NDEBUG\n return_logger = false;\n#endif\n#ifdef ENABLE_JSON_LOGGING\n return_logger = true;\n#endif\n\n if (return_logger)\n {\n return &logger;\n }\n\n return nullptr;\n }\n\n void initialize(const std::string& name)\n {\n if (!map.get())\n {\n map.reset(new MapT());\n }\n (*map)[name] = Object();\n }\n\n void render(const std::string& name, Object& obj) const\n {\n obj.values[\"debug\"] = map->at(name);\n }\n\n boost::thread_specific_ptr map;\n};\n\n\n}\n}\n\n#endif \/* JSON_LOGGER_HPP *\/\nDo not include Boost.Thread is a sub-header is good enough.\/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef JSON_LOGGER_HPP\n#define JSON_LOGGER_HPP\n\n#include \n\n#include \n\n#include \n#include \n\nnamespace osrm\n{\nnamespace json\n{\n\n\/\/ Used to append additional debugging information to the JSON response in a\n\/\/ thread safe manner.\nclass Logger\n{\n using MapT = std::unordered_map;\n\n public:\n static Logger* get()\n {\n static Logger logger;\n\n bool return_logger = true;\n#ifdef NDEBUG\n return_logger = false;\n#endif\n#ifdef ENABLE_JSON_LOGGING\n return_logger = true;\n#endif\n\n if (return_logger)\n {\n return &logger;\n }\n\n return nullptr;\n }\n\n void initialize(const std::string& name)\n {\n if (!map.get())\n {\n map.reset(new MapT());\n }\n (*map)[name] = Object();\n }\n\n void render(const std::string& name, Object& obj) const\n {\n obj.values[\"debug\"] = map->at(name);\n }\n\n boost::thread_specific_ptr map;\n};\n\n\n}\n}\n\n#endif \/* JSON_LOGGER_HPP *\/\n<|endoftext|>"} {"text":"#ifndef HERMIT_TASK_REMAPPER_HPP\n#define HERMIT_TASK_REMAPPER_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef BOOST_NO_0X_HDR_FUTURE\n#include \n#include \n#include \n#else\n# ifdef BOOST_NO_LAMBDAS\n#include \n# endif\n#include \n#endif\n\nnamespace hermit {\n class poller_core {\n public:\n template< typename Func >\n poller_core( boost::asio::io_service &service, Func func,\n boost::posix_time::milliseconds time\n ) : timer( service ), task( func ), interval( time ) {\n timer.expires_from_now( interval );\n timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );\n }\n void timeout( const boost::system::error_code &error ) {\n if( !error ) {\n task();\n timer.expires_from_now( interval );\n timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );\n }\n }\n private:\n boost::asio::deadline_timer timer;\n std::function< void() > task;\n boost::posix_time::milliseconds interval;\n };\n\n class poller {\n public:\n template< typename Func >\n poller( boost::asio::io_service &service_, Func func,\n boost::posix_time::milliseconds time\n ) : core( new poller_core( service_, func, time ) ) {}\n private:\n std::shared_ptr< poller_core > core;\n };\n\n class task_remapper {\n public:\n task_remapper( size_t size ) {\n work.reset( new boost::asio::io_service::work( task_queue ) );\n for( int count = 0; count != size; ++count ) {\n#ifdef BOOST_NO_0X_HDR_FUTURE\n end_sync.create_thread( std::bind( &task_remapper::run, this ) );\n#else\n# ifdef BOOST_NO_LAMBDAS\n end_sync.push_back( std::async( std::launch::async, std::bind( &task_remapper::run, this ) ) );\n# else\n end_sync.push_back( std::async( std::launch::async, [&]() { this->run(); } ) );\n# endif\n#endif\n }\n }\n#ifdef BOOST_NO_DELETED_FUNCTIONS\n private:\n task_remapper( const task_remapper& );\n task_remapper& operator=( const task_remapper& );\n public:\n#else\n task_remapper( const task_remapper& ) = delete;\n task_remapper& operator=( const task_remapper& ) = delete;\n#endif \n ~task_remapper() {\n work.reset();\n#ifdef BOOST_NO_0X_HDR_FUTURE\n end_sync.join_all();\n#else\n for( auto &elem: end_sync )\n elem.get();\n#endif\n }\n template< typename T >\n void post( T func ) {\n task_queue.post( func );\n }\n template< typename T, typename Time >\n poller post( T func, Time time ) {\n return poller( task_queue, func, time );\n }\n template< typename T >\n void set_epilogue( T func ) {\n epilogue.post( func );\n }\n void sync() {\n#ifdef BOOST_NO_0X_HDR_FUTURE\n std::shared_ptr< boost::thread::promise< void > > signal( new boost::thread::promise< void >() );\n#else\n std::shared_ptr< std::promise< void > > signal( new std::promise< void >() );\n#endif\n task_queue.post( [=](){ signal->set_value(); } );\n signal->get_future().wait();\n }\n private:\n static void null_epilogue() {}\n void run() noexcept {\n try {\n std::cout << \"hoge\" << std::endl;\n task_queue.run();\n epilogue.run();\n } catch ( std::exception &e ) {\n std::cerr << \"An exception was thrown from queued tasks. : \" << e.what() << std::endl;\n std::cerr << \"Aborting.\" << std::endl;\n std::abort();\n } catch ( ... ) {\n std::cerr << \"An exception was thrown from queued tasks.\" << std::endl;\n std::cerr << \"Aborting.\" << std::endl;\n std::abort();\n }\n }\n std::unique_ptr work;\n boost::asio::io_service task_queue;\n boost::asio::io_service epilogue;\n#ifdef BOOST_NO_0X_HDR_FUTURE\n boost::thread_group end_sync;\n#else\n std::vector< std::future< void > > end_sync;\n#endif\n };\n}\n\n#endif\ntask_remapperのC++03対応#ifndef HERMIT_TASK_REMAPPER_HPP\n#define HERMIT_TASK_REMAPPER_HPP\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef BOOST_NO_0X_HDR_FUTURE\n#include \n#include \n#include \n#else\n# ifdef BOOST_NO_LAMBDAS\n#include \n# endif\n#include \n#endif\n\nnamespace hermit {\n class poller_core {\n public:\n template< typename Func >\n poller_core( boost::asio::io_service &service, Func func,\n boost::posix_time::milliseconds time\n ) : timer( service ), task( func ), interval( time ) {\n timer.expires_from_now( interval );\n timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );\n }\n void timeout( const boost::system::error_code &error ) {\n if( !error ) {\n task();\n timer.expires_from_now( interval );\n timer.async_wait( boost::bind( &poller_core::timeout, this, boost::asio::placeholders::error ) );\n }\n }\n private:\n boost::asio::deadline_timer timer;\n std::function< void() > task;\n boost::posix_time::milliseconds interval;\n };\n\n class poller {\n public:\n template< typename Func >\n poller( boost::asio::io_service &service_, Func func,\n boost::posix_time::milliseconds time\n ) : core( new poller_core( service_, func, time ) ) {}\n private:\n std::shared_ptr< poller_core > core;\n };\n\n class task_remapper {\n public:\n task_remapper( size_t size ) {\n work.reset( new boost::asio::io_service::work( task_queue ) );\n for( int count = 0; count != size; ++count ) {\n#ifdef BOOST_NO_0X_HDR_FUTURE\n end_sync.create_thread( std::bind( &task_remapper::run, this ) );\n#else\n# ifdef BOOST_NO_LAMBDAS\n end_sync.push_back( std::async( std::launch::async, std::bind( &task_remapper::run, this ) ) );\n# else\n end_sync.push_back( std::async( std::launch::async, [&]() { this->run(); } ) );\n# endif\n#endif\n }\n }\n#ifdef BOOST_NO_DELETED_FUNCTIONS\n private:\n task_remapper( const task_remapper& );\n task_remapper& operator=( const task_remapper& );\n public:\n#else\n task_remapper( const task_remapper& ) = delete;\n task_remapper& operator=( const task_remapper& ) = delete;\n#endif \n ~task_remapper() {\n work.reset();\n#ifdef BOOST_NO_0X_HDR_FUTURE\n end_sync.join_all();\n#else\n for(\n std::vector< std::future< void > >::iterator iter = end_sync.begin();\n iter != end_sync.end(); ++iter\n ) iter->get();\n#endif\n }\n template< typename T >\n void post( T func ) {\n task_queue.post( func );\n }\n template< typename T, typename Time >\n poller post( T func, Time time ) {\n return poller( task_queue, func, time );\n }\n template< typename T >\n void set_epilogue( T func ) {\n epilogue.post( func );\n }\n void sync() {\n#ifdef BOOST_NO_0X_HDR_FUTURE\n std::shared_ptr< boost::thread::promise< void > > signal( new boost::thread::promise< void >() );\n#else\n std::shared_ptr< std::promise< void > > signal( new std::promise< void >() );\n#endif\n#ifdef BOOST_NO_LAMBDAS\n# ifdef BOOST_NO_0X_HDR_FUTURE\n task_queue.post( std::bind( &boost::thread::promise< void >::set_value, signal ) );\n# else\n task_queue.post( std::bind( &std::promise< void >::set_value, signal ) );\n#else\n task_queue.post( [=](){ signal->set_value(); } );\n#endif\n signal->get_future().wait();\n }\n private:\n static void null_epilogue() {}\n#ifdef BOOST_NO_NOEXCEPT\n void run() {\n#else\n void run() noexcept {\n#endif\n try {\n task_queue.run();\n epilogue.run();\n } catch ( std::exception &e ) {\n std::cerr << \"An exception was thrown from queued tasks. : \" << e.what() << std::endl;\n std::cerr << \"Aborting.\" << std::endl;\n std::abort();\n } catch ( ... ) {\n std::cerr << \"An exception was thrown from queued tasks.\" << std::endl;\n std::cerr << \"Aborting.\" << std::endl;\n std::abort();\n }\n }\n std::unique_ptr work;\n boost::asio::io_service task_queue;\n boost::asio::io_service epilogue;\n#ifdef BOOST_NO_0X_HDR_FUTURE\n boost::thread_group end_sync;\n#else\n std::vector< std::future< void > > end_sync;\n#endif\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_XML_PARSE_HPP\n#define TORRENT_XML_PARSE_HPP\n\n#include \n#include \n\n#include \"libtorrent\/escape_string.hpp\"\n\nnamespace libtorrent\n{\n\tenum\n\t{\n\t\txml_start_tag,\n\t\txml_end_tag,\n\t\txml_empty_tag,\n\t\txml_declaration_tag,\n\t\txml_string,\n\t\txml_attribute,\n\t\txml_comment,\n\t\txml_parse_error\n\t};\n\n\t\/\/ callback(int type, char const* name, char const* val)\n\t\/\/ str2 is only used for attributes. name is element or attribute\n\t\/\/ name and val is attribute value\n\n\ttemplate \t\n\tvoid xml_parse(char* p, char* end, CallbackType callback)\n\t{\n\t\tfor(;p != end; ++p)\n\t\t{\n\t\t\tchar const* start = p;\n\t\t\tchar const* val_start = 0;\n\t\t\tint token;\n\t\t\t\/\/ look for tag start\n\t\t\tfor(; *p != '<' && p != end; ++p);\n\n\t\t\tif (p != start)\n\t\t\t{\n\t\t\t\tif (p != end)\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(*p == '<');\n\t\t\t\t\t*p = 0;\n\t\t\t\t}\n\t\t\t\ttoken = xml_string;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tif (p != end) *p = '<';\n\t\t\t}\n\n\t\t\tif (p == end) break;\n\t\t\n\t\t\t\/\/ skip '<'\n\t\t\t++p;\n\t\t\tif (p != end && p+8 < end && string_begins_no_case(\"![CDATA[\", p))\n\t\t\t{\n\t\t\t\t\/\/ CDATA. match '![CDATA['\n\t\t\t\tp += 8;\n\t\t\t\tstart = p;\n\t\t\t\twhile (p != end && !string_begins_no_case(\"]]>\", p-2)) ++p;\n\n\t\t\t\t\/\/ parse error\n\t\t\t\tif (p == end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tstart = \"unexpected end of file\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\n\t\t\t\ttoken = xml_string;\n\t\t\t\tchar tmp = p[-2];\n\t\t\t\tp[-2] = 0;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tp[-2] = tmp;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ parse the name of the tag.\n\t\t\tfor (start = p; p != end && *p != '>' && !is_space(*p); ++p);\n\n\t\t\tchar* tag_name_end = p;\n\n\t\t\t\/\/ skip the attributes for now\n\t\t\tfor (; p != end && *p != '>'; ++p);\n\n\t\t\t\/\/ parse error\n\t\t\tif (p == end)\n\t\t\t{\n\t\t\t\ttoken = xml_parse_error;\n\t\t\t\tstart = \"unexpected end of file\";\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tTORRENT_ASSERT(*p == '>');\n\t\t\t\/\/ save the character that terminated the tag name\n\t\t\t\/\/ it could be both '>' and ' '.\n\t\t\tchar save = *tag_name_end;\n\t\t\t*tag_name_end = 0;\n\n\t\t\tchar* tag_end = p;\n\t\t\tif (*start == '\/')\n\t\t\t{\n\t\t\t\t++start;\n\t\t\t\ttoken = xml_end_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t}\n\t\t\telse if (*(p-1) == '\/')\n\t\t\t{\n\t\t\t\t*(p-1) = 0;\n\t\t\t\ttoken = xml_empty_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-1) = '\/';\n\t\t\t\ttag_end = p - 1;\n\t\t\t}\n\t\t\telse if (*start == '?' && *(p-1) == '?')\n\t\t\t{\n\t\t\t\t*(p-1) = 0;\n\t\t\t\t++start;\n\t\t\t\ttoken = xml_declaration_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-1) = '?';\n\t\t\t\ttag_end = p - 1;\n\t\t\t}\n\t\t\telse if (start + 5 < p && std::memcmp(start, \"!--\", 3) == 0 && std::memcmp(p-2, \"--\", 2) == 0)\n\t\t\t{\n\t\t\t\tstart += 3;\n\t\t\t\t*(p-2) = 0;\n\t\t\t\ttoken = xml_comment;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-2) = '-';\n\t\t\t\ttag_end = p - 2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttoken = xml_start_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t}\n\n\t\t\t*tag_name_end = save;\n\n\t\t\t\/\/ parse attributes\n\t\t\tfor (char* i = tag_name_end; i < tag_end; ++i)\n\t\t\t{\n\t\t\t\t\/\/ find start of attribute name\n\t\t\t\tfor (; i != tag_end && isspace(*i); ++i);\n\t\t\t\tif (i == tag_end) break;\n\t\t\t\tstart = i;\n\t\t\t\t\/\/ find end of attribute name\n\t\t\t\tfor (; i != tag_end && *i != '=' && !isspace(*i); ++i);\n\t\t\t\tchar* name_end = i;\n\n\t\t\t\t\/\/ look for equality sign\n\t\t\t\tfor (; i != tag_end && *i != '='; ++i);\n\n\t\t\t\tif (i == tag_end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"garbage inside element brackets\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t++i;\n\t\t\t\tfor (; i != tag_end && isspace(*i); ++i);\n\t\t\t\t\/\/ check for parse error (values must be quoted)\n\t\t\t\tif (i == tag_end || (*i != '\\'' && *i != '\\\"'))\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"unquoted attribute value\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tchar quote = *i;\n\t\t\t\t++i;\n\t\t\t\tval_start = i;\n\t\t\t\tfor (; i != tag_end && *i != quote; ++i);\n\t\t\t\t\/\/ parse error (missing end quote)\n\t\t\t\tif (i == tag_end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"missing end quote on attribute\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsave = *i;\n\t\t\t\t*i = 0;\n\t\t\t\t*name_end = 0;\n\t\t\t\ttoken = xml_attribute;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*name_end = '=';\n\t\t\t\t*i = save;\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\n#endif\n\nreplace calls to isspace() with is_space() to avoid asserts in the CRT\/*\n\nCopyright (c) 2007, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#ifndef TORRENT_XML_PARSE_HPP\n#define TORRENT_XML_PARSE_HPP\n\n#include \n#include \n\n#include \"libtorrent\/escape_string.hpp\"\n\nnamespace libtorrent\n{\n\tenum\n\t{\n\t\txml_start_tag,\n\t\txml_end_tag,\n\t\txml_empty_tag,\n\t\txml_declaration_tag,\n\t\txml_string,\n\t\txml_attribute,\n\t\txml_comment,\n\t\txml_parse_error\n\t};\n\n\t\/\/ callback(int type, char const* name, char const* val)\n\t\/\/ str2 is only used for attributes. name is element or attribute\n\t\/\/ name and val is attribute value\n\n\ttemplate \t\n\tvoid xml_parse(char* p, char* end, CallbackType callback)\n\t{\n\t\tfor(;p != end; ++p)\n\t\t{\n\t\t\tchar const* start = p;\n\t\t\tchar const* val_start = 0;\n\t\t\tint token;\n\t\t\t\/\/ look for tag start\n\t\t\tfor(; *p != '<' && p != end; ++p);\n\n\t\t\tif (p != start)\n\t\t\t{\n\t\t\t\tif (p != end)\n\t\t\t\t{\n\t\t\t\t\tTORRENT_ASSERT(*p == '<');\n\t\t\t\t\t*p = 0;\n\t\t\t\t}\n\t\t\t\ttoken = xml_string;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tif (p != end) *p = '<';\n\t\t\t}\n\n\t\t\tif (p == end) break;\n\t\t\n\t\t\t\/\/ skip '<'\n\t\t\t++p;\n\t\t\tif (p != end && p+8 < end && string_begins_no_case(\"![CDATA[\", p))\n\t\t\t{\n\t\t\t\t\/\/ CDATA. match '![CDATA['\n\t\t\t\tp += 8;\n\t\t\t\tstart = p;\n\t\t\t\twhile (p != end && !string_begins_no_case(\"]]>\", p-2)) ++p;\n\n\t\t\t\t\/\/ parse error\n\t\t\t\tif (p == end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tstart = \"unexpected end of file\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\n\t\t\t\ttoken = xml_string;\n\t\t\t\tchar tmp = p[-2];\n\t\t\t\tp[-2] = 0;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tp[-2] = tmp;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t\/\/ parse the name of the tag.\n\t\t\tfor (start = p; p != end && *p != '>' && !is_space(*p); ++p);\n\n\t\t\tchar* tag_name_end = p;\n\n\t\t\t\/\/ skip the attributes for now\n\t\t\tfor (; p != end && *p != '>'; ++p);\n\n\t\t\t\/\/ parse error\n\t\t\tif (p == end)\n\t\t\t{\n\t\t\t\ttoken = xml_parse_error;\n\t\t\t\tstart = \"unexpected end of file\";\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t\n\t\t\tTORRENT_ASSERT(*p == '>');\n\t\t\t\/\/ save the character that terminated the tag name\n\t\t\t\/\/ it could be both '>' and ' '.\n\t\t\tchar save = *tag_name_end;\n\t\t\t*tag_name_end = 0;\n\n\t\t\tchar* tag_end = p;\n\t\t\tif (*start == '\/')\n\t\t\t{\n\t\t\t\t++start;\n\t\t\t\ttoken = xml_end_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t}\n\t\t\telse if (*(p-1) == '\/')\n\t\t\t{\n\t\t\t\t*(p-1) = 0;\n\t\t\t\ttoken = xml_empty_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-1) = '\/';\n\t\t\t\ttag_end = p - 1;\n\t\t\t}\n\t\t\telse if (*start == '?' && *(p-1) == '?')\n\t\t\t{\n\t\t\t\t*(p-1) = 0;\n\t\t\t\t++start;\n\t\t\t\ttoken = xml_declaration_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-1) = '?';\n\t\t\t\ttag_end = p - 1;\n\t\t\t}\n\t\t\telse if (start + 5 < p && std::memcmp(start, \"!--\", 3) == 0 && std::memcmp(p-2, \"--\", 2) == 0)\n\t\t\t{\n\t\t\t\tstart += 3;\n\t\t\t\t*(p-2) = 0;\n\t\t\t\ttoken = xml_comment;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*(p-2) = '-';\n\t\t\t\ttag_end = p - 2;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\ttoken = xml_start_tag;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t}\n\n\t\t\t*tag_name_end = save;\n\n\t\t\t\/\/ parse attributes\n\t\t\tfor (char* i = tag_name_end; i < tag_end; ++i)\n\t\t\t{\n\t\t\t\t\/\/ find start of attribute name\n\t\t\t\tfor (; i != tag_end && is_space(*i); ++i);\n\t\t\t\tif (i == tag_end) break;\n\t\t\t\tstart = i;\n\t\t\t\t\/\/ find end of attribute name\n\t\t\t\tfor (; i != tag_end && *i != '=' && !is_space(*i); ++i);\n\t\t\t\tchar* name_end = i;\n\n\t\t\t\t\/\/ look for equality sign\n\t\t\t\tfor (; i != tag_end && *i != '='; ++i);\n\n\t\t\t\tif (i == tag_end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"garbage inside element brackets\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t++i;\n\t\t\t\tfor (; i != tag_end && is_space(*i); ++i);\n\t\t\t\t\/\/ check for parse error (values must be quoted)\n\t\t\t\tif (i == tag_end || (*i != '\\'' && *i != '\\\"'))\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"unquoted attribute value\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tchar quote = *i;\n\t\t\t\t++i;\n\t\t\t\tval_start = i;\n\t\t\t\tfor (; i != tag_end && *i != quote; ++i);\n\t\t\t\t\/\/ parse error (missing end quote)\n\t\t\t\tif (i == tag_end)\n\t\t\t\t{\n\t\t\t\t\ttoken = xml_parse_error;\n\t\t\t\t\tval_start = 0;\n\t\t\t\t\tstart = \"missing end quote on attribute\";\n\t\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tsave = *i;\n\t\t\t\t*i = 0;\n\t\t\t\t*name_end = 0;\n\t\t\t\ttoken = xml_attribute;\n\t\t\t\tcallback(token, start, val_start);\n\t\t\t\t*name_end = '=';\n\t\t\t\t*i = save;\n\t\t\t}\n\t\t}\n\t}\n\n}\n\n\n#endif\n\n<|endoftext|>"} {"text":"\/*\n* Copyright 2018 NXP.\n*\n* Redistribution and use in source and binary forms, with or without modification,\n* are permitted provided that the following conditions are met:\n*\n* Redistributions of source code must retain the above copyright notice, this\n* list of conditions and the following disclaimer.\n*\n* Redistributions in binary form must reproduce the above copyright notice, this\n* list of conditions and the following disclaimer in the documentation and\/or\n* other materials provided with the distribution.\n*\n* Neither the name of the NXP Semiconductor nor the names of its\n* contributors may be used to endorse or promote products derived from this\n* software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"buildincmd.h\"\n\n#include \"..\/libuuu\/libuuu.h\"\n\n#ifndef _MSC_VER\n#include \n#include \n#else\n#include \n#endif\n\nvoid linux_auto_arg(const char *space = \" \", const char * filter = \"\")\n{\n\tstring str = filter;\n\n\tconst char *param[] = { \"-b\", \"-d\", \"-v\", \"-V\", \"-s\", NULL };\n\tint i = 0;\n\n\tfor (int i = 0; param[i]; i++)\n\t{\n\t\tif (str.find(param[i]) == string::npos)\n\t\t\tcout << param[i] << space << endl;\n\t}\n}\n\nint linux_autocomplete_ls(const char *path, void *p)\n{\n\tcout << path + 2 << endl;\n\treturn 0;\n}\n\nvoid linux_autocomplete(int argc, char **argv)\n{\n\tstring last = argv[3];\n\tstring cur = argv[2];\n\n\tif (argv[2][0] == '-')\n\t{\n\t\tif (cur.size() == 1)\n\t\t\tlinux_auto_arg();\n\t\telse\n\t\t\tcout << cur << \" \" << endl;\n\n\t\treturn;\n\t}\n\n\tif (last.size()>=3)\n\t{\n\t\tif (last.substr(last.size() - 3) == \"uuu\" &&(cur.empty() || cur[0] == '-'))\n\t\t{\n\t\t\tlinux_auto_arg();\n\t\t\tcout << cur << endl;\n\t\t}\n\n\t}else if(last.empty())\n\t{\n\t\tlinux_auto_arg();\n\t}\n\telse if (last == \"-b\")\n\t{\n\t\treturn g_BuildScripts.PrintAutoComplete(cur);\n\n\t}else if(last[0] == '-')\n\t{\n\t\tlinux_auto_arg();\n\t}\n\n\tuuu_for_each_ls_file(linux_autocomplete_ls, cur.c_str(), NULL);\n}\n\nstring get_next_word(string str, size_t &pos)\n{\n\tsize_t start = 0;\n\tstart = str.find(' ', pos);\n\tstring sub = str.substr(pos, start - pos);\n\tpos = start == string::npos ? start : start + 1;\n\treturn sub;\n}\n\nvoid power_shell_autocomplete(const char *p)\n{\n\tstring pstr = p;\n\tsize_t pos = 0;\n\n\tstring file;\n\n\tvector argv; string params;\n\twhile (pos != string::npos && pos < pstr.size())\n\t{\n\t\tfile = get_next_word(pstr, pos);\n\t\targv.push_back(file);\n\n\t\tif (file.size() && file[0] == '-')\n\t\t\tparams += \" \" + file;\n\t}\n\n\tstring last = argv[argv.size() - 1];\n\tstring prev = argv.size() > 1 ? argv[argv.size() - 2] : \"\";\n\tif (last == \"-b\" || prev == \"-b\")\n\t{\n\t\tstring cur;\n\t\tif (prev == \"-b\")\n\t\t\tcur = last;\n\n\t\tif (g_BuildScripts.find(cur) == g_BuildScripts.end())\n\t\t\tg_BuildScripts.PrintAutoComplete(cur, \"\");\n\n\t\tlast.clear();\n\t}\n\telse\n\t{\n\t\tif (last[0] == '-' || argv.size() == 1)\n\t\t\tlinux_auto_arg(\"\", params.c_str());\n\t}\n\n\tif (argv.size() == 1)\n\t\tlast.clear();\n\n\tuuu_for_each_ls_file(linux_autocomplete_ls, last.c_str(), NULL);\n}\n\nint auto_complete(int argc, char**argv)\n{\n\tif (argc == 4)\n\t{\n\t\tstring str = argv[1];\n\t\tif (str.size() >= 3)\n\t\t\tif (str.substr(str.size() - 3) == \"uuu\")\n\t\t\t{\n\t\t\t\tlinux_autocomplete(argc, argv);\n\t\t\t\treturn 0;\n\t\t\t}\n\t}\n\n\tif (argc >= 2)\n\t{\n\t\tstring str = argv[1];\n\t\tif (str == \"-autocomplete\")\n\t\t{\n\t\t\tpower_shell_autocomplete(argc == 2 ? \"\" : argv[2]);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nvoid print_autocomplete_help()\n{\n\n#ifndef _MSC_VER\n\t{\n\t\tcout << \"Enjoy auto [tab] command complete by run below command\" << endl;\n\t\tchar result[PATH_MAX];\n\t\tmemset(result, 0, PATH_MAX);\n\t\tssize_t count = readlink(\"\/proc\/self\/exe\", result, PATH_MAX);\n\t\tcout << \" complete -o nospace -C \" << result << \" uuu\" << endl << endl;\n\t}\n#else\n\t{\n\t\tprintf(\"Powershell: Enjoy auto [tab] command complete by run below command\\n\");\n\t\t\n\t\tHMODULE hModule = GetModuleHandleA(NULL);\n\t\tchar path[MAX_PATH];\n\t\tGetModuleFileNameA(hModule, path, MAX_PATH);\n\n\t\tprintf(\" Register-ArgumentCompleter -CommandName uuu -ScriptBlock {param($commandName,$parameterName,$wordToComplete,$commandAst,$fakeBoundParameter); %s -autocomplete $parameterName }\\n\",\n\t\t\tpath);\n\t}\n#endif\n\n}\nAdd one more new line about autocomplete\/*\n* Copyright 2018 NXP.\n*\n* Redistribution and use in source and binary forms, with or without modification,\n* are permitted provided that the following conditions are met:\n*\n* Redistributions of source code must retain the above copyright notice, this\n* list of conditions and the following disclaimer.\n*\n* Redistributions in binary form must reproduce the above copyright notice, this\n* list of conditions and the following disclaimer in the documentation and\/or\n* other materials provided with the distribution.\n*\n* Neither the name of the NXP Semiconductor nor the names of its\n* contributors may be used to endorse or promote products derived from this\n* software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"buildincmd.h\"\n\n#include \"..\/libuuu\/libuuu.h\"\n\n#ifndef _MSC_VER\n#include \n#include \n#else\n#include \n#endif\n\nvoid linux_auto_arg(const char *space = \" \", const char * filter = \"\")\n{\n\tstring str = filter;\n\n\tconst char *param[] = { \"-b\", \"-d\", \"-v\", \"-V\", \"-s\", NULL };\n\tint i = 0;\n\n\tfor (int i = 0; param[i]; i++)\n\t{\n\t\tif (str.find(param[i]) == string::npos)\n\t\t\tcout << param[i] << space << endl;\n\t}\n}\n\nint linux_autocomplete_ls(const char *path, void *p)\n{\n\tcout << path + 2 << endl;\n\treturn 0;\n}\n\nvoid linux_autocomplete(int argc, char **argv)\n{\n\tstring last = argv[3];\n\tstring cur = argv[2];\n\n\tif (argv[2][0] == '-')\n\t{\n\t\tif (cur.size() == 1)\n\t\t\tlinux_auto_arg();\n\t\telse\n\t\t\tcout << cur << \" \" << endl;\n\n\t\treturn;\n\t}\n\n\tif (last.size()>=3)\n\t{\n\t\tif (last.substr(last.size() - 3) == \"uuu\" &&(cur.empty() || cur[0] == '-'))\n\t\t{\n\t\t\tlinux_auto_arg();\n\t\t\tcout << cur << endl;\n\t\t}\n\n\t}else if(last.empty())\n\t{\n\t\tlinux_auto_arg();\n\t}\n\telse if (last == \"-b\")\n\t{\n\t\treturn g_BuildScripts.PrintAutoComplete(cur);\n\n\t}else if(last[0] == '-')\n\t{\n\t\tlinux_auto_arg();\n\t}\n\n\tuuu_for_each_ls_file(linux_autocomplete_ls, cur.c_str(), NULL);\n}\n\nstring get_next_word(string str, size_t &pos)\n{\n\tsize_t start = 0;\n\tstart = str.find(' ', pos);\n\tstring sub = str.substr(pos, start - pos);\n\tpos = start == string::npos ? start : start + 1;\n\treturn sub;\n}\n\nvoid power_shell_autocomplete(const char *p)\n{\n\tstring pstr = p;\n\tsize_t pos = 0;\n\n\tstring file;\n\n\tvector argv; string params;\n\twhile (pos != string::npos && pos < pstr.size())\n\t{\n\t\tfile = get_next_word(pstr, pos);\n\t\targv.push_back(file);\n\n\t\tif (file.size() && file[0] == '-')\n\t\t\tparams += \" \" + file;\n\t}\n\n\tstring last = argv[argv.size() - 1];\n\tstring prev = argv.size() > 1 ? argv[argv.size() - 2] : \"\";\n\tif (last == \"-b\" || prev == \"-b\")\n\t{\n\t\tstring cur;\n\t\tif (prev == \"-b\")\n\t\t\tcur = last;\n\n\t\tif (g_BuildScripts.find(cur) == g_BuildScripts.end())\n\t\t\tg_BuildScripts.PrintAutoComplete(cur, \"\");\n\n\t\tlast.clear();\n\t}\n\telse\n\t{\n\t\tif (last[0] == '-' || argv.size() == 1)\n\t\t\tlinux_auto_arg(\"\", params.c_str());\n\t}\n\n\tif (argv.size() == 1)\n\t\tlast.clear();\n\n\tuuu_for_each_ls_file(linux_autocomplete_ls, last.c_str(), NULL);\n}\n\nint auto_complete(int argc, char**argv)\n{\n\tif (argc == 4)\n\t{\n\t\tstring str = argv[1];\n\t\tif (str.size() >= 3)\n\t\t\tif (str.substr(str.size() - 3) == \"uuu\")\n\t\t\t{\n\t\t\t\tlinux_autocomplete(argc, argv);\n\t\t\t\treturn 0;\n\t\t\t}\n\t}\n\n\tif (argc >= 2)\n\t{\n\t\tstring str = argv[1];\n\t\tif (str == \"-autocomplete\")\n\t\t{\n\t\t\tpower_shell_autocomplete(argc == 2 ? \"\" : argv[2]);\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\treturn 1;\n}\n\nvoid print_autocomplete_help()\n{\n\n#ifndef _MSC_VER\n\t{\n\t\tcout << \"Enjoy auto [tab] command complete by run below command\" << endl;\n\t\tchar result[PATH_MAX];\n\t\tmemset(result, 0, PATH_MAX);\n\t\tssize_t count = readlink(\"\/proc\/self\/exe\", result, PATH_MAX);\n\t\tcout << \" complete -o nospace -C \" << result << \" uuu\" << endl << endl;\n\t}\n#else\n\t{\n\t\tprintf(\"Powershell: Enjoy auto [tab] command complete by run below command\\n\");\n\t\t\n\t\tHMODULE hModule = GetModuleHandleA(NULL);\n\t\tchar path[MAX_PATH];\n\t\tGetModuleFileNameA(hModule, path, MAX_PATH);\n\n\t\tprintf(\" Register-ArgumentCompleter -CommandName uuu -ScriptBlock {param($commandName,$parameterName,$wordToComplete,$commandAst,$fakeBoundParameter); %s -autocomplete $parameterName }\\n\\n\",\n\t\t\tpath);\n\t}\n#endif\n\n}\n<|endoftext|>"} {"text":"Wrap \"\" in OUString: error: conversion from const char* to non-scalar...<|endoftext|>"} {"text":"\/\/============================================================================\n\/\/ vSMC\/include\/vsmc\/rng\/random_walk.hpp\n\/\/----------------------------------------------------------------------------\n\/\/ vSMC: Scalable Monte Carlo\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013-2016, Yan Zhou\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/============================================================================\n\n#ifndef VSMC_RNG_RANDOM_WALK_HPP\n#define VSMC_RNG_RANDOM_WALK_HPP\n\n#include \n#include \n#include \n#include \n\n#define VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(flag, Name) \\\n VSMC_RUNTIME_ASSERT( \\\n (flag), \"**RandomWal\" #Name \"** CONSTRUCTED WITH INVALID PARAMETERS\")\n\nnamespace vsmc\n{\n\nnamespace internal\n{\n\ntemplate \ninline bool random_walk_normal_check_param(\n RealType stddev, RealType a, RealType b)\n{\n return (stddev > 0) && (a < b);\n}\n\ntemplate \ninline bool random_walk_normal_mv_check_param(std::size_t dim,\n const RealType *, const std::size_t *a, const std::size_t *b)\n{\n for (std::size_t i = 0; i != dim; ++i)\n if (a[i] > b[i])\n return false;\n return true;\n}\n\ntemplate \nRealType random_walk_normal_q0(RealType x, RealType &y, RealType z)\n{\n y = x + z;\n\n return 0;\n}\n\ntemplate \nRealType random_walk_normal_qa(RealType x, RealType &y, RealType z, RealType a)\n{\n y = a + (x - a) * std::exp(z);\n\n return z;\n}\n\ntemplate \nRealType random_walk_normal_qb(RealType x, RealType &y, RealType z, RealType b)\n{\n y = b - (b - x) * std::exp(z);\n\n return z;\n}\n\ntemplate \nRealType random_walk_normal_qab(\n RealType x, RealType &y, RealType z, RealType a, RealType b)\n{\n RealType r = std::exp(z) * (x - a) \/ (b - x);\n y = (a + b * r) \/ (1 + r);\n\n return std::log((y - a) \/ (x - a) * (b - y) \/ (b - x));\n}\n\n} \/\/ namespace vsmc::internal\n\n\/\/\/ \\brief Random walk MCMC\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkMCMC\n{\n public:\n using result_type = RealType;\n\n template \n result_type operator()(RNGType &rng, result_type x,\n LogTargetType &&log_target, RandomWalkType &&random_walk)\n {\n result_type y = 0;\n result_type q = random_walk(rng, x, y);\n result_type p = log_target(y) - log_target(x) + q;\n result_type u = std::log(runif_(rng));\n\n return u < p ? y : x;\n }\n\n template \n void operator()(RNGType &rng, std::size_t dim, const result_type *x,\n result_type *y, LogTargetType &&log_target,\n RandomWalkType &&random_walk)\n {\n Vector r(dim);\n result_type q = random_walk(rng, dim, x, r.data());\n result_type p = log_target(dim, r.data()) - log_target(dim, x) + q;\n result_type u = std::log(runif_(rng));\n if (u < p)\n std::copy(r.begin(), r.end(), y);\n else\n std::copy_n(x, dim, y);\n }\n\n private:\n U01Distribution runif_;\n}; \/\/ class MCMC\n\n\/\/\/ \\brief Normal random walk proposal\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkNormal\n{\n public:\n using result_type = RealType;\n\n explicit RandomWalkNormal(result_type stddev = 1,\n result_type a = -std::numeric_limits::infinity(),\n result_type b = std::numeric_limits::infinity())\n : rnorm_(0, stddev), a_(a), b_(b), flag_(0)\n {\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_check_param(stddev, a, b), Normal);\n\n unsigned lower = std::isfinite(a) ? 1 : 0;\n unsigned upper = std::isfinite(b) ? 1 : 0;\n flag_ = (lower << 1) + upper;\n }\n\n template \n result_type operator()(RNGType &rng, result_type x, result_type &y)\n {\n result_type z = rnorm_(rng);\n switch (flag_) {\n case 0: return internal::random_walk_normal_q0(x, y, z);\n case 1: return internal::random_walk_normal_qb(x, y, z, b_);\n case 2: return internal::random_walk_normal_qa(x, y, z, a_);\n case 3: return internal::random_walk_normal_qab(x, y, z, a_, b_);\n default: return 0;\n }\n }\n\n private:\n NormalDistribution rnorm_;\n result_type a_;\n result_type b_;\n unsigned flag_;\n}; \/\/ class RandomWalkNormal\n\n\/\/\/ \\brief Multivariate Normal random walk proposal\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkNormalMV\n{\n public:\n using result_type = RealType;\n\n explicit RandomWalkNormalMV(const result_type *chol = nullptr,\n const result_type *a = nullptr, const result_type *b = nullptr)\n : rnorm_(nullptr, chol)\n {\n init(Dim, a, b);\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_mv_check_param(\n Dim, chol, a_.data(), b_.data()),\n NormalMV);\n }\n\n explicit RandomWalkNormalMV(std::size_t dim = 1,\n const result_type *chol = nullptr, const result_type *a = nullptr,\n const result_type *b = nullptr)\n : rnorm_(dim, nullptr, chol), a_(dim), b_(dim), flag_(dim)\n {\n init(dim, a, b);\n std::copy_n(a, dim, a_.begin());\n std::copy_n(b, dim, b_.begin());\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_check_param(\n dim, chol, a_.data(), b_.data()),\n NormalMV);\n }\n\n template \n result_type operator()(\n RNGType &rng, std::size_t, const result_type *x, result_type *y)\n {\n rnorm_(rng, y);\n result_type q = 0;\n for (std::size_t i = 0; i != dim(); ++i) {\n switch (flag_[i]) {\n case 0:\n q += internal::random_walk_normal_q0(x[i], y[i], y[i]);\n break;\n case 1:\n q += internal::random_walk_normal_qb(\n x[i], y[i], y[i], b_[i]);\n break;\n case 2:\n q += internal::random_walk_normal_qa(\n x[i], y[i], y[i], a_[i]);\n break;\n case 3:\n q += internal::random_walk_normal_qab(\n x[i], y[i], y[i], a_[i], b_[i]);\n break;\n default: break;\n }\n }\n\n return q;\n }\n\n std::size_t dim() const { return rnorm_.dim(); }\n\n private:\n template \n using vtype = typename std::conditional,\n std::array>::type;\n\n NormalMVDistribution rnorm_;\n vtype a_;\n vtype b_;\n vtype flag_;\n\n void init(std::size_t dim, const result_type *a, const result_type *b)\n {\n if (a == nullptr)\n std::fill(a_.begin(), a_.end(), 0);\n else\n std::copy_n(a, dim, a_.begin());\n\n if (b == nullptr)\n std::fill(b_.begin(), b_.end(), 0);\n else\n std::copy_n(b, dim, b_.begin());\n\n for (std::size_t i = 0; i != dim; ++i) {\n unsigned lower = std::isfinite(a_[i]) ? 1 : 0;\n unsigned upper = std::isfinite(b_[i]) ? 1 : 0;\n flag_[i] = (lower << 1) + upper;\n }\n }\n}; \/\/ class RandomWalkNormalMV\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_RNG_RANDOM_WALK_HPP\nreturn acceptance from random walk mcmc\/\/============================================================================\n\/\/ vSMC\/include\/vsmc\/rng\/random_walk.hpp\n\/\/----------------------------------------------------------------------------\n\/\/ vSMC: Scalable Monte Carlo\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013-2016, Yan Zhou\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/============================================================================\n\n#ifndef VSMC_RNG_RANDOM_WALK_HPP\n#define VSMC_RNG_RANDOM_WALK_HPP\n\n#include \n#include \n#include \n#include \n\n#define VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(flag, Name) \\\n VSMC_RUNTIME_ASSERT( \\\n (flag), \"**RandomWal\" #Name \"** CONSTRUCTED WITH INVALID PARAMETERS\")\n\nnamespace vsmc\n{\n\nnamespace internal\n{\n\ntemplate \ninline bool random_walk_normal_check_param(\n RealType stddev, RealType a, RealType b)\n{\n return (stddev > 0) && (a < b);\n}\n\ntemplate \ninline bool random_walk_normal_mv_check_param(std::size_t dim,\n const RealType *, const std::size_t *a, const std::size_t *b)\n{\n for (std::size_t i = 0; i != dim; ++i)\n if (a[i] > b[i])\n return false;\n return true;\n}\n\ntemplate \nRealType random_walk_normal_q0(RealType x, RealType &y, RealType z)\n{\n y = x + z;\n\n return 0;\n}\n\ntemplate \nRealType random_walk_normal_qa(RealType x, RealType &y, RealType z, RealType a)\n{\n y = a + (x - a) * std::exp(z);\n\n return z;\n}\n\ntemplate \nRealType random_walk_normal_qb(RealType x, RealType &y, RealType z, RealType b)\n{\n y = b - (b - x) * std::exp(z);\n\n return z;\n}\n\ntemplate \nRealType random_walk_normal_qab(\n RealType x, RealType &y, RealType z, RealType a, RealType b)\n{\n RealType r = std::exp(z) * (x - a) \/ (b - x);\n y = (a + b * r) \/ (1 + r);\n\n return std::log((y - a) \/ (x - a) * (b - y) \/ (b - x));\n}\n\n} \/\/ namespace vsmc::internal\n\n\/\/\/ \\brief Random walk MCMC\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkMCMC\n{\n public:\n using result_type = RealType;\n\n template \n bool operator()(RNGType &rng, result_type x, result_type &y,\n LogTargetType &&log_target, RandomWalkType &&random_walk)\n {\n result_type r = 0;\n result_type q = random_walk(rng, x, r);\n result_type p = log_target(r) - log_target(x) + q;\n result_type u = std::log(runif_(rng));\n\n if (u < p) {\n y = r;\n return true;\n } else {\n y = x;\n return false;\n }\n }\n\n template \n bool operator()(RNGType &rng, std::size_t dim, const result_type *x,\n result_type *y, LogTargetType &&log_target,\n RandomWalkType &&random_walk)\n {\n Vector r(dim);\n result_type q = random_walk(rng, dim, x, r.data());\n result_type p = log_target(dim, r.data()) - log_target(dim, x) + q;\n result_type u = std::log(runif_(rng));\n\n if (u < p) {\n std::copy(r.begin(), r.end(), y);\n return true;\n } else {\n std::copy_n(x, dim, y);\n return false;\n }\n }\n\n private:\n U01Distribution runif_;\n}; \/\/ class MCMC\n\n\/\/\/ \\brief Normal random walk proposal\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkNormal\n{\n public:\n using result_type = RealType;\n\n explicit RandomWalkNormal(result_type stddev = 1,\n result_type a = -std::numeric_limits::infinity(),\n result_type b = std::numeric_limits::infinity())\n : rnorm_(0, stddev), a_(a), b_(b), flag_(0)\n {\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_check_param(stddev, a, b), Normal);\n\n unsigned lower = std::isfinite(a) ? 1 : 0;\n unsigned upper = std::isfinite(b) ? 1 : 0;\n flag_ = (lower << 1) + upper;\n }\n\n template \n result_type operator()(RNGType &rng, result_type x, result_type &y)\n {\n result_type z = rnorm_(rng);\n switch (flag_) {\n case 0: return internal::random_walk_normal_q0(x, y, z);\n case 1: return internal::random_walk_normal_qb(x, y, z, b_);\n case 2: return internal::random_walk_normal_qa(x, y, z, a_);\n case 3: return internal::random_walk_normal_qab(x, y, z, a_, b_);\n default: return 0;\n }\n }\n\n private:\n NormalDistribution rnorm_;\n result_type a_;\n result_type b_;\n unsigned flag_;\n}; \/\/ class RandomWalkNormal\n\n\/\/\/ \\brief Multivariate Normal random walk proposal\n\/\/\/ \\ingroup RandomWalk\ntemplate \nclass RandomWalkNormalMV\n{\n public:\n using result_type = RealType;\n\n explicit RandomWalkNormalMV(const result_type *chol = nullptr,\n const result_type *a = nullptr, const result_type *b = nullptr)\n : rnorm_(nullptr, chol)\n {\n init(Dim, a, b);\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_mv_check_param(\n Dim, chol, a_.data(), b_.data()),\n NormalMV);\n }\n\n explicit RandomWalkNormalMV(std::size_t dim = 1,\n const result_type *chol = nullptr, const result_type *a = nullptr,\n const result_type *b = nullptr)\n : rnorm_(dim, nullptr, chol), a_(dim), b_(dim), flag_(dim)\n {\n init(dim, a, b);\n std::copy_n(a, dim, a_.begin());\n std::copy_n(b, dim, b_.begin());\n VSMC_RUNTIME_ASSERT_RNG_RANDOM_WALK_PARAM(\n internal::random_walk_normal_check_param(\n dim, chol, a_.data(), b_.data()),\n NormalMV);\n }\n\n template \n result_type operator()(\n RNGType &rng, std::size_t, const result_type *x, result_type *y)\n {\n rnorm_(rng, y);\n result_type q = 0;\n for (std::size_t i = 0; i != dim(); ++i) {\n switch (flag_[i]) {\n case 0:\n q += internal::random_walk_normal_q0(x[i], y[i], y[i]);\n break;\n case 1:\n q += internal::random_walk_normal_qb(\n x[i], y[i], y[i], b_[i]);\n break;\n case 2:\n q += internal::random_walk_normal_qa(\n x[i], y[i], y[i], a_[i]);\n break;\n case 3:\n q += internal::random_walk_normal_qab(\n x[i], y[i], y[i], a_[i], b_[i]);\n break;\n default: break;\n }\n }\n\n return q;\n }\n\n std::size_t dim() const { return rnorm_.dim(); }\n\n private:\n template \n using vtype = typename std::conditional,\n std::array>::type;\n\n NormalMVDistribution rnorm_;\n vtype a_;\n vtype b_;\n vtype flag_;\n\n void init(std::size_t dim, const result_type *a, const result_type *b)\n {\n if (a == nullptr)\n std::fill(a_.begin(), a_.end(), 0);\n else\n std::copy_n(a, dim, a_.begin());\n\n if (b == nullptr)\n std::fill(b_.begin(), b_.end(), 0);\n else\n std::copy_n(b, dim, b_.begin());\n\n for (std::size_t i = 0; i != dim; ++i) {\n unsigned lower = std::isfinite(a_[i]) ? 1 : 0;\n unsigned upper = std::isfinite(b_[i]) ? 1 : 0;\n flag_[i] = (lower << 1) + upper;\n }\n }\n}; \/\/ class RandomWalkNormalMV\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_RNG_RANDOM_WALK_HPP\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"Camera.h\"\n#include \"Utility.h\"\n#include \"CameraNotConnectedException.h\"\n#include \"IsoManager.h\"\n#include \"ExposureTimeManager.h\"\n\nnamespace EosClr\n{\n\tCamera::Camera(EdsCameraRef CameraHandle)\n\t{\n\t\tthis->CameraHandle = CameraHandle;\n\t\t_SupportedIsoSpeeds = gcnew List();\n\t\t_SupportedExposureTimes = gcnew List();\n\t\tLiveViewClosingLock = gcnew Object();\n\t\t\n\t\t\/\/ Initialize the camera and its details\n\t\tEdsDeviceInfo deviceInfo;\n\t\tErrorCheck(EdsGetDeviceInfo(CameraHandle, &deviceInfo));\n\t\tName = Marshal::PtrToStringAnsi((IntPtr)deviceInfo.szDeviceDescription);\n\t\tPort = Marshal::PtrToStringAnsi((IntPtr)deviceInfo.szPortName);\n\t\tProtocol = static_cast(deviceInfo.deviceSubType);\n\n\t\t\/\/ Subscribe to the property change event\n\t\tHandler = gcnew PropertyEventHandlerDelegate(this, &Camera::OnPropertyEvent);\n\t\tIntPtr delegatePointer = Marshal::GetFunctionPointerForDelegate(Handler);\n\t\tEdsPropertyEventHandler handler = static_cast(delegatePointer.ToPointer());\n\t\tErrorCheck(EdsSetPropertyEventHandler(CameraHandle, kEdsPropertyEvent_All, handler, NULL));\n\t}\n\n\tString^ Camera::Name::get()\n\t{\n\t\treturn _Name;\n\t}\n\n\tvoid Camera::Name::set(String^ Name)\n\t{\n\t\t_Name = Name;\n\t}\n\n\tString^ Camera::Port::get()\n\t{\n\t\treturn _Port;\n\t}\n\n\tvoid Camera::Port::set(String^ Port)\n\t{\n\t\t_Port = Port;\n\t}\n\n\tConnectionProtocol Camera::Protocol::get()\n\t{\n\t\treturn _Protocol;\n\t}\n\n\tvoid Camera::Protocol::set(ConnectionProtocol Protocol)\n\t{\n\t\t_Protocol = Protocol;\n\t}\n\n\tIsoSpeed Camera::Iso::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _Iso;\n\t}\n\n\tvoid Camera::Iso::set(IsoSpeed Iso)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ If the user sets it to the value that's already assigned, just ignore it.\n\t\tif (Iso == _Iso)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (!_SupportedIsoSpeeds->Contains(Iso))\n\t\t{\n\t\t\tthrow gcnew Exception(\"This camera doesn't support ISO \" + Iso.ToString());\n\t\t}\n\n\t\t\/\/ Send it down to the camera.\n\t\tEdsUInt32 edsIsoValue = IsoManager::GetEdsIsoValue(Iso);\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_ISOSpeed, 0, sizeof(edsIsoValue), &edsIsoValue));\n\t\t_Iso = Iso;\n\t\tIsoChanged(Iso);\n\t}\n\n\tint Camera::PicturesRemaining::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _PicturesRemaining;\n\t}\n\n\tvoid Camera::PicturesRemaining::set(int PicturesRemaining)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\t_PicturesRemaining = PicturesRemaining;\n\t\tPicturesRemainingChanged(PicturesRemaining);\n\t}\n\n\tExposureTime Camera::Exposure::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _Exposure;\n\t}\n\n\tvoid Camera::Exposure::set(ExposureTime Exposure)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ If the user sets it to the value that's already assigned, just ignore it.\n\t\tif (Exposure == _Exposure)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (!_SupportedExposureTimes->Contains(Exposure))\n\t\t{\n\t\t\tthrow gcnew Exception(\"This camera doesn't support exposure \" + Exposure.ToString());\n\t\t}\n\n\t\t\/\/ Send it down to the camera.\n\t\tEdsUInt32 edsExposureValue = ExposureTimeManager::GetEdsExposureValue(Exposure);\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Tv, 0, sizeof(edsExposureValue), &edsExposureValue));\n\t\t_Exposure = Exposure;\n\t\tExposureTimeChanged(Exposure);\n\t}\n\n\tIEnumerable^ Camera::SupportedIsoSpeeds::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _SupportedIsoSpeeds;\n\t}\n\n\tIEnumerable^ Camera::SupportedExposureTimes::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _SupportedExposureTimes;\n\t}\n\n\tvoid Camera::Connect()\n\t{\n\t\tif (CurrentCamera != nullptr)\n\t\t{\n\t\t\tCurrentCamera->Disconnect();\n\t\t}\n\t\tCurrentCamera = this;\n\t\tErrorCheck(EdsOpenSession(CameraHandle));\n\n\t\tRefreshSupportedIsoSpeeds();\n\t\tRefreshSupportedExposureTimes();\n\t}\n\n\tvoid Camera::Disconnect()\n\t{\n\t\tif (CurrentCamera == this)\n\t\t{\n\t\t\tErrorCheck(EdsCloseSession(CameraHandle));\n\t\t\tCurrentCamera = nullptr;\n\t\t}\n\t}\n\n\tvoid Camera::ActivateLiveView()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\tJpegDecompressor = tjInitDecompress();\n\n\t\t\/\/ This is pretty much taken straight from the reference docs.\n\t\tEdsUInt32 propValue;\n\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\tpropValue = kEdsEvfOutputDevice_PC;\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\t\n\t\tpin_ptr pinnedLiveViewStream = &LiveViewStream;\n\t\tpin_ptr pinnedLiveViewImage = &LiveViewImage;\n\t\tErrorCheck(EdsCreateMemoryStream(0, pinnedLiveViewStream));\n\t\tErrorCheck(EdsCreateEvfImageRef(LiveViewStream, pinnedLiveViewImage));\n\t\tLiveViewClosing = false;\n\t\tEdsSize size;\n\t\tErrorCheck(EdsDownloadEvfImage(CameraHandle, LiveViewImage));\n\t\tErrorCheck(EdsGetPropertyData(LiveViewImage, kEdsPropID_Evf_CoordinateSystem, 0, sizeof(size), &size));\n\t\tPropertyChanged(\"EVF Size! Height = \" + size.height + \", width = \" + size.width);\n\t\tLiveViewReadTask = Task::Factory->StartNew(gcnew Action(this, &Camera::LiveViewReadLoop));\n\t}\n\n\tvoid Camera::DeactivateLiveView()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ This is also taken straight from the reference docs.\n\t\tif (LiveViewImage == NULL || LiveViewStream == NULL)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tMonitor::Enter(LiveViewClosingLock);\n\t\t\tLiveViewClosing = true;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tMonitor::Exit(LiveViewClosingLock);\n\t\t}\n\t\tLiveViewReadTask->Wait();\n\n\t\ttjDestroy(JpegDecompressor);\n\n\t\tErrorCheck(EdsRelease(LiveViewImage));\n\t\tErrorCheck(EdsRelease(LiveViewStream));\n\t\tLiveViewImage = NULL;\n\t\tLiveViewStream = NULL;\n\n\t\tEdsUInt32 propValue;\n\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\tpropValue = kEdsEvfOutputDevice_TFT;\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t}\n\n\tint imgCounter = 0;\n\n\tvoid Camera::LiveViewReadLoop()\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ Check to see if LiveView is closing, and return if it is.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tMonitor::Enter(LiveViewClosingLock);\n\t\t\t\tif (LiveViewClosing)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tMonitor::Exit(LiveViewClosingLock);\n\t\t\t}\n\n\t\t\t\/\/ Download the image from the camera\n\t\t\tEdsError result = EdsDownloadEvfImage(CameraHandle, LiveViewImage);\n\t\t\tif (result == EDS_ERR_OBJECT_NOTREADY)\n\t\t\t{\n\t\t\t\tThread::Sleep(500);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (result == EDS_ERR_CANNOT_MAKE_OBJECT)\n\t\t\t{\n\t\t\t\tPropertyChanged(\"Can't make object :\/\");\n\t\t\t\tThread::Sleep(1000);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tErrorCheck(result);\n\n\t\t\tEdsUInt32 streamPos;\n\t\t\tEdsVoid* streamPtr;\n\t\t\tEdsImageRef imageRef;\n\t\t\tEdsImageInfo imageInfo;\n\t\t\tErrorCheck(EdsGetPosition(LiveViewStream, &streamPos));\n\t\t\tErrorCheck(EdsGetPointer(LiveViewStream, &streamPtr));\n\t\t\tErrorCheck(EdsCreateImageRef(LiveViewStream, &imageRef));\n\t\t\tErrorCheck(EdsGetImageInfo(imageRef, kEdsImageSrc_FullView, &imageInfo));\n\t\t\t\n\t\t\tint bytesPerPixel = imageInfo.componentDepth \/ 8;\n\t\t\tint numberOfChannels = imageInfo.numOfComponents;\n\t\t\tint width = imageInfo.width;\n\t\t\tint height = imageInfo.height;\n\t\t\tint totalSize = width * height * numberOfChannels * bytesPerPixel;\n\n\t\t\tunsigned char* jpegBuffer = reinterpret_cast(streamPtr);\n\n\n\n\t\t\t\/\/tjDecompress2(JpegDecompressor, jpegBuffer, totalSize, NULL, width, 0, height, TJPF_RGB, TJFLAG_FASTDCT);\n\n\t\t\tarray^ imgBytes = gcnew array(streamPos);\n\t\t\tMarshal::Copy((IntPtr)streamPtr, imgBytes, 0, imgBytes->Length);\n\t\t\tSystem::IO::File::WriteAllBytes(\"C:\\\\kappa\\\\img\" + (imgCounter++) + \".jpg\", imgBytes);\n\n\t\t\t\/\/ErrorCheck(EdsGetLength(LiveViewStream, &streamLength));\n\t\t\tPropertyChanged(\"New image!\" + Environment::NewLine + \n\t\t\t\t\"\\tPos = \" + streamPos + Environment::NewLine + \n\t\t\t\t\"\\tPtr = \" + ((unsigned int)streamPtr).ToString(\"X\") + Environment::NewLine + \n\t\t\t\t\"\\tHeight = \" + imageInfo.height + Environment::NewLine +\n\t\t\t\t\"\\tWidth = \" + imageInfo.width);\n\t\t\tThread::Sleep(1000);\n\t\t}\n\t}\n\n\tvoid Camera::RefreshSupportedIsoSpeeds()\n\t{\n\t\t_SupportedIsoSpeeds->Clear();\n\t\tEdsPropertyDesc isoSpeeds;\n\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_ISOSpeed, &isoSpeeds));\n\t\tfor (int i = 0; i < isoSpeeds.numElements; i++)\n\t\t{\n\t\t\tEdsInt32 speedValue = isoSpeeds.propDesc[i];\n\t\t\tIsoSpeed speed = IsoManager::GetIsoSpeed(speedValue);\n\t\t\t_SupportedIsoSpeeds->Add(speed);\n\t\t}\n\t}\n\n\tvoid Camera::RefreshSupportedExposureTimes()\n\t{\n\t\t_SupportedExposureTimes->Clear();\n\t\tEdsPropertyDesc exposureTimes;\n\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_Tv, &exposureTimes));\n\t\tfor (int i = 0; i < exposureTimes.numElements; i++)\n\t\t{\n\t\t\tEdsInt32 exposureValue = exposureTimes.propDesc[i];\n\t\t\tExposureTime exposure = ExposureTimeManager::GetExposureTime(exposureValue);\n\t\t\t_SupportedExposureTimes->Add(exposure);\n\t\t}\n\t}\n\n\tEdsError Camera::OnPropertyEvent(EdsPropertyEvent EventType,\n\t\tEdsPropertyID PropertyID,\n\t\tEdsUInt32 Param,\n\t\tEdsVoid* Context)\n\t{\n\t\tif (EventType == kEdsPropertyEvent_PropertyChanged)\n\t\t{\n\t\t\tOnPropertyValueChanged(PropertyID, Param);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOnPropertyOptionsChanged(PropertyID, Param);\n\t\t}\n\t\treturn EDS_ERR_OK;\n\t}\n\n\tvoid Camera::OnPropertyValueChanged(EdsPropertyID PropertyID, EdsUInt32 Param)\n\t{\n\t\tswitch (PropertyID)\n\t\t{\n\t\t\tcase kEdsPropID_ISOSpeed: \/\/ ISO Speed\n\t\t\t{\n\t\t\t\tEdsUInt32 currentIsoValue;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_ISOSpeed, 0, sizeof(currentIsoValue), ¤tIsoValue));\n\t\t\t\t_Iso = IsoManager::GetIsoSpeed(currentIsoValue);\n\t\t\t\tIsoChanged(_Iso);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase kEdsPropID_AvailableShots: \/\/ How many pictures can fit in the available disk space\n\t\t\t{\n\t\t\t\tEdsUInt32 numShots;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_AvailableShots, 0, sizeof(numShots), &numShots));\n\t\t\t\t_PicturesRemaining = numShots;\n\t\t\t\tPicturesRemainingChanged(_PicturesRemaining);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase kEdsPropID_Tv: \/\/ Exposure time\n\t\t\t{\n\t\t\t\tEdsUInt32 exposure;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Tv, 0, sizeof(exposure), &exposure));\n\t\t\t\t_Exposure = ExposureTimeManager::GetExposureTime(exposure);\n\t\t\t\tExposureTimeChanged(_Exposure);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: \/\/ Anything that we haven't handled yet gets printed to the debug event\n\t\t\t\tPropertyChanged(\"PropertyValueChanged, Prop = \" + PropertyID.ToString(\"X\") + \", Param = \" + Param.ToString(\"X\"));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Camera::OnPropertyOptionsChanged(EdsPropertyID PropertyID, EdsUInt32 Param)\n\t{\n\t\tswitch (PropertyID)\n\t\t{\n\t\tcase kEdsPropID_ISOSpeed: \/\/ ISO Speed\n\t\t{\n\t\t\tRefreshSupportedIsoSpeeds();\n\t\t\tSupportedIsoSpeedsChanged(_SupportedIsoSpeeds);\n\t\t\tbreak;\n\t\t}\n\t\tcase kEdsPropID_Tv: \/\/ Exposure time\n\t\t{\n\t\t\tRefreshSupportedExposureTimes();\n\t\t\tSupportedExposureTimesChanged(_SupportedExposureTimes);\n\t\t\tbreak;\n\t\t}\n\t\tcase kEdsPropID_Evf_AFMode:\n\t\t{\n\t\t\tEdsPropertyDesc afModes;\n\t\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_Evf_AFMode, &afModes));\n\t\t\tPropertyChanged(\"AF MODE OPTIONS:\");\n\t\t\tfor (int i = 0; i < afModes.numElements; i++)\n\t\t\t{\n\t\t\t\tEdsInt32 mode = afModes.propDesc[i];\n\t\t\t\tPropertyChanged(\"\\t\" + mode.ToString(\"X\"));\n\t\t\t}\n\t\t}\n\t\tdefault: \/\/ Anything that we haven't handled yet gets printed to the debug event\n\t\t\tPropertyChanged(\"PropertyOptionsChanged, Prop = \" + PropertyID.ToString(\"X\") + \", Param = \" + Param.ToString(\"X\"));\n\t\t\tbreak;\n\t\t}\n\t}\n}\nReverted LiveView force display test#include \"stdafx.h\"\n#include \"Camera.h\"\n#include \"Utility.h\"\n#include \"CameraNotConnectedException.h\"\n#include \"IsoManager.h\"\n#include \"ExposureTimeManager.h\"\n\nnamespace EosClr\n{\n\tCamera::Camera(EdsCameraRef CameraHandle)\n\t{\n\t\tthis->CameraHandle = CameraHandle;\n\t\t_SupportedIsoSpeeds = gcnew List();\n\t\t_SupportedExposureTimes = gcnew List();\n\t\tLiveViewClosingLock = gcnew Object();\n\t\t\n\t\t\/\/ Initialize the camera and its details\n\t\tEdsDeviceInfo deviceInfo;\n\t\tErrorCheck(EdsGetDeviceInfo(CameraHandle, &deviceInfo));\n\t\tName = Marshal::PtrToStringAnsi((IntPtr)deviceInfo.szDeviceDescription);\n\t\tPort = Marshal::PtrToStringAnsi((IntPtr)deviceInfo.szPortName);\n\t\tProtocol = static_cast(deviceInfo.deviceSubType);\n\n\t\t\/\/ Subscribe to the property change event\n\t\tHandler = gcnew PropertyEventHandlerDelegate(this, &Camera::OnPropertyEvent);\n\t\tIntPtr delegatePointer = Marshal::GetFunctionPointerForDelegate(Handler);\n\t\tEdsPropertyEventHandler handler = static_cast(delegatePointer.ToPointer());\n\t\tErrorCheck(EdsSetPropertyEventHandler(CameraHandle, kEdsPropertyEvent_All, handler, NULL));\n\t}\n\n\tString^ Camera::Name::get()\n\t{\n\t\treturn _Name;\n\t}\n\n\tvoid Camera::Name::set(String^ Name)\n\t{\n\t\t_Name = Name;\n\t}\n\n\tString^ Camera::Port::get()\n\t{\n\t\treturn _Port;\n\t}\n\n\tvoid Camera::Port::set(String^ Port)\n\t{\n\t\t_Port = Port;\n\t}\n\n\tConnectionProtocol Camera::Protocol::get()\n\t{\n\t\treturn _Protocol;\n\t}\n\n\tvoid Camera::Protocol::set(ConnectionProtocol Protocol)\n\t{\n\t\t_Protocol = Protocol;\n\t}\n\n\tIsoSpeed Camera::Iso::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _Iso;\n\t}\n\n\tvoid Camera::Iso::set(IsoSpeed Iso)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ If the user sets it to the value that's already assigned, just ignore it.\n\t\tif (Iso == _Iso)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (!_SupportedIsoSpeeds->Contains(Iso))\n\t\t{\n\t\t\tthrow gcnew Exception(\"This camera doesn't support ISO \" + Iso.ToString());\n\t\t}\n\n\t\t\/\/ Send it down to the camera.\n\t\tEdsUInt32 edsIsoValue = IsoManager::GetEdsIsoValue(Iso);\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_ISOSpeed, 0, sizeof(edsIsoValue), &edsIsoValue));\n\t\t_Iso = Iso;\n\t\tIsoChanged(Iso);\n\t}\n\n\tint Camera::PicturesRemaining::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _PicturesRemaining;\n\t}\n\n\tvoid Camera::PicturesRemaining::set(int PicturesRemaining)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\t_PicturesRemaining = PicturesRemaining;\n\t\tPicturesRemainingChanged(PicturesRemaining);\n\t}\n\n\tExposureTime Camera::Exposure::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _Exposure;\n\t}\n\n\tvoid Camera::Exposure::set(ExposureTime Exposure)\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ If the user sets it to the value that's already assigned, just ignore it.\n\t\tif (Exposure == _Exposure)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tif (!_SupportedExposureTimes->Contains(Exposure))\n\t\t{\n\t\t\tthrow gcnew Exception(\"This camera doesn't support exposure \" + Exposure.ToString());\n\t\t}\n\n\t\t\/\/ Send it down to the camera.\n\t\tEdsUInt32 edsExposureValue = ExposureTimeManager::GetEdsExposureValue(Exposure);\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Tv, 0, sizeof(edsExposureValue), &edsExposureValue));\n\t\t_Exposure = Exposure;\n\t\tExposureTimeChanged(Exposure);\n\t}\n\n\tIEnumerable^ Camera::SupportedIsoSpeeds::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _SupportedIsoSpeeds;\n\t}\n\n\tIEnumerable^ Camera::SupportedExposureTimes::get()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\t\treturn _SupportedExposureTimes;\n\t}\n\n\tvoid Camera::Connect()\n\t{\n\t\tif (CurrentCamera != nullptr)\n\t\t{\n\t\t\tCurrentCamera->Disconnect();\n\t\t}\n\t\tCurrentCamera = this;\n\t\tErrorCheck(EdsOpenSession(CameraHandle));\n\n\t\tRefreshSupportedIsoSpeeds();\n\t\tRefreshSupportedExposureTimes();\n\t}\n\n\tvoid Camera::Disconnect()\n\t{\n\t\tif (CurrentCamera == this)\n\t\t{\n\t\t\tErrorCheck(EdsCloseSession(CameraHandle));\n\t\t\tCurrentCamera = nullptr;\n\t\t}\n\t}\n\n\tvoid Camera::ActivateLiveView()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\tJpegDecompressor = tjInitDecompress();\n\n\t\t\/\/ This is pretty much taken straight from the reference docs.\n\t\tEdsUInt32 propValue;\n\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\tpropValue |= kEdsEvfOutputDevice_PC;\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\t\n\t\tpin_ptr pinnedLiveViewStream = &LiveViewStream;\n\t\tpin_ptr pinnedLiveViewImage = &LiveViewImage;\n\t\tErrorCheck(EdsCreateMemoryStream(0, pinnedLiveViewStream));\n\t\tErrorCheck(EdsCreateEvfImageRef(LiveViewStream, pinnedLiveViewImage));\n\t\tLiveViewClosing = false;\n\t\tEdsSize size;\n\t\tErrorCheck(EdsDownloadEvfImage(CameraHandle, LiveViewImage));\n\t\tErrorCheck(EdsGetPropertyData(LiveViewImage, kEdsPropID_Evf_CoordinateSystem, 0, sizeof(size), &size));\n\t\tPropertyChanged(\"EVF Size! Height = \" + size.height + \", width = \" + size.width);\n\t\tLiveViewReadTask = Task::Factory->StartNew(gcnew Action(this, &Camera::LiveViewReadLoop));\n\t}\n\n\tvoid Camera::DeactivateLiveView()\n\t{\n\t\tif (CurrentCamera != this)\n\t\t{\n\t\t\tthrow gcnew CameraNotConnectedException();\n\t\t}\n\n\t\t\/\/ This is also taken straight from the reference docs.\n\t\tif (LiveViewImage == NULL || LiveViewStream == NULL)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tMonitor::Enter(LiveViewClosingLock);\n\t\t\tLiveViewClosing = true;\n\t\t}\n\t\tfinally\n\t\t{\n\t\t\tMonitor::Exit(LiveViewClosingLock);\n\t\t}\n\t\tLiveViewReadTask->Wait();\n\n\t\ttjDestroy(JpegDecompressor);\n\n\t\tErrorCheck(EdsRelease(LiveViewImage));\n\t\tErrorCheck(EdsRelease(LiveViewStream));\n\t\tLiveViewImage = NULL;\n\t\tLiveViewStream = NULL;\n\n\t\tEdsUInt32 propValue;\n\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t\tpropValue &= ~kEdsEvfOutputDevice_PC;\n\t\tErrorCheck(EdsSetPropertyData(CameraHandle, kEdsPropID_Evf_OutputDevice, 0, sizeof(propValue), &propValue));\n\t}\n\n\tint imgCounter = 0;\n\n\tvoid Camera::LiveViewReadLoop()\n\t{\n\t\twhile (true)\n\t\t{\n\t\t\t\/\/ Check to see if LiveView is closing, and return if it is.\n\t\t\ttry\n\t\t\t{\n\t\t\t\tMonitor::Enter(LiveViewClosingLock);\n\t\t\t\tif (LiveViewClosing)\n\t\t\t\t{\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t\tfinally\n\t\t\t{\n\t\t\t\tMonitor::Exit(LiveViewClosingLock);\n\t\t\t}\n\n\t\t\t\/\/ Download the image from the camera\n\t\t\tEdsError result = EdsDownloadEvfImage(CameraHandle, LiveViewImage);\n\t\t\tif (result == EDS_ERR_OBJECT_NOTREADY)\n\t\t\t{\n\t\t\t\tThread::Sleep(500);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\telse if (result == EDS_ERR_CANNOT_MAKE_OBJECT)\n\t\t\t{\n\t\t\t\tPropertyChanged(\"Can't make object :\/\");\n\t\t\t\tThread::Sleep(1000);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tErrorCheck(result);\n\n\t\t\tEdsUInt32 streamPos;\n\t\t\tEdsVoid* streamPtr;\n\t\t\tEdsImageRef imageRef;\n\t\t\tEdsImageInfo imageInfo;\n\t\t\tErrorCheck(EdsGetPosition(LiveViewStream, &streamPos));\n\t\t\tErrorCheck(EdsGetPointer(LiveViewStream, &streamPtr));\n\t\t\tErrorCheck(EdsCreateImageRef(LiveViewStream, &imageRef));\n\t\t\tErrorCheck(EdsGetImageInfo(imageRef, kEdsImageSrc_FullView, &imageInfo));\n\t\t\t\n\t\t\tint bytesPerPixel = imageInfo.componentDepth \/ 8;\n\t\t\tint numberOfChannels = imageInfo.numOfComponents;\n\t\t\tint width = imageInfo.width;\n\t\t\tint height = imageInfo.height;\n\t\t\tint totalSize = width * height * numberOfChannels * bytesPerPixel;\n\n\t\t\tunsigned char* jpegBuffer = reinterpret_cast(streamPtr);\n\n\n\n\t\t\t\/\/tjDecompress2(JpegDecompressor, jpegBuffer, totalSize, NULL, width, 0, height, TJPF_RGB, TJFLAG_FASTDCT);\n\n\t\t\tarray^ imgBytes = gcnew array(streamPos);\n\t\t\tMarshal::Copy((IntPtr)streamPtr, imgBytes, 0, imgBytes->Length);\n\t\t\tSystem::IO::File::WriteAllBytes(\"C:\\\\kappa\\\\img\" + (imgCounter++) + \".jpg\", imgBytes);\n\n\t\t\t\/\/ErrorCheck(EdsGetLength(LiveViewStream, &streamLength));\n\t\t\tPropertyChanged(\"New image!\" + Environment::NewLine + \n\t\t\t\t\"\\tPos = \" + streamPos + Environment::NewLine + \n\t\t\t\t\"\\tPtr = \" + ((unsigned int)streamPtr).ToString(\"X\") + Environment::NewLine + \n\t\t\t\t\"\\tHeight = \" + imageInfo.height + Environment::NewLine +\n\t\t\t\t\"\\tWidth = \" + imageInfo.width);\n\t\t\tThread::Sleep(1000);\n\t\t}\n\t}\n\n\tvoid Camera::RefreshSupportedIsoSpeeds()\n\t{\n\t\t_SupportedIsoSpeeds->Clear();\n\t\tEdsPropertyDesc isoSpeeds;\n\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_ISOSpeed, &isoSpeeds));\n\t\tfor (int i = 0; i < isoSpeeds.numElements; i++)\n\t\t{\n\t\t\tEdsInt32 speedValue = isoSpeeds.propDesc[i];\n\t\t\tIsoSpeed speed = IsoManager::GetIsoSpeed(speedValue);\n\t\t\t_SupportedIsoSpeeds->Add(speed);\n\t\t}\n\t}\n\n\tvoid Camera::RefreshSupportedExposureTimes()\n\t{\n\t\t_SupportedExposureTimes->Clear();\n\t\tEdsPropertyDesc exposureTimes;\n\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_Tv, &exposureTimes));\n\t\tfor (int i = 0; i < exposureTimes.numElements; i++)\n\t\t{\n\t\t\tEdsInt32 exposureValue = exposureTimes.propDesc[i];\n\t\t\tExposureTime exposure = ExposureTimeManager::GetExposureTime(exposureValue);\n\t\t\t_SupportedExposureTimes->Add(exposure);\n\t\t}\n\t}\n\n\tEdsError Camera::OnPropertyEvent(EdsPropertyEvent EventType,\n\t\tEdsPropertyID PropertyID,\n\t\tEdsUInt32 Param,\n\t\tEdsVoid* Context)\n\t{\n\t\tif (EventType == kEdsPropertyEvent_PropertyChanged)\n\t\t{\n\t\t\tOnPropertyValueChanged(PropertyID, Param);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tOnPropertyOptionsChanged(PropertyID, Param);\n\t\t}\n\t\treturn EDS_ERR_OK;\n\t}\n\n\tvoid Camera::OnPropertyValueChanged(EdsPropertyID PropertyID, EdsUInt32 Param)\n\t{\n\t\tswitch (PropertyID)\n\t\t{\n\t\t\tcase kEdsPropID_ISOSpeed: \/\/ ISO Speed\n\t\t\t{\n\t\t\t\tEdsUInt32 currentIsoValue;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_ISOSpeed, 0, sizeof(currentIsoValue), ¤tIsoValue));\n\t\t\t\t_Iso = IsoManager::GetIsoSpeed(currentIsoValue);\n\t\t\t\tIsoChanged(_Iso);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase kEdsPropID_AvailableShots: \/\/ How many pictures can fit in the available disk space\n\t\t\t{\n\t\t\t\tEdsUInt32 numShots;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_AvailableShots, 0, sizeof(numShots), &numShots));\n\t\t\t\t_PicturesRemaining = numShots;\n\t\t\t\tPicturesRemainingChanged(_PicturesRemaining);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase kEdsPropID_Tv: \/\/ Exposure time\n\t\t\t{\n\t\t\t\tEdsUInt32 exposure;\n\t\t\t\tErrorCheck(EdsGetPropertyData(CameraHandle, kEdsPropID_Tv, 0, sizeof(exposure), &exposure));\n\t\t\t\t_Exposure = ExposureTimeManager::GetExposureTime(exposure);\n\t\t\t\tExposureTimeChanged(_Exposure);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tdefault: \/\/ Anything that we haven't handled yet gets printed to the debug event\n\t\t\t\tPropertyChanged(\"PropertyValueChanged, Prop = \" + PropertyID.ToString(\"X\") + \", Param = \" + Param.ToString(\"X\"));\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tvoid Camera::OnPropertyOptionsChanged(EdsPropertyID PropertyID, EdsUInt32 Param)\n\t{\n\t\tswitch (PropertyID)\n\t\t{\n\t\tcase kEdsPropID_ISOSpeed: \/\/ ISO Speed\n\t\t{\n\t\t\tRefreshSupportedIsoSpeeds();\n\t\t\tSupportedIsoSpeedsChanged(_SupportedIsoSpeeds);\n\t\t\tbreak;\n\t\t}\n\t\tcase kEdsPropID_Tv: \/\/ Exposure time\n\t\t{\n\t\t\tRefreshSupportedExposureTimes();\n\t\t\tSupportedExposureTimesChanged(_SupportedExposureTimes);\n\t\t\tbreak;\n\t\t}\n\t\tcase kEdsPropID_Evf_AFMode:\n\t\t{\n\t\t\tEdsPropertyDesc afModes;\n\t\t\tErrorCheck(EdsGetPropertyDesc(CameraHandle, kEdsPropID_Evf_AFMode, &afModes));\n\t\t\tPropertyChanged(\"AF MODE OPTIONS:\");\n\t\t\tfor (int i = 0; i < afModes.numElements; i++)\n\t\t\t{\n\t\t\t\tEdsInt32 mode = afModes.propDesc[i];\n\t\t\t\tPropertyChanged(\"\\t\" + mode.ToString(\"X\"));\n\t\t\t}\n\t\t}\n\t\tdefault: \/\/ Anything that we haven't handled yet gets printed to the debug event\n\t\t\tPropertyChanged(\"PropertyOptionsChanged, Prop = \" + PropertyID.ToString(\"X\") + \", Param = \" + Param.ToString(\"X\"));\n\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 Kolibre\n *\n * This file is part of kolibre-clientcore.\n *\n * Kolibre-clientcore is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * Kolibre-clientcore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with kolibre-clientcore. If not, see .\n *\/\n\n#include \"Input.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ create a root logger\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"kolibre\"));\n\n\/\/ create logger which will become a child to logger kolibre.sampleclient\nlog4cxx::LoggerPtr sampleClientMainLog(log4cxx::Logger::getLogger(\"kolibre.sampleclient.main\"));\n\n\/\/ exit values: 0 -> NORMAL QUIT\n\/\/ 2 -> SIGINT\n\/\/ 3 -> SIGQUIT\n\/\/ 15 -> SIGTERM\n\/\/ 100 -> SLEEPTIMER TIMEOUT\n\/\/ 101 -> LOGIN FAILED\nint exitValue = 0;\nbool exitSignal = false;\nvoid handleSignal(int sig);\nvoid onSleepTimeout();\nvoid onInvalidAuth();\n\n\nchar* applicationPath;\nvoid usage()\n{\n printf(\"usage: %s [OPTIONS]\\n\", applicationPath);\n printf(\"OPTIONS\\n\");\n printf(\" -s \\t\\turl to Daisy Online service\\n\");\n printf(\" -u \\tusername for service, must be specified along with -s option\\n\");\n printf(\" -p \\tpassword for service, must be specified along with -s option\\n\");\n printf(\" -r \\t\\t\\tremember password for specified service\\n\");\n printf(\" -m \\t\\tpath to local media\\n\");\n printf(\" -l \\t\\tlanguage to use, options: sv, fi, en [default: en]\\n\");\n printf(\" -i \\t\\tpath to client configuration\\n\");\n printf(\" -c \\t\\tpath to log configuration\\n\");\n printf(\" -d \\t\\tpath to input device\\n\");\n printf(\" -a \\tstring to use as UserAgent\\n\");\n printf(\" -h \\t\\t\\tshow this message\\n\");\n printf(\"\\n\");\n printf(\"Note! You must specify either a Daisy Online service, a local media path\\n\");\n printf(\"or client configuration path.\\n\");\n printf(\" e.g. %s -s http:\/\/daisyonline.com\/service -u username -p password\\n\", applicationPath);\n printf(\" %s -m \/home\/user\/Media\\n\", applicationPath);\n printf(\" %s -i \/home\/user\/settings.ini\\n\", applicationPath);\n}\n\nint main(int argc, char **argv)\n{\n applicationPath = argv[0];\n if (argc < 2)\n {\n usage();\n return 1;\n }\n\n signal(SIGINT, handleSignal);\n signal(SIGQUIT, handleSignal);\n signal(SIGTERM, handleSignal);\n\n \/\/ variables for storing user arguments\n std::string serviceUrl, username, password = \"\";\n bool rememberPassword = false;\n std::string mediaPath = \"\";\n std::string language = \"en\"; \/\/ default to English\n std::string inputDev = \"\";\n std::string useragent = \"KolibreSampleClient\/0.0.1\";\n char *settingsPath = NULL;\n char *logConf = NULL;\n\n \/\/ parse user arguments\n int opt;\n while ((opt = getopt(argc, argv, \"s:u:p:rm:l:i:c:h\")) != -1)\n {\n switch (opt)\n {\n case 's':\n {\n serviceUrl = optarg;\n mediaPath = \"\";\n settingsPath = NULL;\n break;\n }\n case 'u':\n {\n username = optarg;\n break;\n }\n case 'p':\n {\n password = optarg;\n break;\n }\n case 'r':\n rememberPassword = true;\n break;\n case 'm':\n {\n serviceUrl = \"\";\n mediaPath = optarg;\n settingsPath = NULL;\n break;\n }\n case 'l':\n {\n if (strcmp(optarg, \"en\") == 0)\n {\n language = optarg;\n }\n else if (strcmp(optarg, \"sv\") == 0)\n {\n language = optarg;\n }\n else if (strcmp(optarg, \"fi\") == 0)\n {\n language = optarg;\n }\n break;\n }\n case 'i':\n {\n serviceUrl = \"\";\n mediaPath = \"\";\n settingsPath = optarg;\n break;\n }\n case 'c':\n {\n logConf = optarg;\n break;\n }\n case 'd':\n {\n inputDev = optarg;\n break;\n }\n case 'a':\n {\n useragent = optarg;\n break;\n }\n case 'h':\n {\n usage();\n return 0;\n }\n default:\n printf(\"Unknown option: %c\\n\", opt);\n break;\n }\n }\n\n \/\/ check user arguments\n if (serviceUrl.empty() && mediaPath.empty() && settingsPath == NULL)\n {\n usage();\n return 1;\n }\n else if (not serviceUrl.empty())\n {\n if (username.empty() || password.empty())\n {\n usage();\n return 1;\n }\n }\n\n \/\/ Setup logging\n try\n {\n if (logConf != NULL)\n {\n \/\/ set up a user defined configuration\n log4cxx::PropertyConfigurator::configure(logConf);\n }\n else\n {\n \/\/ set up a simple configuration that logs on the console\n log4cxx::BasicConfigurator::configure();\n }\n }\n catch (log4cxx::helpers::Exception&)\n {\n printf(\"Configuration of logger failed\\n\");\n return -1;\n }\n\n \/\/ Set language\n ClientCore::setLanguage(language);\n\n ClientCore *clientcore = new ClientCore(useragent);\n\n \/\/ add service or path or parse settings file\n if (not serviceUrl.empty())\n {\n clientcore->addDaisyOnlineService(\"main\", serviceUrl, username, password, rememberPassword);\n }\n else if (not mediaPath.empty())\n {\n clientcore->addFileSystemPath(\"main\", mediaPath);\n }\n else if (settingsPath != NULL)\n {\n GKeyFile *keyFile;\n GKeyFileFlags keyFileFlags = G_KEY_FILE_NONE;\n GError *error;\n\n \/\/ create a new GKeyFile object\n keyFile = g_key_file_new();\n\n \/\/ load data from file\n if (not g_key_file_load_from_file(keyFile, settingsPath, keyFileFlags, &error))\n {\n LOG4CXX_ERROR(sampleClientMainLog, \"error while loading file '\" << settingsPath << \"':\" << error->message);\n g_key_file_free(keyFile);\n delete clientcore;\n return -1;\n }\n\n \/\/ get all groups in file\n gchar **groups = NULL;\n gsize length = NULL;\n groups = g_key_file_get_groups(keyFile, &length);\n\n \/\/ loop through each group and search for matches\n for (unsigned long i = 0; i < length; i++)\n {\n \/\/ if group name contains 'DaisyOnlineService'\n if (strstr(groups[i], \"DaisyOnlineService\") != NULL)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Found DaisyOnline service group '\" << groups[i] << \"'\");\n bool missingKey = false;\n gchar *name, *url, *username, *password = NULL;\n\n \/\/ get key name\n name = g_key_file_get_string(keyFile, groups[i], \"NAME\", NULL);\n if (name == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'NAME'\");\n missingKey = true;\n }\n\n \/\/ get key url\n url = g_key_file_get_string(keyFile, groups[i], \"URL\", NULL);\n if (url == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'URL'\");\n missingKey = true;\n }\n\n \/\/ get key username\n username = g_key_file_get_string(keyFile, groups[i], \"USERNAME\", NULL);\n if (username == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'USERNAME'\");\n missingKey = true;\n }\n\n \/\/ get key password\n password = g_key_file_get_string(keyFile, groups[i], \"PASSWORD\", NULL);\n if (password == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'PASSWORD'\");\n missingKey = true;\n }\n\n if (not missingKey)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Adding '\" << name << \"' as a DaisyOnlineService\");\n clientcore->addDaisyOnlineService(name, url, username, password);\n }\n\n }\n \/\/ if group name contains 'FileSystemPath'\n else if (strstr(groups[i], \"FileSystemPath\") != NULL)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Found file system path group '\" << groups[i] << \"'\");\n bool missingKey = false;\n gchar *name, *path = NULL;\n\n \/\/ get key name\n name = g_key_file_get_string(keyFile, groups[i], \"NAME\", NULL);\n if (name == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'NAME'\");\n missingKey = true;\n }\n\n \/\/ get key path\n path = g_key_file_get_string(keyFile, groups[i], \"PATH\", NULL);\n if (path == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'PATH'\");\n missingKey = true;\n }\n\n if (not missingKey)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Adding '\" << name << \"' as a FileSystemPath\");\n clientcore->addFileSystemPath(name, path);\n }\n }\n }\n\n \/\/ free allocated memory\n g_strfreev(groups);\n g_key_file_free(keyFile);\n }\n\n \/\/ Connect slots to signals\n clientcore->sleepTimeout_signal.connect(&onSleepTimeout);\n clientcore->invalidAuth_signal.connect(&onInvalidAuth);\n Input *input = Input::Instance();\n input->keyPressed_signal.connect(boost::bind(&ClientCore::pushCommand, clientcore, _1));\n if(inputDev.compare(\"\") != 0)\n input->set_input_device(inputDev);\n\n \/\/ start client and wait for it to exit\n clientcore->start();\n while (clientcore->isRunning())\n usleep(100000);\n\n LOG4CXX_DEBUG(sampleClientMainLog, \"Deleting clientcore\");\n delete clientcore;\n\n LOG4CXX_DEBUG(sampleClientMainLog, \"Deleting input\");\n delete input;\n\n LOG4CXX_INFO(sampleClientMainLog, \"Exiting application with value \" << exitValue);\n return exitValue;\n}\n\n\/\/ Handle boost signals\nvoid onSleepTimeout()\n{\n exitValue = 100;\n}\n\n\/\/ Handle the different unix signals we might receive\nvoid handleSignal(int sig)\n{\n if (!exitSignal)\n {\n exitSignal = true;\n exitValue = sig;\n std::string signal;\n switch (sig)\n {\n case 2:\n signal = \"SIGINT\";\n break;\n case 3:\n signal = \"SIGQUIT\";\n break;\n case 15:\n signal = \"SIGTERM\";\n break;\n default:\n signal = \"UNKNOWN\";\n break;\n }\n LOG4CXX_INFO(sampleClientMainLog, \"Caught signal '\" << signal << \"' (\" << sig << \"), exiting application\");\n Input *input = Input::Instance();\n input->keyPressed_signal(ClientCore::EXIT);\n sleep(1);\n }\n}\n\nvoid onInvalidAuth() {\n if (!exitSignal)\n {\n exitSignal = true;\n exitValue = 101;\n\n LOG4CXX_INFO(sampleClientMainLog, \"Login failed, exiting application\");\n Input *input = Input::Instance();\n input->keyPressed_signal(ClientCore::EXIT);\n }\n}\n\nFix compile warning\/*\n * Copyright (C) 2012 Kolibre\n *\n * This file is part of kolibre-clientcore.\n *\n * Kolibre-clientcore is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * Kolibre-clientcore is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with kolibre-clientcore. If not, see .\n *\/\n\n#include \"Input.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ create a root logger\nlog4cxx::LoggerPtr logger(log4cxx::Logger::getLogger(\"kolibre\"));\n\n\/\/ create logger which will become a child to logger kolibre.sampleclient\nlog4cxx::LoggerPtr sampleClientMainLog(log4cxx::Logger::getLogger(\"kolibre.sampleclient.main\"));\n\n\/\/ exit values: 0 -> NORMAL QUIT\n\/\/ 2 -> SIGINT\n\/\/ 3 -> SIGQUIT\n\/\/ 15 -> SIGTERM\n\/\/ 100 -> SLEEPTIMER TIMEOUT\n\/\/ 101 -> LOGIN FAILED\nint exitValue = 0;\nbool exitSignal = false;\nvoid handleSignal(int sig);\nvoid onSleepTimeout();\nvoid onInvalidAuth();\n\n\nchar* applicationPath;\nvoid usage()\n{\n printf(\"usage: %s [OPTIONS]\\n\", applicationPath);\n printf(\"OPTIONS\\n\");\n printf(\" -s \\t\\turl to Daisy Online service\\n\");\n printf(\" -u \\tusername for service, must be specified along with -s option\\n\");\n printf(\" -p \\tpassword for service, must be specified along with -s option\\n\");\n printf(\" -r \\t\\t\\tremember password for specified service\\n\");\n printf(\" -m \\t\\tpath to local media\\n\");\n printf(\" -l \\t\\tlanguage to use, options: sv, fi, en [default: en]\\n\");\n printf(\" -i \\t\\tpath to client configuration\\n\");\n printf(\" -c \\t\\tpath to log configuration\\n\");\n printf(\" -d \\t\\tpath to input device\\n\");\n printf(\" -a \\tstring to use as UserAgent\\n\");\n printf(\" -h \\t\\t\\tshow this message\\n\");\n printf(\"\\n\");\n printf(\"Note! You must specify either a Daisy Online service, a local media path\\n\");\n printf(\"or client configuration path.\\n\");\n printf(\" e.g. %s -s http:\/\/daisyonline.com\/service -u username -p password\\n\", applicationPath);\n printf(\" %s -m \/home\/user\/Media\\n\", applicationPath);\n printf(\" %s -i \/home\/user\/settings.ini\\n\", applicationPath);\n}\n\nint main(int argc, char **argv)\n{\n applicationPath = argv[0];\n if (argc < 2)\n {\n usage();\n return 1;\n }\n\n signal(SIGINT, handleSignal);\n signal(SIGQUIT, handleSignal);\n signal(SIGTERM, handleSignal);\n\n \/\/ variables for storing user arguments\n std::string serviceUrl, username, password = \"\";\n bool rememberPassword = false;\n std::string mediaPath = \"\";\n std::string language = \"en\"; \/\/ default to English\n std::string inputDev = \"\";\n std::string useragent = \"KolibreSampleClient\/0.0.1\";\n char *settingsPath = NULL;\n char *logConf = NULL;\n\n \/\/ parse user arguments\n int opt;\n while ((opt = getopt(argc, argv, \"s:u:p:rm:l:i:c:h\")) != -1)\n {\n switch (opt)\n {\n case 's':\n {\n serviceUrl = optarg;\n mediaPath = \"\";\n settingsPath = NULL;\n break;\n }\n case 'u':\n {\n username = optarg;\n break;\n }\n case 'p':\n {\n password = optarg;\n break;\n }\n case 'r':\n rememberPassword = true;\n break;\n case 'm':\n {\n serviceUrl = \"\";\n mediaPath = optarg;\n settingsPath = NULL;\n break;\n }\n case 'l':\n {\n if (strcmp(optarg, \"en\") == 0)\n {\n language = optarg;\n }\n else if (strcmp(optarg, \"sv\") == 0)\n {\n language = optarg;\n }\n else if (strcmp(optarg, \"fi\") == 0)\n {\n language = optarg;\n }\n break;\n }\n case 'i':\n {\n serviceUrl = \"\";\n mediaPath = \"\";\n settingsPath = optarg;\n break;\n }\n case 'c':\n {\n logConf = optarg;\n break;\n }\n case 'd':\n {\n inputDev = optarg;\n break;\n }\n case 'a':\n {\n useragent = optarg;\n break;\n }\n case 'h':\n {\n usage();\n return 0;\n }\n default:\n printf(\"Unknown option: %c\\n\", opt);\n break;\n }\n }\n\n \/\/ check user arguments\n if (serviceUrl.empty() && mediaPath.empty() && settingsPath == NULL)\n {\n usage();\n return 1;\n }\n else if (not serviceUrl.empty())\n {\n if (username.empty() || password.empty())\n {\n usage();\n return 1;\n }\n }\n\n \/\/ Setup logging\n try\n {\n if (logConf != NULL)\n {\n \/\/ set up a user defined configuration\n log4cxx::PropertyConfigurator::configure(logConf);\n }\n else\n {\n \/\/ set up a simple configuration that logs on the console\n log4cxx::BasicConfigurator::configure();\n }\n }\n catch (log4cxx::helpers::Exception&)\n {\n printf(\"Configuration of logger failed\\n\");\n return -1;\n }\n\n \/\/ Set language\n ClientCore::setLanguage(language);\n\n ClientCore *clientcore = new ClientCore(useragent);\n\n \/\/ add service or path or parse settings file\n if (not serviceUrl.empty())\n {\n clientcore->addDaisyOnlineService(\"main\", serviceUrl, username, password, rememberPassword);\n }\n else if (not mediaPath.empty())\n {\n clientcore->addFileSystemPath(\"main\", mediaPath);\n }\n else if (settingsPath != NULL)\n {\n GKeyFile *keyFile;\n GKeyFileFlags keyFileFlags = G_KEY_FILE_NONE;\n GError *error;\n\n \/\/ create a new GKeyFile object\n keyFile = g_key_file_new();\n\n \/\/ load data from file\n if (not g_key_file_load_from_file(keyFile, settingsPath, keyFileFlags, &error))\n {\n LOG4CXX_ERROR(sampleClientMainLog, \"error while loading file '\" << settingsPath << \"':\" << error->message);\n g_key_file_free(keyFile);\n delete clientcore;\n return -1;\n }\n\n \/\/ get all groups in file\n gchar **groups = NULL;\n gsize length;\n groups = g_key_file_get_groups(keyFile, &length);\n\n \/\/ loop through each group and search for matches\n for (unsigned long i = 0; i < length; i++)\n {\n \/\/ if group name contains 'DaisyOnlineService'\n if (strstr(groups[i], \"DaisyOnlineService\") != NULL)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Found DaisyOnline service group '\" << groups[i] << \"'\");\n bool missingKey = false;\n gchar *name, *url, *username, *password = NULL;\n\n \/\/ get key name\n name = g_key_file_get_string(keyFile, groups[i], \"NAME\", NULL);\n if (name == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'NAME'\");\n missingKey = true;\n }\n\n \/\/ get key url\n url = g_key_file_get_string(keyFile, groups[i], \"URL\", NULL);\n if (url == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'URL'\");\n missingKey = true;\n }\n\n \/\/ get key username\n username = g_key_file_get_string(keyFile, groups[i], \"USERNAME\", NULL);\n if (username == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'USERNAME'\");\n missingKey = true;\n }\n\n \/\/ get key password\n password = g_key_file_get_string(keyFile, groups[i], \"PASSWORD\", NULL);\n if (password == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'PASSWORD'\");\n missingKey = true;\n }\n\n if (not missingKey)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Adding '\" << name << \"' as a DaisyOnlineService\");\n clientcore->addDaisyOnlineService(name, url, username, password);\n }\n\n }\n \/\/ if group name contains 'FileSystemPath'\n else if (strstr(groups[i], \"FileSystemPath\") != NULL)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Found file system path group '\" << groups[i] << \"'\");\n bool missingKey = false;\n gchar *name, *path = NULL;\n\n \/\/ get key name\n name = g_key_file_get_string(keyFile, groups[i], \"NAME\", NULL);\n if (name == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'NAME'\");\n missingKey = true;\n }\n\n \/\/ get key path\n path = g_key_file_get_string(keyFile, groups[i], \"PATH\", NULL);\n if (path == NULL)\n {\n LOG4CXX_WARN(sampleClientMainLog, \"Group '\" << groups[i] << \"' does not have key 'PATH'\");\n missingKey = true;\n }\n\n if (not missingKey)\n {\n LOG4CXX_INFO(sampleClientMainLog, \"Adding '\" << name << \"' as a FileSystemPath\");\n clientcore->addFileSystemPath(name, path);\n }\n }\n }\n\n \/\/ free allocated memory\n g_strfreev(groups);\n g_key_file_free(keyFile);\n }\n\n \/\/ Connect slots to signals\n clientcore->sleepTimeout_signal.connect(&onSleepTimeout);\n clientcore->invalidAuth_signal.connect(&onInvalidAuth);\n Input *input = Input::Instance();\n input->keyPressed_signal.connect(boost::bind(&ClientCore::pushCommand, clientcore, _1));\n if(inputDev.compare(\"\") != 0)\n input->set_input_device(inputDev);\n\n \/\/ start client and wait for it to exit\n clientcore->start();\n while (clientcore->isRunning())\n usleep(100000);\n\n LOG4CXX_DEBUG(sampleClientMainLog, \"Deleting clientcore\");\n delete clientcore;\n\n LOG4CXX_DEBUG(sampleClientMainLog, \"Deleting input\");\n delete input;\n\n LOG4CXX_INFO(sampleClientMainLog, \"Exiting application with value \" << exitValue);\n return exitValue;\n}\n\n\/\/ Handle boost signals\nvoid onSleepTimeout()\n{\n exitValue = 100;\n}\n\n\/\/ Handle the different unix signals we might receive\nvoid handleSignal(int sig)\n{\n if (!exitSignal)\n {\n exitSignal = true;\n exitValue = sig;\n std::string signal;\n switch (sig)\n {\n case 2:\n signal = \"SIGINT\";\n break;\n case 3:\n signal = \"SIGQUIT\";\n break;\n case 15:\n signal = \"SIGTERM\";\n break;\n default:\n signal = \"UNKNOWN\";\n break;\n }\n LOG4CXX_INFO(sampleClientMainLog, \"Caught signal '\" << signal << \"' (\" << sig << \"), exiting application\");\n Input *input = Input::Instance();\n input->keyPressed_signal(ClientCore::EXIT);\n sleep(1);\n }\n}\n\nvoid onInvalidAuth() {\n if (!exitSignal)\n {\n exitSignal = true;\n exitValue = 101;\n\n LOG4CXX_INFO(sampleClientMainLog, \"Login failed, exiting application\");\n Input *input = Input::Instance();\n input->keyPressed_signal(ClientCore::EXIT);\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright [2015] \n\/\/=====================================================================================\n\/\/\n\/\/ Filename: cmdIfElse.cpp\n\/\/\n\/\/ Description: if...else.. 分支支持\n\/\/\n\/\/ Version: 1.0\n\/\/ Created: 2015年01月28日 14时53分29秒\n\/\/ Revision: none\n\/\/ Compiler: gcc\n\/\/\n\/\/ Author: lgb (LiuGuangBao), easyeagel@gmx.com\n\/\/ Organization: ezbty.org\n\/\/\n\/\/=====================================================================================\n\/\/\n\n#include\"option.hpp\"\n#include\"script.hpp\"\n#include\"optionPredication.hpp\"\n\nnamespace ezsh\n{\n\nclass GroupHeadIf: public GroupPointBaseT>\n{\n typedef GroupPointBaseT> BaseThis;\npublic:\n GroupHeadIf(const char* msg=\"if - if group begin\")\n :BaseThis(msg)\n {}\n\n void doit()\n {\n predicationInit(mapGet());\n }\n\n void doDry()\n {\n BaseThis::doDry();\n return doit();\n }\n\n static const char* nameGet()\n {\n return \"if\";\n }\n\n bool needCall() const\n {\n return isPassed();\n }\n};\n\nclass GroupHeadElseIf: public GroupHeadIf\n{\npublic:\n GroupHeadElseIf()\n :GroupHeadIf(\"elseif - elseif branch of if group\")\n {}\n\n static const char* nameGet()\n {\n return \"elseif\";\n }\n};\n\nclass GroupHeadElse: public GroupPointBaseT\n{\n typedef GroupPointBaseT BaseThis;\npublic:\n GroupHeadElse()\n :BaseThis(\"else - else branch of if group\")\n {}\n\n void doit()\n {\n }\n\n static const char* nameGet()\n {\n return \"else\";\n }\n\n bool needCall() const\n {\n return true;\n }\n};\n\nclass GroupTailEndIf: public GroupPointBaseT\n{\n typedef GroupPointBaseT BaseThis;\npublic:\n GroupTailEndIf()\n :BaseThis(\"endif - if group end\")\n {}\n\n void doit()\n {\n }\n\n static const char* nameGet()\n {\n return \"endif\";\n }\n};\n\nclass CmdIfElse:public CommandGroupT\n{\n typedef CommandGroupT BaseThis;\npublic:\n CmdIfElse(const GroupCommand::BodySet& b, const ScriptCommand& e)\n : BaseThis(b, e)\n {}\n\n static CommandGroupTrait::Type_t typeCheck(CommandGroupTrait::CheckStatus& status, const std::string& str)\n {\n if(status.empty())\n status.resize(4, 0);\n\n if(str==GroupHeadIf::nameGet())\n {\n status[0] += 1;\n return CommandGroupTrait::eHead;\n }\n\n if(str==GroupHeadElseIf::nameGet())\n {\n status[1] += 1;\n return CommandGroupTrait::eMiddle;\n }\n\n if(str==GroupHeadElse::nameGet())\n {\n auto& c=status[2];\n c += 1;\n if(c>1) \/\/esle 只能出现一次\n return CommandGroupTrait::eNone;\n return CommandGroupTrait::eMiddle;\n }\n\n if(str==GroupTailEndIf::nameGet())\n {\n status[3] += 1;\n return CommandGroupTrait::eTail;\n }\n\n return CommandGroupTrait::eNone;\n }\n\n void taskDoit()\n {\n tail_.oldContextSet(this->contextGet());\n auto ctx=this->contextGet()->alloc();\n contextGet()->yield([this, &ctx]()\n {\n this->contextStart(ctx);\n }\n );\n }\n\n template\n bool call(const ContextSPtr& ctx, const GroupCommand::Body& body)\n {\n Cmd cmd;\n cmd.oldContextSet(this->contextGet());\n body.head.init(this->ecGet(), ctx, cmd);\n if(this->bad())\n return false;\n\n cmd.doit();\n if(cmd.bad())\n {\n this->ecSet(cmd.ecGet());\n return false;\n }\n\n if(!cmd.needCall())\n return false;\n\n const auto& script=*body.script;\n script.execute(this->ecGet(), ctx);\n return true;\n }\n\nprivate:\n void contextStart(const ContextSPtr& ctx)\n {\n ctx->start([this, &ctx]()\n {\n auto itr=scBody_.begin();\n auto const end=scBody_.end();\n\n assert(itr!=end);\n \n \/\/循环处理可能的 if elseif\n for(;; ++itr)\n {\n if(itr==end)\n break;\n\n const auto& sc=itr->head;\n if(sc.cmdGet()==GroupHeadIf::nameGet())\n {\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n } else if(sc.cmdGet()==GroupHeadElseIf::nameGet()) {\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n } else {\n assert(sc.cmdGet()==GroupHeadElse::nameGet());\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n }\n }\n\n scTail_.init(this->ecGet(), ctx, tail_);\n if(this->bad())\n return;\n\n tail_.taskDoit();\n if(tail_.bad())\n this->ecSet(tail_.ecGet());\n }\n );\n }\n\nprivate:\n GroupTailEndIf tail_;\n};\n\nnamespace\n{\n CommandGroupRegister gsCommandGroupRegister;\n}\n\n}\n\n没有合适唤醒上层协程\/\/ Copyright [2015] \n\/\/=====================================================================================\n\/\/\n\/\/ Filename: cmdIfElse.cpp\n\/\/\n\/\/ Description: if...else.. 分支支持\n\/\/\n\/\/ Version: 1.0\n\/\/ Created: 2015年01月28日 14时53分29秒\n\/\/ Revision: none\n\/\/ Compiler: gcc\n\/\/\n\/\/ Author: lgb (LiuGuangBao), easyeagel@gmx.com\n\/\/ Organization: ezbty.org\n\/\/\n\/\/=====================================================================================\n\/\/\n\n#include\"option.hpp\"\n#include\"script.hpp\"\n#include\"optionPredication.hpp\"\n\nnamespace ezsh\n{\n\nclass GroupHeadIf: public GroupPointBaseT>\n{\n typedef GroupPointBaseT> BaseThis;\npublic:\n GroupHeadIf(const char* msg=\"if - if group begin\")\n :BaseThis(msg)\n {}\n\n void doit()\n {\n predicationInit(mapGet());\n }\n\n void doDry()\n {\n BaseThis::doDry();\n return doit();\n }\n\n static const char* nameGet()\n {\n return \"if\";\n }\n\n bool needCall() const\n {\n return isPassed();\n }\n};\n\nclass GroupHeadElseIf: public GroupHeadIf\n{\npublic:\n GroupHeadElseIf()\n :GroupHeadIf(\"elseif - elseif branch of if group\")\n {}\n\n static const char* nameGet()\n {\n return \"elseif\";\n }\n};\n\nclass GroupHeadElse: public GroupPointBaseT\n{\n typedef GroupPointBaseT BaseThis;\npublic:\n GroupHeadElse()\n :BaseThis(\"else - else branch of if group\")\n {}\n\n void doit()\n {\n }\n\n static const char* nameGet()\n {\n return \"else\";\n }\n\n bool needCall() const\n {\n return true;\n }\n};\n\nclass GroupTailEndIf: public GroupPointBaseT\n{\n typedef GroupPointBaseT BaseThis;\npublic:\n GroupTailEndIf()\n :BaseThis(\"endif - if group end\")\n {}\n\n void doit()\n {\n }\n\n static const char* nameGet()\n {\n return \"endif\";\n }\n};\n\nclass CmdIfElse:public CommandGroupT\n{\n typedef CommandGroupT BaseThis;\npublic:\n CmdIfElse(const GroupCommand::BodySet& b, const ScriptCommand& e)\n : BaseThis(b, e)\n {}\n\n static CommandGroupTrait::Type_t typeCheck(CommandGroupTrait::CheckStatus& status, const std::string& str)\n {\n if(status.empty())\n status.resize(4, 0);\n\n if(str==GroupHeadIf::nameGet())\n {\n status[0] += 1;\n return CommandGroupTrait::eHead;\n }\n\n if(str==GroupHeadElseIf::nameGet())\n {\n status[1] += 1;\n return CommandGroupTrait::eMiddle;\n }\n\n if(str==GroupHeadElse::nameGet())\n {\n auto& c=status[2];\n c += 1;\n if(c>1) \/\/esle 只能出现一次\n return CommandGroupTrait::eNone;\n return CommandGroupTrait::eMiddle;\n }\n\n if(str==GroupTailEndIf::nameGet())\n {\n status[3] += 1;\n return CommandGroupTrait::eTail;\n }\n\n return CommandGroupTrait::eNone;\n }\n\n void taskDoit()\n {\n tail_.oldContextSet(this->contextGet());\n auto ctx=this->contextGet()->alloc();\n contextGet()->yield([this, &ctx]()\n {\n this->contextStart(ctx);\n }\n );\n }\n\n template\n bool call(const ContextSPtr& ctx, const GroupCommand::Body& body)\n {\n Cmd cmd;\n cmd.oldContextSet(this->contextGet());\n body.head.init(this->ecGet(), ctx, cmd);\n if(this->bad())\n return false;\n\n cmd.doit();\n if(cmd.bad())\n {\n this->ecSet(cmd.ecGet());\n return false;\n }\n\n if(!cmd.needCall())\n return false;\n\n const auto& script=*body.script;\n script.execute(this->ecGet(), ctx);\n return true;\n }\n\nprivate:\n void contextStart(const ContextSPtr& ctx)\n {\n ctx->start([this, &ctx]()\n {\n auto itr=scBody_.begin();\n auto const end=scBody_.end();\n\n assert(itr!=end);\n \n \/\/循环处理可能的 if elseif\n for(;; ++itr)\n {\n if(itr==end)\n break;\n\n const auto& sc=itr->head;\n if(sc.cmdGet()==GroupHeadIf::nameGet())\n {\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n } else if(sc.cmdGet()==GroupHeadElseIf::nameGet()) {\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n } else {\n assert(sc.cmdGet()==GroupHeadElse::nameGet());\n auto const called=call(ctx, *itr);\n if(this->bad())\n return;\n if(called)\n break;\n continue;\n }\n }\n\n scTail_.init(this->ecGet(), ctx, tail_);\n if(this->bad())\n return;\n\n tail_.taskDoit();\n if(tail_.bad())\n this->ecSet(tail_.ecGet());\n\n core::MainServer::post([this]()\n {\n this->contextGet()->resume();\n }\n );\n }\n );\n }\n\nprivate:\n GroupTailEndIf tail_;\n};\n\nnamespace\n{\n CommandGroupRegister gsCommandGroupRegister;\n}\n\n}\n\n<|endoftext|>"} {"text":"#include \"VISIRenderer.hpp\"\n#include \n#include \n#include \n#include \"athena\/Global.hpp\"\n#include \"logvisor\/logvisor.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#define MWM_HINTS_FUNCTIONS (1L << 0)\n#define MWM_HINTS_DECORATIONS (1L << 1)\n\n#define MWM_DECOR_BORDER (1L<<1)\n#define MWM_DECOR_RESIZEH (1L<<2)\n#define MWM_DECOR_TITLE (1L<<3)\n#define MWM_DECOR_MENU (1L<<4)\n#define MWM_DECOR_MINIMIZE (1L<<5)\n#define MWM_DECOR_MAXIMIZE (1L<<6)\n\n#define MWM_FUNC_RESIZE (1L<<1)\n#define MWM_FUNC_MOVE (1L<<2)\n#define MWM_FUNC_MINIMIZE (1L<<3)\n#define MWM_FUNC_MAXIMIZE (1L<<4)\n#define MWM_FUNC_CLOSE (1L<<5)\n\ntypedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);\nstatic glXCreateContextAttribsARBProc glXCreateContextAttribsARB = 0;\n\nstatic const int ContextAttribList[7][7] =\n{\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 5,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 4,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 3,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 2,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 1,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 0,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 3,\n GLX_CONTEXT_MINOR_VERSION_ARB, 3,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n};\n\nstatic bool s_glxError;\nstatic int ctxErrorHandler(Display *dpy, XErrorEvent *ev)\n{\n s_glxError = true;\n return 0;\n}\n\nstatic logvisor::Module Log(\"visigen-xlib\");\nstatic logvisor::Module AthenaLog(\"Athena\");\nstatic void AthenaExc(athena::error::Level level, const char* file,\n const char*, int line, const char* fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n AthenaLog.report(logvisor::Level(level), fmt, ap);\n va_end(ap);\n}\n\nstatic Display* xDisp;\nstatic Window windowId;\n\nstatic void UpdatePercent(float percent)\n{\n XLockDisplay(xDisp);\n char title[256];\n snprintf(title, 256, \"VISIGen [%g%%]\", percent * 100.f);\n XChangeProperty(xDisp, windowId, XA_WM_NAME, XA_STRING, 8,\n PropModeReplace, (unsigned char*)title, strlen(title));\n XUnlockDisplay(xDisp);\n}\n\n\/* Empty handler for SIGINT *\/\nstatic void _sigint(int) {}\n\nint main(int argc, const char** argv)\n{\n if (argc > 1 && !strcmp(argv[1], \"--dlpackage\"))\n {\n printf(\"%s\\n\", URDE_DLPACKAGE);\n return 100;\n }\n\n \/* Program is portable to all locales *\/\n setlocale(LC_ALL, \"\");\n\n logvisor::RegisterStandardExceptions();\n logvisor::RegisterConsoleLogger();\n atSetExceptionHandler(AthenaExc);\n VISIRenderer renderer(argc, argv);\n\n if (!XInitThreads())\n {\n Log.report(logvisor::Error, \"X doesn't support multithreading\");\n return 1;\n }\n\n \/* Open Xlib Display *\/\n xDisp = XOpenDisplay(0);\n if (!xDisp)\n {\n Log.report(logvisor::Error, \"Can't open X display\");\n return 1;\n }\n\n \/* Default screen *\/\n int xDefaultScreen = DefaultScreen(xDisp);\n Screen* screen = ScreenOfDisplay(xDisp, xDefaultScreen);\n\n \/* Query framebuffer configurations *\/\n GLXFBConfig* fbConfigs = nullptr;\n int numFBConfigs = 0;\n fbConfigs = glXGetFBConfigs(xDisp, xDefaultScreen, &numFBConfigs);\n if (!fbConfigs || numFBConfigs == 0)\n {\n Log.report(logvisor::Error, \"glXGetFBConfigs failed\");\n return 1;\n }\n\n int selVisualId = -1;\n GLXFBConfig selFBConfig = nullptr;\n for (int i=0 ; i= 32 && depthSize >= 24)\n {\n selFBConfig = config;\n selVisualId = visualId;\n break;\n }\n }\n XFree(fbConfigs);\n\n if (!selFBConfig)\n {\n Log.report(logvisor::Error, \"unable to find suitable pixel format\");\n return 1;\n }\n\n XVisualInfo visTemplate = {};\n visTemplate.screen = xDefaultScreen;\n int numVisuals;\n XVisualInfo* visualList = XGetVisualInfo(xDisp, VisualScreenMask, &visTemplate, &numVisuals);\n Visual* selectedVisual = nullptr;\n for (int i=0 ; iroot, selectedVisual, AllocNone);\n\n \/* Create window *\/\n XSetWindowAttributes swa;\n swa.colormap = colormapId;\n swa.border_pixmap = 0;\n swa.event_mask = 0;\n\n int instIdx = -1;\n if (argc > 3)\n instIdx = atoi(argv[3]);\n\n int x = 0;\n int y = 0;\n if (instIdx != -1)\n {\n x = (instIdx & 1) != 0;\n y = (instIdx & 2) != 0;\n }\n\n windowId = XCreateWindow(xDisp, screen->root, x, y, 768, 512, 10,\n CopyFromParent, CopyFromParent, selectedVisual,\n CWBorderPixel | CWEventMask | CWColormap, &swa);\n\n if (!glXCreateContextAttribsARB)\n {\n glXCreateContextAttribsARB = (glXCreateContextAttribsARBProc)\n glXGetProcAddressARB((const GLubyte*)\"glXCreateContextAttribsARB\");\n if (!glXCreateContextAttribsARB)\n {\n Log.report(logvisor::Error, \"unable to resolve glXCreateContextAttribsARB\");\n return 1;\n }\n }\n\n s_glxError = false;\n XErrorHandler oldHandler = XSetErrorHandler(ctxErrorHandler);\n GLXContext glxCtx = nullptr;\n for (int attribIdx=0 ; attribIdx::value ; ++attribIdx)\n {\n glxCtx = glXCreateContextAttribsARB(xDisp, selFBConfig, nullptr, True, ContextAttribList[attribIdx]);\n if (glxCtx)\n break;\n }\n XSetErrorHandler(oldHandler);\n if (!glxCtx)\n {\n Log.report(logvisor::Fatal, \"unable to make new GLX context\");\n return 1;\n }\n GLXWindow glxWindow = glXCreateWindow(xDisp, selFBConfig, windowId, nullptr);\n if (!glxWindow)\n {\n Log.report(logvisor::Fatal, \"unable to make new GLX window\");\n return 1;\n }\n\n XMapWindow(xDisp, windowId);\n\n struct\n {\n unsigned long flags;\n unsigned long functions;\n unsigned long decorations;\n long inputMode;\n unsigned long status;\n } wmHints = {0};\n\n Atom motifWmHints = XInternAtom(xDisp, \"_MOTIF_WM_HINTS\", True);\n if (motifWmHints)\n {\n wmHints.flags = MWM_HINTS_DECORATIONS | MWM_HINTS_FUNCTIONS;\n wmHints.decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;\n wmHints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;\n XChangeProperty(xDisp, windowId, motifWmHints, motifWmHints, 32, PropModeReplace, (unsigned char*)&wmHints, 5);\n }\n\n \/* SIGINT will be used to cancel main thread when client thread ends\n * (also enables graceful quitting via ctrl-c) *\/\n pthread_t mainThread = pthread_self();\n struct sigaction s;\n s.sa_handler = _sigint;\n sigemptyset(&s.sa_mask);\n s.sa_flags = 0;\n sigaction(SIGINT, &s, nullptr);\n sigaction(SIGUSR2, &s, nullptr);\n\n sigset_t waitmask, origmask;\n sigemptyset(&waitmask);\n sigaddset(&waitmask, SIGINT);\n sigaddset(&waitmask, SIGUSR2);\n pthread_sigmask(SIG_BLOCK, &waitmask, &origmask);\n\n int x11Fd = ConnectionNumber(xDisp);\n\n \/* Spawn client thread *\/\n bool clientRunning = true;\n std::mutex initmt;\n std::condition_variable initcv;\n std::unique_lock outerLk(initmt);\n std::thread clientThread([&]()\n {\n std::unique_lock innerLk(initmt);\n innerLk.unlock();\n initcv.notify_one();\n\n XLockDisplay(xDisp);\n if (!glXMakeContextCurrent(xDisp, glxWindow, glxWindow, glxCtx))\n Log.report(logvisor::Fatal, \"unable to make GLX context current\");\n XUnlockDisplay(xDisp);\n\n renderer.Run(UpdatePercent);\n clientRunning = false;\n\n XLockDisplay(xDisp);\n XClientMessageEvent exitEvent = {};\n exitEvent.type = ClientMessage;\n exitEvent.window = windowId;\n exitEvent.format = 32;\n XSendEvent(xDisp, windowId, 0, 0, (XEvent*)&exitEvent);\n XFlush(xDisp);\n XUnlockDisplay(xDisp);\n });\n initcv.wait(outerLk);\n\n \/* Begin application event loop *\/\n while (clientRunning)\n {\n fd_set fds;\n FD_ZERO(&fds);\n FD_SET(x11Fd, &fds);\n if (pselect(x11Fd+1, &fds, NULL, NULL, NULL, &origmask) < 0)\n {\n \/* SIGINT\/SIGUSR2 handled here *\/\n if (errno == EINTR)\n break;\n }\n\n if (FD_ISSET(x11Fd, &fds))\n {\n XLockDisplay(xDisp);\n while (XPending(xDisp))\n {\n XEvent event;\n XNextEvent(xDisp, &event);\n if (XFilterEvent(&event, None)) continue;\n }\n XUnlockDisplay(xDisp);\n }\n }\n\n renderer.Terminate();\n if (clientThread.joinable())\n clientThread.join();\n\n return renderer.ReturnVal();\n}\nMinor visigen cleanup and GLX fix#include \"VISIRenderer.hpp\"\n#include \n#include \n#include \n#include \"athena\/Global.hpp\"\n#include \"logvisor\/logvisor.hpp\"\n#include \n#include \n#include \n#include \n#include \n\n#define MWM_HINTS_FUNCTIONS (1L << 0)\n#define MWM_HINTS_DECORATIONS (1L << 1)\n\n#define MWM_DECOR_BORDER (1L<<1)\n#define MWM_DECOR_RESIZEH (1L<<2)\n#define MWM_DECOR_TITLE (1L<<3)\n#define MWM_DECOR_MENU (1L<<4)\n#define MWM_DECOR_MINIMIZE (1L<<5)\n#define MWM_DECOR_MAXIMIZE (1L<<6)\n\n#define MWM_FUNC_RESIZE (1L<<1)\n#define MWM_FUNC_MOVE (1L<<2)\n#define MWM_FUNC_MINIMIZE (1L<<3)\n#define MWM_FUNC_MAXIMIZE (1L<<4)\n#define MWM_FUNC_CLOSE (1L<<5)\n\ntypedef GLXContext (*glXCreateContextAttribsARBProc)(Display*, GLXFBConfig, GLXContext, Bool, const int*);\nstatic glXCreateContextAttribsARBProc glXCreateContextAttribsARB = nullptr;\n\nstatic const int ContextAttribList[7][7] =\n{\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 5,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 4,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 3,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 2,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 1,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 4,\n GLX_CONTEXT_MINOR_VERSION_ARB, 0,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n{ GLX_CONTEXT_MAJOR_VERSION_ARB, 3,\n GLX_CONTEXT_MINOR_VERSION_ARB, 3,\n GLX_CONTEXT_FLAGS_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB,\n 0\n},\n};\n\nstatic bool s_glxError;\nstatic int ctxErrorHandler(Display *\/*dpy*\/, XErrorEvent *\/*ev*\/)\n{\n s_glxError = true;\n return 0;\n}\n\nstatic logvisor::Module Log(\"visigen-xlib\");\nstatic logvisor::Module AthenaLog(\"Athena\");\nstatic void AthenaExc(athena::error::Level level, const char* \/*file*\/,\n const char*, int \/*line*\/, const char* fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n AthenaLog.report(logvisor::Level(level), fmt, ap);\n va_end(ap);\n}\n\nstatic Display* xDisp;\nstatic Window windowId;\n\nstatic void UpdatePercent(float percent)\n{\n XLockDisplay(xDisp);\n char title[256];\n snprintf(title, 256, \"VISIGen [%g%%]\", double(percent * 100.f));\n XChangeProperty(xDisp, windowId, XA_WM_NAME, XA_STRING, 8,\n PropModeReplace, reinterpret_cast(title), int(strlen(title)));\n XUnlockDisplay(xDisp);\n}\n\n\/* Empty handler for SIGINT *\/\nstatic void _sigint(int) {}\n\nint main(int argc, const char** argv)\n{\n if (argc > 1 && !strcmp(argv[1], \"--dlpackage\"))\n {\n printf(\"%s\\n\", URDE_DLPACKAGE);\n return 100;\n }\n\n \/* Program is portable to all locales *\/\n setlocale(LC_ALL, \"\");\n\n logvisor::RegisterStandardExceptions();\n logvisor::RegisterConsoleLogger();\n atSetExceptionHandler(AthenaExc);\n VISIRenderer renderer(argc, argv);\n\n if (!XInitThreads())\n {\n Log.report(logvisor::Error, \"X doesn't support multithreading\");\n return 1;\n }\n\n \/* Open Xlib Display *\/\n xDisp = XOpenDisplay(nullptr);\n if (!xDisp)\n {\n Log.report(logvisor::Error, \"Can't open X display\");\n return 1;\n }\n\n \/* Default screen *\/\n int xDefaultScreen = DefaultScreen(xDisp);\n Screen* screen = ScreenOfDisplay(xDisp, xDefaultScreen);\n\n \/* Query framebuffer configurations *\/\n GLXFBConfig* fbConfigs = nullptr;\n int numFBConfigs = 0;\n fbConfigs = glXGetFBConfigs(xDisp, xDefaultScreen, &numFBConfigs);\n if (!fbConfigs || numFBConfigs == 0)\n {\n Log.report(logvisor::Error, \"glXGetFBConfigs failed\");\n return 1;\n }\n\n VisualID selVisualId = 0;\n GLXFBConfig selFBConfig = nullptr;\n for (int i=0 ; i= 32 && depthSize >= 24 && visualId != 0)\n {\n selFBConfig = config;\n selVisualId = VisualID(visualId);\n break;\n }\n }\n XFree(fbConfigs);\n\n if (!selFBConfig)\n {\n Log.report(logvisor::Error, \"unable to find suitable pixel format\");\n return 1;\n }\n\n XVisualInfo visTemplate = {};\n visTemplate.screen = xDefaultScreen;\n int numVisuals;\n XVisualInfo* visualList = XGetVisualInfo(xDisp, VisualScreenMask, &visTemplate, &numVisuals);\n Visual* selectedVisual = nullptr;\n for (int i=0 ; iroot, selectedVisual, AllocNone);\n\n \/* Create window *\/\n XSetWindowAttributes swa;\n swa.colormap = colormapId;\n swa.border_pixmap = 0;\n swa.event_mask = 0;\n\n int instIdx = -1;\n if (argc > 3)\n instIdx = atoi(argv[3]);\n\n int x = 0;\n int y = 0;\n if (instIdx != -1)\n {\n x = (instIdx & 1) != 0;\n y = (instIdx & 2) != 0;\n }\n\n windowId = XCreateWindow(xDisp, screen->root, x, y, 768, 512, 10,\n CopyFromParent, CopyFromParent, selectedVisual,\n CWBorderPixel | CWEventMask | CWColormap, &swa);\n\n if (!glXCreateContextAttribsARB)\n {\n glXCreateContextAttribsARB = reinterpret_cast(\n glXGetProcAddressARB(reinterpret_cast(\"glXCreateContextAttribsARB\")));\n if (!glXCreateContextAttribsARB)\n {\n Log.report(logvisor::Error, \"unable to resolve glXCreateContextAttribsARB\");\n return 1;\n }\n }\n\n s_glxError = false;\n XErrorHandler oldHandler = XSetErrorHandler(ctxErrorHandler);\n GLXContext glxCtx = nullptr;\n for (uint32_t attribIdx=0 ; attribIdx::value ; ++attribIdx)\n {\n glxCtx = glXCreateContextAttribsARB(xDisp, selFBConfig, nullptr, True, ContextAttribList[attribIdx]);\n if (glxCtx)\n break;\n }\n XSetErrorHandler(oldHandler);\n if (!glxCtx)\n {\n Log.report(logvisor::Fatal, \"unable to make new GLX context\");\n return 1;\n }\n GLXWindow glxWindow = glXCreateWindow(xDisp, selFBConfig, windowId, nullptr);\n if (!glxWindow)\n {\n Log.report(logvisor::Fatal, \"unable to make new GLX window\");\n return 1;\n }\n\n XMapWindow(xDisp, windowId);\n\n struct\n {\n unsigned long flags = 0;\n unsigned long functions = 0;\n unsigned long decorations = 0;\n long inputMode = 0;\n unsigned long status = 0;\n } wmHints;\n\n Atom motifWmHints = XInternAtom(xDisp, \"_MOTIF_WM_HINTS\", True);\n if (motifWmHints)\n {\n wmHints.flags = MWM_HINTS_DECORATIONS | MWM_HINTS_FUNCTIONS;\n wmHints.decorations |= MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MINIMIZE | MWM_DECOR_MENU;\n wmHints.functions |= MWM_FUNC_MOVE | MWM_FUNC_MINIMIZE;\n XChangeProperty(xDisp, windowId, motifWmHints, motifWmHints, 32, PropModeReplace, reinterpret_cast(&wmHints), 5);\n }\n\n \/* SIGINT will be used to cancel main thread when client thread ends\n * (also enables graceful quitting via ctrl-c) *\/\n pthread_t mainThread = pthread_self();\n struct sigaction s;\n s.sa_handler = _sigint;\n sigemptyset(&s.sa_mask);\n s.sa_flags = 0;\n sigaction(SIGINT, &s, nullptr);\n sigaction(SIGUSR2, &s, nullptr);\n\n sigset_t waitmask, origmask;\n sigemptyset(&waitmask);\n sigaddset(&waitmask, SIGINT);\n sigaddset(&waitmask, SIGUSR2);\n pthread_sigmask(SIG_BLOCK, &waitmask, &origmask);\n\n int x11Fd = ConnectionNumber(xDisp);\n\n \/* Spawn client thread *\/\n bool clientRunning = true;\n std::mutex initmt;\n std::condition_variable initcv;\n std::unique_lock outerLk(initmt);\n std::thread clientThread([&]()\n {\n std::unique_lock innerLk(initmt);\n innerLk.unlock();\n initcv.notify_one();\n\n XLockDisplay(xDisp);\n if (!glXMakeContextCurrent(xDisp, glxWindow, glxWindow, glxCtx))\n Log.report(logvisor::Fatal, \"unable to make GLX context current\");\n XUnlockDisplay(xDisp);\n\n renderer.Run(UpdatePercent);\n clientRunning = false;\n\n XLockDisplay(xDisp);\n XClientMessageEvent exitEvent = {};\n exitEvent.type = ClientMessage;\n exitEvent.window = windowId;\n exitEvent.format = 32;\n XSendEvent(xDisp, windowId, 0, 0, reinterpret_cast(&exitEvent));\n XFlush(xDisp);\n XUnlockDisplay(xDisp);\n });\n initcv.wait(outerLk);\n\n \/* Begin application event loop *\/\n while (clientRunning)\n {\n fd_set fds;\n FD_ZERO(&fds);\n FD_SET(x11Fd, &fds);\n if (pselect(x11Fd+1, &fds, nullptr, nullptr, nullptr, &origmask) < 0)\n {\n \/* SIGINT\/SIGUSR2 handled here *\/\n if (errno == EINTR || errno == SIGUSR2)\n break;\n }\n\n if (FD_ISSET(x11Fd, &fds))\n {\n XLockDisplay(xDisp);\n while (XPending(xDisp))\n {\n XEvent event;\n XNextEvent(xDisp, &event);\n if (XFilterEvent(&event, None)) continue;\n }\n XUnlockDisplay(xDisp);\n }\n }\n\n renderer.Terminate();\n pthread_cancel(clientThread.native_handle());\n if (clientThread.joinable())\n clientThread.join();\n\n return renderer.ReturnVal();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nusing namespace std;\n\n\/\/util classes\nstruct Input {\n\tint r, c, l, h;\n\tvector> tomatoes;\n};\n\nstruct Slice {\n\tint r1, c1, r2, c2;\n};\n\nstruct Output {\n\tvector slices;\n};\n\n\nbool checkSlice(Input &input, Slice &s)\n{\n\tbool t = false;\n\tbool f = false;\n\tfor (int j = s.c1; j <= s.c2; j++)\n\t{\n\t\tif (input.tomatoes[s.r1][j])\n\t\t\tt = true;\n\t\telse\n\t\t\tf = true;\n\n\t\tif (t == true && f == true)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid solveSimpleHorizontal(Input& input, Output& output) {\n\tfor (int i = 0; i < input.r; i++)\n\t{\n\t\tfor (int j = 0; j < input.c; j += input.h)\n\t\t{\n\t\t\tSlice s;\n\t\t\ts.r1 = i;\n\t\t\ts.c1 = j;\n\t\t\ts.r2 = i;\n\t\t\ts.c2 = min(j+input.h-1, input.c-1);\n\t\t\tif (checkSlice(input, s))\n\t\t\t\toutput.slices.push_back(s);\n\t\t}\n\t}\n}\n\nvoid solveSimpleVertical(Input& input, Output& output) {\n\tfor (int j = 0; j < input.c; j++)\n\t{\n\t\tfor (int i = 0; i < input.r; i += input.h)\n\t\t{\n\t\t\tSlice s;\n\t\t\ts.r1 = i;\n\t\t\ts.c1 = j;\n\t\t\ts.r2 = min(i+input.h-1, input.r-1);\n\t\t\ts.c2 = j;\n\t\t\tif (checkSlice(input, s))\n\t\t\t\toutput.slices.push_back(s);\n\t\t}\n\t}\n}\n\n\n\nint add_slice(const vector &a, int l, int r)\t{\n\tint cnt1 = 0, cnt2 = 0;\n\tfor (int i = l; i <= r; i++)\n\t\tif (a[i])\n\t\t\tcnt1++;\n\t\telse\n\t\t\tcnt2++;\n\t\n\tif (cnt1 >= l && cnt2 >= l)\n\t\treturn r-l+1;\n\treturn 0;\n}\n\nvoid solve_row(const vector &a, int row_num, int n, int l, int h, vector &ans)\t{\n\tvector d(n,0), prev(n,0);\n\t\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 2*l; j <= h; j++)\n\t\t\t if (i-j+1 >= 0)\n\t\t\t {\n\t\t\t \tint temp = add_slice(a,i-j+1,i);\n\t\t\t \tif (d[i] < d[i-j+1] + temp)\n\t\t\t\t{\n\t\t\t \t\td[i] = d[i-j+1] + temp;\n\t\t\t\t\tprev[i] = i-j+1;\n\t\t\t \t}\n\t\t\t}\n\t\t\n\tint i_max = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tif (d[i] > d[i_max])\n\t\t\ti_max = i;\n\t\n\tSlice c;\t\t\n\tc.r1 = c.r2 = row_num;\n\t\n\tfor (int i = i_max; i > 0; i--)\n\t{\n\t\tc.c1 = prev[i]; c.c2 = i;\n\t\ti = prev[i]-1;\n\t\tans.push_back(c);\n\t}\n}\n\n\nvoid solveDP(Input& input, Output& output) {\n\t\n\tfor (int i = 0; i < input.r; i++)\n\t\tsolve_row(input.tomatoes[i],i,input.c,input.l,input.h,output.slices);\n}\n\n\/\/input\/output code\nint main(int argc, char* argv[]) {\n\tios::sync_with_stdio(false);\n\t\n\t\/\/read input\n\tInput input;\n\tcin >> input.r >> input.c >> input.l >> input.h;\n\tfor(int i = 0; i < input.r; i++) {\n\t\tvector row(input.c);\n\t\tfor(int j = 0; j < input.c; j++) {\n\t\t\tchar cell;\n\t\t\tcin >> cell;\n\t\t\trow[j] = cell == 'T';\n\t\t}\n\t\tinput.tomatoes.push_back(row);\n\t\t\/\/TODO do we read line breaks?\n\t}\n\t\n\t\/\/read command line args\n\tstring algorithm = \"simplehorizontal\";\n\tif(argc > 2) {\n\t\talgorithm = argv[1];\n\t}\n\t\n\t\/\/solve problem\n\tOutput output;\n\tcerr << \"using algorithm \" << algorithm << endl;\n\tif(algorithm == \"simplehorizontal\") {\n\t\tsolveSimpleHorizontal(input, output);\n\t}\n\telse if(algorithm == \"simplevertical\") {\n\t\tsolveSimpleVertical(input, output);\n\t}\n\telse if(algorithm == \"dp\") {\n\t\tsolveDP(input, output);\n\t}\n\telse {\n\t\tcerr << \"unknown algorithm\" << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/print output\n\tcout << output.slices.size() << endl;\n\tfor(Slice slice: output.slices) {\n\t\tcout << slice.r1 << ' ' << slice.c1 << ' ' << slice.r2 << ' ' << slice.c2 << endl;\n\t}\n};\nSplitted checkSlice function for horizontal and vertical version#include \n#include \n#include \n\nusing namespace std;\n\n\/\/util classes\nstruct Input {\n\tint r, c, l, h;\n\tvector> tomatoes;\n};\n\nstruct Slice {\n\tint r1, c1, r2, c2;\n};\n\nstruct Output {\n\tvector slices;\n};\n\n\nbool checkSliceHorizontal(Input &input, Slice &s)\n{\n\tbool t = false;\n\tbool f = false;\n\tfor (int j = s.c1; j <= s.c2; j++)\n\t{\n\t\tif (input.tomatoes[s.r1][j])\n\t\t\tt = true;\n\t\telse\n\t\t\tf = true;\n\n\t\tif (t == true && f == true)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nbool checkSliceVertical(Input &input, Slice &s)\n{\n\tbool t = false;\n\tbool f = false;\n\tfor (int i = s.r1; i <= s.r2; i++)\n\t{\n\t\tif (input.tomatoes[i][s.c1])\n\t\t\tt = true;\n\t\telse\n\t\t\tf = true;\n\n\t\tif (t == true && f == true)\n\t\t\treturn true;\n\t}\n\treturn false;\n}\n\n\nvoid solveSimpleHorizontal(Input& input, Output& output) {\n\tfor (int i = 0; i < input.r; i++)\n\t{\n\t\tfor (int j = 0; j < input.c; j += input.h)\n\t\t{\n\t\t\tSlice s;\n\t\t\ts.r1 = i;\n\t\t\ts.c1 = j;\n\t\t\ts.r2 = i;\n\t\t\ts.c2 = min(j+input.h-1, input.c-1);\n\t\t\tif (checkSliceHorizontal(input, s))\n\t\t\t\toutput.slices.push_back(s);\n\t\t}\n\t}\n}\n\nvoid solveSimpleVertical(Input& input, Output& output) {\n\tfor (int j = 0; j < input.c; j++)\n\t{\n\t\tfor (int i = 0; i < input.r; i += input.h)\n\t\t{\n\t\t\tSlice s;\n\t\t\ts.r1 = i;\n\t\t\ts.c1 = j;\n\t\t\ts.r2 = min(i+input.h-1, input.r-1);\n\t\t\ts.c2 = j;\n\t\t\tif (checkSliceVertical(input, s))\n\t\t\t\toutput.slices.push_back(s);\n\t\t}\n\t}\n}\n\n\n\nint add_slice(const vector &a, int l, int r)\t{\n\tint cnt1 = 0, cnt2 = 0;\n\tfor (int i = l; i <= r; i++)\n\t\tif (a[i])\n\t\t\tcnt1++;\n\t\telse\n\t\t\tcnt2++;\n\t\n\tif (cnt1 >= l && cnt2 >= l)\n\t\treturn r-l+1;\n\treturn 0;\n}\n\nvoid solve_row(const vector &a, int row_num, int n, int l, int h, vector &ans)\t{\n\tvector d(n,0), prev(n,0);\n\t\n\tfor (int i = 0; i < n; i++)\n\t\tfor (int j = 2*l; j <= h; j++)\n\t\t\t if (i-j+1 >= 0)\n\t\t\t {\n\t\t\t \tint temp = add_slice(a,i-j+1,i);\n\t\t\t \tif (d[i] < d[i-j+1] + temp)\n\t\t\t\t{\n\t\t\t \t\td[i] = d[i-j+1] + temp;\n\t\t\t\t\tprev[i] = i-j+1;\n\t\t\t \t}\n\t\t\t}\n\t\t\n\tint i_max = 0;\n\tfor (int i = 0; i < n; i++)\n\t\tif (d[i] > d[i_max])\n\t\t\ti_max = i;\n\t\n\tSlice c;\t\t\n\tc.r1 = c.r2 = row_num;\n\t\n\tfor (int i = i_max; i > 0; i--)\n\t{\n\t\tc.c1 = prev[i]; c.c2 = i;\n\t\ti = prev[i]-1;\n\t\tans.push_back(c);\n\t}\n}\n\n\nvoid solveDP(Input& input, Output& output) {\n\t\n\tfor (int i = 0; i < input.r; i++)\n\t\tsolve_row(input.tomatoes[i],i,input.c,input.l,input.h,output.slices);\n}\n\n\/\/input\/output code\nint main(int argc, char* argv[]) {\n\tios::sync_with_stdio(false);\n\t\n\t\/\/read input\n\tInput input;\n\tcin >> input.r >> input.c >> input.l >> input.h;\n\tfor(int i = 0; i < input.r; i++) {\n\t\tvector row(input.c);\n\t\tfor(int j = 0; j < input.c; j++) {\n\t\t\tchar cell;\n\t\t\tcin >> cell;\n\t\t\trow[j] = cell == 'T';\n\t\t}\n\t\tinput.tomatoes.push_back(row);\n\t\t\/\/TODO do we read line breaks?\n\t}\n\t\n\t\/\/read command line args\n\tstring algorithm = \"simplehorizontal\";\n\tif(argc > 2) {\n\t\talgorithm = argv[1];\n\t}\n\t\n\t\/\/solve problem\n\tOutput output;\n\tcerr << \"using algorithm \" << algorithm << endl;\n\tif(algorithm == \"simplehorizontal\") {\n\t\tsolveSimpleHorizontal(input, output);\n\t}\n\telse if(algorithm == \"simplevertical\") {\n\t\tsolveSimpleVertical(input, output);\n\t}\n\telse if(algorithm == \"dp\") {\n\t\tsolveDP(input, output);\n\t}\n\telse {\n\t\tcerr << \"unknown algorithm\" << endl;\n\t\treturn 1;\n\t}\n\t\n\t\/\/print output\n\tcout << output.slices.size() << endl;\n\tfor(Slice slice: output.slices) {\n\t\tcout << slice.r1 << ' ' << slice.c1 << ' ' << slice.r2 << ' ' << slice.c2 << endl;\n\t}\n};\n<|endoftext|>"} {"text":"#include \"Common\/HighQueuePch.h\"\n#define BOOST_TEST_NO_MAIN HighQueuePerformanceTest\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace HighQueue;\ntypedef TestMessage<20> ActualMessage;\n\nnamespace\n{\n volatile std::atomic threadsReady;\n volatile bool producerGo = false;\n\n void producerFunction(Connection & connection, uint32_t producerNumber, uint64_t messageCount, bool solo)\n {\n Producer producer(connection, solo);\n HighQueue::Message producerMessage;\n if(!connection.allocate(producerMessage))\n {\n std::cerr << \"Failed to allocate message for producer Number \" << producerNumber << std::endl;\n return;\n }\n\n ++threadsReady;\n while(!producerGo)\n {\n std::this_thread::yield();\n }\n\n for(uint32_t messageNumber = 0; messageNumber < messageCount; ++messageNumber)\n {\n auto testMessage = producerMessage.construct(producerNumber, messageNumber);\n producer.publish(producerMessage);\n }\n }\n}\n\n#define DISABLE_MultithreadMessagePassingPerformancex\n#ifdef DISABLE_MultithreadMessagePassingPerformance\n#pragma message (\"DISABLE_MultithreadMessagePassingPerformance\")\n#else \/\/ DISABLE_MultithreadMessagePassingPerformance \nBOOST_AUTO_TEST_CASE(testMultithreadMessagePassingPerformance)\n{\n static const size_t entryCount = 100000;\n static const size_t messageSize = sizeof(ActualMessage);\n\n static const uint64_t targetMessageCount = 1000000 * 100; \/\/ runs about 5 to 10 seconds in release\/optimized build\n static const size_t producerLimit = 2;\/\/10; \/\/ running on 8 core system. Once we go over 7 producers it slows down. That's one thing we want to see.\n static const size_t consumerLimit = 1; \/\/ Just for documentation\n static const size_t messageCount = entryCount + consumerLimit + producerLimit;\n\n static const size_t spinCount = 0;\n static const size_t yieldCount = ConsumerWaitStrategy::FOREVER;\n\n ConsumerWaitStrategy strategy(spinCount, yieldCount);\n CreationParameters parameters(strategy, entryCount, messageSize, messageCount);\n Connection connection;\n connection.createLocal(\"LocalIv\", parameters);\n\n Consumer consumer(connection);\n HighQueue::Message consumerMessage;\n BOOST_REQUIRE(connection.allocate(consumerMessage));\n\n for(size_t producerCount = 1; producerCount < producerLimit; ++producerCount)\n {\n std::cerr << \"Test \" << producerCount << \" producer\";\n\n std::vector producerThreads;\n std::vector nextMessage;\n\n threadsReady = 0;\n producerGo = false;\n size_t perProducer = targetMessageCount \/ producerCount;\n size_t actualMessageCount = perProducer * producerCount;\n\n for(uint32_t nTh = 0; nTh < producerCount; ++nTh)\n {\n nextMessage.emplace_back(0u);\n producerThreads.emplace_back(\n std::bind(producerFunction, std::ref(connection), nTh, perProducer, producerCount == 1));\n }\n std::this_thread::yield();\n\n while(threadsReady < producerCount)\n {\n std::this_thread::yield();\n }\n\n Stopwatch timer;\n producerGo = true;\n\n for(uint64_t messageNumber = 0; messageNumber < actualMessageCount; ++messageNumber)\n {\n consumer.getNext(consumerMessage);\n auto testMessage = consumerMessage.get();\n testMessage->touch();\n auto & msgNumber = nextMessage[testMessage->producerNumber()];\n if(msgNumber != testMessage->messageNumber())\n {\n \/\/ the if avoids the performance hit of BOOST_CHECK_EQUAL unless it's needed.\n BOOST_CHECK_EQUAL(messageNumber, testMessage->messageNumber());\n }\n ++ msgNumber; \n }\n\n auto lapse = timer.nanoseconds();\n\n \/\/ sometimes we synchronize thread shut down.\n producerGo = false;\n\n for(size_t nTh = 0; nTh < producerCount; ++nTh)\n {\n producerThreads[nTh].join();\n }\n\n auto messageBytes = sizeof(ActualMessage);\n auto messageBits = sizeof(ActualMessage) * 8;\n std::cout << \" Passed \" << actualMessageCount << ' ' << messageBytes << \" byte messages in \"\n << std::setprecision(9) << double(lapse) \/ double(Stopwatch::nanosecondsPerSecond) << \" seconds. \" \n << lapse \/ actualMessageCount << \" nsec.\/message \"\n << std::setprecision(3) << double(actualMessageCount) \/ double(lapse) << \" GMsg\/second \"\n << std::setprecision(3) << double(actualMessageCount * messageBytes) \/ double(lapse) << \" GByte\/second \"\n << std::setprecision(3) << double(actualMessageCount * messageBits) \/ double(lapse) << \" GBit\/second.\"\n << std::endl;\n }\n}\n#endif \/\/ DISABLE_MultithreadMessagePassingPerformance\nRe-enable multithread test#include \"Common\/HighQueuePch.h\"\n#define BOOST_TEST_NO_MAIN HighQueuePerformanceTest\n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace HighQueue;\ntypedef TestMessage<20> ActualMessage;\n\nnamespace\n{\n volatile std::atomic threadsReady;\n volatile bool producerGo = false;\n\n void producerFunction(Connection & connection, uint32_t producerNumber, uint64_t messageCount, bool solo)\n {\n Producer producer(connection, solo);\n HighQueue::Message producerMessage;\n if(!connection.allocate(producerMessage))\n {\n std::cerr << \"Failed to allocate message for producer Number \" << producerNumber << std::endl;\n return;\n }\n\n ++threadsReady;\n while(!producerGo)\n {\n std::this_thread::yield();\n }\n\n for(uint32_t messageNumber = 0; messageNumber < messageCount; ++messageNumber)\n {\n auto testMessage = producerMessage.construct(producerNumber, messageNumber);\n producer.publish(producerMessage);\n }\n }\n}\n\n#define DISABLE_MultithreadMessagePassingPerformancex\n#ifdef DISABLE_MultithreadMessagePassingPerformance\n#pragma message (\"DISABLE_MultithreadMessagePassingPerformance\")\n#else \/\/ DISABLE_MultithreadMessagePassingPerformance \nBOOST_AUTO_TEST_CASE(testMultithreadMessagePassingPerformance)\n{\n static const size_t entryCount = 100000;\n static const size_t messageSize = sizeof(ActualMessage);\n\n static const uint64_t targetMessageCount = 1000000 * 100; \/\/ runs about 5 to 10 seconds in release\/optimized build\n static const size_t producerLimit = 8; \/\/ running on 8 core system. Once we go over 7 producers it slows down. That's one thing we want to see.\n static const size_t consumerLimit = 1; \/\/ Just for documentation\n static const size_t messageCount = entryCount + consumerLimit + producerLimit;\n\n static const size_t spinCount = 0;\n static const size_t yieldCount = ConsumerWaitStrategy::FOREVER;\n\n ConsumerWaitStrategy strategy(spinCount, yieldCount);\n CreationParameters parameters(strategy, entryCount, messageSize, messageCount);\n Connection connection;\n connection.createLocal(\"LocalIv\", parameters);\n\n Consumer consumer(connection);\n HighQueue::Message consumerMessage;\n BOOST_REQUIRE(connection.allocate(consumerMessage));\n\n for(size_t producerCount = 1; producerCount <= producerLimit; ++producerCount)\n {\n std::cerr << \"Test \" << producerCount << \" producer\";\n\n std::vector producerThreads;\n std::vector nextMessage;\n\n threadsReady = 0;\n producerGo = false;\n size_t perProducer = targetMessageCount \/ producerCount;\n size_t actualMessageCount = perProducer * producerCount;\n\n for(uint32_t nTh = 0; nTh < producerCount; ++nTh)\n {\n nextMessage.emplace_back(0u);\n producerThreads.emplace_back(\n std::bind(producerFunction, std::ref(connection), nTh, perProducer, producerCount == 1));\n }\n std::this_thread::yield();\n\n while(threadsReady < producerCount)\n {\n std::this_thread::yield();\n }\n\n Stopwatch timer;\n producerGo = true;\n\n for(uint64_t messageNumber = 0; messageNumber < actualMessageCount; ++messageNumber)\n {\n consumer.getNext(consumerMessage);\n auto testMessage = consumerMessage.get();\n testMessage->touch();\n auto & msgNumber = nextMessage[testMessage->producerNumber()];\n if(msgNumber != testMessage->messageNumber())\n {\n \/\/ the if avoids the performance hit of BOOST_CHECK_EQUAL unless it's needed.\n BOOST_CHECK_EQUAL(messageNumber, testMessage->messageNumber());\n }\n ++ msgNumber; \n }\n\n auto lapse = timer.nanoseconds();\n\n \/\/ sometimes we synchronize thread shut down.\n producerGo = false;\n\n for(size_t nTh = 0; nTh < producerCount; ++nTh)\n {\n producerThreads[nTh].join();\n }\n\n auto messageBytes = sizeof(ActualMessage);\n auto messageBits = sizeof(ActualMessage) * 8;\n std::cout << \" Passed \" << actualMessageCount << ' ' << messageBytes << \" byte messages in \"\n << std::setprecision(9) << double(lapse) \/ double(Stopwatch::nanosecondsPerSecond) << \" seconds. \" \n << lapse \/ actualMessageCount << \" nsec.\/message \"\n << std::setprecision(3) << double(actualMessageCount) \/ double(lapse) << \" GMsg\/second \"\n << std::setprecision(3) << double(actualMessageCount * messageBytes) \/ double(lapse) << \" GByte\/second \"\n << std::setprecision(3) << double(actualMessageCount * messageBits) \/ double(lapse) << \" GBit\/second.\"\n << std::endl;\n }\n}\n#endif \/\/ DISABLE_MultithreadMessagePassingPerformance\n<|endoftext|>"} {"text":"#include \"vm.hpp\"\n#include \"vm\/object_utils.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"objectmemory.hpp\"\n#include \"primitives.hpp\"\n\n#include \n\n\/* Implementation certain Array methods. These methods are just\n * the ones the VM requires, not the entire set of all Array methods.\n * This includes methods required to implement certain Array\n * primitives. *\/\n\nnamespace rubinius {\n\n void Array::init(STATE) {\n GO(array).set(state->new_class(\"Array\", G(object)));\n G(array)->set_object_type(state, ArrayType);\n\n native_int wordsize = as(\n G(rubinius)->get_const(state, \"WORDSIZE\"))->to_native();\n size_t maxsize = ((size_t)::exp2(wordsize)) \/ (wordsize\/8U);\n G(array)->set_const(state, \"MAX_SIZE\", Fixnum::from(maxsize));\n }\n\n size_t Array::size() {\n return total_->to_native();\n }\n\n Array* Array::create(STATE, size_t idx) {\n Array* ary;\n ary = state->new_object(G(array));\n\n ary->setup(state, idx);\n\n return ary;\n }\n\n \/\/ 'self' is passed in automatically by the primitive glue\n Array* Array::allocate(STATE, Object* self) {\n Array* ary = Array::create(state, 0U);\n ary->klass(state, (Class*)self);\n return ary;\n }\n\n Array* Array::from_tuple(STATE, Tuple* tup) {\n size_t length = tup->num_fields();\n Array* ary = Array::create(state, length);\n ary->tuple_->copy_from(state, tup,\n\t\t\t Fixnum::from(0), Fixnum::from(length),\n\t\t\t Fixnum::from(0));\n ary->total(state, Fixnum::from(length));\n return ary;\n }\n\n void Array::setup(STATE, size_t size) {\n this->tuple(state, Tuple::create(state, size));\n this->start(state, Fixnum::from(0));\n this->total(state, Fixnum::from(0));\n }\n\n \/\/ NOTE: We don't use Primitives::failure() here because the wrapper\n \/\/ code makes sure we're only called when the arity and type are correct.\n \/\/ Thus we know that this is a simple a[n] case only, which we can\n \/\/ fully handle.\n Object* Array::aref(STATE, Fixnum* idx) {\n native_int index = idx->to_native();\n const native_int start = start_->to_native();\n const native_int total = start + total_->to_native();\n\n \/\/ Handle negative indexes\n if(index < 0) {\n index += total;\n } else {\n index += start;\n }\n\n \/\/ Off either end, return nil\n if(index >= total || index < start) return Qnil;\n\n return tuple_->at(state, index);\n }\n\n Object* Array::aset(STATE, Fixnum* idx, Object* val) {\n native_int index = idx->to_native();\n\n if(index < 0) {\n return Primitives::failure();\n }\n\n return this->set(state, index, val);\n }\n\n Object* Array::get(STATE, size_t idx) {\n if(idx >= (size_t)total_->to_native()) {\n return Qnil;\n }\n\n idx += start_->to_native();\n\n return tuple_->at(state, idx);\n }\n\n Object* Array::set(STATE, size_t idx, Object* val) {\n size_t tuple_size = tuple_->num_fields();\n size_t oidx = idx;\n idx += start_->to_native();\n\n if(idx >= tuple_size) {\n \/\/ Uses the same algo as 1.8 to resize the tuple\n size_t new_size = tuple_size \/ 2;\n if(new_size < 3) {\n new_size = 3;\n }\n\n Tuple* nt = Tuple::create(state, new_size+idx);\n nt->copy_from(state, tuple_, start_, total_, Fixnum::from(0));\n tuple(state, nt);\n start(state, Fixnum::from(0));\n idx = oidx;\n }\n\n tuple_->put(state, idx, val);\n if((size_t)total_->to_native() <= oidx) {\n total(state, Fixnum::from(oidx+1));\n }\n return val;\n }\n\n void Array::unshift(STATE, Object* val) {\n size_t new_size = total_->to_native() + 1;\n size_t lend = start_->to_native();\n\n if(lend > 0) {\n tuple_->put(state, lend-1, val);\n start(state, Fixnum::from(lend-1));\n total(state, Fixnum::from(new_size));\n } else {\n Tuple* nt = Tuple::create(state, new_size);\n nt->copy_from(state, tuple_, start_, total_,\n\t\t Fixnum::from(1));\n nt->put(state, 0, val);\n\n total(state, Fixnum::from(new_size));\n start(state, Fixnum::from(0));\n tuple(state, nt);\n }\n }\n\n Object* Array::shift(STATE) {\n size_t cnt = total_->to_native();\n\n if(cnt == 0) return Qnil;\n Object* obj = get(state, 0);\n set(state, 0, Qnil);\n start(state, Fixnum::from(start_->to_native() + 1));\n total(state, Fixnum::from(cnt - 1));\n return obj;\n }\n\n Object* Array::append(STATE, Object* val) {\n set(state, (size_t)total_->to_native(), val);\n return val;\n }\n\n bool Array::includes_p(STATE, Object* val) {\n size_t cnt = total_->to_native();\n\n for(size_t i = 0; i < cnt; i++) {\n if(get(state, i) == val) return true;\n }\n\n return false;\n }\n\n Object* Array::pop(STATE) {\n size_t cnt = total_->to_native();\n\n if(cnt == 0) return Qnil;\n Object *obj = get(state, cnt - 1);\n set(state, cnt-1, Qnil);\n total(state, Fixnum::from(cnt - 1));\n return obj;\n }\n\n void Array::Info::show(STATE, Object* self, int level) {\n Array* ary = as(self);\n size_t size = ary->size();\n size_t stop = size < 5 ? size : 5;\n\n if(size == 0) {\n class_info(state, self, true);\n return;\n }\n\n class_info(state, self);\n std::cout << \": \" << size << std::endl;\n ++level;\n for(size_t i = 0; i < stop; i++) {\n indent(level);\n Object* obj = ary->get(state, i);\n if(obj == ary) {\n class_info(state, obj, true);\n } else {\n obj->show(state, level);\n }\n }\n if(ary->size() > stop) ellipsis(level);\n close_body(level);\n }\n}\nAnd add the header.#include \"vm.hpp\"\n#include \"vm\/object_utils.hpp\"\n\n#include \"builtin\/array.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/tuple.hpp\"\n#include \"builtin\/class.hpp\"\n#include \"objectmemory.hpp\"\n#include \"primitives.hpp\"\n\n#include \n#include \n\n\/* Implementation certain Array methods. These methods are just\n * the ones the VM requires, not the entire set of all Array methods.\n * This includes methods required to implement certain Array\n * primitives. *\/\n\nnamespace rubinius {\n\n void Array::init(STATE) {\n GO(array).set(state->new_class(\"Array\", G(object)));\n G(array)->set_object_type(state, ArrayType);\n\n native_int wordsize = as(\n G(rubinius)->get_const(state, \"WORDSIZE\"))->to_native();\n size_t maxsize = ((size_t)::exp2(wordsize)) \/ (wordsize\/8U);\n G(array)->set_const(state, \"MAX_SIZE\", Fixnum::from(maxsize));\n }\n\n size_t Array::size() {\n return total_->to_native();\n }\n\n Array* Array::create(STATE, size_t idx) {\n Array* ary;\n ary = state->new_object(G(array));\n\n ary->setup(state, idx);\n\n return ary;\n }\n\n \/\/ 'self' is passed in automatically by the primitive glue\n Array* Array::allocate(STATE, Object* self) {\n Array* ary = Array::create(state, 0U);\n ary->klass(state, (Class*)self);\n return ary;\n }\n\n Array* Array::from_tuple(STATE, Tuple* tup) {\n size_t length = tup->num_fields();\n Array* ary = Array::create(state, length);\n ary->tuple_->copy_from(state, tup,\n\t\t\t Fixnum::from(0), Fixnum::from(length),\n\t\t\t Fixnum::from(0));\n ary->total(state, Fixnum::from(length));\n return ary;\n }\n\n void Array::setup(STATE, size_t size) {\n this->tuple(state, Tuple::create(state, size));\n this->start(state, Fixnum::from(0));\n this->total(state, Fixnum::from(0));\n }\n\n \/\/ NOTE: We don't use Primitives::failure() here because the wrapper\n \/\/ code makes sure we're only called when the arity and type are correct.\n \/\/ Thus we know that this is a simple a[n] case only, which we can\n \/\/ fully handle.\n Object* Array::aref(STATE, Fixnum* idx) {\n native_int index = idx->to_native();\n const native_int start = start_->to_native();\n const native_int total = start + total_->to_native();\n\n \/\/ Handle negative indexes\n if(index < 0) {\n index += total;\n } else {\n index += start;\n }\n\n \/\/ Off either end, return nil\n if(index >= total || index < start) return Qnil;\n\n return tuple_->at(state, index);\n }\n\n Object* Array::aset(STATE, Fixnum* idx, Object* val) {\n native_int index = idx->to_native();\n\n if(index < 0) {\n return Primitives::failure();\n }\n\n return this->set(state, index, val);\n }\n\n Object* Array::get(STATE, size_t idx) {\n if(idx >= (size_t)total_->to_native()) {\n return Qnil;\n }\n\n idx += start_->to_native();\n\n return tuple_->at(state, idx);\n }\n\n Object* Array::set(STATE, size_t idx, Object* val) {\n size_t tuple_size = tuple_->num_fields();\n size_t oidx = idx;\n idx += start_->to_native();\n\n if(idx >= tuple_size) {\n \/\/ Uses the same algo as 1.8 to resize the tuple\n size_t new_size = tuple_size \/ 2;\n if(new_size < 3) {\n new_size = 3;\n }\n\n Tuple* nt = Tuple::create(state, new_size+idx);\n nt->copy_from(state, tuple_, start_, total_, Fixnum::from(0));\n tuple(state, nt);\n start(state, Fixnum::from(0));\n idx = oidx;\n }\n\n tuple_->put(state, idx, val);\n if((size_t)total_->to_native() <= oidx) {\n total(state, Fixnum::from(oidx+1));\n }\n return val;\n }\n\n void Array::unshift(STATE, Object* val) {\n size_t new_size = total_->to_native() + 1;\n size_t lend = start_->to_native();\n\n if(lend > 0) {\n tuple_->put(state, lend-1, val);\n start(state, Fixnum::from(lend-1));\n total(state, Fixnum::from(new_size));\n } else {\n Tuple* nt = Tuple::create(state, new_size);\n nt->copy_from(state, tuple_, start_, total_,\n\t\t Fixnum::from(1));\n nt->put(state, 0, val);\n\n total(state, Fixnum::from(new_size));\n start(state, Fixnum::from(0));\n tuple(state, nt);\n }\n }\n\n Object* Array::shift(STATE) {\n size_t cnt = total_->to_native();\n\n if(cnt == 0) return Qnil;\n Object* obj = get(state, 0);\n set(state, 0, Qnil);\n start(state, Fixnum::from(start_->to_native() + 1));\n total(state, Fixnum::from(cnt - 1));\n return obj;\n }\n\n Object* Array::append(STATE, Object* val) {\n set(state, (size_t)total_->to_native(), val);\n return val;\n }\n\n bool Array::includes_p(STATE, Object* val) {\n size_t cnt = total_->to_native();\n\n for(size_t i = 0; i < cnt; i++) {\n if(get(state, i) == val) return true;\n }\n\n return false;\n }\n\n Object* Array::pop(STATE) {\n size_t cnt = total_->to_native();\n\n if(cnt == 0) return Qnil;\n Object *obj = get(state, cnt - 1);\n set(state, cnt-1, Qnil);\n total(state, Fixnum::from(cnt - 1));\n return obj;\n }\n\n void Array::Info::show(STATE, Object* self, int level) {\n Array* ary = as(self);\n size_t size = ary->size();\n size_t stop = size < 5 ? size : 5;\n\n if(size == 0) {\n class_info(state, self, true);\n return;\n }\n\n class_info(state, self);\n std::cout << \": \" << size << std::endl;\n ++level;\n for(size_t i = 0; i < stop; i++) {\n indent(level);\n Object* obj = ary->get(state, i);\n if(obj == ary) {\n class_info(state, obj, true);\n } else {\n obj->show(state, level);\n }\n }\n if(ary->size() > stop) ellipsis(level);\n close_body(level);\n }\n}\n<|endoftext|>"} {"text":"#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"objectmemory.hpp\"\n#include \"vm.hpp\"\n#include \"vm\/object_utils.hpp\"\n#include \"primitives.hpp\"\n#include \"configuration.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"missing\/math.h\"\n\nnamespace rubinius {\n\n void Float::init(STATE) {\n GO(floatpoint).set(state->new_class(\"Float\", G(numeric)));\n G(floatpoint)->set_object_type(state, FloatType);\n\n G(floatpoint)->set_const(state, \"RADIX\", Fixnum::from(FLT_RADIX));\n G(floatpoint)->set_const(state, \"ROUNDS\", Fixnum::from(FLT_ROUNDS));\n G(floatpoint)->set_const(state, \"MIN\", Float::create(state, DBL_MIN));\n G(floatpoint)->set_const(state, \"MAX\", Float::create(state, DBL_MAX));\n G(floatpoint)->set_const(state, \"MIN_EXP\", Fixnum::from(DBL_MIN_EXP));\n G(floatpoint)->set_const(state, \"MAX_EXP\", Fixnum::from(DBL_MAX_EXP));\n G(floatpoint)->set_const(state, \"MIN_10_EXP\", Fixnum::from(DBL_MIN_10_EXP));\n G(floatpoint)->set_const(state, \"MAX_10_EXP\", Fixnum::from(DBL_MAX_10_EXP));\n G(floatpoint)->set_const(state, \"DIG\", Fixnum::from(DBL_DIG));\n G(floatpoint)->set_const(state, \"MANT_DIG\", Fixnum::from(DBL_MANT_DIG));\n G(floatpoint)->set_const(state, \"EPSILON\", Float::create(state, DBL_EPSILON));\n\n }\n\n Float* Float::create(STATE, double val) {\n Float* flt = state->new_struct(G(floatpoint));\n flt->val = val;\n return flt;\n }\n\n Float* Float::create(STATE, float val) {\n return Float::create(state, (double)val);\n }\n\n Float* Float::create(STATE, native_int val) {\n return Float::create(state, (double)val);\n }\n\n Float* Float::coerce(STATE, Object* value) {\n if(value->fixnum_p()) {\n return Float::create(state, (double)(as(value)->to_native()));\n } else if(kind_of(value)) {\n return Float::create(state, as(value)->to_double(state));\n }\n\n \/* FIXME this used to just return value, but this wants to coerce, so\n * we give a default float value of 0.0 back instead. *\/\n return Float::create(state, 0.0);\n }\n\n Float* Float::add(STATE, Float* other) {\n return Float::create(state, this->val + other->val);\n }\n\n Float* Float::add(STATE, Integer* other) {\n return Float::create(state, this->val + Float::coerce(state, other)->val);\n }\n\n Float* Float::sub(STATE, Float* other) {\n return Float::create(state, this->val - other->val);\n }\n\n Float* Float::sub(STATE, Integer* other) {\n return Float::create(state, this->val - Float::coerce(state, other)->val);\n }\n\n Float* Float::mul(STATE, Float* other) {\n return Float::create(state, this->val * other->val);\n }\n\n Float* Float::mul(STATE, Integer* other) {\n return Float::create(state, this->val * Float::coerce(state, other)->val);\n }\n\n Float* Float::fpow(STATE, Float* other) {\n return Float::create(state, pow(this->val, other->val));\n }\n\n Float* Float::fpow(STATE, Integer* other) {\n return Float::create(state, pow(this->val, Float::coerce(state, other)->val));\n }\n\n Float* Float::div(STATE, Float* other) {\n return Float::create(state, this->val \/ other->val);\n }\n\n Float* Float::div(STATE, Integer* other) {\n return Float::create(state, this->val \/ Float::coerce(state, other)->val);\n }\n\n Float* Float::mod(STATE, Float* other) {\n double res = fmod(this->val, other->val);\n if((other->val < 0.0 && this->val > 0.0 && res != 0) ||\n (other->val > 0.0 && this->val < 0.0 && res != 0)) {\n res += other->val;\n }\n return Float::create(state, res);\n }\n\n Float* Float::mod(STATE, Integer* other) {\n return mod(state, Float::coerce(state, other));\n }\n\n Array* Float::divmod(STATE, Float* other) {\n if(LANGUAGE_19_ENABLED(state)) {\n if(other->val == 0.0) {\n Exception::zero_division_error(state, \"divided by 0\");\n }\n }\n\n Array* ary = Array::create(state, 2);\n ary->set(state, 0, Bignum::from_double(state, floor(this->val \/ other->val) ));\n ary->set(state, 1, mod(state, other));\n return ary;\n }\n\n Array* Float::divmod(STATE, Integer* other) {\n return divmod(state, Float::coerce(state, other));\n }\n\n Float* Float::neg(STATE) {\n return Float::create(state, -this->val);\n }\n\n Object* Float::equal(STATE, Float* other) {\n if(this->val == other->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::equal(STATE, Integer* other) {\n Float* o = Float::coerce(state, other);\n if(this->val == o->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::eql(STATE, Float* other) {\n if(this->val == other->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::eql(STATE, Integer* other) {\n return Qfalse;\n }\n\n Object* Float::compare(STATE, Float* other) {\n if(this->val == other->val) {\n return Fixnum::from(0);\n } else if(this->val > other->val) {\n return Fixnum::from(1);\n } else if(this->val < other->val){\n return Fixnum::from(-1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::compare(STATE, Integer* other) {\n if(isinf(this->val)) {\n if(this->val > 0) {\n return Fixnum::from(1);\n } else {\n return Fixnum::from(-1);\n }\n }\n Float* o = Float::coerce(state, other);\n if(this->val == o->val) {\n return Fixnum::from(0);\n } else if(this->val > o->val) {\n return Fixnum::from(1);\n } else if(this->val < o->val){\n return Fixnum::from(-1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::gt(STATE, Float* other) {\n return this->val > other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::gt(STATE, Integer* other) {\n return this->val > Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::ge(STATE, Float* other) {\n return this->val >= other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::ge(STATE, Integer* other) {\n return this->val >= Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::lt(STATE, Float* other) {\n return this->val < other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::lt(STATE, Integer* other) {\n return this->val < Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::le(STATE, Float* other) {\n return this->val <= other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::le(STATE, Integer* other) {\n return this->val <= Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::fisinf(STATE) {\n if(isinf(this->val) != 0) {\n return this->val < 0 ? Fixnum::from(-1) : Fixnum::from(1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::fisnan(STATE) {\n return isnan(this->val) == 1 ? Qtrue : Qfalse;\n }\n\n Integer* Float::fround(STATE) {\n double value = this->val;\n if(value > 0.0) {\n value = floor(value);\n if(this->val - value >= 0.5) value += 1.0;\n }\n\n if(value < 0.0) {\n value = ceil(value);\n if(value - this->val >= 0.5) value -= 1.0;\n }\n return Bignum::from_double(state, value);\n }\n\n Integer* Float::to_i(STATE) {\n if(this->val > 0.0) {\n return Bignum::from_double(state, floor(this->val));\n } else if(this->val < 0.0) {\n return Bignum::from_double(state, ceil(this->val));\n }\n return Bignum::from_double(state, this->val);\n }\n\n\/* It requires \"%.1022f\" to print all digits of Float::MIN.\n * If you really need more digits than that, change this constant.\n *\/\n#define FLOAT_TO_S_STRLEN 1280\n\n String* Float::to_s_formatted(STATE, String* format) {\n char str[FLOAT_TO_S_STRLEN];\n\n size_t size = snprintf(str, FLOAT_TO_S_STRLEN, format->c_str(state), val);\n\n if(size >= FLOAT_TO_S_STRLEN) {\n std::ostringstream msg;\n msg << \"formatted string exceeds \" << FLOAT_TO_S_STRLEN << \" bytes\";\n Exception::argument_error(state, msg.str().c_str());\n }\n\n return String::create(state, str, size);\n }\n\n String* Float::to_s_minimal(STATE) {\n char str[FLOAT_TO_S_STRLEN];\n\n if(g_dfmt(str, &val, 0, FLOAT_TO_S_STRLEN) == 0) {\n return reinterpret_cast(kPrimitiveFailed);\n }\n\n String* s = String::create(state, str);\n if(is_tainted_p()) s->set_tainted();\n\n return s;\n }\n\n String* Float::to_packed(STATE, Object* want_double) {\n char str[sizeof(double)];\n int sz;\n\n if (want_double == Qtrue) {\n double* p = (double *)str;\n *p = this->val;\n sz = 8;\n }\n else {\n float* p = (float *)str;\n *p = this->val;\n sz = 4;\n }\n\n return String::create(state, str, sz);\n }\n\n void Float::into_string(STATE, char* buf, size_t sz) {\n snprintf(buf, sz, \"%+.17e\", val);\n }\n\n void Float::Info::mark(Object* t, ObjectMark& mark) { }\n\n void Float::Info::show(STATE, Object* self, int level) {\n Float* f = as(self);\n std::cout << f->val << std::endl;\n }\n\n void Float::Info::show_simple(STATE, Object* self, int level) {\n show(state, self, level);\n }\n}\nFloat#% Float#modulo raise ZeroDivisionError when other is zero in 1.9#include \"builtin\/array.hpp\"\n#include \"builtin\/exception.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/float.hpp\"\n#include \"builtin\/string.hpp\"\n\n#include \"objectmemory.hpp\"\n#include \"vm.hpp\"\n#include \"vm\/object_utils.hpp\"\n#include \"primitives.hpp\"\n#include \"configuration.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"missing\/math.h\"\n\nnamespace rubinius {\n\n void Float::init(STATE) {\n GO(floatpoint).set(state->new_class(\"Float\", G(numeric)));\n G(floatpoint)->set_object_type(state, FloatType);\n\n G(floatpoint)->set_const(state, \"RADIX\", Fixnum::from(FLT_RADIX));\n G(floatpoint)->set_const(state, \"ROUNDS\", Fixnum::from(FLT_ROUNDS));\n G(floatpoint)->set_const(state, \"MIN\", Float::create(state, DBL_MIN));\n G(floatpoint)->set_const(state, \"MAX\", Float::create(state, DBL_MAX));\n G(floatpoint)->set_const(state, \"MIN_EXP\", Fixnum::from(DBL_MIN_EXP));\n G(floatpoint)->set_const(state, \"MAX_EXP\", Fixnum::from(DBL_MAX_EXP));\n G(floatpoint)->set_const(state, \"MIN_10_EXP\", Fixnum::from(DBL_MIN_10_EXP));\n G(floatpoint)->set_const(state, \"MAX_10_EXP\", Fixnum::from(DBL_MAX_10_EXP));\n G(floatpoint)->set_const(state, \"DIG\", Fixnum::from(DBL_DIG));\n G(floatpoint)->set_const(state, \"MANT_DIG\", Fixnum::from(DBL_MANT_DIG));\n G(floatpoint)->set_const(state, \"EPSILON\", Float::create(state, DBL_EPSILON));\n\n }\n\n Float* Float::create(STATE, double val) {\n Float* flt = state->new_struct(G(floatpoint));\n flt->val = val;\n return flt;\n }\n\n Float* Float::create(STATE, float val) {\n return Float::create(state, (double)val);\n }\n\n Float* Float::create(STATE, native_int val) {\n return Float::create(state, (double)val);\n }\n\n Float* Float::coerce(STATE, Object* value) {\n if(value->fixnum_p()) {\n return Float::create(state, (double)(as(value)->to_native()));\n } else if(kind_of(value)) {\n return Float::create(state, as(value)->to_double(state));\n }\n\n \/* FIXME this used to just return value, but this wants to coerce, so\n * we give a default float value of 0.0 back instead. *\/\n return Float::create(state, 0.0);\n }\n\n Float* Float::add(STATE, Float* other) {\n return Float::create(state, this->val + other->val);\n }\n\n Float* Float::add(STATE, Integer* other) {\n return Float::create(state, this->val + Float::coerce(state, other)->val);\n }\n\n Float* Float::sub(STATE, Float* other) {\n return Float::create(state, this->val - other->val);\n }\n\n Float* Float::sub(STATE, Integer* other) {\n return Float::create(state, this->val - Float::coerce(state, other)->val);\n }\n\n Float* Float::mul(STATE, Float* other) {\n return Float::create(state, this->val * other->val);\n }\n\n Float* Float::mul(STATE, Integer* other) {\n return Float::create(state, this->val * Float::coerce(state, other)->val);\n }\n\n Float* Float::fpow(STATE, Float* other) {\n return Float::create(state, pow(this->val, other->val));\n }\n\n Float* Float::fpow(STATE, Integer* other) {\n return Float::create(state, pow(this->val, Float::coerce(state, other)->val));\n }\n\n Float* Float::div(STATE, Float* other) {\n return Float::create(state, this->val \/ other->val);\n }\n\n Float* Float::div(STATE, Integer* other) {\n return Float::create(state, this->val \/ Float::coerce(state, other)->val);\n }\n\n Float* Float::mod(STATE, Float* other) {\n if(LANGUAGE_19_ENABLED(state)) {\n if(other->val == 0.0) {\n Exception::zero_division_error(state, \"divided by 0\");\n }\n }\n\n double res = fmod(this->val, other->val);\n if((other->val < 0.0 && this->val > 0.0 && res != 0) ||\n (other->val > 0.0 && this->val < 0.0 && res != 0)) {\n res += other->val;\n }\n return Float::create(state, res);\n }\n\n Float* Float::mod(STATE, Integer* other) {\n return mod(state, Float::coerce(state, other));\n }\n\n Array* Float::divmod(STATE, Float* other) {\n if(LANGUAGE_19_ENABLED(state)) {\n if(other->val == 0.0) {\n Exception::zero_division_error(state, \"divided by 0\");\n }\n }\n\n Array* ary = Array::create(state, 2);\n ary->set(state, 0, Bignum::from_double(state, floor(this->val \/ other->val) ));\n ary->set(state, 1, mod(state, other));\n return ary;\n }\n\n Array* Float::divmod(STATE, Integer* other) {\n return divmod(state, Float::coerce(state, other));\n }\n\n Float* Float::neg(STATE) {\n return Float::create(state, -this->val);\n }\n\n Object* Float::equal(STATE, Float* other) {\n if(this->val == other->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::equal(STATE, Integer* other) {\n Float* o = Float::coerce(state, other);\n if(this->val == o->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::eql(STATE, Float* other) {\n if(this->val == other->val) {\n return Qtrue;\n }\n return Qfalse;\n }\n\n Object* Float::eql(STATE, Integer* other) {\n return Qfalse;\n }\n\n Object* Float::compare(STATE, Float* other) {\n if(this->val == other->val) {\n return Fixnum::from(0);\n } else if(this->val > other->val) {\n return Fixnum::from(1);\n } else if(this->val < other->val){\n return Fixnum::from(-1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::compare(STATE, Integer* other) {\n if(isinf(this->val)) {\n if(this->val > 0) {\n return Fixnum::from(1);\n } else {\n return Fixnum::from(-1);\n }\n }\n Float* o = Float::coerce(state, other);\n if(this->val == o->val) {\n return Fixnum::from(0);\n } else if(this->val > o->val) {\n return Fixnum::from(1);\n } else if(this->val < o->val){\n return Fixnum::from(-1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::gt(STATE, Float* other) {\n return this->val > other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::gt(STATE, Integer* other) {\n return this->val > Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::ge(STATE, Float* other) {\n return this->val >= other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::ge(STATE, Integer* other) {\n return this->val >= Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::lt(STATE, Float* other) {\n return this->val < other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::lt(STATE, Integer* other) {\n return this->val < Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::le(STATE, Float* other) {\n return this->val <= other->val ? Qtrue : Qfalse;\n }\n\n Object* Float::le(STATE, Integer* other) {\n return this->val <= Float::coerce(state, other)->val ? Qtrue : Qfalse;\n }\n\n Object* Float::fisinf(STATE) {\n if(isinf(this->val) != 0) {\n return this->val < 0 ? Fixnum::from(-1) : Fixnum::from(1);\n } else {\n return Qnil;\n }\n }\n\n Object* Float::fisnan(STATE) {\n return isnan(this->val) == 1 ? Qtrue : Qfalse;\n }\n\n Integer* Float::fround(STATE) {\n double value = this->val;\n if(value > 0.0) {\n value = floor(value);\n if(this->val - value >= 0.5) value += 1.0;\n }\n\n if(value < 0.0) {\n value = ceil(value);\n if(value - this->val >= 0.5) value -= 1.0;\n }\n return Bignum::from_double(state, value);\n }\n\n Integer* Float::to_i(STATE) {\n if(this->val > 0.0) {\n return Bignum::from_double(state, floor(this->val));\n } else if(this->val < 0.0) {\n return Bignum::from_double(state, ceil(this->val));\n }\n return Bignum::from_double(state, this->val);\n }\n\n\/* It requires \"%.1022f\" to print all digits of Float::MIN.\n * If you really need more digits than that, change this constant.\n *\/\n#define FLOAT_TO_S_STRLEN 1280\n\n String* Float::to_s_formatted(STATE, String* format) {\n char str[FLOAT_TO_S_STRLEN];\n\n size_t size = snprintf(str, FLOAT_TO_S_STRLEN, format->c_str(state), val);\n\n if(size >= FLOAT_TO_S_STRLEN) {\n std::ostringstream msg;\n msg << \"formatted string exceeds \" << FLOAT_TO_S_STRLEN << \" bytes\";\n Exception::argument_error(state, msg.str().c_str());\n }\n\n return String::create(state, str, size);\n }\n\n String* Float::to_s_minimal(STATE) {\n char str[FLOAT_TO_S_STRLEN];\n\n if(g_dfmt(str, &val, 0, FLOAT_TO_S_STRLEN) == 0) {\n return reinterpret_cast(kPrimitiveFailed);\n }\n\n String* s = String::create(state, str);\n if(is_tainted_p()) s->set_tainted();\n\n return s;\n }\n\n String* Float::to_packed(STATE, Object* want_double) {\n char str[sizeof(double)];\n int sz;\n\n if (want_double == Qtrue) {\n double* p = (double *)str;\n *p = this->val;\n sz = 8;\n }\n else {\n float* p = (float *)str;\n *p = this->val;\n sz = 4;\n }\n\n return String::create(state, str, sz);\n }\n\n void Float::into_string(STATE, char* buf, size_t sz) {\n snprintf(buf, sz, \"%+.17e\", val);\n }\n\n void Float::Info::mark(Object* t, ObjectMark& mark) { }\n\n void Float::Info::show(STATE, Object* self, int level) {\n Float* f = as(self);\n std::cout << f->val << std::endl;\n }\n\n void Float::Info::show_simple(STATE, Object* self, int level) {\n show(state, self, level);\n }\n}\n<|endoftext|>"} {"text":"#ifndef VPP_IMAGENd_HPP__\n# define VPP_IMAGENd_HPP__\n\n# include \n# include \n# include \n# include \n# include \n\n# ifndef VPP_DEFAULT_IMAGE_ALIGNMENT\n\n# ifdef __AVX2__\n# define VPP_DEFAULT_IMAGE_ALIGNMENT 32\n# else\n# define VPP_DEFAULT_IMAGE_ALIGNMENT 16\n# endif\n\n# endif\n\nnamespace vpp\n{\n\n template \n imageNd::imageNd()\n {\n }\n\n template \n template \n imageNd::imageNd(const std::initializer_list& dims, const O&... options)\n {\n allocate(dims, iod::D(options...));\n index_rows();\n }\n\n template \n template \n imageNd::imageNd(const std::vector& dims, const O&... options)\n {\n allocate(dims, iod::D(options...));\n index_rows();\n }\n\n\n template \n template \n imageNd::imageNd(int ncols, const O&... options)\n : imageNd(make_box1d(ncols), options...)\n {\n static_assert(N == 1, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n template \n imageNd::imageNd(int nrows, int ncols, const O&... options)\n : imageNd(make_box2d(nrows, ncols), options...)\n {\n static_assert(N == 2, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n template \n imageNd::imageNd(int nslices, int nrows, int ncols, const O&... options)\n : imageNd(make_box3d(nslices, nrows, ncols), options...)\n {\n static_assert(N == 3, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n imageNd::imageNd(imageNd&& other)\n : ptr_(std::move(other.ptr_))\n {\n }\n\n\n template \n imageNd& imageNd::operator=(const imageNd& other)\n {\n ptr_ = other.ptr_;\n return *this;\n }\n\n template \n imageNd::imageNd(const imageNd& other)\n {\n *this = other;\n }\n\n\n template \n imageNd& imageNd::operator=(imageNd&& other)\n {\n ptr_ = std::move(other.ptr_);\n return *this;\n }\n\n template \n template \n imageNd::imageNd(const boxNd& domain, const O&... _options)\n {\n std::vector dims(N);\n\n for (int i = 0; i < int(N); i++)\n dims[i] = domain.size(i);\n\n const auto options = iod::D(_options...);\n\n static_assert(\n !options.has(_data) or options.has(_pitch),\n \"You must provide the pitch (Number of bits between the begining of to successive lines when providing a data pointer the image constructor.\");\n\n if (options.has(_data))\n {\n ptr_ = std::shared_ptr>(new imageNd_data());\n\n ptr_->data_ = (V*) options.get(_data, (V*)0);\n ptr_->begin_ = ptr_->data_;\n ptr_->pitch_ = options.get(_pitch, 0);\n ptr_->domain_ = domain;\n ptr_->buffer_domain_ = domain;\n ptr_->border_ = options.get(_border, 0);\n\n \/\/ compute alignement.\n unsigned int data_al = 1;\n typedef unsigned long UL;\n while ((UL(ptr_->data_) % (data_al * 2)) == 0) data_al *= 2;\n unsigned int pitch_al = 1;\n while ((UL(ptr_->pitch_) % (pitch_al * 2)) == 0) pitch_al *= 2;\n ptr_->alignment_ = std::min(data_al, pitch_al);\n\n int size = ptr_->pitch_;\n for (int n = 0; n < N - 1; n++)\n size *= ptr_->domain_.size(n);\n\n ptr_->data_end_ = (V*)((char*) ptr_->data_ + size);\n }\n else\n allocate(dims, options);\n\n index_rows();\n }\n\n template \n imageNd::~imageNd()\n {\n \/\/ The shared_ptr this_->ptr_ will destroy the data if needed.\n }\n\n template \n template \n void imageNd::allocate(const std::vector& dims, const iod::sio& options)\n {\n const int align_size = options.get(_aligned, VPP_DEFAULT_IMAGE_ALIGNMENT); \/\/ Memory alignment of rows.\n assert(align_size != 0);\n typedef unsigned long long ULL;\n ptr_ = std::make_shared>();\n auto& d = *ptr_;\n d.border_ = options.get(_border, 0);\n d.alignment_ = align_size;\n\n int border_size = d.border_ * sizeof(V);\n int border_padding = 0;\n if (border_size % align_size)\n {\n border_padding = align_size - (border_size % align_size);\n border_size += border_padding;\n }\n\n d.pitch_ = dims[N - 1] * sizeof(V) + border_size * 2;\n if (d.pitch_ % align_size) d.pitch_ += align_size - (d.pitch_ % align_size);\n\n int size = 1;\n for (int i = 0; i < N - 1; i++)\n size *= dims[i] + (d.border_ * 2);\n size *= d.pitch_;\n\n d.data_ = (V*) malloc(align_size + size);\n d.data_sptr_ = std::shared_ptr(d.data_, [] (V* p) { \n free((char*)p); \n });\n\n if (ULL(d.data_) % align_size)\n d.data_ = (V*)((char*)(d.data_) + align_size - int(ULL(d.data_) % align_size));\n\n d.data_end_ = d.data_ + size \/ sizeof(V);\n assert(!(ULL(d.data_) % align_size));\n d.domain_.p1() = vint::Zero();\n for (unsigned i = 0; i < N; i++)\n d.domain_.p2()[i] = dims[i] - 1;\n\n \/\/ Set begin_, the address of the first pixel.\n vint p = vint::Ones() * d.border_;\n d.begin_ = (V*)((char*)d.data_ + border_padding + coords_to_offset(p));\n d.buffer_domain_ = d.domain_;\n }\n\n \n template \n void imageNd::index_rows()\n {\n \n std::vector& rows = ptr_->rows_;\n rows.clear();\n boxNd row_domain(domain_with_border().p1().template segment(0),\n domain_with_border().p2().template segment(0));\n\n int ras = 0;\n for(vint r : row_domain)\n {\n vint p = domain().p1();\n p.template segment(0) = r;\n\n rows.push_back(this->address_of(p));\n\n if (p == vint::Zero())\n ras = rows.size() - 1;\n }\n\n ptr_->rows_array_start_ = &rows[ras];\n }\n \n template \n int imageNd::coords_to_offset(const vint& p) const\n {\n int row_idx = p[N-2];\n int ds = 1;\n for (int i = N - 3; i >= 0; i--)\n {\n ds *= ptr_->buffer_domain_.size(i + 1);\n row_idx += ds * p[i];\n }\n return row_idx * ptr_->pitch_ + p[N - 1] * sizeof(V);\n }\n\n template \n V&\n imageNd::operator()(const vint& p)\n {\n assert(domain_with_border().has(p));\n V* addr = (V*)((char*)ptr_->begin_ + coords_to_offset(p));\n assert(addr < ptr_->data_end_);\n return *addr;\n }\n\n template \n const V&\n imageNd::operator()(const vint& p) const\n {\n assert(domain_with_border().has(p));\n const V* addr = (V*)((char*)ptr_->begin_ + coords_to_offset(p));\n assert(addr < ptr_->data_end_);\n return *addr;\n }\n\n template \n V*\n imageNd::operator[](int r)\n {\n return ptr_->rows_array_start_[r];\n }\n\n template \n const V*\n imageNd::operator[](int r) const\n {\n return ptr_->rows_array_start_[r];\n }\n \n template \n V\n imageNd::linear_interpolate(const vfloat& p) const\n {\n static_assert(N == 2, \"linear_interpolate only supports 2d images.\");\n\n vint2 x = p.template cast();\n float a0 = p[0] - x[0];\n float a1 = p[1] - x[1];\n\n const V* l1 = address_of(x);\n const V* l2 = (const V*)((const char*)l1 + ptr_->pitch_);\n\n \/\/typedef plus_promotion S;\n typedef cast_to_float S;\n\n return vpp::cast((1 - a0) * (1 - a1) * vpp::cast(l1[0]) +\n a0 * (1 - a1) * vpp::cast(l2[0]) +\n (1 - a0) * a1 * vpp::cast(l1[1]) +\n a0 * a1 * vpp::cast(l2[1]));\n }\n\n template \n V*\n imageNd::address_of(const vint& p)\n {\n return (V*)((char*)(ptr_->begin_) + coords_to_offset(p));\n }\n\n template \n const V*\n imageNd::address_of(const vint& p) const\n {\n return (V*)((char*)(ptr_->begin_) + coords_to_offset(p));\n }\n\n template \n int\n imageNd::offset_of(const vint& p) const\n {\n return coords_to_offset(p);\n }\n\n template \n imageNd\n imageNd::subimage(const boxNd& d)\n {\n imageNd res;\n res.ptr_ = std::shared_ptr>(new imageNd_data());\n *res.ptr_.get() = *this->ptr_.get(); \/\/ Copy the image data.\n res.ptr_->begin_ = address_of(d.p1());\n boxNd domain = d;\n domain.p2() -= domain.p1();\n domain.p1() -= domain.p1();\n res.ptr_->domain_ = domain;\n\n for (V*& r_start : res.ptr_->rows_)\n r_start += d.p1()[1] - this->domain().p1()[1];\n\n res.ptr_->rows_array_start_ += d.p1()[0] - this->domain().p1()[0];\n\n return res;\n }\n\n template \n const imageNd\n imageNd::const_subimage(const boxNd& d) const\n {\n imageNd res;\n\n res.ptr_ = std::shared_ptr>(new imageNd_data());\n *res.ptr_.get() = *this->ptr_.get();\n res.ptr_->begin_ = const_cast(address_of(d.p1()));\n boxNd domain = d;\n domain.p2() -= domain.p1();\n domain.p1() -= domain.p1();\n res.ptr_->domain_ = domain;\n\n for (V*& r_start : res.ptr_->rows_)\n r_start += d.p1()[1] - this->domain().p1()[1];\n \n res.ptr_->rows_array_start_ += d.p1()[0] - this->domain().p1()[0];\n\n return res;\n }\n\n};\n\n#endif\nimg(p) is not equivalent to the faster img[][]. Fix a bug in subimage.#ifndef VPP_IMAGENd_HPP__\n# define VPP_IMAGENd_HPP__\n\n# include \n# include \n# include \n# include \n# include \n\n# ifndef VPP_DEFAULT_IMAGE_ALIGNMENT\n\n# ifdef __AVX2__\n# define VPP_DEFAULT_IMAGE_ALIGNMENT 32\n# else\n# define VPP_DEFAULT_IMAGE_ALIGNMENT 16\n# endif\n\n# endif\n\nnamespace vpp\n{\n\n template \n imageNd::imageNd()\n {\n }\n\n template \n template \n imageNd::imageNd(const std::initializer_list& dims, const O&... options)\n {\n allocate(dims, iod::D(options...));\n index_rows();\n }\n\n template \n template \n imageNd::imageNd(const std::vector& dims, const O&... options)\n {\n allocate(dims, iod::D(options...));\n index_rows();\n }\n\n\n template \n template \n imageNd::imageNd(int ncols, const O&... options)\n : imageNd(make_box1d(ncols), options...)\n {\n static_assert(N == 1, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n template \n imageNd::imageNd(int nrows, int ncols, const O&... options)\n : imageNd(make_box2d(nrows, ncols), options...)\n {\n static_assert(N == 2, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n template \n imageNd::imageNd(int nslices, int nrows, int ncols, const O&... options)\n : imageNd(make_box3d(nslices, nrows, ncols), options...)\n {\n static_assert(N == 3, \"ImageNd constructor: bad dimension.\");\n }\n\n template \n imageNd::imageNd(imageNd&& other)\n : ptr_(std::move(other.ptr_))\n {\n }\n\n\n template \n imageNd& imageNd::operator=(const imageNd& other)\n {\n ptr_ = other.ptr_;\n return *this;\n }\n\n template \n imageNd::imageNd(const imageNd& other)\n {\n *this = other;\n }\n\n\n template \n imageNd& imageNd::operator=(imageNd&& other)\n {\n ptr_ = std::move(other.ptr_);\n return *this;\n }\n\n template \n template \n imageNd::imageNd(const boxNd& domain, const O&... _options)\n {\n std::vector dims(N);\n\n for (int i = 0; i < int(N); i++)\n dims[i] = domain.size(i);\n\n const auto options = iod::D(_options...);\n\n static_assert(\n !options.has(_data) or options.has(_pitch),\n \"You must provide the pitch (Number of bits between the begining of to successive lines when providing a data pointer the image constructor.\");\n\n if (options.has(_data))\n {\n ptr_ = std::shared_ptr>(new imageNd_data());\n\n ptr_->data_ = (V*) options.get(_data, (V*)0);\n ptr_->begin_ = ptr_->data_;\n ptr_->pitch_ = options.get(_pitch, 0);\n ptr_->domain_ = domain;\n ptr_->buffer_domain_ = domain;\n ptr_->border_ = options.get(_border, 0);\n\n \/\/ compute alignement.\n unsigned int data_al = 1;\n typedef unsigned long UL;\n while ((UL(ptr_->data_) % (data_al * 2)) == 0) data_al *= 2;\n unsigned int pitch_al = 1;\n while ((UL(ptr_->pitch_) % (pitch_al * 2)) == 0) pitch_al *= 2;\n ptr_->alignment_ = std::min(data_al, pitch_al);\n\n int size = ptr_->pitch_;\n for (int n = 0; n < N - 1; n++)\n size *= ptr_->domain_.size(n);\n\n ptr_->data_end_ = (V*)((char*) ptr_->data_ + size);\n }\n else\n allocate(dims, options);\n\n index_rows();\n }\n\n template \n imageNd::~imageNd()\n {\n \/\/ The shared_ptr this_->ptr_ will destroy the data if needed.\n }\n\n template \n template \n void imageNd::allocate(const std::vector& dims, const iod::sio& options)\n {\n const int align_size = options.get(_aligned, VPP_DEFAULT_IMAGE_ALIGNMENT); \/\/ Memory alignment of rows.\n assert(align_size != 0);\n typedef unsigned long long ULL;\n ptr_ = std::make_shared>();\n auto& d = *ptr_;\n d.border_ = options.get(_border, 0);\n d.alignment_ = align_size;\n\n int border_size = d.border_ * sizeof(V);\n int border_padding = 0;\n if (border_size % align_size)\n {\n border_padding = align_size - (border_size % align_size);\n border_size += border_padding;\n }\n\n d.pitch_ = dims[N - 1] * sizeof(V) + border_size * 2;\n if (d.pitch_ % align_size) d.pitch_ += align_size - (d.pitch_ % align_size);\n\n int size = 1;\n for (int i = 0; i < N - 1; i++)\n size *= dims[i] + (d.border_ * 2);\n size *= d.pitch_;\n\n d.data_ = (V*) malloc(align_size + size);\n d.data_sptr_ = std::shared_ptr(d.data_, [] (V* p) { \n free((char*)p); \n });\n\n if (ULL(d.data_) % align_size)\n d.data_ = (V*)((char*)(d.data_) + align_size - int(ULL(d.data_) % align_size));\n\n d.data_end_ = d.data_ + size \/ sizeof(V);\n assert(!(ULL(d.data_) % align_size));\n d.domain_.p1() = vint::Zero();\n for (unsigned i = 0; i < N; i++)\n d.domain_.p2()[i] = dims[i] - 1;\n\n \/\/ Set begin_, the address of the first pixel.\n vint p = vint::Ones() * d.border_;\n d.begin_ = (V*)((char*)d.data_ + border_padding + coords_to_offset(p));\n d.buffer_domain_ = d.domain_;\n }\n\n \n template \n void imageNd::index_rows()\n {\n \n std::vector& rows = ptr_->rows_;\n rows.clear();\n boxNd row_domain(domain_with_border().p1().template segment(0),\n domain_with_border().p2().template segment(0));\n\n int ras = 0;\n for(vint r : row_domain)\n {\n vint p = domain().p1();\n p.template segment(0) = r;\n\n rows.push_back(this->address_of(p));\n\n if (p == vint::Zero())\n ras = rows.size() - 1;\n }\n\n ptr_->rows_array_start_ = &rows[ras];\n }\n \n template \n int imageNd::coords_to_offset(const vint& p) const\n {\n int row_idx = p[N-2];\n int ds = 1;\n for (int i = N - 3; i >= 0; i--)\n {\n ds *= ptr_->buffer_domain_.size(i + 1);\n row_idx += ds * p[i];\n }\n return row_idx * ptr_->pitch_ + p[N - 1] * sizeof(V);\n }\n\n template \n V&\n imageNd::operator()(const vint& p)\n {\n assert(domain_with_border().has(p));\n if (N == 2)\n return (*this)[p[0]][p[1]];\n else\n {\n V* addr = (V*)((char*)ptr_->begin_ + coords_to_offset(p));\n assert(addr < ptr_->data_end_);\n return *addr;\n }\n }\n\n template \n const V&\n imageNd::operator()(const vint& p) const\n {\n assert(domain_with_border().has(p));\n if (N == 2)\n return (*this)[p[0]][p[1]];\n else\n {\n const V* addr = (V*)((char*)ptr_->begin_ + coords_to_offset(p));\n assert(addr < ptr_->data_end_);\n return *addr;\n }\n }\n\n template \n V*\n imageNd::operator[](int r)\n {\n return ptr_->rows_array_start_[r];\n }\n\n template \n const V*\n imageNd::operator[](int r) const\n {\n return ptr_->rows_array_start_[r];\n }\n \n template \n V\n imageNd::linear_interpolate(const vfloat& p) const\n {\n static_assert(N == 2, \"linear_interpolate only supports 2d images.\");\n\n vint2 x = p.template cast();\n float a0 = p[0] - x[0];\n float a1 = p[1] - x[1];\n\n const V* l1 = address_of(x);\n const V* l2 = (const V*)((const char*)l1 + ptr_->pitch_);\n\n \/\/typedef plus_promotion S;\n typedef cast_to_float S;\n\n return vpp::cast((1 - a0) * (1 - a1) * vpp::cast(l1[0]) +\n a0 * (1 - a1) * vpp::cast(l2[0]) +\n (1 - a0) * a1 * vpp::cast(l1[1]) +\n a0 * a1 * vpp::cast(l2[1]));\n }\n\n template \n V*\n imageNd::address_of(const vint& p)\n {\n return (V*)((char*)(ptr_->begin_) + coords_to_offset(p));\n }\n\n template \n const V*\n imageNd::address_of(const vint& p) const\n {\n return (V*)((char*)(ptr_->begin_) + coords_to_offset(p));\n }\n\n template \n int\n imageNd::offset_of(const vint& p) const\n {\n return coords_to_offset(p);\n }\n\n template \n imageNd\n imageNd::subimage(const boxNd& d)\n {\n imageNd res;\n res.ptr_ = std::shared_ptr>(new imageNd_data());\n *res.ptr_.get() = *this->ptr_.get(); \/\/ Copy the image data.\n res.ptr_->begin_ = address_of(d.p1());\n boxNd domain = d;\n domain.p2() -= domain.p1();\n domain.p1() -= domain.p1();\n res.ptr_->domain_ = domain;\n\n for (auto& r_start : res.ptr_->rows_)\n r_start += d.p1()[1] - this->domain().p1()[1];\n\n res.ptr_->rows_array_start_ = &res.ptr_->rows_.front() +\n (*this->ptr_->rows_array_start_ - &(*this->ptr_->rows_.front()))\n + (d.p1()[0] - this->domain().p1()[0]);\n\n\n return res;\n }\n\n template \n const imageNd\n imageNd::const_subimage(const boxNd& d) const\n {\n imageNd res;\n\n res.ptr_ = std::shared_ptr>(new imageNd_data());\n *res.ptr_.get() = *this->ptr_.get();\n res.ptr_->begin_ = const_cast(address_of(d.p1()));\n boxNd domain = d;\n domain.p2() -= domain.p1();\n domain.p1() -= domain.p1();\n res.ptr_->domain_ = domain;\n\n for (V*& r_start : res.ptr_->rows_)\n r_start += d.p1()[1] - this->domain().p1()[1];\n \n res.ptr_->rows_array_start_ += d.p1()[0] - this->domain().p1()[0];\n\n return res;\n }\n\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\nint Ws(const cv::Point2d &a, const cv::Point2d &b, const int radius) {\n return ((cv::norm(cv::Mat(a), cv::Mat(b), cv::NORM_L2) < radius) ? 1 : 0);\n}\n\ndouble Wm(const cv::Point2d &a, const cv::Point2d &b, const cv::Mat &grad,\n const double eta = 1.0) {\n double ga = grad.at(a.y, a.x);\n double gb = grad.at(b.y, b.x);\n return (0.5 * (1.0 + std::tanh(eta * (gb - ga))));\n}\n\ndouble Wd(const cv::Point2d &a, const cv::Point2d &b, const cv::Mat &tcurr) {\n double ta = tcurr.at(a.y, a.x);\n double tb = tcurr.at(b.y, b.x);\n double mult = ta * tb;\n return ((mult > 0) ? std::abs(mult) : -1.0 * std::abs(mult));\n}\n\nvoid ETFIteration(cv::Mat &tcurr, const cv::Mat &grad, const int kradius) {\n cv::Mat tnew = cv::Mat::zeros(tcurr.size(), CV_64FC1);\n for (uint y = 0; y < tcurr.size().height; ++y) {\n for (uint x = 0; x < tcurr.size().width; ++x) {\n const auto pa = cv::Point2d(x, y);\n double sigma = 0;\n double k = 0;\n for (uint oy = -kradius; oy <= kradius; ++oy) {\n int py = y + oy;\n if (py < 0 || py > tcurr.size().height)\n continue;\n for (uint ox = -kradius; ox <= kradius; ++ox) {\n int px = x + ox;\n if (px < 0 || px > tcurr.size().width)\n continue;\n k += 1.0;\n const auto pb = cv::Point2d(px, py);\n sigma += tcurr.at(pb) * Ws(pa, pb, kradius) *\n Wm(pa, pb, grad) * Wd(pa, pb, tcurr);\n }\n }\n tnew.at(pa) = (k > 0.1) ? sigma \/ k : 0.0;\n }\n }\n tcurr = tnew;\n}\n\ncv::Mat coherentLines(const cv::Mat &img, const int kernel_radius = 5,\n const int etf_iterations = 3) {\n cv::Mat gray;\n cv::cvtColor(img, gray, CV_BGR2GRAY);\n\n cv::Mat gx, gy, gm, gt, gmnorm;\n cv::Sobel(gray, gx, CV_16S, 1, 0, 3);\n cv::Sobel(gray, gy, CV_16S, 0, 1, 3);\n cv::magnitude(gx, gy, gm);\n cv::normalize(gm, gt, 1.0, 0.0, cv::NORM_INF);\n gt.convertTo(gmnorm, CV_64FC1);\n\n cv::Mat etf;\n gmnorm.copyTo(etf);\n}\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n std::cout << argv[0] << \" \" << std::endl;\n return 1;\n }\n\n auto img = cv::imread(argv[1]);\n cv::imshow(\"input\", img);\n cv::waitKey(0);\n\n return 0;\n}\ndrawing poor results#include \n#include \n#include \n\n#include \n\nint Ws(const cv::Point2d &a, const cv::Point2d &b, const int radius) {\n return ((cv::norm(cv::Mat(a), cv::Mat(b), cv::NORM_L2) < radius) ? 1 : 0);\n}\n\ndouble Wm(const cv::Point2d &a, const cv::Point2d &b, const cv::Mat &grad,\n const double eta = 1.0) {\n double ga = grad.at(a.y, a.x);\n double gb = grad.at(b.y, b.x);\n return (0.5 * (1.0 + std::tanh(eta * (gb - ga))));\n}\n\ndouble Wd(const cv::Point2d &a, const cv::Point2d &b, const cv::Mat &tcurr) {\n double ta = tcurr.at(a.y, a.x);\n double tb = tcurr.at(b.y, b.x);\n double mult = ta * tb;\n return ((mult > 0) ? std::abs(mult) : -1.0 * std::abs(mult));\n}\n\nvoid ETFIteration(cv::Mat &tcurr, const cv::Mat &grad, const int kradius) {\n cv::Mat tnew = cv::Mat::zeros(tcurr.size(), CV_64FC1);\n for (auto y = 0; y < (int)tcurr.size().height; ++y) {\n for (auto x = 0; x < (int)tcurr.size().width; ++x) {\n const auto pa = cv::Point2d(x, y);\n double sigma = 0;\n double k = 0;\n for (auto oy = -kradius; oy <= kradius; ++oy) {\n int py = y + oy;\n if (py < 0 || py > tcurr.size().height)\n continue;\n for (auto ox = -kradius; ox <= kradius; ++ox) {\n int px = x + ox;\n if (px < 0 || px > tcurr.size().width)\n continue;\n k += 1.0;\n const auto pb = cv::Point2d(px, py);\n sigma += tcurr.at(pb) * Ws(pa, pb, kradius) *\n Wm(pa, pb, grad) * Wd(pa, pb, tcurr);\n }\n }\n tnew.at(pa) = (k > 0.1) ? sigma \/ k : 0.0;\n }\n }\n tcurr = tnew;\n}\n\ncv::Mat coherentLines(const cv::Mat &img, const int kernel_radius = 5,\n const int etf_iterations = 3) {\n cv::Mat gray;\n cv::cvtColor(img, gray, CV_BGR2GRAY);\n\n cv::Mat gx, gy, gm, gt, gmnorm;\n cv::Sobel(gray, gx, CV_64F, 1, 0, 3);\n cv::Sobel(gray, gy, CV_64F, 0, 1, 3);\n cv::magnitude(gx, gy, gm);\n cv::normalize(gm, gt, 1.0, 0.0, cv::NORM_INF);\n gt.convertTo(gmnorm, CV_64FC1);\n\n cv::imshow(\"Grad\", gmnorm);\n cv::waitKey(100);\n\n cv::Mat etf;\n gmnorm.copyTo(etf);\n for (auto i = 0; i < etf_iterations; ++i)\n ETFIteration(etf, gmnorm, kernel_radius);\n\n cv::Mat etf_vis;\n cv::normalize(etf, etf_vis, 1.0, 0.0, cv::NORM_MINMAX);\n cv::imshow(\"ETF\", etf_vis);\n\n return etf;\n}\n\nint main(int argc, char **argv) {\n if (argc != 2) {\n std::cout << argv[0] << \" \" << std::endl;\n return 1;\n }\n\n auto img = cv::imread(argv[1]);\n cv::imshow(\"input\", img);\n cv::waitKey(100);\n\n coherentLines(img);\n cv::waitKey(0);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n\n#include \"PointerDataType.h\"\n#include \"HelperFunction.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\nusing namespace FTL;\n\nnamespace FTLTest\n{\n\tTEST_CLASS(PointerTest)\n\t{\n\tpublic:\n\t\tTEST_METHOD(PointerTest1)\n\t\t{\n\t\t\tunique_ptr ptpt;\n\t\t\tint a = 3;\n\t\t\tint* pA = &a;\n\t\t\tPointerDataType t1 = &a;\n\t\t\tint*& ppA = pA;\n\t\t\t*ppA;\n\t\t\tdecltype((*ppA)) pppA = *pA;\n\t\t\tLog(*t1);\n\t\t}\n\t};\n}Pointer test added#include \"stdafx.h\"\n#include \"CppUnitTest.h\"\n\n#include \"PointerDataType.h\"\n#include \"HelperFunction.h\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\nusing namespace std;\nusing namespace FTL;\n\nnamespace FTLTest\n{\n\tTEST_CLASS(PointerTest)\n\t{\n\tpublic:\n\t\tTEST_METHOD(PointerTest1)\n\t\t{\n\t\t\tint a = 3;\n\t\t\tint* pA = &a;\n\t\t\tPointerDataType t1 = &a;\n\n\t\t\tAssert::AreEqual(pA, t1);\n\t\t\tAssert::AreEqual(&a, t1);\n\n\t\t\tAssert::AreEqual(3, a);\n\t\t\tAssert::AreEqual(3, *pA);\n\t\t\tAssert::AreEqual(3, *t1);\n\n\t\t\ta = 4;\n\n\t\t\tAssert::AreEqual(4, a);\n\t\t\tAssert::AreEqual(4, *pA);\n\t\t\tAssert::AreEqual(4, *t1);\n\n\t\t\t*pA = 5;\n\n\t\t\tAssert::AreEqual(5, a);\n\t\t\tAssert::AreEqual(5, *pA);\n\t\t\tAssert::AreEqual(5, *t1);\n\n\t\t\t*t1 = 6;\n\n\t\t\tAssert::AreEqual(6, a);\n\t\t\tAssert::AreEqual(6, *pA);\n\t\t\tAssert::AreEqual(6, *t1);\n\t\t}\n\n\t\tTEST_METHOD(PointerTest2)\n\t\t{\n\t\t\tint* pA = new int(3);\n\t\t\tunique_ptr upt(pA);\n\n\t\t\tAssert::AreEqual(3, *upt);\n\n\t\t\tPointerDataType pt;\n\t\t\tpt.swap(upt);\n\n\t\t\tAssert::AreEqual(true, std::is_same::value);\n\t\t\tAssert::AreEqual(true, upt.get() == nullptr);\n\t\t\tAssert::AreEqual(3, *pt);\n\t\t\tAssert::AreEqual(pA, pt.get());\n\n\t\t\t*pA = 4;\n\n\t\t\tAssert::AreEqual(4, *pA);\n\t\t\tAssert::AreEqual(4, *pt);\n\n\t\t\t*pt = 5;\n\n\t\t\tAssert::AreEqual(5, *pA);\n\t\t\tAssert::AreEqual(5, *pt);\n\t\t}\n\t};\n}<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Stephen F. Booth \n * All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * - Neither the name of Stephen F. Booth nor the names of its \n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n\n#include \"MP3Metadata.h\"\n#include \"CreateDisplayNameForURL.h\"\n#include \"AddID3v1TagToDictionary.h\"\n#include \"AddID3v2TagToDictionary.h\"\n#include \"SetID3v2TagFromMetadata.h\"\n#include \"AddAudioPropertiesToDictionary.h\"\n\n#pragma mark Static Methods\n\nCFArrayRef MP3Metadata::CreateSupportedFileExtensions()\n{\n\tCFStringRef supportedExtensions [] = { CFSTR(\"mp3\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedExtensions), 1, &kCFTypeArrayCallBacks);\n}\n\nCFArrayRef MP3Metadata::CreateSupportedMIMETypes()\n{\n\tCFStringRef supportedMIMETypes [] = { CFSTR(\"audio\/mpeg\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);\n}\n\nbool MP3Metadata::HandlesFilesWithExtension(CFStringRef extension)\n{\n\tif(NULL == extension)\n\t\treturn false;\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"mp3\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\n\treturn false;\n}\n\nbool MP3Metadata::HandlesMIMEType(CFStringRef mimeType)\n{\n\tif(NULL == mimeType)\n\t\treturn false;\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR(\"audio\/mpeg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\t\n\treturn false;\n}\n\n#pragma mark Creation and Destruction\n\nMP3Metadata::MP3Metadata(CFURLRef url)\n\t: AudioMetadata(url)\n{}\n\nMP3Metadata::~MP3Metadata()\n{}\n\n#pragma mark Functionality\n\nbool MP3Metadata::ReadMetadata(CFErrorRef *error)\n{\n\t\/\/ Start from scratch\n\tCFDictionaryRemoveAllValues(mMetadata);\n\tCFDictionaryRemoveAllValues(mChangedMetadata);\n\t\n\tUInt8 buf [PATH_MAX];\n\tif(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\t\n\tTagLib::MPEG::File file(reinterpret_cast(buf), TagLib::ID3v2::FrameFactory::instance(), true);\n\t\n\tif(!file.isValid()) {\n\t\tif(NULL != error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not a MPEG file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MP3\"));\n\n\tif(file.audioProperties()) {\n\t\tTagLib::MPEG::Properties *properties = file.audioProperties();\n\t\tAddAudioPropertiesToDictionary(mMetadata, properties);\n\n\t\t\/\/ TODO: Is this too much information?\n#if 0\n\t\tswitch(properties->version()) {\n\t\t\tcase TagLib::MPEG::Header::Version1:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer I\"));\t\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TagLib::MPEG::Header::Version2:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer I\"));\t\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TagLib::MPEG::Header::Version2_5:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer I\"));\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n#endif\n\n\t\tif(properties->xingHeader() && properties->xingHeader()->totalFrames()) {\n\t\t\tTagLib::uint frames = properties->xingHeader()->totalFrames();\n\t\t\tCFNumberRef totalFrames = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frames);\n\t\t\tCFDictionaryAddValue(mMetadata, kPropertiesTotalFramesKey, totalFrames);\n\t\t\tCFRelease(totalFrames), totalFrames = NULL;\t\t\t\n\t\t}\n\t}\n\n\tif(file.ID3v1Tag())\n\t\tAddID3v1TagToDictionary(mMetadata, file.ID3v1Tag());\n\n\tif(file.ID3v2Tag())\n\t\tAddID3v2TagToDictionary(mMetadata, file.ID3v2Tag());\n\n\treturn true;\n}\n\nbool MP3Metadata::WriteMetadata(CFErrorRef *error)\n{\n\tUInt8 buf [PATH_MAX];\n\tif(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\n\tTagLib::MPEG::File file(reinterpret_cast(buf), false, false);\n\t\n\tif(!file.isValid()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not a MPEG file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\tSetID3v2TagFromMetadata(*this, file.ID3v2Tag(true));\n\n\tif(!file.save()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Unable to write metadata\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tMergeChangedMetadataIntoMetadata();\n\t\n\treturn true;\n}\nEnsure MP3 files are opened read-only in ReadMetadata()\/*\n * Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Stephen F. Booth \n * All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * - Neither the name of Stephen F. Booth nor the names of its \n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n\n#include \"MP3Metadata.h\"\n#include \"CreateDisplayNameForURL.h\"\n#include \"AddID3v1TagToDictionary.h\"\n#include \"AddID3v2TagToDictionary.h\"\n#include \"SetID3v2TagFromMetadata.h\"\n#include \"AddAudioPropertiesToDictionary.h\"\n\n#pragma mark Static Methods\n\nCFArrayRef MP3Metadata::CreateSupportedFileExtensions()\n{\n\tCFStringRef supportedExtensions [] = { CFSTR(\"mp3\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedExtensions), 1, &kCFTypeArrayCallBacks);\n}\n\nCFArrayRef MP3Metadata::CreateSupportedMIMETypes()\n{\n\tCFStringRef supportedMIMETypes [] = { CFSTR(\"audio\/mpeg\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);\n}\n\nbool MP3Metadata::HandlesFilesWithExtension(CFStringRef extension)\n{\n\tif(NULL == extension)\n\t\treturn false;\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"mp3\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\n\treturn false;\n}\n\nbool MP3Metadata::HandlesMIMEType(CFStringRef mimeType)\n{\n\tif(NULL == mimeType)\n\t\treturn false;\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR(\"audio\/mpeg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\t\n\treturn false;\n}\n\n#pragma mark Creation and Destruction\n\nMP3Metadata::MP3Metadata(CFURLRef url)\n\t: AudioMetadata(url)\n{}\n\nMP3Metadata::~MP3Metadata()\n{}\n\n#pragma mark Functionality\n\nbool MP3Metadata::ReadMetadata(CFErrorRef *error)\n{\n\t\/\/ Start from scratch\n\tCFDictionaryRemoveAllValues(mMetadata);\n\tCFDictionaryRemoveAllValues(mChangedMetadata);\n\t\n\tUInt8 buf [PATH_MAX];\n\tif(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\t\n\tTagLib::IOStream *stream = new TagLib::FileStream(reinterpret_cast(buf), true);\n\tTagLib::MPEG::File file(stream, TagLib::ID3v2::FrameFactory::instance());\n\t\n\tif(!file.isValid()) {\n\t\tif(NULL != error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not a MPEG file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MP3\"));\n\n\tif(file.audioProperties()) {\n\t\tTagLib::MPEG::Properties *properties = file.audioProperties();\n\t\tAddAudioPropertiesToDictionary(mMetadata, properties);\n\n\t\t\/\/ TODO: Is this too much information?\n#if 0\n\t\tswitch(properties->version()) {\n\t\t\tcase TagLib::MPEG::Header::Version1:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer I\"));\t\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-1 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TagLib::MPEG::Header::Version2:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer I\"));\t\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TagLib::MPEG::Header::Version2_5:\n\t\t\t\tswitch(properties->layer()) {\n\t\t\t\t\tcase 1:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer I\"));\tbreak;\n\t\t\t\t\tcase 2:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer II\"));\tbreak;\n\t\t\t\t\tcase 3:\t\tCFDictionarySetValue(mMetadata, kPropertiesFormatNameKey, CFSTR(\"MPEG-2.5 Layer III\"));\tbreak;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n#endif\n\n\t\tif(properties->xingHeader() && properties->xingHeader()->totalFrames()) {\n\t\t\tTagLib::uint frames = properties->xingHeader()->totalFrames();\n\t\t\tCFNumberRef totalFrames = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frames);\n\t\t\tCFDictionaryAddValue(mMetadata, kPropertiesTotalFramesKey, totalFrames);\n\t\t\tCFRelease(totalFrames), totalFrames = NULL;\t\t\t\n\t\t}\n\t}\n\n\tif(file.ID3v1Tag())\n\t\tAddID3v1TagToDictionary(mMetadata, file.ID3v1Tag());\n\n\tif(file.ID3v2Tag())\n\t\tAddID3v2TagToDictionary(mMetadata, file.ID3v2Tag());\n\n\treturn true;\n}\n\nbool MP3Metadata::WriteMetadata(CFErrorRef *error)\n{\n\tUInt8 buf [PATH_MAX];\n\tif(!CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\n\tTagLib::IOStream *stream = new TagLib::FileStream(reinterpret_cast(buf));\n\tTagLib::MPEG::File file(stream, TagLib::ID3v2::FrameFactory::instance(), false);\n\t\n\tif(!file.isValid()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not a MPEG file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\tSetID3v2TagFromMetadata(*this, file.ID3v2Tag(true));\n\n\tif(!file.save()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file “%@” is not a valid MPEG file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Unable to write metadata\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\tMergeChangedMetadataIntoMetadata();\n\t\n\treturn true;\n}\n<|endoftext|>"} {"text":"#ifndef _MZ_NET_ADDRESS_HPP_\n#define _MZ_NET_ADDRESS_HPP_\n\n#include \"Metazion\/Net\/NetInclude.hpp\"\n\nDECL_NAMESPACE_MZ_NET_BEGIN\n\nstruct Address {\n UINT32 m_ip = 0;\n UINT16 m_port = 0;\n};\n\nDECL_NAMESPACE_MZ_NET_END\n\n#endif \/\/ _MZ_NET_ADDRESS_HPP_\nFix some issues.#ifndef _MZ_NET_ADDRESS_HPP_\n#define _MZ_NET_ADDRESS_HPP_\n\n#include \"Metazion\/Net\/NetInclude.hpp\"\n\nDECL_NAMESPACE_MZ_NET_BEGIN\n\nstruct Address {\n uint32_t m_ip = 0;\n uint16_t m_port = 0;\n};\n\nDECL_NAMESPACE_MZ_NET_END\n\n#endif \/\/ _MZ_NET_ADDRESS_HPP_\n<|endoftext|>"} {"text":"#include \"Pong\/State\/GameState.hpp\"\n\n#include \n\n#include \"Pong\/Pong.hpp\"\n#include \"Pong\/InputHandler\/RaquetInputHandler.hpp\"\n#include \"Pong\/InputHandler\/ComputerPlayerInputHandler.hpp\"\n\nnamespace pong {\n\nvoid syncBodyToTransformable(b2Body* body, sf::Transformable& transformable) {\n b2Vec2 position = body->GetPosition();\n float angle = body->GetAngle();\n transformable.setPosition(position.x * PIXELS_PER_METER,\n position.y * PIXELS_PER_METER);\n transformable.setRotation(angle * 180.0f \/ M_PI);\n}\n\nvoid GameState::create() {\n setupGameWorld();\n setupInputHandlers();\n createShapes();\n createScoreBoard();\n}\n\nvoid GameState::enter() {\n}\n\nvoid GameState::setupGameWorld() {\n gameWorld_.create();\n gameWorld_.addScoreListener(&scoreBoard_);\n gameWorld_.addScoreListener(this);\n gameWorld_.start();\n\n#ifndef NDEBUG\n setupDebugDraw();\n#endif \/* ifndef NDEBUG *\/\n}\n\nvoid GameState::setupDebugDraw() {\n debugDraw_.reset(new mxg::SFMLDebugDraw(game_->window(), PIXELS_PER_METER));\n gameWorld_.setDebugDraw(debugDraw_.get());\n debugDraw_->SetFlags(b2Draw::e_shapeBit);\n}\n\nvoid GameState::setupInputHandlers() {\n setupPlayerOneInputHandler();\n setupPlayerTwoInputHandler(); }\n\nvoid GameState::setupPlayerOneInputHandler() {\n b2Body* leftRaquet = gameWorld_.leftRaquet();\n b2Vec2 upVelocity(0.0f, -RAQUET_BASE_SPEED);\n b2Vec2 downVelocity(0.0f, RAQUET_BASE_SPEED);\n\n RaquetInputHandler* leftHandler = new RaquetInputHandler(leftRaquet);\n leftHandler->bindKey(sf::Keyboard::W, InputHandler::UP);\n leftHandler->bindKey(sf::Keyboard::S, InputHandler::DOWN);\n\n Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);\n leftHandler->bindCommand(InputHandler::UP, command);\n command = new MoveRaquetCommand(leftRaquet, downVelocity);\n leftHandler->bindCommand(InputHandler::DOWN, command);\n\n inputHandlers_[PLAYER_1].reset(leftHandler);\n}\n\nvoid GameState::setupPlayerTwoInputHandler() {\n b2Body* rightRaquet = gameWorld_.rightRaquet();\n b2Body* ball = gameWorld_.ball();\n b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);\n b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);\n\n float xMaxDistance = (WINDOW_HALF_WIDHT - RAQUET_WIDTH) \/ PIXELS_PER_METER;\n float yMaxDistance = (RAQUET_HALF_HEIGHT - 20.0f) \/ PIXELS_PER_METER;\n ComputerPlayerInputHandler* rightHandler =\n new ComputerPlayerInputHandler(rightRaquet, ball,\n xMaxDistance, yMaxDistance);\n\n Command* command = new MoveRaquetCommand(rightRaquet, upVelocity);\n rightHandler->bindCommand(InputHandler::UP, command);\n command = new MoveRaquetCommand(rightRaquet, downVelocity);\n rightHandler->bindCommand(InputHandler::DOWN, command);\n\n inputHandlers_[PLAYER_2].reset(rightHandler);\n}\n\nvoid GameState::createShapes() {\n midfield_ = shapeFactory_.makeMidfield();\n ball_ = shapeFactory_.makeBall();\n syncBodyToTransformable(gameWorld_.ball(), ball_);\n leftRaquet_ = shapeFactory_.makeLeftRaquet();\n syncBodyToTransformable(gameWorld_.leftRaquet(), leftRaquet_);\n rightRaquet_ = shapeFactory_.makeRightRaquet();\n syncBodyToTransformable(gameWorld_.rightRaquet(), rightRaquet_);\n topWall_ = shapeFactory_.makeTopWall();\n syncBodyToTransformable(gameWorld_.topWall(), topWall_);\n bottomWall_ = shapeFactory_.makeBottomWall();\n syncBodyToTransformable(gameWorld_.bottomWall(), bottomWall_);\n}\n\nvoid GameState::createScoreBoard() {\n sf::Vector2f position(WINDOW_HALF_WIDHT, 32);\n\n Assets& assets = game_->assets();\n scoreBoard_.create(assets.defaultFont());\n scoreBoard_.setPosition(position);\n}\n\nvoid GameState::updateShapes() {\n syncBodyToTransformable(gameWorld_.ball(), ball_);\n syncBodyToTransformable(gameWorld_.leftRaquet(), leftRaquet_);\n syncBodyToTransformable(gameWorld_.rightRaquet(), rightRaquet_);\n}\n\nvoid GameState::renderShapes(sf::RenderTarget& renderTarget) {\n renderTarget.draw(midfield_);\n renderTarget.draw(ball_);\n renderTarget.draw(leftRaquet_);\n renderTarget.draw(rightRaquet_);\n renderTarget.draw(topWall_);\n renderTarget.draw(bottomWall_);\n renderTarget.draw(scoreBoard_);\n}\n\nvoid GameState::exit() {\n}\n\nvoid GameState::processEvent(const sf::Event& event) {\n if (event.type == sf::Event::KeyReleased) {\n if (event.key.code == sf::Keyboard::R) {\n GameState* state = new GameState(game_);\n state->create();\n game_->changeState(state);\n } else if (event.key.code == sf::Keyboard::P) {\n gameWorld_.toggleRunning();\n }\n } else {\n DefaultState::processEvent(event);\n }\n}\n\nvoid GameState::update() {\n for (auto& handler : inputHandlers_) {\n Command* command = handler->handleInput();\n command->execute();\n }\n\n gameWorld_.update();\n\n updateShapes();\n scoreBoard_.update();\n\n if (scoreBoard_.rightScore() >= MATCH_POINT) {\n game_->changeState(new GameState(game_));\n std::cout << \"Left win!\" << std::endl;\n } else if (scoreBoard_.leftScore() >= MATCH_POINT) {\n game_->changeState(new GameState(game_));\n std::cout << \"Right win!\" << std::endl;\n }\n}\n\nvoid GameState::render(sf::RenderTarget& renderTarget) {\n renderShapes(renderTarget);\n\n#ifndef NDEBUG\n gameWorld_.drawDebugData();\n#endif \/* ifndef NDEBUG *\/\n}\n\nvoid GameState::leftScored(GameWorld& gameWorld) {\n gameWorld.resetBall();\n gameWorld.start();\n}\n\nvoid GameState::rightScored(GameWorld& gameWorld) {\n gameWorld.resetBall();\n gameWorld.start();\n}\n\n} \/* namespace pong *\/\nMove enter() close to exit()#include \"Pong\/State\/GameState.hpp\"\n\n#include \n\n#include \"Pong\/Pong.hpp\"\n#include \"Pong\/InputHandler\/RaquetInputHandler.hpp\"\n#include \"Pong\/InputHandler\/ComputerPlayerInputHandler.hpp\"\n\nnamespace pong {\n\nvoid syncBodyToTransformable(b2Body* body, sf::Transformable& transformable) {\n b2Vec2 position = body->GetPosition();\n float angle = body->GetAngle();\n transformable.setPosition(position.x * PIXELS_PER_METER,\n position.y * PIXELS_PER_METER);\n transformable.setRotation(angle * 180.0f \/ M_PI);\n}\n\nvoid GameState::create() {\n setupGameWorld();\n setupInputHandlers();\n createShapes();\n createScoreBoard();\n}\n\nvoid GameState::setupGameWorld() {\n gameWorld_.create();\n gameWorld_.addScoreListener(&scoreBoard_);\n gameWorld_.addScoreListener(this);\n gameWorld_.start();\n\n#ifndef NDEBUG\n setupDebugDraw();\n#endif \/* ifndef NDEBUG *\/\n}\n\nvoid GameState::setupDebugDraw() {\n debugDraw_.reset(new mxg::SFMLDebugDraw(game_->window(), PIXELS_PER_METER));\n gameWorld_.setDebugDraw(debugDraw_.get());\n debugDraw_->SetFlags(b2Draw::e_shapeBit);\n}\n\nvoid GameState::setupInputHandlers() {\n setupPlayerOneInputHandler();\n setupPlayerTwoInputHandler(); }\n\nvoid GameState::setupPlayerOneInputHandler() {\n b2Body* leftRaquet = gameWorld_.leftRaquet();\n b2Vec2 upVelocity(0.0f, -RAQUET_BASE_SPEED);\n b2Vec2 downVelocity(0.0f, RAQUET_BASE_SPEED);\n\n RaquetInputHandler* leftHandler = new RaquetInputHandler(leftRaquet);\n leftHandler->bindKey(sf::Keyboard::W, InputHandler::UP);\n leftHandler->bindKey(sf::Keyboard::S, InputHandler::DOWN);\n\n Command* command = new MoveRaquetCommand(leftRaquet, upVelocity);\n leftHandler->bindCommand(InputHandler::UP, command);\n command = new MoveRaquetCommand(leftRaquet, downVelocity);\n leftHandler->bindCommand(InputHandler::DOWN, command);\n\n inputHandlers_[PLAYER_1].reset(leftHandler);\n}\n\nvoid GameState::setupPlayerTwoInputHandler() {\n b2Body* rightRaquet = gameWorld_.rightRaquet();\n b2Body* ball = gameWorld_.ball();\n b2Vec2 upVelocity(0.0f, RAQUET_BASE_SPEED);\n b2Vec2 downVelocity(0.0f, -RAQUET_BASE_SPEED);\n\n float xMaxDistance = (WINDOW_HALF_WIDHT - RAQUET_WIDTH) \/ PIXELS_PER_METER;\n float yMaxDistance = (RAQUET_HALF_HEIGHT - 20.0f) \/ PIXELS_PER_METER;\n ComputerPlayerInputHandler* rightHandler =\n new ComputerPlayerInputHandler(rightRaquet, ball,\n xMaxDistance, yMaxDistance);\n\n Command* command = new MoveRaquetCommand(rightRaquet, upVelocity);\n rightHandler->bindCommand(InputHandler::UP, command);\n command = new MoveRaquetCommand(rightRaquet, downVelocity);\n rightHandler->bindCommand(InputHandler::DOWN, command);\n\n inputHandlers_[PLAYER_2].reset(rightHandler);\n}\n\nvoid GameState::createShapes() {\n midfield_ = shapeFactory_.makeMidfield();\n ball_ = shapeFactory_.makeBall();\n syncBodyToTransformable(gameWorld_.ball(), ball_);\n leftRaquet_ = shapeFactory_.makeLeftRaquet();\n syncBodyToTransformable(gameWorld_.leftRaquet(), leftRaquet_);\n rightRaquet_ = shapeFactory_.makeRightRaquet();\n syncBodyToTransformable(gameWorld_.rightRaquet(), rightRaquet_);\n topWall_ = shapeFactory_.makeTopWall();\n syncBodyToTransformable(gameWorld_.topWall(), topWall_);\n bottomWall_ = shapeFactory_.makeBottomWall();\n syncBodyToTransformable(gameWorld_.bottomWall(), bottomWall_);\n}\n\nvoid GameState::createScoreBoard() {\n sf::Vector2f position(WINDOW_HALF_WIDHT, 32);\n\n Assets& assets = game_->assets();\n scoreBoard_.create(assets.defaultFont());\n scoreBoard_.setPosition(position);\n}\n\nvoid GameState::updateShapes() {\n syncBodyToTransformable(gameWorld_.ball(), ball_);\n syncBodyToTransformable(gameWorld_.leftRaquet(), leftRaquet_);\n syncBodyToTransformable(gameWorld_.rightRaquet(), rightRaquet_);\n}\n\nvoid GameState::renderShapes(sf::RenderTarget& renderTarget) {\n renderTarget.draw(midfield_);\n renderTarget.draw(ball_);\n renderTarget.draw(leftRaquet_);\n renderTarget.draw(rightRaquet_);\n renderTarget.draw(topWall_);\n renderTarget.draw(bottomWall_);\n renderTarget.draw(scoreBoard_);\n}\n\nvoid GameState::enter() {\n}\n\nvoid GameState::exit() {\n}\n\nvoid GameState::processEvent(const sf::Event& event) {\n if (event.type == sf::Event::KeyReleased) {\n if (event.key.code == sf::Keyboard::R) {\n GameState* state = new GameState(game_);\n state->create();\n game_->changeState(state);\n } else if (event.key.code == sf::Keyboard::P) {\n gameWorld_.toggleRunning();\n }\n } else {\n DefaultState::processEvent(event);\n }\n}\n\nvoid GameState::update() {\n for (auto& handler : inputHandlers_) {\n Command* command = handler->handleInput();\n command->execute();\n }\n\n gameWorld_.update();\n\n updateShapes();\n scoreBoard_.update();\n\n if (scoreBoard_.rightScore() >= MATCH_POINT) {\n game_->changeState(new GameState(game_));\n std::cout << \"Left win!\" << std::endl;\n } else if (scoreBoard_.leftScore() >= MATCH_POINT) {\n game_->changeState(new GameState(game_));\n std::cout << \"Right win!\" << std::endl;\n }\n}\n\nvoid GameState::render(sf::RenderTarget& renderTarget) {\n renderShapes(renderTarget);\n\n#ifndef NDEBUG\n gameWorld_.drawDebugData();\n#endif \/* ifndef NDEBUG *\/\n}\n\nvoid GameState::leftScored(GameWorld& gameWorld) {\n gameWorld.resetBall();\n gameWorld.start();\n}\n\nvoid GameState::rightScored(GameWorld& gameWorld) {\n gameWorld.resetBall();\n gameWorld.start();\n}\n\n} \/* namespace pong *\/\n<|endoftext|>"} {"text":"fix cputrack test build<|endoftext|>"} {"text":"#include \"Really.hpp\"\n#include \"..\/Core\/Core.hpp\"\n\nvoid Really::onButtonPressed(bool witch_button)\n{\n\tif(witch_button)\n\t{\n\t\tfor(LG::WindowList::Iterator* itr = ::Core::script_windows.getIterator(0); itr ;itr=itr->getNext())\n\t\t\titr->getValue().delete_me = true;\n\t}\n\n\tdelete_me = true;\n\t::Core::commander.command(\"observe -script\");\n}FIX: 디버깅 도중 종료를 하면 에러가 발생함#include \"Really.hpp\"\n#include \"..\/Core\/Core.hpp\"\n\nvoid Really::onButtonPressed(bool witch_button)\n{\n\tif(witch_button)\n\t{\n\t\tfor(LG::WindowList::Iterator* itr = ::Core::script_windows.getIterator(0); itr ;itr=itr->getNext())\n\t\t\titr->getValue().delete_me = true;\n\t}\n\n\tdelete_me = true;\n\tEditor::getInstance().getEventHandler().stopTest();\n\t::Core::commander.command(\"observe -script\");\n}<|endoftext|>"} {"text":"\/**\n *\n * HX711 library for Arduino\n * https:\/\/github.com\/bogde\/HX711\n *\n * MIT License\n * (c) 2018 Bogdan Necula\n *\n**\/\n#include \n#include \n\n#ifndef ESP_H\n\t#if ARDUINO <= 106\n \/\/ \"yield\" is not implemented as noop in older Arduino Core releases, so let's define it.\n \/\/ See also: https:\/\/stackoverflow.com\/questions\/34497758\/what-is-the-secret-of-the-arduino-yieldfunction\/34498165#34498165\n \tvoid yield(void) {};\n\t#endif\n#endif\n\n#ifdef ESP_H\nuint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {\n uint8_t value = 0;\n uint8_t i;\n\n for(i = 0; i < 8; ++i) {\n digitalWrite(clockPin, HIGH);\n delayMicroseconds(1);\n if(bitOrder == LSBFIRST)\n value |= digitalRead(dataPin) << i;\n else\n value |= digitalRead(dataPin) << (7 - i);\n digitalWrite(clockPin, LOW);\n delayMicroseconds(1);\n }\n return value;\n}\n#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)\n#else\n#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)\n#endif\n\nHX711::HX711() {\n}\n\nHX711::~HX711() {\n}\n\nvoid HX711::begin(byte dout, byte pd_sck, byte gain) {\n\tPD_SCK = pd_sck;\n\tDOUT = dout;\n\n\tpinMode(PD_SCK, OUTPUT);\n\tpinMode(DOUT, INPUT);\n\n\tset_gain(gain);\n}\n\nbool HX711::is_ready() {\n\treturn digitalRead(DOUT) == LOW;\n}\n\nvoid HX711::set_gain(byte gain) {\n\tswitch (gain) {\n\t\tcase 128:\t\t\/\/ channel A, gain factor 128\n\t\t\tGAIN = 1;\n\t\t\tbreak;\n\t\tcase 64:\t\t\/\/ channel A, gain factor 64\n\t\t\tGAIN = 3;\n\t\t\tbreak;\n\t\tcase 32:\t\t\/\/ channel B, gain factor 32\n\t\t\tGAIN = 2;\n\t\t\tbreak;\n\t}\n\n\tdigitalWrite(PD_SCK, LOW);\n\tread();\n}\n\nlong HX711::read() {\n\t\/\/ wait for the chip to become ready\n\twhile (!is_ready()) {\n\t\t\/\/ Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)\n\t\tyield();\n\t}\n\n\tunsigned long value = 0;\n\tuint8_t data[3] = { 0 };\n\tuint8_t filler = 0x00;\n\n\t\/\/ pulse the clock pin 24 times to read the data\n\tdata[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\tdata[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\tdata[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\n\t\/\/ set the channel and the gain factor for the next reading using the clock pin\n\tfor (unsigned int i = 0; i < GAIN; i++) {\n\t\tdigitalWrite(PD_SCK, HIGH);\n\t\t#ifdef ESP_H\n\t\tdelayMicroseconds(1);\n\t\t#endif\n\t\tdigitalWrite(PD_SCK, LOW);\n\t\t#ifdef ESP_H\n\t\tdelayMicroseconds(1);\n\t\t#endif\n\t}\n\n\t\/\/ Replicate the most significant bit to pad out a 32-bit signed integer\n\tif (data[2] & 0x80) {\n\t\tfiller = 0xFF;\n\t} else {\n\t\tfiller = 0x00;\n\t}\n\n\t\/\/ Construct a 32-bit signed integer\n\tvalue = ( static_cast(filler) << 24\n\t\t\t| static_cast(data[2]) << 16\n\t\t\t| static_cast(data[1]) << 8\n\t\t\t| static_cast(data[0]) );\n\n\treturn static_cast(value);\n}\n\nlong HX711::read_average(byte times) {\n\tlong sum = 0;\n\tfor (byte i = 0; i < times; i++) {\n\t\tsum += read();\n\t\tyield();\n\t}\n\treturn sum \/ times;\n}\n\ndouble HX711::get_value(byte times) {\n\treturn read_average(times) - OFFSET;\n}\n\nfloat HX711::get_units(byte times) {\n\treturn get_value(times) \/ SCALE;\n}\n\nvoid HX711::tare(byte times) {\n\tdouble sum = read_average(times);\n\tset_offset(sum);\n}\n\nvoid HX711::set_scale(float scale) {\n\tSCALE = scale;\n}\n\nfloat HX711::get_scale() {\n\treturn SCALE;\n}\n\nvoid HX711::set_offset(long offset) {\n\tOFFSET = offset;\n}\n\nlong HX711::get_offset() {\n\treturn OFFSET;\n}\n\nvoid HX711::power_down() {\n\tdigitalWrite(PD_SCK, LOW);\n\tdigitalWrite(PD_SCK, HIGH);\n}\n\nvoid HX711::power_up() {\n\tdigitalWrite(PD_SCK, LOW);\n}\nAdd shiftIn() speed support for Teensy\/**\n *\n * HX711 library for Arduino\n * https:\/\/github.com\/bogde\/HX711\n *\n * MIT License\n * (c) 2018 Bogdan Necula\n *\n**\/\n#include \n#include \n\n#ifndef ESP_H\n\t#if ARDUINO <= 106\n \/\/ \"yield\" is not implemented as noop in older Arduino Core releases, so let's define it.\n \/\/ See also: https:\/\/stackoverflow.com\/questions\/34497758\/what-is-the-secret-of-the-arduino-yieldfunction\/34498165#34498165\n \tvoid yield(void) {};\n\t#endif\n#endif\n\n#if defined(ESP_H) || defined(CORE_TEENSY)\n\/\/ Make shiftIn() be aware of clockspeed for ESP32, Teensy 3.x and friends\n\/\/ https:\/\/github.com\/bogde\/HX711\/issues\/75\n\/\/ https:\/\/github.com\/arduino\/Arduino\/issues\/6561\n\/\/ https:\/\/community.hiveeyes.org\/t\/using-bogdans-canonical-hx711-library-on-the-esp32\/539\nuint8_t shiftInSlow(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {\n uint8_t value = 0;\n uint8_t i;\n\n for(i = 0; i < 8; ++i) {\n digitalWrite(clockPin, HIGH);\n delayMicroseconds(1);\n if(bitOrder == LSBFIRST)\n value |= digitalRead(dataPin) << i;\n else\n value |= digitalRead(dataPin) << (7 - i);\n digitalWrite(clockPin, LOW);\n delayMicroseconds(1);\n }\n return value;\n}\n#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftInSlow(data,clock,order)\n#else\n#define SHIFTIN_WITH_SPEED_SUPPORT(data,clock,order) shiftIn(data,clock,order)\n#endif\n\nHX711::HX711() {\n}\n\nHX711::~HX711() {\n}\n\nvoid HX711::begin(byte dout, byte pd_sck, byte gain) {\n\tPD_SCK = pd_sck;\n\tDOUT = dout;\n\n\tpinMode(PD_SCK, OUTPUT);\n\tpinMode(DOUT, INPUT);\n\n\tset_gain(gain);\n}\n\nbool HX711::is_ready() {\n\treturn digitalRead(DOUT) == LOW;\n}\n\nvoid HX711::set_gain(byte gain) {\n\tswitch (gain) {\n\t\tcase 128:\t\t\/\/ channel A, gain factor 128\n\t\t\tGAIN = 1;\n\t\t\tbreak;\n\t\tcase 64:\t\t\/\/ channel A, gain factor 64\n\t\t\tGAIN = 3;\n\t\t\tbreak;\n\t\tcase 32:\t\t\/\/ channel B, gain factor 32\n\t\t\tGAIN = 2;\n\t\t\tbreak;\n\t}\n\n\tdigitalWrite(PD_SCK, LOW);\n\tread();\n}\n\nlong HX711::read() {\n\t\/\/ wait for the chip to become ready\n\twhile (!is_ready()) {\n\t\t\/\/ Will do nothing on Arduino but prevent resets of ESP8266 (Watchdog Issue)\n\t\tyield();\n\t}\n\n\tunsigned long value = 0;\n\tuint8_t data[3] = { 0 };\n\tuint8_t filler = 0x00;\n\n\t\/\/ pulse the clock pin 24 times to read the data\n\tdata[2] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\tdata[1] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\tdata[0] = SHIFTIN_WITH_SPEED_SUPPORT(DOUT, PD_SCK, MSBFIRST);\n\n\t\/\/ set the channel and the gain factor for the next reading using the clock pin\n\tfor (unsigned int i = 0; i < GAIN; i++) {\n\t\tdigitalWrite(PD_SCK, HIGH);\n\t\t#ifdef ESP_H\n\t\tdelayMicroseconds(1);\n\t\t#endif\n\t\tdigitalWrite(PD_SCK, LOW);\n\t\t#ifdef ESP_H\n\t\tdelayMicroseconds(1);\n\t\t#endif\n\t}\n\n\t\/\/ Replicate the most significant bit to pad out a 32-bit signed integer\n\tif (data[2] & 0x80) {\n\t\tfiller = 0xFF;\n\t} else {\n\t\tfiller = 0x00;\n\t}\n\n\t\/\/ Construct a 32-bit signed integer\n\tvalue = ( static_cast(filler) << 24\n\t\t\t| static_cast(data[2]) << 16\n\t\t\t| static_cast(data[1]) << 8\n\t\t\t| static_cast(data[0]) );\n\n\treturn static_cast(value);\n}\n\nlong HX711::read_average(byte times) {\n\tlong sum = 0;\n\tfor (byte i = 0; i < times; i++) {\n\t\tsum += read();\n\t\tyield();\n\t}\n\treturn sum \/ times;\n}\n\ndouble HX711::get_value(byte times) {\n\treturn read_average(times) - OFFSET;\n}\n\nfloat HX711::get_units(byte times) {\n\treturn get_value(times) \/ SCALE;\n}\n\nvoid HX711::tare(byte times) {\n\tdouble sum = read_average(times);\n\tset_offset(sum);\n}\n\nvoid HX711::set_scale(float scale) {\n\tSCALE = scale;\n}\n\nfloat HX711::get_scale() {\n\treturn SCALE;\n}\n\nvoid HX711::set_offset(long offset) {\n\tOFFSET = offset;\n}\n\nlong HX711::get_offset() {\n\treturn OFFSET;\n}\n\nvoid HX711::power_down() {\n\tdigitalWrite(PD_SCK, LOW);\n\tdigitalWrite(PD_SCK, HIGH);\n}\n\nvoid HX711::power_up() {\n\tdigitalWrite(PD_SCK, LOW);\n}\n<|endoftext|>"} {"text":"#include \"IOLoop.h\"\n\n#include \"io_connector.h\"\n#include \"log_macros.h\"\n#include \"IOHandle.h\"\n#include \"kernel.h\"\n\n#include \n#include \n\n#include \n#include \n\n\n#define SYSTEM_HEARTBEAT_MS 10\n\nstatic const char* safe_str(const char* s)\n{\n return s? s : \"null\";\n}\n\nnamespace XXX {\n\nstruct io_request\n{\n enum request_type\n {\n eNone = 0,\n eCancelHandle,\n eAddServer,\n eAddConnection\n } type;\n\n logger & logptr;\n std::string addr;\n std::string port;\n bool resolve_hostname;\n std::unique_ptr< std::promise > listener_err;\n uv_tcp_t * tcp_handle = nullptr;\n uv_close_cb on_close_cb = nullptr;\n socket_accept_cb on_accept;\n\n std::shared_ptr connector;\n\n io_request(request_type __type,\n logger & __logger)\n : type(__type),\n logptr(__logger)\n {}\n\n io_request(request_type __type,\n logger & __logger,\n std::string port,\n std::promise p,\n socket_accept_cb );\n\n};\n\n\n\nvoid IOLoop::on_tcp_connect_cb(uv_connect_t* connect_req, int status)\n{\n \/* IO thread *\/\n\n std::unique_ptr ioreq ((io_request*) connect_req->data );\n\n if (status < 0)\n {\n std::ostringstream oss;\n oss << \"uv_connect: \" << status << \", \" << safe_str(uv_err_name(status))\n << \", \" << safe_str(uv_strerror(status));\n ioreq->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n }\n else\n {\n ioreq->connector->io_on_connect_success();\n }\n}\n\n\nstatic void __on_tcp_connect(uv_stream_t* server, int status)\n{\n \/\/ IOLoop has set itself as the uv_loop data member\n tcp_server* myserver = (tcp_server*) server;\n IOLoop * myIOLoop = static_cast(server->loop->data);\n\n logger & __logger = myIOLoop->get_logger();\n\n \/\/ TODO: review if this is correct error handling\n if (status < 0)\n {\n LOG_ERROR(\"New connection error \" << uv_strerror(status));\n return;\n }\n\n uv_tcp_t *client = new uv_tcp_t();\n uv_tcp_init(myIOLoop->uv_loop(), client);\n\n if (uv_accept(server, (uv_stream_t *) client) == 0)\n {\n IOHandle* ioh = new IOHandle( myIOLoop->get_kernel(),\n (uv_stream_t *) client, myIOLoop);\n\n int fd = client->io_watcher.fd;\n\n LOG_INFO(\"accept: type=\" << client->type\n << \", fd=\" << fd);\n\n \/\/ register the stream before beginning read operations\n myserver->ioloop->add_passive_handle(myserver, ioh );\n\n \/\/ \/\/ NOTE: registration of read event moved into the handle\n\n \/\/ \/\/ \/\/ new client is accepted, identified via its stream handle ... need to put\n \/\/ \/\/ \/\/ in place a lot more session tracking here.\n \/\/ \/\/ uv_read_start((uv_stream_t *) client, alloc_buffer, io_on_read);\n }\n else\n {\n uv_close((uv_handle_t *) client, NULL);\n }\n\n}\n\n\n\n\n\n\nio_request::io_request(request_type __type,\n logger & lp,\n std::string __port,\n std::promise listen_err,\n socket_accept_cb __on_accept)\n : type( __type),\n logptr( lp ),\n port( __port ),\n listener_err( new std::promise(std::move(listen_err) ) ),\n on_accept( std::move(__on_accept) )\n{\n}\n\n\nIOLoop::IOLoop(kernel& k)\n : m_kernel(k),\n __logger( k.get_logger() ),\n m_uv_loop( new uv_loop_t() ),\n\n m_async( new uv_async_t() ),\n m_pending_flags( eNone )\n{\n uv_loop_init(m_uv_loop);\n m_uv_loop->data = this;\n\n \/\/ set up the async handler\n uv_async_init(m_uv_loop, m_async.get(), [](uv_async_t* h) {\n IOLoop* p = static_cast( h->data );\n p->on_async();\n });\n m_async->data = this;\n\n \/\/ TODO: I prefer to not have to do this. Need to review what is the correct\n \/\/ policy for handling sigpipe using libuv.\n \/\/ signal(SIGPIPE, SIG_IGN);\n}\n\nvoid IOLoop::stop()\n{\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_flags |= eFinal;\n }\n async_send();\n if (m_thread.joinable()) m_thread.join();\n}\n\nIOLoop::~IOLoop()\n{\n \/\/ uv_loop kept as raw pointer, because need to pass to several uv functions\n uv_loop_close(m_uv_loop);\n delete m_uv_loop;\n}\n\nvoid IOLoop::create_tcp_server_socket(int port,\n socket_accept_cb cb,\n std::unique_ptr< std::promise > listener_err )\n{\n \/* UV Loop *\/\n\n \/\/ Create a tcp socket, and configure for listen\n tcp_server * myserver = new tcp_server();\n myserver->port = port;\n myserver->ioloop = this;\n myserver->cb = cb;\n\n uv_tcp_init(m_uv_loop, &myserver->uvh);\n\n struct sockaddr_in addr;\n uv_ip4_addr(\"0.0.0.0\", port, &addr);\n\n unsigned flags = 0;\n int r;\n\n r = uv_tcp_bind(&myserver->uvh, (const struct sockaddr*)&addr, flags);\n if (r == 0)\n r = uv_listen((uv_stream_t *) &myserver->uvh, 5, __on_tcp_connect);\n listener_err->set_value(std::abs(r));\n\n m_server_handles.push_back( std::unique_ptr(myserver) );\n}\n\n\nvoid IOLoop::on_async()\n{\n \/* IO thread *\/\n std::vector< std::unique_ptr > work;\n int pending_flags = eNone;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n work.swap( m_pending_requests );\n std::swap(pending_flags, m_pending_flags);\n }\n\n if (m_async_closed) return;\n\n if (pending_flags & eFinal)\n {\n for (auto & i : m_server_handles)\n uv_close((uv_handle_t*)i.get(), 0);\n\n uv_close((uv_handle_t*) m_async.get(), 0);\n\n m_async_closed = true;\n return;\n }\n\n for (auto & user_req : work)\n {\n if (user_req->type == io_request::eCancelHandle)\n {\n uv_close((uv_handle_t*) user_req->tcp_handle, user_req->on_close_cb);\n }\n else if (user_req->type == io_request::eAddConnection)\n {\n \/\/ create the request\n std::unique_ptr req( std::move(user_req) ); \/\/ <--- the sp is here now\n\n const struct sockaddr* addrptr;\n struct sockaddr_in inetaddr;\n memset(&inetaddr, 0, sizeof(inetaddr));\n\n int r = 0;\n uv_getaddrinfo_t resolver;\n memset(&resolver, 0, sizeof(resolver));\n\n if (req->resolve_hostname)\n {\n struct addrinfo hints;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = PF_INET;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_protocol = IPPROTO_TCP;\n hints.ai_flags = 0;\n\n r = uv_getaddrinfo(m_uv_loop, &resolver, nullptr,\n req->addr.c_str(), req->port.c_str(),\n &hints);\n\n if (r<0)\n {\n \/\/ address resolution failed, to set an error on the promise\n std::ostringstream oss;\n oss << \"uv_getaddrinfo: \" << r << \", \" << safe_str(uv_err_name(r))\n << \", \" << safe_str(uv_strerror(r));\n req->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n return;\n }\n\n addrptr = resolver.addrinfo->ai_addr;\n }\n else\n {\n \/\/ use inet_pton functions\n uv_ip4_addr(req->addr.c_str(), atoi(req->port.c_str()), &inetaddr);\n addrptr = (const struct sockaddr*) &inetaddr;\n }\n\n std::unique_ptr connect_req ( new uv_connect_t() );\n connect_req->data = (void*) req.get();\n\n LOG_INFO(\"making new tcp connection to \" << req->addr.c_str() << \":\" << req->port);\n\n r = uv_tcp_connect(\n connect_req.get(),\n req->connector->get_handle(),\n addrptr,\n [](uv_connect_t* __req, int status)\n {\n std::unique_ptr connect_req(__req);\n IOLoop * ioloop = static_cast(__req->handle->loop->data);\n try\n {\n ioloop->on_tcp_connect_cb(__req, status);\n }\n catch (...){}\n });\n\n if (r == 0)\n {\n \/\/ resource ownership transfered to UV callback\n req.release();\n connect_req.release();\n }\n else\n {\n std::ostringstream oss;\n\n oss << \"uv_tcp_connect: \" << r << \", \" << safe_str(uv_err_name(r))\n << \", \" << safe_str(uv_strerror(r));\n req->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n }\n }\n else if (user_req->type == io_request::eAddServer)\n {\n create_tcp_server_socket(atoi(user_req->port.c_str()),\n user_req->on_accept,\n std::move(user_req->listener_err));\n }\n }\n\n}\n\n\nvoid IOLoop::async_send()\n{\n \/* ANY thread *\/\n\n \/\/ cause the IO thread to wake up\n uv_async_send( m_async.get() );\n}\n\nvoid IOLoop::run_loop()\n{\n LOG_INFO(\"IOLoop thread starting\");\n while ( true )\n {\n try\n {\n int r = uv_run(m_uv_loop, UV_RUN_DEFAULT);\n\n \/\/ if r == 0, there are no more handles; implies we are shutting down.\n if (r == 0) return;\n }\n catch(std::exception & e)\n {\n LOG_ERROR(\"exception in io_loop: \" << e.what());\n }\n catch(...)\n {\n LOG_ERROR(\"exception in io_loop: uknown\");\n }\n }\n}\n\nvoid IOLoop::start()\n{\n m_thread = std::thread(&IOLoop::run_loop, this);\n}\n\n\nvoid IOLoop::add_server(int port,\n std::promise listen_err,\n socket_accept_cb cb)\n{\n std::ostringstream oss;\n oss << port;\n\n std::unique_ptr r( new io_request( io_request::eAddServer,\n __logger,\n oss.str(),\n std::move(listen_err),\n std::move(cb) ) );\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n\n this->async_send();\n}\n\n\nvoid IOLoop::add_passive_handle(tcp_server* myserver, IOHandle* iohandle)\n{\n if (myserver->cb) myserver->cb(myserver->port, std::unique_ptr(iohandle));\n}\n\n\nstd::shared_ptr IOLoop::add_connection(std::string addr,\n std::string port,\n bool resolve_hostname)\n{\n \/\/ create the handle, need it here, so that the caller can later request\n \/\/ cancellation\n uv_tcp_t * tcp_handle = new uv_tcp_t();\n uv_tcp_init(m_uv_loop, tcp_handle);\n\n std::shared_ptr conn ( new io_connector(m_kernel, tcp_handle) );\n\n std::unique_ptr r( new io_request(io_request::eAddConnection, __logger ) );\n r->connector = conn;\n r->addr = addr;\n r->port = port;\n r->resolve_hostname = resolve_hostname;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n\n this->async_send();\n\n return conn;\n}\n\n\n\n\nvoid IOLoop::request_cancel(uv_tcp_t* h, uv_close_cb cb)\n{\n std::unique_ptr r( new io_request(io_request::eCancelHandle, __logger ) );\n\n r->tcp_handle = h;\n r->on_close_cb = cb;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n this->async_send();\n}\n\n\n\n} \/\/ namespace XXX\nremoved unused include#include \"IOLoop.h\"\n\n#include \"io_connector.h\"\n#include \"log_macros.h\"\n#include \"IOHandle.h\"\n#include \"kernel.h\"\n\n\n#include \n\n#include \n#include \n\n\n#define SYSTEM_HEARTBEAT_MS 10\n\nstatic const char* safe_str(const char* s)\n{\n return s? s : \"null\";\n}\n\nnamespace XXX {\n\nstruct io_request\n{\n enum request_type\n {\n eNone = 0,\n eCancelHandle,\n eAddServer,\n eAddConnection\n } type;\n\n logger & logptr;\n std::string addr;\n std::string port;\n bool resolve_hostname;\n std::unique_ptr< std::promise > listener_err;\n uv_tcp_t * tcp_handle = nullptr;\n uv_close_cb on_close_cb = nullptr;\n socket_accept_cb on_accept;\n\n std::shared_ptr connector;\n\n io_request(request_type __type,\n logger & __logger)\n : type(__type),\n logptr(__logger)\n {}\n\n io_request(request_type __type,\n logger & __logger,\n std::string port,\n std::promise p,\n socket_accept_cb );\n\n};\n\n\n\nvoid IOLoop::on_tcp_connect_cb(uv_connect_t* connect_req, int status)\n{\n \/* IO thread *\/\n\n std::unique_ptr ioreq ((io_request*) connect_req->data );\n\n if (status < 0)\n {\n std::ostringstream oss;\n oss << \"uv_connect: \" << status << \", \" << safe_str(uv_err_name(status))\n << \", \" << safe_str(uv_strerror(status));\n ioreq->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n }\n else\n {\n ioreq->connector->io_on_connect_success();\n }\n}\n\n\nstatic void __on_tcp_connect(uv_stream_t* server, int status)\n{\n \/\/ IOLoop has set itself as the uv_loop data member\n tcp_server* myserver = (tcp_server*) server;\n IOLoop * myIOLoop = static_cast(server->loop->data);\n\n logger & __logger = myIOLoop->get_logger();\n\n \/\/ TODO: review if this is correct error handling\n if (status < 0)\n {\n LOG_ERROR(\"New connection error \" << uv_strerror(status));\n return;\n }\n\n uv_tcp_t *client = new uv_tcp_t();\n uv_tcp_init(myIOLoop->uv_loop(), client);\n\n if (uv_accept(server, (uv_stream_t *) client) == 0)\n {\n IOHandle* ioh = new IOHandle( myIOLoop->get_kernel(),\n (uv_stream_t *) client, myIOLoop);\n\n int fd = client->io_watcher.fd;\n\n LOG_INFO(\"accept: type=\" << client->type\n << \", fd=\" << fd);\n\n \/\/ register the stream before beginning read operations\n myserver->ioloop->add_passive_handle(myserver, ioh );\n\n \/\/ \/\/ NOTE: registration of read event moved into the handle\n\n \/\/ \/\/ \/\/ new client is accepted, identified via its stream handle ... need to put\n \/\/ \/\/ \/\/ in place a lot more session tracking here.\n \/\/ \/\/ uv_read_start((uv_stream_t *) client, alloc_buffer, io_on_read);\n }\n else\n {\n uv_close((uv_handle_t *) client, NULL);\n }\n\n}\n\n\n\n\n\n\nio_request::io_request(request_type __type,\n logger & lp,\n std::string __port,\n std::promise listen_err,\n socket_accept_cb __on_accept)\n : type( __type),\n logptr( lp ),\n port( __port ),\n listener_err( new std::promise(std::move(listen_err) ) ),\n on_accept( std::move(__on_accept) )\n{\n}\n\n\nIOLoop::IOLoop(kernel& k)\n : m_kernel(k),\n __logger( k.get_logger() ),\n m_uv_loop( new uv_loop_t() ),\n\n m_async( new uv_async_t() ),\n m_pending_flags( eNone )\n{\n uv_loop_init(m_uv_loop);\n m_uv_loop->data = this;\n\n \/\/ set up the async handler\n uv_async_init(m_uv_loop, m_async.get(), [](uv_async_t* h) {\n IOLoop* p = static_cast( h->data );\n p->on_async();\n });\n m_async->data = this;\n\n \/\/ TODO: I prefer to not have to do this. Need to review what is the correct\n \/\/ policy for handling sigpipe using libuv.\n \/\/ signal(SIGPIPE, SIG_IGN);\n}\n\nvoid IOLoop::stop()\n{\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_flags |= eFinal;\n }\n async_send();\n if (m_thread.joinable()) m_thread.join();\n}\n\nIOLoop::~IOLoop()\n{\n \/\/ uv_loop kept as raw pointer, because need to pass to several uv functions\n uv_loop_close(m_uv_loop);\n delete m_uv_loop;\n}\n\nvoid IOLoop::create_tcp_server_socket(int port,\n socket_accept_cb cb,\n std::unique_ptr< std::promise > listener_err )\n{\n \/* UV Loop *\/\n\n \/\/ Create a tcp socket, and configure for listen\n tcp_server * myserver = new tcp_server();\n myserver->port = port;\n myserver->ioloop = this;\n myserver->cb = cb;\n\n uv_tcp_init(m_uv_loop, &myserver->uvh);\n\n struct sockaddr_in addr;\n uv_ip4_addr(\"0.0.0.0\", port, &addr);\n\n unsigned flags = 0;\n int r;\n\n r = uv_tcp_bind(&myserver->uvh, (const struct sockaddr*)&addr, flags);\n if (r == 0)\n r = uv_listen((uv_stream_t *) &myserver->uvh, 5, __on_tcp_connect);\n listener_err->set_value(std::abs(r));\n\n m_server_handles.push_back( std::unique_ptr(myserver) );\n}\n\n\nvoid IOLoop::on_async()\n{\n \/* IO thread *\/\n std::vector< std::unique_ptr > work;\n int pending_flags = eNone;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n work.swap( m_pending_requests );\n std::swap(pending_flags, m_pending_flags);\n }\n\n if (m_async_closed) return;\n\n if (pending_flags & eFinal)\n {\n for (auto & i : m_server_handles)\n uv_close((uv_handle_t*)i.get(), 0);\n\n uv_close((uv_handle_t*) m_async.get(), 0);\n\n m_async_closed = true;\n return;\n }\n\n for (auto & user_req : work)\n {\n if (user_req->type == io_request::eCancelHandle)\n {\n uv_close((uv_handle_t*) user_req->tcp_handle, user_req->on_close_cb);\n }\n else if (user_req->type == io_request::eAddConnection)\n {\n \/\/ create the request\n std::unique_ptr req( std::move(user_req) ); \/\/ <--- the sp is here now\n\n const struct sockaddr* addrptr;\n struct sockaddr_in inetaddr;\n memset(&inetaddr, 0, sizeof(inetaddr));\n\n int r = 0;\n uv_getaddrinfo_t resolver;\n memset(&resolver, 0, sizeof(resolver));\n\n if (req->resolve_hostname)\n {\n struct addrinfo hints;\n memset(&hints, 0, sizeof(hints));\n hints.ai_family = PF_INET;\n hints.ai_socktype = SOCK_STREAM;\n hints.ai_protocol = IPPROTO_TCP;\n hints.ai_flags = 0;\n\n r = uv_getaddrinfo(m_uv_loop, &resolver, nullptr,\n req->addr.c_str(), req->port.c_str(),\n &hints);\n\n if (r<0)\n {\n \/\/ address resolution failed, to set an error on the promise\n std::ostringstream oss;\n oss << \"uv_getaddrinfo: \" << r << \", \" << safe_str(uv_err_name(r))\n << \", \" << safe_str(uv_strerror(r));\n req->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n return;\n }\n\n addrptr = resolver.addrinfo->ai_addr;\n }\n else\n {\n \/\/ use inet_pton functions\n uv_ip4_addr(req->addr.c_str(), atoi(req->port.c_str()), &inetaddr);\n addrptr = (const struct sockaddr*) &inetaddr;\n }\n\n std::unique_ptr connect_req ( new uv_connect_t() );\n connect_req->data = (void*) req.get();\n\n LOG_INFO(\"making new tcp connection to \" << req->addr.c_str() << \":\" << req->port);\n\n r = uv_tcp_connect(\n connect_req.get(),\n req->connector->get_handle(),\n addrptr,\n [](uv_connect_t* __req, int status)\n {\n std::unique_ptr connect_req(__req);\n IOLoop * ioloop = static_cast(__req->handle->loop->data);\n try\n {\n ioloop->on_tcp_connect_cb(__req, status);\n }\n catch (...){}\n });\n\n if (r == 0)\n {\n \/\/ resource ownership transfered to UV callback\n req.release();\n connect_req.release();\n }\n else\n {\n std::ostringstream oss;\n\n oss << \"uv_tcp_connect: \" << r << \", \" << safe_str(uv_err_name(r))\n << \", \" << safe_str(uv_strerror(r));\n req->connector->io_on_connect_exception(\n std::make_exception_ptr( std::runtime_error(oss.str()) )\n );\n }\n }\n else if (user_req->type == io_request::eAddServer)\n {\n create_tcp_server_socket(atoi(user_req->port.c_str()),\n user_req->on_accept,\n std::move(user_req->listener_err));\n }\n }\n\n}\n\n\nvoid IOLoop::async_send()\n{\n \/* ANY thread *\/\n\n \/\/ cause the IO thread to wake up\n uv_async_send( m_async.get() );\n}\n\nvoid IOLoop::run_loop()\n{\n LOG_INFO(\"IOLoop thread starting\");\n while ( true )\n {\n try\n {\n int r = uv_run(m_uv_loop, UV_RUN_DEFAULT);\n\n \/\/ if r == 0, there are no more handles; implies we are shutting down.\n if (r == 0) return;\n }\n catch(std::exception & e)\n {\n LOG_ERROR(\"exception in io_loop: \" << e.what());\n }\n catch(...)\n {\n LOG_ERROR(\"exception in io_loop: uknown\");\n }\n }\n}\n\nvoid IOLoop::start()\n{\n m_thread = std::thread(&IOLoop::run_loop, this);\n}\n\n\nvoid IOLoop::add_server(int port,\n std::promise listen_err,\n socket_accept_cb cb)\n{\n std::ostringstream oss;\n oss << port;\n\n std::unique_ptr r( new io_request( io_request::eAddServer,\n __logger,\n oss.str(),\n std::move(listen_err),\n std::move(cb) ) );\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n\n this->async_send();\n}\n\n\nvoid IOLoop::add_passive_handle(tcp_server* myserver, IOHandle* iohandle)\n{\n if (myserver->cb) myserver->cb(myserver->port, std::unique_ptr(iohandle));\n}\n\n\nstd::shared_ptr IOLoop::add_connection(std::string addr,\n std::string port,\n bool resolve_hostname)\n{\n \/\/ create the handle, need it here, so that the caller can later request\n \/\/ cancellation\n uv_tcp_t * tcp_handle = new uv_tcp_t();\n uv_tcp_init(m_uv_loop, tcp_handle);\n\n std::shared_ptr conn ( new io_connector(m_kernel, tcp_handle) );\n\n std::unique_ptr r( new io_request(io_request::eAddConnection, __logger ) );\n r->connector = conn;\n r->addr = addr;\n r->port = port;\n r->resolve_hostname = resolve_hostname;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n\n this->async_send();\n\n return conn;\n}\n\n\n\n\nvoid IOLoop::request_cancel(uv_tcp_t* h, uv_close_cb cb)\n{\n std::unique_ptr r( new io_request(io_request::eCancelHandle, __logger ) );\n\n r->tcp_handle = h;\n r->on_close_cb = cb;\n\n {\n std::lock_guard< std::mutex > guard (m_pending_requests_lock);\n m_pending_requests.push_back( std::move(r) );\n }\n this->async_send();\n}\n\n\n\n} \/\/ namespace XXX\n<|endoftext|>"} {"text":"Fix ParaView restart mode on Windows<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Image.h\"\n\n#ifndef NDEBUG\n#define SIZECHECK(x, y) do { \\\n\t\tif((x) < 0 || (x) >= m_width) \\\n\t\t\tthrow std::out_of_range(\"sizecheck x\"); \\\n\t\tif((y) < 0 || (y) >= m_height) \\\n\t\t\tthrow std::out_of_range(\"sizecheck y\"); \\\n\t} while(0)\n#else\n#define SIZECHECK(x, y) do {} while(0)\n#endif\n\n\/\/ ARGB but with inverted alpha\n\nstatic inline int color2int(Color c)\n{\n\tu8 a = 255 - c.a;\n\treturn (a << 24) | (c.r << 16) | (c.g << 8) | c.b;\n}\n\nstatic inline Color int2color(int c)\n{\n\tColor c2;\n\tu8 a;\n\tc2.b = c & 0xff;\n\tc2.g = (c >> 8) & 0xff;\n\tc2.r = (c >> 16) & 0xff;\n\ta = (c >> 24) & 0xff;\n\tc2.a = 255 - a;\n\treturn c2;\n}\n\n\nImage::Image(int width, int height) :\n\tm_width(width), m_height(height), m_image(NULL)\n{\n\tm_image = gdImageCreateTrueColor(m_width, m_height);\n}\n\nImage::~Image()\n{\n\tgdImageDestroy(m_image);\n}\n\nvoid Image::setPixel(int x, int y, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tm_image->tpixels[y][x] = color2int(c);\n}\n\nColor Image::getPixel(int x, int y)\n{\n#ifndef NDEBUG\n\tif(x < 0 || x > m_width || y < 0 || y > m_height)\n\t\tthrow std::out_of_range(\"sizecheck\");\n#endif\n\treturn int2color(m_image->tpixels[y][x]);\n}\n\nvoid Image::drawLine(int x1, int y1, int x2, int y2, const Color &c)\n{\n\tSIZECHECK(x1, y1);\n\tSIZECHECK(x2, y2);\n\tgdImageLine(m_image, x1, y1, x2, y2, color2int(c));\n}\n\nvoid Image::drawText(int x, int y, const std::string &s, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tgdImageString(m_image, gdFontGetMediumBold(), x, y, (unsigned char*) s.c_str(), color2int(c));\n}\n\nvoid Image::drawFilledRect(int x, int y, int w, int h, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tSIZECHECK(x + w - 1, y + h - 1);\n\tgdImageFilledRectangle(m_image, x, y, x + w - 1, y + h - 1, color2int(c));\n}\n\nvoid Image::drawCircle(int x, int y, int diameter, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tgdImageArc(m_image, x, y, diameter, diameter, 0, 360, color2int(c));\n}\n\nvoid Image::save(const std::string &filename)\n{\n\tFILE *f = fopen(filename.c_str(), \"wb\");\n\tif(!f) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Error writing image file: \" << std::strerror(errno);\n\t\tthrow std::runtime_error(oss.str());\n\t}\n\tgdImagePng(m_image, f); \/\/ other formats?\n\tfclose(f);\n}\nImprove exception messages for out-of-bounds image access#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"Image.h\"\n\n#ifndef NDEBUG\n#define SIZECHECK(x, y) check_bounds((x), (y), m_width, m_height)\n#else\n#define SIZECHECK(x, y) do {} while(0)\n#endif\n\n\/\/ ARGB but with inverted alpha\n\nstatic inline int color2int(Color c)\n{\n\tu8 a = 255 - c.a;\n\treturn (a << 24) | (c.r << 16) | (c.g << 8) | c.b;\n}\n\nstatic inline Color int2color(int c)\n{\n\tColor c2;\n\tu8 a;\n\tc2.b = c & 0xff;\n\tc2.g = (c >> 8) & 0xff;\n\tc2.r = (c >> 16) & 0xff;\n\ta = (c >> 24) & 0xff;\n\tc2.a = 255 - a;\n\treturn c2;\n}\n\nstatic inline void check_bounds(int x, int y, int width, int height)\n{\n\tif(x < 0 || x >= width) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Access outside image bounds (x), 0 < \"\n\t\t\t<< x << \" < \" << width << \" is false.\";\n\t\tthrow std::out_of_range(oss.str());\n\t}\n\tif(y < 0 || y >= height) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Access outside image bounds (y), 0 < \"\n\t\t\t<< y << \" < \" << height << \" is false.\";\n\t\tthrow std::out_of_range(oss.str());\n\t}\n}\n\n\nImage::Image(int width, int height) :\n\tm_width(width), m_height(height), m_image(NULL)\n{\n\tm_image = gdImageCreateTrueColor(m_width, m_height);\n}\n\nImage::~Image()\n{\n\tgdImageDestroy(m_image);\n}\n\nvoid Image::setPixel(int x, int y, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tm_image->tpixels[y][x] = color2int(c);\n}\n\nColor Image::getPixel(int x, int y)\n{\n\tSIZECHECK(x, y);\n\treturn int2color(m_image->tpixels[y][x]);\n}\n\nvoid Image::drawLine(int x1, int y1, int x2, int y2, const Color &c)\n{\n\tSIZECHECK(x1, y1);\n\tSIZECHECK(x2, y2);\n\tgdImageLine(m_image, x1, y1, x2, y2, color2int(c));\n}\n\nvoid Image::drawText(int x, int y, const std::string &s, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tgdImageString(m_image, gdFontGetMediumBold(), x, y, (unsigned char*) s.c_str(), color2int(c));\n}\n\nvoid Image::drawFilledRect(int x, int y, int w, int h, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tSIZECHECK(x + w - 1, y + h - 1);\n\tgdImageFilledRectangle(m_image, x, y, x + w - 1, y + h - 1, color2int(c));\n}\n\nvoid Image::drawCircle(int x, int y, int diameter, const Color &c)\n{\n\tSIZECHECK(x, y);\n\tgdImageArc(m_image, x, y, diameter, diameter, 0, 360, color2int(c));\n}\n\nvoid Image::save(const std::string &filename)\n{\n\tFILE *f = fopen(filename.c_str(), \"wb\");\n\tif(!f) {\n\t\tstd::ostringstream oss;\n\t\toss << \"Error writing image file: \" << std::strerror(errno);\n\t\tthrow std::runtime_error(oss.str());\n\t}\n\tgdImagePng(m_image, f); \/\/ other formats?\n\tfclose(f);\n}\n<|endoftext|>"} {"text":"added more debug output in relation to block actions<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SimpleTest.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace cms;\nusing namespace activemq;\nusing namespace activemq::test;\nusing namespace activemq::util;\nusing namespace activemq::exceptions;\nusing namespace decaf;\nusing namespace decaf::lang;\nusing namespace decaf::util;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testAutoAck() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr bytesMessage( session->createBytesMessage() );\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( txtMessage.get() );\n }\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( bytesMessage.get() );\n }\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testClientAck() {\n\n try {\n\n cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );\n cmsProvider->reconnectSession();\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr bytesMessage( session->createBytesMessage() );\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( txtMessage.get() );\n }\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( bytesMessage.get() );\n }\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerWithNullDestination() {\n\n try{\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getNoDestProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n producer->send( cmsProvider->getDestination(), txtMessage.get() );\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( 1 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == 1 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerSendWithNullDestination() {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an InvalidDestinationException\",\n producer->send( NULL, txtMessage.get() ),\n cms::InvalidDestinationException );\n\n producer = cmsProvider->getNoDestProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an UnsupportedOperationException\",\n producer->send( NULL, txtMessage.get() ),\n cms::UnsupportedOperationException );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerSendToNonDefaultDestination() {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr destination( session->createTemporaryTopic() );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an UnsupportedOperationException\",\n producer->send( destination.get(), txtMessage.get() ),\n cms::UnsupportedOperationException );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testSyncReceive() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n \/\/ Send some text messages\n producer->send( txtMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testSyncReceiveClientAck() {\n\n try {\n\n cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );\n cmsProvider->reconnectSession();\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n \/\/ Send some text messages\n producer->send( txtMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testMultipleConnections() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::ConnectionFactory* factory = cmsProvider->getConnectionFactory();\n auto_ptr connection1( factory->createConnection() );\n connection1->start();\n\n auto_ptr connection2( factory->createConnection() );\n connection2->start();\n\n CPPUNIT_ASSERT( connection1->getClientID() != connection2->getClientID() );\n\n auto_ptr session1( connection1->createSession() );\n auto_ptr session2( connection1->createSession() );\n\n auto_ptr topic( session1->createTopic( UUID::randomUUID().toString() ) );\n\n auto_ptr consumer1( session1->createConsumer( topic.get() ) );\n auto_ptr consumer2( session2->createConsumer( topic.get() ) );\n\n auto_ptr producer( session2->createProducer( topic.get() ) );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr textMessage( session2->createTextMessage() );\n\n \/\/ Send some text messages\n producer->send( textMessage.get() );\n\n auto_ptr message( consumer1->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n message.reset( consumer2->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer1->close();\n consumer2->close();\n producer->close();\n session1->close();\n session2->close();\n\n this->cmsProvider->destroyDestination( topic.get() );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testMultipleSessions() {\n try {\n\n \/\/ Create CMS Object for Comms\n auto_ptr session1( cmsProvider->getConnection()->createSession() );\n auto_ptr session2( cmsProvider->getConnection()->createSession() );\n\n auto_ptr topic( session1->createTopic( UUID::randomUUID().toString() ) );\n\n auto_ptr consumer1( session1->createConsumer( topic.get() ) );\n auto_ptr consumer2( session2->createConsumer( topic.get() ) );\n\n auto_ptr producer( session2->createProducer( topic.get() ) );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr textMessage( session2->createTextMessage() );\n\n \/\/ Send some text messages\n producer->send( textMessage.get() );\n\n auto_ptr message( consumer1->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n message.reset( consumer2->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer1->close();\n consumer2->close();\n producer->close();\n session1->close();\n session2->close();\n\n this->cmsProvider->destroyDestination( topic.get() );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testReceiveAlreadyInQueue() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::ConnectionFactory* factory = cmsProvider->getConnectionFactory();\n auto_ptr connection( factory->createConnection() );\n\n auto_ptr session( connection->createSession() );\n auto_ptr topic( session->createTopic( UUID::randomUUID().toString() ) );\n auto_ptr consumer( session->createConsumer( topic.get() ) );\n auto_ptr producer( session->createProducer( topic.get() ) );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n auto_ptr textMessage( session->createTextMessage() );\n\n \/\/ Send some text messages\n producer->send( textMessage.get() );\n\n Thread::sleep( 250 );\n\n connection->start();\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer->close();\n producer->close();\n session->close();\n\n this->cmsProvider->destroyDestination( topic.get() );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testQuickCreateAndDestroy() {\n\n try{\n\n cms::ConnectionFactory* factory = cmsProvider->getConnectionFactory();\n auto_ptr connection( factory->createConnection() );\n auto_ptr session( connection->createSession() );\n\n session.reset( NULL );\n connection.reset( NULL );\n\n connection.reset( factory->createConnection() );\n session.reset( connection->createSession() );\n connection->start();\n\n session.reset( NULL );\n connection.reset( NULL );\n\n for( int i = 0; i < 50; ++i ) {\n CMSProvider lcmsProvider( this->getBrokerURL() );\n lcmsProvider.getSession();\n lcmsProvider.getConsumer();\n lcmsProvider.getProducer();\n }\n\n } catch ( CMSException& e ) {\n e.printStackTrace();\n CPPUNIT_ASSERT( false );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testBytesMessageSendRecv() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr bytesMessage( session->createBytesMessage() );\n\n bytesMessage->writeBoolean( true );\n bytesMessage->writeByte( 127 );\n bytesMessage->writeDouble( 123456.789 );\n bytesMessage->writeInt( 65537 );\n bytesMessage->writeString( \"TEST-STRING\" );\n\n \/\/ Send some text messages\n producer->send( bytesMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should throw an ActiveMQExceptio\",\n message->setStringProperty( \"FOO\", \"BAR\" ),\n cms::CMSException );\n\n BytesMessage* bytesMessage2 = dynamic_cast( message.get() );\n CPPUNIT_ASSERT( bytesMessage2 != NULL );\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should throw an ActiveMQExceptio\",\n bytesMessage2->writeBoolean( false ),\n cms::CMSException );\n\n CPPUNIT_ASSERT( bytesMessage2->readBoolean() == true );\n CPPUNIT_ASSERT( bytesMessage2->readByte() == 127 );\n CPPUNIT_ASSERT( bytesMessage2->readDouble() == 123456.789 );\n CPPUNIT_ASSERT( bytesMessage2->readInt() == 65537 );\n CPPUNIT_ASSERT( bytesMessage2->readString() == \"TEST-STRING\" );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testLibraryInitShutdownInit() {\n\n {\n this->tearDown();\n\n \/\/ Shutdown the ActiveMQ library\n CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::shutdownLibrary() );\n }\n\n {\n \/\/ Initialize the ActiveMQ library\n CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::initializeLibrary() );\n\n cmsProvider.reset( new util::CMSProvider( getBrokerURL() ) );\n }\n}\nFix test failures\/*\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed with\n * this work for additional information regarding copyright ownership.\n * The ASF licenses this file to You under the Apache License, Version 2.0\n * (the \"License\"); you may not use this file except in compliance with\n * the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"SimpleTest.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace std;\nusing namespace cms;\nusing namespace activemq;\nusing namespace activemq::core;\nusing namespace activemq::test;\nusing namespace activemq::util;\nusing namespace activemq::exceptions;\nusing namespace decaf;\nusing namespace decaf::lang;\nusing namespace decaf::util;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testAutoAck() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr bytesMessage( session->createBytesMessage() );\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( txtMessage.get() );\n }\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( bytesMessage.get() );\n }\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testClientAck() {\n\n try {\n\n cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );\n cmsProvider->reconnectSession();\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr bytesMessage( session->createBytesMessage() );\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( txtMessage.get() );\n }\n\n for( unsigned int i = 0; i < IntegrationCommon::defaultMsgCount; ++i ) {\n producer->send( bytesMessage.get() );\n }\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( IntegrationCommon::defaultMsgCount * 2 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == IntegrationCommon::defaultMsgCount * 2 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerWithNullDestination() {\n\n try{\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n consumer->setMessageListener( &listener );\n cms::MessageProducer* producer = cmsProvider->getNoDestProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n producer->send( cmsProvider->getDestination(), txtMessage.get() );\n\n \/\/ Wait for the messages to get here\n listener.asyncWaitForMessages( 1 );\n\n unsigned int numReceived = listener.getNumReceived();\n CPPUNIT_ASSERT( numReceived == 1 );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerSendWithNullDestination() {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an InvalidDestinationException\",\n producer->send( NULL, txtMessage.get() ),\n cms::InvalidDestinationException );\n\n producer = cmsProvider->getNoDestProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an UnsupportedOperationException\",\n producer->send( NULL, txtMessage.get() ),\n cms::UnsupportedOperationException );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testProducerSendToNonDefaultDestination() {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n\n CMSListener listener( session );\n\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n auto_ptr destination( session->createTemporaryTopic() );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should Throw an UnsupportedOperationException\",\n producer->send( destination.get(), txtMessage.get() ),\n cms::UnsupportedOperationException );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testSyncReceive() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n \/\/ Send some text messages\n producer->send( txtMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testSyncReceiveClientAck() {\n\n try {\n\n cmsProvider->setAckMode( cms::Session::CLIENT_ACKNOWLEDGE );\n cmsProvider->reconnectSession();\n\n \/\/ Create CMS Object for Comms\n cms::Session* session( cmsProvider->getSession() );\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr txtMessage( session->createTextMessage( \"TEST MESSAGE\" ) );\n\n \/\/ Send some text messages\n producer->send( txtMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testMultipleConnections() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n auto_ptr factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));\n auto_ptr connection1( factory->createConnection() );\n connection1->start();\n\n auto_ptr connection2( factory->createConnection() );\n connection2->start();\n\n CPPUNIT_ASSERT( connection1->getClientID() != connection2->getClientID() );\n\n auto_ptr session1( connection1->createSession() );\n auto_ptr session2( connection1->createSession() );\n\n auto_ptr topic( session1->createTopic( UUID::randomUUID().toString() ) );\n\n auto_ptr consumer1( session1->createConsumer( topic.get() ) );\n auto_ptr consumer2( session2->createConsumer( topic.get() ) );\n\n auto_ptr producer( session2->createProducer( topic.get() ) );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr textMessage( session2->createTextMessage() );\n\n \/\/ Send some text messages\n producer->send( textMessage.get() );\n\n auto_ptr message( consumer1->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n message.reset( consumer2->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer1->close();\n consumer2->close();\n producer->close();\n session1->close();\n session2->close();\n\n this->cmsProvider->destroyDestination( topic.get() );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testMultipleSessions() {\n try {\n\n \/\/ Create CMS Object for Comms\n auto_ptr session1( cmsProvider->getConnection()->createSession() );\n auto_ptr session2( cmsProvider->getConnection()->createSession() );\n\n auto_ptr topic( session1->createTopic( UUID::randomUUID().toString() ) );\n\n auto_ptr consumer1( session1->createConsumer( topic.get() ) );\n auto_ptr consumer2( session2->createConsumer( topic.get() ) );\n\n auto_ptr producer( session2->createProducer( topic.get() ) );\n producer->setDeliveryMode( DeliveryMode::NON_PERSISTENT );\n\n auto_ptr textMessage( session2->createTextMessage() );\n\n \/\/ Send some text messages\n producer->send( textMessage.get() );\n\n auto_ptr message( consumer1->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n message.reset( consumer2->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer1->close();\n consumer2->close();\n producer->close();\n session1->close();\n session2->close();\n\n this->cmsProvider->destroyDestination( topic.get() );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testReceiveAlreadyInQueue() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n auto_ptr factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));\n auto_ptr connection(factory->createConnection());\n\n auto_ptr session(connection->createSession());\n auto_ptr topic(session->createTopic(UUID::randomUUID().toString()));\n auto_ptr consumer(session->createConsumer(topic.get()));\n auto_ptr producer(session->createProducer(topic.get()));\n producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);\n auto_ptr textMessage(session->createTextMessage());\n\n \/\/ Send some text messages\n producer->send(textMessage.get());\n\n Thread::sleep(250);\n\n connection->start();\n\n auto_ptr message(consumer->receive(2000));\n CPPUNIT_ASSERT( message.get() != NULL );\n\n \/\/ Clean up if we can\n consumer->close();\n producer->close();\n session->close();\n\n this->cmsProvider->destroyDestination(topic.get());\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testQuickCreateAndDestroy() {\n\n try{\n\n auto_ptr factory(new ActiveMQConnectionFactory(cmsProvider->getBrokerURL()));\n auto_ptr connection( factory->createConnection() );\n auto_ptr session( connection->createSession() );\n\n session.reset( NULL );\n connection.reset( NULL );\n\n connection.reset( factory->createConnection() );\n session.reset( connection->createSession() );\n connection->start();\n\n session.reset( NULL );\n connection.reset( NULL );\n\n for( int i = 0; i < 50; ++i ) {\n CMSProvider lcmsProvider( this->getBrokerURL() );\n lcmsProvider.getSession();\n lcmsProvider.getConsumer();\n lcmsProvider.getProducer();\n }\n\n } catch ( CMSException& e ) {\n e.printStackTrace();\n CPPUNIT_ASSERT( false );\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testBytesMessageSendRecv() {\n\n try {\n\n \/\/ Create CMS Object for Comms\n cms::Session* session(cmsProvider->getSession());\n cms::MessageConsumer* consumer = cmsProvider->getConsumer();\n cms::MessageProducer* producer = cmsProvider->getProducer();\n producer->setDeliveryMode(DeliveryMode::NON_PERSISTENT);\n\n auto_ptr bytesMessage(session->createBytesMessage());\n\n bytesMessage->writeBoolean(true);\n bytesMessage->writeByte(127);\n bytesMessage->writeDouble(123456.789);\n bytesMessage->writeInt(65537);\n bytesMessage->writeString(\"TEST-STRING\");\n\n \/\/ Send some text messages\n producer->send( bytesMessage.get() );\n\n auto_ptr message( consumer->receive( 2000 ) );\n CPPUNIT_ASSERT( message.get() != NULL );\n\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should throw an ActiveMQExceptio\",\n message->setStringProperty( \"FOO\", \"BAR\" ),\n cms::CMSException );\n\n BytesMessage* bytesMessage2 = dynamic_cast( message.get() );\n CPPUNIT_ASSERT( bytesMessage2 != NULL );\n CPPUNIT_ASSERT_THROW_MESSAGE(\n \"Should throw an ActiveMQExceptio\",\n bytesMessage2->writeBoolean( false ),\n cms::CMSException );\n\n CPPUNIT_ASSERT( bytesMessage2->readBoolean() == true );\n CPPUNIT_ASSERT( bytesMessage2->readByte() == 127 );\n CPPUNIT_ASSERT( bytesMessage2->readDouble() == 123456.789 );\n CPPUNIT_ASSERT( bytesMessage2->readInt() == 65537 );\n CPPUNIT_ASSERT( bytesMessage2->readString() == \"TEST-STRING\" );\n }\n AMQ_CATCH_RETHROW( ActiveMQException )\n AMQ_CATCHALL_THROW( ActiveMQException )\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid SimpleTest::testLibraryInitShutdownInit() {\n\n {\n this->tearDown();\n \/\/ Shutdown the ActiveMQ library\n CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::shutdownLibrary() );\n }\n {\n \/\/ Initialize the ActiveMQ library\n CPPUNIT_ASSERT_NO_THROW( activemq::library::ActiveMQCPP::initializeLibrary() );\n cmsProvider.reset(new util::CMSProvider(getBrokerURL()));\n }\n}\n<|endoftext|>"} {"text":"#if !defined(__CINT__) || defined(__MAKECINT__)\n#include \n#include \n#include \"AliAnalysisManager.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliAODHandler.h\"\n#include \"AliAnalysisTaskESDfilter.h\"\n#include \"AliAnalysisDataContainer.h\"\n#endif\n\nvoid CreateAODfromESD(const char *inFileName = \"AliESDs.root\",\n\t\t const char *outFileName = \"AliAODs.root\",\n\t\t Bool_t bKineFilter = kTRUE) \n{\n \n gSystem->Load(\"libTree\");\n gSystem->Load(\"libGeom\");\n gSystem->Load(\"libPhysics\");\n gSystem->Load(\"libVMC\");\n gSystem->Load(\"libSTEERBase\");\n gSystem->Load(\"libESD\");\n gSystem->Load(\"libAOD\");\n \n gSystem->Load(\"libANALYSIS\");\n gSystem->Load(\"libANALYSISalice\");\n gSystem->Load(\"libPWG3muon\");\n\n TChain *chain = new TChain(\"esdTree\");\n \/\/ Steering input chain\n chain->Add(inFileName);\n AliAnalysisManager *mgr = new AliAnalysisManager(\"ESD to AOD\", \"Analysis Manager\");\n\n \/\/ Input\n AliESDInputHandler* inpHandler = new AliESDInputHandler();\n inpHandler->SetReadTags();\n mgr->SetInputEventHandler (inpHandler);\n \/\/ Output\n AliAODHandler* aodHandler = new AliAODHandler();\n aodHandler->SetOutputFileName(outFileName);\n mgr->SetOutputEventHandler(aodHandler);\n\n \/\/ MC Truth\n if(bKineFilter){\n\tAliMCEventHandler* mcHandler = new AliMCEventHandler();\n\tmgr->SetMCtruthEventHandler(mcHandler);\n }\n\n\n \/\/ Tasks\n \/\/ Filtering of MC particles (decays conversions etc)\n \/\/ this task is also needed to set the MCEventHandler\n \/\/ to the AODHandler, this will not be needed when\n \/\/ AODHandler goes to ANALYSISalice\n AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter(\"Particle Filter\");\n if (bKineFilter) mgr->AddTask(kinefilter);\n \n \/\/ Barrel Tracks\n AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter(\"Filter\");\n mgr->AddTask(filter);\n \/\/ Muons\n AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter(\"ESD Muon Filter\");\n mgr->AddTask(esdmuonfilter);\n\n \/\/ Cuts on primary tracks\n AliESDtrackCuts* esdTrackCutsL = new AliESDtrackCuts(\"AliESDtrackCuts\", \"Standard\");\n esdTrackCutsL->SetMinNClustersTPC(50);\n esdTrackCutsL->SetMaxChi2PerClusterTPC(3.5);\n esdTrackCutsL->SetMaxCovDiagonalElements(2, 2, 0.5, 0.5, 2);\n esdTrackCutsL->SetRequireTPCRefit(kTRUE);\n esdTrackCutsL->SetMaxDCAToVertexXY(3.0);\n esdTrackCutsL->SetMaxDCAToVertexZ(3.0);\n esdTrackCutsL->SetDCAToVertex2D(kTRUE);\n esdTrackCutsL->SetRequireSigmaToVertex(kFALSE);\n esdTrackCutsL->SetAcceptKinkDaughters(kFALSE);\n \/\/ ITS stand-alone tracks\n AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts(\"AliESDtrackCuts\", \"ITS stand-alone\");\n esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);\n\n AliAnalysisFilter* trackFilter = new AliAnalysisFilter(\"trackFilter\");\n trackFilter->AddCuts(esdTrackCutsL);\n trackFilter->AddCuts(esdTrackCutsITSsa);\n\n \/\/ Cuts on V0s\n AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts(\"AliESDv0Cuts\", \"Standard pp\");\n esdV0Cuts->SetMinRadius(0.2);\n esdV0Cuts->SetMaxRadius(200);\n esdV0Cuts->SetMinDcaPosToVertex(0.05);\n esdV0Cuts->SetMinDcaNegToVertex(0.05);\n esdV0Cuts->SetMaxDcaV0Daughters(1.0);\n esdV0Cuts->SetMinCosinePointingAngle(0.99);\n AliAnalysisFilter* v0Filter = new AliAnalysisFilter(\"v0Filter\");\n v0Filter->AddCuts(esdV0Cuts);\n\n\n\/\/\n filter->SetTrackFilter(trackFilter);\n filter->SetV0Filter(v0Filter);\n\n\n\/\/ Create AOD Tags\n AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator(\"AOD Tag Creator\");\n mgr->AddTask(tagTask);\n\n \/\/ Pipelining\n AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); \n AliAnalysisDataContainer *coutput1 = mgr->GetCommonOutputContainer();\n \n \n AliAnalysisDataContainer *coutputT\n\t= mgr->CreateContainer(\"cTag\", TTree::Class(), AliAnalysisManager::kOutputContainer, \"AOD.tag.root\");\n\n coutput1->SetSpecialOutput();\n coutputT->SetSpecialOutput();\n \n if(bKineFilter) {\n\tmgr->ConnectInput (kinefilter, 0, cinput1 );\n\tmgr->ConnectOutput (kinefilter, 0, coutput1 );\n }\n\n mgr->ConnectInput (filter, 0, cinput1 );\n mgr->ConnectOutput(filter, 0, coutput1);\n\n mgr->ConnectInput (esdmuonfilter, 0, cinput1 );\n\/\/ mgr->ConnectOutput(esdmuonfilter, 0, coutput1);\n\n mgr->ConnectInput (tagTask, 0, cinput1);\n mgr->ConnectOutput(tagTask, 1, coutputT);\n\n \/\/\n \/\/ Run the analysis\n \/\/\n mgr->InitAnalysis();\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\", chain);\n}\n\nlibPWG3muon needs libCORRFW#if !defined(__CINT__) || defined(__MAKECINT__)\n#include \n#include \n#include \"AliAnalysisManager.h\"\n#include \"AliESDInputHandler.h\"\n#include \"AliAODHandler.h\"\n#include \"AliAnalysisTaskESDfilter.h\"\n#include \"AliAnalysisDataContainer.h\"\n#endif\n\nvoid CreateAODfromESD(const char *inFileName = \"AliESDs.root\",\n\t\t const char *outFileName = \"AliAODs.root\",\n\t\t Bool_t bKineFilter = kTRUE) \n{\n \n gSystem->Load(\"libTree\");\n gSystem->Load(\"libGeom\");\n gSystem->Load(\"libPhysics\");\n gSystem->Load(\"libVMC\");\n gSystem->Load(\"libSTEERBase\");\n gSystem->Load(\"libESD\");\n gSystem->Load(\"libAOD\");\n \n gSystem->Load(\"libANALYSIS\");\n gSystem->Load(\"libANALYSISalice\");\n gSystem->Load(\"libCORRFW\");\n gSystem->Load(\"libPWG3muon\");\n\n TChain *chain = new TChain(\"esdTree\");\n \/\/ Steering input chain\n chain->Add(inFileName);\n AliAnalysisManager *mgr = new AliAnalysisManager(\"ESD to AOD\", \"Analysis Manager\");\n\n \/\/ Input\n AliESDInputHandler* inpHandler = new AliESDInputHandler();\n inpHandler->SetReadTags();\n mgr->SetInputEventHandler (inpHandler);\n \/\/ Output\n AliAODHandler* aodHandler = new AliAODHandler();\n aodHandler->SetOutputFileName(outFileName);\n mgr->SetOutputEventHandler(aodHandler);\n\n \/\/ MC Truth\n if(bKineFilter){\n\tAliMCEventHandler* mcHandler = new AliMCEventHandler();\n\tmgr->SetMCtruthEventHandler(mcHandler);\n }\n\n\n \/\/ Tasks\n \/\/ Filtering of MC particles (decays conversions etc)\n \/\/ this task is also needed to set the MCEventHandler\n \/\/ to the AODHandler, this will not be needed when\n \/\/ AODHandler goes to ANALYSISalice\n AliAnalysisTaskMCParticleFilter *kinefilter = new AliAnalysisTaskMCParticleFilter(\"Particle Filter\");\n if (bKineFilter) mgr->AddTask(kinefilter);\n \n \/\/ Barrel Tracks\n AliAnalysisTaskESDfilter *filter = new AliAnalysisTaskESDfilter(\"Filter\");\n mgr->AddTask(filter);\n \/\/ Muons\n AliAnalysisTaskESDMuonFilter *esdmuonfilter = new AliAnalysisTaskESDMuonFilter(\"ESD Muon Filter\");\n mgr->AddTask(esdmuonfilter);\n\n \/\/ Cuts on primary tracks\n AliESDtrackCuts* esdTrackCutsL = new AliESDtrackCuts(\"AliESDtrackCuts\", \"Standard\");\n esdTrackCutsL->SetMinNClustersTPC(50);\n esdTrackCutsL->SetMaxChi2PerClusterTPC(3.5);\n esdTrackCutsL->SetMaxCovDiagonalElements(2, 2, 0.5, 0.5, 2);\n esdTrackCutsL->SetRequireTPCRefit(kTRUE);\n esdTrackCutsL->SetMaxDCAToVertexXY(3.0);\n esdTrackCutsL->SetMaxDCAToVertexZ(3.0);\n esdTrackCutsL->SetDCAToVertex2D(kTRUE);\n esdTrackCutsL->SetRequireSigmaToVertex(kFALSE);\n esdTrackCutsL->SetAcceptKinkDaughters(kFALSE);\n \/\/ ITS stand-alone tracks\n AliESDtrackCuts* esdTrackCutsITSsa = new AliESDtrackCuts(\"AliESDtrackCuts\", \"ITS stand-alone\");\n esdTrackCutsITSsa->SetRequireITSStandAlone(kTRUE);\n\n AliAnalysisFilter* trackFilter = new AliAnalysisFilter(\"trackFilter\");\n trackFilter->AddCuts(esdTrackCutsL);\n trackFilter->AddCuts(esdTrackCutsITSsa);\n\n \/\/ Cuts on V0s\n AliESDv0Cuts* esdV0Cuts = new AliESDv0Cuts(\"AliESDv0Cuts\", \"Standard pp\");\n esdV0Cuts->SetMinRadius(0.2);\n esdV0Cuts->SetMaxRadius(200);\n esdV0Cuts->SetMinDcaPosToVertex(0.05);\n esdV0Cuts->SetMinDcaNegToVertex(0.05);\n esdV0Cuts->SetMaxDcaV0Daughters(1.0);\n esdV0Cuts->SetMinCosinePointingAngle(0.99);\n AliAnalysisFilter* v0Filter = new AliAnalysisFilter(\"v0Filter\");\n v0Filter->AddCuts(esdV0Cuts);\n\n\n\/\/\n filter->SetTrackFilter(trackFilter);\n filter->SetV0Filter(v0Filter);\n\n\n\/\/ Create AOD Tags\n AliAnalysisTaskTagCreator* tagTask = new AliAnalysisTaskTagCreator(\"AOD Tag Creator\");\n mgr->AddTask(tagTask);\n\n \/\/ Pipelining\n AliAnalysisDataContainer *cinput1 = mgr->GetCommonInputContainer(); \n AliAnalysisDataContainer *coutput1 = mgr->GetCommonOutputContainer();\n \n \n AliAnalysisDataContainer *coutputT\n\t= mgr->CreateContainer(\"cTag\", TTree::Class(), AliAnalysisManager::kOutputContainer, \"AOD.tag.root\");\n\n coutput1->SetSpecialOutput();\n coutputT->SetSpecialOutput();\n \n if(bKineFilter) {\n\tmgr->ConnectInput (kinefilter, 0, cinput1 );\n\tmgr->ConnectOutput (kinefilter, 0, coutput1 );\n }\n\n mgr->ConnectInput (filter, 0, cinput1 );\n mgr->ConnectOutput(filter, 0, coutput1);\n\n mgr->ConnectInput (esdmuonfilter, 0, cinput1 );\n\/\/ mgr->ConnectOutput(esdmuonfilter, 0, coutput1);\n\n mgr->ConnectInput (tagTask, 0, cinput1);\n mgr->ConnectOutput(tagTask, 1, coutputT);\n\n \/\/\n \/\/ Run the analysis\n \/\/\n mgr->InitAnalysis();\n mgr->PrintStatus();\n mgr->StartAnalysis(\"local\", chain);\n}\n\n<|endoftext|>"} {"text":"Limit helix DCA phase*r search to 100cm,<|endoftext|>"} {"text":"\/*===- ShieldedCoulombForce.cpp - libSimulation -===============================\n*\n* DEMON\n*\n* This file is distributed under the BSD Open Source License. See LICENSE.TXT \n* for details. \n*\n*===-----------------------------------------------------------------------===*\/\n\n#include \"ShieldedCoulombForce.h\"\n#include \n\nconst double ShieldedCoulombForce::coulomb = 1.0\/(4.0*M_PI*8.85E-12);\n\nShieldedCoulombForce::ShieldedCoulombForce(Cloud * const myCloud, const double shieldingConstant)\n: Force(myCloud), shielding(shieldingConstant) {}\n\nvoid ShieldedCoulombForce::force1(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx1_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety1_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq1_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq1_pd(i), vx1 - cloud->getx1_pd(i), vy1 - cloud->gety1_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq1r_pd(i), vx1 - cloud->getx1r_pd(i), vy1 - cloud->gety1r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force2(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx2_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety2_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq2_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq2_pd(i), vx1 - cloud->getx2_pd(i), vy1 - cloud->gety2_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq2r_pd(i), vx1 - cloud->getx2r_pd(i), vy1 - cloud->gety2r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force3(const double currentTime)\n{\n for (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx3_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety3_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq3_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq3_pd(i), vx1 - cloud->getx3_pd(i), vy1 - cloud->gety3_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq3r_pd(i), vx1 - cloud->getx3r_pd(i), vy1 - cloud->gety3r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force4(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx4_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety4_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq4_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq4_pd(i), vx1 - cloud->getx4_pd(i), vy1 - cloud->gety4_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq4r_pd(i), vx1 - cloud->getx4r_pd(i), vy1 - cloud->gety4r_pd(i));\n\t\t}\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const cloud_index currentParticle, const cloud_index iParticle, \n const double currentCharge, const double iCharge,\n const double displacementX, const double displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst double displacement = sqrt(displacementX*displacementX + displacementY*displacementY);\n\tconst double valExp = displacement*shielding;\n\n\tif (valExp < 10.0) \/\/ restrict to 10*(ion debye length)\n\t{\n\t\t\/\/ calculate phi\n\t\tconst double coeffient = coulomb\/(displacement*exp(valExp));\n\t\tcloud->phi[currentParticle] += coeffient*iCharge;\n\t\tcloud->phi[iParticle] += coeffient*currentCharge;\n\t\t\n\t\t\/\/ calculate force\n\t\tconst double forceC = currentCharge*iCharge*coeffient*(1.0 + valExp)\/(displacement*displacement);\n\t\tcloud->forceX[currentParticle] += forceC*displacementX;\n\t\tcloud->forceY[currentParticle] += forceC*displacementY;\n\n\t\t\/\/ equal and opposite force:\n\t\tcloud->forceX[iParticle] -= forceC*displacementX;\n\t\tcloud->forceY[iParticle] -= forceC*displacementY;\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const cloud_index currentParticle, const cloud_index iParticle, \n const __m128d currentCharge, const __m128d iCharge,\n const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-valExpH) : 0.0, \/\/ _mm_set_pd is backwards\n\t\t\t\t\t\t\t boolL ? exp(-valExpL) : 0.0);\n\n\t\/\/ calculate phi\n\tconst __m128d coeffient = _mm_set1_pd(coulomb)\/displacement*expv;\n\tdouble *pPh = cloud->phi + currentParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*iCharge);\n\tpPh = cloud->phi + iParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*currentCharge);\n\t\n\t\/\/ calculate force\n\tconst __m128d forceC = currentCharge*iCharge*coeffient*(_mm_set1_pd(1.0) + valExp)\/(displacement*displacement);\n\t\n\tconst __m128d forcevX = forceC*displacementX;\n\tconst __m128d forcevY = forceC*displacementY;\n\n\tdouble *pFx = cloud->forceX + currentParticle;\n\tdouble *pFy = cloud->forceY + currentParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/ equal and opposite force:\n\tpFx = cloud->forceX + iParticle;\n\tpFy = cloud->forceY + iParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) - forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) - forcevY);\n}\n\ninline void ShieldedCoulombForce::forcer(const cloud_index currentParticle, const cloud_index iParticle, \n const __m128d currentCharge, const __m128d iCharge,\n const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-valExpH) : 0.0, \/\/ _mm_set_pd is backwards\n\t\t\t\t\t\t\t boolL ? exp(-valExpL) : 0.0);\n\t\n\t\/\/ calculate phi\n\tconst __m128d coeffient = _mm_set1_pd(coulomb)\/displacement*expv;\n\tdouble *pPh = cloud->phi + currentParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*iCharge);\n\tpPh = cloud->phi + iParticle;\n\t_mm_storer_pd(pPh, _mm_loadr_pd(pPh) + coeffient*currentCharge);\n \n\t\/\/ calculate force\n\tconst __m128d forceC = currentCharge*iCharge*coeffient*(_mm_set1_pd(1.0) + valExp)\/(displacement*displacement);\n\t\n\tconst __m128d forcevX = forceC*displacementX;\n\tconst __m128d forcevY = forceC*displacementY;\n\t\n\tdouble *pFx = cloud->forceX + currentParticle;\n\tdouble *pFy = cloud->forceY + currentParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\t\n\t\/\/ equal and opposite force:\n\tpFx = cloud->forceX + iParticle;\n\tpFy = cloud->forceY + iParticle;\n\t_mm_storer_pd(pFx, _mm_loadr_pd(pFx) - forcevX);\n\t_mm_storer_pd(pFy, _mm_loadr_pd(pFy) - forcevY);\n}\n\nvoid ShieldedCoulombForce::writeForce(fitsfile * const file, int * const error) const\n{\n\t\/\/ move to primary HDU:\n\tif (!*error)\n\t\t\/\/ file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\t\/\/ add flag indicating that the drag force is used:\n\tif (!*error) \n\t{\n\t\tlong forceFlags = 0;\n\t\tfits_read_key_lng(file, const_cast (\"FORCES\"), &forceFlags, NULL, error);\n\n\t\t\/\/ add ShieldedCoulombForce bit:\n\t\tforceFlags |= ShieldedCoulombForceFlag; \/\/ compound bitwise OR\n\n\t\tif (*error == KEY_NO_EXIST || *error == VALUE_UNDEFINED)\n\t\t\t*error = 0; \/\/ clear above error.\n\n\t\t\/\/ add or update keyword.\n\t\tif (!*error) \n\t\t\tfits_update_key(file, TLONG, const_cast (\"FORCES\"), &forceFlags, const_cast (\"Force configuration.\"), error);\n\t}\n\n\tif (!*error)\n\t\t\/\/ file, key name, value, precision (scientific format), comment\n\t\tfits_write_key_dbl(file, const_cast (\"shieldingConstant\"), shielding, 6, const_cast (\"[m^-1] (ShieldedCoulombForce)\"), error);\n}\n\nvoid ShieldedCoulombForce::readForce(fitsfile * const file, int * const error)\n{\n\t\/\/ move to primary HDU:\n\tif (!*error)\n\t\t\/\/ file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\tif (!*error)\n\t\t\/\/ file, key name, value, don't read comment, error\n\t\tfits_read_key_dbl(file, const_cast (\"shieldingConstant\"), &shielding, NULL, error);\n}\nChange permittivity of free space to match value in NRL plasma formulary.\/*===- ShieldedCoulombForce.cpp - libSimulation -===============================\n*\n* DEMON\n*\n* This file is distributed under the BSD Open Source License. See LICENSE.TXT \n* for details. \n*\n*===-----------------------------------------------------------------------===*\/\n\n#include \"ShieldedCoulombForce.h\"\n#include \n\nconst double ShieldedCoulombForce::coulomb = 1.0\/(4.0*M_PI*8.8542E-12);\n\nShieldedCoulombForce::ShieldedCoulombForce(Cloud * const myCloud, const double shieldingConstant)\n: Force(myCloud), shielding(shieldingConstant) {}\n\nvoid ShieldedCoulombForce::force1(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx1_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety1_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq1_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq1_pd(i), vx1 - cloud->getx1_pd(i), vy1 - cloud->gety1_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq1r_pd(i), vx1 - cloud->getx1r_pd(i), vy1 - cloud->gety1r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force2(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx2_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety2_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq2_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq2_pd(i), vx1 - cloud->getx2_pd(i), vy1 - cloud->gety2_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq2r_pd(i), vx1 - cloud->getx2r_pd(i), vy1 - cloud->gety2r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force3(const double currentTime)\n{\n for (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx3_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety3_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq3_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq3_pd(i), vx1 - cloud->getx3_pd(i), vy1 - cloud->gety3_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq3r_pd(i), vx1 - cloud->getx3r_pd(i), vy1 - cloud->gety3r_pd(i));\n\t\t}\n\t}\n}\n\nvoid ShieldedCoulombForce::force4(const double currentTime)\n{\n\tfor (cloud_index currentParticle = 0, numParticles = cloud->n, e = cloud->n - 1; currentParticle < e; currentParticle += 2) \n\t{\n\t\tconst __m128d vx1 = cloud->getx4_pd(currentParticle);\n\t\tconst __m128d vy1 = cloud->gety4_pd(currentParticle);\n\t\tconst __m128d vq1 = cloud->getq4_pd(currentParticle);\n\t\tdouble x1, x2, y1, y2, q1, q2;\n\t\t_mm_storel_pd(&x1, vx1);\n\t\t_mm_storeh_pd(&x2, vx1);\n\t\t_mm_storel_pd(&y1, vy1);\n\t\t_mm_storeh_pd(&y2, vy1);\n\t\t_mm_storel_pd(&q1, vq1);\n\t\t_mm_storeh_pd(&q2, vq1);\n\n\t\tforce(currentParticle, currentParticle + 1, q1, q2, x1 - x2, y1 - y2);\n\t\tfor (cloud_index i = currentParticle + 2; i < numParticles; i += 2)\n\t\t{\n\t\t\tforce(currentParticle, i, vq1, cloud->getq4_pd(i), vx1 - cloud->getx4_pd(i), vy1 - cloud->gety4_pd(i));\n\t\t\tforcer(currentParticle, i, vq1, cloud->getq4r_pd(i), vx1 - cloud->getx4r_pd(i), vy1 - cloud->gety4r_pd(i));\n\t\t}\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const cloud_index currentParticle, const cloud_index iParticle, \n const double currentCharge, const double iCharge,\n const double displacementX, const double displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst double displacement = sqrt(displacementX*displacementX + displacementY*displacementY);\n\tconst double valExp = displacement*shielding;\n\n\tif (valExp < 10.0) \/\/ restrict to 10*(ion debye length)\n\t{\n\t\t\/\/ calculate phi\n\t\tconst double coeffient = coulomb\/(displacement*exp(valExp));\n\t\tcloud->phi[currentParticle] += coeffient*iCharge;\n\t\tcloud->phi[iParticle] += coeffient*currentCharge;\n\t\t\n\t\t\/\/ calculate force\n\t\tconst double forceC = currentCharge*iCharge*coeffient*(1.0 + valExp)\/(displacement*displacement);\n\t\tcloud->forceX[currentParticle] += forceC*displacementX;\n\t\tcloud->forceY[currentParticle] += forceC*displacementY;\n\n\t\t\/\/ equal and opposite force:\n\t\tcloud->forceX[iParticle] -= forceC*displacementX;\n\t\tcloud->forceY[iParticle] -= forceC*displacementY;\n\t}\n}\n\ninline void ShieldedCoulombForce::force(const cloud_index currentParticle, const cloud_index iParticle, \n const __m128d currentCharge, const __m128d iCharge,\n const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-valExpH) : 0.0, \/\/ _mm_set_pd is backwards\n\t\t\t\t\t\t\t boolL ? exp(-valExpL) : 0.0);\n\n\t\/\/ calculate phi\n\tconst __m128d coeffient = _mm_set1_pd(coulomb)\/displacement*expv;\n\tdouble *pPh = cloud->phi + currentParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*iCharge);\n\tpPh = cloud->phi + iParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*currentCharge);\n\t\n\t\/\/ calculate force\n\tconst __m128d forceC = currentCharge*iCharge*coeffient*(_mm_set1_pd(1.0) + valExp)\/(displacement*displacement);\n\t\n\tconst __m128d forcevX = forceC*displacementX;\n\tconst __m128d forcevY = forceC*displacementY;\n\n\tdouble *pFx = cloud->forceX + currentParticle;\n\tdouble *pFy = cloud->forceY + currentParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\n\t\/\/ equal and opposite force:\n\tpFx = cloud->forceX + iParticle;\n\tpFy = cloud->forceY + iParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) - forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) - forcevY);\n}\n\ninline void ShieldedCoulombForce::forcer(const cloud_index currentParticle, const cloud_index iParticle, \n const __m128d currentCharge, const __m128d iCharge,\n const __m128d displacementX, const __m128d displacementY)\n{\n\t\/\/ Calculate displacement between particles.\n\tconst __m128d displacement = _mm_sqrt_pd(displacementX*displacementX + displacementY*displacementY);\n\tconst __m128d valExp = displacement*_mm_set_pd(shielding, shielding);\n\t\n\tdouble valExpL, valExpH;\n\t_mm_storel_pd(&valExpL, valExp);\n\t_mm_storeh_pd(&valExpH, valExp);\n\t\n\tconst bool boolL = valExpL < 10.0;\n\tconst bool boolH = valExpH < 10.0;\n\tif (!boolL && !boolH)\n\t\treturn;\n\t\n\t__m128d expv = _mm_set_pd(boolH ? exp(-valExpH) : 0.0, \/\/ _mm_set_pd is backwards\n\t\t\t\t\t\t\t boolL ? exp(-valExpL) : 0.0);\n\t\n\t\/\/ calculate phi\n\tconst __m128d coeffient = _mm_set1_pd(coulomb)\/displacement*expv;\n\tdouble *pPh = cloud->phi + currentParticle;\n\t_mm_store_pd(pPh, _mm_load_pd(pPh) + coeffient*iCharge);\n\tpPh = cloud->phi + iParticle;\n\t_mm_storer_pd(pPh, _mm_loadr_pd(pPh) + coeffient*currentCharge);\n \n\t\/\/ calculate force\n\tconst __m128d forceC = currentCharge*iCharge*coeffient*(_mm_set1_pd(1.0) + valExp)\/(displacement*displacement);\n\t\n\tconst __m128d forcevX = forceC*displacementX;\n\tconst __m128d forcevY = forceC*displacementY;\n\t\n\tdouble *pFx = cloud->forceX + currentParticle;\n\tdouble *pFy = cloud->forceY + currentParticle;\n\t_mm_store_pd(pFx, _mm_load_pd(pFx) + forcevX);\n\t_mm_store_pd(pFy, _mm_load_pd(pFy) + forcevY);\n\t\n\t\/\/ equal and opposite force:\n\tpFx = cloud->forceX + iParticle;\n\tpFy = cloud->forceY + iParticle;\n\t_mm_storer_pd(pFx, _mm_loadr_pd(pFx) - forcevX);\n\t_mm_storer_pd(pFy, _mm_loadr_pd(pFy) - forcevY);\n}\n\nvoid ShieldedCoulombForce::writeForce(fitsfile * const file, int * const error) const\n{\n\t\/\/ move to primary HDU:\n\tif (!*error)\n\t\t\/\/ file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\t\/\/ add flag indicating that the drag force is used:\n\tif (!*error) \n\t{\n\t\tlong forceFlags = 0;\n\t\tfits_read_key_lng(file, const_cast (\"FORCES\"), &forceFlags, NULL, error);\n\n\t\t\/\/ add ShieldedCoulombForce bit:\n\t\tforceFlags |= ShieldedCoulombForceFlag; \/\/ compound bitwise OR\n\n\t\tif (*error == KEY_NO_EXIST || *error == VALUE_UNDEFINED)\n\t\t\t*error = 0; \/\/ clear above error.\n\n\t\t\/\/ add or update keyword.\n\t\tif (!*error) \n\t\t\tfits_update_key(file, TLONG, const_cast (\"FORCES\"), &forceFlags, const_cast (\"Force configuration.\"), error);\n\t}\n\n\tif (!*error)\n\t\t\/\/ file, key name, value, precision (scientific format), comment\n\t\tfits_write_key_dbl(file, const_cast (\"shieldingConstant\"), shielding, 6, const_cast (\"[m^-1] (ShieldedCoulombForce)\"), error);\n}\n\nvoid ShieldedCoulombForce::readForce(fitsfile * const file, int * const error)\n{\n\t\/\/ move to primary HDU:\n\tif (!*error)\n\t\t\/\/ file, # indicating primary HDU, HDU type, error\n \t\tfits_movabs_hdu(file, 1, IMAGE_HDU, error);\n\t\n\tif (!*error)\n\t\t\/\/ file, key name, value, don't read comment, error\n\t\tfits_read_key_dbl(file, const_cast (\"shieldingConstant\"), &shielding, NULL, error);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ CPullingSwing.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 24\/02\/2015.\n\/\/ Copyright (c) 2015 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include files\n\/\/ -----------------------------------------------------------------------------\n#include \"CPullingSwing.hpp\"\n#include \"CPlayer.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static members\n\/\/ -----------------------------------------------------------------------------\nfloat CPullingSwing::smPullSpeedIncrement = 350.0f;\nfloat CPullingSwing::smPullSpeedMax = 500.0f;\nfloat CPullingSwing::smDetachLength = CSwing::smMinLength;\n\n\/\/ =============================================================================\n\/\/ CPullingSwing constructor\/destructor\n\/\/ -----------------------------------------------------------------------------\nCPullingSwing::CPullingSwing(CPlayer *theBob, CLevel *theParentLevel)\n: CSwing(theBob, theParentLevel)\n{\n \/\/ Make it blue\n mColour = CColour::Blue;\n}\n\nCPullingSwing::~CPullingSwing()\n{\n \n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CPullingSwing::Update(CTime elapsedTime)\n{\n if (mAttached)\n {\n \/\/ Update the length since the player will be closer now\n mLength = GetDistanceToBob();\n \n \/\/ Detach the player if they are close enough\n if (mLength <= smDetachLength)\n {\n Detach();\n }\n else\n {\n \/\/ Accelerate the player towards the origin\n CVector2f v = mBob->GetVelocity();\n CVector2f bobToOrigin = mOrigin - mBob->GetPosition();\n bobToOrigin.Normalise();\n float timedInc = smPullSpeedIncrement * elapsedTime.asSeconds();\n CVector2f newV = v + (bobToOrigin * timedInc);\n \n \/\/ Clamp the new velocity\n if (newV.GetMagnitude() > smPullSpeedMax)\n {\n newV = bobToOrigin * smPullSpeedMax;\n }\n \n mBob->SetVelocity(newV);\n }\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::AttenuateGravity\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPullingSwing::AttenuateGravity(CVector2f gravity)\n{\n \/\/ Have no gravity when on this swing\n if (mAttached)\n {\n gravity = CVector2f(0.0f, 0.0f);\n }\n \n return gravity;\n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::RespondToAttach\n\/\/ -----------------------------------------------------------------------------\nvoid CPullingSwing::RespondToAttach()\n{\n \/\/ Throw away all player velocity, we'll give them a vel towards the origin\n \/\/ in update\n mBob->SetVelocity(CVector2f(0.0f, 0.0f));\n}Make sure the players velocity is always towards the origin when on the pulling swing, even after they have collided with something\/\/\n\/\/ CPullingSwing.cpp\n\/\/ SwingGame\n\/\/\n\/\/ Created by Tim Brier on 24\/02\/2015.\n\/\/ Copyright (c) 2015 tbrier. All rights reserved.\n\/\/\n\n\/\/ =============================================================================\n\/\/ Include files\n\/\/ -----------------------------------------------------------------------------\n#include \"CPullingSwing.hpp\"\n#include \"CPlayer.hpp\"\n\n\/\/ =============================================================================\n\/\/ Static members\n\/\/ -----------------------------------------------------------------------------\nfloat CPullingSwing::smPullSpeedIncrement = 350.0f;\nfloat CPullingSwing::smPullSpeedMax = 500.0f;\nfloat CPullingSwing::smDetachLength = CSwing::smMinLength;\n\n\/\/ =============================================================================\n\/\/ CPullingSwing constructor\/destructor\n\/\/ -----------------------------------------------------------------------------\nCPullingSwing::CPullingSwing(CPlayer *theBob, CLevel *theParentLevel)\n: CSwing(theBob, theParentLevel)\n{\n \/\/ Make it blue\n mColour = CColour::Blue;\n}\n\nCPullingSwing::~CPullingSwing()\n{\n \n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::Update\n\/\/ -----------------------------------------------------------------------------\nvoid CPullingSwing::Update(CTime elapsedTime)\n{\n if (mAttached)\n {\n \/\/ Update the length since the player will be closer now\n mLength = GetDistanceToBob();\n \n \/\/ Detach the player if they are close enough\n if (mLength <= smDetachLength)\n {\n Detach();\n }\n else\n {\n \/\/ Make sure the players velocity is towards the origin\n CVector2f v = mBob->GetVelocity();\n CVector2f bobToOrigin = mOrigin - mBob->GetPosition();\n bobToOrigin.Normalise();\n v = v.GetComponentInDirection(bobToOrigin);\n \n \/\/ Accelerate the player towards the origin\n float timedInc = smPullSpeedIncrement * elapsedTime.asSeconds();\n CVector2f newV = v + (bobToOrigin * timedInc);\n \n \/\/ Clamp the new velocity\n if (newV.GetMagnitude() > smPullSpeedMax)\n {\n newV = bobToOrigin * smPullSpeedMax;\n }\n \n mBob->SetVelocity(newV);\n }\n }\n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::AttenuateGravity\n\/\/ -----------------------------------------------------------------------------\nCVector2f CPullingSwing::AttenuateGravity(CVector2f gravity)\n{\n \/\/ Have no gravity when on this swing\n if (mAttached)\n {\n gravity = CVector2f(0.0f, 0.0f);\n }\n \n return gravity;\n}\n\n\/\/ =============================================================================\n\/\/ CPullingSwing::RespondToAttach\n\/\/ -----------------------------------------------------------------------------\nvoid CPullingSwing::RespondToAttach()\n{\n \/\/ Throw away all player velocity, we'll give them a vel towards the origin\n \/\/ in update\n mBob->SetVelocity(CVector2f(0.0f, 0.0f));\n}<|endoftext|>"} {"text":"\/\/Source: The LLVM Compiler Infrastructure - lib\/addsf3.c\n\/\/Modified to truncate result of addition\n\n#include \n#include \n#ifdef _WIN32\n#include \n#endif\n#include \"FpMulTruncate.h\"\n\ntypedef uint32 rep_t;\ntypedef int32 srep_t;\ntypedef float fp_t;\n#define REP_C UINT32_C\n#define significandBits 23\n\n#define typeWidth (sizeof(rep_t)*CHAR_BIT)\n#define exponentBits (typeWidth - significandBits - 1)\n#define maxExponent ((1 << exponentBits) - 1)\n#define exponentBias (maxExponent >> 1)\n\n#define implicitBit (REP_C(1) << significandBits)\n#define significandMask (implicitBit - 1U)\n#define signBit (REP_C(1) << (significandBits + exponentBits))\n#define absMask (signBit - 1U)\n#define exponentMask (absMask ^ significandMask)\n#define oneRep ((rep_t)exponentBias << significandBits)\n#define infRep exponentMask\n#define quietBit (implicitBit >> 1)\n#define qnanRep (exponentMask | quietBit)\n\nstatic inline int rep_clz(rep_t a) {\n#ifdef _WIN32\n DWORD r = 0;\n _BitScanForward(&r, a);\n return 32 - r;\n#else\n\treturn __builtin_clz(a);\n#endif\n}\n\nuint32 FpAddTruncate(uint32 a, uint32 b) \n{\n const rep_t aAbs = a & absMask;\n const rep_t bAbs = b & absMask;\n \n \/\/ Detect if a or b is zero, infinity, or NaN.\n if (aAbs - 1U >= infRep - 1U || bAbs - 1U >= infRep - 1U) {\n \n \/\/ NaN + anything = qNaN\n if (aAbs > infRep) return (a | quietBit);\n \/\/ anything + NaN = qNaN\n if (bAbs > infRep) return (b | quietBit);\n \n if (aAbs == infRep) {\n \/\/ +\/-infinity + -\/+infinity = qNaN\n if ((a ^ b) == signBit) return qnanRep;\n \/\/ +\/-infinity + anything remaining = +\/- infinity\n else return a;\n }\n \n \/\/ anything remaining + +\/-infinity = +\/-infinity\n if (bAbs == infRep) return b;\n \n \/\/ zero + anything = anything\n if (!aAbs) {\n \/\/ but we need to get the sign right for zero + zero\n if (!bAbs) return (a & b);\n else return b;\n }\n \n \/\/ anything + zero = anything\n if (!bAbs) return a;\n }\n \n \/\/ Swap a and b if necessary so that a has the larger absolute value.\n if (bAbs > aAbs) {\n const uint32 temp = a;\n a = b;\n b = temp;\n }\n \n \/\/ Extract the exponent and significand from the (possibly swapped) a and b.\n int aExponent = a >> significandBits & maxExponent;\n int bExponent = b >> significandBits & maxExponent;\n rep_t aSignificand = a & significandMask;\n rep_t bSignificand = b & significandMask;\n \n \/\/ Normalize any denormals, and adjust the exponent accordingly.\n \/\/if (aExponent == 0) aExponent = normalize(&aSignificand);\n \/\/if (bExponent == 0) bExponent = normalize(&bSignificand);\n \n \/\/ The sign of the result is the sign of the larger operand, a. If they\n \/\/ have opposite signs, we are performing a subtraction; otherwise addition.\n const rep_t resultSign = a & signBit;\n const bool subtraction = (a ^ b) & signBit;\n \n \/\/ Shift the significands to give us round, guard and sticky, and or in the\n \/\/ implicit significand bit. (If we fell through from the denormal path it\n \/\/ was already set by normalize( ), but setting it twice won't hurt\n \/\/ anything.)\n aSignificand = (aSignificand | implicitBit) << 3;\n bSignificand = (bSignificand | implicitBit) << 3;\n \n \/\/ Shift the significand of b by the difference in exponents, with a sticky\n \/\/ bottom bit to get rounding correct.\n const unsigned int align = aExponent - bExponent;\n if (align) {\n if (align < typeWidth) {\n \/\/const bool sticky = bSignificand << (typeWidth - align);\n bSignificand = bSignificand >> align;\n } else {\n bSignificand = 0; \/\/ sticky; b is known to be non-zero.\n }\n }\n \n if (subtraction) {\n aSignificand -= bSignificand;\n \n \/\/ If a == -b, return +zero.\n if (aSignificand == 0) return 0;\n \n \/\/ If partial cancellation occured, we need to left-shift the result\n \/\/ and adjust the exponent:\n if (aSignificand < implicitBit << 3) {\n const int shift = rep_clz(aSignificand) - rep_clz(implicitBit << 3);\n aSignificand <<= shift;\n aExponent -= shift;\n }\n }\n \n else \/* addition *\/ {\n aSignificand += bSignificand;\n \n \/\/ If the addition carried up, we need to right-shift the result and\n \/\/ adjust the exponent:\n if (aSignificand & implicitBit << 4) {\n const bool sticky = aSignificand & 1;\n aSignificand = aSignificand >> 1 | sticky;\n aExponent += 1;\n }\n }\n \n \/\/ If we have overflowed the type, return +\/- infinity:\n if (aExponent >= maxExponent) return infRep | resultSign;\n \n if (aExponent <= 0) {\n \/\/ Result is denormal before rounding; the exponent is zero and we\n \/\/ need to shift the significand.\n const int shift = 1 - aExponent;\n const bool sticky = aSignificand << (typeWidth - shift);\n aSignificand = aSignificand >> shift | sticky;\n aExponent = 0;\n }\n \n \/\/ Low three bits are round, guard, and sticky.\n const int roundGuardSticky = aSignificand & 0x7;\n \n \/\/ Shift the significand into place, and mask off the implicit bit.\n rep_t result = aSignificand >> 3 & significandMask;\n \n \/\/ Insert the exponent and sign.\n result |= (rep_t)aExponent << significandBits;\n result |= resultSign;\n \n return result;\n}\nFixed bug in FpAddTruncate.\/\/Source: The LLVM Compiler Infrastructure - lib\/addsf3.c\n\/\/Modified to truncate result of addition\n\n#include \n#include \n#ifdef _WIN32\n#include \n#endif\n#include \"FpAddTruncate.h\"\n\ntypedef uint32 rep_t;\ntypedef int32 srep_t;\ntypedef float fp_t;\n#define REP_C UINT32_C\n#define significandBits 23\n\n#define typeWidth (sizeof(rep_t)*CHAR_BIT)\n#define exponentBits (typeWidth - significandBits - 1)\n#define maxExponent ((1 << exponentBits) - 1)\n#define exponentBias (maxExponent >> 1)\n\n#define implicitBit (REP_C(1) << significandBits)\n#define significandMask (implicitBit - 1U)\n#define signBit (REP_C(1) << (significandBits + exponentBits))\n#define absMask (signBit - 1U)\n#define exponentMask (absMask ^ significandMask)\n#define oneRep ((rep_t)exponentBias << significandBits)\n#define infRep exponentMask\n#define quietBit (implicitBit >> 1)\n#define qnanRep (exponentMask | quietBit)\n\nstatic inline int rep_clz(rep_t a) {\n#ifdef _WIN32\n DWORD r = 0;\n _BitScanReverse(&r, a);\n return (31 - r);\n#else\n\treturn __builtin_clz(a);\n#endif\n}\n\nuint32 FpAddTruncate(uint32 a, uint32 b) \n{\n const rep_t aAbs = a & absMask;\n const rep_t bAbs = b & absMask;\n \n \/\/ Detect if a or b is zero, infinity, or NaN.\n if (aAbs - 1U >= infRep - 1U || bAbs - 1U >= infRep - 1U) {\n \n \/\/ NaN + anything = qNaN\n if (aAbs > infRep) return (a | quietBit);\n \/\/ anything + NaN = qNaN\n if (bAbs > infRep) return (b | quietBit);\n \n if (aAbs == infRep) {\n \/\/ +\/-infinity + -\/+infinity = qNaN\n if ((a ^ b) == signBit) return qnanRep;\n \/\/ +\/-infinity + anything remaining = +\/- infinity\n else return a;\n }\n \n \/\/ anything remaining + +\/-infinity = +\/-infinity\n if (bAbs == infRep) return b;\n \n \/\/ zero + anything = anything\n if (!aAbs) {\n \/\/ but we need to get the sign right for zero + zero\n if (!bAbs) return (a & b);\n else return b;\n }\n \n \/\/ anything + zero = anything\n if (!bAbs) return a;\n }\n \n \/\/ Swap a and b if necessary so that a has the larger absolute value.\n if (bAbs > aAbs) {\n const uint32 temp = a;\n a = b;\n b = temp;\n }\n \n \/\/ Extract the exponent and significand from the (possibly swapped) a and b.\n int aExponent = a >> significandBits & maxExponent;\n int bExponent = b >> significandBits & maxExponent;\n rep_t aSignificand = a & significandMask;\n rep_t bSignificand = b & significandMask;\n \n \/\/ Normalize any denormals, and adjust the exponent accordingly.\n \/\/if (aExponent == 0) aExponent = normalize(&aSignificand);\n \/\/if (bExponent == 0) bExponent = normalize(&bSignificand);\n \n \/\/ The sign of the result is the sign of the larger operand, a. If they\n \/\/ have opposite signs, we are performing a subtraction; otherwise addition.\n const rep_t resultSign = a & signBit;\n const bool subtraction = (a ^ b) & signBit;\n \n \/\/ Shift the significands to give us round, guard and sticky, and or in the\n \/\/ implicit significand bit. (If we fell through from the denormal path it\n \/\/ was already set by normalize( ), but setting it twice won't hurt\n \/\/ anything.)\n aSignificand = (aSignificand | implicitBit) << 3;\n bSignificand = (bSignificand | implicitBit) << 3;\n \n \/\/ Shift the significand of b by the difference in exponents, with a sticky\n \/\/ bottom bit to get rounding correct.\n const unsigned int align = aExponent - bExponent;\n if (align) {\n if (align < typeWidth) {\n \/\/const bool sticky = bSignificand << (typeWidth - align);\n bSignificand = bSignificand >> align;\n } else {\n bSignificand = 0; \/\/ sticky; b is known to be non-zero.\n }\n }\n \n if (subtraction) {\n aSignificand -= bSignificand;\n \n \/\/ If a == -b, return +zero.\n if (aSignificand == 0) return 0;\n \n \/\/ If partial cancellation occured, we need to left-shift the result\n \/\/ and adjust the exponent:\n if (aSignificand < implicitBit << 3) {\n const int shift = rep_clz(aSignificand) - rep_clz(implicitBit << 3);\n aSignificand <<= shift;\n aExponent -= shift;\n }\n }\n \n else \/* addition *\/ {\n aSignificand += bSignificand;\n \n \/\/ If the addition carried up, we need to right-shift the result and\n \/\/ adjust the exponent:\n if (aSignificand & implicitBit << 4) {\n const bool sticky = aSignificand & 1;\n aSignificand = aSignificand >> 1 | sticky;\n aExponent += 1;\n }\n }\n \n \/\/ If we have overflowed the type, return +\/- infinity:\n if (aExponent >= maxExponent) return infRep | resultSign;\n \n if (aExponent <= 0) {\n \/\/ Result is denormal before rounding; the exponent is zero and we\n \/\/ need to shift the significand.\n const int shift = 1 - aExponent;\n const bool sticky = aSignificand << (typeWidth - shift);\n aSignificand = aSignificand >> shift | sticky;\n aExponent = 0;\n }\n \n \/\/ Low three bits are round, guard, and sticky.\n const int roundGuardSticky = aSignificand & 0x7;\n \n \/\/ Shift the significand into place, and mask off the implicit bit.\n rep_t result = aSignificand >> 3 & significandMask;\n \n \/\/ Insert the exponent and sign.\n result |= (rep_t)aExponent << significandBits;\n result |= resultSign;\n \n return result;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) Microsoft Corporation\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pch.h\"\n#include \"..\/HTTP\/httpcall.h\"\n#include \"buildver.h\"\n#include \"global.h\"\n#include \"..\/Mock\/lhc_mock.h\"\n\n#if !HC_NOWEBSOCKETS\n#include \"..\/WebSocket\/hcwebsocket.h\"\n#endif\n\nusing namespace xbox::httpclient;\n\nNAMESPACE_XBOX_HTTP_CLIENT_BEGIN\n\nHRESULT http_singleton::singleton_access(\n _In_ singleton_access_mode mode,\n _In_opt_ HCInitArgs* createArgs,\n _Out_ std::shared_ptr& singleton\n) noexcept\n{\n static std::mutex s_mutex;\n static std::shared_ptr s_singleton{ nullptr };\n static uint8_t s_useCount{ 0 };\n\n std::lock_guard lock{ s_mutex };\n switch (mode)\n {\n case singleton_access_mode::create:\n {\n \/\/ Create the singleton only for the first client calling create\n if (!s_useCount)\n {\n PerformEnv performEnv;\n RETURN_IF_FAILED(Internal_InitializeHttpPlatform(createArgs, performEnv));\n\n auto rawSingleton = new (http_memory::mem_alloc(sizeof(http_singleton))) http_singleton(\n GetUserHttpPerformHandler(),\n#if !HC_NOWEBSOCKETS\n GetUserWebSocketPerformHandlers(),\n#endif\n std::move(performEnv)\n );\n\n s_singleton = std::shared_ptr(rawSingleton, http_alloc_deleter());\n s_singleton->m_self = s_singleton;\n }\n\n ++s_useCount;\n singleton = s_singleton;\n\n return S_OK;\n }\n case singleton_access_mode::get:\n {\n assert(!createArgs);\n singleton = s_singleton;\n return S_OK;\n }\n case singleton_access_mode::cleanup:\n {\n assert(!createArgs);\n\n if (!s_singleton)\n {\n assert(s_useCount == 0);\n return E_HC_NOT_INITIALISED;\n }\n\n --s_useCount;\n singleton = s_singleton;\n\n if (s_useCount > 0)\n {\n return E_HC_INTERNAL_STILLINUSE;\n }\n\n s_singleton.reset();\n return S_OK;\n }\n default:\n {\n assert(false);\n return S_OK;\n }\n }\n}\n\nstd::shared_ptr http_singleton::get() noexcept\n{\n std::shared_ptr singleton{};\n auto hr = singleton_access(singleton_access_mode::get, nullptr, singleton);\n\n \/\/ get should never fail\n assert(SUCCEEDED(hr));\n UNREFERENCED_PARAMETER(hr);\n\n return singleton;\n}\n\nHRESULT http_singleton::create(\n _In_ HCInitArgs* args\n) noexcept\n{\n std::shared_ptr singleton{};\n return singleton_access(singleton_access_mode::create, args, singleton);\n}\n\nHRESULT http_singleton::cleanup_async(\n _In_ XAsyncBlock* async\n) noexcept\n{\n std::shared_ptr singleton{};\n RETURN_IF_FAILED(singleton_access(singleton_access_mode::cleanup, nullptr, singleton));\n\n return XAsyncBegin(\n async,\n singleton.get(),\n reinterpret_cast(cleanup_async),\n __FUNCTION__,\n [](XAsyncOp op, const XAsyncProviderData* data)\n {\n switch (op)\n {\n case XAsyncOp::Begin:\n {\n return XAsyncSchedule(data->async, 0);\n }\n case XAsyncOp::DoWork:\n {\n auto& self{ static_cast(data->context)->m_self };\n\n \/\/ Wait for all other references to the singleton to go away\n \/\/ Note that the use count check here is only valid because we never create\n \/\/ a weak_ptr to the singleton. If we did that could cause the use count\n \/\/ to increase even though we are the only strong reference\n if (self.use_count() > 1)\n {\n return XAsyncSchedule(data->async, 10);\n }\n\n shared_ptr_cache::cleanup(self);\n\n \/\/ self is the only reference at this point, the singleton will be destroyed on this thread.\n self.reset();\n\n XAsyncComplete(data->async, S_OK, 0);\n return S_OK;\n }\n default:\n {\n return S_OK;\n }\n }\n });\n}\n\nhttp_singleton::http_singleton(\n HttpPerformInfo const& httpPerformInfo,\n#if !HC_NOWEBSOCKETS\n WebSocketPerformInfo const& websocketPerformInfo,\n#endif\n PerformEnv&& performEnv\n) :\n m_httpPerform{ httpPerformInfo },\n m_performEnv{ std::move(performEnv) }\n#if !HC_NOWEBSOCKETS\n , m_websocketPerform{ websocketPerformInfo }\n#endif\n{}\n\nhttp_singleton::~http_singleton()\n{\n for (auto& mockCall : m_mocks)\n {\n HCHttpCallCloseHandle(mockCall);\n }\n m_mocks.clear();\n}\n\nstd::shared_ptr get_http_singleton()\n{\n return http_singleton::get();\n}\n\nvoid http_singleton::set_retry_state(\n _In_ uint32_t retryAfterCacheId,\n _In_ const http_retry_after_api_state& state)\n{\n std::lock_guard lock(m_retryAfterCacheLock); \/\/ STL is not safe for multithreaded writes\n http_retry_after_api_state oldstate = get_retry_state(retryAfterCacheId);\n if (oldstate.statusCode < 400)\n {\n m_retryAfterCache[retryAfterCacheId] = state;\n }\n else if (oldstate.retryAfterTime <= state.retryAfterTime)\n {\n m_retryAfterCache[retryAfterCacheId] = state;\n }\n}\n\nhttp_retry_after_api_state http_singleton::get_retry_state(_In_ uint32_t retryAfterCacheId)\n{\n auto it = m_retryAfterCache.find(retryAfterCacheId); \/\/ STL is multithread read safe\n if (it != m_retryAfterCache.end())\n {\n return it->second; \/\/ returning a copy of state struct\n }\n\n return http_retry_after_api_state();\n}\n\nvoid http_singleton::clear_retry_state(_In_ uint32_t retryAfterCacheId)\n{\n std::lock_guard lock(m_retryAfterCacheLock); \/\/ STL is not safe for multithreaded writes\n m_retryAfterCache.erase(retryAfterCacheId);\n}\n\nHRESULT http_singleton::set_global_proxy(_In_ const char* proxyUri)\n{\n#if HC_PLATFORM == HC_PLATFORM_WIN32\n return Internal_SetGlobalProxy(m_performEnv.get(), proxyUri);\n#else\n UNREFERENCED_PARAMETER(proxyUri);\n return E_NOTIMPL;\n#endif\n}\n\nHttpPerformInfo& GetUserHttpPerformHandler() noexcept\n{\n static HttpPerformInfo handler(&Internal_HCHttpCallPerformAsync, nullptr);\n return handler;\n}\n\n#if !HC_NOWEBSOCKETS\nWebSocketPerformInfo& GetUserWebSocketPerformHandlers() noexcept\n{\n static WebSocketPerformInfo handlers(\n Internal_HCWebSocketConnectAsync,\n Internal_HCWebSocketSendMessageAsync,\n Internal_HCWebSocketSendBinaryMessageAsync,\n Internal_HCWebSocketDisconnect,\n nullptr\n );\n return handlers;\n}\n#endif\n\nNAMESPACE_XBOX_HTTP_CLIENT_END\nCleanupAsync needs to return E_PENDING unless its done (#499)\/\/ Copyright (c) Microsoft Corporation\n\/\/ Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n#include \"pch.h\"\n#include \"..\/HTTP\/httpcall.h\"\n#include \"buildver.h\"\n#include \"global.h\"\n#include \"..\/Mock\/lhc_mock.h\"\n\n#if !HC_NOWEBSOCKETS\n#include \"..\/WebSocket\/hcwebsocket.h\"\n#endif\n\nusing namespace xbox::httpclient;\n\nNAMESPACE_XBOX_HTTP_CLIENT_BEGIN\n\nHRESULT http_singleton::singleton_access(\n _In_ singleton_access_mode mode,\n _In_opt_ HCInitArgs* createArgs,\n _Out_ std::shared_ptr& singleton\n) noexcept\n{\n static std::mutex s_mutex;\n static std::shared_ptr s_singleton{ nullptr };\n static uint8_t s_useCount{ 0 };\n\n std::lock_guard lock{ s_mutex };\n switch (mode)\n {\n case singleton_access_mode::create:\n {\n \/\/ Create the singleton only for the first client calling create\n if (!s_useCount)\n {\n PerformEnv performEnv;\n RETURN_IF_FAILED(Internal_InitializeHttpPlatform(createArgs, performEnv));\n\n auto rawSingleton = new (http_memory::mem_alloc(sizeof(http_singleton))) http_singleton(\n GetUserHttpPerformHandler(),\n#if !HC_NOWEBSOCKETS\n GetUserWebSocketPerformHandlers(),\n#endif\n std::move(performEnv)\n );\n\n s_singleton = std::shared_ptr(rawSingleton, http_alloc_deleter());\n s_singleton->m_self = s_singleton;\n }\n\n ++s_useCount;\n singleton = s_singleton;\n\n return S_OK;\n }\n case singleton_access_mode::get:\n {\n assert(!createArgs);\n singleton = s_singleton;\n return S_OK;\n }\n case singleton_access_mode::cleanup:\n {\n assert(!createArgs);\n\n if (!s_singleton)\n {\n assert(s_useCount == 0);\n return E_HC_NOT_INITIALISED;\n }\n\n --s_useCount;\n singleton = s_singleton;\n\n if (s_useCount > 0)\n {\n return E_HC_INTERNAL_STILLINUSE;\n }\n\n s_singleton.reset();\n return S_OK;\n }\n default:\n {\n assert(false);\n return S_OK;\n }\n }\n}\n\nstd::shared_ptr http_singleton::get() noexcept\n{\n std::shared_ptr singleton{};\n auto hr = singleton_access(singleton_access_mode::get, nullptr, singleton);\n\n \/\/ get should never fail\n assert(SUCCEEDED(hr));\n UNREFERENCED_PARAMETER(hr);\n\n return singleton;\n}\n\nHRESULT http_singleton::create(\n _In_ HCInitArgs* args\n) noexcept\n{\n std::shared_ptr singleton{};\n return singleton_access(singleton_access_mode::create, args, singleton);\n}\n\nHRESULT http_singleton::cleanup_async(\n _In_ XAsyncBlock* async\n) noexcept\n{\n std::shared_ptr singleton{};\n RETURN_IF_FAILED(singleton_access(singleton_access_mode::cleanup, nullptr, singleton));\n\n return XAsyncBegin(\n async,\n singleton.get(),\n reinterpret_cast(cleanup_async),\n __FUNCTION__,\n [](XAsyncOp op, const XAsyncProviderData* data)\n {\n switch (op)\n {\n case XAsyncOp::Begin:\n {\n return XAsyncSchedule(data->async, 0);\n }\n case XAsyncOp::DoWork:\n {\n auto& self{ static_cast(data->context)->m_self };\n\n \/\/ Wait for all other references to the singleton to go away\n \/\/ Note that the use count check here is only valid because we never create\n \/\/ a weak_ptr to the singleton. If we did that could cause the use count\n \/\/ to increase even though we are the only strong reference\n if (self.use_count() > 1)\n {\n RETURN_IF_FAILED(XAsyncSchedule(data->async, 10));\n return E_PENDING;\n }\n\n shared_ptr_cache::cleanup(self);\n\n \/\/ self is the only reference at this point, the singleton will be destroyed on this thread.\n self.reset();\n\n XAsyncComplete(data->async, S_OK, 0);\n return S_OK;\n }\n default:\n {\n return S_OK;\n }\n }\n });\n}\n\nhttp_singleton::http_singleton(\n HttpPerformInfo const& httpPerformInfo,\n#if !HC_NOWEBSOCKETS\n WebSocketPerformInfo const& websocketPerformInfo,\n#endif\n PerformEnv&& performEnv\n) :\n m_httpPerform{ httpPerformInfo },\n m_performEnv{ std::move(performEnv) }\n#if !HC_NOWEBSOCKETS\n , m_websocketPerform{ websocketPerformInfo }\n#endif\n{}\n\nhttp_singleton::~http_singleton()\n{\n for (auto& mockCall : m_mocks)\n {\n HCHttpCallCloseHandle(mockCall);\n }\n m_mocks.clear();\n}\n\nstd::shared_ptr get_http_singleton()\n{\n return http_singleton::get();\n}\n\nvoid http_singleton::set_retry_state(\n _In_ uint32_t retryAfterCacheId,\n _In_ const http_retry_after_api_state& state)\n{\n std::lock_guard lock(m_retryAfterCacheLock); \/\/ STL is not safe for multithreaded writes\n http_retry_after_api_state oldstate = get_retry_state(retryAfterCacheId);\n if (oldstate.statusCode < 400)\n {\n m_retryAfterCache[retryAfterCacheId] = state;\n }\n else if (oldstate.retryAfterTime <= state.retryAfterTime)\n {\n m_retryAfterCache[retryAfterCacheId] = state;\n }\n}\n\nhttp_retry_after_api_state http_singleton::get_retry_state(_In_ uint32_t retryAfterCacheId)\n{\n auto it = m_retryAfterCache.find(retryAfterCacheId); \/\/ STL is multithread read safe\n if (it != m_retryAfterCache.end())\n {\n return it->second; \/\/ returning a copy of state struct\n }\n\n return http_retry_after_api_state();\n}\n\nvoid http_singleton::clear_retry_state(_In_ uint32_t retryAfterCacheId)\n{\n std::lock_guard lock(m_retryAfterCacheLock); \/\/ STL is not safe for multithreaded writes\n m_retryAfterCache.erase(retryAfterCacheId);\n}\n\nHRESULT http_singleton::set_global_proxy(_In_ const char* proxyUri)\n{\n#if HC_PLATFORM == HC_PLATFORM_WIN32\n return Internal_SetGlobalProxy(m_performEnv.get(), proxyUri);\n#else\n UNREFERENCED_PARAMETER(proxyUri);\n return E_NOTIMPL;\n#endif\n}\n\nHttpPerformInfo& GetUserHttpPerformHandler() noexcept\n{\n static HttpPerformInfo handler(&Internal_HCHttpCallPerformAsync, nullptr);\n return handler;\n}\n\n#if !HC_NOWEBSOCKETS\nWebSocketPerformInfo& GetUserWebSocketPerformHandlers() noexcept\n{\n static WebSocketPerformInfo handlers(\n Internal_HCWebSocketConnectAsync,\n Internal_HCWebSocketSendMessageAsync,\n Internal_HCWebSocketSendBinaryMessageAsync,\n Internal_HCWebSocketDisconnect,\n nullptr\n );\n return handlers;\n}\n#endif\n\nNAMESPACE_XBOX_HTTP_CLIENT_END\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n * \n * http:\/\/aws.amazon.com\/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Aws::Client;\nusing namespace Aws::Http;\nusing namespace Aws::Http::Standard;\nusing namespace Aws::Utils;\nusing namespace Aws::Utils::Logging;\n\nstatic const uint32_t HTTP_REQUEST_WRITE_BUFFER_LENGTH = 8192;\n\nWinINetSyncHttpClient::WinINetSyncHttpClient(const ClientConfiguration& config) :\n Base()\n{\n AWS_LOGSTREAM_INFO(GetLogTag(), \"Creating http client with user agent \" << config.userAgent << \" with max connections \" <<\n config.maxConnections << \", request timeout \" << config.requestTimeoutMs << \",and connect timeout \" << config.connectTimeoutMs); \n\n m_allowRedirects = config.followRedirects;\n\n DWORD inetFlags = INTERNET_OPEN_TYPE_DIRECT;\n const char* proxyHosts = nullptr;\n Aws::String strProxyHosts;\n\n bool isUsingProxy = !config.proxyHost.empty();\n \/\/setup initial proxy config.\n if (isUsingProxy)\n {\n const char* const proxySchemeString = Aws::Http::SchemeMapper::ToString(config.proxyScheme);\n AWS_LOGSTREAM_INFO(GetLogTag(), \"Http Client is using a proxy. Setting up proxy with settings scheme \" << proxySchemeString\n << \", host \" << config.proxyHost << \", port \" << config.proxyPort << \", username \" << config.proxyUserName << \".\");\n\n inetFlags = INTERNET_OPEN_TYPE_PROXY;\n Aws::StringStream ss;\n const char* schemeString = Aws::Http::SchemeMapper::ToString(config.scheme);\n ss << StringUtils::ToUpper(schemeString) << \"=\" << proxySchemeString << \":\/\/\" << config.proxyHost << \":\" << config.proxyPort;\n strProxyHosts.assign(ss.str());\n proxyHosts = strProxyHosts.c_str();\n\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Adding proxy host string to wininet \" << proxyHosts);\n }\n\n SetOpenHandle(InternetOpenA(config.userAgent.c_str(), inetFlags, proxyHosts, nullptr, 0));\n\n \/\/override offline mode.\n InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_IGNORE_OFFLINE, nullptr, 0);\n \/\/add proxy auth credentials to everything using this handle.\n if (isUsingProxy)\n {\n if (!config.proxyUserName.empty() && !InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_PROXY_USERNAME, (LPVOID)config.proxyUserName.c_str(), (DWORD)config.proxyUserName.length()))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed setting username for proxy with error code: \" << GetLastError());\n if (!config.proxyPassword.empty() && !InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)config.proxyPassword.c_str(), (DWORD)config.proxyPassword.length()))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed setting password for proxy with error code: \" << GetLastError());\n }\n\n if (!config.verifySSL)\n {\n AWS_LOGSTREAM_WARN(GetLogTag(), \"Turning ssl unknown ca verification off.\");\n DWORD flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;\n\n if (!InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags)))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed to turn ssl cert ca verification off.\");\n }\n\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"API handle \" << GetOpenHandle());\n SetConnectionPoolManager(Aws::New(GetLogTag(),\n GetOpenHandle(), config.maxConnections, config.requestTimeoutMs, config.connectTimeoutMs));\n}\n\n\nWinINetSyncHttpClient::~WinINetSyncHttpClient()\n{\n\n}\n\nvoid* WinINetSyncHttpClient::OpenRequest(const Aws::Http::HttpRequest& request, void* connection, const Aws::StringStream& ss) const\n{\n DWORD requestFlags =\n INTERNET_FLAG_NO_AUTH | \n INTERNET_FLAG_RELOAD | \n INTERNET_FLAG_KEEP_CONNECTION | \n (request.GetUri().GetScheme() == Scheme::HTTPS ? INTERNET_FLAG_SECURE : 0) |\n INTERNET_FLAG_NO_CACHE_WRITE |\n (m_allowRedirects ? 0 : INTERNET_FLAG_NO_AUTO_REDIRECT);\n\n LPCSTR accept[2] = { nullptr, nullptr };\n\n Aws::String acceptHeader(\"*\/*\");\n\n if (request.HasHeader(Aws::Http::ACCEPT_HEADER))\n {\n acceptHeader = request.GetHeaderValue(Aws::Http::ACCEPT_HEADER).c_str();\n }\n\n accept[0] = acceptHeader.c_str();\n\n HINTERNET hHttpRequest = HttpOpenRequestA(connection, HttpMethodMapper::GetNameForHttpMethod(request.GetMethod()),\n ss.str().c_str(), nullptr, nullptr, accept, requestFlags, 0);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"HttpOpenRequestA returned handle \" << hHttpRequest);\n\n return hHttpRequest;\n}\n\nvoid WinINetSyncHttpClient::DoAddHeaders(void* hHttpRequest, Aws::String& headerStr) const\n{\n if (!HttpAddRequestHeadersA(hHttpRequest, headerStr.c_str(), (DWORD)headerStr.length(), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))\n AWS_LOGSTREAM_ERROR(GetLogTag(), \"Failed to add HTTP request headers with error code: \" << GetLastError());\n}\n\nuint64_t WinINetSyncHttpClient::DoWriteData(void* hHttpRequest, char* streamBuffer, uint64_t bytesRead) const\n{\n DWORD bytesWritten = 0;\n if(!InternetWriteFile(hHttpRequest, streamBuffer, (DWORD)bytesRead, &bytesWritten))\n {\n return 0;\n }\n\n return bytesWritten;\n}\n\nbool WinINetSyncHttpClient::DoReceiveResponse(void* hHttpRequest) const\n{\n return (HttpEndRequest(hHttpRequest, nullptr, 0, 0) != 0);\n}\n \nbool WinINetSyncHttpClient::DoQueryHeaders(void* hHttpRequest, std::shared_ptr& response, Aws::StringStream& ss, uint64_t& read) const\n{\n\n char dwStatusCode[256];\n DWORD dwSize = sizeof(dwStatusCode);\n\n HttpQueryInfoA(hHttpRequest, HTTP_QUERY_STATUS_CODE, &dwStatusCode, &dwSize, 0);\n response->SetResponseCode((HttpResponseCode)atoi(dwStatusCode));\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received response code \" << dwStatusCode);\n\n char contentTypeStr[1024];\n dwSize = sizeof(contentTypeStr);\n HttpQueryInfoA(hHttpRequest, HTTP_QUERY_CONTENT_TYPE, &contentTypeStr, &dwSize, 0);\n if (contentTypeStr[0] != NULL)\n {\n response->SetContentType(contentTypeStr);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received content type \" << contentTypeStr);\n }\n\n char headerStr[1024];\n dwSize = sizeof(headerStr);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received headers:\");\n while (HttpQueryInfoA(hHttpRequest, HTTP_QUERY_RAW_HEADERS_CRLF, headerStr, &dwSize, (LPDWORD)&read) && dwSize > 0)\n {\n AWS_LOGSTREAM_DEBUG(GetLogTag(), headerStr);\n ss << headerStr;\n }\n return (read != 0);\n}\n\nbool WinINetSyncHttpClient::DoSendRequest(void* hHttpRequest) const\n{\n return (HttpSendRequestEx(hHttpRequest, NULL, NULL, 0, 0) != 0);\n}\n\nbool WinINetSyncHttpClient::DoReadData(void* hHttpRequest, char* body, uint64_t size, uint64_t& read) const\n{\n return (InternetReadFile(hHttpRequest, body, (DWORD)size, (LPDWORD)&read) != 0);\n}\n\nvoid* WinINetSyncHttpClient::GetClientModule() const\n{\n return GetModuleHandle(TEXT(\"wininet.dll\"));\n}\nRemoved superfluous c_str()\/*\n * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\").\n * You may not use this file except in compliance with the License.\n * A copy of the License is located at\n * \n * http:\/\/aws.amazon.com\/apache2.0\n * \n * or in the \"license\" file accompanying this file. This file is distributed\n * on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n * express or implied. See the License for the specific language governing\n * permissions and limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Aws::Client;\nusing namespace Aws::Http;\nusing namespace Aws::Http::Standard;\nusing namespace Aws::Utils;\nusing namespace Aws::Utils::Logging;\n\nstatic const uint32_t HTTP_REQUEST_WRITE_BUFFER_LENGTH = 8192;\n\nWinINetSyncHttpClient::WinINetSyncHttpClient(const ClientConfiguration& config) :\n Base()\n{\n AWS_LOGSTREAM_INFO(GetLogTag(), \"Creating http client with user agent \" << config.userAgent << \" with max connections \" <<\n config.maxConnections << \", request timeout \" << config.requestTimeoutMs << \",and connect timeout \" << config.connectTimeoutMs); \n\n m_allowRedirects = config.followRedirects;\n\n DWORD inetFlags = INTERNET_OPEN_TYPE_DIRECT;\n const char* proxyHosts = nullptr;\n Aws::String strProxyHosts;\n\n bool isUsingProxy = !config.proxyHost.empty();\n \/\/setup initial proxy config.\n if (isUsingProxy)\n {\n const char* const proxySchemeString = Aws::Http::SchemeMapper::ToString(config.proxyScheme);\n AWS_LOGSTREAM_INFO(GetLogTag(), \"Http Client is using a proxy. Setting up proxy with settings scheme \" << proxySchemeString\n << \", host \" << config.proxyHost << \", port \" << config.proxyPort << \", username \" << config.proxyUserName << \".\");\n\n inetFlags = INTERNET_OPEN_TYPE_PROXY;\n Aws::StringStream ss;\n const char* schemeString = Aws::Http::SchemeMapper::ToString(config.scheme);\n ss << StringUtils::ToUpper(schemeString) << \"=\" << proxySchemeString << \":\/\/\" << config.proxyHost << \":\" << config.proxyPort;\n strProxyHosts.assign(ss.str());\n proxyHosts = strProxyHosts.c_str();\n\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Adding proxy host string to wininet \" << proxyHosts);\n }\n\n SetOpenHandle(InternetOpenA(config.userAgent.c_str(), inetFlags, proxyHosts, nullptr, 0));\n\n \/\/override offline mode.\n InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_IGNORE_OFFLINE, nullptr, 0);\n \/\/add proxy auth credentials to everything using this handle.\n if (isUsingProxy)\n {\n if (!config.proxyUserName.empty() && !InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_PROXY_USERNAME, (LPVOID)config.proxyUserName.c_str(), (DWORD)config.proxyUserName.length()))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed setting username for proxy with error code: \" << GetLastError());\n if (!config.proxyPassword.empty() && !InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_PROXY_PASSWORD, (LPVOID)config.proxyPassword.c_str(), (DWORD)config.proxyPassword.length()))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed setting password for proxy with error code: \" << GetLastError());\n }\n\n if (!config.verifySSL)\n {\n AWS_LOGSTREAM_WARN(GetLogTag(), \"Turning ssl unknown ca verification off.\");\n DWORD flags = SECURITY_FLAG_IGNORE_UNKNOWN_CA | INTERNET_FLAG_IGNORE_CERT_CN_INVALID;\n\n if (!InternetSetOptionA(GetOpenHandle(), INTERNET_OPTION_SECURITY_FLAGS, &flags, sizeof(flags)))\n AWS_LOGSTREAM_FATAL(GetLogTag(), \"Failed to turn ssl cert ca verification off.\");\n }\n\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"API handle \" << GetOpenHandle());\n SetConnectionPoolManager(Aws::New(GetLogTag(),\n GetOpenHandle(), config.maxConnections, config.requestTimeoutMs, config.connectTimeoutMs));\n}\n\n\nWinINetSyncHttpClient::~WinINetSyncHttpClient()\n{\n\n}\n\nvoid* WinINetSyncHttpClient::OpenRequest(const Aws::Http::HttpRequest& request, void* connection, const Aws::StringStream& ss) const\n{\n DWORD requestFlags =\n INTERNET_FLAG_NO_AUTH | \n INTERNET_FLAG_RELOAD | \n INTERNET_FLAG_KEEP_CONNECTION | \n (request.GetUri().GetScheme() == Scheme::HTTPS ? INTERNET_FLAG_SECURE : 0) |\n INTERNET_FLAG_NO_CACHE_WRITE |\n (m_allowRedirects ? 0 : INTERNET_FLAG_NO_AUTO_REDIRECT);\n\n LPCSTR accept[2] = { nullptr, nullptr };\n\n Aws::String acceptHeader(\"*\/*\");\n\n if (request.HasHeader(Aws::Http::ACCEPT_HEADER))\n {\n acceptHeader = request.GetHeaderValue(Aws::Http::ACCEPT_HEADER);\n }\n\n accept[0] = acceptHeader.c_str();\n\n HINTERNET hHttpRequest = HttpOpenRequestA(connection, HttpMethodMapper::GetNameForHttpMethod(request.GetMethod()),\n ss.str().c_str(), nullptr, nullptr, accept, requestFlags, 0);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"HttpOpenRequestA returned handle \" << hHttpRequest);\n\n return hHttpRequest;\n}\n\nvoid WinINetSyncHttpClient::DoAddHeaders(void* hHttpRequest, Aws::String& headerStr) const\n{\n if (!HttpAddRequestHeadersA(hHttpRequest, headerStr.c_str(), (DWORD)headerStr.length(), HTTP_ADDREQ_FLAG_REPLACE | HTTP_ADDREQ_FLAG_ADD))\n AWS_LOGSTREAM_ERROR(GetLogTag(), \"Failed to add HTTP request headers with error code: \" << GetLastError());\n}\n\nuint64_t WinINetSyncHttpClient::DoWriteData(void* hHttpRequest, char* streamBuffer, uint64_t bytesRead) const\n{\n DWORD bytesWritten = 0;\n if(!InternetWriteFile(hHttpRequest, streamBuffer, (DWORD)bytesRead, &bytesWritten))\n {\n return 0;\n }\n\n return bytesWritten;\n}\n\nbool WinINetSyncHttpClient::DoReceiveResponse(void* hHttpRequest) const\n{\n return (HttpEndRequest(hHttpRequest, nullptr, 0, 0) != 0);\n}\n \nbool WinINetSyncHttpClient::DoQueryHeaders(void* hHttpRequest, std::shared_ptr& response, Aws::StringStream& ss, uint64_t& read) const\n{\n\n char dwStatusCode[256];\n DWORD dwSize = sizeof(dwStatusCode);\n\n HttpQueryInfoA(hHttpRequest, HTTP_QUERY_STATUS_CODE, &dwStatusCode, &dwSize, 0);\n response->SetResponseCode((HttpResponseCode)atoi(dwStatusCode));\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received response code \" << dwStatusCode);\n\n char contentTypeStr[1024];\n dwSize = sizeof(contentTypeStr);\n HttpQueryInfoA(hHttpRequest, HTTP_QUERY_CONTENT_TYPE, &contentTypeStr, &dwSize, 0);\n if (contentTypeStr[0] != NULL)\n {\n response->SetContentType(contentTypeStr);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received content type \" << contentTypeStr);\n }\n\n char headerStr[1024];\n dwSize = sizeof(headerStr);\n AWS_LOGSTREAM_DEBUG(GetLogTag(), \"Received headers:\");\n while (HttpQueryInfoA(hHttpRequest, HTTP_QUERY_RAW_HEADERS_CRLF, headerStr, &dwSize, (LPDWORD)&read) && dwSize > 0)\n {\n AWS_LOGSTREAM_DEBUG(GetLogTag(), headerStr);\n ss << headerStr;\n }\n return (read != 0);\n}\n\nbool WinINetSyncHttpClient::DoSendRequest(void* hHttpRequest) const\n{\n return (HttpSendRequestEx(hHttpRequest, NULL, NULL, 0, 0) != 0);\n}\n\nbool WinINetSyncHttpClient::DoReadData(void* hHttpRequest, char* body, uint64_t size, uint64_t& read) const\n{\n return (InternetReadFile(hHttpRequest, body, (DWORD)size, (LPDWORD)&read) != 0);\n}\n\nvoid* WinINetSyncHttpClient::GetClientModule() const\n{\n return GetModuleHandle(TEXT(\"wininet.dll\"));\n}\n<|endoftext|>"} {"text":"#include \"StackPlaneView.h\"\n#include \"StackSession.h\"\n#include \"StackPlaneController.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"QVTKWidget.h\"\n#include \n#include \n\nusing namespace NeuroProof;\nusing std::tr1::unordered_map;\n\nStackPlaneView::StackPlaneView(StackSession* stack_session_, \n StackPlaneController* controller_, QWidget* widget_parent_) : \n stack_session(stack_session_), controller(controller_),\n widget_parent(widget_parent_), renderWindowInteractor(0)\n{\n stack_session->attach_observer(this);\n} \n\nStackPlaneView::~StackPlaneView()\n{\n stack_session->detach_observer(this);\n if (qt_widget) {\n if (layout) {\n QLayoutItem * item;\n if ((item = layout->takeAt(0)) != 0) {\n layout->removeItem(item);\n }\n layout->removeWidget(qt_widget);\n delete layout;\n }\n delete qt_widget;\n }\n}\n \nvoid StackPlaneView::pan(int xdiff, int ydiff)\n{\n double viewFocus[4], viewPoint[3];\n\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n\n \/\/ use old focus and position points\n camera->GetFocalPoint(viewFocus);\n camera->GetPosition(viewPoint);\n \n camera->SetFocalPoint(xdiff + viewFocus[0], ydiff + viewFocus[1],\n viewFocus[2]);\n camera->SetPosition(xdiff + viewPoint[0], ydiff + viewPoint[1],\n viewPoint[2]);\n\n if (renderWindowInteractor->GetLightFollowCamera()) {\n renderer->UpdateLightsGeometryToFollowCamera();\n }\n renderWindowInteractor->Render();\n}\n\n\/\/ call update and create controller -- rag, gray, and labels must exist\nvoid StackPlaneView::initialize()\n{\n Stack* stack = stack_session->get_stack();\n\n VolumeLabelPtr labelvol = stack->get_labelvol(); \n VolumeGrayPtr grayvol = stack->get_grayvol();\n if (!grayvol) {\n throw ErrMsg(\"Cannot Initialize: no gray volume loaded\");\n }\n \n \/\/ load gray volume into vtk array\n grayarray = vtkSmartPointer::New();\n grayarray->SetArray(grayvol->begin(), grayvol->shape(0) * \n grayvol->shape(1) * grayvol->shape(2), 1);\n \n \/\/ load array into gray vtk image volume\n grayvtk = vtkSmartPointer::New();\n grayvtk->GetPointData()->SetScalars(grayarray); \n\n \/\/ set grayscale properties\n grayvtk->SetDimensions(grayvol->shape(0), grayvol->shape(1),\n grayvol->shape(2));\n grayvtk->SetScalarType(VTK_UNSIGNED_CHAR);\n grayvtk->SetSpacing(1, 1, 1); \/\/ hack for now; TODO: set res from stack?\n grayvtk->SetOrigin(0.0, 0.0, 0.0);\n\n graylookup = vtkSmartPointer::New();\n graylookup->SetNumberOfTableValues(256);\n graylookup->SetRange(0.0, 256);\n graylookup->SetHueRange(0.0,1.0);\n graylookup->SetValueRange(0.0,1.0);\n graylookup->Build();\n for (int i = 0; i < 256; ++i) {\n graylookup->SetTableValue(i, i\/255.0, i\/255.0, i\/255.0, 1);\n }\n gray_mapped = vtkSmartPointer::New();\n gray_mapped->SetInput(grayvtk);\n gray_mapped->SetLookupTable(graylookup);\n gray_mapped->Update();\n\n \/\/ rebase label volume and enable show all labels in a different color\n unsigned int * labels_rebase = new unsigned int [labelvol->shape(0) * \n labelvol->shape(1) * labelvol->shape(2)];\n unsigned int * iter = labels_rebase;\n Label_t max_label = 0;\n volume_forXYZ(*labelvol, x, y, z) {\n Label_t label = (*labelvol)(x,y,z);\n if (label > max_label) {\n max_label = label;\n }\n *iter++ = label;\n }\n \/\/ 32 bit array takes some time to load -- could convert the 32 bit\n \/\/ image to a 8 bit uchar for color\n labelarray = vtkSmartPointer::New();\n labelarray->SetArray(labels_rebase, labelvol->shape(0) * labelvol->shape(1) *\n labelvol->shape(2), 0);\n\n \/\/ set label options\n labelvtk = vtkSmartPointer::New();\n labelvtk->GetPointData()->SetScalars(labelarray);\n labelvtk->SetDimensions(labelvol->shape(0), labelvol->shape(1),\n labelvol->shape(2));\n labelvtk->SetScalarType(VTK_UNSIGNED_INT);\n labelvtk->SetSpacing(1, 1, 1);\n labelvtk->SetOrigin(0.0, 0.0, 0.0);\n\n \/\/ set lookup table\n label_lookup = vtkSmartPointer::New();\n label_lookup->SetNumberOfTableValues(max_label+1);\n label_lookup->SetRange( 0.0, max_label); \n label_lookup->SetHueRange( 0.0, 1.0 );\n label_lookup->SetValueRange( 0.0, 1.0 );\n label_lookup->Build();\n\n RagPtr rag = stack->get_rag();\n load_rag_colors(rag);\n \n \/\/ map colors for each label\n labelvtk_mapped = vtkSmartPointer::New();\n labelvtk_mapped->SetInput(labelvtk);\n labelvtk_mapped->SetLookupTable(label_lookup);\n labelvtk_mapped->Update();\n\n\n \/\/ blend both images\n vtkblend = vtkSmartPointer::New();\n vtkblend->AddInputConnection(gray_mapped->GetOutputPort());\n vtkblend->AddInputConnection(labelvtk_mapped->GetOutputPort());\n vtkblend->SetOpacity(0, 1);\n vtkblend->SetOpacity(1, 0.3);\n vtkblend->Update();\n \n \/\/ flip along y\n vtkblend_flipped = vtkSmartPointer::New();\n vtkblend_flipped->SetInputConnection(vtkblend->GetOutputPort());\n vtkblend_flipped->SetFilteredAxis(1);\n vtkblend_flipped->Update();\n\n\n \/\/ create 2D view\n viewer = vtkSmartPointer::New();\n viewer->SetColorLevel(127.5);\n viewer->SetColorWindow(255);\n viewer->SetInputConnection(vtkblend_flipped->GetOutputPort());\n\n \/\/qt widgets\n \n if (widget_parent) {\n layout = new QVBoxLayout;\n qt_widget = new QVTKWidget;\n layout->addWidget(qt_widget);\n widget_parent->setLayout(layout);\n \/\/qt_widget = new QVTKWidget(widget_parent);\n \/\/planeView->setGeometry(QRect(0, 0, 671, 571));\n } else {\n qt_widget = new QVTKWidget;\n }\n\n \/\/qt_widget->setObjectName(QString::fromUtf8(\"planeView\"));\n \/\/qt_widget->showMaximized();\n qt_widget->SetRenderWindow(viewer->GetRenderWindow());\n renderWindowInteractor = qt_widget->GetInteractor();\n\n viewer->SetupInteractor(renderWindowInteractor);\n viewer->Render();\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n initial_zoom = camera->GetParallelScale();\n}\n\nvoid StackPlaneView::load_rag_colors(RagPtr rag)\n{\n \/\/ compute different colors for each RAG node\n \/\/ using greedy graph coloring algorithm\n stack_session->compute_label_colors(rag);\n \n for (Rag_t::nodes_iterator iter = rag->nodes_begin();\n iter != rag->nodes_end(); ++iter) {\n int color_id = (*iter)->get_property(\"color\");\n unsigned char r, g, b;\n stack_session->get_rgb(color_id, r, g, b);\n label_lookup->SetTableValue((*iter)->get_node_id(), r\/255.0,\n g\/255.0, b\/255.0, 1);\n }\n}\n\nvoid StackPlaneView::start()\n{\n qt_widget->show();\n}\n\nvoid StackPlaneView::update()\n{\n bool show_all;\n unsigned int plane_id;\n Label_t select_id = 0;\n Label_t select_id_old = 0;\n Label_t ignore_label = 0;\n double rgba[4];\n unordered_map active_labels;\n\n bool show_all_change = stack_session->get_show_all(show_all);\n double opacity_val = 1.0;\n if (!show_all) {\n opacity_val = 0.0;\n }\n\n VolumeLabelPtr labelvol;\n RagPtr rag;\n if (stack_session->get_reset_stack(labelvol, rag)) {\n \/\/ rebase label volume and enable show all labels in a different color\n unsigned int * labels_rebase = new unsigned int [labelvol->shape(0) * labelvol->shape(1) * labelvol->shape(2)];\n unsigned int * iter = labels_rebase;\n Label_t max_label = 0;\n volume_forXYZ(*labelvol, x, y, z) {\n Label_t label = (*labelvol)(x,y,z);\n if (label > max_label) {\n max_label = label;\n }\n *iter++ = label;\n }\n label_lookup->SetNumberOfTableValues(max_label+1);\n label_lookup->SetRange(0.0, max_label); \n\n labelarray = vtkSmartPointer::New();\n labelarray->SetArray(labels_rebase, labelvol->shape(0) * labelvol->shape(1) *\n labelvol->shape(2), 0);\n labelvtk->GetPointData()->SetScalars(labelarray);\n\n load_rag_colors(rag); \n }\n\n unsigned int xloc, yloc;\n double zoom_factor;\n \/\/ grab zoom and set absolute -- zoom should be called on reset along with plane set\n if (stack_session->get_zoom_loc(xloc, yloc, zoom_factor)) {\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n\n double viewFocus[4], viewPoint[3];\n camera->GetFocalPoint(viewFocus);\n camera->GetPosition(viewPoint);\n\n unsigned ysize = stack_session->get_stack()->get_ysize();\n camera->SetFocalPoint(xloc, ysize - yloc - 1, viewFocus[2]);\n camera->SetPosition(xloc, ysize - yloc - 1, viewPoint[2]);\n \n \/\/camera->Zoom(2.0);\n camera->SetParallelScale(initial_zoom \/ zoom_factor);\n }\n\n \/\/ color selected labels, if nothing selected, color everything\n rag = stack_session->get_stack()->get_rag();\n if (stack_session->get_active_labels(active_labels)) {\n for (int i = 0; i < label_lookup->GetNumberOfTableValues(); ++i) {\n label_lookup->GetTableValue(i, rgba);\n rgba[3] = 0;\n label_lookup->SetTableValue(i, rgba);\n } \n for (unordered_map::iterator iter = active_labels.begin();\n iter != active_labels.end(); ++iter) {\n unsigned char r, g, b;\n stack_session->get_rgb(iter->second, r, g, b);\n label_lookup->SetTableValue(iter->first, r\/255.0,\n g\/255.0, b\/255.0, 1);\n }\n }\n\n \/\/ toggle color for clicked body label\n if (stack_session->get_select_label(select_id, select_id_old)) {\n if (select_id_old && (active_labels.empty() ||\n (active_labels.find(select_id_old) != active_labels.end())) ) {\n label_lookup->GetTableValue(select_id_old, rgba);\n rgba[3] = 1.0;\n label_lookup->SetTableValue(select_id_old, rgba);\n label_lookup->Modified();\n } \n }\n \n if (select_id) {\n \/\/ do not toggle this label on when doing global toggle\n ignore_label = select_id;\n }\n\n \/\/ toggle color for all bodies\n if (show_all_change) {\n double opacity_val = 1.0;\n if (!show_all) {\n opacity_val = 0.0;\n }\n double rgba[4];\n\n if (!active_labels.empty()) {\n for (unordered_map::iterator iter = active_labels.begin();\n iter != active_labels.end(); ++iter) {\n label_lookup->GetTableValue(iter->first, rgba);\n rgba[3] = opacity_val;\n label_lookup->SetTableValue(iter->first, rgba);\n }\n } else { \n for (int i = 0; i < label_lookup->GetNumberOfTableValues(); ++i) {\n label_lookup->GetTableValue(i, rgba);\n rgba[3] = opacity_val;\n label_lookup->SetTableValue(i, rgba);\n }\n }\n label_lookup->Modified();\n }\n\n if (ignore_label) {\n label_lookup->GetTableValue(ignore_label, rgba);\n rgba[3] = 0.0;\n label_lookup->SetTableValue(ignore_label, rgba);\n label_lookup->Modified();\n }\n\n \/\/ set the current plane\n if (stack_session->get_plane(plane_id)) {\n viewer->SetSlice(plane_id);\n }\n\n \/\/ set the current color opacity\n unsigned int curr_opacity = 0;\n if (stack_session->get_opacity(curr_opacity)) {\n vtkblend->SetOpacity(1, curr_opacity \/ 10.0);\n }\n\n viewer->Render();\n}\nexplicit cast of vigra to unsigned char#include \"StackPlaneView.h\"\n#include \"StackSession.h\"\n#include \"StackPlaneController.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \"QVTKWidget.h\"\n#include \n#include \n\nusing namespace NeuroProof;\nusing std::tr1::unordered_map;\n\nStackPlaneView::StackPlaneView(StackSession* stack_session_, \n StackPlaneController* controller_, QWidget* widget_parent_) : \n stack_session(stack_session_), controller(controller_),\n widget_parent(widget_parent_), renderWindowInteractor(0)\n{\n stack_session->attach_observer(this);\n} \n\nStackPlaneView::~StackPlaneView()\n{\n stack_session->detach_observer(this);\n if (qt_widget) {\n if (layout) {\n QLayoutItem * item;\n if ((item = layout->takeAt(0)) != 0) {\n layout->removeItem(item);\n }\n layout->removeWidget(qt_widget);\n delete layout;\n }\n delete qt_widget;\n }\n}\n \nvoid StackPlaneView::pan(int xdiff, int ydiff)\n{\n double viewFocus[4], viewPoint[3];\n\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n\n \/\/ use old focus and position points\n camera->GetFocalPoint(viewFocus);\n camera->GetPosition(viewPoint);\n \n camera->SetFocalPoint(xdiff + viewFocus[0], ydiff + viewFocus[1],\n viewFocus[2]);\n camera->SetPosition(xdiff + viewPoint[0], ydiff + viewPoint[1],\n viewPoint[2]);\n\n if (renderWindowInteractor->GetLightFollowCamera()) {\n renderer->UpdateLightsGeometryToFollowCamera();\n }\n renderWindowInteractor->Render();\n}\n\n\/\/ call update and create controller -- rag, gray, and labels must exist\nvoid StackPlaneView::initialize()\n{\n Stack* stack = stack_session->get_stack();\n\n VolumeLabelPtr labelvol = stack->get_labelvol(); \n VolumeGrayPtr grayvol = stack->get_grayvol();\n if (!grayvol) {\n throw ErrMsg(\"Cannot Initialize: no gray volume loaded\");\n }\n \n \/\/ load gray volume into vtk array\n grayarray = vtkSmartPointer::New();\n grayarray->SetArray((unsigned char *)(grayvol->begin()), grayvol->shape(0) * \n grayvol->shape(1) * grayvol->shape(2), 1);\n \n \/\/ load array into gray vtk image volume\n grayvtk = vtkSmartPointer::New();\n grayvtk->GetPointData()->SetScalars(grayarray); \n\n \/\/ set grayscale properties\n grayvtk->SetDimensions(grayvol->shape(0), grayvol->shape(1),\n grayvol->shape(2));\n grayvtk->SetScalarType(VTK_UNSIGNED_CHAR);\n grayvtk->SetSpacing(1, 1, 1); \/\/ hack for now; TODO: set res from stack?\n grayvtk->SetOrigin(0.0, 0.0, 0.0);\n\n graylookup = vtkSmartPointer::New();\n graylookup->SetNumberOfTableValues(256);\n graylookup->SetRange(0.0, 256);\n graylookup->SetHueRange(0.0,1.0);\n graylookup->SetValueRange(0.0,1.0);\n graylookup->Build();\n for (int i = 0; i < 256; ++i) {\n graylookup->SetTableValue(i, i\/255.0, i\/255.0, i\/255.0, 1);\n }\n gray_mapped = vtkSmartPointer::New();\n gray_mapped->SetInput(grayvtk);\n gray_mapped->SetLookupTable(graylookup);\n gray_mapped->Update();\n\n \/\/ rebase label volume and enable show all labels in a different color\n unsigned int * labels_rebase = new unsigned int [labelvol->shape(0) * \n labelvol->shape(1) * labelvol->shape(2)];\n unsigned int * iter = labels_rebase;\n Label_t max_label = 0;\n volume_forXYZ(*labelvol, x, y, z) {\n Label_t label = (*labelvol)(x,y,z);\n if (label > max_label) {\n max_label = label;\n }\n *iter++ = label;\n }\n \/\/ 32 bit array takes some time to load -- could convert the 32 bit\n \/\/ image to a 8 bit uchar for color\n labelarray = vtkSmartPointer::New();\n labelarray->SetArray(labels_rebase, labelvol->shape(0) * labelvol->shape(1) *\n labelvol->shape(2), 0);\n\n \/\/ set label options\n labelvtk = vtkSmartPointer::New();\n labelvtk->GetPointData()->SetScalars(labelarray);\n labelvtk->SetDimensions(labelvol->shape(0), labelvol->shape(1),\n labelvol->shape(2));\n labelvtk->SetScalarType(VTK_UNSIGNED_INT);\n labelvtk->SetSpacing(1, 1, 1);\n labelvtk->SetOrigin(0.0, 0.0, 0.0);\n\n \/\/ set lookup table\n label_lookup = vtkSmartPointer::New();\n label_lookup->SetNumberOfTableValues(max_label+1);\n label_lookup->SetRange( 0.0, max_label); \n label_lookup->SetHueRange( 0.0, 1.0 );\n label_lookup->SetValueRange( 0.0, 1.0 );\n label_lookup->Build();\n\n RagPtr rag = stack->get_rag();\n load_rag_colors(rag);\n \n \/\/ map colors for each label\n labelvtk_mapped = vtkSmartPointer::New();\n labelvtk_mapped->SetInput(labelvtk);\n labelvtk_mapped->SetLookupTable(label_lookup);\n labelvtk_mapped->Update();\n\n\n \/\/ blend both images\n vtkblend = vtkSmartPointer::New();\n vtkblend->AddInputConnection(gray_mapped->GetOutputPort());\n vtkblend->AddInputConnection(labelvtk_mapped->GetOutputPort());\n vtkblend->SetOpacity(0, 1);\n vtkblend->SetOpacity(1, 0.3);\n vtkblend->Update();\n \n \/\/ flip along y\n vtkblend_flipped = vtkSmartPointer::New();\n vtkblend_flipped->SetInputConnection(vtkblend->GetOutputPort());\n vtkblend_flipped->SetFilteredAxis(1);\n vtkblend_flipped->Update();\n\n\n \/\/ create 2D view\n viewer = vtkSmartPointer::New();\n viewer->SetColorLevel(127.5);\n viewer->SetColorWindow(255);\n viewer->SetInputConnection(vtkblend_flipped->GetOutputPort());\n\n \/\/qt widgets\n \n if (widget_parent) {\n layout = new QVBoxLayout;\n qt_widget = new QVTKWidget;\n layout->addWidget(qt_widget);\n widget_parent->setLayout(layout);\n \/\/qt_widget = new QVTKWidget(widget_parent);\n \/\/planeView->setGeometry(QRect(0, 0, 671, 571));\n } else {\n qt_widget = new QVTKWidget;\n }\n\n \/\/qt_widget->setObjectName(QString::fromUtf8(\"planeView\"));\n \/\/qt_widget->showMaximized();\n qt_widget->SetRenderWindow(viewer->GetRenderWindow());\n renderWindowInteractor = qt_widget->GetInteractor();\n\n viewer->SetupInteractor(renderWindowInteractor);\n viewer->Render();\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n initial_zoom = camera->GetParallelScale();\n}\n\nvoid StackPlaneView::load_rag_colors(RagPtr rag)\n{\n \/\/ compute different colors for each RAG node\n \/\/ using greedy graph coloring algorithm\n stack_session->compute_label_colors(rag);\n \n for (Rag_t::nodes_iterator iter = rag->nodes_begin();\n iter != rag->nodes_end(); ++iter) {\n int color_id = (*iter)->get_property(\"color\");\n unsigned char r, g, b;\n stack_session->get_rgb(color_id, r, g, b);\n label_lookup->SetTableValue((*iter)->get_node_id(), r\/255.0,\n g\/255.0, b\/255.0, 1);\n }\n}\n\nvoid StackPlaneView::start()\n{\n qt_widget->show();\n}\n\nvoid StackPlaneView::update()\n{\n bool show_all;\n unsigned int plane_id;\n Label_t select_id = 0;\n Label_t select_id_old = 0;\n Label_t ignore_label = 0;\n double rgba[4];\n unordered_map active_labels;\n\n bool show_all_change = stack_session->get_show_all(show_all);\n double opacity_val = 1.0;\n if (!show_all) {\n opacity_val = 0.0;\n }\n\n VolumeLabelPtr labelvol;\n RagPtr rag;\n if (stack_session->get_reset_stack(labelvol, rag)) {\n \/\/ rebase label volume and enable show all labels in a different color\n unsigned int * labels_rebase = new unsigned int [labelvol->shape(0) * labelvol->shape(1) * labelvol->shape(2)];\n unsigned int * iter = labels_rebase;\n Label_t max_label = 0;\n volume_forXYZ(*labelvol, x, y, z) {\n Label_t label = (*labelvol)(x,y,z);\n if (label > max_label) {\n max_label = label;\n }\n *iter++ = label;\n }\n label_lookup->SetNumberOfTableValues(max_label+1);\n label_lookup->SetRange(0.0, max_label); \n\n labelarray = vtkSmartPointer::New();\n labelarray->SetArray(labels_rebase, labelvol->shape(0) * labelvol->shape(1) *\n labelvol->shape(2), 0);\n labelvtk->GetPointData()->SetScalars(labelarray);\n\n load_rag_colors(rag); \n }\n\n unsigned int xloc, yloc;\n double zoom_factor;\n \/\/ grab zoom and set absolute -- zoom should be called on reset along with plane set\n if (stack_session->get_zoom_loc(xloc, yloc, zoom_factor)) {\n vtkRenderer * renderer = viewer->GetRenderer(); \n vtkCamera *camera = renderer->GetActiveCamera();\n\n double viewFocus[4], viewPoint[3];\n camera->GetFocalPoint(viewFocus);\n camera->GetPosition(viewPoint);\n\n unsigned ysize = stack_session->get_stack()->get_ysize();\n camera->SetFocalPoint(xloc, ysize - yloc - 1, viewFocus[2]);\n camera->SetPosition(xloc, ysize - yloc - 1, viewPoint[2]);\n \n \/\/camera->Zoom(2.0);\n camera->SetParallelScale(initial_zoom \/ zoom_factor);\n }\n\n \/\/ color selected labels, if nothing selected, color everything\n rag = stack_session->get_stack()->get_rag();\n if (stack_session->get_active_labels(active_labels)) {\n for (int i = 0; i < label_lookup->GetNumberOfTableValues(); ++i) {\n label_lookup->GetTableValue(i, rgba);\n rgba[3] = 0;\n label_lookup->SetTableValue(i, rgba);\n } \n for (unordered_map::iterator iter = active_labels.begin();\n iter != active_labels.end(); ++iter) {\n unsigned char r, g, b;\n stack_session->get_rgb(iter->second, r, g, b);\n label_lookup->SetTableValue(iter->first, r\/255.0,\n g\/255.0, b\/255.0, 1);\n }\n }\n\n \/\/ toggle color for clicked body label\n if (stack_session->get_select_label(select_id, select_id_old)) {\n if (select_id_old && (active_labels.empty() ||\n (active_labels.find(select_id_old) != active_labels.end())) ) {\n label_lookup->GetTableValue(select_id_old, rgba);\n rgba[3] = 1.0;\n label_lookup->SetTableValue(select_id_old, rgba);\n label_lookup->Modified();\n } \n }\n \n if (select_id) {\n \/\/ do not toggle this label on when doing global toggle\n ignore_label = select_id;\n }\n\n \/\/ toggle color for all bodies\n if (show_all_change) {\n double opacity_val = 1.0;\n if (!show_all) {\n opacity_val = 0.0;\n }\n double rgba[4];\n\n if (!active_labels.empty()) {\n for (unordered_map::iterator iter = active_labels.begin();\n iter != active_labels.end(); ++iter) {\n label_lookup->GetTableValue(iter->first, rgba);\n rgba[3] = opacity_val;\n label_lookup->SetTableValue(iter->first, rgba);\n }\n } else { \n for (int i = 0; i < label_lookup->GetNumberOfTableValues(); ++i) {\n label_lookup->GetTableValue(i, rgba);\n rgba[3] = opacity_val;\n label_lookup->SetTableValue(i, rgba);\n }\n }\n label_lookup->Modified();\n }\n\n if (ignore_label) {\n label_lookup->GetTableValue(ignore_label, rgba);\n rgba[3] = 0.0;\n label_lookup->SetTableValue(ignore_label, rgba);\n label_lookup->Modified();\n }\n\n \/\/ set the current plane\n if (stack_session->get_plane(plane_id)) {\n viewer->SetSlice(plane_id);\n }\n\n \/\/ set the current color opacity\n unsigned int curr_opacity = 0;\n if (stack_session->get_opacity(curr_opacity)) {\n vtkblend->SetOpacity(1, curr_opacity \/ 10.0);\n }\n\n viewer->Render();\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/*\n$Log: AliT0Preprocessor.cxx,v $\nRevision 1.8 2007\/12\/07 15:22:51 alla\nbug fixed by Alberto\n\nRevision 1.7 2007\/12\/06 16:35:24 alla\nnew bugs fixed by Tomek\n\nRevision 1.5 2007\/11\/23 19:28:52 alla\nbug fixed\n\nVersion 2.1 2007\/11\/21 \nPreprocessor storing data to OCDB (T.Malkiewicz)\n\nVersion 1.1 2006\/10 \nPreliminary test version (T.Malkiewicz)\n*\/ \n\/\/ T0 preprocessor:\n\/\/ 1) takes data from DCS and passes it to the class AliTOFDataDCS \n\/\/ for processing and writes the result to the Reference DB.\n\/\/ 2) takes data form DAQ (both from Laser Calibration and Physics runs), \n\/\/ processes it, and stores either to OCDB or to Reference DB.\n\n\n#include \"AliT0Preprocessor.h\"\n#include \"AliT0DataDCS.h\"\n#include \"AliT0CalibWalk.h\"\n#include \"AliT0CalibTimeEq.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \"AliT0Dqclass.h\"\n\n\nClassImp(AliT0Preprocessor)\n\n\/\/____________________________________________________\nAliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : \n AliPreprocessor(\"T00\", shuttle), \n fData(0)\n{\n \/\/constructor\n}\n\/\/____________________________________________________\n\nAliT0Preprocessor::~AliT0Preprocessor()\n{\n \/\/destructor\n delete fData;\n fData = 0;\n}\n\/\/____________________________________________________\n\nvoid AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)\n{\n \/\/ Creates AliT0DataDCS object\n AliPreprocessor::Initialize(run, startTime, endTime);\n AliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));\n fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);\n}\n\/\/____________________________________________________\n\nUInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )\n{\n \/\/ T0 preprocessor return codes:\n \/\/ return=0 : all ok\n \/\/ return=1 : no DCS input data \n \/\/ return=2 : failed to store DCS data\n \/\/ return=3 : no Laser data (Walk correction)\n \/\/ return=4 : failed to store OCDB time equalized data\n \/\/ return=5 : no DAQ input for OCDB\n \/\/ return=6 : failed to retrieve DAQ data from OCDB\n \/\/ return=7 : failed to store T0 OCDB data\n\n\tBool_t resultDCSMap=kFALSE;\n\tBool_t resultDCSStore=kFALSE;\n\tBool_t resultLaser=kFALSE;\n\tBool_t resultOnline=kFALSE; \n \n if(!dcsAliasMap)\n {\n Log(\"No DCS input data\");\n return 1;\n }\n else\n {\n\t \/* \n resultDCSMap=fData->ProcessData(*dcsAliasMap);\n if(!resultDCSMap)\n {\n Log(\"Error when processing DCS data\");\n return 2;\/\/ return error Code for processed DCS data not stored\n }\n else\n {\n AliCDBMetaData metaDataDCS;\n metaDataDCS.SetBeamPeriod(0);\n metaDataDCS.SetResponsible(\"Tomasz Malkiewicz\");\n metaDataDCS.SetComment(\"This preprocessor fills an AliTODataDCS object.\");\n AliInfo(\"Storing DCS Data\");\n resultDCSStore = Store(\"Calib\",\"DCSData\",fData, &metaDataDCS);\n if (!resultDCSStore)\n {\n Log(\"Some problems occurred while storing DCS data results in ReferenceDB\");\n return 2;\/\/ return error Code for processed DCS data not stored\n }\n\n }\n\t *\/\n }\n\n \/\/ processing DAQ\n\n TString runType = GetRunType();\n\n if(runType == \"STANDALONE\")\n {\n TList* list = GetFileSources(kDAQ, \"LASER\");\n if (list)\n {\n TIter iter(list);\n TObjString *source;\n while ((source = dynamic_cast (iter.Next())))\n {\n const char *laserFile = GetFile(kDAQ, \"LASER\", source->GetName());\n if (laserFile)\n {\n Log(Form(\"File with Id LASER found in source %s!\", source->GetName()));\n AliT0CalibWalk *laser = new AliT0CalibWalk();\n laser->MakeWalkCorrGraph(laserFile);\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Tomek&Michal\");\n metaData.SetComment(\"Walk correction from laser runs.\");\n\t\tresultLaser=Store(\"Calib\",\"Slewing_Walk\", laser, &metaData, 0, 1);\n delete laser;\n }\n else\n {\n Log(Form(\"Could not find file with Id LASER in source %s!\", source->GetName()));\n return 1;\n }\n }\n if (!resultLaser)\n {\n Log(\"No Laser Data stored\");\n return 3;\/\/return error code for failure in storing Laser Data\n }\n } else {\n\t \tLog(\"No sources found for id LASER!\");\n\t\treturn 1;\n\t }\n }\n else if(runType == \"PHYSICS\")\n {\n TList* listPhys = GetFileSources(kDAQ, \"PHYSICS\");\n if (listPhys)\n {\n TIter iter(listPhys);\n TObjString *sourcePhys;\n while ((sourcePhys = dynamic_cast (iter.Next())))\n {\n const char *filePhys = GetFile(kDAQ, \"PHYSICS\", sourcePhys->GetName());\n if (filePhys)\n {\n AliT0CalibTimeEq *online = new AliT0CalibTimeEq();\n online->Reset();\n online->ComputeOnlineParams(filePhys);\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Tomek&Michal\");\n metaData.SetComment(\"Time equalizing result.\");\n resultOnline = Store(\"Calib\",\"TimeDelay\", online, &metaData, 0, 1);\n delete online;\n }\n else\n {\n Log(Form(\"Could not find file with Id PHYSICS in source %s!\", sourcePhys->GetName()));\n return 1;\n }\n }\n if (!resultOnline)\n {\n Log(\"No Laser Data stored\");\n return 4;\/\/return error code for failure in storing OCDB Data\n }\n } else {\n\t \tLog(\"No sources found for id PHYSICS!\");\n\t\treturn 1;\n\t }\n }\n\n return 0;\n}\n remove DSC data from preprocessor\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\/*\n$Log: AliT0Preprocessor.cxx,v $\nRevision 1.8 2007\/12\/07 15:22:51 alla\nbug fixed by Alberto\n\nRevision 1.7 2007\/12\/06 16:35:24 alla\nnew bugs fixed by Tomek\n\nRevision 1.5 2007\/11\/23 19:28:52 alla\nbug fixed\n\nVersion 2.1 2007\/11\/21 \nPreprocessor storing data to OCDB (T.Malkiewicz)\n\nVersion 1.1 2006\/10 \nPreliminary test version (T.Malkiewicz)\n*\/ \n\/\/ T0 preprocessor:\n\/\/ 1) takes data from DCS and passes it to the class AliTOFDataDCS \n\/\/ for processing and writes the result to the Reference DB.\n\/\/ 2) takes data form DAQ (both from Laser Calibration and Physics runs), \n\/\/ processes it, and stores either to OCDB or to Reference DB.\n\n\n#include \"AliT0Preprocessor.h\"\n#include \"AliT0DataDCS.h\"\n#include \"AliT0CalibWalk.h\"\n#include \"AliT0CalibTimeEq.h\"\n\n#include \"AliCDBMetaData.h\"\n#include \"AliDCSValue.h\"\n#include \"AliLog.h\"\n\n#include \n#include \n#include \n#include \n#include \"AliT0Dqclass.h\"\n\n\nClassImp(AliT0Preprocessor)\n\n\/\/____________________________________________________\nAliT0Preprocessor::AliT0Preprocessor(AliShuttleInterface* shuttle) : \n AliPreprocessor(\"T00\", shuttle), \n fData(0)\n{\n \/\/constructor\n}\n\/\/____________________________________________________\n\nAliT0Preprocessor::~AliT0Preprocessor()\n{\n \/\/destructor\n delete fData;\n fData = 0;\n}\n\/\/____________________________________________________\n\nvoid AliT0Preprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime)\n{\n \/\/ Creates AliT0DataDCS object\n AliPreprocessor::Initialize(run, startTime, endTime);\n AliInfo(Form(\"\\n\\tRun %d \\n\\tStartTime %s \\n\\tEndTime %s\", run, TTimeStamp(startTime).AsString(), TTimeStamp(endTime).AsString()));\n fData = new AliT0DataDCS(fRun, fStartTime, fEndTime);\n}\n\/\/____________________________________________________\n\nUInt_t AliT0Preprocessor::Process(TMap* dcsAliasMap )\n{\n \/\/ T0 preprocessor return codes:\n \/\/ return=0 : all ok\n \/\/ return=1 : no DCS input data \n \/\/ return=2 : failed to store DCS data\n \/\/ return=3 : no Laser data (Walk correction)\n \/\/ return=4 : failed to store OCDB time equalized data\n \/\/ return=5 : no DAQ input for OCDB\n \/\/ return=6 : failed to retrieve DAQ data from OCDB\n \/\/ return=7 : failed to store T0 OCDB data\n\n\tBool_t resultDCSMap=kFALSE;\n\tBool_t resultDCSStore=kFALSE;\n\tBool_t resultLaser=kFALSE;\n\tBool_t resultOnline=kFALSE; \n \n if(!dcsAliasMap)\n {\n Log(\"No DCS input data\");\n \/\/ return 1;\n }\n else\n {\n\t \/* \n resultDCSMap=fData->ProcessData(*dcsAliasMap);\n if(!resultDCSMap)\n {\n Log(\"Error when processing DCS data\");\n return 2;\/\/ return error Code for processed DCS data not stored\n }\n else\n {\n AliCDBMetaData metaDataDCS;\n metaDataDCS.SetBeamPeriod(0);\n metaDataDCS.SetResponsible(\"Tomasz Malkiewicz\");\n metaDataDCS.SetComment(\"This preprocessor fills an AliTODataDCS object.\");\n AliInfo(\"Storing DCS Data\");\n resultDCSStore = Store(\"Calib\",\"DCSData\",fData, &metaDataDCS);\n if (!resultDCSStore)\n {\n Log(\"Some problems occurred while storing DCS data results in ReferenceDB\");\n return 2;\/\/ return error Code for processed DCS data not stored\n }\n\n }\n\t *\/\n\t Log(\"No DCS input data\");\n }\n\n \/\/ processing DAQ\n\n TString runType = GetRunType();\n\n if(runType == \"STANDALONE\")\n {\n TList* list = GetFileSources(kDAQ, \"LASER\");\n if (list)\n {\n TIter iter(list);\n TObjString *source;\n while ((source = dynamic_cast (iter.Next())))\n {\n const char *laserFile = GetFile(kDAQ, \"LASER\", source->GetName());\n if (laserFile)\n {\n Log(Form(\"File with Id LASER found in source %s!\", source->GetName()));\n AliT0CalibWalk *laser = new AliT0CalibWalk();\n laser->MakeWalkCorrGraph(laserFile);\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Tomek&Michal\");\n metaData.SetComment(\"Walk correction from laser runs.\");\n\t\tresultLaser=Store(\"Calib\",\"Slewing_Walk\", laser, &metaData, 0, 1);\n delete laser;\n }\n else\n {\n Log(Form(\"Could not find file with Id LASER in source %s!\", source->GetName()));\n return 1;\n }\n }\n if (!resultLaser)\n {\n Log(\"No Laser Data stored\");\n return 3;\/\/return error code for failure in storing Laser Data\n }\n } else {\n\t \tLog(\"No sources found for id LASER!\");\n\t\treturn 1;\n\t }\n }\n else if(runType == \"PHYSICS\")\n {\n TList* listPhys = GetFileSources(kDAQ, \"PHYSICS\");\n if (listPhys)\n {\n TIter iter(listPhys);\n TObjString *sourcePhys;\n while ((sourcePhys = dynamic_cast (iter.Next())))\n {\n const char *filePhys = GetFile(kDAQ, \"PHYSICS\", sourcePhys->GetName());\n if (filePhys)\n {\n AliT0CalibTimeEq *online = new AliT0CalibTimeEq();\n online->Reset();\n online->ComputeOnlineParams(filePhys);\n AliCDBMetaData metaData;\n metaData.SetBeamPeriod(0);\n metaData.SetResponsible(\"Tomek&Michal\");\n metaData.SetComment(\"Time equalizing result.\");\n resultOnline = Store(\"Calib\",\"TimeDelay\", online, &metaData, 0, 1);\n delete online;\n }\n else\n {\n Log(Form(\"Could not find file with Id PHYSICS in source %s!\", sourcePhys->GetName()));\n return 1;\n }\n }\n if (!resultOnline)\n {\n Log(\"No Laser Data stored\");\n return 4;\/\/return error code for failure in storing OCDB Data\n }\n } else {\n\t \tLog(\"No sources found for id PHYSICS!\");\n\t\treturn 1;\n\t }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#define __TUPLE_NAMESPACE foo\n\n#include \n#include \n#include \n\nint main()\n{\n using type0 = foo::tuple<>;\n assert(std::tuple_size::value == 0);\n assert((std::is_empty>::value == true));\n\n assert(type0{} == type0{});\n assert(!(type0{} != type0{}));\n assert(!(type0{} < type0{}));\n assert(!(type0{} > type0{}));\n\n using type1 = foo::tuple;\n assert(std::tuple_size::value == 1);\n assert((\n std::is_same<\n std::tuple_element_t<0,type1>,\n int\n >::value\n ));\n\n type1 t1;\n assert(std::get<0>(t1) == 0);\n\n type1 t2(13);\n assert(std::get<0>(t2) == 13);\n\n assert(t1 <= t2);\n assert(t1 < t2);\n\n assert(t2 >= t2);\n assert(t2 > t1);\n\n assert(t1 == t1);\n assert(t1 <= t1);\n assert(t1 >= t1);\n\n using type2 = foo::tuple;\n assert(std::tuple_size::value == 2);\n assert((\n std::is_same<\n std::tuple_element_t<0,type2>,\n int\n >::value\n ));\n assert((\n std::is_same<\n std::tuple_element_t<1,type2>,\n float\n >::value\n ));\n\n type2 t3;\n assert(std::get<0>(t3) == 0);\n assert(std::get<1>(t3) == 0);\n\n type2 t4(13,7);\n assert(std::get<0>(t4) == 13);\n assert(std::get<1>(t4) == 7);\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(t3)),\n int&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(t3)),\n float&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(static_cast(t3))),\n const int&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(static_cast(t3))),\n const float&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(std::move(t3))),\n int&&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(std::move(t3))),\n float&&\n >::value\n ));\n \n using type3 = foo::tuple;\n type3 t5(1,2,3);\n assert(std::get<0>(t5) == 1);\n assert(std::get<1>(t5) == 2);\n assert(std::get<2>(t5) == 3);\n\n type3 t6{};\n assert(std::get<0>(t6) == 0);\n assert(std::get<1>(t6) == 0);\n assert(std::get<2>(t6) == 0);\n\n assert(t5 != t6);\n assert(t5 > t6);\n assert(t6 < t5);\n assert(t5 >= t6);\n assert(t6 <= t5);\n\n t6 = t5;\n assert(std::get<0>(t6) == 1);\n assert(std::get<1>(t6) == 2);\n assert(std::get<2>(t6) == 3);\n\n assert(t5 == t6);\n assert(t5 <= t6);\n assert(t5 >= t6);\n\n using type4 = foo::tuple;\n type4 t7(type3(1,2,3), type3(4,5,6));\n assert(std::get<0>(std::get<0>(t7)) == 1);\n assert(std::get<1>(std::get<0>(t7)) == 2);\n assert(std::get<2>(std::get<0>(t7)) == 3);\n\n assert(std::get<0>(std::get<1>(t7)) == 4);\n assert(std::get<1>(std::get<1>(t7)) == 5);\n assert(std::get<2>(std::get<1>(t7)) == 6);\n\n type3 t8(1,2,3);\n assert(std::get<0>(t5) == 1);\n assert(std::get<1>(t5) == 2);\n assert(std::get<2>(t5) == 3);\n\n int a, b, c;\n foo::tie(a,b,c) = t5;\n assert(a == 1);\n assert(b == 2);\n assert(c == 3);\n\n assert(foo::tie(a,b,c) == t5);\n assert(foo::tie(a,b,c) <= t5);\n assert(foo::tie(a,b,c) >= t5);\n\n auto t9 = foo::make_tuple(std::string(\"hi\"));\n foo::tuple t10;\n t10 = std::move(t9);\n assert(std::get<0>(t9) == \"\");\n assert(std::get<0>(t10) == \"hi\");\n\n assert(foo::make_tuple(1,2,3) < foo::make_tuple(1,2,4));\n assert(foo::make_tuple(1,2,4) > foo::make_tuple(1,2,3));\n\n return 0;\n}\n\nensures that tuple&>::operator=(tuple&>) has not been deleted#define __TUPLE_NAMESPACE foo\n\n#include \n#include \n#include \n\nint main()\n{\n using type0 = foo::tuple<>;\n assert(std::tuple_size::value == 0);\n assert((std::is_empty>::value == true));\n\n assert(type0{} == type0{});\n assert(!(type0{} != type0{}));\n assert(!(type0{} < type0{}));\n assert(!(type0{} > type0{}));\n\n using type1 = foo::tuple;\n assert(std::tuple_size::value == 1);\n assert((\n std::is_same<\n std::tuple_element_t<0,type1>,\n int\n >::value\n ));\n\n type1 t1;\n assert(std::get<0>(t1) == 0);\n\n type1 t2(13);\n assert(std::get<0>(t2) == 13);\n\n assert(t1 <= t2);\n assert(t1 < t2);\n\n assert(t2 >= t2);\n assert(t2 > t1);\n\n assert(t1 == t1);\n assert(t1 <= t1);\n assert(t1 >= t1);\n\n using type2 = foo::tuple;\n assert(std::tuple_size::value == 2);\n assert((\n std::is_same<\n std::tuple_element_t<0,type2>,\n int\n >::value\n ));\n assert((\n std::is_same<\n std::tuple_element_t<1,type2>,\n float\n >::value\n ));\n\n type2 t3;\n assert(std::get<0>(t3) == 0);\n assert(std::get<1>(t3) == 0);\n\n type2 t4(13,7);\n assert(std::get<0>(t4) == 13);\n assert(std::get<1>(t4) == 7);\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(t3)),\n int&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(t3)),\n float&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(static_cast(t3))),\n const int&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(static_cast(t3))),\n const float&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<0>(std::move(t3))),\n int&&\n >::value\n ));\n\n\n assert((\n std::is_same<\n decltype(std::get<1>(std::move(t3))),\n float&&\n >::value\n ));\n \n using type3 = foo::tuple;\n type3 t5(1,2,3);\n assert(std::get<0>(t5) == 1);\n assert(std::get<1>(t5) == 2);\n assert(std::get<2>(t5) == 3);\n\n type3 t6{};\n assert(std::get<0>(t6) == 0);\n assert(std::get<1>(t6) == 0);\n assert(std::get<2>(t6) == 0);\n\n assert(t5 != t6);\n assert(t5 > t6);\n assert(t6 < t5);\n assert(t5 >= t6);\n assert(t6 <= t5);\n\n t6 = t5;\n assert(std::get<0>(t6) == 1);\n assert(std::get<1>(t6) == 2);\n assert(std::get<2>(t6) == 3);\n\n assert(t5 == t6);\n assert(t5 <= t6);\n assert(t5 >= t6);\n\n using type4 = foo::tuple;\n type4 t7(type3(1,2,3), type3(4,5,6));\n assert(std::get<0>(std::get<0>(t7)) == 1);\n assert(std::get<1>(std::get<0>(t7)) == 2);\n assert(std::get<2>(std::get<0>(t7)) == 3);\n\n assert(std::get<0>(std::get<1>(t7)) == 4);\n assert(std::get<1>(std::get<1>(t7)) == 5);\n assert(std::get<2>(std::get<1>(t7)) == 6);\n\n type3 t8(1,2,3);\n assert(std::get<0>(t5) == 1);\n assert(std::get<1>(t5) == 2);\n assert(std::get<2>(t5) == 3);\n\n int a, b, c;\n foo::tie(a,b,c) = t5;\n assert(a == 1);\n assert(b == 2);\n assert(c == 3);\n\n assert(foo::tie(a,b,c) == t5);\n assert(foo::tie(a,b,c) <= t5);\n assert(foo::tie(a,b,c) >= t5);\n\n auto t9 = foo::make_tuple(std::string(\"hi\"));\n foo::tuple t10;\n t10 = std::move(t9);\n assert(std::get<0>(t9) == \"\");\n assert(std::get<0>(t10) == \"hi\");\n\n assert(foo::make_tuple(1,2,3) < foo::make_tuple(1,2,4));\n assert(foo::make_tuple(1,2,4) > foo::make_tuple(1,2,3));\n\n auto x = foo::tie(b);\n x = x; \/\/ ensure that tuple&>::operator=(tuple&>) has not been deleted\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"service.h\"\n#include \"ev++.h\"\n#include \"control.h\"\n#include \"dinit-log.h\"\n\n#ifdef __linux__\n#include \n#endif\n\n\/* TODO: prevent services from respawning too quickly *\/\n\/* TODO: optional automatic restart of services *\/\n\n\/*\n * \"simpleinit\" from util-linux package handles signals as follows:\n * SIGTSTP - spawn no more gettys (in preparation for shutdown etc).\n * In dinit terms this should probably mean \"no more auto restarts\"\n * (for any service). (Actually the signal acts as a toggle, if\n * respawn is disabled it will be re-enabled and init will\n * act as if SIGHUP had also been sent)\n * SIGTERM - kill spawned gettys (which are still alive)\n * Interestingly, simpleinit just sends a SIGTERM to the gettys.\n * \"shutdown\" however has already sent SIGTERM to every process...\n * \"\/sbin\/initctl -r\" - rollback services (ran by \"shutdown\"\/halt etc)\n * shouldn't return until all services have been stopped.\n * shutdown calls this *after* sending SIGTERM to all processes.\n * I guess this allows user processes, if any are still around,\n * to die before (or just as) the services fall out from underneath\n * them. On the other hand it largely subverts the ordered service\n * shutdown that init provides.\n * SIGQUIT - init will exec() shutdown. shutdown will detect that it is\n * running as pid 1 and will just loop and reap child processes.\n * This is used by shutdown so that init will not hang on to its\n * inode, allowing the filesystem to be re-mounted readonly\n * (this is only an issue if the init binary has been unlinked,\n * since it's then holding an inode which can't be maintained\n * when the filesystem is unmounted).\n *\n * Not sent by shutdown:\n * SIGHUP - re-read inittab and spawn any new getty entries\n * SIGINT - (ctrl+alt+del handler) - fork & exec \"reboot\"\n * \n * On the contrary dinit currently uses:\n * SIGTERM - roll back services and then fork\/exec \/sbin\/halt\n * SIGINT - roll back services and then fork\/exec \/sbin\/reboot\n * SIGQUIT - exec() \/sbin\/shutdown as per above.\n *\n * It's an open question about whether dinit should roll back services *before*\n * running halt\/reboot, since those commands should prompt rollback of services\n * anyway. But it seems safe to do so.\n *\/\n\n\nstatic bool got_sigterm = false;\n\nstatic ServiceSet *service_set;\n\nstatic bool am_system_init = false; \/\/ true if we are the system init process\nstatic bool do_reboot = false; \/\/ whether to reboot (instead of halting)\n\nstatic bool control_socket_open = false;\nint active_control_conns = 0;\n\nstatic void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents);\nstatic void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents);\nstatic void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents);\n\nvoid open_control_socket(struct ev_loop *loop);\n\nstruct ev_io control_socket_io;\n\n\nint main(int argc, char **argv)\n{\n using namespace std;\n \n am_system_init = (getpid() == 1);\n \n if (am_system_init) {\n \/\/ setup STDIN, STDOUT, STDERR so that we can use them\n int onefd = open(\"\/dev\/console\", O_RDONLY, 0);\n dup2(onefd, 0);\n int twofd = open(\"\/dev\/console\", O_RDWR, 0);\n dup2(twofd, 1);\n dup2(twofd, 2);\n }\n \n \/* Set up signal handlers etc *\/\n \/* SIG_CHILD is ignored by default: good *\/\n \/* sigemptyset(&sigwait_set); *\/\n \/* sigaddset(&sigwait_set, SIGCHLD); *\/\n \/* sigaddset(&sigwait_set, SIGINT); *\/\n \/* sigaddset(&sigwait_set, SIGTERM); *\/\n \/* sigprocmask(SIG_BLOCK, &sigwait_set, NULL); *\/\n \n \/* list of services to start *\/\n list services_to_start;\n \n \/* service directory name *\/\n const char * service_dir = \"\/etc\/dinit.d\";\n \n \/\/ Arguments, if given, specify a list of services to start.\n \/\/ If we are running as init (PID=1), the kernel gives us any command line\n \/\/ arguments it was given but didn't recognize, including \"single\" (usually\n \/\/ for \"boot to single user mode\" aka just start the shell). We can treat\n \/\/ them as service names. In the worst case we can't find any of the named\n \/\/ services, and so we'll start the \"boot\" service by default.\n if (argc > 1) {\n for (int i = 1; i < argc; i++) {\n if (argv[i][0] == '-') {\n \/\/ An option...\n if (strcmp(argv[i], \"--services-dir\") == 0 ||\n strcmp(argv[i], \"-d\") == 0) {\n ++i;\n if (i < argc) {\n service_dir = argv[i];\n }\n else {\n \/\/ error TODO\n }\n }\n else if (strcmp(argv[i], \"--help\") == 0) {\n cout << \"dinit, an init with dependency management\" << endl;\n cout << \" --help : display help\" << endl;\n cout << \" --services-dir , -d : set base directory for service description files (-d )\" << endl;\n cout << \" : start service with name \" << endl;\n return 0;\n }\n else {\n \/\/ unrecognized\n if (! am_system_init) {\n cerr << \"Unrecognized option: \" << argv[i] << endl;\n return 1;\n }\n }\n }\n else {\n \/\/ LILO puts \"auto\" on the kernel command line for unattended boots; we'll filter it.\n if (! am_system_init || strcmp(argv[i], \"auto\") != 0) {\n services_to_start.push_back(argv[i]);\n }\n }\n }\n }\n \n if (services_to_start.empty()) {\n services_to_start.push_back(\"boot\");\n }\n\n \/\/ Set up signal handlers\n ev_signal sigint_ev_signal;\n if (am_system_init) {\n ev_signal_init(&sigint_ev_signal, sigint_reboot_cb, SIGINT);\n }\n else {\n ev_signal_init(&sigint_ev_signal, sigterm_cb, SIGINT);\n }\n \n ev_signal sigquit_ev_signal;\n if (am_system_init) {\n \/\/ PID 1: SIGQUIT exec's shutdown\n ev_signal_init(&sigquit_ev_signal, sigquit_cb, SIGQUIT);\n }\n else {\n \/\/ Otherwise: SIGQUIT terminates dinit\n ev_signal_init(&sigquit_ev_signal, sigterm_cb, SIGQUIT);\n }\n \n ev_signal sigterm_ev_signal;\n ev_signal_init(&sigterm_ev_signal, sigterm_cb, SIGTERM);\n \n \/* Set up libev *\/\n struct ev_loop *loop = ev_default_loop(EVFLAG_AUTO \/* | EVFLAG_SIGNALFD *\/);\n ev_signal_start(loop, &sigint_ev_signal);\n ev_signal_start(loop, &sigquit_ev_signal);\n ev_signal_start(loop, &sigterm_ev_signal);\n\n \/\/ Try to open control socket (may fail due to readonly filesystem)\n open_control_socket(loop);\n \n#ifdef __linux__\n if (am_system_init) {\n \/\/ Disable non-critical kernel output to console\n klogctl(6 \/* SYSLOG_ACTION_CONSOLE_OFF *\/, nullptr, 0);\n }\n#endif\n \n \/* start requested services *\/\n service_set = new ServiceSet(service_dir);\n for (list::iterator i = services_to_start.begin();\n i != services_to_start.end();\n ++i) {\n try {\n service_set->startService(*i);\n }\n catch (ServiceNotFound &snf) {\n log(LogLevel::ERROR, \"Could not find service description: \", snf.serviceName);\n }\n catch (ServiceLoadExc &sle) {\n log(LogLevel::ERROR, \"Problem loading service description: \", sle.serviceName);\n }\n }\n \n event_loop:\n \n \/\/ Process events until all services have terminated.\n while (service_set->count_active_services() != 0 || active_control_conns != 0) {\n ev_loop(loop, EVLOOP_ONESHOT);\n }\n \n if (am_system_init) {\n logMsgBegin(LogLevel::INFO, \"No more active services.\");\n if (do_reboot) {\n logMsgEnd(\" Will reboot.\");\n }\n else if (got_sigterm) {\n logMsgEnd(\" Will halt.\");\n }\n else {\n logMsgEnd(\" Re-initiating boot sequence.\");\n }\n }\n \n if (am_system_init) {\n if (do_reboot) {\n \/\/ TODO log error from fork\n if (fork() == 0) {\n execl(\"\/sbin\/reboot\", \"\/sbin\/reboot\", (char *) 0);\n }\n }\n else if (got_sigterm) {\n \/\/ TODO log error from fork\n if (fork() == 0) {\n execl(\"\/sbin\/halt\", \"\/sbin\/halt\", (char *) 0);\n }\n }\n else {\n \/\/ Hmmmmmm.\n \/\/ It could be that we started in single user mode, and the\n \/\/ user has now exited the shell. We'll try and re-start the\n \/\/ boot process...\n try {\n service_set->startService(\"boot\");\n goto event_loop; \/\/ yes, the \"evil\" goto\n }\n catch (...) {\n \/\/ Now WTF do we do? try to reboot\n log(LogLevel::ERROR, \"Could not start 'boot' service; rebooting.\");\n if (fork() == 0) {\n execl(\"\/sbin\/reboot\", \"\/sbin\/reboot\", (char *) 0);\n }\n }\n }\n \n \/\/ PID 1 should never exit:\n while (true) {\n pause();\n }\n }\n \n return 0;\n}\n\n\/\/ Callback for control socket\nstatic void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)\n{\n \/\/ TODO limit the number of active connections. Keep a tally, and disable the\n \/\/ control connection listening socket watcher if it gets high, and re-enable\n \/\/ it once it falls below the maximum.\n\n \/\/ Accept a connection\n int sockfd = w->fd;\n\n int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);\n\n if (newfd != -1) {\n try {\n new ControlConn(loop, service_set, newfd); \/\/ will delete itself when it's finished\n }\n catch (std::bad_alloc &bad_alloc_exc) {\n log(LogLevel::ERROR, \"Accepting control connection: Out of memory\");\n close(newfd);\n }\n }\n}\n\nvoid open_control_socket(struct ev_loop *loop)\n{\n if (! control_socket_open) {\n \/\/ TODO make this use a per-user address if PID != 1, and make the address\n \/\/ overridable from the command line\n\n const char * saddrname = \"\/dev\/dinitctl\";\n struct sockaddr_un name;\n\n if (am_system_init) {\n unlink(saddrname);\n }\n\n name.sun_family = AF_UNIX;\n strcpy(name.sun_path, saddrname); \/\/ TODO make this safe for long names\n int namelen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(saddrname);\n\n int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n if (sockfd == -1) {\n log(LogLevel::ERROR, \"Error creating control socket: \", strerror(errno));\n return;\n }\n\n if (bind(sockfd, (struct sockaddr *) &name, namelen) == -1) {\n log(LogLevel::ERROR, \"Error binding control socket: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n \/\/ No connections can be made until we listen, so it is fine to change the permissions now\n \/\/ (and anyway there is no way to atomically create the socket and set permissions):\n if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {\n log(LogLevel::ERROR, \"Error setting control socket permissions: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n if (listen(sockfd, 10) == -1) {\n log(LogLevel::ERROR, \"Error listening on control socket: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n control_socket_open = true;\n ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);\n ev_io_start(loop, &control_socket_io);\n }\n}\n\n\/* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) *\/\nstatic void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n do_reboot = true;\n log_to_console = true;\n service_set->stop_all_services();\n}\n\n\/* handle SIGQUIT (if we are system init) *\/\nstatic void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n \/\/ This allows remounting the filesystem read-only if the dinit binary has been\n \/\/ unlinked. In that case the kernel holds the binary open, so that it can't be\n \/\/ properly removed.\n execl(\"\/sbin\/shutdown\", \"\/sbin\/shutdown\", (char *) 0);\n log(LogLevel::ERROR, \"Error executing \/sbin\/shutdown: \", strerror(errno));\n}\n\n\/* handle SIGTERM - stop all services *\/\nstatic void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n got_sigterm = true;\n log_to_console = true;\n service_set->stop_all_services();\n}\nRemove functional TODO comments.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"service.h\"\n#include \"ev++.h\"\n#include \"control.h\"\n#include \"dinit-log.h\"\n\n#ifdef __linux__\n#include \n#endif\n\n\/*\n * \"simpleinit\" from util-linux package handles signals as follows:\n * SIGTSTP - spawn no more gettys (in preparation for shutdown etc).\n * In dinit terms this should probably mean \"no more auto restarts\"\n * (for any service). (Actually the signal acts as a toggle, if\n * respawn is disabled it will be re-enabled and init will\n * act as if SIGHUP had also been sent)\n * SIGTERM - kill spawned gettys (which are still alive)\n * Interestingly, simpleinit just sends a SIGTERM to the gettys.\n * \"shutdown\" however has already sent SIGTERM to every process...\n * \"\/sbin\/initctl -r\" - rollback services (ran by \"shutdown\"\/halt etc)\n * shouldn't return until all services have been stopped.\n * shutdown calls this *after* sending SIGTERM to all processes.\n * I guess this allows user processes, if any are still around,\n * to die before (or just as) the services fall out from underneath\n * them. On the other hand it largely subverts the ordered service\n * shutdown that init provides.\n * SIGQUIT - init will exec() shutdown. shutdown will detect that it is\n * running as pid 1 and will just loop and reap child processes.\n * This is used by shutdown so that init will not hang on to its\n * inode, allowing the filesystem to be re-mounted readonly\n * (this is only an issue if the init binary has been unlinked,\n * since it's then holding an inode which can't be maintained\n * when the filesystem is unmounted).\n *\n * Not sent by shutdown:\n * SIGHUP - re-read inittab and spawn any new getty entries\n * SIGINT - (ctrl+alt+del handler) - fork & exec \"reboot\"\n * \n * On the contrary dinit currently uses:\n * SIGTERM - roll back services and then fork\/exec \/sbin\/halt\n * SIGINT - roll back services and then fork\/exec \/sbin\/reboot\n * SIGQUIT - exec() \/sbin\/shutdown as per above.\n *\n * It's an open question about whether dinit should roll back services *before*\n * running halt\/reboot, since those commands should prompt rollback of services\n * anyway. But it seems safe to do so.\n *\/\n\n\nstatic bool got_sigterm = false;\n\nstatic ServiceSet *service_set;\n\nstatic bool am_system_init = false; \/\/ true if we are the system init process\nstatic bool do_reboot = false; \/\/ whether to reboot (instead of halting)\n\nstatic bool control_socket_open = false;\nint active_control_conns = 0;\n\nstatic void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents);\nstatic void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents);\nstatic void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents);\n\nvoid open_control_socket(struct ev_loop *loop);\n\nstruct ev_io control_socket_io;\n\n\nint main(int argc, char **argv)\n{\n using namespace std;\n \n am_system_init = (getpid() == 1);\n \n if (am_system_init) {\n \/\/ setup STDIN, STDOUT, STDERR so that we can use them\n int onefd = open(\"\/dev\/console\", O_RDONLY, 0);\n dup2(onefd, 0);\n int twofd = open(\"\/dev\/console\", O_RDWR, 0);\n dup2(twofd, 1);\n dup2(twofd, 2);\n }\n \n \/* Set up signal handlers etc *\/\n \/* SIG_CHILD is ignored by default: good *\/\n \/* sigemptyset(&sigwait_set); *\/\n \/* sigaddset(&sigwait_set, SIGCHLD); *\/\n \/* sigaddset(&sigwait_set, SIGINT); *\/\n \/* sigaddset(&sigwait_set, SIGTERM); *\/\n \/* sigprocmask(SIG_BLOCK, &sigwait_set, NULL); *\/\n \n \/* list of services to start *\/\n list services_to_start;\n \n \/* service directory name *\/\n const char * service_dir = \"\/etc\/dinit.d\";\n \n \/\/ Arguments, if given, specify a list of services to start.\n \/\/ If we are running as init (PID=1), the kernel gives us any command line\n \/\/ arguments it was given but didn't recognize, including \"single\" (usually\n \/\/ for \"boot to single user mode\" aka just start the shell). We can treat\n \/\/ them as service names. In the worst case we can't find any of the named\n \/\/ services, and so we'll start the \"boot\" service by default.\n if (argc > 1) {\n for (int i = 1; i < argc; i++) {\n if (argv[i][0] == '-') {\n \/\/ An option...\n if (strcmp(argv[i], \"--services-dir\") == 0 ||\n strcmp(argv[i], \"-d\") == 0) {\n ++i;\n if (i < argc) {\n service_dir = argv[i];\n }\n else {\n \/\/ error TODO\n }\n }\n else if (strcmp(argv[i], \"--help\") == 0) {\n cout << \"dinit, an init with dependency management\" << endl;\n cout << \" --help : display help\" << endl;\n cout << \" --services-dir , -d : set base directory for service description files (-d )\" << endl;\n cout << \" : start service with name \" << endl;\n return 0;\n }\n else {\n \/\/ unrecognized\n if (! am_system_init) {\n cerr << \"Unrecognized option: \" << argv[i] << endl;\n return 1;\n }\n }\n }\n else {\n \/\/ LILO puts \"auto\" on the kernel command line for unattended boots; we'll filter it.\n if (! am_system_init || strcmp(argv[i], \"auto\") != 0) {\n services_to_start.push_back(argv[i]);\n }\n }\n }\n }\n \n if (services_to_start.empty()) {\n services_to_start.push_back(\"boot\");\n }\n\n \/\/ Set up signal handlers\n ev_signal sigint_ev_signal;\n if (am_system_init) {\n ev_signal_init(&sigint_ev_signal, sigint_reboot_cb, SIGINT);\n }\n else {\n ev_signal_init(&sigint_ev_signal, sigterm_cb, SIGINT);\n }\n \n ev_signal sigquit_ev_signal;\n if (am_system_init) {\n \/\/ PID 1: SIGQUIT exec's shutdown\n ev_signal_init(&sigquit_ev_signal, sigquit_cb, SIGQUIT);\n }\n else {\n \/\/ Otherwise: SIGQUIT terminates dinit\n ev_signal_init(&sigquit_ev_signal, sigterm_cb, SIGQUIT);\n }\n \n ev_signal sigterm_ev_signal;\n ev_signal_init(&sigterm_ev_signal, sigterm_cb, SIGTERM);\n \n \/* Set up libev *\/\n struct ev_loop *loop = ev_default_loop(EVFLAG_AUTO \/* | EVFLAG_SIGNALFD *\/);\n ev_signal_start(loop, &sigint_ev_signal);\n ev_signal_start(loop, &sigquit_ev_signal);\n ev_signal_start(loop, &sigterm_ev_signal);\n\n \/\/ Try to open control socket (may fail due to readonly filesystem)\n open_control_socket(loop);\n \n#ifdef __linux__\n if (am_system_init) {\n \/\/ Disable non-critical kernel output to console\n klogctl(6 \/* SYSLOG_ACTION_CONSOLE_OFF *\/, nullptr, 0);\n }\n#endif\n \n \/* start requested services *\/\n service_set = new ServiceSet(service_dir);\n for (list::iterator i = services_to_start.begin();\n i != services_to_start.end();\n ++i) {\n try {\n service_set->startService(*i);\n }\n catch (ServiceNotFound &snf) {\n log(LogLevel::ERROR, \"Could not find service description: \", snf.serviceName);\n }\n catch (ServiceLoadExc &sle) {\n log(LogLevel::ERROR, \"Problem loading service description: \", sle.serviceName);\n }\n }\n \n event_loop:\n \n \/\/ Process events until all services have terminated.\n while (service_set->count_active_services() != 0 || active_control_conns != 0) {\n ev_loop(loop, EVLOOP_ONESHOT);\n }\n \n if (am_system_init) {\n logMsgBegin(LogLevel::INFO, \"No more active services.\");\n if (do_reboot) {\n logMsgEnd(\" Will reboot.\");\n }\n else if (got_sigterm) {\n logMsgEnd(\" Will halt.\");\n }\n else {\n logMsgEnd(\" Re-initiating boot sequence.\");\n }\n }\n \n if (am_system_init) {\n if (do_reboot) {\n \/\/ TODO log error from fork\n if (fork() == 0) {\n execl(\"\/sbin\/reboot\", \"\/sbin\/reboot\", (char *) 0);\n }\n }\n else if (got_sigterm) {\n \/\/ TODO log error from fork\n if (fork() == 0) {\n execl(\"\/sbin\/halt\", \"\/sbin\/halt\", (char *) 0);\n }\n }\n else {\n \/\/ Hmmmmmm.\n \/\/ It could be that we started in single user mode, and the\n \/\/ user has now exited the shell. We'll try and re-start the\n \/\/ boot process...\n try {\n service_set->startService(\"boot\");\n goto event_loop; \/\/ yes, the \"evil\" goto\n }\n catch (...) {\n \/\/ Now WTF do we do? try to reboot\n log(LogLevel::ERROR, \"Could not start 'boot' service; rebooting.\");\n if (fork() == 0) {\n execl(\"\/sbin\/reboot\", \"\/sbin\/reboot\", (char *) 0);\n }\n }\n }\n \n \/\/ PID 1 should never exit:\n while (true) {\n pause();\n }\n }\n \n return 0;\n}\n\n\/\/ Callback for control socket\nstatic void control_socket_cb(struct ev_loop *loop, ev_io *w, int revents)\n{\n \/\/ TODO limit the number of active connections. Keep a tally, and disable the\n \/\/ control connection listening socket watcher if it gets high, and re-enable\n \/\/ it once it falls below the maximum.\n\n \/\/ Accept a connection\n int sockfd = w->fd;\n\n int newfd = accept4(sockfd, nullptr, nullptr, SOCK_NONBLOCK | SOCK_CLOEXEC);\n\n if (newfd != -1) {\n try {\n new ControlConn(loop, service_set, newfd); \/\/ will delete itself when it's finished\n }\n catch (std::bad_alloc &bad_alloc_exc) {\n log(LogLevel::ERROR, \"Accepting control connection: Out of memory\");\n close(newfd);\n }\n }\n}\n\nvoid open_control_socket(struct ev_loop *loop)\n{\n if (! control_socket_open) {\n \/\/ TODO make this use a per-user address if PID != 1, and make the address\n \/\/ overridable from the command line\n\n const char * saddrname = \"\/dev\/dinitctl\";\n struct sockaddr_un name;\n\n if (am_system_init) {\n unlink(saddrname);\n }\n\n name.sun_family = AF_UNIX;\n strcpy(name.sun_path, saddrname); \/\/ TODO make this safe for long names\n int namelen = offsetof(struct sockaddr_un, sun_path) + 1 + strlen(saddrname);\n\n int sockfd = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);\n if (sockfd == -1) {\n log(LogLevel::ERROR, \"Error creating control socket: \", strerror(errno));\n return;\n }\n\n if (bind(sockfd, (struct sockaddr *) &name, namelen) == -1) {\n log(LogLevel::ERROR, \"Error binding control socket: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n \/\/ No connections can be made until we listen, so it is fine to change the permissions now\n \/\/ (and anyway there is no way to atomically create the socket and set permissions):\n if (chmod(saddrname, S_IRUSR | S_IWUSR) == -1) {\n log(LogLevel::ERROR, \"Error setting control socket permissions: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n if (listen(sockfd, 10) == -1) {\n log(LogLevel::ERROR, \"Error listening on control socket: \", strerror(errno));\n close(sockfd);\n return;\n }\n\n control_socket_open = true;\n ev_io_init(&control_socket_io, control_socket_cb, sockfd, EV_READ);\n ev_io_start(loop, &control_socket_io);\n }\n}\n\n\/* handle SIGINT signal (generated by kernel when ctrl+alt+del pressed) *\/\nstatic void sigint_reboot_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n do_reboot = true;\n log_to_console = true;\n service_set->stop_all_services();\n}\n\n\/* handle SIGQUIT (if we are system init) *\/\nstatic void sigquit_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n \/\/ This allows remounting the filesystem read-only if the dinit binary has been\n \/\/ unlinked. In that case the kernel holds the binary open, so that it can't be\n \/\/ properly removed.\n execl(\"\/sbin\/shutdown\", \"\/sbin\/shutdown\", (char *) 0);\n log(LogLevel::ERROR, \"Error executing \/sbin\/shutdown: \", strerror(errno));\n}\n\n\/* handle SIGTERM - stop all services *\/\nstatic void sigterm_cb(struct ev_loop *loop, ev_signal *w, int revents)\n{\n got_sigterm = true;\n log_to_console = true;\n service_set->stop_all_services();\n}\n<|endoftext|>"} {"text":"#include \nusing namespace std;\n\/\/ ROOT\n#include \n#include \n#include \n#include \nusing namespace TMath;\n\/\/ UNIC\n#include \n#include \nusing namespace UNIC;\n\/\/ MAD\n#include \nusing namespace MAD;\n\/\/ thin flat infinite plasma sheet\nint main(int argc, char** argv)\n{\n double dt=1e-7*ns; \/\/ large dt causes E to decrease too fast\n double dx=0.1*nm; \/\/ large dx may cause asymmetry \n double Ee=10000*volt\/cm;\n\n \/\/double mean=0, sigma=5*um, height=0.05\/nm\/nm; \/\/ Si\n double mean=0, sigma=3*nm, height=8e-8\/nm\/nm; \/\/ Ge\n bool norm;\n\n GeCrystal ge;\n double epsilon=ge.Epsilon()*epsilon0;\n double Q=Abs(electron_charge);\n \/\/double De=100*cm2\/s, Dh=50*cm2\/s;\n\n \/\/ initialize arrays\n const int N = 500;\n \/\/ p and n are number densities\n double x[2*N+1], p[2*N+1], n[2*N+1], E[2*N+1];\n for (int i=0; i<2*N+1; i++) {\n x[i]=(i-N)*dx;\n p[i]=n[i]=height*Gaus(x[i],mean=0,sigma,norm=kTRUE);\n E[i]=Ee;\n }\n \/\/ slopes\n double dp[2*N+1], dn[2*N+1], dE[2*N+1];\n for (int i=1; i<2*N; i++) {\n dp[i] = (p[i+1]-p[i-1])\/2;\n dn[i] = (n[i+1]-n[i-1])\/2;\n dE[i] = (E[i+1]-E[i-1])\/2;\n }\n dp[2*N] = dp[0] = 0;\n dn[2*N] = dn[0] = 0;\n dE[2*N] = dE[0] = 0;\n double d2p[2*N+1], d2n[2*N+1];\n for (int i=1; i<2*N; i++) {\n d2p[i] = (dp[i+1]-dp[i-1])\/2;\n d2n[i] = (dn[i+1]-dn[i-1])\/2;\n }\n d2p[2*N] = d2p[0] = 0;\n d2n[2*N] = d2n[0] = 0;\n\n double phi[2*N+1]; \/\/ weighting potential\n for (int i=0; i<2*N+1; i++) phi[i]=float(i)\/2\/N;\n\n \/\/ output\n TFile *output = new TFile(\"sheet.root\",\"recreate\");\n TTree *t = new TTree(\"t\",\"time slices\");\n t->Branch(\"x\",x,Form(\"x[%d]\/D\",2*N+1));\n t->Branch(\"p\",p,Form(\"p[%d]\/D\",2*N+1));\n t->Branch(\"n\",n,Form(\"n[%d]\/D\",2*N+1));\n t->Branch(\"E\",E,Form(\"E[%d]\/D\",2*N+1));\n t->Branch(\"dp\",dp,Form(\"dp[%d]\/D\",2*N+1));\n t->Branch(\"dn\",dn,Form(\"dn[%d]\/D\",2*N+1));\n t->Branch(\"dE\",dE,Form(\"dE[%d]\/D\",2*N+1));\n t->Branch(\"d2p\",d2p,Form(\"d2p[%d]\/D\",2*N+1));\n t->Branch(\"d2n\",d2n,Form(\"d2n[%d]\/D\",2*N+1));\n t->Branch(\"dx\",&dx,\"dx\/D\");\n t->Branch(\"dt\",&dt,\"dt\/D\");\n \/\/ save units into tree\n double CM3=cm3, CM=cm, UM=um, V=volt, SEC=s, NS=ns, NM=nm;\n t->Branch(\"cm3\",&CM3,\"cm3\/D\");\n t->Branch(\"V\",&V,\"V\/D\");\n t->Branch(\"cm\",&CM,\"cm\/D\");\n t->Branch(\"um\",&UM,\"um\/D\");\n t->Branch(\"nm\",&NM,\"nm\/D\");\n t->Branch(\"ns\",&NS,\"ns\/D\");\n t->Branch(\"s\",&SEC,\"s\/D\");\n t->Branch(\"eps\",&epsilon,\"eps\/D\");\n t->Branch(\"q\",&Q,\"q\/D\");\n\n int iStep=0, nSteps = 100;\n double time[1000]={0}, charge[1000]={0};\n\n \/\/ evolve\n if (argc>1) nSteps = atoi(argv[1]);\n \/\/double mu_e=1350*cm2\/volt\/s; \/\/ Si\n \/\/double mu_h=1350*cm2\/volt\/s; \/\/ Si\n double mu_e=40000*cm2\/volt\/s; \/\/ Ge\n double mu_h=40000*cm2\/volt\/s; \/\/ Ge\n t->Branch(\"mue\",&mu_e,\"mue\/D\");\n t->Branch(\"muh\",&mu_h,\"muh\/D\");\n while (iStepFill();\n \/\/ update charge\n for (int i=0; i<2*N+1; i++) {\n charge[iStep]+=(p[i]-n[i])*phi[i];\n }\n time[iStep]=iStep*dt;\n \/\/ update electron and hole distributions\n for (int i=0; i<2*N+1; i++) {\n\t double dn_dt = mu_e*(dn[i]\/dx*E[i]+n[i]*dE[i]\/dx);\n\t double dp_dt =-mu_h*(dp[i]\/dx*E[i]+p[i]*dE[i]\/dx);\n \/\/dn_dt+=De*d2n[i]\/dx\/dx;\n \/\/dp_dt+=Dh*d2p[i]\/dx\/dx;\n\t n[i]+=dn_dt*dt;\n\t p[i]+=dp_dt*dt;\n }\n \/\/ update electric field distribution\n for (int i=0; i<2*N+1; i++) {\n E[i]=0;\n for (int j=0; jWrite(\"t\",6);\n\n TGraph *g = new TGraph(nSteps,time,charge);\n g->Write(\"g\");\n\n output->Close();\n\n return 0;\n}\nstarted to mix course and fine grids#include \nusing namespace std;\n\/\/ ROOT\n#include \n#include \n#include \n#include \nusing namespace TMath;\n\/\/ UNIC\n#include \n#include \nusing namespace UNIC;\n\/\/ MAD\n#include \nusing namespace MAD;\n\n\/\/ parameters\ndouble dx;\ndouble dt=5e-7*ns; \/\/ large dt causes E to decrease too fast\ndouble Ee=1000*volt\/cm;\ndouble R=1.97e-7*cm, mean=0, sigma=R\/3, height=84.\/(Pi()*R*R);\n\nconst int Nmidd = 50; \/\/ # of points in (0,5*sigma)\nconst int Nwing = 95; \/\/ # of points in (5*sigma, 100*sigma)\nconst int Ntotal = 2*(Nmidd + Nwing) + 1;\n\nGeCrystal ge;\ndouble epsilon=ge.Epsilon()*epsilon0;\ndouble Q=Abs(electron_charge);\n\n\/\/ df at i\ndouble d(double *f, int i)\n{\n if (i<1 || i>Ntotal-1) return 0;\n return (f[i+1]-f[i-1])\/2; \/\/ 2 points\n \/\/if (i<2 || i>Ntotal-2) return 0;\n \/\/return (-f[i+2]+8*f[i+1]-8*f[i-1]+f[i-2])\/12; \/\/ 4\n \/\/if (i<4 || i>Ntotal-4) return 0;\n \/\/return (-f[i+4]-8*f[i+2]+128*f[i+1]-128*f[i-1]+8*f[i-2]+f[i-4])\/180; \/\/ 6\n}\n\n\/\/ thin flat infinite plasma sheet\nint main(int argc, char** argv)\n{\n \/\/ initialize arrays\n double x[Ntotal], E[Ntotal], p[Ntotal], n[Ntotal], pE[Ntotal], nE[Ntotal];\n for (int i=0; i<=Nwing; i++) { \/\/ wings\n dx = sigma;\n x[i]=-100*sigma + i*dx;\n x[Ntotal-1-i]= 100*sigma - i*dx;\n p[i]=n[i]=height*Gaus(x[i],mean=0,sigma,kTRUE);\n p[Ntotal-1-i]=height*Gaus(x[Ntotal-1-i],mean=0,sigma,kTRUE);\n n[Ntotal-1-i]=height*Gaus(x[Ntotal-1-i],mean=0,sigma,kTRUE);\n E[i]=E[Ntotal-1-i]=Ee;\n pE[i]=p[i]*E[i];\n nE[i]=n[i]*E[i];\n pE[Ntotal-1-i]=p[Ntotal-1-i]*E[Ntotal-1-i];\n nE[Ntotal-1-i]=n[Ntotal-1-i]*E[Ntotal-1-i];\n }\n for (int i=Nwing+1; iBranch(\"x\",x,Form(\"x[%d]\/D\",Ntotal));\n t->Branch(\"p\",p,Form(\"p[%d]\/D\",Ntotal));\n t->Branch(\"n\",n,Form(\"n[%d]\/D\",Ntotal));\n t->Branch(\"E\",E,Form(\"E[%d]\/D\",Ntotal));\n t->Branch(\"dt\",&dt,\"dt\/D\");\n \/\/ save units into tree\n double V=volt, nanosec=ns, nanometer=nm;\n t->Branch(\"V\",&V,\"V\/D\");\n t->Branch(\"nm\",&nanometer,\"nm\/D\");\n t->Branch(\"ns\",&nanosec,\"ns\/D\");\n\n \/\/ evolve\n int iStep=0, nSteps = 100;\n if (argc>1) nSteps = atoi(argv[1]);\n while (iStepFill();\n for (int i=0; iWrite(\"t\",6);\n\n output->Close();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"common\/common.h\"\n#include \"common\/input_output.h\"\n#include \"common\/parser.h\"\n#include \"common\/generation.h\"\nChVector<> lpos(0, 0, 0);\nChQuaternion<> quat(1, 0, 0, 0);\n\n\/\/all dimensions are in millimeters, milligrams\nreal container_width = 5;\t\t\/\/width of area with particles\nreal container_length = 25;\t\t\/\/length of area that roller will go over\t\t1194mm maximum\nreal container_thickness = .25; \/\/thickness of container walls\nreal container_height = 2;\t\t\/\/height of the outer walls\nreal container_friction = 0;\nreal floor_friction = .2;\nreal spacer_width = 1;\nreal spacer_height = 1;\n\nreal roller_overlap = 1; \t\t\/\/amount that roller goes over the container area\nreal roller_length = 2.5-.25;\t\t\t\/\/length of the roller\nreal roller_radius = 76.2 \/ 2.0;\t\t\t\/\/radius of roller\nreal roller_omega = 0;\nreal roller_velocity = -127;\nreal roller_mass = 1;\nreal roller_friction = .2;\nreal roller_cohesion = 0;\nreal particle_radius = .058 \/ 2.0;\nreal particle_std_dev = .015 \/ 2.0;\nreal particle_mass = .05;\nreal particle_density = 0.446;\nreal particle_layer_thickness = particle_radius * 6;\nreal particle_friction = .1;\nreal gravity = -9810;\t\t\t\/\/acceleration due to gravity\nreal timestep = .00002;\t\t\t\/\/step size\nreal time_to_run = 1;\t\t\t\/\/length of simulation\nreal current_time = 0;\n\nint num_steps = time_to_run \/ timestep;\nint max_iteration = 15;\nint tolerance = 0;\n\nstring data_folder = \"data\/sls\";\nChSharedBodyPtr ROLLER;\nreal ang = 0;\n\ntemplate\nvoid RunTimeStep(T* mSys, const int frame) {\n\tChVector<> roller_pos = ROLLER->GetPos();\n\n\tROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep));\n\tROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));\n\troller_omega = roller_velocity \/ roller_radius;\n\tang += roller_omega * timestep;\n\tif (ang >= 2 * CH_C_PI) {\n\t\tang = 0;\n\t}\n\n\tQuaternion q1;\n\tq1.Q_from_AngY(ang);\n\tQuaternion q2;\n\tq1 = Q_from_AngX(-ang);\n\n\tChQuaternion<> roller_quat;\n\troller_quat.Q_from_AngAxis(PI \/ 2.0, ChVector<>(0, 0, 1));\n\n\tROLLER->SetRot(q1 % roller_quat);\n\tROLLER->SetWvel_loc(Vector(0, roller_omega, 0));\n\n}\nint main(int argc, char* argv[]) {\n\tbool visualize = false;\n\tint threads = 0;\n\n\tif (argc > 1) {\n\t\tthreads = atoi(argv[1]);\n\t\tomp_set_num_threads(threads);\n\n\t\tvisualize = atoi(argv[2]);\n\t\t\/\/visualize\n\t\t\/\/distribution_type\n\t\t\/\/min_radius\n\t\t\/\/max_radius\n\t\t\/\/mass\n\t\t\/\/friction\n\t\t\/\/cohesion\n\t\t\/\/layer_thickness\n\t\t\/\/roller_velocity\n\t\t\/\/roller_omega\n\t\t\/\/roller_friction\n\t\t\/\/roller_cohesion\n\n\t}\n\n\t\/\/cout << \"Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration\" << endl;\n\t\/\/string solver_string = \"ACCELERATED_PROJECTED_GRADIENT_DESCENT\";\n\t\/\/=========================================================================================================\n\tChSystemGPU * system_gpu = new ChSystemGPU;\n\tsystem_gpu->SetIntegrationType(ChSystem::INT_ANITESCU);\n\n\t\/\/=========================================================================================================\n\n\tsystem_gpu->SetMaxiter(max_iteration);\n\tsystem_gpu->SetIterLCPmaxItersSpeed(max_iteration);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration);\n\tsystem_gpu->SetTol(0);\n\tsystem_gpu->SetTolSpeeds(0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT);\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05);\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(40, 20, 200));\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50);\n\tsystem_gpu->Set_G_acc(ChVector<>(0, gravity, 0));\n\tsystem_gpu->SetStep(timestep);\n\n\t\/\/=========================================================================================================\n\tsystem_gpu->Set_G_acc(ChVector<>(0, gravity, 0));\n\tsystem_gpu->SetStep(timestep);\n\t\/\/=========================================================================================================\n\n\tChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\n\tChSharedPtr material_plate;\n\tmaterial_plate = ChSharedPtr(new ChMaterialSurface);\n\tmaterial_plate->SetFriction(floor_friction);\n\n\tInitObject(PLATE, 100000, ChVector<>(0, 0, 0), quat, material_plate, true, true, -20, -20);\n\n\tChSharedPtr material;\n\tmaterial = ChSharedPtr(new ChMaterialSurface);\n\tmaterial->SetFriction(container_friction);\n\n\t\/\/InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20);\n\t\/\/InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20);\n\t\/\/InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20);\n\n\tAddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness), quat);\n\t\/\/AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat);\n\t\/\/AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat);\n\n\tFinalizeObject(PLATE, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(L, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(R, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(F, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(B, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu);\n\n\tROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChQuaternion<> roller_quat;\n\troller_quat.Q_from_AngAxis(PI \/ 2.0, ChVector<>(0, 0, 1));\n\n\tChSharedPtr material_roller;\n\tmaterial_roller = ChSharedPtr(new ChMaterialSurface);\n\tmaterial_roller->SetFriction(roller_friction);\n\n\tInitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius\/3.0), roller_quat, material_roller, true, false, -20, -20);\n\tAddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat);\n\tFinalizeObject(ROLLER, (ChSystemGPU *) system_gpu);\n\t\/\/68\n\tint3 num_per_dir = I3(68 * 2, 6, 540 * 2);\n\t\/\/num_per_dir = I3(1, 8, 440);\n\tnum_per_dir = I3(74, 8,440);\n\tParticleGenerator layer_gen(system_gpu);\n\tlayer_gen.SetDensity(particle_density);\n\tlayer_gen.SetRadius(R3(particle_radius));\n\tlayer_gen.SetNormalDistribution(particle_radius, particle_std_dev);\n\tlayer_gen.material->SetFriction(particle_friction);\n\tlayer_gen.addPerturbedVolume(R3(0, .7, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));\n\tnum_per_dir = I3(74, 30, 50);\n\t\/\/num_per_dir = I3(1, 30, 50);\n\tlayer_gen.addPerturbedVolume(R3(0, 2.8, 15), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));\n\n\t\/\/=========================================================================================================\n\t\/\/\/\/\/\/Rendering specific stuff:\n\tif (visualize) {\n\t\tChOpenGLManager * window_manager = new ChOpenGLManager();\n\t\tChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, \"Test_Solvers\");\n\t\topenGLView.render_camera->camera_pos = Vector(-50, 0, -50);\n\t\topenGLView.render_camera->look_at = Vector(0, 0, 0);\n\t\topenGLView.SetCustomCallback(RunTimeStep);\n\t\topenGLView.StartSpinning(window_manager);\n\t\twindow_manager->CallGlutMainLoop();\n\t}\n\t\/\/=========================================================================================================\n\tstringstream ss_m;\n\tss_m << data_folder << \"\/\" << \"timing.txt\";\n\tstring timing_file_name = ss_m.str();\n\tofstream ofile(timing_file_name.c_str());\n\tofile.close();\n\tint file = 0;\n\tfor (int i = 0; i < num_steps; i++) {\n\t\tcout << \"step \" << i;\n\t\tcout << \" Residual: \" << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual();\n\t\tcout << \" ITER: \" << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations();\n\t\tcout << \" OUTPUT STEP: Time= \" << current_time << \" bodies= \" << system_gpu->GetNbodies() << \" contacts= \" << system_gpu->GetNcontacts() << \" step time=\" << system_gpu->GetTimerStep()\n\t\t\t\t<< \" lcp time=\" << system_gpu->GetTimerLcp() << \" CDbroad time=\" << system_gpu->GetTimerCollisionBroad() << \" CDnarrow time=\" << system_gpu->GetTimerCollisionNarrow() << \" Iterations=\"\n\t\t\t\t<< ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << \"\\n\";\n\t\t\/\/TimingFile(system_gpu, timing_file_name, current_time);\n\t\tsystem_gpu->DoStepDynamics(timestep);\n\t\tRunTimeStep(system_gpu, i);\n\t\tint save_every = 1.0 \/ timestep \/ 6000.0; \/\/save data every n steps\n\t\tif (i % save_every == 0) {\n\t\t\tstringstream ss;\n\t\t\tcout << \"Frame: \" << file << endl;\n\t\t\tss << data_folder << \"\/\" << file << \".txt\";\n\t\t\tDumpAllObjectsWithGeometryPovray(system_gpu, ss.str());\n\t\t\t\/\/output.ExportData(ss.str());\n\t\t\tfile++;\n\t\t}\n\t\tcurrent_time += timestep;\n\t}\n\tstringstream ss;\n\t\/\/ss << data_folder << \"\/\" << particle_friction << \"_\" << plate_friction << \"_\" << create_particle_plate << \".txt\";\n\n\t\/\/DumpAllObjectsWithGeometry(system_gpu, ss.str());\n\treturn 0;\n}\n\nAdded AABB inactive pruning to help with instability#include \"common\/common.h\"\n#include \"common\/input_output.h\"\n#include \"common\/parser.h\"\n#include \"common\/generation.h\"\nChVector<> lpos(0, 0, 0);\nChQuaternion<> quat(1, 0, 0, 0);\n\n\/\/all dimensions are in millimeters, milligrams\nreal container_width = 5;\t\t\/\/width of area with particles\nreal container_length = 25;\t\t\/\/length of area that roller will go over\t\t1194mm maximum\nreal container_thickness = .25; \/\/thickness of container walls\nreal container_height = 2;\t\t\/\/height of the outer walls\nreal container_friction = 0;\nreal floor_friction = .2;\nreal spacer_width = 1;\nreal spacer_height = 1;\n\nreal roller_overlap = 1; \t\t\/\/amount that roller goes over the container area\nreal roller_length = 2.5-.25;\t\t\t\/\/length of the roller\nreal roller_radius = 76.2 \/ 2.0;\t\t\t\/\/radius of roller\nreal roller_omega = 0;\nreal roller_velocity = -127;\nreal roller_mass = 1;\nreal roller_friction = .2;\nreal roller_cohesion = 0;\nreal particle_radius = .058 \/ 2.0;\nreal particle_std_dev = .015 \/ 2.0;\nreal particle_mass = .05;\nreal particle_density = 0.446;\nreal particle_layer_thickness = particle_radius * 6;\nreal particle_friction = .1;\nreal gravity = -9810;\t\t\t\/\/acceleration due to gravity\nreal timestep = .00001;\t\t\t\/\/step size\nreal time_to_run = 1;\t\t\t\/\/length of simulation\nreal current_time = 0;\n\nint num_steps = time_to_run \/ timestep;\nint max_iteration = 15;\nint tolerance = 0;\n\nstring data_folder = \"data\/sls\";\nChSharedBodyPtr ROLLER;\nreal ang = 0;\n\ntemplate\nvoid RunTimeStep(T* mSys, const int frame) {\n\tChVector<> roller_pos = ROLLER->GetPos();\n\n\tROLLER->SetPos(ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, roller_pos.z + roller_velocity * timestep));\n\tROLLER->SetPos_dt(ChVector<>(0, 0, roller_velocity));\n\troller_omega = roller_velocity \/ roller_radius;\n\tang += roller_omega * timestep;\n\tif (ang >= 2 * CH_C_PI) {\n\t\tang = 0;\n\t}\n\n\tQuaternion q1;\n\tq1.Q_from_AngY(ang);\n\tQuaternion q2;\n\tq1 = Q_from_AngX(-ang);\n\n\tChQuaternion<> roller_quat;\n\troller_quat.Q_from_AngAxis(PI \/ 2.0, ChVector<>(0, 0, 1));\n\n\tROLLER->SetRot(q1 % roller_quat);\n\tROLLER->SetWvel_loc(Vector(0, roller_omega, 0));\n\n}\nint main(int argc, char* argv[]) {\n\tbool visualize = false;\n\tint threads = 0;\n\n\tif (argc > 1) {\n\t\tthreads = atoi(argv[1]);\n\t\tomp_set_num_threads(threads);\n\n\t\tvisualize = atoi(argv[2]);\n\t\t\/\/visualize\n\t\t\/\/distribution_type\n\t\t\/\/min_radius\n\t\t\/\/max_radius\n\t\t\/\/mass\n\t\t\/\/friction\n\t\t\/\/cohesion\n\t\t\/\/layer_thickness\n\t\t\/\/roller_velocity\n\t\t\/\/roller_omega\n\t\t\/\/roller_friction\n\t\t\/\/roller_cohesion\n\n\t}\n\n\t\/\/cout << \"Mass, Radius, Friction_Sphere, Friction_Plate, Data Folder, create_particle_plate all_three_kinds, particle configuration\" << endl;\n\t\/\/string solver_string = \"ACCELERATED_PROJECTED_GRADIENT_DESCENT\";\n\t\/\/=========================================================================================================\n\tChSystemGPU * system_gpu = new ChSystemGPU;\n\tsystem_gpu->SetIntegrationType(ChSystem::INT_ANITESCU);\n\n\t\/\/=========================================================================================================\n\n\tsystem_gpu->SetMaxiter(max_iteration);\n\tsystem_gpu->SetIterLCPmaxItersSpeed(max_iteration);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetMaxIteration(max_iteration);\n\tsystem_gpu->SetTol(0);\n\tsystem_gpu->SetTolSpeeds(0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetTolerance(0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetCompliance(0, 0, 0);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetContactRecoverySpeed(300);\n\t((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->SetSolverType(ACCELERATED_PROJECTED_GRADIENT_DESCENT);\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->SetCollisionEnvelope(particle_radius * .05);\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBinsPerAxis(R3(40, 20, 200));\n\t((ChCollisionSystemGPU *) (system_gpu->GetCollisionSystem()))->setBodyPerBin(100, 50);\n\tsystem_gpu->Set_G_acc(ChVector<>(0, gravity, 0));\n\tsystem_gpu->SetStep(timestep);\n\n\t\/\/=========================================================================================================\n\tsystem_gpu->Set_G_acc(ChVector<>(0, gravity, 0));\n\tsystem_gpu->SetStep(timestep);\n\t\/\/=========================================================================================================\n\t ((ChSystemGPU*) system_gpu)->SetAABB(R3(-6,-3,-30), R3(6,5,30));\n\n\n\tChSharedBodyPtr PLATE = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr F = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr B = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr SPACER_L = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChSharedBodyPtr SPACER_R = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\n\tChSharedPtr material_plate;\n\tmaterial_plate = ChSharedPtr(new ChMaterialSurface);\n\tmaterial_plate->SetFriction(floor_friction);\n\n\tInitObject(PLATE, 100000, ChVector<>(0, 0, 0), quat, material_plate, true, true, -20, -20);\n\n\tChSharedPtr material;\n\tmaterial = ChSharedPtr(new ChMaterialSurface);\n\tmaterial->SetFriction(container_friction);\n\n\t\/\/InitObject(L, 100000, Vector(-container_width + container_thickness, container_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(R, 100000, Vector(container_width - container_thickness, container_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(F, 100000, Vector(0, container_height, -container_length + container_thickness), quat, material, true, true, -20, -20);\n\t\/\/InitObject(B, 100000, Vector(0, container_height, container_length - container_thickness), quat, material, true, true, -20, -20);\n\t\/\/InitObject(SPACER_L, 100000, Vector(-container_width + container_thickness * 2 + spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20);\n\t\/\/InitObject(SPACER_R, 100000, Vector(container_width - container_thickness * 2 - spacer_width, container_thickness + spacer_height, 0), quat, material, true, true, -20, -20);\n\n\tAddCollisionGeometry(PLATE, BOX, ChVector<>(container_width, container_thickness, container_length), lpos, quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(-container_width + container_thickness, container_height, 0), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_thickness, container_height, container_length), Vector(container_width - container_thickness, container_height, 0), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, -container_length + container_thickness), quat);\n\tAddCollisionGeometry(PLATE, BOX, Vector(container_width, container_height, container_thickness), Vector(0, container_height, container_length - container_thickness), quat);\n\t\/\/AddCollisionGeometry(SPACER_L, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat);\n\t\/\/AddCollisionGeometry(SPACER_R, BOX, Vector(spacer_width, spacer_height, container_length), lpos, quat);\n\n\tFinalizeObject(PLATE, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(L, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(R, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(F, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(B, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(SPACER_L, (ChSystemGPU *) system_gpu);\n\t\/\/FinalizeObject(SPACER_R, (ChSystemGPU *) system_gpu);\n\n\tROLLER = ChSharedBodyPtr(new ChBody(new ChCollisionModelGPU));\n\tChQuaternion<> roller_quat;\n\troller_quat.Q_from_AngAxis(PI \/ 2.0, ChVector<>(0, 0, 1));\n\n\tChSharedPtr material_roller;\n\tmaterial_roller = ChSharedPtr(new ChMaterialSurface);\n\tmaterial_roller->SetFriction(roller_friction);\n\n\tInitObject(ROLLER, 1000, ChVector<>(0, roller_radius + particle_layer_thickness + container_thickness, container_length + roller_radius\/3.0), roller_quat, material_roller, true, false, -20, -20);\n\tAddCollisionGeometry(ROLLER, CYLINDER, ChVector<>(roller_radius, roller_length * 2, roller_radius), lpos, quat);\n\tFinalizeObject(ROLLER, (ChSystemGPU *) system_gpu);\n\t\/\/68\n\tint3 num_per_dir = I3(68 * 2, 6, 540 * 2);\n\t\/\/num_per_dir = I3(1, 8, 440);\n\tnum_per_dir = I3(74, 8,440);\n\tParticleGenerator layer_gen(system_gpu);\n\tlayer_gen.SetDensity(particle_density);\n\tlayer_gen.SetRadius(R3(particle_radius));\n\tlayer_gen.SetNormalDistribution(particle_radius, particle_std_dev);\n\tlayer_gen.material->SetFriction(particle_friction);\n\tlayer_gen.addPerturbedVolume(R3(0, .7, 0), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));\n\tnum_per_dir = I3(74, 30, 50);\n\t\/\/num_per_dir = I3(1, 30, 50);\n\tlayer_gen.addPerturbedVolume(R3(0, 2.8, 15), SPHERE, num_per_dir, R3(.1, .1, .1), R3(0));\n\n\t\/\/=========================================================================================================\n\t\/\/\/\/\/\/Rendering specific stuff:\n\tif (visualize) {\n\t\tChOpenGLManager * window_manager = new ChOpenGLManager();\n\t\tChOpenGL openGLView(window_manager, system_gpu, 800, 600, 0, 0, \"Test_Solvers\");\n\t\topenGLView.render_camera->camera_pos = Vector(-50, 0, -50);\n\t\topenGLView.render_camera->look_at = Vector(0, 0, 0);\n\t\topenGLView.SetCustomCallback(RunTimeStep);\n\t\topenGLView.StartSpinning(window_manager);\n\t\twindow_manager->CallGlutMainLoop();\n\t}\n\t\/\/=========================================================================================================\n\tstringstream ss_m;\n\tss_m << data_folder << \"\/\" << \"timing.txt\";\n\tstring timing_file_name = ss_m.str();\n\tofstream ofile(timing_file_name.c_str());\n\tofile.close();\n\tint file = 0;\n\tfor (int i = 0; i < num_steps; i++) {\n\t\tcout << \"step \" << i;\n\t\tcout << \" Residual: \" << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetResidual();\n\t\tcout << \" ITER: \" << ((ChLcpSolverGPU *) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations();\n\t\tcout << \" OUTPUT STEP: Time= \" << current_time << \" bodies= \" << system_gpu->GetNbodies() << \" contacts= \" << system_gpu->GetNcontacts() << \" step time=\" << system_gpu->GetTimerStep()\n\t\t\t\t<< \" lcp time=\" << system_gpu->GetTimerLcp() << \" CDbroad time=\" << system_gpu->GetTimerCollisionBroad() << \" CDnarrow time=\" << system_gpu->GetTimerCollisionNarrow() << \" Iterations=\"\n\t\t\t\t<< ((ChLcpSolverGPU*) (system_gpu->GetLcpSolverSpeed()))->GetTotalIterations() << \"\\n\";\n\t\t\/\/TimingFile(system_gpu, timing_file_name, current_time);\n\t\tsystem_gpu->DoStepDynamics(timestep);\n\t\tRunTimeStep(system_gpu, i);\n\t\tint save_every = 1.0 \/ timestep \/ 6000.0; \/\/save data every n steps\n\t\tif (i % save_every == 0) {\n\t\t\tstringstream ss;\n\t\t\tcout << \"Frame: \" << file << endl;\n\t\t\tss << data_folder << \"\/\" << file << \".txt\";\n\t\t\tDumpAllObjectsWithGeometryPovray(system_gpu, ss.str());\n\t\t\t\/\/output.ExportData(ss.str());\n\t\t\tfile++;\n\t\t}\n\t\tcurrent_time += timestep;\n\t}\n\tstringstream ss;\n\t\/\/ss << data_folder << \"\/\" << particle_friction << \"_\" << plate_friction << \"_\" << create_particle_plate << \".txt\";\n\n\t\/\/DumpAllObjectsWithGeometry(system_gpu, ss.str());\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace apc\n{\n using namespace std;\n\n namespace res\n {\n struct NilOk {};\n\n struct Error\n {\n virtual std::string description(size_t offset) = 0;\n virtual Error& previous() = 0;\n virtual bool is_nil()\n {\n return false;\n }\n\n void print_trace(std::ostream& out = std::cerr)\n {\n out << description(0) << std::endl;\n }\n };\n\n struct NilErr : Error\n {\n virtual string description(size_t offset = 0) override\n {\n return \"NilErr\";\n }\n\n virtual Error& previous() override\n {\n static NilErr global;\n\n return global;\n }\n\n virtual bool is_nil() override\n {\n return true;\n }\n };\n\n struct EOI\n {\n vector trace;\n\n EOI() : trace() {}\n EOI(string&& s) : trace{s} {}\n EOI(string& s) : trace{s} {}\n\n void print_trace(ostream& out = cerr) const\n {\n out << \"End of input\" << endl;\n\n for (auto iter = trace.crbegin(); iter != trace.crend(); iter++)\n {\n out << \"\\tIn \" << *iter << endl;\n }\n }\n };\n\n template< typename T, typename I >\n struct Ok\n {\n T res;\n I pos;\n\n Ok(T res, I pos) : res(move(res)), pos(move(pos)) {}\n };\n\n template< typename E, typename I >\n struct Err\n {\n E err;\n I pos;\n\n Err(E err, I pos) : err(move(err)), pos(move(pos)) {}\n };\n\n template< typename T, typename I >\n Ok ok(T t, I i)\n {\n return Ok(move(t), move(i));\n }\n\n template< typename E, typename I >\n Err err(E e, I i)\n {\n return Err(move(e), move(i));\n }\n\n\n template< typename T, typename E, typename I >\n using Result = variant, Err, EOI>;\n\n\n template< typename T, typename E, typename I >\n bool is_ok(const Result& res)\n {\n return holds_alternative>(res);\n }\n\n template< typename T, typename E, typename I >\n bool is_err(const Result& res)\n {\n return holds_alternative>(res);\n }\n\n template< typename T, typename E, typename I >\n bool is_eoi(const Result& res)\n {\n return holds_alternative(res);\n }\n\n\n template< typename T, typename E, typename I >\n Ok& unwrap_ok(Result& res)\n {\n return get>(res);\n }\n\n template< typename T, typename E, typename I >\n Ok unwrap_ok(Result&& res)\n {\n return get>(move(res));\n }\n\n template< typename T, typename E, typename I >\n const Ok& unwrap_ok(const Result& res)\n {\n return get>(res);\n }\n\n\n template< typename T, typename E, typename I >\n Err& unwrap_err(Result& res)\n {\n return get>(res);\n }\n\n template< typename T, typename E, typename I >\n Err unwrap_err(Result&& res)\n {\n return get>(move(res));\n }\n\n template< typename T, typename E, typename I >\n const Err& unwrap_err(const Result& res)\n {\n return get>(res);\n }\n\n\n template< typename T, typename E, typename I >\n EOI& unwrap_eoi(Result& res)\n {\n return get(res);\n }\n\n template< typename T, typename E, typename I >\n EOI unwrap_eoi(Result&& res)\n {\n return get(move(res));\n }\n\n template< typename T, typename E, typename I >\n const EOI& unwrap_eoi(const Result& res)\n {\n return get(res);\n }\n\n\n template< typename T, typename E, typename I,\n typename MOK, typename MERR, typename MEOI >\n void match (Result res,\n MOK match_ok,\n MERR match_err,\n MEOI match_eoi\n )\n {\n\n if (is_ok(res))\n {\n match_ok(unwrap_ok(move(res)));\n }\n else if (is_err(res))\n {\n match_err(unwrap_err(move(res)));\n }\n else\n {\n match_eoi(unwrap_eoi(move(res)));\n }\n }\n\n template< typename T, typename T1, typename E, typename E1, typename I,\n typename MOK, typename MERR, typename MEOI >\n Result match (Result res,\n MOK match_ok,\n MERR match_err,\n MEOI match_eoi\n )\n {\n\n if (is_ok(res))\n {\n return match_ok(unwrap_ok(move(res)));\n }\n else if (is_err(res))\n {\n return match_err(unwrap_err(move(res)));\n }\n else\n {\n return match_eoi(unwrap_eoi(move(res)));\n }\n }\n }\n}\nNilErr not returns itself instead of a static#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace apc\n{\n using namespace std;\n\n namespace res\n {\n struct NilOk {};\n\n struct Error\n {\n virtual std::string description(size_t offset) = 0;\n virtual Error& previous() = 0;\n virtual bool is_nil()\n {\n return false;\n }\n\n void print_trace(std::ostream& out = std::cerr)\n {\n out << description(0) << std::endl;\n }\n };\n\n struct NilErr : Error\n {\n virtual string description(size_t offset = 0) override\n {\n return \"NilErr\";\n }\n\n virtual Error& previous() override\n {\n return *this;\n }\n\n virtual bool is_nil() override\n {\n return true;\n }\n };\n\n struct EOI\n {\n vector trace;\n\n EOI() : trace() {}\n EOI(string&& s) : trace{s} {}\n EOI(string& s) : trace{s} {}\n\n void print_trace(ostream& out = cerr) const\n {\n out << \"End of input\" << endl;\n\n for (auto iter = trace.crbegin(); iter != trace.crend(); iter++)\n {\n out << \"\\tIn \" << *iter << endl;\n }\n }\n };\n\n template< typename T, typename I >\n struct Ok\n {\n T res;\n I pos;\n\n Ok(T res, I pos) : res(move(res)), pos(move(pos)) {}\n };\n\n template< typename E, typename I >\n struct Err\n {\n E err;\n I pos;\n\n Err(E err, I pos) : err(move(err)), pos(move(pos)) {}\n };\n\n template< typename T, typename I >\n Ok ok(T t, I i)\n {\n return Ok(move(t), move(i));\n }\n\n template< typename E, typename I >\n Err err(E e, I i)\n {\n return Err(move(e), move(i));\n }\n\n\n template< typename T, typename E, typename I >\n using Result = variant, Err, EOI>;\n\n\n template< typename T, typename E, typename I >\n bool is_ok(const Result& res)\n {\n return holds_alternative>(res);\n }\n\n template< typename T, typename E, typename I >\n bool is_err(const Result& res)\n {\n return holds_alternative>(res);\n }\n\n template< typename T, typename E, typename I >\n bool is_eoi(const Result& res)\n {\n return holds_alternative(res);\n }\n\n\n template< typename T, typename E, typename I >\n Ok& unwrap_ok(Result& res)\n {\n return get>(res);\n }\n\n template< typename T, typename E, typename I >\n Ok unwrap_ok(Result&& res)\n {\n return get>(move(res));\n }\n\n template< typename T, typename E, typename I >\n const Ok& unwrap_ok(const Result& res)\n {\n return get>(res);\n }\n\n\n template< typename T, typename E, typename I >\n Err& unwrap_err(Result& res)\n {\n return get>(res);\n }\n\n template< typename T, typename E, typename I >\n Err unwrap_err(Result&& res)\n {\n return get>(move(res));\n }\n\n template< typename T, typename E, typename I >\n const Err& unwrap_err(const Result& res)\n {\n return get>(res);\n }\n\n\n template< typename T, typename E, typename I >\n EOI& unwrap_eoi(Result& res)\n {\n return get(res);\n }\n\n template< typename T, typename E, typename I >\n EOI unwrap_eoi(Result&& res)\n {\n return get(move(res));\n }\n\n template< typename T, typename E, typename I >\n const EOI& unwrap_eoi(const Result& res)\n {\n return get(res);\n }\n\n\n template< typename T, typename E, typename I,\n typename MOK, typename MERR, typename MEOI >\n void match (Result res,\n MOK match_ok,\n MERR match_err,\n MEOI match_eoi\n )\n {\n\n if (is_ok(res))\n {\n match_ok(unwrap_ok(move(res)));\n }\n else if (is_err(res))\n {\n match_err(unwrap_err(move(res)));\n }\n else\n {\n match_eoi(unwrap_eoi(move(res)));\n }\n }\n\n template< typename T, typename T1, typename E, typename E1, typename I,\n typename MOK, typename MERR, typename MEOI >\n Result match (Result res,\n MOK match_ok,\n MERR match_err,\n MEOI match_eoi\n )\n {\n\n if (is_ok(res))\n {\n return match_ok(unwrap_ok(move(res)));\n }\n else if (is_err(res))\n {\n return match_err(unwrap_err(move(res)));\n }\n else\n {\n return match_eoi(unwrap_eoi(move(res)));\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#include \nusing namespace std;\n\/\/ ROOT\n#include \n#include \n#include \nusing namespace TMath;\n\/\/ UNIC\n#include \n#include \nusing namespace UNIC;\n#include \nusing namespace MAD;\n\/\/ infinite thin flat plasma sheet\nint main(int argc, char** argv)\n{\n double dt=0.1;\/\/ns\n double dx=1;\/\/nm\n double Ee=100;\/\/volt\/cm\n\n double mean=0, sigma=100,\/*nm*\/ height=1e22;\/\/1\/nm2\n bool norm;\n\n double epsilon=16.2*8.854187817620e-14;\/\/C\/V\/cm\n double Q=1.60217657e-19;\/\/C\n\n \/\/ initialize arrays\n const int N = 100;\n \/\/ p and n are number densities\n double x[2*N+1], p[2*N+1], n[2*N+1], E[2*N+1];\n for (int i=0; i<2*N+1; i++) {\n x[i]=(i-N)*dx;\n p[i]=n[i]=height*Gaus(x[i],mean=0,sigma,norm=kTRUE);\n E[i]=Ee;\n }\n double dp[2*N+1], dn[2*N+1], dE[2*N+1];\n for (int i=0; i<2*N; i++) {\n dp[i] = p[i+1]-p[i];\n dn[i] = n[i+1]-n[i];\n dE[i] = E[i+1]-E[i];\n }\n dp[2*N] = p[2*N]-p[2*N-1];\n dn[2*N] = n[2*N]-n[2*N-1];\n dE[2*N] = E[2*N]-E[2*N-1];\n\n \/\/ output\n TFile *output = new TFile(\"sheet.root\",\"recreate\");\n TTree *t = new TTree(\"t\",\"time slices\");\n t->Branch(\"x\",x,Form(\"x[%d]\/D\",2*N+1));\n t->Branch(\"p\",p,Form(\"p[%d]\/D\",2*N+1));\n t->Branch(\"n\",n,Form(\"n[%d]\/D\",2*N+1));\n t->Branch(\"E\",E,Form(\"E[%d]\/D\",2*N+1));\n t->Branch(\"dp\",dp,Form(\"dp[%d]\/D\",2*N+1));\n t->Branch(\"dn\",dn,Form(\"dn[%d]\/D\",2*N+1));\n t->Branch(\"dE\",dE,Form(\"dE[%d]\/D\",2*N+1));\n\n \/\/ evolve\n int iStep=0, nSteps = 100;\n if (argc>1) nSteps = atoi(argv[1]);\n while (iStepFill();\n \/\/ update electron and hole distributions\n for (int i=0; i<2*N+1; i++) {\n double mu_e = 1;\/\/cm2\/(Vs)\n\t double mu_h = 1;\/\/cm2\/(Vs)\n\t double dn_dt = mu_e*(dn[i]\/dx*E[i]+n[i]*dE[i]\/dx);\n\t double dp_dt = -mu_h*(dp[i]\/dx*E[i]+p[i]*dE[i]\/dx);\n\t n[i]+=dn_dt*dt;\n\t p[i]+=dp_dt*dt;\n }\n \/\/ update electric field distribution\n for (int i=0; i<2*N+1; i++) {\n E[i]=0;\n for (int j=0; jWrite(\"t\",6);\n output->Close();\n\n return 0;\n}\n\nintroduced diffusion and mobility calculated regarding plasma zone as metal#include \nusing namespace std;\n\/\/ ROOT\n#include \n#include \n#include \nusing namespace TMath;\n\/\/ UNIC\n#include \n#include \nusing namespace UNIC;\n\/\/ MAD\n#include \nusing namespace MAD;\n\/\/ thin flat infinite plasma sheet\nint main(int argc, char** argv)\n{\n double dt=1e-1;\/\/ns\n double dx=1;\/\/nm\n double Ee=100;\/\/volt\/cm\n\n double mean=0, sigma=10,\/*nm*\/ height=25;\/\/1\/nm2\n bool norm;\n\n double epsilon=16.2*8.854187817620e-14;\/\/C\/V\/cm\n double Q=1.60217657e-19;\/\/C\n double De=100, Dh=50;\/\/cm2\/s\n\n \/\/ initialize arrays\n const int N = 100;\n \/\/ p and n are number densities\n double x[2*N+1], p[2*N+1], n[2*N+1], E[2*N+1];\n for (int i=0; i<2*N+1; i++) {\n x[i]=(i-N)*dx;\n p[i]=n[i]=height*Gaus(x[i],mean=0,sigma,norm=kTRUE); \/\/1\/nm3\n E[i]=Ee;\n }\n double dp[2*N+1], dn[2*N+1], dE[2*N+1];\n for (int i=0; i<2*N; i++) {\n dp[i] = p[i+1]-p[i];\n dn[i] = n[i+1]-n[i];\n dE[i] = E[i+1]-E[i];\n }\n dp[2*N] = p[2*N]-p[2*N-1];\n dn[2*N] = n[2*N]-n[2*N-1];\n dE[2*N] = E[2*N]-E[2*N-1];\n double d2p[2*N+1], d2n[2*N+1];\n for (int i=0; i<2*N; i++) {\n d2p[i] = dp[i+1]-dp[i];\n d2n[i] = dn[i+1]-dn[i];\n }\n d2p[2*N] = dp[2*N]-dp[2*N-1];\n d2n[2*N] = dn[2*N]-dn[2*N-1];\n\n \/\/ output\n TFile *output = new TFile(\"sheet.root\",\"recreate\");\n TTree *t = new TTree(\"t\",\"time slices\");\n t->Branch(\"x\",x,Form(\"x[%d]\/D\",2*N+1));\n t->Branch(\"p\",p,Form(\"p[%d]\/D\",2*N+1));\n t->Branch(\"n\",n,Form(\"n[%d]\/D\",2*N+1));\n t->Branch(\"E\",E,Form(\"E[%d]\/D\",2*N+1));\n t->Branch(\"dp\",dp,Form(\"dp[%d]\/D\",2*N+1));\n t->Branch(\"dn\",dn,Form(\"dn[%d]\/D\",2*N+1));\n t->Branch(\"dE\",dE,Form(\"dE[%d]\/D\",2*N+1));\n t->Branch(\"d2p\",d2p,Form(\"d2p[%d]\/D\",2*N+1));\n t->Branch(\"d2n\",d2n,Form(\"d2n[%d]\/D\",2*N+1));\n\n \/\/ evolve\n int iStep=0, nSteps = 100;\n if (argc>1) nSteps = atoi(argv[1]);\n double mu_e=40000;\n double mu_h=40000;\n while (iStepFill();\n \/\/ update electron and hole distributions\n for (int i=0; i<2*N+1; i++) {\n if (n[i]>1e-3)\n mu_e = 2.14e36\/Power(n[i]*1e21,1.82);\/\/cm2\/(Vs)\n if (p[i]>1e-3)\n mu_h = 2.14e36\/Power(p[i]*1e21,1.82);\/\/cm2\/(Vs)\n\t double dn_dt = mu_e*(dn[i]\/dx*E[i]+n[i]*dE[i]\/dx); \/\/ 1e7\/nm3\/s\n\t double dp_dt = -mu_h*(dp[i]\/dx*E[i]+p[i]*dE[i]\/dx);\n dn_dt+=De*d2n[i]\/dx\/dx\/1e7; \/\/ 1e7\/nm3\/s\n dp_dt+=Dh*d2p[i]\/dx\/dx\/1e7;\n\t n[i]+=dn_dt*dt;\n\t p[i]+=dp_dt*dt;\n }\n \/\/ update electric field distribution\n for (int i=0; i<2*N+1; i++) {\n E[i]=0;\n for (int j=0; jWrite(\"t\",6);\n output->Close();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * A worst-case O(N) time algorithm for the\n * total variation filter problem in one dimension.\n *\/\n\n#include \n#include \n\nnamespace tvf\n{\n\nnamespace detail\n{\n \nstruct Point\n{\n double x;\n double y;\n\n void operator+= (const Point &rhs)\n {\n x += rhs.x;\n y += rhs.y;\n }\n\n void operator-= (const Point &rhs)\n {\n x -= rhs.x;\n y -= rhs.y;\n }\n};\n\ninline double inner_product (const Point &u, const Point &v)\n{\n return u.x * v.y - u.y * v.x;\n}\n\n\/*\n * Add point on the right of convex\/concave chain\n * removing all points not in the convex hull of the\n * new set.\n *\/\ntemplate\nvoid convex_chain_extend (Q &chain, Point p, const Dot &dot)\n{\n while (!chain.empty () && dot (p, chain.back ()) <= 0.)\n {\n p += chain.back ();\n chain.pop_back ();\n }\n\n chain.push_back (p);\n}\n\ntemplate\nInputIt\nconvex_chain_reduce (Point &p,\n\t\t InputIt chain_begin,\n\t\t const InputIt &chain_end,\n\t\t const Dot &dot)\n{\n Point v {0., 0.};\n for (; chain_begin != chain_end; ++chain_begin)\n {\n auto next_v = v;\n next_v += *chain_begin;\n\n if (dot (p, next_v) > 0)\n {\n break;\n }\n\n v = next_v;\n }\n\n p -= v;\n return chain_begin;\n}\n\n} \/\/ namespace detail {\n\ntemplate\nOutIt total_variation_filter (InputIt first,\n\t\t\t InputIt last,\n\t\t\t const double lambda,\n\t\t\t OutIt output)\n{\n using namespace detail;\n\n \/*\n * Geodesics to upper\/lower bounding chains \n *\/\n std::deque upper;\n std::deque lower;\n\n \/*\n * Handle input of length <= 1 separately\n *\/\n if (first == last)\n {\n return output;\n }\n\n if (std::distance (first, last) == 1)\n {\n *output++ = *first;\n return output;\n }\n else\n {\n const auto v = *first++;\n upper.push_back ({v + lambda\/2, 1});\n lower.push_back ({v - lambda\/2, 1});\n }\n\n \/*\n * Logic to update upper\/lower geodesics\n *\/\n const auto update = [&] (\n auto &u, auto &l, const Point &p, auto &&dot)\n {\n convex_chain_extend (u, p, dot);\n\n if (u.size () == 1 && !l.empty ())\n {\n const auto nf = convex_chain_reduce (\n u.front (), l.begin (), l.end (), dot);\n\n if (nf != l.begin ())\n {\n\tfor (auto it = l.begin (); it != nf; ++it)\n\t{\n\t output = std::fill_n (output, it->y, it->x \/ it->y);\n\t}\n\n\tl.erase (l.begin (), nf);\n }\n }\n };\n\n for (;;)\n {\n const auto value = *first++;\n const bool is_last = (first == last);\n\n const Point p {is_last ? (value - lambda \/ 2) : value, 1};\n\n update (upper, lower, p, inner_product);\n\n if (is_last)\n {\n for (const auto &p : upper)\n {\n\toutput = std::fill_n (output, p.y, p.x \/ p.y);\n }\n\n return output;\n }\n else\n {\n update (lower, upper, p, [] (auto &&x, auto &&y)\n {\n\treturn inner_product (y, x);\n });\n }\n }\n\n return output;\n}\n\n} \/\/ namespace tvf {\nFixed logic of lower geodesic update\/**\n * A worst-case O(N) time algorithm for the\n * total variation filter problem in one dimension.\n *\/\n\n#include \n#include \n\nnamespace tvf\n{\n\n\/**\n * Calculate total variation denoised (filtered) values of\n * the input range [@p first, @last) with TV penalty lambda.\n * Write output values in @output.\n *\/\ntemplate\nOutIt total_variation_filter (\n FwdIt first, FwdIt last,\n double lambda, OutIt output);\n\n\/*************************************************\n *\n * Inlined implementation\n *\n *************************************************\/ \nnamespace detail\n{\n \nstruct Point\n{\n double x;\n double y;\n\n void operator+= (const Point &rhs)\n {\n x += rhs.x;\n y += rhs.y;\n }\n\n void operator-= (const Point &rhs)\n {\n x -= rhs.x;\n y -= rhs.y;\n }\n};\n\ninline double inner_product (const Point &u, const Point &v)\n{\n return u.x * v.y - u.y * v.x;\n}\n\n\/*\n * Add point on the right of convex\/concave chain\n * removing all points not in the convex hull of the\n * new set.\n *\/\ntemplate\nvoid convex_chain_extend (Q &chain, Point p, const Dot &dot)\n{\n while (!chain.empty () && dot (p, chain.back ()) <= 0.)\n {\n p += chain.back ();\n chain.pop_back ();\n }\n\n chain.push_back (p);\n}\n\n\/*\n * Symmetric\n *\/\ntemplate\nInputIt\nconvex_chain_reduce (Point &p,\n\t\t InputIt chain_begin,\n\t\t const InputIt &chain_end,\n\t\t const Dot &dot)\n{\n while (chain_begin != chain_end &&\n\t dot (p, *chain_begin) < 0)\n {\n p -= *chain_begin;\n ++chain_begin;\n }\n\n return chain_begin;\n}\n\n} \/\/ namespace detail {\n\ntemplate\nOutIt total_variation_filter (InputIt first,\n\t\t\t InputIt last,\n\t\t\t const double lambda,\n\t\t\t OutIt output)\n{\n using namespace detail;\n\n \/*\n * Geodesics to upper\/lower bounding chains \n *\/\n std::deque upper;\n std::deque lower;\n \n \/*\n * Handle input of length <= 1 separately\n *\/\n if (first == last)\n {\n return output;\n }\n if (first + 1 == last)\n {\n *output++ = *first;\n return output;\n }\n else\n {\n const auto v = *first++;\n upper.push_back ({v + lambda\/2, 1});\n lower.push_back ({v - lambda\/2, 1});\n }\n \n \/*\n * Logic to update upper\/lower geodesics\n *\/\n const auto update = [&] (\n auto &u, auto &l, const Point &p, auto &&dot)\n {\n convex_chain_extend (u, p, dot);\n\n if (u.size () == 1 && !l.empty ())\n {\n const auto nf = convex_chain_reduce (\n u.front (), l.begin (), l.end (), dot);\n\n if (nf != l.begin ())\n {\n\tfor (auto it = l.begin (); it != nf; ++it)\n\t{\n\t output = std::fill_n (output, it->y, it->x \/ it->y);\n\t}\n\n\tl.erase (l.begin (), nf);\n }\n }\n };\n\n for (;;)\n {\n const auto value = *first++;\n const bool is_last = (first == last);\n\n const Point p {is_last ? (value - lambda \/ 2) : value, 1};\n\n update (upper, lower, p, inner_product);\n \n if (is_last)\n {\n for (const auto &p : upper)\n {\n\toutput = std::fill_n (output, p.y, p.x \/ p.y);\n }\n\n break;\n }\n else\n {\n update (lower, upper, p, [] (auto &&x, auto &&y)\n {\n\treturn inner_product (y, x);\n });\n }\n }\n\n return output;\n}\n\n} \/\/ namespace tvf {\n<|endoftext|>"} {"text":"\/\/\/ This file contains the implementation of VNS\n#include \"header\/vns-priv.hpp\"\n\nusing namespace std;\n\nnamespace pcp {\n\tSolution bestSolution;\n\tSolution origSolution;\n\n\tbool checkValid(Solution* s);\n\n\t\/\/\/ Some constants\n\tconst int NUM_VNS = 2;\n\tconst int SHAKE_START = 1;\n\t\n\t\/\/\/ Implementation of VNS, see vns.hpp\n\tSolution vnsRun(Solution& best, Solution& orig, char* units, int unsuccessfulShake, \n\t\t\t\t\t\t int shakeStart, int shakeIncrement, int maxTime) {\n\n\t\t\/\/\/ Backup the starting solutions\n\t\tbestSolution = new Solution(best);\n\t\torigSolution = new Solution(orig);\n\t\t\n\t\tif (DEBUG_LEVEL > 1) {\n\t\t\tcout<<\"Best solution uses \"< 1) {\n\t\t\tcout<<\"The supplied solution is valid: \"<<(checkValid(&best) ? \"true\": \"false\")< 1) {\n\t\t\t\t\tcout<<\"Running: \"<< neigh->name() <findLocalMin(best, orig);\n\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\tcout<name()<<\" took about \";\n\t\t\t\t\tcout<<(clock() - start)\/(float)CLOCKS_PER_SEC;\n\t\t\t\t\tcout<<\" seconds to complete\"<colorsUsed < toImprove->colorsUsed) {\n\t\t\t\t\tdelete toImprove;\n\t\t\t\t\ttoImprove = improved;\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\t\tcout<<\"Improvement found with \"<name()< 1) {\n\t\t\t\t\t\tcout<<\"No improvement found\"< 1) {\n\t\t\t\t\tcout<colorsUsed < best.colorsUsed) {\n\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\tcout<<\"Improvement to global best solution found\"< unsuccessfulShake) {\n\t\t\t\t\tif (DEBUG_LEVEL > 0) {\n\t\t\t\t\t\tcout<<\"Too many unsuccessful shakes\"<shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement));\n\t\t\t\n\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\tcout<<\"Shaking Solution using \"<name()<<\" with \";\n\t\t\t\tcout< 0) {\n\t\t\t\t\tcout<<\"Time's up\"< 0) {\n\t\t\tcout<colorsUsed<<\" colors\";\n\t\t\tcout< vIter;\n\t\tint parts[s->numParts];\n\t\tint colors[s->numParts];\n\t\ttypedef boost::graph_traits::adjacency_iterator AdjIter;\n\t\tVertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g);\n\t\tbool valid = true;\n\t\n\t\tfor (int i = 0; i < s->numParts; i++) {\n\t\t\tparts[i] = 0;\n\t\t\tcolors[i] = 0;\n\t\t}\n\t\n\t\tfor (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {\n\t\t\tparts[vParts[*vIter.first]] = 1;\n\t\t\tcolors[s->partition[vParts[*vIter.first]]] = 1;\n\t\t\t\n\t\t\tpair aIter;\n\t\t\tfor (aIter = adjacent_vertices(*vIter.first, *s->g); \n\t\t\t\t aIter.first != aIter.second; aIter.first++) {\n\t\t\t\n\t\t\t\tif (s->partition[vParts[*aIter.first]] == \n\t\t\t\t\t s->partition[vParts[*vIter.first]]) {\n\t\t\t\t\n\t\t\t\t\tvalid = false;\n\t\t\t\t\tcerr<<\"Solution is invalid\"<partition[vParts[*vIter.first]];\n\t\t\t\t\tcerr<numParts; i++) {\n\t\t\tif (colors[i] == 1) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\tif (count != s->colorsUsed) {\n\t\t\tvalid = false;\n\t\t\tcerr<<\"Solution is invalid\"<colorsUsed;\n\t\t\tcerr<<\", computed: \"<numParts; i++) {\n\t\t\tif (parts[i] == 0) {\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<representatives[vParts[i]] != i) {\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<Added comments to checkValid method\/\/\/ This file contains the implementation of VNS\n#include \"header\/vns-priv.hpp\"\n\nusing namespace std;\n\nnamespace pcp {\n\tSolution bestSolution;\n\tSolution origSolution;\n\n\tbool checkValid(Solution* s);\n\n\t\/\/\/ Some constants\n\tconst int NUM_VNS = 2;\n\tconst int SHAKE_START = 1;\n\t\n\t\/\/\/ Implementation of VNS, see vns.hpp\n\tSolution vnsRun(Solution& best, Solution& orig, char* units, int unsuccessfulShake, \n\t\t\t\t\t\t int shakeStart, int shakeIncrement, int maxTime) {\n\n\t\t\/\/\/ Backup the starting solutions\n\t\tbestSolution = new Solution(best);\n\t\torigSolution = new Solution(orig);\n\t\t\n\t\tif (DEBUG_LEVEL > 1) {\n\t\t\tcout<<\"Best solution uses \"< 1) {\n\t\t\tcout<<\"The supplied solution is valid: \"<<(checkValid(&best) ? \"true\": \"false\")< 1) {\n\t\t\t\t\tcout<<\"Running: \"<< neigh->name() <findLocalMin(best, orig);\n\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\tcout<name()<<\" took about \";\n\t\t\t\t\tcout<<(clock() - start)\/(float)CLOCKS_PER_SEC;\n\t\t\t\t\tcout<<\" seconds to complete\"<colorsUsed < toImprove->colorsUsed) {\n\t\t\t\t\tdelete toImprove;\n\t\t\t\t\ttoImprove = improved;\n\t\t\t\t\t\n\t\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\t\tcout<<\"Improvement found with \"<name()< 1) {\n\t\t\t\t\t\tcout<<\"No improvement found\"< 1) {\n\t\t\t\t\tcout<colorsUsed < best.colorsUsed) {\n\t\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\t\tcout<<\"Improvement to global best solution found\"< unsuccessfulShake) {\n\t\t\t\t\tif (DEBUG_LEVEL > 0) {\n\t\t\t\t\t\tcout<<\"Too many unsuccessful shakes\"<shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement));\n\t\t\t\n\t\t\tif (DEBUG_LEVEL > 1) {\n\t\t\t\tcout<<\"Shaking Solution using \"<name()<<\" with \";\n\t\t\t\tcout< 0) {\n\t\t\t\t\tcout<<\"Time's up\"< 0) {\n\t\t\tcout<colorsUsed<<\" colors\";\n\t\t\tcout< vIter;\n\t\tint parts[s->numParts];\n\t\tint colors[s->numParts];\n\t\ttypedef boost::graph_traits::adjacency_iterator AdjIter;\n\t\tVertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g);\n\t\tbool valid = true;\n\t\n\t\t\/\/\/ Initialize parts and colors\n\t\tfor (int i = 0; i < s->numParts; i++) {\n\t\t\tparts[i] = 0;\n\t\t\tcolors[i] = 0;\n\t\t}\n\t\n\t\t\/\/\/ Check all vertices\n\t\tfor (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {\n\t\t\t\/\/\/ Mark partition and color as used\n\t\t\tparts[vParts[*vIter.first]] = 1;\n\t\t\tcolors[s->partition[vParts[*vIter.first]]] = 1;\n\t\t\t\n\t\t\t\/\/\/ Check color conflicts\n\t\t\tpair aIter;\n\t\t\tfor (aIter = adjacent_vertices(*vIter.first, *s->g); \n\t\t\t\t aIter.first != aIter.second; aIter.first++) {\n\t\t\t\n\t\t\t\tif (s->partition[vParts[*aIter.first]] == \n\t\t\t\t\t s->partition[vParts[*vIter.first]]) {\n\t\t\t\t\n\t\t\t\t\tvalid = false;\n\t\t\t\t\tcerr<<\"Solution is invalid\"<partition[vParts[*vIter.first]];\n\t\t\t\t\tcerr<numParts; i++) {\n\t\t\tif (colors[i] == 1) {\n\t\t\t\tcount++;\n\t\t\t}\n\t\t}\n\t\tif (count != s->colorsUsed) {\n\t\t\tvalid = false;\n\t\t\tcerr<<\"Solution is invalid\"<colorsUsed;\n\t\t\tcerr<<\", computed: \"<numParts; i++) {\n\t\t\tif (parts[i] == 0) {\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<representatives[vParts[i]] != i) {\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<"} {"text":"#ifndef ZIP_HPP\n#define ZIP_HPP\n\n#include \"iterator_range.hpp\"\n\n#include \n#include \n\nnamespace iter {\n template \n class zip_iter;\n\n template \n auto zip(Containers && ... containers) ->\n iterator_range>\n {\n auto begin =\n zip_iter(std::begin(containers)...);\n\n auto end =\n zip_iter(std::end(containers)...);\n\n return iterator_range(begin,end);\n }\n\n\n template \n class zip_iter {\n private:\n Iterator iter;\n\n public:\n using elem_type = decltype(*iter);\n zip_iter(const Iterator & i) :\n iter(i){ }\n\n auto operator*() -> decltype(std::tie(*iter))\n {\n return std::tie(*iter);\n }\n zip_iter & operator++() {\n ++iter;\n return *this;\n }\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter != rhs.iter);\n }\n };\n#if 0\n template \n struct zip_iter {\n\n private:\n First iter1;\n Second iter2;\n\n public:\n using Elem1_t = decltype(*iter1);\n using Elem2_t = decltype(*iter2);\n zip_iter(const First & f, const Second & s) :\n iter1(f),iter2(s) { }\n\n auto operator*() -> decltype(std::tie(*iter1,*iter2))\n {\n return std::tie(*iter1,*iter2);\n }\n zip_iter & operator++() {\n ++iter1;\n ++iter2;\n return *this;\n }\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter1 != rhs.iter1) && (this->iter2 != rhs.iter2);\n }\n };\n#endif\n \/\/this specialization commented out \n template \n class zip_iter {\n private:\n First iter;\n zip_iter inner_iter;\n \n public:\n using elem_type = decltype(*iter);\n using tuple_type = \n decltype(std::tuple_cat(std::tie(*iter),*inner_iter));\n\n zip_iter(const First & f, const Rest & ... rest) :\n iter(f),\n inner_iter(rest...) {}\n\n\n tuple_type operator*()\n {\n return std::tuple_cat(std::tie(*iter),*inner_iter);\n }\n\n zip_iter & operator++() {\n ++iter;\n ++inner_iter;\n return *this;\n }\n\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter != rhs.iter) &&\n (this->inner_iter != rhs.inner_iter);\n }\n };\n}\n\nnamespace std {\n template \n struct iterator_traits> {\n using difference_type = ptrdiff_t;\n using iterator_category = input_iterator_tag;\n };\n}\n#endif \/\/ZIP_HPP\nchanged std::tie to std::forward_as_tuple#ifndef ZIP_HPP\n#define ZIP_HPP\n\n#include \"iterator_range.hpp\"\n\n#include \n#include \n\nnamespace iter {\n template \n class zip_iter;\n\n template \n auto zip(Containers && ... containers) ->\n iterator_range>\n {\n auto begin =\n zip_iter(std::begin(containers)...);\n\n auto end =\n zip_iter(std::end(containers)...);\n\n return iterator_range(begin,end);\n }\n\n\n template \n class zip_iter {\n private:\n Iterator iter;\n\n public:\n using elem_type = decltype(*iter);\n zip_iter(const Iterator & i) :\n iter(i){ }\n\n auto operator*() -> decltype(std::forward_as_tuple(*iter))\n {\n return std::forward_as_tuple(*iter);\n }\n zip_iter & operator++() {\n ++iter;\n return *this;\n }\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter != rhs.iter);\n }\n };\n#if 0\n template \n struct zip_iter {\n\n private:\n First iter1;\n Second iter2;\n\n public:\n using Elem1_t = decltype(*iter1);\n using Elem2_t = decltype(*iter2);\n zip_iter(const First & f, const Second & s) :\n iter1(f),iter2(s) { }\n\n auto operator*() -> decltype(std::forward_as_tuple(*iter1,*iter2))\n {\n return std::forward_as_tuple(*iter1,*iter2);\n }\n zip_iter & operator++() {\n ++iter1;\n ++iter2;\n return *this;\n }\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter1 != rhs.iter1) && (this->iter2 != rhs.iter2);\n }\n };\n#endif\n \/\/this specialization commented out \n template \n class zip_iter {\n private:\n First iter;\n zip_iter inner_iter;\n \n public:\n using elem_type = decltype(*iter);\n using tuple_type = \n decltype(std::tuple_cat(std::forward_as_tuple(*iter),*inner_iter));\n\n zip_iter(const First & f, const Rest & ... rest) :\n iter(f),\n inner_iter(rest...) {}\n\n\n tuple_type operator*()\n {\n return std::tuple_cat(std::forward_as_tuple(*iter),*inner_iter);\n }\n\n zip_iter & operator++() {\n ++iter;\n ++inner_iter;\n return *this;\n }\n\n bool operator!=(const zip_iter & rhs) const {\n return (this->iter != rhs.iter) &&\n (this->inner_iter != rhs.inner_iter);\n }\n };\n}\n\nnamespace std {\n template \n struct iterator_traits> {\n using difference_type = ptrdiff_t;\n using iterator_category = input_iterator_tag;\n };\n}\n#endif \/\/ZIP_HPP\n<|endoftext|>"} {"text":"#include \"voip.h\"\n#include \"Central.h\"\n \nusing namespace ns3;\n#define MAXONVOIP 0.1\n#define MINONVOIP 0.2\n#define MAXOFFVOIP 0.8\n#define MINOFFVOIP 0.9\n\n\nvoip::voip (Central * centralita, uint64_t tamPkt, Time media, Time duracion, DataRate tasaCodec[2], Address IP, Ptr node) : OnOffHelper(\"ns3::UdpSocketFactory\", IP)\n{\n\n\tm_centralita = centralita;\n\tm_ocupado = false;\n\tm_tamPaquete = tamPkt;\n\ttiempo_entre_llamadas.SetAttribute(\"Mean\",DoubleValue(media.GetSeconds()) );\n\tduracion_de_llamada.SetAttribute(\"Mean\", DoubleValue (duracion.GetSeconds()));\n uint32_t minTasa = tasaCodec[0].GetBitRate();\n uint32_t maxTasa = tasaCodec[1].GetBitRate();\n m_tasa = tasa_llamadas.GetValue(minTasa,maxTasa);\n m_IP = IP;\n m_node = node;\n m_numeroNodo = m_centralita->registrar (m_IP);\n}\n\n\n\n\nvoid\nvoip::setDestino (Address destino){\n\n\tm_destino = destino;\n}\n\n\nvoid\nvoip::setTamPaquete (uint64_t tamPkt){\n\n\tm_tamPaquete = tamPkt;\n\n}\n\n\n\nbool\nvoip::getOcupado(){\nreturn m_ocupado;\n}\n\n\nvoid voip::CancelaLlamada (){\n\nSimulator::Cancel(m_proximallamada);\n}\n\nvoid voip::ProgramaLlamada (){\n\n\tm_proximallamada=Simulator::Schedule (Time (tiempo_entre_llamadas.GetValue()) , this, Llama ); \/\/m_tiempo no es tipo Time, falla\n\n}\n\n\n\nvoid\nvoip::Llama (){\n\n\t\/\/Me pongo en contacto con la centralita\n\tm_ocupado=true;\n\tm_llamadaactual = m_proximallamada;\n\tm_duracion = Time(duracion_de_llamada.GetValue());\n\n\t\tAddress direccion_envio = m_centralita->llamar ( m_numeroNodo, m_duracion);\n\n\t\/\/Configuro OnOff?\n\n\t\tm_AppOnOff = OnOffHelper(\"ns3::UdpSocketFactory\", direccion_envio);\n\n\t\tm_AppOnOff.SetConstantRate (DataRate( m_tasa) );\n\t\tm_AppOnOff.SetAttribute(\"PacketSize\",UintegerValue( m_tamPaquete) );\n\n\n\n\n\t varon=CreateObject();\n\t varon->SetAttribute(\"Max\", DoubleValue(MAXONVOIP));\n\t varon->SetAttribute(\"Min\", DoubleValue(MINONVOIP));\n\n\t varoff=CreateObject();\n\t varoff->SetAttribute(\"Max\", DoubleValue(MAXOFFVOIP));\n\t varoff->SetAttribute(\"Min\", DoubleValue(MINOFFVOIP));\n\t \/\/Configuramos la aplicación OnOff\n\n\t m_AppOnOff.SetAttribute(\"OnTime\", PointerValue(varon));\n\t m_AppOnOff.SetAttribute(\"OffTime\", PointerValue(varoff));\n\n\n\n\n\t m_appc = m_AppOnOff.Install(m_node); \/\/Pasarle por parametro al puntero al nodo.\n\t m_appc.Start(Simulator::Now());\n\t Simulator::Schedule (Simulator::Now()+m_duracion,this, Cuelga);\n\n}\n\n\n\nvoid\nvoip::Cuelga(){\n\n\t\/\/llamo al OnOffStopApplication\n\tm_appc.Stop(Simulator::Now());\n\tm_ocupado=0;\n\t\/\/Llamo a programallamada\n\tProgramaLlamada();\n\n\n}\n\nvoid voip::Descuelga(Address destino, Time duracion){\n\n\tCancelaLlamada();\n\n\n\tm_AppOnOff = OnOffHelper(\"ns3::UdpSocketFactory\", destino);\n\n\t\t\tm_AppOnOff.SetConstantRate (DataRate( m_tasa) );\n\n\n\n\n\t\t varon=CreateObject();\n\t\t varon->SetAttribute(\"Max\", DoubleValue(MAXONVOIP));\n\t\t varon->SetAttribute(\"Min\", DoubleValue(MINONVOIP));\n\n\t\t varoff=CreateObject();\n\t\t varoff->SetAttribute(\"Max\", DoubleValue(MAXOFFVOIP));\n\t\t varoff->SetAttribute(\"Min\", DoubleValue(MINOFFVOIP));\n\t\t \/\/Configuramos la aplicación OnOff\n\n\t\t m_AppOnOff.SetAttribute(\"OnTime\", PointerValue(varon));\n\t\t m_AppOnOff.SetAttribute(\"OffTime\", PointerValue(varoff));\n\n\n\n\n\t\t m_appc = m_AppOnOff.Install(m_node); \/\/Pasarle por parametro al puntero al nodo.\n\t\t m_appc.Start(Simulator::Now());\n\t\t Simulator::Schedule (Simulator::Now()+m_duracion,this, Cuelga);\n\n}\nDeshecho#include \"voip.h\"\n#include \"Central.h\"\n \nusing namespace ns3;\n#define MAXONVOIP 0.1\n#define MINONVOIP 0.2\n#define MAXOFFVOIP 0.8\n#define MINOFFVOIP 0.9\n\n\nvoip::voip (Central * centralita, uint64_t tamPkt, Time media, Time duracion, DataRate tasaCodec[2], Address IP, Ptr node) : Application()\n{\n\n\tm_centralita = centralita;\n\tm_ocupado = false;\n\tm_tamPaquete = tamPkt;\n\ttiempo_entre_llamadas.SetAttribute(\"Mean\",DoubleValue(media.GetSeconds()) );\n\tduracion_de_llamada.SetAttribute(\"Mean\", DoubleValue (duracion.GetSeconds()));\n uint32_t minTasa = tasaCodec[0].GetBitRate();\n uint32_t maxTasa = tasaCodec[1].GetBitRate();\n m_tasa = tasa_llamadas.GetValue(minTasa,maxTasa);\n m_IP = IP;\n m_node = node;\n m_numeroNodo = m_centralita->registrar (m_IP);\n}\n\n\n\n\nvoid\nvoip::setDestino (Address destino){\n\n\tm_destino = destino;\n}\n\n\nvoid\nvoip::setTamPaquete (uint64_t tamPkt){\n\n\tm_tamPaquete = tamPkt;\n\n}\n\n\n\nbool\nvoip::getOcupado(){\nreturn m_ocupado;\n}\n\n\nvoid voip::CancelaLlamada (){\n\nSimulator::Cancel(m_proximallamada);\n}\n\nvoid voip::ProgramaLlamada (){\n\n\tm_proximallamada=Simulator::Schedule (Time (tiempo_entre_llamadas.GetValue()) , this, Llama ); \/\/m_tiempo no es tipo Time, falla\n\n}\n\n\n\nvoid\nvoip::Llama (){\n\n\t\/\/Me pongo en contacto con la centralita\n\tm_ocupado=true;\n\tm_llamadaactual = m_proximallamada;\n\tm_duracion = Time(duracion_de_llamada.GetValue());\n\n\t\tAddress direccion_envio = m_centralita->llamar ( m_numeroNodo, m_duracion);\n\n\t\/\/Configuro OnOff?\n\n\t\tm_AppOnOff = OnOffHelper(\"ns3::UdpSocketFactory\", direccion_envio);\n\n\t\tm_AppOnOff.SetConstantRate (DataRate( m_tasa) );\n\t\tm_AppOnOff.SetAttribute(\"PacketSize\",UintegerValue( m_tamPaquete) );\n\n\n\n\n\t varon=CreateObject();\n\t varon->SetAttribute(\"Max\", DoubleValue(MAXONVOIP));\n\t varon->SetAttribute(\"Min\", DoubleValue(MINONVOIP));\n\n\t varoff=CreateObject();\n\t varoff->SetAttribute(\"Max\", DoubleValue(MAXOFFVOIP));\n\t varoff->SetAttribute(\"Min\", DoubleValue(MINOFFVOIP));\n\t \/\/Configuramos la aplicación OnOff\n\n\t m_AppOnOff.SetAttribute(\"OnTime\", PointerValue(varon));\n\t m_AppOnOff.SetAttribute(\"OffTime\", PointerValue(varoff));\n\n\n\n\n\t m_appc = m_AppOnOff.Install(m_node); \/\/Pasarle por parametro al puntero al nodo.\n\t m_appc.Start(Simulator::Now());\n\t Simulator::Schedule (Simulator::Now()+m_duracion,this, Cuelga);\n\n}\n\n\n\nvoid\nvoip::Cuelga(){\n\n\t\/\/llamo al OnOffStopApplication\n\tm_appc.Stop(Simulator::Now());\n\tm_ocupado=0;\n\t\/\/Llamo a programallamada\n\tProgramaLlamada();\n\n\n}\n\nvoid voip::Descuelga(Address destino, Time duracion){\n\n\tCancelaLlamada();\n\n\n\tm_AppOnOff = OnOffHelper(\"ns3::UdpSocketFactory\", destino);\n\n\t\t\tm_AppOnOff.SetConstantRate (DataRate( m_tasa) );\n\n\n\n\n\t\t varon=CreateObject();\n\t\t varon->SetAttribute(\"Max\", DoubleValue(MAXONVOIP));\n\t\t varon->SetAttribute(\"Min\", DoubleValue(MINONVOIP));\n\n\t\t varoff=CreateObject();\n\t\t varoff->SetAttribute(\"Max\", DoubleValue(MAXOFFVOIP));\n\t\t varoff->SetAttribute(\"Min\", DoubleValue(MINOFFVOIP));\n\t\t \/\/Configuramos la aplicación OnOff\n\n\t\t m_AppOnOff.SetAttribute(\"OnTime\", PointerValue(varon));\n\t\t m_AppOnOff.SetAttribute(\"OffTime\", PointerValue(varoff));\n\n\n\n\n\t\t m_appc = m_AppOnOff.Install(m_node); \/\/Pasarle por parametro al puntero al nodo.\n\t\t m_appc.Start(Simulator::Now());\n\t\t Simulator::Schedule (Simulator::Now()+m_duracion,this, Cuelga);\n\n}\n<|endoftext|>"} {"text":"\/*\nThis Source Code Form is subject to the\nterms of the Mozilla Public License, v.\n2.0. If a copy of the MPL was not\ndistributed with this file, You can\nobtain one at\nhttp:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\/*\n MaSzyna EU07 locomotive simulator\n Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others\n\n*\/\n\/*\nAuthors:\nMarcinW, McZapkie, Shaxbee, ABu, nbmx, youBy, Ra, winger, mamut, Q424,\nStele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others\n*\/\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n\n#include \"Globals.h\"\n#include \"Logs.h\"\n#include \"keyboardinput.h\"\n#include \"gamepadinput.h\"\n#include \"Console.h\"\n#include \"PyInt.h\"\n#include \"World.h\"\n#include \"Mover.h\"\n#include \"usefull.h\"\n#include \"timer.h\"\n#include \"resource.h\"\n#include \"uilayer.h\"\n\n#pragma comment (lib, \"glu32.lib\")\n#pragma comment (lib, \"dsound.lib\")\n#pragma comment (lib, \"winmm.lib\")\n#pragma comment (lib, \"setupapi.lib\")\n#pragma comment (lib, \"dbghelp.lib\")\n\nTWorld World;\n\nnamespace input {\n\nkeyboard_input Keyboard;\ngamepad_input Gamepad;\n\n}\n\nvoid screenshot_save_thread( char *img )\n{\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png_image));\n\tpng.version = PNG_IMAGE_VERSION;\n\tpng.width = Global::ScreenWidth;\n\tpng.height = Global::ScreenHeight;\n\tpng.format = PNG_FORMAT_RGB;\n\n\tchar datetime[64];\n\ttime_t timer;\n\tstruct tm* tm_info;\n\ttime(&timer);\n\ttm_info = localtime(&timer);\n\tstrftime(datetime, 64, \"%Y-%m-%d_%H-%M-%S\", tm_info);\n\n\tuint64_t perf;\n\tQueryPerformanceCounter((LARGE_INTEGER*)&perf);\n\n\tstd::string filename = \"screenshots\/\" + std::string(datetime) +\n\t \"_\" + std::to_string(perf) + \".png\";\n\n\tif (png_image_write_to_file(&png, filename.c_str(), 0, img, -Global::ScreenWidth * 3, nullptr) == 1)\n\t\tWriteLog(\"saved \" + filename + \".\");\n\telse\n\t\tWriteLog(\"failed to save screenshot.\");\n\n\tdelete[] img;\n}\n\nvoid make_screenshot()\n{\n\tchar *img = new char[Global::ScreenWidth * Global::ScreenHeight * 3];\n\tglReadPixels(0, 0, Global::ScreenWidth, Global::ScreenHeight, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)img);\n\n\tstd::thread t(screenshot_save_thread, img);\n\tt.detach();\n}\n\nvoid window_resize_callback(GLFWwindow *window, int w, int h)\n{\n \/\/ NOTE: we have two variables which basically do the same thing as we don't have dynamic fullscreen toggle\n \/\/ TBD, TODO: merge them?\n\tGlobal::ScreenWidth = Global::iWindowWidth = w;\n\tGlobal::ScreenHeight = Global::iWindowHeight = h;\n Global::fDistanceFactor = std::max( 0.5f, h \/ 768.0f ); \/\/ not sure if this is really something we want to use\n\tglViewport(0, 0, w, h);\n}\n\nvoid cursor_pos_callback(GLFWwindow *window, double x, double y)\n{\n input::Keyboard.mouse( x, y );\n#ifdef EU07_USE_OLD_COMMAND_SYSTEM\n\tWorld.OnMouseMove(x * 0.005, y * 0.01);\n#endif\n\tglfwSetCursorPos(window, 0.0, 0.0);\n}\n\nvoid key_callback( GLFWwindow *window, int key, int scancode, int action, int mods )\n{\n input::Keyboard.key( key, action );\n\n Global::shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false;\n Global::ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false;\n\n if( ( key == GLFW_KEY_LEFT_SHIFT )\n || ( key == GLFW_KEY_LEFT_CONTROL )\n || ( key == GLFW_KEY_LEFT_ALT )\n || ( key == GLFW_KEY_RIGHT_SHIFT )\n || ( key == GLFW_KEY_RIGHT_CONTROL )\n || ( key == GLFW_KEY_RIGHT_ALT ) ) {\n \/\/ don't bother passing these\n return;\n }\n\n if( action == GLFW_PRESS || action == GLFW_REPEAT )\n {\n World.OnKeyDown( key );\n\n switch( key )\n {\n\n case GLFW_KEY_F11: {\n make_screenshot();\n break;\n }\n\n default: { break; }\n }\n }\n}\n\nvoid focus_callback( GLFWwindow *window, int focus )\n{\n if( Global::bInactivePause ) \/\/ jeśli ma być pauzowanie okna w tle\n if( focus )\n Global::iPause &= ~4; \/\/ odpauzowanie, gdy jest na pierwszym planie\n else\n Global::iPause |= 4; \/\/ włączenie pauzy, gdy nieaktywy\n}\n\nvoid scroll_callback( GLFWwindow* window, double xoffset, double yoffset ) {\n\n if( Global::ctrlState ) {\n \/\/ ctrl + scroll wheel adjusts fov in debug mode\n Global::FieldOfView = clamp( static_cast(Global::FieldOfView - yoffset * 20.0 \/ Global::fFpsAverage), 15.0f, 75.0f );\n }\n}\n\n#ifdef _WINDOWS\nextern \"C\"\n{\n GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window);\n}\n\nLONG CALLBACK unhandled_handler(::EXCEPTION_POINTERS* e);\nLRESULT APIENTRY WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);\nextern HWND Hwnd;\nextern WNDPROC BaseWindowProc;\n#endif\n\nint main(int argc, char *argv[])\n{\n#ifdef _WINDOWS\n\t::SetUnhandledExceptionFilter(unhandled_handler);\n#endif\n\n\tif (!glfwInit())\n\t\treturn -1;\n\n#ifdef _WINDOWS\n DeleteFile( \"log.txt\" );\n DeleteFile( \"errors.txt\" );\n mkdir(\"logs\");\n#endif\n Global::LoadIniFile(\"eu07.ini\");\n Global::InitKeys();\n\n \/\/ hunter-271211: ukrywanie konsoli\n if( Global::iWriteLogEnabled & 2 )\n\t{\n AllocConsole();\n SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN );\n }\n\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\tstd::string token(argv[i]);\n\n\t\tif (token == \"-modifytga\")\n\t\t\tGlobal::iModifyTGA = -1;\n\t\telse if (token == \"-e3d\")\n\t\t{\n\t\t\tif (Global::iConvertModels > 0)\n\t\t\t\tGlobal::iConvertModels = -Global::iConvertModels;\n\t\t\telse\n\t\t\t\tGlobal::iConvertModels = -7; \/\/ z optymalizacją, bananami i prawidłowym Opacity\n\t\t}\n\t\telse if (i + 1 < argc && token == \"-s\")\n\t\t\tGlobal::SceneryFile = std::string(argv[++i]);\n\t\telse if (i + 1 < argc && token == \"-v\")\n\t\t{\n\t\t\tstd::string v(argv[++i]);\n\t\t\tstd::transform(v.begin(), v.end(), v.begin(), ::tolower);\n\t\t\tGlobal::asHumanCtrlVehicle = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"usage: \" << std::string(argv[0]) << \" [-s sceneryfilepath] \"\n\t\t\t\t << \"[-v vehiclename] [-modifytga] [-e3d]\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n \/\/ match requested video mode to current to allow for\n \/\/ fullwindow creation when resolution is the same\n GLFWmonitor *monitor = glfwGetPrimaryMonitor();\n const GLFWvidmode *vmode = glfwGetVideoMode(monitor);\n\n glfwWindowHint(GLFW_RED_BITS, vmode->redBits);\n glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);\n glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);\n glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);\n\n glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);\n if( Global::iMultisampling > 0 ) {\n glfwWindowHint( GLFW_SAMPLES, 1 << Global::iMultisampling );\n }\n\n if (Global::bFullScreen)\n\t{\n \/\/ match screen dimensions with selected monitor, for 'borderless window' in fullscreen mode\n Global::iWindowWidth = vmode->width;\n Global::iWindowHeight = vmode->height;\n }\n\n GLFWwindow *window =\n glfwCreateWindow( Global::iWindowWidth, Global::iWindowHeight,\n\t\t\tGlobal::AppName.c_str(), Global::bFullScreen ? monitor : nullptr, nullptr );\n\n if (!window)\n\t{\n std::cout << \"failed to create window\" << std::endl;\n return -1;\n }\n glfwMakeContextCurrent(window);\n glfwSwapInterval(Global::VSync ? 1 : 0); \/\/vsync\n glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); \/\/capture cursor\n glfwSetCursorPos(window, 0.0, 0.0);\n glfwSetFramebufferSizeCallback(window, window_resize_callback);\n glfwSetCursorPosCallback(window, cursor_pos_callback);\n glfwSetKeyCallback(window, key_callback);\n glfwSetScrollCallback( window, scroll_callback );\n glfwSetWindowFocusCallback(window, focus_callback);\n {\n int width, height;\n glfwGetFramebufferSize(window, &width, &height);\n window_resize_callback(window, width, height);\n }\n\n if (glewInit() != GLEW_OK)\n\t{\n std::cout << \"failed to init GLEW\" << std::endl;\n return -1;\n }\n\n#ifdef _WINDOWS\n \/\/ setup wrapper for base glfw window proc, to handle copydata messages\n Hwnd = glfwGetWin32Window( window );\n BaseWindowProc = (WNDPROC)::SetWindowLongPtr( Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc );\n \/\/ switch off the topmost flag\n ::SetWindowPos( Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );\n\n const HANDLE icon = ::LoadImage(\n ::GetModuleHandle( 0 ),\n MAKEINTRESOURCE( IDI_ICON1 ),\n IMAGE_ICON,\n ::GetSystemMetrics( SM_CXSMICON ),\n ::GetSystemMetrics( SM_CYSMICON ),\n 0 );\n if( icon )\n ::SendMessage( Hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast( icon ) );\n#endif\n\n if( ( false == GfxRenderer.Init( window ) )\n || ( false == UILayer.init( window ) ) ) {\n\n return -1;\n }\n input::Keyboard.init();\n input::Gamepad.init();\n\n Global::pWorld = &World; \/\/ Ra: wskaźnik potrzebny do usuwania pojazdów\n\ttry\n\t{\n\t\tif (!World.Init(window))\n\t\t{\n\t\t\tstd::cout << \"failed to init TWorld\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\t}\n\tcatch (std::runtime_error e)\n\t{\n\t\tWriteLog(e.what());\n\t\treturn -1;\n\t}\n\n Console *pConsole = new Console(); \/\/ Ra: nie wiem, czy ma to sens, ale jakoś zainicjowac trzeba\n\/*\n if( !joyGetNumDevs() )\n WriteLog( \"No joystick\" );\n*\/\n if( Global::iModifyTGA < 0 ) { \/\/ tylko modyfikacja TGA, bez uruchamiania symulacji\n Global::iMaxTextureSize = 64; \/\/żeby nie zamulać pamięci\n World.ModifyTGA(); \/\/ rekurencyjne przeglądanie katalogów\n }\n else {\n if( Global::iConvertModels < 0 ) {\n Global::iConvertModels = -Global::iConvertModels;\n World.CreateE3D( \"models\\\\\" ); \/\/ rekurencyjne przeglądanie katalogów\n World.CreateE3D( \"dynamic\\\\\", true );\n } \/\/ po zrobieniu E3D odpalamy normalnie scenerię, by ją zobaczyć\n\n Console::On(); \/\/ włączenie konsoli\n while (!glfwWindowShouldClose(window)\n && World.Update()\n && GfxRenderer.Render())\n {\n glfwPollEvents();\n input::Gamepad.poll();\n }\n Console::Off(); \/\/ wyłączenie konsoli (komunikacji zwrotnej)\n }\n\n\tTPythonInterpreter::killInstance();\n\tdelete pConsole;\n\n\tglfwDestroyWindow(window);\n\tglfwTerminate();\n\n\treturn 0;\n}\ncatch exceptions in gfxrenderer init and other inits\/*\nThis Source Code Form is subject to the\nterms of the Mozilla Public License, v.\n2.0. If a copy of the MPL was not\ndistributed with this file, You can\nobtain one at\nhttp:\/\/mozilla.org\/MPL\/2.0\/.\n*\/\n\/*\n MaSzyna EU07 locomotive simulator\n Copyright (C) 2001-2004 Marcin Wozniak, Maciej Czapkiewicz and others\n\n*\/\n\/*\nAuthors:\nMarcinW, McZapkie, Shaxbee, ABu, nbmx, youBy, Ra, winger, mamut, Q424,\nStele, firleju, szociu, hunter, ZiomalCl, OLI_EU and others\n*\/\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n\n#include \"Globals.h\"\n#include \"Logs.h\"\n#include \"keyboardinput.h\"\n#include \"gamepadinput.h\"\n#include \"Console.h\"\n#include \"PyInt.h\"\n#include \"World.h\"\n#include \"Mover.h\"\n#include \"usefull.h\"\n#include \"timer.h\"\n#include \"resource.h\"\n#include \"uilayer.h\"\n\n#pragma comment (lib, \"glu32.lib\")\n#pragma comment (lib, \"dsound.lib\")\n#pragma comment (lib, \"winmm.lib\")\n#pragma comment (lib, \"setupapi.lib\")\n#pragma comment (lib, \"dbghelp.lib\")\n\nTWorld World;\n\nnamespace input {\n\nkeyboard_input Keyboard;\ngamepad_input Gamepad;\n\n}\n\nvoid screenshot_save_thread( char *img )\n{\n\tpng_image png;\n\tmemset(&png, 0, sizeof(png_image));\n\tpng.version = PNG_IMAGE_VERSION;\n\tpng.width = Global::ScreenWidth;\n\tpng.height = Global::ScreenHeight;\n\tpng.format = PNG_FORMAT_RGB;\n\n\tchar datetime[64];\n\ttime_t timer;\n\tstruct tm* tm_info;\n\ttime(&timer);\n\ttm_info = localtime(&timer);\n\tstrftime(datetime, 64, \"%Y-%m-%d_%H-%M-%S\", tm_info);\n\n\tuint64_t perf;\n\tQueryPerformanceCounter((LARGE_INTEGER*)&perf);\n\n\tstd::string filename = \"screenshots\/\" + std::string(datetime) +\n\t \"_\" + std::to_string(perf) + \".png\";\n\n\tif (png_image_write_to_file(&png, filename.c_str(), 0, img, -Global::ScreenWidth * 3, nullptr) == 1)\n\t\tWriteLog(\"saved \" + filename + \".\");\n\telse\n\t\tWriteLog(\"failed to save screenshot.\");\n\n\tdelete[] img;\n}\n\nvoid make_screenshot()\n{\n\tchar *img = new char[Global::ScreenWidth * Global::ScreenHeight * 3];\n\tglReadPixels(0, 0, Global::ScreenWidth, Global::ScreenHeight, GL_RGB, GL_UNSIGNED_BYTE, (GLvoid*)img);\n\n\tstd::thread t(screenshot_save_thread, img);\n\tt.detach();\n}\n\nvoid window_resize_callback(GLFWwindow *window, int w, int h)\n{\n \/\/ NOTE: we have two variables which basically do the same thing as we don't have dynamic fullscreen toggle\n \/\/ TBD, TODO: merge them?\n\tGlobal::ScreenWidth = Global::iWindowWidth = w;\n\tGlobal::ScreenHeight = Global::iWindowHeight = h;\n Global::fDistanceFactor = std::max( 0.5f, h \/ 768.0f ); \/\/ not sure if this is really something we want to use\n\tglViewport(0, 0, w, h);\n}\n\nvoid cursor_pos_callback(GLFWwindow *window, double x, double y)\n{\n input::Keyboard.mouse( x, y );\n#ifdef EU07_USE_OLD_COMMAND_SYSTEM\n\tWorld.OnMouseMove(x * 0.005, y * 0.01);\n#endif\n\tglfwSetCursorPos(window, 0.0, 0.0);\n}\n\nvoid key_callback( GLFWwindow *window, int key, int scancode, int action, int mods )\n{\n input::Keyboard.key( key, action );\n\n Global::shiftState = ( mods & GLFW_MOD_SHIFT ) ? true : false;\n Global::ctrlState = ( mods & GLFW_MOD_CONTROL ) ? true : false;\n\n if( ( key == GLFW_KEY_LEFT_SHIFT )\n || ( key == GLFW_KEY_LEFT_CONTROL )\n || ( key == GLFW_KEY_LEFT_ALT )\n || ( key == GLFW_KEY_RIGHT_SHIFT )\n || ( key == GLFW_KEY_RIGHT_CONTROL )\n || ( key == GLFW_KEY_RIGHT_ALT ) ) {\n \/\/ don't bother passing these\n return;\n }\n\n if( action == GLFW_PRESS || action == GLFW_REPEAT )\n {\n World.OnKeyDown( key );\n\n switch( key )\n {\n\n case GLFW_KEY_F11: {\n make_screenshot();\n break;\n }\n\n default: { break; }\n }\n }\n}\n\nvoid focus_callback( GLFWwindow *window, int focus )\n{\n if( Global::bInactivePause ) \/\/ jeśli ma być pauzowanie okna w tle\n if( focus )\n Global::iPause &= ~4; \/\/ odpauzowanie, gdy jest na pierwszym planie\n else\n Global::iPause |= 4; \/\/ włączenie pauzy, gdy nieaktywy\n}\n\nvoid scroll_callback( GLFWwindow* window, double xoffset, double yoffset ) {\n\n if( Global::ctrlState ) {\n \/\/ ctrl + scroll wheel adjusts fov in debug mode\n Global::FieldOfView = clamp( static_cast(Global::FieldOfView - yoffset * 20.0 \/ Global::fFpsAverage), 15.0f, 75.0f );\n }\n}\n\n#ifdef _WINDOWS\nextern \"C\"\n{\n GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window);\n}\n\nLONG CALLBACK unhandled_handler(::EXCEPTION_POINTERS* e);\nLRESULT APIENTRY WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam);\nextern HWND Hwnd;\nextern WNDPROC BaseWindowProc;\n#endif\n\nint main(int argc, char *argv[])\n{\n#ifdef _WINDOWS\n\t::SetUnhandledExceptionFilter(unhandled_handler);\n#endif\n\n\tif (!glfwInit())\n\t\treturn -1;\n\n#ifdef _WINDOWS\n DeleteFile( \"log.txt\" );\n DeleteFile( \"errors.txt\" );\n mkdir(\"logs\");\n#endif\n Global::LoadIniFile(\"eu07.ini\");\n Global::InitKeys();\n\n \/\/ hunter-271211: ukrywanie konsoli\n if( Global::iWriteLogEnabled & 2 )\n\t{\n AllocConsole();\n SetConsoleTextAttribute( GetStdHandle( STD_OUTPUT_HANDLE ), FOREGROUND_GREEN );\n }\n\n\tfor (int i = 1; i < argc; i++)\n\t{\n\t\tstd::string token(argv[i]);\n\n\t\tif (token == \"-modifytga\")\n\t\t\tGlobal::iModifyTGA = -1;\n\t\telse if (token == \"-e3d\")\n\t\t{\n\t\t\tif (Global::iConvertModels > 0)\n\t\t\t\tGlobal::iConvertModels = -Global::iConvertModels;\n\t\t\telse\n\t\t\t\tGlobal::iConvertModels = -7; \/\/ z optymalizacją, bananami i prawidłowym Opacity\n\t\t}\n\t\telse if (i + 1 < argc && token == \"-s\")\n\t\t\tGlobal::SceneryFile = std::string(argv[++i]);\n\t\telse if (i + 1 < argc && token == \"-v\")\n\t\t{\n\t\t\tstd::string v(argv[++i]);\n\t\t\tstd::transform(v.begin(), v.end(), v.begin(), ::tolower);\n\t\t\tGlobal::asHumanCtrlVehicle = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"usage: \" << std::string(argv[0]) << \" [-s sceneryfilepath] \"\n\t\t\t\t << \"[-v vehiclename] [-modifytga] [-e3d]\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\t}\n\n \/\/ match requested video mode to current to allow for\n \/\/ fullwindow creation when resolution is the same\n GLFWmonitor *monitor = glfwGetPrimaryMonitor();\n const GLFWvidmode *vmode = glfwGetVideoMode(monitor);\n\n glfwWindowHint(GLFW_RED_BITS, vmode->redBits);\n glfwWindowHint(GLFW_GREEN_BITS, vmode->greenBits);\n glfwWindowHint(GLFW_BLUE_BITS, vmode->blueBits);\n glfwWindowHint(GLFW_REFRESH_RATE, vmode->refreshRate);\n\n glfwWindowHint(GLFW_AUTO_ICONIFY, GLFW_FALSE);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);\n\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);\n if( Global::iMultisampling > 0 ) {\n glfwWindowHint( GLFW_SAMPLES, 1 << Global::iMultisampling );\n }\n\n if (Global::bFullScreen)\n\t{\n \/\/ match screen dimensions with selected monitor, for 'borderless window' in fullscreen mode\n Global::iWindowWidth = vmode->width;\n Global::iWindowHeight = vmode->height;\n }\n\n GLFWwindow *window =\n glfwCreateWindow( Global::iWindowWidth, Global::iWindowHeight,\n\t\t\tGlobal::AppName.c_str(), Global::bFullScreen ? monitor : nullptr, nullptr );\n\n if (!window)\n\t{\n std::cout << \"failed to create window\" << std::endl;\n return -1;\n }\n glfwMakeContextCurrent(window);\n glfwSwapInterval(Global::VSync ? 1 : 0); \/\/vsync\n glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); \/\/capture cursor\n glfwSetCursorPos(window, 0.0, 0.0);\n glfwSetFramebufferSizeCallback(window, window_resize_callback);\n glfwSetCursorPosCallback(window, cursor_pos_callback);\n glfwSetKeyCallback(window, key_callback);\n glfwSetScrollCallback( window, scroll_callback );\n glfwSetWindowFocusCallback(window, focus_callback);\n {\n int width, height;\n glfwGetFramebufferSize(window, &width, &height);\n window_resize_callback(window, width, height);\n }\n\n if (glewInit() != GLEW_OK)\n\t{\n std::cout << \"failed to init GLEW\" << std::endl;\n return -1;\n }\n\n#ifdef _WINDOWS\n \/\/ setup wrapper for base glfw window proc, to handle copydata messages\n Hwnd = glfwGetWin32Window( window );\n BaseWindowProc = (WNDPROC)::SetWindowLongPtr( Hwnd, GWLP_WNDPROC, (LONG_PTR)WndProc );\n \/\/ switch off the topmost flag\n ::SetWindowPos( Hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );\n\n const HANDLE icon = ::LoadImage(\n ::GetModuleHandle( 0 ),\n MAKEINTRESOURCE( IDI_ICON1 ),\n IMAGE_ICON,\n ::GetSystemMetrics( SM_CXSMICON ),\n ::GetSystemMetrics( SM_CYSMICON ),\n 0 );\n if( icon )\n ::SendMessage( Hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast( icon ) );\n#endif\n\n Global::pWorld = &World; \/\/ Ra: wskaźnik potrzebny do usuwania pojazdów\n\ttry\n\t{\n\t\tif ((false == GfxRenderer.Init(window))\n\t\t\t|| (false == UILayer.init(window)))\n\t\t\treturn -1;\n\t\tinput::Keyboard.init();\n\t\tinput::Gamepad.init();\n\n\t\tif (!World.Init(window))\n\t\t{\n\t\t\tstd::cout << \"failed to init TWorld\" << std::endl;\n\t\t\treturn -1;\n\t\t}\n\t}\n\tcatch (std::runtime_error e)\n\t{\n\t\tWriteLog(e.what());\n\t\treturn -1;\n\t}\n\n Console *pConsole = new Console(); \/\/ Ra: nie wiem, czy ma to sens, ale jakoś zainicjowac trzeba\n\/*\n if( !joyGetNumDevs() )\n WriteLog( \"No joystick\" );\n*\/\n if( Global::iModifyTGA < 0 ) { \/\/ tylko modyfikacja TGA, bez uruchamiania symulacji\n Global::iMaxTextureSize = 64; \/\/żeby nie zamulać pamięci\n World.ModifyTGA(); \/\/ rekurencyjne przeglądanie katalogów\n }\n else {\n if( Global::iConvertModels < 0 ) {\n Global::iConvertModels = -Global::iConvertModels;\n World.CreateE3D( \"models\\\\\" ); \/\/ rekurencyjne przeglądanie katalogów\n World.CreateE3D( \"dynamic\\\\\", true );\n } \/\/ po zrobieniu E3D odpalamy normalnie scenerię, by ją zobaczyć\n\n Console::On(); \/\/ włączenie konsoli\n while (!glfwWindowShouldClose(window)\n && World.Update()\n && GfxRenderer.Render())\n {\n glfwPollEvents();\n input::Gamepad.poll();\n }\n Console::Off(); \/\/ wyłączenie konsoli (komunikacji zwrotnej)\n }\n\n\tTPythonInterpreter::killInstance();\n\tdelete pConsole;\n\n\tglfwDestroyWindow(window);\n\tglfwTerminate();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL.hpp\"\n\nnamespace ReQL {\n\nResult::Result() : type(REQL_R_JSON) {}\n\nResult::Result(const Result &other) {\n value.copy(other.value, type);\n}\n\nResult::Result(Result &&other) {\n value.move(std::move(other.value), type);\n}\n\nResult::~Result() {\n value.release(type);\n}\n\nResult &\nResult::operator=(const Result &other) {\n if (this != &other) {\n value.copy(other.value, type);\n }\n return *this;\n}\n\nResult &\nResult::operator=(Result &&other) {\n if (this != &other) {\n value.move(std::move(other.value), type);\n }\n return *this;\n}\n \nResult::JSON_Value::JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nResult::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array = other.array;\n break;\n }\n case REQL_R_BOOL: {\n boolean = other.boolean;\n break;\n }\n case REQL_R_NUM: {\n num = other.num;\n break;\n }\n case REQL_R_OBJECT: {\n object = other.object;\n break;\n }\n case REQL_R_STR: {\n string = other.string;\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array = std::move(other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = std::move(other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = std::move(other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = std::move(other.object);\n break;\n }\n case REQL_R_STR: {\n string = std::move(other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::release(ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array.~vector();\n break;\n }\n case REQL_R_OBJECT: {\n object.~map();\n break;\n }\n case REQL_R_STR: {\n string.~basic_string();\n break;\n }\n case REQL_R_BOOL:\n case REQL_R_JSON:\n case REQL_R_NULL:\n case REQL_R_NUM:\n case REQL_R_REQL: break;\n }\n}\n\nResult::JSON_Value::~JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n \nvoid\nParser::parse(ReQL_Obj_t *val) {\n switch (reql_datum_type(val)) {\n case REQL_R_ARRAY: {\n startArray();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *elem = NULL;\n\n while ((elem = reql_iter_next(&it)) != NULL) {\n parse(elem);\n }\n\n endArray();\n break;\n }\n case REQL_R_BOOL: {\n addElement(static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_NULL: {\n addElement();\n break;\n }\n case REQL_R_NUM: {\n addElement(reql_to_number(val));\n break;\n }\n case REQL_R_OBJECT: {\n startObject();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *key = NULL;\n ReQL_Obj_t *value = NULL;\n\n while ((key = reql_iter_next(&it)) != NULL) {\n value = reql_object_get(val, key);\n std::string key_string((char *)reql_string_buf(key), reql_size(key));\n\n switch (reql_datum_type(value)) {\n case REQL_R_BOOL: {\n addKeyValue(key_string, static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_ARRAY:\n case REQL_R_OBJECT: {\n addKey(key_string);\n parse(value);\n break;\n }\n case REQL_R_NULL: {\n addKeyValue(key_string);\n break;\n }\n case REQL_R_NUM: {\n addKeyValue(key_string, reql_to_number(value));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_STR: {\n addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));\n break;\n }\n }\n }\n \n endObject();\n break;\n }\n case REQL_R_STR: {\n addElement(std::string((char *)reql_string_buf(val), reql_size(val)));\n break;\n }\n }\n}\n\nclass ResultBuilder : public Parser {\npublic:\n Result result() { return p_result; }\n\nprivate:\n void startObject() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_OBJECT;\n p_stack.end()->value.object = std::map();\n }\n\n void addKey(std::string key) {\n p_keys.push_back(key);\n }\n\n void addKeyValue(std::string key) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = value;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = value;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, std::string value) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void endObject() {\n end();\n }\n\n void startArray() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_ARRAY;\n p_stack.end()->value.array = std::vector();\n }\n\n void addElement() {\n Result res;\n res.type = REQL_R_NULL;\n addElement(std::move(res));\n }\n\n void addElement(bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = value;\n addElement(std::move(res));\n }\n\n void addElement(double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = value;\n addElement(std::move(res));\n }\n\n void addElement(std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = value;\n addElement(std::move(res));\n }\n\n void endArray() {\n end();\n }\n\n void addElement(Result &&val) {\n if (p_stack.empty()) {\n p_result = std::move(val);\n } else {\n std::vector *array = &p_stack.end()->value.array;\n array->insert(array->end(), std::move(val));\n }\n }\n\n void end() {\n Result last = *p_stack.end();\n p_stack.pop_back();\n if (p_stack.empty()) {\n p_result = last;\n } else if (p_stack.end()->type == REQL_R_OBJECT) {\n std::string key = *p_keys.end();\n p_keys.pop_back();\n p_stack.end()->value.object.insert({key, last});\n } else {\n addElement(std::move(last));\n }\n }\n\n std::vector p_stack;\n std::vector p_keys;\n Result p_result;\n};\n\nCursor::Cursor() : cur(new ReQL_Cur_t) {\n reql_cursor_init(data());\n}\n\nCursor::~Cursor() {\n}\n\nbool Cursor::isOpen() const {\n return reql_cur_open(data());\n}\n\nResult\nCursor::next() {\n ResultBuilder builder;\n next(builder);\n return builder.result();\n}\n\nvoid\nCursor::next(Parser &p) {\n p.parse(reql_cursor_next(data()));\n}\n\nReQL_Cur_t *\nCursor::data() const {\n return cur.get();\n}\n\nvoid\nCursor::close() {\n}\n\nConnection::Connection() : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n if (key.size() > UINT32_MAX) {\n }\n\n std::uint32_t key_len = (std::uint32_t)key.size();\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n reql_conn_set_auth(data(), key_len, (char *)key.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const Connection &other) {\n}\n\nConnection::Connection(Connection &&other) {\n conn = std::move(other.conn);\n}\n\nConnection::~Connection() {\n reql_ensure_conn_close(data());\n}\n\nConnection &Connection::operator=(const Connection &other) {\n return *this;\n}\n\nConnection &Connection::operator=(Connection &&other) {\n conn = std::move(other.conn);\n return *this;\n}\n\nvoid\nConnection::close() {\n reql_close_conn(data());\n}\n\nbool\nConnection::isOpen() const {\n return reql_conn_open(data());\n}\n\nReQL_Conn_t *\nConnection::data() const {\n return conn.get();\n}\n\nCursor Query::run(const Connection &conn) const {\n if (!conn.isOpen()) {\n }\n\n Cursor cur;\n\n ReQL kwargs;\n\n reql_run(cur.data(), p_query.data(), conn.data(), kwargs.data());\n\n return cur;\n}\n\nQuery &Query::operator=(const Query &other) {\n Expr::operator=(other);\n return *this;\n}\n\nQuery &Query::operator=(Query &&other) {\n Expr::operator=(std::move(other));\n return *this;\n}\n\nbool Query::operator<(const Query &other) const {\n return Expr::operator<(other);\n}\n\n}\nAdd include for `memset`.\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL.hpp\"\n\n#include \n\nnamespace ReQL {\n\nResult::Result() : type(REQL_R_JSON) {}\n\nResult::Result(const Result &other) {\n value.copy(other.value, type);\n}\n\nResult::Result(Result &&other) {\n value.move(std::move(other.value), type);\n}\n\nResult::~Result() {\n value.release(type);\n}\n\nResult &\nResult::operator=(const Result &other) {\n if (this != &other) {\n value.copy(other.value, type);\n }\n return *this;\n}\n\nResult &\nResult::operator=(Result &&other) {\n if (this != &other) {\n value.move(std::move(other.value), type);\n }\n return *this;\n}\n \nResult::JSON_Value::JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nResult::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array = other.array;\n break;\n }\n case REQL_R_BOOL: {\n boolean = other.boolean;\n break;\n }\n case REQL_R_NUM: {\n num = other.num;\n break;\n }\n case REQL_R_OBJECT: {\n object = other.object;\n break;\n }\n case REQL_R_STR: {\n string = other.string;\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array = std::move(other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = std::move(other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = std::move(other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = std::move(other.object);\n break;\n }\n case REQL_R_STR: {\n string = std::move(other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::release(ReQL_Datum_t type) {\n switch (type) {\n case REQL_R_ARRAY: {\n array.~vector();\n break;\n }\n case REQL_R_OBJECT: {\n object.~map();\n break;\n }\n case REQL_R_STR: {\n string.~basic_string();\n break;\n }\n case REQL_R_BOOL:\n case REQL_R_JSON:\n case REQL_R_NULL:\n case REQL_R_NUM:\n case REQL_R_REQL: break;\n }\n}\n\nResult::JSON_Value::~JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n \nvoid\nParser::parse(ReQL_Obj_t *val) {\n switch (reql_datum_type(val)) {\n case REQL_R_ARRAY: {\n startArray();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *elem = NULL;\n\n while ((elem = reql_iter_next(&it)) != NULL) {\n parse(elem);\n }\n\n endArray();\n break;\n }\n case REQL_R_BOOL: {\n addElement(static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_NULL: {\n addElement();\n break;\n }\n case REQL_R_NUM: {\n addElement(reql_to_number(val));\n break;\n }\n case REQL_R_OBJECT: {\n startObject();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *key = NULL;\n ReQL_Obj_t *value = NULL;\n\n while ((key = reql_iter_next(&it)) != NULL) {\n value = reql_object_get(val, key);\n std::string key_string((char *)reql_string_buf(key), reql_size(key));\n\n switch (reql_datum_type(value)) {\n case REQL_R_BOOL: {\n addKeyValue(key_string, static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_ARRAY:\n case REQL_R_OBJECT: {\n addKey(key_string);\n parse(value);\n break;\n }\n case REQL_R_NULL: {\n addKeyValue(key_string);\n break;\n }\n case REQL_R_NUM: {\n addKeyValue(key_string, reql_to_number(value));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_STR: {\n addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));\n break;\n }\n }\n }\n \n endObject();\n break;\n }\n case REQL_R_STR: {\n addElement(std::string((char *)reql_string_buf(val), reql_size(val)));\n break;\n }\n }\n}\n\nclass ResultBuilder : public Parser {\npublic:\n Result result() { return p_result; }\n\nprivate:\n void startObject() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_OBJECT;\n p_stack.end()->value.object = std::map();\n }\n\n void addKey(std::string key) {\n p_keys.push_back(key);\n }\n\n void addKeyValue(std::string key) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = value;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = value;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void addKeyValue(std::string key, std::string value) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object.insert({key, res});\n }\n\n void endObject() {\n end();\n }\n\n void startArray() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_ARRAY;\n p_stack.end()->value.array = std::vector();\n }\n\n void addElement() {\n Result res;\n res.type = REQL_R_NULL;\n addElement(std::move(res));\n }\n\n void addElement(bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = value;\n addElement(std::move(res));\n }\n\n void addElement(double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = value;\n addElement(std::move(res));\n }\n\n void addElement(std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = value;\n addElement(std::move(res));\n }\n\n void endArray() {\n end();\n }\n\n void addElement(Result &&val) {\n if (p_stack.empty()) {\n p_result = std::move(val);\n } else {\n std::vector *array = &p_stack.end()->value.array;\n array->insert(array->end(), std::move(val));\n }\n }\n\n void end() {\n Result last = *p_stack.end();\n p_stack.pop_back();\n if (p_stack.empty()) {\n p_result = last;\n } else if (p_stack.end()->type == REQL_R_OBJECT) {\n std::string key = *p_keys.end();\n p_keys.pop_back();\n p_stack.end()->value.object.insert({key, last});\n } else {\n addElement(std::move(last));\n }\n }\n\n std::vector p_stack;\n std::vector p_keys;\n Result p_result;\n};\n\nCursor::Cursor() : cur(new ReQL_Cur_t) {\n reql_cursor_init(data());\n}\n\nCursor::~Cursor() {\n}\n\nbool Cursor::isOpen() const {\n return reql_cur_open(data());\n}\n\nResult\nCursor::next() {\n ResultBuilder builder;\n next(builder);\n return builder.result();\n}\n\nvoid\nCursor::next(Parser &p) {\n p.parse(reql_cursor_next(data()));\n}\n\nReQL_Cur_t *\nCursor::data() const {\n return cur.get();\n}\n\nvoid\nCursor::close() {\n}\n\nConnection::Connection() : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n if (key.size() > UINT32_MAX) {\n }\n\n std::uint32_t key_len = (std::uint32_t)key.size();\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n reql_conn_set_auth(data(), key_len, (char *)key.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const Connection &other) {\n}\n\nConnection::Connection(Connection &&other) {\n conn = std::move(other.conn);\n}\n\nConnection::~Connection() {\n reql_ensure_conn_close(data());\n}\n\nConnection &Connection::operator=(const Connection &other) {\n return *this;\n}\n\nConnection &Connection::operator=(Connection &&other) {\n conn = std::move(other.conn);\n return *this;\n}\n\nvoid\nConnection::close() {\n reql_close_conn(data());\n}\n\nbool\nConnection::isOpen() const {\n return reql_conn_open(data());\n}\n\nReQL_Conn_t *\nConnection::data() const {\n return conn.get();\n}\n\nCursor Query::run(const Connection &conn) const {\n if (!conn.isOpen()) {\n }\n\n Cursor cur;\n\n ReQL kwargs;\n\n reql_run(cur.data(), p_query.data(), conn.data(), kwargs.data());\n\n return cur;\n}\n\nQuery &Query::operator=(const Query &other) {\n Expr::operator=(other);\n return *this;\n}\n\nQuery &Query::operator=(Query &&other) {\n Expr::operator=(std::move(other));\n return *this;\n}\n\nbool Query::operator<(const Query &other) const {\n return Expr::operator<(other);\n}\n\n}\n<|endoftext|>"} {"text":"#include \"Sign.h\"\n\nSign::Sign(void){\n\n uint8_t lengths[LETTERS_COUNT][16] = {\n {3, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2}\n };\n\n for(uint16_t i=0; i < LETTERS_COUNT; i++){\n letters[i] = new Letter(lengths[i]);\n for(uint16_t j=0; j<16; j++){\n segments[(i*16)+j] = letters[i] -> segments[j];\n }\n }\n \/\/uint16_t pixel_count = this -> pixelCount();\n\n characters[0] = 'D';\n characters[1] = 'A';\n characters[2] = 'D';\n characters[3] = 'A';\n};\n\nvoid Sign::pushChar(char character){\n this -> pushChar(character, false);\n}\nvoid Sign::pushChar(char character, bool shouldPrint){\n if( shouldPrint ){\n Serial.print(character);\n Serial1.print(character);\n }\n if( binarySegsForChar(character) == 0xFFFF ){ return; }\n\n for(uint8_t i=0; i< LETTERS_COUNT - 1; i++){\n characters[i] = characters[i+1];\n }\n characters[LETTERS_COUNT-1] = character;\n\n this -> sanitize();\n\n for(uint8_t i=0; i< LETTERS_COUNT; i++){\n letters[i] -> currentChar = characters[i];\n }\n}\n\nvoid Sign::setCharacters(){\n for(uint8_t i=0; i letters[i] -> setChar(characters[i]);\n }\n}\n\nvoid Sign::setLayer(uint8_t layer, bool isOn){\n for(uint8_t i=0; i setLayer(layer, isOn);\n }\n}\n\nvoid Sign::setWord(String word){\n uint8_t size = min((uint8_t)word.length(), LETTERS_COUNT);\n\n for(uint8_t i=0; i sanitize();\n\n for(uint8_t i=0; i setChar( characters[i] );\n }\n}\n\nvoid Sign::_setWord(String word, uint8_t size){\n char ctr;\n for(uint8_t i=0; i< size; i++){\n ctr = word.charAt(i);\n characters[i] = ctr;\n letters[i] -> setChar( ctr );\n }\n}\n\n#define BAD_WORDS_COUNT 18\nconst String badWords[BAD_WORDS_COUNT] = {\n \/\/\"TEST\"\n \"CUNT\", \"GOOK\", \"FUCK\", \"SHIT\", \"FAGG\",\n \"FAG \", \" FAG\", \"COON\", \"HEEB\", \"SLUT\",\n \"COON\", \"KKK \", \" KKK\", \"KYKE\", \"SPIC\",\n \"SPIK\", \"TWAT\", \"HOMO\"\n};\n\nvoid Sign::sanitize(){\n String ctrs = String(characters).substring(0, LETTERS_COUNT);\n String badWord;\n for(uint8_t i=0; i< BAD_WORDS_COUNT; i++){\n badWord = badWords[i];\n if(badWord.equalsIgnoreCase(ctrs)){\n this -> _setWord(String(\"LOVE\"), LETTERS_COUNT);\n }\n }\n}\n\nuint16_t Sign::pixelCount(){\n\n if(_pixel_count > 0){\n return _pixel_count;\n }\n\n uint16_t pixel_count = 0;\n for(uint8_t i = 0; i < LETTERS_COUNT; i++){\n pixel_count += letters[i]->pixelCount();\n }\n _pixel_count = pixel_count;\n return pixel_count;\n}\n\nuint8_t Sign::letterCount(){\n return LETTERS_COUNT;\n}\n\nuint16_t Sign::segmentCount(){\n return 16*LETTERS_COUNT;\n}\nRemove SHIT and FUCK from bad words list#include \"Sign.h\"\n\nSign::Sign(void){\n\n uint8_t lengths[LETTERS_COUNT][16] = {\n {3, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2},\n {2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 4, 4, 2, 2, 2, 2}\n };\n\n for(uint16_t i=0; i < LETTERS_COUNT; i++){\n letters[i] = new Letter(lengths[i]);\n for(uint16_t j=0; j<16; j++){\n segments[(i*16)+j] = letters[i] -> segments[j];\n }\n }\n \/\/uint16_t pixel_count = this -> pixelCount();\n\n characters[0] = 'D';\n characters[1] = 'A';\n characters[2] = 'D';\n characters[3] = 'A';\n};\n\nvoid Sign::pushChar(char character){\n this -> pushChar(character, false);\n}\nvoid Sign::pushChar(char character, bool shouldPrint){\n if( shouldPrint ){\n Serial.print(character);\n Serial1.print(character);\n }\n if( binarySegsForChar(character) == 0xFFFF ){ return; }\n\n for(uint8_t i=0; i< LETTERS_COUNT - 1; i++){\n characters[i] = characters[i+1];\n }\n characters[LETTERS_COUNT-1] = character;\n\n this -> sanitize();\n\n for(uint8_t i=0; i< LETTERS_COUNT; i++){\n letters[i] -> currentChar = characters[i];\n }\n}\n\nvoid Sign::setCharacters(){\n for(uint8_t i=0; i letters[i] -> setChar(characters[i]);\n }\n}\n\nvoid Sign::setLayer(uint8_t layer, bool isOn){\n for(uint8_t i=0; i setLayer(layer, isOn);\n }\n}\n\nvoid Sign::setWord(String word){\n uint8_t size = min((uint8_t)word.length(), LETTERS_COUNT);\n\n for(uint8_t i=0; i sanitize();\n\n for(uint8_t i=0; i setChar( characters[i] );\n }\n}\n\nvoid Sign::_setWord(String word, uint8_t size){\n char ctr;\n for(uint8_t i=0; i< size; i++){\n ctr = word.charAt(i);\n characters[i] = ctr;\n letters[i] -> setChar( ctr );\n }\n}\n\n#define BAD_WORDS_COUNT 16\nconst String badWords[BAD_WORDS_COUNT] = {\n \/\/\"TEST\"\n \"CUNT\", \"GOOK\", \"FAGG\",\n \"FAG \", \" FAG\", \"COON\", \"HEEB\", \"SLUT\",\n \"COON\", \"KKK \", \" KKK\", \"KYKE\", \"SPIC\",\n \"SPIK\", \"TWAT\", \"HOMO\"\n};\n\nvoid Sign::sanitize(){\n String ctrs = String(characters).substring(0, LETTERS_COUNT);\n String badWord;\n for(uint8_t i=0; i< BAD_WORDS_COUNT; i++){\n badWord = badWords[i];\n if(badWord.equalsIgnoreCase(ctrs)){\n this -> _setWord(String(\"LOVE\"), LETTERS_COUNT);\n }\n }\n}\n\nuint16_t Sign::pixelCount(){\n\n if(_pixel_count > 0){\n return _pixel_count;\n }\n\n uint16_t pixel_count = 0;\n for(uint8_t i = 0; i < LETTERS_COUNT; i++){\n pixel_count += letters[i]->pixelCount();\n }\n _pixel_count = pixel_count;\n return pixel_count;\n}\n\nuint8_t Sign::letterCount(){\n return LETTERS_COUNT;\n}\n\nuint16_t Sign::segmentCount(){\n return 16*LETTERS_COUNT;\n}\n<|endoftext|>"} {"text":"\/\/ cc.in79\n\/\/ problem with templatized forward decl?\n\/\/ no, was a problem with templatized prototypes\n\nclass istream;\n\ntemplate class smanip;\n\/\/template class smanip {};\n\ntemplate\ninline istream& operator>>(istream& i, const smanip& m);\n\/\/int foo(smanip &m);\n\ntypedef smanip smanip_int;\n\ntemplate class smanip {\n smanip *whatever;\n smanip *whatever2;\n};\n\nvoid f()\n{\n smanip_int s;\n s.whatever;\n}\n\nFix gcc compilation issue, thanks to Evan Driscoll.\/\/ in\/t0079.cc\n\/\/ problem with templatized forward decl?\n\/\/ no, was a problem with templatized prototypes\n\nclass istream;\n\ntemplate class smanip;\n\/\/template class smanip {};\n\ntemplate\ninline istream& operator>>(istream& i, const smanip& m);\n\/\/int foo(smanip &m);\n\ntypedef smanip smanip_int;\n\ntemplate class smanip {\npublic:\n smanip *whatever;\n smanip *whatever2;\n};\n\nvoid f()\n{\n smanip_int s;\n s.whatever;\n}\n\n<|endoftext|>"} {"text":"\/* This file is part of VoltDB.\n * Copyright (C) 2008-2013 VoltDB Inc.\n *\n * This file contains original code and\/or modifications of original code.\n * Any modifications made by VoltDB Inc. are licensed under the following\n * terms and conditions:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with VoltDB. If not, see .\n *\/\n\/* Copyright (C) 2008 by H-Store Project\n * Brown University\n * Massachusetts Institute of Technology\n * Yale University\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \"seqscanexecutor.h\"\n#include \"common\/debuglog.h\"\n#include \"common\/common.h\"\n#include \"common\/tabletuple.h\"\n#include \"common\/FatalException.hpp\"\n#include \"expressions\/abstractexpression.h\"\n#include \"plannodes\/seqscannode.h\"\n#include \"plannodes\/projectionnode.h\"\n#include \"plannodes\/limitnode.h\"\n#include \"storage\/table.h\"\n#include \"storage\/temptable.h\"\n#include \"storage\/tablefactory.h\"\n#include \"storage\/tableiterator.h\"\n\nusing namespace voltdb;\n\nbool SeqScanExecutor::p_init(AbstractPlanNode* abstract_node,\n TempTableLimits* limits)\n{\n VOLT_TRACE(\"init SeqScan Executor\");\n\n SeqScanPlanNode* node = dynamic_cast(abstract_node);\n assert(node);\n assert(node->isSubQuery() || node->getTargetTable());\n assert((node->isSubQuery() && node->getChildren().size() == 1) ||\n !node->isSubQuery());\n\n \/\/\n \/\/ OPTIMIZATION: If there is no predicate for this SeqScan,\n \/\/ then we want to just set our OutputTable pointer to be the\n \/\/ pointer of our TargetTable. This prevents us from just\n \/\/ reading through the entire TargetTable and copying all of\n \/\/ the tuples. We are guarenteed that no Executor will ever\n \/\/ modify an input table, so this operation is safe\n \/\/\n if (!this->needsOutputTableClear())\n {\n node->setOutputTable(node->getTargetTable());\n }\n \/\/\n \/\/ Otherwise create a new temp table that mirrors the\n \/\/ output schema specified in the plan (which should mirror\n \/\/ the output schema for any inlined projection)\n \/\/\n else\n {\n \/\/ Create output table based on output schema from the plan\n const std::string& temp_name = (!node->isSubQuery()) ?\n node->getTargetTable()->name() :\n node->getChildren()[0]->getOutputTable()->name();\n setTempOutputTable(limits, temp_name);\n }\n return true;\n}\n\nbool SeqScanExecutor::needsOutputTableClear() {\n \/\/ clear the temporary output table only when it has a predicate.\n \/\/ if it doesn't have a predicate, it's the original persistent table\n \/\/ and we don't have to (and must not) clear it.\n SeqScanPlanNode* node = dynamic_cast(m_abstractNode);\n assert(node);\n return node->needsOutputTableClear();\n}\n\nbool SeqScanExecutor::p_execute(const NValueArray ¶ms) {\n SeqScanPlanNode* node = dynamic_cast(m_abstractNode);\n assert(node);\n Table* output_table = node->getOutputTable();\n assert(output_table);\n\n Table* input_table = (!node->isSubQuery()) ?\n dynamic_cast(node->getTargetTable()) :\n node->getChildren()[0]->getOutputTable();\n\n assert(input_table);\n \/\/cout << \"SeqScanExecutor: node id\" << node->getPlanNodeId() << endl;\n VOLT_TRACE(\"Sequential Scanning table :\\n %s\",\n input_table->debug().c_str());\n VOLT_DEBUG(\"Sequential Scanning table : %s which has %d active, %d\"\n \" allocated\",\n input_table->name().c_str(),\n (int)input_table->activeTupleCount(),\n (int)input_table->allocatedTupleCount());\n\n \/\/\n \/\/ OPTIMIZATION: NESTED PROJECTION\n \/\/\n \/\/ Since we have the input params, we need to call substitute to\n \/\/ change any nodes in our expression tree to be ready for the\n \/\/ projection operations in execute\n \/\/\n int num_of_columns = (int)output_table->columnCount();\n ProjectionPlanNode* projection_node = dynamic_cast(node->getInlinePlanNode(PLAN_NODE_TYPE_PROJECTION));\n if (projection_node != NULL) {\n for (int ctr = 0; ctr < num_of_columns; ctr++) {\n assert(projection_node->getOutputColumnExpressions()[ctr]);\n projection_node->getOutputColumnExpressions()[ctr]->substitute(params);\n }\n }\n\n \/\/\n \/\/ OPTIMIZATION: NESTED LIMIT\n \/\/ How nice! We can also cut off our scanning with a nested limit!\n \/\/\n LimitPlanNode* limit_node = dynamic_cast(node->getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));\n\n \/\/\n \/\/ OPTIMIZATION:\n \/\/\n \/\/ If there is no predicate and no Projection for this SeqScan,\n \/\/ then we have already set the node's OutputTable to just point\n \/\/ at the TargetTable. Therefore, there is nothing we more we need\n \/\/ to do here\n \/\/\n if (node->getPredicate() != NULL || projection_node != NULL ||\n limit_node != NULL)\n {\n \/\/\n \/\/ Just walk through the table using our iterator and apply\n \/\/ the predicate to each tuple. For each tuple that satisfies\n \/\/ our expression, we'll insert them into the output table.\n \/\/\n TableTuple tuple(input_table->schema());\n TableIterator iterator = input_table->iterator();\n AbstractExpression *predicate = node->getPredicate();\n\n if (predicate)\n {\n VOLT_TRACE(\"SCAN PREDICATE A:\\n%s\\n\", predicate->debug(true).c_str());\n predicate->substitute(params);\n assert(predicate != NULL);\n VOLT_DEBUG(\"SCAN PREDICATE B:\\n%s\\n\",\n predicate->debug(true).c_str());\n }\n\n int limit = -1;\n int offset = -1;\n if (limit_node) {\n limit_node->getLimitAndOffsetByReference(params, limit, offset);\n }\n\n int tuple_ctr = 0;\n int tuple_skipped = 0;\n m_engine->setLastAccessedTable(target_table);\n while ((limit == -1 || tuple_ctr < limit) && iterator.next(tuple))\n {\n VOLT_TRACE(\"INPUT TUPLE: %s, %d\/%d\\n\",\n tuple.debug(input_table->name()).c_str(), tuple_ctr,\n (int)input_table->activeTupleCount());\n m_engine->noteTuplesProcessedForProgressMonitoring(1);\n \/\/\n \/\/ For each tuple we need to evaluate it against our predicate\n \/\/\n if (predicate == NULL || predicate->eval(&tuple, NULL).isTrue())\n {\n \/\/ Check if we have to skip this tuple because of offset\n if (tuple_skipped < offset) {\n tuple_skipped++;\n continue;\n }\n ++tuple_ctr;\n\n \/\/\n \/\/ Nested Projection\n \/\/ Project (or replace) values from input tuple\n \/\/\n if (projection_node != NULL)\n {\n TableTuple &temp_tuple = output_table->tempTuple();\n for (int ctr = 0; ctr < num_of_columns; ctr++)\n {\n NValue value =\n projection_node->\n getOutputColumnExpressions()[ctr]->eval(&tuple, NULL);\n temp_tuple.setNValue(ctr, value);\n }\n if (!output_table->insertTuple(temp_tuple))\n {\n VOLT_ERROR(\"Failed to insert tuple from table '%s' into\"\n \" output table '%s'\",\n input_table->name().c_str(),\n output_table->name().c_str());\n return false;\n }\n }\n else\n {\n \/\/\n \/\/ Insert the tuple into our output table\n \/\/\n if (!output_table->insertTuple(tuple)) {\n VOLT_ERROR(\"Failed to insert tuple from table '%s' into\"\n \" output table '%s'\",\n input_table->name().c_str(),\n output_table->name().c_str());\n return false;\n }\n }\n }\n }\n }\n VOLT_TRACE(\"\\n%s\\n\", output_table->debug().c_str());\n VOLT_DEBUG(\"Finished Seq scanning\");\n\n return true;\n}\nFixed merge error\/* This file is part of VoltDB.\n * Copyright (C) 2008-2013 VoltDB Inc.\n *\n * This file contains original code and\/or modifications of original code.\n * Any modifications made by VoltDB Inc. are licensed under the following\n * terms and conditions:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with VoltDB. If not, see .\n *\/\n\/* Copyright (C) 2008 by H-Store Project\n * Brown University\n * Massachusetts Institute of Technology\n * Yale University\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \n#include \"seqscanexecutor.h\"\n#include \"common\/debuglog.h\"\n#include \"common\/common.h\"\n#include \"common\/tabletuple.h\"\n#include \"common\/FatalException.hpp\"\n#include \"expressions\/abstractexpression.h\"\n#include \"plannodes\/seqscannode.h\"\n#include \"plannodes\/projectionnode.h\"\n#include \"plannodes\/limitnode.h\"\n#include \"storage\/table.h\"\n#include \"storage\/temptable.h\"\n#include \"storage\/tablefactory.h\"\n#include \"storage\/tableiterator.h\"\n\nusing namespace voltdb;\n\nbool SeqScanExecutor::p_init(AbstractPlanNode* abstract_node,\n TempTableLimits* limits)\n{\n VOLT_TRACE(\"init SeqScan Executor\");\n\n SeqScanPlanNode* node = dynamic_cast(abstract_node);\n assert(node);\n assert(node->isSubQuery() || node->getTargetTable());\n assert((node->isSubQuery() && node->getChildren().size() == 1) ||\n !node->isSubQuery());\n\n \/\/\n \/\/ OPTIMIZATION: If there is no predicate for this SeqScan,\n \/\/ then we want to just set our OutputTable pointer to be the\n \/\/ pointer of our TargetTable. This prevents us from just\n \/\/ reading through the entire TargetTable and copying all of\n \/\/ the tuples. We are guarenteed that no Executor will ever\n \/\/ modify an input table, so this operation is safe\n \/\/\n if (!this->needsOutputTableClear())\n {\n node->setOutputTable(node->getTargetTable());\n }\n \/\/\n \/\/ Otherwise create a new temp table that mirrors the\n \/\/ output schema specified in the plan (which should mirror\n \/\/ the output schema for any inlined projection)\n \/\/\n else\n {\n \/\/ Create output table based on output schema from the plan\n const std::string& temp_name = (!node->isSubQuery()) ?\n node->getTargetTable()->name() :\n node->getChildren()[0]->getOutputTable()->name();\n setTempOutputTable(limits, temp_name);\n }\n return true;\n}\n\nbool SeqScanExecutor::needsOutputTableClear() {\n \/\/ clear the temporary output table only when it has a predicate.\n \/\/ if it doesn't have a predicate, it's the original persistent table\n \/\/ and we don't have to (and must not) clear it.\n SeqScanPlanNode* node = dynamic_cast(m_abstractNode);\n assert(node);\n return node->needsOutputTableClear();\n}\n\nbool SeqScanExecutor::p_execute(const NValueArray ¶ms) {\n SeqScanPlanNode* node = dynamic_cast(m_abstractNode);\n assert(node);\n Table* output_table = node->getOutputTable();\n assert(output_table);\n\n Table* input_table = (!node->isSubQuery()) ?\n dynamic_cast(node->getTargetTable()) :\n node->getChildren()[0]->getOutputTable();\n\n assert(input_table);\n \/\/cout << \"SeqScanExecutor: node id\" << node->getPlanNodeId() << endl;\n VOLT_TRACE(\"Sequential Scanning table :\\n %s\",\n input_table->debug().c_str());\n VOLT_DEBUG(\"Sequential Scanning table : %s which has %d active, %d\"\n \" allocated\",\n input_table->name().c_str(),\n (int)input_table->activeTupleCount(),\n (int)input_table->allocatedTupleCount());\n\n \/\/\n \/\/ OPTIMIZATION: NESTED PROJECTION\n \/\/\n \/\/ Since we have the input params, we need to call substitute to\n \/\/ change any nodes in our expression tree to be ready for the\n \/\/ projection operations in execute\n \/\/\n int num_of_columns = (int)output_table->columnCount();\n ProjectionPlanNode* projection_node = dynamic_cast(node->getInlinePlanNode(PLAN_NODE_TYPE_PROJECTION));\n if (projection_node != NULL) {\n for (int ctr = 0; ctr < num_of_columns; ctr++) {\n assert(projection_node->getOutputColumnExpressions()[ctr]);\n projection_node->getOutputColumnExpressions()[ctr]->substitute(params);\n }\n }\n\n \/\/\n \/\/ OPTIMIZATION: NESTED LIMIT\n \/\/ How nice! We can also cut off our scanning with a nested limit!\n \/\/\n LimitPlanNode* limit_node = dynamic_cast(node->getInlinePlanNode(PLAN_NODE_TYPE_LIMIT));\n\n \/\/\n \/\/ OPTIMIZATION:\n \/\/\n \/\/ If there is no predicate and no Projection for this SeqScan,\n \/\/ then we have already set the node's OutputTable to just point\n \/\/ at the TargetTable. Therefore, there is nothing we more we need\n \/\/ to do here\n \/\/\n if (node->getPredicate() != NULL || projection_node != NULL ||\n limit_node != NULL)\n {\n \/\/\n \/\/ Just walk through the table using our iterator and apply\n \/\/ the predicate to each tuple. For each tuple that satisfies\n \/\/ our expression, we'll insert them into the output table.\n \/\/\n TableTuple tuple(input_table->schema());\n TableIterator iterator = input_table->iterator();\n AbstractExpression *predicate = node->getPredicate();\n\n if (predicate)\n {\n VOLT_TRACE(\"SCAN PREDICATE A:\\n%s\\n\", predicate->debug(true).c_str());\n predicate->substitute(params);\n assert(predicate != NULL);\n VOLT_DEBUG(\"SCAN PREDICATE B:\\n%s\\n\",\n predicate->debug(true).c_str());\n }\n\n int limit = -1;\n int offset = -1;\n if (limit_node) {\n limit_node->getLimitAndOffsetByReference(params, limit, offset);\n }\n\n int tuple_ctr = 0;\n int tuple_skipped = 0;\n if (!node->isSubQuery()) {\n \/\/ Input table is the target table in this case\n m_engine->setLastAccessedTable(input_table);\n }\n while ((limit == -1 || tuple_ctr < limit) && iterator.next(tuple))\n {\n VOLT_TRACE(\"INPUT TUPLE: %s, %d\/%d\\n\",\n tuple.debug(input_table->name()).c_str(), tuple_ctr,\n (int)input_table->activeTupleCount());\n m_engine->noteTuplesProcessedForProgressMonitoring(1);\n \/\/\n \/\/ For each tuple we need to evaluate it against our predicate\n \/\/\n if (predicate == NULL || predicate->eval(&tuple, NULL).isTrue())\n {\n \/\/ Check if we have to skip this tuple because of offset\n if (tuple_skipped < offset) {\n tuple_skipped++;\n continue;\n }\n ++tuple_ctr;\n\n \/\/\n \/\/ Nested Projection\n \/\/ Project (or replace) values from input tuple\n \/\/\n if (projection_node != NULL)\n {\n TableTuple &temp_tuple = output_table->tempTuple();\n for (int ctr = 0; ctr < num_of_columns; ctr++)\n {\n NValue value =\n projection_node->\n getOutputColumnExpressions()[ctr]->eval(&tuple, NULL);\n temp_tuple.setNValue(ctr, value);\n }\n if (!output_table->insertTuple(temp_tuple))\n {\n VOLT_ERROR(\"Failed to insert tuple from table '%s' into\"\n \" output table '%s'\",\n input_table->name().c_str(),\n output_table->name().c_str());\n return false;\n }\n }\n else\n {\n \/\/\n \/\/ Insert the tuple into our output table\n \/\/\n if (!output_table->insertTuple(tuple)) {\n VOLT_ERROR(\"Failed to insert tuple from table '%s' into\"\n \" output table '%s'\",\n input_table->name().c_str(),\n output_table->name().c_str());\n return false;\n }\n }\n }\n }\n }\n VOLT_TRACE(\"\\n%s\\n\", output_table->debug().c_str());\n VOLT_DEBUG(\"Finished Seq scanning\");\n\n return true;\n}\n<|endoftext|>"} {"text":"Move Upsample code to keep alphabetical op order<|endoftext|>"} {"text":"PWM cleanup FIFO access<|endoftext|>"} {"text":"\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"RestartableDataIO.h\"\n#include \"MooseUtils.h\"\n#include \"RestartableData.h\"\n#include \"FEProblem.h\"\n\n#include \n\nRestartableDataIO::RestartableDataIO(FEProblem & fe_problem) :\n _fe_problem(fe_problem)\n{\n}\n\nvoid\nRestartableDataIO::writeRestartableData(std::string base_file_name)\n{\n unsigned int n_threads = libMesh::n_threads();\n unsigned int n_procs = libMesh::n_processors();\n unsigned int proc_id = libMesh::processor_id();\n\n for(unsigned int tid=0; tid restartable_data = _fe_problem._restartable_data[tid];\n\n if(restartable_data.size())\n {\n const unsigned int file_version = 1;\n\n std::ofstream out;\n\n std::ostringstream file_name_stream;\n file_name_stream << base_file_name;\n\n file_name_stream << \"-\" << proc_id;\n\n if(n_threads > 1)\n file_name_stream << \"-\" << tid;\n\n std::string file_name = file_name_stream.str();\n\n { \/\/ Write out header\n out.open(file_name.c_str(), std::ios::out | std::ios::binary);\n\n char id[2];\n\n \/\/ header\n id[0] = 'R';\n id[1] = 'D';\n\n out.write(id, 2);\n out.write((const char *)&file_version, sizeof(file_version));\n\n out.write((const char *)&n_procs, sizeof(n_procs));\n out.write((const char *)&n_threads, sizeof(n_threads));\n\n \/\/ number of RestartableData\n unsigned int n_data = restartable_data.size();\n out.write((const char *) &n_data, sizeof(n_data));\n\n \/\/ data names\n for(std::map::iterator it = restartable_data.begin();\n it != restartable_data.end();\n ++it)\n {\n std::string name = it->second->name();\n out.write(name.c_str(), name.length() + 1); \/\/ trailing 0!\n }\n }\n {\n std::ostringstream data_blk;\n\n for(std::map::iterator it = restartable_data.begin();\n it != restartable_data.end();\n ++it)\n {\n \/\/ std::cout<<\"Storing \"<first<second->store(data);\n\n \/\/ Store the size of the data then the data\n unsigned int data_size = data.tellp();\n data_blk.write((const char *) &data_size, sizeof(data_size));\n data_blk << data.str();\n }\n\n \/\/ Write out this proc's block size\n unsigned int data_blk_size = data_blk.tellp();\n out.write((const char *) &data_blk_size, sizeof(data_blk_size));\n\n \/\/ Write out the values\n out << data_blk.str();\n\n out.close();\n }\n }\n }\n}\n\nvoid\nRestartableDataIO::readRestartableData(std::string base_file_name)\n{\n unsigned int n_threads = libMesh::n_threads();\n unsigned int n_procs = libMesh::n_processors();\n unsigned int proc_id = libMesh::processor_id();\n\n std::vector ignored_data;\n\n for(unsigned int tid=0; tid restartable_data = _fe_problem._restartable_data[tid];\n\n if(restartable_data.size())\n {\n std::ostringstream file_name_stream;\n file_name_stream << base_file_name;\n\n file_name_stream << \"-\" << proc_id;\n\n if(n_threads > 1)\n file_name_stream << \"-\" << tid;\n\n std::string file_name = file_name_stream.str();\n\n MooseUtils::checkFileReadable(file_name);\n\n const unsigned int file_version = 1;\n\n std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);\n\n \/\/ header\n char id[2];\n in.read(id, 2);\n\n unsigned int this_file_version;\n in.read((char *)&this_file_version, sizeof(this_file_version));\n\n unsigned int this_n_procs = 0;\n unsigned int this_n_threads = 0;\n\n in.read((char *)&this_n_procs, sizeof(this_n_procs));\n in.read((char *)&this_n_threads, sizeof(this_n_threads));\n\n \/\/ check the header\n if(id[0] != 'R' || id[1] != 'D')\n mooseError(\"Corrupted restartable data file!\");\n\n \/\/ check the file version\n if(this_file_version > file_version)\n mooseError(\"Trying to restart from a newer file version - you need to update MOOSE\");\n\n if(this_file_version < file_version)\n mooseError(\"Trying to restart from an older file version - you need to checkout an older version of MOOSE.\");\n\n if(this_n_procs != n_procs)\n mooseError(\"Cannot restart using a different number of processors!\");\n\n if(this_n_threads != n_threads)\n mooseError(\"Cannot restart using a different number of threads!\");\n\n \/\/ number of data\n unsigned int n_data = 0;\n in.read((char *) &n_data, sizeof(n_data));\n\n \/\/ data names\n std::vector data_names(n_data);\n\n for(unsigned int i=0; i < n_data; i++)\n {\n std::string data_name;\n char ch = 0;\n do {\n in.read(&ch, 1);\n if (ch != '\\0')\n data_name += ch;\n } while (ch != '\\0');\n data_names[i] = data_name;\n }\n\n \/\/ Grab this processor's block size\n unsigned int data_blk_size = 0;\n in.read((char *) &data_blk_size, sizeof(data_blk_size));\n\n for(unsigned int i=0; i < n_data; i++)\n {\n std::string current_name = data_names[i];\n\n unsigned int data_size = 0;\n in.read((char *) &data_size, sizeof(data_size));\n\n if(restartable_data.find(current_name) != restartable_data.end()) \/\/ Only restore values if they're currently being used\n {\n \/\/ std::cout<<\"Loading \"<load(in);\n }\n else\n {\n \/\/ Skip this piece of data\n in.seekg(data_size, std::ios_base::cur);\n ignored_data.push_back(current_name);\n }\n }\n\n in.close();\n }\n }\n\n if(ignored_data.size())\n {\n std::ostringstream names;\n\n for(unsigned int i=0; iFix issue with displaced refs #1169\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"RestartableDataIO.h\"\n#include \"MooseUtils.h\"\n#include \"RestartableData.h\"\n#include \"FEProblem.h\"\n\n#include \n\nRestartableDataIO::RestartableDataIO(FEProblem & fe_problem) :\n _fe_problem(fe_problem)\n{\n}\n\nvoid\nRestartableDataIO::writeRestartableData(std::string base_file_name)\n{\n unsigned int n_threads = libMesh::n_threads();\n unsigned int n_procs = libMesh::n_processors();\n unsigned int proc_id = libMesh::processor_id();\n\n for(unsigned int tid=0; tid & restartable_data = _fe_problem._restartable_data[tid];\n\n if(restartable_data.size())\n {\n const unsigned int file_version = 1;\n\n std::ofstream out;\n\n std::ostringstream file_name_stream;\n file_name_stream << base_file_name;\n\n file_name_stream << \"-\" << proc_id;\n\n if(n_threads > 1)\n file_name_stream << \"-\" << tid;\n\n std::string file_name = file_name_stream.str();\n\n { \/\/ Write out header\n out.open(file_name.c_str(), std::ios::out | std::ios::binary);\n\n char id[2];\n\n \/\/ header\n id[0] = 'R';\n id[1] = 'D';\n\n out.write(id, 2);\n out.write((const char *)&file_version, sizeof(file_version));\n\n out.write((const char *)&n_procs, sizeof(n_procs));\n out.write((const char *)&n_threads, sizeof(n_threads));\n\n \/\/ number of RestartableData\n unsigned int n_data = restartable_data.size();\n out.write((const char *) &n_data, sizeof(n_data));\n\n \/\/ data names\n for(std::map::const_iterator it = restartable_data.begin();\n it != restartable_data.end();\n ++it)\n {\n std::string name = it->first;\n out.write(name.c_str(), name.length() + 1); \/\/ trailing 0!\n }\n }\n {\n std::ostringstream data_blk;\n\n for(std::map::const_iterator it = restartable_data.begin();\n it != restartable_data.end();\n ++it)\n {\n \/\/ std::cout<<\"Storing \"<first<second->store(data);\n\n \/\/ Store the size of the data then the data\n unsigned int data_size = data.tellp();\n data_blk.write((const char *) &data_size, sizeof(data_size));\n data_blk << data.str();\n }\n\n \/\/ Write out this proc's block size\n unsigned int data_blk_size = data_blk.tellp();\n out.write((const char *) &data_blk_size, sizeof(data_blk_size));\n\n \/\/ Write out the values\n out << data_blk.str();\n\n out.close();\n }\n }\n }\n}\n\nvoid\nRestartableDataIO::readRestartableData(std::string base_file_name)\n{\n unsigned int n_threads = libMesh::n_threads();\n unsigned int n_procs = libMesh::n_processors();\n unsigned int proc_id = libMesh::processor_id();\n\n std::vector ignored_data;\n\n for(unsigned int tid=0; tid restartable_data = _fe_problem._restartable_data[tid];\n\n if(restartable_data.size())\n {\n std::ostringstream file_name_stream;\n file_name_stream << base_file_name;\n\n file_name_stream << \"-\" << proc_id;\n\n if(n_threads > 1)\n file_name_stream << \"-\" << tid;\n\n std::string file_name = file_name_stream.str();\n\n MooseUtils::checkFileReadable(file_name);\n\n const unsigned int file_version = 1;\n\n std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);\n\n \/\/ header\n char id[2];\n in.read(id, 2);\n\n unsigned int this_file_version;\n in.read((char *)&this_file_version, sizeof(this_file_version));\n\n unsigned int this_n_procs = 0;\n unsigned int this_n_threads = 0;\n\n in.read((char *)&this_n_procs, sizeof(this_n_procs));\n in.read((char *)&this_n_threads, sizeof(this_n_threads));\n\n \/\/ check the header\n if(id[0] != 'R' || id[1] != 'D')\n mooseError(\"Corrupted restartable data file!\");\n\n \/\/ check the file version\n if(this_file_version > file_version)\n mooseError(\"Trying to restart from a newer file version - you need to update MOOSE\");\n\n if(this_file_version < file_version)\n mooseError(\"Trying to restart from an older file version - you need to checkout an older version of MOOSE.\");\n\n if(this_n_procs != n_procs)\n mooseError(\"Cannot restart using a different number of processors!\");\n\n if(this_n_threads != n_threads)\n mooseError(\"Cannot restart using a different number of threads!\");\n\n \/\/ number of data\n unsigned int n_data = 0;\n in.read((char *) &n_data, sizeof(n_data));\n\n \/\/ data names\n std::vector data_names(n_data);\n\n for(unsigned int i=0; i < n_data; i++)\n {\n std::string data_name;\n char ch = 0;\n do {\n in.read(&ch, 1);\n if (ch != '\\0')\n data_name += ch;\n } while (ch != '\\0');\n data_names[i] = data_name;\n }\n\n \/\/ Grab this processor's block size\n unsigned int data_blk_size = 0;\n in.read((char *) &data_blk_size, sizeof(data_blk_size));\n\n for(unsigned int i=0; i < n_data; i++)\n {\n std::string current_name = data_names[i];\n\n unsigned int data_size = 0;\n in.read((char *) &data_size, sizeof(data_size));\n\n if(restartable_data.find(current_name) != restartable_data.end()) \/\/ Only restore values if they're currently being used\n {\n \/\/ std::cout<<\"Loading \"<load(in);\n }\n else\n {\n \/\/ Skip this piece of data\n in.seekg(data_size, std::ios_base::cur);\n ignored_data.push_back(current_name);\n }\n }\n\n in.close();\n }\n }\n\n if(ignored_data.size())\n {\n std::ostringstream names;\n\n for(unsigned int i=0; i"} {"text":"#include \"SkBenchmark.h\"\n#include \"SkMatrix.h\"\n#include \"SkRandom.h\"\n#include \"SkString.h\"\n\nclass MatrixBench : public SkBenchmark {\n SkString fName;\n enum { N = 100000 };\npublic:\n MatrixBench(void* param, const char name[]) : INHERITED(param) {\n fName.printf(\"matrix_%s\", name);\n }\n\n virtual void performTest() = 0;\n\nprotected:\n virtual int mulLoopCount() const { return 1; }\n\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n int n = N * this->mulLoopCount();\n for (int i = 0; i < n; i++) {\n this->performTest();\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/ we want to stop the compiler from eliminating code that it thinks is a no-op\n\/\/ so we have a non-static global we increment, hoping that will convince the\n\/\/ compiler to execute everything\nint gMatrixBench_NonStaticGlobal;\n\n#define always_do(pred) \\\n do { \\\n if (pred) { \\\n ++gMatrixBench_NonStaticGlobal; \\\n } \\\n } while (0)\n\nclass EqualsMatrixBench : public MatrixBench {\npublic:\n EqualsMatrixBench(void* param) : INHERITED(param, \"equals\") {}\nprotected:\n virtual void performTest() {\n SkMatrix m0, m1, m2;\n\n m0.reset();\n m1.reset();\n m2.reset();\n always_do(m0 == m1);\n always_do(m1 == m2);\n always_do(m2 == m0);\n always_do(m0.getType());\n always_do(m1.getType());\n always_do(m2.getType());\n }\nprivate:\n typedef MatrixBench INHERITED;\n};\n\nclass ScaleMatrixBench : public MatrixBench {\npublic:\n ScaleMatrixBench(void* param) : INHERITED(param, \"scale\") {\n\n fM0.reset();\n fM1.setScale(fSX, fSY);\n fM2.setTranslate(fSX, fSY);\n fSX = fSY = SkFloatToScalar(1.5f);\n }\nprotected:\n virtual void performTest() {\n SkMatrix m;\n m = fM0; m.preScale(fSX, fSY);\n m = fM1; m.preScale(fSX, fSY);\n m = fM2; m.preScale(fSX, fSY);\n }\nprivate:\n SkMatrix fM0, fM1, fM2;\n SkScalar fSX, fSY;\n typedef MatrixBench INHERITED;\n};\n\n\/\/ having unknown values in our arrays can throw off the timing a lot, perhaps\n\/\/ handling NaN values is a lot slower. Anyway, this guy is just meant to put\n\/\/ reasonable values in our arrays.\ntemplate void init9(T array[9]) {\n SkRandom rand;\n for (int i = 0; i < 9; i++) {\n array[i] = rand.nextSScalar1();\n }\n}\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using floating point precision only.\nclass FloatConcatMatrixBench : public MatrixBench {\npublic:\n FloatConcatMatrixBench(void* p) : INHERITED(p, \"concat_floatfloat\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(float a, float b, float c, float d,\n float* result) {\n *result = a * b + c * d;\n }\n virtual void performTest() {\n const float* a = mya;\n const float* b = myb;\n float* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0f;\n r[8] = 1.0f;\n }\nprivate:\n float mya [9];\n float myb [9];\n float myr [9];\n typedef MatrixBench INHERITED;\n};\n\nstatic inline float SkDoubleToFloat(double x) {\n return static_cast(x);\n}\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using floating point precision but casting up to float for\n\/\/ intermediate results during computations.\nclass FloatDoubleConcatMatrixBench : public MatrixBench {\npublic:\n FloatDoubleConcatMatrixBench(void* p) : INHERITED(p, \"concat_floatdouble\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(float a, float b, float c, float d,\n float* result) {\n *result = SkDoubleToFloat((double)a * b + (double)c * d);\n }\n virtual void performTest() {\n const float* a = mya;\n const float* b = myb;\n float* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0f;\n r[8] = 1.0f;\n }\nprivate:\n float mya [9];\n float myb [9];\n float myr [9];\n typedef MatrixBench INHERITED;\n};\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using double precision only.\nclass DoubleConcatMatrixBench : public MatrixBench {\npublic:\n DoubleConcatMatrixBench(void* p) : INHERITED(p, \"concat_double\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(double a, double b, double c, double d,\n double* result) {\n *result = a * b + c * d;\n }\n virtual void performTest() {\n const double* a = mya;\n const double* b = myb;\n double* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0;\n r[8] = 1.0;\n }\nprivate:\n double mya [9];\n double myb [9];\n double myr [9];\n typedef MatrixBench INHERITED;\n};\n\n\nstatic SkBenchmark* M0(void* p) { return new EqualsMatrixBench(p); }\nstatic SkBenchmark* M1(void* p) { return new ScaleMatrixBench(p); }\nstatic SkBenchmark* M2(void* p) { return new FloatConcatMatrixBench(p); }\nstatic SkBenchmark* M3(void* p) { return new FloatDoubleConcatMatrixBench(p); }\nstatic SkBenchmark* M4(void* p) { return new DoubleConcatMatrixBench(p); }\n\nstatic BenchRegistry gReg0(M0);\nstatic BenchRegistry gReg1(M1);\nstatic BenchRegistry gReg2(M2);\nstatic BenchRegistry gReg3(M3);\nstatic BenchRegistry gReg4(M4);\nNew benchmarks to determine performance of matrix-point multiplication for floating point vs. double matrices.#include \"SkBenchmark.h\"\n#include \"SkMatrix.h\"\n#include \"SkRandom.h\"\n#include \"SkString.h\"\n\nclass MatrixBench : public SkBenchmark {\n SkString fName;\n enum { N = 100000 };\npublic:\n MatrixBench(void* param, const char name[]) : INHERITED(param) {\n fName.printf(\"matrix_%s\", name);\n }\n\n virtual void performTest() = 0;\n\nprotected:\n virtual int mulLoopCount() const { return 1; }\n\n virtual const char* onGetName() {\n return fName.c_str();\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n int n = N * this->mulLoopCount();\n for (int i = 0; i < n; i++) {\n this->performTest();\n }\n }\n\nprivate:\n typedef SkBenchmark INHERITED;\n};\n\n\/\/ we want to stop the compiler from eliminating code that it thinks is a no-op\n\/\/ so we have a non-static global we increment, hoping that will convince the\n\/\/ compiler to execute everything\nint gMatrixBench_NonStaticGlobal;\n\n#define always_do(pred) \\\n do { \\\n if (pred) { \\\n ++gMatrixBench_NonStaticGlobal; \\\n } \\\n } while (0)\n\nclass EqualsMatrixBench : public MatrixBench {\npublic:\n EqualsMatrixBench(void* param) : INHERITED(param, \"equals\") {}\nprotected:\n virtual void performTest() {\n SkMatrix m0, m1, m2;\n\n m0.reset();\n m1.reset();\n m2.reset();\n always_do(m0 == m1);\n always_do(m1 == m2);\n always_do(m2 == m0);\n always_do(m0.getType());\n always_do(m1.getType());\n always_do(m2.getType());\n }\nprivate:\n typedef MatrixBench INHERITED;\n};\n\nclass ScaleMatrixBench : public MatrixBench {\npublic:\n ScaleMatrixBench(void* param) : INHERITED(param, \"scale\") {\n\n fM0.reset();\n fM1.setScale(fSX, fSY);\n fM2.setTranslate(fSX, fSY);\n fSX = fSY = SkFloatToScalar(1.5f);\n }\nprotected:\n virtual void performTest() {\n SkMatrix m;\n m = fM0; m.preScale(fSX, fSY);\n m = fM1; m.preScale(fSX, fSY);\n m = fM2; m.preScale(fSX, fSY);\n }\nprivate:\n SkMatrix fM0, fM1, fM2;\n SkScalar fSX, fSY;\n typedef MatrixBench INHERITED;\n};\n\n\/\/ having unknown values in our arrays can throw off the timing a lot, perhaps\n\/\/ handling NaN values is a lot slower. Anyway, this guy is just meant to put\n\/\/ reasonable values in our arrays.\ntemplate void init9(T array[9]) {\n SkRandom rand;\n for (int i = 0; i < 9; i++) {\n array[i] = rand.nextSScalar1();\n }\n}\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using floating point precision only.\nclass FloatConcatMatrixBench : public MatrixBench {\npublic:\n FloatConcatMatrixBench(void* p) : INHERITED(p, \"concat_floatfloat\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(float a, float b, float c, float d,\n float* result) {\n *result = a * b + c * d;\n }\n virtual void performTest() {\n const float* a = mya;\n const float* b = myb;\n float* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0f;\n r[8] = 1.0f;\n }\nprivate:\n float mya [9];\n float myb [9];\n float myr [9];\n typedef MatrixBench INHERITED;\n};\n\nstatic inline float SkDoubleToFloat(double x) {\n return static_cast(x);\n}\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using floating point precision but casting up to float for\n\/\/ intermediate results during computations.\nclass FloatDoubleConcatMatrixBench : public MatrixBench {\npublic:\n FloatDoubleConcatMatrixBench(void* p) : INHERITED(p, \"concat_floatdouble\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(float a, float b, float c, float d,\n float* result) {\n *result = SkDoubleToFloat((double)a * b + (double)c * d);\n }\n virtual void performTest() {\n const float* a = mya;\n const float* b = myb;\n float* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0f;\n r[8] = 1.0f;\n }\nprivate:\n float mya [9];\n float myb [9];\n float myr [9];\n typedef MatrixBench INHERITED;\n};\n\n\/\/ Test the performance of setConcat() non-perspective case:\n\/\/ using double precision only.\nclass DoubleConcatMatrixBench : public MatrixBench {\npublic:\n DoubleConcatMatrixBench(void* p) : INHERITED(p, \"concat_double\") {\n init9(mya);\n init9(myb);\n init9(myr);\n }\nprotected:\n virtual int mulLoopCount() const { return 4; }\n\n static inline void muladdmul(double a, double b, double c, double d,\n double* result) {\n *result = a * b + c * d;\n }\n virtual void performTest() {\n const double* a = mya;\n const double* b = myb;\n double* r = myr;\n muladdmul(a[0], b[0], a[1], b[3], &r[0]);\n muladdmul(a[0], b[1], a[1], b[4], &r[1]);\n muladdmul(a[0], b[2], a[1], b[5], &r[2]);\n r[2] += a[2];\n muladdmul(a[3], b[0], a[4], b[3], &r[3]);\n muladdmul(a[3], b[1], a[4], b[4], &r[4]);\n muladdmul(a[3], b[2], a[4], b[5], &r[5]);\n r[5] += a[5];\n r[6] = r[7] = 0.0;\n r[8] = 1.0;\n }\nprivate:\n double mya [9];\n double myb [9];\n double myr [9];\n typedef MatrixBench INHERITED;\n};\n\n#ifdef SK_SCALAR_IS_FLOAT\nclass ScaleTransMixedMatrixBench : public MatrixBench {\n public:\n ScaleTransMixedMatrixBench(void* p) : INHERITED(p, \"scaletrans_mixed\"), fCount (16) {\n fMatrix.setAll(fRandom.nextS(), fRandom.nextS(), fRandom.nextS(),\n fRandom.nextS(), fRandom.nextS(), fRandom.nextS(),\n fRandom.nextS(), fRandom.nextS(), fRandom.nextS());\n int i;\n for (i = 0; i < fCount; i++) {\n fSrc[i].fX = fRandom.nextS();\n fSrc[i].fY = fRandom.nextS();\n fDst[i].fX = fRandom.nextS();\n fDst[i].fY = fRandom.nextS();\n }\n }\n protected:\n virtual void performTest() {\n SkPoint* dst = fDst;\n const SkPoint* src = fSrc;\n int count = fCount;\n float mx = fMatrix[SkMatrix::kMScaleX];\n float my = fMatrix[SkMatrix::kMScaleY];\n float tx = fMatrix[SkMatrix::kMTransX];\n float ty = fMatrix[SkMatrix::kMTransY];\n do {\n dst->fY = SkScalarMulAdd(src->fY, my, ty);\n dst->fX = SkScalarMulAdd(src->fX, mx, tx);\n src += 1;\n dst += 1;\n } while (--count);\n }\n private:\n SkMatrix fMatrix;\n SkPoint fSrc [16];\n SkPoint fDst [16];\n int fCount;\n SkRandom fRandom;\n typedef MatrixBench INHERITED;\n};\n\n\nclass ScaleTransDoubleMatrixBench : public MatrixBench {\n public:\n ScaleTransDoubleMatrixBench(void* p) : INHERITED(p, \"scaletrans_double\"), fCount (16) {\n init9(fMatrix);\n int i;\n for (i = 0; i < fCount; i++) {\n fSrc[i].fX = fRandom.nextS();\n fSrc[i].fY = fRandom.nextS();\n fDst[i].fX = fRandom.nextS();\n fDst[i].fY = fRandom.nextS();\n }\n }\n protected:\n virtual void performTest() {\n SkPoint* dst = fDst;\n const SkPoint* src = fSrc;\n int count = fCount;\n \/\/ As doubles, on Z600 Linux systems this is 2.5x as expensive as mixed mode\n float mx = fMatrix[SkMatrix::kMScaleX];\n float my = fMatrix[SkMatrix::kMScaleY];\n float tx = fMatrix[SkMatrix::kMTransX];\n float ty = fMatrix[SkMatrix::kMTransY];\n do {\n dst->fY = src->fY * my + ty;\n dst->fX = src->fX * mx + tx;\n src += 1;\n dst += 1;\n } while (--count);\n }\n private:\n double fMatrix [9];\n SkPoint fSrc [16];\n SkPoint fDst [16];\n int fCount;\n SkRandom fRandom;\n typedef MatrixBench INHERITED;\n};\n#endif\n\n\n\n\n\nstatic SkBenchmark* M0(void* p) { return new EqualsMatrixBench(p); }\nstatic SkBenchmark* M1(void* p) { return new ScaleMatrixBench(p); }\nstatic SkBenchmark* M2(void* p) { return new FloatConcatMatrixBench(p); }\nstatic SkBenchmark* M3(void* p) { return new FloatDoubleConcatMatrixBench(p); }\nstatic SkBenchmark* M4(void* p) { return new DoubleConcatMatrixBench(p); }\n\nstatic BenchRegistry gReg0(M0);\nstatic BenchRegistry gReg1(M1);\nstatic BenchRegistry gReg2(M2);\nstatic BenchRegistry gReg3(M3);\nstatic BenchRegistry gReg4(M4);\n\n#ifdef SK_SCALAR_IS_FLOAT\nstatic SkBenchmark* FlM0(void* p) { return new ScaleTransMixedMatrixBench(p); }\nstatic SkBenchmark* FlM1(void* p) { return new ScaleTransDoubleMatrixBench(p); }\nstatic BenchRegistry gFlReg5(FlM0);\nstatic BenchRegistry gFlReg6(FlM1);\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: color.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: thb $ $Date: 2006-07-28 12:43:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_BASEBMP_COLOR_HXX\n#define INCLUDED_BASEBMP_COLOR_HXX\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n#include \n\nnamespace basebmp\n{\n\nclass Color\n{\nprivate:\n sal_uInt32 mnColor;\n\npublic:\n typedef sal_uInt32 value_type;\n typedef sal_uInt8 component_type;\n\n Color() : mnColor(0) {}\n explicit Color( sal_uInt32 nVal ) : mnColor(nVal) {}\n Color( sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue ) :\n mnColor( ((sal_uInt32)nRed << 16) | ((sal_uInt32)nGreen << 8) | nBlue )\n {}\n\n void setRed( sal_uInt8 nRed ) { mnColor &= ~0x00FF0000UL; mnColor |= (sal_uInt32)nRed << 16; }\n void setGreen( sal_uInt8 nGreen ) { mnColor &= ~0x0000FF00UL; mnColor |= (sal_uInt32)nGreen << 8; }\n void setBlue( sal_uInt8 nBlue ) { mnColor &= ~0x000000FFUL; mnColor |= nBlue; }\n\n void setGrey( sal_uInt8 nGreyVal ) { mnColor = (sal_uInt32)nGreyVal << 16 | (sal_uInt32)nGreyVal << 8 | nGreyVal; }\n\n sal_uInt8 getRed() const { return 0xFF & (sal_uInt8)(mnColor >> 16); }\n sal_uInt8 getGreen() const { return 0xFF & (sal_uInt8)(mnColor >> 8); }\n sal_uInt8 getBlue() const { return 0xFF & (sal_uInt8)mnColor; }\n\n sal_uInt8 getGreyscale() const { return (sal_uInt8)((getBlue()*28UL +\n getGreen()*151 +\n getRed()*77) \/ 256); }\n\n sal_uInt32 toInt32() const { return mnColor; }\n\n bool operator!() const { return mnColor == 0; }\n Color operator&( sal_uInt32 nMask ) const { return Color(mnColor & nMask); }\n Color operator^( Color col ) const { return Color(col.getRed()^getRed(),\n col.getGreen()^getGreen(),\n col.getBlue()^getBlue()); }\n Color operator-( Color col ) const { return Color((sal_uInt8)abs((int)getRed()-col.getRed()),\n (sal_uInt8)abs((int)getGreen()-col.getGreen()),\n (sal_uInt8)abs((int)getBlue()-col.getBlue())); }\n Color operator+( Color col ) const { return Color(getRed()+col.getRed(),\n getGreen()+col.getGreen(),\n getBlue()+col.getBlue()); }\n Color operator*( Color col ) const { return Color((sal_uInt8)((sal_uInt32)col.getRed()*getRed()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)col.getGreen()*getGreen()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)col.getBlue()*getBlue()\/SAL_MAX_UINT8)); }\n Color operator*( sal_uInt8 n ) const { return Color((sal_uInt8)((sal_uInt32)n*getRed()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)n*getGreen()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)n*getBlue()\/SAL_MAX_UINT8)); }\n Color operator*( double n ) const { return Color((sal_uInt8)(n*getRed()+.5),\n (sal_uInt8)(n*getGreen()+.5),\n (sal_uInt8)(n*getBlue()+.5)); }\n bool operator==( const Color& rhs ) const { return (getRed()==rhs.getRed() &&\n getGreen()==rhs.getGreen() &&\n getBlue()==rhs.getBlue()); }\n bool operator!=( const Color& rhs ) const { return !(*this==rhs); }\n double magnitude() const { return sqrt((double)getRed()*getRed()\n + getGreen()*getGreen()\n + getBlue()*getBlue()); }\n};\n\n} \/\/ namespace vigra\n\n#endif \/* INCLUDED_BASEBMP_COLOR_HXX *\/\nINTEGRATION: CWS presfixes09 (1.15.8); FILE MERGED 2006\/10\/20 14:43:49 thb 1.15.8.1: #142144# No more direct math.h includes - using rtl\/math.hxx instead\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: color.hxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 15:05:05 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_BASEBMP_COLOR_HXX\n#define INCLUDED_BASEBMP_COLOR_HXX\n\n#ifndef _SAL_TYPES_H_\n#include \n#endif\n#ifndef INCLUDED_RTL_MATH_HXX\n#include \n#endif\n\nnamespace basebmp\n{\n\nclass Color\n{\nprivate:\n sal_uInt32 mnColor;\n\npublic:\n typedef sal_uInt32 value_type;\n typedef sal_uInt8 component_type;\n\n Color() : mnColor(0) {}\n explicit Color( sal_uInt32 nVal ) : mnColor(nVal) {}\n Color( sal_uInt8 nRed, sal_uInt8 nGreen, sal_uInt8 nBlue ) :\n mnColor( ((sal_uInt32)nRed << 16) | ((sal_uInt32)nGreen << 8) | nBlue )\n {}\n\n void setRed( sal_uInt8 nRed ) { mnColor &= ~0x00FF0000UL; mnColor |= (sal_uInt32)nRed << 16; }\n void setGreen( sal_uInt8 nGreen ) { mnColor &= ~0x0000FF00UL; mnColor |= (sal_uInt32)nGreen << 8; }\n void setBlue( sal_uInt8 nBlue ) { mnColor &= ~0x000000FFUL; mnColor |= nBlue; }\n\n void setGrey( sal_uInt8 nGreyVal ) { mnColor = (sal_uInt32)nGreyVal << 16 | (sal_uInt32)nGreyVal << 8 | nGreyVal; }\n\n sal_uInt8 getRed() const { return 0xFF & (sal_uInt8)(mnColor >> 16); }\n sal_uInt8 getGreen() const { return 0xFF & (sal_uInt8)(mnColor >> 8); }\n sal_uInt8 getBlue() const { return 0xFF & (sal_uInt8)mnColor; }\n\n sal_uInt8 getGreyscale() const { return (sal_uInt8)((getBlue()*28UL +\n getGreen()*151 +\n getRed()*77) \/ 256); }\n\n sal_uInt32 toInt32() const { return mnColor; }\n\n bool operator!() const { return mnColor == 0; }\n Color operator&( sal_uInt32 nMask ) const { return Color(mnColor & nMask); }\n Color operator^( Color col ) const { return Color(col.getRed()^getRed(),\n col.getGreen()^getGreen(),\n col.getBlue()^getBlue()); }\n Color operator-( Color col ) const { return Color((sal_uInt8)abs((int)getRed()-col.getRed()),\n (sal_uInt8)abs((int)getGreen()-col.getGreen()),\n (sal_uInt8)abs((int)getBlue()-col.getBlue())); }\n Color operator+( Color col ) const { return Color(getRed()+col.getRed(),\n getGreen()+col.getGreen(),\n getBlue()+col.getBlue()); }\n Color operator*( Color col ) const { return Color((sal_uInt8)((sal_uInt32)col.getRed()*getRed()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)col.getGreen()*getGreen()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)col.getBlue()*getBlue()\/SAL_MAX_UINT8)); }\n Color operator*( sal_uInt8 n ) const { return Color((sal_uInt8)((sal_uInt32)n*getRed()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)n*getGreen()\/SAL_MAX_UINT8),\n (sal_uInt8)((sal_uInt32)n*getBlue()\/SAL_MAX_UINT8)); }\n Color operator*( double n ) const { return Color((sal_uInt8)(n*getRed()+.5),\n (sal_uInt8)(n*getGreen()+.5),\n (sal_uInt8)(n*getBlue()+.5)); }\n bool operator==( const Color& rhs ) const { return (getRed()==rhs.getRed() &&\n getGreen()==rhs.getGreen() &&\n getBlue()==rhs.getBlue()); }\n bool operator!=( const Color& rhs ) const { return !(*this==rhs); }\n double magnitude() const { return sqrt((double)getRed()*getRed()\n + getGreen()*getGreen()\n + getBlue()*getBlue()); }\n};\n\n} \/\/ namespace vigra\n\n#endif \/* INCLUDED_BASEBMP_COLOR_HXX *\/\n<|endoftext|>"} {"text":"#include \n\n#include \"MusicFile.h\"\n#include \"MusicName.h\"\n\nnamespace std\n{\n\t\/\/ Hash specialization, since GCC doesn't support enum classes used as keys\n\t\/\/ in unordered_maps.\n\ttemplate <>\n\tstruct hash\n\t{\n\t\tsize_t operator()(const MusicName &x) const\n\t\t{\n\t\t\treturn static_cast(x);\n\t\t}\n\t};\n}\n\nnamespace\n{\n\t\/\/ Each MusicName has a corresponding filename. Interestingly, it seems Arena\n\t\/\/ has separate XFM files for FM synth output devices (OPL, as on Adlib and\n\t\/\/ Sound Blaster before the AWE32), while the corresponding XMI files are for\n\t\/\/ MT-32, MPU-401, and other General MIDI devices.\n\t\/\/ - Dungeon1 uses the .XFM version because the .XMI version is a duplicate\n\t\/\/ of Dungeon5.\n\tconst std::unordered_map MusicFilenames =\n\t{\n\t\t{ MusicName::ArabCityEnter, \"ARABCITY.XMI\" },\n\t\t{ MusicName::ArabTownEnter, \"ARABTOWN.XMI\" },\n\t\t{ MusicName::ArabVillageEnter, \"ARAB_VLG.XMI\" },\n\t\t{ MusicName::CityEnter, \"CITY.XMI\" },\n\t\t{ MusicName::Combat, \"COMBAT.XMI\" },\n\t\t{ MusicName::Credits, \"CREDITS.XMI\" },\n\t\t{ MusicName::Dungeon1, \"DUNGEON1.XFM\" },\n\t\t{ MusicName::Dungeon2, \"DUNGEON2.XMI\" },\n\t\t{ MusicName::Dungeon3, \"DUNGEON3.XMI\" },\n\t\t{ MusicName::Dungeon4, \"DUNGEON4.XMI\" },\n\t\t{ MusicName::Dungeon5, \"DUNGEON5.XMI\" },\n\t\t{ MusicName::Equipment, \"EQUIPMNT.XMI\" },\n\t\t{ MusicName::Evil, \"EVIL.XMI\" },\n\t\t{ MusicName::EvilIntro, \"EVLINTRO.XMI\" },\n\t\t{ MusicName::Magic, \"MAGIC_2.XMI\" },\n\t\t{ MusicName::Night, \"NIGHT.XMI\" },\n\t\t{ MusicName::Overcast, \"OVERCAST.XMI\" },\n\t\t{ MusicName::OverSnow, \"OVERSNOW.XMI\" },\n\t\t{ MusicName::Palace, \"PALACE.XMI\" },\n\t\t{ MusicName::PercIntro, \"PERCNTRO.XMI\" },\n\t\t{ MusicName::Raining, \"RAINING.XMI\" },\n\t\t{ MusicName::Sheet, \"SHEET.XMI\" },\n\t\t{ MusicName::Sneaking, \"SNEAKING.XMI\" },\n\t\t{ MusicName::Snowing, \"SNOWING.XMI\" },\n\t\t{ MusicName::Square, \"SQUARE.XMI\" },\n\t\t{ MusicName::SunnyDay, \"SUNNYDAY.XFM\" },\n\t\t{ MusicName::Swimming, \"SWIMMING.XMI\" },\n\t\t{ MusicName::Tavern, \"TAVERN.XMI\" },\n\t\t{ MusicName::Temple, \"TEMPLE.XMI\" },\n\t\t{ MusicName::TownEnter, \"TOWN.XMI\" },\n\t\t{ MusicName::VillageEnter, \"VILLAGE.XMI\" },\n\t\t{ MusicName::Vision, \"VISION.XMI\" },\n\t\t{ MusicName::WinGame, \"WINGAME.XMI\" }\n\t};\n}\n\nconst std::string &MusicFile::fromName(MusicName musicName)\n{\n\tconst std::string &filename = MusicFilenames.at(musicName);\n\treturn filename;\n}\nChanged OverSnow from XMI to XFM.#include \n\n#include \"MusicFile.h\"\n#include \"MusicName.h\"\n\nnamespace std\n{\n\t\/\/ Hash specialization, since GCC doesn't support enum classes used as keys\n\t\/\/ in unordered_maps.\n\ttemplate <>\n\tstruct hash\n\t{\n\t\tsize_t operator()(const MusicName &x) const\n\t\t{\n\t\t\treturn static_cast(x);\n\t\t}\n\t};\n}\n\nnamespace\n{\n\t\/\/ Each MusicName has a corresponding filename. Interestingly, it seems Arena\n\t\/\/ has separate XFM files for FM synth output devices (OPL, as on Adlib and\n\t\/\/ Sound Blaster before the AWE32), while the corresponding XMI files are for\n\t\/\/ MT-32, MPU-401, and other General MIDI devices.\n\t\/\/ - Dungeon1 uses the .XFM version because the .XMI version is a duplicate\n\t\/\/ of Dungeon5.\n\tconst std::unordered_map MusicFilenames =\n\t{\n\t\t{ MusicName::ArabCityEnter, \"ARABCITY.XMI\" },\n\t\t{ MusicName::ArabTownEnter, \"ARABTOWN.XMI\" },\n\t\t{ MusicName::ArabVillageEnter, \"ARAB_VLG.XMI\" },\n\t\t{ MusicName::CityEnter, \"CITY.XMI\" },\n\t\t{ MusicName::Combat, \"COMBAT.XMI\" },\n\t\t{ MusicName::Credits, \"CREDITS.XMI\" },\n\t\t{ MusicName::Dungeon1, \"DUNGEON1.XFM\" },\n\t\t{ MusicName::Dungeon2, \"DUNGEON2.XMI\" },\n\t\t{ MusicName::Dungeon3, \"DUNGEON3.XMI\" },\n\t\t{ MusicName::Dungeon4, \"DUNGEON4.XMI\" },\n\t\t{ MusicName::Dungeon5, \"DUNGEON5.XMI\" },\n\t\t{ MusicName::Equipment, \"EQUIPMNT.XMI\" },\n\t\t{ MusicName::Evil, \"EVIL.XMI\" },\n\t\t{ MusicName::EvilIntro, \"EVLINTRO.XMI\" },\n\t\t{ MusicName::Magic, \"MAGIC_2.XMI\" },\n\t\t{ MusicName::Night, \"NIGHT.XMI\" },\n\t\t{ MusicName::Overcast, \"OVERCAST.XMI\" },\n\t\t{ MusicName::OverSnow, \"OVERSNOW.XFM\" },\n\t\t{ MusicName::Palace, \"PALACE.XMI\" },\n\t\t{ MusicName::PercIntro, \"PERCNTRO.XMI\" },\n\t\t{ MusicName::Raining, \"RAINING.XMI\" },\n\t\t{ MusicName::Sheet, \"SHEET.XMI\" },\n\t\t{ MusicName::Sneaking, \"SNEAKING.XMI\" },\n\t\t{ MusicName::Snowing, \"SNOWING.XMI\" },\n\t\t{ MusicName::Square, \"SQUARE.XMI\" },\n\t\t{ MusicName::SunnyDay, \"SUNNYDAY.XFM\" },\n\t\t{ MusicName::Swimming, \"SWIMMING.XMI\" },\n\t\t{ MusicName::Tavern, \"TAVERN.XMI\" },\n\t\t{ MusicName::Temple, \"TEMPLE.XMI\" },\n\t\t{ MusicName::TownEnter, \"TOWN.XMI\" },\n\t\t{ MusicName::VillageEnter, \"VILLAGE.XMI\" },\n\t\t{ MusicName::Vision, \"VISION.XMI\" },\n\t\t{ MusicName::WinGame, \"WINGAME.XMI\" }\n\t};\n}\n\nconst std::string &MusicFile::fromName(MusicName musicName)\n{\n\tconst std::string &filename = MusicFilenames.at(musicName);\n\treturn filename;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ lr_lalr_general.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 02\/05\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \n#include \n\n#include \"lr_lalr_general.h\"\n\n#include \"Dfa\/character_lexer.h\"\n#include \"ContextFree\/grammar.h\"\n#include \"Lr\/lalr_builder.h\"\n#include \"Lr\/parser.h\"\n\nusing namespace std;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace lr;\n\nstatic void dump(const item& it, const grammar& gram, const terminal_dictionary& dict) {\n if (it.type() == item::nonterminal) {\n wcerr << gram.name_for_nonterminal(it.symbol());\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else if (it.type() == item::terminal) {\n wcerr << dict.name_for_symbol(it.symbol());\n } else if (it.type() == item::eoi) {\n wcerr << L\"$\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else if (it.type() == item::empty) {\n wcerr << L\"#\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else {\n wcerr << L\"?\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n }\n}\n\nstatic void dump(const item_set& la, const grammar& gram, const terminal_dictionary& dict) {\n for (item_set::const_iterator it = la.begin(); it != la.end(); it++) {\n wcerr << L\" \";\n dump(**it, gram, dict);\n }\n}\n\nstatic void dump(const rule& rule, const grammar& gram, const terminal_dictionary& dict) {\n wcerr << gram.identifier_for_rule(rule) << L\": \";\n dump(*rule.nonterminal(), gram, dict);\n \n wcerr << L\" ->\";\n int pos;\n for (pos = 0; pos < rule.items().size(); pos++) {\n wcerr << L\" \";\n dump(*rule.items()[pos], gram, dict);\n }\n}\n\nstatic void dump(const lr0_item& item, const item_set& la, const grammar& gram, const terminal_dictionary& dict) {\n wcerr << gram.identifier_for_rule(item.rule()) << L\": \";\n dump(*item.rule()->nonterminal(), gram, dict);\n \n wcerr << L\" ->\";\n int pos;\n for (pos = 0; pos < item.rule()->items().size(); pos++) {\n if (pos == item.offset()) wcerr << L\" *\";\n wcerr << L\" \";\n dump(*item.rule()->items()[pos], gram, dict);\n }\n if (pos == item.offset()) wcerr << L\" *\";\n \n wcerr << L\",\";\n dump(la, gram, dict);\n \n wcerr << L\" [\";\n if (item.offset() < item.rule()->items().size()) {\n dump(*item.rule()->items()[item.offset()], gram, dict);\n wcerr << L\" >FIRST>\";\n dump(gram.first(*item.rule()->items()[item.offset()]), gram, dict);\n }\n wcerr << L\"]\";\n}\n\nstatic void dump(const lr_action_set& actions, const grammar& gram, const terminal_dictionary& dict) {\n for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) {\n wcerr << L\" \";\n switch ((*it)->type()) {\n case lr_action::act_accept:\n wcerr << L\"ACCEPT \";\n break;\n case lr_action::act_reduce:\n wcerr << L\"REDUCE \";\n break;\n case lr_action::act_shift:\n wcerr << L\"SHIFT \";\n break;\n case lr_action::act_weakreduce:\n wcerr << L\"WEAK REDUCE \";\n break;\n case lr_action::act_goto:\n wcerr << L\"GOTO \";\n break;\n case lr_action::act_ignore:\n wcerr << L\"IGNORE \";\n break;\n }\n dump(*(*it)->item(), gram, dict);\n \n if ((*it)->type() == lr_action::act_reduce || (*it)->type() == lr_action::act_weakreduce) {\n wcerr << L\" on \";\n dump(*(*it)->rule(), gram, dict);\n } else {\n wcerr << L\" -> \" << (*it)->next_state();\n }\n wcerr << endl;\n }\n}\n\n\/\/\/ \\brief Dumps out a state machine to wcerr\nstatic void dump_machine(const lalr_builder& builder) {\n item_set empty_set;\n empty_item empty;\n empty_set.insert(empty);\n const lalr_machine& machine = builder.machine();\n \n for (int stateId = 0; stateId < machine.count_states(); stateId++) {\n wcerr << L\"STATE \" << stateId << endl;\n \n const lalr_state& state = *machine.state_with_id(stateId);\n lr1_item_set closure;\n \n for (lalr_state::set_iterator nextItem = state.begin_kernel(); nextItem != state.end_kernel(); nextItem++) {\n int itemId = nextItem->second;\n const lr0_item& item = *state[itemId];\n wcerr << L\" \";\n dump(item, state.lookahead_for(itemId), machine.gram(), builder.terminals());\n wcerr << endl;\n \n if (item.offset() < item.rule()->items().size()) {\n lr1_item lr1(item, empty_set);\n item.rule()->items()[item.offset()]->closure(lr1, closure, machine.gram());\n }\n }\n\n if (!closure.empty()) {\n wcerr << endl;\n for (lr1_item_set::iterator closed = closure.begin(); closed != closure.end(); closed++) {\n wcerr << L\" \";\n dump(**closed, (*closed)->lookahead(), machine.gram(), builder.terminals());\n wcerr << endl;\n }\n }\n \n wcerr << endl;\n \n dump(builder.actions_for_state(stateId), builder.gram(), builder.terminals());\n\n wcerr << endl;\n }\n}\n\nvoid test_lalr_general::run_tests() {\n \/\/ Grammar specified in example 4.46 of the dragon book\n grammar dragon446;\n terminal_dictionary terms;\n \n nonterminal sPrime(dragon446.id_for_nonterminal(L\"S'\"));\n nonterminal s(dragon446.id_for_nonterminal(L\"S\"));\n nonterminal l(dragon446.id_for_nonterminal(L\"L\"));\n nonterminal r(dragon446.id_for_nonterminal(L\"R\"));\n \n int equalsId = terms.add_symbol(L\"'='\");\n int timesId = terms.add_symbol(L\"'*'\");\n int idId = terms.add_symbol(L\"'i'\");\n \n terminal equals(equalsId);\n terminal times(timesId);\n terminal id(idId);\n \n \/\/ S' -> S\n (dragon446 += sPrime) << s;\n \n \/\/ S -> L = R | R\n (dragon446 += s) << l << equals << r;\n (dragon446 += s) << r;\n \n \/\/ L -> * R | id\n (dragon446 += l) << times << r;\n (dragon446 += l) << id;\n \n \/\/ R -> L\n (dragon446 += r) << l;\n \n \/\/ Build this grammar\n lalr_builder builder(dragon446, terms);\n \n \/\/ S' defines the language\n builder.add_initial_state(s);\n builder.complete_parser();\n \n dump_machine(builder);\n \n \/\/ Assert some things about the machine (specified in the dragon book)\n report(\"num-states\", builder.machine().count_states() == 10); \/\/ Figure 4.42: the result should have 10 states\n \n \/\/ Create a parser for this grammar\n simple_parser p(builder);\n character_lexer lex;\n \n typedef basic_string symbol_string;\n typedef basic_stringstream symbol_stringstream;\n \n symbol_string test1;\n symbol_string test2;\n \n test1 += idId;\n test2 += timesId;\n test2 += idId;\n test2 += equalsId;\n test2 += idId;\n \n symbol_stringstream stream1(test1);\n symbol_stringstream stream2(test2);\n \n simple_parser::state* parse1 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream1)));\n simple_parser::state* parse2 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream2)));\n \n \/\/ Test the parser\n report(\"accept1\", parse1->parse());\n report(\"accept2\", parse2->parse());\n \n delete parse1;\n delete parse2;\n \n#if 0\n \/\/ Run the parser 50000 times\n for (int x=0; x<50000; x++) {\n stringstream stream2(test2);\n simple_parser::state* parse2 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream2)));\n \n parse2->parse();\n delete parse2;\n }\n \n \/\/ Build the parser 10000 times\n for (int x=0; x<10000; x++) {\n \/\/ Build this grammar\n lalr_builder builder(dragon446);\n \n \/\/ S' defines the language\n builder.add_initial_state(s);\n builder.complete_parser();\n }\n#endif\n}\nAdded more tests, to detect if there are any duplicate states (there are, and that's why I think the generator is failing at the moment), or if there's a case where state ordering doesn't work (there isn't at present)\/\/\n\/\/ lr_lalr_general.cpp\n\/\/ Parse\n\/\/\n\/\/ Created by Andrew Hunter on 02\/05\/2011.\n\/\/ Copyright 2011 __MyCompanyName__. All rights reserved.\n\/\/\n\n#include \n#include \n\n#include \"lr_lalr_general.h\"\n\n#include \"Dfa\/character_lexer.h\"\n#include \"ContextFree\/grammar.h\"\n#include \"Lr\/lalr_builder.h\"\n#include \"Lr\/parser.h\"\n#include \"Language\/formatter.h\"\n\nusing namespace std;\nusing namespace dfa;\nusing namespace contextfree;\nusing namespace language;\nusing namespace lr;\n\nstatic void dump(const item& it, const grammar& gram, const terminal_dictionary& dict) {\n if (it.type() == item::nonterminal) {\n wcerr << gram.name_for_nonterminal(it.symbol());\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else if (it.type() == item::terminal) {\n wcerr << dict.name_for_symbol(it.symbol());\n } else if (it.type() == item::eoi) {\n wcerr << L\"$\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else if (it.type() == item::empty) {\n wcerr << L\"#\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n } else {\n wcerr << L\"?\";\n wcerr << \"(\" << gram.identifier_for_item(it) << L\")\";\n }\n}\n\nstatic void dump(const item_set& la, const grammar& gram, const terminal_dictionary& dict) {\n for (item_set::const_iterator it = la.begin(); it != la.end(); it++) {\n wcerr << L\" \";\n dump(**it, gram, dict);\n }\n}\n\nstatic void dump(const rule& rule, const grammar& gram, const terminal_dictionary& dict) {\n wcerr << gram.identifier_for_rule(rule) << L\": \";\n dump(*rule.nonterminal(), gram, dict);\n \n wcerr << L\" ->\";\n int pos;\n for (pos = 0; pos < rule.items().size(); pos++) {\n wcerr << L\" \";\n dump(*rule.items()[pos], gram, dict);\n }\n}\n\nstatic void dump(const lr0_item& item, const item_set& la, const grammar& gram, const terminal_dictionary& dict) {\n wcerr << gram.identifier_for_rule(item.rule()) << L\": \";\n dump(*item.rule()->nonterminal(), gram, dict);\n \n wcerr << L\" ->\";\n int pos;\n for (pos = 0; pos < item.rule()->items().size(); pos++) {\n if (pos == item.offset()) wcerr << L\" *\";\n wcerr << L\" \";\n dump(*item.rule()->items()[pos], gram, dict);\n }\n if (pos == item.offset()) wcerr << L\" *\";\n \n wcerr << L\",\";\n dump(la, gram, dict);\n \n wcerr << L\" [\";\n if (item.offset() < item.rule()->items().size()) {\n dump(*item.rule()->items()[item.offset()], gram, dict);\n wcerr << L\" >FIRST>\";\n dump(gram.first(*item.rule()->items()[item.offset()]), gram, dict);\n }\n wcerr << L\"]\";\n}\n\nstatic void dump(const lr_action_set& actions, const grammar& gram, const terminal_dictionary& dict) {\n for (lr_action_set::const_iterator it = actions.begin(); it != actions.end(); it++) {\n wcerr << L\" \";\n switch ((*it)->type()) {\n case lr_action::act_accept:\n wcerr << L\"ACCEPT \";\n break;\n case lr_action::act_reduce:\n wcerr << L\"REDUCE \";\n break;\n case lr_action::act_shift:\n wcerr << L\"SHIFT \";\n break;\n case lr_action::act_weakreduce:\n wcerr << L\"WEAK REDUCE \";\n break;\n case lr_action::act_goto:\n wcerr << L\"GOTO \";\n break;\n case lr_action::act_ignore:\n wcerr << L\"IGNORE \";\n break;\n }\n dump(*(*it)->item(), gram, dict);\n \n if ((*it)->type() == lr_action::act_reduce || (*it)->type() == lr_action::act_weakreduce) {\n wcerr << L\" on \";\n dump(*(*it)->rule(), gram, dict);\n } else {\n wcerr << L\" -> \" << (*it)->next_state();\n }\n wcerr << endl;\n }\n}\n\n\/\/\/ \\brief Dumps out a state machine to wcerr\nstatic void dump_machine(const lalr_builder& builder) {\n item_set empty_set;\n empty_item empty;\n empty_set.insert(empty);\n const lalr_machine& machine = builder.machine();\n \n for (int stateId = 0; stateId < machine.count_states(); stateId++) {\n wcerr << L\"STATE \" << stateId << endl;\n \n const lalr_state& state = *machine.state_with_id(stateId);\n lr1_item_set closure;\n \n for (lalr_state::set_iterator nextItem = state.begin_kernel(); nextItem != state.end_kernel(); nextItem++) {\n int itemId = nextItem->second;\n const lr0_item& item = *state[itemId];\n wcerr << L\" \";\n dump(item, state.lookahead_for(itemId), machine.gram(), builder.terminals());\n wcerr << endl;\n \n if (item.offset() < item.rule()->items().size()) {\n lr1_item lr1(item, empty_set);\n item.rule()->items()[item.offset()]->closure(lr1, closure, machine.gram());\n }\n }\n\n if (!closure.empty()) {\n wcerr << endl;\n for (lr1_item_set::iterator closed = closure.begin(); closed != closure.end(); closed++) {\n wcerr << L\" \";\n dump(**closed, (*closed)->lookahead(), machine.gram(), builder.terminals());\n wcerr << endl;\n }\n }\n \n wcerr << endl;\n \n dump(builder.actions_for_state(stateId), builder.gram(), builder.terminals());\n\n wcerr << endl;\n }\n}\n\nstatic bool state_comparison_always_reversible(lalr_machine& m) {\n \/\/ If state X is less than state Y then state Y must not be less than state X\n for (int stateX = 0; stateX < m.count_states(); stateX++) {\n const lalr_state& stateXreal = *m.state_with_id(stateX);\n \n for (int stateY = 0; stateY < m.count_states(); stateY++) {\n const lalr_state& stateYreal = *m.state_with_id(stateY);\n \n if (stateXreal < stateYreal) {\n if (stateYreal < stateXreal) {\n \/\/ DOH!\n wcerr << stateX << L\" is less than \" << stateY << L\" but is also greater than or equal to it!\" << endl;\n return false;\n }\n }\n }\n }\n \n return true;\n}\n\nstatic bool no_duplicate_states(lalr_machine& m) {\n \/\/ State X and state Y can only be the same if they have the same ID\n bool ok = true;\n \n for (int stateX = 0; stateX < m.count_states(); stateX++) {\n const lalr_state& stateXreal = *m.state_with_id(stateX);\n \n for (int stateY = 0; stateY < m.count_states(); stateY++) {\n const lalr_state& stateYreal = *m.state_with_id(stateY);\n \n if (stateXreal == stateYreal) {\n if (stateX != stateY) {\n \/\/ DOH!\n wcerr << stateX << L\" is a duplicate of \" << stateY << endl;\n ok = false;\n }\n } else {\n if (stateX == stateY) {\n \/\/ DOH!\n wcerr << stateX << L\" isn't equal to itself!\" << endl;\n ok = false;\n }\n }\n }\n }\n \n return ok;\n}\n\nvoid test_lalr_general::run_tests() {\n \/\/ Grammar specified in example 4.46 of the dragon book\n grammar dragon446;\n terminal_dictionary terms;\n \n nonterminal sPrime(dragon446.id_for_nonterminal(L\"S'\"));\n nonterminal s(dragon446.id_for_nonterminal(L\"S\"));\n nonterminal l(dragon446.id_for_nonterminal(L\"L\"));\n nonterminal r(dragon446.id_for_nonterminal(L\"R\"));\n \n int equalsId = terms.add_symbol(L\"'='\");\n int timesId = terms.add_symbol(L\"'*'\");\n int idId = terms.add_symbol(L\"'i'\");\n \n terminal equals(equalsId);\n terminal times(timesId);\n terminal id(idId);\n \n \/\/ S' -> S\n (dragon446 += sPrime) << s;\n \n \/\/ S -> L = R | R\n (dragon446 += s) << l << equals << r;\n (dragon446 += s) << r;\n \n \/\/ L -> * R | id\n (dragon446 += l) << times << r;\n (dragon446 += l) << id;\n \n \/\/ R -> L\n (dragon446 += r) << l;\n \n \/\/ Build this grammar\n lalr_builder builder(dragon446, terms);\n \n \/\/ S' defines the language\n builder.add_initial_state(s);\n builder.complete_parser();\n \n dump_machine(builder);\n \n \/\/ Assert some things about the machine (specified in the dragon book)\n report(\"num-states\", builder.machine().count_states() == 10); \/\/ Figure 4.42: the result should have 10 states\n report(\"not-equal-simple\", (*builder.machine().state_with_id(1)) != (*builder.machine().state_with_id(6)));\n report(\"no-duplicate-states\", no_duplicate_states(builder.machine()));\n report(\"state-ordering-works\", state_comparison_always_reversible(builder.machine()));\n \n wcerr << formatter::to_string(*builder.machine().state_with_id(1), dragon446, terms) << endl;\n wcerr << formatter::to_string(*builder.machine().state_with_id(6), dragon446, terms) << endl;\n \n \/\/ Create a parser for this grammar\n simple_parser p(builder);\n character_lexer lex;\n \n typedef basic_string symbol_string;\n typedef basic_stringstream symbol_stringstream;\n \n symbol_string test1;\n symbol_string test2;\n \n test1 += idId;\n test2 += timesId;\n test2 += idId;\n test2 += equalsId;\n test2 += idId;\n \n symbol_stringstream stream1(test1);\n symbol_stringstream stream2(test2);\n \n simple_parser::state* parse1 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream1)));\n simple_parser::state* parse2 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream2)));\n \n \/\/ Test the parser\n report(\"accept1\", parse1->parse());\n report(\"accept2\", parse2->parse());\n \n delete parse1;\n delete parse2;\n \n#if 0\n \/\/ Run the parser 50000 times\n for (int x=0; x<50000; x++) {\n stringstream stream2(test2);\n simple_parser::state* parse2 = p.create_parser(new simple_parser_actions(lex.create_stream_from(stream2)));\n \n parse2->parse();\n delete parse2;\n }\n \n \/\/ Build the parser 10000 times\n for (int x=0; x<10000; x++) {\n \/\/ Build this grammar\n lalr_builder builder(dragon446);\n \n \/\/ S' defines the language\n builder.add_initial_state(s);\n builder.complete_parser();\n }\n#endif\n}\n<|endoftext|>"} {"text":"missed one<|endoftext|>"} {"text":"\/\/ Copyright 2017 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \"rcl\/expand_topic_name.h\"\n#include \"rcl\/validate_topic_name.h\"\n#include \"rmw\/validate_full_topic_name.h\"\n#include \"rmw\/validate_namespace.h\"\n#include \"rmw\/validate_node_name.h\"\n\n#include \"rclcpp\/exceptions.hpp\"\n#include \"rclcpp\/expand_topic_or_service_name.hpp\"\n\n#include \"..\/mocking_utils\/patch.hpp\"\n#include \"..\/utils\/rclcpp_gtest_macros.hpp\"\n\n\/*\n Testing expand_topic_or_service_name.\n *\/\nTEST(TestExpandTopicOrServiceName, normal) {\n using rclcpp::expand_topic_or_service_name;\n {\n ASSERT_EQ(\"\/ns\/chatter\", expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"));\n }\n}\n\n\/*\n Testing exceptions of expand_topic_or_service_name.\n *\/\nTEST(TestExpandTopicOrServiceName, exceptions) {\n using rclcpp::expand_topic_or_service_name;\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\", \"invalid_node?\", \"\/ns\");\n }, rclcpp::exceptions::InvalidNodeNameError);\n }\n\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\", \"node\", \"\/invalid_ns?\");\n }, rclcpp::exceptions::InvalidNamespaceError);\n }\n\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\/42invalid\", \"node\", \"\/ns\");\n }, rclcpp::exceptions::InvalidTopicNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ this one will only fail on the \"full\" topic name validation check\n expand_topic_or_service_name(\"chatter\/{ns}\/invalid\", \"node\", \"\/ns\");\n }, rclcpp::exceptions::InvalidTopicNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ is_service = true\n expand_topic_or_service_name(\"chatter\/42invalid\", \"node\", \"\/ns\", true);\n }, rclcpp::exceptions::InvalidServiceNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ is_service = true\n \/\/ this one will only fail on the \"full\" topic name validation check\n expand_topic_or_service_name(\"chatter\/{ns}\/invalid\", \"node\", \"\/ns\", true);\n }, rclcpp::exceptions::InvalidServiceNameError);\n }\n}\n\n\/\/ Required for mocking_utils below\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, ==)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, !=)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, <)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, >)\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_init_fail_bad_alloc) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_init, RCUTILS_RET_BAD_ALLOC);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::bad_alloc());\n}\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_init_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_init, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_get_default_topic_name_substitutions, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_and_map_fini_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_get_default_topic_name_substitutions, RCL_RET_ERROR);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_fini, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_fini_fail_bad_alloc) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_fini, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_valid_full_topic_name_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_full_topic_name, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_TOPIC_NAME_INVALID);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"topic name unexpectedly valid\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_validate_topic_name_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_TOPIC_NAME_INVALID);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_validate_topic_name, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_node_name_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAME);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_node_name, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate node name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_node_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAME);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_node_name, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate node name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_namespace_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAMESPACE);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_namespace, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate namespace\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_namespace_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAMESPACE);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_namespace, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate namespace\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(RCL_RET_ERROR, rcl_get_error_state(), \"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_full_topic_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_full_topic_name, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\nAdd in two more tests for expand_topic_or_service_name. (#1350)\/\/ Copyright 2017 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \n\n#include \"rcl\/expand_topic_name.h\"\n#include \"rcl\/validate_topic_name.h\"\n#include \"rmw\/validate_full_topic_name.h\"\n#include \"rmw\/validate_namespace.h\"\n#include \"rmw\/validate_node_name.h\"\n\n#include \"rclcpp\/exceptions.hpp\"\n#include \"rclcpp\/expand_topic_or_service_name.hpp\"\n\n#include \"..\/mocking_utils\/patch.hpp\"\n#include \"..\/utils\/rclcpp_gtest_macros.hpp\"\n\n\/*\n Testing expand_topic_or_service_name.\n *\/\nTEST(TestExpandTopicOrServiceName, normal) {\n using rclcpp::expand_topic_or_service_name;\n {\n ASSERT_EQ(\"\/ns\/chatter\", expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"));\n }\n}\n\n\/*\n Testing exceptions of expand_topic_or_service_name.\n *\/\nTEST(TestExpandTopicOrServiceName, exceptions) {\n using rclcpp::expand_topic_or_service_name;\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\", \"invalid_node?\", \"\/ns\");\n }, rclcpp::exceptions::InvalidNodeNameError);\n }\n\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\", \"node\", \"\/invalid_ns?\");\n }, rclcpp::exceptions::InvalidNamespaceError);\n }\n\n {\n ASSERT_THROW(\n {\n expand_topic_or_service_name(\"chatter\/42invalid\", \"node\", \"\/ns\");\n }, rclcpp::exceptions::InvalidTopicNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ this one will only fail on the \"full\" topic name validation check\n expand_topic_or_service_name(\"chatter\/{ns}\/invalid\", \"node\", \"\/ns\");\n }, rclcpp::exceptions::InvalidTopicNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ is_service = true\n expand_topic_or_service_name(\"chatter\/42invalid\", \"node\", \"\/ns\", true);\n }, rclcpp::exceptions::InvalidServiceNameError);\n }\n\n {\n ASSERT_THROW(\n {\n \/\/ is_service = true\n \/\/ this one will only fail on the \"full\" topic name validation check\n expand_topic_or_service_name(\"chatter\/{ns}\/invalid\", \"node\", \"\/ns\", true);\n }, rclcpp::exceptions::InvalidServiceNameError);\n }\n}\n\n\/\/ Required for mocking_utils below\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, ==)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, !=)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, <)\nMOCKING_UTILS_BOOL_OPERATOR_RETURNS_FALSE(rcutils_allocator_t, >)\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_init_fail_bad_alloc) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_init, RCUTILS_RET_BAD_ALLOC);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::bad_alloc());\n}\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_init_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_init, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_get_default_topic_name_substitutions, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_get_default_topic_name_substitution_and_map_fini_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_get_default_topic_name_substitutions, RCL_RET_ERROR);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_fini, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcutils_string_map_fini_fail_bad_alloc) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcutils_string_map_fini, RCUTILS_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_valid_full_topic_name_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_full_topic_name, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_TOPIC_NAME_INVALID);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"topic name unexpectedly valid\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_validate_topic_name_fail) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_TOPIC_NAME_INVALID);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_validate_topic_name, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_node_name_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAME);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_node_name, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate node name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_node_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAME);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_node_name, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate node name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_namespace_fail_invalid_argument) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAMESPACE);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_namespace, RMW_RET_INVALID_ARGUMENT);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLInvalidArgument(\n RCL_RET_INVALID_ARGUMENT, rcl_get_error_state(), \"failed to validate namespace\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_namespace_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAMESPACE);\n auto mock2 = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_namespace, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate namespace\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(RCL_RET_ERROR, rcl_get_error_state(), \"error not set\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail_invalid_node_name) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAME);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"invalid rcl node name but valid rmw node name\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rcl_expand_topic_name_fail_invalid_node_namespace) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rcl_expand_topic_name, RCL_RET_NODE_INVALID_NAMESPACE);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n std::runtime_error(\"invalid rcl namespace but valid rmw namespace\"));\n}\n\nTEST(TestExpandTopicOrServiceName, rmw_validate_full_topic_name_fail_other) {\n auto mock = mocking_utils::patch_and_return(\n \"lib:rclcpp\", rmw_validate_full_topic_name, RMW_RET_ERROR);\n RCLCPP_EXPECT_THROW_EQ(\n rclcpp::expand_topic_or_service_name(\"chatter\", \"node\", \"\/ns\"),\n rclcpp::exceptions::RCLError(\n RCL_RET_ERROR, rcl_get_error_state(), \"failed to validate full topic name\"));\n}\n<|endoftext|>"} {"text":"#include \"elem.hpp\"\n\nQComboBox *file_list() {\n QStringList string = QStringList() << \"BINARY\" << \"MOTOROLA\"\n << \"AIFF\" << \"WAVE\" << \"MP3\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n return combo;\n}\n\nQComboBox *track_list() {\n QStringList string = QStringList() << \"AUDIO\" << \"CDG\"\n << \"MODE1\/2048\" << \"MODE1\/2352\"\n << \"MODE2\/2336\" << \"MODE2\/2352\"\n << \"CDI\/2336\" << \"CDI\/2352\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n return combo;\n}\n\nQComboBox *genre_list() {\n QStringList string = QStringList() << \"\" << \"GENRE1\" << \"GENRE2\" << \"GENRE3\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n combo->setEditable(true);\n return combo;\n}\n\nQString GetFileName() {\n QString file_name = QFileDialog::getOpenFileName(0,\"Name\",\"cdda.wav\",\"Audio File (*.wav *.flac *.ape)\");\n int begin = file_name.lastIndexOf(QDir::separator());\n if (begin == -1)\n begin = 0;\n return file_name.mid(begin+1);\n}\n\nbool ParseMiddle(QString expstr, QString &var, QString line, int begin) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.at(begin);\n for (int x = begin+1; x < list.size()-1; ++x)\n line += \" \" + list.at(x);\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool ParseLast(QString expstr, QString &var, QString line) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.back();\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool ParseLast(QString expstr, QString &var, QString line, int begin) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.at(begin);\n for (int x = begin+1; x < list.size(); ++x)\n line += \" \" + list.at(x);\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool MMSSFF_valid(QString line) {\n if (line.count() != 8)\n return false;\n QStringList list = line.split(\":\",QString::SkipEmptyParts);\n if (list.size() != 3)\n return false;\n bool ok = true;\n int time = 0;\n time = list.at(0).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=99)) {\n time = list.at(1).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=59)) {\n time = list.at(2).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=74)) {\n return true;\n }\n }\n }\n return false;\n}\n\nQString MMSSFF_sum(QString line1, QString line2, bool &ok) {\n ok = true;\n QString retstr = \"00:00:00\";\n QStringList list1;\n QStringList list2;\n int mm = 0, ss = 0, ff = 0;\n if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {\n list1 = line1.split(\":\",QString::SkipEmptyParts);\n list2 = line2.split(\":\",QString::SkipEmptyParts);\n mm = list1.at(0).toInt() + list2.at(0).toInt();\n ss = list1.at(1).toInt() + list2.at(1).toInt();\n ff = list1.at(2).toInt() + list2.at(2).toInt();\n if (ff > 74) {\n ff = ff - 75;\n ss = ss + 1;\n }\n if (ss > 59) {\n ss = ss - 60;\n mm = mm + 1;\n }\n if (mm > 99)\n ok = false;\n else {\n retstr.clear();\n if (mm < 10)\n retstr += \"0\";\n retstr += QString::number(mm) + \":\";\n if (ss < 10)\n retstr += \"0\";\n retstr += QString::number(ss) + \":\";\n if (ff < 10)\n retstr += \"0\";\n retstr += QString::number(ff);\n }\n } else\n ok = false;\n return retstr;\n}\n\nQString MMSSFF_diff(QString line1, QString line2, bool &ok) {\n ok = true;\n QString retstr = \"00:00:00\";\n QStringList list1;\n QStringList list2;\n int mm = 0, ss = 0, ff = 0;\n if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {\n list1 = line1.split(\":\",QString::SkipEmptyParts);\n list2 = line2.split(\":\",QString::SkipEmptyParts);\n mm = list1.at(0).toInt() - list2.at(0).toInt();\n ss = list1.at(1).toInt() - list2.at(1).toInt();\n ff = list1.at(2).toInt() - list2.at(2).toInt();\n if (ff < 0) {\n ff = 75 + ff;\n ss = ss - 1;\n }\n if (ss < 0) {\n ss = 60 + ss;\n mm = mm - 1;\n }\n if (mm < 0)\n ok = false;\n else {\n if (mm < 10)\n retstr = \"0\";\n retstr += QString::number(mm) + \":\";\n if (ss < 10)\n retstr += \"0\";\n retstr += QString::number(ss) + \":\";\n if (ff < 10)\n retstr += \"0\";\n retstr += QString::number(ff);\n }\n } else\n ok = false;\n return retstr;\n}\nupdate genres list#include \"elem.hpp\"\n\nQComboBox *file_list() {\n QStringList string = QStringList() << \"BINARY\" << \"MOTOROLA\"\n << \"AIFF\" << \"WAVE\" << \"MP3\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n return combo;\n}\n\nQComboBox *track_list() {\n QStringList string = QStringList() << \"AUDIO\" << \"CDG\"\n << \"MODE1\/2048\" << \"MODE1\/2352\"\n << \"MODE2\/2336\" << \"MODE2\/2352\"\n << \"CDI\/2336\" << \"CDI\/2352\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n return combo;\n}\n\nQComboBox *genre_list() {\n QStringList string = QStringList() << \"\"\n << \"Blues\"\n << \"Classical\"\n << \"Country\"\n << \"Electronic\"\n << \"Folk\"\n << \"Funk\"\n << \"Hip-Hop\"\n << \"Jazz\"\n << \"Latin\"\n << \"New-Age\"\n << \"Pop\"\n << \"R&B\"\n << \"Reggae\"\n << \"Rock\"\n << \"Soundtrack\";\n QComboBox* combo = new QComboBox();\n combo->addItems(string);\n combo->setEditable(true);\n return combo;\n}\n\nQString GetFileName() {\n QString file_name = QFileDialog::getOpenFileName(0,\"Name\",\"cdda.wav\",\"Audio File (*.wav *.flac *.ape)\");\n int begin = file_name.lastIndexOf(QDir::separator());\n if (begin == -1)\n begin = 0;\n return file_name.mid(begin+1);\n}\n\nbool ParseMiddle(QString expstr, QString &var, QString line, int begin) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.at(begin);\n for (int x = begin+1; x < list.size()-1; ++x)\n line += \" \" + list.at(x);\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool ParseLast(QString expstr, QString &var, QString line) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.back();\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool ParseLast(QString expstr, QString &var, QString line, int begin) {\n QRegExp regexp;\n QStringList list;\n regexp.setPattern(expstr);\n if (line.contains(regexp))\n {\n list = line.split(\" \",QString::SkipEmptyParts);\n line = list.at(begin);\n for (int x = begin+1; x < list.size(); ++x)\n line += \" \" + list.at(x);\n list = line.split(\"\\\"\",QString::SkipEmptyParts);\n var = list.at(0);\n return true;\n } else\n return false;\n}\n\nbool MMSSFF_valid(QString line) {\n if (line.count() != 8)\n return false;\n QStringList list = line.split(\":\",QString::SkipEmptyParts);\n if (list.size() != 3)\n return false;\n bool ok = true;\n int time = 0;\n time = list.at(0).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=99)) {\n time = list.at(1).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=59)) {\n time = list.at(2).toInt(&ok);\n if ((ok)&&(time>=0)&&(time<=74)) {\n return true;\n }\n }\n }\n return false;\n}\n\nQString MMSSFF_sum(QString line1, QString line2, bool &ok) {\n ok = true;\n QString retstr = \"00:00:00\";\n QStringList list1;\n QStringList list2;\n int mm = 0, ss = 0, ff = 0;\n if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {\n list1 = line1.split(\":\",QString::SkipEmptyParts);\n list2 = line2.split(\":\",QString::SkipEmptyParts);\n mm = list1.at(0).toInt() + list2.at(0).toInt();\n ss = list1.at(1).toInt() + list2.at(1).toInt();\n ff = list1.at(2).toInt() + list2.at(2).toInt();\n if (ff > 74) {\n ff = ff - 75;\n ss = ss + 1;\n }\n if (ss > 59) {\n ss = ss - 60;\n mm = mm + 1;\n }\n if (mm > 99)\n ok = false;\n else {\n retstr.clear();\n if (mm < 10)\n retstr += \"0\";\n retstr += QString::number(mm) + \":\";\n if (ss < 10)\n retstr += \"0\";\n retstr += QString::number(ss) + \":\";\n if (ff < 10)\n retstr += \"0\";\n retstr += QString::number(ff);\n }\n } else\n ok = false;\n return retstr;\n}\n\nQString MMSSFF_diff(QString line1, QString line2, bool &ok) {\n ok = true;\n QString retstr = \"00:00:00\";\n QStringList list1;\n QStringList list2;\n int mm = 0, ss = 0, ff = 0;\n if ((MMSSFF_valid(line1))&&(MMSSFF_valid(line2))) {\n list1 = line1.split(\":\",QString::SkipEmptyParts);\n list2 = line2.split(\":\",QString::SkipEmptyParts);\n mm = list1.at(0).toInt() - list2.at(0).toInt();\n ss = list1.at(1).toInt() - list2.at(1).toInt();\n ff = list1.at(2).toInt() - list2.at(2).toInt();\n if (ff < 0) {\n ff = 75 + ff;\n ss = ss - 1;\n }\n if (ss < 0) {\n ss = 60 + ss;\n mm = mm - 1;\n }\n if (mm < 0)\n ok = false;\n else {\n if (mm < 10)\n retstr = \"0\";\n retstr += QString::number(mm) + \":\";\n if (ss < 10)\n retstr += \"0\";\n retstr += QString::number(ss) + \":\";\n if (ff < 10)\n retstr += \"0\";\n retstr += QString::number(ff);\n }\n } else\n ok = false;\n return retstr;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"OtherTranslationUnit.hpp\"\n\n\nclass Benchmarks\n{\npublic:\n\ttypedef joint::TypeList\tJointInterfaces;\n\nprivate:\n\tJoint_ModuleHandle _module;\n\npublic:\n\tBenchmarks(Joint_ModuleHandle module)\n\t\t: _module(module)\n\t{ }\n\n\t~Benchmarks()\n\t{ }\n\n\tvoid NoParamsMethod() { }\n\n\tvoid MeasureNativeNoParams(int64_t n)\n\t{\n\t\tfor (auto i = 0; i < n; ++i)\n\t\t\tNoParamsFunc();\n\t}\n\n\tvoid MeasureOutcomingNoParams(benchmarks::IInvokable_Ptr invokable, int64_t n)\n\t{\n\t\tfor (auto i = 0; i < n; ++i)\n\t\t\tinvokable->NoParamsMethod();\n\t}\n};\n\nextern \"C\"\n{\n\n#ifdef _MSC_VER\n\t__declspec(dllexport)\n#endif\n\tJoint_ObjectHandle GetBenchmarks(Joint_ModuleHandle module)\n\t{ return joint::Export(joint::MakeComponent(module, module)); }\n\n}\nAdded using namespace joint to Benchmarks.cpp#include \n\n#include \"OtherTranslationUnit.hpp\"\n\n\nusing namespace joint;\n\n\nclass Benchmarks\n{\npublic:\n\ttypedef TypeList\tJointInterfaces;\n\nprivate:\n\tJoint_ModuleHandle _module;\n\npublic:\n\tBenchmarks(Joint_ModuleHandle module)\n\t\t: _module(module)\n\t{ }\n\n\t~Benchmarks()\n\t{ }\n\n\tvoid NoParamsMethod() { }\n\n\tvoid MeasureNativeNoParams(int64_t n)\n\t{\n\t\tfor (auto i = 0; i < n; ++i)\n\t\t\tNoParamsFunc();\n\t}\n\n\tvoid MeasureOutcomingNoParams(benchmarks::IInvokable_Ptr invokable, int64_t n)\n\t{\n\t\tfor (auto i = 0; i < n; ++i)\n\t\t\tinvokable->NoParamsMethod();\n\t}\n};\n\nextern \"C\"\n{\n\n#ifdef _MSC_VER\n\t__declspec(dllexport)\n#endif\n\tJoint_ObjectHandle GetBenchmarks(Joint_ModuleHandle module)\n\t{ return Export(MakeComponent(module, module)); }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"bench_common.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace po = boost::program_options;\n\nstd::atomic_long append_count{0};\nstd::atomic_size_t reads_count{0};\nbool stop_info = false;\nbool stop_readers = false;\n\nclass BenchCallback : public dariadb::storage::ReaderClb {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &) { count++; }\n size_t count;\n};\n\nvoid show_info(dariadb::storage::Engine *storage) {\n clock_t t0 = clock();\n auto all_writes = dariadb_bench::total_threads_count * dariadb_bench::iteration_count;\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n clock_t t1 = clock();\n auto writes_per_sec = append_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto reads_per_sec = reads_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\"\n << \" reads: \" << reads_count << \" speed:\" << reads_per_sec << \"\/sec\"\n << \" writes: \" << append_count << \" speed: \" << writes_per_sec\n << \"\/sec progress:\" << (int64_t(100) * append_count) \/ all_writes\n << \"% \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set,\n dariadb::Time from, dariadb::Time to) {\n std::random_device r;\n std::default_random_engine e1(r());\n std::uniform_int_distribution uniform_dist(from, to);\n std::shared_ptr clbk{new BenchCallback};\n\n while (true) {\n clbk->count = 0;\n auto time_point1 = uniform_dist(e1);\n auto time_point2 = uniform_dist(e1);\n auto f = std::min(time_point1, time_point2);\n auto t = std::max(time_point1, time_point2);\n\n auto qi = dariadb::storage::QueryInterval(\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);\n ms->readInterval(qi)->readAll(clbk.get());\n\n reads_count += clbk->count;\n if (stop_readers) {\n break;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n std::cout << \"Performance benchmark\" << std::endl;\n std::cout << \"Writers count:\" << dariadb_bench::total_threads_count << std::endl;\n\n const std::string storage_path = \"testStorage\";\n bool readers_enable = false;\n bool metrics_enable = false;\n bool readonly = false;\n bool readall_enabled = false;\n bool dont_clean = false;\n po::options_description desc(\"Allowed options\");\n desc.add_options()(\"help\", \"produce help message\")\n (\"readonly\", \"readonly mode\")\n\t (\"readall\", \"read all benchmark enable.\")\n\t (\"enable-readers\", po::value(&readers_enable)->default_value(readers_enable),\"enable readers threads\")\n\t (\"enable-metrics\", po::value(&metrics_enable)->default_value(metrics_enable))\n\t (\"dont-clean\", po::value(&dont_clean)->default_value(dont_clean),\"dont clean storage path before start.\");\n\n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm);\n } catch (std::exception &ex) {\n logger(\"Error: \" << ex.what());\n exit(1);\n }\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (metrics_enable) {\n\t std::cout << \"enable metrics.\" << std::endl;\n }\n\n if (vm.count(\"readonly\")) {\n std::cout << \"Readonly mode.\" << std::endl;\n readonly=true;\n }\n\n if (vm.count(\"readall\")) {\n\t std::cout << \"Read all benchmark enabled.\" << std::endl;\n\t readall_enabled = true;\n }\n\n if (readers_enable) {\n std::cout << \"Readers enable. count: \" << dariadb_bench::total_readers_count\n << std::endl;\n }\n\n {\n std::cout << \"write...\" << std::endl;\n\n const size_t chunk_per_storage = 1024 * 100;\n const size_t chunk_size = 1024;\n const size_t cap_B = 50;\n const size_t max_mem_chunks = 100;\n\n \/\/ dont_clean = true;\n if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {\n if(!readonly){\n std::cout<<\" remove \"< writers(dariadb_bench::total_threads_count);\n std::vector readers(dariadb_bench::total_readers_count);\n\n size_t pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n auto id_from = dariadb_bench::get_id_from(pos);\n auto id_to = dariadb_bench::get_id_to(pos);\n for (size_t j = id_from; j < id_to; j++) {\n all_id_set.insert(j);\n }\n if(!readonly){\n std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),\n dariadb::Time(i), &append_count, raw_ptr};\n writers[pos] = std::move(t);\n }\n\t pos++;\n }\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t{reader, ms, all_id_set, dariadb::Time(0),\n dariadb::timeutil::current_time()};\n readers[pos++] = std::move(t);\n }\n }\n\n if(!readonly){\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n std::thread t = std::move(writers[pos++]);\n t.join();\n }\n }\n stop_readers = true;\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t = std::move(readers[pos++]);\n t.join();\n }\n }\n\n stop_info = true;\n info_thread.join();\n std::cout << \" total id:\" << all_id_set.size() << std::endl;\n {\n std::cout << \"full flush...\" << std::endl;\n auto start = clock();\n raw_ptr->flush();\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"flush time: \" << elapsed << std::endl;\n }\n\n auto queue_sizes = raw_ptr->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\"\n << \" reads: \" << reads_count\n << \" writes: \" << append_count\n << std::endl;\n\n dariadb_bench::readBenchark(all_id_set, ms.get(), 10, start_time,\n dariadb::timeutil::current_time());\n\tif(readall_enabled){\n std::cout << \"read all...\" << std::endl;\n std::shared_ptr clbk{new BenchCallback()};\n auto max_time = ms->maxTime();\n std::cout << \" end time: \" << dariadb::timeutil::to_string(max_time) << std::endl;\n\n auto start = clock();\n\n dariadb::storage::QueryInterval qi{\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,\n max_time};\n ms->readInterval(qi)->readAll(clbk.get());\n\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << clbk->count << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n auto expected = (dariadb_bench::iteration_count *\n dariadb_bench::total_threads_count * dariadb_bench::id_per_thread);\n\n if (!readonly && (!dont_clean && clbk->count != expected)) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n } else {\n if (!readonly && (dont_clean && clbk->count < expected)) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n }\n }\n }\n std::cout << \"stoping storage...\\n\";\n ms = nullptr;\n }\n std::cout << \"cleaning...\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n if (metrics_enable) {\n\t std::cout << \"metrics:\\n\" << dariadb::utils::MetricsManager::instance()->to_string() << std::endl;\n }\n}\nperf_benchmark: refact.#include \n#include \n#include \n#include \n\n#include \"bench_common.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace po = boost::program_options;\n\nstd::atomic_long append_count{0};\nstd::atomic_size_t reads_count{0};\nbool stop_info = false;\nbool stop_readers = false;\n\nclass BenchCallback : public dariadb::storage::ReaderClb {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &) { count++; }\n size_t count;\n};\n\nvoid show_info(dariadb::storage::Engine *storage) {\n clock_t t0 = clock();\n auto all_writes = dariadb_bench::total_threads_count * dariadb_bench::iteration_count;\n while (true) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n\n clock_t t1 = clock();\n auto writes_per_sec = append_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto reads_per_sec = reads_count.load() \/ double((t1 - t0) \/ CLOCKS_PER_SEC);\n auto queue_sizes = storage->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\"\n << \" reads: \" << reads_count << \" speed:\" << reads_per_sec << \"\/sec\"\n << \" writes: \" << append_count << \" speed: \" << writes_per_sec\n << \"\/sec progress:\" << (int64_t(100) * append_count) \/ all_writes\n << \"% \";\n std::cout.flush();\n if (stop_info) {\n std::cout.flush();\n break;\n }\n }\n std::cout << \"\\n\";\n}\n\nvoid reader(dariadb::storage::MeasStorage_ptr ms, dariadb::IdSet all_id_set,\n dariadb::Time from, dariadb::Time to) {\n std::random_device r;\n std::default_random_engine e1(r());\n std::uniform_int_distribution uniform_dist(from, to);\n std::shared_ptr clbk{new BenchCallback};\n\n while (true) {\n clbk->count = 0;\n auto time_point1 = uniform_dist(e1);\n auto time_point2 = uniform_dist(e1);\n auto f = std::min(time_point1, time_point2);\n auto t = std::max(time_point1, time_point2);\n\n auto qi = dariadb::storage::QueryInterval(\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, f, t);\n ms->readInterval(qi)->readAll(clbk.get());\n\n reads_count += clbk->count;\n if (stop_readers) {\n break;\n }\n }\n}\n\nint main(int argc, char *argv[]) {\n (void)argc;\n (void)argv;\n std::cout << \"Performance benchmark\" << std::endl;\n std::cout << \"Writers count:\" << dariadb_bench::total_threads_count << std::endl;\n\n const std::string storage_path = \"testStorage\";\n bool readers_enable = false;\n bool metrics_enable = false;\n bool readonly = false;\n bool readall_enabled = false;\n bool dont_clean = false;\n po::options_description desc(\"Allowed options\");\n desc.add_options()(\"help\", \"produce help message\")\n (\"readonly\", \"readonly mode\")\n\t (\"readall\", \"read all benchmark enable.\")\n\t (\"enable-readers\", po::value(&readers_enable)->default_value(readers_enable),\"enable readers threads\")\n\t (\"enable-metrics\", po::value(&metrics_enable)->default_value(metrics_enable))\n\t (\"dont-clean\", po::value(&dont_clean)->default_value(dont_clean),\"dont clean storage path before start.\");\n\n po::variables_map vm;\n try {\n po::store(po::parse_command_line(argc, argv, desc), vm);\n } catch (std::exception &ex) {\n logger(\"Error: \" << ex.what());\n exit(1);\n }\n po::notify(vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 1;\n }\n\n if (metrics_enable) {\n\t std::cout << \"enable metrics.\" << std::endl;\n }\n\n if (vm.count(\"readonly\")) {\n std::cout << \"Readonly mode.\" << std::endl;\n readonly=true;\n }\n\n if (vm.count(\"readall\")) {\n\t std::cout << \"Read all benchmark enabled.\" << std::endl;\n\t readall_enabled = true;\n }\n\n if (readers_enable) {\n std::cout << \"Readers enable. count: \" << dariadb_bench::total_readers_count\n << std::endl;\n }\n\n {\n std::cout << \"write...\" << std::endl;\n\n const size_t chunk_per_storage = 1024 * 100;\n const size_t chunk_size = 1024;\n const size_t cap_B = 50;\n const size_t max_mem_chunks = 100;\n\n \/\/ dont_clean = true;\n if (!dont_clean && dariadb::utils::fs::path_exists(storage_path)) {\n if(!readonly){\n std::cout<<\" remove \"< writers(dariadb_bench::total_threads_count);\n std::vector readers(dariadb_bench::total_readers_count);\n\n size_t pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n auto id_from = dariadb_bench::get_id_from(pos);\n auto id_to = dariadb_bench::get_id_to(pos);\n for (size_t j = id_from; j < id_to; j++) {\n all_id_set.insert(j);\n }\n if(!readonly){\n std::thread t{dariadb_bench::thread_writer_rnd_stor, dariadb::Id(pos),\n dariadb::Time(i), &append_count, raw_ptr};\n writers[pos] = std::move(t);\n }\n\t pos++;\n }\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t{reader, ms, all_id_set, dariadb::Time(0),\n dariadb::timeutil::current_time()};\n readers[pos++] = std::move(t);\n }\n }\n\n if(!readonly){\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_threads_count + 1; i++) {\n std::thread t = std::move(writers[pos++]);\n t.join();\n }\n }\n stop_readers = true;\n if (readers_enable) {\n pos = 0;\n for (size_t i = 1; i < dariadb_bench::total_readers_count + 1; i++) {\n std::thread t = std::move(readers[pos++]);\n t.join();\n }\n }\n\n stop_info = true;\n info_thread.join();\n std::cout << \" total id:\" << all_id_set.size() << std::endl;\n {\n std::cout << \"full flush...\" << std::endl;\n auto start = clock();\n raw_ptr->flush();\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"flush time: \" << elapsed << std::endl;\n }\n\n auto queue_sizes = raw_ptr->queue_size();\n std::cout << \"\\r\"\n << \" in queue: (p:\" << queue_sizes.pages_count\n << \" cap:\" << queue_sizes.cola_count << \" a:\" << queue_sizes.aofs_count\n << \")\"\n << \" reads: \" << reads_count\n << \" writes: \" << append_count\n << std::endl;\n\n dariadb_bench::readBenchark(all_id_set, ms.get(), 10, start_time,\n dariadb::timeutil::current_time());\n\tif(readall_enabled){\n std::cout << \"read all...\" << std::endl;\n std::shared_ptr clbk{new BenchCallback()};\n auto max_time = ms->maxTime();\n std::cout << \" end time: \" << dariadb::timeutil::to_string(max_time) << std::endl;\n\n auto start = clock();\n\n dariadb::storage::QueryInterval qi{\n dariadb::IdArray(all_id_set.begin(), all_id_set.end()), 0, start_time,\n max_time};\n ms->readInterval(qi)->readAll(clbk.get());\n\n auto elapsed = (((float)clock() - start) \/ CLOCKS_PER_SEC);\n std::cout << \"readed: \" << clbk->count << std::endl;\n std::cout << \"time: \" << elapsed << std::endl;\n auto expected = (dariadb_bench::iteration_count *\n dariadb_bench::total_threads_count * dariadb_bench::id_per_thread);\n\n if (!readonly && (!dont_clean && clbk->count != expected)) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n } else {\n if (!readonly && (dont_clean && clbk->count < expected)) {\n std::cout << \"expected: \" << expected << \" get:\" << clbk->count << std::endl;\n throw MAKE_EXCEPTION(\"(clbk->count!=(iteration_count*total_threads_count))\");\n }\n }\n }\n std::cout << \"stoping storage...\\n\";\n ms = nullptr;\n }\n \n if(!(dont_clean || readonly) && (dariadb::utils::fs::path_exists(storage_path)) ){\n std::cout << \"cleaning...\\n\";\n dariadb::utils::fs::rm(storage_path);\n }\n \n if (metrics_enable) {\n\t std::cout << \"metrics:\\n\" << dariadb::utils::MetricsManager::instance()->to_string() << std::endl;\n }\n}\n<|endoftext|>"} {"text":"#include \"Hardware.h\"\n\n#include \n#include \n#include \n\n#include \"..\/..\/..\/Fido\/include\/Fido.h\"\n#include \"..\/..\/Connection.h\"\n\n#define I_MIN_SAFE_ANG -65\n#define I_MAX_SAFE_ANG 65\n\n#define J_MIN_SAFE_ANG 35\n#define J_MAX_SAFE_ANG 180\n\n#define K_MIN_SAFE_ANG 0\n#define K_MAX_SAFE_ANG 90\n\ndouble randOutput() {\n\treturn ((double) rand() \/ (RAND_MAX))*2.0 - 1.0;\n}\n\nbool executeScaledAngles(Hardware *hardware, double i, double j, double k) {\n\tdouble iAng = Hardware::map(i, -1, 1, I_MIN_SAFE_ANG, I_MAX_SAFE_ANG);\n\tdouble jAng = Hardware::map(j, -1, 1, J_MIN_SAFE_ANG, J_MAX_SAFE_ANG);\n\tdouble kAng = Hardware::map(k, -1, 1, K_MIN_SAFE_ANG, K_MAX_SAFE_ANG);\n\n\treturn hardware->setJoints(iAng, jAng, kAng);\n}\n\nvoid stressTest(Hardware *hardware, int trials) {\n\tfor (int i=0; igetSonars(&l, &r);\n\t\tstd::cout << \"Sonars: (\" << l << \", \" << r << \")\\n\";\n\t\tstd::cout.flush();\n\t}\n}\n\nvoid proceduralPingPong() {\n\tHardware hand;\n\n\tint THRESH = 50;\n\tint NUM_SONAR_READINGS = 1;\n\n\thand.setJoints(0, 180, 45);\n\n\twhile (true) {\n\t\tint l, r;\n\t\thand.getSonars(&l, &r);\n\n std::cout << l << \", \" << r << \"\\n\";\n\n\t\tint delay = 0;\n\t\tdouble i = 0;\n\t\tif (abs(r-l) > THRESH) {\n\t\t\tif (r > l) {\n\t\t\t\tstd::cout << \"RIGHT\\n\";\n\t\t\t\ti = -30;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"LEFT\\n\";\n\t\t\t\ti = 30;\n\t\t\t} delay = 500000;\n\t\t} else std::cout << \"NOTHING\\n\";\n\n\t\t\/\/hand.setJoints(i, 180, 40, true);\n\t\t\/\/usleep(delay);\n\t}\n}\n\nvoid proceduralDrawing(Hardware *hand) {\n\thand->setJoints(-6, 95, 50);\n usleep(500000);\n\thand->setJoints(6, 95, 50);\n\tusleep(500000);\n\thand->setJoints(6, 100, 30);\n\tusleep(500000);\n\thand->setJoints(-6, 100, 30);\n\tusleep(500000);\n\thand->setJoints(-6, 95, 50);\n usleep(500000);\n\thand->poise();\n}\n\nint main() {\n\tsrand(time(NULL));\n proceduralPingPong();\n}\nWork on procedural ping pong#include \"Hardware.h\"\n\n#include \n#include \n#include \n\n#include \"..\/..\/..\/Fido\/include\/Fido.h\"\n#include \"..\/..\/Connection.h\"\n\n#define I_MIN_SAFE_ANG -65\n#define I_MAX_SAFE_ANG 65\n\n#define J_MIN_SAFE_ANG 35\n#define J_MAX_SAFE_ANG 180\n\n#define K_MIN_SAFE_ANG 0\n#define K_MAX_SAFE_ANG 90\n\ndouble randOutput() {\n\treturn ((double) rand() \/ (RAND_MAX))*2.0 - 1.0;\n}\n\nbool executeScaledAngles(Hardware *hardware, double i, double j, double k) {\n\tdouble iAng = Hardware::map(i, -1, 1, I_MIN_SAFE_ANG, I_MAX_SAFE_ANG);\n\tdouble jAng = Hardware::map(j, -1, 1, J_MIN_SAFE_ANG, J_MAX_SAFE_ANG);\n\tdouble kAng = Hardware::map(k, -1, 1, K_MIN_SAFE_ANG, K_MAX_SAFE_ANG);\n\n\treturn hardware->setJoints(iAng, jAng, kAng);\n}\n\nvoid stressTest(Hardware *hardware, int trials) {\n\tfor (int i=0; igetSonars(&l, &r);\n\t\tstd::cout << \"Sonars: (\" << l << \", \" << r << \")\\n\";\n\t\tstd::cout.flush();\n\t}\n}\n\nvoid proceduralPingPong() {\n\tHardware hand;\n\n\tint THRESH = 300;\n\tint NUM_SONAR_READINGS = 1;\n\n\thand.setJoints(0, 180, 45);\n\n\twhile (true) {\n\t\tdouble l = 0, r = 0;\n\t\tconst int NUM_READINGS = 3;\n for(int a = 0; a < NUM_READINGS; a++) {\n int tempL, tempR;\n hand.getSonars(&tempL, &tempR);\n l += tempL;\n r += tempR;\n }\n l \/= double(NUM_READINGS);\n r \/= double(NUM_READINGS);\n\n std::cout << l << \", \" << r << \"\\n\";\n\t\t\n int delay = 0;\n\t\tdouble i = 0;\n\t\tif (fabs(r-l) > THRESH) {\n\t\t\tif (r < l) {\n\t\t\t\tstd::cout << \"RIGHT\\n\";\n\t\t\t\ti = -30;\n\t\t\t} else {\n\t\t\t\tstd::cout << \"LEFT\\n\";\n\t\t\t\ti = 30;\n\t\t\t} delay = 500000;\n\t\t} else std::cout << \"NOTHING\\n\";\n\n\t\t\/\/hand.setJoints(i, 180, 40, true);\n\t\t\/\/usleep(delay);\n\t}\n}\n\nvoid proceduralDrawing(Hardware *hand) {\n\thand->setJoints(-6, 95, 50);\n usleep(500000);\n\thand->setJoints(6, 95, 50);\n\tusleep(500000);\n\thand->setJoints(6, 100, 30);\n\tusleep(500000);\n\thand->setJoints(-6, 100, 30);\n\tusleep(500000);\n\thand->setJoints(-6, 95, 50);\n usleep(500000);\n\thand->poise();\n}\n\nint main() {\n\tsrand(time(NULL));\n proceduralPingPong();\n}\n<|endoftext|>"} {"text":"\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\/\/ Boost\n#include \n#include \n\/\/ Standard Airline Object Model\n#include \n#include \n#include \n#include \n\/\/ Airline Inventory\n#include \n\/\/ Airline Schedule\n#include \n\/\/ Simcrs\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace SIMCRS {\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::\n SIMCRS_Service (std::ostream& ioLogStream, const CRSCode_T& iCRSCode,\n const stdair::Filename_T& iScheduleInputFilename)\n : _simcrsServiceContext (NULL) {\n init (ioLogStream, iCRSCode, iScheduleInputFilename);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::SIMCRS_Service () : _simcrsServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::SIMCRS_Service (const SIMCRS_Service& iService) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::~SIMCRS_Service () {\n \/\/ Delete\/Clean all the objects from memory\n finalise();\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void logInit (const LOG::EN_LogLevel iLogLevel,\n std::ostream& ioLogOutputFile) {\n Logger::instance().setLogParameters (iLogLevel, ioLogOutputFile);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::init (std::ostream& ioLogStream,\n const CRSCode_T& iCRSCode,\n const stdair::Filename_T& iScheduleInputFilename) {\n \/\/ Set the log file\n logInit (LOG::DEBUG, ioLogStream);\n\n \/\/ Initialise the context\n SIMCRS_ServiceContext& lSIMCRS_ServiceContext = \n FacSimcrsServiceContext::instance().create (iCRSCode);\n _simcrsServiceContext = &lSIMCRS_ServiceContext;\n\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Airline Inventory Management (AirInv) \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ TODO: do not hardcode the airline code (e.g., take it from a\n \/\/ configuration file).\n \/\/ Initialise the AIRINV service handler\n const stdair::AirlineCode_T lAirlineCode = \"BA\";\n\n \/\/ Note that the (Boost.)Smart Pointer keeps track of the references\n \/\/ on the Service object, and deletes that object when it is no longer\n \/\/ referenced (e.g., at the end of the process).\n AIRINV_ServicePtr_T lAIRINV_Service =\n AIRINV_ServicePtr_T (new AIRINV::AIRINV_Service (ioLogStream,\n lAirlineCode));\n\n \/\/ Store the AirInv service object within the (SimCRS) service context\n lSIMCRS_ServiceContext.setAIRINV_Service (lAIRINV_Service);\n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/ Airline Schedule Management (AirSched) \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ TODO: do not hardcode the initialisation phase of the schedule\n \/\/ Initialise the schedule\n stdair::AirlineFeatureSet& lAirlineFeatureSet =\n stdair::FacBomContent::instance().create();\n\n \/\/ TODO: do not harcode the airline code for the AirlineFeature object\n stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);\n stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::instance().\n create (lAirlineFeatureSet, lAirlineFeatureKey);\n\n \/\/ TODO: do not hardcode the start analysis date\n const stdair::Date_T lStartAnalysisDate (2000, 1, 1);\n\n \/\/ Initialise the AIRSCHED service handler\n AIRSCHED_ServicePtr_T lAIRSCHED_Service = \n AIRSCHED_ServicePtr_T (new AIRSCHED::\n AIRSCHED_Service (ioLogStream, lAirlineFeatureSet,\n lStartAnalysisDate,\n iScheduleInputFilename));\n\n \/\/ Store the AirSched service object within the (SimCRS) service context\n lSIMCRS_ServiceContext.setAIRSCHED_Service (lAIRSCHED_Service);\n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::finalise () {\n assert (_simcrsServiceContext != NULL);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::sell (const stdair::AirlineCode_T& iAirlineCode,\n const stdair::PartySize_T& iPartySize) {\n \n if (_simcrsServiceContext == NULL) {\n throw NonInitialisedServiceException();\n }\n assert (_simcrsServiceContext != NULL);\n SIMCRS_ServiceContext& lSIMCRS_ServiceContext= *_simcrsServiceContext;\n\n try {\n \n \/\/ Get a reference on the AIRINV service handler\n AIRINV::AIRINV_Service& lAIRINV_Service =\n lSIMCRS_ServiceContext.getAIRINV_Service();\n \n \/\/ Retrieve the airline code\n const CRSCode_T& lCRSCode =\n lSIMCRS_ServiceContext.getCRSCode();\n \n \/\/ Delegate the booking to the dedicated command\n BasChronometer lSellChronometer;\n lSellChronometer.start();\n DistributionManager::sell (lAIRINV_Service,\n lCRSCode, iAirlineCode, iPartySize);\n const double lSellMeasure = lSellChronometer.elapsed();\n \n \/\/ DEBUG\n SIMCRS_LOG_DEBUG (\"Booking sell: \" << lSellMeasure << \" - \"\n << lSIMCRS_ServiceContext.display());\n\n } catch (const std::exception& error) {\n SIMCRS_LOG_ERROR (\"Exception: \" << error.what());\n throw BookingException();\n }\n }\n \n}\nSeperate the linkage phase from the initialisation phase of the content child.\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Import section\n\/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ STL\n#include \n#include \n\/\/ Boost\n#include \n#include \n\/\/ Standard Airline Object Model\n#include \n#include \n#include \n#include \n\/\/ Airline Inventory\n#include \n\/\/ Airline Schedule\n#include \n\/\/ Simcrs\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace SIMCRS {\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::\n SIMCRS_Service (std::ostream& ioLogStream, const CRSCode_T& iCRSCode,\n const stdair::Filename_T& iScheduleInputFilename)\n : _simcrsServiceContext (NULL) {\n init (ioLogStream, iCRSCode, iScheduleInputFilename);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::SIMCRS_Service () : _simcrsServiceContext (NULL) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::SIMCRS_Service (const SIMCRS_Service& iService) {\n assert (false);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SIMCRS_Service::~SIMCRS_Service () {\n \/\/ Delete\/Clean all the objects from memory\n finalise();\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void logInit (const LOG::EN_LogLevel iLogLevel,\n std::ostream& ioLogOutputFile) {\n Logger::instance().setLogParameters (iLogLevel, ioLogOutputFile);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::init (std::ostream& ioLogStream,\n const CRSCode_T& iCRSCode,\n const stdair::Filename_T& iScheduleInputFilename) {\n \/\/ Set the log file\n logInit (LOG::DEBUG, ioLogStream);\n\n \/\/ Initialise the context\n SIMCRS_ServiceContext& lSIMCRS_ServiceContext = \n FacSimcrsServiceContext::instance().create (iCRSCode);\n _simcrsServiceContext = &lSIMCRS_ServiceContext;\n\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ Airline Inventory Management (AirInv) \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ TODO: do not hardcode the airline code (e.g., take it from a\n \/\/ configuration file).\n \/\/ Initialise the AIRINV service handler\n const stdair::AirlineCode_T lAirlineCode = \"BA\";\n\n \/\/ Note that the (Boost.)Smart Pointer keeps track of the references\n \/\/ on the Service object, and deletes that object when it is no longer\n \/\/ referenced (e.g., at the end of the process).\n AIRINV_ServicePtr_T lAIRINV_Service =\n AIRINV_ServicePtr_T (new AIRINV::AIRINV_Service (ioLogStream,\n lAirlineCode));\n\n \/\/ Store the AirInv service object within the (SimCRS) service context\n lSIMCRS_ServiceContext.setAIRINV_Service (lAIRINV_Service);\n\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/ Airline Schedule Management (AirSched) \/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ TODO: do not hardcode the initialisation phase of the schedule\n \/\/ Initialise the schedule\n stdair::AirlineFeatureSet& lAirlineFeatureSet =\n stdair::FacBomContent::instance().create();\n\n \/\/ TODO: do not harcode the airline code for the AirlineFeature object\n stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);\n stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::\n instance().create (lAirlineFeatureKey);\n stdair::FacBomContent::\n linkWithParent (lAirlineFeature,\n lAirlineFeatureSet);\n\n \/\/ TODO: do not hardcode the start analysis date\n const stdair::Date_T lStartAnalysisDate (2000, 1, 1);\n\n \/\/ Initialise the AIRSCHED service handler\n AIRSCHED_ServicePtr_T lAIRSCHED_Service = \n AIRSCHED_ServicePtr_T (new AIRSCHED::\n AIRSCHED_Service (ioLogStream, lAirlineFeatureSet,\n lStartAnalysisDate,\n iScheduleInputFilename));\n\n \/\/ Store the AirSched service object within the (SimCRS) service context\n lSIMCRS_ServiceContext.setAIRSCHED_Service (lAIRSCHED_Service);\n }\n \n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::finalise () {\n assert (_simcrsServiceContext != NULL);\n }\n\n \/\/ \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SIMCRS_Service::sell (const stdair::AirlineCode_T& iAirlineCode,\n const stdair::PartySize_T& iPartySize) {\n \n if (_simcrsServiceContext == NULL) {\n throw NonInitialisedServiceException();\n }\n assert (_simcrsServiceContext != NULL);\n SIMCRS_ServiceContext& lSIMCRS_ServiceContext= *_simcrsServiceContext;\n\n try {\n \n \/\/ Get a reference on the AIRINV service handler\n AIRINV::AIRINV_Service& lAIRINV_Service =\n lSIMCRS_ServiceContext.getAIRINV_Service();\n \n \/\/ Retrieve the airline code\n const CRSCode_T& lCRSCode =\n lSIMCRS_ServiceContext.getCRSCode();\n \n \/\/ Delegate the booking to the dedicated command\n BasChronometer lSellChronometer;\n lSellChronometer.start();\n DistributionManager::sell (lAIRINV_Service,\n lCRSCode, iAirlineCode, iPartySize);\n const double lSellMeasure = lSellChronometer.elapsed();\n \n \/\/ DEBUG\n SIMCRS_LOG_DEBUG (\"Booking sell: \" << lSellMeasure << \" - \"\n << lSIMCRS_ServiceContext.display());\n\n } catch (const std::exception& error) {\n SIMCRS_LOG_ERROR (\"Exception: \" << error.what());\n throw BookingException();\n }\n }\n \n}\n<|endoftext|>"} {"text":"\/*\n Source File : InputFlateDecodeStream.cpp\n\n\n Copyright 2011 Gal Kahana PDFWriter\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n \n*\/\n#include \"InputFlateDecodeStream.h\"\n\n#include \"Trace.h\"\n#include \"zlib.h\"\n\n\nInputFlateDecodeStream::InputFlateDecodeStream(void)\n{\n\tmZLibState = new z_stream;\n\tmSourceStream = NULL;\n\tmCurrentlyEncoding = false;\n\tmEndOfCompressionEoncountered = false;\n}\n\nInputFlateDecodeStream::~InputFlateDecodeStream(void)\n{\n\tif(mCurrentlyEncoding)\n\t\tFinalizeEncoding();\n\tif(mSourceStream)\n\t\tdelete mSourceStream;\n\tdelete mZLibState;\n}\n\nvoid InputFlateDecodeStream::FinalizeEncoding()\n{\n\t\/\/ no need for flushing here, there's no notion of Z_FINISH. so just end the library work\n\tinflateEnd(mZLibState);\n\tmCurrentlyEncoding = false;\n}\n\nInputFlateDecodeStream::InputFlateDecodeStream(IByteReader* inSourceReader)\n{\n\tmZLibState = new z_stream;\n\tmSourceStream = NULL;\n\tmCurrentlyEncoding = false;\n\n\tAssign(inSourceReader);\n}\n\nvoid InputFlateDecodeStream::Assign(IByteReader* inSourceReader)\n{\n\tmSourceStream = inSourceReader;\n\tif(mSourceStream)\n\t\tStartEncoding();\n}\n\nvoid InputFlateDecodeStream::StartEncoding()\n{\n\tmZLibState->zalloc = Z_NULL;\n mZLibState->zfree = Z_NULL;\n mZLibState->opaque = Z_NULL;\n\tmZLibState->avail_in = 0;\n\tmZLibState->next_in = Z_NULL;\n\tmEndOfCompressionEoncountered = false;\n\n\n int inflateStatus = inflateInit(mZLibState);\n if (inflateStatus != Z_OK)\n\t\tTRACE_LOG1(\"InputFlateDecodeStream::StartEncoding, Unexpected failure in initializating flate library. status code = %d\",inflateStatus);\n\telse\n\t\tmCurrentlyEncoding = true;\n}\n\nstatic bool isError(int inflateResult)\n{\n\treturn (Z_STREAM_ERROR == inflateResult ||\n\t\tZ_NEED_DICT == inflateResult ||\n\t\tZ_DATA_ERROR == inflateResult ||\n\t\tZ_MEM_ERROR == inflateResult);\n}\n\nIOBasicTypes::LongBufferSizeType InputFlateDecodeStream::Read(IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)\n{\n\tif(mCurrentlyEncoding)\n\t\treturn DecodeBufferAndRead(inBuffer,inBufferSize);\n\telse if(mSourceStream)\n\t\treturn mSourceStream->Read(inBuffer,inBufferSize);\n\telse\n\t\treturn 0;\n}\n\nIOBasicTypes::LongBufferSizeType InputFlateDecodeStream::DecodeBufferAndRead(const IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inSize)\n{\n\tif(0 == inSize)\n\t\treturn 0; \/\/ inflate kinda touchy about getting 0 lengths\n\n\tint inflateResult = Z_OK;\n\n\tdo\n\t{\n\t\tmZLibState->avail_out = (uInt)inSize;\n\t\tmZLibState->next_out = (Bytef*)inBuffer;\n\n\t\t\/\/ first, flush whatever is already available\n\t\twhile(mZLibState->avail_in != 0 && mZLibState->avail_out != 0)\n\t\t{\n\t\t\tinflateResult = inflate(mZLibState,Z_NO_FLUSH);\n\t\t\tif(isError(inflateResult))\n\t\t\t{\n\t\t\t\tTRACE_LOG1(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read zlib information. returned error code = %d\",inflateResult);\n\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(Z_OK != inflateResult && Z_STREAM_END != inflateResult)\n\t\t\tbreak;\n\n\t\t\/\/ if not finished read buffer, repeatedly read from input stream, and inflate till done\n\t\twhile((0 < mZLibState->avail_out) && mSourceStream->NotEnded())\n\t\t{\n\t\t\tif(mSourceStream->Read(&mBuffer,1) != 1)\n\t\t\t{\n\t\t\t\tTRACE_LOG(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read from source stream\");\n\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\tinflateResult = Z_STREAM_ERROR;\n\t\t\t\tmCurrentlyEncoding = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmZLibState->avail_in = 1; \n\t\t\tmZLibState->next_in = (Bytef*)&mBuffer;\n\n\t\t\twhile(mZLibState->avail_in != 0 && mZLibState->avail_out != 0 && inflateResult != Z_STREAM_END)\n\t\t\t{\n\t\t\t\tinflateResult = inflate(mZLibState,Z_NO_FLUSH);\n\t\t\t\tif(isError(inflateResult))\n\t\t\t\t{\n\t\t\t\t\tTRACE_LOG1(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read zlib information. returned error code = %d\",inflateResult);\n\t\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(Z_OK != inflateResult && Z_STREAM_END != inflateResult)\n\t\t\t\tbreak;\n\t\t}\n\t} while(false);\n\n\t\/\/ should be that at the last buffer we'll get here a nice Z_STREAM_END\n\tmEndOfCompressionEoncountered = (Z_STREAM_END == inflateResult) || isError(inflateResult);\n\tif(Z_OK == inflateResult || Z_STREAM_END == inflateResult)\n\t\treturn inSize - mZLibState->avail_out;\n\telse\n\t\treturn 0;\n}\n\nbool InputFlateDecodeStream::NotEnded()\n{\n\tif(mSourceStream)\n\t\treturn (mSourceStream->NotEnded() || mZLibState->avail_in != 0) && !mEndOfCompressionEoncountered;\n\telse\n\t\treturn mZLibState->avail_in != 0 && mEndOfCompressionEoncountered;\n}to switch\/*\n Source File : InputFlateDecodeStream.cpp\n\n\n Copyright 2011 Gal Kahana PDFWriter\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n \n*\/\n#include \"InputFlateDecodeStream.h\"\n\n#include \"Trace.h\"\n#include \"zlib.h\"\n\n\nInputFlateDecodeStream::InputFlateDecodeStream(void)\n{\n\tmZLibState = new z_stream;\n\tmSourceStream = NULL;\n\tmCurrentlyEncoding = false;\n\tmEndOfCompressionEoncountered = false;\n}\n\nInputFlateDecodeStream::~InputFlateDecodeStream(void)\n{\n\tif(mCurrentlyEncoding)\n\t\tFinalizeEncoding();\n\tif(mSourceStream)\n\t\tdelete mSourceStream;\n\tdelete mZLibState;\n}\n\nvoid InputFlateDecodeStream::FinalizeEncoding()\n{\n\t\/\/ no need for flushing here, there's no notion of Z_FINISH. so just end the library work\n\tinflateEnd(mZLibState);\n\tmCurrentlyEncoding = false;\n}\n\nInputFlateDecodeStream::InputFlateDecodeStream(IByteReader* inSourceReader)\n{\n\tmZLibState = new z_stream;\n\tmSourceStream = NULL;\n\tmCurrentlyEncoding = false;\n\n\tAssign(inSourceReader);\n}\n\nvoid InputFlateDecodeStream::Assign(IByteReader* inSourceReader)\n{\n\tmSourceStream = inSourceReader;\n\tif(mSourceStream)\n\t\tStartEncoding();\n}\n\nvoid InputFlateDecodeStream::StartEncoding()\n{\n\tmZLibState->zalloc = Z_NULL;\n mZLibState->zfree = Z_NULL;\n mZLibState->opaque = Z_NULL;\n\tmZLibState->avail_in = 0;\n\tmZLibState->next_in = Z_NULL;\n\tmEndOfCompressionEoncountered = false;\n\n\n int inflateStatus = inflateInit(mZLibState);\n if (inflateStatus != Z_OK)\n\t\tTRACE_LOG1(\"InputFlateDecodeStream::StartEncoding, Unexpected failure in initializating flate library. status code = %d\",inflateStatus);\n\telse\n\t\tmCurrentlyEncoding = true;\n}\n\nstatic bool isError(int inflateResult)\n{\n\tswitch(inflateResult) {\n\t\tcase Z_STREAM_ERROR:\n\t\tcase Z_NEED_DICT:\n\t\tcase Z_DATA_ERROR:\n\t\tcase Z_MEM_ERROR:\n\t\t\treturn true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\nIOBasicTypes::LongBufferSizeType InputFlateDecodeStream::Read(IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inBufferSize)\n{\n\tif(mCurrentlyEncoding)\n\t\treturn DecodeBufferAndRead(inBuffer,inBufferSize);\n\telse if(mSourceStream)\n\t\treturn mSourceStream->Read(inBuffer,inBufferSize);\n\telse\n\t\treturn 0;\n}\n\nIOBasicTypes::LongBufferSizeType InputFlateDecodeStream::DecodeBufferAndRead(const IOBasicTypes::Byte* inBuffer,IOBasicTypes::LongBufferSizeType inSize)\n{\n\tif(0 == inSize)\n\t\treturn 0; \/\/ inflate kinda touchy about getting 0 lengths\n\n\tint inflateResult = Z_OK;\n\n\tdo\n\t{\n\t\tmZLibState->avail_out = (uInt)inSize;\n\t\tmZLibState->next_out = (Bytef*)inBuffer;\n\n\t\t\/\/ first, flush whatever is already available\n\t\twhile(mZLibState->avail_in != 0 && mZLibState->avail_out != 0)\n\t\t{\n\t\t\tinflateResult = inflate(mZLibState,Z_NO_FLUSH);\n\t\t\tif(isError(inflateResult))\n\t\t\t{\n\t\t\t\tTRACE_LOG1(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read zlib information. returned error code = %d\",inflateResult);\n\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tif(Z_OK != inflateResult && Z_STREAM_END != inflateResult)\n\t\t\tbreak;\n\n\t\t\/\/ if not finished read buffer, repeatedly read from input stream, and inflate till done\n\t\twhile((0 < mZLibState->avail_out) && mSourceStream->NotEnded())\n\t\t{\n\t\t\tif(mSourceStream->Read(&mBuffer,1) != 1)\n\t\t\t{\n\t\t\t\tTRACE_LOG(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read from source stream\");\n\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\tinflateResult = Z_STREAM_ERROR;\n\t\t\t\tmCurrentlyEncoding = false;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tmZLibState->avail_in = 1; \n\t\t\tmZLibState->next_in = (Bytef*)&mBuffer;\n\n\t\t\twhile(mZLibState->avail_in != 0 && mZLibState->avail_out != 0 && inflateResult != Z_STREAM_END)\n\t\t\t{\n\t\t\t\tinflateResult = inflate(mZLibState,Z_NO_FLUSH);\n\t\t\t\tif(isError(inflateResult))\n\t\t\t\t{\n\t\t\t\t\tTRACE_LOG1(\"InputFlateDecodeStream::DecodeBufferAndRead, failed to read zlib information. returned error code = %d\",inflateResult);\n\t\t\t\t\tinflateEnd(mZLibState);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(Z_OK != inflateResult && Z_STREAM_END != inflateResult)\n\t\t\t\tbreak;\n\t\t}\n\t} while(false);\n\n\t\/\/ should be that at the last buffer we'll get here a nice Z_STREAM_END\n\tmEndOfCompressionEoncountered = (Z_STREAM_END == inflateResult) || isError(inflateResult);\n\tif(Z_OK == inflateResult || Z_STREAM_END == inflateResult)\n\t\treturn inSize - mZLibState->avail_out;\n\telse\n\t\treturn 0;\n}\n\nbool InputFlateDecodeStream::NotEnded()\n{\n\tif(mSourceStream)\n\t\treturn (mSourceStream->NotEnded() || mZLibState->avail_in != 0) && !mEndOfCompressionEoncountered;\n\telse\n\t\treturn mZLibState->avail_in != 0 && mEndOfCompressionEoncountered;\n}<|endoftext|>"} {"text":"AliAnalysisTaskStrange *AddTaskStrange(Short_t lCollidingSystems=0, \/*0 = pp, 1 = AA*\/,\n\t\t\t\t TString lAnalysisCut=\"no\" )\n{\n\/\/ Creates, configures and attaches to the train a strangeness task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskStrange\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskStrange\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n\n \/\/ Create and configure the task\n\tAliAnalysisTaskStrange *taskstrange = new AliAnalysisTaskStrange(\"TaskStrange\");\n taskstrange->SetCollidingSystems(lCollidingSystems);\n taskstrange->SetAnalysisType(type);\n taskstrange->SetAnalysisCut(lAnalysisCut);\n mgr->AddTask(taskstrange);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outname = \"PP\";\n if (lCollidingSystems) outname = \"AA\";\n if (mgr->GetMCtruthEventHandler()) outname += \"-MC-\";\n outname += \"StrangeList.root\";\n\tAliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"clistStrange\",\n\t\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outname );\n \n mgr->ConnectInput(taskstrange, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskstrange, 1, coutput1);\n return taskstrange;\n} \nFix trivial syntax errorAliAnalysisTaskStrange *AddTaskStrange(Short_t lCollidingSystems=0, \/*0 = pp, 1 = AA*\/\n\t\t\t\t TString lAnalysisCut=\"no\" )\n{\n\/\/ Creates, configures and attaches to the train a strangeness task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskStrange\", \"No analysis manager to connect to.\");\n return NULL;\n } \n\n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskStrange\", \"This task requires an input event handler\");\n return NULL;\n } \n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n\n \/\/ Create and configure the task\n\tAliAnalysisTaskStrange *taskstrange = new AliAnalysisTaskStrange(\"TaskStrange\");\n taskstrange->SetCollidingSystems(lCollidingSystems);\n taskstrange->SetAnalysisType(type);\n taskstrange->SetAnalysisCut(lAnalysisCut);\n mgr->AddTask(taskstrange);\n\n \/\/ Create ONLY the output containers for the data produced by the task.\n \/\/ Get and connect other common input\/output containers via the manager as below\n \/\/==============================================================================\n TString outname = \"PP\";\n if (lCollidingSystems) outname = \"AA\";\n if (mgr->GetMCtruthEventHandler()) outname += \"-MC-\";\n outname += \"StrangeList.root\";\n\tAliAnalysisDataContainer *coutput1 = mgr->CreateContainer(\"clistStrange\",\n\t\t\t\t\t\t\t\t TList::Class(),\n\t\t\t\t\t\t\t\t AliAnalysisManager::kOutputContainer,\n\t\t\t\t\t\t\t\t outname );\n \n mgr->ConnectInput(taskstrange, 0, mgr->GetCommonInputContainer());\n mgr->ConnectOutput(taskstrange, 1, coutput1);\n return taskstrange;\n} \n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 Austin Robot Technology\n * License: Modified BSD Software License Agreement\n *\n * $Id$\n *\/\n\n\/** @file\n\n Implementation for converting a Velodyne 3D LIDAR PointXYZIR cloud\n to PointXYZRGB, assigning colors for visualization of the laser\n rings.\n\n @author Jack O'Quin\n*\/\n\n#include \"colors.h\"\n#include \n\n\/\/\/ @todo make sure these includes are really necessary\n#include \n#include \n\nnamespace\n{\n \/\/ RGB color values\n const int color_red = 0xff0000;\n const int color_orange = 0xff8800;\n const int color_yellow = 0xffff00;\n const int color_green = 0x00ff00;\n const int color_blue = 0x0000ff;\n const int color_violet = 0xff00ff;\n\n const int N_COLORS = 6;\n int rainbow[N_COLORS] = {color_red, color_orange, color_yellow,\n color_green, color_blue, color_violet};\n}\n\nnamespace velodyne_pointcloud\n{\n\n \/** types of output point and cloud *\/\n typedef pcl::PointXYZRGB RGBPoint;\n typedef pcl::PointCloud RGBPointCloud;\n\n \/** @brief Constructor. *\/\n RingColors::RingColors(ros::NodeHandle node, ros::NodeHandle private_nh)\n {\n \/\/ advertise output point cloud (before subscribing to input data)\n output_ =\n node.advertise(\"velodyne_rings\", 10);\n\n \/\/ subscribe to VelodyneScan packets\n input_ =\n node.subscribe(\"velodyne_points\", 10,\n &RingColors::convertPoints, this,\n ros::TransportHints().tcpNoDelay(true));\n }\n\n\n \/** @brief Callback for Velodyne PointXYZRI messages. *\/\n void\n RingColors::convertPoints(const VPointCloud::ConstPtr &inMsg)\n {\n if (output_.getNumSubscribers() == 0) \/\/ no one listening?\n return; \/\/ do nothing\n\n \/\/ allocate an PointXYZRGB message with same time and frame ID as\n \/\/ input data\n RGBPointCloud::Ptr outMsg(new RGBPointCloud());\n outMsg->header.stamp = inMsg->header.stamp;\n outMsg->header.frame_id = inMsg->header.frame_id;\n outMsg->height = 1;\n\n for (size_t i = 0; i < inMsg->points.size(); ++i)\n {\n RGBPoint p;\n p.x = inMsg->points[i].x;\n p.y = inMsg->points[i].y;\n p.z = inMsg->points[i].z;\n\n \/\/ color lasers with the rainbow array\n int color = inMsg->points[i].ring % N_COLORS;\n p.rgb = *reinterpret_cast(&rainbow[color]);\n\n outMsg->points.push_back(p);\n ++outMsg->width;\n }\n\n output_.publish(outMsg);\n }\n\n} \/\/ namespace velodyne_pcl\nModified velodyne_pointcloud\/src\/conversion\/colors.cc to remove address build warning for strict-aliasing.\/*\n * Copyright (C) 2012 Austin Robot Technology\n * License: Modified BSD Software License Agreement\n *\n * $Id$\n *\/\n\n\/** @file\n\n Implementation for converting a Velodyne 3D LIDAR PointXYZIR cloud\n to PointXYZRGB, assigning colors for visualization of the laser\n rings.\n\n @author Jack O'Quin\n*\/\n\n#include \"colors.h\"\n#include \n\n\/\/\/ @todo make sure these includes are really necessary\n#include \n#include \n\nnamespace\n{\n \/\/ RGB color values\n const int color_red = 0xff0000;\n const int color_orange = 0xff8800;\n const int color_yellow = 0xffff00;\n const int color_green = 0x00ff00;\n const int color_blue = 0x0000ff;\n const int color_violet = 0xff00ff;\n\n const int N_COLORS = 6;\n int rainbow[N_COLORS] = {color_red, color_orange, color_yellow,\n color_green, color_blue, color_violet};\n}\n\nnamespace velodyne_pointcloud\n{\n\n \/** types of output point and cloud *\/\n typedef pcl::PointXYZRGB RGBPoint;\n typedef pcl::PointCloud RGBPointCloud;\n\n \/** @brief Constructor. *\/\n RingColors::RingColors(ros::NodeHandle node, ros::NodeHandle private_nh)\n {\n \/\/ advertise output point cloud (before subscribing to input data)\n output_ =\n node.advertise(\"velodyne_rings\", 10);\n\n \/\/ subscribe to VelodyneScan packets\n input_ =\n node.subscribe(\"velodyne_points\", 10,\n &RingColors::convertPoints, this,\n ros::TransportHints().tcpNoDelay(true));\n }\n\n\n \/** @brief Callback for Velodyne PointXYZRI messages. *\/\n void\n RingColors::convertPoints(const VPointCloud::ConstPtr &inMsg)\n {\n if (output_.getNumSubscribers() == 0) \/\/ no one listening?\n return; \/\/ do nothing\n\n \/\/ allocate an PointXYZRGB message with same time and frame ID as\n \/\/ input data\n RGBPointCloud::Ptr outMsg(new RGBPointCloud());\n outMsg->header.stamp = inMsg->header.stamp;\n outMsg->header.frame_id = inMsg->header.frame_id;\n outMsg->height = 1;\n\n for (size_t i = 0; i < inMsg->points.size(); ++i)\n {\n RGBPoint p;\n p.x = inMsg->points[i].x;\n p.y = inMsg->points[i].y;\n p.z = inMsg->points[i].z;\n\n \/\/ color lasers with the rainbow array\n int color = inMsg->points[i].ring % N_COLORS;\n p.rgb = *reinterpret_cast(rainbow+color);\n\n outMsg->points.push_back(p);\n ++outMsg->width;\n }\n\n output_.publish(outMsg);\n }\n\n} \/\/ namespace velodyne_pcl\n<|endoftext|>"} {"text":"#include \"Genes\/King_Confinement_Gene.h\"\n\n#include \n#include \n#include \n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Game\/Square.h\"\n#include \"Game\/Piece.h\"\n\n#include \"Utility\/Random.h\"\n#include \"Utility\/Math.h\"\n\nKing_Confinement_Gene::King_Confinement_Gene() noexcept\n{\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\nstd::string King_Confinement_Gene::name() const noexcept\n{\n return \"King Confinement Gene\";\n}\n\nvoid King_Confinement_Gene::load_gene_properties(const std::map& properties)\n{\n friendly_block_score = properties.at(\"Friendly Block Score\");\n opponent_block_score = properties.at(\"Opponent Block Score\");\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\nvoid King_Confinement_Gene::adjust_properties(std::map& properties) const noexcept\n{\n properties[\"Friendly Block Score\"] = friendly_block_score;\n properties[\"Opponent Block Score\"] = opponent_block_score;\n}\n\nvoid King_Confinement_Gene::gene_specific_mutation() noexcept\n{\n auto mutation_size = Random::random_laplace(0.03);\n if(Random::coin_flip())\n {\n friendly_block_score += mutation_size;\n }\n else\n {\n opponent_block_score += mutation_size;\n }\n\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\ndouble King_Confinement_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept\n{\n std::array square_queue{};\n size_t queue_insertion_point = 0;\n std::array in_queue{};\n\n const auto king_square = board.find_king(perspective);\n\n square_queue[queue_insertion_point++] = king_square;\n in_queue[king_square.index()] = true;\n\n double friendly_block_total = 0.0;\n double opponent_block_total = 0.0;\n int free_space_total = 0;\n\n for(auto square : square_queue)\n {\n if( ! square.is_set())\n {\n break;\n }\n\n \/\/ Always check the squares surrounding the king's current positions, even if\n \/\/ it is not safe (i.e., the king is in check).\n auto add_surrounding_squares = square == king_square;\n\n auto piece = board.piece_on_square(square);\n\n if(piece && piece.color() == perspective && piece.type() != Piece_Type::KING) \/\/ Square is blocked by a friendly piece\n {\n friendly_block_total += friendly_block_score;\n }\n else if( ! board.safe_for_king(square, perspective)) \/\/ Square is attacked by an opposing piece\n {\n opponent_block_total += opponent_block_score;\n }\n else\n {\n ++free_space_total;\n add_surrounding_squares = true;\n }\n\n \/\/ Add surrounding squares to square_queue.\n if(add_surrounding_squares)\n {\n for(auto file_step = -1; file_step <= 1; ++file_step)\n {\n for(auto rank_step = -1; rank_step <= 1; ++rank_step)\n {\n auto new_square = square + Square_Difference{file_step, rank_step};\n if(new_square.inside_board() && ! in_queue[new_square.index()])\n {\n square_queue[queue_insertion_point++] = new_square;\n in_queue[new_square.index()] = true;\n }\n }\n }\n }\n }\n\n return (friendly_block_total + opponent_block_total)\/(1 + free_space_total);\n}\nReduce numeric conversions#include \"Genes\/King_Confinement_Gene.h\"\n\n#include \n#include \n#include \n\n#include \"Genes\/Gene.h\"\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Game\/Square.h\"\n#include \"Game\/Piece.h\"\n\n#include \"Utility\/Random.h\"\n#include \"Utility\/Math.h\"\n\nKing_Confinement_Gene::King_Confinement_Gene() noexcept\n{\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\nstd::string King_Confinement_Gene::name() const noexcept\n{\n return \"King Confinement Gene\";\n}\n\nvoid King_Confinement_Gene::load_gene_properties(const std::map& properties)\n{\n friendly_block_score = properties.at(\"Friendly Block Score\");\n opponent_block_score = properties.at(\"Opponent Block Score\");\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\nvoid King_Confinement_Gene::adjust_properties(std::map& properties) const noexcept\n{\n properties[\"Friendly Block Score\"] = friendly_block_score;\n properties[\"Opponent Block Score\"] = opponent_block_score;\n}\n\nvoid King_Confinement_Gene::gene_specific_mutation() noexcept\n{\n auto mutation_size = Random::random_laplace(0.03);\n if(Random::coin_flip())\n {\n friendly_block_score += mutation_size;\n }\n else\n {\n opponent_block_score += mutation_size;\n }\n\n Math::normalize(friendly_block_score, opponent_block_score);\n}\n\ndouble King_Confinement_Gene::score_board(const Board& board, Piece_Color perspective, size_t) const noexcept\n{\n std::array square_queue{};\n size_t queue_insertion_point = 0;\n std::array in_queue{};\n\n const auto king_square = board.find_king(perspective);\n\n square_queue[queue_insertion_point++] = king_square;\n in_queue[king_square.index()] = true;\n\n double friendly_block_total = 0.0;\n double opponent_block_total = 0.0;\n double free_space_total = 0.0;\n\n for(auto square : square_queue)\n {\n if( ! square.is_set())\n {\n break;\n }\n\n \/\/ Always check the squares surrounding the king's current positions, even if\n \/\/ it is not safe (i.e., the king is in check).\n auto add_surrounding_squares = square == king_square;\n\n auto piece = board.piece_on_square(square);\n\n if(piece && piece.color() == perspective && piece.type() != Piece_Type::KING) \/\/ Square is blocked by a friendly piece\n {\n friendly_block_total += friendly_block_score;\n }\n else if( ! board.safe_for_king(square, perspective)) \/\/ Square is attacked by an opposing piece\n {\n opponent_block_total += opponent_block_score;\n }\n else\n {\n free_space_total += 1.0;\n add_surrounding_squares = true;\n }\n\n \/\/ Add surrounding squares to square_queue.\n if(add_surrounding_squares)\n {\n for(auto file_step = -1; file_step <= 1; ++file_step)\n {\n for(auto rank_step = -1; rank_step <= 1; ++rank_step)\n {\n auto new_square = square + Square_Difference{file_step, rank_step};\n if(new_square.inside_board() && ! in_queue[new_square.index()])\n {\n square_queue[queue_insertion_point++] = new_square;\n in_queue[new_square.index()] = true;\n }\n }\n }\n }\n }\n\n return (friendly_block_total + opponent_block_total)\/(1.0 + free_space_total);\n}\n<|endoftext|>"} {"text":"#include \"Genes\/King_Confinement_Gene.h\"\n\n#include \n\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Pieces\/Piece.h\"\n\nKing_Confinement_Gene::King_Confinement_Gene() : maximum_score(0.0)\n{\n \/\/ Maximum score comes from a king in the middle of an empty board\n auto king_file = 'e';\n auto king_rank = 4;\n\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n for(auto rank = 1; rank <= 8; ++rank)\n {\n auto distance = std::max(std::abs(king_file - file), std::abs(king_rank - rank));\n maximum_score += 1.0\/(distance + 1.0);\n }\n }\n}\n\nKing_Confinement_Gene::~King_Confinement_Gene()\n{\n}\n\nKing_Confinement_Gene* King_Confinement_Gene::duplicate() const\n{\n return new King_Confinement_Gene(*this);\n}\n\nstd::string King_Confinement_Gene::name() const\n{\n return \"King Confinement Gene\";\n}\n\ndouble King_Confinement_Gene::score_board(const Board& board, Color perspective) const\n{\n \/\/ A flood-fill-like algorithm to count the squares that are reachable by the\n \/\/ king from its current positions with unlimited consecutive moves. The\n \/\/ boundaries of this area area squares attacked by the other color or occupied\n \/\/ by pieces of the same color.\n \/\/\n \/\/ The more moves it takes to reach a square, the less it adds to the score.\n\n std::vector square_queue;\n square_queue.reserve(64);\n auto king_square = board.find_king(perspective);\n square_queue.push_back(king_square);\n\n std::map distance;\n distance[king_square] = 1;\n\n double score = 0.0;\n\n for(size_t i = 0; i < square_queue.size(); ++i)\n {\n auto square = square_queue[i];\n\n bool attacked_by_other = ! board.safe_for_king(square.file,\n square.rank,\n perspective);\n\n auto piece = board.view_piece_on_square(square.file, square.rank);\n bool occupied_by_same = piece &&\n piece->color() == perspective &&\n ! piece->is_king();\n\n auto is_safe = ! attacked_by_other && ! occupied_by_same;\n if(is_safe)\n {\n score += 1.0\/distance[square];\n }\n\n \/\/ Add surrounding squares to square_queue.\n \/\/ always check the squares surrounding the king's current positions, even if\n \/\/ it is not safe (i.e., the king is in check).\n if(is_safe || square_queue.size() == 1)\n {\n for(char new_file = square.file - 1; new_file <= square.file + 1; ++new_file)\n {\n if( ! board.inside_board(new_file))\n {\n continue;\n }\n\n for(int new_rank = square.rank - 1; new_rank <= square.rank + 1; ++new_rank)\n {\n if( ! board.inside_board(new_rank))\n {\n continue;\n }\n\n auto new_square = Square{new_file, new_rank};\n if(distance[new_square] == 0) \/\/ never checked\n {\n square_queue.push_back(new_square);\n distance[new_square] = distance[square] + 1;\n }\n }\n }\n }\n }\n\n return score\/maximum_score; \/\/ normalized so max is 1\n}\nSimplifying calculation of King Confinement normalization#include \"Genes\/King_Confinement_Gene.h\"\n\n#include \n\n#include \"Game\/Board.h\"\n#include \"Game\/Color.h\"\n#include \"Pieces\/Piece.h\"\n\nKing_Confinement_Gene::King_Confinement_Gene() : maximum_score(0.0)\n{\n \/\/ Maximum score comes from a king in the middle of an empty board\n auto king_square = Square{'e', 4};\n\n for(auto file = 'a'; file <= 'h'; ++file)\n {\n for(auto rank = 1; rank <= 8; ++rank)\n {\n auto distance = king_distance(king_square, {file, rank});\n maximum_score += 1.0\/(distance + 1.0);\n }\n }\n}\n\nKing_Confinement_Gene::~King_Confinement_Gene()\n{\n}\n\nKing_Confinement_Gene* King_Confinement_Gene::duplicate() const\n{\n return new King_Confinement_Gene(*this);\n}\n\nstd::string King_Confinement_Gene::name() const\n{\n return \"King Confinement Gene\";\n}\n\ndouble King_Confinement_Gene::score_board(const Board& board, Color perspective) const\n{\n \/\/ A flood-fill-like algorithm to count the squares that are reachable by the\n \/\/ king from its current positions with unlimited consecutive moves. The\n \/\/ boundaries of this area area squares attacked by the other color or occupied\n \/\/ by pieces of the same color.\n \/\/\n \/\/ The more moves it takes to reach a square, the less it adds to the score.\n\n std::vector square_queue;\n square_queue.reserve(64);\n auto king_square = board.find_king(perspective);\n square_queue.push_back(king_square);\n\n std::map distance;\n distance[king_square] = 1;\n\n double score = 0.0;\n\n for(size_t i = 0; i < square_queue.size(); ++i)\n {\n auto square = square_queue[i];\n\n bool attacked_by_other = ! board.safe_for_king(square.file,\n square.rank,\n perspective);\n\n auto piece = board.view_piece_on_square(square.file, square.rank);\n bool occupied_by_same = piece &&\n piece->color() == perspective &&\n ! piece->is_king();\n\n auto is_safe = ! attacked_by_other && ! occupied_by_same;\n if(is_safe)\n {\n score += 1.0\/distance[square];\n }\n\n \/\/ Add surrounding squares to square_queue.\n \/\/ always check the squares surrounding the king's current positions, even if\n \/\/ it is not safe (i.e., the king is in check).\n if(is_safe || square_queue.size() == 1)\n {\n for(char new_file = square.file - 1; new_file <= square.file + 1; ++new_file)\n {\n if( ! board.inside_board(new_file))\n {\n continue;\n }\n\n for(int new_rank = square.rank - 1; new_rank <= square.rank + 1; ++new_rank)\n {\n if( ! board.inside_board(new_rank))\n {\n continue;\n }\n\n auto new_square = Square{new_file, new_rank};\n if(distance[new_square] == 0) \/\/ never checked\n {\n square_queue.push_back(new_square);\n distance[new_square] = distance[square] + 1;\n }\n }\n }\n }\n }\n\n return score\/maximum_score; \/\/ normalized so max is 1\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Ra {\nnamespace Gui {\n\/\/\/ An utility class used to map a (combination) of key \/ modifier to a specific action.\n\/\/\/ It can load configuration from a file or if no config is found it will load an\n\/\/\/ internal version of the default configuration.\nclass RA_GUI_API KeyMappingManager : public Ra::Core::Utils::ObservableVoid\n{\n RA_SINGLETON_INTERFACE( KeyMappingManager );\n\n \/\/ Needed by Q_ENUM\n Q_GADGET\n\n public:\n using KeyMappingAction = Ra::Core::Utils::Index;\n using Context = Ra::Core::Utils::Index;\n\n \/\/\/ load configuration from filename, or default configration filename. It\n \/\/\/ calls the listener callback then.\n void loadConfiguration( const char* filename = nullptr );\n\n \/\/\/ Save the configuration\n \/\/\/ @param filename the file to write to. It will be replaced\n \/\/\/ @return true if file was correctly saved\n bool saveConfiguration( const char* filename = nullptr );\n\n \/\/\/ reload last open file.\n void reloadConfiguration();\n\n \/\/\/ Return the action associated to the binding buttons + modifiers + key\n \/\/\/ \\param buttons are the mouse buttons pressed, could be NoButton\n \/\/\/ \\param modifiers are the keyboard modifiers, could be NoModifiers\n \/\/\/ \\param key is the key pressed, could be -1\n KeyMappingManager::KeyMappingAction getAction( const KeyMappingManager::Context& context,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key,\n bool wheel = false );\n\n \/\/\/ Add a given action to the mapping system.\n \/\/\/ This allow to define default behavior when some KeyMappingManageable object is not\n \/\/\/ parameterized in the application config file. The action is added to the current config file\n \/\/\/ so that it will remain for subsequent usage.\n \/\/\/ @todo write the configuration in the configFile to be later reused or modified ?\n \/\/\/ @param context the context of the action\n \/\/\/ @param keyString represents the key that needs to be pressed to trigger the event\n \/\/\/ (ie Key_Z, for example), \"\" or \"-1\" corresponds to no key needed.\n \/\/\/ @param modifiersString represents the modifier used along with key or mouse button `\n \/\/\/ (needs to be a Qt::Modifier enum value) to trigger the action. Multiples modifiers can be\n \/\/\/ specified, separated by commas as in \"ControlModifier,ShiftModifier\".\n \/\/\/ @param buttonsString represents the button to trigger the event (e.g. LeftButton).\n \/\/\/ @param wheelString if true, it's a wheel event !\n \/\/\/ @param actionString represents the KeyMappingAction enum's value you want to\n \/\/\/ trigger.\n void addAction( const std::string& context,\n const std::string& keyString,\n const std::string& modifiersString,\n const std::string& buttonsString,\n const std::string& wheelString,\n const std::string& actionString );\n\n \/\/\/ Return the context index corresponding to contextName\n \/\/\/ \\param contextName the name of the context\n \/\/\/ \\return an invalid context if contextName has not been created\n Context getContext( const std::string& contextName );\n\n \/\/\/ Return the action index corresponding to a context index and actionName\n \/\/\/ \\param context the index of the context\n \/\/\/ \\param actionName the name of the action\n \/\/\/ \\return an invalid action if context is not valid, or if actionName has not been created.\n \/\/\/ (i,e action.isInvalid())\n KeyMappingAction getActionIndex( const Context& context, const std::string& actionName );\n\n \/\/\/ \\return Action name if context index and action index are valid, \"Invalid\" otherwise\n std::string getActionName( const Context& context, const KeyMappingAction& action );\n\n \/\/\/ \\return Context name if context index is valid, \"Invalid\" otherwise\n std::string getContextName( const Context& context );\n\n \/\/\/ Add a callback, triggered when configuration is load or reloaded.\n int addListener( Observable::Observer callback );\n\n \/\/\/ Remove a callback. To be called when the related Context\/Actions are no more needed.\n \/\/\/ @param callbackId the Id, returned by addListener, of the Observer to be removed.\n void removeListener( int callbackId );\n\n \/\/\/ return a string of enum names from mouse buttons, comma separated,\n \/\/\/ without space\n static std::string enumNamesFromMouseButtons( const Qt::MouseButtons& buttons );\n\n \/\/\/ return a string of enum names from keyboard modifiers, comma separated,\n \/\/\/ without space\n static std::string enumNamesFromKeyboardModifiers( const Qt::KeyboardModifiers& modifiers );\n\n private:\n KeyMappingManager();\n ~KeyMappingManager();\n\n \/\/\/ Save an XML node that describes an event\/action.\n void saveNode( QXmlStreamWriter& stream, const QDomNode& domNode );\n\n \/\/ Private for now, but may need to be public if we want to customize keymapping configuration\n \/\/ otherwise than by editing the XML configuration file.\n class MouseBinding\n {\n public:\n explicit MouseBinding( Qt::MouseButtons buttons,\n Qt::KeyboardModifiers modifiers = Qt::NoModifier,\n int key = -1,\n bool wheel = false ) :\n\n m_buttons {buttons}, m_modifiers {modifiers}, m_key {key}, m_wheel {wheel} {}\n bool operator<( const MouseBinding& b ) const {\n return ( m_buttons < b.m_buttons ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers < b.m_modifiers ) ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers == b.m_modifiers ) &&\n ( m_key < b.m_key ) ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers == b.m_modifiers ) &&\n ( m_key == b.m_key ) && ( m_wheel < b.m_wheel ) );\n }\n\n \/\/ private:\n Qt::MouseButtons m_buttons;\n Qt::KeyboardModifiers m_modifiers;\n \/\/ only one key\n int m_key;\n bool m_wheel;\n };\n\n \/\/\/ bind binding to actionIndex, in contextIndex. If replace previously\n \/\/\/ binded action, with a warning if binding was alreasly present.,\n void bindKeyToAction( Ra::Core::Utils::Index contextIndex,\n const MouseBinding& binding,\n Ra::Core::Utils::Index actionIndex );\n\n void loadConfigurationInternal();\n void loadConfigurationTagsInternal( QDomElement& node );\n void loadConfigurationMappingInternal( const std::string& context,\n const std::string& keyString,\n const std::string& modifiersString,\n const std::string& buttonsString,\n const std::string& wheelString,\n const std::string& actionString );\n\n \/\/\/ Return KeyboardModifiers described in modifierString, multiple modifiers\n \/\/\/ are comma separated in the modifiers string, as in\n \/\/\/ \"ShiftModifier,AltModifier\". This function do note trim any white space.\n static Qt::KeyboardModifiers getQtModifiersValue( const std::string& modifierString );\n\n \/\/\/ Return MouseButtons desribed in buttonString, multiple modifiers\n \/\/\/ are comma separated in the modifiers string, \\note only one button is\n \/\/\/ supported for the moment.\n static Qt::MouseButtons getQtMouseButtonsValue( const std::string& buttonsString );\n\n private:\n std::string m_defaultConfigFile;\n \/\/ For XML parsing using Qt\n QDomDocument m_domDocument;\n QMetaEnum m_metaEnumAction;\n QMetaEnum m_metaEnumKey;\n QFile* m_file;\n\n using MouseBindingMapping = std::map;\n using ContextNameMap = std::map;\n using ActionNameMap = std::map;\n\n ContextNameMap m_contextNameToIndex; \/\/\/< context string give index\n std::vector m_actionNameToIndex; \/\/\/< one element per context\n std::vector m_mappingAction; \/\/\/< one element per context\n};\n\n\/\/\/ KeyMappingManageable decorate, typical use as a CRTP :\n\/\/\/ class MyClass : public KeyMappingManageable { [...]\n\/\/\/ it defines a static class member m_keyMappingContext, readable with\n\/\/\/ getContext()\n\/\/\/ This context index must be registered by the class to the KeyMappingManager\n\/\/\/ with KeyMappingManager::getContext(\"MyClassContextName\"); after a\n\/\/\/ configuration file is loaded.\ntemplate \nclass KeyMappingManageable\n{\n public:\n static inline KeyMappingManager::Context getContext() { return m_keyMappingContext; }\n\n \/\/\/ KeyManageable class should implement static configureKeyMapping_impl to get their\n \/\/\/ keyMappingAction constants.\n static inline void configureKeyMapping() { T::configureKeyMapping_impl(); }\n\n protected:\n T& self() { return static_cast( *this ); }\n static inline void setContext( const KeyMappingManager::Context& c ) {\n m_keyMappingContext = c;\n }\n\n private:\n static KeyMappingManager::Context m_keyMappingContext;\n};\n\n\/\/\/ create one m_keyMappingContext by template type.\ntemplate \nKeyMappingManager::Context KeyMappingManageable::m_keyMappingContext;\n\n} \/\/ namespace Gui\n} \/\/ namespace Ra\n[gui] add accessor to keymapping filename.#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace Ra {\nnamespace Gui {\n\/\/\/ An utility class used to map a (combination) of key \/ modifier to a specific action.\n\/\/\/ It can load configuration from a file or if no config is found it will load an\n\/\/\/ internal version of the default configuration.\nclass RA_GUI_API KeyMappingManager : public Ra::Core::Utils::ObservableVoid\n{\n RA_SINGLETON_INTERFACE( KeyMappingManager );\n\n \/\/ Needed by Q_ENUM\n Q_GADGET\n\n public:\n using KeyMappingAction = Ra::Core::Utils::Index;\n using Context = Ra::Core::Utils::Index;\n\n \/\/\/ load configuration from filename, or default configration filename. It\n \/\/\/ calls the listener callback then.\n void loadConfiguration( const char* filename = nullptr );\n\n \/\/\/ Save the configuration\n \/\/\/ @param filename the file to write to. It will be replaced\n \/\/\/ @return true if file was correctly saved\n bool saveConfiguration( const char* filename = nullptr );\n\n \/\/\/ reload last open file.\n void reloadConfiguration();\n\n std::string getLoadedFilename() { return m_file->fileName().toStdString(); }\n\n \/\/\/ Return the action associated to the binding buttons + modifiers + key\n \/\/\/ \\param buttons are the mouse buttons pressed, could be NoButton\n \/\/\/ \\param modifiers are the keyboard modifiers, could be NoModifiers\n \/\/\/ \\param key is the key pressed, could be -1\n KeyMappingManager::KeyMappingAction getAction( const KeyMappingManager::Context& context,\n const Qt::MouseButtons& buttons,\n const Qt::KeyboardModifiers& modifiers,\n int key,\n bool wheel = false );\n\n \/\/\/ Add a given action to the mapping system.\n \/\/\/ This allow to define default behavior when some KeyMappingManageable object is not\n \/\/\/ parameterized in the application config file. The action is added to the current config file\n \/\/\/ so that it will remain for subsequent usage.\n \/\/\/ @todo write the configuration in the configFile to be later reused or modified ?\n \/\/\/ @param context the context of the action\n \/\/\/ @param keyString represents the key that needs to be pressed to trigger the event\n \/\/\/ (ie Key_Z, for example), \"\" or \"-1\" corresponds to no key needed.\n \/\/\/ @param modifiersString represents the modifier used along with key or mouse button `\n \/\/\/ (needs to be a Qt::Modifier enum value) to trigger the action. Multiples modifiers can be\n \/\/\/ specified, separated by commas as in \"ControlModifier,ShiftModifier\".\n \/\/\/ @param buttonsString represents the button to trigger the event (e.g. LeftButton).\n \/\/\/ @param wheelString if true, it's a wheel event !\n \/\/\/ @param actionString represents the KeyMappingAction enum's value you want to\n \/\/\/ trigger.\n void addAction( const std::string& context,\n const std::string& keyString,\n const std::string& modifiersString,\n const std::string& buttonsString,\n const std::string& wheelString,\n const std::string& actionString );\n\n \/\/\/ Return the context index corresponding to contextName\n \/\/\/ \\param contextName the name of the context\n \/\/\/ \\return an invalid context if contextName has not been created\n Context getContext( const std::string& contextName );\n\n \/\/\/ Return the action index corresponding to a context index and actionName\n \/\/\/ \\param context the index of the context\n \/\/\/ \\param actionName the name of the action\n \/\/\/ \\return an invalid action if context is not valid, or if actionName has not been created.\n \/\/\/ (i,e action.isInvalid())\n KeyMappingAction getActionIndex( const Context& context, const std::string& actionName );\n\n \/\/\/ \\return Action name if context index and action index are valid, \"Invalid\" otherwise\n std::string getActionName( const Context& context, const KeyMappingAction& action );\n\n \/\/\/ \\return Context name if context index is valid, \"Invalid\" otherwise\n std::string getContextName( const Context& context );\n\n \/\/\/ Add a callback, triggered when configuration is load or reloaded.\n int addListener( Observable::Observer callback );\n\n \/\/\/ Remove a callback. To be called when the related Context\/Actions are no more needed.\n \/\/\/ @param callbackId the Id, returned by addListener, of the Observer to be removed.\n void removeListener( int callbackId );\n\n \/\/\/ return a string of enum names from mouse buttons, comma separated,\n \/\/\/ without space\n static std::string enumNamesFromMouseButtons( const Qt::MouseButtons& buttons );\n\n \/\/\/ return a string of enum names from keyboard modifiers, comma separated,\n \/\/\/ without space\n static std::string enumNamesFromKeyboardModifiers( const Qt::KeyboardModifiers& modifiers );\n\n private:\n KeyMappingManager();\n ~KeyMappingManager();\n\n \/\/\/ Save an XML node that describes an event\/action.\n void saveNode( QXmlStreamWriter& stream, const QDomNode& domNode );\n\n \/\/ Private for now, but may need to be public if we want to customize keymapping configuration\n \/\/ otherwise than by editing the XML configuration file.\n class MouseBinding\n {\n public:\n explicit MouseBinding( Qt::MouseButtons buttons,\n Qt::KeyboardModifiers modifiers = Qt::NoModifier,\n int key = -1,\n bool wheel = false ) :\n\n m_buttons {buttons}, m_modifiers {modifiers}, m_key {key}, m_wheel {wheel} {}\n bool operator<( const MouseBinding& b ) const {\n return ( m_buttons < b.m_buttons ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers < b.m_modifiers ) ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers == b.m_modifiers ) &&\n ( m_key < b.m_key ) ) ||\n ( ( m_buttons == b.m_buttons ) && ( m_modifiers == b.m_modifiers ) &&\n ( m_key == b.m_key ) && ( m_wheel < b.m_wheel ) );\n }\n\n \/\/ private:\n Qt::MouseButtons m_buttons;\n Qt::KeyboardModifiers m_modifiers;\n \/\/ only one key\n int m_key;\n bool m_wheel;\n };\n\n \/\/\/ bind binding to actionIndex, in contextIndex. If replace previously\n \/\/\/ binded action, with a warning if binding was alreasly present.,\n void bindKeyToAction( Ra::Core::Utils::Index contextIndex,\n const MouseBinding& binding,\n Ra::Core::Utils::Index actionIndex );\n\n void loadConfigurationInternal();\n void loadConfigurationTagsInternal( QDomElement& node );\n void loadConfigurationMappingInternal( const std::string& context,\n const std::string& keyString,\n const std::string& modifiersString,\n const std::string& buttonsString,\n const std::string& wheelString,\n const std::string& actionString );\n\n \/\/\/ Return KeyboardModifiers described in modifierString, multiple modifiers\n \/\/\/ are comma separated in the modifiers string, as in\n \/\/\/ \"ShiftModifier,AltModifier\". This function do note trim any white space.\n static Qt::KeyboardModifiers getQtModifiersValue( const std::string& modifierString );\n\n \/\/\/ Return MouseButtons desribed in buttonString, multiple modifiers\n \/\/\/ are comma separated in the modifiers string, \\note only one button is\n \/\/\/ supported for the moment.\n static Qt::MouseButtons getQtMouseButtonsValue( const std::string& buttonsString );\n\n private:\n std::string m_defaultConfigFile;\n \/\/ For XML parsing using Qt\n QDomDocument m_domDocument;\n QMetaEnum m_metaEnumAction;\n QMetaEnum m_metaEnumKey;\n QFile* m_file;\n\n using MouseBindingMapping = std::map;\n using ContextNameMap = std::map;\n using ActionNameMap = std::map;\n\n ContextNameMap m_contextNameToIndex; \/\/\/< context string give index\n std::vector m_actionNameToIndex; \/\/\/< one element per context\n std::vector m_mappingAction; \/\/\/< one element per context\n};\n\n\/\/\/ KeyMappingManageable decorate, typical use as a CRTP :\n\/\/\/ class MyClass : public KeyMappingManageable { [...]\n\/\/\/ it defines a static class member m_keyMappingContext, readable with\n\/\/\/ getContext()\n\/\/\/ This context index must be registered by the class to the KeyMappingManager\n\/\/\/ with KeyMappingManager::getContext(\"MyClassContextName\"); after a\n\/\/\/ configuration file is loaded.\ntemplate \nclass KeyMappingManageable\n{\n public:\n static inline KeyMappingManager::Context getContext() { return m_keyMappingContext; }\n\n \/\/\/ KeyManageable class should implement static configureKeyMapping_impl to get their\n \/\/\/ keyMappingAction constants.\n static inline void configureKeyMapping() { T::configureKeyMapping_impl(); }\n\n protected:\n T& self() { return static_cast( *this ); }\n static inline void setContext( const KeyMappingManager::Context& c ) {\n m_keyMappingContext = c;\n }\n\n private:\n static KeyMappingManager::Context m_keyMappingContext;\n};\n\n\/\/\/ create one m_keyMappingContext by template type.\ntemplate \nKeyMappingManager::Context KeyMappingManageable::m_keyMappingContext;\n\n} \/\/ namespace Gui\n} \/\/ namespace Ra\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/native\/native_view_host_gtk.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"views\/controls\/native\/native_view_host.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/widget\/gtk_views_fixed.h\"\n#include \"views\/widget\/native_widget_gtk.h\"\n\nnamespace views {\n\nnamespace {\nstatic bool signal_id_initialized_ = false;\nstatic guint focus_in_event_signal_id_;\nstatic guint focus_out_event_signal_id_;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Utility functions to block focus signals while re-creating\n\/\/ Fixed widget.\n\nvoid InitSignalIds() {\n if (!signal_id_initialized_) {\n signal_id_initialized_ = true;\n focus_in_event_signal_id_ =\n g_signal_lookup(\"focus-in-event\", GTK_TYPE_WIDGET);\n focus_out_event_signal_id_ =\n g_signal_lookup(\"focus-out-event\", GTK_TYPE_WIDGET);\n }\n}\n\n\/\/ Blocks a |signal_id| on the given |widget| if any.\nvoid BlockSignal(GtkWidget* widget, guint signal_id) {\n gulong handler_id = g_signal_handler_find(G_OBJECT(widget),\n G_SIGNAL_MATCH_ID,\n signal_id,\n 0, NULL, NULL, NULL);\n if (handler_id) {\n g_signal_handler_block(G_OBJECT(widget), handler_id);\n }\n}\n\n\/\/ Unblocks a |signal_id| on the given |widget| if any.\nvoid UnblockSignal(GtkWidget* widget, guint signal_id) {\n gulong handler_id = g_signal_handler_find(G_OBJECT(widget),\n G_SIGNAL_MATCH_ID,\n signal_id,\n 0, NULL, NULL, NULL);\n if (handler_id) {\n g_signal_handler_unblock(G_OBJECT(widget), handler_id);\n }\n}\n\n\/\/ Blocks focus in\/out signals of the widget and its descendent\n\/\/ children.\n\/\/ Note: Due to the limiation of Gtk API, this only blocks the 1st\n\/\/ handler found and won't block the rest if there is more than one handlers.\n\/\/ See bug http:\/\/crbug.com\/33236.\nvoid BlockFocusSignals(GtkWidget* widget, gpointer data) {\n if (!widget)\n return;\n InitSignalIds();\n BlockSignal(widget, focus_in_event_signal_id_);\n BlockSignal(widget, focus_out_event_signal_id_);\n if (GTK_IS_CONTAINER(widget))\n gtk_container_foreach(GTK_CONTAINER(widget), BlockFocusSignals, data);\n}\n\n\/\/ Unlocks focus in\/out signals of the widget and its descendent children.\nvoid UnblockFocusSignals(GtkWidget* widget, gpointer data) {\n if (!widget)\n return;\n InitSignalIds();\n UnblockSignal(widget, focus_in_event_signal_id_);\n UnblockSignal(widget, focus_out_event_signal_id_);\n if (GTK_IS_CONTAINER(widget))\n gtk_container_foreach(GTK_CONTAINER(widget), UnblockFocusSignals, data);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, public:\n\nNativeViewHostGtk::NativeViewHostGtk(NativeViewHost* host)\n : host_(host),\n installed_clip_(false),\n destroy_signal_id_(0),\n focus_signal_id_(0),\n fixed_(NULL) {\n CreateFixed(false);\n}\n\nNativeViewHostGtk::~NativeViewHostGtk() {\n if (fixed_)\n gtk_widget_destroy(fixed_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, NativeViewHostWrapper implementation:\n\nvoid NativeViewHostGtk::NativeViewAttached() {\n DCHECK(host_->native_view());\n if (gtk_widget_get_parent(host_->native_view()))\n gtk_widget_reparent(host_->native_view(), fixed_);\n else\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n \/\/ Let the widget know that the native component has been painted.\n views::NativeWidgetGtk::RegisterChildExposeHandler(host_->native_view());\n\n if (!destroy_signal_id_) {\n destroy_signal_id_ = g_signal_connect(host_->native_view(),\n \"destroy\", G_CALLBACK(CallDestroy),\n this);\n }\n\n if (!focus_signal_id_) {\n focus_signal_id_ = g_signal_connect(host_->native_view(),\n \"focus-in-event\",\n G_CALLBACK(CallFocusIn), this);\n }\n\n \/\/ Always layout though.\n host_->Layout();\n\n \/\/ We own the native view as long as it's attached, so that we can safely\n \/\/ reparent it in multiple passes.\n gtk_widget_ref(host_->native_view());\n\n \/\/ TODO(port): figure out focus.\n}\n\nvoid NativeViewHostGtk::NativeViewDetaching(bool destroyed) {\n DCHECK(host_->native_view());\n\n g_signal_handler_disconnect(G_OBJECT(host_->native_view()),\n destroy_signal_id_);\n destroy_signal_id_ = 0;\n\n g_signal_handler_disconnect(G_OBJECT(host_->native_view()),\n focus_signal_id_);\n focus_signal_id_ = 0;\n\n installed_clip_ = false;\n\n if (fixed_ && !destroyed) {\n DCHECK_NE(static_cast(NULL),\n gtk_widget_get_parent(host_->native_view()));\n gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());\n DCHECK_EQ(\n 0U, g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));\n }\n\n g_object_unref(G_OBJECT(host_->native_view()));\n}\n\nvoid NativeViewHostGtk::AddedToWidget() {\n if (!fixed_)\n CreateFixed(false);\n if (gtk_widget_get_parent(fixed_))\n GetHostWidget()->ReparentChild(fixed_);\n else\n GetHostWidget()->AddChild(fixed_);\n\n if (!host_->native_view())\n return;\n\n if (gtk_widget_get_parent(host_->native_view()))\n gtk_widget_reparent(host_->native_view(), fixed_);\n else\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n if (host_->IsVisibleInRootView())\n gtk_widget_show(fixed_);\n else\n gtk_widget_hide(fixed_);\n host_->Layout();\n}\n\nvoid NativeViewHostGtk::RemovedFromWidget() {\n if (!host_->native_view())\n return;\n DestroyFixed();\n}\n\nvoid NativeViewHostGtk::InstallClip(int x, int y, int w, int h) {\n DCHECK(w > 0 && h > 0);\n installed_clip_bounds_.SetRect(x, y, w, h);\n if (!installed_clip_) {\n installed_clip_ = true;\n\n \/\/ We only re-create the fixed with a window when a cliprect is installed.\n \/\/ Because the presence of a X Window will prevent transparency from working\n \/\/ properly, we only want it to be active for the duration of a clip\n \/\/ (typically during animations and scrolling.)\n CreateFixed(true);\n }\n}\n\nbool NativeViewHostGtk::HasInstalledClip() {\n return installed_clip_;\n}\n\nvoid NativeViewHostGtk::UninstallClip() {\n installed_clip_ = false;\n \/\/ We now re-create the fixed without a X Window so transparency works again.\n CreateFixed(false);\n}\n\nvoid NativeViewHostGtk::ShowWidget(int x, int y, int w, int h) {\n \/\/ x and y are the desired position of host_ in NativeWidgetGtk coordinates.\n int fixed_x = x;\n int fixed_y = y;\n int fixed_w = w;\n int fixed_h = h;\n int child_x = 0;\n int child_y = 0;\n int child_w = w;\n int child_h = h;\n if (installed_clip_) {\n child_x = -installed_clip_bounds_.x();\n child_y = -installed_clip_bounds_.y();\n fixed_x += -child_x;\n fixed_y += -child_y;\n fixed_w = std::min(installed_clip_bounds_.width(), w);\n fixed_h = std::min(installed_clip_bounds_.height(), h);\n }\n\n \/\/ Don't call gtk_widget_size_allocate now, as we're possibly in the\n \/\/ middle of a re-size, and it kicks off another re-size, and you\n \/\/ get flashing. Instead, we'll set the desired size as properties\n \/\/ on the widget and queue the re-size.\n gtk_views_fixed_set_widget_size(host_->native_view(), child_w, child_h);\n gtk_fixed_move(GTK_FIXED(fixed_), host_->native_view(), child_x, child_y);\n\n \/\/ Size and place the fixed_.\n GetHostWidget()->PositionChild(fixed_, fixed_x, fixed_y, fixed_w, fixed_h);\n\n gtk_widget_show(fixed_);\n gtk_widget_show(host_->native_view());\n}\n\nvoid NativeViewHostGtk::HideWidget() {\n if (fixed_)\n gtk_widget_hide(fixed_);\n}\n\nvoid NativeViewHostGtk::SetFocus() {\n DCHECK(host_->native_view());\n gtk_widget_grab_focus(host_->native_view());\n}\n\ngfx::NativeViewAccessible NativeViewHostGtk::GetNativeViewAccessible() {\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, private:\n\nvoid NativeViewHostGtk::CreateFixed(bool needs_window) {\n GtkWidget* focused_widget = GetFocusedDescendant();\n\n bool focus_event_blocked = false;\n \/\/ We move focus around and do not want focus events to be emitted\n \/\/ during this process.\n if (fixed_) {\n BlockFocusSignals(GetHostWidget()->GetNativeView(), NULL);\n focus_event_blocked = true;\n }\n\n if (focused_widget) {\n \/\/ A descendant of our fixed has focus. When we destroy the fixed focus is\n \/\/ automatically moved. Temporarily move focus to our host widget, then\n \/\/ restore focus after we create the new fixed_. This way focus hasn't\n \/\/ really moved.\n gtk_widget_grab_focus(GetHostWidget()->GetNativeView());\n }\n\n DestroyFixed();\n\n fixed_ = gtk_views_fixed_new();\n gtk_widget_set_name(fixed_, \"views-native-view-host-fixed\");\n gtk_fixed_set_has_window(GTK_FIXED(fixed_), needs_window);\n \/\/ Defeat refcounting. We need to own the fixed.\n gtk_widget_ref(fixed_);\n\n NativeWidgetGtk* widget_gtk = GetHostWidget();\n if (widget_gtk)\n widget_gtk->AddChild(fixed_);\n\n if (host_->native_view())\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n if (widget_gtk && host_->native_view() && focused_widget) {\n gtk_widget_grab_focus(focused_widget);\n }\n if (focus_event_blocked) {\n \/\/ Unblocking a signal handler that is not blocked fails.\n \/\/ Unblock only when it's unblocked.\n UnblockFocusSignals(GetHostWidget()->GetNativeView(), NULL);\n }\n}\n\nvoid NativeViewHostGtk::DestroyFixed() {\n if (!fixed_)\n return;\n\n gtk_widget_hide(fixed_);\n GetHostWidget()->RemoveChild(fixed_);\n\n if (host_->native_view()) {\n \/\/ We can safely remove the widget from its container since we own the\n \/\/ widget from the moment it is attached.\n gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());\n }\n \/\/ fixed_ should not have any children this point.\n DCHECK_EQ(0U,\n g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));\n gtk_widget_destroy(fixed_);\n fixed_ = NULL;\n}\n\nNativeWidgetGtk* NativeViewHostGtk::GetHostWidget() const {\n return static_cast(host_->GetWidget()->native_widget());\n}\n\nGtkWidget* NativeViewHostGtk::GetFocusedDescendant() {\n if (!fixed_)\n return NULL;\n NativeWidgetGtk* host = GetHostWidget();\n if (!host)\n return NULL;\n GtkWidget* top_level = gtk_widget_get_toplevel(host->GetNativeView());\n if (!top_level || !GTK_IS_WINDOW(top_level))\n return NULL;\n GtkWidget* focused = gtk_window_get_focus(GTK_WINDOW(top_level));\n if (!focused)\n return NULL;\n return (focused == fixed_ || gtk_widget_is_ancestor(focused, fixed_)) ?\n focused : NULL;\n}\n\n\/\/ static\nvoid NativeViewHostGtk::CallDestroy(GtkObject* object,\n NativeViewHostGtk* host) {\n host->host_->NativeViewDestroyed();\n}\n\n\/\/ static\ngboolean NativeViewHostGtk::CallFocusIn(GtkWidget* widget,\n GdkEventFocus* event,\n NativeViewHostGtk* host) {\n FocusManager* focus_manager =\n FocusManager::GetFocusManagerForNativeView(widget);\n if (!focus_manager) {\n \/\/ TODO(jcampan): http:\/\/crbug.com\/21378 Reenable this NOTREACHED() when the\n \/\/ options page is only based on views.\n \/\/ NOTREACHED();\n NOTIMPLEMENTED();\n return false;\n }\n focus_manager->SetFocusedView(host->host_->focus_view());\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostWrapper, public:\n\n\/\/ static\nNativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper(\n NativeViewHost* host) {\n return new NativeViewHostGtk(host);\n}\n\n} \/\/ namespace views\nUse NativeViewHostViews when using pure-views instead of NativeViewHostGtk.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/native\/native_view_host_gtk.h\"\n\n#include \n#include \n\n#include \"base\/logging.h\"\n#include \"views\/controls\/native\/native_view_host.h\"\n#include \"views\/controls\/native\/native_view_host_views.h\"\n#include \"views\/focus\/focus_manager.h\"\n#include \"views\/widget\/gtk_views_fixed.h\"\n#include \"views\/widget\/native_widget_gtk.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace views {\n\nnamespace {\nstatic bool signal_id_initialized_ = false;\nstatic guint focus_in_event_signal_id_;\nstatic guint focus_out_event_signal_id_;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Utility functions to block focus signals while re-creating\n\/\/ Fixed widget.\n\nvoid InitSignalIds() {\n if (!signal_id_initialized_) {\n signal_id_initialized_ = true;\n focus_in_event_signal_id_ =\n g_signal_lookup(\"focus-in-event\", GTK_TYPE_WIDGET);\n focus_out_event_signal_id_ =\n g_signal_lookup(\"focus-out-event\", GTK_TYPE_WIDGET);\n }\n}\n\n\/\/ Blocks a |signal_id| on the given |widget| if any.\nvoid BlockSignal(GtkWidget* widget, guint signal_id) {\n gulong handler_id = g_signal_handler_find(G_OBJECT(widget),\n G_SIGNAL_MATCH_ID,\n signal_id,\n 0, NULL, NULL, NULL);\n if (handler_id) {\n g_signal_handler_block(G_OBJECT(widget), handler_id);\n }\n}\n\n\/\/ Unblocks a |signal_id| on the given |widget| if any.\nvoid UnblockSignal(GtkWidget* widget, guint signal_id) {\n gulong handler_id = g_signal_handler_find(G_OBJECT(widget),\n G_SIGNAL_MATCH_ID,\n signal_id,\n 0, NULL, NULL, NULL);\n if (handler_id) {\n g_signal_handler_unblock(G_OBJECT(widget), handler_id);\n }\n}\n\n\/\/ Blocks focus in\/out signals of the widget and its descendent\n\/\/ children.\n\/\/ Note: Due to the limiation of Gtk API, this only blocks the 1st\n\/\/ handler found and won't block the rest if there is more than one handlers.\n\/\/ See bug http:\/\/crbug.com\/33236.\nvoid BlockFocusSignals(GtkWidget* widget, gpointer data) {\n if (!widget)\n return;\n InitSignalIds();\n BlockSignal(widget, focus_in_event_signal_id_);\n BlockSignal(widget, focus_out_event_signal_id_);\n if (GTK_IS_CONTAINER(widget))\n gtk_container_foreach(GTK_CONTAINER(widget), BlockFocusSignals, data);\n}\n\n\/\/ Unlocks focus in\/out signals of the widget and its descendent children.\nvoid UnblockFocusSignals(GtkWidget* widget, gpointer data) {\n if (!widget)\n return;\n InitSignalIds();\n UnblockSignal(widget, focus_in_event_signal_id_);\n UnblockSignal(widget, focus_out_event_signal_id_);\n if (GTK_IS_CONTAINER(widget))\n gtk_container_foreach(GTK_CONTAINER(widget), UnblockFocusSignals, data);\n}\n\n} \/\/ namespace\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, public:\n\nNativeViewHostGtk::NativeViewHostGtk(NativeViewHost* host)\n : host_(host),\n installed_clip_(false),\n destroy_signal_id_(0),\n focus_signal_id_(0),\n fixed_(NULL) {\n CreateFixed(false);\n}\n\nNativeViewHostGtk::~NativeViewHostGtk() {\n if (fixed_)\n gtk_widget_destroy(fixed_);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, NativeViewHostWrapper implementation:\n\nvoid NativeViewHostGtk::NativeViewAttached() {\n DCHECK(host_->native_view());\n if (gtk_widget_get_parent(host_->native_view()))\n gtk_widget_reparent(host_->native_view(), fixed_);\n else\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n \/\/ Let the widget know that the native component has been painted.\n views::NativeWidgetGtk::RegisterChildExposeHandler(host_->native_view());\n\n if (!destroy_signal_id_) {\n destroy_signal_id_ = g_signal_connect(host_->native_view(),\n \"destroy\", G_CALLBACK(CallDestroy),\n this);\n }\n\n if (!focus_signal_id_) {\n focus_signal_id_ = g_signal_connect(host_->native_view(),\n \"focus-in-event\",\n G_CALLBACK(CallFocusIn), this);\n }\n\n \/\/ Always layout though.\n host_->Layout();\n\n \/\/ We own the native view as long as it's attached, so that we can safely\n \/\/ reparent it in multiple passes.\n gtk_widget_ref(host_->native_view());\n\n \/\/ TODO(port): figure out focus.\n}\n\nvoid NativeViewHostGtk::NativeViewDetaching(bool destroyed) {\n DCHECK(host_->native_view());\n\n g_signal_handler_disconnect(G_OBJECT(host_->native_view()),\n destroy_signal_id_);\n destroy_signal_id_ = 0;\n\n g_signal_handler_disconnect(G_OBJECT(host_->native_view()),\n focus_signal_id_);\n focus_signal_id_ = 0;\n\n installed_clip_ = false;\n\n if (fixed_ && !destroyed) {\n DCHECK_NE(static_cast(NULL),\n gtk_widget_get_parent(host_->native_view()));\n gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());\n DCHECK_EQ(\n 0U, g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));\n }\n\n g_object_unref(G_OBJECT(host_->native_view()));\n}\n\nvoid NativeViewHostGtk::AddedToWidget() {\n if (!fixed_)\n CreateFixed(false);\n if (gtk_widget_get_parent(fixed_))\n GetHostWidget()->ReparentChild(fixed_);\n else\n GetHostWidget()->AddChild(fixed_);\n\n if (!host_->native_view())\n return;\n\n if (gtk_widget_get_parent(host_->native_view()))\n gtk_widget_reparent(host_->native_view(), fixed_);\n else\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n if (host_->IsVisibleInRootView())\n gtk_widget_show(fixed_);\n else\n gtk_widget_hide(fixed_);\n host_->Layout();\n}\n\nvoid NativeViewHostGtk::RemovedFromWidget() {\n if (!host_->native_view())\n return;\n DestroyFixed();\n}\n\nvoid NativeViewHostGtk::InstallClip(int x, int y, int w, int h) {\n DCHECK(w > 0 && h > 0);\n installed_clip_bounds_.SetRect(x, y, w, h);\n if (!installed_clip_) {\n installed_clip_ = true;\n\n \/\/ We only re-create the fixed with a window when a cliprect is installed.\n \/\/ Because the presence of a X Window will prevent transparency from working\n \/\/ properly, we only want it to be active for the duration of a clip\n \/\/ (typically during animations and scrolling.)\n CreateFixed(true);\n }\n}\n\nbool NativeViewHostGtk::HasInstalledClip() {\n return installed_clip_;\n}\n\nvoid NativeViewHostGtk::UninstallClip() {\n installed_clip_ = false;\n \/\/ We now re-create the fixed without a X Window so transparency works again.\n CreateFixed(false);\n}\n\nvoid NativeViewHostGtk::ShowWidget(int x, int y, int w, int h) {\n \/\/ x and y are the desired position of host_ in NativeWidgetGtk coordinates.\n int fixed_x = x;\n int fixed_y = y;\n int fixed_w = w;\n int fixed_h = h;\n int child_x = 0;\n int child_y = 0;\n int child_w = w;\n int child_h = h;\n if (installed_clip_) {\n child_x = -installed_clip_bounds_.x();\n child_y = -installed_clip_bounds_.y();\n fixed_x += -child_x;\n fixed_y += -child_y;\n fixed_w = std::min(installed_clip_bounds_.width(), w);\n fixed_h = std::min(installed_clip_bounds_.height(), h);\n }\n\n \/\/ Don't call gtk_widget_size_allocate now, as we're possibly in the\n \/\/ middle of a re-size, and it kicks off another re-size, and you\n \/\/ get flashing. Instead, we'll set the desired size as properties\n \/\/ on the widget and queue the re-size.\n gtk_views_fixed_set_widget_size(host_->native_view(), child_w, child_h);\n gtk_fixed_move(GTK_FIXED(fixed_), host_->native_view(), child_x, child_y);\n\n \/\/ Size and place the fixed_.\n GetHostWidget()->PositionChild(fixed_, fixed_x, fixed_y, fixed_w, fixed_h);\n\n gtk_widget_show(fixed_);\n gtk_widget_show(host_->native_view());\n}\n\nvoid NativeViewHostGtk::HideWidget() {\n if (fixed_)\n gtk_widget_hide(fixed_);\n}\n\nvoid NativeViewHostGtk::SetFocus() {\n DCHECK(host_->native_view());\n gtk_widget_grab_focus(host_->native_view());\n}\n\ngfx::NativeViewAccessible NativeViewHostGtk::GetNativeViewAccessible() {\n return NULL;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostGtk, private:\n\nvoid NativeViewHostGtk::CreateFixed(bool needs_window) {\n GtkWidget* focused_widget = GetFocusedDescendant();\n\n bool focus_event_blocked = false;\n \/\/ We move focus around and do not want focus events to be emitted\n \/\/ during this process.\n if (fixed_) {\n BlockFocusSignals(GetHostWidget()->GetNativeView(), NULL);\n focus_event_blocked = true;\n }\n\n if (focused_widget) {\n \/\/ A descendant of our fixed has focus. When we destroy the fixed focus is\n \/\/ automatically moved. Temporarily move focus to our host widget, then\n \/\/ restore focus after we create the new fixed_. This way focus hasn't\n \/\/ really moved.\n gtk_widget_grab_focus(GetHostWidget()->GetNativeView());\n }\n\n DestroyFixed();\n\n fixed_ = gtk_views_fixed_new();\n gtk_widget_set_name(fixed_, \"views-native-view-host-fixed\");\n gtk_fixed_set_has_window(GTK_FIXED(fixed_), needs_window);\n \/\/ Defeat refcounting. We need to own the fixed.\n gtk_widget_ref(fixed_);\n\n NativeWidgetGtk* widget_gtk = GetHostWidget();\n if (widget_gtk)\n widget_gtk->AddChild(fixed_);\n\n if (host_->native_view())\n gtk_container_add(GTK_CONTAINER(fixed_), host_->native_view());\n\n if (widget_gtk && host_->native_view() && focused_widget) {\n gtk_widget_grab_focus(focused_widget);\n }\n if (focus_event_blocked) {\n \/\/ Unblocking a signal handler that is not blocked fails.\n \/\/ Unblock only when it's unblocked.\n UnblockFocusSignals(GetHostWidget()->GetNativeView(), NULL);\n }\n}\n\nvoid NativeViewHostGtk::DestroyFixed() {\n if (!fixed_)\n return;\n\n gtk_widget_hide(fixed_);\n GetHostWidget()->RemoveChild(fixed_);\n\n if (host_->native_view()) {\n \/\/ We can safely remove the widget from its container since we own the\n \/\/ widget from the moment it is attached.\n gtk_container_remove(GTK_CONTAINER(fixed_), host_->native_view());\n }\n \/\/ fixed_ should not have any children this point.\n DCHECK_EQ(0U,\n g_list_length(gtk_container_get_children(GTK_CONTAINER(fixed_))));\n gtk_widget_destroy(fixed_);\n fixed_ = NULL;\n}\n\nNativeWidgetGtk* NativeViewHostGtk::GetHostWidget() const {\n return static_cast(host_->GetWidget()->native_widget());\n}\n\nGtkWidget* NativeViewHostGtk::GetFocusedDescendant() {\n if (!fixed_)\n return NULL;\n NativeWidgetGtk* host = GetHostWidget();\n if (!host)\n return NULL;\n GtkWidget* top_level = gtk_widget_get_toplevel(host->GetNativeView());\n if (!top_level || !GTK_IS_WINDOW(top_level))\n return NULL;\n GtkWidget* focused = gtk_window_get_focus(GTK_WINDOW(top_level));\n if (!focused)\n return NULL;\n return (focused == fixed_ || gtk_widget_is_ancestor(focused, fixed_)) ?\n focused : NULL;\n}\n\n\/\/ static\nvoid NativeViewHostGtk::CallDestroy(GtkObject* object,\n NativeViewHostGtk* host) {\n host->host_->NativeViewDestroyed();\n}\n\n\/\/ static\ngboolean NativeViewHostGtk::CallFocusIn(GtkWidget* widget,\n GdkEventFocus* event,\n NativeViewHostGtk* host) {\n FocusManager* focus_manager =\n FocusManager::GetFocusManagerForNativeView(widget);\n if (!focus_manager) {\n \/\/ TODO(jcampan): http:\/\/crbug.com\/21378 Reenable this NOTREACHED() when the\n \/\/ options page is only based on views.\n \/\/ NOTREACHED();\n NOTIMPLEMENTED();\n return false;\n }\n focus_manager->SetFocusedView(host->host_->focus_view());\n return false;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ NativeViewHostWrapper, public:\n\n\/\/ static\nNativeViewHostWrapper* NativeViewHostWrapper::CreateWrapper(\n NativeViewHost* host) {\n if (Widget::IsPureViews())\n return new NativeViewHostViews(host);\n else\n return new NativeViewHostGtk(host);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"\/\/ Copyright WRLD Ltd (2018-), All Rights Reserved\n\n#include \"SearchWidgetController.h\"\n#include \"SearchResultSectionItemSelectedMessage.h\"\n#include \"SearchServicesResult.h\"\n#include \"IMenuSectionViewModel.h\"\n#include \"IMenuView.h\"\n#include \"IMenuOption.h\"\n#include \"MenuItemModel.h\"\n#include \"IMenuModel.h\"\n\nnamespace ExampleApp\n{\n namespace SearchMenu\n {\n namespace View\n {\n SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,\n SearchServices& searchServices,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Modality::View::IModalBackgroundView& modalBackgroundView,\n Menu::View::IMenuViewModel& viewModel,\n ExampleAppMessaging::TMessageBus& messageBus)\n : m_view(view)\n\t\t\t, m_modalBackgroundView(modalBackgroundView)\n , m_viewModel(viewModel)\n , m_messageBus(messageBus)\n , m_searchServices(searchServices)\n , m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)\n , m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)\n , m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)\n , m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)\n , m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchDeepLinkRequestedMessage)\n , m_menuContentsChanged(true)\n\t\t\t, m_inInteriorMode(false)\n , m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)\n , m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)\n , m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)\n , m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)\n , m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)\n , m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)\n\t\t\t, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)\n , m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)\n , m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)\n\t\t\t, m_tagCollection(m_messageBus)\n , m_shouldSelectFirstResult(false)\n {\n m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);\n\t\t\t\tm_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);\n m_view.InsertOnItemSelected(m_onItemSelectedCallback);\n m_view.InsertOnViewClosed(m_onViewClosedCallback);\n m_view.InsertOnViewOpened(m_onViewOpenedCallback);\n\n m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);\n m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);\n\n\t\t\t\tm_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);\n\n m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);\n \n m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);\n m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);\n m_messageBus.SubscribeUi(m_onAppModeChanged);\n\n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast(i)));\n\t\t\t\t\tSetGroupStart(section);\n Menu::View::IMenuModel& menuModel = section.GetModel();\n menuModel.InsertItemAddedCallback(m_onItemAddedCallback);\n menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);\n }\n }\n\n SearchWidgetController::~SearchWidgetController()\n {\n\t\t\t\tfor(int i = static_cast(m_viewModel.SectionsCount()); --i >= 0;)\n\t\t\t\t{\n\t\t\t\t\tMenu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n\t\t\t\t\tMenu::View::IMenuModel& menuModel = section.GetModel();\n\t\t\t\t\tmenuModel.RemoveItemAddedCallback(m_onItemAddedCallback);\n\t\t\t\t\tmenuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);\n\t\t\t\t}\n\n m_messageBus.UnsubscribeUi(m_onAppModeChanged);\n m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);\n m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);\n m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);\n\n\t\t\t\tm_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);\n\n m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);\n\n m_view.RemoveOnViewOpened(m_onViewOpenedCallback);\n m_view.RemoveOnViewClosed(m_onViewClosedCallback);\n m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);\n m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);\n m_view.RemoveOnItemSelected(m_onItemSelectedCallback);\n\t\t\t}\n\n\t\t\tvoid SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)\n\t\t\t{\n\t\t\t\tif (section.Name() == \"Find\" ||\n\t\t\t\t\tsection.Name() == \"Drop Pin\" ||\n\t\t\t\t\tsection.Name() == \"Weather\")\n\t\t\t\t{\n\t\t\t\t\tsection.SetGroupStart(true);\n\t\t\t\t}\n }\n\n void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {\n m_menuContentsChanged = true;\n }\n\n void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){\n m_menuContentsChanged = true;\n }\n\n void SearchWidgetController::OnSearchResultsCleared()\n {\n m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());\n }\n\n void SearchWidgetController::OnSearchResultSelected(int& index)\n {\n const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_searchServices.GetSdkSearchResultByIndex(index);\n\n m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(\n sdkSearchResult.GetLocation().ToECEF(),\n sdkSearchResult.IsInterior(),\n sdkSearchResult.GetBuildingId(),\n sdkSearchResult.GetFloor(),\n m_searchServices.GetResultOriginalIndexFromCurrentIndex(index),\n sdkSearchResult.GetIdentifier()));\n }\n \n void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)\n {\n if (m_shouldSelectFirstResult && message.GetResults().size() > 0){\n int val = 0;\n OnSearchResultSelected(val);\n m_shouldSelectFirstResult = false;\n }\n }\n \n void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)\n {\n const Search::SdkModel::SearchQuery &query = message.Query();\n\n\t\t\t\tstd::string visibleText = query.Query();\n\t\t\t\tstd::string tagText = \"\";\n\n\t\t\t\tif (query.IsTag())\n\t\t\t\t{\n\t\t\t\t\ttagText = visibleText;\n\n\t\t\t\t\tconst TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);\n\n\t\t\t\t\tvisibleText = tagInfo.VisibleText();\n\t\t\t\t}\n\n m_view.PerformSearch(visibleText,\n QueryContext(false,\n query.IsTag(),\n tagText,\n query.ShouldTryInteriorSearch(),\n message.Location(),\n message.Radius()));\n }\n \n void SearchWidgetController::OnSearchDeepLinkRequestedMessage(const Search::DeepLinkedSearchQueryRequestMessage& message)\n {\n auto query = message.Query();\n auto clearPreviousResults = false;\n std::string visibleText = query.Query();\n std::string tagText = \"\";\n\n if (query.IsTag())\n {\n tagText = visibleText;\n \n if (m_tagCollection.HasText(tagText))\n {\n const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);\n \n visibleText = tagInfo.VisibleText();\n }\n }\n\n auto queryContext = QueryContext(clearPreviousResults,\n query.IsTag(),\n tagText,\n query.ShouldTryInteriorSearch(),\n query.Location(),\n query.Radius());\n m_shouldSelectFirstResult = true;\n m_view.PerformSearch(visibleText, queryContext);\n }\n \n void SearchWidgetController::UpdateUiThread(float dt)\n {\n\t\t\t\tRefreshPresentation();\n }\n\n void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)\n {\n\t\t\t\tm_menuContentsChanged = true;\n\t\t\t\tm_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;\n\n RefreshPresentation();\n }\n\n void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)\n {\n Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);\n\n\t\t\t\tif (m_tagCollection.HasTag(menuText))\n\t\t\t\t{\n\t\t\t\t\tm_view.ClearSearchResults();\n\n\t\t\t\t\tTagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);\n\n\t\t\t\t\tm_view.PerformSearch(menuText,\n\t\t\t\t\t\t\t\t\t\t QueryContext(true, true, tagInfo.Tag(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t tagInfo.ShouldTryInterior()));\n\t\t\t\t}\n else if(!section.IsExpandable() || section.GetTotalItemCount()>0)\n {\n section.GetItemAtIndex(itemIndex).MenuOption().Select();\n }\n }\n\n void SearchWidgetController::RefreshPresentation()\n {\n if (!m_menuContentsChanged)\n {\n return;\n }\n m_menuContentsChanged = false;\n\n const size_t numSections = m_viewModel.SectionsCount();\n Menu::View::TSections sections;\n sections.reserve(numSections);\n\n for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)\n {\n Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast(groupIndex));\n\n\t\t\t\t\tif (section.Name() != \"Discover\" || !m_inInteriorMode)\n\t\t\t\t\t{\n\t\t\t\t\t\tsections.push_back(§ion);\n\t\t\t\t\t}\n }\n\n m_view.UpdateMenuSectionViews(sections);\n }\n\n void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)\n {\n if(m_viewModel.IsAddedToScreen())\n {\n if (m_viewModel.IsFullyClosed() || m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n else\n {\n m_view.SetFullyOffScreen();\n }\n }\n\n void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)\n {\n if (m_viewModel.IsFullyOnScreen())\n {\n m_view.SetFullyOnScreen();\n }\n else if (m_viewModel.IsFullyOffScreen())\n {\n m_view.SetFullyOffScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n void SearchWidgetController::OnViewOpened()\n {\n if(!m_viewModel.IsFullyOpen())\n {\n m_viewModel.Open();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void SearchWidgetController::OnViewClosed()\n {\n\n if(!m_viewModel.IsFullyClosed())\n {\n m_viewModel.Close(false);\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n\t\t\tvoid SearchWidgetController::OnModalBackgroundTouch()\n\t\t\t{\n\t\t\t\t\/\/ the modal background goes away after the first touch, so no need to throttle\n\n\t\t\t\tm_view.CloseMenu();\n\t\t\t}\n }\n }\n}\nFix to MPLY-9710: crash on startup queries\/\/ Copyright WRLD Ltd (2018-), All Rights Reserved\n\n#include \"SearchWidgetController.h\"\n#include \"SearchResultSectionItemSelectedMessage.h\"\n#include \"SearchServicesResult.h\"\n#include \"IMenuSectionViewModel.h\"\n#include \"IMenuView.h\"\n#include \"IMenuOption.h\"\n#include \"MenuItemModel.h\"\n#include \"IMenuModel.h\"\n\nnamespace ExampleApp\n{\n namespace SearchMenu\n {\n namespace View\n {\n SearchWidgetController::SearchWidgetController(ISearchWidgetView& view,\n SearchServices& searchServices,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t Modality::View::IModalBackgroundView& modalBackgroundView,\n Menu::View::IMenuViewModel& viewModel,\n ExampleAppMessaging::TMessageBus& messageBus)\n : m_view(view)\n\t\t\t, m_modalBackgroundView(modalBackgroundView)\n , m_viewModel(viewModel)\n , m_messageBus(messageBus)\n , m_searchServices(searchServices)\n , m_onSearchResultsClearedCallback(this, &SearchWidgetController::OnSearchResultsCleared)\n , m_onSearchResultSelectedCallback(this, &SearchWidgetController::OnSearchResultSelected)\n , m_onSearchQueryRefreshedHandler(this, &SearchWidgetController::OnSearchQueryRefreshedMessage)\n , m_onSearchQueryResultsLoadedHandler(this, &SearchWidgetController::OnSearchResultsLoaded)\n , m_deepLinkRequestedHandler(this, &SearchWidgetController::OnSearchDeepLinkRequestedMessage)\n , m_menuContentsChanged(true)\n\t\t\t, m_inInteriorMode(false)\n , m_onAppModeChanged(this, &SearchWidgetController::OnAppModeChanged)\n , m_onItemSelectedCallback(this, &SearchWidgetController::OnItemSelected)\n , m_onItemAddedCallback(this, &SearchWidgetController::OnItemAdded)\n , m_onItemRemovedCallback(this, &SearchWidgetController::OnItemRemoved)\n , m_onScreenStateChanged(this, &SearchWidgetController::OnScreenControlStateChanged)\n , m_onOpenableStateChanged(this, &SearchWidgetController::OnOpenableStateChanged)\n\t\t\t, m_onModalBackgroundTouchCallback(this, &SearchWidgetController::OnModalBackgroundTouch)\n , m_onViewOpenedCallback(this, &SearchWidgetController::OnViewOpened)\n , m_onViewClosedCallback(this, &SearchWidgetController::OnViewClosed)\n\t\t\t, m_tagCollection(m_messageBus)\n , m_shouldSelectFirstResult(false)\n {\n m_view.InsertSearchClearedCallback(m_onSearchResultsClearedCallback);\n\t\t\t\tm_view.InsertResultSelectedCallback(m_onSearchResultSelectedCallback);\n m_view.InsertOnItemSelected(m_onItemSelectedCallback);\n m_view.InsertOnViewClosed(m_onViewClosedCallback);\n m_view.InsertOnViewOpened(m_onViewOpenedCallback);\n\n m_viewModel.InsertOpenStateChangedCallback(m_onOpenableStateChanged);\n m_viewModel.InsertOnScreenStateChangedCallback(m_onScreenStateChanged);\n\n\t\t\t\tm_modalBackgroundView.InsertTouchCallback(m_onModalBackgroundTouchCallback);\n\n m_messageBus.SubscribeUi(m_onSearchQueryRefreshedHandler);\n \n m_messageBus.SubscribeUi(m_onSearchQueryResultsLoadedHandler);\n m_messageBus.SubscribeUi(m_deepLinkRequestedHandler);\n m_messageBus.SubscribeUi(m_onAppModeChanged);\n\n for(size_t i = 0; i < m_viewModel.SectionsCount(); ++ i)\n {\n Menu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(static_cast(i)));\n\t\t\t\t\tSetGroupStart(section);\n Menu::View::IMenuModel& menuModel = section.GetModel();\n menuModel.InsertItemAddedCallback(m_onItemAddedCallback);\n menuModel.InsertItemRemovedCallback(m_onItemRemovedCallback);\n }\n }\n\n SearchWidgetController::~SearchWidgetController()\n {\n\t\t\t\tfor(int i = static_cast(m_viewModel.SectionsCount()); --i >= 0;)\n\t\t\t\t{\n\t\t\t\t\tMenu::View::IMenuSectionViewModel& section(m_viewModel.GetMenuSection(i));\n\t\t\t\t\tMenu::View::IMenuModel& menuModel = section.GetModel();\n\t\t\t\t\tmenuModel.RemoveItemAddedCallback(m_onItemAddedCallback);\n\t\t\t\t\tmenuModel.RemoveItemRemovedCallback(m_onItemRemovedCallback);\n\t\t\t\t}\n\n m_messageBus.UnsubscribeUi(m_onAppModeChanged);\n m_messageBus.UnsubscribeUi(m_onSearchQueryRefreshedHandler);\n m_messageBus.UnsubscribeUi(m_onSearchQueryResultsLoadedHandler);\n m_messageBus.UnsubscribeUi(m_deepLinkRequestedHandler);\n\n\t\t\t\tm_modalBackgroundView.RemoveTouchCallback(m_onModalBackgroundTouchCallback);\n\n m_viewModel.RemoveOnScreenStateChangedCallback(m_onScreenStateChanged);\n m_viewModel.RemoveOpenStateChangedCallback(m_onOpenableStateChanged);\n\n m_view.RemoveOnViewOpened(m_onViewOpenedCallback);\n m_view.RemoveOnViewClosed(m_onViewClosedCallback);\n m_view.RemoveResultSelectedCallback(m_onSearchResultSelectedCallback);\n m_view.RemoveSearchClearedCallback(m_onSearchResultsClearedCallback);\n m_view.RemoveOnItemSelected(m_onItemSelectedCallback);\n\t\t\t}\n\n\t\t\tvoid SearchWidgetController::SetGroupStart(Menu::View::IMenuSectionViewModel& section)\n\t\t\t{\n\t\t\t\tif (section.Name() == \"Find\" ||\n\t\t\t\t\tsection.Name() == \"Drop Pin\" ||\n\t\t\t\t\tsection.Name() == \"Weather\")\n\t\t\t\t{\n\t\t\t\t\tsection.SetGroupStart(true);\n\t\t\t\t}\n }\n\n void SearchWidgetController::OnItemAdded(Menu::View::MenuItemModel& item) {\n m_menuContentsChanged = true;\n }\n\n void SearchWidgetController::OnItemRemoved(Menu::View::MenuItemModel& item){\n m_menuContentsChanged = true;\n }\n\n void SearchWidgetController::OnSearchResultsCleared()\n {\n m_messageBus.Publish(SearchResultSection::SearchResultViewClearedMessage());\n }\n\n void SearchWidgetController::OnSearchResultSelected(int& index)\n {\n const SearchServicesResult::TSdkSearchResult& sdkSearchResult = m_searchServices.GetSdkSearchResultByIndex(index);\n\n m_messageBus.Publish(SearchResultSection::SearchResultSectionItemSelectedMessage(\n sdkSearchResult.GetLocation().ToECEF(),\n sdkSearchResult.IsInterior(),\n sdkSearchResult.GetBuildingId(),\n sdkSearchResult.GetFloor(),\n m_searchServices.GetResultOriginalIndexFromCurrentIndex(index),\n sdkSearchResult.GetIdentifier()));\n }\n \n void SearchWidgetController::OnSearchResultsLoaded(const Search::SearchQueryResponseReceivedMessage& message)\n {\n if (m_shouldSelectFirstResult && message.GetResults().size() > 0){\n int val = 0;\n OnSearchResultSelected(val);\n m_shouldSelectFirstResult = false;\n }\n }\n \n void SearchWidgetController::OnSearchQueryRefreshedMessage(const Search::SearchQueryRefreshedMessage& message)\n {\n const Search::SdkModel::SearchQuery &query = message.Query();\n\n\t\t\t\tstd::string visibleText = query.Query();\n\t\t\t\tstd::string tagText = \"\";\n\n\t\t\t\tif (query.IsTag())\n\t\t\t\t{\n\t\t\t\t\ttagText = visibleText;\n\n\t\t\t\t\tconst TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);\n\n\t\t\t\t\tvisibleText = tagInfo.VisibleText();\n\t\t\t\t}\n\n m_view.PerformSearch(visibleText,\n QueryContext(false,\n query.IsTag(),\n tagText,\n query.ShouldTryInteriorSearch(),\n message.Location(),\n message.Radius()));\n }\n \n void SearchWidgetController::OnSearchDeepLinkRequestedMessage(const Search::DeepLinkedSearchQueryRequestMessage& message)\n {\n \/\/ needed to avoid a reentrant call on the reactor logic on startup queries \/ deeplinks\n m_view.CloseMenu();\n\n auto query = message.Query();\n auto clearPreviousResults = false;\n std::string visibleText = query.Query();\n std::string tagText = \"\";\n\n if (query.IsTag())\n {\n tagText = visibleText;\n \n if (m_tagCollection.HasText(tagText))\n {\n const TagCollection::TagInfo& tagInfo = m_tagCollection.GetInfoByTag(tagText);\n \n visibleText = tagInfo.VisibleText();\n }\n }\n\n auto queryContext = QueryContext(clearPreviousResults,\n query.IsTag(),\n tagText,\n query.ShouldTryInteriorSearch(),\n query.Location(),\n query.Radius());\n m_shouldSelectFirstResult = true;\n m_view.PerformSearch(visibleText, queryContext);\n }\n \n void SearchWidgetController::UpdateUiThread(float dt)\n {\n\t\t\t\tRefreshPresentation();\n }\n\n void SearchWidgetController::OnAppModeChanged(const AppModes::AppModeChangedMessage &message)\n {\n\t\t\t\tm_menuContentsChanged = true;\n\t\t\t\tm_inInteriorMode = message.GetAppMode() == AppModes::SdkModel::AppMode::InteriorMode;\n\n RefreshPresentation();\n }\n\n void SearchWidgetController::OnItemSelected(const std::string& menuText, int& sectionIndex, int& itemIndex)\n {\n Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(sectionIndex);\n\n\t\t\t\tif (m_tagCollection.HasTag(menuText))\n\t\t\t\t{\n\t\t\t\t\tm_view.ClearSearchResults();\n\n\t\t\t\t\tTagCollection::TagInfo tagInfo = m_tagCollection.GetInfoByText(menuText);\n\n\t\t\t\t\tm_view.PerformSearch(menuText,\n\t\t\t\t\t\t\t\t\t\t QueryContext(true, true, tagInfo.Tag(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t tagInfo.ShouldTryInterior()));\n\t\t\t\t}\n else if(!section.IsExpandable() || section.GetTotalItemCount()>0)\n {\n section.GetItemAtIndex(itemIndex).MenuOption().Select();\n }\n }\n\n void SearchWidgetController::RefreshPresentation()\n {\n if (!m_menuContentsChanged)\n {\n return;\n }\n m_menuContentsChanged = false;\n\n const size_t numSections = m_viewModel.SectionsCount();\n Menu::View::TSections sections;\n sections.reserve(numSections);\n\n for(size_t groupIndex = 0; groupIndex < numSections; groupIndex++)\n {\n Menu::View::IMenuSectionViewModel& section = m_viewModel.GetMenuSection(static_cast(groupIndex));\n\n\t\t\t\t\tif (section.Name() != \"Discover\" || !m_inInteriorMode)\n\t\t\t\t\t{\n\t\t\t\t\t\tsections.push_back(§ion);\n\t\t\t\t\t}\n }\n\n m_view.UpdateMenuSectionViews(sections);\n }\n\n void SearchWidgetController::OnOpenableStateChanged(OpenableControl::View::IOpenableControlViewModel& viewModel, float& state)\n {\n if(m_viewModel.IsAddedToScreen())\n {\n if (m_viewModel.IsFullyClosed() || m_viewModel.IsFullyOpen())\n {\n m_view.SetFullyOnScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n else\n {\n m_view.SetFullyOffScreen();\n }\n }\n\n void SearchWidgetController::OnScreenControlStateChanged(ScreenControl::View::IScreenControlViewModel& viewModel, float& state)\n {\n if (m_viewModel.IsFullyOnScreen())\n {\n m_view.SetFullyOnScreen();\n }\n else if (m_viewModel.IsFullyOffScreen())\n {\n m_view.SetFullyOffScreen();\n }\n else\n {\n m_view.SetOnScreenStateToIntermediateValue(state);\n }\n }\n\n void SearchWidgetController::OnViewOpened()\n {\n if(!m_viewModel.IsFullyOpen())\n {\n m_viewModel.Open();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n void SearchWidgetController::OnViewClosed()\n {\n if(!m_viewModel.IsFullyClosed())\n {\n m_viewModel.Close();\n }\n\n if(m_viewModel.HasReactorControl())\n {\n m_viewModel.ReleaseReactorControl();\n }\n }\n\n\t\t\tvoid SearchWidgetController::OnModalBackgroundTouch()\n\t\t\t{\n\t\t\t\t\/\/ the modal background goes away after the first touch, so no need to throttle\n\n\t\t\t\tm_view.CloseMenu();\n\t\t\t}\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/TODO: Améliorer\n\nnamespace\n{\n\tstatic NzColor primaryColor = NzColor::Red;\n\tstatic NzColor secondaryColor = NzColor::Green;\n\tstatic NzShader* shader = nullptr;\n\tstatic NzVertexBuffer* vertexBuffer = nullptr;\n\tstatic NzVertexDeclaration* vertexDeclaration = nullptr;\n\tstatic bool depthTest = true;\n\tstatic bool initialized = false;\n\tstatic float lineWidth = 2.f;\n\tstatic float pointSize = 3.f;\n\tstatic int colorLocation = -1;\n}\n\nvoid NzDebugDrawer::Draw(const NzAxisAlignedBox& aabb)\n{\n\tif (!aabb.IsFinite())\n\t\treturn;\n\n\tDraw(aabb.GetCube());\n}\n\nvoid NzDebugDrawer::Draw(const NzCubei& cube)\n{\n\tDraw(NzCubef(cube));\n}\n\nvoid NzDebugDrawer::Draw(const NzCubef& cube)\n{\n\tif (!initialized)\n\t{\n\t\tNazaraError(\"Debug drawer is not initialized\");\n\t\treturn;\n\t}\n\n\tNzVertexStruct_XYZ* vertex = reinterpret_cast(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, 24));\n\tif (!vertex)\n\t{\n\t\tNazaraError(\"Failed to map buffer\");\n\t\treturn;\n\t}\n\n\tNzVector3f max, min;\n\tmax = cube.GetPosition() + cube.GetSize();\n\tmin = cube.GetPosition();\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tif (!vertexBuffer->Unmap())\n\t\tNazaraWarning(\"Failed to unmap buffer\");\n\n\tNzShader* oldShader = NzRenderer::GetShader();\n\n\tif (!NzRenderer::SetShader(shader))\n\t{\n\t\tNazaraError(\"Failed to set debug shader\");\n\t\treturn;\n\t}\n\n\tbool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);\n\tif (depthTestActive != depthTest)\n\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);\n\n\tNzRenderer::SetVertexBuffer(vertexBuffer);\n\n\tshader->SendColor(colorLocation, primaryColor);\n\n\tNzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, 24);\n\n\tif (depthTestActive != depthTest)\n\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);\n\n\tif (!NzRenderer::SetShader(oldShader))\n\t\tNazaraWarning(\"Failed to reset shader\");\n}\n\nvoid NzDebugDrawer::Draw(const NzCubeui& cube)\n{\n\tDraw(NzCubef(cube));\n}\n\nvoid NzDebugDrawer::Draw(const NzSkeleton* skeleton)\n{\n\tif (!initialized)\n\t{\n\t\tNazaraError(\"Debug drawer is not initialized\");\n\t\treturn;\n\t}\n\n\tunsigned int jointCount = skeleton->GetJointCount();\n\tif (vertexBuffer->GetVertexCount() < jointCount*2)\n\t{\n\t\tNazaraError(\"Debug buffer not length enougth to draw object\");\n\t\treturn;\n\t}\n\n\tNzVertexStruct_XYZ* vertex = reinterpret_cast(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, jointCount*2));\n\tif (!vertex)\n\t{\n\t\tNazaraError(\"Failed to map buffer\");\n\t\treturn;\n\t}\n\n\tunsigned int vertexCount = 0;\n\tfor (unsigned int i = 0; i < jointCount; ++i)\n\t{\n\t\tconst NzNode* joint = skeleton->GetJoint(i);\n\t\tconst NzNode* parent = joint->GetParent();\n\t\tif (parent)\n\t\t{\n\t\t\tvertex->position = joint->GetDerivedTranslation();\n\t\t\tvertex++;\n\n\t\t\tvertex->position = parent->GetDerivedTranslation();\n\t\t\tvertex++;\n\n\t\t\tvertexCount += 2;\n\t\t}\n\t}\n\n\tif (!vertexBuffer->Unmap())\n\t\tNazaraWarning(\"Failed to unmap buffer\");\n\n\tif (vertexCount > 0)\n\t{\n\t\tNzShader* oldShader = NzRenderer::GetShader();\n\n\t\tif (!NzRenderer::SetShader(shader))\n\t\t{\n\t\t\tNazaraError(\"Failed to set debug shader\");\n\t\t\treturn;\n\t\t}\n\n\t\tbool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);\n\t\tif (depthTestActive != depthTest)\n\t\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);\n\n\t\tNzRenderer::SetVertexBuffer(vertexBuffer);\n\n\t\tshader->SendColor(colorLocation, primaryColor);\n\t\tNzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, vertexCount);\n\n\t\tfloat oldPointSize = NzRenderer::GetPointSize();\n\t\tNzRenderer::SetPointSize(pointSize);\n\n\t\tshader->SendColor(colorLocation, secondaryColor);\n\t\tNzRenderer::DrawPrimitives(nzPrimitiveType_PointList, 0, vertexCount);\n\n\t\tNzRenderer::SetPointSize(oldPointSize);\n\n\t\tif (depthTestActive != depthTest)\n\t\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);\n\n\t\tif (!NzRenderer::SetShader(oldShader))\n\t\t\tNazaraWarning(\"Failed to reset shader\");\n\t}\n}\n\nbool NzDebugDrawer::Initialize()\n{\n\tif (!initialized)\n\t{\n\t\t\/\/ Shader\n\t\t{\n\t\t\tconst char* fragmentSource110 =\n\t\t\t\"#version 110\\n\"\n\t\t\t\"uniform vec3 color;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\"\tgl_FragColor = vec4(color, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* fragmentSource140 =\n\t\t\t\"#version 140\\n\"\n\t\t\t\"uniform vec3 color;\\n\"\n\t\t\t\"out vec4 RenderTarget0;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\"\tRenderTarget0 = vec4(color, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* vertexSource110 =\n\t\t\t\"#version 110\\n\"\n\t\t\t\"attribute vec3 Position;\\n\"\n\t\t\t\"uniform mat4 WorldViewProjMatrix;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\" gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* vertexSource140 =\n\t\t\t\"#version 140\\n\"\n\t\t\t\"in vec3 Position;\\n\"\n\t\t\t\"uniform mat4 WorldViewProjMatrix;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\" gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tbool useGLSL140 = (NzOpenGL::GetVersion() >= 310);\n\n\t\t\tshader = new NzShader(nzShaderLanguage_GLSL);\n\t\t\tif (!shader->Load(nzShaderType_Fragment, (useGLSL140) ? fragmentSource140 : fragmentSource110))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load fragment shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!shader->Load(nzShaderType_Vertex, (useGLSL140) ? vertexSource140 : vertexSource110))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load vertex shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!shader->Compile())\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to compile shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tcolorLocation = shader->GetUniformLocation(\"color\");\n\t\t}\n\n\t\t\/\/ VertexDeclaration\n\t\t{\n\t\t\tNzVertexElement element;\n\t\t\telement.offset = 0;\n\t\t\telement.type = nzElementType_Float3;\n\t\t\telement.usage = nzElementUsage_Position;\n\n\t\t\tvertexDeclaration = new NzVertexDeclaration;\n\t\t\tif (!vertexDeclaration->Create(&element, 1))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create declaration\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ VertexBuffer (Nécessite la déclaration)\n\t\t{\n\t\t\tvertexBuffer = new NzVertexBuffer(vertexDeclaration, 256, nzBufferStorage_Hardware, nzBufferUsage_Dynamic);\n\t\t\tif (!vertexBuffer->GetBuffer()->IsValid())\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tinitialized = true;\n\t}\n\n\treturn true;\n}\n\nbool NzDebugDrawer::GetDepthTest()\n{\n\treturn depthTest;\n}\n\nfloat NzDebugDrawer::GetLineWidth()\n{\n\treturn lineWidth;\n}\n\nfloat NzDebugDrawer::GetPointSize()\n{\n\treturn pointSize;\n}\n\nNzColor NzDebugDrawer::GetPrimaryColor()\n{\n\treturn primaryColor;\n}\n\nNzColor NzDebugDrawer::GetSecondaryColor()\n{\n\treturn secondaryColor;\n}\n\nvoid NzDebugDrawer::SetDepthTest(bool shouldTest)\n{\n\tdepthTest = shouldTest;\n}\n\nvoid NzDebugDrawer::SetLineWidth(float width)\n{\n\tlineWidth = width;\n}\n\nvoid NzDebugDrawer::SetPointSize(float size)\n{\n\tpointSize = size;\n}\n\nvoid NzDebugDrawer::SetPrimaryColor(const NzColor& color)\n{\n\tprimaryColor = color;\n}\n\nvoid NzDebugDrawer::SetSecondaryColor(const NzColor& color)\n{\n\tsecondaryColor = color;\n}\n\nvoid NzDebugDrawer::Uninitialize()\n{\n\tif (shader)\n\t{\n\t\tdelete shader;\n\t\tshader = nullptr;\n\t}\n\n\tif (vertexBuffer)\n\t{\n\t\tdelete vertexBuffer;\n\t\tvertexBuffer = nullptr;\n\t}\n\n\tif (vertexDeclaration)\n\t{\n\t\tdelete vertexDeclaration;\n\t\tvertexDeclaration = nullptr;\n\t}\n\n\tinitialized = false;\n}\nFixed debug drawer not setting line width\/\/ Copyright (C) 2012 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Renderer module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/\/TODO: Améliorer\n\nnamespace\n{\n\tstatic NzColor primaryColor = NzColor::Red;\n\tstatic NzColor secondaryColor = NzColor::Green;\n\tstatic NzShader* shader = nullptr;\n\tstatic NzVertexBuffer* vertexBuffer = nullptr;\n\tstatic NzVertexDeclaration* vertexDeclaration = nullptr;\n\tstatic bool depthTest = true;\n\tstatic bool initialized = false;\n\tstatic float lineWidth = 2.f;\n\tstatic float pointSize = 3.f;\n\tstatic int colorLocation = -1;\n}\n\nvoid NzDebugDrawer::Draw(const NzAxisAlignedBox& aabb)\n{\n\tif (!aabb.IsFinite())\n\t\treturn;\n\n\tDraw(aabb.GetCube());\n}\n\nvoid NzDebugDrawer::Draw(const NzCubei& cube)\n{\n\tDraw(NzCubef(cube));\n}\n\nvoid NzDebugDrawer::Draw(const NzCubef& cube)\n{\n\tif (!initialized)\n\t{\n\t\tNazaraError(\"Debug drawer is not initialized\");\n\t\treturn;\n\t}\n\n\tNzVertexStruct_XYZ* vertex = reinterpret_cast(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, 24));\n\tif (!vertex)\n\t{\n\t\tNazaraError(\"Failed to map buffer\");\n\t\treturn;\n\t}\n\n\tNzVector3f max, min;\n\tmax = cube.GetPosition() + cube.GetSize();\n\tmin = cube.GetPosition();\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, max.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, min.y, max.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(min.x, max.y, min.z);\n\tvertex++;\n\tvertex->position.Set(min.x, max.y, max.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, max.y, min.z);\n\tvertex++;\n\n\tvertex->position.Set(max.x, min.y, min.z);\n\tvertex++;\n\tvertex->position.Set(max.x, min.y, max.z);\n\tvertex++;\n\n\tif (!vertexBuffer->Unmap())\n\t\tNazaraWarning(\"Failed to unmap buffer\");\n\n\tNzShader* oldShader = NzRenderer::GetShader();\n\n\tif (!NzRenderer::SetShader(shader))\n\t{\n\t\tNazaraError(\"Failed to set debug shader\");\n\t\treturn;\n\t}\n\n\tbool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);\n\tif (depthTestActive != depthTest)\n\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);\n\n\tNzRenderer::SetVertexBuffer(vertexBuffer);\n\n\tshader->SendColor(colorLocation, primaryColor);\n\n\tNzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, 24);\n\n\tif (depthTestActive != depthTest)\n\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);\n\n\tif (!NzRenderer::SetShader(oldShader))\n\t\tNazaraWarning(\"Failed to reset shader\");\n}\n\nvoid NzDebugDrawer::Draw(const NzCubeui& cube)\n{\n\tDraw(NzCubef(cube));\n}\n\nvoid NzDebugDrawer::Draw(const NzSkeleton* skeleton)\n{\n\tif (!initialized)\n\t{\n\t\tNazaraError(\"Debug drawer is not initialized\");\n\t\treturn;\n\t}\n\n\tunsigned int jointCount = skeleton->GetJointCount();\n\tif (vertexBuffer->GetVertexCount() < jointCount*2)\n\t{\n\t\tNazaraError(\"Debug buffer not length enougth to draw object\");\n\t\treturn;\n\t}\n\n\tNzVertexStruct_XYZ* vertex = reinterpret_cast(vertexBuffer->Map(nzBufferAccess_DiscardAndWrite, 0, jointCount*2));\n\tif (!vertex)\n\t{\n\t\tNazaraError(\"Failed to map buffer\");\n\t\treturn;\n\t}\n\n\tunsigned int vertexCount = 0;\n\tfor (unsigned int i = 0; i < jointCount; ++i)\n\t{\n\t\tconst NzNode* joint = skeleton->GetJoint(i);\n\t\tconst NzNode* parent = joint->GetParent();\n\t\tif (parent)\n\t\t{\n\t\t\tvertex->position = joint->GetDerivedTranslation();\n\t\t\tvertex++;\n\n\t\t\tvertex->position = parent->GetDerivedTranslation();\n\t\t\tvertex++;\n\n\t\t\tvertexCount += 2;\n\t\t}\n\t}\n\n\tif (!vertexBuffer->Unmap())\n\t\tNazaraWarning(\"Failed to unmap buffer\");\n\n\tif (vertexCount > 0)\n\t{\n\t\tNzShader* oldShader = NzRenderer::GetShader();\n\n\t\tif (!NzRenderer::SetShader(shader))\n\t\t{\n\t\t\tNazaraError(\"Failed to set debug shader\");\n\t\t\treturn;\n\t\t}\n\n\t\tbool depthTestActive = NzRenderer::IsEnabled(nzRendererParameter_DepthTest);\n\t\tif (depthTestActive != depthTest)\n\t\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTest);\n\n\t\tNzRenderer::SetVertexBuffer(vertexBuffer);\n\n\t\tfloat oldLineWidth = NzRenderer::GetLineWidth();\n\t\tNzRenderer::SetLineWidth(lineWidth);\n\n\t\tshader->SendColor(colorLocation, primaryColor);\n\t\tNzRenderer::DrawPrimitives(nzPrimitiveType_LineList, 0, vertexCount);\n\n\t\tfloat oldPointSize = NzRenderer::GetPointSize();\n\t\tNzRenderer::SetPointSize(pointSize);\n\n\t\tshader->SendColor(colorLocation, secondaryColor);\n\t\tNzRenderer::DrawPrimitives(nzPrimitiveType_PointList, 0, vertexCount);\n\n\t\tNzRenderer::SetLineWidth(oldLineWidth);\n\t\tNzRenderer::SetPointSize(oldPointSize);\n\n\t\tif (depthTestActive != depthTest)\n\t\t\tNzRenderer::Enable(nzRendererParameter_DepthTest, depthTestActive);\n\n\t\tif (!NzRenderer::SetShader(oldShader))\n\t\t\tNazaraWarning(\"Failed to reset shader\");\n\t}\n}\n\nbool NzDebugDrawer::Initialize()\n{\n\tif (!initialized)\n\t{\n\t\t\/\/ Shader\n\t\t{\n\t\t\tconst char* fragmentSource110 =\n\t\t\t\"#version 110\\n\"\n\t\t\t\"uniform vec3 color;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\"\tgl_FragColor = vec4(color, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* fragmentSource140 =\n\t\t\t\"#version 140\\n\"\n\t\t\t\"uniform vec3 color;\\n\"\n\t\t\t\"out vec4 RenderTarget0;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\"\tRenderTarget0 = vec4(color, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* vertexSource110 =\n\t\t\t\"#version 110\\n\"\n\t\t\t\"attribute vec3 Position;\\n\"\n\t\t\t\"uniform mat4 WorldViewProjMatrix;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\" gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tconst char* vertexSource140 =\n\t\t\t\"#version 140\\n\"\n\t\t\t\"in vec3 Position;\\n\"\n\t\t\t\"uniform mat4 WorldViewProjMatrix;\\n\"\n\t\t\t\"void main()\\n\"\n\t\t\t\"{\\n\"\n\t\t\t\" gl_Position = WorldViewProjMatrix * vec4(Position, 1.0);\\n\"\n\t\t\t\"}\\n\";\n\n\t\t\tbool useGLSL140 = (NzOpenGL::GetVersion() >= 310);\n\n\t\t\tshader = new NzShader(nzShaderLanguage_GLSL);\n\t\t\tif (!shader->Load(nzShaderType_Fragment, (useGLSL140) ? fragmentSource140 : fragmentSource110))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load fragment shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!shader->Load(nzShaderType_Vertex, (useGLSL140) ? vertexSource140 : vertexSource110))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to load vertex shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif (!shader->Compile())\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to compile shader\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tcolorLocation = shader->GetUniformLocation(\"color\");\n\t\t}\n\n\t\t\/\/ VertexDeclaration\n\t\t{\n\t\t\tNzVertexElement element;\n\t\t\telement.offset = 0;\n\t\t\telement.type = nzElementType_Float3;\n\t\t\telement.usage = nzElementUsage_Position;\n\n\t\t\tvertexDeclaration = new NzVertexDeclaration;\n\t\t\tif (!vertexDeclaration->Create(&element, 1))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create declaration\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ VertexBuffer (Nécessite la déclaration)\n\t\t{\n\t\t\tvertexBuffer = new NzVertexBuffer(vertexDeclaration, 256, nzBufferStorage_Hardware, nzBufferUsage_Dynamic);\n\t\t\tif (!vertexBuffer->GetBuffer()->IsValid())\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create buffer\");\n\t\t\t\tUninitialize();\n\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tinitialized = true;\n\t}\n\n\treturn true;\n}\n\nbool NzDebugDrawer::GetDepthTest()\n{\n\treturn depthTest;\n}\n\nfloat NzDebugDrawer::GetLineWidth()\n{\n\treturn lineWidth;\n}\n\nfloat NzDebugDrawer::GetPointSize()\n{\n\treturn pointSize;\n}\n\nNzColor NzDebugDrawer::GetPrimaryColor()\n{\n\treturn primaryColor;\n}\n\nNzColor NzDebugDrawer::GetSecondaryColor()\n{\n\treturn secondaryColor;\n}\n\nvoid NzDebugDrawer::SetDepthTest(bool shouldTest)\n{\n\tdepthTest = shouldTest;\n}\n\nvoid NzDebugDrawer::SetLineWidth(float width)\n{\n\tlineWidth = width;\n}\n\nvoid NzDebugDrawer::SetPointSize(float size)\n{\n\tpointSize = size;\n}\n\nvoid NzDebugDrawer::SetPrimaryColor(const NzColor& color)\n{\n\tprimaryColor = color;\n}\n\nvoid NzDebugDrawer::SetSecondaryColor(const NzColor& color)\n{\n\tsecondaryColor = color;\n}\n\nvoid NzDebugDrawer::Uninitialize()\n{\n\tif (shader)\n\t{\n\t\tdelete shader;\n\t\tshader = nullptr;\n\t}\n\n\tif (vertexBuffer)\n\t{\n\t\tdelete vertexBuffer;\n\t\tvertexBuffer = nullptr;\n\t}\n\n\tif (vertexDeclaration)\n\t{\n\t\tdelete vertexDeclaration;\n\t\tvertexDeclaration = nullptr;\n\t}\n\n\tinitialized = false;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2014-2016 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\/\/ Author: Adrien Bruneton (CEA)\n\n#include \"PVViewer_Behaviors.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint PVViewer_Behaviors::BehaviorLoadingLevel = 0;\n\nPVViewer_Behaviors::PVViewer_Behaviors(QMainWindow * parent)\n : QObject(parent)\n{\n}\n\n\/**! Instanciate minimal ParaView behaviors needed when using an instance of PVViewer.\n * This method should be updated at each new version of ParaView with what is found in\n * Qt\/ApplicationComponents\/pqParaViewBehaviors.cxx\n *\/\nvoid PVViewer_Behaviors::instanciateMinimalBehaviors(QMainWindow * desk)\n{\n if (BehaviorLoadingLevel < 1)\n {\n \/\/ Register ParaView interfaces.\n pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();\n\n \/\/ Register standard types of property widgets.\n pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));\n \/\/ Register standard types of view-frame actions.\n pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));\n\n \/\/ Load plugins distributed with application.\n pqApplicationCore::instance()->loadDistributedPlugins();\n\n new pqDefaultViewBehavior(this); \/\/ shows a 3D view as soon as a server connection is made\n new pqAlwaysConnectedBehavior(this); \/\/ client always connected to a server\n new pqVerifyRequiredPluginBehavior(this);\n new pqPluginSettingsBehavior(this);\n new pqFixPathsInStateFilesBehavior(this);\n new pqCrashRecoveryBehavior(this);\n new pqCommandLineOptionsBehavior(this);\n\n BehaviorLoadingLevel = 1;\n }\n}\n\n\/**! Instanciate usual ParaView behaviors.\n * This method should be updated at each new version of ParaView with what is found in\n * Qt\/ApplicationComponents\/pqParaViewBehaviors.cxx\n *\/\nvoid PVViewer_Behaviors::instanciateAllBehaviors(QMainWindow * desk)\n{\n \/\/ \"new pqParaViewBehaviors(anApp->desktop(), this);\"\n \/\/ -> (which loads all standard ParaView behaviors at once) has to be replaced in order to\n \/\/ exclude using of pqQtMessageHandlerBehaviour\n\n \/\/ Define application behaviors.\n if (BehaviorLoadingLevel < 1)\n instanciateMinimalBehaviors(desk);\n\n if (BehaviorLoadingLevel < 2)\n {\n \/\/new pqQtMessageHandlerBehavior(this); \/\/ THIS ONE TO EXCLUDE !! see comment above\n new pqDataTimeStepBehavior(this);\n new pqSpreadSheetVisibilityBehavior(this);\n new pqPipelineContextMenuBehavior(this);\n new pqUndoRedoBehavior(this);\n new pqAutoLoadPluginXMLBehavior(this); \/\/ auto load plugins GUI stuff\n new pqPluginDockWidgetsBehavior(desk);\n new pqPluginActionGroupBehavior(desk);\n new pqPersistentMainWindowStateBehavior(desk);\n new pqObjectPickingBehavior(desk);\n new pqCollaborationBehavior(this);\n new pqViewStreamingBehavior(this);\n\n pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);\n foreach (pqPropertiesPanel* ppanel, desk->findChildren())\n {\n applyBehavior->registerPanel(ppanel);\n }\n BehaviorLoadingLevel = 2;\n }\n}\nFix for the '0023265: [CEA 1809] In PARAVIS, th field vtkBlockColors is displayed with a continute scalar bar instead of a discrete one' issue.\/\/ Copyright (C) 2014-2016 CEA\/DEN, EDF R&D, OPEN CASCADE\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ See http:\/\/www.salome-platform.org\/ or email : webmaster.salome@opencascade.com\n\/\/\n\/\/ Author: Adrien Bruneton (CEA)\n\n#include \"PVViewer_Behaviors.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint PVViewer_Behaviors::BehaviorLoadingLevel = 0;\n\nPVViewer_Behaviors::PVViewer_Behaviors(QMainWindow * parent)\n : QObject(parent)\n{\n}\n\n\/**! Instanciate minimal ParaView behaviors needed when using an instance of PVViewer.\n * This method should be updated at each new version of ParaView with what is found in\n * Qt\/ApplicationComponents\/pqParaViewBehaviors.cxx\n *\/\nvoid PVViewer_Behaviors::instanciateMinimalBehaviors(QMainWindow * desk)\n{\n if (BehaviorLoadingLevel < 1)\n {\n \/\/ Register ParaView interfaces.\n pqInterfaceTracker* pgm = pqApplicationCore::instance()->interfaceTracker();\n\n \/\/ Register standard types of property widgets.\n pgm->addInterface(new pqStandardPropertyWidgetInterface(pgm));\n \/\/ Register standard types of view-frame actions.\n pgm->addInterface(new pqStandardViewFrameActionsImplementation(pgm));\n\n \/\/ Load plugins distributed with application.\n pqApplicationCore::instance()->loadDistributedPlugins();\n\n new pqDefaultViewBehavior(this); \/\/ shows a 3D view as soon as a server connection is made\n new pqAlwaysConnectedBehavior(this); \/\/ client always connected to a server\n new pqVerifyRequiredPluginBehavior(this);\n new pqPluginSettingsBehavior(this);\n new pqFixPathsInStateFilesBehavior(this);\n new pqCrashRecoveryBehavior(this);\n new pqCommandLineOptionsBehavior(this);\n\n BehaviorLoadingLevel = 1;\n }\n}\n\n\/**! Instanciate usual ParaView behaviors.\n * This method should be updated at each new version of ParaView with what is found in\n * Qt\/ApplicationComponents\/pqParaViewBehaviors.cxx\n *\/\nvoid PVViewer_Behaviors::instanciateAllBehaviors(QMainWindow * desk)\n{\n \/\/ \"new pqParaViewBehaviors(anApp->desktop(), this);\"\n \/\/ -> (which loads all standard ParaView behaviors at once) has to be replaced in order to\n \/\/ exclude using of pqQtMessageHandlerBehaviour\n\n \/\/ Define application behaviors.\n if (BehaviorLoadingLevel < 1)\n instanciateMinimalBehaviors(desk);\n\n if (BehaviorLoadingLevel < 2)\n {\n \/\/new pqQtMessageHandlerBehavior(this); \/\/ THIS ONE TO EXCLUDE !! see comment above\n new pqDataTimeStepBehavior(this);\n new pqSpreadSheetVisibilityBehavior(this);\n new pqPipelineContextMenuBehavior(this);\n new pqUndoRedoBehavior(this);\n new pqAutoLoadPluginXMLBehavior(this); \/\/ auto load plugins GUI stuff\n new pqPluginDockWidgetsBehavior(desk);\n new pqPluginActionGroupBehavior(desk);\n new pqPersistentMainWindowStateBehavior(desk);\n new pqObjectPickingBehavior(desk);\n new pqCollaborationBehavior(this);\n new pqViewStreamingBehavior(this);\n new pqStandardArrayColorMapsBehavior(this);\n\n pqApplyBehavior* applyBehavior = new pqApplyBehavior(this);\n foreach (pqPropertiesPanel* ppanel, desk->findChildren())\n {\n applyBehavior->registerPanel(ppanel);\n }\n BehaviorLoadingLevel = 2;\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace corpus {\n#include \"lword.hh\"\n#include \"corpus.hh\"\n#include \"file2eigen.hh\"\n};\nusing namespace corpus;\n\nvoid usage() {\n std::cout << \"tools (lword|lbalance|corpus|toc|redig|stat|reconstruct|diff)\" << std::endl;\n}\n\nconst int szwindow(200);\nconst int szblock(8000);\nconst int Mbalance(40);\nconst double threshin(.1);\nstd::vector delimiter;\nstd::vector csvelim;\nstd::vector csvdelim;\n\nstd::pair loadbuf(const char* filename) {\n std::ifstream input;\n std::string line;\n std::string inbuf;\n input.open(filename);\n while(getline(input, line)) {\n inbuf += line + std::string(\"\\n\");\n if(input.eof() || input.bad())\n break;\n }\n input.close();\n \n std::string name0(filename);\n int slash = - 1;\n for(int j = 0; j < name0.size(); j ++)\n if(name0[j] == '\/')\n slash = j;\n std::string name;\n slash ++;\n for(int j = slash; j < name0.size(); j ++)\n name += name0[j];\n \n return std::make_pair(name, inbuf);\n}\n\nint main(int argc, const char* argv[]) {\n if(argc < 3) {\n usage();\n return - 2;\n }\n delimiter.push_back(string(\".\"));\n delimiter.push_back(string(\",\"));\n delimiter.push_back(string(\"\\'\"));\n delimiter.push_back(string(\"\\\"\"));\n delimiter.push_back(string(\"。\"));\n delimiter.push_back(string(\"、\"));\n delimiter.push_back(string(\"「\"));\n delimiter.push_back(string(\"」\"));\n delimiter.push_back(string(\"(\"));\n delimiter.push_back(string(\")\"));\n csvelim.push_back(string(\" \"));\n csvelim.push_back(string(\"\\t\"));\n csvdelim.push_back(string(\",\"));\n csvdelim.push_back(string(\"\\r\"));\n csvdelim.push_back(string(\"\\n\"));\n auto csv(cutText(loadbuf(argv[3]).second, csvelim, csvdelim, true));\n const auto input(loadbuf(argv[2]).second);\n if(std::strcmp(argv[1], \"lword\") == 0) {\n csv.insert(csv.end(), csvelim.begin(), csvelim.end());\n csv.insert(csv.end(), csvdelim.begin(), csvdelim.end());\n const auto inputs(cutText(input, csv, delimiter));\n lword stat;\n std::wstring_convert, char32_t> converter;\n for(int j = 0; j < inputs.size(); j ++) {\n std::u32string itrans(converter.from_bytes(inputs[j]));\n for(int i0 = 0; i0 <= input.size() \/ szblock; i0 ++)\n for(int i = 2; i < 20; i ++) {\n stat.init(60, i, i);\n auto words(stat.compute(itrans.substr(i0 * szblock, szblock)));\n for(auto itr = words.begin(); itr != words.end(); ++ itr)\n if(itr->str.size() > 2 && itr->count >= i) {\n std::cout << converter.to_bytes(itr->str) << \", \";\n std::cout << itr->count << std::endl;\n }\n }\n }\n } else if(std::strcmp(argv[1], \"lbalance\") == 0) {\n const auto cinput(cutText(input, csvelim, delimiter));\n const auto idxs(pseudoWordsBalance(cinput, csv, Mbalance));\n std::cout << idxs.size() << \"sets.\" << std::endl;\n for(int i = 0; i < idxs.size(); i ++)\n std::cout << cinput[idxs[i]] << std::endl;\n } \/* else if(std::strcmp(argv[1], \"corpus\") == 0) {\n corpus stat;\n for(int i = 0; i < input.size() \/ szwindow + 1; i ++) {\n stat.init(csv, 0, 120);\n const auto& words(stat.getWords());\n stat.compute(input.substr(i * szwindow, szwindow), delimiter);\n const auto& corpus(stat.getCorpus());\n std::cout << words << std::endl;\n \/\/ std::cout << corpus << std::endl;\n }\n } *\/ else if(std::strcmp(argv[1], \"toc\") == 0 ||\n std::strcmp(argv[1], \"lack\") == 0) {\n std::vector details;\n std::vector tocs;\n std::vector detailwords;\n std::vector tocwords;\n bool toc(false);\n for(int iidx = 4; iidx < argc; iidx ++) {\n if(std::string(argv[iidx]) == std::string(\"-toc\")) {\n toc = true;\n continue;\n }\n const auto work(loadbuf(argv[iidx]));\n if(toc) {\n tocs.push_back(work.second);\n tocwords.push_back(work.first);\n } else {\n details.push_back(work.second);\n detailwords.push_back(work.first);\n }\n }\n csv.insert(csv.end(), tocwords.begin(), tocwords.end());\n csv.insert(csv.end(), detailwords.begin(), detailwords.end());\n std::sort(csv.begin(), csv.end());\n csv.erase(std::unique(csv.begin(), csv.end()), csv.end());\n std::cout << std::string(\"<\/head>\") << std::endl;\n std::cout << std::string(\"\");\n std::cout << preparedTOC(input, csv, detailwords, details, tocwords, tocs, delimiter, szwindow, 8, threshin, .125, std::strcmp(argv[1], \"lack\") == 0) << std::string(\"\") << std::endl;\n std::cout << std::string(\"<\/body><\/html>\");\n } else if(std::strcmp(argv[1], \"reconstruct\") == 0) { \n corpus stat;\n stat.compute(input, delimiter, csv);\n corpushl recons(stat);\n std::cout << recons.serialize();\n } else if(std::strcmp(argv[1], \"redig\") == 0) {\n std::vector emph;\n emph.push_back(4.);\n emph.push_back(1.);\n emph.push_back(.25);\n for(int ei = 0; ei < emph.size(); ei ++) {\n for(int i = 0; i < input.size() \/ szwindow + 1; i ++) {\n corpus stat; \n stat.compute(input.substr(i * szwindow, szwindow), delimiter, csv);\n corpushl recons(stat);\n recons.reDig(emph[ei]);\n std::cout << recons.serialize() << std::endl;\n }\n std::cout << std::endl << std::endl;\n }\n } else if(std::strcmp(argv[1], \"diff\") == 0) {\n std::vector details, details2;\n std::vector detailwords, detailwords2;\n bool second(false);\n for(int iidx = 4; iidx < argc; iidx ++) {\n if(std::string(argv[iidx]) == std::string(\"-dict\")) {\n second = false;\n continue;\n } else if(std::string(argv[iidx]) == std::string(\"-dict2\")) {\n second = true;\n continue;\n }\n const auto work(loadbuf(argv[iidx]));\n if(second) {\n details2.push_back(work.second);\n detailwords2.push_back(work.first);\n } else {\n details.push_back(work.second);\n detailwords.push_back(work.first);\n }\n }\n csv.insert(csv.end(), detailwords.begin(), detailwords.end());\n csv.insert(csv.end(), detailwords2.begin(), detailwords2.end());\n std::sort(csv.begin(), csv.end());\n csv.erase(std::unique(csv.begin(), csv.end()), csv.end());\n std::cout << std::string(\"<\/head>\") << std::endl;\n std::cout << std::string(\"\");\n std::cout << diff(input, csv, details, detailwords, details2, detailwords2, delimiter, szwindow, threshin) << std::string(\"\") << std::endl;\n std::cout << \"<\/body><\/html>\" << std::endl;\n } else if(std::strcmp(argv[1], \"stat\") == 0 ||\n std::strcmp(argv[1], \"findroot\") == 0) {\n std::vector rdetails;\n std::vector rdetailwords;\n for(int iidx = 4; iidx < argc; iidx ++) {\n const auto work(loadbuf(argv[iidx]));\n rdetails.push_back(work.second);\n rdetailwords.push_back(work.first);\n }\n csv.insert(csv.end(), rdetailwords.begin(), rdetailwords.end());\n std::sort(csv.begin(), csv.end());\n csv.erase(std::unique(csv.begin(), csv.end()), csv.end());\n std::cout << std::string(\"<\/head>\") << std::endl;\n std::cout << std::string(\"\");\n std::cout << optimizeTOC(input, csv, rdetails, rdetailwords, delimiter, szwindow, 8, threshin, 1., std::strcmp(argv[1], \"findroot\") == 0) << std::string(\"\") << std::endl;\n std::cout << std::string(\"<\/body><\/html>\");\n } else if(std::strcmp(argv[1], \"prep\") == 0) {\n std::vector buf;\n corpus stat;\n for(int i = 0; i < input.size() \/ szwindow + 1; i ++) {\n stat.compute(input.substr(i * szwindow, szwindow), delimiter, csv);\n const auto work(corpushl(stat).reverseLink());\n buf.insert(buf.end(), work.begin(), work.end());\n }\n std::sort(buf.begin(), buf.end());\n buf.erase(std::unique(buf.begin(), buf.end()), buf.end());\n for(int i = 0; i < buf.size(); i ++)\n std::cout << buf[i] << std::endl;\n } else if(std::strcmp(argv[1], \"optdict\") == 0)\n assert(0 && \"group dicts: not implemented around NOT word tables.\");\n else if(std::strcmp(argv[1], \"conflict\") == 0)\n assert(0 && \"conflict : not implemented around NOT word tables.\");\n else if(std::strcmp(argv[1], \"negate\") == 0)\n assert(0 && \"negate: not implemented around NOT word tables.\");\n else if(std::strcmp(argv[1], \"consistency\") == 0)\n assert(0 && \"consistancy : Logics check so far...\");\n else if(std::strcmp(argv[1], \"logiccheck\") == 0)\n assert(0 && \"logic check : Logics check so far...\");\n else {\n usage();\n return - 2;\n }\n return 0;\n}\n\nDelete test.cc<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n--allow-empty_message\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n<|endoftext|>"} {"text":"\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ Basket ball demo.\n\/\/ Serves as a test for the sphere vs trimesh collider\n\/\/ By Bram Stolk.\n\/\/ Press the spacebar to reset the position of the ball.\n\n#include \n#include \n#ifdef HAVE_UNISTD_H\n#include \n#endif\n#include \n#include \n\n#include \"basket_geom.h\" \/\/ this is our world mesh\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ some constants\n\n#define RADIUS 0.14\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\n\nstatic dBodyID sphbody;\nstatic dGeomID sphgeom;\n\nstatic dJointGroupID contactgroup;\nstatic dGeomID world_mesh;\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n assert(o1);\n assert(o2);\n\n if (dGeomIsSpace(o1) || dGeomIsSpace(o2))\n {\n fprintf(stderr,\"testing space %p %p\\n\", o1,o2);\n \/\/ colliding a space with something\n dSpaceCollide2(o1,o2,data,&nearCallback);\n \/\/ Note we do not want to test intersections within a space,\n \/\/ only between spaces.\n return;\n }\n\n\/\/ fprintf(stderr,\"testing geoms %p %p\\n\", o1, o2);\n\n const int N = 32;\n dContact contact[N];\n int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));\n if (n > 0) \n {\n for (int i=0; iMake it score on linux+opcode\/*************************************************************************\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/\/ Basket ball demo.\n\/\/ Serves as a test for the sphere vs trimesh collider\n\/\/ By Bram Stolk.\n\/\/ Press the spacebar to reset the position of the ball.\n\n#include \n#include \n#ifdef HAVE_UNISTD_H\n#include \n#endif\n#include \n#include \n\n#include \"basket_geom.h\" \/\/ this is our world mesh\n\n#ifdef _MSC_VER\n#pragma warning(disable:4244 4305) \/\/ for VC++, no precision loss complaints\n#endif\n\n\/\/ some constants\n\n#define RADIUS 0.14\n\n\/\/ dynamics and collision objects (chassis, 3 wheels, environment)\n\nstatic dWorldID world;\nstatic dSpaceID space;\n\nstatic dBodyID sphbody;\nstatic dGeomID sphgeom;\n\nstatic dJointGroupID contactgroup;\nstatic dGeomID world_mesh;\n\n\n\/\/ this is called by dSpaceCollide when two objects in space are\n\/\/ potentially colliding.\n\nstatic void nearCallback (void *data, dGeomID o1, dGeomID o2)\n{\n assert(o1);\n assert(o2);\n\n if (dGeomIsSpace(o1) || dGeomIsSpace(o2))\n {\n fprintf(stderr,\"testing space %p %p\\n\", o1,o2);\n \/\/ colliding a space with something\n dSpaceCollide2(o1,o2,data,&nearCallback);\n \/\/ Note we do not want to test intersections within a space,\n \/\/ only between spaces.\n return;\n }\n\n\/\/ fprintf(stderr,\"testing geoms %p %p\\n\", o1, o2);\n\n const int N = 32;\n dContact contact[N];\n int n = dCollide (o1,o2,N,&(contact[0].geom),sizeof(dContact));\n if (n > 0) \n {\n for (int i=0; i"} {"text":"#include \"Resource.hpp\"\r\n#include \"Asset.hpp\"\r\n#include \"SDInputFile.hpp\"\r\n\r\nnamespace MPACK\r\n{\r\n\tnamespace Core\r\n\t{\r\n\t\tconst int PATH_BUFFER_SIZE=256;\r\n\r\n\t\tResource::Resource(const char* pPath)\r\n\t\t{\r\n\t\t\tmPath = new char[strlen(pPath)+2];\r\n\t\t\tstrcpy(mPath,pPath);\r\n\t\t}\r\n\r\n\t\tconst char* Resource::GetPath()\r\n\t\t{\r\n\t\t\treturn mPath;\r\n\t\t}\r\n\r\n\t\tResource::~Resource()\r\n\t\t{\r\n\t\t\tdelete[] mPath;\r\n\t\t}\r\n\r\n\t\tResource* LoadResource(const char* pPath)\r\n\t\t{\r\n\t#ifdef ANDROID_PLATFORM\r\n\t\t\tif(pPath[0]=='@')\r\n\t\t\t{\r\n\t\t\t\treturn (Resource*)(new Asset(pPath+1));\r\n\t\t\t}\r\n\t\t\tif(pPath[1]=='&')\r\n\t\t\t{\r\n\t\t\t\treturn (Resource*)(new SDInputFile(pPath+1));\r\n\t\t\t}\r\n\t#elif\tdefined(WINDOWS_PLATFORM) || defined(LINUX_PLATFORM)\r\n\t\t\tchar pathBuffer[PATH_BUFFER_SIZE];\r\n\t\t\tif(pPath[0]=='@')\r\n\t\t\t{\r\n\t\t\t\tstrcpy(pathBuffer,\"assets\/\");\r\n\t\t\t\tstrcat(pathBuffer,pPath+1);\r\n\t\t\t}\r\n\t\t\tif(pPath[1]=='&')\r\n\t\t\t{\r\n\t\t\t\tstrcpy(pathBuffer,pPath+1);\r\n\t\t\t}\r\n\t\t\treturn (Resource*)(new SDInputFile(pathBuffer));\r\n\t#endif\r\n\t\t\tLOGE(\"LoadResource: invalid path %s\",pPath);\r\n\t\t\treturn NULL;\r\n\t\t}\r\n\t}\r\n}\r\nFixed resource loading bug#include \"Resource.hpp\"\r\n#include \"Asset.hpp\"\r\n#include \"SDInputFile.hpp\"\r\n\r\nusing namespace std;\r\n\r\nnamespace MPACK\r\n{\r\n\tnamespace Core\r\n\t{\r\n\t\tconst int PATH_BUFFER_SIZE=256;\r\n\r\n\t\tResource::Resource(const char* pPath)\r\n\t\t{\r\n\t\t\tmPath = new char[strlen(pPath)+2];\r\n\t\t\tstrcpy(mPath,pPath);\r\n\t\t}\r\n\r\n\t\tconst char* Resource::GetPath()\r\n\t\t{\r\n\t\t\treturn mPath;\r\n\t\t}\r\n\r\n\t\tResource::~Resource()\r\n\t\t{\r\n\t\t\tdelete[] mPath;\r\n\t\t}\r\n\r\n\t\tResource* LoadResource(const char* pPath)\r\n\t\t{\r\n\t#ifdef ANDROID_PLATFORM\r\n\t\t\tif(pPath[0]=='@')\r\n\t\t\t{\r\n\t\t\t\treturn (Resource*)(new Asset(pPath+1));\r\n\t\t\t}\r\n\t\t\tif(pPath[0]=='&')\r\n\t\t\t{\r\n\t\t\t\treturn (Resource*)(new SDInputFile(pPath+1));\r\n\t\t\t}\r\n\t#elif\tdefined(WINDOWS_PLATFORM) || defined(LINUX_PLATFORM)\r\n\t\t\tchar pathBuffer[PATH_BUFFER_SIZE];\r\n\t\t\tif(pPath[0]=='@')\r\n\t\t\t{\r\n\t\t\t\tstrcpy(pathBuffer,\"assets\/\");\r\n\t\t\t\tstrcat(pathBuffer,pPath+1);\r\n\t\t\t}\r\n\t\t\tif(pPath[0]=='&')\r\n\t\t\t{\r\n\t\t\t\tstrcpy(pathBuffer,pPath+1);\r\n\t\t\t}\r\n\t\t\treturn (Resource*)(new SDInputFile(pathBuffer));\r\n\t#endif\r\n\t\t\tLOGE(\"LoadResource: invalid path %s\",pPath);\r\n\t\t\treturn NULL;\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\/**\n * \n * @author David N. Bertoni (david_n_bertoni@lotus.com)\n * *\/\n\n\n\n\/\/ Base class header file.\n#include \"ProblemListenerDefault.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n\n\n\n#include \n\n\n\nstatic const char* const\terrorHeader = \"error: \";\nstatic const char* const\twarningHeader = \"warning: \";\n\nstatic const char* const\txslHeader = \"XSLT \";\nstatic const char* const\txmlHeader = \"XML \";\nstatic const char* const\txpathHeader = \"XPath \";\n\nstatic const char* const\tstyleTreeNodeHeader = \", style tree node: \";\nstatic const char* const\tsourceTreeNodeHeader = \", source tree node: \";\nstatic const char* const\tlocationOpen = \" (\";\nstatic const char* const\turiHeader = \"\";\nstatic const char* const\tlineNoHeader = \", line \";\nstatic const char* const\tcharOffsetHeader = \", column \";\nstatic const char* const\tlocationClose = \")\";\n\n\n\nProblemListenerDefault::ProblemListenerDefault(PrintWriter*\t\tpw) :\n\tProblemListener(),\n\tm_pw(pw)\n{\n}\n\n\n\nProblemListenerDefault::~ProblemListenerDefault()\n{\n\tm_pw = 0;\n}\n\n\n\nvoid\nProblemListenerDefault::setPrintWriter(PrintWriter*\t\tpw)\n{\n\tm_pw = pw;\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (m_pw != 0)\n\t{\n\t\tif (eXMLPARSER == where)\n\t\t{\n\t\t\tm_pw->print(xmlHeader);\n\t\t}\n\t\telse if (eXPATH == where)\n\t\t{\n\t\t\tm_pw->print(xpathHeader);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_pw->print(xslHeader);\n\t\t}\n\n\t\tif (eERROR == classification)\n\t\t{\n\t\t\tm_pw->print(errorHeader);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_pw->print(warningHeader);\n\t\t}\n\n\t\tm_pw->print(msg);\n\n\t\tif (0 != styleNode)\n\t\t{\n\t\t\tm_pw->print(styleTreeNodeHeader);\n\t\t\tm_pw->print(styleNode->getNodeName());\n\t\t}\n\n\t\tif (0 != sourceNode)\n\t\t{\n\t\t\tm_pw->print(sourceTreeNodeHeader);\n\t\t\tm_pw->print(sourceNode->getNodeName());\n\t\t}\n\n\t\tm_pw->print(locationOpen);\n\n\t\tif (0 != uri)\n\t\t{\n\t\t\tm_pw->print(uriHeader);\n\t\t\tm_pw->print(uri);\n\t\t}\n\n\t\tif (0 != lineNo)\n\t\t{\n\t\t\tm_pw->print(lineNoHeader);\n\t\t\tm_pw->print(lineNo);\n\t\t}\n\n\t\tif (0 != charOffset)\n\t\t{\n\t\t\tm_pw->print(charOffsetHeader);\n\t\t\tm_pw->print(charOffset);\n\t\t}\n\n\t\tm_pw->print(locationClose);\n\n\t\tm_pw->println();\n\t}\n}\nRemoved bogus destructor code.\/*\n * The Apache Software License, Version 1.1\n *\n *\n * Copyright (c) 1999 The Apache Software Foundation. All rights \n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer. \n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment: \n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xalan\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written \n * permission, please contact apache@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com. For more\n * information on the Apache Software Foundation, please see\n * .\n *\/\n\/**\n * \n * @author David N. Bertoni (david_n_bertoni@lotus.com)\n * *\/\n\n\n\n\/\/ Base class header file.\n#include \"ProblemListenerDefault.hpp\"\n\n\n\n#include \n\n\n\n#include \n#include \n\n\n\n#include \n\n\n\nstatic const char* const\terrorHeader = \"error: \";\nstatic const char* const\twarningHeader = \"warning: \";\n\nstatic const char* const\txslHeader = \"XSLT \";\nstatic const char* const\txmlHeader = \"XML \";\nstatic const char* const\txpathHeader = \"XPath \";\n\nstatic const char* const\tstyleTreeNodeHeader = \", style tree node: \";\nstatic const char* const\tsourceTreeNodeHeader = \", source tree node: \";\nstatic const char* const\tlocationOpen = \" (\";\nstatic const char* const\turiHeader = \"\";\nstatic const char* const\tlineNoHeader = \", line \";\nstatic const char* const\tcharOffsetHeader = \", column \";\nstatic const char* const\tlocationClose = \")\";\n\n\n\nProblemListenerDefault::ProblemListenerDefault(PrintWriter*\t\tpw) :\n\tProblemListener(),\n\tm_pw(pw)\n{\n}\n\n\n\nProblemListenerDefault::~ProblemListenerDefault()\n{\n}\n\n\n\nvoid\nProblemListenerDefault::setPrintWriter(PrintWriter*\t\tpw)\n{\n\tm_pw = pw;\n}\n\n\n\nvoid\nProblemListenerDefault::problem(\n\t\t\teProblemSource\t\t\twhere,\n\t\t\teClassification\t\t\tclassification, \n\t\t\tconst XalanNode*\t\tsourceNode,\n\t\t\tconst XalanNode*\t\tstyleNode,\n\t\t\tconst XalanDOMString&\tmsg,\n\t\t\tconst XalanDOMChar*\t\turi,\n\t\t\tint\t\t\t\t\t\tlineNo,\n\t\t\tint\t\t\t\t\t\tcharOffset)\n{\n\tif (m_pw != 0)\n\t{\n\t\tif (eXMLPARSER == where)\n\t\t{\n\t\t\tm_pw->print(xmlHeader);\n\t\t}\n\t\telse if (eXPATH == where)\n\t\t{\n\t\t\tm_pw->print(xpathHeader);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_pw->print(xslHeader);\n\t\t}\n\n\t\tif (eERROR == classification)\n\t\t{\n\t\t\tm_pw->print(errorHeader);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tm_pw->print(warningHeader);\n\t\t}\n\n\t\tm_pw->print(msg);\n\n\t\tif (0 != styleNode)\n\t\t{\n\t\t\tm_pw->print(styleTreeNodeHeader);\n\t\t\tm_pw->print(styleNode->getNodeName());\n\t\t}\n\n\t\tif (0 != sourceNode)\n\t\t{\n\t\t\tm_pw->print(sourceTreeNodeHeader);\n\t\t\tm_pw->print(sourceNode->getNodeName());\n\t\t}\n\n\t\tm_pw->print(locationOpen);\n\n\t\tif (0 != uri)\n\t\t{\n\t\t\tm_pw->print(uriHeader);\n\t\t\tm_pw->print(uri);\n\t\t}\n\n\t\tif (0 != lineNo)\n\t\t{\n\t\t\tm_pw->print(lineNoHeader);\n\t\t\tm_pw->print(lineNo);\n\t\t}\n\n\t\tif (0 != charOffset)\n\t\t{\n\t\t\tm_pw->print(charOffsetHeader);\n\t\t\tm_pw->print(charOffset);\n\t\t}\n\n\t\tm_pw->print(locationClose);\n\n\t\tm_pw->println();\n\t}\n}\n<|endoftext|>"} {"text":"#include \"KinectStreamer.hpp\"\n#include \n#include \n#include \n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Data\/Mesh.hpp\"\n\nnamespace fast {\n\n\nbool KinectStreamer::mInitialized = false;\nstd::stack KinectStreamer::mAvailableDevices;\n\nKinectStreamer::KinectStreamer() {\n createOutputPort(0); \/\/ RGB\n createOutputPort(1); \/\/ Depth image\n createOutputPort(2); \/\/ Point cloud\n mNrOfFrames = 0;\n mHasReachedEnd = false;\n mFirstFrameIsInserted = false;\n mStreamIsStarted = false;\n mIsModified = true;\n mPointCloudFilterEnabled = false;\n registration = NULL;\n}\n\nvoid KinectStreamer::setPointCloudFiltering(bool enabled) {\n mPointCloudFilterEnabled = enabled;\n}\n\nvoid KinectStreamer::execute() {\n if(!mStreamIsStarted) {\n \/\/ Check that first frame exists before starting streamer\n\n mStreamIsStarted = true;\n mStop = false;\n mThread = new std::thread(std::bind(&KinectStreamer::producerStream, this));\n }\n\n \/\/ Wait here for first frame\n std::unique_lock lock(mFirstFrameMutex);\n while(!mFirstFrameIsInserted) {\n mFirstFrameCondition.wait(lock);\n }\n}\n\n\nMeshVertex KinectStreamer::getPoint(int x, int y) {\n float x2, y2, z2, rgb;\n Color color;\n if(registration != NULL) {\n registration->getPointXYZRGB(mUndistorted, mRegistered, y, x, x2, y2, z2, rgb);\n const uint8_t *p = reinterpret_cast(&rgb);\n uint8_t red = p[0];\n uint8_t green = p[1];\n uint8_t blue = p[2];\n color = Color(red\/255.0f, green\/255.0f, blue\/255.0f);\n } else {\n throw Exception();\n }\n\n MeshVertex vertex(Vector3f(x2*1000, y2*1000, z2*1000));\n vertex.setColor(color);\n return vertex;\n}\n\nvoid KinectStreamer::producerStream() {\n reportInfo() << \"Trying to set up kinect stream...\" << reportEnd();\n libfreenect2::Freenect2 freenect2;\n libfreenect2::Freenect2Device *dev = 0;\n libfreenect2::PacketPipeline *pipeline = 0;\n std::string serial = \"\";\n\n int nrOfDevices = freenect2.enumerateDevices();\n if(nrOfDevices == 0) {\n throw Exception(\"Unable to find any Kinect devices\");\n }\n if(!mInitialized) {\n for(int i = 0; i < nrOfDevices; ++i) {\n mAvailableDevices.push(freenect2.getDeviceSerialNumber(i));\n }\n mInitialized = true;\n }\n if(mAvailableDevices.empty()) {\n throw Exception(\"No more available kinect devices for KinectStreamer\");\n } else {\n \/\/ Select first\n serial = mAvailableDevices.top();\n mAvailableDevices.pop();\n }\n\n reportInfo() << \"Using kinect device with serial: \" << serial << reportEnd();\n pipeline = new libfreenect2::OpenGLPacketPipeline();\n dev = freenect2.openDevice(serial, pipeline);\n\n int types = libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;\n libfreenect2::SyncMultiFrameListener listener(types);\n libfreenect2::FrameMap frames;\n dev->setColorFrameListener(&listener);\n dev->setIrAndDepthFrameListener(&listener);\n\n if(!dev->start())\n throw Exception(\"Failed to start Kinect device streaming\");\n\n reportInfo() << \"Kinect device serial: \" << dev->getSerialNumber() << reportEnd();\n reportInfo() << \"Kinect device firmware: \" << dev->getFirmwareVersion() << reportEnd();\n\n registration = new libfreenect2::Registration(dev->getIrCameraParams(),\n dev->getColorCameraParams());\n libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);\n\n while(true) {\n {\n \/\/ Check if stop signal is sent\n std::unique_lock lock(mStopMutex);\n if(mStop) {\n mStreamIsStarted = false;\n mFirstFrameIsInserted = false;\n mHasReachedEnd = false;\n break;\n }\n }\n if(!listener.waitForNewFrame(frames, 10 * 1000)) { \/\/ 10 seconds\n throw Exception(\"Kinect streaming timeout\");\n }\n libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];\n libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];\n libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];\n\n registration->apply(rgb, depth, &undistorted, ®istered);\n mUndistorted = &undistorted;\n mRegistered = ®istered;\n\n auto * depth_data = (float*)undistorted.data;\n auto * rgb_data = (unsigned char*)registered.data;\n\n Image::pointer depthImage = Image::New();\n depthImage->create(512, 424, TYPE_FLOAT, 1, depth_data);\n\n if(rgb->format == libfreenect2::Frame::Format::BGRX) {\n \/\/ Have to swap B and R channel\n for(int i = 0; i < 512*424; ++i) {\n uchar blue = rgb_data[i*4];\n rgb_data[i*4] = rgb_data[i*4+2];\n rgb_data[i*4+2] = blue;\n }\n }\n\n auto rgbImage = Image::New();\n rgbImage->create(512, 424, TYPE_UINT8, 4, rgb_data);\n auto imageAccess = rgbImage->getImageAccess(ACCESS_READ_WRITE);\n uchar* rgb_data2 = (uchar*)imageAccess->get();\n auto depthAccess = depthImage->getImageAccess(ACCESS_READ_WRITE);\n float* depth_data2 = (float*)depthAccess->get();\n\n \/\/ Create point cloud\n std::vector points;\n for(int r=0; r<424; ++r) { \/\/ y\n for(int c = 0; c < 512; ++c) { \/\/ x\n \/\/ Flip image horizontally\n if(c < 512\/2) {\n for(uchar i = 0; i < 3; i++) {\n std::swap(rgb_data2[(c + r * 512) * 4 + i], rgb_data2[(512 - c - 1 + r * 512) * 4 + i]);\n }\n std::swap(depth_data2[(c + r * 512)], depth_data2[(512 - c - 1 + r * 512)]);\n }\n float x, y, z, color;\n registration->getPointXYZRGB(&undistorted, ®istered, r, c, x, y, z, color);\n if(z < mMinRange || z > mMaxRange) {\n continue;\n }\n if(!std::isnan(x)) {\n \/\/ for each valid neigbhor; is the depth similar\n if(mPointCloudFilterEnabled) {\n int invalidNeighbors = 0;\n const int size = 1;\n for(int a = -size; a <= size; ++a) {\n for(int b = -size; b <= size; ++b) {\n if(r + a < 0 || r + a >= 424 || c + b < 0 || c + b >= 512)\n continue;\n float x2, y2, z2, color2;\n registration->getPointXYZRGB(&undistorted, ®istered, r + a, c + b, x2, y2, z2,\n color2);\n if(std::isnan(x2))\n invalidNeighbors++;\n if(fabs(z - z2) * 1000 > 10)\n invalidNeighbors++;\n\n }\n }\n if (invalidNeighbors > 0)\n continue;\n }\n\n \/\/ Decode color channels\n const uint8_t *p = reinterpret_cast(&color);\n uint8_t red = p[0];\n uint8_t green = p[1];\n uint8_t blue = p[2];\n MeshVertex point(Vector3f(-x*1000, y*1000, z*1000)); \/\/ Flip x\n point.setColor(Color(red\/255.0f, green\/255.0f, blue\/255.0f));\n points.push_back(point);\n }\n }\n }\n auto cloud = Mesh::New();\n cloud->create(points);\n imageAccess->release();\n depthAccess->release();\n\n addOutputData(0, rgbImage);\n addOutputData(1, depthImage);\n addOutputData(2, cloud);\n if(!mFirstFrameIsInserted) {\n {\n std::lock_guard lock(mFirstFrameMutex);\n mFirstFrameIsInserted = true;\n }\n mFirstFrameCondition.notify_one();\n }\n mNrOfFrames++;\n listener.release(frames);\n }\n\n dev->stop();\n dev->close();\n delete dev;\n reportInfo() << \"Kinect streamer stopped\" << Reporter::end();\n mAvailableDevices.push(serial); \/\/ Adding streamer back to queue\n}\n\nbool KinectStreamer::hasReachedEnd() {\n return mHasReachedEnd;\n}\n\nuint KinectStreamer::getNrOfFrames() const {\n return mNrOfFrames;\n}\n\nKinectStreamer::~KinectStreamer() {\n if(mStreamIsStarted) {\n stop();\n mThread->join();\n }\n}\n\nvoid KinectStreamer::stop() {\n std::unique_lock lock(mStopMutex);\n reportInfo() << \"Stopping kinect streamer\" << Reporter::end();\n mStop = true;\n}\n\nvoid KinectStreamer::setMaxRange(float range) {\n if(range < 0)\n throw Exception(\"Range has to be >= 0\");\n mMaxRange = range;\n}\n\nvoid KinectStreamer::setMinRange(float range) {\n if(range < 0)\n throw Exception(\"Range has to be >= 0\");\n mMinRange = range;\n}\n\n}fixed KinectStreamer::getPoint due to flipping#include \"KinectStreamer.hpp\"\n#include \n#include \n#include \n#include \"FAST\/Data\/Image.hpp\"\n#include \"FAST\/Data\/Mesh.hpp\"\n\nnamespace fast {\n\n\nbool KinectStreamer::mInitialized = false;\nstd::stack KinectStreamer::mAvailableDevices;\n\nKinectStreamer::KinectStreamer() {\n createOutputPort(0); \/\/ RGB\n createOutputPort(1); \/\/ Depth image\n createOutputPort(2); \/\/ Point cloud\n mNrOfFrames = 0;\n mHasReachedEnd = false;\n mFirstFrameIsInserted = false;\n mStreamIsStarted = false;\n mIsModified = true;\n mPointCloudFilterEnabled = false;\n registration = NULL;\n}\n\nvoid KinectStreamer::setPointCloudFiltering(bool enabled) {\n mPointCloudFilterEnabled = enabled;\n}\n\nvoid KinectStreamer::execute() {\n if(!mStreamIsStarted) {\n \/\/ Check that first frame exists before starting streamer\n\n mStreamIsStarted = true;\n mStop = false;\n mThread = new std::thread(std::bind(&KinectStreamer::producerStream, this));\n }\n\n \/\/ Wait here for first frame\n std::unique_lock lock(mFirstFrameMutex);\n while(!mFirstFrameIsInserted) {\n mFirstFrameCondition.wait(lock);\n }\n}\n\n\nMeshVertex KinectStreamer::getPoint(int x, int y) {\n float x2, y2, z2, rgb;\n Color color;\n if(registration != NULL) {\n registration->getPointXYZRGB(mUndistorted, mRegistered, y, 512-x-1, x2, y2, z2, rgb);\n const uint8_t *p = reinterpret_cast(&rgb);\n uint8_t red = p[0];\n uint8_t green = p[1];\n uint8_t blue = p[2];\n color = Color(red\/255.0f, green\/255.0f, blue\/255.0f);\n } else {\n throw Exception();\n }\n\n MeshVertex vertex(Vector3f(-x2*1000, y2*1000, z2*1000));\n vertex.setColor(color);\n return vertex;\n}\n\nvoid KinectStreamer::producerStream() {\n reportInfo() << \"Trying to set up kinect stream...\" << reportEnd();\n libfreenect2::Freenect2 freenect2;\n libfreenect2::Freenect2Device *dev = 0;\n libfreenect2::PacketPipeline *pipeline = 0;\n std::string serial = \"\";\n\n int nrOfDevices = freenect2.enumerateDevices();\n if(nrOfDevices == 0) {\n throw Exception(\"Unable to find any Kinect devices\");\n }\n if(!mInitialized) {\n for(int i = 0; i < nrOfDevices; ++i) {\n mAvailableDevices.push(freenect2.getDeviceSerialNumber(i));\n }\n mInitialized = true;\n }\n if(mAvailableDevices.empty()) {\n throw Exception(\"No more available kinect devices for KinectStreamer\");\n } else {\n \/\/ Select first\n serial = mAvailableDevices.top();\n mAvailableDevices.pop();\n }\n\n reportInfo() << \"Using kinect device with serial: \" << serial << reportEnd();\n pipeline = new libfreenect2::OpenGLPacketPipeline();\n dev = freenect2.openDevice(serial, pipeline);\n\n int types = libfreenect2::Frame::Color | libfreenect2::Frame::Ir | libfreenect2::Frame::Depth;\n libfreenect2::SyncMultiFrameListener listener(types);\n libfreenect2::FrameMap frames;\n dev->setColorFrameListener(&listener);\n dev->setIrAndDepthFrameListener(&listener);\n\n if(!dev->start())\n throw Exception(\"Failed to start Kinect device streaming\");\n\n reportInfo() << \"Kinect device serial: \" << dev->getSerialNumber() << reportEnd();\n reportInfo() << \"Kinect device firmware: \" << dev->getFirmwareVersion() << reportEnd();\n\n registration = new libfreenect2::Registration(dev->getIrCameraParams(),\n dev->getColorCameraParams());\n libfreenect2::Frame undistorted(512, 424, 4), registered(512, 424, 4);\n\n while(true) {\n {\n \/\/ Check if stop signal is sent\n std::unique_lock lock(mStopMutex);\n if(mStop) {\n mStreamIsStarted = false;\n mFirstFrameIsInserted = false;\n mHasReachedEnd = false;\n break;\n }\n }\n if(!listener.waitForNewFrame(frames, 10 * 1000)) { \/\/ 10 seconds\n throw Exception(\"Kinect streaming timeout\");\n }\n libfreenect2::Frame *rgb = frames[libfreenect2::Frame::Color];\n libfreenect2::Frame *ir = frames[libfreenect2::Frame::Ir];\n libfreenect2::Frame *depth = frames[libfreenect2::Frame::Depth];\n\n registration->apply(rgb, depth, &undistorted, ®istered);\n mUndistorted = &undistorted;\n mRegistered = ®istered;\n\n auto * depth_data = (float*)undistorted.data;\n auto * rgb_data = (unsigned char*)registered.data;\n\n Image::pointer depthImage = Image::New();\n depthImage->create(512, 424, TYPE_FLOAT, 1, depth_data);\n\n if(rgb->format == libfreenect2::Frame::Format::BGRX) {\n \/\/ Have to swap B and R channel\n for(int i = 0; i < 512*424; ++i) {\n uchar blue = rgb_data[i*4];\n rgb_data[i*4] = rgb_data[i*4+2];\n rgb_data[i*4+2] = blue;\n }\n }\n\n auto rgbImage = Image::New();\n rgbImage->create(512, 424, TYPE_UINT8, 4, rgb_data);\n auto imageAccess = rgbImage->getImageAccess(ACCESS_READ_WRITE);\n uchar* rgb_data2 = (uchar*)imageAccess->get();\n auto depthAccess = depthImage->getImageAccess(ACCESS_READ_WRITE);\n float* depth_data2 = (float*)depthAccess->get();\n\n \/\/ Create point cloud\n std::vector points;\n for(int r=0; r<424; ++r) { \/\/ y\n for(int c = 0; c < 512; ++c) { \/\/ x\n \/\/ Flip image horizontally\n if(c < 512\/2) {\n for(uchar i = 0; i < 3; i++) {\n std::swap(rgb_data2[(c + r * 512) * 4 + i], rgb_data2[(512 - c - 1 + r * 512) * 4 + i]);\n }\n std::swap(depth_data2[(c + r * 512)], depth_data2[(512 - c - 1 + r * 512)]);\n }\n float x, y, z, color;\n registration->getPointXYZRGB(&undistorted, ®istered, r, c, x, y, z, color);\n if(z < mMinRange || z > mMaxRange) {\n continue;\n }\n if(!std::isnan(x)) {\n \/\/ for each valid neigbhor; is the depth similar\n if(mPointCloudFilterEnabled) {\n int invalidNeighbors = 0;\n const int size = 1;\n for(int a = -size; a <= size; ++a) {\n for(int b = -size; b <= size; ++b) {\n if(r + a < 0 || r + a >= 424 || c + b < 0 || c + b >= 512)\n continue;\n float x2, y2, z2, color2;\n registration->getPointXYZRGB(&undistorted, ®istered, r + a, c + b, x2, y2, z2,\n color2);\n if(std::isnan(x2))\n invalidNeighbors++;\n if(fabs(z - z2) * 1000 > 10)\n invalidNeighbors++;\n\n }\n }\n if (invalidNeighbors > 0)\n continue;\n }\n\n \/\/ Decode color channels\n const uint8_t *p = reinterpret_cast(&color);\n uint8_t red = p[0];\n uint8_t green = p[1];\n uint8_t blue = p[2];\n MeshVertex point(Vector3f(-x*1000, y*1000, z*1000)); \/\/ Flip x\n point.setColor(Color(red\/255.0f, green\/255.0f, blue\/255.0f));\n points.push_back(point);\n }\n }\n }\n auto cloud = Mesh::New();\n cloud->create(points);\n imageAccess->release();\n depthAccess->release();\n\n addOutputData(0, rgbImage);\n addOutputData(1, depthImage);\n addOutputData(2, cloud);\n if(!mFirstFrameIsInserted) {\n {\n std::lock_guard lock(mFirstFrameMutex);\n mFirstFrameIsInserted = true;\n }\n mFirstFrameCondition.notify_one();\n }\n mNrOfFrames++;\n listener.release(frames);\n }\n\n dev->stop();\n dev->close();\n delete dev;\n reportInfo() << \"Kinect streamer stopped\" << Reporter::end();\n mAvailableDevices.push(serial); \/\/ Adding streamer back to queue\n}\n\nbool KinectStreamer::hasReachedEnd() {\n return mHasReachedEnd;\n}\n\nuint KinectStreamer::getNrOfFrames() const {\n return mNrOfFrames;\n}\n\nKinectStreamer::~KinectStreamer() {\n if(mStreamIsStarted) {\n stop();\n mThread->join();\n }\n}\n\nvoid KinectStreamer::stop() {\n std::unique_lock lock(mStopMutex);\n reportInfo() << \"Stopping kinect streamer\" << Reporter::end();\n mStop = true;\n}\n\nvoid KinectStreamer::setMaxRange(float range) {\n if(range < 0)\n throw Exception(\"Range has to be >= 0\");\n mMaxRange = range;\n}\n\nvoid KinectStreamer::setMinRange(float range) {\n if(range < 0)\n throw Exception(\"Range has to be >= 0\");\n mMinRange = range;\n}\n\n}<|endoftext|>"} {"text":"#include \"compiler\/build_tables\/build_parse_table.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"compiler\/prepared_grammar.h\"\n#include \"compiler\/rules\/built_in_symbols.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/build_tables\/parse_conflict_manager.h\"\n#include \"compiler\/build_tables\/parse_item.h\"\n#include \"compiler\/build_tables\/item_set_closure.h\"\n#include \"compiler\/build_tables\/item_set_transitions.h\"\n\nnamespace tree_sitter {\n using std::pair;\n using std::string;\n using std::vector;\n using std::set;\n using std::unordered_map;\n using std::make_shared;\n using rules::Symbol;\n\n namespace build_tables {\n class ParseTableBuilder {\n const PreparedGrammar grammar;\n ParseConflictManager conflict_manager;\n unordered_map parse_state_ids;\n SymTransitions sym_transitions;\n ParseTable parse_table;\n\n ParseStateId add_parse_state(const ParseItemSet &item_set) {\n auto pair = parse_state_ids.find(item_set);\n if (pair == parse_state_ids.end()) {\n ParseStateId state_id = parse_table.add_state();\n parse_state_ids[item_set] = state_id;\n add_shift_actions(item_set, state_id);\n add_reduce_actions(item_set, state_id);\n return state_id;\n } else {\n return pair->second;\n }\n }\n\n void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &transition : sym_transitions(item_set, grammar)) {\n const Symbol &symbol = transition.first;\n const ParseItemSet &item_set = transition.second;\n auto &actions = parse_table.states[state_id].actions;\n auto current_action = actions.find(symbol);\n\n set precedence_values = precedence_values_for_item_set(item_set);\n if (current_action == actions.end() ||\n conflict_manager.resolve_parse_action(symbol, current_action->second, ParseAction::Shift(0, precedence_values))) {\n ParseStateId new_state_id = add_parse_state(item_set);\n parse_table.add_action(state_id, symbol, ParseAction::Shift(new_state_id, precedence_values));\n }\n }\n\n for (const Symbol &symbol : grammar.options.ubiquitous_tokens) {\n auto &actions = parse_table.states[state_id].actions;\n if (actions.find(symbol) == actions.end())\n parse_table.add_action(state_id, symbol, ParseAction::Shift(state_id, { 0 }));\n }\n }\n\n void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const ParseItem &item : item_set) {\n if (item.is_done()) {\n ParseAction action = (item.lhs == rules::START()) ?\n ParseAction::Accept() :\n ParseAction::Reduce(item.lhs, item.consumed_symbol_count, item.precedence());\n auto current_actions = parse_table.states[state_id].actions;\n auto current_action = current_actions.find(item.lookahead_sym);\n\n if (current_action == current_actions.end() ||\n conflict_manager.resolve_parse_action(item.lookahead_sym, current_action->second, action)) {\n parse_table.add_action(state_id, item.lookahead_sym, action);\n }\n }\n }\n }\n\n set precedence_values_for_item_set(const ParseItemSet &item_set) {\n set result;\n for (const auto &item : item_set)\n if (item.consumed_symbol_count > 0)\n result.insert(item.precedence());\n return result;\n }\n\n public:\n ParseTableBuilder(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) :\n grammar(grammar),\n conflict_manager(ParseConflictManager(grammar, lex_grammar)) {}\n\n pair> build() {\n ParseItem start_item(rules::START(), make_shared(0), 0, rules::END_OF_INPUT());\n add_parse_state(item_set_closure(start_item, grammar));\n return { parse_table, conflict_manager.conflicts() };\n }\n };\n\n pair>\n build_parse_table(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) {\n return ParseTableBuilder(grammar, lex_grammar).build();\n }\n }\n}\nCleanup - extract method in parse table builder#include \"compiler\/build_tables\/build_parse_table.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"compiler\/prepared_grammar.h\"\n#include \"compiler\/rules\/built_in_symbols.h\"\n#include \"compiler\/rules\/symbol.h\"\n#include \"compiler\/build_tables\/parse_conflict_manager.h\"\n#include \"compiler\/build_tables\/parse_item.h\"\n#include \"compiler\/build_tables\/item_set_closure.h\"\n#include \"compiler\/build_tables\/item_set_transitions.h\"\n\nnamespace tree_sitter {\n using std::pair;\n using std::string;\n using std::vector;\n using std::set;\n using std::unordered_map;\n using std::make_shared;\n using rules::Symbol;\n\n namespace build_tables {\n class ParseTableBuilder {\n const PreparedGrammar grammar;\n ParseConflictManager conflict_manager;\n unordered_map parse_state_ids;\n SymTransitions sym_transitions;\n ParseTable parse_table;\n\n ParseStateId add_parse_state(const ParseItemSet &item_set) {\n auto pair = parse_state_ids.find(item_set);\n if (pair == parse_state_ids.end()) {\n ParseStateId state_id = parse_table.add_state();\n parse_state_ids[item_set] = state_id;\n add_shift_actions(item_set, state_id);\n add_ubiquitous_token_actions(item_set, state_id);\n add_reduce_actions(item_set, state_id);\n return state_id;\n } else {\n return pair->second;\n }\n }\n\n void add_shift_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const auto &transition : sym_transitions(item_set, grammar)) {\n const Symbol &symbol = transition.first;\n const ParseItemSet &item_set = transition.second;\n auto &actions = parse_table.states[state_id].actions;\n auto current_action = actions.find(symbol);\n\n set precedence_values = precedence_values_for_item_set(item_set);\n if (current_action == actions.end() ||\n conflict_manager.resolve_parse_action(symbol, current_action->second, ParseAction::Shift(0, precedence_values))) {\n ParseStateId new_state_id = add_parse_state(item_set);\n parse_table.add_action(state_id, symbol, ParseAction::Shift(new_state_id, precedence_values));\n }\n }\n }\n \n void add_ubiquitous_token_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const Symbol &symbol : grammar.options.ubiquitous_tokens) {\n auto &actions = parse_table.states[state_id].actions;\n if (actions.find(symbol) == actions.end())\n parse_table.add_action(state_id, symbol, ParseAction::Shift(state_id, { 0 }));\n }\n }\n\n void add_reduce_actions(const ParseItemSet &item_set, ParseStateId state_id) {\n for (const ParseItem &item : item_set) {\n if (item.is_done()) {\n ParseAction action = (item.lhs == rules::START()) ?\n ParseAction::Accept() :\n ParseAction::Reduce(item.lhs, item.consumed_symbol_count, item.precedence());\n auto current_actions = parse_table.states[state_id].actions;\n auto current_action = current_actions.find(item.lookahead_sym);\n\n if (current_action == current_actions.end() ||\n conflict_manager.resolve_parse_action(item.lookahead_sym, current_action->second, action)) {\n parse_table.add_action(state_id, item.lookahead_sym, action);\n }\n }\n }\n }\n\n set precedence_values_for_item_set(const ParseItemSet &item_set) {\n set result;\n for (const auto &item : item_set)\n if (item.consumed_symbol_count > 0)\n result.insert(item.precedence());\n return result;\n }\n\n public:\n ParseTableBuilder(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) :\n grammar(grammar),\n conflict_manager(ParseConflictManager(grammar, lex_grammar)) {}\n\n pair> build() {\n ParseItem start_item(rules::START(), make_shared(0), 0, rules::END_OF_INPUT());\n add_parse_state(item_set_closure(start_item, grammar));\n return { parse_table, conflict_manager.conflicts() };\n }\n };\n\n pair>\n build_parse_table(const PreparedGrammar &grammar, const PreparedGrammar &lex_grammar) {\n return ParseTableBuilder(grammar, lex_grammar).build();\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"autocomplete_api.h\"\n#include \"type\/pb_converter.h\"\n#include \n\nnamespace navitia { namespace autocomplete {\n\/**\n * se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre\n *\n *\/\nvoid create_pb(const std::vector::fl_quality>& result,\n const nt::Type_e type, uint32_t depth, const nt::Data& data,\n pbnavitia::Autocomplete& pb_fl){\n for(auto result_item : result){\n pbnavitia::AutocompleteItem* item = pb_fl.add_items();\n pbnavitia::PlaceMark* place_mark = item->mutable_object();\n switch(type){\n case nt::Type_e::StopArea:\n place_mark->set_type(pbnavitia::STOP_AREA);\n fill_pb_object(result_item.idx, data, place_mark->mutable_stop_area(), depth);\n item->set_name(data.pt_data.stop_areas[result_item.idx].name);\n item->set_uri(data.pt_data.stop_areas[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::City:\n place_mark->set_type(pbnavitia::CITY);\n fill_pb_object(result_item.idx, data, place_mark->mutable_city(), depth);\n item->set_name(data.pt_data.cities[result_item.idx].name);\n item->set_uri(data.pt_data.cities[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::StopPoint:\n place_mark->set_type(pbnavitia::STOP_POINT);\n fill_pb_object(result_item.idx, data, place_mark->mutable_stop_point(), depth);\n item->set_name(data.pt_data.stop_points[result_item.idx].name);\n item->set_uri(data.pt_data.stop_points[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::Address:\n place_mark->set_type(pbnavitia::ADDRESS);\n \/\/fill_pb_object(result_item.idx, data, place_mark->mutable_way(), 2);\n fill_pb_object(result_item.idx, data, place_mark->mutable_address(), result_item.house_number,result_item.coord, depth);\n item->set_name(data.geo_ref.ways[result_item.idx].name);\n item->set_uri(data.geo_ref.ways[result_item.idx].uri+\":\"+boost::lexical_cast(result_item.house_number));\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::POI:\n place_mark->set_type(pbnavitia::POI);\n fill_pb_object(result_item.idx, data, place_mark->mutable_poi(), 2);\n item->set_name(data.geo_ref.pois[result_item.idx].name);\n item->set_uri(data.geo_ref.pois[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n default:\n break;\n }\n }\n}\n\nint penalty_by_type(navitia::type::Type_e ntype, bool Is_address_type) {\n \/\/ Ordre de tri :\n \/\/ Add, SA, POI, SP, City : si présence de addressType dans le recherche\n \/\/ City, SA, POI, Add, SP : si non\n int result = 0;\n switch(ntype){\n case navitia::type::Type_e::City:\n result = Is_address_type ? 8 : 0;\n break;\n case navitia::type::Type_e::StopArea:\n result = 2;\n break;\n case navitia::type::Type_e::POI:\n result = 4;\n break;\n case navitia::type::Type_e::Address:\n result = Is_address_type ? 0 : 6;\n break;\n case navitia::type::Type_e::StopPoint:\n result = 8;\n result = Is_address_type ? 6 : 8;\n break;\n default:\n break;\n }\n return result;\n}\n\nvoid Update_quality(std::vector::fl_quality>& ac_result, navitia::type::Type_e ntype, bool Is_address_type){\n \/\/Mettre à jour la qualité sur la pénalité par type\n int penalty = penalty_by_type(ntype, Is_address_type);\n for(auto &item : ac_result){\n item.quality -= penalty;\n }\n}\n\n\npbnavitia::Response autocomplete(const std::string &name,\n const std::vector &filter,\n uint32_t depth,\n uint32_t nbmax,\n const navitia::type::Data &d){\n\n pbnavitia::Response pb_response;\n pb_response.set_requested_api(pbnavitia::AUTOCOMPLETE);\n\n bool addType = d.pt_data.stop_area_autocomplete.is_address_type(name, d.geo_ref.alias, d.geo_ref.synonymes);\n std::vector::fl_quality> result;\n pbnavitia::Autocomplete* pb = pb_response.mutable_autocomplete();\n BOOST_FOREACH(nt::Type_e type, filter){\n switch(type){\n case nt::Type_e::StopArea:\n result = d.pt_data.stop_area_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::StopPoint:\n result = d.pt_data.stop_point_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::City:\n result = d.pt_data.city_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::Address:\n \/\/result = d.geo_ref.fl.find_complete(name);\n result = d.geo_ref.find_ways(name);\n break;\n case nt::Type_e::POI:\n result = d.geo_ref.fl_poi.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n default: break;\n }\n\n if (result.size() > nbmax){result.resize(nbmax);}\n Update_quality(result, type, addType);\n\n create_pb(result, type, depth, d, *pb);\n }\n return pb_response;\n}\n\n}} \/\/namespace navitia::autocomplete\nAutocompletion : retrier la liste de réponse limiter sa taille.#include \"autocomplete_api.h\"\n#include \"type\/pb_converter.h\"\n#include \n\nnamespace navitia { namespace autocomplete {\n\/**\n * se charge de remplir l'objet protocolbuffer autocomplete passé en paramètre\n *\n *\/\nvoid create_pb(const std::vector::fl_quality>& result,\n const nt::Type_e type, uint32_t depth, const nt::Data& data,\n pbnavitia::Autocomplete& pb_fl){\n for(auto result_item : result){\n pbnavitia::AutocompleteItem* item = pb_fl.add_items();\n pbnavitia::PlaceMark* place_mark = item->mutable_object();\n switch(type){\n case nt::Type_e::StopArea:\n place_mark->set_type(pbnavitia::STOP_AREA);\n fill_pb_object(result_item.idx, data, place_mark->mutable_stop_area(), depth);\n item->set_name(data.pt_data.stop_areas[result_item.idx].name);\n item->set_uri(data.pt_data.stop_areas[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::City:\n place_mark->set_type(pbnavitia::CITY);\n fill_pb_object(result_item.idx, data, place_mark->mutable_city(), depth);\n item->set_name(data.pt_data.cities[result_item.idx].name);\n item->set_uri(data.pt_data.cities[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::StopPoint:\n place_mark->set_type(pbnavitia::STOP_POINT);\n fill_pb_object(result_item.idx, data, place_mark->mutable_stop_point(), depth);\n item->set_name(data.pt_data.stop_points[result_item.idx].name);\n item->set_uri(data.pt_data.stop_points[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::Address:\n place_mark->set_type(pbnavitia::ADDRESS);\n \/\/fill_pb_object(result_item.idx, data, place_mark->mutable_way(), 2);\n fill_pb_object(result_item.idx, data, place_mark->mutable_address(), result_item.house_number,result_item.coord, depth);\n item->set_name(data.geo_ref.ways[result_item.idx].name);\n item->set_uri(data.geo_ref.ways[result_item.idx].uri+\":\"+boost::lexical_cast(result_item.house_number));\n item->set_quality(result_item.quality);\n break;\n case nt::Type_e::POI:\n place_mark->set_type(pbnavitia::POI);\n fill_pb_object(result_item.idx, data, place_mark->mutable_poi(), 2);\n item->set_name(data.geo_ref.pois[result_item.idx].name);\n item->set_uri(data.geo_ref.pois[result_item.idx].uri);\n item->set_quality(result_item.quality);\n break;\n default:\n break;\n }\n }\n}\n\nint penalty_by_type(navitia::type::Type_e ntype, bool Is_address_type) {\n \/\/ Ordre de tri :\n \/\/ Add, SA, POI, SP, City : si présence de addressType dans le recherche\n \/\/ City, SA, POI, Add, SP : si non\n int result = 0;\n switch(ntype){\n case navitia::type::Type_e::City:\n result = Is_address_type ? 8 : 0;\n break;\n case navitia::type::Type_e::StopArea:\n result = 2;\n break;\n case navitia::type::Type_e::POI:\n result = 4;\n break;\n case navitia::type::Type_e::Address:\n result = Is_address_type ? 0 : 6;\n break;\n case navitia::type::Type_e::StopPoint:\n result = 8;\n result = Is_address_type ? 6 : 8;\n break;\n default:\n break;\n }\n return result;\n}\n\nvoid Update_quality(std::vector::fl_quality>& ac_result, navitia::type::Type_e ntype, bool Is_address_type){\n \/\/Mettre à jour la qualité sur la pénalité par type\n int penalty = penalty_by_type(ntype, Is_address_type);\n for(auto &item : ac_result){\n item.quality -= penalty;\n }\n}\n\n\npbnavitia::Response autocomplete(const std::string &name,\n const std::vector &filter,\n uint32_t depth,\n uint32_t nbmax,\n const navitia::type::Data &d){\n\n pbnavitia::Response pb_response;\n pb_response.set_requested_api(pbnavitia::AUTOCOMPLETE);\n\n bool addType = d.pt_data.stop_area_autocomplete.is_address_type(name, d.geo_ref.alias, d.geo_ref.synonymes);\n std::vector::fl_quality> result;\n pbnavitia::Autocomplete* pb = pb_response.mutable_autocomplete();\n BOOST_FOREACH(nt::Type_e type, filter){\n switch(type){\n case nt::Type_e::StopArea:\n result = d.pt_data.stop_area_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::StopPoint:\n result = d.pt_data.stop_point_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::City:\n result = d.pt_data.city_autocomplete.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n break;\n case nt::Type_e::Address:\n \/\/result = d.geo_ref.fl.find_complete(name);\n result = d.geo_ref.find_ways(name);\n break;\n case nt::Type_e::POI:\n result = d.geo_ref.fl_poi.find_complete(name, d.geo_ref.alias, d.geo_ref.synonymes, d.geo_ref.word_weight);\n default: break;\n }\n\n if (result.size() > nbmax){result.resize(nbmax);}\n Update_quality(result, type, addType);\n\n create_pb(result, type, depth, d, *pb);\n }\n\n auto compare = [](pbnavitia::AutocompleteItem a, pbnavitia::AutocompleteItem b){\n return a.quality() > b.quality();\n };\n\n std::sort(pb_response.mutable_autocomplete()->mutable_items()->begin(), pb_response.mutable_autocomplete()->mutable_items()->end(),compare);\n\n while (pb_response.mutable_autocomplete()->mutable_items()->size() > nbmax){\n pb_response.mutable_autocomplete()->mutable_items()->RemoveLast();\n }\n\n return pb_response;\n}\n\n}} \/\/namespace navitia::autocomplete\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/\/\/ \\file urbi\/uvalue.hh\n#ifndef URBI_UVALUE_HH\n# define URBI_UVALUE_HH\n\n# include \n\n# include \n\n# include \n# include \n# include \n\n# include \n# include \n# include \n\nnamespace urbi\n{\n\n \/\/ UValue and other related types\n\n \/\/\/ Possible value types a UValue can contain.\n enum UDataType\n {\n DATA_BINARY,\n DATA_DICTIONARY,\n DATA_DOUBLE,\n DATA_LIST,\n DATA_OBJECT,\n DATA_STRING,\n DATA_VOID\n };\n\n \/*--------.\n | UList. |\n `--------*\/\n\n \/\/\/ Class storing URBI List type\n class URBI_SDK_API UList\n {\n public:\n UList();\n UList(const UList &b);\n ~UList();\n\n UList& operator=(const UList &b);\n\n \/\/ Assign a container to the UList\n template\n UList& operator=(const T& container);\n\n UList& operator=(UVar& v);\n\n \/\/ Transform the UList to a container.\n template\n T as();\n\n \/\/ Append an element to the end.\n template\n UList&\n push_back(const T& v);\n\n void pop_back();\n\n UValue& front();\n\n UValue& operator[](size_t i);\n const UValue& operator[](size_t i) const;\n\n size_t size() const;\n void setOffset(size_t n);\n\n std::ostream& print(std::ostream& o) const;\n\n \/\/ The actual contents.\n std::vector array;\n\n private:\n void clear();\n size_t offset;\n };\n\n URBI_SDK_API\n std::ostream& operator<< (std::ostream& o, const UList& t);\n\n\n \/*--------------.\n | UDictionary. |\n `--------------*\/\n typedef boost::unordered_map UDictionary;\n\n\n \/*--------------.\n | UNamedValue. |\n `--------------*\/\n\n class URBI_SDK_API UNamedValue\n {\n public:\n UNamedValue(const std::string& n = \"\", UValue* v = 0);\n \/\/ Used on errors.\n static UNamedValue& error();\n std::string name;\n UValue* val;\n };\n\n\n \/*----------------.\n | UObjectStruct. |\n `----------------*\/\n\n class URBI_SDK_API UObjectStruct\n {\n public:\n UObjectStruct();\n UObjectStruct(const UObjectStruct &b);\n UObjectStruct& operator=(const UObjectStruct &b);\n ~UObjectStruct();\n\n \/\/\/ Return UValue::error() on errors.\n UValue& operator[](const std::string& s);\n\n \/\/\/ Return UNamedValue::error() on errors.\n const UNamedValue& operator[](size_t i) const;\n UNamedValue& operator [](size_t i);\n\n size_t size() const;\n\n std::ostream& print(std::ostream& o) const;\n\n std::string refName;\n std::vector array;\n };\n\n URBI_SDK_API\n std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);\n\n\n \/*---------.\n | UValue. |\n `---------*\/\n\n \/** Container for a value that handles all types known to URBI.\n *\/\n class URBI_SDK_API UValue\n {\n public:\n UDataType type;\n ufloat val; \/\/\/< value if of type DATA_DOUBLE\n union\n {\n std::string* stringValue; \/\/\/< value if of type DATA_STRING\n UBinary* binary; \/\/\/< value if of type DATA_BINARY\n UList* list; \/\/\/< value if of type DATA_LIST\n UDictionary* dictionary; \/\/\/< value if of type DATA_DICTIONARY\n UObjectStruct* object; \/\/\/< value if of type DATA_OBJ\n void* storage; \/\/\/< internal\n };\n\n UValue();\n UValue(const UValue&);\n\n ~UValue();\n\n UValue& operator=(const UValue&);\n \/\/\/ Setter. If copy is false, binary data if present is not copied.\n \/\/\/ This is dangerous, as the user must ensure that the source UValue\n \/\/\/ lives longer than this one.\n UValue& set(const UValue&, bool copy=true);\n \/\/\/ Delete content and reset type to void.\n void clear();\n \/\/\/ A specific UValue used when we want to return an error.\n \/\/\/ For instance, out-of-bound access returns this object.\n static UValue& error();\n\n \/\/\/ We use an operator , that behaves like an assignment. The\n \/\/\/ only difference is when the rhs is void, in which case it is\n \/\/\/ the regular comma which is used. This allows to write \"uval,\n \/\/\/ expr\" to mean \"compute expr and assign its result to uval,\n \/\/\/ unless expr is void\".\n UValue& operator, (const UValue &b);\n\n \/\/\/ Return a legible definition of UDataType\n const char* format_string() const;\n\n#define CTOR_AND_ASSIGN_AND_COMMA(Type)\t\t\\\n explicit UValue(Type, bool copy=true);\t\\\n UValue& operator=(Type);\t\t\t\\\n UValue& operator,(Type rhs)\n\n \/\/ UFloats.\n CTOR_AND_ASSIGN_AND_COMMA(ufloat);\n CTOR_AND_ASSIGN_AND_COMMA(int);\n CTOR_AND_ASSIGN_AND_COMMA(long);\n CTOR_AND_ASSIGN_AND_COMMA(unsigned int);\n CTOR_AND_ASSIGN_AND_COMMA(unsigned long);\n\n \/\/ Strings.\n CTOR_AND_ASSIGN_AND_COMMA(const char*);\n CTOR_AND_ASSIGN_AND_COMMA(const void*);\n CTOR_AND_ASSIGN_AND_COMMA(const std::string&);\n\n \/\/ Others.\n CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);\n CTOR_AND_ASSIGN_AND_COMMA(const UList&);\n CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);\n CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);\n CTOR_AND_ASSIGN_AND_COMMA(const USound&);\n CTOR_AND_ASSIGN_AND_COMMA(const UImage&);\n\n#undef CTOR_AND_ASSIGN_AND_COMMA\n\n operator ufloat() const;\n operator std::string() const;\n operator int() const;\n operator unsigned int() const;\n operator long() const;\n operator unsigned long() const;\n operator bool() const;\n\n \/\/\/ Accessor. Gives us an implicit operator UBinary() const\n operator const UBinary&() const;\n\n \/\/\/ Deep copy.\n operator UList() const;\n\n \/\/\/ Deep copy.\n operator UDictionary() const;\n\n \/\/\/ Shallow copy.\n operator UImage() const;\n\n \/\/\/ Shallow copy.\n operator USound() const;\n\n \/\/\/ This operator does nothing, but helps with the previous operator,.\n \/\/\/ Indeed, when writing \"uval, void_expr\", the compiler complains\n \/\/\/ about uval being evaluated for nothing. Let's have it believe\n \/\/\/ we're doing something...\n UValue& operator()();\n\n \/\/\/ Parse an uvalue in current message+pos, returns pos of end of\n \/\/\/ match -pos of error if error.\n int parse(const char* message,\n\t int pos,\n\t const std::list& bins,\n\t std::list::const_iterator& binpos);\n\n \/\/\/ Print itself on \\c s, and return it.\n std::ostream& print(std::ostream& s) const;\n\n \/\/\/ Print the dictionary on \\c s and return it.\n std::ostream& dictionary_print(std::ostream& s) const;\n\n \/\/ Huge hack.\n static const bool copy = true;\n };\n\n inline\n std::ostream&\n operator<<(std::ostream& s, const UValue& v);\n\n inline\n std::ostream&\n operator<<(std::ostream& s, const UDictionary& d);\n\n\n \/*----------.\n | Casters. |\n `----------*\/\n\n \/\/ For each Type, define an operator() that casts its UValue&\n \/\/ argument into Type. We need partial specialization.\n template \n struct uvalue_caster\n {\n };\n\n \/\/ T -> UVar& if T = UVar\n \/\/ T -> T otherwise.\n template \n struct uvar_ref_traits\n {\n typedef T type;\n };\n\n template <>\n struct uvar_ref_traits\n {\n typedef UVar& type;\n };\n\n \/\/ Run the uvalue_caster on v.\n template \n typename uvar_ref_traits::type>::type\n uvalue_cast (UValue& v);\n\n} \/\/ namespace urbi\n\n# include \n\n# include \n\n#endif \/\/ ! URBI_UVALUE_HH\nRemove leftover declaration of dictionary_print.\/*\n * Copyright (C) 2007, 2008, 2009, 2010, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\n\/\/\/ \\file urbi\/uvalue.hh\n#ifndef URBI_UVALUE_HH\n# define URBI_UVALUE_HH\n\n# include \n\n# include \n\n# include \n# include \n# include \n\n# include \n# include \n# include \n\nnamespace urbi\n{\n\n \/\/ UValue and other related types\n\n \/\/\/ Possible value types a UValue can contain.\n enum UDataType\n {\n DATA_BINARY,\n DATA_DICTIONARY,\n DATA_DOUBLE,\n DATA_LIST,\n DATA_OBJECT,\n DATA_STRING,\n DATA_VOID\n };\n\n \/*--------.\n | UList. |\n `--------*\/\n\n \/\/\/ Class storing URBI List type\n class URBI_SDK_API UList\n {\n public:\n UList();\n UList(const UList &b);\n ~UList();\n\n UList& operator=(const UList &b);\n\n \/\/ Assign a container to the UList\n template\n UList& operator=(const T& container);\n\n UList& operator=(UVar& v);\n\n \/\/ Transform the UList to a container.\n template\n T as();\n\n \/\/ Append an element to the end.\n template\n UList&\n push_back(const T& v);\n\n void pop_back();\n\n UValue& front();\n\n UValue& operator[](size_t i);\n const UValue& operator[](size_t i) const;\n\n size_t size() const;\n void setOffset(size_t n);\n\n std::ostream& print(std::ostream& o) const;\n\n \/\/ The actual contents.\n std::vector array;\n\n private:\n void clear();\n size_t offset;\n };\n\n URBI_SDK_API\n std::ostream& operator<< (std::ostream& o, const UList& t);\n\n\n \/*--------------.\n | UDictionary. |\n `--------------*\/\n typedef boost::unordered_map UDictionary;\n\n\n \/*--------------.\n | UNamedValue. |\n `--------------*\/\n\n class URBI_SDK_API UNamedValue\n {\n public:\n UNamedValue(const std::string& n = \"\", UValue* v = 0);\n \/\/ Used on errors.\n static UNamedValue& error();\n std::string name;\n UValue* val;\n };\n\n\n \/*----------------.\n | UObjectStruct. |\n `----------------*\/\n\n class URBI_SDK_API UObjectStruct\n {\n public:\n UObjectStruct();\n UObjectStruct(const UObjectStruct &b);\n UObjectStruct& operator=(const UObjectStruct &b);\n ~UObjectStruct();\n\n \/\/\/ Return UValue::error() on errors.\n UValue& operator[](const std::string& s);\n\n \/\/\/ Return UNamedValue::error() on errors.\n const UNamedValue& operator[](size_t i) const;\n UNamedValue& operator [](size_t i);\n\n size_t size() const;\n\n std::ostream& print(std::ostream& o) const;\n\n std::string refName;\n std::vector array;\n };\n\n URBI_SDK_API\n std::ostream& operator<< (std::ostream& o, const UObjectStruct& t);\n\n\n \/*---------.\n | UValue. |\n `---------*\/\n\n \/** Container for a value that handles all types known to URBI.\n *\/\n class URBI_SDK_API UValue\n {\n public:\n UDataType type;\n ufloat val; \/\/\/< value if of type DATA_DOUBLE\n union\n {\n std::string* stringValue; \/\/\/< value if of type DATA_STRING\n UBinary* binary; \/\/\/< value if of type DATA_BINARY\n UList* list; \/\/\/< value if of type DATA_LIST\n UDictionary* dictionary; \/\/\/< value if of type DATA_DICTIONARY\n UObjectStruct* object; \/\/\/< value if of type DATA_OBJ\n void* storage; \/\/\/< internal\n };\n\n UValue();\n UValue(const UValue&);\n\n ~UValue();\n\n UValue& operator=(const UValue&);\n \/\/\/ Setter. If copy is false, binary data if present is not copied.\n \/\/\/ This is dangerous, as the user must ensure that the source UValue\n \/\/\/ lives longer than this one.\n UValue& set(const UValue&, bool copy=true);\n \/\/\/ Delete content and reset type to void.\n void clear();\n \/\/\/ A specific UValue used when we want to return an error.\n \/\/\/ For instance, out-of-bound access returns this object.\n static UValue& error();\n\n \/\/\/ We use an operator , that behaves like an assignment. The\n \/\/\/ only difference is when the rhs is void, in which case it is\n \/\/\/ the regular comma which is used. This allows to write \"uval,\n \/\/\/ expr\" to mean \"compute expr and assign its result to uval,\n \/\/\/ unless expr is void\".\n UValue& operator, (const UValue &b);\n\n \/\/\/ Return a legible definition of UDataType\n const char* format_string() const;\n\n#define CTOR_AND_ASSIGN_AND_COMMA(Type)\t\t\\\n explicit UValue(Type, bool copy=true);\t\\\n UValue& operator=(Type);\t\t\t\\\n UValue& operator,(Type rhs)\n\n \/\/ UFloats.\n CTOR_AND_ASSIGN_AND_COMMA(ufloat);\n CTOR_AND_ASSIGN_AND_COMMA(int);\n CTOR_AND_ASSIGN_AND_COMMA(long);\n CTOR_AND_ASSIGN_AND_COMMA(unsigned int);\n CTOR_AND_ASSIGN_AND_COMMA(unsigned long);\n\n \/\/ Strings.\n CTOR_AND_ASSIGN_AND_COMMA(const char*);\n CTOR_AND_ASSIGN_AND_COMMA(const void*);\n CTOR_AND_ASSIGN_AND_COMMA(const std::string&);\n\n \/\/ Others.\n CTOR_AND_ASSIGN_AND_COMMA(const UBinary&);\n CTOR_AND_ASSIGN_AND_COMMA(const UList&);\n CTOR_AND_ASSIGN_AND_COMMA(const UDictionary&);\n CTOR_AND_ASSIGN_AND_COMMA(const UObjectStruct&);\n CTOR_AND_ASSIGN_AND_COMMA(const USound&);\n CTOR_AND_ASSIGN_AND_COMMA(const UImage&);\n\n#undef CTOR_AND_ASSIGN_AND_COMMA\n\n operator ufloat() const;\n operator std::string() const;\n operator int() const;\n operator unsigned int() const;\n operator long() const;\n operator unsigned long() const;\n operator bool() const;\n\n \/\/\/ Accessor. Gives us an implicit operator UBinary() const\n operator const UBinary&() const;\n\n \/\/\/ Deep copy.\n operator UList() const;\n\n \/\/\/ Deep copy.\n operator UDictionary() const;\n\n \/\/\/ Shallow copy.\n operator UImage() const;\n\n \/\/\/ Shallow copy.\n operator USound() const;\n\n \/\/\/ This operator does nothing, but helps with the previous operator,.\n \/\/\/ Indeed, when writing \"uval, void_expr\", the compiler complains\n \/\/\/ about uval being evaluated for nothing. Let's have it believe\n \/\/\/ we're doing something...\n UValue& operator()();\n\n \/\/\/ Parse an uvalue in current message+pos, returns pos of end of\n \/\/\/ match -pos of error if error.\n int parse(const char* message,\n\t int pos,\n\t const std::list& bins,\n\t std::list::const_iterator& binpos);\n\n \/\/\/ Print itself on \\c s, and return it.\n std::ostream& print(std::ostream& s) const;\n\n \/\/ Huge hack.\n static const bool copy = true;\n };\n\n inline\n std::ostream&\n operator<<(std::ostream& s, const UValue& v);\n\n inline\n std::ostream&\n operator<<(std::ostream& s, const UDictionary& d);\n\n\n \/*----------.\n | Casters. |\n `----------*\/\n\n \/\/ For each Type, define an operator() that casts its UValue&\n \/\/ argument into Type. We need partial specialization.\n template \n struct uvalue_caster\n {\n };\n\n \/\/ T -> UVar& if T = UVar\n \/\/ T -> T otherwise.\n template \n struct uvar_ref_traits\n {\n typedef T type;\n };\n\n template <>\n struct uvar_ref_traits\n {\n typedef UVar& type;\n };\n\n \/\/ Run the uvalue_caster on v.\n template \n typename uvar_ref_traits::type>::type\n uvalue_cast (UValue& v);\n\n} \/\/ namespace urbi\n\n# include \n\n# include \n\n#endif \/\/ ! URBI_UVALUE_HH\n<|endoftext|>"} {"text":"\/*\n * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)\n *\n * Copyright (c) 2019 Grégory Van den Borre\n *\n * More infos available: https:\/\/engine.yildiz-games.be\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"..\/includes\/yz_ogre_vfs_Archive.hpp\"\n\nbool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {\n LOG_FUNCTION\n return PhysFS::exists(mName + '\/' + filename);\n}\n\nOgre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {\n LOG_FUNCTION\n Ogre::String fullName = mName + '\/' + filename;\n return Ogre::DataStreamPtr(new DataStream(filename, fullName));\n}\n\nvoid yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {\n LOG_FUNCTION\n Ogre::String baseDir = mName + '\/' + base;\n StringVector files = this->vfs->enumerateFiles(baseDir);\n\n Ogre::FileInfo fileInfo;\n fileInfo.archive = this;\n fileInfo.path = base;\n fileInfo.compressedSize = 0;\n\n \/\/ iterate over all files and directories in the given directory\n for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {\n fileInfo.basename = *it;\n fileInfo.filename = base + *it;\n if (this->vfs->isDirectory(*it)) {\n if (dirs) {\n fileInfo.uncompressedSize = 0;\n fileInfoList->push_back(fileInfo);\n }\n if (recursive) {\n listInfoRecursive(base + *it + '\/', recursive, dirs, fileInfoList);\n }\n } else {\n if (!dirs) {\n \/\/ get file size\n yz::physfs::File* file = new yz::physfs::File(mName + '\/' + fileInfo.filename);\n fileInfo.uncompressedSize = (size_t) file->getSize();\n file->close();\n\n fileInfoList->push_back(fileInfo);\n }\n }\n }\n }\n\nvoid yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {\n LOG_FUNCTION\n\n Ogre::String baseDir = mName + '\/' + base;\n StringVector files = this->vfs->enumerateFiles(baseDir);\n\n \/\/ iterate over all files and directories in the given directory\n for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {\n if (this->vfs->isDirectory(*it)) {\n if (dirs) {\n fileList->push_back(base + *it);\n }\n if (recursive) {\n listRecursive(base + *it + '\/', recursive, dirs, fileList);\n }\n } else {\n if (!dirs) {\n fileList->push_back(base + *it);\n }\n }\n }\n }\n\nOgre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());\n listInfoRecursive(\"\", recursive, dirs, fileInfoList);\n return fileInfoList;\n }\n\nOgre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::StringVectorPtr fileList(new Ogre::StringVector());\n listRecursive(\"\", recursive, dirs, fileList);\n return fileList;\n }\n\nOgre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::StringVectorPtr fileList = list(recursive, dirs);\n Ogre::StringVectorPtr ret(new Ogre::StringVector());\n\n for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {\n if (Ogre::StringUtil::match(*it, pattern))\n ret->push_back(*it);\n }\n return ret;\n }\n\nOgre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::FileInfoListPtr fileList = const_cast(this)->listFileInfo(recursive, dirs);\n Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());\n\n for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {\n if (Ogre::StringUtil::match(it->filename, pattern))\n ret->push_back(*it);\n }\n\n return ret;\n }\nUpdate yz_ogre_vfs_Archive.cpp\/*\n * This file is part of the Yildiz-Engine project, licenced under the MIT License (MIT)\n *\n * Copyright (c) 2019 Grégory Van den Borre\n *\n * More infos available: https:\/\/engine.yildiz-games.be\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without\n * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is furnished to do so,\n * subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial\n * portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS\n * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"..\/includes\/yz_ogre_vfs_Archive.hpp\"\n\nbool yz::ogre::vfs::Archive::exists(const Ogre::String& filename) const {\n LOG_FUNCTION\n return this->vfs->exists(mName + '\/' + filename);\n}\n\nOgre::DataStreamPtr yz::ogre::vfs::Archive::open(const Ogre::String& filename, bool append) const {\n LOG_FUNCTION\n Ogre::String fullName = mName + '\/' + filename;\n return Ogre::DataStreamPtr(new DataStream(filename, fullName));\n}\n\nvoid yz::ogre::vfs::Archive::listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const {\n LOG_FUNCTION\n Ogre::String baseDir = mName + '\/' + base;\n StringVector files = this->vfs->enumerateFiles(baseDir);\n\n Ogre::FileInfo fileInfo;\n fileInfo.archive = this;\n fileInfo.path = base;\n fileInfo.compressedSize = 0;\n\n \/\/ iterate over all files and directories in the given directory\n for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {\n fileInfo.basename = *it;\n fileInfo.filename = base + *it;\n if (this->vfs->isDirectory(*it)) {\n if (dirs) {\n fileInfo.uncompressedSize = 0;\n fileInfoList->push_back(fileInfo);\n }\n if (recursive) {\n listInfoRecursive(base + *it + '\/', recursive, dirs, fileInfoList);\n }\n } else {\n if (!dirs) {\n \/\/ get file size\n yz::physfs::File* file = new yz::physfs::File(mName + '\/' + fileInfo.filename);\n fileInfo.uncompressedSize = (size_t) file->getSize();\n file->close();\n\n fileInfoList->push_back(fileInfo);\n }\n }\n }\n }\n\nvoid yz::ogre::vfs::Archive::listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const {\n LOG_FUNCTION\n\n Ogre::String baseDir = mName + '\/' + base;\n StringVector files = this->vfs->enumerateFiles(baseDir);\n\n \/\/ iterate over all files and directories in the given directory\n for (StringVector::iterator it = files.begin(); it != files.end(); ++it) {\n if (this->vfs->isDirectory(*it)) {\n if (dirs) {\n fileList->push_back(base + *it);\n }\n if (recursive) {\n listRecursive(base + *it + '\/', recursive, dirs, fileList);\n }\n } else {\n if (!dirs) {\n fileList->push_back(base + *it);\n }\n }\n }\n }\n\nOgre::FileInfoListPtr yz::ogre::vfs::Archive::listFileInfo(bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::FileInfoListPtr fileInfoList(new Ogre::FileInfoList());\n listInfoRecursive(\"\", recursive, dirs, fileInfoList);\n return fileInfoList;\n }\n\nOgre::StringVectorPtr yz::ogre::vfs::Archive::list(bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::StringVectorPtr fileList(new Ogre::StringVector());\n listRecursive(\"\", recursive, dirs, fileList);\n return fileList;\n }\n\nOgre::StringVectorPtr yz::ogre::vfs::Archive::find(const Ogre::String& pattern, bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::StringVectorPtr fileList = list(recursive, dirs);\n Ogre::StringVectorPtr ret(new Ogre::StringVector());\n\n for (Ogre::StringVector::iterator it = fileList->begin(); it != fileList->end(); ++it) {\n if (Ogre::StringUtil::match(*it, pattern))\n ret->push_back(*it);\n }\n return ret;\n }\n\nOgre::FileInfoListPtr yz::ogre::vfs::Archive::findFileInfo(const Ogre::String& pattern, bool recursive, bool dirs) const {\n LOG_FUNCTION\n Ogre::FileInfoListPtr fileList = const_cast(this)->listFileInfo(recursive, dirs);\n Ogre::FileInfoListPtr ret(new Ogre::FileInfoList());\n\n for (Ogre::FileInfoList::iterator it = fileList->begin(); it != fileList->end(); ++it) {\n if (Ogre::StringUtil::match(it->filename, pattern))\n ret->push_back(*it);\n }\n\n return ret;\n }\n<|endoftext|>"} {"text":"\/\/ XDRStreamUnMarshaller.cc\n\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: Patrick West \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n\/\/ (c) COPYRIGHT URI\/MIT 1994-1999\n\/\/ Please read the full copyright statement in the file COPYRIGHT_URI.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West \n#include \"config.h\"\n#include \"XDRStreamUnMarshaller.h\"\n\n#include \/\/ for memcpy\n#include \n#include \n\n\/\/#define DODS_DEBUG2 1\n\/\/#define DODS_DEBUG 1\n\n#include \"Str.h\"\n\/\/ #include \"Vector.h\"\n#include \"Array.h\"\n#include \"util.h\"\n#include \"InternalErr.h\"\n#include \"debug.h\"\n\nnamespace libdap {\n\nchar *XDRStreamUnMarshaller::d_buf = 0;\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller(istream &in) : \/*&d_source( 0 ),*\/\n d_in(in)\n{\n if (!d_buf)\n d_buf = (char *) malloc(XDR_DAP_BUFF_SIZE);\n if (!d_buf)\n throw Error(internal_error, \"Failed to allocate memory for data serialization.\");\n\n \/\/&d_source = new XDR;\n xdrmem_create(&d_source, d_buf, XDR_DAP_BUFF_SIZE, XDR_DECODE);\n}\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller() :\n UnMarshaller(), \/*&d_source( 0 ),*\/d_in(cin)\n{\n throw InternalErr(__FILE__, __LINE__, \"Default constructor not implemented.\");\n}\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller(const XDRStreamUnMarshaller &um) :\n UnMarshaller(um), \/*&d_source( 0 ),*\/d_in(cin)\n{\n throw InternalErr(__FILE__, __LINE__, \"Copy constructor not implemented.\");\n}\n\nXDRStreamUnMarshaller &\nXDRStreamUnMarshaller::operator=(const XDRStreamUnMarshaller &)\n{\n throw InternalErr(__FILE__, __LINE__, \"Copy operator not implemented.\");\n\n return *this;\n}\n\nXDRStreamUnMarshaller::~XDRStreamUnMarshaller()\n{\n xdr_destroy( &d_source );\n \/\/&d_source = 0;\n}\n\nvoid XDRStreamUnMarshaller::get_byte(dods_byte &val)\n{\n if (xdr_setpos( &d_source, 0 ) < 0)\n throw Error(\"Failed to reposition input stream\");\n if (!(d_in.read(d_buf, 4))) {\n if (d_in.eof())\n throw Error(\"Premature EOF in input stream\");\n else {\n ostringstream ss(\"Error reading from input stream: \");\n ss << d_in.rdstate();\n throw Error(ss.str());\n }\n }\n\n DBG2( std::cerr << \"_in.gcount(): \" << d_in.gcount() << std::endl ); DBG2( std::cerr << \"_in.tellg(): \" << d_in.tellg() << std::endl ); DBG2( std::cerr << \"_buf[0]: \" << hex << d_buf[0] << \"; _buf[1]: \" << d_buf[1]\n << \"; _buf[2]: \" << d_buf[2] << \"; _buf[3]: \" << d_buf[3]\n << dec << std::endl );\n\n if (!xdr_char(&d_source, (char *) &val))\n throw Error(\"Network I\/O Error. Could not read byte data.\");\n\n DBG2(std::cerr << \"get_byte: \" << val << std::endl );\n}\n\nvoid XDRStreamUnMarshaller::get_int16(dods_int16 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_INT16(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read int 16 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_int32(dods_int32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_INT32(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read int 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_float32(dods_float32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!xdr_float(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read float 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_float64(dods_float64 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 8);\n\n if (!xdr_double(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read float 64 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_uint16(dods_uint16 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_UINT16(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read uint 16 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_uint32(dods_uint32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_UINT32(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read uint 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_str(string &val)\n{\n int i;\n get_int(i);\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/ Must round up string size to next 4\n i = ((i + 3) \/ 4) * 4;\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n char *in_tmp = 0;\n \/\/char *buf = 0;\n \/\/XDR *source = 0;\n \/\/ Must address the case where the string is larger than the buffer\n if (i + 4 > XDR_DAP_BUFF_SIZE) {\n#if 0\n char *buf = (char *) malloc(i + 4);\n if (!buf)\n throw InternalErr(__FILE__, __LINE__, \"Error allocating memory\");\n#endif\n vector buf(i+4);\n\n XDR source;\/\/ = new XDR;\n xdrmem_create(&source, &buf[0], i + 4, XDR_DECODE);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, i);\n\n xdr_setpos( &source, 0);\n if (!xdr_string( &source, &in_tmp, max_str_len)) {\n xdr_destroy( &source );\n throw Error(\"Network I\/O Error. Could not read string data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, i);\n\n xdr_setpos( &d_source, 0);\n if (!xdr_string(&d_source, &in_tmp, max_str_len))\n throw Error(\"Network I\/O Error. Could not read string data.\");\n }\n\n val = in_tmp;\n\n free(in_tmp);\n}\n\nvoid XDRStreamUnMarshaller::get_url(string &val)\n{\n get_str(val);\n}\n\nvoid XDRStreamUnMarshaller::get_opaque(char *val, unsigned int len)\n{\n xdr_setpos( &d_source, 0);\n\n \/\/ Round len up to the next multiple of 4. There is also the RNDUP()\n \/\/ macro in xdr.h, at least on OS\/X.\n len += len & 3;\n if (static_cast(len) > XDR_DAP_BUFF_SIZE)\n throw Error(\"Network I\/O Error. Length of opaque data larger than allowed\");\n\n d_in.read(d_buf, len);\n\n xdr_opaque(&d_source, val, len);\n}\n\nvoid XDRStreamUnMarshaller::get_int(int &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!xdr_int(&d_source, &val))\n throw Error(\"Network I\/O Error(1).\");\n\n DBG(std::cerr << \"get_int: \" << val << std::endl);\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, Vector &)\n{\n int i;\n get_int(i); \/\/ This leaves the XDR encoded value in d_buf; used later\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/ Must round up string size to next 4\n i += i & 3;\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/char *buf = 0;\n \/\/XDR *source = 0;\n \/\/ Must address the case where the string is larger than the buffer\n if (i + 4 > XDR_DAP_BUFF_SIZE) {\n \tvector buf(i+4);\n XDR source;\n xdrmem_create(&source, &buf[0], i + 4, XDR_DECODE);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, i);\n DBG2(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&source, 0);\n if (!xdr_bytes(&d_source, val, &num, DODS_MAX_ARRAY)) {\n xdr_destroy(&source);\n throw Error(\"Network I\/O Error. Could not read byte array data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, i);\n DBG2(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&d_source, 0);\n if (!xdr_bytes(&d_source, val, &num, DODS_MAX_ARRAY))\n throw Error(\"Network I\/O Error. Could not read byte array data.\");\n }\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, int width, Vector &vec)\n{\n get_vector(val, num, width, vec.var()->type());\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, int width, Type type)\n{\n int i;\n get_int(i); \/\/ This leaves the XDR encoded value in d_buf; used later\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n width += width & 3;\n DBG(std::cerr << \"width: \" << width << std::endl);\n\n int size = i * width; \/\/ + 4; \/\/ '+ 4' to hold the int already read\n\n \/\/ Must address the case where the string is larger than the buffer\n if (size > XDR_DAP_BUFF_SIZE) {\n \tvector buf(size+4);\n XDR source;\n xdrmem_create(&source, &buf[0], size + 4, XDR_DECODE);\n DBG(cerr << \"size: \" << size << endl);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, size); \/\/ +4 for the int already read\n DBG(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&source, 0);\n if (!xdr_array(&source, val, &num, DODS_MAX_ARRAY, width, XDRUtils::xdr_coder(type))) {\n xdr_destroy( &source );\n throw Error(\"Network I\/O Error. Could not read array data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, size);\n DBG(cerr << \"bytes read (2): \" << d_in.gcount() << endl);\n\n xdr_setpos( &d_source, 0);\n if (!xdr_array(&d_source, val, &num, DODS_MAX_ARRAY, width, XDRUtils::xdr_coder(type)))\n throw Error(\"Network I\/O Error. Could not read array data.\");\n }\n}\n\nvoid XDRStreamUnMarshaller::dump(ostream &strm) const\n{\n strm << DapIndent::LMarg << \"XDRStreamUnMarshaller::dump - (\" << (void *) this << \")\" << endl;\n}\n\n} \/\/ namespace libdap\n\nFixed ugly DBG2() macro calls\/\/ XDRStreamUnMarshaller.cc\n\n\/\/ -*- mode: c++; c-basic-offset:4 -*-\n\n\/\/ This file is part of libdap, A C++ implementation of the OPeNDAP Data\n\/\/ Access Protocol.\n\n\/\/ Copyright (c) 2002,2003 OPeNDAP, Inc.\n\/\/ Author: Patrick West \n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\/\/ You can contact OPeNDAP, Inc. at PO Box 112, Saunderstown, RI. 02874-0112.\n\n\/\/ (c) COPYRIGHT URI\/MIT 1994-1999\n\/\/ Please read the full copyright statement in the file COPYRIGHT_URI.\n\/\/\n\/\/ Authors:\n\/\/ pwest Patrick West \n#include \"config.h\"\n#include \"XDRStreamUnMarshaller.h\"\n\n#include \/\/ for memcpy\n#include \n#include \n\n\/\/#define DODS_DEBUG2 1\n\/\/#define DODS_DEBUG 1\n\n#include \"Str.h\"\n\/\/ #include \"Vector.h\"\n#include \"Array.h\"\n#include \"util.h\"\n#include \"InternalErr.h\"\n#include \"debug.h\"\n\nnamespace libdap {\n\nchar *XDRStreamUnMarshaller::d_buf = 0;\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller(istream &in) : \/*&d_source( 0 ),*\/\n d_in(in)\n{\n if (!d_buf)\n d_buf = (char *) malloc(XDR_DAP_BUFF_SIZE);\n if (!d_buf)\n throw Error(internal_error, \"Failed to allocate memory for data serialization.\");\n\n \/\/&d_source = new XDR;\n xdrmem_create(&d_source, d_buf, XDR_DAP_BUFF_SIZE, XDR_DECODE);\n}\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller() :\n UnMarshaller(), \/*&d_source( 0 ),*\/d_in(cin)\n{\n throw InternalErr(__FILE__, __LINE__, \"Default constructor not implemented.\");\n}\n\nXDRStreamUnMarshaller::XDRStreamUnMarshaller(const XDRStreamUnMarshaller &um) :\n UnMarshaller(um), \/*&d_source( 0 ),*\/d_in(cin)\n{\n throw InternalErr(__FILE__, __LINE__, \"Copy constructor not implemented.\");\n}\n\nXDRStreamUnMarshaller &\nXDRStreamUnMarshaller::operator=(const XDRStreamUnMarshaller &)\n{\n throw InternalErr(__FILE__, __LINE__, \"Copy operator not implemented.\");\n\n return *this;\n}\n\nXDRStreamUnMarshaller::~XDRStreamUnMarshaller()\n{\n xdr_destroy( &d_source );\n \/\/&d_source = 0;\n}\n\nvoid XDRStreamUnMarshaller::get_byte(dods_byte &val)\n{\n if (xdr_setpos( &d_source, 0 ) < 0)\n throw Error(\"Failed to reposition input stream\");\n if (!(d_in.read(d_buf, 4))) {\n if (d_in.eof())\n throw Error(\"Premature EOF in input stream\");\n else {\n ostringstream ss(\"Error reading from input stream: \");\n ss << d_in.rdstate();\n throw Error(ss.str());\n }\n }\n\n DBG2( std::cerr << \"_in.gcount(): \" << d_in.gcount() << std::endl );\n DBG2( std::cerr << \"_in.tellg(): \" << d_in.tellg() << std::endl );\n DBG2( std::cerr << \"_buf[0]: \" << hex << d_buf[0] << \"; _buf[1]: \" << d_buf[1]\n << \"; _buf[2]: \" << d_buf[2] << \"; _buf[3]: \" << d_buf[3]\n << dec << std::endl );\n\n if (!xdr_char(&d_source, (char *) &val))\n throw Error(\"Network I\/O Error. Could not read byte data.\");\n\n DBG2(std::cerr << \"get_byte: \" << val << std::endl );\n}\n\nvoid XDRStreamUnMarshaller::get_int16(dods_int16 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_INT16(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read int 16 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_int32(dods_int32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_INT32(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read int 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_float32(dods_float32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!xdr_float(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read float 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_float64(dods_float64 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 8);\n\n if (!xdr_double(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read float 64 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_uint16(dods_uint16 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_UINT16(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read uint 16 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_uint32(dods_uint32 &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!XDR_UINT32(&d_source, &val))\n throw Error(\"Network I\/O Error. Could not read uint 32 data.\");\n}\n\nvoid XDRStreamUnMarshaller::get_str(string &val)\n{\n int i;\n get_int(i);\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/ Must round up string size to next 4\n i = ((i + 3) \/ 4) * 4;\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n char *in_tmp = 0;\n \/\/char *buf = 0;\n \/\/XDR *source = 0;\n \/\/ Must address the case where the string is larger than the buffer\n if (i + 4 > XDR_DAP_BUFF_SIZE) {\n#if 0\n char *buf = (char *) malloc(i + 4);\n if (!buf)\n throw InternalErr(__FILE__, __LINE__, \"Error allocating memory\");\n#endif\n vector buf(i+4);\n\n XDR source;\/\/ = new XDR;\n xdrmem_create(&source, &buf[0], i + 4, XDR_DECODE);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, i);\n\n xdr_setpos( &source, 0);\n if (!xdr_string( &source, &in_tmp, max_str_len)) {\n xdr_destroy( &source );\n throw Error(\"Network I\/O Error. Could not read string data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, i);\n\n xdr_setpos( &d_source, 0);\n if (!xdr_string(&d_source, &in_tmp, max_str_len))\n throw Error(\"Network I\/O Error. Could not read string data.\");\n }\n\n val = in_tmp;\n\n free(in_tmp);\n}\n\nvoid XDRStreamUnMarshaller::get_url(string &val)\n{\n get_str(val);\n}\n\nvoid XDRStreamUnMarshaller::get_opaque(char *val, unsigned int len)\n{\n xdr_setpos( &d_source, 0);\n\n \/\/ Round len up to the next multiple of 4. There is also the RNDUP()\n \/\/ macro in xdr.h, at least on OS\/X.\n len += len & 3;\n if (static_cast(len) > XDR_DAP_BUFF_SIZE)\n throw Error(\"Network I\/O Error. Length of opaque data larger than allowed\");\n\n d_in.read(d_buf, len);\n\n xdr_opaque(&d_source, val, len);\n}\n\nvoid XDRStreamUnMarshaller::get_int(int &val)\n{\n xdr_setpos( &d_source, 0);\n d_in.read(d_buf, 4);\n\n if (!xdr_int(&d_source, &val))\n throw Error(\"Network I\/O Error(1).\");\n\n DBG(std::cerr << \"get_int: \" << val << std::endl);\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, Vector &)\n{\n int i;\n get_int(i); \/\/ This leaves the XDR encoded value in d_buf; used later\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/ Must round up string size to next 4\n i += i & 3;\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n \/\/char *buf = 0;\n \/\/XDR *source = 0;\n \/\/ Must address the case where the string is larger than the buffer\n if (i + 4 > XDR_DAP_BUFF_SIZE) {\n \tvector buf(i+4);\n XDR source;\n xdrmem_create(&source, &buf[0], i + 4, XDR_DECODE);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, i);\n DBG2(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&source, 0);\n if (!xdr_bytes(&d_source, val, &num, DODS_MAX_ARRAY)) {\n xdr_destroy(&source);\n throw Error(\"Network I\/O Error. Could not read byte array data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, i);\n DBG2(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&d_source, 0);\n if (!xdr_bytes(&d_source, val, &num, DODS_MAX_ARRAY))\n throw Error(\"Network I\/O Error. Could not read byte array data.\");\n }\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, int width, Vector &vec)\n{\n get_vector(val, num, width, vec.var()->type());\n}\n\nvoid XDRStreamUnMarshaller::get_vector(char **val, unsigned int &num, int width, Type type)\n{\n int i;\n get_int(i); \/\/ This leaves the XDR encoded value in d_buf; used later\n DBG(std::cerr << \"i: \" << i << std::endl);\n\n width += width & 3;\n DBG(std::cerr << \"width: \" << width << std::endl);\n\n int size = i * width; \/\/ + 4; \/\/ '+ 4' to hold the int already read\n\n \/\/ Must address the case where the string is larger than the buffer\n if (size > XDR_DAP_BUFF_SIZE) {\n \tvector buf(size+4);\n XDR source;\n xdrmem_create(&source, &buf[0], size + 4, XDR_DECODE);\n DBG(cerr << \"size: \" << size << endl);\n memcpy(&buf[0], d_buf, 4);\n\n d_in.read(&buf[0] + 4, size); \/\/ +4 for the int already read\n DBG(cerr << \"bytes read: \" << d_in.gcount() << endl);\n\n xdr_setpos(&source, 0);\n if (!xdr_array(&source, val, &num, DODS_MAX_ARRAY, width, XDRUtils::xdr_coder(type))) {\n xdr_destroy( &source );\n throw Error(\"Network I\/O Error. Could not read array data.\");\n }\n\n xdr_destroy( &source );\n }\n else {\n d_in.read(d_buf + 4, size);\n DBG(cerr << \"bytes read (2): \" << d_in.gcount() << endl);\n\n xdr_setpos( &d_source, 0);\n if (!xdr_array(&d_source, val, &num, DODS_MAX_ARRAY, width, XDRUtils::xdr_coder(type)))\n throw Error(\"Network I\/O Error. Could not read array data.\");\n }\n}\n\nvoid XDRStreamUnMarshaller::dump(ostream &strm) const\n{\n strm << DapIndent::LMarg << \"XDRStreamUnMarshaller::dump - (\" << (void *) this << \")\" << endl;\n}\n\n} \/\/ namespace libdap\n\n<|endoftext|>"} {"text":"\/* Copyright © 2001-2016, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nchannel `#navitia` on riot https:\/\/riot.im\/app\/#\/room\/#navitia:matrix.org\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"ed\/data.h\"\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_ed\n#include \n#include \n#include \n#include \"conf.h\"\n#include \"ed\/build_helper.h\"\n#include \"ed\/connectors\/osm_tags_reader.h\"\n#include \"ed\/default_poi_types.h\"\n#include \"tests\/utils_test.h\"\n\nstruct logger_initialized {\n logger_initialized() { navitia::init_logger(); }\n};\nBOOST_GLOBAL_FIXTURE(logger_initialized);\n\n\/*\n * default poi-types and minimal json should be ok\n *\/\nBOOST_AUTO_TEST_CASE(def_json_poi_types_ok) {\n auto default_json = ed::connectors::DEFAULT_JSON_POI_TYPES;\n BOOST_CHECK_NO_THROW(const ed::connectors::PoiTypeParams params(default_json));\n auto minimal_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_NO_THROW(const ed::connectors::PoiTypeParams params(minimal_json));\n}\n\n\/*\n * poi-type parking and bss-rental are mandatory (used by kraken)\n *\/\nBOOST_AUTO_TEST_CASE(no_parking_json_poi_types_ko) {\n auto no_bss_rental_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(no_bss_rental_json), std::invalid_argument);\n auto no_parking_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(no_parking_json), std::invalid_argument);\n}\n\n\/*\n * poi-type id can't be defined twice\n *\/\nBOOST_AUTO_TEST_CASE(double_poi_types_ko) {\n auto json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"BSS station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), std::invalid_argument);\n}\n\n\/*\n * can't use a poi-type id that's not defined\n *\/\nBOOST_AUTO_TEST_CASE(undefined_poi_type_ko) {\n auto json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"leisure\", \"value\": \"park\"}\n ],\n \"poi_type_id\": \"leisure:park\"\n }\n ]\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), std::invalid_argument);\n}\n\n\/*\n * can't provide an empty json, or an ill-formed json\n *\/\nBOOST_AUTO_TEST_CASE(ill_json_poi_type_ko) {\n auto json = R\"({})\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), boost::property_tree::ptree_bad_path);\n auto ill_json = R\"(\n {\n \"poi_types\":\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n \"rules\": [\n {\n non-sense!!!!!\n ]\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(ill_json),\n boost::property_tree::json_parser::json_parser_error);\n}\n\n\/*\n * default tagging: check that default parameters chooses the good tag\n *\/\nBOOST_AUTO_TEST_CASE(default_tagging) {\n auto default_json = ed::connectors::DEFAULT_JSON_POI_TYPES;\n const ed::connectors::PoiTypeParams params(default_json);\n\n BOOST_CHECK(params.get_applicable_poi_rule({}) == nullptr);\n BOOST_CHECK_EQUAL(params.get_applicable_poi_rule({{\"amenity\", \"parking\"}})->poi_type_id, \"amenity:parking\");\n BOOST_CHECK_EQUAL(params.get_applicable_poi_rule({{\"leisure\", \"garden\"}})->poi_type_id, \"leisure:garden\");\n}\n\n\/*\n * multiple matches tagging: check that first matches\n *\/\nBOOST_AUTO_TEST_CASE(multiple_match_tagging) {\n auto velib_prior_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"velib\", \"name\": \"Velib Station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"},\n {\"key\": \"bss_type\", \"value\": \"velib\"}\n ],\n \"poi_type_id\": \"velib\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams velib_prior_params(velib_prior_json);\n auto bss_prior_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"velib\", \"name\": \"Velib Station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"},\n {\"key\": \"bss_type\", \"value\": \"velib\"}\n ],\n \"poi_type_id\": \"velib\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams bss_prior_params(bss_prior_json);\n\n CanalTP::Tags velib_tags = {{\"amenity\", \"bicycle_rental\"}, {\"bss_type\", \"velib\"}};\n CanalTP::Tags bss_tags = {{\"amenity\", \"bicycle_rental\"}, {\"bss_type\", \"unknown\"}};\n\n BOOST_CHECK_EQUAL(velib_prior_params.get_applicable_poi_rule(velib_tags)->poi_type_id, \"velib\");\n BOOST_CHECK_EQUAL(bss_prior_params.get_applicable_poi_rule(velib_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(velib_prior_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(bss_prior_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n}\n\n\/*\n * `:` bug test (we can use an osm-tag key or osm-tag value that contains a colon)\n *\/\nBOOST_AUTO_TEST_CASE(colon_tagging) {\n auto colon_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity:bicycle_rental\", \"value\": \"true\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"parking:effia\"}\n ],\n \"poi_type_id\": \"amenity:parking\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams colon_params(colon_json);\n\n CanalTP::Tags bss_tags = {{\"amenity:bicycle_rental\", \"true\"}};\n CanalTP::Tags effia_tags = {{\"amenity\", \"parking:effia\"}};\n\n BOOST_CHECK_EQUAL(colon_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(colon_params.get_applicable_poi_rule(effia_tags)->poi_type_id, \"amenity:parking\");\n}\nMask highway=trunk, trunk_link, motorway, motorway_link at autocomplete\/* Copyright © 2001-2016, Canal TP and\/or its affiliates. All rights reserved.\n\nThis file is part of Navitia,\n the software to build cool stuff with public transport.\n\nHope you'll enjoy and contribute to this project,\n powered by Canal TP (www.canaltp.fr).\nHelp us simplify mobility and open public transport:\n a non ending quest to the responsive locomotion way of traveling!\n\nLICENCE: This program is free software; you can redistribute it and\/or modify\nit under the terms of the GNU Affero General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License\nalong with this program. If not, see .\n\nStay tuned using\ntwitter @navitia\nchannel `#navitia` on riot https:\/\/riot.im\/app\/#\/room\/#navitia:matrix.org\nhttps:\/\/groups.google.com\/d\/forum\/navitia\nwww.navitia.io\n*\/\n\n#include \"ed\/data.h\"\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE test_ed\n#include \n#include \n#include \n#include \"conf.h\"\n#include \"ed\/build_helper.h\"\n#include \"ed\/connectors\/osm_tags_reader.h\"\n#include \"ed\/default_poi_types.h\"\n#include \"tests\/utils_test.h\"\n\nstruct logger_initialized {\n logger_initialized() { navitia::init_logger(); }\n};\nBOOST_GLOBAL_FIXTURE(logger_initialized);\n\n\/*\n * default poi-types and minimal json should be ok\n *\/\nBOOST_AUTO_TEST_CASE(def_json_poi_types_ok) {\n auto default_json = ed::connectors::DEFAULT_JSON_POI_TYPES;\n BOOST_CHECK_NO_THROW(const ed::connectors::PoiTypeParams params(default_json));\n auto minimal_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_NO_THROW(const ed::connectors::PoiTypeParams params(minimal_json));\n}\n\n\/*\n * poi-type parking and bss-rental are mandatory (used by kraken)\n *\/\nBOOST_AUTO_TEST_CASE(no_parking_json_poi_types_ko) {\n auto no_bss_rental_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(no_bss_rental_json), std::invalid_argument);\n auto no_parking_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(no_parking_json), std::invalid_argument);\n}\n\n\/*\n * poi-type id can't be defined twice\n *\/\nBOOST_AUTO_TEST_CASE(double_poi_types_ko) {\n auto json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"BSS station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": []\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), std::invalid_argument);\n}\n\n\/*\n * can't use a poi-type id that's not defined\n *\/\nBOOST_AUTO_TEST_CASE(undefined_poi_type_ko) {\n auto json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"leisure\", \"value\": \"park\"}\n ],\n \"poi_type_id\": \"leisure:park\"\n }\n ]\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), std::invalid_argument);\n}\n\n\/*\n * can't provide an empty json, or an ill-formed json\n *\/\nBOOST_AUTO_TEST_CASE(ill_json_poi_type_ko) {\n auto json = R\"({})\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(json), boost::property_tree::ptree_bad_path);\n auto ill_json = R\"(\n {\n \"poi_types\":\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n \"rules\": [\n {\n non-sense!!!!!\n ]\n })\";\n BOOST_CHECK_THROW(const ed::connectors::PoiTypeParams params(ill_json),\n boost::property_tree::json_parser::json_parser_error);\n}\n\n\/*\n * default tagging: check that default parameters chooses the good tag\n *\/\nBOOST_AUTO_TEST_CASE(default_tagging) {\n auto default_json = ed::connectors::DEFAULT_JSON_POI_TYPES;\n const ed::connectors::PoiTypeParams params(default_json);\n\n BOOST_CHECK(params.get_applicable_poi_rule({}) == nullptr);\n BOOST_CHECK_EQUAL(params.get_applicable_poi_rule({{\"amenity\", \"parking\"}})->poi_type_id, \"amenity:parking\");\n BOOST_CHECK_EQUAL(params.get_applicable_poi_rule({{\"leisure\", \"garden\"}})->poi_type_id, \"leisure:garden\");\n}\n\n\/*\n * multiple matches tagging: check that first matches\n *\/\nBOOST_AUTO_TEST_CASE(multiple_match_tagging) {\n auto velib_prior_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"velib\", \"name\": \"Velib Station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"},\n {\"key\": \"bss_type\", \"value\": \"velib\"}\n ],\n \"poi_type_id\": \"velib\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams velib_prior_params(velib_prior_json);\n auto bss_prior_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"velib\", \"name\": \"Velib Station\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"bicycle_rental\"},\n {\"key\": \"bss_type\", \"value\": \"velib\"}\n ],\n \"poi_type_id\": \"velib\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams bss_prior_params(bss_prior_json);\n\n CanalTP::Tags velib_tags = {{\"amenity\", \"bicycle_rental\"}, {\"bss_type\", \"velib\"}};\n CanalTP::Tags bss_tags = {{\"amenity\", \"bicycle_rental\"}, {\"bss_type\", \"unknown\"}};\n\n BOOST_CHECK_EQUAL(velib_prior_params.get_applicable_poi_rule(velib_tags)->poi_type_id, \"velib\");\n BOOST_CHECK_EQUAL(bss_prior_params.get_applicable_poi_rule(velib_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(velib_prior_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(bss_prior_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n}\n\n\/*\n * `:` bug test (we can use an osm-tag key or osm-tag value that contains a colon)\n *\/\nBOOST_AUTO_TEST_CASE(colon_tagging) {\n auto colon_json = R\"(\n {\n \"poi_types\": [\n {\"id\": \"amenity:bicycle_rental\", \"name\": \"Station VLS\"},\n {\"id\": \"amenity:parking\", \"name\": \"Parking\"}\n ],\n \"rules\": [\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity:bicycle_rental\", \"value\": \"true\"}\n ],\n \"poi_type_id\": \"amenity:bicycle_rental\"\n },\n {\n \"osm_tags_filters\": [\n {\"key\": \"amenity\", \"value\": \"parking:effia\"}\n ],\n \"poi_type_id\": \"amenity:parking\"\n }\n ]\n })\";\n const ed::connectors::PoiTypeParams colon_params(colon_json);\n\n CanalTP::Tags bss_tags = {{\"amenity:bicycle_rental\", \"true\"}};\n CanalTP::Tags effia_tags = {{\"amenity\", \"parking:effia\"}};\n\n BOOST_CHECK_EQUAL(colon_params.get_applicable_poi_rule(bss_tags)->poi_type_id, \"amenity:bicycle_rental\");\n BOOST_CHECK_EQUAL(colon_params.get_applicable_poi_rule(effia_tags)->poi_type_id, \"amenity:parking\");\n}\n\nBOOST_AUTO_TEST_CASE(highway_trunk_not_visible) {\n std::bitset<8> res = ed::connectors::parse_way_tags({{\"highway\", \"trunk\"}});\n BOOST_CHECK_EQUAL(res[ed::connectors::VISIBLE], false);\n}\n\nBOOST_AUTO_TEST_CASE(highway_trunk_link_not_visible) {\n std::bitset<8> res = ed::connectors::parse_way_tags({{\"highway\", \"trunk_link\"}});\n BOOST_CHECK_EQUAL(res[ed::connectors::VISIBLE], false);\n}\n\nBOOST_AUTO_TEST_CASE(highway_motorway_not_visible) {\n std::bitset<8> res = ed::connectors::parse_way_tags({{\"highway\", \"motorway\"}});\n BOOST_CHECK_EQUAL(res[ed::connectors::VISIBLE], false);\n}\n\nBOOST_AUTO_TEST_CASE(highway_motorway_link_not_visible) {\n std::bitset<8> res = ed::connectors::parse_way_tags({{\"highway\", \"motorway_link\"}});\n BOOST_CHECK_EQUAL(res[ed::connectors::VISIBLE], false);\n}\n\nBOOST_AUTO_TEST_CASE(highway_cycleway_visible) {\n std::bitset<8> res = ed::connectors::parse_way_tags({{\"highway\", \"cycleway\"}});\n BOOST_CHECK_EQUAL(res[ed::connectors::VISIBLE], true);\n}\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n\r\nnamespace crashes {\r\n\r\n\ttypedef std::function on_feedback;\r\n\r\n\tnamespace detail {\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttypedef std::shared_ptr shared_number;\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\tclass simple_count {\r\n\t\t\tsize_t copy_nr;\r\n\t\tpublic:\r\n\r\n\t\t\tsimple_count():copy_nr(0){}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tclass shared_count {\r\n\t\t\tTSharedInt copy_nr;\r\n\r\n\t\tpublic:\r\n\r\n\t\t\tshared_count():copy_nr(new size_t(0)){}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn *copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++(*copy_nr);\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tclass total_count\r\n\t\t{\r\n\t\t\tstatic size_t count_nr;\r\n\r\n\t\tpublic:\r\n\r\n\t\t\ttotal_count()\r\n\t\t\t{\r\n\t\t\t\tincrement();\r\n\t\t\t}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn count_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++count_nr;\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t N) {\r\n\t\t\t\treturn count_nr>=N;\r\n\t\t\t}\r\n\r\n\t\t\/\/protected:\r\n\r\n\t\t\t~total_count()\r\n\t\t\t{\r\n\t\t\t\t--count_nr;\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate size_t total_count::count_nr(0);\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tstruct when {\r\n\t\t\tclass copies {\r\n\t\t\t\tTCounter counter;\r\n\t\t\t\tTFeedback feedback;\r\n\t\t\tpublic:\r\n\r\n\t\t\t\tcopies() {\r\n\t\t\t\t\tif (counter.should_have_crashed_on(MaxN))\r\n\t\t\t\t\t\tthrow std::runtime_error(\"illegal number of copies\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvirtual ~copies() {} \/\/todo: review\r\n\r\n\t\t\t\tcopies(const copies& other):\r\n\t\t\t\t\tcounter(other.counter),\r\n\t\t\t\t\tfeedback(other.feedback)\r\n\t\t\t\t{\r\n\t\t\t\t\tcounter.increment();\r\n\t\t\t\t\tsize_t count=counter.get_copy_nr();\r\n\t\t\t\t\tif (feedback)\r\n\t\t\t\t\t\tfeedback(count);\r\n\t\t\t\t\tif (count>=MaxN)\r\n\t\t\t\t\t\tthrow std::runtime_error(\"illegal number of copies\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcopies& operator=(copies const& other) {\r\n\t\t\t\t\tcopies tmp(other);\r\n\t\t\t\t\tswap(other);\r\n\t\t\t\t\treturn *this;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvoid swap(copies const& other) {\r\n\t\t\t\t\tstd::swap(counter,other.counter);\r\n\t\t\t\t\tstd::swap(feedback,other.feedback);\r\n\t\t\t\t}\r\n\r\n\t\t\tpublic:\r\n\r\n\t\t\t\tvoid set_feedback(TFeedback const& f) {\r\n\t\t\t\t\tfeedback=f;\r\n\t\t\t\t}\r\n\r\n\t\t\t};\r\n\t\t\ttypedef copies copy;\r\n\t\t};\r\n\t}\r\n\r\n\t\/\/\/ crashes on MaxN total number of copies\r\n\ttemplate \r\n\tstruct on : public detail::when>\r\n\t{};\r\n\r\n\t\/\/\/ crashes on MaxN'th copy\r\n\ttemplate \r\n\tstruct after : public detail::when\r\n\t{};\r\n\r\n\t\/\/\/ crashes on MaxN total instances of T\r\n\ttemplate \r\n\tstruct on_total : public detail::when>\r\n\t{\r\n\t\ttypedef copies instances;\r\n\t\ttypedef copies instance;\r\n\t};\r\n}total_count decrement configurable#include \r\n#include \r\n#include \r\n#include \r\n\r\nnamespace crashes {\r\n\r\n\ttypedef std::function on_feedback;\r\n\r\n\tnamespace detail {\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttypedef std::shared_ptr shared_number;\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\tclass simple_count {\r\n\t\t\tsize_t copy_nr;\r\n\t\tpublic:\r\n\r\n\t\t\tsimple_count():copy_nr(0){}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tclass shared_count {\r\n\t\t\tTSharedInt copy_nr;\r\n\r\n\t\tpublic:\r\n\r\n\t\t\tshared_count():copy_nr(new size_t(0)){}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn *copy_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++(*copy_nr);\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\tstruct should_decrement_on_destruction {\r\n\t\t\tstatic const bool should_decrement=true;\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\tstruct shouldnt_decrement_on_destruction {\r\n\t\t\tstatic const bool should_decrement=false;\r\n\t\t};\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tclass total_count\r\n\t\t{\r\n\t\t\tstatic size_t count_nr;\r\n\r\n\t\tpublic:\r\n\r\n\t\t\ttotal_count()\r\n\t\t\t{\r\n\t\t\t\tincrement();\r\n\t\t\t}\r\n\r\n\t\t\tsize_t get_copy_nr() const {\r\n\t\t\t\treturn count_nr;\r\n\t\t\t}\r\n\r\n\t\t\tvoid increment() {\r\n\t\t\t\t++count_nr;\r\n\t\t\t}\r\n\r\n\t\t\tbool should_have_crashed_on(size_t N) {\r\n\t\t\t\treturn count_nr>=N;\r\n\t\t\t}\r\n\r\n\t\t\t\/\/protected:\r\n\r\n\t\t\t~total_count()\r\n\t\t\t{\r\n\t\t\t\tif (TDecrement::should_decrement)\r\n\t\t\t\t\t--count_nr;\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate size_t total_count::count_nr(0);\r\n\r\n\t\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\t\ttemplate \r\n\t\tstruct when {\r\n\t\t\tclass copies {\r\n\t\t\t\tTCounter counter;\r\n\t\t\t\tTFeedback feedback;\r\n\t\t\tpublic:\r\n\r\n\t\t\t\tcopies() {\r\n\t\t\t\t\tif (counter.should_have_crashed_on(MaxN))\r\n\t\t\t\t\t\tthrow std::runtime_error(\"illegal number of copies\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvirtual ~copies() {} \/\/todo: review\r\n\r\n\t\t\t\tcopies(const copies& other):\r\n\t\t\t\t\tcounter(other.counter),\r\n\t\t\t\t\tfeedback(other.feedback)\r\n\t\t\t\t{\r\n\t\t\t\t\tcounter.increment();\r\n\t\t\t\t\tsize_t count=counter.get_copy_nr();\r\n\t\t\t\t\tif (feedback)\r\n\t\t\t\t\t\tfeedback(count);\r\n\t\t\t\t\tif (count>=MaxN)\r\n\t\t\t\t\t\tthrow std::runtime_error(\"illegal number of copies\");\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcopies& operator=(copies const& other) {\r\n\t\t\t\t\tcopies tmp(other);\r\n\t\t\t\t\tswap(other);\r\n\t\t\t\t\treturn *this;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tvoid swap(copies const& other) {\r\n\t\t\t\t\tstd::swap(counter,other.counter);\r\n\t\t\t\t\tstd::swap(feedback,other.feedback);\r\n\t\t\t\t}\r\n\r\n\t\t\tpublic:\r\n\r\n\t\t\t\tvoid set_feedback(TFeedback const& f) {\r\n\t\t\t\t\tfeedback=f;\r\n\t\t\t\t}\r\n\r\n\t\t\t};\r\n\t\t\ttypedef copies copy;\r\n\t\t};\r\n\t}\r\n\r\n\t\/\/\/ crashes on MaxN total number of copies\r\n\ttemplate \r\n\tstruct on : public detail::when>\r\n\t{};\r\n\r\n\t\/\/\/ crashes on MaxN'th copy\r\n\ttemplate \r\n\tstruct after : public detail::when\r\n\t{};\r\n\r\n\t\/\/\/ crashes on MaxN total instances of T\r\n\ttemplate \r\n\tstruct on_total : public detail::when>\r\n\t{\r\n\t\ttypedef copies instances;\r\n\t\ttypedef copies instance;\r\n\t};\r\n}<|endoftext|>"} {"text":"#include \"face_registry.hh\"\n\n#include \"containers.hh\"\n#include \"exception.hh\"\n#include \"containers.hh\"\n\nnamespace Kakoune\n{\n\nstatic Face parse_face(StringView facedesc)\n{\n auto bg_it = find(facedesc, ',');\n auto attr_it = find(facedesc, '+');\n if (bg_it != facedesc.end() and attr_it < bg_it)\n throw runtime_error(\"invalid face description, expected [,][+]\");\n Face res;\n res.fg = str_to_color({facedesc.begin(), std::min(attr_it, bg_it)});\n if (bg_it != facedesc.end())\n res.bg = str_to_color({bg_it+1, attr_it});\n if (attr_it != facedesc.end())\n {\n for (++attr_it; attr_it != facedesc.end(); ++attr_it)\n {\n switch (*attr_it)\n {\n case 'u': res.attributes |= Attribute::Underline; break;\n case 'r': res.attributes |= Attribute::Reverse; break;\n case 'b': res.attributes |= Attribute::Bold; break;\n case 'B': res.attributes |= Attribute::Blink; break;\n case 'd': res.attributes |= Attribute::Dim; break;\n default: throw runtime_error(format(\"unknown face attribute '{}'\", StringView{*attr_it}));\n }\n }\n }\n return res;\n}\n\nFace FaceRegistry::operator[](const String& facedesc)\n{\n auto it = m_aliases.find(facedesc);\n while (it != m_aliases.end())\n {\n if (it->second.alias.empty())\n return it->second.face;\n it = m_aliases.find(it->second.alias);\n }\n return parse_face(facedesc);\n}\n\nvoid FaceRegistry::register_alias(const String& name, const String& facedesc,\n bool override)\n{\n if (not override and m_aliases.find(name) != m_aliases.end())\n throw runtime_error(format(\"alias '{}' already defined\", name));\n\n if (name.empty() or is_color_name(name) or\n std::any_of(name.begin(), name.end(),\n [](char c){ return not isalnum(c); }))\n throw runtime_error(format(\"invalid alias name: '{}'\", name));\n\n FaceOrAlias& alias = m_aliases[name];\n auto it = m_aliases.find(facedesc);\n if (it != m_aliases.end())\n {\n while (it != m_aliases.end())\n {\n if (it->second.alias.empty())\n break;\n if (it->second.alias == name)\n throw runtime_error(\"face cycle detected\");\n it = m_aliases.find(it->second.alias);\n }\n\n alias.alias = facedesc;\n }\n else\n {\n alias.alias = \"\";\n alias.face = parse_face(facedesc);\n }\n}\n\nCandidateList FaceRegistry::complete_alias_name(StringView prefix,\n ByteCount cursor_pos) const\n{\n using ValueType = std::pair;\n return complete(prefix, cursor_pos,\n transformed(m_aliases,\n [](const ValueType& v){ return v.first; }));\n}\n\nFaceRegistry::FaceRegistry()\n : m_aliases{\n { \"Default\", Face{ Color::Default, Color::Default } },\n { \"PrimarySelection\", Face{ Color::White, Color::Blue } },\n { \"SecondarySelection\", Face{ Color::Black, Color::Blue } },\n { \"PrimaryCursor\", Face{ Color::Black, Color::White } },\n { \"SecondaryCursor\", Face{ Color::Black, Color::White } },\n { \"LineNumbers\", Face{ Color::Default, Color::Default } },\n { \"LineNumberCursor\", Face{ Color::Default, Color::Default, Attribute::Reverse } },\n { \"MenuForeground\", Face{ Color::White, Color::Blue } },\n { \"MenuBackground\", Face{ Color::Blue, Color::White } },\n { \"Information\", Face{ Color::Black, Color::Yellow } },\n { \"Error\", Face{ Color::Black, Color::Red } },\n { \"StatusLine\", Face{ Color::Cyan, Color::Default } },\n { \"StatusCursor\", Face{ Color::Black, Color::Cyan } },\n { \"Prompt\", Face{ Color::Yellow, Color::Default } },\n { \"MatchingChar\", Face{ Color::Default, Color::Default, Attribute::Bold } },\n { \"Search\", Face{ Color::Default, Color::Default, Attribute::Underline } },\n }\n{}\n\n}\nDetect face being aliased to itself#include \"face_registry.hh\"\n\n#include \"containers.hh\"\n#include \"exception.hh\"\n#include \"containers.hh\"\n\nnamespace Kakoune\n{\n\nstatic Face parse_face(StringView facedesc)\n{\n auto bg_it = find(facedesc, ',');\n auto attr_it = find(facedesc, '+');\n if (bg_it != facedesc.end() and attr_it < bg_it)\n throw runtime_error(\"invalid face description, expected [,][+]\");\n Face res;\n res.fg = str_to_color({facedesc.begin(), std::min(attr_it, bg_it)});\n if (bg_it != facedesc.end())\n res.bg = str_to_color({bg_it+1, attr_it});\n if (attr_it != facedesc.end())\n {\n for (++attr_it; attr_it != facedesc.end(); ++attr_it)\n {\n switch (*attr_it)\n {\n case 'u': res.attributes |= Attribute::Underline; break;\n case 'r': res.attributes |= Attribute::Reverse; break;\n case 'b': res.attributes |= Attribute::Bold; break;\n case 'B': res.attributes |= Attribute::Blink; break;\n case 'd': res.attributes |= Attribute::Dim; break;\n default: throw runtime_error(format(\"unknown face attribute '{}'\", StringView{*attr_it}));\n }\n }\n }\n return res;\n}\n\nFace FaceRegistry::operator[](const String& facedesc)\n{\n auto it = m_aliases.find(facedesc);\n while (it != m_aliases.end())\n {\n if (it->second.alias.empty())\n return it->second.face;\n it = m_aliases.find(it->second.alias);\n }\n return parse_face(facedesc);\n}\n\nvoid FaceRegistry::register_alias(const String& name, const String& facedesc,\n bool override)\n{\n if (not override and m_aliases.find(name) != m_aliases.end())\n throw runtime_error(format(\"alias '{}' already defined\", name));\n\n if (name.empty() or is_color_name(name) or\n std::any_of(name.begin(), name.end(),\n [](char c){ return not isalnum(c); }))\n throw runtime_error(format(\"invalid alias name: '{}'\", name));\n\n if (name == facedesc)\n throw runtime_error(format(\"cannot alias face '{}' to itself\", name));\n\n FaceOrAlias& alias = m_aliases[name];\n auto it = m_aliases.find(facedesc);\n if (it != m_aliases.end())\n {\n while (it != m_aliases.end())\n {\n if (it->second.alias.empty())\n break;\n if (it->second.alias == name)\n throw runtime_error(\"face cycle detected\");\n it = m_aliases.find(it->second.alias);\n }\n\n alias.alias = facedesc;\n }\n else\n {\n alias.alias = \"\";\n alias.face = parse_face(facedesc);\n }\n}\n\nCandidateList FaceRegistry::complete_alias_name(StringView prefix,\n ByteCount cursor_pos) const\n{\n using ValueType = std::pair;\n return complete(prefix, cursor_pos,\n transformed(m_aliases,\n [](const ValueType& v){ return v.first; }));\n}\n\nFaceRegistry::FaceRegistry()\n : m_aliases{\n { \"Default\", Face{ Color::Default, Color::Default } },\n { \"PrimarySelection\", Face{ Color::White, Color::Blue } },\n { \"SecondarySelection\", Face{ Color::Black, Color::Blue } },\n { \"PrimaryCursor\", Face{ Color::Black, Color::White } },\n { \"SecondaryCursor\", Face{ Color::Black, Color::White } },\n { \"LineNumbers\", Face{ Color::Default, Color::Default } },\n { \"LineNumberCursor\", Face{ Color::Default, Color::Default, Attribute::Reverse } },\n { \"MenuForeground\", Face{ Color::White, Color::Blue } },\n { \"MenuBackground\", Face{ Color::Blue, Color::White } },\n { \"Information\", Face{ Color::Black, Color::Yellow } },\n { \"Error\", Face{ Color::Black, Color::Red } },\n { \"StatusLine\", Face{ Color::Cyan, Color::Default } },\n { \"StatusCursor\", Face{ Color::Black, Color::Cyan } },\n { \"Prompt\", Face{ Color::Yellow, Color::Default } },\n { \"MatchingChar\", Face{ Color::Default, Color::Default, Attribute::Bold } },\n { \"Search\", Face{ Color::Default, Color::Default, Attribute::Underline } },\n }\n{}\n\n}\n<|endoftext|>"} {"text":"fixed: wrote atom names containing whitespaces and could no longer read those<|endoftext|>"} {"text":"\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"processcontrol.h\"\n\n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#include \n#include \n#endif\n\nusing namespace Akonadi;\n\nProcessControl::ProcessControl( QObject *parent )\n : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),\n mRestartOnceOnExit( false )\n{\n connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ),\n this, SLOT( slotError( QProcess::ProcessError ) ) );\n connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ),\n this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) );\n connect( &mProcess, SIGNAL( readyReadStandardError() ),\n this, SLOT( slotErrorMessages() ) );\n connect( &mProcess, SIGNAL( readyReadStandardOutput() ),\n this, SLOT( slotStdoutMessages() ) );\n}\n\nProcessControl::~ProcessControl()\n{\n stop();\n}\n\nvoid ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )\n{\n mFailedToStart = false;\n\n mApplication = application;\n mArguments = arguments;\n mPolicy = policy;\n\n start();\n}\n\nvoid ProcessControl::setCrashPolicy( CrashPolicy policy )\n{\n mPolicy = policy;\n}\n\nvoid ProcessControl::stop()\n{\n if ( mProcess.state() != QProcess::NotRunning ) {\n mProcess.waitForFinished( 10000 );\n mProcess.terminate();\n }\n}\n\nvoid ProcessControl::slotError( QProcess::ProcessError error )\n{\n switch ( error ) {\n case QProcess::Crashed:\n \/\/ do nothing, we'll respawn in slotFinished\n break;\n case QProcess::FailedToStart:\n default:\n mFailedToStart = true;\n break;\n }\n\n qDebug( \"ProcessControl: Application '%s' stopped unexpected (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n}\n\nvoid ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )\n{\n if ( exitStatus == QProcess::CrashExit ) {\n if ( mPolicy == RestartOnCrash ) {\n if ( !mFailedToStart ) \/\/ don't try to start an unstartable application\n start();\n }\n } else {\n if ( exitCode != 0 ) {\n qDebug( \"ProcessControl: Application '%s' returned with exit code %d (%s)\",\n qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );\n if ( mPolicy == RestartOnCrash ) {\n if ( mCrashCount > 2 ) {\n qWarning() << mApplication << \"crashed too often and will not be restarted!\";\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n ++mCrashCount;\n QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );\n if ( !mFailedToStart ) \/\/ don't try to start an unstartable application\n start();\n }\n } else {\n if ( mRestartOnceOnExit ) {\n mRestartOnceOnExit = false;\n qDebug( \"Restarting application '%s'.\", qPrintable( mApplication ) );\n start();\n } else {\n qDebug( \"Application '%s' exited normally...\", qPrintable( mApplication ) );\n }\n }\n }\n}\n\nnamespace {\n static QString getEnv( const char* name, const QString& defaultValue=QString() ) {\n const QString v = QString::fromLocal8Bit( qgetenv( name ) );\n return !v.isEmpty() ? v : defaultValue;\n }\n}\n\nvoid ProcessControl::start()\n{\n#ifdef Q_OS_UNIX\n QString agentValgrind = getEnv( \"AKONADI_VALGRIND\" );\n if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {\n\n mArguments.prepend( mApplication );\n mApplication = QString::fromLocal8Bit( \"valgrind\" );\n\n const QString valgrindSkin = getEnv( \"AKONADI_VALGRIND_SKIN\", QString::fromLocal8Bit( \"memcheck\" ) );\n mArguments.prepend( QLatin1String( \"--tool=\" ) + valgrindSkin );\n\n const QString valgrindOptions = getEnv( \"AKONADI_VALGRIND_OPTIONS\" );\n if ( !valgrindOptions.isEmpty() )\n mArguments = valgrindOptions.split( ' ' ) << mArguments;\n\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Valgrinding process\" << mApplication;\n if ( !valgrindSkin.isEmpty() )\n qDebug() << \"ProcessControl: Valgrind skin:\" << valgrindSkin;\n if ( !valgrindOptions.isEmpty() )\n qDebug() << \"ProcessControl: Additional Valgrind options:\" << valgrindOptions;\n qDebug() << \"============================================================\";\n qDebug();\n }\n#endif\n\n mProcess.start( mApplication, mArguments );\n if ( !mProcess.waitForStarted( ) ) {\n qDebug( \"ProcessControl: Unable to start application '%s' (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n return;\n }\n\n#ifdef Q_OS_UNIX\n else {\n QString agentDebug = QString::fromLocal8Bit( qgetenv( \"AKONADI_DEBUG_WAIT\" ) );\n pid_t pid = mProcess.pid();\n if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Suspending process\" << mApplication;\n qDebug() << \"'gdb\" << pid << \"' to debug\";\n qDebug() << \"'kill -SIGCONT\" << pid << \"' to continue\";\n qDebug() << \"============================================================\";\n qDebug();\n kill( pid, SIGSTOP );\n }\n }\n#endif\n}\n\nvoid Akonadi::ProcessControl::slotStdoutMessages()\n{\n mProcess.setReadChannel( QProcess::StandardOutput );\n while ( mProcess.canReadLine() ) {\n QString message = QString::fromUtf8( mProcess.readLine() );\n qDebug() << mApplication << \"[out]\" << message;\n }\n}\n\nvoid ProcessControl::slotErrorMessages()\n{\n mProcess.setReadChannel( QProcess::StandardError );\n while ( mProcess.canReadLine() ) {\n QString message = QString::fromUtf8( mProcess.readLine() );\n emit processErrorMessages( message );\n qDebug( \"[%s] %s\", qPrintable( mApplication ), qPrintable( message.trimmed() ) );\n }\n}\n\nvoid ProcessControl::resetCrashCount()\n{\n mCrashCount = 0;\n}\n\n#include \"processcontrol.moc\"\nFix printing the process name which is being valgrinded.\/***************************************************************************\n * Copyright (C) 2006 by Tobias Koenig *\n * *\n * This program is free software; you can redistribute it and\/or modify *\n * it under the terms of the GNU Library General Public License as *\n * published by the Free Software Foundation; either version 2 of the *\n * License, or (at your option) any later version. *\n * *\n * This program is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\n * GNU General Public License for more details. *\n * *\n * You should have received a copy of the GNU Library General Public *\n * License along with this program; if not, write to the *\n * Free Software Foundation, Inc., *\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *\n ***************************************************************************\/\n\n#include \"processcontrol.h\"\n\n#include \n#include \n#include \n\n#ifdef Q_OS_UNIX\n#include \n#include \n#endif\n\nusing namespace Akonadi;\n\nProcessControl::ProcessControl( QObject *parent )\n : QObject( parent ), mFailedToStart( false ), mCrashCount( 0 ),\n mRestartOnceOnExit( false )\n{\n connect( &mProcess, SIGNAL( error( QProcess::ProcessError ) ),\n this, SLOT( slotError( QProcess::ProcessError ) ) );\n connect( &mProcess, SIGNAL( finished( int, QProcess::ExitStatus ) ),\n this, SLOT( slotFinished( int, QProcess::ExitStatus ) ) );\n connect( &mProcess, SIGNAL( readyReadStandardError() ),\n this, SLOT( slotErrorMessages() ) );\n connect( &mProcess, SIGNAL( readyReadStandardOutput() ),\n this, SLOT( slotStdoutMessages() ) );\n}\n\nProcessControl::~ProcessControl()\n{\n stop();\n}\n\nvoid ProcessControl::start( const QString &application, const QStringList &arguments, CrashPolicy policy )\n{\n mFailedToStart = false;\n\n mApplication = application;\n mArguments = arguments;\n mPolicy = policy;\n\n start();\n}\n\nvoid ProcessControl::setCrashPolicy( CrashPolicy policy )\n{\n mPolicy = policy;\n}\n\nvoid ProcessControl::stop()\n{\n if ( mProcess.state() != QProcess::NotRunning ) {\n mProcess.waitForFinished( 10000 );\n mProcess.terminate();\n }\n}\n\nvoid ProcessControl::slotError( QProcess::ProcessError error )\n{\n switch ( error ) {\n case QProcess::Crashed:\n \/\/ do nothing, we'll respawn in slotFinished\n break;\n case QProcess::FailedToStart:\n default:\n mFailedToStart = true;\n break;\n }\n\n qDebug( \"ProcessControl: Application '%s' stopped unexpected (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n}\n\nvoid ProcessControl::slotFinished( int exitCode, QProcess::ExitStatus exitStatus )\n{\n if ( exitStatus == QProcess::CrashExit ) {\n if ( mPolicy == RestartOnCrash ) {\n if ( !mFailedToStart ) \/\/ don't try to start an unstartable application\n start();\n }\n } else {\n if ( exitCode != 0 ) {\n qDebug( \"ProcessControl: Application '%s' returned with exit code %d (%s)\",\n qPrintable( mApplication ), exitCode, qPrintable( mProcess.errorString() ) );\n if ( mPolicy == RestartOnCrash ) {\n if ( mCrashCount > 2 ) {\n qWarning() << mApplication << \"crashed too often and will not be restarted!\";\n mPolicy = StopOnCrash;\n emit unableToStart();\n return;\n }\n ++mCrashCount;\n QTimer::singleShot( 60000, this, SLOT(resetCrashCount()) );\n if ( !mFailedToStart ) \/\/ don't try to start an unstartable application\n start();\n }\n } else {\n if ( mRestartOnceOnExit ) {\n mRestartOnceOnExit = false;\n qDebug( \"Restarting application '%s'.\", qPrintable( mApplication ) );\n start();\n } else {\n qDebug( \"Application '%s' exited normally...\", qPrintable( mApplication ) );\n }\n }\n }\n}\n\nnamespace {\n static QString getEnv( const char* name, const QString& defaultValue=QString() ) {\n const QString v = QString::fromLocal8Bit( qgetenv( name ) );\n return !v.isEmpty() ? v : defaultValue;\n }\n}\n\nvoid ProcessControl::start()\n{\n#ifdef Q_OS_UNIX\n QString agentValgrind = getEnv( \"AKONADI_VALGRIND\" );\n if ( !agentValgrind.isEmpty() && mApplication.contains( agentValgrind ) ) {\n\n mArguments.prepend( mApplication );\n const QString originalArguments = mArguments.join( QString::fromLocal8Bit( \" \" ) );\n mApplication = QString::fromLocal8Bit( \"valgrind\" );\n\n const QString valgrindSkin = getEnv( \"AKONADI_VALGRIND_SKIN\", QString::fromLocal8Bit( \"memcheck\" ) );\n mArguments.prepend( QLatin1String( \"--tool=\" ) + valgrindSkin );\n\n const QString valgrindOptions = getEnv( \"AKONADI_VALGRIND_OPTIONS\" );\n if ( !valgrindOptions.isEmpty() )\n mArguments = valgrindOptions.split( ' ' ) << mArguments;\n\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Valgrinding process\" << originalArguments;\n if ( !valgrindSkin.isEmpty() )\n qDebug() << \"ProcessControl: Valgrind skin:\" << valgrindSkin;\n if ( !valgrindOptions.isEmpty() )\n qDebug() << \"ProcessControl: Additional Valgrind options:\" << valgrindOptions;\n qDebug() << \"============================================================\";\n qDebug();\n }\n#endif\n\n mProcess.start( mApplication, mArguments );\n if ( !mProcess.waitForStarted( ) ) {\n qDebug( \"ProcessControl: Unable to start application '%s' (%s)\",\n qPrintable( mApplication ), qPrintable( mProcess.errorString() ) );\n return;\n }\n\n#ifdef Q_OS_UNIX\n else {\n QString agentDebug = QString::fromLocal8Bit( qgetenv( \"AKONADI_DEBUG_WAIT\" ) );\n pid_t pid = mProcess.pid();\n if ( !agentDebug.isEmpty() && mApplication.contains( agentDebug ) ) {\n qDebug();\n qDebug() << \"============================================================\";\n qDebug() << \"ProcessControl: Suspending process\" << mApplication;\n qDebug() << \"'gdb\" << pid << \"' to debug\";\n qDebug() << \"'kill -SIGCONT\" << pid << \"' to continue\";\n qDebug() << \"============================================================\";\n qDebug();\n kill( pid, SIGSTOP );\n }\n }\n#endif\n}\n\nvoid Akonadi::ProcessControl::slotStdoutMessages()\n{\n mProcess.setReadChannel( QProcess::StandardOutput );\n while ( mProcess.canReadLine() ) {\n QString message = QString::fromUtf8( mProcess.readLine() );\n qDebug() << mApplication << \"[out]\" << message;\n }\n}\n\nvoid ProcessControl::slotErrorMessages()\n{\n mProcess.setReadChannel( QProcess::StandardError );\n while ( mProcess.canReadLine() ) {\n QString message = QString::fromUtf8( mProcess.readLine() );\n emit processErrorMessages( message );\n qDebug( \"[%s] %s\", qPrintable( mApplication ), qPrintable( message.trimmed() ) );\n }\n}\n\nvoid ProcessControl::resetCrashCount()\n{\n mCrashCount = 0;\n}\n\n#include \"processcontrol.moc\"\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"dcpurenderer.hpp\"\n\nnamespace dcpu {\n\n void DcpuRenderer::Change(int width, int height) {\n glViewport(0, 0, width, height);\n auto aspect = static_cast(width) \/ height;\n projection = glm::frustum(-0.1f * aspect, 0.1f * aspect, -0.1f, 0.1f, 0.1f, 1000.0f);\n }\n\n void DcpuRenderer::Create() {\n glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n glEnable(GL_BLEND);\n glDepthMask(GL_FALSE);\n glDisable(GL_CULL_FACE);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n \/\/ glLineWidth(2.0f);\n\n vertex_shader.CreateFromFile(GL_VERTEX_SHADER, \"source\/vertex.glsl\");\n fragment_shader.CreateFromFile(GL_FRAGMENT_SHADER, \"source\/fragment.glsl\");\n program.Create({&vertex_shader, &fragment_shader});\n program.CompileAndLink();\n vertex_format.Create({\n {\"vertex_position\", GL_FLOAT, 3},\n {\"vertex_color\", GL_FLOAT, 4}\n });\n\n beam_buffer.Create(GL_ARRAY_BUFFER);\n beam_vertex_array.Create();\n vertex_format.Apply(beam_vertex_array, program);\n\n line_buffer.Create(GL_ARRAY_BUFFER);\n line_vertex_array.Create();\n vertex_format.Apply(line_vertex_array, program);\n\n CHECK_STATE(!glGetError());\n\n dcpu.Connect(&display);\n\n model_view = glm::mat4(\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, -0.8f, -1.5f, 1.0f\n );\n }\n\n void DcpuRenderer::Render() {\n Update();\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n program.Use();\n program.UniformsMatrix4f({\n {\"model_view\", &model_view},\n {\"projection\", &projection}\n });\n\n auto beam_drawable = display.BeamView();\n beam_buffer.Data(beam_drawable.data_size(), beam_drawable.data.data(), GL_STREAM_DRAW);\n beam_vertex_array.Bind();\n glDrawArrays(beam_drawable.element_type, 0, beam_drawable.element_count);\n\n auto line_drawable = display.LineView();\n line_buffer.Data(line_drawable.data_size(), line_drawable.data.data(), GL_STREAM_DRAW);\n line_vertex_array.Bind();\n glDrawArrays(line_drawable.element_type, 0, line_drawable.element_count);\n\n CHECK_STATE(!glGetError());\n }\n\n void DcpuRenderer::Update() {\n \/\/ dcpu.ExecuteInstructions(1666);\n display.Execute();\n\n x += vx;\n y += vy;\n z += vz;\n if (x < 0) {\n x = 0;\n vx *= -1;\n }\n if (x > 223) {\n x = 223;\n vx *= -1;\n }if (y < 0) {\n y = 0;\n vy *= -1;\n }\n if (y > 223) {\n y = 223;\n vy *= -1;\n }\n if (z < 0) {\n z = 0;\n vz *= -1;\n }\n if (z > 223) {\n z = 223;\n vz *= -1;\n }\n Word word0 = (y << 8) | x;\n Word word1 = z;\n auto data = {\n 0x0000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0700 + word1,\n 0x2020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0700 + word1,\n 0x0000 + word0, 0x0700 + word1,\n\n 0x0000 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0720 + word1,\n\n 0x0000 + word0, 0x0720 + word1,\n 0x2000 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0720 + word1,\n 0x0020 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0020 + word1,\n\n 0x3000 + word0, 0x0000 + word1,\n 0x3000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0700 + word1,\n 0x5020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0700 + word1,\n 0x3000 + word0, 0x0700 + word1,\n\n 0x3000 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0720 + word1,\n\n 0x3000 + word0, 0x0720 + word1,\n 0x5000 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0720 + word1,\n 0x3020 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0020 + word1,\n\n 0x0000, 0x0000,\n 0x0000, 0x0700,\n 0x2000, 0x0700,\n 0x2000, 0x0000,\n 0xDF00, 0x0000,\n 0xDF00, 0x0700,\n 0xFF00, 0x0700,\n 0xFF20, 0x0700,\n 0xFF20, 0x0000,\n 0xFFDF, 0x0000,\n 0xFFDF, 0x0700,\n 0xFFFF, 0x0700,\n 0xDFFF, 0x0700,\n 0xDFFF, 0x0000,\n 0x20FF, 0x0000,\n 0x20FF, 0x0700,\n 0x00FF, 0x0700,\n 0x00DF, 0x0700,\n 0x00DF, 0x0000,\n 0x0020, 0x0000,\n 0x0020, 0x0700,\n 0x0000, 0x0700,\n 0x0000, 0x0000,\n\n 0x0000, 0x00FF,\n 0x0000, 0x07FF,\n 0x2000, 0x07FF,\n 0x2000, 0x00FF,\n 0xDF00, 0x00FF,\n 0xDF00, 0x07FF,\n 0xFF00, 0x07FF,\n 0xFF20, 0x07FF,\n 0xFF20, 0x00FF,\n 0xFFDF, 0x00FF,\n 0xFFDF, 0x07FF,\n 0xFFFF, 0x07FF,\n 0xDFFF, 0x07FF,\n 0xDFFF, 0x00FF,\n 0x20FF, 0x00FF,\n 0x20FF, 0x07FF,\n 0x00FF, 0x07FF,\n 0x00DF, 0x07FF,\n 0x00DF, 0x00FF,\n 0x0020, 0x00FF,\n 0x0020, 0x07FF,\n 0x0000, 0x07FF\n };\n std::copy(data.begin(), data.end(), dcpu.memory_begin());\n display.Map(0, data.size() \/ 2);\n }\n}\nAdd a TODO.#include \n#include \n#include \n#include \n\n#include \"dcpurenderer.hpp\"\n\nnamespace dcpu {\n\n void DcpuRenderer::Change(int width, int height) {\n glViewport(0, 0, width, height);\n auto aspect = static_cast(width) \/ height;\n projection = glm::frustum(-0.1f * aspect, 0.1f * aspect, -0.1f, 0.1f, 0.1f, 1000.0f);\n }\n\n void DcpuRenderer::Create() {\n glClearColor(0.0f, 0.0f, 0.0f, 0.0f);\n glEnable(GL_BLEND);\n glDepthMask(GL_FALSE);\n glDisable(GL_CULL_FACE);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE);\n \/\/ glLineWidth(2.0f);\n\n vertex_shader.CreateFromFile(GL_VERTEX_SHADER, \"source\/vertex.glsl\");\n fragment_shader.CreateFromFile(GL_FRAGMENT_SHADER, \"source\/fragment.glsl\");\n program.Create({&vertex_shader, &fragment_shader});\n program.CompileAndLink();\n vertex_format.Create({\n {\"vertex_position\", GL_FLOAT, 3},\n {\"vertex_color\", GL_FLOAT, 4}\n });\n\n beam_buffer.Create(GL_ARRAY_BUFFER);\n beam_vertex_array.Create();\n vertex_format.Apply(beam_vertex_array, program);\n\n line_buffer.Create(GL_ARRAY_BUFFER);\n line_vertex_array.Create();\n vertex_format.Apply(line_vertex_array, program);\n\n CHECK_STATE(!glGetError());\n\n dcpu.Connect(&display);\n\n model_view = glm::mat4(\n 1.0f, 0.0f, 0.0f, 0.0f,\n 0.0f, 1.0f, 0.0f, 0.0f,\n 0.0f, 0.0f, 1.0f, 0.0f,\n 0.0f, -0.8f, -1.5f, 1.0f\n );\n }\n\n void DcpuRenderer::Render() {\n Update();\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n program.Use();\n program.UniformsMatrix4f({\n {\"model_view\", &model_view},\n {\"projection\", &projection}\n });\n\n auto beam_drawable = display.BeamView();\n beam_buffer.Data(beam_drawable.data_size(), beam_drawable.data.data(), GL_STREAM_DRAW);\n beam_vertex_array.Bind();\n glDrawArrays(beam_drawable.element_type, 0, beam_drawable.element_count);\n\n auto line_drawable = display.LineView();\n line_buffer.Data(line_drawable.data_size(), line_drawable.data.data(), GL_STREAM_DRAW);\n line_vertex_array.Bind();\n glDrawArrays(line_drawable.element_type, 0, line_drawable.element_count);\n\n CHECK_STATE(!glGetError());\n }\n\n void DcpuRenderer::Update() {\n \/\/ dcpu.ExecuteInstructions(1666);\n display.Execute();\n\n \/\/ TODO(robertsdionne): implement the logic in DCPU-16.\n x += vx;\n y += vy;\n z += vz;\n if (x < 0) {\n x = 0;\n vx *= -1;\n }\n if (x > 223) {\n x = 223;\n vx *= -1;\n }if (y < 0) {\n y = 0;\n vy *= -1;\n }\n if (y > 223) {\n y = 223;\n vy *= -1;\n }\n if (z < 0) {\n z = 0;\n vz *= -1;\n }\n if (z > 223) {\n z = 223;\n vz *= -1;\n }\n Word word0 = (y << 8) | x;\n Word word1 = z;\n auto data = {\n 0x0000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0700 + word1,\n 0x2020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0700 + word1,\n 0x0000 + word0, 0x0700 + word1,\n\n 0x0000 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0700 + word1,\n 0x2000 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0700 + word1,\n 0x0020 + word0, 0x0720 + word1,\n\n 0x0000 + word0, 0x0720 + word1,\n 0x2000 + word0, 0x0720 + word1,\n 0x2020 + word0, 0x0720 + word1,\n 0x0020 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0720 + word1,\n 0x0000 + word0, 0x0020 + word1,\n\n 0x3000 + word0, 0x0000 + word1,\n 0x3000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0700 + word1,\n 0x5020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0700 + word1,\n 0x3000 + word0, 0x0700 + word1,\n\n 0x3000 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0700 + word1,\n 0x5000 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0700 + word1,\n 0x3020 + word0, 0x0720 + word1,\n\n 0x3000 + word0, 0x0720 + word1,\n 0x5000 + word0, 0x0720 + word1,\n 0x5020 + word0, 0x0720 + word1,\n 0x3020 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0720 + word1,\n 0x3000 + word0, 0x0020 + word1,\n\n 0x0000, 0x0000,\n 0x0000, 0x0700,\n 0x2000, 0x0700,\n 0x2000, 0x0000,\n 0xDF00, 0x0000,\n 0xDF00, 0x0700,\n 0xFF00, 0x0700,\n 0xFF20, 0x0700,\n 0xFF20, 0x0000,\n 0xFFDF, 0x0000,\n 0xFFDF, 0x0700,\n 0xFFFF, 0x0700,\n 0xDFFF, 0x0700,\n 0xDFFF, 0x0000,\n 0x20FF, 0x0000,\n 0x20FF, 0x0700,\n 0x00FF, 0x0700,\n 0x00DF, 0x0700,\n 0x00DF, 0x0000,\n 0x0020, 0x0000,\n 0x0020, 0x0700,\n 0x0000, 0x0700,\n 0x0000, 0x0000,\n\n 0x0000, 0x00FF,\n 0x0000, 0x07FF,\n 0x2000, 0x07FF,\n 0x2000, 0x00FF,\n 0xDF00, 0x00FF,\n 0xDF00, 0x07FF,\n 0xFF00, 0x07FF,\n 0xFF20, 0x07FF,\n 0xFF20, 0x00FF,\n 0xFFDF, 0x00FF,\n 0xFFDF, 0x07FF,\n 0xFFFF, 0x07FF,\n 0xDFFF, 0x07FF,\n 0xDFFF, 0x00FF,\n 0x20FF, 0x00FF,\n 0x20FF, 0x07FF,\n 0x00FF, 0x07FF,\n 0x00DF, 0x07FF,\n 0x00DF, 0x00FF,\n 0x0020, 0x00FF,\n 0x0020, 0x07FF,\n 0x0000, 0x07FF\n };\n std::copy(data.begin(), data.end(), dcpu.memory_begin());\n display.Map(0, data.size() \/ 2);\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2003-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\nusing namespace log4cxx::spi;\n\nIMPLEMENT_LOG4CXX_OBJECT(FileAppender)\n\nFileAppender::FileAppender()\n: fileAppend(true), fileName(), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName,\n bool append, bool bufferedIO, int bufferSize)\n: fileAppend(append), fileName(fileName), bufferedIO(bufferedIO), bufferSize(bufferSize),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName,\n bool append)\n: fileAppend(append), fileName(fileName), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName)\n: fileAppend(true), fileName(fileName), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::~FileAppender()\n{\n if (!APRInitializer::isDestructed) {\n finalize();\n }\n}\n\nvoid FileAppender::setFile(const File& file)\n{\n fileName = file;\n}\n\nvoid FileAppender::setFile(const File& file, bool append,\n bool bufferedIO, int bufferSize) {\n fileName = file;\n fileAppend = append;\n this->bufferedIO = bufferedIO;\n this->bufferSize = bufferSize;\n}\n\n\nvoid FileAppender::closeWriter() {\n if (ofs != NULL) {\n apr_file_close(ofs);\n ofs = NULL;\n }\n}\n\n\n\nvoid FileAppender::setBufferedIO(bool bufferedIO)\n{\n this->bufferedIO = bufferedIO;\n if(bufferedIO)\n {\n immediateFlush = false;\n }\n}\n\nvoid FileAppender::setOption(const LogString& option,\n const LogString& value)\n{\n if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"FILE\"), LOG4CXX_STR(\"file\"))\n || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"FILENAME\"), LOG4CXX_STR(\"filename\")))\n {\n fileName = value;\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"APPEND\"), LOG4CXX_STR(\"append\")))\n {\n fileAppend = OptionConverter::toBoolean(value, true);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"BUFFEREDIO\"), LOG4CXX_STR(\"bufferedio\")))\n {\n bufferedIO = OptionConverter::toBoolean(value, true);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"IMMEDIATEFLUSH\"), LOG4CXX_STR(\"immediateflush\")))\n {\n bufferedIO = !OptionConverter::toBoolean(value, false);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"BUFFERSIZE\"), LOG4CXX_STR(\"buffersize\")))\n {\n bufferSize = OptionConverter::toFileSize(value, 8*1024);\n }\n else\n {\n WriterAppender::setOption(option, value);\n }\n}\n\nvoid FileAppender::activateOptions(Pool& p)\n{\n if (fileName.getName().empty()) {\n LogLog::warn((LogString) LOG4CXX_STR(\"File option not set for appender [\")\n + name + LOG4CXX_STR(\"].\"));\n LogLog::warn(LOG4CXX_STR(\"Are you using FileAppender instead of ConsoleAppender?\"));\n } else {\n synchronized sync(mutex);\n if (ofs != NULL) {\n LogLog::warn((LogString) LOG4CXX_STR(\"Appender [\") +\n name + LOG4CXX_STR(\"] already open.\"));\n }\n apr_fileperms_t perm = APR_OS_DEFAULT;\n apr_int32_t flags = APR_WRITE | APR_CREATE;\n if (fileAppend) {\n flags |= APR_APPEND;\n } else {\n flags |= APR_TRUNCATE;\n }\n if (bufferedIO) {\n flags |= APR_BUFFERED;\n }\n ofs = NULL;\n fileName.open(&ofs, flags, perm, pool);\n fileClosed = 0;\n }\n if (ofs != NULL) {\n writeHeader(p);\n }\n}\n\nvoid FileAppender::subAppend(const char* encoded, log4cxx_size_t size, Pool& p) {\n if (ofs != NULL) {\n apr_status_t rv = apr_file_write(ofs, encoded, &size);\n if (rv == APR_SUCCESS && immediateFlush) {\n rv = apr_file_flush(ofs);\n }\n }\n}\n\n\nLOGCXX-58: Immediate flush'd FileAppenders extremely slow on Windows\/*\n * Copyright 2003-2005 The Apache Software Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace log4cxx;\nusing namespace log4cxx::helpers;\nusing namespace log4cxx::spi;\n\nIMPLEMENT_LOG4CXX_OBJECT(FileAppender)\n\nFileAppender::FileAppender()\n: fileAppend(true), fileName(), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName,\n bool append, bool bufferedIO, int bufferSize)\n: fileAppend(append), fileName(fileName), bufferedIO(bufferedIO), bufferSize(bufferSize),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName,\n bool append)\n: fileAppend(append), fileName(fileName), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::FileAppender(const LayoutPtr& layout, const File& fileName)\n: fileAppend(true), fileName(fileName), bufferedIO(false), bufferSize(8*1024),\n pool(), ofs(NULL), fileClosed(1)\n{\n this->layout = layout;\n Pool p;\n activateOptions(p);\n}\n\nFileAppender::~FileAppender()\n{\n if (!APRInitializer::isDestructed) {\n finalize();\n }\n}\n\nvoid FileAppender::setFile(const File& file)\n{\n fileName = file;\n}\n\nvoid FileAppender::setFile(const File& file, bool append,\n bool bufferedIO, int bufferSize) {\n fileName = file;\n fileAppend = append;\n this->bufferedIO = bufferedIO;\n this->bufferSize = bufferSize;\n}\n\n\nvoid FileAppender::closeWriter() {\n if (ofs != NULL) {\n apr_file_close(ofs);\n ofs = NULL;\n }\n}\n\n\n\nvoid FileAppender::setBufferedIO(bool bufferedIO)\n{\n this->bufferedIO = bufferedIO;\n if(bufferedIO)\n {\n immediateFlush = false;\n }\n}\n\nvoid FileAppender::setOption(const LogString& option,\n const LogString& value)\n{\n if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"FILE\"), LOG4CXX_STR(\"file\"))\n || StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"FILENAME\"), LOG4CXX_STR(\"filename\")))\n {\n fileName = value;\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"APPEND\"), LOG4CXX_STR(\"append\")))\n {\n fileAppend = OptionConverter::toBoolean(value, true);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"BUFFEREDIO\"), LOG4CXX_STR(\"bufferedio\")))\n {\n bufferedIO = OptionConverter::toBoolean(value, true);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"IMMEDIATEFLUSH\"), LOG4CXX_STR(\"immediateflush\")))\n {\n bufferedIO = !OptionConverter::toBoolean(value, false);\n }\n else if (StringHelper::equalsIgnoreCase(option, LOG4CXX_STR(\"BUFFERSIZE\"), LOG4CXX_STR(\"buffersize\")))\n {\n bufferSize = OptionConverter::toFileSize(value, 8*1024);\n }\n else\n {\n WriterAppender::setOption(option, value);\n }\n}\n\nvoid FileAppender::activateOptions(Pool& p)\n{\n if (fileName.getName().empty()) {\n LogLog::warn((LogString) LOG4CXX_STR(\"File option not set for appender [\")\n + name + LOG4CXX_STR(\"].\"));\n LogLog::warn(LOG4CXX_STR(\"Are you using FileAppender instead of ConsoleAppender?\"));\n } else {\n synchronized sync(mutex);\n if (ofs != NULL) {\n LogLog::warn((LogString) LOG4CXX_STR(\"Appender [\") +\n name + LOG4CXX_STR(\"] already open.\"));\n }\n apr_fileperms_t perm = APR_OS_DEFAULT;\n apr_int32_t flags = APR_WRITE | APR_CREATE;\n if (fileAppend) {\n flags |= APR_APPEND;\n } else {\n flags |= APR_TRUNCATE;\n }\n if (bufferedIO) {\n flags |= APR_BUFFERED;\n }\n ofs = NULL;\n fileName.open(&ofs, flags, perm, pool);\n fileClosed = 0;\n }\n if (ofs != NULL) {\n writeHeader(p);\n }\n}\n\nvoid FileAppender::subAppend(const char* encoded, log4cxx_size_t size, Pool& p) {\n if (ofs != NULL) {\n apr_file_write(ofs, encoded, &size);\n \/\/\n \/\/ do not call apr_file_flush here as it is a no-op\n \/\/ on Unix and wildly expensive on Windows.\n \/\/ See LOGCXX-58 for details\n }\n}\n\n\n<|endoftext|>"} {"text":"cppcheck: Redundant checking of STL container<|endoftext|>"} {"text":"\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2012 Esteban Tovagliari.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Has to be first, to avoid redifinition warnings.\n#include \"bind_auto_release_ptr.h\"\n\n#include \"renderer\/utility\/transformsequence.h\"\n#include \"foundation\/utility\/iostreamop.h\"\n\nnamespace bpy = boost::python;\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace detail\n{\n\ntemplate\nvoid bind_typed_transform( const char *class_name)\n{\n typedef typename Transform::MatrixType MatrixType;\n\n bpy::class_ >( class_name)\n .def( bpy::init())\n .def( bpy::init())\n\n .def( \"identity\", &Transform::identity).staticmethod( \"identity\")\n\n .def( \"get_local_to_parent\", &Transform::get_local_to_parent, bpy::return_value_policy())\n .def( \"get_parent_to_local\", &Transform::get_parent_to_local, bpy::return_value_policy())\n\n .def( bpy::self * bpy::self)\n\n\t\t\/\/ a bug in boost::python, this needs\n\t\t\/\/ the extra self_ns qualification\n\t\t.def( bpy::self_ns::str( bpy::self))\n\t\t.def( bpy::self_ns::repr( bpy::self))\n ;\n}\n\nbpy::tuple transform_seq_get_transform( const TransformSequence& seq, std::size_t index)\n{\n double time;\n Transformd xform;\n seq.get_transform( index, time, xform);\n return bpy::make_tuple( time, xform);\n}\n\nTransformd transform_seq_get_earliest( const TransformSequence& seq)\n{\n return seq.earliest_transform();\n}\n\n} \/\/ detail\n\nvoid bind_transform()\n{\n detail::bind_typed_transform( \"Transformf\");\n detail::bind_typed_transform( \"Transformd\");\n\n bpy::class_( \"TransformSequence\", bpy::no_init)\n .def( \"clear\", &TransformSequence::clear)\n .def( \"set_transform\", &TransformSequence::set_transform)\n .def( \"get_transform\", &detail::transform_seq_get_transform)\n .def( \"earliest_transform\", &detail::transform_seq_get_earliest)\n .def( \"empty\", &TransformSequence::empty)\n .def( \"size\", &TransformSequence::size)\n .def( \"prepare\", &TransformSequence::prepare)\n .def( \"evaluate\", &TransformSequence::evaluate)\n ;\n}\nfixed mixed tabs\/spaces.\/\/\n\/\/ This source file is part of appleseed.\n\/\/ Visit http:\/\/appleseedhq.net\/ for additional information and resources.\n\/\/\n\/\/ This software is released under the MIT license.\n\/\/\n\/\/ Copyright (c) 2012 Esteban Tovagliari.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\/\/\n\n\/\/ Has to be first, to avoid redifinition warnings.\n#include \"bind_auto_release_ptr.h\"\n\n#include \"renderer\/utility\/transformsequence.h\"\n#include \"foundation\/utility\/iostreamop.h\"\n\nnamespace bpy = boost::python;\nusing namespace foundation;\nusing namespace renderer;\n\nnamespace detail\n{\n\ntemplate\nvoid bind_typed_transform( const char *class_name)\n{\n typedef typename Transform::MatrixType MatrixType;\n\n bpy::class_ >( class_name)\n .def( bpy::init())\n .def( bpy::init())\n\n .def( \"identity\", &Transform::identity).staticmethod( \"identity\")\n\n .def( \"get_local_to_parent\", &Transform::get_local_to_parent, bpy::return_value_policy())\n .def( \"get_parent_to_local\", &Transform::get_parent_to_local, bpy::return_value_policy())\n\n .def( bpy::self * bpy::self)\n\n \/\/ a bug in boost::python, this needs\n \/\/ the extra self_ns qualification\n .def( bpy::self_ns::str( bpy::self))\n .def( bpy::self_ns::repr( bpy::self))\n ;\n}\n\nbpy::tuple transform_seq_get_transform( const TransformSequence& seq, std::size_t index)\n{\n double time;\n Transformd xform;\n seq.get_transform( index, time, xform);\n return bpy::make_tuple( time, xform);\n}\n\nTransformd transform_seq_get_earliest( const TransformSequence& seq)\n{\n return seq.earliest_transform();\n}\n\n} \/\/ detail\n\nvoid bind_transform()\n{\n detail::bind_typed_transform( \"Transformf\");\n detail::bind_typed_transform( \"Transformd\");\n\n bpy::class_( \"TransformSequence\", bpy::no_init)\n .def( \"clear\", &TransformSequence::clear)\n .def( \"set_transform\", &TransformSequence::set_transform)\n .def( \"get_transform\", &detail::transform_seq_get_transform)\n .def( \"earliest_transform\", &detail::transform_seq_get_earliest)\n .def( \"empty\", &TransformSequence::empty)\n .def( \"size\", &TransformSequence::size)\n .def( \"prepare\", &TransformSequence::prepare)\n .def( \"evaluate\", &TransformSequence::evaluate)\n ;\n}\n<|endoftext|>"} {"text":"#include \"main_window.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"adaptor.h\"\n\nnamespace {\n\nQAction* makeAction(QString title, std::function fn, QWidget* parent) {\n\tQAction* result = new QAction(title, parent);\n\tnode_editor::qt_bind(result, SIGNAL(triggered(bool)), fn);\n\treturn result;\n}\n\n}\n\nMainWindow::MainWindow() : QMainWindow() {\n\tpossumwood::App::instance().setMainWindow(this);\n\n\tm_viewport = new Viewport();\n\tsetCentralWidget(m_viewport);\n\n\tm_properties = new Properties();\n\tQDockWidget* propDock = new QDockWidget(\"Properties\", this);\n\tpropDock->setWidget(m_properties);\n\tm_properties->setMinimumWidth(300);\n\taddDockWidget(Qt::RightDockWidgetArea, propDock);\n\n\tm_adaptor = new Adaptor(&possumwood::App::instance().graph());\n\tauto geom = m_adaptor->sizeHint();\n\tgeom.setWidth(QApplication::desktop()->screenGeometry().width() \/ 2 - 200);\n\tm_adaptor->setSizeHint(geom);\n\n\tQDockWidget* graphDock = new QDockWidget(\"Graph\", this);\n\tgraphDock->setWidget(m_adaptor);\n\taddDockWidget(Qt::LeftDockWidgetArea, graphDock);\n\n\t\/\/ connect the selection signal\n\tm_adaptor->scene().setNodeSelectionCallback(\n\t[&](std::set, node_editor::GraphScene::NodeRefComparator> selection) {\n\t\tm_properties->show(m_adaptor->selectedNodes());\n\t}\n\t);\n\n\t\/\/ create the context click menu\n\tm_adaptor->setContextMenuPolicy(Qt::CustomContextMenu);\n\n\t{\n\t\tQMenu* contextMenu = new QMenu(m_adaptor);\n\t\tconnect(m_adaptor, &Adaptor::customContextMenuRequested, [contextMenu, this](QPoint pos) {\n\t\t\tcontextMenu->popup(m_adaptor->mapToGlobal(pos));\n\t\t});\n\n\t\t{\n\t\t\tstd::map groups;\n\n\t\t\tfor(auto& m : possumwood::Metadata::instances()) {\n\t\t\t\tstd::vector pieces;\n\t\t\t\tboost::split(pieces, m.type(), boost::algorithm::is_any_of(\"\/\"));\n\n\t\t\t\tQMenu* current = contextMenu;\n\t\t\t\tfor(unsigned a=0;aaddMenu(pieces[a].c_str());\n\n\t\t\t\t\tcurrent = groups[pieces[a]];\n\t\t\t\t}\n\n\t\t\t\tconst std::string name = pieces.back();\n\t\t\t\tcurrent->addAction(makeAction(name.c_str(), [&m, name, contextMenu, this]() {\n\t\t\t\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(contextMenu->pos()));\n\t\t\t\t\tpossumwood::App::instance().graph().nodes().add(m, name, possumwood::NodeData{pos});\n\t\t\t\t}, m_adaptor));\n\t\t\t}\n\t\t}\n\n\t\tQAction* separator = new QAction(m_adaptor);\n\t\tseparator->setSeparator(true);\n\t\tcontextMenu->addAction(separator);\n\n\t\tQAction* deleteAction = new QAction(\"Delete selected items\", m_adaptor);\n\t\tdeleteAction->setShortcut(QKeySequence::Delete);\n\t\tcontextMenu->addAction(deleteAction);\n\t\tm_adaptor->addAction(deleteAction);\n\t\tnode_editor::qt_bind(deleteAction, SIGNAL(triggered()), [this]() {\n\t\t\tm_adaptor->deleteSelected();\n\t\t});\n\t}\n\n\t\/\/ drawing callback\n\tconnect(m_viewport, SIGNAL(render(float)), this, SLOT(draw(float)));\n\tpossumwood::App::instance().graph().onDirty([this]() {\n\t\tm_viewport->update();\n\t});\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ window actions\n\tQAction* newAct = new QAction(\"&New...\", this);\n\tnewAct->setShortcuts(QKeySequence::New);\n\tconnect(newAct, &QAction::triggered, [&](bool) {\n\t\tQMessageBox::StandardButton res = QMessageBox::question(this, \"New file...\", \"Do you want to clear the scene?\");\n\t\tif(res == QMessageBox::Yes)\n\t\t\tpossumwood::App::instance().newFile();\n\t});\n\n\tQAction* openAct = new QAction(\"&Open...\", this);\n\topenAct->setShortcuts(QKeySequence::Open);\n\tconnect(openAct, &QAction::triggered, [this](bool) {\n\t\tQString filename = QFileDialog::getOpenFileName(this, tr(\"Open File\"),\n\t\t possumwood::App::instance().filename().string().c_str(),\n\t\t tr(\"Possumwood files (*.psw)\"));\n\n\t\tif(!filename.isEmpty()) {\n\t\t\ttry {\n\t\t\t\tpossumwood::App::instance().loadFile(filename.toStdString());\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error loading file...\", \"Error loading \" + filename + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error loading file...\", \"Error loading \" + filename + \":\\nUnhandled exception thrown during loading.\");\n\t\t\t}\n\t\t}\n\t});\n\n\tQAction* saveAct = new QAction(\"&Save...\", this);\n\tsaveAct->setShortcuts(QKeySequence::Save);\n\tQAction* saveAsAct = new QAction(\"Save &As...\", this);\n\tsaveAsAct->setShortcuts(QKeySequence::SaveAs);\n\n\tconnect(saveAct, &QAction::triggered, [saveAsAct, this](bool) {\n\t\tif(possumwood::App::instance().filename().empty())\n\t\t\tsaveAsAct->triggered(true);\n\n\t\telse {\n\t\t\ttry {\n\t\t\t\tpossumwood::App::instance().saveFile();\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\nUnhandled exception thrown during saving.\");\n\t\t\t}\n\t\t}\n\t});\n\n\tconnect(saveAsAct, &QAction::triggered, [saveAct, this](bool) {\n\t\tQString filename = QFileDialog::getSaveFileName(this, tr(\"Save File\"),\n\t\t possumwood::App::instance().filename().string().c_str(),\n\t\t tr(\"Possumwood files (*.psw)\"));\n\n\t\tif(!filename.isEmpty()) {\n\t\t\ttry {\n\t\t\t\tpossumwood::App::instance().saveFile(filename.toStdString());\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\nUnhandled exception thrown during saving.\");\n\t\t\t}\n\t\t}\n\t});\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ create menu\n\n\tQMenu* fileMenu = menuBar()->addMenu(\"&File\");\n\n\tfileMenu->addAction(newAct);\n\tfileMenu->addAction(openAct);\n\tfileMenu->addAction(saveAct);\n\n\tQMenu* viewMenu = menuBar()->addMenu(\"&View\");\n\tfileMenu->addAction(saveAsAct);\n\n\tviewMenu->addAction(propDock->toggleViewAction());\n\tviewMenu->addAction(graphDock->toggleViewAction());\n}\n\nMainWindow::~MainWindow() {\n\tpossumwood::App::instance().graph().clear();\n}\n\nvoid MainWindow::draw(float dt) {\n\t\/\/ draw the floor grid\n\tglBegin(GL_LINES);\n\n\tfor(int a = -10; a <= 10; ++a) {\n\t\tconst float c = 0.3f + (float)(a % 10 == 0) * 0.2f;\n\t\tglColor3f(c, c, c);\n\n\t\tglVertex3f(a, 0, -10);\n\t\tglVertex3f(a, 0, 10);\n\t}\n\n\tfor(int a = -10; a <= 10; ++a) {\n\t\tconst float c = 0.3f + (float)(a % 10 == 0) * 0.2f;\n\t\tglColor3f(c, c, c);\n\n\t\tglVertex3f(-10, 0, a);\n\t\tglVertex3f(10, 0, a);\n\t}\n\n\tglEnd();\n\n\t\/\/ draw everything else\n\tfor(auto& n : m_adaptor->graph().nodes()) {\n\t\tglPushAttrib(GL_ALL_ATTRIB_BITS);\n\n\t\tconst possumwood::Metadata& meta = dynamic_cast(n.metadata());\n\t\tmeta.draw(dependency_graph::Values(n));\n\n\t\tglPopAttrib();\n\t}\n\n}\nFixed properties window refresh when opening a new scene#include \"main_window.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"adaptor.h\"\n\nnamespace {\n\nQAction* makeAction(QString title, std::function fn, QWidget* parent) {\n\tQAction* result = new QAction(title, parent);\n\tnode_editor::qt_bind(result, SIGNAL(triggered(bool)), fn);\n\treturn result;\n}\n\n}\n\nMainWindow::MainWindow() : QMainWindow() {\n\tpossumwood::App::instance().setMainWindow(this);\n\n\tm_viewport = new Viewport();\n\tsetCentralWidget(m_viewport);\n\n\tm_properties = new Properties();\n\tQDockWidget* propDock = new QDockWidget(\"Properties\", this);\n\tpropDock->setWidget(m_properties);\n\tm_properties->setMinimumWidth(300);\n\taddDockWidget(Qt::RightDockWidgetArea, propDock);\n\n\tm_adaptor = new Adaptor(&possumwood::App::instance().graph());\n\tauto geom = m_adaptor->sizeHint();\n\tgeom.setWidth(QApplication::desktop()->screenGeometry().width() \/ 2 - 200);\n\tm_adaptor->setSizeHint(geom);\n\n\tQDockWidget* graphDock = new QDockWidget(\"Graph\", this);\n\tgraphDock->setWidget(m_adaptor);\n\taddDockWidget(Qt::LeftDockWidgetArea, graphDock);\n\n\t\/\/ connect the selection signal\n\tm_adaptor->scene().setNodeSelectionCallback(\n\t[&](std::set, node_editor::GraphScene::NodeRefComparator> selection) {\n\t\tm_properties->show(m_adaptor->selectedNodes());\n\t}\n\t);\n\n\t\/\/ create the context click menu\n\tm_adaptor->setContextMenuPolicy(Qt::CustomContextMenu);\n\n\t{\n\t\tQMenu* contextMenu = new QMenu(m_adaptor);\n\t\tconnect(m_adaptor, &Adaptor::customContextMenuRequested, [contextMenu, this](QPoint pos) {\n\t\t\tcontextMenu->popup(m_adaptor->mapToGlobal(pos));\n\t\t});\n\n\t\t{\n\t\t\tstd::map groups;\n\n\t\t\tfor(auto& m : possumwood::Metadata::instances()) {\n\t\t\t\tstd::vector pieces;\n\t\t\t\tboost::split(pieces, m.type(), boost::algorithm::is_any_of(\"\/\"));\n\n\t\t\t\tQMenu* current = contextMenu;\n\t\t\t\tfor(unsigned a=0;aaddMenu(pieces[a].c_str());\n\n\t\t\t\t\tcurrent = groups[pieces[a]];\n\t\t\t\t}\n\n\t\t\t\tconst std::string name = pieces.back();\n\t\t\t\tcurrent->addAction(makeAction(name.c_str(), [&m, name, contextMenu, this]() {\n\t\t\t\t\tQPointF pos = m_adaptor->mapToScene(m_adaptor->mapFromGlobal(contextMenu->pos()));\n\t\t\t\t\tpossumwood::App::instance().graph().nodes().add(m, name, possumwood::NodeData{pos});\n\t\t\t\t}, m_adaptor));\n\t\t\t}\n\t\t}\n\n\t\tQAction* separator = new QAction(m_adaptor);\n\t\tseparator->setSeparator(true);\n\t\tcontextMenu->addAction(separator);\n\n\t\tQAction* deleteAction = new QAction(\"Delete selected items\", m_adaptor);\n\t\tdeleteAction->setShortcut(QKeySequence::Delete);\n\t\tcontextMenu->addAction(deleteAction);\n\t\tm_adaptor->addAction(deleteAction);\n\t\tnode_editor::qt_bind(deleteAction, SIGNAL(triggered()), [this]() {\n\t\t\tm_adaptor->deleteSelected();\n\t\t});\n\t}\n\n\t\/\/ drawing callback\n\tconnect(m_viewport, SIGNAL(render(float)), this, SLOT(draw(float)));\n\tpossumwood::App::instance().graph().onDirty([this]() {\n\t\tm_viewport->update();\n\t});\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ window actions\n\tQAction* newAct = new QAction(\"&New...\", this);\n\tnewAct->setShortcuts(QKeySequence::New);\n\tconnect(newAct, &QAction::triggered, [&](bool) {\n\t\tQMessageBox::StandardButton res = QMessageBox::question(this, \"New file...\", \"Do you want to clear the scene?\");\n\t\tif(res == QMessageBox::Yes) {\n\t\t\tm_properties->show({});\n\t\t\tpossumwood::App::instance().newFile();\n\t\t}\n\t});\n\n\tQAction* openAct = new QAction(\"&Open...\", this);\n\topenAct->setShortcuts(QKeySequence::Open);\n\tconnect(openAct, &QAction::triggered, [this](bool) {\n\t\tQString filename = QFileDialog::getOpenFileName(this, tr(\"Open File\"),\n\t\t possumwood::App::instance().filename().string().c_str(),\n\t\t tr(\"Possumwood files (*.psw)\"));\n\n\t\tif(!filename.isEmpty()) {\n\t\t\ttry {\n\t\t\t\tm_properties->show({});\n\t\t\t\tpossumwood::App::instance().loadFile(filename.toStdString());\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error loading file...\", \"Error loading \" + filename + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error loading file...\", \"Error loading \" + filename + \":\\nUnhandled exception thrown during loading.\");\n\t\t\t}\n\t\t}\n\t});\n\n\tQAction* saveAct = new QAction(\"&Save...\", this);\n\tsaveAct->setShortcuts(QKeySequence::Save);\n\tQAction* saveAsAct = new QAction(\"Save &As...\", this);\n\tsaveAsAct->setShortcuts(QKeySequence::SaveAs);\n\n\tconnect(saveAct, &QAction::triggered, [saveAsAct, this](bool) {\n\t\tif(possumwood::App::instance().filename().empty())\n\t\t\tsaveAsAct->triggered(true);\n\n\t\telse {\n\t\t\ttry {\n\t\t\t\tpossumwood::App::instance().saveFile();\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\nUnhandled exception thrown during saving.\");\n\t\t\t}\n\t\t}\n\t});\n\n\tconnect(saveAsAct, &QAction::triggered, [saveAct, this](bool) {\n\t\tQString filename = QFileDialog::getSaveFileName(this, tr(\"Save File\"),\n\t\t possumwood::App::instance().filename().string().c_str(),\n\t\t tr(\"Possumwood files (*.psw)\"));\n\n\t\tif(!filename.isEmpty()) {\n\t\t\ttry {\n\t\t\t\tpossumwood::App::instance().saveFile(filename.toStdString());\n\t\t\t}\n\t\t\tcatch(std::exception& err) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\n\" + err.what());\n\t\t\t}\n\t\t\tcatch(...) {\n\t\t\t\tQMessageBox::critical(this, \"Error saving file...\", \"Error saving \" + QString(possumwood::App::instance().filename().string().c_str()) + \":\\nUnhandled exception thrown during saving.\");\n\t\t\t}\n\t\t}\n\t});\n\n\n\t\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\t\/\/ create menu\n\n\tQMenu* fileMenu = menuBar()->addMenu(\"&File\");\n\n\tfileMenu->addAction(newAct);\n\tfileMenu->addAction(openAct);\n\tfileMenu->addAction(saveAct);\n\n\tQMenu* viewMenu = menuBar()->addMenu(\"&View\");\n\tfileMenu->addAction(saveAsAct);\n\n\tviewMenu->addAction(propDock->toggleViewAction());\n\tviewMenu->addAction(graphDock->toggleViewAction());\n}\n\nMainWindow::~MainWindow() {\n\tpossumwood::App::instance().graph().clear();\n}\n\nvoid MainWindow::draw(float dt) {\n\t\/\/ draw the floor grid\n\tglBegin(GL_LINES);\n\n\tfor(int a = -10; a <= 10; ++a) {\n\t\tconst float c = 0.3f + (float)(a % 10 == 0) * 0.2f;\n\t\tglColor3f(c, c, c);\n\n\t\tglVertex3f(a, 0, -10);\n\t\tglVertex3f(a, 0, 10);\n\t}\n\n\tfor(int a = -10; a <= 10; ++a) {\n\t\tconst float c = 0.3f + (float)(a % 10 == 0) * 0.2f;\n\t\tglColor3f(c, c, c);\n\n\t\tglVertex3f(-10, 0, a);\n\t\tglVertex3f(10, 0, a);\n\t}\n\n\tglEnd();\n\n\t\/\/ draw everything else\n\tfor(auto& n : m_adaptor->graph().nodes()) {\n\t\tglPushAttrib(GL_ALL_ATTRIB_BITS);\n\n\t\tconst possumwood::Metadata& meta = dynamic_cast(n.metadata());\n\t\tmeta.draw(dependency_graph::Values(n));\n\n\t\tglPopAttrib();\n\t}\n\n}\n<|endoftext|>"} {"text":"\/\/ GlutAppSkeleton.cpp\n\n#ifdef _WIN32\n# define WINDOWS_LEAN_AND_MEAN\n# define NOMINMAX\n# include \n#endif\n#include \n#include \n\n#include \n\n#include \"GlutAppSkeleton.h\"\n\n#include \"GL\/GLUtils.h\"\n#include \"GL\/ShaderFunctions.h\"\n#include \"MatrixMath.h\"\n#include \"utils\/Logger.h\"\n#include \"paramgl.h\"\n\n\nvoid GlutAppSkeleton::glut_PrintString(void *font, const char *str)\n{\n int l = (int)strlen(str);\n for (int i=0; iSetBarColorInner(0.8f, 0.2f, 0.2f);\n\n paramlistA->AddParam(new Param(\"rotation.x\", g_rotation.x,\n 0.0f, 360.0f, .1f, &(g_rotation.x)));\n paramlistA->AddParam(new Param(\"rotation.y\", g_rotation.y,\n 0.0f, 360.0f, .1f, &(g_rotation.y)));\n paramlistA->AddParam(new Param(\"rotation.z\", g_rotation.z,\n 0.0f, 360.0f, .1f, &(g_rotation.z)));\n }\n paramlist = paramlistA;\n}\n\n\n\/\/\/\n\/\/\/ Another layer of abstraction for printing text to screen.\n\/\/\/ Allows us to easily use uniforms for color when shaders are the norm.\n\/\/\/\n\/\/\/ @param font A glut \\#define like GLUT_BITMAP_HELVETICA_12.\n\/\/\/ @param color A float3 rgb color value.\n\/\/\/ @param prog A GL shader program to set the color as uniform.\n\/\/\/ @param pos An int2 screen space pixel coordinate pair.\n\/\/\/ @param str A pointer to char(string) of ASCII text to print.\n\/\/\/\nvoid GlutAppSkeleton::GlutDrawText(\n void* font,\n const float3 color,\n const GLuint prog,\n const int2 pos,\n const char* str) const\n{\n if (prog == 0)\n {\n \/\/\/@todo Log an error\n return;\n }\n\n glUniform3f(getUniLoc(prog, \"u_col\"), color.x, color.y, color.z);\n glRasterPos2i(pos.x, pos.y);\n glut_PrintString(font, str);\n}\n\n\nvoid GlutAppSkeleton::drawOverlay() const\n{\n glUseProgram(g_progOverlay);\n\n \/\/\/ Set up a simple orthographic projection matrix for text\n float proj[16];\n glhOrtho(proj,\n 0.0f, (float)g_windowWidth,\n 0.0f, (float)g_windowHeight,\n -1.0f, 1.0f);\n glUniformMatrix4fv(getUniLoc(g_progOverlay, \"prmtx\"), 1, false, proj);\n\n std::ostringstream oss;\n oss.str(\"\");\n oss.clear();\n oss << g_cameraLocation.x << \" \"\n << g_cameraLocation.y << \" \"\n << g_cameraLocation.z << \" \"\n << g_rotation.x << \" \"\n << g_rotation.y;\n\n float3 white = {g_colorVal,1,1};\n int2 pos = make_int2(10,20);\n GlutDrawText(\n GLUT_BITMAP_HELVETICA_12,\n white,\n g_progOverlay,\n pos,\n oss.str().c_str());\n\n glUseProgram(0);\n}\n\n\n\/\/\/ Draw param sliders with fixed pipeline\nvoid GlutAppSkeleton::drawSlidersFixedPipeline() const\n{\n glUseProgram(0);\n glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); \/\/ invert color\n glEnable(GL_BLEND);\n if (paramlist)\n paramlist->Render(0, 0);\n glDisable(GL_BLEND);\n}\n\n\nvoid GlutAppSkeleton::display() const\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glEnable(GL_DEPTH_TEST);\n\n glUseProgram(g_progBasic);\n {\n \/\/\/ Set up our 3D transformation matrices\n float modelviewMatrix[16];\n float projectionMatrix[16];\n\n float3 origin = g_cameraLocation + g_lookVector;\n glhLookAtf2(modelviewMatrix,\n g_cameraLocation,\n origin,\n g_upVector);\n glhTranslate(modelviewMatrix, 0.0f, g_distance, 0.0f);\n glhRotate(modelviewMatrix, g_rotation.x, 0.0f, 0.0f, 1.0f);\n glhRotate(modelviewMatrix, g_rotation.y, 1.0f, 0.0f, 0.0f);\n\n glhPerspectivef2(projectionMatrix, g_viewAngle, (float)g_windowWidth\/(float)g_windowHeight, 0.004, 500.0);\n\n glUniformMatrix4fv(getUniLoc(g_progBasic, \"mvmtx\"), 1, false, modelviewMatrix);\n glUniformMatrix4fv(getUniLoc(g_progBasic, \"prmtx\"), 1, false, projectionMatrix);\n\n \/\/glutWireSphere(1.0f, 16, 16);\n drawObject();\n }\n glUseProgram(0);\n\n drawOverlay();\n\n drawSlidersFixedPipeline();\n\n CHECK_GL_ERROR_MACRO();\n}\n\n\nvoid GlutAppSkeleton::mouseDown(int button, int state, int x, int y)\n{\n {\n if (paramlist && paramlist->Mouse(x, y, button, state))\n {\n curMouseAction = AdjustParam;\n return;\n }\n }\n curMouseAction = None;\n\n TriAppSkeleton::mouseDown(button, state, x, y);\n}\n\n\nvoid GlutAppSkeleton::mouseMove(int x, int y)\n{\n if (AdjustParam == curMouseAction)\n {\n if (paramlist && paramlist->Motion(x, y))\n {\n }\n return;\n }\n\n TriAppSkeleton::mouseMove(x,y);\n}\n\n\nvoid GlutAppSkeleton::keyboard(int key, int x, int y)\n{\n TriAppSkeleton::keyboard(key, x, y);\n}\n\n\nvoid GlutAppSkeleton::resize(int w, int h)\n{\n g_windowWidth = w;\n g_windowHeight = h;\n\n glViewport(0,0, (GLsizei)w, (GLsizei)h);\n}\n\n\nbool GlutAppSkeleton::initGL(int argc, char **argv)\n{\n bool ret = TriAppSkeleton::initGL(argc, argv);\n\n glClearColor(0.0, 0.0, 0.0, 0.0);\n \/\/glDisable(GL_LIGHTING);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n CHECK_GL_ERROR_MACRO();\n\n return ret;\n}\nAdd escape quit clause to Glut key handler.\/\/ GlutAppSkeleton.cpp\n\n#ifdef _WIN32\n# define WINDOWS_LEAN_AND_MEAN\n# define NOMINMAX\n# include \n#endif\n#include \n#include \n\n#include \n\n#include \"GlutAppSkeleton.h\"\n\n#include \"GL\/GLUtils.h\"\n#include \"GL\/ShaderFunctions.h\"\n#include \"MatrixMath.h\"\n#include \"utils\/Logger.h\"\n#include \"paramgl.h\"\n\n\nvoid GlutAppSkeleton::glut_PrintString(void *font, const char *str)\n{\n int l = (int)strlen(str);\n for (int i=0; iSetBarColorInner(0.8f, 0.2f, 0.2f);\n\n paramlistA->AddParam(new Param(\"rotation.x\", g_rotation.x,\n 0.0f, 360.0f, .1f, &(g_rotation.x)));\n paramlistA->AddParam(new Param(\"rotation.y\", g_rotation.y,\n 0.0f, 360.0f, .1f, &(g_rotation.y)));\n paramlistA->AddParam(new Param(\"rotation.z\", g_rotation.z,\n 0.0f, 360.0f, .1f, &(g_rotation.z)));\n }\n paramlist = paramlistA;\n}\n\n\n\/\/\/\n\/\/\/ Another layer of abstraction for printing text to screen.\n\/\/\/ Allows us to easily use uniforms for color when shaders are the norm.\n\/\/\/\n\/\/\/ @param font A glut \\#define like GLUT_BITMAP_HELVETICA_12.\n\/\/\/ @param color A float3 rgb color value.\n\/\/\/ @param prog A GL shader program to set the color as uniform.\n\/\/\/ @param pos An int2 screen space pixel coordinate pair.\n\/\/\/ @param str A pointer to char(string) of ASCII text to print.\n\/\/\/\nvoid GlutAppSkeleton::GlutDrawText(\n void* font,\n const float3 color,\n const GLuint prog,\n const int2 pos,\n const char* str) const\n{\n if (prog == 0)\n {\n \/\/\/@todo Log an error\n return;\n }\n\n glUniform3f(getUniLoc(prog, \"u_col\"), color.x, color.y, color.z);\n glRasterPos2i(pos.x, pos.y);\n glut_PrintString(font, str);\n}\n\n\nvoid GlutAppSkeleton::drawOverlay() const\n{\n glUseProgram(g_progOverlay);\n\n \/\/\/ Set up a simple orthographic projection matrix for text\n float proj[16];\n glhOrtho(proj,\n 0.0f, (float)g_windowWidth,\n 0.0f, (float)g_windowHeight,\n -1.0f, 1.0f);\n glUniformMatrix4fv(getUniLoc(g_progOverlay, \"prmtx\"), 1, false, proj);\n\n std::ostringstream oss;\n oss.str(\"\");\n oss.clear();\n oss << g_cameraLocation.x << \" \"\n << g_cameraLocation.y << \" \"\n << g_cameraLocation.z << \" \"\n << g_rotation.x << \" \"\n << g_rotation.y;\n\n float3 white = {g_colorVal,1,1};\n int2 pos = make_int2(10,20);\n GlutDrawText(\n GLUT_BITMAP_HELVETICA_12,\n white,\n g_progOverlay,\n pos,\n oss.str().c_str());\n\n glUseProgram(0);\n}\n\n\n\/\/\/ Draw param sliders with fixed pipeline\nvoid GlutAppSkeleton::drawSlidersFixedPipeline() const\n{\n glUseProgram(0);\n glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ZERO); \/\/ invert color\n glEnable(GL_BLEND);\n if (paramlist)\n paramlist->Render(0, 0);\n glDisable(GL_BLEND);\n}\n\n\nvoid GlutAppSkeleton::display() const\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glEnable(GL_DEPTH_TEST);\n\n glUseProgram(g_progBasic);\n {\n \/\/\/ Set up our 3D transformation matrices\n float modelviewMatrix[16];\n float projectionMatrix[16];\n\n float3 origin = g_cameraLocation + g_lookVector;\n glhLookAtf2(modelviewMatrix,\n g_cameraLocation,\n origin,\n g_upVector);\n glhTranslate(modelviewMatrix, 0.0f, g_distance, 0.0f);\n glhRotate(modelviewMatrix, g_rotation.x, 0.0f, 0.0f, 1.0f);\n glhRotate(modelviewMatrix, g_rotation.y, 1.0f, 0.0f, 0.0f);\n\n glhPerspectivef2(projectionMatrix, g_viewAngle, (float)g_windowWidth\/(float)g_windowHeight, 0.004, 500.0);\n\n glUniformMatrix4fv(getUniLoc(g_progBasic, \"mvmtx\"), 1, false, modelviewMatrix);\n glUniformMatrix4fv(getUniLoc(g_progBasic, \"prmtx\"), 1, false, projectionMatrix);\n\n \/\/glutWireSphere(1.0f, 16, 16);\n drawObject();\n }\n glUseProgram(0);\n\n drawOverlay();\n\n drawSlidersFixedPipeline();\n\n CHECK_GL_ERROR_MACRO();\n}\n\n\nvoid GlutAppSkeleton::mouseDown(int button, int state, int x, int y)\n{\n {\n if (paramlist && paramlist->Mouse(x, y, button, state))\n {\n curMouseAction = AdjustParam;\n return;\n }\n }\n curMouseAction = None;\n\n TriAppSkeleton::mouseDown(button, state, x, y);\n}\n\n\nvoid GlutAppSkeleton::mouseMove(int x, int y)\n{\n if (AdjustParam == curMouseAction)\n {\n if (paramlist && paramlist->Motion(x, y))\n {\n }\n return;\n }\n\n TriAppSkeleton::mouseMove(x,y);\n}\n\n\nvoid GlutAppSkeleton::keyboard(int key, int x, int y)\n{\n switch(key)\n {\n default:\n break;\n\n case 27: \/\/ Escape\n exit(0);\n break;\n }\n TriAppSkeleton::keyboard(key, x, y);\n}\n\n\nvoid GlutAppSkeleton::resize(int w, int h)\n{\n g_windowWidth = w;\n g_windowHeight = h;\n\n glViewport(0,0, (GLsizei)w, (GLsizei)h);\n}\n\n\nbool GlutAppSkeleton::initGL(int argc, char **argv)\n{\n bool ret = TriAppSkeleton::initGL(argc, argv);\n\n glClearColor(0.0, 0.0, 0.0, 0.0);\n \/\/glDisable(GL_LIGHTING);\n\n glPixelStorei(GL_UNPACK_ALIGNMENT, 1);\n\n CHECK_GL_ERROR_MACRO();\n\n return ret;\n}\n<|endoftext|>"} {"text":"source\/qt5xhb_utils.cpp: changes related with xHarbour compatibility<|endoftext|>"} {"text":"\/*\r\n * ArcEmu MMORPG Server\r\n * Copyright (C) 2005-2007 Ascent Team \r\n * Copyright (C) 2008-2010 \r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as published by\r\n * the Free Software Foundation, either version 3 of the License, or\r\n * any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see .\r\n *\r\n *\/\r\n\r\n#include \"StdAfx.h\"\r\n\r\nclass HotStreakSpellProc : public SpellProc\r\n{\r\n\tSPELL_PROC_FACTORY_FUNCTION(HotStreakSpellProc);\r\n\r\n\tvoid Init(Object* obj)\r\n\t{\r\n\t\tmCritsInARow = 0;\r\n\t}\r\n\r\n\tbool DoEffect(Unit *victim, SpellEntry *CastingSpell, uint32 flag, uint32 dmg, uint32 abs, int *dmg_overwrite)\r\n\t{\r\n\t\t\/\/ Check for classmask. Should proc only if CastingSpell is one listed in http:\/\/www.wowhead.com\/spell=44448\r\n\t\tif ( ! CheckClassMask(victim, CastingSpell) )\r\n\t\t\treturn true;\r\n\r\n\t\t\/\/ If was not a crit, reset counter and don't proc\r\n\t\tif ( ! (flag & PROC_ON_SPELL_CRIT_HIT) )\r\n\t\t{\r\n\t\t\tmCritsInARow = 0;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\t\/\/ If was not at least 2nd crit in a row, don't proc\r\n\t\tif ( ++mCritsInARow < 2 )\r\n\t\t\treturn true;\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\nprivate:\r\n\tint mCritsInARow;\r\n};\r\n\r\nvoid SpellProcMgr::SetupMage()\r\n{\r\n\tAddById( 48108, &HotStreakSpellProc::Create );\r\n}FIXED: Mage Hot Streak was triggering by any spell. r3425 introduced a new parameter in DoEffect, and it was missing in HotStreakSpellProc\/*\r\n * ArcEmu MMORPG Server\r\n * Copyright (C) 2005-2007 Ascent Team \r\n * Copyright (C) 2008-2010 \r\n *\r\n * This program is free software: you can redistribute it and\/or modify\r\n * it under the terms of the GNU Affero General Public License as published by\r\n * the Free Software Foundation, either version 3 of the License, or\r\n * any later version.\r\n *\r\n * This program is distributed in the hope that it will be useful,\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n * GNU Affero General Public License for more details.\r\n *\r\n * You should have received a copy of the GNU Affero General Public License\r\n * along with this program. If not, see .\r\n *\r\n *\/\r\n\r\n#include \"StdAfx.h\"\r\n\r\nclass HotStreakSpellProc : public SpellProc\r\n{\r\n\tSPELL_PROC_FACTORY_FUNCTION(HotStreakSpellProc);\r\n\r\n\tvoid Init(Object* obj)\r\n\t{\r\n\t\tmCritsInARow = 0;\r\n\t}\r\n\r\n\tbool DoEffect(Unit *victim, SpellEntry *CastingSpell, uint32 flag, uint32 dmg, uint32 abs, int *dmg_overwrite, uint32 weapon_damage_type)\r\n\t{\r\n\t\t\/\/ Check for classmask. Should proc only if CastingSpell is one listed in http:\/\/www.wowhead.com\/spell=44448\r\n\t\tif ( ! CheckClassMask(victim, CastingSpell) )\r\n\t\t\treturn true;\r\n\r\n\t\t\/\/ If was not a crit, reset counter and don't proc\r\n\t\tif ( ! (flag & PROC_ON_SPELL_CRIT_HIT) )\r\n\t\t{\r\n\t\t\tmCritsInARow = 0;\r\n\t\t\treturn true;\r\n\t\t}\r\n\r\n\t\t\/\/ If was not at least 2nd crit in a row, don't proc\r\n\t\tif ( ++mCritsInARow < 2 )\r\n\t\t\treturn true;\r\n\r\n\t\treturn false;\r\n\t}\r\n\r\nprivate:\r\n\tint mCritsInARow;\r\n};\r\n\r\nvoid SpellProcMgr::SetupMage()\r\n{\r\n\tAddById( 48108, &HotStreakSpellProc::Create );\r\n}<|endoftext|>"} {"text":"\/*\n Copyright (c) 2009 Tobias Koenig \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"contactswitcher.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nContactSwitcher::ContactSwitcher( QWidget *parent )\n : QWidget( parent ),\n mView( 0 )\n{\n QHBoxLayout *layout = new QHBoxLayout( this );\n\n mPreviousButton = new QPushButton( i18n( \"Previous\" ) );\n mNextButton = new QPushButton( i18n( \"Next\" ) );\n mStatusLabel = new QLabel();\n\n layout->addWidget( mPreviousButton );\n layout->addWidget( mNextButton );\n layout->addStretch( 1 );\n layout->addWidget( mStatusLabel );\n\n connect( mPreviousButton, SIGNAL( clicked() ), SLOT( previousClicked() ) );\n connect( mNextButton, SIGNAL( clicked() ), SLOT( nextClicked() ) );\n}\n\nvoid ContactSwitcher::setView( QAbstractItemView *view )\n{\n mView = view;\n\n Q_ASSERT_X( mView->model(), \"ContactSwitcher::setView\", \"The view has no model set!\" );\n\n connect( mView->model(), SIGNAL( layoutChanged() ), SLOT( updateStatus() ) );\n connect( mView->model(), SIGNAL( rowsInserted(const QModelIndex&, int, int) ), SLOT( updateStatus() ) );\n connect( mView->model(), SIGNAL( rowsRemoved(const QModelIndex&, int, int) ), SLOT( updateStatus() ) );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::nextClicked()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row() + 1;\n\n mView->selectionModel()->setCurrentIndex( mView->model()->index( row, 0 ),\n QItemSelectionModel::Rows |\n QItemSelectionModel::ClearAndSelect );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::previousClicked()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row() - 1;\n\n mView->selectionModel()->setCurrentIndex( mView->model()->index( row, 0 ),\n QItemSelectionModel::Rows |\n QItemSelectionModel::ClearAndSelect );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::updateStatus()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row();\n\n mPreviousButton->setEnabled( row != 0 );\n mNextButton->setEnabled( row != (mView->model()->rowCount() - 1) );\n\n mStatusLabel->setText( i18n( \"%1 out of %2\" ).arg( row + 1 ).arg( mView->model()->rowCount() ) );\n}\n\n#include \"contactswitcher.moc\"\nfix broken i18n call\/*\n Copyright (c) 2009 Tobias Koenig \n\n This library is free software; you can redistribute it and\/or modify it\n under the terms of the GNU Library General Public License as published by\n the Free Software Foundation; either version 2 of the License, or (at your\n option) any later version.\n\n This library is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public\n License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to the\n Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n 02110-1301, USA.\n*\/\n\n#include \"contactswitcher.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nContactSwitcher::ContactSwitcher( QWidget *parent )\n : QWidget( parent ),\n mView( 0 )\n{\n QHBoxLayout *layout = new QHBoxLayout( this );\n\n mPreviousButton = new QPushButton( i18n( \"Previous\" ) );\n mNextButton = new QPushButton( i18n( \"Next\" ) );\n mStatusLabel = new QLabel();\n\n layout->addWidget( mPreviousButton );\n layout->addWidget( mNextButton );\n layout->addStretch( 1 );\n layout->addWidget( mStatusLabel );\n\n connect( mPreviousButton, SIGNAL( clicked() ), SLOT( previousClicked() ) );\n connect( mNextButton, SIGNAL( clicked() ), SLOT( nextClicked() ) );\n}\n\nvoid ContactSwitcher::setView( QAbstractItemView *view )\n{\n mView = view;\n\n Q_ASSERT_X( mView->model(), \"ContactSwitcher::setView\", \"The view has no model set!\" );\n\n connect( mView->model(), SIGNAL( layoutChanged() ), SLOT( updateStatus() ) );\n connect( mView->model(), SIGNAL( rowsInserted(const QModelIndex&, int, int) ), SLOT( updateStatus() ) );\n connect( mView->model(), SIGNAL( rowsRemoved(const QModelIndex&, int, int) ), SLOT( updateStatus() ) );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::nextClicked()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row() + 1;\n\n mView->selectionModel()->setCurrentIndex( mView->model()->index( row, 0 ),\n QItemSelectionModel::Rows |\n QItemSelectionModel::ClearAndSelect );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::previousClicked()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row() - 1;\n\n mView->selectionModel()->setCurrentIndex( mView->model()->index( row, 0 ),\n QItemSelectionModel::Rows |\n QItemSelectionModel::ClearAndSelect );\n\n updateStatus();\n}\n\nvoid ContactSwitcher::updateStatus()\n{\n if ( !mView || !mView->model() )\n return;\n\n const QModelIndex index = mView->selectionModel()->currentIndex();\n\n int row = 0;\n if ( index.isValid() )\n row = index.row();\n\n mPreviousButton->setEnabled( row != 0 );\n mNextButton->setEnabled( row != (mView->model()->rowCount() - 1) );\n\n mStatusLabel->setText( i18n( \"%1 out of %2\", row + 1, mView->model()->rowCount() ) );\n}\n\n#include \"contactswitcher.moc\"\n<|endoftext|>"} {"text":"\n\/\/ (c) COPYRIGHT URI\/MIT 1994-1996\n\/\/ Please read the full copyright statement in the file COPYRIGH. \n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation for the CE Clause class.\n\n\/\/ $Log: Error.cc,v $\n\/\/ Revision 1.5 1996\/06\/22 00:02:46 jimg\n\/\/ Added Gui pointer to the Error oject's correct_error() and\n\/\/ display_message() mfuncs. These mfuncs now used the GUI to display\n\/\/ messages.\n\/\/\n\/\/ Revision 1.4 1996\/06\/04 21:33:22 jimg\n\/\/ Multiple connections are now possible. It is now possible to open several\n\/\/ URLs at the same time and read from them in a round-robin fashion. To do\n\/\/ this I added data source and sink parameters to the serialize and\n\/\/ deserialize mfuncs. Connect was also modified so that it manages the data\n\/\/ source `object' (which is just an XDR pointer).\n\/\/\n\/\/ Revision 1.3 1996\/06\/03 06:26:51 jimg\n\/\/ Added declarations for Errorparse() and Errorrestart().\n\/\/\n\/\/ Revision 1.2 1996\/06\/01 00:03:38 jimg\n\/\/ Added.\n\/\/\n\n#ifdef __GNUG__\n#pragma implementation\n#endif\n\nstatic char rcsid[]={\"$Id: Error.cc,v 1.5 1996\/06\/22 00:02:46 jimg Exp $\"};\n\n#include \n\n#include \"Error.h\"\n#include \"parser.h\"\n\nvoid Errorrestart(FILE *yyin);\nint Errorparse(void *arg); \/\/ defined in dds.tab.c\n\nError::Error()\n : _error_code(undefined_error), _error_message(\"\"), \n _program_type(undefined_prog_type), _program(0)\n{\n}\n\nError::Error(ErrorCode ec, String msg)\n : _error_code(ec), _error_message(msg), \n _program_type(undefined_prog_type), _program(0)\n{\n}\n\nError::Error(ErrorCode ec, String msg, ProgramType pt, char *pgm)\n : _error_code(ec), _error_message(msg), \n _program_type(pt), _program(0)\n{\n _program = new char[strlen(pgm) + 1];\n strcpy(_program, pgm);\n}\n\nError::Error(const Error ©_from)\n : _error_code(copy_from._error_code),\n _error_message(copy_from._error_message),\n _program_type(copy_from._program_type), _program(0)\n{\n _program = new char[strlen(copy_from._program) + 1];\n strcpy(_program, copy_from._program);\n} \n\nError::~Error()\n{\n delete _program;\n}\n\nError &\nError::operator=(const Error &rhs)\n{\n if (&rhs == this)\t\t\/\/ are they identical?\n\treturn *this;\n else {\n\t_error_code = rhs._error_code;\n\t_error_message = rhs._error_message;\n\t_program_type = rhs._program_type;\n\n\t_program = new char[strlen(rhs._program) + 1];\n\tstrcpy(_program, rhs._program);\n\n\treturn *this;\n }\n}\n\n\/\/ To be a valid, an Error object must either be: 1) empty, 2) contain a\n\/\/ message and a program or 3) contain only a message. Since the program is\n\/\/ optional, there is no need to test for it here. \n\/\/\n\/\/ NB: This mfunc does not test for malformed messages or programs - ones\n\/\/ where the code is defined but not the `data'.\n\nbool\nError::OK()\n{\n bool empty = ((_error_code == undefined_error) \n\t\t && (_error_message == \"\")\n\t\t && (_program_type == undefined_prog_type) \n\t\t && (_program == 0));\n\n bool message = ((_error_code != undefined_error) \n\t\t && (_error_message != \"\"));\n\n \/\/ bool program = ((_program_type != undefined_prog_type) \n \/\/ && (_program != 0))\n\n return empty || message;\n}\n\nbool\nError::parse(FILE *fp)\n{\n if (!fp) {\n\tcerr << \"Error::parse: Null input stream\" << endl;\n\treturn false;\n }\n\n Errorrestart(fp);\n\n parser_arg arg(this);\n\n bool status = Errorparse((void *)&arg) == 0;\n\n fclose(fp);\n\n \/\/ need to check the arg status because the parser may have recovered\n \/\/ from an error (and thus returned true).\n return status && arg.status() && OK();\n}\n \nvoid\nError::print(ostream &os = cout)\n{\n if (!OK()) {\n\tcerr << \"Bad Error object\" << endl;\n\treturn;\n }\n\n os << \"Error {\" << endl;\n\n if (_error_code != undefined_error) {\n\tos << \" \" << \"code = \" << _error_code << \";\" << endl;\n\tos << \" \" << \"message = \" << _error_message << \";\" << endl;\n\n\tif (_program_type != undefined_prog_type) {\n\t os << \" \" << \"program_type = \" << _program_type << \";\" << endl;\n\t os << \" \" << \"program = \" << _program << \";\" << endl;\n\t}\n } \n\n os << \"};\" << endl;\n}\n\nErrorCode\nError::error_code(ErrorCode ec = undefined_error)\n{\n if (ec == undefined_error)\n\treturn _error_code;\n else {\n\t_error_code = ec;\n\treturn _error_code;\n }\n}\n\nString\nError::error_message(String msg = \"\")\n{\n if (msg == \"\")\n\treturn String(_error_message);\n else {\n\t_error_message = msg;\n\treturn String (_error_message);\n }\n}\n\n\/\/ Check the DISPLAY environment variable, if defined, use X11. If not use\n\/\/ stderr. \nvoid\nError::display_message(Gui *gui)\n{\n if (gui->show_gui()) {\n\tString cmd = (String)\"dialog \" + _error_message + \"\\r\";\n\t(void)gui->command(cmd);\n }\n else\n\tcerr << _error_message << endl;\n}\n\nProgramType\nError::program_type(ProgramType pt = undefined_prog_type)\n{\n if (pt == undefined_prog_type)\n\treturn _program_type;\n else {\n\t_program_type = pt;\n\treturn _program_type;\n }\n}\n\nchar *\nError::program(char *pgm = 0)\n{\n if (pgm == 0)\n\treturn _program;\n else {\n\t_program = new char[strlen(pgm) + 1];\n\tstrcpy(_program, pgm);\n\treturn _program;\n }\n}\n\nString\nError::correct_error(Gui *gui)\n{\n if (OK())\n\tdisplay_message(gui);\n\n return String(\"\");\n}\nSwitched to the parser_arg object for passing parameters to\/from the Error.y parser. NB: if an error object is bad a message is sent to stderr to avoid going round and round with bad error objects! Changed the interface to display_message; Gui is by default NULL so that calling it with an empty parameter list causes the message string to be sent to stderr. Changed the interface to correct_error(); it now returns a string which is the corrected error or \"\".\n\/\/ (c) COPYRIGHT URI\/MIT 1994-1996\n\/\/ Please read the full copyright statement in the file COPYRIGH. \n\/\/\n\/\/ Authors:\n\/\/ jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)\n\n\/\/ Implementation for the Error class.\n\n\/\/ $Log: Error.cc,v $\n\/\/ Revision 1.6 1996\/08\/13 18:14:28 jimg\n\/\/ Switched to the parser_arg object for passing parameters to\/from the Error.y\n\/\/ parser. NB: if an error object is bad a message is sent to stderr to avoid\n\/\/ going round and round with bad error objects!\n\/\/ Changed the interface to display_message; Gui is by default NULL so that\n\/\/ calling it with an empty parameter list causes the message string to be sent\n\/\/ to stderr.\n\/\/ Changed the interface to correct_error(); it now returns a string which is\n\/\/ the corrected error or \"\".\n\/\/\n\/\/ Revision 1.5 1996\/06\/22 00:02:46 jimg\n\/\/ Added Gui pointer to the Error oject's correct_error() and\n\/\/ display_message() mfuncs. These mfuncs now used the GUI to display\n\/\/ messages.\n\/\/\n\/\/ Revision 1.4 1996\/06\/04 21:33:22 jimg\n\/\/ Multiple connections are now possible. It is now possible to open several\n\/\/ URLs at the same time and read from them in a round-robin fashion. To do\n\/\/ this I added data source and sink parameters to the serialize and\n\/\/ deserialize mfuncs. Connect was also modified so that it manages the data\n\/\/ source `object' (which is just an XDR pointer).\n\/\/\n\/\/ Revision 1.3 1996\/06\/03 06:26:51 jimg\n\/\/ Added declarations for Errorparse() and Errorrestart().\n\/\/\n\/\/ Revision 1.2 1996\/06\/01 00:03:38 jimg\n\/\/ Added.\n\/\/\n\n#ifdef __GNUG__\n#pragma implementation\n#endif\n\n#include \"config_dap.h\"\n\nstatic char rcsid[] __unused__ = {\"$Id: Error.cc,v 1.6 1996\/08\/13 18:14:28 jimg Exp $\"};\n\n#include \n#include \n\n#include \"Error.h\"\n#include \"parser.h\"\n\nvoid Errorrestart(FILE *yyin);\t\/\/ defined in Error.tab.c\nint Errorparse(void *arg);\t\n\nError::Error()\n : _error_code(undefined_error), _error_message(\"\"), \n _program_type(undefined_prog_type), _program(0)\n{\n}\n\nError::Error(ErrorCode ec, String msg)\n : _error_code(ec), _error_message(msg), \n _program_type(undefined_prog_type), _program(0)\n{\n}\n\nError::Error(ErrorCode ec, String msg, ProgramType pt, char *pgm)\n : _error_code(ec), _error_message(msg), \n _program_type(pt), _program(0)\n{\n _program = new char[strlen(pgm) + 1];\n strcpy(_program, pgm);\n}\n\nError::Error(const Error ©_from)\n : _error_code(copy_from._error_code),\n _error_message(copy_from._error_message),\n _program_type(copy_from._program_type), _program(0)\n{\n _program = new char[strlen(copy_from._program) + 1];\n strcpy(_program, copy_from._program);\n} \n\nError::~Error()\n{\n delete _program;\n}\n\nError &\nError::operator=(const Error &rhs)\n{\n if (&rhs == this)\t\t\/\/ are they identical?\n\treturn *this;\n else {\n\t_error_code = rhs._error_code;\n\t_error_message = rhs._error_message;\n\t_program_type = rhs._program_type;\n\n\t_program = new char[strlen(rhs._program) + 1];\n\tstrcpy(_program, rhs._program);\n\n\treturn *this;\n }\n}\n\n\/\/ To be a valid, an Error object must either be: 1) empty, 2) contain a\n\/\/ message and a program or 3) contain only a message. Since the program is\n\/\/ optional, there is no need to test for it here. \n\/\/\n\/\/ NB: This mfunc does not test for malformed messages or programs - ones\n\/\/ where the code is defined but not the `data'.\n\nbool\nError::OK()\n{\n bool empty = ((_error_code == undefined_error) \n\t\t && (_error_message == \"\")\n\t\t && (_program_type == undefined_prog_type) \n\t\t && (_program == 0));\n\n bool message = ((_error_code != undefined_error) \n\t\t && (_error_message != \"\"));\n\n \/\/ bool program = ((_program_type != undefined_prog_type) \n \/\/ && (_program != 0))\n\n return empty || message;\n}\n\nbool\nError::parse(FILE *fp)\n{\n if (!fp) {\n\tcerr << \"Error::parse: Null input stream\" << endl;\n\treturn false;\n }\n\n Errorrestart(fp);\n\n parser_arg arg(this);\n\n bool status = Errorparse((void *)&arg) == 0;\n\n fclose(fp);\n\n \/\/ STATUS is the result of the parser function; if a recoverable error\n \/\/ was found it will be true but arg.status() will be false.\n if (!status || !arg.status()) {\/\/ Check parse result\n\tcerr << \"Error parsing error object!\" << endl;\n\treturn false;\n }\n else\n\treturn OK();\t\t\/\/ Check object consistancy\n}\n \nvoid\nError::print(ostream &os = cout)\n{\n if (!OK()) {\n\tcerr << \"Bad Error object\" << endl;\n\treturn;\n }\n\n os << \"Error {\" << endl;\n\n if (_error_code != undefined_error) {\n\tos << \" \" << \"code = \" << _error_code << \";\" << endl;\n\tos << \" \" << \"message = \" << _error_message << \";\" << endl;\n\n\tif (_program_type != undefined_prog_type) {\n\t os << \" \" << \"program_type = \" << _program_type << \";\" << endl;\n\t os << \" \" << \"program = \" << _program << \";\" << endl;\n\t}\n } \n\n os << \"};\" << endl;\n}\n\nErrorCode\nError::error_code(ErrorCode ec = undefined_error)\n{\n if (ec == undefined_error)\n\treturn _error_code;\n else {\n\t_error_code = ec;\n\treturn _error_code;\n }\n}\n\nString\nError::error_message(String msg = \"\")\n{\n if (msg == \"\")\n\treturn String(_error_message);\n else {\n\t_error_message = msg;\n\treturn String (_error_message);\n }\n}\n\nvoid\nError::display_message(Gui *gui = 0)\n{\n if (gui && gui->show_gui()) {\n\tString cmd = (String)\"dialog \" + _error_message + \"\\r\";\n\tgui->command(cmd);\n }\n else\n\tcerr << _error_message << endl;\n}\n\nProgramType\nError::program_type(ProgramType pt = undefined_prog_type)\n{\n if (pt == undefined_prog_type)\n\treturn _program_type;\n else {\n\t_program_type = pt;\n\treturn _program_type;\n }\n}\n\nchar *\nError::program(char *pgm = 0)\n{\n if (pgm == 0)\n\treturn _program;\n else {\n\t_program = new char[strlen(pgm) + 1];\n\tstrcpy(_program, pgm);\n\treturn _program;\n }\n}\n\n\/\/ Assuming the object is OK, if the Error object has only a meesage, dispay\n\/\/ it in a dialog box. Once the user dismisses the dialog, return the null\n\/\/ string. However, if program() is true, then source the code it returns in\n\/\/ the Gui object and return the value of Gui::command(). Note that this\n\/\/ means that the code in the program must run itself (i.e., in addition to\n\/\/ any procedure definitions, etc. it must also contain the necessary\n\/\/ instructions to popup an initial window).\n\nString\nError::correct_error(Gui *gui)\n{\n if (!OK())\n\treturn String(\"\");\n\n if (program()) {\n\tString result;\n\n\tif (gui->response(program(), result))\n\t return result;\n\telse\n\t return String(\"\");\n }\n else {\n\tdisplay_message(gui);\n\treturn String(\"\");\n }\n}\n<|endoftext|>"} {"text":"\/*\n * HTTP server implementation.\n *\n * author: Max Kellermann \n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_upgrade.hxx\"\n#include \"direct.hxx\"\n#include \"header_writer.hxx\"\n#include \"format.h\"\n#include \"date.h\"\n#include \"growing_buffer.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_dechunk.hxx\"\n#include \"istream\/istream_memory.hxx\"\n#include \"istream\/istream_string.hxx\"\n\n#include \n\nbool\nhttp_server_connection::MaybeSend100Continue()\n{\n assert(IsValid());\n assert(request.read_state == Request::BODY);\n\n if (!request.expect_100_continue)\n return true;\n\n assert(response.istream == nullptr);\n\n request.expect_100_continue = false;\n\n \/* this string is simple enough to expect that we don't need to\n check for partial writes, not before we have sent a single byte\n of response to the peer *\/\n static const char *const response = \"HTTP\/1.1 100 Continue\\r\\n\\r\\n\";\n const size_t length = strlen(response);\n ssize_t nbytes = socket.Write(response, length);\n if (gcc_likely(nbytes == (ssize_t)length))\n return true;\n\n if (nbytes == WRITE_ERRNO)\n ErrorErrno(\"write error\");\n else if (nbytes != WRITE_DESTROYED)\n Error(\"write error\");\n return false;\n}\n\nstatic size_t\nformat_status_line(char *p, http_status_t status)\n{\n assert(http_status_is_valid(status));\n\n const char *status_string = http_status_to_string(status);\n assert(status_string != nullptr);\n size_t length = strlen(status_string);\n\n memcpy(p, \"HTTP\/1.1 \", 9);\n memcpy(p + 9, status_string, length);\n length += 9;\n p[length++] = '\\r';\n p[length++] = '\\n';\n\n return length;\n}\n\nvoid\nhttp_server_response(const struct http_server_request *request,\n http_status_t status,\n HttpHeaders &&headers,\n struct istream *body)\n{\n struct http_server_connection *connection = request->connection;\n\n assert(connection->score != HTTP_SERVER_NEW);\n assert(connection->request.request == request);\n assert(connection->socket.IsConnected());\n\n connection->request.async_ref.Poison();\n\n if (http_status_is_success(status)) {\n if (connection->score == HTTP_SERVER_FIRST)\n connection->score = HTTP_SERVER_SUCCESS;\n } else {\n connection->score = HTTP_SERVER_ERROR;\n }\n\n if (connection->request.read_state == http_server_connection::Request::BODY &&\n \/* if we didn't send \"100 Continue\" yet, we should do it now;\n we don't know if the request body will be used, but at\n least it hasn't been closed yet *\/\n !connection->MaybeSend100Continue())\n return;\n\n connection->response.status = status;\n struct istream *status_stream\n = istream_memory_new(request->pool,\n connection->response.status_buffer,\n format_status_line(connection->response.status_buffer,\n status));\n\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 256);\n\n \/* how will we transfer the body? determine length and\n transfer-encoding *\/\n\n const off_t content_length = body == nullptr\n ? 0 : istream_available(body, false);\n if (content_length == (off_t)-1) {\n \/* the response length is unknown yet *\/\n assert(!http_status_is_empty(status));\n\n if (!http_method_is_empty(request->method) && connection->keep_alive) {\n \/* keep-alive is enabled, which means that we have to\n enable chunking *\/\n header_write(&headers2, \"transfer-encoding\", \"chunked\");\n\n \/* optimized code path: if an istream_dechunked shall get\n chunked via istream_chunk, let's just skip both to\n reduce the amount of work and I\/O we have to do *\/\n if (!istream_dechunk_check_verbatim(body))\n body = istream_chunked_new(request->pool, body);\n }\n } else if (http_status_is_empty(status)) {\n assert(content_length == 0);\n } else if (body != nullptr || !http_method_is_empty(request->method)) {\n \/* fixed body size *\/\n format_uint64(connection->response.content_length_buffer, content_length);\n header_write(&headers2, \"content-length\",\n connection->response.content_length_buffer);\n }\n\n if (http_method_is_empty(request->method) && body != nullptr)\n istream_free_unused(&body);\n\n const bool upgrade = body != nullptr && http_is_upgrade(status, headers);\n if (upgrade) {\n headers.Write(*request->pool, \"connection\", \"upgrade\");\n headers.MoveToBuffer(*request->pool, \"upgrade\");\n } else if (!connection->keep_alive && !connection->request.http_1_0)\n header_write(&headers2, \"connection\", \"close\");\n\n GrowingBuffer &headers3 = headers.ToBuffer(*request->pool);\n growing_buffer_write_buffer(&headers3, \"\\r\\n\", 2);\n struct istream *header_stream = istream_gb_new(request->pool, &headers3);\n\n connection->response.length = - istream_available(status_stream, false)\n - istream_available(header_stream, false);\n\n body = istream_cat_new(request->pool, status_stream,\n header_stream, body, nullptr);\n\n connection->response.istream = body;\n istream_handler_set(connection->response.istream,\n &http_server_response_stream_handler, connection,\n connection->socket.GetDirectMask());\n\n connection->socket.SetCork(true);\n if (connection->TryWrite())\n connection->socket.SetCork(false);\n}\n\nvoid\nhttp_server_send_message(const struct http_server_request *request,\n http_status_t status, const char *msg)\n{\n HttpHeaders headers;\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 256);\n\n header_write(&headers2, \"content-type\", \"text\/plain\");\n\n#ifndef NO_DATE_HEADER\n header_write(&headers2, \"date\", http_date_format(time(nullptr)));\n#endif\n\n http_server_response(request, status, std::move(headers),\n istream_string_new(request->pool, msg));\n}\n\nvoid\nhttp_server_send_redirect(const struct http_server_request *request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(request != nullptr);\n assert(status >= 300 && status < 400);\n assert(location != nullptr);\n\n if (msg == nullptr)\n msg = \"redirection\";\n\n HttpHeaders headers;\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 1024);\n\n header_write(&headers2, \"content-type\", \"text\/plain\");\n header_write(&headers2, \"location\", location);\n\n#ifndef NO_DATE_HEADER\n header_write(&headers2, \"date\", http_date_format(time(nullptr)));\n#endif\n\n http_server_response(request, status, std::move(headers),\n istream_string_new(request->pool, msg));\n}\nhttp_server: fix shadow warning\/*\n * HTTP server implementation.\n *\n * author: Max Kellermann \n *\/\n\n#include \"Internal.hxx\"\n#include \"Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"http_upgrade.hxx\"\n#include \"direct.hxx\"\n#include \"header_writer.hxx\"\n#include \"format.h\"\n#include \"date.h\"\n#include \"growing_buffer.hxx\"\n#include \"istream_gb.hxx\"\n#include \"istream\/istream_cat.hxx\"\n#include \"istream\/istream_chunked.hxx\"\n#include \"istream\/istream_dechunk.hxx\"\n#include \"istream\/istream_memory.hxx\"\n#include \"istream\/istream_string.hxx\"\n\n#include \n\nbool\nhttp_server_connection::MaybeSend100Continue()\n{\n assert(IsValid());\n assert(request.read_state == Request::BODY);\n\n if (!request.expect_100_continue)\n return true;\n\n assert(response.istream == nullptr);\n\n request.expect_100_continue = false;\n\n \/* this string is simple enough to expect that we don't need to\n check for partial writes, not before we have sent a single byte\n of response to the peer *\/\n static const char *const response_string = \"HTTP\/1.1 100 Continue\\r\\n\\r\\n\";\n const size_t length = strlen(response_string);\n ssize_t nbytes = socket.Write(response_string, length);\n if (gcc_likely(nbytes == (ssize_t)length))\n return true;\n\n if (nbytes == WRITE_ERRNO)\n ErrorErrno(\"write error\");\n else if (nbytes != WRITE_DESTROYED)\n Error(\"write error\");\n return false;\n}\n\nstatic size_t\nformat_status_line(char *p, http_status_t status)\n{\n assert(http_status_is_valid(status));\n\n const char *status_string = http_status_to_string(status);\n assert(status_string != nullptr);\n size_t length = strlen(status_string);\n\n memcpy(p, \"HTTP\/1.1 \", 9);\n memcpy(p + 9, status_string, length);\n length += 9;\n p[length++] = '\\r';\n p[length++] = '\\n';\n\n return length;\n}\n\nvoid\nhttp_server_response(const struct http_server_request *request,\n http_status_t status,\n HttpHeaders &&headers,\n struct istream *body)\n{\n struct http_server_connection *connection = request->connection;\n\n assert(connection->score != HTTP_SERVER_NEW);\n assert(connection->request.request == request);\n assert(connection->socket.IsConnected());\n\n connection->request.async_ref.Poison();\n\n if (http_status_is_success(status)) {\n if (connection->score == HTTP_SERVER_FIRST)\n connection->score = HTTP_SERVER_SUCCESS;\n } else {\n connection->score = HTTP_SERVER_ERROR;\n }\n\n if (connection->request.read_state == http_server_connection::Request::BODY &&\n \/* if we didn't send \"100 Continue\" yet, we should do it now;\n we don't know if the request body will be used, but at\n least it hasn't been closed yet *\/\n !connection->MaybeSend100Continue())\n return;\n\n connection->response.status = status;\n struct istream *status_stream\n = istream_memory_new(request->pool,\n connection->response.status_buffer,\n format_status_line(connection->response.status_buffer,\n status));\n\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 256);\n\n \/* how will we transfer the body? determine length and\n transfer-encoding *\/\n\n const off_t content_length = body == nullptr\n ? 0 : istream_available(body, false);\n if (content_length == (off_t)-1) {\n \/* the response length is unknown yet *\/\n assert(!http_status_is_empty(status));\n\n if (!http_method_is_empty(request->method) && connection->keep_alive) {\n \/* keep-alive is enabled, which means that we have to\n enable chunking *\/\n header_write(&headers2, \"transfer-encoding\", \"chunked\");\n\n \/* optimized code path: if an istream_dechunked shall get\n chunked via istream_chunk, let's just skip both to\n reduce the amount of work and I\/O we have to do *\/\n if (!istream_dechunk_check_verbatim(body))\n body = istream_chunked_new(request->pool, body);\n }\n } else if (http_status_is_empty(status)) {\n assert(content_length == 0);\n } else if (body != nullptr || !http_method_is_empty(request->method)) {\n \/* fixed body size *\/\n format_uint64(connection->response.content_length_buffer, content_length);\n header_write(&headers2, \"content-length\",\n connection->response.content_length_buffer);\n }\n\n if (http_method_is_empty(request->method) && body != nullptr)\n istream_free_unused(&body);\n\n const bool upgrade = body != nullptr && http_is_upgrade(status, headers);\n if (upgrade) {\n headers.Write(*request->pool, \"connection\", \"upgrade\");\n headers.MoveToBuffer(*request->pool, \"upgrade\");\n } else if (!connection->keep_alive && !connection->request.http_1_0)\n header_write(&headers2, \"connection\", \"close\");\n\n GrowingBuffer &headers3 = headers.ToBuffer(*request->pool);\n growing_buffer_write_buffer(&headers3, \"\\r\\n\", 2);\n struct istream *header_stream = istream_gb_new(request->pool, &headers3);\n\n connection->response.length = - istream_available(status_stream, false)\n - istream_available(header_stream, false);\n\n body = istream_cat_new(request->pool, status_stream,\n header_stream, body, nullptr);\n\n connection->response.istream = body;\n istream_handler_set(connection->response.istream,\n &http_server_response_stream_handler, connection,\n connection->socket.GetDirectMask());\n\n connection->socket.SetCork(true);\n if (connection->TryWrite())\n connection->socket.SetCork(false);\n}\n\nvoid\nhttp_server_send_message(const struct http_server_request *request,\n http_status_t status, const char *msg)\n{\n HttpHeaders headers;\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 256);\n\n header_write(&headers2, \"content-type\", \"text\/plain\");\n\n#ifndef NO_DATE_HEADER\n header_write(&headers2, \"date\", http_date_format(time(nullptr)));\n#endif\n\n http_server_response(request, status, std::move(headers),\n istream_string_new(request->pool, msg));\n}\n\nvoid\nhttp_server_send_redirect(const struct http_server_request *request,\n http_status_t status, const char *location,\n const char *msg)\n{\n assert(request != nullptr);\n assert(status >= 300 && status < 400);\n assert(location != nullptr);\n\n if (msg == nullptr)\n msg = \"redirection\";\n\n HttpHeaders headers;\n GrowingBuffer &headers2 = headers.MakeBuffer(*request->pool, 1024);\n\n header_write(&headers2, \"content-type\", \"text\/plain\");\n header_write(&headers2, \"location\", location);\n\n#ifndef NO_DATE_HEADER\n header_write(&headers2, \"date\", http_date_format(time(nullptr)));\n#endif\n\n http_server_response(request, status, std::move(headers),\n istream_string_new(request->pool, msg));\n}\n<|endoftext|>"} {"text":"#include \"Game.h\"\n#include \"TextureManager.h\"\n#include \"Player.h\"\n#include \"Enemy.h\"\n#include \"InputHandler.h\"\n#include \"MenuState.h\"\n#include \"PlayState.h\"\n\n\/\/definition for static instance \nGame* Game::s_pInstance = 0;\n\nbool Game::init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen)\n{\t\n\tint flags = 0;\n\tif (fullscreen)\n\t{\n\t\tflags = SDL_WINDOW_FULLSCREEN;\n\t}\n\n\t\/\/attempt to initialize SDL\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == 0)\n\t{\t\n\t\tstd::cout << \"SDL init success\\n\";\n\t\t\/\/init the window\n\t\tm_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);\n\n\t\tif (m_pWindow != 0)\t\/\/window init success\n\t\t{\n\t\t\tstd::cout << \"Window creation success\\n\";\n\t\t\tm_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);\n\n\t\t\tif (m_pRenderer != 0) \/\/renderer init success\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init success\\n\";\n\t\t\t\tSDL_SetRenderDrawColor(m_pRenderer, 255, 0, 0, 255);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init failed\\n\";\n\t\t\t\treturn false;\t\/\/renderer init fail\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"window init fail\\n\";\n\t\t\treturn false;\t\/\/window init fail\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout << \"SDL init fail\\n\";\n\t\treturn false;\t\/\/SDL init fail\n\t}\n\t\n\t\/\/initialise joysticks\n\tTheInputHandler::Instance()->initialiseJoysticks();\n\n\tstd::cout << \"init success\\n\";\n\n\t\/\/load TextureManager\n\tif (!TheTextureManager::Instance()->load(\"assets\/animate-alpha.png\", \"animate\", m_pRenderer))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/creating and pushing objects\n\tm_gameObjects.push_back(new Player(new LoaderParams(100, 100, 128, 82, \"animate\")));\n\tm_gameObjects.push_back(new Enemy(new LoaderParams(300, 300, 128, 82, \"animate\")));\n\n\tm_bRunning = true;\t\/\/everything inited successfully, start the main loop\n\n\t\/\/load MENU state \n\tm_pGameStateMachine = new GameStateMachine();\n\tm_pGameStateMachine->changeState(new MenuState());\n\n\treturn true;\n}\n\nbool Game::running()\n{\n\treturn m_bRunning;\n}\n\nGameStateMachine* Game::getStateMachine()\n{\n\treturn m_pGameStateMachine;\n}\n\nvoid Game::handleEvents()\n{\t\n\t\/\/waits and listens for a quit event \n\tTheInputHandler::Instance()->update();\n\n\tif (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RETURN))\n\t{\n\t\tm_pGameStateMachine->changeState(new PlayState());\n\t}\n}\n\nvoid Game::update()\n{\n\t\/\/use GameStateMachine's update function\n\tm_pGameStateMachine->update();\n}\n\nvoid Game::render()\n{\n\tSDL_RenderClear(m_pRenderer); \/\/clear the renderer to the draw color\n\t\n\t\/\/use GameStateMachine's render function\n\tm_pGameStateMachine->render();\n\n\tSDL_RenderPresent(m_pRenderer);\t\/\/draw to the screen\n}\n\nvoid Game::clean()\n{\n\tstd::cout << \"cleaning game\\n\";\n\t\n\t\/\/close the joysticks\n\tTheInputHandler::Instance()->clean();\n\n\tSDL_DestroyWindow(m_pWindow);\n\tSDL_DestroyRenderer(m_pRenderer);\n\tSDL_Quit();\n}\n\nvoid Game::quit()\n{\n\tm_bRunning = false;\n}Frame value is set to 6 for Enemy and Player in Game.cpp#include \"Game.h\"\n#include \"TextureManager.h\"\n#include \"Player.h\"\n#include \"Enemy.h\"\n#include \"InputHandler.h\"\n#include \"MenuState.h\"\n#include \"PlayState.h\"\n\n\/\/definition for static instance \nGame* Game::s_pInstance = 0;\n\nbool Game::init(const char *title, int xpos, int ypos, int width, int height, bool fullscreen)\n{\t\n\tint flags = 0;\n\tif (fullscreen)\n\t{\n\t\tflags = SDL_WINDOW_FULLSCREEN;\n\t}\n\n\t\/\/attempt to initialize SDL\n\tif (SDL_Init(SDL_INIT_EVERYTHING) == 0)\n\t{\t\n\t\tstd::cout << \"SDL init success\\n\";\n\t\t\/\/init the window\n\t\tm_pWindow = SDL_CreateWindow(title, xpos, ypos, width, height, flags);\n\n\t\tif (m_pWindow != 0)\t\/\/window init success\n\t\t{\n\t\t\tstd::cout << \"Window creation success\\n\";\n\t\t\tm_pRenderer = SDL_CreateRenderer(m_pWindow, -1, 0);\n\n\t\t\tif (m_pRenderer != 0) \/\/renderer init success\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init success\\n\";\n\t\t\t\tSDL_SetRenderDrawColor(m_pRenderer, 255, 0, 0, 255);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tstd::cout << \"renderer init failed\\n\";\n\t\t\t\treturn false;\t\/\/renderer init fail\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tstd::cout << \"window init fail\\n\";\n\t\t\treturn false;\t\/\/window init fail\n\t\t}\n\t}\n\telse\n\t{\n\t\tstd::cout << \"SDL init fail\\n\";\n\t\treturn false;\t\/\/SDL init fail\n\t}\n\t\n\t\/\/initialise joysticks\n\tTheInputHandler::Instance()->initialiseJoysticks();\n\n\tstd::cout << \"init success\\n\";\n\n\t\/\/load TextureManager\n\tif (!TheTextureManager::Instance()->load(\"assets\/animate-alpha.png\", \"animate\", m_pRenderer))\n\t{\n\t\treturn false;\n\t}\n\n\t\/\/creating and pushing objects\n\tm_gameObjects.push_back(new Player(new LoaderParams(100, 100, 128, 82, 6, \"animate\")));\n\tm_gameObjects.push_back(new Enemy(new LoaderParams(300, 300, 128, 82, 6, \"animate\")));\n\n\tm_bRunning = true;\t\/\/everything inited successfully, start the main loop\n\n\t\/\/load MENU state \n\tm_pGameStateMachine = new GameStateMachine();\n\tm_pGameStateMachine->changeState(new MenuState());\n\n\treturn true;\n}\n\nbool Game::running()\n{\n\treturn m_bRunning;\n}\n\nGameStateMachine* Game::getStateMachine()\n{\n\treturn m_pGameStateMachine;\n}\n\nvoid Game::handleEvents()\n{\t\n\t\/\/waits and listens for a quit event \n\tTheInputHandler::Instance()->update();\n\n\tif (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RETURN))\n\t{\n\t\tm_pGameStateMachine->changeState(new PlayState());\n\t}\n}\n\nvoid Game::update()\n{\n\t\/\/use GameStateMachine's update function\n\tm_pGameStateMachine->update();\n}\n\nvoid Game::render()\n{\n\tSDL_RenderClear(m_pRenderer); \/\/clear the renderer to the draw color\n\t\n\t\/\/use GameStateMachine's render function\n\tm_pGameStateMachine->render();\n\n\tSDL_RenderPresent(m_pRenderer);\t\/\/draw to the screen\n}\n\nvoid Game::clean()\n{\n\tstd::cout << \"cleaning game\\n\";\n\t\n\t\/\/close the joysticks\n\tTheInputHandler::Instance()->clean();\n\n\tSDL_DestroyWindow(m_pWindow);\n\tSDL_DestroyRenderer(m_pRenderer);\n\tSDL_Quit();\n}\n\nvoid Game::quit()\n{\n\tm_bRunning = false;\n}<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Game Base\n\/\/ Copyright (C) 2012 Chase Warrington (staff@spacechase0.com)\n\/\/\n\/\/ This software is provided 'as-is', without any express or implied warranty.\n\/\/ In no event will the authors be held liable for any damages arising from the use of this software.\n\/\/\n\/\/ Permission is granted to anyone to use this software for any purpose,\n\/\/ including commercial applications, and to alter it and redistribute it freely,\n\/\/ subject to the following restrictions:\n\/\/\n\/\/ 1. The origin of this software must not be misrepresented;\n\/\/ you must not claim that you wrote the original software.\n\/\/ If you use this software in a product, an acknowledgment\n\/\/ in the product documentation would be appreciated but is not required.\n\/\/\n\/\/ 2. Altered source versions must be plainly marked as such,\n\/\/ and must not be misrepresented as being the original software.\n\/\/\n\/\/ 3. This notice may not be removed or altered from any source distribution.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Game.h\"\n\n#include \n\n#include \"Scene.h\"\n#include \"scenes\/GameScene.h\"\n\nconst int Game::UPDATE_RATE = 50;\nconst int Game::RENDER_RATE = 50;\n\nGame::Game()\n : isRunning( false )\n{\n}\n\nvoid Game::run()\n{\n\tinitialize();\n\n\tconst float DELTA = 1.f \/ UPDATE_RATE;\n\tfloat updateBuffer = 0.f; \/\/ Can't think of a good name. :P\n\tsf::Clock updateTimer;\n\n\tisRunning = true;\n\twhile ( isRunning )\n\t{\n\t Debug::draw(window);\n\n\t\tstd::shared_ptr< Scene > scene;\n\t\tif ( currentScene != nextScene )\n\t\t{\n\t\t\tif ( currentScene != \"\" )\n\t\t\t{\n\t\t\t\tscenes[ currentScene ]->terminate();\n\t\t\t}\n\n\t\t\tscene = scenes[ nextScene ];\n\t\t\tscene->initialize( changeEvent );\n\n\t\t\tcurrentScene = nextScene;\n\t\t}\n\t\telse if ( currentScene != \"\" )\n\t\t{\n\t\t\tscene = scenes[ currentScene ];\n\t\t}\n\n\t\twhile ( updateBuffer >= DELTA )\n\t\t{\n\t\t\tsf::Event event;\n\t\t\twhile ( window.pollEvent( event ) )\n\t\t\t{\n\t\t\t\tif ( event.type == sf::Event::Closed )\n\t\t\t\t{\n\t\t\t\t\tclose();\n\t\t\t\t}\n\n\t\t\t\tscene->update( event );\n\t\t\t}\n\n\t\t\tscene->update();\n\n\t\t\tupdateBuffer -= DELTA;\n\t\t}\n\t\tupdateBuffer += updateTimer.restart().asSeconds();\n\n\t\twindow.clear();\n\t\tscene->render( window );\n\t\twindow.display();\n\t}\n\n\tterminate();\n}\n\nvoid Game::close()\n{\n\tisRunning = false;\n}\n\nvoid Game::changeScenes( const std::string& name, SceneChangeEvent event )\n{\n\tnextScene = name;\n\tchangeEvent = event;\n}\n\nstd::shared_ptr< Scene > Game::getScene( const std::string& name )\n{\n\tif ( scenes.find( name ) == scenes.end() )\n\t{\n\t\tstd::cout << \"Failed to find scene '\" << name << \"'.\" << std::endl;\n\t\treturn std::shared_ptr< Scene >();\n\t}\n\n\treturn scenes.find( name )->second;\n}\n\nvoid Game::initialize()\n{\n\twindow.create( sf::VideoMode( 640, 480 ), \"Game Base\" );\n\twindow.setFramerateLimit( RENDER_RATE );\n\n\taddScene( \"Game\", std::shared_ptr< Scene >( new GameScene( * this ) ) );\n\n\tchangeScenes( \"Game\", SceneChangeEvent() );\n}\n\nvoid Game::terminate()\n{\n}\n\nvoid Game::addScene( const std::string& name, std::shared_ptr< Scene > scene )\n{\n\tscenes.insert( std::make_pair( name, scene ) );\n}\nLeftover stuff from the project I pulled this from. :P\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Game Base\n\/\/ Copyright (C) 2012 Chase Warrington (staff@spacechase0.com)\n\/\/\n\/\/ This software is provided 'as-is', without any express or implied warranty.\n\/\/ In no event will the authors be held liable for any damages arising from the use of this software.\n\/\/\n\/\/ Permission is granted to anyone to use this software for any purpose,\n\/\/ including commercial applications, and to alter it and redistribute it freely,\n\/\/ subject to the following restrictions:\n\/\/\n\/\/ 1. The origin of this software must not be misrepresented;\n\/\/ you must not claim that you wrote the original software.\n\/\/ If you use this software in a product, an acknowledgment\n\/\/ in the product documentation would be appreciated but is not required.\n\/\/\n\/\/ 2. Altered source versions must be plainly marked as such,\n\/\/ and must not be misrepresented as being the original software.\n\/\/\n\/\/ 3. This notice may not be removed or altered from any source distribution.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"Game.h\"\n\n#include \n\n#include \"Scene.h\"\n#include \"scenes\/GameScene.h\"\n\nconst int Game::UPDATE_RATE = 50;\nconst int Game::RENDER_RATE = 50;\n\nGame::Game()\n : isRunning( false )\n{\n}\n\nvoid Game::run()\n{\n\tinitialize();\n\n\tconst float DELTA = 1.f \/ UPDATE_RATE;\n\tfloat updateBuffer = 0.f; \/\/ Can't think of a good name. :P\n\tsf::Clock updateTimer;\n\n\tisRunning = true;\n\twhile ( isRunning )\n\t{\n\t\tstd::shared_ptr< Scene > scene;\n\t\tif ( currentScene != nextScene )\n\t\t{\n\t\t\tif ( currentScene != \"\" )\n\t\t\t{\n\t\t\t\tscenes[ currentScene ]->terminate();\n\t\t\t}\n\n\t\t\tscene = scenes[ nextScene ];\n\t\t\tscene->initialize( changeEvent );\n\n\t\t\tcurrentScene = nextScene;\n\t\t}\n\t\telse if ( currentScene != \"\" )\n\t\t{\n\t\t\tscene = scenes[ currentScene ];\n\t\t}\n\n\t\twhile ( updateBuffer >= DELTA )\n\t\t{\n\t\t\tsf::Event event;\n\t\t\twhile ( window.pollEvent( event ) )\n\t\t\t{\n\t\t\t\tif ( event.type == sf::Event::Closed )\n\t\t\t\t{\n\t\t\t\t\tclose();\n\t\t\t\t}\n\n\t\t\t\tscene->update( event );\n\t\t\t}\n\n\t\t\tscene->update();\n\n\t\t\tupdateBuffer -= DELTA;\n\t\t}\n\t\tupdateBuffer += updateTimer.restart().asSeconds();\n\n\t\twindow.clear();\n\t\tscene->render( window );\n\t\twindow.display();\n\t}\n\n\tterminate();\n}\n\nvoid Game::close()\n{\n\tisRunning = false;\n}\n\nvoid Game::changeScenes( const std::string& name, SceneChangeEvent event )\n{\n\tnextScene = name;\n\tchangeEvent = event;\n}\n\nstd::shared_ptr< Scene > Game::getScene( const std::string& name )\n{\n\tif ( scenes.find( name ) == scenes.end() )\n\t{\n\t\tstd::cout << \"Failed to find scene '\" << name << \"'.\" << std::endl;\n\t\treturn std::shared_ptr< Scene >();\n\t}\n\n\treturn scenes.find( name )->second;\n}\n\nvoid Game::initialize()\n{\n\twindow.create( sf::VideoMode( 640, 480 ), \"Game Base\" );\n\twindow.setFramerateLimit( RENDER_RATE );\n\n\taddScene( \"Game\", std::shared_ptr< Scene >( new GameScene( * this ) ) );\n\n\tchangeScenes( \"Game\", SceneChangeEvent() );\n}\n\nvoid Game::terminate()\n{\n}\n\nvoid Game::addScene( const std::string& name, std::shared_ptr< Scene > scene )\n{\n\tscenes.insert( std::make_pair( name, scene ) );\n}\n<|endoftext|>"} {"text":"\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: basencSupplier.cpp,v 1.5 2006\/05\/25 16:53:58 dfugate Exp $\"\n*\n* who when what\n* -------- --------- ----------------------------------------------\n*\/\n\n#include \"basencSupplier.h\"\n#include \n\n\/\/-----------------------------------------------------------------------------\nBaseSupplier::BaseSupplier(const char* channelName) :\n BaseHelper(channelName)\n{\n \/\/no-op\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::init(CosNaming::NamingContext_ptr nc_p)\n{\n \/\/delegate to common helper class\n BaseHelper::init(nc_p);\n \n \/\/get the supplier admin\n supplierAdmin_m = notifyChannel_m->new_for_suppliers(ifgop_m, adminID_m);\n ACE_ASSERT (!CORBA::is_nil(supplierAdmin_m.in()));\n \n \/\/connect the supplier admin which really means connect \n \/\/ourselves to the proxy consumer\n this->connect();\n \n}\n\/\/-----------------------------------------------------------------------------\nBaseSupplier::~BaseSupplier()\n{\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::connect()\n{\n \/\/turn ourselves into a CORBA object\n corbaRef_m = acsnc::OSPushSupplier::_duplicate(getCORBARef());\n ACE_ASSERT(!CORBA::is_nil(corbaRef_m.in()));\n \n \/\/get the proxy consumer from the supplier admin.\n CosNotifyChannelAdmin::ProxyConsumer_var proxyconsumer =\n\tsupplierAdmin_m->obtain_notification_push_consumer(CosNotifyChannelAdmin::STRUCTURED_EVENT, \n\t\t\t\t\t\t\t proxyConsumerID_m);\n ACE_ASSERT(!CORBA::is_nil(proxyconsumer.in()));\n \n \/\/ narrow\n proxyConsumer_m = CosNotifyChannelAdmin::StructuredProxyPushConsumer::_narrow(proxyconsumer.in());\n ACE_ASSERT(!CORBA::is_nil(proxyConsumer_m.in()));\n\n \/\/final piece of code connects us to the channel\n proxyConsumer_m->connect_structured_push_supplier(corbaRef_m.in());\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::disconnect()\n{\n \/\/take care of the proxy consumer\n ACE_ASSERT(!CORBA::is_nil(proxyConsumer_m.in()));\n \/\/sole ownership of the proxy\n CosNotifyChannelAdmin::StructuredProxyPushConsumer_var proxyConsumer = proxyConsumer_m;\n proxyConsumer_m=CosNotifyChannelAdmin::StructuredProxyPushConsumer::_nil(); \n \/\/disconnect from the proxy consumer\n proxyConsumer->disconnect_structured_push_consumer();\n\n \/\/take care of the supplier admin\n ACE_ASSERT(!CORBA::is_nil(supplierAdmin_m.in()));\n \/\/sole ownership of the proxy\n CosNotifyChannelAdmin::SupplierAdmin_var supplierAdmin = supplierAdmin_m;\n supplierAdmin_m = CosNotifyChannelAdmin::SupplierAdmin::_nil();\n \/\/destroy it\n supplierAdmin->destroy();\n\n \/\/DWF-need some code here to remove our own CORBA servant???\n\n BaseHelper::disconnect();\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::subscription_change(const CosNotification::EventTypeSeq &a,\n\t\t\t\t const CosNotification::EventTypeSeq &b)\n throw(CORBA::SystemException,\n\t CosNotifyComm::InvalidEventType)\n{\n \/\/No-Op.\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::publishEvent(const CosNotification::StructuredEvent& event)\n{\n ACE_ASSERT(!CORBA::is_nil(this->proxyConsumer_m.in()));\n \/\/pass it on to the proxy consumer\n try\n\t{\n\tproxyConsumer_m->push_structured_event(event);\n\t}\n catch(CORBA::COMM_FAILURE ex)\n\t{\n\tstd::cerr << \"ERROR (CORBA::COMM_FAILURE): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n catch(CORBA::TRANSIENT ex)\n\t{\n\tstd::cerr << \"ERROR (CORBA::TRANSIENT): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n catch(...)\n\t{\n\tstd::cerr << \"ERROR (Unkwown): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::disconnect_structured_push_supplier()\n throw(CORBA::SystemException)\n{\n \/\/ No-Op.\n}\n\/\/-----------------------------------------------------------------------------\nacsnc::OSPushSupplier_ptr\nBaseSupplier::getCORBARef()\n{\n acsnc::OSPushSupplier_var retVal = this->_this();\n return retVal._retn();\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::populateHeader(CosNotification::StructuredEvent& event)\n{\n \/\/just delegate this to other functions\n event.header.fixed_header.event_type.domain_name = CORBA::string_dup(getChannelDomain());\n event.header.fixed_header.event_type.type_name = CORBA::string_dup(getEventType()); \n event.header.fixed_header.event_name = CORBA::string_dup(getEventName());\n\n \/\/no reason to put anything in the variable header.\n event.header.variable_header.length(0);\n}\n\nput deactivation of corba object in the dicvonnect method\/*******************************************************************************\n* ALMA - Atacama Large Millimiter Array\n* (c) European Southern Observatory, 2002\n* Copyright by ESO (in the framework of the ALMA collaboration)\n* and Cosylab 2002, All rights reserved\n*\n* This library is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* This library is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with this library; if not, write to the Free Software\n* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n*\n* \"@(#) $Id: basencSupplier.cpp,v 1.6 2006\/10\/24 15:30:18 bjeram Exp $\"\n*\n* who when what\n* -------- --------- ----------------------------------------------\n*\/\n\n#include \"basencSupplier.h\"\n#include \n\n\/\/-----------------------------------------------------------------------------\nBaseSupplier::BaseSupplier(const char* channelName) :\n BaseHelper(channelName)\n{\n \/\/no-op\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::init(CosNaming::NamingContext_ptr nc_p)\n{\n \/\/delegate to common helper class\n BaseHelper::init(nc_p);\n \n \/\/get the supplier admin\n supplierAdmin_m = notifyChannel_m->new_for_suppliers(ifgop_m, adminID_m);\n ACE_ASSERT (!CORBA::is_nil(supplierAdmin_m.in()));\n \n \/\/connect the supplier admin which really means connect \n \/\/ourselves to the proxy consumer\n this->connect();\n \n}\n\/\/-----------------------------------------------------------------------------\nBaseSupplier::~BaseSupplier()\n{\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::connect()\n{\n \/\/turn ourselves into a CORBA object\n corbaRef_m = acsnc::OSPushSupplier::_duplicate(getCORBARef());\n ACE_ASSERT(!CORBA::is_nil(corbaRef_m.in()));\n \n \/\/get the proxy consumer from the supplier admin.\n CosNotifyChannelAdmin::ProxyConsumer_var proxyconsumer =\n\tsupplierAdmin_m->obtain_notification_push_consumer(CosNotifyChannelAdmin::STRUCTURED_EVENT, \n\t\t\t\t\t\t\t proxyConsumerID_m);\n ACE_ASSERT(!CORBA::is_nil(proxyconsumer.in()));\n \n \/\/ narrow\n proxyConsumer_m = CosNotifyChannelAdmin::StructuredProxyPushConsumer::_narrow(proxyconsumer.in());\n ACE_ASSERT(!CORBA::is_nil(proxyConsumer_m.in()));\n\n \/\/final piece of code connects us to the channel\n proxyConsumer_m->connect_structured_push_supplier(corbaRef_m.in());\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::disconnect()\n{\n \/\/take care of the proxy consumer\n ACE_ASSERT(!CORBA::is_nil(proxyConsumer_m.in()));\n \/\/sole ownership of the proxy\n CosNotifyChannelAdmin::StructuredProxyPushConsumer_var proxyConsumer = proxyConsumer_m;\n proxyConsumer_m=CosNotifyChannelAdmin::StructuredProxyPushConsumer::_nil(); \n \/\/disconnect from the proxy consumer\n proxyConsumer->disconnect_structured_push_consumer();\n\n \/\/take care of the supplier admin\n ACE_ASSERT(!CORBA::is_nil(supplierAdmin_m.in()));\n \/\/sole ownership of the proxy\n CosNotifyChannelAdmin::SupplierAdmin_var supplierAdmin = supplierAdmin_m;\n supplierAdmin_m = CosNotifyChannelAdmin::SupplierAdmin::_nil();\n \/\/destroy it\n supplierAdmin->destroy();\n\n \/\/DWF-need some code here to remove our own CORBA servant???\n this->_default_POA()->deactivate_object(*(this->_default_POA()->servant_to_id(this)));\n \n BaseHelper::disconnect();\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::subscription_change(const CosNotification::EventTypeSeq &a,\n\t\t\t\t const CosNotification::EventTypeSeq &b)\n throw(CORBA::SystemException,\n\t CosNotifyComm::InvalidEventType)\n{\n \/\/No-Op.\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::publishEvent(const CosNotification::StructuredEvent& event)\n{\n ACE_ASSERT(!CORBA::is_nil(this->proxyConsumer_m.in()));\n \/\/pass it on to the proxy consumer\n try\n\t{\n\tproxyConsumer_m->push_structured_event(event);\n\t}\n catch(CORBA::COMM_FAILURE ex)\n\t{\n\tstd::cerr << \"ERROR (CORBA::COMM_FAILURE): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n catch(CORBA::TRANSIENT ex)\n\t{\n\tstd::cerr << \"ERROR (CORBA::TRANSIENT): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n catch(...)\n\t{\n\tstd::cerr << \"ERROR (Unkwown): \";\n\tstd::cerr << \"failed to send an event of type '\";\n\tstd::cerr << event.header.fixed_header.event_type.type_name;\n\tstd::cerr << \"' to the '\";\n\tstd::cerr << channelName_mp << \"' channel!\" << std::endl;\n\t}\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::disconnect_structured_push_supplier()\n throw(CORBA::SystemException)\n{\n \/\/ No-Op.\n}\n\/\/-----------------------------------------------------------------------------\nacsnc::OSPushSupplier_ptr\nBaseSupplier::getCORBARef()\n{\n acsnc::OSPushSupplier_var retVal = this->_this();\n return retVal._retn();\n}\n\/\/-----------------------------------------------------------------------------\nvoid\nBaseSupplier::populateHeader(CosNotification::StructuredEvent& event)\n{\n \/\/just delegate this to other functions\n event.header.fixed_header.event_type.domain_name = CORBA::string_dup(getChannelDomain());\n event.header.fixed_header.event_type.type_name = CORBA::string_dup(getEventType()); \n event.header.fixed_header.event_name = CORBA::string_dup(getEventName());\n\n \/\/no reason to put anything in the variable header.\n event.header.variable_header.length(0);\n}\n\n<|endoftext|>"} {"text":"\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"face_quad.h\"\n#include \"edge_edge2.h\"\n\nnamespace libMesh\n{\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Quad class member functions\nunsigned int Quad::key (const unsigned int s) const\n{\n libmesh_assert (s < this->n_sides());\n \n switch (s)\n {\n case 0:\n return\n\tthis->compute_key (this->node(0),\n\t\t\t this->node(1));\n \n case 1:\n return\n\tthis->compute_key (this->node(1),\n\t\t\t this->node(2));\n\t\n case 2:\n return\n\tthis->compute_key (this->node(2),\n\t\t\t this->node(3));\n\t\n case 3:\n return\n\tthis->compute_key (this->node(3),\n\t\t\t this->node(0));\t\n }\n\n\n \/\/ We will never get here... Look at the code above.\n libmesh_error(); \n return 0;\n}\n\n\n\nAutoPtr Quad::side (const unsigned int i) const\n{\n libmesh_assert (i < this->n_sides());\n\n Elem* edge = new Edge2;\n\n switch (i)\n {\n case 0:\n {\n\tedge->set_node(0) = this->get_node(0);\n\tedge->set_node(1) = this->get_node(1);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 1:\n {\n\tedge->set_node(0) = this->get_node(1);\n\tedge->set_node(1) = this->get_node(2);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 2:\n {\n\tedge->set_node(0) = this->get_node(2);\n\tedge->set_node(1) = this->get_node(3);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 3:\n {\n\tedge->set_node(0) = this->get_node(3);\n\tedge->set_node(1) = this->get_node(0);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n default:\n {\n\tlibmesh_error();\n }\n }\n\n\n \/\/ We will never get here... Look at the code above.\n libmesh_error(); \n AutoPtr ap_edge(edge);\n return ap_edge;\n}\n\n\n\nbool Quad::is_child_on_side(const unsigned int c,\n const unsigned int s) const\n{\n libmesh_assert (c < this->n_children());\n libmesh_assert (s < this->n_sides());\n\n \/\/ A quad's children and nodes don't share the same ordering:\n \/\/ child 2 and 3 are swapped;\n unsigned int n = (c < 2) ? c : 5-c;\n return (n == s || n == (s+1)%4);\n}\n\n\n\nunsigned int Quad::opposite_side(const unsigned int side) const\n{\n libmesh_assert(side < 4);\n\n return (side + 2) % 4;\n}\n\n\n\nunsigned int Quad::opposite_node(const unsigned int node,\n const unsigned int side) const\n{\n libmesh_assert(node < 8);\n libmesh_assert(node < this->n_nodes());\n libmesh_assert(side < this->n_sides());\n libmesh_assert(this->is_node_on_side(node, side));\n\n unsigned int opposite;\n\n switch (side)\n {\n case 0:\n case 2:\n static const unsigned char side02_nodes_map[] =\n {3, 2, 1, 0, 6, 255, 4, 255};\n return side02_nodes_map[node];\n break;\n case 1:\n case 3:\n static const unsigned char side13_nodes_map[] =\n {1, 0, 3, 2, 255, 7, 255, 5};\n return side13_nodes_map[node];\n break;\n }\n\n libmesh_error();\n return 255;\n}\n\n\nReal Quad::quality (const ElemQuality q) const\n{\n switch (q)\n {\n \n \/**\n * Compue the min\/max diagonal ratio.\n * This is modeled after the Hex element\n *\/\n case DISTORTION:\n case DIAGONAL:\n case STRETCH:\n {\n\t\/\/ Diagonal between node 0 and node 2\n\tconst Real d02 = this->length(0,2);\n\n\t\/\/ Diagonal between node 1 and node 3\n\tconst Real d13 = this->length(1,3);\n\n\t\/\/ Find the biggest and smallest diagonals\n if ( (d02 > 0.) && (d13 >0.) )\n if (d02 < d13) return d02 \/ d13;\n else return d13 \/ d02;\n else\n return 0.;\n\tbreak;\n }\n\n default:\n return Elem::quality(q);\n }\n \n \/**\n * I don't know what to do for this metric. \n * Maybe the base class knows. We won't get\n * here because of the default case above.\n *\/\n return Elem::quality(q);\n}\n\n\n\n\n\n\nstd::pair Quad::qual_bounds (const ElemQuality q) const\n{\n std::pair bounds;\n \n switch (q)\n {\n\n case ASPECT_RATIO:\n bounds.first = 1.;\n bounds.second = 4.;\n break;\n \n case SKEW:\n bounds.first = 0.;\n bounds.second = 0.5;\n break;\n\n case TAPER:\n bounds.first = 0.;\n bounds.second = 0.7;\n break;\n\n case WARP:\n bounds.first = 0.9;\n bounds.second = 1.;\n break;\n \n case STRETCH:\n bounds.first = 0.25;\n bounds.second = 1.;\n break;\n\n case MIN_ANGLE:\n bounds.first = 45.;\n bounds.second = 90.;\n break;\n \n case MAX_ANGLE:\n bounds.first = 90.;\n bounds.second = 135.;\n break;\n \n case CONDITION:\n bounds.first = 1.;\n bounds.second = 4.;\n break;\n\n case JACOBIAN:\n bounds.first = 0.5;\n bounds.second = 1.;\n break;\n \n case SHEAR:\n case SHAPE:\n case SIZE:\n bounds.first = 0.3;\n bounds.second = 1.;\n break;\n \n case DISTORTION:\n bounds.first = 0.6;\n bounds.second = 1.;\n break;\n \n default:\n libMesh::out << \"Warning: Invalid quality measure chosen.\" << std::endl;\n bounds.first = -1;\n bounds.second = -1;\n }\n\n return bounds;\n}\n\n\n\n\nconst unsigned short int Quad::_second_order_adjacent_vertices[4][2] = \n{\n {0, 1}, \/\/ vertices adjacent to node 4 \n {1, 2}, \/\/ vertices adjacent to node 5 \n {2, 3}, \/\/ vertices adjacent to node 6 \n {0, 3} \/\/ vertices adjacent to node 7 \n};\n\n\n\nconst unsigned short int Quad::_second_order_vertex_child_number[9] =\n{\n 99,99,99,99, \/\/ Vertices\n 0,1,2,0, \/\/ Edges\n 0 \/\/ Interior\n};\n\n\n\nconst unsigned short int Quad::_second_order_vertex_child_index[9] =\n{\n 99,99,99,99, \/\/ Vertices\n 1,2,3,3, \/\/ Edges\n 2 \/\/ Interior\n};\n\n} \/\/ namespace libMesh\nFix unused variable warning in DEBUG mode.\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2008 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"face_quad.h\"\n#include \"edge_edge2.h\"\n\nnamespace libMesh\n{\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Quad class member functions\nunsigned int Quad::key (const unsigned int s) const\n{\n libmesh_assert (s < this->n_sides());\n \n switch (s)\n {\n case 0:\n return\n\tthis->compute_key (this->node(0),\n\t\t\t this->node(1));\n \n case 1:\n return\n\tthis->compute_key (this->node(1),\n\t\t\t this->node(2));\n\t\n case 2:\n return\n\tthis->compute_key (this->node(2),\n\t\t\t this->node(3));\n\t\n case 3:\n return\n\tthis->compute_key (this->node(3),\n\t\t\t this->node(0));\t\n }\n\n\n \/\/ We will never get here... Look at the code above.\n libmesh_error(); \n return 0;\n}\n\n\n\nAutoPtr Quad::side (const unsigned int i) const\n{\n libmesh_assert (i < this->n_sides());\n\n Elem* edge = new Edge2;\n\n switch (i)\n {\n case 0:\n {\n\tedge->set_node(0) = this->get_node(0);\n\tedge->set_node(1) = this->get_node(1);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 1:\n {\n\tedge->set_node(0) = this->get_node(1);\n\tedge->set_node(1) = this->get_node(2);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 2:\n {\n\tedge->set_node(0) = this->get_node(2);\n\tedge->set_node(1) = this->get_node(3);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n case 3:\n {\n\tedge->set_node(0) = this->get_node(3);\n\tedge->set_node(1) = this->get_node(0);\n\t\n AutoPtr ap_edge(edge);\n\treturn ap_edge;\n }\n default:\n {\n\tlibmesh_error();\n }\n }\n\n\n \/\/ We will never get here... Look at the code above.\n libmesh_error(); \n AutoPtr ap_edge(edge);\n return ap_edge;\n}\n\n\n\nbool Quad::is_child_on_side(const unsigned int c,\n const unsigned int s) const\n{\n libmesh_assert (c < this->n_children());\n libmesh_assert (s < this->n_sides());\n\n \/\/ A quad's children and nodes don't share the same ordering:\n \/\/ child 2 and 3 are swapped;\n unsigned int n = (c < 2) ? c : 5-c;\n return (n == s || n == (s+1)%4);\n}\n\n\n\nunsigned int Quad::opposite_side(const unsigned int side) const\n{\n libmesh_assert(side < 4);\n\n return (side + 2) % 4;\n}\n\n\n\nunsigned int Quad::opposite_node(const unsigned int node,\n const unsigned int side) const\n{\n libmesh_assert(node < 8);\n libmesh_assert(node < this->n_nodes());\n libmesh_assert(side < this->n_sides());\n libmesh_assert(this->is_node_on_side(node, side));\n\n \/\/unsigned int opposite;\n\n switch (side)\n {\n case 0:\n case 2:\n static const unsigned char side02_nodes_map[] =\n {3, 2, 1, 0, 6, 255, 4, 255};\n return side02_nodes_map[node];\n break;\n case 1:\n case 3:\n static const unsigned char side13_nodes_map[] =\n {1, 0, 3, 2, 255, 7, 255, 5};\n return side13_nodes_map[node];\n break;\n }\n\n libmesh_error();\n return 255;\n}\n\n\nReal Quad::quality (const ElemQuality q) const\n{\n switch (q)\n {\n \n \/**\n * Compue the min\/max diagonal ratio.\n * This is modeled after the Hex element\n *\/\n case DISTORTION:\n case DIAGONAL:\n case STRETCH:\n {\n\t\/\/ Diagonal between node 0 and node 2\n\tconst Real d02 = this->length(0,2);\n\n\t\/\/ Diagonal between node 1 and node 3\n\tconst Real d13 = this->length(1,3);\n\n\t\/\/ Find the biggest and smallest diagonals\n if ( (d02 > 0.) && (d13 >0.) )\n if (d02 < d13) return d02 \/ d13;\n else return d13 \/ d02;\n else\n return 0.;\n\tbreak;\n }\n\n default:\n return Elem::quality(q);\n }\n \n \/**\n * I don't know what to do for this metric. \n * Maybe the base class knows. We won't get\n * here because of the default case above.\n *\/\n return Elem::quality(q);\n}\n\n\n\n\n\n\nstd::pair Quad::qual_bounds (const ElemQuality q) const\n{\n std::pair bounds;\n \n switch (q)\n {\n\n case ASPECT_RATIO:\n bounds.first = 1.;\n bounds.second = 4.;\n break;\n \n case SKEW:\n bounds.first = 0.;\n bounds.second = 0.5;\n break;\n\n case TAPER:\n bounds.first = 0.;\n bounds.second = 0.7;\n break;\n\n case WARP:\n bounds.first = 0.9;\n bounds.second = 1.;\n break;\n \n case STRETCH:\n bounds.first = 0.25;\n bounds.second = 1.;\n break;\n\n case MIN_ANGLE:\n bounds.first = 45.;\n bounds.second = 90.;\n break;\n \n case MAX_ANGLE:\n bounds.first = 90.;\n bounds.second = 135.;\n break;\n \n case CONDITION:\n bounds.first = 1.;\n bounds.second = 4.;\n break;\n\n case JACOBIAN:\n bounds.first = 0.5;\n bounds.second = 1.;\n break;\n \n case SHEAR:\n case SHAPE:\n case SIZE:\n bounds.first = 0.3;\n bounds.second = 1.;\n break;\n \n case DISTORTION:\n bounds.first = 0.6;\n bounds.second = 1.;\n break;\n \n default:\n libMesh::out << \"Warning: Invalid quality measure chosen.\" << std::endl;\n bounds.first = -1;\n bounds.second = -1;\n }\n\n return bounds;\n}\n\n\n\n\nconst unsigned short int Quad::_second_order_adjacent_vertices[4][2] = \n{\n {0, 1}, \/\/ vertices adjacent to node 4 \n {1, 2}, \/\/ vertices adjacent to node 5 \n {2, 3}, \/\/ vertices adjacent to node 6 \n {0, 3} \/\/ vertices adjacent to node 7 \n};\n\n\n\nconst unsigned short int Quad::_second_order_vertex_child_number[9] =\n{\n 99,99,99,99, \/\/ Vertices\n 0,1,2,0, \/\/ Edges\n 0 \/\/ Interior\n};\n\n\n\nconst unsigned short int Quad::_second_order_vertex_child_index[9] =\n{\n 99,99,99,99, \/\/ Vertices\n 1,2,3,3, \/\/ Edges\n 2 \/\/ Interior\n};\n\n} \/\/ namespace libMesh\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"Header.h\"\n#include \"EasyBMP.h\"\n#define _CRT_SECURE_NO_WARNINGS\n\nint main() {\n\tfor (int count = 0; count < 16; count++) {\n\t\tint sqSize = (2 << 3) + 1;\n\t\tint x = sqSize;\n\t\tint y = sqSize;\n\t\tint z = 50;\n\t\tWorld_Map Plot(x, y, z);\n\t\t\/\/Diamond_Square terrain(5, 100);\n\t\tBMP *image = new BMP;\n\t\t\/*\n\t\tint *tl = (int*)calloc(sizeof(int), 4);\n\t\tint *tr = (int*)calloc(sizeof(int), 4);\n\t\tint *br = (int*)calloc(sizeof(int), 4);\n\t\tint *bl = (int*)calloc(sizeof(int), 4);\n\t\ttl[0] = 0;\n\t\ttl[1] = terrain.get_size() - 1;\n\t\ttr[0] = terrain.get_size() - 1;\n\t\ttr[1] = terrain.get_size() - 1;\n\t\tbr[0] = terrain.get_size() - 1;\n\t\tbr[1] = 0;\n\t\tbl[0] = 0;\n\t\tbl[1] = 0;\n\t\tterrain.square(tl, tr, br, bl);\n\t\t*\/\n\t\t\/\/Generate_Shapes shape(4);\n\t\t\/\/shape.make2dterrainimage(terrain.get_array2d());\n\n\t\tDS* obj = new DS(sqSize);\n\t\tobj->DiamondSquare(z - 1);\n\t\tPlot.convert_to_3d(obj->get_grid());\n\t\tIsometric_Render iso(&Plot, image, 0, x - 1, 0, y - 1, 0, z - 1);\n\t\timage->SetSize(iso.width + DEBUGGING_WIDTH, iso.height + DEBUGGING_HEIGHT);\n\n\t\t\/\/for (int level = x + y + z - 3; level >=3; level--) {\n\t\t\/\/for (int level = 3; level < x + y + z - 3; level++) {\n\t\tfor (int level = ((count >> 3) % 2) ? 3 : x + y + z - 3; ((count >> 3) % 2) ? (level < x + y + z - 3) : (level >= 3); level += ((count >> 3) % 2) ? 1 : -1) {\n\t\n\t\t\t\/\/cout << \"hi\" << endl;\n\t\t\t\n\t\t\t\/\/for (i = 1; i < x - 1; i++) {\n\t\t\t\/\/for (i = x - 1; i >= 1; i--) {\n\t\t\tfor (int i = ((count >> 2) % 2) ? x - 1 : 1; ((count >> 2) % 2) ? (i >= 1) : (i < x - 1); i += ((count >> 2) % 2) ? -1 : 1) {\n\t\t\t\n\t\t\t\t\/\/cout << \"can\" << endl;\n\t\t\t\n\t\t\t\t\/\/for (j = 1; j < y - 1; j++) {\n\t\t\t\t\/\/for (j = y - 1; j >= 1; j--) {\n\t\t\t\tfor (int j = ((count >> 1) % 2) ? y - 1 : 1; ((count >> 1) % 2) ? (j >= 1) : (j < y - 1); j += ((count >> 1) % 2) ? -1 : 1) {\n\t\t\t\t\n\t\t\t\t\t\/\/cout << \"i\" << endl;\n\t\t\t\t\t\n\t\t\t\t\t\/\/for (k = z-1; k >= 1; k--) {\n\t\t\t\t\t\/\/for (k = 1; k < z - 1; k++) {\n\t\t\t\t\tfor (int k = ((count >> 0) % 2) ? z - 1 : 1; ((count >> 0) % 2) ? (k >= 1) : (k < z - 1); k += ((count >> 0) % 2) ? -1 : 1) {\n\t\t\t\t\t\n\t\t\t\t\t\t\/\/cout << \"help\" << endl;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((i + j + k) == level) {\n\t\t\t\t\t\t\tif (Plot.map[i][j][k]->isSet == 1) {\n\t\t\t\t\t\t\t\t\/*Plot.map[i][j][k]->r = 192;\n\t\t\t\t\t\t\t\tPlot.map[i][j][k]->g = 192;\n\t\t\t\t\t\t\t\tPlot.map[i][j][k]->b = 192;\n\t\t\t\t\t\t\t\t*\/iso.place_cube(i, j, k);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\ttime_t now = time(NULL);\n\t\tstruct tm *time_info = new tm;\n\t\tlocaltime_s(time_info, &now);\n\t\tif (time_info) {}\n\t\t\/\/time_t t = time(0); \/\/ get time now\n\t\t\/\/struct tm * now = localtime_s(&t);\n\t\tstd::stringstream buffer;\n\t\t\n\t\t\/\/buffer << \"sets\/isometric\"\n\t\t\t\/*\t<< (time_info->tm_year + 1900) << '.'\n\t\t\t<< (time_info->tm_mon + 1) << '.'\n\t\t\t<< time_info->tm_mday << '-'\n\t\t\t<< time_info->tm_hour << \"h_\"\n\t\t\t<< time_info->tm_min << \"m_\"\n\t\t\t<< time_info->tm_sec << \"s\"\n\t\t\t*\/\n\t\tbuffer << \"sets\/\"\n\t\t\t<< (count >> 3)%2 << (count >> 2) % 2 << (count >> 1) % 2 << (count >> 0) % 2\n\t\t\t\t\t<< \".bmp\";\n\t\timage->WriteToFile(buffer.str().c_str());\n\t\tdelete time_info;\n\t\t\/\/delete[]iso;\n\t\t\/\/delete[]obj;\n\t\t\/\/delete[]image;\n\t\t\/\/delete[]Plot;\n\t\t\/\/delete[]terrain;\n\t\t\n\t}\n\treturn EXIT_SUCCESS;\n}\nadded depricated code#include \n#include \n#include \n#include \"Header.h\"\n#include \"EasyBMP.h\"\n#define _CRT_SECURE_NO_WARNINGS\n\nint main() {\n\tfor (int count = 0; count < 16; count++) {\n\t\tint sqSize = (2 << 3) + 1;\n\t\tint x = sqSize;\n\t\tint y = sqSize;\n\t\tint z = 50;\n\t\tWorld_Map Plot(x, y, z);\n\t\t\/\/Diamond_Square terrain(5, 100);\n\t\tBMP *image = new BMP;\n\t\t\/*\n\t\tint *tl = (int*)calloc(sizeof(int), 4);\n\t\tint *tr = (int*)calloc(sizeof(int), 4);\n\t\tint *br = (int*)calloc(sizeof(int), 4);\n\t\tint *bl = (int*)calloc(sizeof(int), 4);\n\t\ttl[0] = 0;\n\t\ttl[1] = terrain.get_size() - 1;\n\t\ttr[0] = terrain.get_size() - 1;\n\t\ttr[1] = terrain.get_size() - 1;\n\t\tbr[0] = terrain.get_size() - 1;\n\t\tbr[1] = 0;\n\t\tbl[0] = 0;\n\t\tbl[1] = 0;\n\t\tterrain.square(tl, tr, br, bl);\n\t\t*\/\n\t\t\/\/Generate_Shapes shape(4);\n\t\t\/\/shape.make2dterrainimage(terrain.get_array2d());\n\n\t\tDS* obj = new DS(sqSize);\n\t\tobj->DiamondSquare(z - 1);\n\t\tPlot.convert_to_3d(obj->get_grid());\n\t\tIsometric_Render iso(&Plot, image, 0, x - 1, 0, y - 1, 0, z - 1);\n\t\timage->SetSize(iso.width + DEBUGGING_WIDTH, iso.height + DEBUGGING_HEIGHT);\n\n\t\t\/\/for (int level = x + y + z - 3; level >=3; level--) {\n\t\t\/\/for (int level = 3; level < x + y + z - 3; level++) {\n\t\tfor (int level = ((count >> 3) % 2) ? 3 : x + y + z - 3; ((count >> 3) % 2) ? (level < x + y + z - 3) : (level >= 3); level += ((count >> 3) % 2) ? 1 : -1) {\n\t\n\t\t\t\/\/cout << \"hi\" << endl;\n\t\t\t\n\t\t\t\/\/for (i = 1; i < x - 1; i++) {\n\t\t\t\/\/for (i = x - 1; i >= 1; i--) {\n\t\t\tfor (int i = ((count >> 2) % 2) ? x - 1 : 1; ((count >> 2) % 2) ? (i >= 1) : (i < x - 1); i += ((count >> 2) % 2) ? -1 : 1) {\n\t\t\t\n\t\t\t\t\/\/cout << \"can\" << endl;\n\t\t\t\n\t\t\t\t\/\/for (j = 1; j < y - 1; j++) {\n\t\t\t\t\/\/for (j = y - 1; j >= 1; j--) {\n\t\t\t\tfor (int j = ((count >> 1) % 2) ? y - 1 : 1; ((count >> 1) % 2) ? (j >= 1) : (j < y - 1); j += ((count >> 1) % 2) ? -1 : 1) {\n\t\t\t\t\n\t\t\t\t\t\/\/cout << \"i\" << endl;\n\t\t\t\t\t\n\t\t\t\t\t\/\/for (k = z-1; k >= 1; k--) {\n\t\t\t\t\t\/\/for (k = 1; k < z - 1; k++) {\n\t\t\t\t\tfor (int k = ((count >> 0) % 2) ? z - 1 : 1; ((count >> 0) % 2) ? (k >= 1) : (k < z - 1); k += ((count >> 0) % 2) ? -1 : 1) {\n\t\t\t\t\t\n\t\t\t\t\t\t\/\/cout << \"help\" << endl;\n\t\t\t\t\t\t\n\t\t\t\t\t\tif ((i + j + k) == level) {\n\t\t\t\t\t\t\tif (Plot.map[i][j][k]->isSet == 1) {\n\t\t\t\t\t\t\t\t\/*Plot.map[i][j][k]->r = 192;\n\t\t\t\t\t\t\t\tPlot.map[i][j][k]->g = 192;\n\t\t\t\t\t\t\t\tPlot.map[i][j][k]->b = 192;\n\t\t\t\t\t\t\t\t*\/iso.place_cube(i, j, k);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\/\/time_t now = time(NULL);\n\t\t\/\/struct tm *time_info = new tm;\n\t\t\/\/localtime_s(time_info, &now);\n\t\ttime_t now = time(0); \/\/ get time now\n\t\tstruct tm * time_info = localtime(&now);\n\t\tstd::stringstream buffer;\n\t\t\n\t\t\/\/buffer << \"sets\/isometric\"\n\t\t\t\/*\t<< (time_info->tm_year + 1900) << '.'\n\t\t\t<< (time_info->tm_mon + 1) << '.'\n\t\t\t<< time_info->tm_mday << '-'\n\t\t\t<< time_info->tm_hour << \"h_\"\n\t\t\t<< time_info->tm_min << \"m_\"\n\t\t\t<< time_info->tm_sec << \"s\"\n\t\t\t*\/\n\t\tbuffer << \"sets\/\"\n\t\t\t<< (count >> 3)%2 << (count >> 2) % 2 << (count >> 1) % 2 << (count >> 0) % 2\n\t\t\t\t\t<< \".bmp\";\n\t\timage->WriteToFile(buffer.str().c_str());\n\t\tdelete time_info;\n\t\t\/\/delete[]iso;\n\t\t\/\/delete[]obj;\n\t\t\/\/delete[]image;\n\t\t\/\/delete[]Plot;\n\t\t\/\/delete[]terrain;\n\t\t\n\t}\n\treturn EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \"geometry\/ray.h\"\n\n\/\/using glm::min;\n\/\/using glm::max;\n\/\/source\n\/\/http:\/\/gamedev.stackexchange.com\/questions\/18436\/most-efficient-aabb-vs-ray-collision-algorithms\n\nbool Ray::intersectAabb(const aabb &bb, float &t) const{\n \/\/ lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner\n \/\/ r.org is origin of ray\n float t1 = (bb.min.x - origin.x)*dirfrac.x;\n float t2 = (bb.max.x - origin.x)*dirfrac.x;\n float t3 = (bb.min.y - origin.y)*dirfrac.y;\n float t4 = (bb.max.y - origin.y)*dirfrac.y;\n float t5 = (bb.min.z - origin.z)*dirfrac.z;\n float t6 = (bb.max.z - origin.z)*dirfrac.z;\n\n float tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6));\n float tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6));\n\n \/\/ if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us\n if (tmax < 0)\n {\n t = tmax;\n return false;\n }\n\n \/\/ if tmin > tmax, ray doesn't intersect AABB\n if (tmin > tmax)\n {\n t = tmax;\n return false;\n }\n\n t = tmin;\n return true;\n}\n\nbool Ray::intersectSphere(const Sphere &s, float &t1, float &t2) const{\n vec3 L = origin-s.pos;\n float a = glm::dot(direction,direction);\n float b = 2*glm::dot(direction,( L));\n float c = glm::dot(L,L) - s.r*s.r;\n float D = b*b + (-4.0f)*a*c;\n\n \/\/ If ray can not intersect then stop\n if (D < 0)\n return false;\n\n\n if(D==0){\n t1 = t2 = - 0.5 * b \/ a;\n }else{\n t1 = -0.5 * (b + sqrt(D)) \/ a ;\n t2 = -0.5 * (b - sqrt(D)) \/ a;\n }\n if (t1 > t2) std::swap(t1, t2);\n\n\n return true;\n}\n\nbool Ray::intersectTriangle(const Triangle &tri, float &out, bool &back) const{\n#define EPSILON 0.000001\n vec3 e1, e2; \/\/Edge1, Edge2\n vec3 P, Q, T;\n float det, inv_det, u, v;\n float t;\n\n \/\/Find vectors for two edges sharing V1\n e1 = tri.b - tri.a;\n e2 = tri.c-tri.a;\n\n \/\/culling\n vec3 n = glm::cross(e1,e2);\n back = glm::dot(direction,n)>0;\n\n \/\/Begin calculating determinant - also used to calculate u parameter\n P = glm::cross( direction, e2);\n \/\/if determinant is near zero, ray lies in plane of triangle\n det = glm::dot(e1, P);\n\n \/\/NOT CULLING\n if(det > -EPSILON && det < EPSILON) return 0;\n inv_det = 1.f \/ det;\n\n \/\/calculate distance from V1 to ray origin\n T=origin-tri.a;\n\n \/\/Calculate u parameter and test bound\n u = glm::dot(T, P) * inv_det;\n \/\/The intersection lies outside of the triangle\n if(u < 0.f || u > 1.f) return 0;\n\n \/\/Prepare to test v parameter\n Q = glm::cross( T, e1);\n\n \/\/Calculate V parameter and test bound\n v = glm::dot(direction, Q) * inv_det;\n \/\/The intersection lies outside of the triangle\n if(v < 0.f || u + v > 1.f) return 0;\n\n t = glm::dot(e2, Q) * inv_det;\n\n if(t > EPSILON) { \/\/ray intersection\n out = t;\n return 1;\n }\n\n \/\/ No hit, no win\n return 0;\n}\n\nbool Ray::intersectPlane(const Plane &p, float &t) const\n{\n#define EPSILON 0.000001\n\n float denom = glm::dot(p.normal, direction);\n if (abs(denom) > EPSILON)\n {\n t = glm::dot(p.point - origin, p.normal) \/ denom;\n if (t >= 0){\n return true;\n }\n }\n return false;\n}\n\nstd::ostream& operator<<(std::ostream& os, const Ray& r)\n{\n std::cout<<\"Ray: (\"<ray intersectionfix#include \"geometry\/ray.h\"\n\n\/\/using glm::min;\n\/\/using glm::max;\n\/\/source\n\/\/http:\/\/gamedev.stackexchange.com\/questions\/18436\/most-efficient-aabb-vs-ray-collision-algorithms\n\nbool Ray::intersectAabb(const aabb &bb, float &t) const{\n \/\/ lb is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner\n \/\/ r.org is origin of ray\n float t1 = (bb.min.x - origin.x)*dirfrac.x;\n float t2 = (bb.max.x - origin.x)*dirfrac.x;\n float t3 = (bb.min.y - origin.y)*dirfrac.y;\n float t4 = (bb.max.y - origin.y)*dirfrac.y;\n float t5 = (bb.min.z - origin.z)*dirfrac.z;\n float t6 = (bb.max.z - origin.z)*dirfrac.z;\n\n float tmin = max(max(min(t1, t2), min(t3, t4)), min(t5, t6));\n float tmax = min(min(max(t1, t2), max(t3, t4)), max(t5, t6));\n\n \/\/ if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us\n if (tmax < 0)\n {\n t = tmax;\n return false;\n }\n\n \/\/ if tmin > tmax, ray doesn't intersect AABB\n if (tmin > tmax)\n {\n t = tmax;\n return false;\n }\n\n t = tmin;\n return true;\n}\n\nbool Ray::intersectSphere(const Sphere &s, float &t1, float &t2) const{\n vec3 L = origin-s.pos;\n float a = glm::dot(direction,direction);\n float b = 2*glm::dot(direction,( L));\n float c = glm::dot(L,L) - s.r*s.r;\n float D = b*b + (-4.0f)*a*c;\n\n \/\/ If ray can not intersect then stop\n if (D < 0)\n return false;\n\n\n if(D==0){\n t1 = t2 = - 0.5 * b \/ a;\n }else{\n t1 = -0.5 * (b + sqrt(D)) \/ a ;\n t2 = -0.5 * (b - sqrt(D)) \/ a;\n }\n if (t1 > t2) std::swap(t1, t2);\n\n\n return true;\n}\n\nbool Ray::intersectTriangle(const Triangle &tri, float &out, bool &back) const{\n#define EPSILON 0.000001\n vec3 e1, e2; \/\/Edge1, Edge2\n vec3 P, Q, T;\n float det, inv_det, u, v;\n float t;\n\n \/\/Find vectors for two edges sharing V1\n e1 = tri.b - tri.a;\n e2 = tri.c-tri.a;\n\n \/\/culling\n vec3 n = glm::cross(e1,e2);\n back = glm::dot(direction,n)>0;\n\n \/\/Begin calculating determinant - also used to calculate u parameter\n P = glm::cross( direction, e2);\n \/\/if determinant is near zero, ray lies in plane of triangle\n det = glm::dot(e1, P);\n\n \/\/NOT CULLING\n if(det > -EPSILON && det < EPSILON) return 0;\n inv_det = 1.f \/ det;\n\n \/\/calculate distance from V1 to ray origin\n T=origin-tri.a;\n\n \/\/Calculate u parameter and test bound\n u = glm::dot(T, P) * inv_det;\n \/\/The intersection lies outside of the triangle\n if(u < 0.f || u > 1.f) return 0;\n\n \/\/Prepare to test v parameter\n Q = glm::cross( T, e1);\n\n \/\/Calculate V parameter and test bound\n v = glm::dot(direction, Q) * inv_det;\n \/\/The intersection lies outside of the triangle\n if(v < 0.f || u + v > 1.f) return 0;\n\n t = glm::dot(e2, Q) * inv_det;\n\n if(t > EPSILON) { \/\/ray intersection\n out = t;\n return 1;\n }\n\n \/\/ No hit, no win\n return 0;\n}\n\nbool Ray::intersectPlane(const Plane &p, float &t) const\n{\n#define EPSILON 0.000001\n\n float denom = glm::dot(p.normal, direction);\n\n if (glm::abs(denom) > EPSILON)\n {\n t = glm::dot(p.point - origin, p.normal) \/ denom;\n if (t >= 0){\n return true;\n }\n }\n return false;\n}\n\nstd::ostream& operator<<(std::ostream& os, const Ray& r)\n{\n std::cout<<\"Ray: (\"<"} {"text":"#include \n#include \n\nusing namespace std;\n\nclass Game{\npublic:\n void Maps(){\n char Map[10][10] = {\n {\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"}\n };\n\n for(row = 0; row < 10; ++row)\n {\n for(cal = 0; col < 10; ++col)\n {\n cout << Map[row][col];\n }\n }\n\n }\n};\n\nint main() {\n Game GP;\n GP.Maps();\n\n return 0;\n}\nI wanted to finish it but im also done!#include \n#include \n\nusing namespace std;\n\nclass Game{\npublic:\n void Maps(){\n char* currentMap;\n char Map[10][10] = {\n {\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \"#\"},\n {\"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\", \"#\"}\n };\n int playerRow = 2;\n int playerCol = 2;\n\n while(true){\n if(GetAsyncKeyState(VK_UP))\n playerRow -= 1;\n if(GetAsyncKeyState(VK_DOWN))\n playerRow += 1;\n if(GetAsyncKeyState(VK_RIGHT))\n playerCol -= 1;\n if(GetAsyncKeyState(VK_LEFT))\n playerCol += 1;\n\n for(row = 0; row < 10; ++row)\n {\n for(cal = 0; col < 10; ++col)\n {\n if(row == playerRow && col == playerCol)\n cout << \">\";\n else\n cout << currentMap[row][col];\n\n }\n }\n }\n\n }\n};\n\nint main() {\n Game GP;\n GP.Maps();\n\n return 0;\n}\n<|endoftext|>"} {"text":"X86: Actually handle 16 bit mode modrm.<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"..\/rwbase.h\"\n#include \"..\/rwerror.h\"\n#include \"..\/rwplg.h\"\n#include \"..\/rwrender.h\"\n#include \"..\/rwengine.h\"\n#include \"..\/rwpipeline.h\"\n#include \"..\/rwobjects.h\"\n#ifdef RW_OPENGL\n#include \n#include \"rwgl3.h\"\n#include \"rwgl3shader.h\"\n\n#include \"rwgl3impl.h\"\n\nint renderpassfudge = 2;\n\nnamespace rw {\nnamespace gl3 {\n\n#define MAX_LIGHTS \n\nvoid\ndrawInst_simple(InstanceDataHeader *header, InstanceData *inst)\n{\n\tflushCache();\n\tglDrawElements(header->primType, inst->numIndex,\n\t GL_UNSIGNED_SHORT, (void*)(uintptr)inst->offset);\n}\n\n\/\/ Emulate PS2 GS alpha test FB_ONLY case: failed alpha writes to frame- but not to depth buffer\nvoid\ndrawInst_GSemu(InstanceDataHeader *header, InstanceData *inst)\n{\n\tuint32 hasAlpha;\n\tint alphafunc, alpharef, gsalpharef;\n\tint zwrite;\n\thasAlpha = getAlphaBlend();\n\tif(hasAlpha){\n\t\tzwrite = rw::GetRenderState(rw::ZWRITEENABLE);\n\t\talphafunc = rw::GetRenderState(rw::ALPHATESTFUNC);\n\t\tif(zwrite){\n\t\t\talpharef = rw::GetRenderState(rw::ALPHATESTREF);\n\t\t\tgsalpharef = rw::GetRenderState(rw::GSALPHATESTREF);\n\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHAGREATEREQUAL);\n\t\t\tSetRenderState(rw::ALPHATESTREF, gsalpharef);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHALESS);\n\t\t\tSetRenderState(rw::ZWRITEENABLE, 0);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ZWRITEENABLE, 1);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, alphafunc);\n\t\t\tSetRenderState(rw::ALPHATESTREF, alpharef);\n\t\t}else{\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHAALWAYS);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, alphafunc);\n\t\t}\n\t}else\n\t\tdrawInst_simple(header, inst);\n}\n\nvoid\ndrawInst(InstanceDataHeader *header, InstanceData *inst)\n{\nif(getAlphaBlend() == renderpassfudge)\nreturn;\n\tif(rw::GetRenderState(rw::GSALPHATEST))\n\t\tdrawInst_GSemu(header, inst);\n\telse\n\t\tdrawInst_simple(header, inst);\n}\n\n\nvoid\nsetAttribPointers(AttribDesc *attribDescs, int32 numAttribs)\n{\n\tAttribDesc *a;\n\tfor(a = attribDescs; a != &attribDescs[numAttribs]; a++){\n\t\tglEnableVertexAttribArray(a->index);\n\t\tglVertexAttribPointer(a->index, a->size, a->type, a->normalized,\n\t\t a->stride, (void*)(uint64)a->offset);\n\t}\n}\n\nvoid\ndisableAttribPointers(AttribDesc *attribDescs, int32 numAttribs)\n{\n\tAttribDesc *a;\n\tfor(a = attribDescs; a != &attribDescs[numAttribs]; a++)\n\t\tglDisableVertexAttribArray(a->index);\n}\n\nint32\nlightingCB(Atomic *atomic)\n{\n\tWorldLights lightData;\n\tLight *directionals[8];\n\tLight *locals[8];\n\tlightData.directionals = directionals;\n\tlightData.numDirectionals = 8;\n\tlightData.locals = locals;\n\tlightData.numLocals = 8;\n\n\tif(atomic->geometry->flags & rw::Geometry::LIGHT){\n\t\t((World*)engine->currentWorld)->enumerateLights(atomic, &lightData);\n\t\tif((atomic->geometry->flags & rw::Geometry::NORMALS) == 0){\n\t\t\t\/\/ Get rid of lights that need normals when we don't have any\n\t\t\tlightData.numDirectionals = 0;\n\t\t\tlightData.numLocals = 0;\n\t\t}\n\t\treturn setLights(&lightData);\n\t}else{\n\t\tmemset(&lightData, 0, sizeof(lightData));\n\t\treturn setLights(&lightData);\n\t}\n}\n\n#define U(i) currentShader->uniformLocations[i]\n\nvoid\ndefaultRenderCB(Atomic *atomic, InstanceDataHeader *header)\n{\n\tMaterial *m;\n\n\tsetWorldMatrix(atomic->getFrame()->getLTM());\n\tlightingCB(atomic);\n\n#ifdef RW_GL_USE_VAOS\n\tglBindVertexArray(header->vao);\n#else\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, header->ibo);\n\tglBindBuffer(GL_ARRAY_BUFFER, header->vbo);\n\tsetAttribPointers(header->attribDesc, header->numAttribs);\n#endif\n\n\tInstanceData *inst = header->inst;\n\tint32 n = header->numMeshes;\n\n\tdefaultShader->use();\n\n\twhile(n--){\n\t\tm = inst->material;\n\n\t\tsetMaterial(m->color, m->surfaceProps);\n\n\t\tsetTexture(0, m->texture);\n\n\t\trw::SetRenderState(VERTEXALPHA, inst->vertexAlpha || m->color.alpha != 0xFF);\n\n\t\tdrawInst(header, inst);\n\t\tinst++;\n\t}\n#ifndef RW_GL_USE_VAOS\n\tdisableAttribPointers(header->attribDesc, header->numAttribs);\n#endif\n}\n\n\n}\n}\n\n#endif\n\nremove test code#include \n#include \n#include \n\n#include \"..\/rwbase.h\"\n#include \"..\/rwerror.h\"\n#include \"..\/rwplg.h\"\n#include \"..\/rwrender.h\"\n#include \"..\/rwengine.h\"\n#include \"..\/rwpipeline.h\"\n#include \"..\/rwobjects.h\"\n#ifdef RW_OPENGL\n#include \n#include \"rwgl3.h\"\n#include \"rwgl3shader.h\"\n\n#include \"rwgl3impl.h\"\n\nnamespace rw {\nnamespace gl3 {\n\n#define MAX_LIGHTS \n\nvoid\ndrawInst_simple(InstanceDataHeader *header, InstanceData *inst)\n{\n\tflushCache();\n\tglDrawElements(header->primType, inst->numIndex,\n\t GL_UNSIGNED_SHORT, (void*)(uintptr)inst->offset);\n}\n\n\/\/ Emulate PS2 GS alpha test FB_ONLY case: failed alpha writes to frame- but not to depth buffer\nvoid\ndrawInst_GSemu(InstanceDataHeader *header, InstanceData *inst)\n{\n\tuint32 hasAlpha;\n\tint alphafunc, alpharef, gsalpharef;\n\tint zwrite;\n\thasAlpha = getAlphaBlend();\n\tif(hasAlpha){\n\t\tzwrite = rw::GetRenderState(rw::ZWRITEENABLE);\n\t\talphafunc = rw::GetRenderState(rw::ALPHATESTFUNC);\n\t\tif(zwrite){\n\t\t\talpharef = rw::GetRenderState(rw::ALPHATESTREF);\n\t\t\tgsalpharef = rw::GetRenderState(rw::GSALPHATESTREF);\n\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHAGREATEREQUAL);\n\t\t\tSetRenderState(rw::ALPHATESTREF, gsalpharef);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHALESS);\n\t\t\tSetRenderState(rw::ZWRITEENABLE, 0);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ZWRITEENABLE, 1);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, alphafunc);\n\t\t\tSetRenderState(rw::ALPHATESTREF, alpharef);\n\t\t}else{\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, rw::ALPHAALWAYS);\n\t\t\tdrawInst_simple(header, inst);\n\t\t\tSetRenderState(rw::ALPHATESTFUNC, alphafunc);\n\t\t}\n\t}else\n\t\tdrawInst_simple(header, inst);\n}\n\nvoid\ndrawInst(InstanceDataHeader *header, InstanceData *inst)\n{\n\tif(rw::GetRenderState(rw::GSALPHATEST))\n\t\tdrawInst_GSemu(header, inst);\n\telse\n\t\tdrawInst_simple(header, inst);\n}\n\n\nvoid\nsetAttribPointers(AttribDesc *attribDescs, int32 numAttribs)\n{\n\tAttribDesc *a;\n\tfor(a = attribDescs; a != &attribDescs[numAttribs]; a++){\n\t\tglEnableVertexAttribArray(a->index);\n\t\tglVertexAttribPointer(a->index, a->size, a->type, a->normalized,\n\t\t a->stride, (void*)(uint64)a->offset);\n\t}\n}\n\nvoid\ndisableAttribPointers(AttribDesc *attribDescs, int32 numAttribs)\n{\n\tAttribDesc *a;\n\tfor(a = attribDescs; a != &attribDescs[numAttribs]; a++)\n\t\tglDisableVertexAttribArray(a->index);\n}\n\nint32\nlightingCB(Atomic *atomic)\n{\n\tWorldLights lightData;\n\tLight *directionals[8];\n\tLight *locals[8];\n\tlightData.directionals = directionals;\n\tlightData.numDirectionals = 8;\n\tlightData.locals = locals;\n\tlightData.numLocals = 8;\n\n\tif(atomic->geometry->flags & rw::Geometry::LIGHT){\n\t\t((World*)engine->currentWorld)->enumerateLights(atomic, &lightData);\n\t\tif((atomic->geometry->flags & rw::Geometry::NORMALS) == 0){\n\t\t\t\/\/ Get rid of lights that need normals when we don't have any\n\t\t\tlightData.numDirectionals = 0;\n\t\t\tlightData.numLocals = 0;\n\t\t}\n\t\treturn setLights(&lightData);\n\t}else{\n\t\tmemset(&lightData, 0, sizeof(lightData));\n\t\treturn setLights(&lightData);\n\t}\n}\n\n#define U(i) currentShader->uniformLocations[i]\n\nvoid\ndefaultRenderCB(Atomic *atomic, InstanceDataHeader *header)\n{\n\tMaterial *m;\n\n\tsetWorldMatrix(atomic->getFrame()->getLTM());\n\tlightingCB(atomic);\n\n#ifdef RW_GL_USE_VAOS\n\tglBindVertexArray(header->vao);\n#else\n\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, header->ibo);\n\tglBindBuffer(GL_ARRAY_BUFFER, header->vbo);\n\tsetAttribPointers(header->attribDesc, header->numAttribs);\n#endif\n\n\tInstanceData *inst = header->inst;\n\tint32 n = header->numMeshes;\n\n\tdefaultShader->use();\n\n\twhile(n--){\n\t\tm = inst->material;\n\n\t\tsetMaterial(m->color, m->surfaceProps);\n\n\t\tsetTexture(0, m->texture);\n\n\t\trw::SetRenderState(VERTEXALPHA, inst->vertexAlpha || m->color.alpha != 0xFF);\n\n\t\tdrawInst(header, inst);\n\t\tinst++;\n\t}\n#ifndef RW_GL_USE_VAOS\n\tdisableAttribPointers(header->attribDesc, header->numAttribs);\n#endif\n}\n\n\n}\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2016 deipi.com LLC and contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \n#include \n\n#include \"AndNode.h\"\n#include \"IdNode.h\"\n#include \"NotNode.h\"\n#include \"SyntacticException.h\"\n#include \"OrNode.h\"\n#include \"XorNode.h\"\n\n#include \"BooleanParser.h\"\n\n\nBooleanTree::BooleanTree(const std::string& input_)\n{\n\tinput = std::make_unique(input_.size()+1);\n\tstd::strcpy(input.get(), input_.c_str());\n\tlexer = std::make_unique(input.get());\n\ttoRPN();\n}\n\n\nvoid\nBooleanTree::Parse()\n{\n\troot = BuildTree();\n\tif (!stack_output.empty()) {\n\t\tToken token = stack_output.back();\n\t\tstring msj = \"'\" + token.lexeme + \"' not expected\";\n\t\tthrow SyntacticException(msj.c_str());\n\t}\n}\n\n\nstd::unique_ptr\nBooleanTree::BuildTree()\n{\n\tif (stack_output.size() == 1 || stack_output.back().type == TokenType::Id) {\n\t\tToken token = stack_output.back();\n\t\tstack_output.pop_back();\n\t\tstring id = token.lexeme;\n\t\treturn std::make_unique(id);\n\t}\n\t\/* Error case *\/\n\telse if (stack_output.size() == 1 && stack_output.back().type != TokenType::Id) {\n\t\tToken token = stack_output.back();\n\t\tstring msj = \"'\" + token.lexeme + \"' not expected\";\n\t\tthrow SyntacticException(msj.c_str());\n\t} else {\n\t\tToken token = stack_output.back();\n\t\tstack_output.pop_back();\n\t\tswitch(token.type) {\n\t\t\tcase TokenType::Not\t:\n\t\t\t\treturn std::make_unique(BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Or:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::And:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Xor:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ Silence compiler switch warning\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\n\/*\n * Convert to RPN (Reverse Polish notation)\n * with Dijkstra's Shunting-yard algorithm.\n *\/\nvoid\nBooleanTree::toRPN()\n{\n\tcurrentToken = lexer->NextToken();\n\n\twhile (currentToken.type != TokenType::EndOfFile) {\n\n\t\tswitch (currentToken.type) {\n\n\t\t\tcase TokenType::Id:\n\t\t\t\tstack_output.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::LeftParenthesis:\n\t\t\t\tstack_operator.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::RightParenthesis:\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (!stack_operator.empty()) {\n\t\t\t\t\t\t\tToken token_back = stack_operator.back();\n\t\t\t\t\t\tif (token_back.type != TokenType::LeftParenthesis) {\n\t\t\t\t\t\t\tstack_output.push_back(token_back);\n\t\t\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstring msj = \") was expected\";\n\t\t\t\t\t\tthrow SyntacticException(msj.c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Not:\n\t\t\tcase TokenType::Or:\n\t\t\tcase TokenType::And:\n\t\t\tcase TokenType::Xor:\n\t\t\t\twhile (!stack_operator.empty() && precedence(currentToken.type) >= precedence(stack_operator.back().type)) {\n\t\t\t\t\tToken token_back = stack_operator.back();\n\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\tstack_output.push_back(token_back);\n\t\t\t\t}\n\t\t\t\tstack_operator.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::EndOfFile:\n\t\t\t\tbreak;\n\t\t}\n\t\tcurrentToken = lexer->NextToken();\n\t}\n\n\twhile (!stack_operator.empty()) {\n\t\tToken tb = stack_operator.back();\n\t\tstack_output.push_back(tb);\n\t\tstack_operator.pop_back();\n\t}\n}\n\n\nunsigned\nBooleanTree::precedence(TokenType type)\n{\n\tswitch (type) {\n\t\tcase TokenType::Not:\n\t\t\treturn 0; break;\n\t\tcase TokenType::And:\n\t\t\treturn 1; break;\n\t\tcase TokenType::Xor:\n\t\t\treturn 2; break;\n\t\tcase TokenType::Or:\n\t\t\treturn 3; break;\n\t\tdefault: return 4;\n\t}\n}\n\n\nvoid\nBooleanTree::PrintTree()\n{\n\tpostorder(root.get());\n}\n\n\nvoid\nBooleanTree::postorder(BaseNode* p, int indent)\n{\n\tif(p != nullptr) {\n\t\tswitch(p->getType()) {\n\t\t\tcase AndNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"AND\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OrNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"OR\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NotNodeType:\n\t\t\t\tif (dynamic_cast(p)) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t\tcout<< \"NOT\" << \"\\n \";\n\t\t\t\t\tpostorder(dynamic_cast(p)->getNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase XorNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"XOR\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase IdNodeType:\n\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\tif (dynamic_cast(p)) {\n\t\t\t\t\tcout<< dynamic_cast(p)->getId() << \"\\n \";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\ncleanups\/*\n * Copyright (C) 2016 deipi.com LLC and contributors.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \n#include \n\n#include \"AndNode.h\"\n#include \"IdNode.h\"\n#include \"NotNode.h\"\n#include \"SyntacticException.h\"\n#include \"OrNode.h\"\n#include \"XorNode.h\"\n\n#include \"BooleanParser.h\"\n\n\nBooleanTree::BooleanTree(const std::string& input_)\n{\n\tinput = std::make_unique(input_.size()+1);\n\tstd::strcpy(input.get(), input_.c_str());\n\tlexer = std::make_unique(input.get());\n\ttoRPN();\n}\n\n\nvoid\nBooleanTree::Parse()\n{\n\troot = BuildTree();\n\tif (!stack_output.empty()) {\n\t\tToken token = stack_output.back();\n\t\tstring msj = \"'\" + token.lexeme + \"' not expected\";\n\t\tthrow SyntacticException(msj.c_str());\n\t}\n}\n\n\nstd::unique_ptr\nBooleanTree::BuildTree()\n{\n\tif (stack_output.size() == 1 || stack_output.back().type == TokenType::Id) {\n\t\tToken token = stack_output.back();\n\t\tstack_output.pop_back();\n\t\tstring id = token.lexeme;\n\t\treturn std::make_unique(id);\n\t}\n\t\/* Error case *\/\n\telse if (stack_output.size() == 1 && stack_output.back().type != TokenType::Id) {\n\t\tToken token = stack_output.back();\n\t\tstring msj = \"'\" + token.lexeme + \"' not expected\";\n\t\tthrow SyntacticException(msj.c_str());\n\t} else {\n\t\tToken token = stack_output.back();\n\t\tstack_output.pop_back();\n\t\tswitch(token.type) {\n\t\t\tcase TokenType::Not\t:\n\t\t\t\treturn std::make_unique(BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Or:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::And:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Xor:\n\t\t\t\treturn std::make_unique(BuildTree(), BuildTree());\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\t\/\/ Silence compiler switch warning\n\t\t\t\tbreak;\n\t\t}\n\t}\n\treturn nullptr;\n}\n\n\n\/*\n * Convert to RPN (Reverse Polish notation)\n * with Dijkstra's Shunting-yard algorithm.\n *\/\nvoid\nBooleanTree::toRPN()\n{\n\tcurrentToken = lexer->NextToken();\n\n\twhile (currentToken.type != TokenType::EndOfFile) {\n\n\t\tswitch (currentToken.type) {\n\n\t\t\tcase TokenType::Id:\n\t\t\t\tstack_output.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::LeftParenthesis:\n\t\t\t\tstack_operator.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::RightParenthesis:\n\t\t\t\twhile (true) {\n\t\t\t\t\tif (!stack_operator.empty()) {\n\t\t\t\t\t\t\tToken token_back = stack_operator.back();\n\t\t\t\t\t\tif (token_back.type != TokenType::LeftParenthesis) {\n\t\t\t\t\t\t\tstack_output.push_back(token_back);\n\t\t\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstring msj = \") was expected\";\n\t\t\t\t\t\tthrow SyntacticException(msj.c_str());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase TokenType::Not:\n\t\t\tcase TokenType::Or:\n\t\t\tcase TokenType::And:\n\t\t\tcase TokenType::Xor:\n\t\t\t\twhile (!stack_operator.empty() && precedence(currentToken.type) >= precedence(stack_operator.back().type)) {\n\t\t\t\t\tToken token_back = stack_operator.back();\n\t\t\t\t\tstack_operator.pop_back();\n\t\t\t\t\tstack_output.push_back(token_back);\n\t\t\t\t}\n\t\t\t\tstack_operator.push_back(currentToken);\n\t\t\t\tbreak;\n\n\t\t\tcase TokenType::EndOfFile:\n\t\t\t\tbreak;\n\t\t}\n\t\tcurrentToken = lexer->NextToken();\n\t}\n\n\twhile (!stack_operator.empty()) {\n\t\tToken tb = stack_operator.back();\n\t\tstack_output.push_back(tb);\n\t\tstack_operator.pop_back();\n\t}\n}\n\n\nunsigned\nBooleanTree::precedence(TokenType type)\n{\n\tswitch (type) {\n\t\tcase TokenType::Not:\n\t\t\treturn 0;\n\t\tcase TokenType::And:\n\t\t\treturn 1;\n\t\tcase TokenType::Xor:\n\t\t\treturn 2;\n\t\tcase TokenType::Or:\n\t\t\treturn 3;\n\t\tdefault: return 4;\n\t}\n}\n\n\nvoid\nBooleanTree::PrintTree()\n{\n\tpostorder(root.get());\n}\n\n\nvoid\nBooleanTree::postorder(BaseNode* p, int indent)\n{\n\tif(p != nullptr) {\n\t\tswitch(p->getType()) {\n\t\t\tcase AndNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"AND\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase OrNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"OR\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase NotNodeType:\n\t\t\t\tif (dynamic_cast(p)) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t\tcout<< \"NOT\" << \"\\n \";\n\t\t\t\t\tpostorder(dynamic_cast(p)->getNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase XorNodeType:\n\t\t\t\tif (dynamic_cast(p)->getLeftNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getLeftNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tif (indent) {\n\t\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\t}\n\t\t\t\tcout<< \"XOR\" << \"\\n \";\n\t\t\t\tif (dynamic_cast(p)->getRightNode()) {\n\t\t\t\t\tpostorder(dynamic_cast(p)->getRightNode(), indent+4);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase IdNodeType:\n\t\t\t\tstd::cout << std::setw(indent) << ' ';\n\t\t\t\tif (dynamic_cast(p)) {\n\t\t\t\t\tcout<< dynamic_cast(p)->getId() << \"\\n \";\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"Fix the System.arraycopy race condition.<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \n#include \nextern \"C\" {\n#include \n#include \n#include \n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\n h2olog quic -s response_header_name -p PID\nOther options:\n -h Print this help and exit\n -d Print debugging information (-dd shows more)\n -r Run without dropping root privilege\n -w Path to write the output (default: stdout)\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic void drop_root_privilege(void)\n{\n if (getuid() == 0) {\n const char *sudo_gid = getenv(\"SUDO_GID\");\n if (sudo_gid == NULL) {\n fprintf(stderr, \"Error: the SUDO_GID environment variable is not set\\n\");\n exit(EXIT_FAILURE);\n }\n errno = 0;\n gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10);\n if (errno != 0) {\n fprintf(stderr, \"Error: failed to parse SUDO_GID\\n\");\n exit(EXIT_FAILURE);\n }\n if (setgid(gid) != 0) {\n perror(\"Error: setgid(2) failed\\n\");\n exit(EXIT_FAILURE);\n }\n const char *sudo_uid = getenv(\"SUDO_UID\");\n if (sudo_uid == NULL) {\n fprintf(stderr, \"Error: the SUDO_UID environment variable is not set\\n\");\n exit(EXIT_FAILURE);\n }\n errno = 0;\n uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10);\n if (errno != 0) {\n fprintf(stderr, \"Error: failed to parse SUDO_UID\\n\");\n exit(EXIT_FAILURE);\n }\n if (setuid(uid) != 0) {\n perror(\"Error: setuid(2) failed\\n\");\n exit(EXIT_FAILURE);\n }\n }\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector &tokens)\n{\n std::vector conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n int debug = 0;\n int preserve_root = 0;\n FILE *outfp = stdout;\n std::vector event_type_filters;\n std::vector response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdrp:t:s:w:\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't':\n event_type_filters.push_back(optarg);\n break;\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'r':\n preserve_root = 1;\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector probes = tracer->init_usdt_probes(h2o_pid);\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n if (!preserve_root) {\n drop_root_privilege();\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\nh2olog: remove redundant newline\/*\n * Copyright (c) 2019-2020 Fastly, Inc., Toru Maesaka, Goro Fuji\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n * sell copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n * IN THE SOFTWARE.\n *\/\n\n#include \n#include \nextern \"C\" {\n#include \n#include \n#include \n#include \"h2o\/memory.h\"\n#include \"h2o\/version.h\"\n}\n#include \"h2olog.h\"\n\n#define POLL_TIMEOUT (1000)\n#define PERF_BUFFER_PAGE_COUNT 256\n\nstatic void usage(void)\n{\n printf(R\"(h2olog (h2o v%s)\nUsage: h2olog -p PID\n h2olog quic -p PID\n h2olog quic -s response_header_name -p PID\nOther options:\n -h Print this help and exit\n -d Print debugging information (-dd shows more)\n -r Run without dropping root privilege\n -w Path to write the output (default: stdout)\n)\",\n H2O_VERSION);\n return;\n}\n\nstatic void make_timestamp(char *buf, size_t buf_len)\n{\n time_t t = time(NULL);\n struct tm tms;\n localtime_r(&t, &tms);\n const char *iso8601format = \"%FT%TZ\";\n strftime(buf, buf_len, iso8601format, &tms);\n}\n\nstatic void infof(const char *fmt, ...) __attribute__((format(printf, 1, 2)));\n\nstatic void infof(const char *fmt, ...)\n{\n char buf[1024];\n va_list args;\n va_start(args, fmt);\n vsnprintf(buf, sizeof(buf), fmt, args);\n va_end(args);\n\n char timestamp[128];\n make_timestamp(timestamp, sizeof(timestamp));\n\n fprintf(stderr, \"%s %s\\n\", timestamp, buf);\n}\n\nuint64_t h2o_tracer::time_milliseconds()\n{\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return (int64_t)tv.tv_sec * 1000 + tv.tv_usec \/ 1000;\n}\n\nvoid h2o_tracer::show_event_per_sec(time_t *t0)\n{\n time_t t1 = time(NULL);\n int64_t d = t1 - *t0;\n if (d > 10) {\n uint64_t c = stats_.num_events \/ d;\n if (c > 0) {\n if (stats_.num_lost > 0) {\n infof(\"%20\" PRIu64 \" events\/s (possibly lost %\" PRIu64 \" events)\", c, stats_.num_lost);\n stats_.num_lost = 0;\n } else {\n infof(\"%20\" PRIu64 \" events\/s\", c);\n }\n stats_.num_events = 0;\n }\n *t0 = t1;\n }\n}\n\nstatic void show_process(pid_t pid)\n{\n char cmdline[256];\n char proc_file[256];\n snprintf(proc_file, sizeof(proc_file), \"\/proc\/%d\/cmdline\", pid);\n FILE *f = fopen(proc_file, \"r\");\n if (f == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n size_t nread = fread(cmdline, 1, sizeof(cmdline), f);\n fclose(f);\n if (nread == 0) {\n fprintf(stderr, \"Error: failed to read from %s: %s\\n\", proc_file, strerror(errno));\n exit(EXIT_FAILURE);\n }\n nread--; \/\/ skip trailing nul\n for (size_t i = 0; i < nread; i++) {\n if (cmdline[i] == '\\0') {\n cmdline[i] = ' ';\n }\n }\n infof(\"Attaching pid=%d (%s)\", pid, cmdline);\n}\n\nstatic void drop_root_privilege(void)\n{\n if (getuid() == 0) {\n const char *sudo_gid = getenv(\"SUDO_GID\");\n if (sudo_gid == NULL) {\n fprintf(stderr, \"Error: the SUDO_GID environment variable is not set\\n\");\n exit(EXIT_FAILURE);\n }\n errno = 0;\n gid_t gid = (gid_t)strtol(sudo_gid, NULL, 10);\n if (errno != 0) {\n fprintf(stderr, \"Error: failed to parse SUDO_GID\\n\");\n exit(EXIT_FAILURE);\n }\n if (setgid(gid) != 0) {\n perror(\"Error: setgid(2) failed\");\n exit(EXIT_FAILURE);\n }\n const char *sudo_uid = getenv(\"SUDO_UID\");\n if (sudo_uid == NULL) {\n fprintf(stderr, \"Error: the SUDO_UID environment variable is not set\\n\");\n exit(EXIT_FAILURE);\n }\n errno = 0;\n uid_t uid = (uid_t)strtol(sudo_uid, NULL, 10);\n if (errno != 0) {\n fprintf(stderr, \"Error: failed to parse SUDO_UID\\n\");\n exit(EXIT_FAILURE);\n }\n if (setuid(uid) != 0) {\n perror(\"Error: setuid(2) failed\\n\");\n exit(EXIT_FAILURE);\n }\n }\n}\n\nstatic std::string join_str(const std::string &sep, const std::vector &strs)\n{\n std::string s;\n for (auto iter = strs.cbegin(); iter != strs.cend(); ++iter) {\n if (iter != strs.cbegin()) {\n s += sep;\n }\n s += *iter;\n }\n return s;\n}\n\nstatic std::string generate_header_filter_cflag(const std::vector &tokens)\n{\n std::vector conditions;\n\n for (auto &token : tokens) {\n char buf[256];\n snprintf(buf, sizeof(buf), \"\/* %s *\/ (slen) == %zu\", token.c_str(), token.size());\n std::vector exprs = {buf};\n\n for (size_t i = 0; i < token.size(); ++i) {\n snprintf(buf, sizeof(buf), \"(s)[%zu] == '%c'\", i, token[i]);\n exprs.push_back(buf);\n }\n conditions.push_back(\"(\" + join_str(\" && \", exprs) + \")\");\n }\n\n std::string cflag(\"-DCHECK_ALLOWED_RES_HEADER_NAME(s,slen)=(\");\n cflag += join_str(\" || \", conditions);\n cflag += \")\";\n return cflag;\n}\n\nstatic std::string make_pid_cflag(const char *macro_name, pid_t pid)\n{\n char buf[256];\n snprintf(buf, sizeof(buf), \"-D%s=%d\", macro_name, pid);\n return std::string(buf);\n}\n\nstatic void event_cb(void *context, void *data, int len)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_event(data, len);\n}\n\nstatic void lost_cb(void *context, uint64_t lost)\n{\n h2o_tracer *tracer = (h2o_tracer *)context;\n tracer->handle_lost(lost);\n}\n\nint main(int argc, char **argv)\n{\n std::unique_ptr tracer;\n if (argc > 1 && strcmp(argv[1], \"quic\") == 0) {\n tracer.reset(create_quic_tracer());\n --argc;\n ++argv;\n } else {\n tracer.reset(create_http_tracer());\n }\n\n int debug = 0;\n int preserve_root = 0;\n FILE *outfp = stdout;\n std::vector event_type_filters;\n std::vector response_header_filters;\n int c;\n pid_t h2o_pid = -1;\n while ((c = getopt(argc, argv, \"hdrp:t:s:w:\")) != -1) {\n switch (c) {\n case 'p':\n h2o_pid = atoi(optarg);\n break;\n case 't':\n event_type_filters.push_back(optarg);\n break;\n case 's':\n response_header_filters.push_back(optarg);\n break;\n case 'w':\n if ((outfp = fopen(optarg, \"w\")) == nullptr) {\n fprintf(stderr, \"Error: failed to open %s: %s\", optarg, strerror(errno));\n exit(EXIT_FAILURE);\n }\n break;\n case 'd':\n debug++;\n break;\n case 'r':\n preserve_root = 1;\n break;\n case 'h':\n usage();\n exit(EXIT_SUCCESS);\n default:\n usage();\n exit(EXIT_FAILURE);\n }\n }\n\n if (argc > optind) {\n fprintf(stderr, \"Error: too many aruments\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (h2o_pid == -1) {\n fprintf(stderr, \"Error: -p option is missing\\n\");\n usage();\n exit(EXIT_FAILURE);\n }\n\n if (geteuid() != 0) {\n fprintf(stderr, \"Error: root privilege is required\\n\");\n exit(EXIT_FAILURE);\n }\n\n tracer->init(outfp);\n\n std::vector cflags({\n make_pid_cflag(\"H2OLOG_H2O_PID\", h2o_pid),\n });\n\n if (!response_header_filters.empty()) {\n cflags.push_back(generate_header_filter_cflag(response_header_filters));\n }\n\n if (debug >= 2) {\n fprintf(stderr, \"cflags=\");\n for (size_t i = 0; i < cflags.size(); i++) {\n if (i > 0) {\n fprintf(stderr, \" \");\n }\n fprintf(stderr, \"%s\", cflags[i].c_str());\n }\n fprintf(stderr, \"\\n\");\n fprintf(stderr, \"\\n%s\\n<\/BPF>\\n\", tracer->bpf_text().c_str());\n }\n\n ebpf::BPF *bpf = new ebpf::BPF();\n std::vector probes = tracer->init_usdt_probes(h2o_pid);\n\n ebpf::StatusTuple ret = bpf->init(tracer->bpf_text(), cflags, probes);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: init: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n bpf->attach_tracepoint(\"sched:sched_process_exit\", \"trace_sched_process_exit\");\n\n for (auto &probe : probes) {\n ret = bpf->attach_usdt(probe);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: attach_usdt: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n }\n\n ret = bpf->open_perf_buffer(\"events\", event_cb, lost_cb, tracer.get(), PERF_BUFFER_PAGE_COUNT);\n if (ret.code() != 0) {\n fprintf(stderr, \"Error: open_perf_buffer: %s\\n\", ret.msg().c_str());\n return EXIT_FAILURE;\n }\n\n if (debug) {\n show_process(h2o_pid);\n }\n if (!preserve_root) {\n drop_root_privilege();\n }\n\n ebpf::BPFPerfBuffer *perf_buffer = bpf->get_perf_buffer(\"events\");\n if (perf_buffer) {\n time_t t0 = time(NULL);\n\n while (true) {\n perf_buffer->poll(POLL_TIMEOUT);\n tracer->flush();\n\n if (debug) {\n tracer->show_event_per_sec(&t0);\n }\n }\n }\n\n fprintf(stderr, \"Error: failed to get_perf_buffer()\\n\");\n return EXIT_FAILURE;\n}\n<|endoftext|>"} {"text":"mode_RPiHQ_mean.cpp: remove mask function<|endoftext|>"} {"text":"added assertion<|endoftext|>"} {"text":"\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n *\n * Condor Software Copyright Notice\n * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n *\n * This source code is covered by the Condor Public License, which can\n * be found in the accompanying LICENSE.TXT file, or online at\n * www.condorproject.org.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * AND THE UNIVERSITY OF WISCONSIN-MADISON \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS\n * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT\n * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON\n * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,\n * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY\n * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY\n * RIGHT.\n *\n ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_string.h\"\n#include \"condor_attributes.h\"\n#include \"basename.h\"\n#include \"directory.h\"\n#include \"basename.h\"\n#include \"build_job_env.h\"\n\n#define X509_USER_PROXY \"X509_USER_PROXY\"\n\nStringMap build_job_env(const ClassAd & ad, bool using_file_transfer)\n{\n\tStringMap results(1,MyStringHash,updateDuplicateKeys);\/\/ rejectDuplicateKeys?\n\n\tMyString Iwd;\n\tif( ! ad.LookupString(ATTR_JOB_IWD, Iwd) ) {\n\t\tASSERT(0);\n\t\tdprintf(D_ALWAYS, \"Job ClassAd lacks required attribute %s. Job's environment may be incorrect.\\n\", ATTR_JOB_IWD);\n\t\treturn results;\n\t}\n\n\tMyString X509Path;\n\tif(ad.LookupString(ATTR_X509_USER_PROXY, X509Path)) {\n\t\tif(using_file_transfer) {\n\t\t\t\/\/ The X509 proxy was put into the IWD, effectively flattening\n\t\t\t\/\/ any relative or absolute paths it might have. So chomp it down.\n\t\t\t\/\/ (Don't try to do this in one line; the old string might be deleted\n\t\t\t\/\/ before the copy.)\n\t\t\tMyString tmp = condor_basename(X509Path.Value());\n\t\t\tX509Path = tmp; \n\t\t}\n\t\tif( ! fullpath(X509Path.Value()) ) {\n\t\t\t\/\/ It's not a full path, so glob on the IWD onto the front\n\t\t\tchar * newpath = dircat(Iwd.Value(), X509Path.Value());\n\t\t\tX509Path = newpath;\n\t\t\tdelete [] newpath; \/\/ dircat returnned newed memory.\n\n\t\t}\n\t\tresults.insert(X509_USER_PROXY, X509Path.Value());\n\t}\n\n\treturn results;\n}\n\n#if 0\nstatic int Insert(ClassAd & ad, const char * lhs, const char * rhs) {\n\tMyString s;\n\ts.sprintf(\"%s=\\\"%s\\\"\",lhs,rhs);\n\treturn ad.Insert(s.Value());\n}\n\nint main() {\n\tClassAd ad;\n\tInsert(ad,ATTR_JOB_IWD,\"\/path\/to\/iwd\");\n\tInsert(ad,ATTR_X509_USER_PROXY,\"\/path\/bob\");\n\tStringMap sm = build_job_env(ad);\n\n\tsm.startIterations();\n\tMyString key,value;\n\twhile(sm.iterate(key,value)) {\n\t\tprintf(\"%s=%s\\n\",key.Value(), value.Value());\n\t}\n\n\t\n\treturn 0;\n}\n#endif\nadd missing include\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n *\n * Condor Software Copyright Notice\n * Copyright (C) 1990-2006, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n *\n * This source code is covered by the Condor Public License, which can\n * be found in the accompanying LICENSE.TXT file, or online at\n * www.condorproject.org.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * AND THE UNIVERSITY OF WISCONSIN-MADISON \"AS IS\" AND ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY, OF SATISFACTORY QUALITY, AND FITNESS\n * FOR A PARTICULAR PURPOSE OR USE ARE DISCLAIMED. THE COPYRIGHT\n * HOLDERS AND CONTRIBUTORS AND THE UNIVERSITY OF WISCONSIN-MADISON\n * MAKE NO MAKE NO REPRESENTATION THAT THE SOFTWARE, MODIFICATIONS,\n * ENHANCEMENTS OR DERIVATIVE WORKS THEREOF, WILL NOT INFRINGE ANY\n * PATENT, COPYRIGHT, TRADEMARK, TRADE SECRET OR OTHER PROPRIETARY\n * RIGHT.\n *\n ****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\n#include \"condor_common.h\"\n#include \"condor_classad.h\"\n#include \"condor_string.h\"\n#include \"condor_attributes.h\"\n#include \"basename.h\"\n#include \"directory.h\"\n#include \"basename.h\"\n#include \"build_job_env.h\"\n#include \"HashTable.h\"\n\n#define X509_USER_PROXY \"X509_USER_PROXY\"\n\nStringMap build_job_env(const ClassAd & ad, bool using_file_transfer)\n{\n\tStringMap results(1,MyStringHash,updateDuplicateKeys);\/\/ rejectDuplicateKeys?\n\n\tMyString Iwd;\n\tif( ! ad.LookupString(ATTR_JOB_IWD, Iwd) ) {\n\t\tASSERT(0);\n\t\tdprintf(D_ALWAYS, \"Job ClassAd lacks required attribute %s. Job's environment may be incorrect.\\n\", ATTR_JOB_IWD);\n\t\treturn results;\n\t}\n\n\tMyString X509Path;\n\tif(ad.LookupString(ATTR_X509_USER_PROXY, X509Path)) {\n\t\tif(using_file_transfer) {\n\t\t\t\/\/ The X509 proxy was put into the IWD, effectively flattening\n\t\t\t\/\/ any relative or absolute paths it might have. So chomp it down.\n\t\t\t\/\/ (Don't try to do this in one line; the old string might be deleted\n\t\t\t\/\/ before the copy.)\n\t\t\tMyString tmp = condor_basename(X509Path.Value());\n\t\t\tX509Path = tmp; \n\t\t}\n\t\tif( ! fullpath(X509Path.Value()) ) {\n\t\t\t\/\/ It's not a full path, so glob on the IWD onto the front\n\t\t\tchar * newpath = dircat(Iwd.Value(), X509Path.Value());\n\t\t\tX509Path = newpath;\n\t\t\tdelete [] newpath; \/\/ dircat returnned newed memory.\n\n\t\t}\n\t\tresults.insert(X509_USER_PROXY, X509Path.Value());\n\t}\n\n\treturn results;\n}\n\n#if 0\nstatic int Insert(ClassAd & ad, const char * lhs, const char * rhs) {\n\tMyString s;\n\ts.sprintf(\"%s=\\\"%s\\\"\",lhs,rhs);\n\treturn ad.Insert(s.Value());\n}\n\nint main() {\n\tClassAd ad;\n\tInsert(ad,ATTR_JOB_IWD,\"\/path\/to\/iwd\");\n\tInsert(ad,ATTR_X509_USER_PROXY,\"\/path\/bob\");\n\tStringMap sm = build_job_env(ad);\n\n\tsm.startIterations();\n\tMyString key,value;\n\twhile(sm.iterate(key,value)) {\n\t\tprintf(\"%s=%s\\n\",key.Value(), value.Value());\n\t}\n\n\t\n\treturn 0;\n}\n#endif\n<|endoftext|>"} {"text":"#include \"File.h\"\n#include \"Exception.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System-specific functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifdef _WIN32\n#include \n#include \n#include \n\nbool joedb::File::lock_file()\n{\n HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));\n return LockFile(hFile, 0, 0, 1, 0) == TRUE;\n}\n\nvoid joedb::File::sync()\n{\n _commit(_fileno(file));\n}\n\n#else\n#include \n#include \n\nbool joedb::File::lock_file()\n{\n return flock(fileno(file), LOCK_EX | LOCK_NB) == 0;\n}\n\nvoid joedb::File::sync()\n{\n fsync(fileno(file));\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::File::try_open(const char *file_name, Open_Mode new_mode)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n static const char *mode_string[3] = {\"rb\", \"r+b\", \"w+b\"};\n mode = new_mode;\n file = std::fopen(file_name, mode_string[static_cast(mode)]);\n return file != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::File::File(const char *file_name, Open_Mode new_mode)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (new_mode == Open_Mode::write_existing_or_create_new)\n {\n try_open(file_name, Open_Mode::write_existing) ||\n try_open(file_name, Open_Mode::create_new);\n }\n else if (new_mode == Open_Mode::create_new)\n {\n if (try_open(file_name, Open_Mode::read_existing))\n {\n close_file();\n throw Exception(\"File already exists: \" + std::string(file_name));\n }\n else\n try_open(file_name, Open_Mode::create_new);\n }\n else\n try_open(file_name, new_mode);\n\n if (!file)\n throw Exception(\"Cannot open file: \" + std::string(file_name));\n\n if ((mode == Open_Mode::write_existing ||\n mode == Open_Mode::create_new) && !lock_file())\n {\n close_file();\n throw Exception(\"File locked: \" + std::string(file_name));\n }\n\n std::setvbuf(file, 0, _IONBF, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsize_t joedb::File::read_buffer()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return std::fread(buffer, 1, buffer_size, file);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::File::write_buffer()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n const size_t written = std::fwrite(buffer, 1, write_buffer_index, file);\n if (written != write_buffer_index)\n throw Exception(\"Error writing file\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint joedb::File::seek(size_t offset)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return std::fseek(file, long(offset), SEEK_SET);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::File::close_file()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (file)\n {\n flush();\n fclose(file);\n file = 0;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint64_t joedb::File::get_size() const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n const long current_tell = std::ftell(file);\n std::fseek(file, 0, SEEK_END);\n const int64_t result = std::ftell(file);\n std::fseek(file, current_tell, SEEK_SET);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::File::~File()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n close_file();\n}\nDummy file lock and sync for Nintendo Switch#include \"File.h\"\n#include \"Exception.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ System-specific functions\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#ifdef _WIN32\n#include \n#include \n#include \n#include \n\nbool joedb::File::lock_file()\n{\n HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));\n return LockFile(hFile, 0, 0, 1, 0) == TRUE;\n}\n\nvoid joedb::File::sync()\n{\n _commit(_fileno(file));\n}\n\n#elif defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))\n#include \n#include \n\nbool joedb::File::lock_file()\n{\n return flock(fileno(file), LOCK_EX | LOCK_NB) == 0;\n}\n\nvoid joedb::File::sync()\n{\n fsync(fileno(file));\n}\n\n#else\n#pragma message(\"warning: unknown system: no lock, no sync\")\n\nbool joedb::File::lock_file()\n{\n return true;\n}\n\nvoid joedb::File::sync()\n{\n}\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::File::try_open(const char *file_name, Open_Mode new_mode)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n static const char *mode_string[3] = {\"rb\", \"r+b\", \"w+b\"};\n mode = new_mode;\n file = std::fopen(file_name, mode_string[static_cast(mode)]);\n return file != 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::File::File(const char *file_name, Open_Mode new_mode)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (new_mode == Open_Mode::write_existing_or_create_new)\n {\n try_open(file_name, Open_Mode::write_existing) ||\n try_open(file_name, Open_Mode::create_new);\n }\n else if (new_mode == Open_Mode::create_new)\n {\n if (try_open(file_name, Open_Mode::read_existing))\n {\n close_file();\n throw Exception(\"File already exists: \" + std::string(file_name));\n }\n else\n try_open(file_name, Open_Mode::create_new);\n }\n else\n try_open(file_name, new_mode);\n\n if (!file)\n throw Exception(\"Cannot open file: \" + std::string(file_name));\n\n if ((mode == Open_Mode::write_existing ||\n mode == Open_Mode::create_new) && !lock_file())\n {\n close_file();\n throw Exception(\"File locked: \" + std::string(file_name));\n }\n\n std::setvbuf(file, 0, _IONBF, 0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nsize_t joedb::File::read_buffer()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return std::fread(buffer, 1, buffer_size, file);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::File::write_buffer()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n const size_t written = std::fwrite(buffer, 1, write_buffer_index, file);\n if (written != write_buffer_index)\n throw Exception(\"Error writing file\");\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint joedb::File::seek(size_t offset)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n return std::fseek(file, long(offset), SEEK_SET);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::File::close_file()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (file)\n {\n flush();\n fclose(file);\n file = 0;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint64_t joedb::File::get_size() const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n const long current_tell = std::ftell(file);\n std::fseek(file, 0, SEEK_END);\n const int64_t result = std::ftell(file);\n std::fseek(file, current_tell, SEEK_SET);\n return result;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\njoedb::File::~File()\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n close_file();\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n\n\/************************************************************************\n**\n**\tSet up the various dprintf variables based on the configuration file.\n**\n************************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_string.h\" \n#include \"condor_sys_types.h\"\n\n#if HAVE_BACKTRACE\n#include \"sig_install.h\"\n#endif\n\nint\t\tTermlog = 0;\n\nextern int\t\tDebugFlags;\nextern FILE\t\t*DebugFP;\nextern uint64_t\t\tMaxLog[D_NUMLEVELS+1];\nextern int \t\t\tMaxLogNum[D_NUMLEVELS+1];\nextern char\t\t*DebugFile[D_NUMLEVELS+1];\nextern char\t\t*DebugLock;\nextern char\t\t*_condor_DebugFlagNames[];\nextern int\t\t_condor_dprintf_works;\nextern time_t\tDebugLastMod;\nextern int\t\tDebugUseTimestamps;\nextern int DebugContinueOnOpenFailure;\n\nextern void\t\t_condor_set_debug_flags( const char *strflags );\nextern void\t\t_condor_dprintf_saved_lines( void );\n\nFILE *open_debug_file( int debug_level, char flags[] );\n\n#if HAVE_EXT_GCB\nvoid\t_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );\nextern \"C\" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));\n#endif\n\n#if HAVE_BACKTRACE\nstatic void\nsig_backtrace_handler(int signum)\n{\n\tdprintf_dump_stack();\n\n\t\t\/\/ terminate for the same reason.\n\tstruct sigaction sa;\n\tsa.sa_handler = SIG_DFL;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = 0;\n\tsigaction(signum, &sa, NULL);\n\tsigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);\n\n\traise(signum);\n}\n\nstatic void\ninstall_backtrace_handler(void)\n{\n\tsigset_t fullset;\n\tsigfillset( &fullset );\n\tinstall_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);\n}\n#endif\n\nint\ndprintf_config_ContinueOnFailure ( int fContinue )\n{\n int fOld = DebugContinueOnOpenFailure;\n\tDebugContinueOnOpenFailure = fContinue;\n\treturn fOld;\n}\n\nvoid\ndprintf_config( const char *subsys )\n{\n\tchar pname[ BUFSIZ ];\n\tchar *pval;\n\tstatic int first_time = 1;\n\tint want_truncate;\n\tint debug_level;\n\n\t\/* \n\t** We want to initialize this here so if we reconfig and the\n\t**\tdebug flags have changed, we actually use the new\n\t** flags. -Derek Wright 12\/8\/97 \n\t*\/\n\tDebugFlags = D_ALWAYS;\n\n\t\/*\n\t** First, add the debug flags that are shared by everyone.\n\t*\/\n\tpval = param(\"ALL_DEBUG\");\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n\t\/*\n\t** Then, pick up the subsys_DEBUG parameters. Note: if we don't have\n\t** anything set, we just leave it as D_ALWAYS.\n\t*\/\n\t(void)sprintf(pname, \"%s_DEBUG\", subsys);\n\tpval = param(pname);\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n#ifdef WIN32\n\t\t\/* Two reasons why we need to lock the log in Windows\n\t\t * (when a lock is configured)\n\t\t * 1) File rotation requires exclusive access in Windows.\n\t\t * 2) O_APPEND doesn't guarantee atomic writes in Windows\n\t\t *\/\n\tDebugShouldLockToAppend = 1;\n#else\n\tDebugShouldLockToAppend = param_boolean_int(\"LOCK_DEBUG_LOG_TO_APPEND\",0);\n#endif\n\n\t\/*\n\t**\tIf this is not going to the terminal, pick up the name\n\t**\tof the log file, maximum log size, and the name of the\n\t**\tlock file (if it is specified).\n\t*\/\n\tif( !( Termlog) ) {\n\t\tfor (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {\n\t\t\twant_truncate = 0;\n\t\t\tif (debug_level == 0) {\n\t\t\t\t\/*\n\t\t\t\t** the level 0 file gets all debug messages; thus, the\n\t\t\t\t** offset into DebugFlagNames is off by one, since the\n\t\t\t\t** first level-specific file goes into the other arrays at\n\t\t\t\t** index 1\n\t\t\t\t*\/\n\t\t\t\t(void)sprintf(pname, \"%s_LOG\", subsys);\n\t\t\t} else {\n\t\t\t\t(void)sprintf(pname, \"%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t}\n\n\t\t\t\/\/ Hold a temporary copy of the old file pointer until\n\t\t\t\/\/ *after* the param -- param can dprintf() in some cases\n\t\t\t{\n\t\t\t\tchar\t*tmp = DebugFile[debug_level];\n\n\t\t\t\t\/\/ NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level\n\t\t\t\t\/\/ is not 0\n\t\t\t\tif(debug_level == 0)\n\t\t\t\t{\n\t\t\t\t\tchar\t*tmp2 = param(pname);\n\n\t\t\t\t\t\/\/ No default value found, so use $(LOG)\/$(SUBSYSTEM)Log\n\t\t\t\t\tif(!tmp2) {\n\t\t\t\t\t\t\/\/ This char* will never be freed, but as long as\n\t\t\t\t\t\t\/\/ defaults are defined in condor_c++_util\/param_info.in\n\t\t\t\t\t\t\/\/ we will never get here.\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tchar *log = param(\"LOG\");\n\t\t\t\t\t\tchar *subsys = param(\"SUBSYSTEM\");\n\t\t\t\t\t\tif(!log || !subsys) {\n\t\t\t\t\t\t\tEXCEPT(\"Unable to find LOG or SUBSYSTEM.\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tstr = (char*)malloc(strlen(log) + strlen(subsys) + 5);\n\t\t\t\t\t\tsprintf(str, \"%s%c%sLog\", log, DIR_DELIM_CHAR, subsys);\n\t\t\t\t\t\t\n\t\t\t\t\t\tDebugFile[debug_level] = str;\n\n\t\t\t\t\t\tfree(log);\n\t\t\t\t\t\tfree(subsys);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tDebugFile[debug_level] = tmp2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ This is looking up configuration options that I can't\n\t\t\t\t\t\/\/ find documentation for, so intead of coding in an\n\t\t\t\t\t\/\/ incorrect default value, I'm gonna use \n\t\t\t\t\t\/\/ param_without_default.\n\t\t\t\t\t\/\/ tristan 5\/29\/09\n\t\t\t\t\tDebugFile[debug_level] = param_without_default(pname);\n\t\t\t\t}\n\t\t\t\tif ( tmp ) {\n\t\t\t\t\tfree( tmp );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( debug_level == 0 && DebugFile[0] == NULL ) {\n\t\t\t\tEXCEPT(\"No '%s' parameter specified.\", pname);\n\t\t\t} else if ( DebugFile[debug_level] != NULL ) {\n\n\t\t\t\tif (debug_level == 0 && first_time) {\n\t\t\t\t\tstruct stat stat_buf;\n\t\t\t\t\tif ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {\n\t\t\t\t\t\tDebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDebugLastMod = -errno;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_LOG_ON_OPEN\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_%s_LOG_ON_OPEN\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval ) {\n\t\t\t\t\tif( *pval == 't' || *pval == 'T' ) {\n\t\t\t\t\t\twant_truncate = 1;\n\t\t\t\t\t} \n\t\t\t\t\tfree(pval);\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"%s_LOCK\", subsys);\n\t\t\t\t\tif (DebugLock) {\n\t\t\t\t\t\tfree(DebugLock);\n\t\t\t\t\t}\n\t\t\t\t\tDebugLock = param(pname);\n\t\t\t\t}\n\n\t\t\t\tif( first_time && want_truncate ) {\n\t\t\t\t\tDebugFP = debug_lock(debug_level, \"w\", 0);\n\t\t\t\t} else {\n\t\t\t\t\tDebugFP = debug_lock(debug_level, \"a\", 0);\n\t\t\t\t}\n\n\t\t\t\tif( DebugFP == NULL && debug_level == 0 ) {\n #ifdef WIN32\n\t\t\t\t\t\/*\n\t\t\t\t\t** If we could not open the log file, we might want to keep running anyway.\n\t\t\t\t\t** If we do, then set the log filename to NUL so we don't keep trying\n\t\t\t\t\t** (and failing) to open the file.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (DebugContinueOnOpenFailure) {\n\n\t\t\t\t\t\t\/\/ change the debug file to point to the NUL device.\n\t\t\t\t\t\tstatic const char strDevNull[] = \"NUL\";\/\/\"\\\\\\\\.\\\\Device\\\\Null\";\n\t\t\t\t\t\tchar * psz = (char*)malloc(sizeof(strDevNull));\n\t\t\t\t\t\tstrcpy(psz, strDevNull);\n\t\t\t\t\t\tif (DebugFile[debug_level]) \n\t\t\t\t\t\t\tfree(DebugFile[debug_level]);\n\t\t\t\t\t\tDebugFile[debug_level] = psz;\n\n\t\t\t\t\t} else\n #endif\n\t\t\t\t\t{\n\t\t\t\t\t EXCEPT(\"Cannot open log file '%s'\",\n\t\t\t\t\t\t DebugFile[debug_level]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (DebugFP) (void)debug_unlock( debug_level );\n\t\t\t\tDebugFP = (FILE *)0;\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval != NULL ) {\n\t\t\t\t\tMaxLog[debug_level] = atoi( pval );\n\t\t\t\t\tfree(pval);\n\t\t\t\t} else {\n\t\t\t\t\tMaxLog[debug_level] = 1024*1024;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif (pval != NULL) {\n\t\t\t\t\tMaxLogNum[debug_level] = atoi(pval);\n\t\t\t\t\tfree(pval);\n\t\t\t\t} else {\n\t\t\t\t\tMaxLogNum[debug_level] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\n#if !defined(WIN32)\n\t\tsetlinebuf( stderr );\n#endif\n\n\t\t(void)fflush( stderr );\t\/* Don't know why we need this, but if not here\n\t\t\t\t\t\t\t the first couple dprintf don't come out right *\/\n\t}\n\n\tfirst_time = 0;\n\t_condor_dprintf_works = 1;\n#if HAVE_EXT_GCB\n\t\t\/*\n\t\t this method currently only lives in libGCB.a, so don't even\n\t\t try to param() or call this function unless we're on a\n\t\t platform where we're using the GCB external\n\t\t*\/\n if ( param_boolean_int(\"NET_REMAP_ENABLE\", 0) ) {\n Generic_set_log_va(_condor_gcb_dprintf_va);\n }\n#endif\n\n\t\t\/*\n\t\t If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps\n\t\t instead of the standard date format in all the log messages\n\t\t*\/\n\tDebugUseTimestamps = param_boolean_int( \"LOGS_USE_TIMESTAMP\", FALSE );\n\n#if HAVE_BACKTRACE\n\tinstall_backtrace_handler();\n#endif\n\n\t_condor_dprintf_saved_lines();\n}\n\n\n#if HAVE_EXT_GCB\nvoid\n_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )\n{\n\tchar* new_fmt;\n\tint len;\n\n\tlen = strlen(fmt);\n\tnew_fmt = (char*) malloc( (len + 6) * sizeof(char) );\n\tif( ! new_fmt ) {\n\t\tEXCEPT( \"_condor_gcb_dprintf_va() out of memory!\" );\n\t}\n\tsnprintf( new_fmt, len + 6, \"GCB: %s\", fmt );\n\t_condor_dprintf_va( flags, new_fmt, args );\n\tfree( new_fmt );\n}\n#endif \/* HAVE_EXT_GCB *\/\nFixed _condor_DebugFlagNames const commit, missed a file\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\n\n\/************************************************************************\n**\n**\tSet up the various dprintf variables based on the configuration file.\n**\n************************************************************************\/\n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\n#include \"condor_string.h\" \n#include \"condor_sys_types.h\"\n\n#if HAVE_BACKTRACE\n#include \"sig_install.h\"\n#endif\n\nint\t\tTermlog = 0;\n\nextern int\t\tDebugFlags;\nextern FILE\t\t*DebugFP;\nextern uint64_t\t\tMaxLog[D_NUMLEVELS+1];\nextern int \t\t\tMaxLogNum[D_NUMLEVELS+1];\nextern char\t\t*DebugFile[D_NUMLEVELS+1];\nextern char\t\t*DebugLock;\nextern const char\t\t*_condor_DebugFlagNames[];\nextern int\t\t_condor_dprintf_works;\nextern time_t\tDebugLastMod;\nextern int\t\tDebugUseTimestamps;\nextern int DebugContinueOnOpenFailure;\n\nextern void\t\t_condor_set_debug_flags( const char *strflags );\nextern void\t\t_condor_dprintf_saved_lines( void );\n\nFILE *open_debug_file( int debug_level, char flags[] );\n\n#if HAVE_EXT_GCB\nvoid\t_condor_gcb_dprintf_va( int flags, char* fmt, va_list args );\nextern \"C\" void Generic_set_log_va(void(*app_log_va)(int level, char *fmt, va_list args));\n#endif\n\n#if HAVE_BACKTRACE\nstatic void\nsig_backtrace_handler(int signum)\n{\n\tdprintf_dump_stack();\n\n\t\t\/\/ terminate for the same reason.\n\tstruct sigaction sa;\n\tsa.sa_handler = SIG_DFL;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = 0;\n\tsigaction(signum, &sa, NULL);\n\tsigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);\n\n\traise(signum);\n}\n\nstatic void\ninstall_backtrace_handler(void)\n{\n\tsigset_t fullset;\n\tsigfillset( &fullset );\n\tinstall_sig_handler_with_mask(SIGSEGV, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGABRT, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGILL, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGFPE, &fullset, sig_backtrace_handler);\n\tinstall_sig_handler_with_mask(SIGBUS, &fullset, sig_backtrace_handler);\n}\n#endif\n\nint\ndprintf_config_ContinueOnFailure ( int fContinue )\n{\n int fOld = DebugContinueOnOpenFailure;\n\tDebugContinueOnOpenFailure = fContinue;\n\treturn fOld;\n}\n\nvoid\ndprintf_config( const char *subsys )\n{\n\tchar pname[ BUFSIZ ];\n\tchar *pval;\n\tstatic int first_time = 1;\n\tint want_truncate;\n\tint debug_level;\n\n\t\/* \n\t** We want to initialize this here so if we reconfig and the\n\t**\tdebug flags have changed, we actually use the new\n\t** flags. -Derek Wright 12\/8\/97 \n\t*\/\n\tDebugFlags = D_ALWAYS;\n\n\t\/*\n\t** First, add the debug flags that are shared by everyone.\n\t*\/\n\tpval = param(\"ALL_DEBUG\");\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n\t\/*\n\t** Then, pick up the subsys_DEBUG parameters. Note: if we don't have\n\t** anything set, we just leave it as D_ALWAYS.\n\t*\/\n\t(void)sprintf(pname, \"%s_DEBUG\", subsys);\n\tpval = param(pname);\n\tif( pval ) {\n\t\t_condor_set_debug_flags( pval );\n\t\tfree( pval );\n\t}\n\n#ifdef WIN32\n\t\t\/* Two reasons why we need to lock the log in Windows\n\t\t * (when a lock is configured)\n\t\t * 1) File rotation requires exclusive access in Windows.\n\t\t * 2) O_APPEND doesn't guarantee atomic writes in Windows\n\t\t *\/\n\tDebugShouldLockToAppend = 1;\n#else\n\tDebugShouldLockToAppend = param_boolean_int(\"LOCK_DEBUG_LOG_TO_APPEND\",0);\n#endif\n\n\t\/*\n\t**\tIf this is not going to the terminal, pick up the name\n\t**\tof the log file, maximum log size, and the name of the\n\t**\tlock file (if it is specified).\n\t*\/\n\tif( !( Termlog) ) {\n\t\tfor (debug_level = 0; debug_level <= D_NUMLEVELS; debug_level++) {\n\t\t\twant_truncate = 0;\n\t\t\tif (debug_level == 0) {\n\t\t\t\t\/*\n\t\t\t\t** the level 0 file gets all debug messages; thus, the\n\t\t\t\t** offset into DebugFlagNames is off by one, since the\n\t\t\t\t** first level-specific file goes into the other arrays at\n\t\t\t\t** index 1\n\t\t\t\t*\/\n\t\t\t\t(void)sprintf(pname, \"%s_LOG\", subsys);\n\t\t\t} else {\n\t\t\t\t(void)sprintf(pname, \"%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t}\n\n\t\t\t\/\/ Hold a temporary copy of the old file pointer until\n\t\t\t\/\/ *after* the param -- param can dprintf() in some cases\n\t\t\t{\n\t\t\t\tchar\t*tmp = DebugFile[debug_level];\n\n\t\t\t\t\/\/ NEGOTIATOR_MATCH_LOG is necessary by default, but debug_level\n\t\t\t\t\/\/ is not 0\n\t\t\t\tif(debug_level == 0)\n\t\t\t\t{\n\t\t\t\t\tchar\t*tmp2 = param(pname);\n\n\t\t\t\t\t\/\/ No default value found, so use $(LOG)\/$(SUBSYSTEM)Log\n\t\t\t\t\tif(!tmp2) {\n\t\t\t\t\t\t\/\/ This char* will never be freed, but as long as\n\t\t\t\t\t\t\/\/ defaults are defined in condor_c++_util\/param_info.in\n\t\t\t\t\t\t\/\/ we will never get here.\n\t\t\t\t\t\tchar *str;\n\t\t\t\t\t\tchar *log = param(\"LOG\");\n\t\t\t\t\t\tchar *subsys = param(\"SUBSYSTEM\");\n\t\t\t\t\t\tif(!log || !subsys) {\n\t\t\t\t\t\t\tEXCEPT(\"Unable to find LOG or SUBSYSTEM.\\n\");\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\tstr = (char*)malloc(strlen(log) + strlen(subsys) + 5);\n\t\t\t\t\t\tsprintf(str, \"%s%c%sLog\", log, DIR_DELIM_CHAR, subsys);\n\t\t\t\t\t\t\n\t\t\t\t\t\tDebugFile[debug_level] = str;\n\n\t\t\t\t\t\tfree(log);\n\t\t\t\t\t\tfree(subsys);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tDebugFile[debug_level] = tmp2;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t\/\/ This is looking up configuration options that I can't\n\t\t\t\t\t\/\/ find documentation for, so intead of coding in an\n\t\t\t\t\t\/\/ incorrect default value, I'm gonna use \n\t\t\t\t\t\/\/ param_without_default.\n\t\t\t\t\t\/\/ tristan 5\/29\/09\n\t\t\t\t\tDebugFile[debug_level] = param_without_default(pname);\n\t\t\t\t}\n\t\t\t\tif ( tmp ) {\n\t\t\t\t\tfree( tmp );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif( debug_level == 0 && DebugFile[0] == NULL ) {\n\t\t\t\tEXCEPT(\"No '%s' parameter specified.\", pname);\n\t\t\t} else if ( DebugFile[debug_level] != NULL ) {\n\n\t\t\t\tif (debug_level == 0 && first_time) {\n\t\t\t\t\tstruct stat stat_buf;\n\t\t\t\t\tif ( stat( DebugFile[debug_level], &stat_buf ) >= 0 ) {\n\t\t\t\t\t\tDebugLastMod = stat_buf.st_mtime > stat_buf.st_ctime ? stat_buf.st_mtime : stat_buf.st_ctime;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tDebugLastMod = -errno;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_LOG_ON_OPEN\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"TRUNC_%s_%s_LOG_ON_OPEN\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval ) {\n\t\t\t\t\tif( *pval == 't' || *pval == 'T' ) {\n\t\t\t\t\t\twant_truncate = 1;\n\t\t\t\t\t} \n\t\t\t\t\tfree(pval);\n\t\t\t\t}\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"%s_LOCK\", subsys);\n\t\t\t\t\tif (DebugLock) {\n\t\t\t\t\t\tfree(DebugLock);\n\t\t\t\t\t}\n\t\t\t\t\tDebugLock = param(pname);\n\t\t\t\t}\n\n\t\t\t\tif( first_time && want_truncate ) {\n\t\t\t\t\tDebugFP = debug_lock(debug_level, \"w\", 0);\n\t\t\t\t} else {\n\t\t\t\t\tDebugFP = debug_lock(debug_level, \"a\", 0);\n\t\t\t\t}\n\n\t\t\t\tif( DebugFP == NULL && debug_level == 0 ) {\n #ifdef WIN32\n\t\t\t\t\t\/*\n\t\t\t\t\t** If we could not open the log file, we might want to keep running anyway.\n\t\t\t\t\t** If we do, then set the log filename to NUL so we don't keep trying\n\t\t\t\t\t** (and failing) to open the file.\n\t\t\t\t\t*\/\n\t\t\t\t\tif (DebugContinueOnOpenFailure) {\n\n\t\t\t\t\t\t\/\/ change the debug file to point to the NUL device.\n\t\t\t\t\t\tstatic const char strDevNull[] = \"NUL\";\/\/\"\\\\\\\\.\\\\Device\\\\Null\";\n\t\t\t\t\t\tchar * psz = (char*)malloc(sizeof(strDevNull));\n\t\t\t\t\t\tstrcpy(psz, strDevNull);\n\t\t\t\t\t\tif (DebugFile[debug_level]) \n\t\t\t\t\t\t\tfree(DebugFile[debug_level]);\n\t\t\t\t\t\tDebugFile[debug_level] = psz;\n\n\t\t\t\t\t} else\n #endif\n\t\t\t\t\t{\n\t\t\t\t\t EXCEPT(\"Cannot open log file '%s'\",\n\t\t\t\t\t\t DebugFile[debug_level]);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (DebugFP) (void)debug_unlock( debug_level );\n\t\t\t\tDebugFP = (FILE *)0;\n\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif( pval != NULL ) {\n\t\t\t\t\tMaxLog[debug_level] = atoi( pval );\n\t\t\t\t\tfree(pval);\n\t\t\t\t} else {\n\t\t\t\t\tMaxLog[debug_level] = 1024*1024;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (debug_level == 0) {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_LOG\", subsys);\n\t\t\t\t} else {\n\t\t\t\t\t(void)sprintf(pname, \"MAX_NUM_%s_%s_LOG\", subsys,\n\t\t\t\t\t\t\t\t _condor_DebugFlagNames[debug_level-1]+2);\n\t\t\t\t}\n\t\t\t\tpval = param(pname);\n\t\t\t\tif (pval != NULL) {\n\t\t\t\t\tMaxLogNum[debug_level] = atoi(pval);\n\t\t\t\t\tfree(pval);\n\t\t\t\t} else {\n\t\t\t\t\tMaxLogNum[debug_level] = 1;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\n#if !defined(WIN32)\n\t\tsetlinebuf( stderr );\n#endif\n\n\t\t(void)fflush( stderr );\t\/* Don't know why we need this, but if not here\n\t\t\t\t\t\t\t the first couple dprintf don't come out right *\/\n\t}\n\n\tfirst_time = 0;\n\t_condor_dprintf_works = 1;\n#if HAVE_EXT_GCB\n\t\t\/*\n\t\t this method currently only lives in libGCB.a, so don't even\n\t\t try to param() or call this function unless we're on a\n\t\t platform where we're using the GCB external\n\t\t*\/\n if ( param_boolean_int(\"NET_REMAP_ENABLE\", 0) ) {\n Generic_set_log_va(_condor_gcb_dprintf_va);\n }\n#endif\n\n\t\t\/*\n\t\t If LOGS_USE_TIMESTAMP is enabled, we will print out Unix timestamps\n\t\t instead of the standard date format in all the log messages\n\t\t*\/\n\tDebugUseTimestamps = param_boolean_int( \"LOGS_USE_TIMESTAMP\", FALSE );\n\n#if HAVE_BACKTRACE\n\tinstall_backtrace_handler();\n#endif\n\n\t_condor_dprintf_saved_lines();\n}\n\n\n#if HAVE_EXT_GCB\nvoid\n_condor_gcb_dprintf_va( int flags, char* fmt, va_list args )\n{\n\tchar* new_fmt;\n\tint len;\n\n\tlen = strlen(fmt);\n\tnew_fmt = (char*) malloc( (len + 6) * sizeof(char) );\n\tif( ! new_fmt ) {\n\t\tEXCEPT( \"_condor_gcb_dprintf_va() out of memory!\" );\n\t}\n\tsnprintf( new_fmt, len + 6, \"GCB: %s\", fmt );\n\t_condor_dprintf_va( flags, new_fmt, args );\n\tfree( new_fmt );\n}\n#endif \/* HAVE_EXT_GCB *\/\n<|endoftext|>"} {"text":"\/* CloneKernelConn.cpp\n *\n * Created on: May 23, 2011\n * Author: peteschultz\n *\/\n\n#include \"CloneKernelConn.hpp\"\n\nnamespace PV {\n\nCloneKernelConn::CloneKernelConn(){\n initialize_base();\n}\n\nCloneKernelConn::CloneKernelConn(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n initialize_base();\n initialize(name, hc, pre_layer_name, post_layer_name, original_kernelconn_name);\n}\n\nint CloneKernelConn::initialize_base() {\n originalConn = NULL;\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::initialize(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n InitCloneKernelWeights * weightInit = new InitCloneKernelWeights();\n assert(weightInit != NULL);\n int status = KernelConn::initialize(name, hc, pre_layer_name, post_layer_name, NULL, weightInit);\n if (original_kernelconn_name==NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName must be set.\\n\",\n name, hc->columnId());\n abort();\n }\n originalConnName = strdup(original_kernelconn_name);\n if (originalConnName == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: unable to allocate memory for originalConnName \\\"%s\\\": %s\\n\",\n name, hc->columnId(), original_kernelconn_name, strerror(errno));\n abort();\n }\n return status;\n}\n\n\/\/int CloneKernelConn::setPatchSize(const char * filename) {\n\/\/ \/\/ nxp, nyp, nfp were set by the read-methods called by HyPerConn::setParams\n\/\/ assert(filename == NULL);\n\/\/ int xScalePre = pre->getXScale();\n\/\/ int xScalePost = post->getXScale();\n\/\/ int status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');\n\/\/ if( status == PV_SUCCESS) {\n\/\/ int yScalePre = pre->getYScale();\n\/\/ int yScalePost = post->getYScale();\n\/\/ status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');\n\/\/ }\n\/\/ return status;\n\/\/}\n\nint CloneKernelConn::initNormalize() {\n normalizer = NULL;\n \/\/ normalize_flag = false; \/\/ replaced by testing whether normalizer!=NULL\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::constructWeights(const char * filename) {\n int status = PV_SUCCESS;\n\n \/\/ CloneKernelConn::readShrinkPatches does nothing; shrinkPatches_flag is set in communicateInitInfo()\n \/\/ if( status == PV_SUCCESS ) readShrinkPatches(parent->parameters());\n\n \/\/ if( status == PV_SUCCESS ) status = setPatchSize(NULL);\n if( status == PV_SUCCESS ) status = setPatchStrides();\n\n wPatches = this->originalConn->get_wPatches();\n wDataStart = this->originalConn->get_wDataStart();\n gSynPatchStart = this->originalConn->getGSynPatchStart();\n aPostOffset = this->originalConn->getAPostOffset();\n dwDataStart = this->originalConn->get_dwDataStart();\n\n\/\/ for( int arbor=0; arborget_wDataStart(arbor);\n\/\/ get_wPatches()[arbor] = originalConn->weights(arbor);\n\/\/ \/\/ this->setKernelPatches(originalConn->getKernelPatches(arbor),arbor);\n\/\/ if( status == PV_SUCCESS )\n\/\/ status = createAxonalArbors(arbor); \/\/ sets gSynPatchStart[arbor][*] and aPostOffset[arbor][*]\n\/\/ if( status != PV_SUCCESS ) break;\n\/\/ }\n\n \/\/ Don't call initPlasticityPatches since plasticityFlag is always false.\n \/\/ Don't call shrinkPatches() since the original connection will have already shrunk patches\n return status;\n}\n\nvoid CloneKernelConn::constructWeightsOutOfMemory() {\n connOutOfMemory(\"CloneKernelConn::constructWeightsOutOfMemory()\");\n}\n\nint CloneKernelConn::createAxonalArbors(int arborId) {\n\/\/ int numPatches = getNumWeightPatches();\n\/\/ for( int kex = 0; kex < numPatches; kex++ ) {\n\/\/ \/\/ kex is in extended frame, this makes transformations more difficult\n\/\/ int kl, offset, nxPatch, nyPatch, dx, dy;\n\/\/ calcPatchSize(arborId, kex, &kl, &offset, &nxPatch, &nyPatch, &dx, &dy);\n\/\/ pvdata_t * gSyn = post->getChannel(channel) + kl;\n\/\/ getGSynPatchStart()[arborId][kex] = gSyn;\n\/\/ getAPostOffset()[arborId][kex] = offset;\n\/\/ \/\/ Don't call pvpatch_adjust because weight patches point to the\n\/\/ \/\/ original conn's weight patches, which were already shrunk.\n\/\/ }\n return PV_SUCCESS;\n}\n\nPVPatch *** CloneKernelConn::initializeWeights(PVPatch *** patches, pvdata_t ** dataStart,\n int numPatches, const char * filename) {\n return patches;\n \/\/ nothing to be done as the weight patches point to originalConn's space.\n}\n\nvoid CloneKernelConn::readShrinkPatches(PVParams * params) {\n \/\/ During the communication phase, shrinkPatches_flag will be copied from originalConn\n}\n\nint CloneKernelConn::setParams(PVParams * params) {\n return KernelConn::setParams(params);\n}\n\nvoid CloneKernelConn::readNumAxonalArbors(PVParams * params) {\n \/\/ During the communication phase, numAxonalArbors will be copied from originalConn\n}\n\nvoid CloneKernelConn::readPlasticityFlag(PVParams * params) {\n plasticityFlag = false; \/\/ CloneKernelConn updates automatically, since it's done using pointer magic.\n}\n\nint CloneKernelConn::readPatchSize(PVParams * params) {\n \/\/ During the communication phase, nxp, nyp, nxpShrunken, nypShrunken will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::readNfp(PVParams * params) {\n \/\/ During the communication phase, nfp will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::communicateInitInfo() {\n \/\/ Need to set originalConn before calling KernelConn::communicate, since KernelConn::communicate calls setPatchSize, which needs originalConn.\n HyPerConn * origHyPerConn = parent->getConnFromName(originalConnName);\n if (origHyPerConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" is not a connection in the column.\\n\",\n name, parent->columnId(), originalConnName);\n }\n originalConn = dynamic_cast(origHyPerConn);\n if (originalConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" must be a KernelConn or a KernelConn-derived class.\\n\",\n name, parent->columnId(), originalConnName);\n }\n\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n int status = KernelConn::communicateInitInfo();\n if (status != PV_SUCCESS) return status;\n\n \/\/ Presynaptic layers of the CloneKernelConn and its original conn must have the same size, or the patches won't line up with each other.\n const PVLayerLoc * preLoc = pre->getLayerLoc();\n const PVLayerLoc * origPreLoc = originalConn->preSynapticLayer()->getLayerLoc();\n\n if (preLoc->nx != origPreLoc->nx || preLoc->ny != origPreLoc->ny || preLoc->nf != origPreLoc->nf || preLoc->nb != origPreLoc->nb ) {\n if (parent->icCommunicator()->commRank()==0) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: CloneKernelConn and originalConn \\\"%s\\\" must have presynaptic layers with the same geometry (including margin width).\\n\",\n name, parent->columnId(), originalConn->getName());\n fprintf(stderr, \"{nx=%d, ny=%d, nf=%d, nb=%d} versus {nx=%d, ny=%d, nf=%d, nb=%d}\\n\",\n preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb, origPreLoc->nx, origPreLoc->ny, origPreLoc->nf, origPreLoc->nb);\n }\n abort();\n }\n\n \/\/Redudent read in case it's a clone of a clone\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n shrinkPatches_flag = originalConn->getShrinkPatches_flag();\n\n return status;\n}\n\nint CloneKernelConn::setPatchSize() {\n assert(originalConn);\n nxp = originalConn->xPatchSize();\n nyp = originalConn->yPatchSize();\n nxpShrunken = originalConn->getNxpShrunken();\n nypShrunken = originalConn->getNypShrunken();\n nfp = originalConn->fPatchSize();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::updateState(double time, double dt) {\n lastUpdateTime = originalConn->getLastUpdateTime();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::deleteWeights() {\n \/\/ Have to make sure not to free memory belonging to originalConn.\n \/\/ Set pointers that point into originalConn to NULL so that free() has no effect\n \/\/ when KernelConn::deleteWeights or HyPerConn::deleteWeights is called\n\t wPatches = NULL;\n\t wDataStart = NULL;\n\t gSynPatchStart = NULL;\n\t aPostOffset = NULL;\n\t dwDataStart = NULL;\n\/\/ for(int arbor=0; arborAdded update timer.\/* CloneKernelConn.cpp\n *\n * Created on: May 23, 2011\n * Author: peteschultz\n *\/\n\n#include \"CloneKernelConn.hpp\"\n\nnamespace PV {\n\nCloneKernelConn::CloneKernelConn(){\n initialize_base();\n}\n\nCloneKernelConn::CloneKernelConn(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n initialize_base();\n initialize(name, hc, pre_layer_name, post_layer_name, original_kernelconn_name);\n}\n\nint CloneKernelConn::initialize_base() {\n originalConn = NULL;\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::initialize(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n InitCloneKernelWeights * weightInit = new InitCloneKernelWeights();\n assert(weightInit != NULL);\n int status = KernelConn::initialize(name, hc, pre_layer_name, post_layer_name, NULL, weightInit);\n if (original_kernelconn_name==NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName must be set.\\n\",\n name, hc->columnId());\n abort();\n }\n originalConnName = strdup(original_kernelconn_name);\n if (originalConnName == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: unable to allocate memory for originalConnName \\\"%s\\\": %s\\n\",\n name, hc->columnId(), original_kernelconn_name, strerror(errno));\n abort();\n }\n return status;\n}\n\n\/\/int CloneKernelConn::setPatchSize(const char * filename) {\n\/\/ \/\/ nxp, nyp, nfp were set by the read-methods called by HyPerConn::setParams\n\/\/ assert(filename == NULL);\n\/\/ int xScalePre = pre->getXScale();\n\/\/ int xScalePost = post->getXScale();\n\/\/ int status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');\n\/\/ if( status == PV_SUCCESS) {\n\/\/ int yScalePre = pre->getYScale();\n\/\/ int yScalePost = post->getYScale();\n\/\/ status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');\n\/\/ }\n\/\/ return status;\n\/\/}\n\nint CloneKernelConn::initNormalize() {\n normalizer = NULL;\n \/\/ normalize_flag = false; \/\/ replaced by testing whether normalizer!=NULL\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::constructWeights(const char * filename) {\n int status = PV_SUCCESS;\n\n \/\/ CloneKernelConn::readShrinkPatches does nothing; shrinkPatches_flag is set in communicateInitInfo()\n \/\/ if( status == PV_SUCCESS ) readShrinkPatches(parent->parameters());\n\n \/\/ if( status == PV_SUCCESS ) status = setPatchSize(NULL);\n if( status == PV_SUCCESS ) status = setPatchStrides();\n\n wPatches = this->originalConn->get_wPatches();\n wDataStart = this->originalConn->get_wDataStart();\n gSynPatchStart = this->originalConn->getGSynPatchStart();\n aPostOffset = this->originalConn->getAPostOffset();\n dwDataStart = this->originalConn->get_dwDataStart();\n\n\/\/ for( int arbor=0; arborget_wDataStart(arbor);\n\/\/ get_wPatches()[arbor] = originalConn->weights(arbor);\n\/\/ \/\/ this->setKernelPatches(originalConn->getKernelPatches(arbor),arbor);\n\/\/ if( status == PV_SUCCESS )\n\/\/ status = createAxonalArbors(arbor); \/\/ sets gSynPatchStart[arbor][*] and aPostOffset[arbor][*]\n\/\/ if( status != PV_SUCCESS ) break;\n\/\/ }\n\n \/\/ Don't call initPlasticityPatches since plasticityFlag is always false.\n \/\/ Don't call shrinkPatches() since the original connection will have already shrunk patches\n return status;\n}\n\nvoid CloneKernelConn::constructWeightsOutOfMemory() {\n connOutOfMemory(\"CloneKernelConn::constructWeightsOutOfMemory()\");\n}\n\nint CloneKernelConn::createAxonalArbors(int arborId) {\n\/\/ int numPatches = getNumWeightPatches();\n\/\/ for( int kex = 0; kex < numPatches; kex++ ) {\n\/\/ \/\/ kex is in extended frame, this makes transformations more difficult\n\/\/ int kl, offset, nxPatch, nyPatch, dx, dy;\n\/\/ calcPatchSize(arborId, kex, &kl, &offset, &nxPatch, &nyPatch, &dx, &dy);\n\/\/ pvdata_t * gSyn = post->getChannel(channel) + kl;\n\/\/ getGSynPatchStart()[arborId][kex] = gSyn;\n\/\/ getAPostOffset()[arborId][kex] = offset;\n\/\/ \/\/ Don't call pvpatch_adjust because weight patches point to the\n\/\/ \/\/ original conn's weight patches, which were already shrunk.\n\/\/ }\n return PV_SUCCESS;\n}\n\nPVPatch *** CloneKernelConn::initializeWeights(PVPatch *** patches, pvdata_t ** dataStart,\n int numPatches, const char * filename) {\n return patches;\n \/\/ nothing to be done as the weight patches point to originalConn's space.\n}\n\nvoid CloneKernelConn::readShrinkPatches(PVParams * params) {\n \/\/ During the communication phase, shrinkPatches_flag will be copied from originalConn\n}\n\nint CloneKernelConn::setParams(PVParams * params) {\n return KernelConn::setParams(params);\n}\n\nvoid CloneKernelConn::readNumAxonalArbors(PVParams * params) {\n \/\/ During the communication phase, numAxonalArbors will be copied from originalConn\n}\n\nvoid CloneKernelConn::readPlasticityFlag(PVParams * params) {\n plasticityFlag = false; \/\/ CloneKernelConn updates automatically, since it's done using pointer magic.\n}\n\nint CloneKernelConn::readPatchSize(PVParams * params) {\n \/\/ During the communication phase, nxp, nyp, nxpShrunken, nypShrunken will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::readNfp(PVParams * params) {\n \/\/ During the communication phase, nfp will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::communicateInitInfo() {\n \/\/ Need to set originalConn before calling KernelConn::communicate, since KernelConn::communicate calls setPatchSize, which needs originalConn.\n HyPerConn * origHyPerConn = parent->getConnFromName(originalConnName);\n if (origHyPerConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" is not a connection in the column.\\n\",\n name, parent->columnId(), originalConnName);\n }\n originalConn = dynamic_cast(origHyPerConn);\n if (originalConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" must be a KernelConn or a KernelConn-derived class.\\n\",\n name, parent->columnId(), originalConnName);\n }\n\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n int status = KernelConn::communicateInitInfo();\n if (status != PV_SUCCESS) return status;\n\n \/\/ Presynaptic layers of the CloneKernelConn and its original conn must have the same size, or the patches won't line up with each other.\n const PVLayerLoc * preLoc = pre->getLayerLoc();\n const PVLayerLoc * origPreLoc = originalConn->preSynapticLayer()->getLayerLoc();\n\n if (preLoc->nx != origPreLoc->nx || preLoc->ny != origPreLoc->ny || preLoc->nf != origPreLoc->nf || preLoc->nb != origPreLoc->nb ) {\n if (parent->icCommunicator()->commRank()==0) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: CloneKernelConn and originalConn \\\"%s\\\" must have presynaptic layers with the same geometry (including margin width).\\n\",\n name, parent->columnId(), originalConn->getName());\n fprintf(stderr, \"{nx=%d, ny=%d, nf=%d, nb=%d} versus {nx=%d, ny=%d, nf=%d, nb=%d}\\n\",\n preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb, origPreLoc->nx, origPreLoc->ny, origPreLoc->nf, origPreLoc->nb);\n }\n abort();\n }\n\n \/\/Redudent read in case it's a clone of a clone\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n shrinkPatches_flag = originalConn->getShrinkPatches_flag();\n\n return status;\n}\n\nint CloneKernelConn::setPatchSize() {\n assert(originalConn);\n nxp = originalConn->xPatchSize();\n nyp = originalConn->yPatchSize();\n nxpShrunken = originalConn->getNxpShrunken();\n nypShrunken = originalConn->getNypShrunken();\n nfp = originalConn->fPatchSize();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::updateState(double time, double dt) {\n update_timer->start();\n\n lastUpdateTime = originalConn->getLastUpdateTime();\n\n update_timer->stop();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::deleteWeights() {\n \/\/ Have to make sure not to free memory belonging to originalConn.\n \/\/ Set pointers that point into originalConn to NULL so that free() has no effect\n \/\/ when KernelConn::deleteWeights or HyPerConn::deleteWeights is called\n\t wPatches = NULL;\n\t wDataStart = NULL;\n\t gSynPatchStart = NULL;\n\t aPostOffset = NULL;\n\t dwDataStart = NULL;\n\/\/ for(int arbor=0; arbor"} {"text":"\/* CloneKernelConn.cpp\n *\n * Created on: May 23, 2011\n * Author: peteschultz\n *\/\n\n#include \"CloneKernelConn.hpp\"\n\nnamespace PV {\n\nCloneKernelConn::CloneKernelConn(){\n initialize_base();\n}\n\nCloneKernelConn::CloneKernelConn(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n initialize_base();\n initialize(name, hc, pre_layer_name, post_layer_name, original_kernelconn_name);\n}\n\nint CloneKernelConn::initialize_base() {\n originalConn = NULL;\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::initialize(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n InitCloneKernelWeights * weightInit = new InitCloneKernelWeights();\n assert(weightInit != NULL);\n int status = KernelConn::initialize(name, hc, pre_layer_name, post_layer_name, NULL, weightInit);\n if (original_kernelconn_name==NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName must be set.\\n\",\n name, hc->columnId());\n abort();\n }\n originalConnName = strdup(original_kernelconn_name);\n if (originalConnName == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: unable to allocate memory for originalConnName \\\"%s\\\": %s\\n\",\n name, hc->columnId(), original_kernelconn_name, strerror(errno));\n abort();\n }\n return status;\n}\n\n\/\/int CloneKernelConn::setPatchSize(const char * filename) {\n\/\/ \/\/ nxp, nyp, nfp were set by the read-methods called by HyPerConn::setParams\n\/\/ assert(filename == NULL);\n\/\/ int xScalePre = pre->getXScale();\n\/\/ int xScalePost = post->getXScale();\n\/\/ int status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');\n\/\/ if( status == PV_SUCCESS) {\n\/\/ int yScalePre = pre->getYScale();\n\/\/ int yScalePost = post->getYScale();\n\/\/ status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');\n\/\/ }\n\/\/ return status;\n\/\/}\n\nint CloneKernelConn::initNormalize() {\n normalizer = NULL;\n \/\/ normalize_flag = false; \/\/ replaced by testing whether normalizer!=NULL\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::constructWeights(const char * filename) {\n int status = PV_SUCCESS;\n\n \/\/ CloneKernelConn::readShrinkPatches does nothing; shrinkPatches_flag is set in communicateInitInfo()\n \/\/ if( status == PV_SUCCESS ) readShrinkPatches(parent->parameters());\n\n \/\/ if( status == PV_SUCCESS ) status = setPatchSize(NULL);\n if( status == PV_SUCCESS ) status = setPatchStrides();\n\n wPatches = this->originalConn->get_wPatches();\n wDataStart = this->originalConn->get_wDataStart();\n gSynPatchStart = this->originalConn->getGSynPatchStart();\n aPostOffset = this->originalConn->getAPostOffset();\n dwDataStart = this->originalConn->get_dwDataStart();\n\n\/\/ for( int arbor=0; arborget_wDataStart(arbor);\n\/\/ get_wPatches()[arbor] = originalConn->weights(arbor);\n\/\/ \/\/ this->setKernelPatches(originalConn->getKernelPatches(arbor),arbor);\n\/\/ if( status == PV_SUCCESS )\n\/\/ status = createAxonalArbors(arbor); \/\/ sets gSynPatchStart[arbor][*] and aPostOffset[arbor][*]\n\/\/ if( status != PV_SUCCESS ) break;\n\/\/ }\n\n \/\/ Don't call initPlasticityPatches since plasticityFlag is always false.\n \/\/ Don't call shrinkPatches() since the original connection will have already shrunk patches\n return status;\n}\n\nvoid CloneKernelConn::constructWeightsOutOfMemory() {\n connOutOfMemory(\"CloneKernelConn::constructWeightsOutOfMemory()\");\n}\n\nint CloneKernelConn::createAxonalArbors(int arborId) {\n\/\/ int numPatches = getNumWeightPatches();\n\/\/ for( int kex = 0; kex < numPatches; kex++ ) {\n\/\/ \/\/ kex is in extended frame, this makes transformations more difficult\n\/\/ int kl, offset, nxPatch, nyPatch, dx, dy;\n\/\/ calcPatchSize(arborId, kex, &kl, &offset, &nxPatch, &nyPatch, &dx, &dy);\n\/\/ pvdata_t * gSyn = post->getChannel(channel) + kl;\n\/\/ getGSynPatchStart()[arborId][kex] = gSyn;\n\/\/ getAPostOffset()[arborId][kex] = offset;\n\/\/ \/\/ Don't call pvpatch_adjust because weight patches point to the\n\/\/ \/\/ original conn's weight patches, which were already shrunk.\n\/\/ }\n return PV_SUCCESS;\n}\n\nPVPatch *** CloneKernelConn::initializeWeights(PVPatch *** patches, pvdata_t ** dataStart,\n int numPatches, const char * filename) {\n return patches;\n \/\/ nothing to be done as the weight patches point to originalConn's space.\n}\n\n\/\/ We override many read-methods because CloneKernelConn will use\n\/\/ originalConn's values. communicateInitInfo will check if the associated\n\/\/ parameters exist in params for theCloneKernelConn group, and whether they\n\/\/ are consistent with the originalConn parameters.\n\/\/ If consistent, issue a warning that the param is unnecessary and continue.\n\/\/ If inconsistent, issue an error and quit.\n\/\/ We can't do that in the read-method because we can't be sure originalConn\n\/\/ has set its own parameter yet (or even if it's been instantiated),\n\/\/ and in theory originalConn could be a subclass that determines\n\/\/ the parameter some way other than reading its own parameter\n\/\/ group's param directly.\n\nvoid CloneKernelConn::readShrinkPatches(PVParams * params) {\n \/\/ During the communication phase, shrinkPatches_flag will be copied from originalConn\n}\n\nint CloneKernelConn::setParams(PVParams * params) {\n return KernelConn::setParams(params);\n}\n\nvoid CloneKernelConn::readNumAxonalArbors(PVParams * params) {\n \/\/ During the communication phase, numAxonalArbors will be copied from originalConn\n}\n\nvoid CloneKernelConn::readPlasticityFlag(PVParams * params) {\n plasticityFlag = false; \/\/ CloneKernelConn updates automatically, since it's done using pointer magic.\n handleUnnecessaryIntParameter(\"plasticityFlag\", plasticityFlag);\n}\n\nint CloneKernelConn::readPatchSize(PVParams * params) {\n \/\/ During the communication phase, nxp, nyp, nxpShrunken, nypShrunken will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::readNfp(PVParams * params) {\n \/\/ During the communication phase, nfp will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::communicateInitInfo() {\n \/\/ Need to set originalConn before calling KernelConn::communicate, since KernelConn::communicate calls setPatchSize, which needs originalConn.\n HyPerConn * origHyPerConn = parent->getConnFromName(originalConnName);\n if (origHyPerConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" is not a connection in the column.\\n\",\n name, parent->columnId(), originalConnName);\n }\n originalConn = dynamic_cast(origHyPerConn);\n if (originalConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" must be a KernelConn or a KernelConn-derived class.\\n\",\n name, parent->columnId(), originalConnName);\n }\n\n \/\/ Copy some parameters from originalConn. Check if parameters exist is\n \/\/ the clone's param group, and issue a warning (if the param has the right\n \/\/ value) or an error (if it has the wrong value).\n int status = PV_SUCCESS;\n PVParams * params = parent->parameters();\n const char * classname = params->groupKeywordFromName(name);\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n handleUnnecessaryIntParameter(\"numAxonalArbors\", numAxonalArborLists);\n status = KernelConn::communicateInitInfo();\n if (status != PV_SUCCESS) return status;\n\n \/\/ Presynaptic layers of the CloneKernelConn and its original conn must have the same size, or the patches won't line up with each other.\n const PVLayerLoc * preLoc = pre->getLayerLoc();\n const PVLayerLoc * origPreLoc = originalConn->preSynapticLayer()->getLayerLoc();\n\n if (preLoc->nx != origPreLoc->nx || preLoc->ny != origPreLoc->ny || preLoc->nf != origPreLoc->nf || preLoc->nb != origPreLoc->nb ) {\n if (parent->icCommunicator()->commRank()==0) {\n fprintf(stderr, \"%s \\\"%s\\\" error in rank %d process: CloneKernelConn and originalConn \\\"%s\\\" must have presynaptic layers with the same geometry (including margin width).\\n\",\n classname, name, parent->columnId(), originalConn->getName());\n fprintf(stderr, \"{nx=%d, ny=%d, nf=%d, nb=%d} versus {nx=%d, ny=%d, nf=%d, nb=%d}\\n\",\n preLoc->nx, preLoc->ny, preLoc->nf, preLoc->nb, origPreLoc->nx, origPreLoc->ny, origPreLoc->nf, origPreLoc->nb);\n }\n abort();\n }\n\n \/\/Redudant read in case it's a clone of a clone\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n shrinkPatches_flag = originalConn->getShrinkPatches_flag();\n handleUnnecessaryIntParameter(\"shrinkPatches\", shrinkPatches_flag);\n\n return status;\n}\n\nint CloneKernelConn::setPatchSize() {\n assert(originalConn);\n nxp = originalConn->xPatchSize();\n nyp = originalConn->yPatchSize();\n nxpShrunken = originalConn->getNxpShrunken();\n nypShrunken = originalConn->getNypShrunken();\n nfp = originalConn->fPatchSize();\n handleUnnecessaryIntParameter(\"nxp\", nxp);\n handleUnnecessaryIntParameter(\"nyp\", nyp);\n handleUnnecessaryIntParameter(\"nxpShrunken\", nxpShrunken);\n handleUnnecessaryIntParameter(\"nypShrunken\", nypShrunken);\n handleUnnecessaryIntParameter(\"nfp\", nfp);\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::updateState(double time, double dt) {\n update_timer->start();\n\n lastUpdateTime = originalConn->getLastUpdateTime();\n\n update_timer->stop();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::deleteWeights() {\n \/\/ Have to make sure not to free memory belonging to originalConn.\n \/\/ Set pointers that point into originalConn to NULL so that free() has no effect\n \/\/ when KernelConn::deleteWeights or HyPerConn::deleteWeights is called\n\t wPatches = NULL;\n\t wDataStart = NULL;\n\t gSynPatchStart = NULL;\n\t aPostOffset = NULL;\n\t dwDataStart = NULL;\n\/\/ for(int arbor=0; arborpresynaptic layers of a CloneKernelConn and its original conn keep their margin widths synchronized instead of checking that they're equal and failing if not.\/* CloneKernelConn.cpp\n *\n * Created on: May 23, 2011\n * Author: peteschultz\n *\/\n\n#include \"CloneKernelConn.hpp\"\n\nnamespace PV {\n\nCloneKernelConn::CloneKernelConn(){\n initialize_base();\n}\n\nCloneKernelConn::CloneKernelConn(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n initialize_base();\n initialize(name, hc, pre_layer_name, post_layer_name, original_kernelconn_name);\n}\n\nint CloneKernelConn::initialize_base() {\n originalConn = NULL;\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::initialize(const char * name, HyPerCol * hc,\n const char * pre_layer_name, const char * post_layer_name,\n const char * original_kernelconn_name) {\n InitCloneKernelWeights * weightInit = new InitCloneKernelWeights();\n assert(weightInit != NULL);\n int status = KernelConn::initialize(name, hc, pre_layer_name, post_layer_name, NULL, weightInit);\n if (original_kernelconn_name==NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName must be set.\\n\",\n name, hc->columnId());\n abort();\n }\n originalConnName = strdup(original_kernelconn_name);\n if (originalConnName == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: unable to allocate memory for originalConnName \\\"%s\\\": %s\\n\",\n name, hc->columnId(), original_kernelconn_name, strerror(errno));\n abort();\n }\n return status;\n}\n\n\/\/int CloneKernelConn::setPatchSize(const char * filename) {\n\/\/ \/\/ nxp, nyp, nfp were set by the read-methods called by HyPerConn::setParams\n\/\/ assert(filename == NULL);\n\/\/ int xScalePre = pre->getXScale();\n\/\/ int xScalePost = post->getXScale();\n\/\/ int status = checkPatchSize(nxp, xScalePre, xScalePost, 'x');\n\/\/ if( status == PV_SUCCESS) {\n\/\/ int yScalePre = pre->getYScale();\n\/\/ int yScalePost = post->getYScale();\n\/\/ status = checkPatchSize(nyp, yScalePre, yScalePost, 'y');\n\/\/ }\n\/\/ return status;\n\/\/}\n\nint CloneKernelConn::initNormalize() {\n normalizer = NULL;\n \/\/ normalize_flag = false; \/\/ replaced by testing whether normalizer!=NULL\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::constructWeights(const char * filename) {\n int status = PV_SUCCESS;\n\n \/\/ CloneKernelConn::readShrinkPatches does nothing; shrinkPatches_flag is set in communicateInitInfo()\n \/\/ if( status == PV_SUCCESS ) readShrinkPatches(parent->parameters());\n\n \/\/ if( status == PV_SUCCESS ) status = setPatchSize(NULL);\n if( status == PV_SUCCESS ) status = setPatchStrides();\n\n wPatches = this->originalConn->get_wPatches();\n wDataStart = this->originalConn->get_wDataStart();\n gSynPatchStart = this->originalConn->getGSynPatchStart();\n aPostOffset = this->originalConn->getAPostOffset();\n dwDataStart = this->originalConn->get_dwDataStart();\n\n\/\/ for( int arbor=0; arborget_wDataStart(arbor);\n\/\/ get_wPatches()[arbor] = originalConn->weights(arbor);\n\/\/ \/\/ this->setKernelPatches(originalConn->getKernelPatches(arbor),arbor);\n\/\/ if( status == PV_SUCCESS )\n\/\/ status = createAxonalArbors(arbor); \/\/ sets gSynPatchStart[arbor][*] and aPostOffset[arbor][*]\n\/\/ if( status != PV_SUCCESS ) break;\n\/\/ }\n\n \/\/ Don't call initPlasticityPatches since plasticityFlag is always false.\n \/\/ Don't call shrinkPatches() since the original connection will have already shrunk patches\n return status;\n}\n\nvoid CloneKernelConn::constructWeightsOutOfMemory() {\n connOutOfMemory(\"CloneKernelConn::constructWeightsOutOfMemory()\");\n}\n\nint CloneKernelConn::createAxonalArbors(int arborId) {\n\/\/ int numPatches = getNumWeightPatches();\n\/\/ for( int kex = 0; kex < numPatches; kex++ ) {\n\/\/ \/\/ kex is in extended frame, this makes transformations more difficult\n\/\/ int kl, offset, nxPatch, nyPatch, dx, dy;\n\/\/ calcPatchSize(arborId, kex, &kl, &offset, &nxPatch, &nyPatch, &dx, &dy);\n\/\/ pvdata_t * gSyn = post->getChannel(channel) + kl;\n\/\/ getGSynPatchStart()[arborId][kex] = gSyn;\n\/\/ getAPostOffset()[arborId][kex] = offset;\n\/\/ \/\/ Don't call pvpatch_adjust because weight patches point to the\n\/\/ \/\/ original conn's weight patches, which were already shrunk.\n\/\/ }\n return PV_SUCCESS;\n}\n\nPVPatch *** CloneKernelConn::initializeWeights(PVPatch *** patches, pvdata_t ** dataStart,\n int numPatches, const char * filename) {\n return patches;\n \/\/ nothing to be done as the weight patches point to originalConn's space.\n}\n\n\/\/ We override many read-methods because CloneKernelConn will use\n\/\/ originalConn's values. communicateInitInfo will check if the associated\n\/\/ parameters exist in params for theCloneKernelConn group, and whether they\n\/\/ are consistent with the originalConn parameters.\n\/\/ If consistent, issue a warning that the param is unnecessary and continue.\n\/\/ If inconsistent, issue an error and quit.\n\/\/ We can't do that in the read-method because we can't be sure originalConn\n\/\/ has set its own parameter yet (or even if it's been instantiated),\n\/\/ and in theory originalConn could be a subclass that determines\n\/\/ the parameter some way other than reading its own parameter\n\/\/ group's param directly.\n\nvoid CloneKernelConn::readShrinkPatches(PVParams * params) {\n \/\/ During the communication phase, shrinkPatches_flag will be copied from originalConn\n}\n\nint CloneKernelConn::setParams(PVParams * params) {\n return KernelConn::setParams(params);\n}\n\nvoid CloneKernelConn::readNumAxonalArbors(PVParams * params) {\n \/\/ During the communication phase, numAxonalArbors will be copied from originalConn\n}\n\nvoid CloneKernelConn::readPlasticityFlag(PVParams * params) {\n plasticityFlag = false; \/\/ CloneKernelConn updates automatically, since it's done using pointer magic.\n handleUnnecessaryIntParameter(\"plasticityFlag\", plasticityFlag);\n}\n\nint CloneKernelConn::readPatchSize(PVParams * params) {\n \/\/ During the communication phase, nxp, nyp, nxpShrunken, nypShrunken will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::readNfp(PVParams * params) {\n \/\/ During the communication phase, nfp will be copied from originalConn\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::communicateInitInfo() {\n \/\/ Need to set originalConn before calling KernelConn::communicate, since KernelConn::communicate calls setPatchSize, which needs originalConn.\n HyPerConn * origHyPerConn = parent->getConnFromName(originalConnName);\n if (origHyPerConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" is not a connection in the column.\\n\",\n name, parent->columnId(), originalConnName);\n }\n originalConn = dynamic_cast(origHyPerConn);\n if (originalConn == NULL) {\n fprintf(stderr, \"CloneKernelConn \\\"%s\\\" error in rank %d process: originalConnName \\\"%s\\\" must be a KernelConn or a KernelConn-derived class.\\n\",\n name, parent->columnId(), originalConnName);\n }\n\n \/\/ Copy some parameters from originalConn. Check if parameters exist is\n \/\/ the clone's param group, and issue a warning (if the param has the right\n \/\/ value) or an error (if it has the wrong value).\n int status = PV_SUCCESS;\n PVParams * params = parent->parameters();\n const char * classname = params->groupKeywordFromName(name);\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n handleUnnecessaryIntParameter(\"numAxonalArbors\", numAxonalArborLists);\n status = KernelConn::communicateInitInfo();\n if (status != PV_SUCCESS) return status;\n\n \/\/ Presynaptic layers of the CloneKernelConn and its original conn must have the same size, or the patches won't line up with each other.\n const PVLayerLoc * preLoc = pre->getLayerLoc();\n const PVLayerLoc * origPreLoc = originalConn->preSynapticLayer()->getLayerLoc();\n\n if (preLoc->nx != origPreLoc->nx || preLoc->ny != origPreLoc->ny || preLoc->nf != origPreLoc->nf ) {\n if (parent->icCommunicator()->commRank()==0) {\n fprintf(stderr, \"%s \\\"%s\\\" error in rank %d process: CloneKernelConn and originalConn \\\"%s\\\" must have presynaptic layers with the same nx,ny,nf.\\n\",\n classname, name, parent->columnId(), originalConn->getName());\n fprintf(stderr, \"{nx=%d, ny=%d, nf=%d} versus {nx=%d, ny=%d, nf=%d}\\n\",\n preLoc->nx, preLoc->ny, preLoc->nf, origPreLoc->nx, origPreLoc->ny, origPreLoc->nf);\n }\n abort();\n }\n\n \/\/ Make sure the original's and the clone's margin widths stay equal\n originalConn->preSynapticLayer()->synchronizeMarginWidth(pre);\n pre->synchronizeMarginWidth(originalConn->preSynapticLayer());\n\n \/\/Redudant read in case it's a clone of a clone\n numAxonalArborLists = originalConn->numberOfAxonalArborLists();\n shrinkPatches_flag = originalConn->getShrinkPatches_flag();\n handleUnnecessaryIntParameter(\"shrinkPatches\", shrinkPatches_flag);\n\n return status;\n}\n\nint CloneKernelConn::setPatchSize() {\n assert(originalConn);\n nxp = originalConn->xPatchSize();\n nyp = originalConn->yPatchSize();\n nxpShrunken = originalConn->getNxpShrunken();\n nypShrunken = originalConn->getNypShrunken();\n nfp = originalConn->fPatchSize();\n handleUnnecessaryIntParameter(\"nxp\", nxp);\n handleUnnecessaryIntParameter(\"nyp\", nyp);\n handleUnnecessaryIntParameter(\"nxpShrunken\", nxpShrunken);\n handleUnnecessaryIntParameter(\"nypShrunken\", nypShrunken);\n handleUnnecessaryIntParameter(\"nfp\", nfp);\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::updateState(double time, double dt) {\n update_timer->start();\n\n lastUpdateTime = originalConn->getLastUpdateTime();\n\n update_timer->stop();\n return PV_SUCCESS;\n}\n\nint CloneKernelConn::deleteWeights() {\n \/\/ Have to make sure not to free memory belonging to originalConn.\n \/\/ Set pointers that point into originalConn to NULL so that free() has no effect\n \/\/ when KernelConn::deleteWeights or HyPerConn::deleteWeights is called\n\t wPatches = NULL;\n\t wDataStart = NULL;\n\t gSynPatchStart = NULL;\n\t aPostOffset = NULL;\n\t dwDataStart = NULL;\n\/\/ for(int arbor=0; arbor"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"pch.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace musik::core;\n\nstatic LibraryFactory::IMessageQueue* sMessageQueue = nullptr;\nstatic std::shared_ptr sInstance;\n\nvoid LibraryFactory::Initialize(IMessageQueue& messageQueue) {\n sMessageQueue = &messageQueue;\n}\n\nLibraryFactory& LibraryFactory::Instance() {\n if (!sInstance) {\n sInstance = std::shared_ptr(new LibraryFactory());\n }\n return *sInstance;\n};\n\nLibraryFactory::LibraryFactory() {\n auto prefs = Preferences::ForComponent(prefs::components::Libraries);\n std::vector libraries;\n prefs->GetKeys(libraries);\n\n for (size_t i = 0; i < libraries.size(); i++) {\n std::string name = libraries.at(i);\n int id = prefs->GetInt(name);\n this->AddLibrary(id, LibraryType::Local, name);\n }\n\n if (this->libraries.empty()) {\n this->CreateLibrary(\"Local Library\", LibraryType::Local);\n }\n}\n\nLibraryFactory::~LibraryFactory() {\n}\n\nILibraryPtr LibraryFactory::AddLibrary(int id, LibraryType type, const std::string& name) {\n ILibraryPtr library = (type == LibraryType::Local)\n ? library::LocalLibrary::Create(name, id)\n : library::RemoteLibrary::Create(name, id);\n\n if (library) {\n if (sMessageQueue) {\n library->SetMessageQueue(*sMessageQueue);\n }\n this->libraries.push_back(library);\n this->libraryMap[id] = library;\n this->LibrariesUpdated();\n }\n\n return library;\n}\n\nvoid LibraryFactory::Shutdown() {\n if (sInstance) {\n for (ILibraryPtr library : sInstance->libraries) {\n library->Close();\n }\n sInstance->libraries.clear();\n }\n}\n\nILibraryPtr LibraryFactory::CreateLibrary(const std::string& name, LibraryType type) {\n auto prefs = Preferences::ForComponent(prefs::components::Libraries);\n std::vector libraries;\n prefs->GetKeys(libraries);\n\n \/* ensure the library doesn't already exist, and figure out a\n new unique identifier for this one... *\/\n\n int existingId = -1;\n int nextId = 0; \/* we start at 1 becuase we always have. *\/\n for (size_t i = 0; i < libraries.size(); i++) {\n std::string n = libraries.at(i);\n int id = prefs->GetInt(name);\n\n if (n == name) {\n \/* we already created a library with this name, let's go ahead\n and look it up and return it. *\/\n existingId = id;\n break;\n }\n\n if (id > nextId) {\n nextId = id;\n }\n }\n\n if (existingId != -1) {\n return this->GetLibrary(existingId);\n }\n\n ++nextId; \/* unique *\/\n prefs->SetInt(name, nextId);\n\n return this->AddLibrary(nextId, type, name);\n}\n\nLibraryFactory::LibraryVector LibraryFactory::Libraries() {\n return LibraryFactory::Instance().libraries;\n}\n\nILibraryPtr LibraryFactory::Default() {\n return LibraryFactory::Instance().libraries.at(0);\n}\n\nILibraryPtr LibraryFactory::GetLibrary(int identifier) {\n if (identifier) {\n LibraryMap::iterator lib = this->libraryMap.find(identifier);\n if (lib != this->libraryMap.end()) {\n return lib->second;\n }\n }\n return ILibraryPtr();\n}\n\nMore LibraryFactory bug fixes. This thing needs to be rethought.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2004-2019 musikcube team\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the author nor the names of other contributors may\n\/\/ be used to endorse or promote products derived from this software\n\/\/ without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"pch.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace musik::core;\n\nstatic LibraryFactory::IMessageQueue* sMessageQueue = nullptr;\nstatic std::shared_ptr sInstance;\n\nvoid LibraryFactory::Initialize(IMessageQueue& messageQueue) {\n sMessageQueue = &messageQueue;\n}\n\nLibraryFactory& LibraryFactory::Instance() {\n if (!sInstance) {\n sInstance = std::shared_ptr(new LibraryFactory());\n }\n return *sInstance;\n};\n\nLibraryFactory::LibraryFactory() {\n this->CreateLibrary(\"Local Library\", LibraryType::Local);\n}\n\nLibraryFactory::~LibraryFactory() {\n}\n\nILibraryPtr LibraryFactory::AddLibrary(int id, LibraryType type, const std::string& name) {\n ILibraryPtr library = (type == LibraryType::Local)\n ? library::LocalLibrary::Create(name, id)\n : library::RemoteLibrary::Create(name, id);\n\n if (library) {\n if (sMessageQueue) {\n library->SetMessageQueue(*sMessageQueue);\n }\n this->libraries.push_back(library);\n this->libraryMap[id] = library;\n this->LibrariesUpdated();\n }\n\n return library;\n}\n\nvoid LibraryFactory::Shutdown() {\n if (sInstance) {\n for (ILibraryPtr library : sInstance->libraries) {\n library->Close();\n }\n sInstance->libraries.clear();\n }\n}\n\nILibraryPtr LibraryFactory::CreateLibrary(const std::string& name, LibraryType type) {\n auto prefs = Preferences::ForComponent(prefs::components::Libraries);\n std::vector libraries;\n prefs->GetKeys(libraries);\n\n \/* ensure the library doesn't already exist, and figure out a\n new unique identifier for this one... *\/\n\n int existingId = -1;\n int nextId = 0; \/* we start at 1 becuase we always have. *\/\n for (size_t i = 0; i < libraries.size(); i++) {\n std::string n = libraries.at(i);\n int id = prefs->GetInt(name);\n\n if (n == name) {\n \/* we already created a library with this name, let's go ahead\n and look it up and return it. *\/\n existingId = id;\n break;\n }\n\n if (id > nextId) {\n nextId = id;\n }\n }\n\n if (existingId != -1) {\n auto library = this->GetLibrary(existingId);\n if (!library) {\n return this->AddLibrary(existingId, type, name);\n }\n }\n\n ++nextId; \/* unique *\/\n prefs->SetInt(name, nextId);\n\n return this->AddLibrary(nextId, type, name);\n}\n\nLibraryFactory::LibraryVector LibraryFactory::Libraries() {\n return LibraryFactory::Instance().libraries;\n}\n\nILibraryPtr LibraryFactory::Default() {\n return LibraryFactory::Instance().libraries.at(0);\n}\n\nILibraryPtr LibraryFactory::GetLibrary(int identifier) {\n if (identifier) {\n LibraryMap::iterator lib = this->libraryMap.find(identifier);\n if (lib != this->libraryMap.end()) {\n return lib->second;\n }\n }\n return ILibraryPtr();\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace sst {\nP2PConnectionManager::P2PConnectionManager(const P2PParams params)\n : my_node_id(params.my_node_id),\n failure_upcall(params.failure_upcall) {\n \n \/\/ HARD-CODED. Adding another request type will break this\n\n request_params.window_sizes[P2P_REPLY] = params.p2p_window_size;\n request_params.window_sizes[P2P_REQUEST] = params.p2p_window_size;\n request_params.window_sizes[RPC_REPLY] = params.rpc_window_size;\n request_params.max_msg_sizes[P2P_REPLY] = params.max_p2p_reply_size;\n request_params.max_msg_sizes[P2P_REQUEST] = params.max_p2p_request_size;\n request_params.max_msg_sizes[RPC_REPLY] = params.max_rpc_reply_size;\n\n p2p_buf_size = 0;\n for(uint8_t i = 0; i < num_request_types; ++i) {\n request_params.offsets[i] = p2p_buf_size;\n p2p_buf_size += request_params.window_sizes[i] * request_params.max_msg_sizes[i];\n }\n p2p_buf_size += sizeof(bool);\n\n p2p_connections[my_node_id] = std::make_unique(my_node_id, my_node_id, p2p_buf_size, request_params);\n\n \/\/ external client doesn't need failure checking\n if (!params.is_external) {\n timeout_thread = std::thread(&P2PConnectionManager::check_failures_loop, this);\n }\n}\n\nP2PConnectionManager::~P2PConnectionManager() {\n shutdown_failures_thread();\n}\n\nvoid P2PConnectionManager::add_connections(const std::vector& node_ids) {\n std::lock_guard lock(connections_mutex);\n for (const node_id_t remote_id : node_ids) {\n\tif (p2p_connections.find(remote_id) == p2p_connections.end()) {\n\t p2p_connections.emplace(remote_id, std::make_unique(my_node_id, remote_id, p2p_buf_size, request_params));\n \t}\n }\n}\n\nvoid P2PConnectionManager::remove_connections(const std::vector& node_ids) {\n std::lock_guard lock(connections_mutex);\n for(const node_id_t remote_id : node_ids) {\n p2p_connections.erase(remote_id);\n }\n}\n\nvoid P2PConnectionManager::shutdown_failures_thread() {\n thread_shutdown = true;\n if(timeout_thread.joinable()) {\n timeout_thread.join();\n }\n}\n\nuint64_t P2PConnectionManager::get_max_p2p_reply_size() {\n return request_params.max_msg_sizes[P2P_REPLY] - sizeof(uint64_t);\n}\n\nvoid P2PConnectionManager::update_incoming_seq_num() {\n p2p_connections[last_node_id]->update_incoming_seq_num();\n}\n\n\/\/ check if there's a new request from any node\nstd::optional> P2PConnectionManager::probe_all() {\n for(const auto& [node_id, p2p_conn] : p2p_connections) {\n auto buf = p2p_conn->probe();\n if(buf && buf[0]) {\n last_node_id = node_id;\n return std::pair(node_id, buf);\n } else if(buf) {\n \/\/ this means that we have a null reply\n \/\/ we don't need to process it, but we still want to increment the seq num\n p2p_conn->update_incoming_seq_num();\n }\n }\n return {};\n}\n\nchar* P2PConnectionManager::get_sendbuffer_ptr(node_id_t node_id, REQUEST_TYPE type) {\n return p2p_connections.at(node_id)->get_sendbuffer_ptr(type);\n}\n\nvoid P2PConnectionManager::send(node_id_t node_id) {\n p2p_connections.at(node_id)->send();\n if(node_id != my_node_id) {\n p2p_connections.at(node_id)->num_rdma_writes++;\n }\n}\n\nvoid P2PConnectionManager::check_failures_loop() {\n pthread_setname_np(pthread_self(), \"p2p_timeout\");\n\n uint32_t heartbeat_ms = derecho::getConfUInt32(CONF_DERECHO_HEARTBEAT_MS);\n const auto tid = std::this_thread::get_id();\n \/\/ get id first\n uint32_t ce_idx = util::polling_data.get_index(tid);\n while(!thread_shutdown) {\n std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_ms));\n std::unordered_set posted_write_to;\n\n util::polling_data.set_waiting(tid);\n#ifdef USE_VERBS_API\n std::map sctxt;\n#else\n std::map sctxt;\n#endif\n\n for(const auto& [node_id, p2p_conn] : p2p_connections) {\n if (node_id == my_node_id || p2p_conn->num_rdma_writes < 1000) {\n continue;\n }\n p2p_conn->num_rdma_writes = 0;\n sctxt[node_id].remote_id = node_id;\n sctxt[node_id].ce_idx = ce_idx;\n\n p2p_conn->get_res()->post_remote_write_with_completion(&sctxt[node_id], p2p_buf_size - sizeof(bool), sizeof(bool));\n posted_write_to.insert(node_id);\n } \n\n \/\/ track which nodes respond successfully\n std::unordered_set polled_successfully_from;\n std::vector failed_node_indexes;\n\n \/** Completion Queue poll timeout in millisec *\/\n const int MAX_POLL_CQ_TIMEOUT = 2000;\n unsigned long start_time_msec;\n unsigned long cur_time_msec;\n struct timeval cur_time;\n\n \/\/ wait for completion for a while before giving up of doing it ..\n gettimeofday(&cur_time, NULL);\n start_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec \/ 1000);\n\n uint32_t num_completions = 0;\n while(num_completions < p2p_connections.size() - 1) {\n std::optional> ce;\n while(true) {\n \/\/ check if polling result is available\n ce = util::polling_data.get_completion_entry(tid);\n if(ce) {\n break;\n }\n gettimeofday(&cur_time, NULL);\n cur_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec \/ 1000);\n if((cur_time_msec - start_time_msec) >= MAX_POLL_CQ_TIMEOUT) {\n break;\n }\n }\n \/\/ if waiting for a completion entry timed out\n if(!ce) {\n \/\/ mark all nodes that have not yet responded as failed\n for(const auto& pair : p2p_connections) {\n const auto& node_id = pair.first;\n if(posted_write_to.find(node_id) == posted_write_to.end() \n || polled_successfully_from.find(node_id) != polled_successfully_from.end()) {\n continue;\n }\n failed_node_indexes.push_back(node_id);\n }\n break;\n }\n num_completions++;\n\n auto ce_v = ce.value();\n int remote_id = ce_v.first;\n int result = ce_v.second;\n if(result == -1) {\n polled_successfully_from.insert(remote_id);\n } else if(result == -1) {\n failed_node_indexes.push_back(remote_id);\n }\n }\n util::polling_data.reset_waiting(tid);\n\n for(auto index : failed_node_indexes) {\n if(failure_upcall) {\n failure_upcall(index);\n }\n }\n }\n}\n\n\nvoid P2PConnectionManager::filter_to(const std::vector& live_nodes_list) {\n std::vector prev_nodes_list;\n for (const auto& e : p2p_connections ) {\n prev_nodes_list.push_back(e.first);\n }\n std::vector departed;\n std::set_difference(prev_nodes_list.begin(), prev_nodes_list.end(),\n live_nodes_list.begin(), live_nodes_list.end(),\n std::back_inserter(departed));\n remove_connections(departed);\n}\nvoid P2PConnectionManager::debug_print() {\n \/\/ std::cout << \"Members: \" << std::endl;\n \/\/ for(const auto& [node_id, p2p_conn] : p2p_connections) {\n \/\/ std::cout << node_id << \" \";\n \/\/ }\n \/\/ std::cout << std::endl;\n\n \/\/ for(const auto& type : p2p_request_types) {\n \/\/ std::cout << \"P2PConnections: Request type \" << type << std::endl;\n \/\/ for(uint32_t node = 0; node < num_members; ++node) {\n \/\/ std::cout << \"Node \" << node << std::endl;\n \/\/ std::cout << \"incoming seq_nums:\";\n \/\/ for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) {\n \/\/ uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t);\n \/\/ std::cout << \" \" << (uint64_t&)p2p_connections[node]->incoming_p2p_buffer[offset];\n \/\/ }\n \/\/ std::cout << std::endl\n \/\/ << \"outgoing seq_nums:\";\n \/\/ for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) {\n \/\/ uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t);\n \/\/ std::cout << \" \" << (uint64_t&)p2p_connections[node]->outgoing_p2p_buffer[offset];\n \/\/ }\n \/\/ std::cout << std::endl;\n \/\/ }\n \/\/ }\n}\n} \/\/ namespace sst\nfixed failure detection so that it checks every 1 second regardless of num_rdma_writes#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace sst {\nP2PConnectionManager::P2PConnectionManager(const P2PParams params)\n : my_node_id(params.my_node_id),\n failure_upcall(params.failure_upcall) {\n \n \/\/ HARD-CODED. Adding another request type will break this\n\n request_params.window_sizes[P2P_REPLY] = params.p2p_window_size;\n request_params.window_sizes[P2P_REQUEST] = params.p2p_window_size;\n request_params.window_sizes[RPC_REPLY] = params.rpc_window_size;\n request_params.max_msg_sizes[P2P_REPLY] = params.max_p2p_reply_size;\n request_params.max_msg_sizes[P2P_REQUEST] = params.max_p2p_request_size;\n request_params.max_msg_sizes[RPC_REPLY] = params.max_rpc_reply_size;\n\n p2p_buf_size = 0;\n for(uint8_t i = 0; i < num_request_types; ++i) {\n request_params.offsets[i] = p2p_buf_size;\n p2p_buf_size += request_params.window_sizes[i] * request_params.max_msg_sizes[i];\n }\n p2p_buf_size += sizeof(bool);\n\n p2p_connections[my_node_id] = std::make_unique(my_node_id, my_node_id, p2p_buf_size, request_params);\n\n \/\/ external client doesn't need failure checking\n if (!params.is_external) {\n timeout_thread = std::thread(&P2PConnectionManager::check_failures_loop, this);\n }\n}\n\nP2PConnectionManager::~P2PConnectionManager() {\n shutdown_failures_thread();\n}\n\nvoid P2PConnectionManager::add_connections(const std::vector& node_ids) {\n std::lock_guard lock(connections_mutex);\n for (const node_id_t remote_id : node_ids) {\n\tif (p2p_connections.find(remote_id) == p2p_connections.end()) {\n\t p2p_connections.emplace(remote_id, std::make_unique(my_node_id, remote_id, p2p_buf_size, request_params));\n \t}\n }\n}\n\nvoid P2PConnectionManager::remove_connections(const std::vector& node_ids) {\n std::lock_guard lock(connections_mutex);\n for(const node_id_t remote_id : node_ids) {\n p2p_connections.erase(remote_id);\n }\n}\n\nvoid P2PConnectionManager::shutdown_failures_thread() {\n thread_shutdown = true;\n if(timeout_thread.joinable()) {\n timeout_thread.join();\n }\n}\n\nuint64_t P2PConnectionManager::get_max_p2p_reply_size() {\n return request_params.max_msg_sizes[P2P_REPLY] - sizeof(uint64_t);\n}\n\nvoid P2PConnectionManager::update_incoming_seq_num() {\n p2p_connections[last_node_id]->update_incoming_seq_num();\n}\n\n\/\/ check if there's a new request from any node\nstd::optional> P2PConnectionManager::probe_all() {\n for(const auto& [node_id, p2p_conn] : p2p_connections) {\n auto buf = p2p_conn->probe();\n if(buf && buf[0]) {\n last_node_id = node_id;\n return std::pair(node_id, buf);\n } else if(buf) {\n \/\/ this means that we have a null reply\n \/\/ we don't need to process it, but we still want to increment the seq num\n p2p_conn->update_incoming_seq_num();\n }\n }\n return {};\n}\n\nchar* P2PConnectionManager::get_sendbuffer_ptr(node_id_t node_id, REQUEST_TYPE type) {\n return p2p_connections.at(node_id)->get_sendbuffer_ptr(type);\n}\n\nvoid P2PConnectionManager::send(node_id_t node_id) {\n p2p_connections.at(node_id)->send();\n if(node_id != my_node_id) {\n p2p_connections.at(node_id)->num_rdma_writes++;\n }\n}\n\nvoid P2PConnectionManager::check_failures_loop() {\n pthread_setname_np(pthread_self(), \"p2p_timeout\");\n\n uint32_t heartbeat_ms = derecho::getConfUInt32(CONF_DERECHO_HEARTBEAT_MS);\n const auto tid = std::this_thread::get_id();\n \/\/ get id first\n uint32_t ce_idx = util::polling_data.get_index(tid);\n\n uint16_t tick_count = 0;\n while(!thread_shutdown) {\n std::this_thread::sleep_for(std::chrono::milliseconds(heartbeat_ms));\n tick_count++;\n std::unordered_set posted_write_to;\n\n util::polling_data.set_waiting(tid);\n#ifdef USE_VERBS_API\n std::map sctxt;\n#else\n std::map sctxt;\n#endif\n\n for(const auto& [node_id, p2p_conn] : p2p_connections) {\n \/\/ checks every second regardless of num_rdma_writes\n if (node_id == my_node_id || (p2p_conn->num_rdma_writes < 1000 && tick_count < 1000)) {\n continue;\n }\n p2p_conn->num_rdma_writes = 0;\n sctxt[node_id].remote_id = node_id;\n sctxt[node_id].ce_idx = ce_idx;\n\n p2p_conn->get_res()->post_remote_write_with_completion(&sctxt[node_id], p2p_buf_size - sizeof(bool), sizeof(bool));\n posted_write_to.insert(node_id);\n } \n if (tick_count >= 1000) {\n tick_count = 0;\n }\n\n \/\/ track which nodes respond successfully\n std::unordered_set polled_successfully_from;\n std::vector failed_node_indexes;\n\n \/** Completion Queue poll timeout in millisec *\/\n const int MAX_POLL_CQ_TIMEOUT = 2000;\n unsigned long start_time_msec;\n unsigned long cur_time_msec;\n struct timeval cur_time;\n\n \/\/ wait for completion for a while before giving up of doing it ..\n gettimeofday(&cur_time, NULL);\n start_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec \/ 1000);\n\n uint32_t num_completions = 0;\n while(num_completions < p2p_connections.size() - 1) {\n std::optional> ce;\n while(true) {\n \/\/ check if polling result is available\n ce = util::polling_data.get_completion_entry(tid);\n if(ce) {\n break;\n }\n gettimeofday(&cur_time, NULL);\n cur_time_msec = (cur_time.tv_sec * 1000) + (cur_time.tv_usec \/ 1000);\n if((cur_time_msec - start_time_msec) >= MAX_POLL_CQ_TIMEOUT) {\n break;\n }\n }\n \/\/ if waiting for a completion entry timed out\n if(!ce) {\n \/\/ mark all nodes that have not yet responded as failed\n for(const auto& pair : p2p_connections) {\n const auto& node_id = pair.first;\n if(posted_write_to.find(node_id) == posted_write_to.end() \n || polled_successfully_from.find(node_id) != polled_successfully_from.end()) {\n continue;\n }\n failed_node_indexes.push_back(node_id);\n }\n break;\n }\n num_completions++;\n\n auto ce_v = ce.value();\n int remote_id = ce_v.first;\n int result = ce_v.second;\n if(result == -1) {\n polled_successfully_from.insert(remote_id);\n } else if(result == -1) {\n failed_node_indexes.push_back(remote_id);\n }\n }\n util::polling_data.reset_waiting(tid);\n\n for(auto index : failed_node_indexes) {\n if(failure_upcall) {\n failure_upcall(index);\n }\n }\n }\n}\n\n\nvoid P2PConnectionManager::filter_to(const std::vector& live_nodes_list) {\n std::vector prev_nodes_list;\n for (const auto& e : p2p_connections ) {\n prev_nodes_list.push_back(e.first);\n }\n std::vector departed;\n std::set_difference(prev_nodes_list.begin(), prev_nodes_list.end(),\n live_nodes_list.begin(), live_nodes_list.end(),\n std::back_inserter(departed));\n remove_connections(departed);\n}\nvoid P2PConnectionManager::debug_print() {\n \/\/ std::cout << \"Members: \" << std::endl;\n \/\/ for(const auto& [node_id, p2p_conn] : p2p_connections) {\n \/\/ std::cout << node_id << \" \";\n \/\/ }\n \/\/ std::cout << std::endl;\n\n \/\/ for(const auto& type : p2p_request_types) {\n \/\/ std::cout << \"P2PConnections: Request type \" << type << std::endl;\n \/\/ for(uint32_t node = 0; node < num_members; ++node) {\n \/\/ std::cout << \"Node \" << node << std::endl;\n \/\/ std::cout << \"incoming seq_nums:\";\n \/\/ for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) {\n \/\/ uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t);\n \/\/ std::cout << \" \" << (uint64_t&)p2p_connections[node]->incoming_p2p_buffer[offset];\n \/\/ }\n \/\/ std::cout << std::endl\n \/\/ << \"outgoing seq_nums:\";\n \/\/ for(uint32_t i = 0; i < request_params.window_sizes[type]; ++i) {\n \/\/ uint64_t offset = request_params.max_msg_sizes[type] * (type * request_params.window_sizes[type] + i + 1) - sizeof(uint64_t);\n \/\/ std::cout << \" \" << (uint64_t&)p2p_connections[node]->outgoing_p2p_buffer[offset];\n \/\/ }\n \/\/ std::cout << std::endl;\n \/\/ }\n \/\/ }\n}\n} \/\/ namespace sst\n<|endoftext|>"} {"text":"#include \"multimediabuffer.hpp\"\n\nusing namespace dash;\nusing namespace player;\n\nMultimediaBuffer::MultimediaBuffer(unsigned int maxBufferedSeconds)\n{\n this->maxBufferedSeconds= (double) maxBufferedSeconds;\n\n toBufferSegmentNumber = 0;\n toConsumeSegmentNumber = 0;\n}\n\nMultimediaBuffer::~MultimediaBuffer()\n{\n}\n\nbool MultimediaBuffer::addToBuffer(unsigned int segmentNumber, const dash::mpd::IRepresentation* usedRepresentation)\n{\n \/\/check if we receive a segment with a too large number\n if(toBufferSegmentNumber < segmentNumber)\n return false;\n\n \/\/fprintf(stderr, \"toBufferSegmentNumber=%d < segmentNumber=%d\\n\",toBufferSegmentNumber,segmentNumber);\n\n \/\/determine segment duration\n double duration = (double) usedRepresentation->GetSegmentList()->GetDuration();\n duration \/= (double) usedRepresentation->GetSegmentList()->GetTimescale ();\n\n \/\/ Check if segment has depIds\n mtx.lock ();\n if(usedRepresentation->GetDependencyId ().size() > 0)\n {\n \/\/ if so find the correct map\n MBuffer::iterator it = buff.find (segmentNumber);\n if(it == buff.end ())\n return false;\n\n BufferRepresentationEntryMap map = it->second;\n\n\n for(std::vector::const_iterator k = usedRepresentation->GetDependencyId ().begin ();\n k != usedRepresentation->GetDependencyId ().end (); k++)\n {\n \/\/depId not found we can not add this layer\n if(map.find ((*k)) == map.end ())\n {\n \/\/fprintf(stderr, \"Could not find '%s' in map\\n\", (*k).c_str());\n mtx.unlock ();\n return false;\n }\n }\n }\n else\n {\n \/\/check if segment with layer == 0 fits in buffer\n if(isFull(usedRepresentation->GetId (),duration))\n {\n mtx.unlock ();\n return false;\n }\n }\n\n \/\/ Add segment to buffer\n \/\/fprintf(stderr, \"Inserted something for Segment %d in Buffer\\n\", segmentNumber);\n\n MultimediaBuffer::BufferRepresentationEntry entry;\n entry.repId = usedRepresentation->GetId ();\n entry.segmentDuration = duration;\n entry.segmentNumber = segmentNumber;\n entry.depIds = usedRepresentation->GetDependencyId ();\n entry.bitrate_bit_s = usedRepresentation->GetBandwidth ();\n\n buff[segmentNumber][usedRepresentation->GetId ()] = entry;\n toBufferSegmentNumber++;\n mtx.unlock ();\n return true;\n}\n\nbool MultimediaBuffer::enoughSpaceInBuffer(unsigned int segmentNumber, const dash::mpd::IRepresentation* usedRepresentation)\n{\n \/\/determine segment duration\n double duration = (double) usedRepresentation->GetSegmentList()->GetDuration();\n duration \/= (double) usedRepresentation->GetSegmentList()->GetTimescale ();\n\n if(isFull(usedRepresentation->GetId (),duration))\n return false;\n\n return true;\n}\n\nbool MultimediaBuffer::isFull(std::string repId, double additional_seconds)\n{\n if(maxBufferedSeconds < additional_seconds+getBufferedSeconds(repId))\n return true;\n return false;\n}\n\nbool MultimediaBuffer::isEmpty()\n{\n if(getBufferedSeconds() <= 0.0)\n return true;\n return false;\n}\n\n\ndouble MultimediaBuffer::getBufferedSeconds()\n{\n double bufferSize = 0.0;\n\n for(MBuffer::iterator it = buff.begin (); it != buff.end (); ++it)\n bufferSize += it->second.begin()->second.segmentDuration;\n\n \/\/fprintf(stderr, \"BufferSize for lowestRep = %f\\n\", bufferSize);\n return bufferSize;\n}\n\ndouble MultimediaBuffer::getBufferedSeconds(std::string repId)\n{\n double bufferSize = 0.0;\n for(MBuffer::iterator it = buff.begin (); it != buff.end (); ++it)\n {\n BufferRepresentationEntryMap::iterator k = it->second.find(repId);\n if(k != it->second.end())\n {\n bufferSize += k->second.segmentDuration;\n }\n }\n \/\/fprintf(stderr, \"BufferSize for rep[%s] = %f\\n\", repId.c_str (),bufferSize);\n return bufferSize;\n}\n\nunsigned int MultimediaBuffer::getHighestBufferedSegmentNr(std::string repId)\n{\n \/\/std::map should be orderd based on operator<, so iterate from the back\n for(MBuffer::reverse_iterator it = buff.rbegin (); it != buff.rend (); ++it)\n {\n BufferRepresentationEntryMap::iterator k = it->second.find(repId);\n if(k != it->second.end())\n {\n return k->second.segmentNumber;\n }\n }\n return 0;\n}\n\n\nMultimediaBuffer::BufferRepresentationEntry MultimediaBuffer::consumeFromBuffer()\n{\n BufferRepresentationEntry entryConsumed;\n\n if(isEmpty())\n return entryConsumed;\n\n MBuffer::iterator it = buff.find (toConsumeSegmentNumber);\n if(it == buff.end ())\n {\n fprintf(stderr, \"Could not find SegmentNumber. This should never happen\\n\");\n return entryConsumed;\n }\n\n mtx.lock ();\n entryConsumed = getHighestConsumableRepresentation(toConsumeSegmentNumber);\n buff.erase (it);\n toConsumeSegmentNumber++;\n mtx.unlock ();\n return entryConsumed;\n}\n\nMultimediaBuffer::BufferRepresentationEntry MultimediaBuffer::getHighestConsumableRepresentation(int segmentNumber)\n{\n BufferRepresentationEntry consumableEntry;\n\n \/\/ find the correct entry map\n MBuffer::iterator it = buff.find (segmentNumber);\n if(it == buff.end ())\n {\n return consumableEntry;\n }\n\n BufferRepresentationEntryMap map = it->second;\n\n \/\/find entry with most depIds.\n unsigned int most_depIds = 0;\n for(BufferRepresentationEntryMap::iterator k = map.begin (); k != map.end (); ++k)\n {\n if(most_depIds <= k->second.depIds.size())\n {\n consumableEntry = k->second;\n most_depIds = k->second.depIds.size();\n }\n }\n return consumableEntry;\n}\n\ndouble MultimediaBuffer::getBufferedPercentage()\n{\n return getBufferedSeconds() \/ maxBufferedSeconds;\n}\n\ndouble MultimediaBuffer::getBufferedPercentage(std::string repId)\n{\n return getBufferedSeconds (repId) \/ maxBufferedSeconds;\n}\n\nfixed mutex usage.#include \"multimediabuffer.hpp\"\n\nusing namespace dash;\nusing namespace player;\n\nMultimediaBuffer::MultimediaBuffer(unsigned int maxBufferedSeconds)\n{\n this->maxBufferedSeconds= (double) maxBufferedSeconds;\n\n toBufferSegmentNumber = 0;\n toConsumeSegmentNumber = 0;\n}\n\nMultimediaBuffer::~MultimediaBuffer()\n{\n}\n\nbool MultimediaBuffer::addToBuffer(unsigned int segmentNumber, const dash::mpd::IRepresentation* usedRepresentation)\n{\n \/\/check if we receive a segment with a too large number\n if(toBufferSegmentNumber < segmentNumber)\n return false;\n\n \/\/fprintf(stderr, \"toBufferSegmentNumber=%d < segmentNumber=%d\\n\",toBufferSegmentNumber,segmentNumber);\n\n \/\/determine segment duration\n double duration = (double) usedRepresentation->GetSegmentList()->GetDuration();\n duration \/= (double) usedRepresentation->GetSegmentList()->GetTimescale ();\n\n \/\/ Check if segment has depIds\n mtx.lock ();\n if(usedRepresentation->GetDependencyId ().size() > 0)\n {\n \/\/ if so find the correct map\n MBuffer::iterator it = buff.find (segmentNumber);\n if(it == buff.end ())\n {\n mtx.unlock();\n return false;\n }\n\n BufferRepresentationEntryMap map = it->second;\n\n\n for(std::vector::const_iterator k = usedRepresentation->GetDependencyId ().begin ();\n k != usedRepresentation->GetDependencyId ().end (); k++)\n {\n \/\/depId not found we can not add this layer\n if(map.find ((*k)) == map.end ())\n {\n \/\/fprintf(stderr, \"Could not find '%s' in map\\n\", (*k).c_str());\n mtx.unlock ();\n return false;\n }\n }\n }\n else\n {\n \/\/check if segment with layer == 0 fits in buffer\n if(isFull(usedRepresentation->GetId (),duration))\n {\n mtx.unlock ();\n return false;\n }\n }\n\n \/\/ Add segment to buffer\n \/\/fprintf(stderr, \"Inserted something for Segment %d in Buffer\\n\", segmentNumber);\n\n MultimediaBuffer::BufferRepresentationEntry entry;\n entry.repId = usedRepresentation->GetId ();\n entry.segmentDuration = duration;\n entry.segmentNumber = segmentNumber;\n entry.depIds = usedRepresentation->GetDependencyId ();\n entry.bitrate_bit_s = usedRepresentation->GetBandwidth ();\n\n buff[segmentNumber][usedRepresentation->GetId ()] = entry;\n toBufferSegmentNumber++;\n mtx.unlock ();\n return true;\n}\n\nbool MultimediaBuffer::enoughSpaceInBuffer(unsigned int segmentNumber, const dash::mpd::IRepresentation* usedRepresentation)\n{\n \/\/determine segment duration\n double duration = (double) usedRepresentation->GetSegmentList()->GetDuration();\n duration \/= (double) usedRepresentation->GetSegmentList()->GetTimescale ();\n\n if(isFull(usedRepresentation->GetId (),duration))\n return false;\n\n return true;\n}\n\nbool MultimediaBuffer::isFull(std::string repId, double additional_seconds)\n{\n if(maxBufferedSeconds < additional_seconds+getBufferedSeconds(repId))\n return true;\n return false;\n}\n\nbool MultimediaBuffer::isEmpty()\n{\n if(getBufferedSeconds() <= 0.0)\n return true;\n return false;\n}\n\n\ndouble MultimediaBuffer::getBufferedSeconds()\n{\n double bufferSize = 0.0;\n\n for(MBuffer::iterator it = buff.begin (); it != buff.end (); ++it)\n bufferSize += it->second.begin()->second.segmentDuration;\n\n \/\/fprintf(stderr, \"BufferSize for lowestRep = %f\\n\", bufferSize);\n return bufferSize;\n}\n\ndouble MultimediaBuffer::getBufferedSeconds(std::string repId)\n{\n double bufferSize = 0.0;\n for(MBuffer::iterator it = buff.begin (); it != buff.end (); ++it)\n {\n BufferRepresentationEntryMap::iterator k = it->second.find(repId);\n if(k != it->second.end())\n {\n bufferSize += k->second.segmentDuration;\n }\n }\n \/\/fprintf(stderr, \"BufferSize for rep[%s] = %f\\n\", repId.c_str (),bufferSize);\n return bufferSize;\n}\n\nunsigned int MultimediaBuffer::getHighestBufferedSegmentNr(std::string repId)\n{\n \/\/std::map should be orderd based on operator<, so iterate from the back\n for(MBuffer::reverse_iterator it = buff.rbegin (); it != buff.rend (); ++it)\n {\n BufferRepresentationEntryMap::iterator k = it->second.find(repId);\n if(k != it->second.end())\n {\n return k->second.segmentNumber;\n }\n }\n return 0;\n}\n\n\nMultimediaBuffer::BufferRepresentationEntry MultimediaBuffer::consumeFromBuffer()\n{\n BufferRepresentationEntry entryConsumed;\n\n if(isEmpty())\n return entryConsumed;\n\n MBuffer::iterator it = buff.find (toConsumeSegmentNumber);\n if(it == buff.end ())\n {\n fprintf(stderr, \"Could not find SegmentNumber. This should never happen\\n\");\n return entryConsumed;\n }\n\n mtx.lock ();\n entryConsumed = getHighestConsumableRepresentation(toConsumeSegmentNumber);\n buff.erase (it);\n toConsumeSegmentNumber++;\n mtx.unlock ();\n return entryConsumed;\n}\n\nMultimediaBuffer::BufferRepresentationEntry MultimediaBuffer::getHighestConsumableRepresentation(int segmentNumber)\n{\n BufferRepresentationEntry consumableEntry;\n\n \/\/ find the correct entry map\n MBuffer::iterator it = buff.find (segmentNumber);\n if(it == buff.end ())\n {\n return consumableEntry;\n }\n\n BufferRepresentationEntryMap map = it->second;\n\n \/\/find entry with most depIds.\n unsigned int most_depIds = 0;\n for(BufferRepresentationEntryMap::iterator k = map.begin (); k != map.end (); ++k)\n {\n if(most_depIds <= k->second.depIds.size())\n {\n consumableEntry = k->second;\n most_depIds = k->second.depIds.size();\n }\n }\n return consumableEntry;\n}\n\ndouble MultimediaBuffer::getBufferedPercentage()\n{\n return getBufferedSeconds() \/ maxBufferedSeconds;\n}\n\ndouble MultimediaBuffer::getBufferedPercentage(std::string repId)\n{\n return getBufferedSeconds (repId) \/ maxBufferedSeconds;\n}\n\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\nusing namespace std::chrono;\ntypedef Timers::id_t id_t;\ntypedef Timers::duration_t duration_t;\ntypedef Timers::handler_t handler_t;\n\nstatic void sched_timer(duration_t when, id_t id);\n\nstruct Timer\n{\n Timer(duration_t p, handler_t cb)\n : period(p), callback(cb), deferred_destruct(false) {}\n \n bool is_alive() const noexcept {\n return deferred_destruct == false;\n }\n \n bool is_oneshot() const noexcept {\n return period.count() == 0;\n }\n \n void reset() {\n callback.reset();\n deferred_destruct = false;\n }\n \n duration_t period;\n handler_t callback;\n bool deferred_destruct = false;\n};\n\n\/**\n * 1. There are no restrictions on when timers can be started or stopped\n * 2. A period of 0 means start a one-shot timer\n * 3. Each timer is a separate object living in a \"fixed\" vector\n * 4. A dead timer is simply a timer which has its handler reset, as well as\n * having been removed from schedule\n * 5. No timer may be scheduled more than once at a time, as that will needlessly\n * inflate the schedule container, as well as complicate stopping timers\n * 6. Free timer IDs are retrieved from a stack of free timer IDs (or through \n * expanding the \"fixed\" vector)\n**\/\n\nstatic std::vector timers;\nstatic std::vector free_timers;\nstatic bool signal_ready = false;\nstatic bool is_running = false;\nstatic Timers::start_func_t arch_start_func;\nstatic Timers::stop_func_t arch_stop_func;\n\n\/\/ timers sorted by timestamp\nstatic std::multimap scheduled;\n\nvoid Timers::init(const start_func_t& start, const stop_func_t& stop)\n{\n \/\/ architecture specific start and stop functions\n arch_start_func = start;\n arch_stop_func = stop;\n}\n\nvoid Timers::ready()\n{\n signal_ready = true;\n \/\/ begin processing timers if any are queued\n if (is_running == false) {\n timers_handler();\n }\n}\n\nstatic id_t create_timer(\n duration_t when, duration_t period, const handler_t& handler)\n{\n id_t id;\n \n if (free_timers.empty()) {\n id = timers.size();\n \n \/\/ occupy new slot\n timers.emplace_back(period, handler);\n }\n else {\n \/\/ get free timer slot\n id = free_timers.back();\n free_timers.pop_back();\n \n \/\/ occupy free slot\n new (&timers[id]) Timer(period, handler);\n }\n \n \/\/ immediately schedule timer\n sched_timer(when, id);\n return id;\n}\nid_t Timers::oneshot(duration_t when, const handler_t& handler)\n{\n return create_timer(when, milliseconds(0), handler);\n}\nid_t Timers::periodic(duration_t when, duration_t period, const handler_t& handler)\n{\n return create_timer(when, period, handler);\n}\n\nvoid Timers::stop(id_t id)\n{\n \/\/ mark as dead already\n timers[id].deferred_destruct = true;\n \/\/ free resources immediately\n timers[id].callback.reset();\n}\n\nsize_t Timers::active()\n{\n return scheduled.size();\n}\n\n\/\/\/ time functions \/\/\/\n\ninline std::chrono::microseconds now() noexcept\n{\n return microseconds(OS::micros_since_boot());\n}\n\n\/\/\/ scheduling \/\/\/\n\nvoid Timers::timers_handler()\n{\n \/\/ lets assume the timer is not running anymore\n is_running = false;\n \n while (!scheduled.empty())\n {\n auto it = scheduled.begin();\n auto when = it->first;\n auto ts_now = now();\n id_t id = it->second;\n \n if (ts_now >= when) {\n \/\/ erase immediately\n scheduled.erase(it);\n \n \/\/ only process timer if still alive\n if (timers[id].is_alive()) {\n \/\/ call the users callback function\n timers[id].callback(id);\n \/\/ if the timers struct was modified in callback, eg. due to\n \/\/ creating a timer, then the timer reference below would have\n \/\/ been invalidated, hence why its BELOW, AND MUST STAY THERE\n auto& timer = timers[id];\n \n \/\/ oneshot timers are automatically freed\n if (timer.deferred_destruct || timer.is_oneshot())\n {\n timer.reset();\n free_timers.push_back(id);\n }\n else if (timer.is_oneshot() == false)\n {\n \/\/ if the timer is recurring, we will simply reschedule it\n \/\/ NOTE: we are carefully using (when + period) to avoid drift\n scheduled.emplace(std::piecewise_construct,\n std::forward_as_tuple(when + timer.period),\n std::forward_as_tuple(id));\n }\n } else {\n \/\/ timer was already dead\n timers[id].reset();\n free_timers.push_back(id);\n }\n \n } else {\n \/\/ not yet time, so schedule it for later\n is_running = true;\n arch_start_func(when - ts_now);\n \/\/ exit early, because we have nothing more to do, and there is a deferred handler\n return;\n }\n }\n \/\/arch_stop_func();\n}\nstatic void sched_timer(duration_t when, id_t id)\n{\n scheduled.emplace(std::piecewise_construct,\n std::forward_as_tuple(now() + when),\n std::forward_as_tuple(id));\n \n \/\/ dont start any hardware until after calibration\n if (!signal_ready) return;\n \n \/\/ if the hardware timer is not running, try starting it\n if (is_running == false) {\n Timers::timers_handler();\n }\n \/\/ or, if the scheduled timer is the new front, restart timer\n else if (scheduled.begin()->second == id) {\n Timers::timers_handler();\n }\n}\ntimer: Optimize branching slightly#include \n\n#include \n#include \n#include \n\nusing namespace std::chrono;\ntypedef Timers::id_t id_t;\ntypedef Timers::duration_t duration_t;\ntypedef Timers::handler_t handler_t;\n\nstatic void sched_timer(duration_t when, id_t id);\n\nstruct Timer\n{\n Timer(duration_t p, handler_t cb)\n : period(p), callback(cb), deferred_destruct(false) {}\n \n bool is_alive() const noexcept {\n return deferred_destruct == false;\n }\n \n bool is_oneshot() const noexcept {\n return period.count() == 0;\n }\n \n void reset() {\n callback.reset();\n deferred_destruct = false;\n }\n \n duration_t period;\n handler_t callback;\n bool deferred_destruct = false;\n};\n\n\/**\n * 1. There are no restrictions on when timers can be started or stopped\n * 2. A period of 0 means start a one-shot timer\n * 3. Each timer is a separate object living in a \"fixed\" vector\n * 4. A dead timer is simply a timer which has its handler reset, as well as\n * having been removed from schedule\n * 5. No timer may be scheduled more than once at a time, as that will needlessly\n * inflate the schedule container, as well as complicate stopping timers\n * 6. Free timer IDs are retrieved from a stack of free timer IDs (or through \n * expanding the \"fixed\" vector)\n**\/\n\nstatic std::vector timers;\nstatic std::vector free_timers;\nstatic bool signal_ready = false;\nstatic bool is_running = false;\nstatic Timers::start_func_t arch_start_func;\nstatic Timers::stop_func_t arch_stop_func;\n\n\/\/ timers sorted by timestamp\nstatic std::multimap scheduled;\n\nvoid Timers::init(const start_func_t& start, const stop_func_t& stop)\n{\n \/\/ architecture specific start and stop functions\n arch_start_func = start;\n arch_stop_func = stop;\n}\n\nvoid Timers::ready()\n{\n signal_ready = true;\n \/\/ begin processing timers if any are queued\n if (is_running == false) {\n timers_handler();\n }\n}\n\nstatic id_t create_timer(\n duration_t when, duration_t period, const handler_t& handler)\n{\n id_t id;\n \n if (UNLIKELY(free_timers.empty())) {\n id = timers.size();\n \n \/\/ occupy new slot\n timers.emplace_back(period, handler);\n }\n else {\n \/\/ get free timer slot\n id = free_timers.back();\n free_timers.pop_back();\n \n \/\/ occupy free slot\n new (&timers[id]) Timer(period, handler);\n }\n \n \/\/ immediately schedule timer\n sched_timer(when, id);\n return id;\n}\nid_t Timers::oneshot(duration_t when, const handler_t& handler)\n{\n return create_timer(when, milliseconds(0), handler);\n}\nid_t Timers::periodic(duration_t when, duration_t period, const handler_t& handler)\n{\n return create_timer(when, period, handler);\n}\n\nvoid Timers::stop(id_t id)\n{\n \/\/ mark as dead already\n timers[id].deferred_destruct = true;\n \/\/ free resources immediately\n timers[id].callback.reset();\n}\n\nsize_t Timers::active()\n{\n return scheduled.size();\n}\n\n\/\/\/ time functions \/\/\/\n\ninline std::chrono::microseconds now() noexcept\n{\n return microseconds(OS::micros_since_boot());\n}\n\n\/\/\/ scheduling \/\/\/\n\nvoid Timers::timers_handler()\n{\n \/\/ lets assume the timer is not running anymore\n is_running = false;\n \n while (!scheduled.empty())\n {\n auto it = scheduled.begin();\n auto when = it->first;\n auto ts_now = now();\n id_t id = it->second;\n \n if (ts_now >= when) {\n \/\/ erase immediately\n scheduled.erase(it);\n \n \/\/ only process timer if still alive\n if (timers[id].is_alive()) {\n \/\/ call the users callback function\n timers[id].callback(id);\n \/\/ if the timers struct was modified in callback, eg. due to\n \/\/ creating a timer, then the timer reference below would have\n \/\/ been invalidated, hence why its BELOW, AND MUST STAY THERE\n auto& timer = timers[id];\n \n \/\/ oneshot timers are automatically freed\n if (timer.deferred_destruct || timer.is_oneshot())\n {\n timer.reset();\n free_timers.push_back(id);\n }\n else if (timer.is_oneshot() == false)\n {\n \/\/ if the timer is recurring, we will simply reschedule it\n \/\/ NOTE: we are carefully using (when + period) to avoid drift\n scheduled.emplace(std::piecewise_construct,\n std::forward_as_tuple(when + timer.period),\n std::forward_as_tuple(id));\n }\n } else {\n \/\/ timer was already dead\n timers[id].reset();\n free_timers.push_back(id);\n }\n \n } else {\n \/\/ not yet time, so schedule it for later\n is_running = true;\n arch_start_func(when - ts_now);\n \/\/ exit early, because we have nothing more to do, and there is a deferred handler\n return;\n }\n }\n \/\/arch_stop_func();\n}\nstatic void sched_timer(duration_t when, id_t id)\n{\n scheduled.emplace(std::piecewise_construct,\n std::forward_as_tuple(now() + when),\n std::forward_as_tuple(id));\n \n \/\/ dont start any hardware until after calibration\n if (UNLIKELY(!signal_ready)) return;\n \n \/\/ if the hardware timer is not running, try starting it\n if (UNLIKELY(is_running == false)) {\n Timers::timers_handler();\n }\n \/\/ or, if the scheduled timer is the new front, restart timer\n else if (scheduled.begin()->second == id) {\n Timers::timers_handler();\n }\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2014\n Author: Jeff Weisberg \n Created: 2014-Mar-14 15:57 (EDT)\n Function: \n\n*\/\n\n#define CURRENT_SUBSYSTEM\t'k'\n\n#include \"defs.h\"\n#include \"diag.h\"\n#include \"config.h\"\n#include \"misc.h\"\n#include \"runmode.h\"\n#include \"network.h\"\n#include \"hrtime.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"std_ipport.pb.h\"\n#include \"mrmagoo.pb.h\"\n\n#include \n\n#define BOOTTIME\t60\n\n\nstatic hrtime_t starttime = 0;\nstatic char pinhost[256];\nstatic uint32_t pinip4 = 0;\n\n\nbool\nNetAddr::is_self(void){\n\n if( ipv4 == pinip4 ) return 1;\n if( ipv4 == myipv4 ) return 1;\n\n return 0;\n}\n\nvoid\nmyself_init(void){\n struct hostent *he;\n\n starttime = lr_now();\n\n \/\/ find private internal network info\n snprintf(pinhost, sizeof(pinhost), \"pin-%s\", myhostname);\n he = gethostbyname( pinhost );\n if( he && he->h_length ){\n pinip4 = ((struct in_addr *)*he->h_addr_list)->s_addr;\n }else{\n VERBOSE(\"no private network found: %s\", pinhost);\n }\n}\n\nvoid\nabout_myself(ACPMRMStatus *g){\n hrtime_t now = lr_now();\n ACPIPPort *ip;\n double load[3];\n struct statvfs vfs;\n\n getloadavg( load, 3 );\n\n g->set_hostname( myhostname );\n g->set_server_id( myserver_id.c_str() );\n g->set_datacenter( mydatacenter.c_str() );\n g->set_environment( config->environment.c_str() );\n g->set_subsystem( MYNAME );\n g->set_via( myserver_id.c_str() );\n g->set_path( \".\" );\n if( config->available && (runmode.mode() == RUN_MODE_RUN) ){\n g->set_status( (now > starttime + BOOTTIME) ? 200 : 102 );\n }else{\n g->set_status( 102 );\n }\n g->set_timestamp( now );\n g->set_lastup( now );\n g->set_boottime( starttime );\n\n g->set_sort_metric( current_load() );\n\n \/\/ determine disk space\n if( ! statvfs( config->basedir.c_str(), &vfs ) ){\n g->set_capacity_metric( vfs.f_bavail \/ 2048 );\t\/\/ MB avail\n }\n\n \/\/ ip info\n ip = g->add_ip();\n ip->set_ipv4( ntohl(myipv4) );\n ip->set_port( myport );\n\n if( pinip4 ){\n ip = g->add_ip();\n ip->set_ipv4( ntohl(pinip4) );\n ip->set_port( myport );\n ip->set_natdom( mydatacenter.c_str() );\n }\n}\n\ncleanup\/*\n Copyright (c) 2014\n Author: Jeff Weisberg \n Created: 2014-Mar-14 15:57 (EDT)\n Function: \n\n*\/\n\n#define CURRENT_SUBSYSTEM\t'k'\n\n#include \"defs.h\"\n#include \"diag.h\"\n#include \"config.h\"\n#include \"misc.h\"\n#include \"runmode.h\"\n#include \"network.h\"\n#include \"hrtime.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"std_ipport.pb.h\"\n#include \"mrmagoo.pb.h\"\n\n#include \n\n#define BOOTTIME\t60\n\n\nstatic hrtime_t starttime = 0;\nstatic char pinhost[256];\nstatic uint32_t pinip4 = 0;\n\n\nbool\nNetAddr::is_self(void){\n\n if( ipv4 == pinip4 ) return 1;\n if( ipv4 == myipv4 ) return 1;\n\n return 0;\n}\n\nvoid\nmyself_init(void){\n struct hostent *he;\n\n starttime = lr_now();\n\n \/\/ find private internal network info\n \/\/ we name the private internal address \"pin-$hostname\"\n \/\/ you may need to adjust this for your network\n\n snprintf(pinhost, sizeof(pinhost), \"pin-%s\", myhostname);\n he = gethostbyname( pinhost );\n if( he && he->h_length ){\n pinip4 = ((struct in_addr *)*he->h_addr_list)->s_addr;\n }else{\n VERBOSE(\"no private network found: %s\", pinhost);\n }\n}\n\nvoid\nabout_myself(ACPMRMStatus *g){\n hrtime_t now = lr_now();\n ACPIPPort *ip;\n struct statvfs vfs;\n\n g->set_hostname( myhostname );\n g->set_server_id( myserver_id.c_str() );\n g->set_datacenter( mydatacenter.c_str() );\n g->set_environment( config->environment.c_str() );\n g->set_subsystem( MYNAME );\n g->set_via( myserver_id.c_str() );\n g->set_path( \".\" );\n if( config->available && (runmode.mode() == RUN_MODE_RUN) ){\n g->set_status( (now > starttime + BOOTTIME) ? 200 : 102 );\n }else{\n g->set_status( 102 );\n }\n g->set_timestamp( now );\n g->set_lastup( now );\n g->set_boottime( starttime );\n\n g->set_sort_metric( current_load() );\n\n \/\/ determine disk space\n if( ! statvfs( config->basedir.c_str(), &vfs ) ){\n g->set_capacity_metric( vfs.f_bavail \/ 2048 );\t\/\/ MB avail\n }\n\n \/\/ ip info\n ip = g->add_ip();\n ip->set_ipv4( ntohl(myipv4) );\n ip->set_port( myport );\n\n if( pinip4 ){\n ip = g->add_ip();\n ip->set_ipv4( ntohl(pinip4) );\n ip->set_port( myport );\n ip->set_natdom( mydatacenter.c_str() );\n }\n}\n\n<|endoftext|>"} {"text":"Disabled Toolbar5ImporterTest.BookmarkParse due to failing valgrind\/purify tests.<|endoftext|>"} {"text":"#include \"..\/USB.h\"\n#include \"..\/configuration.h\"\n#include \"..\/deviceproxy.h\"\n#include \"..\/usb-pad\/config.h\"\n#include \"..\/usb-pad\/padproxy.h\"\n#include \"..\/usb-mic\/audiosourceproxy.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"ini.h\"\n#include \"config.h\"\n\n\/\/libjoyrumble used as an example\n\/\/Hopefully PCSX2 has inited all the GTK stuff already\nusing namespace std;\n\nstatic std::string usb_path;\nstd::string IniDir;\nstd::string LogDir;\nconst char* iniFile = \"USBqemu-wheel.ini\";\n\nvoid SysMessage(const char *fmt, ...)\n{\n\tva_list arglist;\n\n\tva_start(arglist, fmt);\n\tvfprintf(stderr, fmt, arglist);\n\tva_end(arglist);\n}\n\nvoid CALLBACK USBsetSettingsDir( const char* dir )\n{\n\tfprintf(stderr, \"USBsetSettingsDir: %s\\n\", dir);\n\tIniDir = dir;\n}\n\nvoid CALLBACK USBsetLogDir( const char* dir )\n{\n\tprintf(\"USBsetLogDir: %s\\n\", dir);\n\tLogDir = dir;\n}\n\ntemplate\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, T& value);\ntemplate\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, T& value);\n\ntemplate<>\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tchar tmp[4096] = {0};\n\tINILoadString(ini.c_str(), section.c_str(), param, tmp);\n\tvalue = tmp;\n\treturn true;\n}\n\ntemplate<>\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, int64_t& value)\n{\n\tINILoadUInt(ini.c_str(), section.c_str(), param, (unsigned int *)value);\n\treturn true;\n}\n\ntemplate<>\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tINISaveString(ini.c_str(), section.c_str(), param, value.c_str());\n\treturn true;\n}\n\ntemplate<>\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, int64_t& value)\n{\n\tINISaveUInt(ini.c_str(), section.c_str(), param, (unsigned int)value);\n\treturn true;\n}\n\nbool LoadSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu load \\\"%s\\\" from %s\\n\", var.name, key.c_str());\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.intValue);\n\t\t\/\/case CONFIG_TYPE_DOUBLE:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.doubleValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\t\/\/case CONFIG_TYPE_WCHAR:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.wstrValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\n\/**\n * \n * [devices]\n * portX = pad\n * \n * [pad X]\n * api = joydev\n * \n * [joydev X]\n * button0 = 1\n * button1 = 2\n * ...\n * \n * *\/\nbool SaveSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu save \\\"%s\\\" to %s\\n\", var.name, key.c_str());\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.intValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\nvoid SaveConfig() {\n\tfprintf(stderr, \"USB save config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/snprintf(path, sizeof(path), \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\t\/\/fprintf(stderr, \"%s\\n\", path);\n\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT0, conf.Port0.c_str());\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT1, conf.Port1.c_str());\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE0, conf.WheelType[0]);\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE1, conf.WheelType[1]);\n\n\tfor (auto& k : changedAPIs)\n\t{\n\t\tCONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tvar.strValue = k.second;\n\t\tfprintf(stderr, \"Save apis: %s %s\\n\", k.first.second.c_str(), k.second.c_str());\n\t\tSaveSetting(k.first.first, k.first.second, var);\n\t}\n}\n\nvoid LoadConfig() {\n\tchar tmp[1024] = {0};\n\tfprintf(stderr, \"USB load config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/sprintf(path, \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT0, tmp);\n\tconf.Port0 = tmp;\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT1, tmp);\n\tconf.Port1 = tmp;\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE0, (u32*)&conf.WheelType[0]);\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE1, (u32*)&conf.WheelType[1]);\n\n\t{\n\t\tauto instance = RegisterDevice::instance();\n\t\tCONFIGVARIANT tmpVar(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tLoadSetting(0, conf.Port0, tmpVar);\n\t\tstd::string api = tmpVar.strValue;\n\t\tauto dev = instance.Device(conf.Port0);\n\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(0, conf.Port0)] = api;\n\n\t\tLoadSetting(1, conf.Port1, tmpVar);\n\t\tapi = tmpVar.strValue;\n\n\t\tdev = instance.Device(conf.Port1);\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(1, conf.Port1)] = api;\n\t}\n}\nlinux\/config.cpp: print key\/port formatted as section name.#include \"..\/USB.h\"\n#include \"..\/configuration.h\"\n#include \"..\/deviceproxy.h\"\n#include \"..\/usb-pad\/config.h\"\n#include \"..\/usb-pad\/padproxy.h\"\n#include \"..\/usb-mic\/audiosourceproxy.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"ini.h\"\n#include \"config.h\"\n\n\/\/libjoyrumble used as an example\n\/\/Hopefully PCSX2 has inited all the GTK stuff already\nusing namespace std;\n\nstatic std::string usb_path;\nstd::string IniDir;\nstd::string LogDir;\nconst char* iniFile = \"USBqemu-wheel.ini\";\n\nvoid SysMessage(const char *fmt, ...)\n{\n\tva_list arglist;\n\n\tva_start(arglist, fmt);\n\tvfprintf(stderr, fmt, arglist);\n\tva_end(arglist);\n}\n\nvoid CALLBACK USBsetSettingsDir( const char* dir )\n{\n\tfprintf(stderr, \"USBsetSettingsDir: %s\\n\", dir);\n\tIniDir = dir;\n}\n\nvoid CALLBACK USBsetLogDir( const char* dir )\n{\n\tprintf(\"USBsetLogDir: %s\\n\", dir);\n\tLogDir = dir;\n}\n\ntemplate\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, T& value);\ntemplate\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, T& value);\n\ntemplate<>\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tchar tmp[4096] = {0};\n\tINILoadString(ini.c_str(), section.c_str(), param, tmp);\n\tvalue = tmp;\n\treturn true;\n}\n\ntemplate<>\nbool LoadSettingValue(const std::string& ini, const std::string& section, const char* param, int64_t& value)\n{\n\tINILoadUInt(ini.c_str(), section.c_str(), param, (unsigned int *)value);\n\treturn true;\n}\n\ntemplate<>\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, std::string& value)\n{\n\tINISaveString(ini.c_str(), section.c_str(), param, value.c_str());\n\treturn true;\n}\n\ntemplate<>\nbool SaveSettingValue(const std::string& ini, const std::string& section, const char* param, int64_t& value)\n{\n\tINISaveUInt(ini.c_str(), section.c_str(), param, (unsigned int)value);\n\treturn true;\n}\n\nbool LoadSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu load \\\"%s\\\" from [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.intValue);\n\t\t\/\/case CONFIG_TYPE_DOUBLE:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.doubleValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\t\/\/case CONFIG_TYPE_WCHAR:\n\t\t\/\/\treturn LoadSettingValue(ini, section.str(), var.name, var.wstrValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\n\/**\n * \n * [devices]\n * portX = pad\n * \n * [pad X]\n * api = joydev\n * \n * [joydev X]\n * button0 = 1\n * button1 = 2\n * ...\n * \n * *\/\nbool SaveSetting(int port, const std::string& key, CONFIGVARIANT& var)\n{\n\tfprintf(stderr, \"USBqemu save \\\"%s\\\" to [%s %d]\\n\", var.name, key.c_str(), port);\n\n\tstd::stringstream section;\n\tsection << key << \" \" << port;\n\n\tstd::string ini(IniDir);\n\tini.append(iniFile);\n\n\tswitch(var.type)\n\t{\n\t\tcase CONFIG_TYPE_INT:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.intValue);\n\t\tcase CONFIG_TYPE_TCHAR:\n\t\t\treturn LoadSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tcase CONFIG_TYPE_CHAR:\n\t\t\treturn SaveSettingValue(ini, section.str(), var.name, var.strValue);\n\t\tbreak;\n\t\tdefault:\n\t\t\tfprintf(stderr, \"Invalid config type %d for %s\\n\", var.type, var.name);\n\t\t\tbreak;\n\t};\n\treturn false;\n}\n\nvoid SaveConfig() {\n\tfprintf(stderr, \"USB save config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/snprintf(path, sizeof(path), \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\t\/\/fprintf(stderr, \"%s\\n\", path);\n\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT0, conf.Port0.c_str());\n\tINISaveString(path, N_DEVICES, N_DEVICE_PORT1, conf.Port1.c_str());\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE0, conf.WheelType[0]);\n\tINISaveUInt(path, N_DEVICES, N_WHEEL_TYPE1, conf.WheelType[1]);\n\n\tfor (auto& k : changedAPIs)\n\t{\n\t\tCONFIGVARIANT var(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tvar.strValue = k.second;\n\t\tfprintf(stderr, \"Save apis: %s %s\\n\", k.first.second.c_str(), k.second.c_str());\n\t\tSaveSetting(k.first.first, k.first.second, var);\n\t}\n}\n\nvoid LoadConfig() {\n\tchar tmp[1024] = {0};\n\tfprintf(stderr, \"USB load config\\n\");\n\t\/\/char* envptr = getenv(\"HOME\");\n\t\/\/if(envptr == NULL)\n\t\/\/\treturn;\n\t\/\/char path[1024];\n\t\/\/sprintf(path, \"%s\/.config\/PCSX2\/inis\/USBqemu-wheel.ini\", envptr);\n\tstd::string iniPath(IniDir);\n\tiniPath.append(iniFile);\n\tconst char *path = iniPath.c_str();\n\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT0, tmp);\n\tconf.Port0 = tmp;\n\tINILoadString(path, N_DEVICES, N_DEVICE_PORT1, tmp);\n\tconf.Port1 = tmp;\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE0, (u32*)&conf.WheelType[0]);\n\tINILoadUInt(path, N_DEVICES, N_WHEEL_TYPE1, (u32*)&conf.WheelType[1]);\n\n\t{\n\t\tauto instance = RegisterDevice::instance();\n\t\tCONFIGVARIANT tmpVar(N_DEVICE_API, CONFIG_TYPE_CHAR);\n\t\tLoadSetting(0, conf.Port0, tmpVar);\n\t\tstd::string api = tmpVar.strValue;\n\t\tauto dev = instance.Device(conf.Port0);\n\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(0, conf.Port0)] = api;\n\n\t\tLoadSetting(1, conf.Port1, tmpVar);\n\t\tapi = tmpVar.strValue;\n\n\t\tdev = instance.Device(conf.Port1);\n\t\tif (dev && !dev->IsValidAPI(api))\n\t\t{\n\t\t\tauto apis = dev->APIs();\n\t\t\tif (!apis.empty())\n\t\t\t\tapi = *apis.begin();\n\t\t}\n\n\t\tif(api.size())\n\t\t\tchangedAPIs[std::make_pair(1, conf.Port1)] = api;\n\t}\n}\n<|endoftext|>"} {"text":"\/***************************************************************************\n* Copyright (C) 2005 by *\n* Jason Kivlighn (jkivlighn@gmail.com) *\n* *\n* This program is free software; you can redistribute it and\/or modify *\n* it under the terms of the GNU General Public License as published by *\n* the Free Software Foundation; either version 2 of the License, or *\n* (at your option) any later version. *\n***************************************************************************\/\n\n#include \"plaintextexporter.h\"\n\n#include \n#include \n#include \n\n#include \"backends\/recipedb.h\"\n\nPlainTextExporter::PlainTextExporter( const QString& filename, const QString& format ) :\n\t\tBaseExporter( filename, format )\n{}\n\n\nPlainTextExporter::~PlainTextExporter()\n{}\n\nint PlainTextExporter::supportedItems() const\n{\n\treturn RecipeDB::All ^ RecipeDB::Photo;\n}\n\nQString PlainTextExporter::generateIngredient( const IngredientData &ing, MixedNumber::Format number_format )\n{\n\tKConfig *config = KGlobal::config();\n\n\tQString content;\n\n\tQString amount_str = MixedNumber( ing.amount ).toString( number_format );\n\n\tif ( ing.amount_offset > 0 )\n\t\tamount_str += \"-\"+MixedNumber( ing.amount + ing.amount_offset ).toString( number_format );\n\telse if ( ing.amount <= 1e-10 )\n\t\tamount_str = \"\";\n\n\tcontent += amount_str;\n\tif ( !amount_str.isEmpty() )\n\t\tcontent += \" \";\n\n\tQString unit_str = ing.units.determineName( ing.amount + ing.amount_offset, config->readBoolEntry(\"AbbreviateUnits\") );\n\n\tcontent += unit_str;\n\tif ( !unit_str.isEmpty() )\n\t\tcontent += \" \";\n\n\tcontent += ing.name;\n\n\tif ( ing.prepMethodList.count() > 0 )\n\t\tcontent += \"; \"+ing.prepMethodList.join(\", \");\n\n\treturn content;\n}\n\n\nQString PlainTextExporter::createContent( const RecipeList& recipes )\n{\n\tKConfig *config = KGlobal::config();\n\tconfig->setGroup( \"Formatting\" );\n\n\tMixedNumber::Format number_format = ( config->readBoolEntry( \"Fraction\" ) ) ? MixedNumber::MixedNumberFormat : MixedNumber::DecimalFormat;\n\n\tQString content;\n\n\tRecipeList::const_iterator recipe_it;\n\tfor ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) {\n\t\tcontent += ( *recipe_it ).title + \"\\n\\n\";\n\n\t\tif ( ( *recipe_it ).authorList.count() > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Authors\"));\n\t\t\tcontent += ( *recipe_it ).authorList.join(\", \");\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( ( *recipe_it ).categoryList.count() > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Categories\"));\n\t\t\tcontent += ( *recipe_it ).categoryList.join(\", \");\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( ( *recipe_it ).yield.amount > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Yields\"));\n\t\t\tcontent += ( *recipe_it ).yield.toString();\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( !( *recipe_it ).prepTime.isNull() ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Preparation Time\"));\n\t\t\tcontent += ( *recipe_it ).prepTime.toString( \"hh:mm\" );\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tcontent += \"\\n\";\n\n\t\tIngredientList list_copy = ( *recipe_it ).ingList;\n\t\tfor ( IngredientList group_list = list_copy.firstGroup(); group_list.count() != 0; group_list = list_copy.nextGroup() ) {\n\t\t\tQString group = group_list[ 0 ].group; \/\/just use the first's name... they're all the same\n\t\t\tif ( !group.isEmpty() )\n\t\t\t\tcontent += group + \":\\n\";\n\n\t\t\tfor ( IngredientList::const_iterator ing_it = group_list.begin(); ing_it != group_list.end(); ++ing_it ) {\n\t\t\t\tif ( !group.isEmpty() )\n\t\t\t\t\tcontent += \" \";\n\n\t\t\t\tcontent += generateIngredient(*ing_it,number_format);\n\n\t\t\t\tif ( (*ing_it).substitutes.count() > 0 )\n\t\t\t\t\tcontent += \", \"+i18n(\"or\");\n\t\t\t\t\n\t\t\t\tfor ( QValueList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) {\n\t\t\t\t\tcontent += \" \"+generateIngredient(*sub_it,number_format);\n\t\t\t\t\tsub_it++;\n\t\t\t\t\tif ( sub_it != (*ing_it).substitutes.end() )\n\t\t\t\t\t\tcontent += \", \"+i18n(\"or\");\n\t\t\t\t\tcontent += \"\\n\";\n\t\t\t\t}\n\n\t\t\t\tcontent += \"\\n\";\n\t\t\t}\n\t\t}\n\n\t\tcontent += \"\\n\";\n\n\t\t\/\/\/ @todo add ingredient properties\n\n\t\tcontent += ( *recipe_it ).instructions;\n\n\t\tcontent += \"\\n\\n\";\n\n\t\tif ( (*recipe_it).ratingList.count() > 0 )\n\t\t\tcontent += \"----------\"+i18n(\"Ratings\")+\"----------\\n\";\n\n\t\tfor ( RatingList::const_iterator rating_it = (*recipe_it).ratingList.begin(); rating_it != (*recipe_it).ratingList.end(); ++rating_it ) {\n\t\t\tif ( !( *rating_it ).rater.isEmpty() )\n\t\t\t\tcontent += \" \"+( *rating_it ).rater+\"\\n\";\n\n\t\t\tif ( (*rating_it).ratingCriteriaList.size() > 0 )\n\t\t\t\tcontent += \"\\n\";\n\n\t\t\tfor ( RatingCriteriaList::const_iterator rc_it = (*rating_it).ratingCriteriaList.begin(); rc_it != (*rating_it).ratingCriteriaList.end(); ++rc_it ) {\n\t\t\t\t\/\/FIXME: This is an ugly hack, but I don't know how else to be i18n friendly (if this is even that)\n\t\t\t\t\/\/ and still be able to display the amount as a fraction\n\t\t\t\tQString starsTrans = i18n(\"1 star\",\"%n stars\",qRound((*rc_it).stars));\n\t\t\t\tstarsTrans.replace(QString::number(qRound((*rc_it).stars)),MixedNumber((*rc_it).stars).toString());\n\n\t\t\t\tcontent += \" \"+(*rc_it).name+\": \"+starsTrans+\"\\n\";\n\t\t\t}\n\n\t\t\tif ( (*rating_it).ratingCriteriaList.size() > 0 )\n\t\t\t\tcontent += \"\\n\";\n\n\t\t\tif ( !( *rating_it ).comment.isEmpty() )\n\t\t\t\tcontent += \" \"+( *rating_it ).comment+\"\\n\";\n\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( (*recipe_it).ratingList.size() > 0 )\n\t\t\tcontent += \"\\n\";\n\n\t\tcontent += \"-----\\n\\n\"; \/\/end of recipe indicator\n\t}\n\n\treturn content;\n}\n\nSlight improvement on how to show substitutes in the text exporter\/***************************************************************************\n* Copyright (C) 2005 by *\n* Jason Kivlighn (jkivlighn@gmail.com) *\n* *\n* This program is free software; you can redistribute it and\/or modify *\n* it under the terms of the GNU General Public License as published by *\n* the Free Software Foundation; either version 2 of the License, or *\n* (at your option) any later version. *\n***************************************************************************\/\n\n#include \"plaintextexporter.h\"\n\n#include \n#include \n#include \n\n#include \"backends\/recipedb.h\"\n\nPlainTextExporter::PlainTextExporter( const QString& filename, const QString& format ) :\n\t\tBaseExporter( filename, format )\n{}\n\n\nPlainTextExporter::~PlainTextExporter()\n{}\n\nint PlainTextExporter::supportedItems() const\n{\n\treturn RecipeDB::All ^ RecipeDB::Photo;\n}\n\nQString PlainTextExporter::generateIngredient( const IngredientData &ing, MixedNumber::Format number_format )\n{\n\tKConfig *config = KGlobal::config();\n\n\tQString content;\n\n\tQString amount_str = MixedNumber( ing.amount ).toString( number_format );\n\n\tif ( ing.amount_offset > 0 )\n\t\tamount_str += \"-\"+MixedNumber( ing.amount + ing.amount_offset ).toString( number_format );\n\telse if ( ing.amount <= 1e-10 )\n\t\tamount_str = \"\";\n\n\tcontent += amount_str;\n\tif ( !amount_str.isEmpty() )\n\t\tcontent += \" \";\n\n\tQString unit_str = ing.units.determineName( ing.amount + ing.amount_offset, config->readBoolEntry(\"AbbreviateUnits\") );\n\n\tcontent += unit_str;\n\tif ( !unit_str.isEmpty() )\n\t\tcontent += \" \";\n\n\tcontent += ing.name;\n\n\tif ( ing.prepMethodList.count() > 0 )\n\t\tcontent += \"; \"+ing.prepMethodList.join(\", \");\n\n\treturn content;\n}\n\n\nQString PlainTextExporter::createContent( const RecipeList& recipes )\n{\n\tKConfig *config = KGlobal::config();\n\tconfig->setGroup( \"Formatting\" );\n\n\tMixedNumber::Format number_format = ( config->readBoolEntry( \"Fraction\" ) ) ? MixedNumber::MixedNumberFormat : MixedNumber::DecimalFormat;\n\n\tQString content;\n\n\tRecipeList::const_iterator recipe_it;\n\tfor ( recipe_it = recipes.begin(); recipe_it != recipes.end(); ++recipe_it ) {\n\t\tcontent += ( *recipe_it ).title + \"\\n\\n\";\n\n\t\tif ( ( *recipe_it ).authorList.count() > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Authors\"));\n\t\t\tcontent += ( *recipe_it ).authorList.join(\", \");\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( ( *recipe_it ).categoryList.count() > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Categories\"));\n\t\t\tcontent += ( *recipe_it ).categoryList.join(\", \");\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( ( *recipe_it ).yield.amount > 0 ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Yields\"));\n\t\t\tcontent += ( *recipe_it ).yield.toString();\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( !( *recipe_it ).prepTime.isNull() ) {\n\t\t\tcontent += QString(\"%1: \").arg(i18n(\"Preparation Time\"));\n\t\t\tcontent += ( *recipe_it ).prepTime.toString( \"hh:mm\" );\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tcontent += \"\\n\";\n\n\t\tIngredientList list_copy = ( *recipe_it ).ingList;\n\t\tfor ( IngredientList group_list = list_copy.firstGroup(); group_list.count() != 0; group_list = list_copy.nextGroup() ) {\n\t\t\tQString group = group_list[ 0 ].group; \/\/just use the first's name... they're all the same\n\t\t\tif ( !group.isEmpty() )\n\t\t\t\tcontent += group + \":\\n\";\n\n\t\t\tfor ( IngredientList::const_iterator ing_it = group_list.begin(); ing_it != group_list.end(); ++ing_it ) {\n\t\t\t\tif ( !group.isEmpty() )\n\t\t\t\t\tcontent += \" \";\n\n\t\t\t\tcontent += generateIngredient(*ing_it,number_format);\n\n\t\t\t\tif ( (*ing_it).substitutes.count() > 0 )\n\t\t\t\t\tcontent += \", \"+i18n(\"or\");\n\t\t\t\tcontent += \"\\n\";\n\t\t\t\t\n\t\t\t\tfor ( QValueList::const_iterator sub_it = (*ing_it).substitutes.begin(); sub_it != (*ing_it).substitutes.end(); ) {\n\t\t\t\t\tif ( !group.isEmpty() )\n\t\t\t\t\t\tcontent += \" \";\n\n\t\t\t\t\tcontent += generateIngredient(*sub_it,number_format);\n\t\t\t\t\tsub_it++;\n\t\t\t\t\tif ( sub_it != (*ing_it).substitutes.end() )\n\t\t\t\t\t\tcontent += \", \"+i18n(\"or\");\n\t\t\t\t\tcontent += \"\\n\";\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tcontent += \"\\n\";\n\n\t\t\/\/\/ @todo add ingredient properties\n\n\t\tcontent += ( *recipe_it ).instructions;\n\n\t\tcontent += \"\\n\\n\";\n\n\t\tif ( (*recipe_it).ratingList.count() > 0 )\n\t\t\tcontent += \"----------\"+i18n(\"Ratings\")+\"----------\\n\";\n\n\t\tfor ( RatingList::const_iterator rating_it = (*recipe_it).ratingList.begin(); rating_it != (*recipe_it).ratingList.end(); ++rating_it ) {\n\t\t\tif ( !( *rating_it ).rater.isEmpty() )\n\t\t\t\tcontent += \" \"+( *rating_it ).rater+\"\\n\";\n\n\t\t\tif ( (*rating_it).ratingCriteriaList.size() > 0 )\n\t\t\t\tcontent += \"\\n\";\n\n\t\t\tfor ( RatingCriteriaList::const_iterator rc_it = (*rating_it).ratingCriteriaList.begin(); rc_it != (*rating_it).ratingCriteriaList.end(); ++rc_it ) {\n\t\t\t\t\/\/FIXME: This is an ugly hack, but I don't know how else to be i18n friendly (if this is even that)\n\t\t\t\t\/\/ and still be able to display the amount as a fraction\n\t\t\t\tQString starsTrans = i18n(\"1 star\",\"%n stars\",qRound((*rc_it).stars));\n\t\t\t\tstarsTrans.replace(QString::number(qRound((*rc_it).stars)),MixedNumber((*rc_it).stars).toString());\n\n\t\t\t\tcontent += \" \"+(*rc_it).name+\": \"+starsTrans+\"\\n\";\n\t\t\t}\n\n\t\t\tif ( (*rating_it).ratingCriteriaList.size() > 0 )\n\t\t\t\tcontent += \"\\n\";\n\n\t\t\tif ( !( *rating_it ).comment.isEmpty() )\n\t\t\t\tcontent += \" \"+( *rating_it ).comment+\"\\n\";\n\n\t\t\tcontent += \"\\n\";\n\t\t}\n\n\t\tif ( (*recipe_it).ratingList.size() > 0 )\n\t\t\tcontent += \"\\n\";\n\n\t\tcontent += \"-----\\n\\n\"; \/\/end of recipe indicator\n\t}\n\n\treturn content;\n}\n\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2017, Loic Blot \n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"l_string.h\"\n#include \n#include \n#include \n#include \n#include \n\nint LuaString::l_base64_decode(lua_State *L)\n{\n\tstd::string to_decode = read(L, 1);\n\twrite(L, base64_decode(to_decode));\n\treturn 1;\n}\n\nint LuaString::l_base64_encode(lua_State *L)\n{\n\tstd::string to_encode = read(L, 1);\n\twrite(L, base64_encode(to_encode));\n\treturn 1;\n}\n\nint LuaString::l_hmac_sha1(lua_State *L)\n{\n\tstd::string key = read(L, 1);\n\tstd::string to_hash = read(L, 2);\n\twrite(L, hmac_sha1(key, to_hash));\n}\n\nint LuaString::l_read_json(lua_State *L)\n{\n\tconst char *jsonstr = luaL_checkstring(L, 1);\n\n\t\/\/ Use passed nullvalue or default to nil\n\tint nullindex = 2;\n\tif (lua_isnone(L, nullindex)) {\n\t\tlua_pushnil(L);\n\t\t\/\/ nullindex = lua_gettop(L);\n\t}\n\n\tJson::Value root;\n\tJson::Reader reader;\n\tstd::istringstream stream(jsonstr);\n\n\tif (!reader.parse(stream, root)) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\n\tif (!write(L, root)) {\n\t\tlua_pushnil(L);\n\t}\n\treturn 1;\n\n}\n\nint LuaString::l_write_json(lua_State *L)\n{\n\tbool styled = false;\n\tif (!lua_isnone(L, 2)) {\n\t\tstyled = read(L, 2);\n\t\tlua_pop(L, 1);\n\t}\n\n\tJson::Value root;\n\tif (!read(L, 1, root)) {\n\t\tlua_pushnil(L);\n\t\tlua_pushstring(L, \"failed to parse json\");\n\t\treturn 2;\n\t}\n\n\tstd::string out;\n\tif (styled) {\n\t\tJson::StyledWriter writer;\n\t\tout = writer.write(root);\n\t} else {\n\t\tJson::FastWriter writer;\n\t\tout = writer.write(root);\n\t}\n\twrite(L, out);\n\treturn 1;\n\n}\n\nvoid LuaString::register_functions(LuaEngine *engine, int top)\n{\n\tengine->REGISTER_LUA_FCT(base64_encode);\n\tengine->REGISTER_LUA_FCT(base64_decode);\n\tengine->REGISTER_LUA_FCT(hmac_sha1);\n\tengine->REGISTER_LUA_FCT(read_json);\n\tengine->REGISTER_LUA_FCT(write_json);\n}\nAdd missing return on hmac_sha1 function\/**\n * Copyright (c) 2017, Loic Blot \n * All rights reserved.\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"l_string.h\"\n#include \n#include \n#include \n#include \n#include \n\nint LuaString::l_base64_decode(lua_State *L)\n{\n\tstd::string to_decode = read(L, 1);\n\twrite(L, base64_decode(to_decode));\n\treturn 1;\n}\n\nint LuaString::l_base64_encode(lua_State *L)\n{\n\tstd::string to_encode = read(L, 1);\n\twrite(L, base64_encode(to_encode));\n\treturn 1;\n}\n\nint LuaString::l_hmac_sha1(lua_State *L)\n{\n\tstd::string key = read(L, 1);\n\tstd::string to_hash = read(L, 2);\n\twrite(L, hmac_sha1(key, to_hash));\n\treturn 1;\n}\n\nint LuaString::l_read_json(lua_State *L)\n{\n\tconst char *jsonstr = luaL_checkstring(L, 1);\n\n\t\/\/ Use passed nullvalue or default to nil\n\tint nullindex = 2;\n\tif (lua_isnone(L, nullindex)) {\n\t\tlua_pushnil(L);\n\t\t\/\/ nullindex = lua_gettop(L);\n\t}\n\n\tJson::Value root;\n\tJson::Reader reader;\n\tstd::istringstream stream(jsonstr);\n\n\tif (!reader.parse(stream, root)) {\n\t\tlua_pushnil(L);\n\t\treturn 1;\n\t}\n\n\tif (!write(L, root)) {\n\t\tlua_pushnil(L);\n\t}\n\treturn 1;\n\n}\n\nint LuaString::l_write_json(lua_State *L)\n{\n\tbool styled = false;\n\tif (!lua_isnone(L, 2)) {\n\t\tstyled = read(L, 2);\n\t\tlua_pop(L, 1);\n\t}\n\n\tJson::Value root;\n\tif (!read(L, 1, root)) {\n\t\tlua_pushnil(L);\n\t\tlua_pushstring(L, \"failed to parse json\");\n\t\treturn 2;\n\t}\n\n\tstd::string out;\n\tif (styled) {\n\t\tJson::StyledWriter writer;\n\t\tout = writer.write(root);\n\t} else {\n\t\tJson::FastWriter writer;\n\t\tout = writer.write(root);\n\t}\n\twrite(L, out);\n\treturn 1;\n\n}\n\nvoid LuaString::register_functions(LuaEngine *engine, int top)\n{\n\tengine->REGISTER_LUA_FCT(base64_encode);\n\tengine->REGISTER_LUA_FCT(base64_decode);\n\tengine->REGISTER_LUA_FCT(hmac_sha1);\n\tengine->REGISTER_LUA_FCT(read_json);\n\tengine->REGISTER_LUA_FCT(write_json);\n}\n<|endoftext|>"} {"text":"#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n\n\nnamespace iter {\n\n template \n void absorb(Ts&&...) { }\n\n template \n class Zipped;\n\n template \n Zipped zip(Containers&&...);\n\n \/\/ specialization for at least 1 template argument\n template \n class Zipped {\n private:\n std::tuple containers;\n std::make_index_sequence indices;\n \n public:\n Zipped(Containers... in_containers)\n : containers{std::forward(in_containers)...}\n { }\n\n class Iterator {\n private:\n std::tuple...> iters;\n std::make_index_sequence indices;\n\n bool not_equal(\n const Iterator&, std::index_sequence<>) const {\n return false;\n }\n\n template \n bool not_equal(const Iterator& other,\n std::index_sequence) const {\n bool results[] = { true,\n (std::get(this->iters) !=\n std::get(other.iters))...\n };\n return std::all_of(\n std::begin(results), std::end(results),\n [](bool b){ return b; } );\n }\n\n template \n void increment(std::index_sequence) {\n absorb(++std::get(this->iters)...);\n }\n\n template \n auto deref(std::index_sequence) {\n return std::tuple...>{\n (*std::get(this->iters))...};\n }\n\n public:\n Iterator(iterator_type... its)\n : iters{its...}\n { }\n\n Iterator& operator++() {\n this->increment(this->indices);\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->not_equal(other, this->indices);\n }\n\n auto operator*() {\n return this->deref(this->indices);\n }\n };\n private:\n template \n Iterator make_begin(std::index_sequence) {\n return {std::begin(std::get(this->containers))...};\n }\n\n template \n Iterator make_end(std::index_sequence) {\n return {std::end(std::get(this->containers))...};\n }\n\n public:\n\n Iterator begin() {\n return this->make_begin(this->indices);\n }\n\n Iterator end() {\n return this->make_end(this->indices);\n }\n };\n\n template \n Zipped zip(Containers&&... containers) {\n return {std::forward(containers)...};\n }\n}\n\n#endif \/\/ #ifndef ITER_ZIP_HPP_\nSimplifies by templating on tuple and Is#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n#include \n\nnamespace iter {\n\n template \n void absorb(Ts&&...) { }\n\n#if 0\n template \n class Zipped;\n\n template \n Zipped zip(Containers&&...);\n#endif\n\n \/\/ specialization for at least 1 template argument\n template \n class Zipped {\n private:\n TupType containers;\n using iters_tuple =\n std::tuple(std::declval()))>...>;\n public:\n Zipped(TupType&& in_containers)\n : containers(std::move(in_containers))\n { }\n\n class Iterator {\n private:\n using iters_tuple =\n std::tuple(std::declval()))>...>;\n using iters_deref_tuple =\n std::tuple(std::declval()))>...>;\n\n iters_tuple iters;\n\n public:\n Iterator(iters_tuple&& its)\n : iters(std::move(its))\n { }\n\n Iterator& operator++() {\n absorb(++std::get(this->iters)...);\n return *this;\n }\n\n bool operator!=(const Iterator& other) const {\n if (sizeof...(Is) == 0) return false;\n\n bool results[] = { true,\n (std::get(this->iters) !=\n std::get(other.iters))...\n };\n return std::all_of(\n std::begin(results), std::end(results),\n [](bool b){ return b; } );\n }\n\n auto operator*() {\n return iters_deref_tuple{\n (*std::get(this->iters))...};\n }\n };\n\n Iterator begin() {\n return iters_tuple{\n std::begin(std::get(this->containers))...};\n }\n\n Iterator end() {\n return iters_tuple{\n std::end(std::get(this->containers))...};\n }\n };\n\n template \n Zipped zip_impl(\n TupType&& in_containers, std::index_sequence) {\n return {std::move(in_containers)};\n }\n\n template \n auto zip(Containers&&... containers) {\n return zip_impl(std::tuple{\n std::forward(containers)...},\n std::index_sequence_for{});\n }\n}\n\n#endif \/\/ #ifndef ITER_ZIP_HPP_\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2002-2012, California Institute of Technology.\n* All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and\/or NAS7-03001.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n* this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* 3. Neither the name of the California Institute of Technology (Caltech), its operating division the Jet Propulsion Laboratory (JPL),\n* the National Aeronautics and Space Administration (NASA), nor the names of its contributors may be used to\n* endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n* IN NO EVENT SHALL THE CALIFORNIA INSTITUTE OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n* Copyright 2014-2015 Esri\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n\n\n\/*\n * $Id$\n * PNG band\n * PNG page compression and decompression functions\n * These functions are not methods, they reside in the global space\n *\n *\/\n\n#include \"marfa.h\"\n#include \n\nCPL_C_START\n#include \"..\/png\/libpng\/png.h\"\nCPL_C_END\n\nNAMESPACE_MRF_START\n\n\/\/Lucian recommended to change the following three lines to above as\n\/\/ it is causing trouble compiling for AMNH folks.\n\/\/CPL_C_START\n\/\/#include \n\/\/CPL_C_END\n\n\/\/ Do Nothing\nstatic void flush_png(png_structp) {}\n\n\/\/ Warning Emit\nstatic void pngWH(png_struct * \/*png*\/, png_const_charp message)\n{\n CPLError(CE_Warning, CPLE_AppDefined, \"MRF: PNG warning %s\", message);\n}\n\n\/\/ Fatal Warning\nstatic void pngEH(png_struct *png, png_const_charp message)\n{\n CPLError(CE_Failure, CPLE_AppDefined, \"MRF: PNG Failure %s\", message);\n longjmp(png->jmpbuf, 1);\n}\n\n\/\/ Read memory handlers for PNG\n\/\/ No check for attempting to read past the end of the buffer\n\nstatic void read_png(png_structp pngp, png_bytep data, png_size_t length)\n{\n buf_mgr *pmgr = (buf_mgr *)png_get_io_ptr(pngp);\n memcpy(data, pmgr->buffer, length);\n pmgr->buffer += length;\n pmgr->size -= length;\n}\n\nstatic void write_png(png_structp pngp, png_bytep data, png_size_t length) {\n buf_mgr *mgr = (buf_mgr *)png_get_io_ptr(pngp);\n \/\/ Buffer could be too small, trigger an error on debug mode\n assert(length <= mgr->size);\n memcpy(mgr->buffer, data, length);\n mgr->buffer += length;\n mgr->size -= length;\n}\n\n\/**\n *\\brief In memory decompression of PNG file\n *\/\n\nCPLErr PNG_Band::DecompressPNG(buf_mgr &dst, buf_mgr &src)\n{\n png_bytep *png_rowp;\n\n \/\/ pngp=png_create_read_struct(PNG_LIBPNG_VER_STRING,0,pngEH,pngWH);\n png_structp pngp = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (0 == pngp) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating PNG decompress\");\n\treturn CE_Failure;\n }\n\n png_infop infop = png_create_info_struct(pngp);\n if (0 == infop) {\n\tif (pngp) png_destroy_read_struct(&pngp, &infop, 0);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating PNG info\");\n\treturn CE_Failure;\n }\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error starting PNG decompress\");\n\treturn CE_Failure;\n }\n\n \/\/ The mgr data ptr is already set up\n png_set_read_fn(pngp, &src, read_png);\n \/\/ Ready to read\n png_read_info(pngp, infop);\n GInt32 height = static_cast(png_get_image_height(pngp, infop));\n GInt32 byte_count = png_get_bit_depth(pngp, infop) \/ 8;\n \/\/ Check the size\n if (dst.size < (png_get_rowbytes(pngp, infop)*height)) {\n\tCPLError(CE_Failure, CPLE_AppDefined,\n\t \"MRF: PNG Page data bigger than the buffer provided\");\n\tpng_destroy_read_struct(&pngp, &infop, 0);\n\treturn CE_Failure;\n }\n\n png_rowp = (png_bytep *)CPLMalloc(sizeof(png_bytep)*height);\n\n int rowbytes = static_cast(png_get_rowbytes(pngp, infop));\n for (int i = 0; i < height; i++)\n\tpng_rowp[i] = (png_bytep)dst.buffer + i*rowbytes;\n\n \/\/ Finally, the read\n \/\/ This is the lower level, the png_read_end allows some transforms\n \/\/ Like pallete to RGBA\n png_read_image(pngp, png_rowp);\n\n if (byte_count != 1) { \/\/ Swap from net order if data is short\n\tfor (int i = 0; i < height; i++) {\n\t unsigned short int*p = (unsigned short int *)png_rowp[i];\n\t for (int j = 0; j < rowbytes \/ 2; j++, p++)\n\t\t*p = net16(*p);\n\t}\n }\n\n \/\/ ppmWrite(\"Test.ppm\",(char *)data,ILSize(512,512,1,4,0));\n \/\/ Required\n png_read_end(pngp, infop);\n\n \/\/ png_set_rows(pngp,infop,png_rowp);\n \/\/ png_read_png(pngp,infop,PNG_TRANSFORM_IDENTITY,0);\n\n CPLFree(png_rowp);\n png_destroy_read_struct(&pngp, &infop, 0);\n return CE_None;\n}\n\n\/**\n *\\Brief Compres a page in PNG format\n * Returns the compressed size in dst.size\n *\n *\/\n\nCPLErr PNG_Band::CompressPNG(buf_mgr &dst, buf_mgr &src)\n\n{\n png_structp pngp;\n png_infop infop;\n buf_mgr mgr = dst;\n\n pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, pngEH, pngWH);\n if (!pngp) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating png structure\");\n\treturn CE_Failure;\n }\n infop = png_create_info_struct(pngp);\n if (!infop) {\n\tpng_destroy_write_struct(&pngp, NULL);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating png info structure\");\n\treturn CE_Failure;\n }\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tpng_destroy_write_struct(&pngp, &infop);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error during png init\");\n\treturn CE_Failure;\n }\n\n png_set_write_fn(pngp, &mgr, write_png, flush_png);\n\n int png_ctype;\n\n switch (img.pagesize.c) {\n case 1: if (PNGColors != NULL) png_ctype = PNG_COLOR_TYPE_PALETTE;\n\t else png_ctype = PNG_COLOR_TYPE_GRAY;\n\t break;\n case 2: png_ctype = PNG_COLOR_TYPE_GRAY_ALPHA; break;\n case 3: png_ctype = PNG_COLOR_TYPE_RGB; break;\n case 4: png_ctype = PNG_COLOR_TYPE_RGB_ALPHA; break;\n default: { \/\/ This never happens if we check at the open\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF:PNG Write with %d colors called\",\n\t img.pagesize.c);\n\treturn CE_Failure;\n }\n }\n\n png_set_IHDR(pngp, infop, img.pagesize.x, img.pagesize.y,\n\tGDALGetDataTypeSize(img.dt), png_ctype,\n\tPNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n\n \/\/ Optional, force certain filters only. Makes it somewhat faster but worse compression\n \/\/ png_set_filter(pngp, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);\n\n#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER > 10200)\n png_uint_32 mask, flags;\n\n flags = png_get_asm_flags(pngp);\n mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);\n png_set_asm_flags(pngp, flags | mask); \/\/ use flags &~mask to disable all\n\n \/\/ Test that the MMX is compiled into PNG\n \/\/\tfprintf(stderr,\"MMX support is %d\\n\", png_mmx_support());\n\n#endif\n\n \/\/ Let the quality control the compression level\n \/\/ Supposedly low numbers work well too while being fast\n png_set_compression_level(pngp, img.quality \/ 10);\n\n \/\/ Custom strategy for zlib, set using the band option Z_STRATEGY\n if (deflate_flags & ZFLAG_SMASK)\n\tpng_set_compression_strategy(pngp, (deflate_flags & ZFLAG_SMASK) >> 6);\n\n \/\/ Write the palete and the transparencies if they exist\n if (PNGColors != NULL)\n {\n\tpng_set_PLTE(pngp, infop, (png_colorp)PNGColors, PalSize);\n\tif (TransSize != 0)\n\t png_set_tRNS(pngp, infop, (unsigned char*)PNGAlpha, TransSize, NULL);\n }\n\n png_write_info(pngp, infop);\n\n png_bytep *png_rowp = (png_bytep *)CPLMalloc(sizeof(png_bytep)*img.pagesize.y);\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tCPLFree(png_rowp);\n\tpng_destroy_write_struct(&pngp, &infop);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error during png compression\");\n\treturn CE_Failure;\n }\n\n int rowbytes = static_cast(png_get_rowbytes(pngp, infop));\n for (int i = 0; i < img.pagesize.y; i++) {\n\tpng_rowp[i] = (png_bytep)(src.buffer + i*rowbytes);\n\tif (img.dt != GDT_Byte) { \/\/ Swap to net order if data is short\n\t unsigned short int*p = (unsigned short int *)png_rowp[i];\n\t for (int j = 0; j < rowbytes \/ 2; j++, p++) *p = net16(*p);\n\t}\n }\n\n png_write_image(pngp, png_rowp);\n png_write_end(pngp, infop);\n\n \/\/ Done\n CPLFree(png_rowp);\n png_destroy_write_struct(&pngp, &infop);\n\n \/\/ Done\n \/\/ mgr.size holds the available bytes, so the size of the compressed png\n \/\/ is the original destination size minus the still available bytes\n dst.size -= mgr.size;\n\n return CE_None;\n}\n\nCPLErr PNG_Band::Decompress(buf_mgr &dst, buf_mgr &src)\n{\n return DecompressPNG(dst, src);\n}\n\n\/\/ The PNG internal palette is set on first band write\nCPLErr PNG_Band::Compress(buf_mgr &dst, buf_mgr &src)\n{ \/\/ Late set palette\n if (img.comp == IL_PPNG && !PNGColors && ResetPalette() != CE_None)\n\treturn CE_Failure;\n return CompressPNG(dst, src);\n}\n\n\nCPLErr PNG_Band::ResetPalette()\n{ \/\/ Convert the GDAL LUT to PNG style\n GDALColorTable *poCT = GetColorTable();\n\n if (!poCT) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"MRF PPNG needs a color table\");\n\treturn CE_Failure;\n }\n\n TransSize = PalSize = poCT->GetColorEntryCount();\n\n png_color *pasPNGColors = (png_color *)CPLMalloc(sizeof(png_color) * PalSize);\n unsigned char *pabyAlpha = (unsigned char *)CPLMalloc(TransSize);\n PNGColors = (void *)pasPNGColors;\n PNGAlpha = (void *)pabyAlpha;\n bool NoTranspYet = true;\n\n \/\/ Set the palette from the end to reduce the size of the opacity mask\n for (int iColor = PalSize - 1; iColor >= 0; iColor--)\n {\n\tGDALColorEntry sEntry;\n\tpoCT->GetColorEntryAsRGB(iColor, &sEntry);\n\n\tpasPNGColors[iColor].red = (png_byte)sEntry.c1;\n\tpasPNGColors[iColor].green = (png_byte)sEntry.c2;\n\tpasPNGColors[iColor].blue = (png_byte)sEntry.c3;\n\tif (NoTranspYet && sEntry.c4 == 255)\n\t TransSize--;\n\telse {\n\t NoTranspYet = false;\n\t pabyAlpha[iColor] = (unsigned char)sEntry.c4;\n\t}\n }\n\n return CE_None;\n}\n\n\/**\n * \\Brief For PPNG, builds the data structures needed to write the palette\n * The presence of the PNGColors and PNGAlpha is used as a flag for PPNG only\n *\/\n\nPNG_Band::PNG_Band(GDALMRFDataset *pDS, const ILImage &image, int b, int level) :\nGDALMRFRasterBand(pDS, image, b, level), PNGColors(NULL), PNGAlpha(NULL)\n\n{ \/\/ Check error conditions\n if (image.dt != GDT_Byte && image.dt != GDT_Int16 && image.dt != GDT_UInt16) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"Data type not supported by MRF PNG\");\n\treturn;\n }\n if (image.pagesize.c > 4) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"MRF PNG can only handle up to 4 bands per page\");\n\treturn;\n }\n}\n\nPNG_Band::~PNG_Band() {\n CPLFree(PNGColors);\n CPLFree(PNGAlpha);\n}\n\nNAMESPACE_MRF_END\nGDAL integration #32\/*\n* Copyright (c) 2002-2012, California Institute of Technology.\n* All rights reserved. Based on Government Sponsored Research under contracts NAS7-1407 and\/or NAS7-03001.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n* 2. Redistributions in binary form must reproduce the above copyright notice,\n* this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* 3. Neither the name of the California Institute of Technology (Caltech), its operating division the Jet Propulsion Laboratory (JPL),\n* the National Aeronautics and Space Administration (NASA), nor the names of its contributors may be used to\n* endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n* IN NO EVENT SHALL THE CALIFORNIA INSTITUTE OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,\n* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\n* Copyright 2014-2015 Esri\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n\n\n\/*\n * $Id$\n * PNG band\n * PNG page compression and decompression functions\n * These functions are not methods, they reside in the global space\n *\n *\/\n\n#include \"marfa.h\"\n#include \n\nCPL_C_START\n#include \"..\/png\/libpng\/png.h\"\nCPL_C_END\n\nNAMESPACE_MRF_START\n\n\/\/Lucian recommended to change the following three lines to above as\n\/\/ it is causing trouble compiling for AMNH folks.\n\/\/CPL_C_START\n\/\/#include \n\/\/CPL_C_END\n\n\/\/ Do Nothing\nstatic void flush_png(png_structp) {}\n\n\/\/ Warning Emit\nstatic void pngWH(png_struct * \/*png*\/, png_const_charp message)\n{\n CPLError(CE_Warning, CPLE_AppDefined, \"MRF: PNG warning %s\", message);\n}\n\n\/\/ Fatal Warning\nstatic void pngEH(png_struct *png, png_const_charp message)\n{\n CPLError(CE_Failure, CPLE_AppDefined, \"MRF: PNG Failure %s\", message);\n longjmp(png->jmpbuf, 1);\n}\n\n\/\/ Read memory handlers for PNG\n\/\/ No check for attempting to read past the end of the buffer\n\nstatic void read_png(png_structp pngp, png_bytep data, png_size_t length)\n{\n buf_mgr *pmgr = (buf_mgr *)png_get_io_ptr(pngp);\n memcpy(data, pmgr->buffer, length);\n pmgr->buffer += length;\n pmgr->size -= length;\n}\n\nstatic void write_png(png_structp pngp, png_bytep data, png_size_t length) {\n buf_mgr *mgr = (buf_mgr *)png_get_io_ptr(pngp);\n \/\/ Buffer could be too small, trigger an error on debug mode\n assert(length <= mgr->size);\n memcpy(mgr->buffer, data, length);\n mgr->buffer += length;\n mgr->size -= length;\n}\n\n\/**\n *\\brief In memory decompression of PNG file\n *\/\n\nCPLErr PNG_Band::DecompressPNG(buf_mgr &dst, buf_mgr &src)\n{\n png_bytep *png_rowp;\n\n \/\/ pngp=png_create_read_struct(PNG_LIBPNG_VER_STRING,0,pngEH,pngWH);\n png_structp pngp = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);\n if (0 == pngp) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating PNG decompress\");\n\treturn CE_Failure;\n }\n\n png_infop infop = png_create_info_struct(pngp);\n if (0 == infop) {\n\tif (pngp) png_destroy_read_struct(&pngp, &infop, 0);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating PNG info\");\n\treturn CE_Failure;\n }\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error starting PNG decompress\");\n\treturn CE_Failure;\n }\n\n \/\/ The mgr data ptr is already set up\n png_set_read_fn(pngp, &src, read_png);\n \/\/ Ready to read\n png_read_info(pngp, infop);\n GInt32 height = static_cast(png_get_image_height(pngp, infop));\n GInt32 byte_count = png_get_bit_depth(pngp, infop) \/ 8;\n \/\/ Check the size\n if (dst.size < (png_get_rowbytes(pngp, infop)*height)) {\n\tCPLError(CE_Failure, CPLE_AppDefined,\n\t \"MRF: PNG Page data bigger than the buffer provided\");\n\tpng_destroy_read_struct(&pngp, &infop, 0);\n\treturn CE_Failure;\n }\n\n png_rowp = (png_bytep *)CPLMalloc(sizeof(png_bytep)*height);\n\n int rowbytes = static_cast(png_get_rowbytes(pngp, infop));\n for (int i = 0; i < height; i++)\n\tpng_rowp[i] = (png_bytep)dst.buffer + i*rowbytes;\n\n \/\/ Finally, the read\n \/\/ This is the lower level, the png_read_end allows some transforms\n \/\/ Like pallete to RGBA\n png_read_image(pngp, png_rowp);\n\n if (byte_count != 1) { \/\/ Swap from net order if data is short\n\tfor (int i = 0; i < height; i++) {\n\t unsigned short int*p = (unsigned short int *)png_rowp[i];\n\t for (int j = 0; j < rowbytes \/ 2; j++, p++)\n\t\t*p = net16(*p);\n\t}\n }\n\n \/\/ ppmWrite(\"Test.ppm\",(char *)data,ILSize(512,512,1,4,0));\n \/\/ Required\n png_read_end(pngp, infop);\n\n \/\/ png_set_rows(pngp,infop,png_rowp);\n \/\/ png_read_png(pngp,infop,PNG_TRANSFORM_IDENTITY,0);\n\n CPLFree(png_rowp);\n png_destroy_read_struct(&pngp, &infop, 0);\n return CE_None;\n}\n\n\/**\n *\\Brief Compres a page in PNG format\n * Returns the compressed size in dst.size\n *\n *\/\n\nCPLErr PNG_Band::CompressPNG(buf_mgr &dst, buf_mgr &src)\n\n{\n png_structp pngp;\n png_infop infop;\n buf_mgr mgr = dst;\n\n pngp = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, pngEH, pngWH);\n if (!pngp) {\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating png structure\");\n\treturn CE_Failure;\n }\n infop = png_create_info_struct(pngp);\n if (!infop) {\n\tpng_destroy_write_struct(&pngp, NULL);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error creating png info structure\");\n\treturn CE_Failure;\n }\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tpng_destroy_write_struct(&pngp, &infop);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error during png init\");\n\treturn CE_Failure;\n }\n\n png_set_write_fn(pngp, &mgr, write_png, flush_png);\n\n int png_ctype;\n\n switch (img.pagesize.c) {\n case 1: if (PNGColors != NULL) png_ctype = PNG_COLOR_TYPE_PALETTE;\n\t else png_ctype = PNG_COLOR_TYPE_GRAY;\n\t break;\n case 2: png_ctype = PNG_COLOR_TYPE_GRAY_ALPHA; break;\n case 3: png_ctype = PNG_COLOR_TYPE_RGB; break;\n case 4: png_ctype = PNG_COLOR_TYPE_RGB_ALPHA; break;\n default: { \/\/ This never happens if we check at the open\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF:PNG Write with %d colors called\",\n\t img.pagesize.c);\n\treturn CE_Failure;\n }\n }\n\n png_set_IHDR(pngp, infop, img.pagesize.x, img.pagesize.y,\n\tGDALGetDataTypeSize(img.dt), png_ctype,\n\tPNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);\n\n \/\/ Optional, force certain filters only. Makes it somewhat faster but worse compression\n \/\/ png_set_filter(pngp, PNG_FILTER_TYPE_BASE, PNG_FILTER_SUB);\n\n#if defined(PNG_LIBPNG_VER) && (PNG_LIBPNG_VER > 10200) && defined(PNG_SELECT_READ)\n png_uint_32 mask, flags;\n\n flags = png_get_asm_flags(pngp);\n mask = png_get_asm_flagmask(PNG_SELECT_READ | PNG_SELECT_WRITE);\n png_set_asm_flags(pngp, flags | mask); \/\/ use flags &~mask to disable all\n\n \/\/ Test that the MMX is compiled into PNG\n \/\/\tfprintf(stderr,\"MMX support is %d\\n\", png_mmx_support());\n\n#endif\n\n \/\/ Let the quality control the compression level\n \/\/ Supposedly low numbers work well too while being fast\n png_set_compression_level(pngp, img.quality \/ 10);\n\n \/\/ Custom strategy for zlib, set using the band option Z_STRATEGY\n if (deflate_flags & ZFLAG_SMASK)\n\tpng_set_compression_strategy(pngp, (deflate_flags & ZFLAG_SMASK) >> 6);\n\n \/\/ Write the palete and the transparencies if they exist\n if (PNGColors != NULL)\n {\n\tpng_set_PLTE(pngp, infop, (png_colorp)PNGColors, PalSize);\n\tif (TransSize != 0)\n\t png_set_tRNS(pngp, infop, (unsigned char*)PNGAlpha, TransSize, NULL);\n }\n\n png_write_info(pngp, infop);\n\n png_bytep *png_rowp = (png_bytep *)CPLMalloc(sizeof(png_bytep)*img.pagesize.y);\n\n if (setjmp(png_jmpbuf(pngp))) {\n\tCPLFree(png_rowp);\n\tpng_destroy_write_struct(&pngp, &infop);\n\tCPLError(CE_Failure, CPLE_AppDefined, \"MRF: Error during png compression\");\n\treturn CE_Failure;\n }\n\n int rowbytes = static_cast(png_get_rowbytes(pngp, infop));\n for (int i = 0; i < img.pagesize.y; i++) {\n\tpng_rowp[i] = (png_bytep)(src.buffer + i*rowbytes);\n\tif (img.dt != GDT_Byte) { \/\/ Swap to net order if data is short\n\t unsigned short int*p = (unsigned short int *)png_rowp[i];\n\t for (int j = 0; j < rowbytes \/ 2; j++, p++) *p = net16(*p);\n\t}\n }\n\n png_write_image(pngp, png_rowp);\n png_write_end(pngp, infop);\n\n \/\/ Done\n CPLFree(png_rowp);\n png_destroy_write_struct(&pngp, &infop);\n\n \/\/ Done\n \/\/ mgr.size holds the available bytes, so the size of the compressed png\n \/\/ is the original destination size minus the still available bytes\n dst.size -= mgr.size;\n\n return CE_None;\n}\n\nCPLErr PNG_Band::Decompress(buf_mgr &dst, buf_mgr &src)\n{\n return DecompressPNG(dst, src);\n}\n\n\/\/ The PNG internal palette is set on first band write\nCPLErr PNG_Band::Compress(buf_mgr &dst, buf_mgr &src)\n{ \/\/ Late set palette\n if (img.comp == IL_PPNG && !PNGColors && ResetPalette() != CE_None)\n\treturn CE_Failure;\n return CompressPNG(dst, src);\n}\n\n\nCPLErr PNG_Band::ResetPalette()\n{ \/\/ Convert the GDAL LUT to PNG style\n GDALColorTable *poCT = GetColorTable();\n\n if (!poCT) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"MRF PPNG needs a color table\");\n\treturn CE_Failure;\n }\n\n TransSize = PalSize = poCT->GetColorEntryCount();\n\n png_color *pasPNGColors = (png_color *)CPLMalloc(sizeof(png_color) * PalSize);\n unsigned char *pabyAlpha = (unsigned char *)CPLMalloc(TransSize);\n PNGColors = (void *)pasPNGColors;\n PNGAlpha = (void *)pabyAlpha;\n bool NoTranspYet = true;\n\n \/\/ Set the palette from the end to reduce the size of the opacity mask\n for (int iColor = PalSize - 1; iColor >= 0; iColor--)\n {\n\tGDALColorEntry sEntry;\n\tpoCT->GetColorEntryAsRGB(iColor, &sEntry);\n\n\tpasPNGColors[iColor].red = (png_byte)sEntry.c1;\n\tpasPNGColors[iColor].green = (png_byte)sEntry.c2;\n\tpasPNGColors[iColor].blue = (png_byte)sEntry.c3;\n\tif (NoTranspYet && sEntry.c4 == 255)\n\t TransSize--;\n\telse {\n\t NoTranspYet = false;\n\t pabyAlpha[iColor] = (unsigned char)sEntry.c4;\n\t}\n }\n\n return CE_None;\n}\n\n\/**\n * \\Brief For PPNG, builds the data structures needed to write the palette\n * The presence of the PNGColors and PNGAlpha is used as a flag for PPNG only\n *\/\n\nPNG_Band::PNG_Band(GDALMRFDataset *pDS, const ILImage &image, int b, int level) :\nGDALMRFRasterBand(pDS, image, b, level), PNGColors(NULL), PNGAlpha(NULL)\n\n{ \/\/ Check error conditions\n if (image.dt != GDT_Byte && image.dt != GDT_Int16 && image.dt != GDT_UInt16) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"Data type not supported by MRF PNG\");\n\treturn;\n }\n if (image.pagesize.c > 4) {\n\tCPLError(CE_Failure, CPLE_NotSupported, \"MRF PNG can only handle up to 4 bands per page\");\n\treturn;\n }\n}\n\nPNG_Band::~PNG_Band() {\n CPLFree(PNGColors);\n CPLFree(PNGAlpha);\n}\n\nNAMESPACE_MRF_END\n<|endoftext|>"} {"text":"#include \"utils.hpp\"\n#include \"mapnik_query.hpp\"\n\n#include \n\nPersistent Query::constructor;\n\nvoid Query::Initialize(Handle target) {\n\n HandleScope scope;\n\n constructor = Persistent::New(FunctionTemplate::New(Query::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Query\"));\n\n target->Set(String::NewSymbol(\"Query\"),constructor->GetFunction());\n}\n\nQuery::Query(mapnik::box2d const& box) :\n ObjectWrap(),\n this_(boost::make_shared(box)) {}\n\nQuery::~Query()\n{\n}\n\nHandle Query::New(const Arguments& args)\n{\n HandleScope scope;\n}\navoid compiler warning#include \"utils.hpp\"\n#include \"mapnik_query.hpp\"\n\n#include \n\nPersistent Query::constructor;\n\nvoid Query::Initialize(Handle target) {\n\n HandleScope scope;\n\n constructor = Persistent::New(FunctionTemplate::New(Query::New));\n constructor->InstanceTemplate()->SetInternalFieldCount(1);\n constructor->SetClassName(String::NewSymbol(\"Query\"));\n\n target->Set(String::NewSymbol(\"Query\"),constructor->GetFunction());\n}\n\nQuery::Query(mapnik::box2d const& box) :\n ObjectWrap(),\n this_(boost::make_shared(box)) {}\n\nQuery::~Query()\n{\n}\n\nHandle Query::New(const Arguments& args)\n{\n HandleScope scope;\n \/\/ TODO - implement this\n return Undefined();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_shared_reference.cpp\n *\n * IR lower pass to replace dereferences of compute shader shared variables\n * with intrinsic function calls.\n *\n * This relieves drivers of the responsibility of allocating space for the\n * shared variables in the shared memory region.\n *\/\n\n#include \"lower_buffer_access.h\"\n#include \"ir_builder.h\"\n#include \"main\/macros.h\"\n#include \"util\/list.h\"\n#include \"glsl_parser_extras.h\"\n\nusing namespace ir_builder;\n\nnamespace {\n\nstruct var_offset {\n struct list_head node;\n const ir_variable *var;\n unsigned offset;\n};\n\nclass lower_shared_reference_visitor :\n public lower_buffer_access::lower_buffer_access {\npublic:\n\n lower_shared_reference_visitor(struct gl_shader *shader)\n : list_ctx(ralloc_context(NULL)), shader(shader), shared_size(0u)\n {\n list_inithead(&var_offsets);\n }\n\n ~lower_shared_reference_visitor()\n {\n ralloc_free(list_ctx);\n }\n\n enum {\n shared_load_access,\n shared_store_access,\n shared_atomic_access,\n } buffer_access_type;\n\n void insert_buffer_access(void *mem_ctx, ir_dereference *deref,\n const glsl_type *type, ir_rvalue *offset,\n unsigned mask, int channel);\n\n void handle_rvalue(ir_rvalue **rvalue);\n ir_visitor_status visit_enter(ir_assignment *ir);\n void handle_assignment(ir_assignment *ir);\n\n unsigned get_shared_offset(const ir_variable *);\n\n ir_call *shared_load(void *mem_ctx, const struct glsl_type *type,\n ir_rvalue *offset);\n ir_call *shared_store(void *mem_ctx, ir_rvalue *deref, ir_rvalue *offset,\n unsigned write_mask);\n\n void *list_ctx;\n struct gl_shader *shader;\n struct list_head var_offsets;\n unsigned shared_size;\n bool progress;\n};\n\nunsigned\nlower_shared_reference_visitor::get_shared_offset(const ir_variable *var)\n{\n list_for_each_entry(var_offset, var_entry, &var_offsets, node) {\n if (var_entry->var == var)\n return var_entry->offset;\n }\n\n struct var_offset *new_entry = rzalloc(list_ctx, struct var_offset);\n list_add(&new_entry->node, &var_offsets);\n new_entry->var = var;\n\n unsigned var_align = var->type->std430_base_alignment(false);\n new_entry->offset = glsl_align(shared_size, var_align);\n\n unsigned var_size = var->type->std430_size(false);\n shared_size = new_entry->offset + var_size;\n\n return new_entry->offset;\n}\n\nvoid\nlower_shared_reference_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_dereference *deref = (*rvalue)->as_dereference();\n if (!deref)\n return;\n\n ir_variable *var = deref->variable_referenced();\n if (!var || var->data.mode != ir_var_shader_shared)\n return;\n\n buffer_access_type = shared_load_access;\n\n void *mem_ctx = ralloc_parent(shader->ir);\n\n ir_rvalue *offset = NULL;\n unsigned const_offset = get_shared_offset(var);\n bool row_major;\n int matrix_columns;\n assert(var->get_interface_type() == NULL);\n const unsigned packing = GLSL_INTERFACE_PACKING_STD430;\n\n setup_buffer_access(mem_ctx, var, deref,\n &offset, &const_offset,\n &row_major, &matrix_columns, packing);\n\n \/* Now that we've calculated the offset to the start of the\n * dereference, walk over the type and emit loads into a temporary.\n *\/\n const glsl_type *type = (*rvalue)->type;\n ir_variable *load_var = new(mem_ctx) ir_variable(type,\n \"shared_load_temp\",\n ir_var_temporary);\n base_ir->insert_before(load_var);\n\n ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,\n \"shared_load_temp_offset\",\n ir_var_temporary);\n base_ir->insert_before(load_offset);\n base_ir->insert_before(assign(load_offset, offset));\n\n deref = new(mem_ctx) ir_dereference_variable(load_var);\n\n emit_access(mem_ctx, false, deref, load_offset, const_offset, row_major,\n matrix_columns, packing, 0);\n\n *rvalue = deref;\n\n progress = true;\n}\n\nvoid\nlower_shared_reference_visitor::handle_assignment(ir_assignment *ir)\n{\n if (!ir || !ir->lhs)\n return;\n\n ir_rvalue *rvalue = ir->lhs->as_rvalue();\n if (!rvalue)\n return;\n\n ir_dereference *deref = ir->lhs->as_dereference();\n if (!deref)\n return;\n\n ir_variable *var = ir->lhs->variable_referenced();\n if (!var || var->data.mode != ir_var_shader_shared)\n return;\n\n buffer_access_type = shared_store_access;\n\n \/* We have a write to a shared variable, so declare a temporary and rewrite\n * the assignment so that the temporary is the LHS.\n *\/\n void *mem_ctx = ralloc_parent(shader->ir);\n\n const glsl_type *type = rvalue->type;\n ir_variable *store_var = new(mem_ctx) ir_variable(type,\n \"shared_store_temp\",\n ir_var_temporary);\n base_ir->insert_before(store_var);\n ir->lhs = new(mem_ctx) ir_dereference_variable(store_var);\n\n ir_rvalue *offset = NULL;\n unsigned const_offset = get_shared_offset(var);\n bool row_major;\n int matrix_columns;\n assert(var->get_interface_type() == NULL);\n const unsigned packing = GLSL_INTERFACE_PACKING_STD430;\n\n setup_buffer_access(mem_ctx, var, deref,\n &offset, &const_offset,\n &row_major, &matrix_columns, packing);\n\n deref = new(mem_ctx) ir_dereference_variable(store_var);\n\n ir_variable *store_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,\n \"shared_store_temp_offset\",\n ir_var_temporary);\n base_ir->insert_before(store_offset);\n base_ir->insert_before(assign(store_offset, offset));\n\n \/* Now we have to write the value assigned to the temporary back to memory *\/\n emit_access(mem_ctx, true, deref, store_offset, const_offset, row_major,\n matrix_columns, packing, ir->write_mask);\n\n progress = true;\n}\n\nir_visitor_status\nlower_shared_reference_visitor::visit_enter(ir_assignment *ir)\n{\n handle_assignment(ir);\n return rvalue_visit(ir);\n}\n\nvoid\nlower_shared_reference_visitor::insert_buffer_access(void *mem_ctx,\n ir_dereference *deref,\n const glsl_type *type,\n ir_rvalue *offset,\n unsigned mask,\n int channel)\n{\n if (buffer_access_type == shared_store_access) {\n ir_call *store = shared_store(mem_ctx, deref, offset, mask);\n base_ir->insert_after(store);\n } else {\n ir_call *load = shared_load(mem_ctx, type, offset);\n base_ir->insert_before(load);\n ir_rvalue *value = load->return_deref->as_rvalue()->clone(mem_ctx, NULL);\n base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),\n value));\n }\n}\n\nstatic bool\ncompute_shader_enabled(const _mesa_glsl_parse_state *state)\n{\n return state->stage == MESA_SHADER_COMPUTE;\n}\n\nir_call *\nlower_shared_reference_visitor::shared_store(void *mem_ctx,\n ir_rvalue *deref,\n ir_rvalue *offset,\n unsigned write_mask)\n{\n exec_list sig_params;\n\n ir_variable *offset_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"offset\" , ir_var_function_in);\n sig_params.push_tail(offset_ref);\n\n ir_variable *val_ref = new(mem_ctx)\n ir_variable(deref->type, \"value\" , ir_var_function_in);\n sig_params.push_tail(val_ref);\n\n ir_variable *writemask_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"write_mask\" , ir_var_function_in);\n sig_params.push_tail(writemask_ref);\n\n ir_function_signature *sig = new(mem_ctx)\n ir_function_signature(glsl_type::void_type, compute_shader_enabled);\n assert(sig);\n sig->replace_parameters(&sig_params);\n sig->is_intrinsic = true;\n\n ir_function *f = new(mem_ctx) ir_function(\"__intrinsic_store_shared\");\n f->add_signature(sig);\n\n exec_list call_params;\n call_params.push_tail(offset->clone(mem_ctx, NULL));\n call_params.push_tail(deref->clone(mem_ctx, NULL));\n call_params.push_tail(new(mem_ctx) ir_constant(write_mask));\n return new(mem_ctx) ir_call(sig, NULL, &call_params);\n}\n\nir_call *\nlower_shared_reference_visitor::shared_load(void *mem_ctx,\n const struct glsl_type *type,\n ir_rvalue *offset)\n{\n exec_list sig_params;\n\n ir_variable *offset_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"offset_ref\" , ir_var_function_in);\n sig_params.push_tail(offset_ref);\n\n ir_function_signature *sig =\n new(mem_ctx) ir_function_signature(type, compute_shader_enabled);\n assert(sig);\n sig->replace_parameters(&sig_params);\n sig->is_intrinsic = true;\n\n ir_function *f = new(mem_ctx) ir_function(\"__intrinsic_load_shared\");\n f->add_signature(sig);\n\n ir_variable *result = new(mem_ctx)\n ir_variable(type, \"shared_load_result\", ir_var_temporary);\n base_ir->insert_before(result);\n ir_dereference_variable *deref_result = new(mem_ctx)\n ir_dereference_variable(result);\n\n exec_list call_params;\n call_params.push_tail(offset->clone(mem_ctx, NULL));\n\n return new(mem_ctx) ir_call(sig, deref_result, &call_params);\n}\n\n} \/* unnamed namespace *\/\n\nvoid\nlower_shared_reference(struct gl_shader *shader, unsigned *shared_size)\n{\n if (shader->Stage != MESA_SHADER_COMPUTE)\n return;\n\n lower_shared_reference_visitor v(shader);\n\n \/* Loop over the instructions lowering references, because we take a deref\n * of an shared variable array using a shared variable dereference as the\n * index will produce a collection of instructions all of which have cloned\n * shared variable dereferences for that array index.\n *\/\n do {\n v.progress = false;\n visit_list_elements(&v, shader->ir);\n } while (v.progress);\n\n *shared_size = v.shared_size;\n}\nglsl: Translate atomic intrinsic functions on shared variables\/*\n * Copyright (c) 2015 Intel Corporation\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the \"Software\"),\n * to deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice (including the next\n * paragraph) shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n * DEALINGS IN THE SOFTWARE.\n *\/\n\n\/**\n * \\file lower_shared_reference.cpp\n *\n * IR lower pass to replace dereferences of compute shader shared variables\n * with intrinsic function calls.\n *\n * This relieves drivers of the responsibility of allocating space for the\n * shared variables in the shared memory region.\n *\/\n\n#include \"lower_buffer_access.h\"\n#include \"ir_builder.h\"\n#include \"main\/macros.h\"\n#include \"util\/list.h\"\n#include \"glsl_parser_extras.h\"\n\nusing namespace ir_builder;\n\nnamespace {\n\nstruct var_offset {\n struct list_head node;\n const ir_variable *var;\n unsigned offset;\n};\n\nclass lower_shared_reference_visitor :\n public lower_buffer_access::lower_buffer_access {\npublic:\n\n lower_shared_reference_visitor(struct gl_shader *shader)\n : list_ctx(ralloc_context(NULL)), shader(shader), shared_size(0u)\n {\n list_inithead(&var_offsets);\n }\n\n ~lower_shared_reference_visitor()\n {\n ralloc_free(list_ctx);\n }\n\n enum {\n shared_load_access,\n shared_store_access,\n shared_atomic_access,\n } buffer_access_type;\n\n void insert_buffer_access(void *mem_ctx, ir_dereference *deref,\n const glsl_type *type, ir_rvalue *offset,\n unsigned mask, int channel);\n\n void handle_rvalue(ir_rvalue **rvalue);\n ir_visitor_status visit_enter(ir_assignment *ir);\n void handle_assignment(ir_assignment *ir);\n\n ir_call *lower_shared_atomic_intrinsic(ir_call *ir);\n ir_call *check_for_shared_atomic_intrinsic(ir_call *ir);\n ir_visitor_status visit_enter(ir_call *ir);\n\n unsigned get_shared_offset(const ir_variable *);\n\n ir_call *shared_load(void *mem_ctx, const struct glsl_type *type,\n ir_rvalue *offset);\n ir_call *shared_store(void *mem_ctx, ir_rvalue *deref, ir_rvalue *offset,\n unsigned write_mask);\n\n void *list_ctx;\n struct gl_shader *shader;\n struct list_head var_offsets;\n unsigned shared_size;\n bool progress;\n};\n\nunsigned\nlower_shared_reference_visitor::get_shared_offset(const ir_variable *var)\n{\n list_for_each_entry(var_offset, var_entry, &var_offsets, node) {\n if (var_entry->var == var)\n return var_entry->offset;\n }\n\n struct var_offset *new_entry = rzalloc(list_ctx, struct var_offset);\n list_add(&new_entry->node, &var_offsets);\n new_entry->var = var;\n\n unsigned var_align = var->type->std430_base_alignment(false);\n new_entry->offset = glsl_align(shared_size, var_align);\n\n unsigned var_size = var->type->std430_size(false);\n shared_size = new_entry->offset + var_size;\n\n return new_entry->offset;\n}\n\nvoid\nlower_shared_reference_visitor::handle_rvalue(ir_rvalue **rvalue)\n{\n if (!*rvalue)\n return;\n\n ir_dereference *deref = (*rvalue)->as_dereference();\n if (!deref)\n return;\n\n ir_variable *var = deref->variable_referenced();\n if (!var || var->data.mode != ir_var_shader_shared)\n return;\n\n buffer_access_type = shared_load_access;\n\n void *mem_ctx = ralloc_parent(shader->ir);\n\n ir_rvalue *offset = NULL;\n unsigned const_offset = get_shared_offset(var);\n bool row_major;\n int matrix_columns;\n assert(var->get_interface_type() == NULL);\n const unsigned packing = GLSL_INTERFACE_PACKING_STD430;\n\n setup_buffer_access(mem_ctx, var, deref,\n &offset, &const_offset,\n &row_major, &matrix_columns, packing);\n\n \/* Now that we've calculated the offset to the start of the\n * dereference, walk over the type and emit loads into a temporary.\n *\/\n const glsl_type *type = (*rvalue)->type;\n ir_variable *load_var = new(mem_ctx) ir_variable(type,\n \"shared_load_temp\",\n ir_var_temporary);\n base_ir->insert_before(load_var);\n\n ir_variable *load_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,\n \"shared_load_temp_offset\",\n ir_var_temporary);\n base_ir->insert_before(load_offset);\n base_ir->insert_before(assign(load_offset, offset));\n\n deref = new(mem_ctx) ir_dereference_variable(load_var);\n\n emit_access(mem_ctx, false, deref, load_offset, const_offset, row_major,\n matrix_columns, packing, 0);\n\n *rvalue = deref;\n\n progress = true;\n}\n\nvoid\nlower_shared_reference_visitor::handle_assignment(ir_assignment *ir)\n{\n if (!ir || !ir->lhs)\n return;\n\n ir_rvalue *rvalue = ir->lhs->as_rvalue();\n if (!rvalue)\n return;\n\n ir_dereference *deref = ir->lhs->as_dereference();\n if (!deref)\n return;\n\n ir_variable *var = ir->lhs->variable_referenced();\n if (!var || var->data.mode != ir_var_shader_shared)\n return;\n\n buffer_access_type = shared_store_access;\n\n \/* We have a write to a shared variable, so declare a temporary and rewrite\n * the assignment so that the temporary is the LHS.\n *\/\n void *mem_ctx = ralloc_parent(shader->ir);\n\n const glsl_type *type = rvalue->type;\n ir_variable *store_var = new(mem_ctx) ir_variable(type,\n \"shared_store_temp\",\n ir_var_temporary);\n base_ir->insert_before(store_var);\n ir->lhs = new(mem_ctx) ir_dereference_variable(store_var);\n\n ir_rvalue *offset = NULL;\n unsigned const_offset = get_shared_offset(var);\n bool row_major;\n int matrix_columns;\n assert(var->get_interface_type() == NULL);\n const unsigned packing = GLSL_INTERFACE_PACKING_STD430;\n\n setup_buffer_access(mem_ctx, var, deref,\n &offset, &const_offset,\n &row_major, &matrix_columns, packing);\n\n deref = new(mem_ctx) ir_dereference_variable(store_var);\n\n ir_variable *store_offset = new(mem_ctx) ir_variable(glsl_type::uint_type,\n \"shared_store_temp_offset\",\n ir_var_temporary);\n base_ir->insert_before(store_offset);\n base_ir->insert_before(assign(store_offset, offset));\n\n \/* Now we have to write the value assigned to the temporary back to memory *\/\n emit_access(mem_ctx, true, deref, store_offset, const_offset, row_major,\n matrix_columns, packing, ir->write_mask);\n\n progress = true;\n}\n\nir_visitor_status\nlower_shared_reference_visitor::visit_enter(ir_assignment *ir)\n{\n handle_assignment(ir);\n return rvalue_visit(ir);\n}\n\nvoid\nlower_shared_reference_visitor::insert_buffer_access(void *mem_ctx,\n ir_dereference *deref,\n const glsl_type *type,\n ir_rvalue *offset,\n unsigned mask,\n int channel)\n{\n if (buffer_access_type == shared_store_access) {\n ir_call *store = shared_store(mem_ctx, deref, offset, mask);\n base_ir->insert_after(store);\n } else {\n ir_call *load = shared_load(mem_ctx, type, offset);\n base_ir->insert_before(load);\n ir_rvalue *value = load->return_deref->as_rvalue()->clone(mem_ctx, NULL);\n base_ir->insert_before(assign(deref->clone(mem_ctx, NULL),\n value));\n }\n}\n\nstatic bool\ncompute_shader_enabled(const _mesa_glsl_parse_state *state)\n{\n return state->stage == MESA_SHADER_COMPUTE;\n}\n\nir_call *\nlower_shared_reference_visitor::shared_store(void *mem_ctx,\n ir_rvalue *deref,\n ir_rvalue *offset,\n unsigned write_mask)\n{\n exec_list sig_params;\n\n ir_variable *offset_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"offset\" , ir_var_function_in);\n sig_params.push_tail(offset_ref);\n\n ir_variable *val_ref = new(mem_ctx)\n ir_variable(deref->type, \"value\" , ir_var_function_in);\n sig_params.push_tail(val_ref);\n\n ir_variable *writemask_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"write_mask\" , ir_var_function_in);\n sig_params.push_tail(writemask_ref);\n\n ir_function_signature *sig = new(mem_ctx)\n ir_function_signature(glsl_type::void_type, compute_shader_enabled);\n assert(sig);\n sig->replace_parameters(&sig_params);\n sig->is_intrinsic = true;\n\n ir_function *f = new(mem_ctx) ir_function(\"__intrinsic_store_shared\");\n f->add_signature(sig);\n\n exec_list call_params;\n call_params.push_tail(offset->clone(mem_ctx, NULL));\n call_params.push_tail(deref->clone(mem_ctx, NULL));\n call_params.push_tail(new(mem_ctx) ir_constant(write_mask));\n return new(mem_ctx) ir_call(sig, NULL, &call_params);\n}\n\nir_call *\nlower_shared_reference_visitor::shared_load(void *mem_ctx,\n const struct glsl_type *type,\n ir_rvalue *offset)\n{\n exec_list sig_params;\n\n ir_variable *offset_ref = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"offset_ref\" , ir_var_function_in);\n sig_params.push_tail(offset_ref);\n\n ir_function_signature *sig =\n new(mem_ctx) ir_function_signature(type, compute_shader_enabled);\n assert(sig);\n sig->replace_parameters(&sig_params);\n sig->is_intrinsic = true;\n\n ir_function *f = new(mem_ctx) ir_function(\"__intrinsic_load_shared\");\n f->add_signature(sig);\n\n ir_variable *result = new(mem_ctx)\n ir_variable(type, \"shared_load_result\", ir_var_temporary);\n base_ir->insert_before(result);\n ir_dereference_variable *deref_result = new(mem_ctx)\n ir_dereference_variable(result);\n\n exec_list call_params;\n call_params.push_tail(offset->clone(mem_ctx, NULL));\n\n return new(mem_ctx) ir_call(sig, deref_result, &call_params);\n}\n\n\/* Lowers the intrinsic call to a new internal intrinsic that swaps the access\n * to the shared variable in the first parameter by an offset. This involves\n * creating the new internal intrinsic (i.e. the new function signature).\n *\/\nir_call *\nlower_shared_reference_visitor::lower_shared_atomic_intrinsic(ir_call *ir)\n{\n \/* Shared atomics usually have 2 parameters, the shared variable and an\n * integer argument. The exception is CompSwap, that has an additional\n * integer parameter.\n *\/\n int param_count = ir->actual_parameters.length();\n assert(param_count == 2 || param_count == 3);\n\n \/* First argument must be a scalar integer shared variable *\/\n exec_node *param = ir->actual_parameters.get_head();\n ir_instruction *inst = (ir_instruction *) param;\n assert(inst->ir_type == ir_type_dereference_variable ||\n inst->ir_type == ir_type_dereference_array ||\n inst->ir_type == ir_type_dereference_record ||\n inst->ir_type == ir_type_swizzle);\n\n ir_rvalue *deref = (ir_rvalue *) inst;\n assert(deref->type->is_scalar() && deref->type->is_integer());\n\n ir_variable *var = deref->variable_referenced();\n assert(var);\n\n \/* Compute the offset to the start if the dereference\n *\/\n void *mem_ctx = ralloc_parent(shader->ir);\n\n ir_rvalue *offset = NULL;\n unsigned const_offset = get_shared_offset(var);\n bool row_major;\n int matrix_columns;\n assert(var->get_interface_type() == NULL);\n const unsigned packing = GLSL_INTERFACE_PACKING_STD430;\n buffer_access_type = shared_atomic_access;\n\n setup_buffer_access(mem_ctx, var, deref,\n &offset, &const_offset,\n &row_major, &matrix_columns, packing);\n\n assert(offset);\n assert(!row_major);\n assert(matrix_columns == 1);\n\n ir_rvalue *deref_offset =\n add(offset, new(mem_ctx) ir_constant(const_offset));\n\n \/* Create the new internal function signature that will take an offset\n * instead of a shared variable\n *\/\n exec_list sig_params;\n ir_variable *sig_param = new(mem_ctx)\n ir_variable(glsl_type::uint_type, \"offset\" , ir_var_function_in);\n sig_params.push_tail(sig_param);\n\n const glsl_type *type = deref->type->base_type == GLSL_TYPE_INT ?\n glsl_type::int_type : glsl_type::uint_type;\n sig_param = new(mem_ctx)\n ir_variable(type, \"data1\", ir_var_function_in);\n sig_params.push_tail(sig_param);\n\n if (param_count == 3) {\n sig_param = new(mem_ctx)\n ir_variable(type, \"data2\", ir_var_function_in);\n sig_params.push_tail(sig_param);\n }\n\n ir_function_signature *sig =\n new(mem_ctx) ir_function_signature(deref->type,\n compute_shader_enabled);\n assert(sig);\n sig->replace_parameters(&sig_params);\n sig->is_intrinsic = true;\n\n char func_name[64];\n sprintf(func_name, \"%s_shared\", ir->callee_name());\n ir_function *f = new(mem_ctx) ir_function(func_name);\n f->add_signature(sig);\n\n \/* Now, create the call to the internal intrinsic *\/\n exec_list call_params;\n call_params.push_tail(deref_offset);\n param = ir->actual_parameters.get_head()->get_next();\n ir_rvalue *param_as_rvalue = ((ir_instruction *) param)->as_rvalue();\n call_params.push_tail(param_as_rvalue->clone(mem_ctx, NULL));\n if (param_count == 3) {\n param = param->get_next();\n param_as_rvalue = ((ir_instruction *) param)->as_rvalue();\n call_params.push_tail(param_as_rvalue->clone(mem_ctx, NULL));\n }\n ir_dereference_variable *return_deref =\n ir->return_deref->clone(mem_ctx, NULL);\n return new(mem_ctx) ir_call(sig, return_deref, &call_params);\n}\n\nir_call *\nlower_shared_reference_visitor::check_for_shared_atomic_intrinsic(ir_call *ir)\n{\n exec_list& params = ir->actual_parameters;\n\n if (params.length() < 2 || params.length() > 3)\n return ir;\n\n ir_rvalue *rvalue =\n ((ir_instruction *) params.get_head())->as_rvalue();\n if (!rvalue)\n return ir;\n\n ir_variable *var = rvalue->variable_referenced();\n if (!var || var->data.mode != ir_var_shader_shared)\n return ir;\n\n const char *callee = ir->callee_name();\n if (!strcmp(\"__intrinsic_atomic_add\", callee) ||\n !strcmp(\"__intrinsic_atomic_min\", callee) ||\n !strcmp(\"__intrinsic_atomic_max\", callee) ||\n !strcmp(\"__intrinsic_atomic_and\", callee) ||\n !strcmp(\"__intrinsic_atomic_or\", callee) ||\n !strcmp(\"__intrinsic_atomic_xor\", callee) ||\n !strcmp(\"__intrinsic_atomic_exchange\", callee) ||\n !strcmp(\"__intrinsic_atomic_comp_swap\", callee)) {\n return lower_shared_atomic_intrinsic(ir);\n }\n\n return ir;\n}\n\nir_visitor_status\nlower_shared_reference_visitor::visit_enter(ir_call *ir)\n{\n ir_call *new_ir = check_for_shared_atomic_intrinsic(ir);\n if (new_ir != ir) {\n progress = true;\n base_ir->replace_with(new_ir);\n return visit_continue_with_parent;\n }\n\n return rvalue_visit(ir);\n}\n\n} \/* unnamed namespace *\/\n\nvoid\nlower_shared_reference(struct gl_shader *shader, unsigned *shared_size)\n{\n if (shader->Stage != MESA_SHADER_COMPUTE)\n return;\n\n lower_shared_reference_visitor v(shader);\n\n \/* Loop over the instructions lowering references, because we take a deref\n * of an shared variable array using a shared variable dereference as the\n * index will produce a collection of instructions all of which have cloned\n * shared variable dereferences for that array index.\n *\/\n do {\n v.progress = false;\n visit_list_elements(&v, shader->ir);\n } while (v.progress);\n\n *shared_size = v.shared_size;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkGpuDevice.h\"\n#include \"GrBlurUtils.h\"\n#include \"GrCaps.h\"\n#include \"GrColorSpaceXform.h\"\n#include \"GrRenderTargetContext.h\"\n#include \"GrStyle.h\"\n#include \"GrTextureAdjuster.h\"\n#include \"GrTextureMaker.h\"\n#include \"SkDraw.h\"\n#include \"SkGr.h\"\n#include \"SkMaskFilter.h\"\n#include \"effects\/GrBicubicEffect.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n#include \"effects\/GrTextureDomain.h\"\n\nstatic inline bool use_shader(bool textureIsAlphaOnly, const SkPaint& paint) {\n return textureIsAlphaOnly && paint.getShader();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper functions for dropping src rect constraint in bilerp mode.\n\nstatic const SkScalar kColorBleedTolerance = 0.001f;\n\nstatic bool has_aligned_samples(const SkRect& srcRect, const SkRect& transformedRect) {\n \/\/ detect pixel disalignment\n if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - transformedRect.left()) < kColorBleedTolerance &&\n SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) - transformedRect.top()) < kColorBleedTolerance &&\n SkScalarAbs(transformedRect.width() - srcRect.width()) < kColorBleedTolerance &&\n SkScalarAbs(transformedRect.height() - srcRect.height()) < kColorBleedTolerance) {\n return true;\n }\n return false;\n}\n\nstatic bool may_color_bleed(const SkRect& srcRect,\n const SkRect& transformedRect,\n const SkMatrix& m,\n GrFSAAType fsaaType) {\n \/\/ Only gets called if has_aligned_samples returned false.\n \/\/ So we can assume that sampling is axis aligned but not texel aligned.\n SkASSERT(!has_aligned_samples(srcRect, transformedRect));\n SkRect innerSrcRect(srcRect), innerTransformedRect, outerTransformedRect(transformedRect);\n if (GrFSAAType::kUnifiedMSAA == fsaaType) {\n innerSrcRect.inset(SK_Scalar1, SK_Scalar1);\n } else {\n innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);\n }\n m.mapRect(&innerTransformedRect, innerSrcRect);\n\n \/\/ The gap between outerTransformedRect and innerTransformedRect\n \/\/ represents the projection of the source border area, which is\n \/\/ problematic for color bleeding. We must check whether any\n \/\/ destination pixels sample the border area.\n outerTransformedRect.inset(kColorBleedTolerance, kColorBleedTolerance);\n innerTransformedRect.outset(kColorBleedTolerance, kColorBleedTolerance);\n SkIRect outer, inner;\n outerTransformedRect.round(&outer);\n innerTransformedRect.round(&inner);\n \/\/ If the inner and outer rects round to the same result, it means the\n \/\/ border does not overlap any pixel centers. Yay!\n return inner != outer;\n}\n\nstatic bool can_ignore_bilerp_constraint(const GrTextureProducer& producer,\n const SkRect& srcRect,\n const SkMatrix& srcRectToDeviceSpace,\n GrFSAAType fsaaType) {\n if (srcRectToDeviceSpace.rectStaysRect()) {\n \/\/ sampling is axis-aligned\n SkRect transformedRect;\n srcRectToDeviceSpace.mapRect(&transformedRect, srcRect);\n\n if (has_aligned_samples(srcRect, transformedRect) ||\n !may_color_bleed(srcRect, transformedRect, srcRectToDeviceSpace, fsaaType)) {\n return true;\n }\n }\n return false;\n}\n\n\/**\n * Checks whether the paint, matrix, and constraint are compatible with using\n * GrRenderTargetContext::drawTextureAffine. It is more effecient than the GrTextureProducer\n * general case.\n *\/\nstatic bool can_use_draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm,\n SkCanvas::SrcRectConstraint constraint) {\n return (!paint.getColorFilter() && !paint.getShader() && !paint.getMaskFilter() &&\n !paint.getImageFilter() && paint.getFilterQuality() < kMedium_SkFilterQuality &&\n paint.getBlendMode() == SkBlendMode::kSrcOver && !ctm.hasPerspective() &&\n SkCanvas::kFast_SrcRectConstraint == constraint);\n}\n\nstatic void draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm, const SkRect* src,\n const SkRect* dst, GrAA aa, sk_sp proxy,\n SkColorSpace* colorSpace, const GrClip& clip,\n GrRenderTargetContext* rtc) {\n SkASSERT(!(SkToBool(src) && !SkToBool(dst)));\n SkRect srcRect = src ? *src : SkRect::MakeWH(proxy->width(), proxy->height());\n SkRect dstRect = dst ? *dst : srcRect;\n if (src && !SkRect::MakeIWH(proxy->width(), proxy->height()).contains(srcRect)) {\n \/\/ Shrink the src rect to be within bounds and proportionately shrink the dst rect.\n SkMatrix srcToDst;\n srcToDst.setRectToRect(srcRect, dstRect, SkMatrix::kFill_ScaleToFit);\n SkAssertResult(srcRect.intersect(SkRect::MakeIWH(proxy->width(), proxy->height())));\n srcToDst.mapRect(&dstRect, srcRect);\n }\n auto csxf = GrColorSpaceXform::Make(colorSpace, proxy->config(),\n rtc->colorSpaceInfo().colorSpace());\n GrSamplerState::Filter filter;\n switch (paint.getFilterQuality()) {\n case kNone_SkFilterQuality:\n filter = GrSamplerState::Filter::kNearest;\n break;\n case kLow_SkFilterQuality:\n filter = GrSamplerState::Filter::kBilerp;\n break;\n case kMedium_SkFilterQuality:\n case kHigh_SkFilterQuality:\n SK_ABORT(\"Quality level not allowed.\");\n }\n GrColor color = GrPixelConfigIsAlphaOnly(proxy->config())\n ? SkColorToPremulGrColor(paint.getColor())\n : SkColorAlphaToGrColor(paint.getColor());\n rtc->drawTextureAffine(clip, std::move(proxy), filter, color, srcRect, dstRect, aa, ctm,\n std::move(csxf));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkGpuDevice::drawPinnedTextureProxy(sk_sp proxy, uint32_t pinnedUniqueID,\n SkColorSpace* colorSpace, SkAlphaType alphaType,\n const SkRect* srcRect, const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix, const SkPaint& paint) {\n if (can_use_draw_texture_affine(paint, this->ctm(), constraint)) {\n draw_texture_affine(paint, viewMatrix, srcRect, dstRect, GrAA(paint.isAntiAlias()),\n std::move(proxy), colorSpace, this->clip(), fRenderTargetContext.get());\n return;\n }\n GrTextureAdjuster adjuster(this->context(), std::move(proxy), alphaType, pinnedUniqueID,\n colorSpace);\n this->drawTextureProducer(&adjuster, srcRect, dstRect, constraint, viewMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureMaker(GrTextureMaker* maker, int imageW, int imageH,\n const SkRect* srcRect, const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix, const SkPaint& paint) {\n if (can_use_draw_texture_affine(paint, viewMatrix, constraint)) {\n sk_sp cs;\n \/\/ We've done enough checks above to allow us to pass ClampNearest() and not check for\n \/\/ scaling adjustments.\n auto proxy = maker->refTextureProxyForParams(\n GrSamplerState::ClampNearest(), fRenderTargetContext->colorSpaceInfo().colorSpace(),\n &cs, nullptr);\n if (!proxy) {\n return;\n }\n draw_texture_affine(paint, viewMatrix, srcRect, dstRect, GrAA(paint.isAntiAlias()),\n std::move(proxy), cs.get(), this->clip(), fRenderTargetContext.get());\n return;\n }\n this->drawTextureProducer(maker, srcRect, dstRect, constraint, viewMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureProducer(GrTextureProducer* producer,\n const SkRect* srcRect,\n const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix,\n const SkPaint& paint) {\n \/\/ This is the funnel for all non-tiled bitmap\/image draw calls. Log a histogram entry.\n SK_HISTOGRAM_BOOLEAN(\"DrawTiled\", false);\n\n \/\/ Figure out the actual dst and src rect by clipping the src rect to the bounds of the\n \/\/ adjuster. If the src rect is clipped then the dst rect must be recomputed. Also determine\n \/\/ the matrix that maps the src rect to the dst rect.\n SkRect clippedSrcRect;\n SkRect clippedDstRect;\n const SkRect srcBounds = SkRect::MakeIWH(producer->width(), producer->height());\n SkMatrix srcToDstMatrix;\n if (srcRect) {\n if (!dstRect) {\n dstRect = &srcBounds;\n }\n if (!srcBounds.contains(*srcRect)) {\n clippedSrcRect = *srcRect;\n if (!clippedSrcRect.intersect(srcBounds)) {\n return;\n }\n if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n srcToDstMatrix.mapRect(&clippedDstRect, clippedSrcRect);\n } else {\n clippedSrcRect = *srcRect;\n clippedDstRect = *dstRect;\n if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n }\n } else {\n clippedSrcRect = srcBounds;\n if (dstRect) {\n clippedDstRect = *dstRect;\n if (!srcToDstMatrix.setRectToRect(srcBounds, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n } else {\n clippedDstRect = srcBounds;\n srcToDstMatrix.reset();\n }\n }\n\n \/\/ Now that we have both the view and srcToDst matrices, log our scale factor.\n LogDrawScaleFactor(SkMatrix::Concat(viewMatrix, srcToDstMatrix), paint.getFilterQuality());\n\n this->drawTextureProducerImpl(producer, clippedSrcRect, clippedDstRect, constraint, viewMatrix,\n srcToDstMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureProducerImpl(GrTextureProducer* producer,\n const SkRect& clippedSrcRect,\n const SkRect& clippedDstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix,\n const SkMatrix& srcToDstMatrix,\n const SkPaint& paint) {\n \/\/ Specifying the texture coords as local coordinates is an attempt to enable more GrDrawOp\n \/\/ combining by not baking anything about the srcRect, dstRect, or viewMatrix, into the texture\n \/\/ FP. In the future this should be an opaque optimization enabled by the combination of\n \/\/ GrDrawOp\/GP and FP.\n const SkMaskFilter* mf = paint.getMaskFilter();\n \/\/ The shader expects proper local coords, so we can't replace local coords with texture coords\n \/\/ if the shader will be used. If we have a mask filter we will change the underlying geometry\n \/\/ that is rendered.\n bool canUseTextureCoordsAsLocalCoords = !use_shader(producer->isAlphaOnly(), paint) && !mf;\n\n bool doBicubic;\n GrSamplerState::Filter fm = GrSkFilterQualityToGrFilterMode(\n paint.getFilterQuality(), viewMatrix, srcToDstMatrix, &doBicubic);\n const GrSamplerState::Filter* filterMode = doBicubic ? nullptr : &fm;\n\n GrTextureProducer::FilterConstraint constraintMode;\n if (SkCanvas::kFast_SrcRectConstraint == constraint) {\n constraintMode = GrTextureAdjuster::kNo_FilterConstraint;\n } else {\n constraintMode = GrTextureAdjuster::kYes_FilterConstraint;\n }\n\n \/\/ If we have to outset for AA then we will generate texture coords outside the src rect. The\n \/\/ same happens for any mask filter that extends the bounds rendered in the dst.\n \/\/ This is conservative as a mask filter does not have to expand the bounds rendered.\n bool coordsAllInsideSrcRect = !paint.isAntiAlias() && !mf;\n\n \/\/ Check for optimization to drop the src rect constraint when on bilerp.\n if (filterMode && GrSamplerState::Filter::kBilerp == *filterMode &&\n GrTextureAdjuster::kYes_FilterConstraint == constraintMode && coordsAllInsideSrcRect) {\n SkMatrix combinedMatrix;\n combinedMatrix.setConcat(viewMatrix, srcToDstMatrix);\n if (can_ignore_bilerp_constraint(*producer, clippedSrcRect, combinedMatrix,\n fRenderTargetContext->fsaaType())) {\n constraintMode = GrTextureAdjuster::kNo_FilterConstraint;\n }\n }\n\n const SkMatrix* textureMatrix;\n SkMatrix tempMatrix;\n if (canUseTextureCoordsAsLocalCoords) {\n textureMatrix = &SkMatrix::I();\n } else {\n if (!srcToDstMatrix.invert(&tempMatrix)) {\n return;\n }\n textureMatrix = &tempMatrix;\n }\n auto fp = producer->createFragmentProcessor(\n *textureMatrix, clippedSrcRect, constraintMode, coordsAllInsideSrcRect, filterMode,\n fRenderTargetContext->colorSpaceInfo().colorSpace());\n if (!fp) {\n return;\n }\n\n GrPaint grPaint;\n if (!SkPaintToGrPaintWithTexture(fContext.get(), fRenderTargetContext->colorSpaceInfo(), paint,\n viewMatrix, std::move(fp), producer->isAlphaOnly(),\n &grPaint)) {\n return;\n }\n GrAA aa = GrAA(paint.isAntiAlias());\n if (canUseTextureCoordsAsLocalCoords) {\n fRenderTargetContext->fillRectToRect(this->clip(), std::move(grPaint), aa, viewMatrix,\n clippedDstRect, clippedSrcRect);\n return;\n }\n\n if (!mf) {\n fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), aa, viewMatrix,\n clippedDstRect);\n return;\n }\n\n \/\/ First see if we can do the draw + mask filter direct to the dst.\n if (viewMatrix.isScaleTranslate()) {\n SkRect devClippedDstRect;\n viewMatrix.mapRectScaleTranslate(&devClippedDstRect, clippedDstRect);\n\n SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);\n if (mf->directFilterRRectMaskGPU(fContext.get(),\n fRenderTargetContext.get(),\n std::move(grPaint),\n this->clip(),\n viewMatrix,\n rec,\n SkRRect::MakeRect(clippedDstRect),\n SkRRect::MakeRect(devClippedDstRect))) {\n return;\n }\n }\n\n SkPath rectPath;\n rectPath.addRect(clippedDstRect);\n rectPath.setIsVolatile(true);\n GrBlurUtils::drawPathWithMaskFilter(this->context(), fRenderTargetContext.get(), this->clip(),\n rectPath, std::move(grPaint), aa, viewMatrix, mf,\n GrStyle::SimpleFill(), true);\n}\nAdd macro to disable using GrTextureOp for AA in Chrome\/*\n * Copyright 2015 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n#include \"SkGpuDevice.h\"\n#include \"GrBlurUtils.h\"\n#include \"GrCaps.h\"\n#include \"GrColorSpaceXform.h\"\n#include \"GrRenderTargetContext.h\"\n#include \"GrStyle.h\"\n#include \"GrTextureAdjuster.h\"\n#include \"GrTextureMaker.h\"\n#include \"SkDraw.h\"\n#include \"SkGr.h\"\n#include \"SkMaskFilter.h\"\n#include \"effects\/GrBicubicEffect.h\"\n#include \"effects\/GrSimpleTextureEffect.h\"\n#include \"effects\/GrTextureDomain.h\"\n\nstatic inline bool use_shader(bool textureIsAlphaOnly, const SkPaint& paint) {\n return textureIsAlphaOnly && paint.getShader();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Helper functions for dropping src rect constraint in bilerp mode.\n\nstatic const SkScalar kColorBleedTolerance = 0.001f;\n\nstatic bool has_aligned_samples(const SkRect& srcRect, const SkRect& transformedRect) {\n \/\/ detect pixel disalignment\n if (SkScalarAbs(SkScalarRoundToScalar(transformedRect.left()) - transformedRect.left()) < kColorBleedTolerance &&\n SkScalarAbs(SkScalarRoundToScalar(transformedRect.top()) - transformedRect.top()) < kColorBleedTolerance &&\n SkScalarAbs(transformedRect.width() - srcRect.width()) < kColorBleedTolerance &&\n SkScalarAbs(transformedRect.height() - srcRect.height()) < kColorBleedTolerance) {\n return true;\n }\n return false;\n}\n\nstatic bool may_color_bleed(const SkRect& srcRect,\n const SkRect& transformedRect,\n const SkMatrix& m,\n GrFSAAType fsaaType) {\n \/\/ Only gets called if has_aligned_samples returned false.\n \/\/ So we can assume that sampling is axis aligned but not texel aligned.\n SkASSERT(!has_aligned_samples(srcRect, transformedRect));\n SkRect innerSrcRect(srcRect), innerTransformedRect, outerTransformedRect(transformedRect);\n if (GrFSAAType::kUnifiedMSAA == fsaaType) {\n innerSrcRect.inset(SK_Scalar1, SK_Scalar1);\n } else {\n innerSrcRect.inset(SK_ScalarHalf, SK_ScalarHalf);\n }\n m.mapRect(&innerTransformedRect, innerSrcRect);\n\n \/\/ The gap between outerTransformedRect and innerTransformedRect\n \/\/ represents the projection of the source border area, which is\n \/\/ problematic for color bleeding. We must check whether any\n \/\/ destination pixels sample the border area.\n outerTransformedRect.inset(kColorBleedTolerance, kColorBleedTolerance);\n innerTransformedRect.outset(kColorBleedTolerance, kColorBleedTolerance);\n SkIRect outer, inner;\n outerTransformedRect.round(&outer);\n innerTransformedRect.round(&inner);\n \/\/ If the inner and outer rects round to the same result, it means the\n \/\/ border does not overlap any pixel centers. Yay!\n return inner != outer;\n}\n\nstatic bool can_ignore_bilerp_constraint(const GrTextureProducer& producer,\n const SkRect& srcRect,\n const SkMatrix& srcRectToDeviceSpace,\n GrFSAAType fsaaType) {\n if (srcRectToDeviceSpace.rectStaysRect()) {\n \/\/ sampling is axis-aligned\n SkRect transformedRect;\n srcRectToDeviceSpace.mapRect(&transformedRect, srcRect);\n\n if (has_aligned_samples(srcRect, transformedRect) ||\n !may_color_bleed(srcRect, transformedRect, srcRectToDeviceSpace, fsaaType)) {\n return true;\n }\n }\n return false;\n}\n\n\/**\n * Checks whether the paint, matrix, and constraint are compatible with using\n * GrRenderTargetContext::drawTextureAffine. It is more effecient than the GrTextureProducer\n * general case.\n *\/\nstatic bool can_use_draw_texture_affine(const SkPaint& paint, GrAA aa, const SkMatrix& ctm,\n SkCanvas::SrcRectConstraint constraint) {\n\/\/ This is disabled in Chrome until crbug.com\/802408 and crbug.com\/801783 can be sorted out.\n#ifdef SK_DISABLE_TEXTURE_OP_AA\n if (GrAA::kYes == aa) {\n return false;\n }\n#endif\n return (!paint.getColorFilter() && !paint.getShader() && !paint.getMaskFilter() &&\n !paint.getImageFilter() && paint.getFilterQuality() < kMedium_SkFilterQuality &&\n paint.getBlendMode() == SkBlendMode::kSrcOver && !ctm.hasPerspective() &&\n SkCanvas::kFast_SrcRectConstraint == constraint);\n}\n\nstatic void draw_texture_affine(const SkPaint& paint, const SkMatrix& ctm, const SkRect* src,\n const SkRect* dst, GrAA aa, sk_sp proxy,\n SkColorSpace* colorSpace, const GrClip& clip,\n GrRenderTargetContext* rtc) {\n SkASSERT(!(SkToBool(src) && !SkToBool(dst)));\n SkRect srcRect = src ? *src : SkRect::MakeWH(proxy->width(), proxy->height());\n SkRect dstRect = dst ? *dst : srcRect;\n if (src && !SkRect::MakeIWH(proxy->width(), proxy->height()).contains(srcRect)) {\n \/\/ Shrink the src rect to be within bounds and proportionately shrink the dst rect.\n SkMatrix srcToDst;\n srcToDst.setRectToRect(srcRect, dstRect, SkMatrix::kFill_ScaleToFit);\n SkAssertResult(srcRect.intersect(SkRect::MakeIWH(proxy->width(), proxy->height())));\n srcToDst.mapRect(&dstRect, srcRect);\n }\n auto csxf = GrColorSpaceXform::Make(colorSpace, proxy->config(),\n rtc->colorSpaceInfo().colorSpace());\n GrSamplerState::Filter filter;\n switch (paint.getFilterQuality()) {\n case kNone_SkFilterQuality:\n filter = GrSamplerState::Filter::kNearest;\n break;\n case kLow_SkFilterQuality:\n filter = GrSamplerState::Filter::kBilerp;\n break;\n case kMedium_SkFilterQuality:\n case kHigh_SkFilterQuality:\n SK_ABORT(\"Quality level not allowed.\");\n }\n GrColor color = GrPixelConfigIsAlphaOnly(proxy->config())\n ? SkColorToPremulGrColor(paint.getColor())\n : SkColorAlphaToGrColor(paint.getColor());\n rtc->drawTextureAffine(clip, std::move(proxy), filter, color, srcRect, dstRect, aa, ctm,\n std::move(csxf));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkGpuDevice::drawPinnedTextureProxy(sk_sp proxy, uint32_t pinnedUniqueID,\n SkColorSpace* colorSpace, SkAlphaType alphaType,\n const SkRect* srcRect, const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix, const SkPaint& paint) {\n GrAA aa = GrAA(paint.isAntiAlias());\n if (can_use_draw_texture_affine(paint, aa, this->ctm(), constraint)) {\n draw_texture_affine(paint, viewMatrix, srcRect, dstRect, aa, std::move(proxy), colorSpace,\n this->clip(), fRenderTargetContext.get());\n return;\n }\n GrTextureAdjuster adjuster(this->context(), std::move(proxy), alphaType, pinnedUniqueID,\n colorSpace);\n this->drawTextureProducer(&adjuster, srcRect, dstRect, constraint, viewMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureMaker(GrTextureMaker* maker, int imageW, int imageH,\n const SkRect* srcRect, const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix, const SkPaint& paint) {\n GrAA aa = GrAA(paint.isAntiAlias());\n if (can_use_draw_texture_affine(paint, aa, viewMatrix, constraint)) {\n sk_sp cs;\n \/\/ We've done enough checks above to allow us to pass ClampNearest() and not check for\n \/\/ scaling adjustments.\n auto proxy = maker->refTextureProxyForParams(\n GrSamplerState::ClampNearest(), fRenderTargetContext->colorSpaceInfo().colorSpace(),\n &cs, nullptr);\n if (!proxy) {\n return;\n }\n draw_texture_affine(paint, viewMatrix, srcRect, dstRect, aa, std::move(proxy), cs.get(),\n this->clip(), fRenderTargetContext.get());\n return;\n }\n this->drawTextureProducer(maker, srcRect, dstRect, constraint, viewMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureProducer(GrTextureProducer* producer,\n const SkRect* srcRect,\n const SkRect* dstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix,\n const SkPaint& paint) {\n \/\/ This is the funnel for all non-tiled bitmap\/image draw calls. Log a histogram entry.\n SK_HISTOGRAM_BOOLEAN(\"DrawTiled\", false);\n\n \/\/ Figure out the actual dst and src rect by clipping the src rect to the bounds of the\n \/\/ adjuster. If the src rect is clipped then the dst rect must be recomputed. Also determine\n \/\/ the matrix that maps the src rect to the dst rect.\n SkRect clippedSrcRect;\n SkRect clippedDstRect;\n const SkRect srcBounds = SkRect::MakeIWH(producer->width(), producer->height());\n SkMatrix srcToDstMatrix;\n if (srcRect) {\n if (!dstRect) {\n dstRect = &srcBounds;\n }\n if (!srcBounds.contains(*srcRect)) {\n clippedSrcRect = *srcRect;\n if (!clippedSrcRect.intersect(srcBounds)) {\n return;\n }\n if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n srcToDstMatrix.mapRect(&clippedDstRect, clippedSrcRect);\n } else {\n clippedSrcRect = *srcRect;\n clippedDstRect = *dstRect;\n if (!srcToDstMatrix.setRectToRect(*srcRect, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n }\n } else {\n clippedSrcRect = srcBounds;\n if (dstRect) {\n clippedDstRect = *dstRect;\n if (!srcToDstMatrix.setRectToRect(srcBounds, *dstRect, SkMatrix::kFill_ScaleToFit)) {\n return;\n }\n } else {\n clippedDstRect = srcBounds;\n srcToDstMatrix.reset();\n }\n }\n\n \/\/ Now that we have both the view and srcToDst matrices, log our scale factor.\n LogDrawScaleFactor(SkMatrix::Concat(viewMatrix, srcToDstMatrix), paint.getFilterQuality());\n\n this->drawTextureProducerImpl(producer, clippedSrcRect, clippedDstRect, constraint, viewMatrix,\n srcToDstMatrix, paint);\n}\n\nvoid SkGpuDevice::drawTextureProducerImpl(GrTextureProducer* producer,\n const SkRect& clippedSrcRect,\n const SkRect& clippedDstRect,\n SkCanvas::SrcRectConstraint constraint,\n const SkMatrix& viewMatrix,\n const SkMatrix& srcToDstMatrix,\n const SkPaint& paint) {\n \/\/ Specifying the texture coords as local coordinates is an attempt to enable more GrDrawOp\n \/\/ combining by not baking anything about the srcRect, dstRect, or viewMatrix, into the texture\n \/\/ FP. In the future this should be an opaque optimization enabled by the combination of\n \/\/ GrDrawOp\/GP and FP.\n const SkMaskFilter* mf = paint.getMaskFilter();\n \/\/ The shader expects proper local coords, so we can't replace local coords with texture coords\n \/\/ if the shader will be used. If we have a mask filter we will change the underlying geometry\n \/\/ that is rendered.\n bool canUseTextureCoordsAsLocalCoords = !use_shader(producer->isAlphaOnly(), paint) && !mf;\n\n bool doBicubic;\n GrSamplerState::Filter fm = GrSkFilterQualityToGrFilterMode(\n paint.getFilterQuality(), viewMatrix, srcToDstMatrix, &doBicubic);\n const GrSamplerState::Filter* filterMode = doBicubic ? nullptr : &fm;\n\n GrTextureProducer::FilterConstraint constraintMode;\n if (SkCanvas::kFast_SrcRectConstraint == constraint) {\n constraintMode = GrTextureAdjuster::kNo_FilterConstraint;\n } else {\n constraintMode = GrTextureAdjuster::kYes_FilterConstraint;\n }\n\n \/\/ If we have to outset for AA then we will generate texture coords outside the src rect. The\n \/\/ same happens for any mask filter that extends the bounds rendered in the dst.\n \/\/ This is conservative as a mask filter does not have to expand the bounds rendered.\n bool coordsAllInsideSrcRect = !paint.isAntiAlias() && !mf;\n\n \/\/ Check for optimization to drop the src rect constraint when on bilerp.\n if (filterMode && GrSamplerState::Filter::kBilerp == *filterMode &&\n GrTextureAdjuster::kYes_FilterConstraint == constraintMode && coordsAllInsideSrcRect) {\n SkMatrix combinedMatrix;\n combinedMatrix.setConcat(viewMatrix, srcToDstMatrix);\n if (can_ignore_bilerp_constraint(*producer, clippedSrcRect, combinedMatrix,\n fRenderTargetContext->fsaaType())) {\n constraintMode = GrTextureAdjuster::kNo_FilterConstraint;\n }\n }\n\n const SkMatrix* textureMatrix;\n SkMatrix tempMatrix;\n if (canUseTextureCoordsAsLocalCoords) {\n textureMatrix = &SkMatrix::I();\n } else {\n if (!srcToDstMatrix.invert(&tempMatrix)) {\n return;\n }\n textureMatrix = &tempMatrix;\n }\n auto fp = producer->createFragmentProcessor(\n *textureMatrix, clippedSrcRect, constraintMode, coordsAllInsideSrcRect, filterMode,\n fRenderTargetContext->colorSpaceInfo().colorSpace());\n if (!fp) {\n return;\n }\n\n GrPaint grPaint;\n if (!SkPaintToGrPaintWithTexture(fContext.get(), fRenderTargetContext->colorSpaceInfo(), paint,\n viewMatrix, std::move(fp), producer->isAlphaOnly(),\n &grPaint)) {\n return;\n }\n GrAA aa = GrAA(paint.isAntiAlias());\n if (canUseTextureCoordsAsLocalCoords) {\n fRenderTargetContext->fillRectToRect(this->clip(), std::move(grPaint), aa, viewMatrix,\n clippedDstRect, clippedSrcRect);\n return;\n }\n\n if (!mf) {\n fRenderTargetContext->drawRect(this->clip(), std::move(grPaint), aa, viewMatrix,\n clippedDstRect);\n return;\n }\n\n \/\/ First see if we can do the draw + mask filter direct to the dst.\n if (viewMatrix.isScaleTranslate()) {\n SkRect devClippedDstRect;\n viewMatrix.mapRectScaleTranslate(&devClippedDstRect, clippedDstRect);\n\n SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);\n if (mf->directFilterRRectMaskGPU(fContext.get(),\n fRenderTargetContext.get(),\n std::move(grPaint),\n this->clip(),\n viewMatrix,\n rec,\n SkRRect::MakeRect(clippedDstRect),\n SkRRect::MakeRect(devClippedDstRect))) {\n return;\n }\n }\n\n SkPath rectPath;\n rectPath.addRect(clippedDstRect);\n rectPath.setIsVolatile(true);\n GrBlurUtils::drawPathWithMaskFilter(this->context(), fRenderTargetContext.get(), this->clip(),\n rectPath, std::move(grPaint), aa, viewMatrix, mf,\n GrStyle::SimpleFill(), true);\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file flight_taks.h\n *\n * Library class to hold and manage all implemented flight task instances\n *\n * @author Matthias Grob \n *\/\n\n#pragma once\n\n#include \"tasks\/FlightTask.hpp\"\n#include \"tasks\/FlightTaskManual.hpp\"\n#include \"tasks\/FlightTaskOrbit.hpp\"\n\n#include \"SubscriptionArray.hpp\"\n\n#include \n\nclass FlightTasks : control::SuperBlock\n{\npublic:\n\tFlightTasks() :\n\t\tSuperBlock(nullptr, \"TSK\")\n\t{};\n\n\t~FlightTasks()\n\t{\n\t\tif (_current_task) {\n\t\t\t_current_task->~FlightTask();\n\t\t}\n\t};\n\n\t\/**\n\t * Call regularly in the control loop cycle to execute the task\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint update()\n\t{\n\t\tif (is_any_task_active()) {\n\t\t\t_subscription_array.update();\n\t\t\treturn _current_task->update();\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\t\/**\n\t * Get the output data from the current task\n\t *\/\n\tconst vehicle_local_position_setpoint_s &get_position_setpoint()\n\t{\n\t\treturn _current_task->get_position_setpoint();\n\t}\n\n\t\/**\n\t * Call this function initially to point all tasks to the general output data\n\t *\/\n\tinline const vehicle_local_position_setpoint_s &operator()()\n\t{\n\t\treturn get_position_setpoint();\n\t}\n\n\t\/**\n\t * Switch to the next task in the available list (for testing)\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint switch_task()\n\t{\n\t\treturn switch_task(_current_task_index + 1);\n\t}\n\n\t\/**\n\t * Switch to a specific task (for normal usage)\n\t * @param task number to switch to\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint switch_task(int task_number)\n\t{\n\t\t\/* switch to the running task, nothing to do *\/\n\t\tif (task_number == _current_task_index) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/* disable the old task if there is any *\/\n\t\tif (_current_task) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t}\n\n\t\tswitch (task_number) {\n\t\tcase 0:\n\t\t\t_current_task = new (&_task_union.manual) FlightTaskManual(this, \"MAN\");\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\t\t_current_task = new (&_task_union.orbit) FlightTaskOrbit(this, \"ORB\");\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/* invalid task *\/\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (!_current_task->initializeSubscriptions(_subscription_array)) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t\treturn -2;\n\t\t}\n\n\t\t_subscription_array.update();\n\n\t\tif (_current_task->activate()) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t\treturn -3;\n\t\t}\n\n\t\t_subscription_array.forcedUpdate(); \/\/ make sure data is available for all new subscriptions\n\n\t\t_current_task_index = task_number;\n\t\treturn 0;\n\t}\n\n\t\/**\n\t * Get the number of the active task\n\t * @return number of active task, -1 if there is none\n\t *\/\n\tint get_active_task() const { return _current_task_index; };\n\n\t\/**\n\t * Check if any task is active\n\t * @return true if a task is active, false if not\n\t *\/\n\tbool is_any_task_active() const { return _current_task; };\n\n\t\/**\n\t * Check if the task number exists\n\t * @return true if yes, false if not\n\t *\/\n\tbool is_task_number_valid(int task_number) const { return task_number > -1 && task_number < _task_count; };\n\nprivate:\n\tstatic constexpr int _task_count = 2;\n\n\t\/** union with all existing tasks: we use it to make sure that only the memory of the largest existing\n\t * task is needed, and to avoid using dynamic memory allocations.\n\t *\/\n\tunion TaskUnion {\n\t\tTaskUnion() {}\n\t\t~TaskUnion() {}\n\n\t\tFlightTaskManual manual;\n\t\tFlightTaskOrbit orbit;\n\t};\n\tTaskUnion _task_union; \/\/\/< storage for the currently active task\n\n\tFlightTask *_current_task = nullptr;\n\tint _current_task_index = -1;\n\n\tSubscriptionArray _subscription_array;\n};\nFlightTasks: use forced update just after initialization\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file flight_taks.h\n *\n * Library class to hold and manage all implemented flight task instances\n *\n * @author Matthias Grob \n *\/\n\n#pragma once\n\n#include \"tasks\/FlightTask.hpp\"\n#include \"tasks\/FlightTaskManual.hpp\"\n#include \"tasks\/FlightTaskOrbit.hpp\"\n\n#include \"SubscriptionArray.hpp\"\n\n#include \n\nclass FlightTasks : control::SuperBlock\n{\npublic:\n\tFlightTasks() :\n\t\tSuperBlock(nullptr, \"TSK\")\n\t{};\n\n\t~FlightTasks()\n\t{\n\t\tif (_current_task) {\n\t\t\t_current_task->~FlightTask();\n\t\t}\n\t};\n\n\t\/**\n\t * Call regularly in the control loop cycle to execute the task\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint update()\n\t{\n\t\tif (is_any_task_active()) {\n\t\t\t_subscription_array.update();\n\t\t\treturn _current_task->update();\n\t\t}\n\n\t\treturn 1;\n\t}\n\n\t\/**\n\t * Get the output data from the current task\n\t *\/\n\tconst vehicle_local_position_setpoint_s &get_position_setpoint()\n\t{\n\t\treturn _current_task->get_position_setpoint();\n\t}\n\n\t\/**\n\t * Call this function initially to point all tasks to the general output data\n\t *\/\n\tinline const vehicle_local_position_setpoint_s &operator()()\n\t{\n\t\treturn get_position_setpoint();\n\t}\n\n\t\/**\n\t * Switch to the next task in the available list (for testing)\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint switch_task()\n\t{\n\t\treturn switch_task(_current_task_index + 1);\n\t}\n\n\t\/**\n\t * Switch to a specific task (for normal usage)\n\t * @param task number to switch to\n\t * @return 0 on success, <0 on error\n\t *\/\n\tint switch_task(int task_number)\n\t{\n\t\t\/* switch to the running task, nothing to do *\/\n\t\tif (task_number == _current_task_index) {\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/* disable the old task if there is any *\/\n\t\tif (_current_task) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t}\n\n\t\tswitch (task_number) {\n\t\tcase 0:\n\t\t\t_current_task = new (&_task_union.manual) FlightTaskManual(this, \"MAN\");\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\t\t_current_task = new (&_task_union.orbit) FlightTaskOrbit(this, \"ORB\");\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\t\/* invalid task *\/\n\t\t\treturn -1;\n\t\t}\n\n\t\tif (!_current_task->initializeSubscriptions(_subscription_array)) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t\treturn -2;\n\t\t}\n\n\t\t_subscription_array.forcedUpdate(); \/\/ make sure data is available for all new subscriptions\n\n\t\tif (_current_task->activate()) {\n\t\t\t_current_task->~FlightTask();\n\t\t\t_current_task = nullptr;\n\t\t\t_current_task_index = -1;\n\t\t\treturn -3;\n\t\t}\n\n\t\t_current_task_index = task_number;\n\t\treturn 0;\n\t}\n\n\t\/**\n\t * Get the number of the active task\n\t * @return number of active task, -1 if there is none\n\t *\/\n\tint get_active_task() const { return _current_task_index; };\n\n\t\/**\n\t * Check if any task is active\n\t * @return true if a task is active, false if not\n\t *\/\n\tbool is_any_task_active() const { return _current_task; };\n\n\t\/**\n\t * Check if the task number exists\n\t * @return true if yes, false if not\n\t *\/\n\tbool is_task_number_valid(int task_number) const { return task_number > -1 && task_number < _task_count; };\n\nprivate:\n\tstatic constexpr int _task_count = 2;\n\n\t\/** union with all existing tasks: we use it to make sure that only the memory of the largest existing\n\t * task is needed, and to avoid using dynamic memory allocations.\n\t *\/\n\tunion TaskUnion {\n\t\tTaskUnion() {}\n\t\t~TaskUnion() {}\n\n\t\tFlightTaskManual manual;\n\t\tFlightTaskOrbit orbit;\n\t};\n\tTaskUnion _task_union; \/\/\/< storage for the currently active task\n\n\tFlightTask *_current_task = nullptr;\n\tint _current_task_index = -1;\n\n\tSubscriptionArray _subscription_array;\n};\n<|endoftext|>"} {"text":"\/*\n*\n* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* iot_support at tid dot es\n*\n* Author: Orion dev team\n*\/\n#include \n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"common\/globals.h\"\n#include \"common\/clockFunctions.h\"\n#include \"common\/statistics.h\"\n#include \"common\/limits.h\"\n#include \"common\/logTracing.h\"\n#include \"alarmMgr\/alarmMgr.h\"\n\n#include \"cache\/subCache.h\"\n#include \"ngsi10\/NotifyContextRequest.h\"\n#include \"rest\/httpRequestSend.h\"\n#include \"ngsiNotify\/QueueStatistics.h\"\n#include \"ngsiNotify\/QueueWorkers.h\"\n\n\n\n\/* ****************************************************************************\n*\n* workerFunc - prototype\n*\/\nstatic void* workerFunc(void* pSyncQ);\n\n\n\n\/* ****************************************************************************\n*\n* QueueWorkers::start() -\n*\/\nint QueueWorkers::start()\n{\n for (int i = 0; i < numberOfThreads; ++i)\n {\n pthread_t tid;\n int rc = pthread_create(&tid, NULL, workerFunc, pQueue);\n\n if (rc != 0)\n {\n LM_E((\"Internal Error (pthread_create: %s)\", strerror(errno)));\n return rc;\n }\n threadIds.push_back(tid);\n }\n\n return 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* QueueWorkers::stop() -\n*\/\nint QueueWorkers::stop()\n{\n for (unsigned int ix = 0; ix < threadIds.size(); ++ix)\n {\n \/\/ FIXME PR: insert comment\n if (pthread_cancel(threadIds[ix]) != 0)\n {\n return -1;\n }\n pthread_join(threadIds[ix], NULL);\n }\n\n return 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* workerFinish -\n*\n* This is invoked upon worker thread termination (typically using pthread_cancel on it)\n*\/\nstatic void workerFinishes(void* curl)\n{\n curl_easy_cleanup((CURL*) curl);\n}\n\n\n\n\/* ****************************************************************************\n*\n* workerFunc -\n*\/\nstatic void* workerFunc(void* pSyncQ)\n{\n SyncQOverflow*>* queue = (SyncQOverflow*> *) pSyncQ;\n CURL* curl;\n\n \/\/ Initialize curl context\n curl = curl_easy_init();\n\n if (curl == NULL)\n {\n LM_E((\"Runtime Error (curl_easy_init)\"));\n pthread_exit(NULL);\n }\n\n \/\/ FIXME PR: insert comment\n \/\/ See: https:\/\/stackoverflow.com\/questions\/67872576\/pthread-join-doesnt-return-on-a-just-cancelled-thread-with-pthread-cancel?noredirect=1#comment119968712_67872576\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);\n\n \/\/ Set pthread_cancel handler\n pthread_cleanup_push(workerFinishes, curl);\n\n for (;;)\n {\n std::vector* paramsV = queue->pop();\n\n for (unsigned ix = 0; ix < paramsV->size(); ix++)\n {\n struct timespec now;\n struct timespec howlong;\n size_t estimatedQSize;\n\n SenderThreadParams* params = (*paramsV)[ix];\n\n QueueStatistics::incOut();\n clock_gettime(CLOCK_REALTIME, &now);\n clock_difftime(&now, ¶ms->timeStamp, &howlong);\n estimatedQSize = queue->size();\n QueueStatistics::addTimeInQWithSize(&howlong, estimatedQSize);\n\n strncpy(transactionId, params->transactionId, sizeof(transactionId));\n\n LM_T(LmtNotifier, (\"worker sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s\",\n params->ip.c_str(),\n params->port,\n params->verb.c_str(),\n params->tenant.c_str(),\n params->servicePath.c_str(),\n params->xauthToken.c_str(),\n params->resource.c_str(),\n params->content_type.c_str()));\n\n char portV[STRING_SIZE_FOR_INT];\n std::string url;\n\n snprintf(portV, sizeof(portV), \"%d\", params->port);\n url = params->ip + \":\" + portV + params->resource;\n\n long long statusCode = -1;\n std::string out;\n\n if (simulatedNotification)\n {\n LM_T(LmtNotifier, (\"simulatedNotification is 'true', skipping outgoing request\"));\n __sync_fetch_and_add(&noOfSimulatedNotifications, 1);\n }\n else \/\/ we'll send the notification\n {\n int r;\n\n r = httpRequestSendWithCurl(curl,\n params->from,\n params->ip,\n params->port,\n params->protocol,\n params->verb,\n params->tenant,\n params->servicePath,\n params->xauthToken,\n params->resource,\n params->content_type,\n params->content,\n params->fiwareCorrelator,\n params->renderFormat,\n &out,\n &statusCode,\n params->extraHeaders);\n\n \/\/\n \/\/ FIXME: ok and error counter should be incremented in the other notification modes (generalizing the concept, i.e.\n \/\/ not as member of QueueStatistics:: which seems to be tied to just the threadpool notification mode)\n \/\/\n if (r == 0)\n {\n __sync_fetch_and_add(&noOfNotificationsSent, 1);\n QueueStatistics::incSentOK();\n alarmMgr.notificationErrorReset(url);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, \"\");\n }\n }\n else\n {\n QueueStatistics::incSentError();\n alarmMgr.notificationError(url, \"notification failure for queue worker: \" + out);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 1, -1, out);\n }\n }\n }\n\n \/\/ Add notificacion result summary in log INFO level\n if (statusCode != -1)\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);\n }\n else\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());\n }\n\n \/\/ End transaction\n lmTransactionEnd();\n\n \/\/ Free params memory\n delete params;\n }\n\n \/\/ Free params vector memory\n delete paramsV;\n\n \/\/ Reset curl for next iteration\n curl_easy_reset(curl);\n }\n\n \/\/ Next statemement never executes but compilation breaks without it. See this note in pthread.h:\n \/\/ \"pthread_cleanup_push and pthread_cleanup_pop are macros and must always be used in\n \/\/ matching pairs at the same nesting level of braces\".\n pthread_cleanup_pop(0);\n}\nFIX improve code comments\/*\n*\n* Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U\n*\n* This file is part of Orion Context Broker.\n*\n* Orion Context Broker is free software: you can redistribute it and\/or\n* modify it under the terms of the GNU Affero General Public License as\n* published by the Free Software Foundation, either version 3 of the\n* License, or (at your option) any later version.\n*\n* Orion Context Broker is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero\n* General Public License for more details.\n*\n* You should have received a copy of the GNU Affero General Public License\n* along with Orion Context Broker. If not, see http:\/\/www.gnu.org\/licenses\/.\n*\n* For those usages not covered by this license please contact with\n* iot_support at tid dot es\n*\n* Author: Orion dev team\n*\/\n#include \n\n#include \"logMsg\/logMsg.h\"\n#include \"logMsg\/traceLevels.h\"\n\n#include \"common\/globals.h\"\n#include \"common\/clockFunctions.h\"\n#include \"common\/statistics.h\"\n#include \"common\/limits.h\"\n#include \"common\/logTracing.h\"\n#include \"alarmMgr\/alarmMgr.h\"\n\n#include \"cache\/subCache.h\"\n#include \"ngsi10\/NotifyContextRequest.h\"\n#include \"rest\/httpRequestSend.h\"\n#include \"ngsiNotify\/QueueStatistics.h\"\n#include \"ngsiNotify\/QueueWorkers.h\"\n\n\n\n\/* ****************************************************************************\n*\n* workerFunc - prototype\n*\/\nstatic void* workerFunc(void* pSyncQ);\n\n\n\n\/* ****************************************************************************\n*\n* QueueWorkers::start() -\n*\/\nint QueueWorkers::start()\n{\n for (int i = 0; i < numberOfThreads; ++i)\n {\n pthread_t tid;\n int rc = pthread_create(&tid, NULL, workerFunc, pQueue);\n\n if (rc != 0)\n {\n LM_E((\"Internal Error (pthread_create: %s)\", strerror(errno)));\n return rc;\n }\n threadIds.push_back(tid);\n }\n\n return 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* QueueWorkers::stop() -\n*\/\nint QueueWorkers::stop()\n{\n for (unsigned int ix = 0; ix < threadIds.size(); ++ix)\n {\n \/\/ FIXME #3877: this is not the best way of cancelling a thread in our case.\n \/\/ By the moment is not a problem (as the release is done only during the process\n \/\/ tear down phase) but if this gets dynamic at some moment (creation\/destroying\n \/\/ pools by API) it needs to be changed\n if (pthread_cancel(threadIds[ix]) != 0)\n {\n return -1;\n }\n pthread_join(threadIds[ix], NULL);\n }\n\n return 0;\n}\n\n\n\n\/* ****************************************************************************\n*\n* workerFinish -\n*\n* This is invoked upon worker thread termination (typically using pthread_cancel on it)\n*\/\nstatic void workerFinishes(void* curl)\n{\n curl_easy_cleanup((CURL*) curl);\n}\n\n\n\n\/* ****************************************************************************\n*\n* workerFunc -\n*\/\nstatic void* workerFunc(void* pSyncQ)\n{\n SyncQOverflow*>* queue = (SyncQOverflow*> *) pSyncQ;\n CURL* curl;\n\n \/\/ Initialize curl context\n curl = curl_easy_init();\n\n if (curl == NULL)\n {\n LM_E((\"Runtime Error (curl_easy_init)\"));\n pthread_exit(NULL);\n }\n\n \/\/ FIXME #3877: this is not the best way of cancelling a thread in our case.\n \/\/ By the moment is not a problem (as the release is done only during the process\n \/\/ tear down phase) but if this gets dynamic at some moment (creation\/destroying\n \/\/ pools by API) it needs to be changed\n pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);\n\n \/\/ Set pthread_cancel handler\n pthread_cleanup_push(workerFinishes, curl);\n\n for (;;)\n {\n std::vector* paramsV = queue->pop();\n\n for (unsigned ix = 0; ix < paramsV->size(); ix++)\n {\n struct timespec now;\n struct timespec howlong;\n size_t estimatedQSize;\n\n SenderThreadParams* params = (*paramsV)[ix];\n\n QueueStatistics::incOut();\n clock_gettime(CLOCK_REALTIME, &now);\n clock_difftime(&now, ¶ms->timeStamp, &howlong);\n estimatedQSize = queue->size();\n QueueStatistics::addTimeInQWithSize(&howlong, estimatedQSize);\n\n strncpy(transactionId, params->transactionId, sizeof(transactionId));\n\n LM_T(LmtNotifier, (\"worker sending to: host='%s', port=%d, verb=%s, tenant='%s', service-path: '%s', xauthToken: '%s', path='%s', content-type: %s\",\n params->ip.c_str(),\n params->port,\n params->verb.c_str(),\n params->tenant.c_str(),\n params->servicePath.c_str(),\n params->xauthToken.c_str(),\n params->resource.c_str(),\n params->content_type.c_str()));\n\n char portV[STRING_SIZE_FOR_INT];\n std::string url;\n\n snprintf(portV, sizeof(portV), \"%d\", params->port);\n url = params->ip + \":\" + portV + params->resource;\n\n long long statusCode = -1;\n std::string out;\n\n if (simulatedNotification)\n {\n LM_T(LmtNotifier, (\"simulatedNotification is 'true', skipping outgoing request\"));\n __sync_fetch_and_add(&noOfSimulatedNotifications, 1);\n }\n else \/\/ we'll send the notification\n {\n int r;\n\n r = httpRequestSendWithCurl(curl,\n params->from,\n params->ip,\n params->port,\n params->protocol,\n params->verb,\n params->tenant,\n params->servicePath,\n params->xauthToken,\n params->resource,\n params->content_type,\n params->content,\n params->fiwareCorrelator,\n params->renderFormat,\n &out,\n &statusCode,\n params->extraHeaders);\n\n \/\/\n \/\/ FIXME: ok and error counter should be incremented in the other notification modes (generalizing the concept, i.e.\n \/\/ not as member of QueueStatistics:: which seems to be tied to just the threadpool notification mode)\n \/\/\n if (r == 0)\n {\n __sync_fetch_and_add(&noOfNotificationsSent, 1);\n QueueStatistics::incSentOK();\n alarmMgr.notificationErrorReset(url);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 0, statusCode, \"\");\n }\n }\n else\n {\n QueueStatistics::incSentError();\n alarmMgr.notificationError(url, \"notification failure for queue worker: \" + out);\n\n if (params->registration == false)\n {\n subNotificationErrorStatus(params->tenant, params->subscriptionId, 1, -1, out);\n }\n }\n }\n\n \/\/ Add notificacion result summary in log INFO level\n if (statusCode != -1)\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), statusCode);\n }\n else\n {\n logInfoNotification(params->subscriptionId.c_str(), params->verb.c_str(), url.c_str(), out.c_str());\n }\n\n \/\/ End transaction\n lmTransactionEnd();\n\n \/\/ Free params memory\n delete params;\n }\n\n \/\/ Free params vector memory\n delete paramsV;\n\n \/\/ Reset curl for next iteration\n curl_easy_reset(curl);\n }\n\n \/\/ Next statement never executes but compilation breaks without it. See this note in pthread.h:\n \/\/ \"pthread_cleanup_push and pthread_cleanup_pop are macros and must always be used in\n \/\/ matching pairs at the same nesting level of braces\".\n pthread_cleanup_pop(0);\n}\n<|endoftext|>"} {"text":"\/*\nThis file is part of BGSLibrary.\n\nBGSLibrary is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nBGSLibrary is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with BGSLibrary. If not, see .\n*\/\n#include \n#include \n\n\n#include \"package_bgs\/FrameDifferenceBGS.h\"\n#include \"package_bgs\/StaticFrameDifferenceBGS.h\"\n#include \"package_bgs\/WeightedMovingMeanBGS.h\"\n#include \"package_bgs\/WeightedMovingVarianceBGS.h\"\n#include \"package_bgs\/MixtureOfGaussianV1BGS.h\"\n#include \"package_bgs\/MixtureOfGaussianV2BGS.h\"\n#include \"package_bgs\/AdaptiveBackgroundLearning.h\"\n#include \"package_bgs\/AdaptiveSelectiveBackgroundLearning.h\"\n\n#if CV_MAJOR_VERSION >= 2 && CV_MINOR_VERSION >= 4 && CV_SUBMINOR_VERSION >= 3\n#include \"package_bgs\/GMG.h\"\n#endif\n\n#include \"package_bgs\/dp\/DPAdaptiveMedianBGS.h\"\n#include \"package_bgs\/dp\/DPGrimsonGMMBGS.h\"\n#include \"package_bgs\/dp\/DPZivkovicAGMMBGS.h\"\n#include \"package_bgs\/dp\/DPMeanBGS.h\"\n#include \"package_bgs\/dp\/DPWrenGABGS.h\"\n#include \"package_bgs\/dp\/DPPratiMediodBGS.h\"\n#include \"package_bgs\/dp\/DPEigenbackgroundBGS.h\"\n#include \"package_bgs\/dp\/DPTextureBGS.h\"\n\n#include \"package_bgs\/tb\/T2FGMM_UM.h\"\n#include \"package_bgs\/tb\/T2FGMM_UV.h\"\n#include \"package_bgs\/tb\/T2FMRF_UM.h\"\n#include \"package_bgs\/tb\/T2FMRF_UV.h\"\n#include \"package_bgs\/tb\/FuzzySugenoIntegral.h\"\n#include \"package_bgs\/tb\/FuzzyChoquetIntegral.h\"\n\n#include \"package_bgs\/lb\/LBSimpleGaussian.h\"\n#include \"package_bgs\/lb\/LBFuzzyGaussian.h\"\n#include \"package_bgs\/lb\/LBMixtureOfGaussians.h\"\n#include \"package_bgs\/lb\/LBAdaptiveSOM.h\"\n#include \"package_bgs\/lb\/LBFuzzyAdaptiveSOM.h\"\n\n#include \"package_bgs\/ck\/LbpMrf.h\"\n#include \"package_bgs\/jmo\/MultiLayerBGS.h\"\n\/\/ The PBAS algorithm was removed from BGSLibrary because it is\n\/\/ based on patented algorithm ViBE\n\/\/ http:\/\/www2.ulg.ac.be\/telecom\/research\/vibe\/\n\/\/#include \"package_bgs\/pt\/PixelBasedAdaptiveSegmenter.h\"\n#include \"package_bgs\/av\/VuMeter.h\"\n#include \"package_bgs\/ae\/KDE.h\"\n#include \"package_bgs\/db\/IndependentMultimodalBGS.h\"\n#include \"package_bgs\/sjn\/SJN_MultiCueBGS.h\"\n#include \"package_bgs\/bl\/SigmaDeltaBGS.h\"\n\n#include \"package_bgs\/pl\/SuBSENSE.h\"\n#include \"package_bgs\/pl\/LOBSTER.h\"\n\nint main(int argc, char **argv)\n{\n std::cout << \"Using OpenCV \" << CV_MAJOR_VERSION << \".\" << CV_MINOR_VERSION << \".\" << CV_SUBMINOR_VERSION << std::endl;\n\n CvCapture *capture = 0;\n int resize_factor = 100;\n\n if(argc > 1)\n {\n std::cout << \"Openning: \" << argv[1] << std::endl;\n capture = cvCaptureFromAVI(argv[1]);\n }\n else\n {\n capture = cvCaptureFromCAM(0);\n resize_factor = 50; \/\/ set size = 50% of original image\n }\n\n if(!capture)\n {\n std::cerr << \"Cannot initialize video!\" << std::endl;\n return -1;\n }\n \n IplImage *frame_aux = cvQueryFrame(capture);\n IplImage *frame = cvCreateImage(cvSize((int)((frame_aux->width*resize_factor)\/100) , (int)((frame_aux->height*resize_factor)\/100)), frame_aux->depth, frame_aux->nChannels);\n cvResize(frame_aux, frame);\n\n \/* Background Subtraction Methods *\/\n IBGS *bgs;\n\n \/*** Default Package ***\/\n bgs = new FrameDifferenceBGS;\n \/\/bgs = new StaticFrameDifferenceBGS;\n \/\/bgs = new WeightedMovingMeanBGS;\n \/\/bgs = new WeightedMovingVarianceBGS;\n \/\/bgs = new MixtureOfGaussianV1BGS;\n \/\/bgs = new MixtureOfGaussianV2BGS;\n \/\/bgs = new AdaptiveBackgroundLearning;\n \/\/bgs = new AdaptiveSelectiveBackgroundLearning;\n \/\/bgs = new GMG;\n \n \/*** DP Package (thanks to Donovan Parks) ***\/\n \/\/bgs = new DPAdaptiveMedianBGS;\n \/\/bgs = new DPGrimsonGMMBGS;\n \/\/bgs = new DPZivkovicAGMMBGS;\n \/\/bgs = new DPMeanBGS;\n \/\/bgs = new DPWrenGABGS;\n \/\/bgs = new DPPratiMediodBGS;\n \/\/bgs = new DPEigenbackgroundBGS;\n \/\/bgs = new DPTextureBGS;\n\n \/*** TB Package (thanks to Thierry Bouwmans, Fida EL BAF and Zhenjie Zhao) ***\/\n \/\/bgs = new T2FGMM_UM;\n \/\/bgs = new T2FGMM_UV;\n \/\/bgs = new T2FMRF_UM;\n \/\/bgs = new T2FMRF_UV;\n \/\/bgs = new FuzzySugenoIntegral;\n \/\/bgs = new FuzzyChoquetIntegral;\n\n \/*** JMO Package (thanks to Jean-Marc Odobez) ***\/\n \/\/bgs = new MultiLayerBGS;\n\n \/*** PT Package (thanks to Martin Hofmann, Philipp Tiefenbacher and Gerhard Rigoll) ***\/\n \/\/bgs = new PixelBasedAdaptiveSegmenter;\n\n \/*** LB Package (thanks to Laurence Bender) ***\/\n \/\/bgs = new LBSimpleGaussian;\n \/\/bgs = new LBFuzzyGaussian;\n \/\/bgs = new LBMixtureOfGaussians;\n \/\/bgs = new LBAdaptiveSOM;\n \/\/bgs = new LBFuzzyAdaptiveSOM;\n\n \/*** LBP-MRF Package (thanks to Csaba Kertész) ***\/\n \/\/bgs = new LbpMrf;\n\n \/*** AV Package (thanks to Lionel Robinault and Antoine Vacavant) ***\/\n \/\/bgs = new VuMeter;\n\n \/*** EG Package (thanks to Ahmed Elgammal) ***\/\n \/\/bgs = new KDE;\n \n \/*** DB Package (thanks to Domenico Daniele Bloisi) ***\/\n \/\/bgs = new IndependentMultimodalBGS;\n\n \/*** SJN Package (thanks to SeungJong Noh) ***\/\n \/\/bgs = new SJN_MultiCueBGS;\n\n \/*** BL Package (thanks to Benjamin Laugraud) ***\/\n \/\/bgs = new SigmaDeltaBGS;\n\n \/*** PL Package ***\/\n \/\/bgs = new SuBSENSEBGS();\n \/\/bgs = new LOBSTERBGS();\n\n int key = 0;\n while(key != 'q')\n {\n frame_aux = cvQueryFrame(capture);\n if(!frame_aux) break;\n\n cvResize(frame_aux, frame);\n \n cv::Mat img_input(frame);\n cv::imshow(\"input\", img_input);\n\n cv::Mat img_mask;\n cv::Mat img_bkgmodel;\n bgs->process(img_input, img_mask, img_bkgmodel); \/\/ by default, it shows automatically the foreground mask image\n \n \/\/if(!img_mask.empty())\n \/\/ cv::imshow(\"Foreground\", img_mask);\n \/\/ do something\n \n key = cvWaitKey(33);\n }\n\n delete bgs;\n\n cvDestroyAllWindows();\n cvReleaseCapture(&capture);\n\n return 0;\n}\nminor mod (added thank you note)\/*\nThis file is part of BGSLibrary.\n\nBGSLibrary is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nBGSLibrary is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with BGSLibrary. If not, see .\n*\/\n#include \n#include \n\n\n#include \"package_bgs\/FrameDifferenceBGS.h\"\n#include \"package_bgs\/StaticFrameDifferenceBGS.h\"\n#include \"package_bgs\/WeightedMovingMeanBGS.h\"\n#include \"package_bgs\/WeightedMovingVarianceBGS.h\"\n#include \"package_bgs\/MixtureOfGaussianV1BGS.h\"\n#include \"package_bgs\/MixtureOfGaussianV2BGS.h\"\n#include \"package_bgs\/AdaptiveBackgroundLearning.h\"\n#include \"package_bgs\/AdaptiveSelectiveBackgroundLearning.h\"\n\n#if CV_MAJOR_VERSION >= 2 && CV_MINOR_VERSION >= 4 && CV_SUBMINOR_VERSION >= 3\n#include \"package_bgs\/GMG.h\"\n#endif\n\n#include \"package_bgs\/dp\/DPAdaptiveMedianBGS.h\"\n#include \"package_bgs\/dp\/DPGrimsonGMMBGS.h\"\n#include \"package_bgs\/dp\/DPZivkovicAGMMBGS.h\"\n#include \"package_bgs\/dp\/DPMeanBGS.h\"\n#include \"package_bgs\/dp\/DPWrenGABGS.h\"\n#include \"package_bgs\/dp\/DPPratiMediodBGS.h\"\n#include \"package_bgs\/dp\/DPEigenbackgroundBGS.h\"\n#include \"package_bgs\/dp\/DPTextureBGS.h\"\n\n#include \"package_bgs\/tb\/T2FGMM_UM.h\"\n#include \"package_bgs\/tb\/T2FGMM_UV.h\"\n#include \"package_bgs\/tb\/T2FMRF_UM.h\"\n#include \"package_bgs\/tb\/T2FMRF_UV.h\"\n#include \"package_bgs\/tb\/FuzzySugenoIntegral.h\"\n#include \"package_bgs\/tb\/FuzzyChoquetIntegral.h\"\n\n#include \"package_bgs\/lb\/LBSimpleGaussian.h\"\n#include \"package_bgs\/lb\/LBFuzzyGaussian.h\"\n#include \"package_bgs\/lb\/LBMixtureOfGaussians.h\"\n#include \"package_bgs\/lb\/LBAdaptiveSOM.h\"\n#include \"package_bgs\/lb\/LBFuzzyAdaptiveSOM.h\"\n\n#include \"package_bgs\/ck\/LbpMrf.h\"\n#include \"package_bgs\/jmo\/MultiLayerBGS.h\"\n\/\/ The PBAS algorithm was removed from BGSLibrary because it is\n\/\/ based on patented algorithm ViBE\n\/\/ http:\/\/www2.ulg.ac.be\/telecom\/research\/vibe\/\n\/\/#include \"package_bgs\/pt\/PixelBasedAdaptiveSegmenter.h\"\n#include \"package_bgs\/av\/VuMeter.h\"\n#include \"package_bgs\/ae\/KDE.h\"\n#include \"package_bgs\/db\/IndependentMultimodalBGS.h\"\n#include \"package_bgs\/sjn\/SJN_MultiCueBGS.h\"\n#include \"package_bgs\/bl\/SigmaDeltaBGS.h\"\n\n#include \"package_bgs\/pl\/SuBSENSE.h\"\n#include \"package_bgs\/pl\/LOBSTER.h\"\n\nint main(int argc, char **argv)\n{\n std::cout << \"Using OpenCV \" << CV_MAJOR_VERSION << \".\" << CV_MINOR_VERSION << \".\" << CV_SUBMINOR_VERSION << std::endl;\n\n CvCapture *capture = 0;\n int resize_factor = 100;\n\n if(argc > 1)\n {\n std::cout << \"Openning: \" << argv[1] << std::endl;\n capture = cvCaptureFromAVI(argv[1]);\n }\n else\n {\n capture = cvCaptureFromCAM(0);\n resize_factor = 50; \/\/ set size = 50% of original image\n }\n\n if(!capture)\n {\n std::cerr << \"Cannot initialize video!\" << std::endl;\n return -1;\n }\n \n IplImage *frame_aux = cvQueryFrame(capture);\n IplImage *frame = cvCreateImage(cvSize((int)((frame_aux->width*resize_factor)\/100) , (int)((frame_aux->height*resize_factor)\/100)), frame_aux->depth, frame_aux->nChannels);\n cvResize(frame_aux, frame);\n\n \/* Background Subtraction Methods *\/\n IBGS *bgs;\n\n \/*** Default Package ***\/\n bgs = new FrameDifferenceBGS;\n \/\/bgs = new StaticFrameDifferenceBGS;\n \/\/bgs = new WeightedMovingMeanBGS;\n \/\/bgs = new WeightedMovingVarianceBGS;\n \/\/bgs = new MixtureOfGaussianV1BGS;\n \/\/bgs = new MixtureOfGaussianV2BGS;\n \/\/bgs = new AdaptiveBackgroundLearning;\n \/\/bgs = new AdaptiveSelectiveBackgroundLearning;\n \/\/bgs = new GMG;\n \n \/*** DP Package (thanks to Donovan Parks) ***\/\n \/\/bgs = new DPAdaptiveMedianBGS;\n \/\/bgs = new DPGrimsonGMMBGS;\n \/\/bgs = new DPZivkovicAGMMBGS;\n \/\/bgs = new DPMeanBGS;\n \/\/bgs = new DPWrenGABGS;\n \/\/bgs = new DPPratiMediodBGS;\n \/\/bgs = new DPEigenbackgroundBGS;\n \/\/bgs = new DPTextureBGS;\n\n \/*** TB Package (thanks to Thierry Bouwmans, Fida EL BAF and Zhenjie Zhao) ***\/\n \/\/bgs = new T2FGMM_UM;\n \/\/bgs = new T2FGMM_UV;\n \/\/bgs = new T2FMRF_UM;\n \/\/bgs = new T2FMRF_UV;\n \/\/bgs = new FuzzySugenoIntegral;\n \/\/bgs = new FuzzyChoquetIntegral;\n\n \/*** JMO Package (thanks to Jean-Marc Odobez) ***\/\n \/\/bgs = new MultiLayerBGS;\n\n \/*** PT Package (thanks to Martin Hofmann, Philipp Tiefenbacher and Gerhard Rigoll) ***\/\n \/\/bgs = new PixelBasedAdaptiveSegmenter;\n\n \/*** LB Package (thanks to Laurence Bender) ***\/\n \/\/bgs = new LBSimpleGaussian;\n \/\/bgs = new LBFuzzyGaussian;\n \/\/bgs = new LBMixtureOfGaussians;\n \/\/bgs = new LBAdaptiveSOM;\n \/\/bgs = new LBFuzzyAdaptiveSOM;\n\n \/*** LBP-MRF Package (thanks to Csaba Kertész) ***\/\n \/\/bgs = new LbpMrf;\n\n \/*** AV Package (thanks to Lionel Robinault and Antoine Vacavant) ***\/\n \/\/bgs = new VuMeter;\n\n \/*** EG Package (thanks to Ahmed Elgammal) ***\/\n \/\/bgs = new KDE;\n \n \/*** DB Package (thanks to Domenico Daniele Bloisi) ***\/\n \/\/bgs = new IndependentMultimodalBGS;\n\n \/*** SJN Package (thanks to SeungJong Noh) ***\/\n \/\/bgs = new SJN_MultiCueBGS;\n\n \/*** BL Package (thanks to Benjamin Laugraud) ***\/\n \/\/bgs = new SigmaDeltaBGS;\n\n \/*** PL Package (thanks to Pierre-Luc) ***\/\n \/\/bgs = new SuBSENSEBGS();\n \/\/bgs = new LOBSTERBGS();\n\n int key = 0;\n while(key != 'q')\n {\n frame_aux = cvQueryFrame(capture);\n if(!frame_aux) break;\n\n cvResize(frame_aux, frame);\n \n cv::Mat img_input(frame);\n cv::imshow(\"input\", img_input);\n\n cv::Mat img_mask;\n cv::Mat img_bkgmodel;\n bgs->process(img_input, img_mask, img_bkgmodel); \/\/ by default, it shows automatically the foreground mask image\n \n \/\/if(!img_mask.empty())\n \/\/ cv::imshow(\"Foreground\", img_mask);\n \/\/ do something\n \n key = cvWaitKey(33);\n }\n\n delete bgs;\n\n cvDestroyAllWindows();\n cvReleaseCapture(&capture);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"default-platform.h\"\n\n#include \n\n\/\/ TODO(jochen): We should have our own version of checks.h.\n#include \"..\/checks.h\"\n\/\/ TODO(jochen): Why is cpu.h not in platform\/?\n#include \"..\/cpu.h\"\n#include \"worker-thread.h\"\n\nnamespace v8 {\nnamespace internal {\n\n\nDefaultPlatform::DefaultPlatform()\n : initialized_(false), thread_pool_size_(0) {}\n\n\nDefaultPlatform::~DefaultPlatform() {\n LockGuard guard(&lock_);\n if (initialized_) {\n queue_.Terminate();\n for (std::vector::iterator i = thread_pool_.begin();\n i != thread_pool_.end(); ++i) {\n delete *i;\n }\n }\n}\n\n\nvoid DefaultPlatform::SetThreadPoolSize(int thread_pool_size) {\n LockGuard guard(&lock_);\n ASSERT(thread_pool_size >= 0);\n if (thread_pool_size < 1)\n thread_pool_size = CPU::NumberOfProcessorsOnline();\n thread_pool_size_ = Max(Min(thread_pool_size, kMaxThreadPoolSize), 1);\n}\n\n\nvoid DefaultPlatform::EnsureInitialized() {\n LockGuard guard(&lock_);\n if (initialized_) return;\n initialized_ = true;\n\n for (int i = 0; i < thread_pool_size_; ++i)\n thread_pool_.push_back(new WorkerThread(&queue_));\n}\n\nvoid DefaultPlatform::CallOnBackgroundThread(Task *task,\n ExpectedRuntime expected_runtime) {\n EnsureInitialized();\n queue_.Append(task);\n}\n\n\nvoid DefaultPlatform::CallOnForegroundThread(v8::Isolate* isolate, Task* task) {\n \/\/ TODO(jochen): implement.\n task->Run();\n delete task;\n}\n\n} } \/\/ namespace v8::internal\nAlways terminate the task queue\/\/ Copyright 2013 the V8 project authors. All rights reserved.\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following\n\/\/ disclaimer in the documentation and\/or other materials provided\n\/\/ with the distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include \"default-platform.h\"\n\n#include \n\n\/\/ TODO(jochen): We should have our own version of checks.h.\n#include \"..\/checks.h\"\n\/\/ TODO(jochen): Why is cpu.h not in platform\/?\n#include \"..\/cpu.h\"\n#include \"worker-thread.h\"\n\nnamespace v8 {\nnamespace internal {\n\n\nDefaultPlatform::DefaultPlatform()\n : initialized_(false), thread_pool_size_(0) {}\n\n\nDefaultPlatform::~DefaultPlatform() {\n LockGuard guard(&lock_);\n queue_.Terminate();\n if (initialized_) {\n for (std::vector::iterator i = thread_pool_.begin();\n i != thread_pool_.end(); ++i) {\n delete *i;\n }\n }\n}\n\n\nvoid DefaultPlatform::SetThreadPoolSize(int thread_pool_size) {\n LockGuard guard(&lock_);\n ASSERT(thread_pool_size >= 0);\n if (thread_pool_size < 1)\n thread_pool_size = CPU::NumberOfProcessorsOnline();\n thread_pool_size_ = Max(Min(thread_pool_size, kMaxThreadPoolSize), 1);\n}\n\n\nvoid DefaultPlatform::EnsureInitialized() {\n LockGuard guard(&lock_);\n if (initialized_) return;\n initialized_ = true;\n\n for (int i = 0; i < thread_pool_size_; ++i)\n thread_pool_.push_back(new WorkerThread(&queue_));\n}\n\nvoid DefaultPlatform::CallOnBackgroundThread(Task *task,\n ExpectedRuntime expected_runtime) {\n EnsureInitialized();\n queue_.Append(task);\n}\n\n\nvoid DefaultPlatform::CallOnForegroundThread(v8::Isolate* isolate, Task* task) {\n \/\/ TODO(jochen): implement.\n task->Run();\n delete task;\n}\n\n} } \/\/ namespace v8::internal\n<|endoftext|>"} {"text":"#include \n#include \n\n\nDice::Dice(int led4, int led2, int led1) {\n _led4 = led4; \/\/ LED that represents MSBit\n _led2 = led2; \/\/ LED that represents medium Bit\n _led1 = led1; \/\/ LED that represents LSBit\n pinMode(_led4, OUTPUT); \/\/ all pins are OUTPUT pins\n pinMode(_led2, OUTPUT);\n pinMode(_led1, OUTPUT);\n randomSeed(analogRead(A0)); \/\/ read random value from analog A0 for initial seed\n}\n\nvoid Dice::roll() {\n int result = random(1,7); \/\/ get a random number from 1..6\n#ifdef DEBUG\n Serial.print(“result = “);\n Serial.println(result);\n#endif\n\n controlLED(_led4, (1 == result \/ 4 )); \/\/ simple arithmetic\n\n#ifdef DEBUG\n Serial.print(“led4 = “); \n Serial.println(1 == result \/ 4);\n#endif\n\n result = result % 4;\n controlLED(_led2, (1 == result \/ 2));\n\n#ifdef DEBUG\n Serial.print(“led2 = “); \n Serial.println(1 == result \/ 2);\n#endif\n\n result = result % 2;\n controlLED(_led1, 1 == result);\n\n#ifdef DEBUG\n Serial.print(“led1 = “); \n Serial.println(1 == result);\n#endif\n}\n\nvoid Dice::controlLED(int led, bool on) {\n if (on)\n digitalWrite(led, HIGH);\n else\n digitalWrite(led, LOW);\n}\nEliminated some stray characters#include \n#include \n\n#define DEBUG\nDice::Dice(int led4, int led2, int led1) {\n _led4 = led4; \/\/ LED that represents MSBit\n _led2 = led2; \/\/ LED that represents medium Bit\n _led1 = led1; \/\/ LED that represents LSBit\n pinMode(_led4, OUTPUT); \/\/ all pins are OUTPUT pins\n pinMode(_led2, OUTPUT);\n pinMode(_led1, OUTPUT);\n randomSeed(analogRead(A0)); \/\/ read random value from analog A0 for initial seed\n}\n\nvoid Dice::roll() {\n int result = random(1,7); \/\/ get a random number from 1..6\n\n#ifdef DEBUG\n Serial.print(\"dice value = \");\n Serial.println(result);\n#endif\n\n controlLED(_led4, (1 == result \/ 4 )); \/\/ simple arithmetic\n\n#ifdef DEBUG\n Serial.print(\"LED4 = \");\n Serial.println(1 == result \/ 4);\n#endif\n\n result = result % 4;\n controlLED(_led2, (1 == result \/ 2));\n\n#ifdef DEBUG\n Serial.print(\"LED2 = \");\n Serial.println(1 == result \/ 2);\n#endif\n\n result = result % 2;\n controlLED(_led1, 1 == result);\n\n#ifdef DEBUG\n Serial.print(\"LED1 = \");\n Serial.println(1 == result);\n#endif\n}\n\nvoid Dice::controlLED(int led, bool on) {\n if (on)\n digitalWrite(led, HIGH);\n else\n digitalWrite(led, LOW);\n}\n<|endoftext|>"} {"text":"\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/ Mat edges;\n for (; ;) {\n Mat mask, hsv_mask;\n Mat frame, hsv;\n cap >> frame; \/\/ get a new frame from camera\n\n cvtColor(frame, hsv, CV_BGR2HSV);\n\n double minH = 0;\n double minS = 0;\n double minV = 0;\n double maxH = 255;\n double maxS = 255;\n double maxV = 255;\n\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, mask);\n \n \/\/ low = Scalar(30, 0, 240);\n\/\/ high = Scalar(80, 70, 255);\n\n\/\/ inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);\n\n bitwise_and(frame, frame, frame, mask);\n\n\/\/ cvtColor(mask, hsv_mask, CV_HS);\n\n vector lines;\n\/\/ HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(hsv_mask, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n }\n\n\n imshow(\"edges\", frame);\n if (waitKey(30) >= 0) break;\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\ncorrect hsv threshold\/*\n\n*\/\n\n#include \"lineFollowing.h\"\n\nusing namespace std;\nusing namespace cv;\n\nControlMovements lineFollowingControl() {\n\n line_main();\n\n return ControlMovements();\n}\n\nvoid line_main() {\n\/\/ printf(\"Hello, this is Caleb\\n\");\n\n VideoCapture cap(\"..\/..\/tests\/videos\/top_down_4.m4v\");\n if (!cap.isOpened()) \/\/ check if we succeeded\n return;\n\n namedWindow(\"edges\", CV_WINDOW_NORMAL);\n\/\/ Mat edges;\n for (; ;) {\n Mat mask, hsv_mask;\n Mat frame, hsv;\n cap >> frame; \/\/ get a new frame from camera\n\n cvtColor(frame, hsv, CV_BGR2HSV);\n\n double minH = 30;\n double minS = 0;\n double minV = 240;\n double maxH = 80;\n double maxS = 70;\n double maxV = 255;\n\n cv::Scalar lower(minH, minS, minV);\n cv::Scalar upper(maxH, maxS, maxV);\n cv::inRange(hsv, lower, upper, mask);\n \n \/\/ low = Scalar(30, 0, 240);\n\/\/ high = Scalar(80, 70, 255);\n\n\/\/ inRange(hsv, Scalar(100, 0, 0), Scalar(255, 255, 255), mask);\n\n bitwise_and(frame, frame, frame, mask);\n\n\/\/ cvtColor(mask, hsv_mask, CV_HS);\n\n vector lines;\n\/\/ HoughLinesP(mask, lines, 1, CV_PI \/ 180, 100, 100, 10);\n\n printf(\"Adding in %d lines\\n\", (int) lines.size());\n for (size_t i = 0; i < lines.size(); i++) {\n Vec4i l = lines[i];\n line(hsv_mask, Point(l[0], l[1]), Point(l[2], l[3]), Scalar(0, 0, 255), 3, CV_AA);\n }\n\n\n imshow(\"edges\", mask);\n if (waitKey(30) >= 0) break;\n }\n \/\/ the camera will be deinitialized automatically in VideoCapture destructor\n return;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2012 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see .\n *\/\n\n#include \"Brewpi.h\"\n#include \"BrewpiStrings.h\"\n\n#if BREWPI_MENU\n\n#include \"Menu.h\"\n\n#include \n#include \"Pins.h\"\n#include \"Display.h\"\n#include \"TempControl.h\"\n#include \"TemperatureFormats.h\"\n#include \"RotaryEncoder.h\"\n#include \"PiLink.h\"\n#include \"Ticks.h\"\n\nMenu menu;\n\n#define MENU_OPTIMIZE 0\n\n#define MENU_TIMEOUT 10u\n\nvoid Menu::pickSettingToChange(){\n\t\/\/ ensure beer temp is displayed\n\tuint8_t flags = display.getDisplayFlags();\n\tdisplay.setDisplayFlags(flags &= ~(LCD_FLAG_ALTERNATE_ROOM|LCD_FLAG_DISPLAY_ROOM));\n\tpickSettingToChangeLoop();\n\tdisplay.setDisplayFlags(flags);\n}\n\n#if MENU_OPTIMIZE \nvoid blinkLoop()\n{\n\tuint16_t timer = ticks.seconds();\n\tuint8_t blinkTimer = 0;\n\twhile(ticks.timeSince(timer) < MENU_TIMEOUT_SECS){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\ttimer=ticks.seconds();\n\t\t\tblinkTimer = 0;\n\t\t}\n\t\n\t\n}\n\n#endif\n\nvoid Menu::pickSettingToChangeLoop(void){\n\t\n\trotaryEncoder.setRange(0, 0, 2); \/\/ mode setting, beer temp, fridge temp\n\tuint16_t lastChangeTime = ticks.seconds();\n\tuint8_t blinkTimer = 0;\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\t\t\n\t\t}\n\t\tif(blinkTimer == 0){\n\t\t\t\/\/ print all text again for blinking\n\t\t\tdisplay.printStationaryText();\t\t\n\t\t}\n\t\tif(blinkTimer == 128){ \/\/ blink one of the options by overwriting it with spaces\n\t\t\tdisplay.printAt_P(0, rotaryEncoder.read(), STR_SPACES_END-6);\n\t\t}\n\t\tif( rotaryEncoder.pushed() ){\n\t\t\trotaryEncoder.resetPushed();\n\t\t\tswitch(rotaryEncoder.read()){\n\t\t\t\tcase 0:\n\t\t\t\t\tpickMode();\n\t\t\t\t\treturn;\n\t\t\t\tcase 1:\n\t\t\t\t\t\/\/ switch to beer constant, because beer setting will be set through display\n\t\t\t\t\ttempControl.setMode(MODE_BEER_CONSTANT);\n\t\t\t\t\tdisplay.printMode();\n\t\t\t\t\tpickBeerSetting();\n\t\t\t\t\treturn;\n\t\t\t\tcase 2:\n\t\t\t\t\t\/\/ switch to fridge constant, because fridge setting will be set through display\n\t\t\t\t\ttempControl.setMode(MODE_FRIDGE_CONSTANT);\n\t\t\t\t\tdisplay.printMode();\n\t\t\t\t\tpickFridgeSetting();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\tblinkTimer++;\n\t\twait.millis(3); \/\/ delay for blinking\n\t}\n}\n\nvoid Menu::initRotaryWithTemp(fixed7_9 oldSetting){\n\tfixed7_9 startVal;\n\tif(oldSetting == INT_MIN){ \/\/ previous temperature was not defined, start at 20C\n\t\tstartVal = 20*512;\n\t}\n\telse{\n\t\tstartVal = oldSetting;\n\t}\n\trotaryEncoder.setRange(fixedToTenths(startVal), fixedToTenths(tempControl.cc.tempSettingMin), fixedToTenths(tempControl.cc.tempSettingMax));\n}\n\nconst char* LOOKUP = \"bfpo\";\n\nvoid Menu::pickMode(void){\n\tdisplay.printStationaryText(); \/\/ restore original text after blinking 'Mode'\n\tchar oldSetting = tempControl.getMode();\n\tuint8_t startValue=0;\n\tstartValue = indexOf(LOOKUP, oldSetting);\n\trotaryEncoder.setRange(startValue, 0, 3); \/\/ toggle between beer constant, beer profile, fridge constant\n\tconst char lookup[] = {'b', 'f', 'p', 'o'};\n\tuint8_t blinkTimer = 0;\t\t\n\tuint16_t lastChangeTime = ticks.seconds();\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\n\t\t\t\n\t\t\ttempControl.setMode(lookup[rotaryEncoder.read()]);\n\t\t\tdisplay.printMode();\n\t\t\t\n\t\t\tif( rotaryEncoder.pushed() ){\n\t\t\t\trotaryEncoder.resetPushed();\n\t\t\t\tchar mode = tempControl.getMode();\n\t\t\t\tif(mode == MODE_BEER_CONSTANT){\n\t\t\t\t\tmenu.pickBeerSetting();\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_FRIDGE_CONSTANT){\n\t\t\t\t\tmenu.pickFridgeSetting();\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_BEER_PROFILE){\n\t\t\t\t\tpiLink.printBeerAnnotation(PSTR(\"Changed to profile mode in menu.\"));\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_OFF){\n\t\t\t\t\tpiLink.printBeerAnnotation(PSTR(\"Temp control turned off in menu.\"));\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(blinkTimer == 0){\n\t\t\t\tdisplay.printMode();\n\t\t\t}\n\t\t\tif(blinkTimer == 128){\n\t\t\t\tdisplay.printAt_P(7, 0, STR_SPACES_END-13);\n\t\t\t}\t\t\t\t\n\t\t\tblinkTimer++;\n\t\t\twait.millis(3); \/\/ delay for blinking\n\t\t}\n\t}\n\t\/\/ Time Out. Restore original setting\n\ttempControl.setMode(oldSetting);\n}\n\n\ntypedef void (* PrintAnnotation)(const char * annotation, ...);\ntypedef void (* DisplayUpdate)(void);\ntypedef fixed7_9 (* ReadTemp)();\ntypedef void (* WriteTemp)(fixed7_9);\n\nvoid pickTempSetting(ReadTemp readTemp, WriteTemp writeTemp, const char* tempName, DisplayUpdate update, PrintAnnotation printAnnoation, int row) {\n\tdisplay.printStationaryText(); \/\/ restore original text after blinking\n\tfixed7_9 oldSetting = readTemp();\n\tmenu.initRotaryWithTemp(oldSetting);\n\t\n\tuint8_t blinkTimer = 0;\n\tuint8_t lastChangeTime = ticks.seconds();\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\n\t\t\t\n\t\t\twriteTemp(tenthsToFixed(rotaryEncoder.read()));\n\t\t\tupdate();\n\t\t\t\n\t\t\tif( rotaryEncoder.pushed() ){\n\t\t\t\trotaryEncoder.resetPushed();\n\t\t\t\tchar tempString[9];\n\t\t\t\tprintAnnoation(PSTR(\"%S temp set to %s in Menu.\"), tempName, tempToString(tempString,readTemp(),1,9));\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(blinkTimer == 0){\n\t\t\t\tupdate();\n\t\t\t}\n\t\t\tif(blinkTimer == 128){\n\t\t\t\tdisplay.printAt_P(12, row, STR_SPACES_END-5);\n\t\t\t}\n\t\t\tblinkTimer++;\n\t\t\twait.millis(3); \/\/ delay for blinking\n\t\t}\n\t}\n\t\/\/ Time Out. Restore original setting\n\twriteTemp(oldSetting);\n\t\n}\n\nvoid Menu::pickFridgeSetting(void){\n\tpickTempSetting(tempControl.getFridgeSetting, tempControl.setFridgeTemp, PSTR(\"Fridge\"), display.printFridgeSet, piLink.printFridgeAnnotation, 2);\n}\n\nvoid Menu::pickBeerSetting(void){\n\tpickTempSetting(tempControl.getBeerSetting, tempControl.setBeerTemp, PSTR(\"Beer\"), display.printBeerSet, piLink.printBeerAnnotation, 1);\n}\n\n\n\n\n#endifmenu optimizations saves 50 bytes\/*\n * Copyright 2012 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n * \n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n * \n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n * \n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see .\n *\/\n\n#include \"Brewpi.h\"\n#include \"BrewpiStrings.h\"\n\n#if BREWPI_MENU\n\n#include \"Menu.h\"\n\n#include \n#include \"Pins.h\"\n#include \"Display.h\"\n#include \"TempControl.h\"\n#include \"TemperatureFormats.h\"\n#include \"RotaryEncoder.h\"\n#include \"PiLink.h\"\n#include \"Ticks.h\"\n\nMenu menu;\n\n#define MENU_OPTIMIZE 1\n\n#define MENU_TIMEOUT 10u\n\nvoid Menu::pickSettingToChange(){\n\t\/\/ ensure beer temp is displayed\n\tuint8_t flags = display.getDisplayFlags();\n\tdisplay.setDisplayFlags(flags &= ~(LCD_FLAG_ALTERNATE_ROOM|LCD_FLAG_DISPLAY_ROOM));\n\tpickSettingToChangeLoop();\n\tdisplay.setDisplayFlags(flags);\n}\n\n#if MENU_OPTIMIZE \n\/**\n * @return {@code true} if a value was selected. {@code false} on timeout.\n *\/\nbool blinkLoop(\n\tvoid (*changed)(),\t\/\/ called to update the value\n\tvoid (*show)(),\t\t\/\/ called to show the current value\n\tvoid (*blink)(),\t\/\/ called to blank out the current value\n\tvoid (*pushed)())\t\/\/ handle selection\n{\t\n\tuint16_t lastChangeTime = ticks.seconds();\n\tuint8_t blinkTimer = 0;\n\t\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\n\t\t\tchanged();\n\t\t}\n\t\tif (blinkTimer==0)\n\t\t\tshow();\n\t\telse if (blinkTimer==128)\n\t\t\tblink();\n\t\t\t\n\t\tif (rotaryEncoder.pushed()) {\n\t\t\trotaryEncoder.resetPushed();\n\t\t\tshow();\n\t\t\tpushed();\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tblinkTimer++;\n\t\twait.millis(3); \/\/ delay for blinking\t\t\n\t}\n\treturn false;\n}\n\nvoid clearSettingText() {\n\tdisplay.printAt_P(0, rotaryEncoder.read(), STR_SPACES_END-6);\n}\n\nvoid settingChanged() {} \/\/ no -op - the only change is to update the display which happens already\n\nvoid settingSelected() {\n\tswitch(rotaryEncoder.read()){\n\t\tcase 0:\n\t\t\tmenu.pickMode();\n\t\t\treturn;\n\t\tcase 1:\n\t\t\t\/\/ switch to beer constant, because beer setting will be set through display\n\t\t\ttempControl.setMode(MODE_BEER_CONSTANT);\n\t\t\tdisplay.printMode();\n\t\t\tmenu.pickBeerSetting();\n\t\t\treturn;\n\t\tcase 2:\n\t\t\t\/\/ switch to fridge constant, because fridge setting will be set through display\n\t\t\ttempControl.setMode(MODE_FRIDGE_CONSTANT);\n\t\t\tdisplay.printMode();\n\t\t\tmenu.pickFridgeSetting();\n\t\t\treturn;\n\t}\t\n}\n\nvoid Menu::pickSettingToChangeLoop(void) {\n\trotaryEncoder.setRange(0, 0, 2); \/\/ mode setting, beer temp, fridge temp\n\tblinkLoop(\n\t\tsettingChanged,\n\t\tdisplay.printStationaryText,\n\t\tclearSettingText,\n\t\tsettingSelected\n\t);\n}\n\nvoid changedMode() {\n\tconst char lookup[] = {'b', 'f', 'p', 'o'};\n\ttempControl.setMode(lookup[rotaryEncoder.read()]);\n}\n\nvoid clearMode() {\n\tdisplay.printAt_P(7, 0, STR_SPACES_END-13);\n}\n\nvoid selectMode() {\n\tchar mode = tempControl.getMode();\n\tif(mode == MODE_BEER_CONSTANT){\n\t\tmenu.pickBeerSetting();\n\t}\n\telse if(mode == MODE_FRIDGE_CONSTANT){\n\t\tmenu.pickFridgeSetting();\n\t}\n\telse if(mode == MODE_BEER_PROFILE){\n\t\tpiLink.printBeerAnnotation(PSTR(\"Changed to profile mode in menu.\"));\n\t}\n\telse if(mode == MODE_OFF){\n\t\tpiLink.printBeerAnnotation(PSTR(\"Temp control turned off in menu.\"));\n\t}\t\n}\n\nvoid Menu::pickMode(void) {\t\n\tchar oldSetting = tempControl.getMode();\n\tuint8_t startValue=0;\n\tconst char* LOOKUP = \"bfpo\";\n\tstartValue = indexOf(LOOKUP, oldSetting);\n\trotaryEncoder.setRange(startValue, 0, 3); \/\/ toggle between beer constant, beer profile, fridge constant\n\t\n\tif (!blinkLoop(changedMode, display.printMode, clearMode, selectMode)) \n\t\ttempControl.setMode(oldSetting);\t\t\n}\n\n\n#else\nvoid Menu::pickSettingToChangeLoop(void){\n\t\n\trotaryEncoder.setRange(0, 0, 2); \/\/ mode setting, beer temp, fridge temp\n\tuint16_t lastChangeTime = ticks.seconds();\n\tuint8_t blinkTimer = 0;\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\t\t\n\t\t}\n\t\tif(blinkTimer == 0){\n\t\t\t\/\/ print all text again for blinking\n\t\t\tdisplay.printStationaryText();\t\t\n\t\t}\n\t\tif(blinkTimer == 128){ \/\/ blink one of the options by overwriting it with spaces\n\t\t\tdisplay.printAt_P(0, rotaryEncoder.read(), STR_SPACES_END-6);\n\t\t}\n\t\tif( rotaryEncoder.pushed() ){\n\t\t\trotaryEncoder.resetPushed();\n\t\t\tswitch(rotaryEncoder.read()){\n\t\t\t\tcase 0:\n\t\t\t\t\tpickMode();\n\t\t\t\t\treturn;\n\t\t\t\tcase 1:\n\t\t\t\t\t\/\/ switch to beer constant, because beer setting will be set through display\n\t\t\t\t\ttempControl.setMode(MODE_BEER_CONSTANT);\n\t\t\t\t\tdisplay.printMode();\n\t\t\t\t\tpickBeerSetting();\n\t\t\t\t\treturn;\n\t\t\t\tcase 2:\n\t\t\t\t\t\/\/ switch to fridge constant, because fridge setting will be set through display\n\t\t\t\t\ttempControl.setMode(MODE_FRIDGE_CONSTANT);\n\t\t\t\t\tdisplay.printMode();\n\t\t\t\t\tpickFridgeSetting();\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\tblinkTimer++;\n\t\twait.millis(3); \/\/ delay for blinking\n\t}\n}\n\nconst char* LOOKUP = \"bfpo\";\n\nvoid Menu::pickMode(void){\n\tdisplay.printStationaryText(); \/\/ restore original text after blinking 'Mode'\n\tchar oldSetting = tempControl.getMode();\n\tuint8_t startValue=0;\n\tstartValue = indexOf(LOOKUP, oldSetting);\n\trotaryEncoder.setRange(startValue, 0, 3); \/\/ toggle between beer constant, beer profile, fridge constant\n\tconst char lookup[] = {'b', 'f', 'p', 'o'};\n\tuint8_t blinkTimer = 0;\t\t\n\tuint16_t lastChangeTime = ticks.seconds();\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\n\t\t\t\n\t\t\ttempControl.setMode(lookup[rotaryEncoder.read()]);\n\t\t\tdisplay.printMode();\n\t\t\t\n\t\t\tif( rotaryEncoder.pushed() ){\n\t\t\t\trotaryEncoder.resetPushed();\n\t\t\t\tchar mode = tempControl.getMode();\n\t\t\t\tif(mode == MODE_BEER_CONSTANT){\n\t\t\t\t\tmenu.pickBeerSetting();\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_FRIDGE_CONSTANT){\n\t\t\t\t\tmenu.pickFridgeSetting();\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_BEER_PROFILE){\n\t\t\t\t\tpiLink.printBeerAnnotation(PSTR(\"Changed to profile mode in menu.\"));\n\t\t\t\t}\n\t\t\t\telse if(mode == MODE_OFF){\n\t\t\t\t\tpiLink.printBeerAnnotation(PSTR(\"Temp control turned off in menu.\"));\n\t\t\t\t}\t\t\t\t\t\t\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\telse{\n\t\t\tif(blinkTimer == 0){\n\t\t\t\tdisplay.printMode();\n\t\t\t}\n\t\t\tif(blinkTimer == 128){\n\t\t\t\tdisplay.printAt_P(7, 0, STR_SPACES_END-13);\n\t\t\t}\t\t\t\t\n\t\t\tblinkTimer++;\n\t\t\twait.millis(3); \/\/ delay for blinking\n\t\t}\n\t}\n\t\/\/ Time Out. Restore original setting\n\ttempControl.setMode(oldSetting);\n}\n#endif\n\ntypedef void (* PrintAnnotation)(const char * annotation, ...);\ntypedef void (* DisplayUpdate)(void);\ntypedef fixed7_9 (* ReadTemp)();\ntypedef void (* WriteTemp)(fixed7_9);\n\nvoid pickTempSetting(ReadTemp readTemp, WriteTemp writeTemp, const char* tempName, DisplayUpdate update, PrintAnnotation printAnnoation, int row) {\n\tdisplay.printStationaryText(); \/\/ restore original text after blinking\n\tfixed7_9 oldSetting = readTemp();\n\tfixed7_9 startVal = oldSetting;\n\tif(oldSetting == INT_MIN)\t \/\/ previous temperature was not defined, start at 20C\n\t\tstartVal = 20*512;\n\t\n\trotaryEncoder.setRange(fixedToTenths(startVal), fixedToTenths(tempControl.cc.tempSettingMin), fixedToTenths(tempControl.cc.tempSettingMax));\n\n\tuint8_t blinkTimer = 0;\n\tuint8_t lastChangeTime = ticks.seconds();\n\twhile(ticks.timeSince(lastChangeTime) < MENU_TIMEOUT){ \/\/ time out at 10 seconds\n\t\tif(rotaryEncoder.changed()){\n\t\t\tlastChangeTime = ticks.seconds();\n\t\t\tblinkTimer = 0;\n\n\t\t\twriteTemp(tenthsToFixed(rotaryEncoder.read()));\t\t\n\t\t\tupdate();\n\n\t\t\tif( rotaryEncoder.pushed() ){\n\t\t\t\trotaryEncoder.resetPushed();\n\t\t\t\tchar tempString[9];\n\t\t\t\tprintAnnoation(PSTR(\"%S temp set to %s in Menu.\"), tempName, tempToString(tempString,readTemp(),1,9));\n\t\t\t\treturn;\n\t\t\t}\n\t}\t\n\t\telse{\n\t\t\tif(blinkTimer == 0){\n\t\t\t\tupdate();\n\t\t\t}\n\t\t\tif(blinkTimer == 128){\n\t\t\t\tdisplay.printAt_P(12, row, STR_SPACES_END-5);\n\t\t\t}\n\t\t\tblinkTimer++;\n\t\t\twait.millis(3); \/\/ delay for blinking\n\t\t}\n\t}\n\t\/\/ Time Out. Restore original setting\n\twriteTemp(oldSetting);\t\n}\n\nvoid Menu::pickFridgeSetting(void){\n\tpickTempSetting(tempControl.getFridgeSetting, tempControl.setFridgeTemp, PSTR(\"Fridge\"), display.printFridgeSet, piLink.printFridgeAnnotation, 2);\n}\n\nvoid Menu::pickBeerSetting(void){\n\tpickTempSetting(tempControl.getBeerSetting, tempControl.setBeerTemp, PSTR(\"Beer\"), display.printBeerSet, piLink.printBeerAnnotation, 1);\n}\n\n\n#endif<|endoftext|>"} {"text":"\/\/! \\file **************************************************************\n\/\/! \\brief Source notification.\n\/\/! \n\/\/! - Compilateur : GCC,MinGW\n\/\/!\n\/\/! \\author Antoine Maleyrie\n\/\/! \\version 0.3\n\/\/! \\date 12.04.2013\n\/\/!\n\/\/! ********************************************************************\n\n\/*\n*\tCopyright © 2013 - Antoine Maleyrie.\n*\/\n\n#include \"notification.hpp\"\n \n#include \n#include \n\n#ifndef USE_EMULATE_NOTIFICATION\n\t\/\/Sous unix on utilise la libnotify\n\t#if defined(__UNIX__)\n\t\t#include \n\t\/\/Pour les autres os on utilise les notifications de wxWidgets\n\t#else\n\t\t#include \n\t#endif\n#endif\n\n\/\/TEST\n#include \n\n\/\/ *********************************************************************\n\/\/ Class FrameNotification\n\/\/ *********************************************************************\n\n#if defined(USE_EMULATE_NOTIFICATION) || defined(__DOXYGEN__)\n\nDialogNotification::DialogNotification(\twxString const& title,\n\t\t\t\t\t\t\t\t\t\twxString const& message)\n: GuiDialogNotification(nullptr, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFRAME_NO_TASKBAR|wxDIALOG_NO_PARENT|wxSTAY_ON_TOP|wxNO_BORDER),\n_timeout(this) \n{\n\t\/\/Affiche le titre et le message.\n\t_staticTextTitle->SetLabelMarkup(\"\"+title+\"<\/b>\");\n\t_staticTextMessage->SetLabel(message);\n\t\n\t\/\/Recalcule de la tille de la fenêtre.\n\tthis->Layout();\n\tGetSizer()->Fit(this);\n\t\n\t\/\/Pour ne pas redimensionner la fenêtre.\n\tthis->SetSizeHints(GetSize(), GetSize());\n\t\n\t\/\/Bind du timer pour le timeout\n\tBind(wxEVT_TIMER, &DialogNotification::OnTimeout, this);\n}\n\nDialogNotification::~DialogNotification()\n{\n\t\/\/Unbind du timer pour le timeout\n\tUnbind(wxEVT_TIMER, &DialogNotification::OnTimeout, this);\n}\n\nvoid DialogNotification::show(int timeout)\n{\n\tShowWithoutActivating();\n\t_timeout.Start(timeout*1000, wxTIMER_ONE_SHOT);\n}\n\nvoid DialogNotification::OnClose(wxCloseEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::OnLeftDown(wxMouseEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::OnTimeout(wxTimerEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::exit()\n{\n\t\/\/Envoi de l'événement.\n\twxCommandEvent event(EVT_EXIT_DIALG_NOTIFICATION, GetId());\n event.SetEventObject(this);\n ProcessWindowEvent(event);\n}\n\nwxDEFINE_EVENT(EVT_EXIT_DIALG_NOTIFICATION, wxCommandEvent);\n\n#endif\n\n\/\/ *********************************************************************\n\/\/ Class Notification\n\/\/ *********************************************************************\n\/\/! \\todo a instenser\/supprimer dans main.cpp\nNotification::Notification()\n{\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t\/\/Sous unix on utilise la libnotify\n\t\t#if defined(__UNIX__)\n\t\t\tif(!notify_init(PROJECT_NAME))\n\t\t\t{\n\t\t\t\twxLogError(_(\"Libnotify could not be initialized.\"));\n\t\t\t}\n\t\t#endif\n\t#endif\n}\n\nNotification::~Notification()\n{\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t\/\/Sous unix on utilise la libnotify\n\t\t#if defined(__UNIX__)\n\t\t\tnotify_uninit();\n\t\t#endif\n\t#else\n\t\t\/\/On détruis les dialogues\n\t\tfor(auto it : _dialogs)\n\t\t{\n\t\t\tit->Destroy();\n\t\t\tdelete it;\n\t\t}\n\t#endif\n}\n\nvoid Notification::notify(\twxString const& title,\n\t\t\t\t\t\t\twxString const& message)\n{\n\t\/\/3s par défaut + 1s de plus tout les 10 caractères.\n\tint timeout = 3+message.Length()\/10;\n\t\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t#if define(__UNIX__)\n\t\t\t\/\/Préparation de la notification.\n\t\t\tNotifyNotification * notify = notify_notification_new(title.mb_str(wxConvUTF8), message.fn_str(), \"dialog-information\");\n\t\t\tnotify_notification_set_timeout(notify, timeout*1000);\n\t\t\t\n\t\t\t\/\/Affichage de la notification\n\t\t\tif(!notify_notification_show(notify, nullptr))\n\t\t\t{\n\t\t\t\t\/\/Si problème\n\t\t\t\twxLogError(_(\"The notify could not be show.\"));\n\t\t\t}\n\t\t#else\n\t\t\t\/\/Préparation de la notification.\n\t\t\twxNotificationMessage notify(title, message);\n\t\t\t\/\/Affichage de la notification\n\t\t\tnotify.Show(timeout);\n\t\t#endif\n\t#else\n\t\tDialogNotification *dialog = new DialogNotification(title, message);\n\t\t\n\t\tif(_dialogs.size() != 0)\n\t\t{\n\t\t\tint positionY = 0;\n\t\t\tint sizeY = 0;\n\t\t\tDialogNotification *lastDialog = _dialogs.back();\n\t\t\n\t\t\tlastDialog->GetPosition(nullptr, &positionY);\n\t\t\tlastDialog->GetSize(nullptr, &sizeY);\n\t\t\t\n\t\t\tdialog->SetPosition(wxPoint(0, positionY+sizeY));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdialog->SetPosition(wxPoint(0, 0));\n\t\t}\n\n\n\t\t_dialogs.push_back(dialog);\n\t\tdialog->Bind(EVT_EXIT_DIALG_NOTIFICATION, &Notification::OnExitDialogNotification, this);\n\t\tdialog->show(timeout);\n\t#endif\n}\n\n#ifdef USE_EMULATE_NOTIFICATION\n\nvoid Notification::OnExitDialogNotification(wxCommandEvent& event)\n{\n\t\/\/Obtenir le dialogue qui provoquer l'événement.\n\tDialogNotification* dialog = static_cast(event.GetEventObject());\n\t\n\t\/\/Unbind le dialogue\n\tdialog->Unbind(EVT_EXIT_DIALG_NOTIFICATION, &Notification::OnExitDialogNotification, this);\n\n\tint iDialog = -1;\n\tint sizeY = 0;\n\t\n\t\/\/On sauvegarde le décalage que l'on doit affecter au dialogue qui doive être décaler.\n\tdialog->GetSize(nullptr, &sizeY);\n\t\n\t\/\/Parcoure tout les dialogues actifs\n\tfor(unsigned int i = 0; i<_dialogs.size(); i++)\n\t{\n\t\t\/\/Si le dialogue a été trouver\n\t\tif(iDialog != -1)\n\t\t{\n\t\t\t\/\/On décale les dialogue qui doive changer de position\n\t\t\twxPoint pos = _dialogs[i]->GetPosition();\n\t\t\tpos.y -= sizeY;\n\t\t\t_dialogs[i]->SetPosition(pos);\n\t\t}\n\t\t\/\/c'est le dialogue que l'on cherche ?\n\t\telse if(_dialogs[i] == dialog)\n\t\t{\n\t\t\t\/\/On retiens sont index dans le vector\n\t\t\tiDialog = i;\n\t\t}\n\t}\n\t\n\t\/\/On détruis le dialogue\n\t_dialogs[iDialog]->Destroy();\n\tdelete _dialogs[iDialog];\n\t\/\/Et on l'enlève du vector\n\t_dialogs.erase(_dialogs.begin()+iDialog);\n}\n\n#endif\nlimited a number notification\/\/! \\file **************************************************************\n\/\/! \\brief Source notification.\n\/\/! \n\/\/! - Compilateur : GCC,MinGW\n\/\/!\n\/\/! \\author Antoine Maleyrie\n\/\/! \\version 0.3\n\/\/! \\date 12.04.2013\n\/\/!\n\/\/! ********************************************************************\n\n\/*\n*\tCopyright © 2013 - Antoine Maleyrie.\n*\/\n\n#include \"notification.hpp\"\n \n#include \n#include \n\n#ifndef USE_EMULATE_NOTIFICATION\n\t\/\/Sous unix on utilise la libnotify\n\t#if defined(__UNIX__)\n\t\t#include \n\t\/\/Pour les autres os on utilise les notifications de wxWidgets\n\t#else\n\t\t#include \n\t#endif\n#else\n\t#include \n#endif\n\n\/\/TEST\n#include \n\n\/\/ *********************************************************************\n\/\/ Class FrameNotification\n\/\/ *********************************************************************\n\n#if defined(USE_EMULATE_NOTIFICATION) || defined(__DOXYGEN__)\n\nDialogNotification::DialogNotification(\twxString const& title,\n\t\t\t\t\t\t\t\t\t\twxString const& message)\n: GuiDialogNotification(nullptr, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxFRAME_NO_TASKBAR|wxDIALOG_NO_PARENT|wxSTAY_ON_TOP|wxNO_BORDER),\n_timeout(this) \n{\n\t\/\/Affiche le titre et le message.\n\t_staticTextTitle->SetLabelMarkup(\"\"+title+\"<\/b>\");\n\t_staticTextMessage->SetLabel(message);\n\t\n\t\/\/Recalcule de la tille de la fenêtre.\n\tthis->Layout();\n\tGetSizer()->Fit(this);\n\t\n\t\/\/Pour ne pas redimensionner la fenêtre.\n\tthis->SetSizeHints(GetSize(), GetSize());\n\t\n\t\/\/Bind du timer pour le timeout\n\tBind(wxEVT_TIMER, &DialogNotification::OnTimeout, this);\n}\n\nDialogNotification::~DialogNotification()\n{\n\t\/\/Unbind du timer pour le timeout\n\tUnbind(wxEVT_TIMER, &DialogNotification::OnTimeout, this);\n}\n\nvoid DialogNotification::show(int timeout)\n{\n\tShowWithoutActivating();\n\t_timeout.Start(timeout*1000, wxTIMER_ONE_SHOT);\n}\n\nvoid DialogNotification::OnClose(wxCloseEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::OnLeftDown(wxMouseEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::OnTimeout(wxTimerEvent&)\n{\n\t\/\/Qui la notification\n\texit();\n}\n\nvoid DialogNotification::exit()\n{\n\t\/\/Envoi de l'événement.\n\twxCommandEvent event(EVT_EXIT_DIALG_NOTIFICATION, GetId());\n event.SetEventObject(this);\n ProcessWindowEvent(event);\n}\n\nwxDEFINE_EVENT(EVT_EXIT_DIALG_NOTIFICATION, wxCommandEvent);\n\n#endif\n\n\/\/ *********************************************************************\n\/\/ Class Notification\n\/\/ *********************************************************************\n\/\/! \\todo a instenser\/supprimer dans main.cpp\nNotification::Notification()\n{\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t\/\/Sous unix on utilise la libnotify\n\t\t#if defined(__UNIX__)\n\t\t\tif(!notify_init(PROJECT_NAME))\n\t\t\t{\n\t\t\t\twxLogError(_(\"Libnotify could not be initialized.\"));\n\t\t\t}\n\t\t#endif\n\t#endif\n}\n\nNotification::~Notification()\n{\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t\/\/Sous unix on utilise la libnotify\n\t\t#if defined(__UNIX__)\n\t\t\tnotify_uninit();\n\t\t#endif\n\t#else\n\t\t\/\/On détruis les dialogues\n\t\tfor(auto it : _dialogs)\n\t\t{\n\t\t\tit->Destroy();\n\t\t\tdelete it;\n\t\t}\n\t#endif\n}\n\nvoid Notification::notify(\twxString const& title,\n\t\t\t\t\t\t\twxString const& message)\n{\n\t\/\/3s par défaut + 1s de plus tout les 10 caractères.\n\tint timeout = 3+message.Length()\/10;\n\t\n\t#ifndef USE_EMULATE_NOTIFICATION\n\t\t#if define(__UNIX__)\n\t\t\t\/\/Préparation de la notification.\n\t\t\tNotifyNotification * notify = notify_notification_new(title.mb_str(wxConvUTF8), message.fn_str(), \"dialog-information\");\n\t\t\tnotify_notification_set_timeout(notify, timeout*1000);\n\t\t\t\n\t\t\t\/\/Affichage de la notification\n\t\t\tif(!notify_notification_show(notify, nullptr))\n\t\t\t{\n\t\t\t\t\/\/Si problème\n\t\t\t\twxLogError(_(\"The notify could not be show.\"));\n\t\t\t}\n\t\t#else\n\t\t\t\/\/Préparation de la notification.\n\t\t\twxNotificationMessage notify(title, message);\n\t\t\t\/\/Affichage de la notification\n\t\t\tnotify.Show(timeout);\n\t\t#endif\n\t#else\n\t\tDialogNotification *dialog = new DialogNotification(title, message);\n\t\t\n\t\tif(_dialogs.size() != 0)\n\t\t{\t\t\t\n\t\t\tint positionY = 0;\n\t\t\tint sizeY = 0;\n\t\t\tDialogNotification *lastDialog = _dialogs.back();\n\t\t\n\t\t\tlastDialog->GetPosition(nullptr, &positionY);\n\t\t\tlastDialog->GetSize(nullptr, &sizeY);\n\t\t\t\n\t\t\tdialog->SetPosition(wxPoint(0, positionY+sizeY));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tdialog->SetPosition(wxPoint(0, 0));\n\t\t}\n\n\t\t_dialogs.push_back(dialog);\n\t\tdialog->Bind(EVT_EXIT_DIALG_NOTIFICATION, &Notification::OnExitDialogNotification, this);\n\t\tdialog->show(timeout);\n\t\t\n\t\tif(_dialogs.size() != 0)\n\t\t{\n\t\t\tint positionY = 0;\n\t\t\tint sizeY = 0;\n\t\t\tint displayY = 0;\n\t\t\t\n\t\t\twxDisplaySize(nullptr, &displayY);\n\t\t\tdialog->GetPosition(nullptr, &positionY);\n\t\t\tdialog->GetSize(nullptr, &sizeY);\n\t\t\t\n\t\t\tif(positionY+sizeY > displayY)\n\t\t\t{\n\t\t\t\t_dialogs[0]->exit();\n\t\t\t}\n\t\t}\n\t#endif\n}\n\n#ifdef USE_EMULATE_NOTIFICATION\n\nvoid Notification::OnExitDialogNotification(wxCommandEvent& event)\n{\n\t\/\/Obtenir le dialogue qui provoquer l'événement.\n\tDialogNotification* dialog = static_cast(event.GetEventObject());\n\t\n\t\/\/Unbind le dialogue\n\tdialog->Unbind(EVT_EXIT_DIALG_NOTIFICATION, &Notification::OnExitDialogNotification, this);\n\n\tint iDialog = -1;\n\tint sizeY = 0;\n\t\n\t\/\/On sauvegarde le décalage que l'on doit affecter au dialogue qui doive être décaler.\n\tdialog->GetSize(nullptr, &sizeY);\n\t\n\t\/\/Parcoure tout les dialogues actifs\n\tfor(unsigned int i = 0; i<_dialogs.size(); i++)\n\t{\n\t\t\/\/Si le dialogue a été trouver\n\t\tif(iDialog != -1)\n\t\t{\n\t\t\t\/\/On décale les dialogue qui doive changer de position\n\t\t\twxPoint pos = _dialogs[i]->GetPosition();\n\t\t\tpos.y -= sizeY;\n\t\t\t_dialogs[i]->SetPosition(pos);\n\t\t}\n\t\t\/\/c'est le dialogue que l'on cherche ?\n\t\telse if(_dialogs[i] == dialog)\n\t\t{\n\t\t\t\/\/On retiens sont index dans le vector\n\t\t\tiDialog = i;\n\t\t}\n\t}\n\t\n\t\/\/On détruis le dialogue\n\t_dialogs[iDialog]->Destroy();\n\tdelete _dialogs[iDialog];\n\t\/\/Et on l'enlève du vector\n\t_dialogs.erase(_dialogs.begin()+iDialog);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace object\n{\n\n\n rObject\n execute_parsed(runner::Runner& r,\n parser::parse_result_type p,\n libport::Symbol fun, UrbiException e)\n {\n runner::Interpreter& run = dynamic_cast(r);\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n throw e;\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n scheduler::rJob job = sub;\n run.link(job);\n sub->start_job();\n run.yield_until_terminated(*job);\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n ::urbiserver->Function();\t\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static rObject\n system_class_sleep (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n type_check(args[1], SYMBOL(sleep));\n rFloat arg1 = args[1]->as();\n libport::utime_t deadline;\n if (arg1->value_get() == std::numeric_limits::infinity())\n deadline = std::numeric_limits::max();\n else\n deadline = r.scheduler_get().get_time() +\n\tstatic_cast(arg1->value_get() * 1000.0);\n r.yield_until (deadline);\n return void_class;\n }\n\n static rObject\n system_class_time(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float(r.scheduler_get().get_time() \/ 1000.0);\n }\n\n static rObject\n system_class_shiftedTime(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float((r.scheduler_get().get_time() -\n\t\t\t r.time_shift_get()) \/ 1000.0);\n }\n\n static rObject\n system_class_assert_(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(3);\n type_check(args[2], SYMBOL(assert_UL));\n rString arg2 = args[2]->as();\n if (!is_true(args[1], SYMBOL(assert_UL)))\n throw PrimitiveError\n\t(SYMBOL(assert_UL),\n\t \"assertion `\" + arg2->value_get() + \"' failed\");\n return void_class;\n }\n\n static rObject\n system_class_eval(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n type_check(args[1], SYMBOL(eval));\n rString arg1 = args[1]->as();\n return\n execute_parsed(r, parser::parse(arg1->value_get()),\n SYMBOL(eval),\n PrimitiveError(SYMBOL(eval),\n \"error executing command: \"\n + arg1->value_get()));\n }\n\n static rObject\n system_class_registerAtJob (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(4);\n runner::register_at_job(dynamic_cast(r),\n\t\t\t args[1], args[2], args[3]);\n return object::void_class;\n }\n\n static rObject\n system_class_scopeTag(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n const scheduler::rTag& scope_tag =\n dynamic_cast(r).scope_tag();\n return new Tag(scope_tag);\n }\n\n static rObject\n system_class_searchFile (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n type_check(args[1], SYMBOL(assert));\n const rString& arg1 = args[1]->as();\n\n UServer& s = r.lobby_get()->value_get().connection.server_get();\n try\n {\n return new String(s.find_file(arg1->value_get()));\n }\n catch (libport::file_library::Not_found&)\n {\n throw\n\tPrimitiveError(SYMBOL(searchFile),\n\t\t \"Unable to find file: \"\n\t\t + arg1->value_get());\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static rObject\n system_class_loadFile(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n type_check(args[1], SYMBOL(assert));\n const rString& arg1 = args[1]->as();\n\n const std::string& filename = arg1->value_get();\n\n if (!libport::path(filename).exists())\n throw PrimitiveError(SYMBOL(loadFile),\n\t\t\t \"No such file: \" + filename);\n return\n execute_parsed(r, parser::parse_file(filename),\n SYMBOL(loadFile),\n PrimitiveError(SYMBOL(loadFile),\n \"error loading file: \" + filename));\n }\n\n static rObject\n system_class_currentRunner (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Task(&r);\n }\n\n static rObject\n system_class_cycle (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float(r.scheduler_get ().cycle_get ());\n }\n\n static rObject\n system_class_fresh (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new String(libport::Symbol::fresh());\n }\n\n static rObject\n system_class_lobby (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return r.lobby_get();\n }\n\n static rObject\n system_class_nonInterruptible (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n r.non_interruptible_set (true);\n return void_class;\n }\n\n static rObject\n system_class_quit (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n r.lobby_get()->value_get().connection.close();\n return void_class;\n }\n\n static rObject\n system_class_spawn(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT_RANGE (2, 3, SYMBOL(spawn));\n rObject arg1 = args[1]->as();\n assert(arg1);\n\n runner::Interpreter* new_runner =\n new runner::Interpreter (dynamic_cast(r),\n\t\t\t rObject(arg1));\n new_runner->copy_tags (r);\n new_runner->time_shift_set (r.time_shift_get ());\n\n if (args.size () == 3)\n {\n if (is_true (args[2], SYMBOL(spawn)))\n\tr.link (new_runner);\n }\n\n new_runner->start_job ();\n\n return object::void_class;\n }\n\n static rObject\n system_class_stats(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n Dictionary::value_type res;\n const scheduler::scheduler_stats_type& stats =\n r.scheduler_get().stats_get();\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n ADDSTAT(, samples, 1);\n ADDSTAT(Max, max, 1000.0);\n ADDSTAT(Mean, mean, 1000.0);\n ADDSTAT(Min, min, 1000.0);\n ADDSTAT(StdDev, standard_deviation, 1000.0);\n ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static rObject\n system_class_backtrace(runner::Runner& r, objects_type args)\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n CHECK_ARG_COUNT (1);\n runner::Runner::backtrace_type bt = r.backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n return void_class;\n }\n\n static rObject\n system_class_jobs(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n List::value_type res;\n foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n res.push_back(new Task(job));\n return new List(res);\n }\n\n static rObject\n system_class_breakpoint(runner::Runner&, objects_type)\n {\n return void_class;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n ::urbiserver->Variable = Value;\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_SET_VAR(debugoff, debugOutput, false)\n SERVER_SET_VAR(debugon, debugOutput, true)\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n\n void\n system_class_initialize ()\n {\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(system, Name)\n\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(debugoff);\n DECLARE(debugon);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(shiftedTime);\n DECLARE(stats);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stopall);\n DECLARE(time);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\nAdd environment access functions.\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n\/\/#define ENABLE_DEBUG_TRACES\n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace object\n{\n\n\n rObject\n execute_parsed(runner::Runner& r,\n parser::parse_result_type p,\n libport::Symbol fun, UrbiException e)\n {\n runner::Interpreter& run = dynamic_cast(r);\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n throw e;\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n scheduler::rJob job = sub;\n run.link(job);\n sub->start_job();\n run.yield_until_terminated(*job);\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function)\t\t\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n ::urbiserver->Function();\t\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static rObject\n system_class_sleep (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n type_check(args[1], SYMBOL(sleep));\n rFloat arg1 = args[1]->as();\n libport::utime_t deadline;\n if (arg1->value_get() == std::numeric_limits::infinity())\n deadline = std::numeric_limits::max();\n else\n deadline = r.scheduler_get().get_time() +\n\tstatic_cast(arg1->value_get() * 1000.0);\n r.yield_until (deadline);\n return void_class;\n }\n\n static rObject\n system_class_time(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float(r.scheduler_get().get_time() \/ 1000.0);\n }\n\n static rObject\n system_class_shiftedTime(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float((r.scheduler_get().get_time() -\n\t\t\t r.time_shift_get()) \/ 1000.0);\n }\n\n static rObject\n system_class_assert_(runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT(3);\n type_check(args[2], SYMBOL(assert_UL));\n rString arg2 = args[2]->as();\n if (!is_true(args[1], SYMBOL(assert_UL)))\n throw PrimitiveError\n\t(SYMBOL(assert_UL),\n\t \"assertion `\" + arg2->value_get() + \"' failed\");\n return void_class;\n }\n\n static rObject\n system_class_eval(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n type_check(args[1], SYMBOL(eval));\n rString arg1 = args[1]->as();\n return\n execute_parsed(r, parser::parse(arg1->value_get()),\n SYMBOL(eval),\n PrimitiveError(SYMBOL(eval),\n \"error executing command: \"\n + arg1->value_get()));\n }\n\n static rObject\n system_class_registerAtJob (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(4);\n runner::register_at_job(dynamic_cast(r),\n\t\t\t args[1], args[2], args[3]);\n return object::void_class;\n }\n\n static rObject\n system_class_scopeTag(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n const scheduler::rTag& scope_tag =\n dynamic_cast(r).scope_tag();\n return new Tag(scope_tag);\n }\n\n static rObject\n system_class_searchFile (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (2);\n type_check(args[1], SYMBOL(assert));\n const rString& arg1 = args[1]->as();\n\n UServer& s = r.lobby_get()->value_get().connection.server_get();\n try\n {\n return new String(s.find_file(arg1->value_get()));\n }\n catch (libport::file_library::Not_found&)\n {\n throw\n\tPrimitiveError(SYMBOL(searchFile),\n\t\t \"Unable to find file: \"\n\t\t + arg1->value_get());\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static rObject\n system_class_loadFile(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(2);\n type_check(args[1], SYMBOL(assert));\n const rString& arg1 = args[1]->as();\n\n const std::string& filename = arg1->value_get();\n\n if (!libport::path(filename).exists())\n throw PrimitiveError(SYMBOL(loadFile),\n\t\t\t \"No such file: \" + filename);\n return\n execute_parsed(r, parser::parse_file(filename),\n SYMBOL(loadFile),\n PrimitiveError(SYMBOL(loadFile),\n \"error loading file: \" + filename));\n }\n\n static rObject\n system_class_currentRunner (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Task(&r);\n }\n\n static rObject\n system_class_cycle (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new Float(r.scheduler_get ().cycle_get ());\n }\n\n static rObject\n system_class_fresh (runner::Runner&, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return new String(libport::Symbol::fresh());\n }\n\n static rObject\n system_class_lobby (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n return r.lobby_get();\n }\n\n static rObject\n system_class_nonInterruptible (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n r.non_interruptible_set (true);\n return void_class;\n }\n\n static rObject\n system_class_quit (runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT (1);\n r.lobby_get()->value_get().connection.close();\n return void_class;\n }\n\n static rObject\n system_class_spawn(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT_RANGE (2, 3, SYMBOL(spawn));\n rObject arg1 = args[1]->as();\n assert(arg1);\n\n runner::Interpreter* new_runner =\n new runner::Interpreter (dynamic_cast(r),\n\t\t\t rObject(arg1));\n new_runner->copy_tags (r);\n new_runner->time_shift_set (r.time_shift_get ());\n\n if (args.size () == 3)\n {\n if (is_true (args[2], SYMBOL(spawn)))\n\tr.link (new_runner);\n }\n\n new_runner->start_job ();\n\n return object::void_class;\n }\n\n static rObject\n system_class_stats(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n Dictionary::value_type res;\n const scheduler::scheduler_stats_type& stats =\n r.scheduler_get().stats_get();\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor)\t\t\t\t\\\n res[libport::Symbol( \"cycles\" # Suffix)] = new Float(stats.Function() \/ Divisor)\n ADDSTAT(, samples, 1);\n ADDSTAT(Max, max, 1000.0);\n ADDSTAT(Mean, mean, 1000.0);\n ADDSTAT(Min, min, 1000.0);\n ADDSTAT(StdDev, standard_deviation, 1000.0);\n ADDSTAT(Variance, variance, 1000.0);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static rObject\n system_class_backtrace(runner::Runner& r, objects_type args)\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n CHECK_ARG_COUNT (1);\n runner::Runner::backtrace_type bt = r.backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n r.send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n return void_class;\n }\n\n static rObject\n system_class_jobs(runner::Runner& r, objects_type args)\n {\n CHECK_ARG_COUNT(1);\n List::value_type res;\n foreach(scheduler::rJob job, r.scheduler_get().jobs_get())\n res.push_back(new Task(job));\n return new List(res);\n }\n\n static rObject\n system_class_breakpoint(runner::Runner&, objects_type)\n {\n return void_class;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value)\t\t\t\\\n static rObject\t\t\t\t\t\t\t\\\n system_class_ ## Function (runner::Runner&, objects_type args)\t\\\n {\t\t\t\t\t\t\t\t\t\\\n CHECK_ARG_COUNT (1);\t\t\t\t\t\t\\\n ::urbiserver->Variable = Value;\t\t\t\t\t\\\n return void_class;\t\t\t\t\t\t\t\\\n }\n\n SERVER_SET_VAR(debugoff, debugOutput, false)\n SERVER_SET_VAR(debugon, debugOutput, true)\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject system_getenv(rObject, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : 0;\n }\n\n static rObject system_setenv(rObject, runner::Runner& r,\n const std::string& name, rObject value)\n {\n rString v = urbi_call(r, value, SYMBOL(asString))->as();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject system_unsetenv(rObject, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n void\n system_class_initialize ()\n {\n#define DECLARE(Name) \\\n system_class->slot_set \\\n (SYMBOL(Name), \\\n make_primitive(&system_##Name, SYMBOL(Name))) \\\n\n DECLARE(getenv);\n DECLARE(setenv);\n DECLARE(unsetenv);\n\n#undef DECLARE\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(system, Name)\n\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(debugoff);\n DECLARE(debugon);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(shiftedTime);\n DECLARE(stats);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stopall);\n DECLARE(time);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\n<|endoftext|>"} {"text":"\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n#include \n\n\/\/#define ENABLE_DEBUG_TRACES\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace object\n{\n using kernel::urbiserver;\n\n\n static inline\n runner::Runner&\n runner()\n {\n return ::kernel::urbiserver->getCurrentRunner();\n }\n\n static inline\n runner::Interpreter&\n interpreter()\n {\n return dynamic_cast(runner());\n }\n\n \/\/ Extract a filename from a String or a Path object\n static std::string\n filename_get(const rObject& o)\n {\n if (o.is_a())\n return o->as()->as_string();\n type_check(o);\n return o->as()->value_get();\n }\n\n\n rObject\n execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = interpreter();\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n runner::raise_primitive_error(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n sched::rJob job = sub;\n libport::Finally finally;\n runner().register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const sched::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Function(); \\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static void\n system_sleep(const rObject&, libport::ufloat seconds)\n {\n runner::Runner& r = runner();\n if (seconds == std::numeric_limits::infinity())\n r.yield_until_terminated(r);\n else\n r.yield_until(r.scheduler_get().get_time()\n + static_cast(seconds * 1000000.0));\n }\n\n static float\n system_time()\n {\n return runner().scheduler_get().get_time() \/ 1000000.0;\n }\n\n static float\n system_shiftedTime()\n {\n runner::Runner& r = runner();\n return (r.scheduler_get().get_time() - r.time_shift_get()) \/ 1000000.0;\n }\n\n static void\n system_assert_(const rObject&,\n const rObject& value, const std::string& assertion)\n {\n if (!is_true(value))\n runner::raise_primitive_error(\"failed assertion: \" + assertion);\n }\n\n static rObject\n system_eval(const rObject&, const std::string& code)\n {\n return execute_parsed(parser::parse(code, ast::loc()),\n SYMBOL(eval),\n \"error executing command: \" + code);\n }\n\n static rObject\n system_class_registerAtJob (objects_type args)\n {\n check_arg_count(args.size() - 1, 3);\n runner::register_at_job(interpreter(),\n\t\t\t args[1], args[2], args[3]);\n return object::void_class;\n }\n\n static rObject\n system_scopeTag()\n {\n return new Tag(interpreter().scope_tag());\n }\n\n static rObject\n system_class_searchFile(objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n const std::string filename = filename_get(args[1]);\n\n try\n {\n return new Path(urbiserver->find_file(filename));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static List::value_type\n system_searchPath()\n {\n List::value_type res;\n foreach (const libport::path& p, urbiserver->search_path.search_path_get())\n res.push_back(new Path(p));\n return res;\n }\n\n static rObject\n system_class_loadFile(objects_type args)\n {\n check_arg_count(args.size() - 1, 1);\n const std::string filename = filename_get(args[1]);\n\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_currentRunner()\n {\n return runner().as_task();\n }\n\n static float\n system_cycle()\n {\n return runner().scheduler_get().cycle_get();\n }\n\n static libport::Symbol\n system_fresh()\n {\n return libport::Symbol::fresh();\n }\n\n static rObject\n system_lobby()\n {\n return runner().lobby_get();\n }\n\n static void\n system_nonInterruptible()\n {\n runner().non_interruptible_set(true);\n }\n\n static void\n system_quit()\n {\n runner().lobby_get()->connection_get().close();\n }\n\n static void\n system_spawn(const rObject&,\n\t const rCode& code,\n const rObject& clear_tags)\n {\n runner::Runner& r = runner();\n runner::Interpreter* new_runner =\n new runner::Interpreter(interpreter(),\n rObject(code),\n libport::Symbol::fresh(r.name_get()));\n\n if (is_true(clear_tags))\n new_runner->tag_stack_clear();\n\n new_runner->time_shift_set(r.time_shift_get());\n new_runner->start_job();\n }\n\n static rObject\n system_stats()\n {\n Dictionary::value_type res;\n const sched::scheduler_stats_type& stats =\n runner().scheduler_get().stats_get();\n\n \/\/ If statistics have just been reset, return \"nil\" since we cannot\n \/\/ return anything significant.\n if (stats.empty())\n return nil_class;\n\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor) \\\n res[libport::Symbol(\"cycles\" # Suffix)] = \\\n new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1e6);\n ADDSTAT(Mean, mean, 1e6);\n ADDSTAT(Min, min, 1e6);\n ADDSTAT(StdDev, standard_deviation, 1e6);\n ADDSTAT(Variance, variance, 1e3);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static void\n system_resetStats()\n {\n runner().scheduler_get().stats_reset();\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static void\n system_backtrace()\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n runner::Runner::backtrace_type bt = runner().backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n runner().send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n }\n\n static List::value_type\n system_jobs()\n {\n List::value_type res;\n foreach(sched::rJob job, runner().scheduler_get().jobs_get())\n res.push_back(dynamic_cast(job.get())->as_task());\n return res;\n }\n\n static int\n system_aliveJobs()\n {\n return sched::Job::alive_jobs();\n }\n\n static void\n system_breakpoint()\n {\n return;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Variable = Value; \\\n }\n\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject system_getenv(const rObject&, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : nil_class;\n }\n\n static rObject system_setenv(const rObject&, const std::string& name, rObject value)\n {\n rString v = value->call(SYMBOL(asString))->as();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject system_unsetenv(const rObject&, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker::set_type system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n\n static void system_loadModule(const rObject&, const std::string& name)\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n initialized = true;\n lt_dlinit();\n }\n lt_dlhandle handle = lt_dlopenext(name.c_str());\n if (!handle)\n runner::raise_primitive_error\n (\"Failed to open `\" + name + \"': \" + lt_dlerror());\n\n \/\/ Reload uobjects\n uobjects_reload();\n\n \/\/ Reload CxxObjects\n CxxObject::create();\n CxxObject::initialize(global_class);\n CxxObject::cleanup();\n }\n\n static libport::cli_args_type urbi_arguments_;\n static boost::optional urbi_program_name_;\n\n void system_push_argument(const std::string& arg)\n {\n urbi_arguments_.push_back(arg);\n }\n\n void system_set_program_name(const std::string& name)\n {\n urbi_program_name_ = name;\n }\n\n static const libport::cli_args_type& system_arguments()\n {\n return urbi_arguments_;\n }\n\n static boost::optional system_programName()\n {\n return urbi_program_name_;\n }\n\n static void system__exit(const rObject&, int status)\n {\n exit(status);\n }\n\n void\n system_class_initialize ()\n {\n#define DECLARE(Name) \\\n system_class->slot_set(SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(_exit);\n DECLARE(aliveJobs);\n DECLARE(arguments);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(getenv);\n DECLARE(jobs);\n DECLARE(loadModule);\n DECLARE(lobbies);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(programName);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(resetStats);\n DECLARE(scopeTag);\n DECLARE(searchPath);\n DECLARE(setenv);\n DECLARE(shiftedTime);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stats);\n DECLARE(stopall);\n DECLARE(time);\n DECLARE(unsetenv);\n\n#undef DECLARE\n\n \/\/\/ \\a Call gives the name of the C++ function, and \\a Name that in Urbi.\n#define DECLARE(Name)\t\t\t\t\\\n DECLARE_PRIMITIVE(system, Name)\n\n DECLARE(loadFile);\n DECLARE(registerAtJob);\n DECLARE(searchFile);\n#undef DECLARE\n }\n\n}; \/\/ namespace object\nsystem: finish migration.\/**\n ** \\file object\/system-class.cc\n ** \\brief Creation of the URBI object system.\n *\/\n\n#include \n\n\/\/#define ENABLE_DEBUG_TRACES\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace object\n{\n using kernel::urbiserver;\n\n\n static inline\n runner::Runner&\n runner()\n {\n return ::kernel::urbiserver->getCurrentRunner();\n }\n\n static inline\n runner::Interpreter&\n interpreter()\n {\n return dynamic_cast(runner());\n }\n\n \/\/ Extract a filename from a String or a Path object\n static std::string\n filename_get(const rObject& o)\n {\n if (o.is_a())\n return o->as()->as_string();\n type_check(o);\n return o->as()->value_get();\n }\n\n\n rObject\n execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e)\n {\n runner::Interpreter& run = interpreter();\n\n \/\/ Report potential errors\n {\n ast::rNary errs = new ast::Nary();\n p->process_errors(*errs);\n run(errs.get());\n }\n\n ast::rConstAst ast = parser::transform(p->ast_get());\n if (!ast)\n runner::raise_primitive_error(e);\n\n runner::Interpreter* sub = new runner::Interpreter(run, ast, fun);\n \/\/ So that it will resist to the call to yield_until_terminated,\n \/\/ and will be reclaimed at the end of the scope.\n sched::rJob job = sub;\n libport::Finally finally;\n runner().register_child(sub, finally);\n sub->start_job();\n try\n {\n run.yield_until_terminated(*job);\n }\n catch (const sched::ChildException& ce)\n {\n \/\/ Kill the sub-job and propagate.\n ce.rethrow_child_exception();\n }\n return sub->result_get();\n }\n\n\n rObject system_class;\n\n \/*--------------------.\n | System primitives. |\n `--------------------*\/\n\n\n#define SERVER_FUNCTION(Function) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Function(); \\\n }\n\n SERVER_FUNCTION(reboot)\n SERVER_FUNCTION(shutdown)\n\n#undef SERVER_FUNCTION\n\n\n static void\n system_sleep(const rObject&, libport::ufloat seconds)\n {\n runner::Runner& r = runner();\n if (seconds == std::numeric_limits::infinity())\n r.yield_until_terminated(r);\n else\n r.yield_until(r.scheduler_get().get_time()\n + static_cast(seconds * 1000000.0));\n }\n\n static float\n system_time()\n {\n return runner().scheduler_get().get_time() \/ 1000000.0;\n }\n\n static float\n system_shiftedTime()\n {\n runner::Runner& r = runner();\n return (r.scheduler_get().get_time() - r.time_shift_get()) \/ 1000000.0;\n }\n\n static void\n system_assert_(const rObject&,\n const rObject& value, const std::string& assertion)\n {\n if (!is_true(value))\n runner::raise_primitive_error(\"failed assertion: \" + assertion);\n }\n\n static rObject\n system_eval(const rObject&, const std::string& code)\n {\n return execute_parsed(parser::parse(code, ast::loc()),\n SYMBOL(eval),\n \"error executing command: \" + code);\n }\n\n static void\n system_registerAtJob(const rObject&,\n const rObject& condition,\n const rObject& clause,\n const rObject& on_leave)\n {\n runner::register_at_job(interpreter(),\n\t\t\t condition, clause, on_leave);\n }\n\n static rObject\n system_scopeTag()\n {\n return new Tag(interpreter().scope_tag());\n }\n\n static rObject\n system_searchFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n try\n {\n return new Path(urbiserver->find_file(filename));\n }\n catch (libport::file_library::Not_found&)\n {\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n \/\/ Never reached\n assertion(false);\n return 0;\n }\n }\n\n static List::value_type\n system_searchPath()\n {\n List::value_type res;\n foreach (const libport::path& p, urbiserver->search_path.search_path_get())\n res.push_back(new Path(p));\n return res;\n }\n\n static rObject\n system_loadFile(const rObject&, const rObject& f)\n {\n const std::string& filename = filename_get(f);\n if (!libport::path(filename).exists())\n runner::raise_urbi(SYMBOL(FileNotFound), to_urbi(filename));\n return\n execute_parsed(parser::parse_file(filename),\n SYMBOL(loadFile),\n\t\t \"error loading file: \" + filename);\n }\n\n static rObject\n system_currentRunner()\n {\n return runner().as_task();\n }\n\n static float\n system_cycle()\n {\n return runner().scheduler_get().cycle_get();\n }\n\n static libport::Symbol\n system_fresh()\n {\n return libport::Symbol::fresh();\n }\n\n static rObject\n system_lobby()\n {\n return runner().lobby_get();\n }\n\n static void\n system_nonInterruptible()\n {\n runner().non_interruptible_set(true);\n }\n\n static void\n system_quit()\n {\n runner().lobby_get()->connection_get().close();\n }\n\n static void\n system_spawn(const rObject&,\n\t const rCode& code,\n const rObject& clear_tags)\n {\n runner::Runner& r = runner();\n runner::Interpreter* new_runner =\n new runner::Interpreter(interpreter(),\n rObject(code),\n libport::Symbol::fresh(r.name_get()));\n\n if (is_true(clear_tags))\n new_runner->tag_stack_clear();\n\n new_runner->time_shift_set(r.time_shift_get());\n new_runner->start_job();\n }\n\n static rObject\n system_stats()\n {\n Dictionary::value_type res;\n const sched::scheduler_stats_type& stats =\n runner().scheduler_get().stats_get();\n\n \/\/ If statistics have just been reset, return \"nil\" since we cannot\n \/\/ return anything significant.\n if (stats.empty())\n return nil_class;\n\n \/\/ The space after \"Symbol(\" is mandatory to avoid triggering an error in\n \/\/ symbol generation code\n#define ADDSTAT(Suffix, Function, Divisor) \\\n res[libport::Symbol(\"cycles\" # Suffix)] = \\\n new Float(stats.Function() \/ Divisor)\n ADDSTAT(, size, 1);\n ADDSTAT(Max, max, 1e6);\n ADDSTAT(Mean, mean, 1e6);\n ADDSTAT(Min, min, 1e6);\n ADDSTAT(StdDev, standard_deviation, 1e6);\n ADDSTAT(Variance, variance, 1e3);\n#undef ADDSTAT\n return new Dictionary(res);\n }\n\n static void\n system_resetStats()\n {\n runner().scheduler_get().stats_reset();\n }\n\n \/\/ This should give a backtrace as an urbi object.\n static void\n system_backtrace()\n {\n \/\/ FIXME: This method sucks a bit, because show_backtrace sucks a\n \/\/ bit, because our channeling\/message-sending system sucks a lot.\n runner::Runner::backtrace_type bt = runner().backtrace_get();\n bt.pop_back();\n foreach (const runner::Runner::frame_type& elt,\n\t boost::make_iterator_range(boost::rbegin(bt),\n\t\t\t\t\tboost::rend(bt)))\n runner().send_message(\"backtrace\", elt.first + \" (\" + elt.second + \")\");\n }\n\n static List::value_type\n system_jobs()\n {\n List::value_type res;\n foreach(sched::rJob job, runner().scheduler_get().jobs_get())\n res.push_back(dynamic_cast(job.get())->as_task());\n return res;\n }\n\n static int\n system_aliveJobs()\n {\n return sched::Job::alive_jobs();\n }\n\n static void\n system_breakpoint()\n {\n return;\n }\n\n#define SERVER_SET_VAR(Function, Variable, Value) \\\n static void \\\n system_ ## Function () \\\n { \\\n urbiserver->Variable = Value; \\\n }\n\n SERVER_SET_VAR(stopall, stopall, true)\n\n#undef SERVER_SET_VAR\n\n static rObject system_getenv(const rObject&, const std::string& name)\n {\n char* res = getenv(name.c_str());\n return res ? new String(res) : nil_class;\n }\n\n static rObject system_setenv(const rObject&, const std::string& name, rObject value)\n {\n rString v = value->call(SYMBOL(asString))->as();\n setenv(name.c_str(), v->value_get().c_str(), 1);\n return v;\n }\n\n static rObject system_unsetenv(const rObject&, const std::string& name)\n {\n rObject res = system_getenv(0, name);\n unsetenv(name.c_str());\n return res;\n }\n\n static libport::InstanceTracker::set_type system_lobbies()\n {\n return Lobby::instances_get();\n }\n\n\n static void system_loadModule(const rObject&, const std::string& name)\n {\n static bool initialized = false;\n\n if (!initialized)\n {\n initialized = true;\n lt_dlinit();\n }\n lt_dlhandle handle = lt_dlopenext(name.c_str());\n if (!handle)\n runner::raise_primitive_error\n (\"Failed to open `\" + name + \"': \" + lt_dlerror());\n\n \/\/ Reload uobjects\n uobjects_reload();\n\n \/\/ Reload CxxObjects\n CxxObject::create();\n CxxObject::initialize(global_class);\n CxxObject::cleanup();\n }\n\n static libport::cli_args_type urbi_arguments_;\n static boost::optional urbi_program_name_;\n\n void system_push_argument(const std::string& arg)\n {\n urbi_arguments_.push_back(arg);\n }\n\n void system_set_program_name(const std::string& name)\n {\n urbi_program_name_ = name;\n }\n\n static const libport::cli_args_type& system_arguments()\n {\n return urbi_arguments_;\n }\n\n static boost::optional system_programName()\n {\n return urbi_program_name_;\n }\n\n static void system__exit(const rObject&, int status)\n {\n exit(status);\n }\n\n void\n system_class_initialize ()\n {\n#define DECLARE(Name) \\\n system_class->slot_set(SYMBOL(Name), \\\n make_primitive(&system_##Name)) \\\n\n DECLARE(_exit);\n DECLARE(aliveJobs);\n DECLARE(arguments);\n DECLARE(assert_);\n DECLARE(backtrace);\n DECLARE(breakpoint);\n DECLARE(currentRunner);\n DECLARE(cycle);\n DECLARE(eval);\n DECLARE(fresh);\n DECLARE(getenv);\n DECLARE(jobs);\n DECLARE(loadFile);\n DECLARE(loadModule);\n DECLARE(lobbies);\n DECLARE(lobby);\n DECLARE(nonInterruptible);\n DECLARE(programName);\n DECLARE(quit);\n DECLARE(reboot);\n DECLARE(registerAtJob);\n DECLARE(resetStats);\n DECLARE(scopeTag);\n DECLARE(searchFile);\n DECLARE(searchPath);\n DECLARE(setenv);\n DECLARE(shiftedTime);\n DECLARE(shutdown);\n DECLARE(sleep);\n DECLARE(spawn);\n DECLARE(stats);\n DECLARE(stopall);\n DECLARE(time);\n DECLARE(unsetenv);\n\n#undef DECLARE\n }\n\n} \/\/ namespace object\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file object\/system-class.hh\n ** \\brief Definition of the URBI object system.\n *\/\n\n#ifndef OBJECT_SYSTEM_CLASS_HH\n# define OBJECT_SYSTEM_CLASS_HH\n\n# include \n# include \n# include \n\nnamespace urbi\n{\n namespace object\n {\n extern rObject system_class;\n\n \/\/\/ Parse, bind etc. and execute code.\n \/\/\/\n \/\/\/ Used internally and from the debugging routines.\n \/\/\/\n \/\/\/ \\param r runner that must be an Interpreter.\n \/\/\/ \\param p the parser result.\n \/\/\/ \\param fun name of the caller.\n \/\/\/ \\param e exception to raise on error.\n \/\/\/ \\returns the result of the evaluation.\n rObject execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e);\n \/\/\/ Set the current script name\n void system_set_program_name(const std::string& name);\n \/\/\/ Register a new user-argument for the script\n void system_push_argument(const std::string& arg);\n\n \/\/\/ Initialize the System class.\n void system_class_initialize();\n\n \/\/\/ Return true if location is from a system file.\n bool is_system_location(const ast::loc& l);\n\n typedef std::set system_files_type;\n \/\/\/ Return the list of loaded system files.\n system_files_type& system_files_get();\n }; \/\/ namespace object\n}\n\n#endif \/\/ !OBJECT_SYSTEM_CLASS_HH\nFormatting changes.\/*\n * Copyright (C) 2009, Gostai S.A.S.\n *\n * This software is provided \"as is\" without warranty of any kind,\n * either expressed or implied, including but not limited to the\n * implied warranties of fitness for a particular purpose.\n *\n * See the LICENSE file for more information.\n *\/\n\/**\n ** \\file object\/system-class.hh\n ** \\brief Definition of the URBI object system.\n *\/\n\n#ifndef OBJECT_SYSTEM_CLASS_HH\n# define OBJECT_SYSTEM_CLASS_HH\n\n# include \n# include \n# include \n\nnamespace urbi\n{\n namespace object\n {\n extern rObject system_class;\n\n \/\/\/ Parse, bind etc. and execute code.\n \/\/\/\n \/\/\/ Used internally and from the debugging routines.\n \/\/\/\n \/\/\/ \\param r runner that must be an Interpreter.\n \/\/\/ \\param p the parser result.\n \/\/\/ \\param fun name of the caller.\n \/\/\/ \\param e exception to raise on error.\n \/\/\/ \\returns the result of the evaluation.\n rObject execute_parsed(parser::parse_result_type p,\n libport::Symbol fun, std::string e);\n \/\/\/ Set the current script name\n void system_set_program_name(const std::string& name);\n \/\/\/ Register a new user-argument for the script\n void system_push_argument(const std::string& arg);\n\n \/\/\/ Initialize the System class.\n void system_class_initialize();\n\n \/\/\/ Return true if location is from a system file.\n bool is_system_location(const ast::loc& l);\n\n typedef std::set system_files_type;\n \/\/\/ Return the list of loaded system files.\n system_files_type& system_files_get();\n }; \/\/ namespace object\n}\n\n#endif \/\/ !OBJECT_SYSTEM_CLASS_HH\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2009 SpringSource, Inc.\n * Copyright (c) 2009 VMware, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#define UNICODE\n#define _UNICODE\n#define _WIN32_DCOM\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sigar.h\"\n#include \"sigar_private.h\"\n#include \"sigar_pdh.h\"\n#include \"sigar_os.h\"\n#include \"sigar_util.h\"\n#include \"sigar_format.h\"\n\n#pragma comment(lib, \"wbemuuid.lib\")\n\n#ifndef SIGAR_CMDLINE_MAX\n#define SIGAR_CMDLINE_MAX 4096<<2\n#endif\n\n#ifndef _MSC_VER\n\nDEFINE_GUID(CLSID_WbemLocator, 0x4590f811, 0x1d3a, 0x11d0, 0x89, 0x1f, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24);\ntemplate <> const GUID & __mingw_uuidof < IWbemLocator > () {\n\treturn IID_IWbemLocator;\n}\n\ntemplate <> const GUID & __mingw_uuidof < IWbemLocator * >() {\n\treturn __mingw_uuidof < IWbemLocator > ();\n}\n#endif\nextern \"C\" {\n\nint wmi_map_sigar_error(HRESULT hres)\n{\n\tswitch (hres) {\n\tcase S_OK:\n\t\treturn ERROR_SUCCESS;\n\tcase WBEM_E_NOT_FOUND:\n\t\treturn ERROR_NOT_FOUND;\n\tcase WBEM_E_ACCESS_DENIED:\n\t\treturn ERROR_ACCESS_DENIED;\n\tcase WBEM_E_NOT_SUPPORTED:\n\t\treturn SIGAR_ENOTIMPL;\n\tdefault:\n\t\treturn ERROR_INVALID_FUNCTION;\n\t}\n}\n\nvoid wmi_handle_close(sigar_wmi_handle_t *wmi_handle)\n{\n\tif(wmi_handle == NULL)\n\t\treturn;\n\n\tif (wmi_handle->services) {\n\t\twmi_handle->services->Release();\n\t\twmi_handle->services = NULL;\n\t}\n\n\tif (wmi_handle->locator) {\n\t\twmi_handle->locator->Release();\n\t\twmi_handle->services = NULL;\n\t}\n}\n\nsigar_wmi_handle_t * wmi_handle_open(int *error)\n{\n\t*error = SIGAR_OK;\n\n\tsigar_wmi_handle_t *handle;\n\n\thandle = (sigar_wmi_handle_t *)calloc(1, sizeof (*handle));\n\n\tHRESULT hres;\n\twchar_t root[] = L\"root\\\\CIMV2\";\n\n\thres = CoInitializeEx(NULL, COINIT_MULTITHREADED);\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\thres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,\n RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0);\n\n\t\/*\n\t* If RPC_E_TOO_LATE then we have already been called. This happens in the case of\n\t* multiple sigar instances since this should only be called once per application.\n\t*\/\n\n\tif (FAILED(hres) && hres != RPC_E_TOO_LATE) {\n\t\tgoto err;\n\t}\n\n\thres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&handle->locator));\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\thres = handle->locator->ConnectServer(root, NULL, NULL, NULL,\n WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &handle->services);\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\treturn handle;\nerr:\n\twmi_handle_close(handle);\n\t*error = wmi_map_sigar_error(hres);\n\treturn NULL;\n}\n\nHRESULT wmi_get_proc_string_property(sigar_t *sigar, DWORD pid, TCHAR * name, TCHAR * value, DWORD len)\n{\n\tIWbemClassObject *obj;\n\tVARIANT var;\n\tHRESULT result;\n\n\tif(sigar->wmi_handle == NULL)\n return (E_INVALIDARG);\n\n\twchar_t query[56];\n\twsprintf(query, L\"Win32_Process.Handle=%d\", pid);\n\n\tresult = sigar->wmi_handle->services->GetObject(query, 0, 0, &obj, 0);\n\n\tif (FAILED(result)) {\n\t\treturn result;\n\t}\n\n\tresult = obj->Get(name, 0, &var, 0, 0);\n\n\tif (SUCCEEDED(result)) {\n\t\tif (var.vt == VT_NULL) {\n\t\t\tresult = E_INVALIDARG;\n\t\t} else {\n\t\t\tlstrcpyn(value, var.bstrVal, len);\n\t\t}\n\t\tVariantClear(&var);\n\t}\n\n\tobj->Release();\n\n\treturn result;\n}\n\nHRESULT wmi_get_proc_executable_path(sigar_t *sigar, DWORD pid, TCHAR * value)\n{\n\twchar_t prop[] = L\"ExecutablePath\";\n\treturn wmi_get_proc_string_property(sigar, pid, prop, value, MAX_PATH);\n}\n\nHRESULT wmi_get_proc_command_line(sigar_t *sigar, DWORD pid, TCHAR * value)\n{\n\twchar_t prop[] = L\"CommandLine\";\n\treturn wmi_get_proc_string_property(sigar, pid, prop, value, MAX_PATH);\n}\n\nIEnumWbemClassObject *wmi_query(sigar_t *sigar, const wchar_t * query)\n{\n\tIEnumWbemClassObject *wmi_enum = NULL;\n\tif (sigar->wmi_handle) {\n\t\twchar_t lang[] = L\"WQL\";\n\t\twchar_t *query_cpy = wcsdup(query);\n\n\t\tHRESULT hres =\n\t\t\tsigar->wmi_handle->services->ExecQuery(lang, query_cpy, WBEM_FLAG_FORWARD_ONLY, NULL, &wmi_enum);\n\n\t\tfree(query_cpy);\n\t}\n\treturn wmi_enum;\n}\n\nint wmi_query_sum_u64(sigar_t *sigar, const wchar_t * query, const wchar_t * attrib,\n\t\t\t\t\t sigar_uint64_t * sum, unsigned long *num_elems)\n{\n\t*sum = 0;\n\t*num_elems = 0;\n\n\tIEnumWbemClassObject *wmi_enum = wmi_query(sigar, query);\n\tif (!wmi_enum) {\n\t\treturn -1;\n\t}\n\n\twchar_t *attrib_cpy = wcsdup(attrib);\n\n\tIWbemClassObject *wmi_obj = NULL;\n\tHRESULT hres;\n\tunsigned long curr_elem = 0;\n\twhile (((hres = wmi_enum->Next(WBEM_INFINITE, 1, &wmi_obj, &curr_elem)) != WBEM_S_FALSE)\n\t\t && !FAILED(hres)) {\n\t\t(*num_elems)++;\n\t\tVARIANT val;\n\t\tVariantInit(&val);\n\t\tif (SUCCEEDED(wmi_obj->Get(attrib_cpy, 0, &val, NULL, NULL))) {\n\t\t\tif (val.vt == VT_BSTR) {\n\t\t\t\t*sum += _wtoi(val.bstrVal);\n\t\t\t} else {\n\t\t\t\t*sum += val.intVal;\n\t\t\t}\n\t\t}\n\t\twmi_obj->Release();\n\t}\n\n\tfree(attrib_cpy);\n\twmi_enum->Release();\n\n\treturn 0;\n}\n\nint wmi_query_sum_u32(sigar_t *sigar, const wchar_t * query,\n\t\tconst wchar_t * attrib, sigar_uint32_t * sum, unsigned long *num_elems)\n{\n\tsigar_uint64_t sum64 = 0;\n\tint rc = wmi_query_sum_u64(sigar, query, attrib, &sum64, num_elems);\n\t*sum = sum64;\n\treturn rc;\n}\n\nint wmi_query_avg(sigar_t *sigar, const wchar_t * query,\n\t\tconst wchar_t * attrib, float *avg)\n{\n\tsigar_uint64_t sum = 0;\n\tunsigned long num_elems = 0;\n\tint rc = wmi_query_sum_u64(sigar, query, attrib, &sum, &num_elems);\n\tif (!rc && num_elems) {\n\t\t*avg = sum \/ (double)(num_elems);\n\t}\n\treturn rc;\n}\n\n\/* in peb.c *\/\nint sigar_parse_proc_args(sigar_t * sigar, WCHAR * buf, sigar_proc_args_t * procargs);\n\nint sigar_proc_args_wmi_get(sigar_t * sigar, sigar_pid_t pid, sigar_proc_args_t * procargs)\n{\n\tTCHAR buf[SIGAR_CMDLINE_MAX];\n\tint status;\n\n\tif ((status = wmi_get_proc_command_line(sigar, pid, buf))) {\n\t\tgoto out;\n\t} else {\n\t\tstatus = sigar_parse_proc_args(sigar, buf, procargs);\n\t}\n\nout:\n\treturn status;\n}\n\nint sigar_proc_exe_wmi_get(sigar_t * sigar, sigar_pid_t pid, sigar_proc_exe_t * procexe)\n{\n\tTCHAR buf[MAX_PATH + 1];\n\tint status;\n\n\tprocexe->name[0] = '\\0';\n\n\tif ((status = wmi_get_proc_executable_path(sigar, pid, buf))) {\n\t\tgoto out;\n\t} else {\n\t\tstatus = SIGAR_OK;\n\t\t\/* SIGAR_W2A(buf, procexe->name, sizeof(procexe->name)); *\/\n\t\tWideCharToMultiByte(CP_ACP, 0, buf, -1,\n\t\t\t(LPSTR) procexe->name, sizeof(procexe->name), NULL, NULL);\n\t}\n\nout:\n\treturn status;\n}\n}\t\t\t\t\t\t\t\t\/\/extern \"C\"\nconditionally define WbemLocator\/*\n * Copyright (c) 2009 SpringSource, Inc.\n * Copyright (c) 2009 VMware, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#define UNICODE\n#define _UNICODE\n#define _WIN32_DCOM\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sigar.h\"\n#include \"sigar_private.h\"\n#include \"sigar_pdh.h\"\n#include \"sigar_os.h\"\n#include \"sigar_util.h\"\n#include \"sigar_format.h\"\n\n#pragma comment(lib, \"wbemuuid.lib\")\n\n#ifndef SIGAR_CMDLINE_MAX\n#define SIGAR_CMDLINE_MAX 4096<<2\n#endif\n\n#if !defined(_MSC_VER) && !defined(__WbemLocator_FWD_DEFINED__)\n\nDEFINE_GUID(CLSID_WbemLocator, 0x4590f811, 0x1d3a, 0x11d0, 0x89, 0x1f, 0x00, 0xaa, 0x00, 0x4b, 0x2e, 0x24);\ntemplate <> const GUID & __mingw_uuidof < IWbemLocator > () {\n\treturn IID_IWbemLocator;\n}\n\ntemplate <> const GUID & __mingw_uuidof < IWbemLocator * >() {\n\treturn __mingw_uuidof < IWbemLocator > ();\n}\n\n#endif\nextern \"C\" {\n\nint wmi_map_sigar_error(HRESULT hres)\n{\n\tswitch (hres) {\n\tcase S_OK:\n\t\treturn ERROR_SUCCESS;\n\tcase WBEM_E_NOT_FOUND:\n\t\treturn ERROR_NOT_FOUND;\n\tcase WBEM_E_ACCESS_DENIED:\n\t\treturn ERROR_ACCESS_DENIED;\n\tcase WBEM_E_NOT_SUPPORTED:\n\t\treturn SIGAR_ENOTIMPL;\n\tdefault:\n\t\treturn ERROR_INVALID_FUNCTION;\n\t}\n}\n\nvoid wmi_handle_close(sigar_wmi_handle_t *wmi_handle)\n{\n\tif(wmi_handle == NULL)\n\t\treturn;\n\n\tif (wmi_handle->services) {\n\t\twmi_handle->services->Release();\n\t\twmi_handle->services = NULL;\n\t}\n\n\tif (wmi_handle->locator) {\n\t\twmi_handle->locator->Release();\n\t\twmi_handle->services = NULL;\n\t}\n}\n\nsigar_wmi_handle_t * wmi_handle_open(int *error)\n{\n\t*error = SIGAR_OK;\n\n\tsigar_wmi_handle_t *handle;\n\n\thandle = (sigar_wmi_handle_t *)calloc(1, sizeof (*handle));\n\n\tHRESULT hres;\n\twchar_t root[] = L\"root\\\\CIMV2\";\n\n\thres = CoInitializeEx(NULL, COINIT_MULTITHREADED);\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\thres = CoInitializeSecurity(NULL, -1, NULL, NULL, RPC_C_AUTHN_LEVEL_CONNECT,\n RPC_C_IMP_LEVEL_IMPERSONATE, NULL, EOAC_NONE, 0);\n\n\t\/*\n\t* If RPC_E_TOO_LATE then we have already been called. This happens in the case of\n\t* multiple sigar instances since this should only be called once per application.\n\t*\/\n\n\tif (FAILED(hres) && hres != RPC_E_TOO_LATE) {\n\t\tgoto err;\n\t}\n\n\thres = CoCreateInstance(CLSID_WbemLocator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&handle->locator));\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\thres = handle->locator->ConnectServer(root, NULL, NULL, NULL,\n WBEM_FLAG_CONNECT_USE_MAX_WAIT, NULL, NULL, &handle->services);\n\tif (FAILED(hres)) {\n\t\tgoto err;\n\t}\n\n\treturn handle;\nerr:\n\twmi_handle_close(handle);\n\t*error = wmi_map_sigar_error(hres);\n\treturn NULL;\n}\n\nHRESULT wmi_get_proc_string_property(sigar_t *sigar, DWORD pid, TCHAR * name, TCHAR * value, DWORD len)\n{\n\tIWbemClassObject *obj;\n\tVARIANT var;\n\tHRESULT result;\n\n\tif(sigar->wmi_handle == NULL)\n return (E_INVALIDARG);\n\n\twchar_t query[56];\n\twsprintf(query, L\"Win32_Process.Handle=%d\", pid);\n\n\tresult = sigar->wmi_handle->services->GetObject(query, 0, 0, &obj, 0);\n\n\tif (FAILED(result)) {\n\t\treturn result;\n\t}\n\n\tresult = obj->Get(name, 0, &var, 0, 0);\n\n\tif (SUCCEEDED(result)) {\n\t\tif (var.vt == VT_NULL) {\n\t\t\tresult = E_INVALIDARG;\n\t\t} else {\n\t\t\tlstrcpyn(value, var.bstrVal, len);\n\t\t}\n\t\tVariantClear(&var);\n\t}\n\n\tobj->Release();\n\n\treturn result;\n}\n\nHRESULT wmi_get_proc_executable_path(sigar_t *sigar, DWORD pid, TCHAR * value)\n{\n\twchar_t prop[] = L\"ExecutablePath\";\n\treturn wmi_get_proc_string_property(sigar, pid, prop, value, MAX_PATH);\n}\n\nHRESULT wmi_get_proc_command_line(sigar_t *sigar, DWORD pid, TCHAR * value)\n{\n\twchar_t prop[] = L\"CommandLine\";\n\treturn wmi_get_proc_string_property(sigar, pid, prop, value, MAX_PATH);\n}\n\nIEnumWbemClassObject *wmi_query(sigar_t *sigar, const wchar_t * query)\n{\n\tIEnumWbemClassObject *wmi_enum = NULL;\n\tif (sigar->wmi_handle) {\n\t\twchar_t lang[] = L\"WQL\";\n\t\twchar_t *query_cpy = wcsdup(query);\n\n\t\tHRESULT hres =\n\t\t\tsigar->wmi_handle->services->ExecQuery(lang, query_cpy, WBEM_FLAG_FORWARD_ONLY, NULL, &wmi_enum);\n\n\t\tfree(query_cpy);\n\t}\n\treturn wmi_enum;\n}\n\nint wmi_query_sum_u64(sigar_t *sigar, const wchar_t * query, const wchar_t * attrib,\n\t\t\t\t\t sigar_uint64_t * sum, unsigned long *num_elems)\n{\n\t*sum = 0;\n\t*num_elems = 0;\n\n\tIEnumWbemClassObject *wmi_enum = wmi_query(sigar, query);\n\tif (!wmi_enum) {\n\t\treturn -1;\n\t}\n\n\twchar_t *attrib_cpy = wcsdup(attrib);\n\n\tIWbemClassObject *wmi_obj = NULL;\n\tHRESULT hres;\n\tunsigned long curr_elem = 0;\n\twhile (((hres = wmi_enum->Next(WBEM_INFINITE, 1, &wmi_obj, &curr_elem)) != WBEM_S_FALSE)\n\t\t && !FAILED(hres)) {\n\t\t(*num_elems)++;\n\t\tVARIANT val;\n\t\tVariantInit(&val);\n\t\tif (SUCCEEDED(wmi_obj->Get(attrib_cpy, 0, &val, NULL, NULL))) {\n\t\t\tif (val.vt == VT_BSTR) {\n\t\t\t\t*sum += _wtoi(val.bstrVal);\n\t\t\t} else {\n\t\t\t\t*sum += val.intVal;\n\t\t\t}\n\t\t}\n\t\twmi_obj->Release();\n\t}\n\n\tfree(attrib_cpy);\n\twmi_enum->Release();\n\n\treturn 0;\n}\n\nint wmi_query_sum_u32(sigar_t *sigar, const wchar_t * query,\n\t\tconst wchar_t * attrib, sigar_uint32_t * sum, unsigned long *num_elems)\n{\n\tsigar_uint64_t sum64 = 0;\n\tint rc = wmi_query_sum_u64(sigar, query, attrib, &sum64, num_elems);\n\t*sum = sum64;\n\treturn rc;\n}\n\nint wmi_query_avg(sigar_t *sigar, const wchar_t * query,\n\t\tconst wchar_t * attrib, float *avg)\n{\n\tsigar_uint64_t sum = 0;\n\tunsigned long num_elems = 0;\n\tint rc = wmi_query_sum_u64(sigar, query, attrib, &sum, &num_elems);\n\tif (!rc && num_elems) {\n\t\t*avg = sum \/ (double)(num_elems);\n\t}\n\treturn rc;\n}\n\n\/* in peb.c *\/\nint sigar_parse_proc_args(sigar_t * sigar, WCHAR * buf, sigar_proc_args_t * procargs);\n\nint sigar_proc_args_wmi_get(sigar_t * sigar, sigar_pid_t pid, sigar_proc_args_t * procargs)\n{\n\tTCHAR buf[SIGAR_CMDLINE_MAX];\n\tint status;\n\n\tif ((status = wmi_get_proc_command_line(sigar, pid, buf))) {\n\t\tgoto out;\n\t} else {\n\t\tstatus = sigar_parse_proc_args(sigar, buf, procargs);\n\t}\n\nout:\n\treturn status;\n}\n\nint sigar_proc_exe_wmi_get(sigar_t * sigar, sigar_pid_t pid, sigar_proc_exe_t * procexe)\n{\n\tTCHAR buf[MAX_PATH + 1];\n\tint status;\n\n\tprocexe->name[0] = '\\0';\n\n\tif ((status = wmi_get_proc_executable_path(sigar, pid, buf))) {\n\t\tgoto out;\n\t} else {\n\t\tstatus = SIGAR_OK;\n\t\t\/* SIGAR_W2A(buf, procexe->name, sizeof(procexe->name)); *\/\n\t\tWideCharToMultiByte(CP_ACP, 0, buf, -1,\n\t\t\t(LPSTR) procexe->name, sizeof(procexe->name), NULL, NULL);\n\t}\n\nout:\n\treturn status;\n}\n}\t\t\t\t\t\t\t\t\/\/extern \"C\"\n<|endoftext|>"} {"text":"code update<|endoftext|>"} {"text":"\/*\n* File: Cell.cpp\n* Author: Ozan YILDIZ\n*\n* Created on November 12, 2015, 4:06 PM\n*\/\n\n#include \n#include \n\n#include \"Cell.h\"\n\nCell::Cell()\n\t: axisX(NULL), axisY(\" \"), who(NULL)\n{\n\n}\n\nCell::Cell(const Cell& copyCell)\n{\n\taxisX = copyCell.axisX;\n\taxisY = copyCell.axisY;\n\twho = copyCell.who;\n}\n\nCell::Cell(char newWho)\n\t: who(newWho)\n{\n\n}\n\n\nCell::Cell(int newAxisX, string newAxisY, char newWho)\n\t: axisX(newAxisX), axisY(newAxisY), who(newWho)\n{\n\n}\n\nbool Cell::operator==(const Cell & temp)\n{\n\tif (axisX == temp.axisX)\n\t\tif (axisY == temp.axisY)\n\t\t\treturn true;\n\n\treturn false;\n}\n\nnew Fundamental\/*\n* File: Cell.cpp\n* Author: Ozan YILDIZ\n*\n* Created on November 25, 2015, 4:06 PM\n*\/\n\n#include \n#include \n\n#include \"Cell.h\"\n\nCell::Cell()\n{\n who = '2';\n}\n\nCell::Cell(const int newAxisX, const string newAxisY, const char newWho)\n\t: axisX(newAxisX), axisY(newAxisY), who(newWho)\n{\n}\n\nCell::Cell(const Cell& orig)\n{\n}\n\n\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: KWSys - Kitware System Library\n Module: Glob.cxx\n\n Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n#include KWSYS_HEADER(Glob.hxx)\n\n#include KWSYS_HEADER(Configure.hxx)\n\n#include KWSYS_HEADER(RegularExpression.hxx)\n#include KWSYS_HEADER(SystemTools.hxx)\n#include KWSYS_HEADER(Directory.hxx)\n#include KWSYS_HEADER(stl\/string)\n#include KWSYS_HEADER(stl\/vector)\n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"Glob.hxx.in\"\n# include \"Configure.hxx.in\"\n# include \"RegularExpression.hxx.in\"\n# include \"SystemTools.hxx.in\"\n# include \"kwsys_stl.hxx.in\"\n# include \"kwsys_stl_string.hxx.in\"\n#endif\n\n#include \n#include \n#include \nnamespace KWSYS_NAMESPACE\n{\n#if defined( _WIN32 ) || defined( APPLE ) || defined( __CYGWIN__ )\n \/\/ On Windows and apple, no difference between lower and upper case\n #define KWSYS_GLOB_CASE_INDEPENDENT\n#endif\n\n#if defined( _WIN32 ) || defined( __CYGWIN__ )\n \/\/ Handle network paths\n #define KWSYS_GLOB_SUPPORT_NETWORK_PATHS\n#endif\n\n\/\/----------------------------------------------------------------------------\nclass GlobInternals\n{\npublic:\n kwsys_stl::vector Files;\n kwsys_stl::vector Expressions;\n kwsys_stl::vector TextExpressions;\n};\n\n\/\/----------------------------------------------------------------------------\nGlob::Glob()\n{\n m_Internals = new GlobInternals;\n m_Recurse = false;\n}\n\n\/\/----------------------------------------------------------------------------\nGlob::~Glob()\n{\n delete m_Internals;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::Escape(int ch, char* buffer)\n{\n if (! (\n 'a' <= ch && ch <= 'z' || \n 'A' <= ch && ch <= 'Z' || \n '0' <= ch && ch <= '9') )\n {\n sprintf(buffer, \"\\\\%c\", ch);\n }\n else\n {\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n sprintf(buffer, \"%c\", tolower(ch));\n#else\n sprintf(buffer, \"%c\", ch);\n#endif\n }\n}\n\n\/\/----------------------------------------------------------------------------\nkwsys_stl::vector& Glob::GetFiles()\n{\n return m_Internals->Files;\n}\n\n\/\/----------------------------------------------------------------------------\nkwsys_stl::string Glob::ConvertExpression(const kwsys_stl::string& expr)\n{\n \n kwsys_stl::string::size_type i = 0;\n kwsys_stl::string::size_type n = expr.size();\n\n kwsys_stl::string res = \"^\";\n kwsys_stl::string stuff = \"\";\n\n while ( i < n )\n {\n int c = expr[i];\n i = i+1;\n if ( c == '*' )\n {\n res = res + \".*\";\n }\n else if ( c == '?' )\n {\n res = res + \".\";\n }\n else if ( c == '[' )\n {\n kwsys_stl::string::size_type j = i;\n if ( j < n && ( expr[j] == '!' || expr[j] == '^' ) )\n {\n j = j+1;\n }\n if ( j < n && expr[j] == ']' )\n {\n j = j+1;\n } \n while ( j < n && expr[j] != ']' )\n {\n j = j+1;\n }\n if ( j >= n )\n {\n res = res + \"\\\\[\";\n }\n else\n {\n stuff = \"\";\n kwsys_stl::string::size_type cc;\n for ( cc = i; cc < j; cc ++ )\n {\n if ( expr[cc] == '\\\\' )\n {\n stuff += \"\\\\\\\\\";\n }\n else\n {\n stuff += expr[cc];\n }\n }\n i = j+1;\n if ( stuff[0] == '!' || stuff[0] == '^' )\n {\n stuff = '^' + stuff.substr(1);\n }\n else if ( stuff[0] == '^' )\n {\n stuff = '\\\\' + stuff;\n }\n res = res + \"[\" + stuff + \"]\";\n }\n }\n else\n {\n char buffer[100];\n buffer[0] = 0;\n this->Escape(c, buffer);\n res = res + buffer;\n }\n }\n return res + \"$\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::RecurseDirectory(kwsys_stl::string::size_type start,\n const kwsys_stl::string& dir, bool dir_only)\n{\n kwsys::Directory d;\n if ( !d.Load(dir.c_str()) )\n {\n return;\n }\n unsigned long cc;\n kwsys_stl::string fullname;\n kwsys_stl::string realname;\n kwsys_stl::string fname;\n for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )\n {\n fname = d.GetFile(cc);\n if ( strcmp(fname.c_str(), \".\") == 0 ||\n strcmp(fname.c_str(), \"..\") == 0 )\n {\n continue;\n }\n\n if ( start == 0 )\n {\n realname = dir + fname;\n }\n else\n {\n realname = dir + \"\/\" + fname;\n }\n\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n fname = kwsys::SystemTools::LowerCase(fname);\n#endif\n\n if ( start == 0 )\n {\n fullname = dir + fname;\n }\n else\n {\n fullname = dir + \"\/\" + fname;\n }\n\n if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n if ( m_Internals->Expressions[m_Internals->Expressions.size()-1].find(fname.c_str()) )\n {\n m_Internals->Files.push_back(realname);\n }\n }\n if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n this->RecurseDirectory(start+1, realname, dir_only);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::ProcessDirectory(kwsys_stl::string::size_type start, \n const kwsys_stl::string& dir, bool dir_only)\n{\n \/\/kwsys_ios::cout << \"ProcessDirectory: \" << dir << kwsys_ios::endl;\n bool last = ( start == m_Internals->Expressions.size()-1 );\n if ( last && m_Recurse )\n {\n this->RecurseDirectory(start, dir, dir_only);\n return;\n }\n kwsys::Directory d;\n if ( !d.Load(dir.c_str()) )\n {\n return;\n }\n unsigned long cc;\n kwsys_stl::string fullname;\n kwsys_stl::string realname;\n kwsys_stl::string fname;\n for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )\n {\n fname = d.GetFile(cc);\n if ( strcmp(fname.c_str(), \".\") == 0 ||\n strcmp(fname.c_str(), \"..\") == 0 )\n {\n continue;\n }\n\n if ( start == 0 )\n {\n realname = dir + fname;\n }\n else\n {\n realname = dir + \"\/\" + fname;\n }\n\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n fname = kwsys::SystemTools::LowerCase(fname);\n#endif\n\n if ( start == 0 )\n {\n fullname = dir + fname;\n }\n else\n {\n fullname = dir + \"\/\" + fname;\n }\n\n \/\/kwsys_ios::cout << \"Look at file: \" << fname << kwsys_ios::endl;\n \/\/kwsys_ios::cout << \"Match: \" << m_Internals->TextExpressions[start].c_str() << kwsys_ios::endl;\n \/\/kwsys_ios::cout << \"Full name: \" << fullname << kwsys_ios::endl;\n\n if ( (!dir_only || !last) && !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n continue;\n }\n\n if ( m_Internals->Expressions[start].find(fname.c_str()) )\n {\n if ( last )\n {\n m_Internals->Files.push_back(realname);\n }\n else\n {\n this->ProcessDirectory(start+1, realname + \"\/\", dir_only);\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool Glob::FindFiles(const kwsys_stl::string& inexpr)\n{\n kwsys_stl::string cexpr;\n kwsys_stl::string::size_type cc;\n kwsys_stl::string expr = inexpr;\n\n m_Internals->Expressions.clear();\n m_Internals->Files.clear();\n\n if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )\n {\n expr = kwsys::SystemTools::GetCurrentWorkingDirectory();\n expr += \"\/\" + inexpr;\n }\n kwsys_stl::string fexpr = expr;\n\n int skip = 0;\n int last_slash = 0;\n for ( cc = 0; cc < expr.size(); cc ++ )\n {\n if ( cc > 0 && expr[cc] == '\/' && expr[cc-1] != '\\\\' )\n {\n last_slash = cc;\n }\n if ( cc > 0 && \n (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&\n expr[cc-1] != '\\\\' )\n {\n break;\n }\n }\n if ( last_slash > 0 )\n {\n \/\/kwsys_ios::cout << \"I can skip: \" << fexpr.substr(0, last_slash) << kwsys_ios::endl;\n skip = last_slash;\n }\n if ( skip == 0 )\n {\n#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )\n \/\/ Handle network paths\n if ( expr[0] == '\/' && expr[1] == '\/' )\n {\n int cnt = 0;\n for ( cc = 2; cc < expr.size(); cc ++ )\n {\n if ( expr[cc] == '\/' )\n {\n cnt ++;\n if ( cnt == 2 )\n {\n break;\n }\n }\n }\n skip = cc + 1;\n }\n else\n#endif\n \/\/ Handle drive letters on Windows\n if ( expr[1] == ':' && expr[0] != '\/' )\n {\n skip = 2;\n }\n }\n\n if ( skip > 0 )\n {\n expr = expr.substr(skip);\n }\n\n cexpr = \"\";\n for ( cc = 0; cc < expr.size(); cc ++ )\n {\n int ch = expr[cc];\n if ( ch == '\/' )\n {\n if ( cexpr.size() > 0 )\n {\n this->AddExpression(cexpr.c_str());\n }\n cexpr = \"\";\n }\n else\n {\n cexpr.append(1, (char)ch);\n }\n }\n if ( cexpr.size() > 0 )\n {\n this->AddExpression(cexpr.c_str());\n }\n\n \/\/ Handle network paths\n if ( skip > 0 )\n {\n this->ProcessDirectory(0, fexpr.substr(0, skip) + \"\/\",\n true); \n }\n else\n {\n this->ProcessDirectory(0, \"\/\", true);\n }\n return true;\n}\n\nvoid Glob::AddExpression(const char* expr)\n{\n m_Internals->Expressions.push_back(\n kwsys::RegularExpression(\n this->ConvertExpression(expr).c_str()));\n m_Internals->TextExpressions.push_back(this->ConvertExpression(expr));\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\nENH: add missing cmake include\/*=========================================================================\n\n Program: KWSys - Kitware System Library\n Module: Glob.cxx\n\n Copyright (c) Kitware, Inc., Insight Consortium. All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"kwsysPrivate.h\"\n#include KWSYS_HEADER(Glob.hxx)\n\n#include KWSYS_HEADER(Configure.hxx)\n\n#include KWSYS_HEADER(RegularExpression.hxx)\n#include KWSYS_HEADER(SystemTools.hxx)\n#include KWSYS_HEADER(Directory.hxx)\n#include KWSYS_HEADER(stl\/string)\n#include KWSYS_HEADER(stl\/vector)\n\n\/\/ Work-around CMake dependency scanning limitation. This must\n\/\/ duplicate the above list of headers.\n#if 0\n# include \"Glob.hxx.in\"\n# include \"Directory.hxx.in\"\n# include \"Configure.hxx.in\"\n# include \"RegularExpression.hxx.in\"\n# include \"SystemTools.hxx.in\"\n# include \"kwsys_stl.hxx.in\"\n# include \"kwsys_stl_string.hxx.in\"\n#endif\n\n#include \n#include \n#include \nnamespace KWSYS_NAMESPACE\n{\n#if defined( _WIN32 ) || defined( APPLE ) || defined( __CYGWIN__ )\n \/\/ On Windows and apple, no difference between lower and upper case\n #define KWSYS_GLOB_CASE_INDEPENDENT\n#endif\n\n#if defined( _WIN32 ) || defined( __CYGWIN__ )\n \/\/ Handle network paths\n #define KWSYS_GLOB_SUPPORT_NETWORK_PATHS\n#endif\n\n\/\/----------------------------------------------------------------------------\nclass GlobInternals\n{\npublic:\n kwsys_stl::vector Files;\n kwsys_stl::vector Expressions;\n kwsys_stl::vector TextExpressions;\n};\n\n\/\/----------------------------------------------------------------------------\nGlob::Glob()\n{\n m_Internals = new GlobInternals;\n m_Recurse = false;\n}\n\n\/\/----------------------------------------------------------------------------\nGlob::~Glob()\n{\n delete m_Internals;\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::Escape(int ch, char* buffer)\n{\n if (! (\n 'a' <= ch && ch <= 'z' || \n 'A' <= ch && ch <= 'Z' || \n '0' <= ch && ch <= '9') )\n {\n sprintf(buffer, \"\\\\%c\", ch);\n }\n else\n {\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n sprintf(buffer, \"%c\", tolower(ch));\n#else\n sprintf(buffer, \"%c\", ch);\n#endif\n }\n}\n\n\/\/----------------------------------------------------------------------------\nkwsys_stl::vector& Glob::GetFiles()\n{\n return m_Internals->Files;\n}\n\n\/\/----------------------------------------------------------------------------\nkwsys_stl::string Glob::ConvertExpression(const kwsys_stl::string& expr)\n{\n \n kwsys_stl::string::size_type i = 0;\n kwsys_stl::string::size_type n = expr.size();\n\n kwsys_stl::string res = \"^\";\n kwsys_stl::string stuff = \"\";\n\n while ( i < n )\n {\n int c = expr[i];\n i = i+1;\n if ( c == '*' )\n {\n res = res + \".*\";\n }\n else if ( c == '?' )\n {\n res = res + \".\";\n }\n else if ( c == '[' )\n {\n kwsys_stl::string::size_type j = i;\n if ( j < n && ( expr[j] == '!' || expr[j] == '^' ) )\n {\n j = j+1;\n }\n if ( j < n && expr[j] == ']' )\n {\n j = j+1;\n } \n while ( j < n && expr[j] != ']' )\n {\n j = j+1;\n }\n if ( j >= n )\n {\n res = res + \"\\\\[\";\n }\n else\n {\n stuff = \"\";\n kwsys_stl::string::size_type cc;\n for ( cc = i; cc < j; cc ++ )\n {\n if ( expr[cc] == '\\\\' )\n {\n stuff += \"\\\\\\\\\";\n }\n else\n {\n stuff += expr[cc];\n }\n }\n i = j+1;\n if ( stuff[0] == '!' || stuff[0] == '^' )\n {\n stuff = '^' + stuff.substr(1);\n }\n else if ( stuff[0] == '^' )\n {\n stuff = '\\\\' + stuff;\n }\n res = res + \"[\" + stuff + \"]\";\n }\n }\n else\n {\n char buffer[100];\n buffer[0] = 0;\n this->Escape(c, buffer);\n res = res + buffer;\n }\n }\n return res + \"$\";\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::RecurseDirectory(kwsys_stl::string::size_type start,\n const kwsys_stl::string& dir, bool dir_only)\n{\n kwsys::Directory d;\n if ( !d.Load(dir.c_str()) )\n {\n return;\n }\n unsigned long cc;\n kwsys_stl::string fullname;\n kwsys_stl::string realname;\n kwsys_stl::string fname;\n for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )\n {\n fname = d.GetFile(cc);\n if ( strcmp(fname.c_str(), \".\") == 0 ||\n strcmp(fname.c_str(), \"..\") == 0 )\n {\n continue;\n }\n\n if ( start == 0 )\n {\n realname = dir + fname;\n }\n else\n {\n realname = dir + \"\/\" + fname;\n }\n\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n fname = kwsys::SystemTools::LowerCase(fname);\n#endif\n\n if ( start == 0 )\n {\n fullname = dir + fname;\n }\n else\n {\n fullname = dir + \"\/\" + fname;\n }\n\n if ( !dir_only || !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n if ( m_Internals->Expressions[m_Internals->Expressions.size()-1].find(fname.c_str()) )\n {\n m_Internals->Files.push_back(realname);\n }\n }\n if ( kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n this->RecurseDirectory(start+1, realname, dir_only);\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nvoid Glob::ProcessDirectory(kwsys_stl::string::size_type start, \n const kwsys_stl::string& dir, bool dir_only)\n{\n \/\/kwsys_ios::cout << \"ProcessDirectory: \" << dir << kwsys_ios::endl;\n bool last = ( start == m_Internals->Expressions.size()-1 );\n if ( last && m_Recurse )\n {\n this->RecurseDirectory(start, dir, dir_only);\n return;\n }\n kwsys::Directory d;\n if ( !d.Load(dir.c_str()) )\n {\n return;\n }\n unsigned long cc;\n kwsys_stl::string fullname;\n kwsys_stl::string realname;\n kwsys_stl::string fname;\n for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )\n {\n fname = d.GetFile(cc);\n if ( strcmp(fname.c_str(), \".\") == 0 ||\n strcmp(fname.c_str(), \"..\") == 0 )\n {\n continue;\n }\n\n if ( start == 0 )\n {\n realname = dir + fname;\n }\n else\n {\n realname = dir + \"\/\" + fname;\n }\n\n#if defined( KWSYS_GLOB_CASE_INDEPENDENT )\n \/\/ On Windows and apple, no difference between lower and upper case\n fname = kwsys::SystemTools::LowerCase(fname);\n#endif\n\n if ( start == 0 )\n {\n fullname = dir + fname;\n }\n else\n {\n fullname = dir + \"\/\" + fname;\n }\n\n \/\/kwsys_ios::cout << \"Look at file: \" << fname << kwsys_ios::endl;\n \/\/kwsys_ios::cout << \"Match: \" << m_Internals->TextExpressions[start].c_str() << kwsys_ios::endl;\n \/\/kwsys_ios::cout << \"Full name: \" << fullname << kwsys_ios::endl;\n\n if ( (!dir_only || !last) && !kwsys::SystemTools::FileIsDirectory(realname.c_str()) )\n {\n continue;\n }\n\n if ( m_Internals->Expressions[start].find(fname.c_str()) )\n {\n if ( last )\n {\n m_Internals->Files.push_back(realname);\n }\n else\n {\n this->ProcessDirectory(start+1, realname + \"\/\", dir_only);\n }\n }\n }\n}\n\n\/\/----------------------------------------------------------------------------\nbool Glob::FindFiles(const kwsys_stl::string& inexpr)\n{\n kwsys_stl::string cexpr;\n kwsys_stl::string::size_type cc;\n kwsys_stl::string expr = inexpr;\n\n m_Internals->Expressions.clear();\n m_Internals->Files.clear();\n\n if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )\n {\n expr = kwsys::SystemTools::GetCurrentWorkingDirectory();\n expr += \"\/\" + inexpr;\n }\n kwsys_stl::string fexpr = expr;\n\n int skip = 0;\n int last_slash = 0;\n for ( cc = 0; cc < expr.size(); cc ++ )\n {\n if ( cc > 0 && expr[cc] == '\/' && expr[cc-1] != '\\\\' )\n {\n last_slash = cc;\n }\n if ( cc > 0 && \n (expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&\n expr[cc-1] != '\\\\' )\n {\n break;\n }\n }\n if ( last_slash > 0 )\n {\n \/\/kwsys_ios::cout << \"I can skip: \" << fexpr.substr(0, last_slash) << kwsys_ios::endl;\n skip = last_slash;\n }\n if ( skip == 0 )\n {\n#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )\n \/\/ Handle network paths\n if ( expr[0] == '\/' && expr[1] == '\/' )\n {\n int cnt = 0;\n for ( cc = 2; cc < expr.size(); cc ++ )\n {\n if ( expr[cc] == '\/' )\n {\n cnt ++;\n if ( cnt == 2 )\n {\n break;\n }\n }\n }\n skip = cc + 1;\n }\n else\n#endif\n \/\/ Handle drive letters on Windows\n if ( expr[1] == ':' && expr[0] != '\/' )\n {\n skip = 2;\n }\n }\n\n if ( skip > 0 )\n {\n expr = expr.substr(skip);\n }\n\n cexpr = \"\";\n for ( cc = 0; cc < expr.size(); cc ++ )\n {\n int ch = expr[cc];\n if ( ch == '\/' )\n {\n if ( cexpr.size() > 0 )\n {\n this->AddExpression(cexpr.c_str());\n }\n cexpr = \"\";\n }\n else\n {\n cexpr.append(1, (char)ch);\n }\n }\n if ( cexpr.size() > 0 )\n {\n this->AddExpression(cexpr.c_str());\n }\n\n \/\/ Handle network paths\n if ( skip > 0 )\n {\n this->ProcessDirectory(0, fexpr.substr(0, skip) + \"\/\",\n true); \n }\n else\n {\n this->ProcessDirectory(0, \"\/\", true);\n }\n return true;\n}\n\nvoid Glob::AddExpression(const char* expr)\n{\n m_Internals->Expressions.push_back(\n kwsys::RegularExpression(\n this->ConvertExpression(expr).c_str()));\n m_Internals->TextExpressions.push_back(this->ConvertExpression(expr));\n}\n\n} \/\/ namespace KWSYS_NAMESPACE\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"HPACK.h\"\n#include \"hpack_table.h\"\n\nuint16_t\nencode_int(uint8_t* &dst, uint32_t I, uint8_t N) {\n if (I < (1 << N)-1) {\n dst = new uint8_t[1];\n *dst = I;\n return 1;\n }\n\n I -= (1 << N)-1;\n uint16_t i;\n uint32_t tmpI = I;\n for (i = 1; tmpI >= 128; i++) {\n tmpI = tmpI >> 7;\n } \/\/ check length\n \n dst = new uint8_t[i+1];\n *dst = (1 << N) - 1;\n uint8_t j = 1;\n for (; I >= 128; j++) {\n *(dst+j) = (I & 0x7f) | 0x80;\n I = I >> 7;\n }\n *(dst+j) = I;\n\n return i+1;\n}\n\nint64_t\nhpack_encode(uint8_t* buf, std::vector
headers, bool from_sTable, bool from_dTable, bool is_huffman, Table* table, int dynamic_table_size) {\n uint16_t len;\n uint8_t* d_table_size;\n if (dynamic_table_size != -1) {\n len = encode_int(d_table_size, dynamic_table_size, 5);\n *d_table_size |= 0x20;\n \/\/delete d_table_size;\n }\n for (header h : headers) {\n int index;\n bool match = table->find_header(index, h);\n if (from_sTable && match) {\n uint8_t index_len = 8;\n uint8_t mask = 0;\n uint8_t* content;\n if (from_dTable) {\n index_len = 7;\n mask = 0x80;\n } else {\n content = table->pack_string(h.second, is_huffman); \/\/ temporally\n }\n uint8_t* intRep;\n len = encode_int(intRep, index, index_len);\n *intRep |= mask;\n \/\/ append gub and intRep\n } else if (from_sTable && !match && index > 0) {\n uint8_t index_len = 4;\n uint8_t mask = 0;\n if (from_dTable) {\n index_len = 6;\n mask = 0x40;\n table->add_header(h);\n }\n }\n }\n return 0;\n}\n\n\nuint32_t\ndecode_int(uint8_t* buf, uint8_t N) {\n uint32_t I = *buf & ((1 << N) - 1);\n if (I == (1 << N) -1) {\n int M = 0;\n do {\n I += (*(++buf) & 0x7f) << M; \n M += 7;\n }\n while (*buf & 0x80);\n }\n return I;\n}\n\nstd::vector< header >\nhpack_decode(uint8_t* buf, Table* table) {\n std::vector< header > headers;\n while (*buf != '\\0') {\n bool isIndexed = 0;\n bool isIncremental = 0;\n uint32_t index;\n if ((*buf & 0xe0) == 0x20) {\n \/\/ 7\/3 Header table Size Update\n uint32_t dst = decode_int(buf, 5);\n table->set_dynamic_table_size(dst);\n }\n\n if ((*buf & 0x80) > 0) {\n \/\/ 7.1 Indexwd Header Field\n if ((*buf & 0x7f) == 0) {\n \/\/ error\n }\n l = decode_int(index, ++buf, 7);\n isIndexed = true;\n } else {\n if ((*buf & 0xc0) == 0x40) {\n \/\/ 7.2.1 Literal Header Field with Incremental Indexing\n l = decode_int(index, ++buf, 6);\n isIncremental = true;\n } else if ((*buf & 0xf0) == 0xf0) {\n l = decode_int(index, ++buf, 4);\n } else {\n l = decode_int(index, ++buf, 4);\n }\n }\n index = decode_int(++buf, nLen);\n header h = table->parse_header(index, buf, isIndexed);\n \/\/buf += l;\n if (isIncremental) {\n table->add_header(h);\n }\n headers.push_back(h);\n }\n return headers;\n}\nimprove code#include \n#include \n#include \n#include \"HPACK.h\"\n#include \"hpack_table.h\"\n\nuint16_t\nencode_int(uint8_t* &dst, uint32_t I, uint8_t N) {\n if (I < (1 << N)-1) {\n dst = new uint8_t[1];\n *dst = I;\n return 1;\n }\n\n I -= (1 << N)-1;\n uint16_t i;\n uint32_t tmpI = I;\n for (i = 1; tmpI >= 128; i++) {\n tmpI = tmpI >> 7;\n } \/\/ check length\n \n dst = new uint8_t[i+1];\n *dst = (1 << N) - 1;\n uint8_t j = 1;\n for (; I >= 128; j++) {\n *(dst+j) = (I & 0x7f) | 0x80;\n I = I >> 7;\n }\n *(dst+j) = I;\n\n return i+1;\n}\n\nint64_t\nhpack_encode(uint8_t* buf, std::vector
headers, bool from_sTable, bool from_dTable, bool is_huffman, Table* table, int dynamic_table_size) {\n uint16_t len;\n uint8_t* d_table_size;\n if (dynamic_table_size != -1) {\n len = encode_int(d_table_size, dynamic_table_size, 5);\n *d_table_size |= 0x20;\n \/\/delete d_table_size;\n }\n for (header h : headers) {\n int index;\n bool match = table->find_header(index, h);\n if (from_sTable && match) {\n uint8_t index_len = 8;\n uint8_t mask = 0;\n uint8_t* content;\n if (from_dTable) {\n index_len = 7;\n mask = 0x80;\n } else {\n content = table->pack_string(h.second, is_huffman); \/\/ temporally\n }\n uint8_t* intRep;\n len = encode_int(intRep, index, index_len);\n *intRep |= mask;\n \/\/ append gub and intRep\n } else if (from_sTable && !match && index > 0) {\n uint8_t index_len = 4;\n uint8_t mask = 0;\n if (from_dTable) {\n index_len = 6;\n mask = 0x40;\n table->add_header(h);\n }\n }\n }\n return 0;\n}\n\n\nuint32_t\ndecode_int(uint8_t* buf, uint8_t N) {\n uint32_t I = *buf & ((1 << N) - 1);\n if (I == (1 << N) -1) {\n int M = 0;\n do {\n I += (*(++buf) & 0x7f) << M; \n M += 7;\n }\n while (*buf & 0x80);\n }\n return I;\n}\n\nstd::vector< header >\nhpack_decode(uint8_t* buf, Table* table) {\n std::vector< header > headers;\n while (*buf != '\\0') {\n bool isIndexed = 0;\n uint32_t index;\n if ((*buf & 0xe0) == 0x20) {\n \/\/ 7\/3 Header table Size Update\n uint32_t dst = decode_int(buf, 5);\n table->set_dynamic_table_size(dst);\n }\n\n uint8_t nLen = 0;\n if ((*buf & 0x80) > 0) {\n \/\/ 7.1 Indexwd Header Field\n if ((*buf & 0x7f) == 0) {\n \/\/ error\n }\n nLen = 7;\n isIndexed = true;\n } else {\n if ((*buf & 0xc0) == 0x40) {\n \/\/ 7.2.1 Literal Header Field with Incremental Indexing\n nLen = 6;\n } else {\n \/\/ when buf[cursor]&0xf0 == 0xf0\n \/\/ 7.2.2 Literal Header Field without Indexing\n \/\/ else\n \/\/ 7.2.3 Literal Header Field never Indexed\n nLen = 4;\n }\n }\n index = decode_int(++buf, nLen);\n header h = table->parse_header(index, buf, isIndexed);\n if (nLen == 6) {\n table->add_header(h);\n }\n headers.push_back(h);\n }\n return headers;\n}\n<|endoftext|>"} {"text":"class Item {\n\n\n\n\n\n\n};item classclass Item {\n\n\n\n\n\n};<|endoftext|>"} {"text":"\/*\n#include \n#include \n\nnamespace Graph\n{\n\ttemplate class Node\n\t{\/\/A single edge of a graph.\n\t\tprivate:\n\t\t\tKey key;\n\t\t\tValue value;\n\t\t\tNode left, right;\n\t\t\tint N;\n\n\t\tpublic:\n\t\t\tNode( Key newKey, Value newValue, int newN );\/\/Constructor with values.\n\t\t\tint size() const;\/\/Return the size.\n\t\t\tValue get( Key getKey );\n\t\t\tvoid put( Key newKey, Value newValue );\n\t};\n}\n*\/\n#include \"Node.h\"\n\nnamespace Graph\n{\n\ttemplate Node::Node()\n\t{\n\t}\n\n\ttemplate Node::Node( Key newKey, Value newValue, int newN )\n\t{\/\/Constructor with values.\n\t}\n\n\tint Node::size() const\n\t{\/\/Return the size.\n\t}\n\n\ttemplate Value Node::get( Key getKey )\n\t{\/\/Return the value of the node with a given key.\n\t}\n\n\ttemplate void put( Key newKey, Value newValue )\n\t{\n\t}\n}\nCommented out a constructor in the Node class.\/*\n#include \n#include \n\nnamespace Graph\n{\n\ttemplate class Node\n\t{\/\/A single edge of a graph.\n\t\tprivate:\n\t\t\tKey key;\n\t\t\tValue value;\n\t\t\tNode left, right;\n\t\t\tint N;\n\n\t\tpublic:\n\t\t\t\/\/Node( Key newKey, Value newValue, int newN );\/\/Constructor with values.\n\t\t\tint size() const;\/\/Return the size.\n\t\t\tValue get( Key getKey );\n\t\t\tvoid put( Key newKey, Value newValue );\n\t};\n}\n*\/\n#include \"Node.h\"\n\nnamespace Graph\n{\n\ttemplate Node::Node()\n\t{\n\t}\n\n\/*\n\ttemplate Node::Node( Key newKey, Value newValue, int newN )\n\t{\/\/Constructor with values.\n\t}\n*\/\n\n\tint Node::size() const\n\t{\/\/Return the size.\n\t}\n\n\ttemplate Value Node::get( Key getKey )\n\t{\/\/Return the value of the node with a given key.\n\t}\n\n\ttemplate void put( Key newKey, Value newValue )\n\t{\n\t}\n}\n<|endoftext|>"} {"text":"#include \n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\n\nvoid logLevel(const Nan::FunctionCallbackInfo& info) {\n\n libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,\n (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);\n\n info.GetReturnValue().Set(info.Holder());\n}\n\nNAN_MODULE_INIT(InitAll) {\n\n Nan::Set(target, Nan::New(\"logLevel\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(logLevel)).ToLocalChecked());\n\n dvbteeParser::Init(target);\n}\n\nNODE_MODULE(addon, InitAll)\naddon: NODE_MODULE(dvbtee, InitAll)#include \n#include \"addon.h\"\n#include \"dvbtee-parser.h\"\n\n\nvoid logLevel(const Nan::FunctionCallbackInfo& info) {\n\n libdvbtee_set_debug_level((info[0]->IsNumber()) ? info[0]->Uint32Value() : 255,\n (info[1]->IsNumber()) ? info[1]->Uint32Value() : 0);\n\n info.GetReturnValue().Set(info.Holder());\n}\n\nNAN_MODULE_INIT(InitAll) {\n\n Nan::Set(target, Nan::New(\"logLevel\").ToLocalChecked(),\n Nan::GetFunction(Nan::New(logLevel)).ToLocalChecked());\n\n dvbteeParser::Init(target);\n}\n\nNODE_MODULE(dvbtee, InitAll)\n<|endoftext|>"} {"text":"\/\/#include \"cmd_args.h\"\n#include \n\n\/\/using namespace cmd_args;\n\n\/\/ structure type that represents the \n\/\/ information to be read\n\/\/struct arguments_t {\n\/\/\tbool show_version;\n\/\/\tbool show_usage;\n\/\/\tint value_a;\n\/\/\tint value_b;\n\/\/};\n\n#include \n#include \n\nusing namespace std;\n\nnamespace command_line {\n\n\tnamespace details {\n\n\t\t\/\/ domain iterator range \n\t\tstruct range_t {\n\t\t\tchar \n\t\t\t\t** it, \n\t\t\t\t** end;\n\n\t\t\t\/\/ returns true if range is length is zero\n\t\t\tinline bool finished () const { return it == end; }\n\n\t\t\t\/\/ consume first item in range and return it's value\n\t\t\tinline const char * consume() {\n\t\t\t\treturn *it++;\n\t\t\t}\n\t\t};\n\n\t\t\/\/ merge two ranges together\n\t\t\/\/ (TODO: this name and operator does not correctly represent method)\n\t\tinline range_t operator && (const range_t & v1, const range_t & v2) {\n\t\t\tif (distance(v1.it, v2.it) > 0)\n\t\t\t\treturn{ v1.it, v2.it };\n\t\t\telse\n\t\t\t\treturn{ v2.it, v1.it };\n\t\t}\n\n\t\t\/\/ value setter abstraction\n\t\tstruct base_setter_t {\n\t\t\tusing unique = unique_ptr < base_setter_t >;\n\t\t\tvirtual void set(const range_t & r) = 0;\n\t\t};\n\n\t\t\/\/ setter specialization for single items\n\t\ttemplate < class _dest_t, class _t >\n\t\tstruct setter_t : public base_setter_t {\n\t\t\t_t _dest_t::*address;\n\n\t\t\tsetter_t(_t _dest_t::*address_v) : address(address) {}\n\n\t\t\tvirtual void set(const range_t & r) {}\n\t\t};\n\n\t\t\/\/ setter specialization for vectors\n\t\ttemplate < class _dest_t, class _t, class ... _other_tv >\n\t\tstruct setter_t < _dest_t, vector < _t, _other_tv...> > : public base_setter_t {\n\t\t\tvector < _t, _other_tv...> _dest_t::*address;\n\t\t\tsetter_t(vector < _t, _other_tv...> _dest_t::*address_v) : address(address) {}\n\n\t\t\tvirtual void set(const range_t & r) {}\n\t\t};\n\n\t\t\/\/ solution building\/execution node\n\t\tstruct solution_node {\n\t\t\trange_t range;\n\t\t\tbase_setter_t::unique setter;\n\n\t\t\tint sequence_index;\n\t\t};\n\n\t\tstruct solution_tree_state_t {\n\t\t\tsize_t\ttree_size;\n\t\t\tint\t\tparent_node;\n\t\t};\n\n\t\tstruct solution_tree_t {\n\t\tprivate:\n\t\t\tvector < solution_node > tree;\n\t\t\tint32_t parent_node;\n\t\tpublic:\n\n\t\t\tinline solution_node & operator [] (size_t i) {\n\t\t\t\treturn tree[i];\n\t\t\t}\n\n\t\t\tinline size_t size() const {\n\t\t\t\treturn tree.size();\n\t\t\t}\n\n\t\t\tinline solution_tree_t() : parent_node(-1) {}\n\n\t\t\tinline void add_node (const range_t & rng, base_setter_t * setter ) {\n\t\t\t\ttree.push_back(solution_node{\n\t\t\t\t\trng,\n\t\t\t\t\tunique_ptr < base_setter_t >(setter),\n\t\t\t\t\tparent_node++\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tinline solution_tree_state_t state () const {\n\t\t\t\treturn{\n\t\t\t\t\ttree.size(),\n\t\t\t\t\tparent_node\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tinline void restore(const solution_tree_state_t & state) {\n\t\t\t\ttree.resize(state.tree_size);\n\t\t\t\tparent_node = state.parent_node;\n\t\t\t}\n\n\t\t\tinline void backtrack(const solution_tree_state_t & state) {\n\t\t\t\tparent_node = state.parent_node;\n\t\t\t}\n\n\t\t};\n\n\t\tstruct context_state {\n\t\t\tsolution_tree_state_t\ttree_state;\n\t\t\trange_t\t\t\t\t\trange;\n\t\t};\n\n\t\tstruct context {\n\t\t\trange_t\t\t\trange;\n\t\t\tsolution_tree_t\tsolution_tree;\n\n\t\t\tinline context_state state() const {\n\t\t\t\treturn {\n\t\t\t\t\tsolution_tree.state(),\n\t\t\t\t\trange\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tinline void restore(const context_state & state) {\n\t\t\t\tsolution_tree.restore(state.tree_state);\n\t\t\t\trange = state.range;\n\t\t\t}\n\n\t\t\tinline void backtrack(const context_state & state) {\n\t\t\t\tsolution_tree.backtrack(state.tree_state);\n\t\t\t\trange = state.range;\n\t\t\t}\n\t\t};\n\n\t\t\/\/ setter_t\n\t\ttemplate < class _exp_t, class _dest_t, class _t >\n\t\tstruct setter_op {\n\t\t\t_exp_t exp;\n\t\t\t_t _dest_t::* address;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = cxt.state();\n\t\t\t\tif (exp.eval(cxt)) {\n\t\t\t\t\tcxt.solution_tree.add_node(\n\t\t\t\t\t\tstate.range && cxt.range, \n\t\t\t\t\t\tnew setter_t < _dest_t, _t >(address)\n\t\t\t\t\t);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline setter_op(const _exp_t & e, _t _dest_t::*address_v) : exp(e), address(address_v) {}\n\t\t};\n\n\t\ttemplate < class _derived_t >\n\t\tstruct setter_container_t {\n\t\t\ttemplate < class _dest_t, class _t >\n\t\t\tinline auto operator [] (_t _dest_t::*address) {\n\t\t\t\treturn setter_op < _derived_t, _dest_t, _t >(*static_cast < _derived_t * > (this), address);\n\t\t\t}\n\t\t};\n\n\t\t\/\/ sequence\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tstruct seq_op {\n\t\t\t_lhe_t lhe;\n\t\t\t_rhe_t rhe;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\treturn lhe.eval(cxt) && rhe.eval(cxt);\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tauto operator >> (const _lhe_t & l, const _rhe_t & r) {\n\t\t\treturn seq_op < _lhe_t, _rhe_t > { l, r };\n\t\t}\n\n\t\t\/\/ alternation\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tstruct alt_op {\n\t\t\t_lhe_t lhe;\n\t\t\t_rhe_t rhe;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto\n\t\t\t\t\tstate = cxt.state(),\n\t\t\t\t\tlhe_state = state;\n\n\t\t\t\tbool \n\t\t\t\t\tvalid = lhe.eval(cxt),\n\t\t\t\t\tbacktrack_lhe_state = valid;\n\n\t\t\t\tif (valid) {\n\t\t\t\t\tlhe_state = cxt.state();\n\t\t\t\t\tcxt.backtrack(state);\n\t\t\t\t} else {\n\t\t\t\t\tcxt.restore(state);\n\t\t\t\t}\n\n\t\t\t\tvalid |= rhe.eval(cxt);\n\n\t\t\t\tif (!valid)\n\t\t\t\t\tcxt.restore(state);\n\n\t\t\t\tif (backtrack_lhe_state)\n\t\t\t\t\tcxt.backtrack(lhe_state);\n\n\t\t\t\treturn valid;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tauto operator | (const _lhe_t & l, const _rhe_t & r) {\n\t\t\treturn alt_op < _lhe_t, _rhe_t > { l, r };\n\t\t}\n\n\t\t\/\/ zero or one\n\t\ttemplate < class _exp_t >\n\t\tstruct z_one_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = context_state();\n\n\t\t\t\tif (!exp.eval(cxt))\n\t\t\t\t\tcxt.restore(state);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator - (const _exp_t & e) {\n\t\t\treturn z_one_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ one or n\n\t\ttemplate < class _exp_t >\n\t\tstruct one_n_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tbool one_valid = exp.eval(cxt);\n\n\t\t\t\tif (one_valid) {\n\t\t\t\t\tauto state = context_state();\n\n\t\t\t\t\tdo {\n\t\t\t\t\t\tstate = cxt.state();\n\t\t\t\t\t} while (exp.eval(cxt));\n\n\t\t\t\t\tcxt.restore(state);\n\t\t\t\t}\n\n\t\t\t\treturn one_valid;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator + (const _exp_t & e) {\n\t\t\treturn one_n_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ zero or n\n\t\ttemplate < class _exp_t >\n\t\tstruct z_n_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = context_state();\n\n\t\t\t\tdo {\n\t\t\t\t\tstate = cxt.state();\n\t\t\t\t} while (exp.eval(cxt));\n\n\t\t\t\t\/\/ restore last correct state\n\t\t\t\tcxt.restore(state);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator * (const _exp_t & e) {\n\t\t\treturn z_n_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ scaners\n\t\tstruct value_t : public setter_container_t < value_t > {\n\t\t\tconst char * key;\n\n\t\t\tinline value_t ( const char * key_v ) : key (key_v) {}\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tif (cxt.range.finished ())\n\t\t\t\t\treturn false;\n\n\t\t\t\tauto v = cxt.range.consume();\n\t\t\t\treturn strcmp(v, key) == 0;\n\t\t\t}\n\t\t};\n\n\t\tstruct any_t : public setter_container_t < any_t > {\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tif (cxt.range.finished())\n\t\t\t\t\treturn false;\n\n\t\t\t\tcxt.range.consume();\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t};\n\n\t\t\/\/ solution node inversion and execution\n\t\tinline bool execute(details::context & cxt, details::range_t & arg_range) {\n\n\t\t\tauto & tree = cxt.solution_tree;\n\t\t\tint solution_index = -1;\n\n\t\t\tfor (\n\t\t\t\tint i = 0;\n\t\t\t\ti < static_cast < int > (tree.size());\n\t\t\t\t++i\n\t\t\t) {\n\t\t\t\tif (tree[i].range.end == arg_range.end) {\n\t\t\t\t\tsolution_index = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (solution_index == -1)\n\t\t\t\treturn false;\n\n\t\t\t\/\/ reorder instructions and execute\n\t\t\t{\n\t\t\t\tint n = solution_index;\n\t\t\t\tint i = tree[n].sequence_index;\n\t\t\t\ttree[n].sequence_index = -1;\n\n\t\t\t\tdo {\n\t\t\t\t\tint t = tree[i].sequence_index;\n\t\t\t\t\ttree[i].sequence_index = n;\n\t\t\t\t\tn = i;\n\t\t\t\t\ti = t;\n\t\t\t\t} while (i != -1);\n\n\t\t\t\twhile (i != -1) {\n\t\t\t\t\tauto & node = tree[i];\n\t\t\t\t\tnode.setter->set(node.range);\n\t\t\t\t\ti = node.sequence_index;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t}\n\n\tinline details::value_t key(const char * k) {\n\t\treturn{ k };\n\t}\n\n\tinline details::any_t any() { return{}; }\n\n\ttemplate < class _exp_t >\n\tinline bool parse(const _exp_t & exp, int arg_c, char ** arg_v) {\n\t\tusing namespace details;\n\n\t\tauto s_range = range_t {\n\t\t\t+arg_v + 1,\t\/\/ ignore first item\n\t\t\t+arg_v + arg_c\n\t\t};\n\n\t\tcontext cxt = { s_range };\n\n\t\t\/\/ evaluate solutions\n\t\texp.eval(cxt);\n\n\t\t\/\/ process and execute solutions\n\t\treturn details::execute (cxt, s_range);\n\t}\n\n}\n\n\nstruct demo {\n\tfloat\txxx;\n\tfloat\tyyy;\n\tint\t\tzzz;\n\n\tvector < string > files;\n\n\tbool show_version;\n\tbool show_help;\n};\n\nint main(int arg_c, char * arg_v[]) {\n\n\tusing namespace command_line;\n\n\t\n\tchar * args[] = { \"garbage\", \"-x\", \"-x\", \"-z\", \"luciano\", \"da\", \"silva\" };\n\t\n\t\/\/auto expression = key(\"-t\") > key(\"-v\") | +key(\"-x\") > key(\"-v\");\n\n\tauto usage_options = *(\n\t\tkey(\"-x\") [&demo::xxx] |\n\t\tkey(\"-y\") [&demo::yyy] |\n\t\tkey(\"-z\") [&demo::zzz]\n\t);\n\t\n\tauto usage_default_values = +any()[&demo::files];\n\t\n\tauto expression =\n\t\tusage_options >> usage_default_values |\n\t\tusage_options\n\t;\n\t\n\tparse (expression, 7, args);\n\t\n\t\/\/auto val = command_line::value(&demo::xxx, .0F);\n\n\t\/*\n\t\/\/ define an instance of the command line parser\n\tparser < arguments_t > command_line;\n\n\t\/\/ set its available arguments and options\n\tcommand_line\n\t\t\/\/ option ( < member field address >, < list of command switches >, < description > )\n\t\t+ option(&arguments_t::show_version, { \"-v\", \"--version\" }, \"shows the version of the application\")\n\t\t+ option(&arguments_t::show_usage, { \"-h, --help\" }, \"shows this usage page\")\n\t\t\/\/ argument ( < member field address >, < list of command switches >, < description >, < is optional >, < default value > )\n\t\t+ argument(&arguments_t::value_a, { \"-va\", \"--value_a\" }, \"multiplicand\")\n\t\t+ argument(&arguments_t::value_b, { \"-vb\", \"--value_b\" }, \"multiplier\");\n\n\targuments_t args;\n\n\t\/\/ command line parser returs a context with information about\n\t\/\/ the success of the parsing operation and related errors\n\tauto context = command_line.parse(arg_c, arg_v, args);\n\n\t\/\/ if the parsing failed\n\tif (context.has_failed()) {\n\t\tcout << \"example failed with the following invalid arguments\" << endl;\n\t\t\/\/ the user can print all errors to an ostream\n\t\tcontext.to_stream(cout);\n\t\treturn -1;\n\t}\n\n\tif (args.show_version)\n\t\tcout << \"example 1.0\" << endl;\n\n\t\/\/ users can also print a list of options and arguments with their descriptions\n\t\/\/ to an ostream\n\tif (args.show_usage)\n\t\tcommand_line.usage_to_stream(cout);\n\n\tcout << \"example value: \" << (args.value_a * args.value_b) << endl;\n\t*\/\n\treturn 0;\n}\nimplementing usage\/\/#include \"cmd_args.h\"\n#include \n#include \n\n\/\/using namespace cmd_args;\n\n\/\/ structure type that represents the \n\/\/ information to be read\n\/\/struct arguments_t {\n\/\/\tbool show_version;\n\/\/\tbool show_usage;\n\/\/\tint value_a;\n\/\/\tint value_b;\n\/\/};\n\n#include \n#include \n\nusing namespace std;\n\nnamespace command_line {\n\n\tnamespace details {\n\n\t\t\/\/ domain iterator range \n\t\tstruct range_t {\n\t\t\tchar \n\t\t\t\t** it, \n\t\t\t\t** end;\n\n\t\t\t\/\/ returns true if range is length is zero\n\t\t\tinline bool finished () const { return it == end; }\n\n\t\t\t\/\/ consume first item in range and return it's value\n\t\t\tinline const char * consume() {\n\t\t\t\treturn *it++;\n\t\t\t}\n\t\t};\n\n\t\t\/\/ merge two ranges together\n\t\t\/\/ (TODO: this name and operator does not correctly represent method)\n\t\tinline range_t operator && (const range_t & v1, const range_t & v2) {\n\t\t\tif (distance(v1.it, v2.it) > 0)\n\t\t\t\treturn{ v1.it, v2.it };\n\t\t\telse\n\t\t\t\treturn{ v2.it, v1.it };\n\t\t}\n\n\t\t\/\/ action\n\t\tstruct base_action_t {\n\t\t\tusing unique = unique_ptr < base_action_t >;\n\t\t\tvirtual void run(const range_t & range) const = 0;\n\t\t};\n\n\t\t\/\/ setter action specialization for single items\n\t\ttemplate < class _dest_t, class _t >\n\t\tstruct setter_t : public base_action_t {\n\t\t\t_t _dest_t::*address;\n\n\t\t\tsetter_t(_t _dest_t::*address_v) : address(address) {}\n\n\t\t\tvirtual void run(const range_t & r) const override {}\n\t\t};\n\n\t\t\/\/ setter specialization for vectors\n\t\ttemplate < class _dest_t, class _t, class ... _other_tv >\n\t\tstruct setter_t < _dest_t, vector < _t, _other_tv...> > : public base_action_t {\n\t\t\tvector < _t, _other_tv...> _dest_t::*address;\n\t\t\tsetter_t(vector < _t, _other_tv...> _dest_t::*address_v) : address(address) {}\n\n\t\t\tvirtual void run(const range_t & r) const override {}\n\t\t};\n\n\t\t\/\/ solution building\/execution node\n\t\tstruct solution_node {\n\t\t\trange_t range;\n\t\t\tbase_action_t::unique action;\n\n\t\t\tint sequence_index;\n\t\t};\n\n\t\tstruct solution_tree_state_t {\n\t\t\tsize_t\ttree_size;\n\t\t\tint\t\tparent_node;\n\t\t};\n\n\t\tstruct solution_tree_t {\n\t\tprivate:\n\t\t\tvector < solution_node > tree;\n\t\t\tint32_t parent_node;\n\t\tpublic:\n\n\t\t\tinline solution_node & operator [] (size_t i) {\n\t\t\t\treturn tree[i];\n\t\t\t}\n\n\t\t\tinline size_t size() const {\n\t\t\t\treturn tree.size();\n\t\t\t}\n\n\t\t\tinline solution_tree_t() : parent_node(-1) {}\n\n\t\t\tinline void add_node (const range_t & rng, base_action_t * setter ) {\n\t\t\t\ttree.push_back(solution_node{\n\t\t\t\t\trng,\n\t\t\t\t\tunique_ptr < base_action_t >(setter),\n\t\t\t\t\tparent_node++\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tinline solution_tree_state_t state () const {\n\t\t\t\treturn{\n\t\t\t\t\ttree.size(),\n\t\t\t\t\tparent_node\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tinline void restore(const solution_tree_state_t & state) {\n\t\t\t\ttree.resize(state.tree_size);\n\t\t\t\tparent_node = state.parent_node;\n\t\t\t}\n\n\t\t\tinline void backtrack(const solution_tree_state_t & state) {\n\t\t\t\tparent_node = state.parent_node;\n\t\t\t}\n\n\t\t};\n\n\t\tstruct context_state {\n\t\t\tsolution_tree_state_t\ttree_state;\n\t\t\trange_t\t\t\t\t\trange;\n\t\t};\n\n\t\tstruct context {\n\t\t\trange_t\t\t\trange;\n\t\t\tsolution_tree_t\tsolution_tree;\n\n\t\t\tinline context_state state() const {\n\t\t\t\treturn {\n\t\t\t\t\tsolution_tree.state(),\n\t\t\t\t\trange\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tinline void restore(const context_state & state) {\n\t\t\t\tsolution_tree.restore(state.tree_state);\n\t\t\t\trange = state.range;\n\t\t\t}\n\n\t\t\tinline void backtrack(const context_state & state) {\n\t\t\t\tsolution_tree.backtrack(state.tree_state);\n\t\t\t\trange = state.range;\n\t\t\t}\n\t\t};\n\n\t\t\/\/ setter_t\n\t\ttemplate < class _exp_t, class _dest_t, class _t >\n\t\tstruct setter_op {\n\t\t\t_exp_t exp;\n\t\t\t_t _dest_t::* address;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = cxt.state();\n\t\t\t\tif (exp.eval(cxt)) {\n\t\t\t\t\tcxt.solution_tree.add_node(\n\t\t\t\t\t\tstate.range && cxt.range, \n\t\t\t\t\t\tnew setter_t < _dest_t, _t >(address)\n\t\t\t\t\t);\n\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tinline setter_op(const _exp_t & e, _t _dest_t::*address_v) : exp(e), address(address_v) {}\n\t\t};\n\n\t\ttemplate < class _derived_t >\n\t\tstruct setter_container_t {\n\t\t\ttemplate < class _dest_t, class _t >\n\t\t\tinline auto operator [] (_t _dest_t::*address) {\n\t\t\t\treturn setter_op < _derived_t, _dest_t, _t >(*static_cast < _derived_t * > (this), address);\n\t\t\t}\n\t\t};\n\n\t\t\/\/ sequence\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tstruct seq_op {\n\t\t\t_lhe_t lhe;\n\t\t\t_rhe_t rhe;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\treturn lhe.eval(cxt) && rhe.eval(cxt);\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tauto operator >> (const _lhe_t & l, const _rhe_t & r) {\n\t\t\treturn seq_op < _lhe_t, _rhe_t > { l, r };\n\t\t}\n\n\t\t\/\/ alternation\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tstruct alt_op {\n\t\t\t_lhe_t lhe;\n\t\t\t_rhe_t rhe;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto\n\t\t\t\t\tstate = cxt.state(),\n\t\t\t\t\tlhe_state = state;\n\n\t\t\t\tbool \n\t\t\t\t\tvalid = lhe.eval(cxt),\n\t\t\t\t\tbacktrack_lhe_state = valid;\n\n\t\t\t\tif (valid) {\n\t\t\t\t\tlhe_state = cxt.state();\n\t\t\t\t\tcxt.backtrack(state);\n\t\t\t\t} else {\n\t\t\t\t\tcxt.restore(state);\n\t\t\t\t}\n\n\t\t\t\tvalid |= rhe.eval(cxt);\n\n\t\t\t\tif (!valid)\n\t\t\t\t\tcxt.restore(state);\n\n\t\t\t\tif (backtrack_lhe_state)\n\t\t\t\t\tcxt.backtrack(lhe_state);\n\n\t\t\t\treturn valid;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _lhe_t, class _rhe_t >\n\t\tauto operator | (const _lhe_t & l, const _rhe_t & r) {\n\t\t\treturn alt_op < _lhe_t, _rhe_t > { l, r };\n\t\t}\n\n\t\t\/\/ zero or one\n\t\ttemplate < class _exp_t >\n\t\tstruct z_one_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = context_state();\n\n\t\t\t\tif (!exp.eval(cxt))\n\t\t\t\t\tcxt.restore(state);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator - (const _exp_t & e) {\n\t\t\treturn z_one_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ one or n\n\t\ttemplate < class _exp_t >\n\t\tstruct one_n_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tbool one_valid = exp.eval(cxt);\n\n\t\t\t\tif (one_valid) {\n\t\t\t\t\tauto state = context_state();\n\n\t\t\t\t\tdo {\n\t\t\t\t\t\tstate = cxt.state();\n\t\t\t\t\t} while (exp.eval(cxt));\n\n\t\t\t\t\tcxt.restore(state);\n\t\t\t\t}\n\n\t\t\t\treturn one_valid;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator + (const _exp_t & e) {\n\t\t\treturn one_n_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ zero or n\n\t\ttemplate < class _exp_t >\n\t\tstruct z_n_op {\n\t\t\t_exp_t exp;\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tauto state = context_state();\n\n\t\t\t\tdo {\n\t\t\t\t\tstate = cxt.state();\n\t\t\t\t} while (exp.eval(cxt));\n\n\t\t\t\t\/\/ restore last correct state\n\t\t\t\tcxt.restore(state);\n\n\t\t\t\treturn true;\n\t\t\t}\n\t\t};\n\n\t\ttemplate < class _exp_t >\n\t\tauto operator * (const _exp_t & e) {\n\t\t\treturn z_n_op < _exp_t > { e };\n\t\t}\n\n\t\t\/\/ scaners\n\t\tstruct value_t : public setter_container_t < value_t > {\n\t\t\tconst char * key;\n\n\t\t\tinline value_t ( const char * key_v ) : key (key_v) {}\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tif (cxt.range.finished ())\n\t\t\t\t\treturn false;\n\n\t\t\t\tauto v = cxt.range.consume();\n\t\t\t\treturn strcmp(v, key) == 0;\n\t\t\t}\n\t\t};\n\n\t\tstruct any_t : public setter_container_t < any_t > {\n\n\t\t\tinline bool eval(context & cxt) const {\n\t\t\t\tif (cxt.range.finished())\n\t\t\t\t\treturn false;\n\n\t\t\t\tcxt.range.consume();\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t};\n\n\t\t\/\/ solution node inversion and execution\n\t\tinline bool execute(details::context & cxt, details::range_t & arg_range) {\n\n\t\t\tauto & tree = cxt.solution_tree;\n\t\t\tint solution_index = -1;\n\n\t\t\tfor (\n\t\t\t\tint i = 0;\n\t\t\t\ti < static_cast < int > (tree.size());\n\t\t\t\t++i\n\t\t\t) {\n\t\t\t\tif (tree[i].range.end == arg_range.end) {\n\t\t\t\t\tsolution_index = i;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (solution_index == -1)\n\t\t\t\treturn false;\n\n\t\t\t\/\/ reorder instructions and execute\n\t\t\t{\n\t\t\t\tint n = solution_index;\n\t\t\t\tint i = tree[n].sequence_index;\n\t\t\t\ttree[n].sequence_index = -1;\n\n\t\t\t\tdo {\n\t\t\t\t\tint t = tree[i].sequence_index;\n\t\t\t\t\ttree[i].sequence_index = n;\n\t\t\t\t\tn = i;\n\t\t\t\t\ti = t;\n\t\t\t\t} while (i != -1);\n\n\t\t\t\twhile (i != -1) {\n\t\t\t\t\tauto & node = tree[i];\n\t\t\t\t\tnode.action->run(node.range);\n\t\t\t\t\ti = node.sequence_index;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t}\n\n\t\/\/ scanner methods\n\tinline details::value_t key(const char * k) {\n\t\treturn{ k };\n\t}\n\n\tinline details::any_t any() { return{}; }\n\n\t\/\/ create parameterless callback expression\n\ttemplate < class _exp_t >\n\tinline auto usage(void(*callback)(), const _exp_t & exp) {\n\t\treturn exp;\n\t}\n\n\t\/\/ create expression callback with parameter\n\ttemplate < class _out_t, class _exp_t >\n\tinline auto usage(void (*callback)(_out_t &), const _exp_t & exp ) {\n\t\treturn exp;\n\t}\n\n\t\/\/ parser \n\ttemplate < class _exp_t >\n\tinline bool parse(const _exp_t & exp, int arg_c, char ** arg_v) {\n\t\tusing namespace details;\n\n\t\tauto s_range = range_t {\n\t\t\t+arg_v + 1,\t\/\/ ignore first item\n\t\t\t+arg_v + arg_c\n\t\t};\n\n\t\tcontext cxt = { s_range };\n\n\t\t\/\/ evaluate solutions\n\t\texp.eval(cxt);\n\n\t\t\/\/ process and execute solutions\n\t\treturn details::execute (cxt, s_range);\n\t}\n\n}\n\nstruct demo {\n\tfloat\txxx;\n\tfloat\tyyy;\n\tint\t\tzzz;\n\n\tvector < string > files;\n\n\tbool show_version;\n\tbool show_help;\n};\n\nvoid main_usage(demo & d) {}\n\nvoid show_version() {}\n\nint main(int arg_c, char * arg_v[]) {\n\n\tusing namespace command_line;\n\n\t\n\tchar * args[] = { \"garbage\", \"-x\", \"-x\", \"-z\", \"luciano\", \"da\", \"silva\" };\n\t\n\t\/\/auto expression = key(\"-t\") > key(\"-v\") | +key(\"-x\") > key(\"-v\");\n\n\tauto usage_options = *(\n\t\tkey(\"-x\") [&demo::xxx] |\n\t\tkey(\"-y\") [&demo::yyy] |\n\t\tkey(\"-z\") [&demo::zzz]\n\t);\n\t\n\tauto usage_default_values = +any()[&demo::files];\n\t\n\tauto expression =\n\t\tusage (&main_usage,\t\tusage_options >> usage_default_values) | \/\/.desc (\"yada yada yada ayad acoiso e tal\") |\n\t\tusage (&main_usage,\t\tusage_options) | \/\/.desc (\"coiso e tal\")\n\t\tusage (&show_version,\tkey(\"-v\"))\n\t;\n\t\n\tparse (expression, 7, args);\n\t\n\t\/\/auto val = command_line::value(&demo::xxx, .0F);\n\n\t\/*\n\t\/\/ define an instance of the command line parser\n\tparser < arguments_t > command_line;\n\n\t\/\/ set its available arguments and options\n\tcommand_line\n\t\t\/\/ option ( < member field address >, < list of command switches >, < description > )\n\t\t+ option(&arguments_t::show_version, { \"-v\", \"--version\" }, \"shows the version of the application\")\n\t\t+ option(&arguments_t::show_usage, { \"-h, --help\" }, \"shows this usage page\")\n\t\t\/\/ argument ( < member field address >, < list of command switches >, < description >, < is optional >, < default value > )\n\t\t+ argument(&arguments_t::value_a, { \"-va\", \"--value_a\" }, \"multiplicand\")\n\t\t+ argument(&arguments_t::value_b, { \"-vb\", \"--value_b\" }, \"multiplier\");\n\n\targuments_t args;\n\n\t\/\/ command line parser returs a context with information about\n\t\/\/ the success of the parsing operation and related errors\n\tauto context = command_line.parse(arg_c, arg_v, args);\n\n\t\/\/ if the parsing failed\n\tif (context.has_failed()) {\n\t\tcout << \"example failed with the following invalid arguments\" << endl;\n\t\t\/\/ the user can print all errors to an ostream\n\t\tcontext.to_stream(cout);\n\t\treturn -1;\n\t}\n\n\tif (args.show_version)\n\t\tcout << \"example 1.0\" << endl;\n\n\t\/\/ users can also print a list of options and arguments with their descriptions\n\t\/\/ to an ostream\n\tif (args.show_usage)\n\t\tcommand_line.usage_to_stream(cout);\n\n\tcout << \"example value: \" << (args.value_a * args.value_b) << endl;\n\t*\/\n\treturn 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\n\/\/---------------------------------------------------------------------------\ntemplate \nvoid solve_cpr(const Matrix &K, const std::vector &rhs, boost::property_tree::ptree &prm)\n{\n auto t1 = prof.scoped_tic(\"CPR\");\n\n typedef amgcl::backend::builtin Backend;\n\n typedef\n amgcl::amg\n PPrecond;\n\n typedef\n amgcl::relaxation::as_preconditioner\n SPrecond;\n\n amgcl::make_solver<\n amgcl::preconditioner::cpr,\n amgcl::runtime::solver::wrapper\n > solve(K, prm);\n\n std::cout << solve.precond() << std::endl;\n\n auto t2 = prof.scoped_tic(\"solve\");\n std::vector x(rhs.size(), 0.0);\n\n size_t iters;\n double error;\n\n std::tie(iters, error) = solve(rhs, x);\n\n std::cout << \"Iterations: \" << iters << std::endl\n << \"Error: \" << error << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\ntemplate \nvoid solve_block_cpr(const Matrix &K, const std::vector &rhs, boost::property_tree::ptree &prm)\n{\n auto t1 = prof.scoped_tic(\"CPR\");\n\n typedef amgcl::static_matrix val_type;\n typedef amgcl::static_matrix rhs_type;\n typedef amgcl::backend::builtin SBackend;\n typedef amgcl::backend::builtin PBackend;\n\n typedef\n amgcl::amg<\n PBackend,\n amgcl::runtime::coarsening::wrapper,\n amgcl::runtime::relaxation::wrapper>\n PPrecond;\n\n typedef\n amgcl::relaxation::as_preconditioner<\n SBackend,\n amgcl::runtime::relaxation::wrapper\n >\n SPrecond;\n\n amgcl::make_solver<\n amgcl::preconditioner::cpr,\n amgcl::runtime::solver::wrapper\n > solve(amgcl::adapter::block_matrix(K), prm);\n\n std::cout << solve.precond() << std::endl;\n\n auto t2 = prof.scoped_tic(\"solve\");\n std::vector x(rhs.size(), amgcl::math::zero());\n\n auto rhs_ptr = reinterpret_cast(rhs.data());\n size_t n = amgcl::backend::rows(K) \/ B;\n\n size_t iters;\n double error;\n\n std::tie(iters, error) = solve(amgcl::make_iterator_range(rhs_ptr, rhs_ptr + n), x);\n\n std::cout << \"Iterations: \" << iters << std::endl\n << \"Error: \" << error << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n using std::string;\n using std::vector;\n using amgcl::prof;\n using amgcl::precondition;\n\n namespace po = boost::program_options;\n namespace io = amgcl::io;\n\n po::options_description desc(\"Options\");\n\n desc.add_options()\n (\"help,h\", \"show help\")\n (\n \"binary,B\",\n po::bool_switch()->default_value(false),\n \"When specified, treat input files as binary instead of as MatrixMarket. \"\n \"It is assumed the files were converted to binary format with mm2bin utility. \"\n )\n (\n \"matrix,A\",\n po::value()->required(),\n \"The system matrix in MatrixMarket format\"\n )\n (\n \"rhs,f\",\n po::value(),\n \"The right-hand side in MatrixMarket format\"\n )\n (\n \"runtime-block-size,b\",\n po::value(),\n \"The block size of the system matrix set at runtime\"\n )\n (\n \"static-block-size,c\",\n po::value()->default_value(1),\n \"The block size of the system matrix set at compiletime\"\n )\n (\n \"params,P\",\n po::value(),\n \"parameter file in json format\"\n )\n (\n \"prm,p\",\n po::value< vector >()->multitoken(),\n \"Parameters specified as name=value pairs. \"\n \"May be provided multiple times. Examples:\\n\"\n \" -p solver.tol=1e-3\\n\"\n \" -p precond.coarse_enough=300\"\n )\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n po::notify(vm);\n\n boost::property_tree::ptree prm;\n if (vm.count(\"params\")) read_json(vm[\"params\"].as(), prm);\n\n if (vm.count(\"prm\")) {\n for(const string &v : vm[\"prm\"].as >()) {\n amgcl::put(prm, v);\n }\n }\n\n int cb = vm[\"static-block-size\"].as();\n\n if (vm.count(\"runtime-block-size\"))\n prm.put(\"precond.block_size\", vm[\"runtime-block-size\"].as());\n else\n prm.put(\"precond.block_size\", cb);\n\n size_t rows;\n vector ptr, col;\n vector val, rhs;\n std::vector pm;\n\n {\n auto t = prof.scoped_tic(\"reading\");\n\n string Afile = vm[\"matrix\"].as();\n bool binary = vm[\"binary\"].as();\n\n if (binary) {\n io::read_crs(Afile, rows, ptr, col, val);\n } else {\n size_t cols;\n std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);\n precondition(rows == cols, \"Non-square system matrix\");\n }\n\n if (vm.count(\"rhs\")) {\n string bfile = vm[\"rhs\"].as();\n\n size_t n, m;\n\n if (binary) {\n io::read_dense(bfile, n, m, rhs);\n } else {\n std::tie(n, m) = io::mm_reader(bfile)(rhs);\n }\n\n precondition(n == rows && m == 1, \"The RHS vector has wrong size\");\n } else {\n rhs.resize(rows, 1.0);\n }\n }\n\n#define CALL_BLOCK_SOLVER(z, data, B) \\\n case B: \\\n solve_block_cpr(std::tie(rows, ptr, col, val), rhs, prm); \\\n break;\n\n switch(cb) {\n case 1:\n solve_cpr(std::tie(rows, ptr, col, val), rhs, prm);\n break;\n\n BOOST_PP_SEQ_FOR_EACH(CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)\n\n default:\n precondition(false, \"Unsupported block size\");\n break;\n }\n\n std::cout << prof << std::endl;\n}\nProfile setup operations in examples\/cpr under \"setup\"#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace amgcl { profiler<> prof; }\nusing amgcl::prof;\nusing amgcl::precondition;\n\n\/\/---------------------------------------------------------------------------\ntemplate \nvoid solve_cpr(const Matrix &K, const std::vector &rhs, boost::property_tree::ptree &prm)\n{\n auto t1 = prof.scoped_tic(\"CPR\");\n\n typedef amgcl::backend::builtin Backend;\n\n typedef\n amgcl::amg\n PPrecond;\n\n typedef\n amgcl::relaxation::as_preconditioner\n SPrecond;\n\n prof.tic(\"setup\");\n amgcl::make_solver<\n amgcl::preconditioner::cpr,\n amgcl::runtime::solver::wrapper\n > solve(K, prm);\n prof.toc(\"setup\");\n\n std::cout << solve.precond() << std::endl;\n\n std::vector x(rhs.size(), 0.0);\n\n size_t iters;\n double error;\n\n prof.tic(\"setup\");\n std::tie(iters, error) = solve(rhs, x);\n prof.toc(\"setup\");\n\n std::cout << \"Iterations: \" << iters << std::endl\n << \"Error: \" << error << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\ntemplate \nvoid solve_block_cpr(const Matrix &K, const std::vector &rhs, boost::property_tree::ptree &prm)\n{\n auto t1 = prof.scoped_tic(\"CPR\");\n\n typedef amgcl::static_matrix val_type;\n typedef amgcl::static_matrix rhs_type;\n typedef amgcl::backend::builtin SBackend;\n typedef amgcl::backend::builtin PBackend;\n\n typedef\n amgcl::amg<\n PBackend,\n amgcl::runtime::coarsening::wrapper,\n amgcl::runtime::relaxation::wrapper>\n PPrecond;\n\n typedef\n amgcl::relaxation::as_preconditioner<\n SBackend,\n amgcl::runtime::relaxation::wrapper\n >\n SPrecond;\n\n prof.tic(\"setup\");\n amgcl::make_solver<\n amgcl::preconditioner::cpr,\n amgcl::runtime::solver::wrapper\n > solve(amgcl::adapter::block_matrix(K), prm);\n prof.toc(\"setup\");\n\n std::cout << solve.precond() << std::endl;\n\n std::vector x(rhs.size(), amgcl::math::zero());\n\n auto rhs_ptr = reinterpret_cast(rhs.data());\n size_t n = amgcl::backend::rows(K) \/ B;\n\n size_t iters;\n double error;\n\n prof.tic(\"solve\");\n std::tie(iters, error) = solve(amgcl::make_iterator_range(rhs_ptr, rhs_ptr + n), x);\n prof.toc(\"solve\");\n\n std::cout << \"Iterations: \" << iters << std::endl\n << \"Error: \" << error << std::endl;\n}\n\n\/\/---------------------------------------------------------------------------\nint main(int argc, char *argv[]) {\n using std::string;\n using std::vector;\n using amgcl::prof;\n using amgcl::precondition;\n\n namespace po = boost::program_options;\n namespace io = amgcl::io;\n\n po::options_description desc(\"Options\");\n\n desc.add_options()\n (\"help,h\", \"show help\")\n (\n \"binary,B\",\n po::bool_switch()->default_value(false),\n \"When specified, treat input files as binary instead of as MatrixMarket. \"\n \"It is assumed the files were converted to binary format with mm2bin utility. \"\n )\n (\n \"matrix,A\",\n po::value()->required(),\n \"The system matrix in MatrixMarket format\"\n )\n (\n \"rhs,f\",\n po::value(),\n \"The right-hand side in MatrixMarket format\"\n )\n (\n \"runtime-block-size,b\",\n po::value(),\n \"The block size of the system matrix set at runtime\"\n )\n (\n \"static-block-size,c\",\n po::value()->default_value(1),\n \"The block size of the system matrix set at compiletime\"\n )\n (\n \"params,P\",\n po::value(),\n \"parameter file in json format\"\n )\n (\n \"prm,p\",\n po::value< vector >()->multitoken(),\n \"Parameters specified as name=value pairs. \"\n \"May be provided multiple times. Examples:\\n\"\n \" -p solver.tol=1e-3\\n\"\n \" -p precond.coarse_enough=300\"\n )\n ;\n\n po::variables_map vm;\n po::store(po::parse_command_line(argc, argv, desc), vm);\n\n if (vm.count(\"help\")) {\n std::cout << desc << std::endl;\n return 0;\n }\n\n po::notify(vm);\n\n boost::property_tree::ptree prm;\n if (vm.count(\"params\")) read_json(vm[\"params\"].as(), prm);\n\n if (vm.count(\"prm\")) {\n for(const string &v : vm[\"prm\"].as >()) {\n amgcl::put(prm, v);\n }\n }\n\n int cb = vm[\"static-block-size\"].as();\n\n if (vm.count(\"runtime-block-size\"))\n prm.put(\"precond.block_size\", vm[\"runtime-block-size\"].as());\n else\n prm.put(\"precond.block_size\", cb);\n\n size_t rows;\n vector ptr, col;\n vector val, rhs;\n std::vector pm;\n\n {\n auto t = prof.scoped_tic(\"reading\");\n\n string Afile = vm[\"matrix\"].as();\n bool binary = vm[\"binary\"].as();\n\n if (binary) {\n io::read_crs(Afile, rows, ptr, col, val);\n } else {\n size_t cols;\n std::tie(rows, cols) = io::mm_reader(Afile)(ptr, col, val);\n precondition(rows == cols, \"Non-square system matrix\");\n }\n\n if (vm.count(\"rhs\")) {\n string bfile = vm[\"rhs\"].as();\n\n size_t n, m;\n\n if (binary) {\n io::read_dense(bfile, n, m, rhs);\n } else {\n std::tie(n, m) = io::mm_reader(bfile)(rhs);\n }\n\n precondition(n == rows && m == 1, \"The RHS vector has wrong size\");\n } else {\n rhs.resize(rows, 1.0);\n }\n }\n\n#define CALL_BLOCK_SOLVER(z, data, B) \\\n case B: \\\n solve_block_cpr(std::tie(rows, ptr, col, val), rhs, prm); \\\n break;\n\n switch(cb) {\n case 1:\n solve_cpr(std::tie(rows, ptr, col, val), rhs, prm);\n break;\n\n BOOST_PP_SEQ_FOR_EACH(CALL_BLOCK_SOLVER, ~, AMGCL_BLOCK_SIZES)\n\n default:\n precondition(false, \"Unsupported block size\");\n break;\n }\n\n std::cout << prof << std::endl;\n}\n<|endoftext|>"} {"text":"Edited a comment.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/app_launcher.h\"\n\n#include \n#include \n\n#include \"app\/resource_bundle.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/task.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/browser\/views\/info_bubble.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/location_bar\/location_bar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"views\/widget\/root_view.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#endif\n\nnamespace {\n\n\/\/ Padding between the navigation bar and the render view contents.\nconst int kNavigationBarBottomPadding = 3;\n\n\/\/ NavigationBar constants.\nconst int kNavigationBarBorderThickness = 1;\n\nconst SkColor kBorderColor = SkColorSetRGB(205, 201, 201);\n\n\/\/ Command line switch for specifying url of the page.\n\/\/ TODO: nuke when we convert to the real app page. Also nuke code in\n\/\/ AddNewContents\nconst wchar_t kURLSwitch[] = L\"main-menu-url\";\n\n\/\/ Returns the URL of the menu.\nstatic GURL GetMenuURL() {\n std::wstring url_string =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);\n if (!url_string.empty())\n return GURL(WideToUTF8(url_string));\n return GURL(chrome::kChromeUIAppLauncherURL);\n}\n\n\/\/ Returns the location bar view of |browser|.\nstatic views::View* GetBrowserLocationBar(Browser* browser) {\n BrowserView* browser_view = static_cast(browser->window());\n views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(\n browser_view->GetNativeHandle())->GetRootView();\n return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);\n}\n\n} \/\/ namespace\n\n\/\/ InfoBubbleContentsView\n\/\/\n\/\/ The view that contains the navigation bar and DOMUI.\n\/\/ It is displayed in an info-bubble.\n\nclass InfoBubbleContentsView : public views::View,\n public LocationBarView::Delegate,\n public CommandUpdater::CommandUpdaterDelegate {\n public:\n explicit InfoBubbleContentsView(AppLauncher* app_launcher);\n ~InfoBubbleContentsView();\n\n \/\/ Computes and sets the preferred size for the InfoBubbleContentsView based\n \/\/ on the preferred size of the DOMUI contents specified.\n void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);\n\n \/\/ Sets the initial focus.\n \/\/ Should be called when the bubble that contains us is shown.\n void BubbleShown();\n\n \/\/ views::View override:\n virtual gfx::Size GetPreferredSize();\n virtual void Layout();\n virtual void ViewHierarchyChanged(bool is_add,\n views::View* parent,\n views::View* child);\n\n \/\/ LocationBarView::Delegate implementation:\n virtual TabContents* GetTabContents();\n virtual void OnInputInProgress(bool in_progress) {}\n\n \/\/ CommandUpdater::CommandUpdaterDelegate implementation:\n virtual void ExecuteCommand(int id);\n\n private:\n \/\/ The application launcher displaying this info bubble.\n AppLauncher* app_launcher_;\n\n \/\/ The location bar.\n LocationBarView* location_bar_;\n\n \/\/ The view containing the renderer view.\n DOMView* dom_view_;\n\n \/\/ The preferred size for this view (at which it fits its contents).\n gfx::Size preferred_size_;\n\n \/\/ CommandUpdater the location bar sends commands to.\n CommandUpdater command_updater_;\n\n \/\/ The width of the browser's location bar.\n int browser_location_bar_width_;\n\n DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);\n};\n\nInfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)\n : app_launcher_(app_launcher),\n location_bar_(NULL),\n dom_view_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {\n \/\/ Allow the location bar to open URLs.\n command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);\n DCHECK(app_launcher);\n\n browser_location_bar_width_ =\n GetBrowserLocationBar(app_launcher->browser())->width();\n}\n\nInfoBubbleContentsView::~InfoBubbleContentsView() {\n}\n\nvoid InfoBubbleContentsView::ComputePreferredSize(\n const gfx::Size& dom_view_preferred_size) {\n preferred_size_ = dom_view_preferred_size;\n\n \/\/ Add the padding and location bar height.\n preferred_size_.Enlarge(\n 0, location_bar_->height() + kNavigationBarBottomPadding);\n\n \/\/ Make sure the width is at least the browser location bar width.\n if (preferred_size_.width() < browser_location_bar_width_)\n preferred_size_.set_width(browser_location_bar_width_);\n}\n\nvoid InfoBubbleContentsView::BubbleShown() {\n location_bar_->RequestFocus();\n}\n\nvoid InfoBubbleContentsView::ViewHierarchyChanged(\n bool is_add, views::View* parent, views::View* child) {\n if (!is_add || child != this)\n return;\n\n DCHECK(!dom_view_);\n dom_view_ = new DOMView();\n AddChildView(dom_view_);\n \/\/ We pass NULL for site instance so the renderer uses its own process.\n dom_view_->Init(app_launcher_->browser()->profile(), NULL);\n \/\/ We make the AppLauncher the TabContents delegate so we get notifications\n \/\/ from the page to open links.\n dom_view_->tab_contents()->set_delegate(app_launcher_);\n GURL url = GetMenuURL();\n std::string ref = url.ref();\n if (!app_launcher_->hash_params().empty()) {\n if (!ref.empty())\n ref += \"&\";\n ref += app_launcher_->hash_params();\n\n url_canon::Replacements replacements;\n replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));\n url = url.ReplaceComponents(replacements);\n }\n dom_view_->LoadURL(url);\n\n Browser* browser = app_launcher_->browser();\n location_bar_ = new LocationBarView(browser->profile(),\n &command_updater_,\n browser->toolbar_model(),\n this,\n LocationBarView::APP_LAUNCHER);\n\n location_bar_->set_border(\n views::Border::CreateSolidBorder(kNavigationBarBorderThickness,\n kBorderColor));\n AddChildView(location_bar_);\n location_bar_->Init();\n \/\/ Size the location to its preferred size so ComputePreferredSize() computes\n \/\/ the right size.\n location_bar_->SizeToPreferredSize();\n ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));\n Layout();\n}\n\nTabContents* InfoBubbleContentsView::GetTabContents() {\n return app_launcher_->browser()->GetSelectedTabContents();\n}\n\ngfx::Size InfoBubbleContentsView::GetPreferredSize() {\n return preferred_size_;\n}\n\nvoid InfoBubbleContentsView::Layout() {\n if (bounds().IsEmpty() || GetChildViewCount() == 0)\n return;\n\n gfx::Rect bounds = GetLocalBounds(false);\n location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),\n location_bar_->GetPreferredSize().height());\n int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;\n dom_view_->SetBounds(0, render_y,\n width(),\n std::max(0, bounds.height() - render_y + bounds.y()));\n}\n\nvoid InfoBubbleContentsView::ExecuteCommand(int id) {\n \/\/ The user navigated by typing or selecting an entry in the location bar.\n DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);\n GURL url(WideToUTF8(location_bar_->GetInputString()));\n app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());\n app_launcher_->Hide();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppLauncher\n\nAppLauncher::AppLauncher(Browser* browser)\n : browser_(browser),\n info_bubble_(NULL) {\n DCHECK(browser);\n info_bubble_content_ = new InfoBubbleContentsView(this);\n}\n\nAppLauncher::~AppLauncher() {\n}\n\n\/\/ static\nAppLauncher* AppLauncher::Show(Browser* browser,\n const gfx::Rect& bounds,\n const gfx::Point& bubble_anchor,\n const std::string& hash_params) {\n AppLauncher* app_launcher = new AppLauncher(browser);\n BrowserView* browser_view = static_cast(browser->window());\n app_launcher->hash_params_ = hash_params;\n app_launcher->info_bubble_ =\n PinnedContentsInfoBubble::Show(browser_view->GetWidget(),\n bounds, BubbleBorder::TOP_LEFT, bubble_anchor,\n app_launcher->info_bubble_content_, app_launcher);\n app_launcher->info_bubble_content_->BubbleShown();\n return app_launcher;\n}\n\n\/\/ static\nAppLauncher* AppLauncher::ShowForNewTab(Browser* browser,\n const std::string& hash_params) {\n BrowserView* browser_view = static_cast(browser->window());\n TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();\n if (!tabstrip)\n return NULL;\n gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();\n gfx::Point origin = bounds.origin();\n views::RootView::ConvertPointToScreen(tabstrip, &origin);\n bounds.set_origin(origin);\n\n \/\/ Figure out where the location bar is, so we can pin the bubble to\n \/\/ make our url bar appear exactly over it.\n views::View* location_bar = GetBrowserLocationBar(browser);\n gfx::Point location_bar_origin = location_bar->bounds().origin();\n views::RootView::ConvertPointToScreen(location_bar->GetParent(),\n &location_bar_origin);\n\n return Show(browser, bounds, location_bar_origin, hash_params);\n}\n\nvoid AppLauncher::Hide() {\n info_bubble_->Close();\n}\n\nvoid AppLauncher::OpenURLFromTab(TabContents* source,\n const GURL& url, const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n \/\/ TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need\n \/\/ to access the app for this URL.\n \/\/ The user clicked an item in the app launcher contents.\n AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);\n Hide();\n}\n\nvoid AppLauncher::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n#if defined(OS_CHROMEOS)\n \/\/ ChromeOS uses the kURLSwitch to specify a page that opens popups. We need\n \/\/ to do this so the popups are opened when the user clicks on the page.\n \/\/ TODO: nuke when convert to the real app page.\n new_contents->set_delegate(NULL);\n browser_->GetSelectedTabContents()->AddNewContents(\n new_contents, disposition, initial_pos, user_gesture);\n Hide();\n#endif\n}\n\nvoid AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {\n if (pref_size.width() == 0 || pref_size.height() == 0)\n return;\n\n gfx::Size size(pref_size);\n info_bubble_content_->ComputePreferredSize(size);\n info_bubble_->SizeToContents();\n}\n\nvoid AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,\n bool closed_by_escape) {\n \/\/ Delay deleting to be safe (we, and our tabcontents may be on the stack).\n \/\/ Remove ourself as a delegate as on GTK the Widget destruction is\n \/\/ asynchronous and will happen after the AppLauncher has been deleted (and it\n \/\/ might notify us after we have been deleted).\n info_bubble_content_->GetTabContents()->set_delegate(NULL);\n MessageLoop::current()->PostTask(FROM_HERE,\n new DeleteTask(this));\n}\n\nvoid AppLauncher::AddTabWithURL(const GURL& url,\n PageTransition::Type transition) {\n#if defined(OS_CHROMEOS)\n switch (chromeos::StatusAreaView::GetOpenTabsMode()) {\n case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {\n \/\/ Add the new tab at the first non-pinned location.\n int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();\n browser_->AddTabWithURL(url, GURL(), transition, index,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n break;\n }\n case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {\n browser_->GetSelectedTabContents()->controller().LoadURL(\n url, GURL(), transition);\n break;\n }\n case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {\n browser_->AddTabWithURL(url, GURL(), transition, -1,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n break;\n }\n }\n#else\n browser_->AddTabWithURL(url, GURL(), transition, -1,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n#endif\n}\nThe wrong TabContents' delegate was being NULLed when the app launcher was closed (the browser's current tab instead of the app launcher's one). This was causing a crasher with the context menu and possibly way more bad things.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/views\/app_launcher.h\"\n\n#include \n#include \n\n#include \"app\/resource_bundle.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/task.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/browser.h\"\n#include \"chrome\/browser\/browser_window.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/browser\/view_ids.h\"\n#include \"chrome\/browser\/views\/dom_view.h\"\n#include \"chrome\/browser\/views\/info_bubble.h\"\n#include \"chrome\/browser\/views\/frame\/browser_view.h\"\n#include \"chrome\/browser\/views\/location_bar\/location_bar_view.h\"\n#include \"chrome\/common\/url_constants.h\"\n#include \"views\/widget\/root_view.h\"\n\n#if defined(OS_CHROMEOS)\n#include \"chrome\/browser\/chromeos\/status\/status_area_view.h\"\n#endif\n\nnamespace {\n\n\/\/ Padding between the navigation bar and the render view contents.\nconst int kNavigationBarBottomPadding = 3;\n\n\/\/ NavigationBar constants.\nconst int kNavigationBarBorderThickness = 1;\n\nconst SkColor kBorderColor = SkColorSetRGB(205, 201, 201);\n\n\/\/ Command line switch for specifying url of the page.\n\/\/ TODO: nuke when we convert to the real app page. Also nuke code in\n\/\/ AddNewContents\nconst wchar_t kURLSwitch[] = L\"main-menu-url\";\n\n\/\/ Returns the URL of the menu.\nstatic GURL GetMenuURL() {\n std::wstring url_string =\n CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);\n if (!url_string.empty())\n return GURL(WideToUTF8(url_string));\n return GURL(chrome::kChromeUIAppLauncherURL);\n}\n\n\/\/ Returns the location bar view of |browser|.\nstatic views::View* GetBrowserLocationBar(Browser* browser) {\n BrowserView* browser_view = static_cast(browser->window());\n views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(\n browser_view->GetNativeHandle())->GetRootView();\n return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);\n}\n\n} \/\/ namespace\n\n\/\/ InfoBubbleContentsView\n\/\/\n\/\/ The view that contains the navigation bar and DOMUI.\n\/\/ It is displayed in an info-bubble.\n\nclass InfoBubbleContentsView : public views::View,\n public LocationBarView::Delegate,\n public CommandUpdater::CommandUpdaterDelegate {\n public:\n explicit InfoBubbleContentsView(AppLauncher* app_launcher);\n ~InfoBubbleContentsView();\n\n \/\/ Computes and sets the preferred size for the InfoBubbleContentsView based\n \/\/ on the preferred size of the DOMUI contents specified.\n void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);\n\n \/\/ Sets the initial focus.\n \/\/ Should be called when the bubble that contains us is shown.\n void BubbleShown();\n\n \/\/ Returns the TabContents displaying the contents for this bubble.\n TabContents* GetBubbleTabContents();\n\n \/\/ views::View override:\n virtual gfx::Size GetPreferredSize();\n virtual void Layout();\n virtual void ViewHierarchyChanged(bool is_add,\n views::View* parent,\n views::View* child);\n\n \/\/ LocationBarView::Delegate implementation:\n\n \/\/ WARNING: this is not the TabContents of the bubble! Use\n \/\/ GetBubbleTabContents() to get the bubble's TabContents.\n virtual TabContents* GetTabContents();\n virtual void OnInputInProgress(bool in_progress) {}\n\n \/\/ CommandUpdater::CommandUpdaterDelegate implementation:\n virtual void ExecuteCommand(int id);\n\n private:\n \/\/ The application launcher displaying this info bubble.\n AppLauncher* app_launcher_;\n\n \/\/ The location bar.\n LocationBarView* location_bar_;\n\n \/\/ The view containing the renderer view.\n DOMView* dom_view_;\n\n \/\/ The preferred size for this view (at which it fits its contents).\n gfx::Size preferred_size_;\n\n \/\/ CommandUpdater the location bar sends commands to.\n CommandUpdater command_updater_;\n\n \/\/ The width of the browser's location bar.\n int browser_location_bar_width_;\n\n DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);\n};\n\nInfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)\n : app_launcher_(app_launcher),\n location_bar_(NULL),\n dom_view_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {\n \/\/ Allow the location bar to open URLs.\n command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);\n DCHECK(app_launcher);\n\n browser_location_bar_width_ =\n GetBrowserLocationBar(app_launcher->browser())->width();\n}\n\nInfoBubbleContentsView::~InfoBubbleContentsView() {\n}\n\nvoid InfoBubbleContentsView::ComputePreferredSize(\n const gfx::Size& dom_view_preferred_size) {\n preferred_size_ = dom_view_preferred_size;\n\n \/\/ Add the padding and location bar height.\n preferred_size_.Enlarge(\n 0, location_bar_->height() + kNavigationBarBottomPadding);\n\n \/\/ Make sure the width is at least the browser location bar width.\n if (preferred_size_.width() < browser_location_bar_width_)\n preferred_size_.set_width(browser_location_bar_width_);\n}\n\nvoid InfoBubbleContentsView::BubbleShown() {\n location_bar_->RequestFocus();\n}\n\nTabContents* InfoBubbleContentsView::GetBubbleTabContents() {\n return dom_view_->tab_contents();\n}\n\nvoid InfoBubbleContentsView::ViewHierarchyChanged(\n bool is_add, views::View* parent, views::View* child) {\n if (!is_add || child != this)\n return;\n\n DCHECK(!dom_view_);\n dom_view_ = new DOMView();\n AddChildView(dom_view_);\n \/\/ We pass NULL for site instance so the renderer uses its own process.\n dom_view_->Init(app_launcher_->browser()->profile(), NULL);\n \/\/ We make the AppLauncher the TabContents delegate so we get notifications\n \/\/ from the page to open links.\n dom_view_->tab_contents()->set_delegate(app_launcher_);\n GURL url = GetMenuURL();\n std::string ref = url.ref();\n if (!app_launcher_->hash_params().empty()) {\n if (!ref.empty())\n ref += \"&\";\n ref += app_launcher_->hash_params();\n\n url_canon::Replacements replacements;\n replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));\n url = url.ReplaceComponents(replacements);\n }\n dom_view_->LoadURL(url);\n\n Browser* browser = app_launcher_->browser();\n location_bar_ = new LocationBarView(browser->profile(),\n &command_updater_,\n browser->toolbar_model(),\n this,\n LocationBarView::APP_LAUNCHER);\n\n location_bar_->set_border(\n views::Border::CreateSolidBorder(kNavigationBarBorderThickness,\n kBorderColor));\n AddChildView(location_bar_);\n location_bar_->Init();\n \/\/ Size the location to its preferred size so ComputePreferredSize() computes\n \/\/ the right size.\n location_bar_->SizeToPreferredSize();\n ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));\n Layout();\n}\n\nTabContents* InfoBubbleContentsView::GetTabContents() {\n return app_launcher_->browser()->GetSelectedTabContents();\n}\n\ngfx::Size InfoBubbleContentsView::GetPreferredSize() {\n return preferred_size_;\n}\n\nvoid InfoBubbleContentsView::Layout() {\n if (bounds().IsEmpty() || GetChildViewCount() == 0)\n return;\n\n gfx::Rect bounds = GetLocalBounds(false);\n location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),\n location_bar_->GetPreferredSize().height());\n int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;\n dom_view_->SetBounds(0, render_y,\n width(),\n std::max(0, bounds.height() - render_y + bounds.y()));\n}\n\nvoid InfoBubbleContentsView::ExecuteCommand(int id) {\n \/\/ The user navigated by typing or selecting an entry in the location bar.\n DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);\n GURL url(WideToUTF8(location_bar_->GetInputString()));\n app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());\n app_launcher_->Hide();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ AppLauncher\n\nAppLauncher::AppLauncher(Browser* browser)\n : browser_(browser),\n info_bubble_(NULL) {\n DCHECK(browser);\n info_bubble_content_ = new InfoBubbleContentsView(this);\n}\n\nAppLauncher::~AppLauncher() {\n}\n\n\/\/ static\nAppLauncher* AppLauncher::Show(Browser* browser,\n const gfx::Rect& bounds,\n const gfx::Point& bubble_anchor,\n const std::string& hash_params) {\n AppLauncher* app_launcher = new AppLauncher(browser);\n BrowserView* browser_view = static_cast(browser->window());\n app_launcher->hash_params_ = hash_params;\n app_launcher->info_bubble_ =\n PinnedContentsInfoBubble::Show(browser_view->GetWidget(),\n bounds, BubbleBorder::TOP_LEFT, bubble_anchor,\n app_launcher->info_bubble_content_, app_launcher);\n app_launcher->info_bubble_content_->BubbleShown();\n return app_launcher;\n}\n\n\/\/ static\nAppLauncher* AppLauncher::ShowForNewTab(Browser* browser,\n const std::string& hash_params) {\n BrowserView* browser_view = static_cast(browser->window());\n TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();\n if (!tabstrip)\n return NULL;\n gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();\n gfx::Point origin = bounds.origin();\n views::RootView::ConvertPointToScreen(tabstrip, &origin);\n bounds.set_origin(origin);\n\n \/\/ Figure out where the location bar is, so we can pin the bubble to\n \/\/ make our url bar appear exactly over it.\n views::View* location_bar = GetBrowserLocationBar(browser);\n gfx::Point location_bar_origin = location_bar->bounds().origin();\n views::RootView::ConvertPointToScreen(location_bar->GetParent(),\n &location_bar_origin);\n\n return Show(browser, bounds, location_bar_origin, hash_params);\n}\n\nvoid AppLauncher::Hide() {\n info_bubble_->Close();\n}\n\nvoid AppLauncher::OpenURLFromTab(TabContents* source,\n const GURL& url, const GURL& referrer,\n WindowOpenDisposition disposition,\n PageTransition::Type transition) {\n \/\/ TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need\n \/\/ to access the app for this URL.\n \/\/ The user clicked an item in the app launcher contents.\n AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);\n Hide();\n}\n\nvoid AppLauncher::AddNewContents(TabContents* source,\n TabContents* new_contents,\n WindowOpenDisposition disposition,\n const gfx::Rect& initial_pos,\n bool user_gesture) {\n#if defined(OS_CHROMEOS)\n \/\/ ChromeOS uses the kURLSwitch to specify a page that opens popups. We need\n \/\/ to do this so the popups are opened when the user clicks on the page.\n \/\/ TODO: nuke when convert to the real app page.\n new_contents->set_delegate(NULL);\n browser_->GetSelectedTabContents()->AddNewContents(\n new_contents, disposition, initial_pos, user_gesture);\n Hide();\n#endif\n}\n\nvoid AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {\n if (pref_size.width() == 0 || pref_size.height() == 0)\n return;\n\n gfx::Size size(pref_size);\n info_bubble_content_->ComputePreferredSize(size);\n info_bubble_->SizeToContents();\n}\n\nvoid AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,\n bool closed_by_escape) {\n \/\/ Delay deleting to be safe (we, and our tabcontents may be on the stack).\n \/\/ Remove ourself as a delegate as on GTK the Widget destruction is\n \/\/ asynchronous and will happen after the AppLauncher has been deleted (and it\n \/\/ might notify us after we have been deleted).\n info_bubble_content_->GetBubbleTabContents()->set_delegate(NULL);\n MessageLoop::current()->PostTask(FROM_HERE,\n new DeleteTask(this));\n}\n\nvoid AppLauncher::AddTabWithURL(const GURL& url,\n PageTransition::Type transition) {\n#if defined(OS_CHROMEOS)\n switch (chromeos::StatusAreaView::GetOpenTabsMode()) {\n case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {\n \/\/ Add the new tab at the first non-pinned location.\n int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();\n browser_->AddTabWithURL(url, GURL(), transition, index,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n break;\n }\n case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {\n browser_->GetSelectedTabContents()->controller().LoadURL(\n url, GURL(), transition);\n break;\n }\n case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {\n browser_->AddTabWithURL(url, GURL(), transition, -1,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n break;\n }\n }\n#else\n browser_->AddTabWithURL(url, GURL(), transition, -1,\n Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,\n NULL, std::string());\n#endif\n}\n<|endoftext|>"} {"text":"Try to cleanup temporary directories created during install operations.<|endoftext|>"} {"text":"#include \"ros\/ros.h\"\n#include \"NavigationControl.hpp\"\n#include \"Robosub\/HighLevelControl.h\"\n\n\nNavigationControl::NavigationControl()\n : m_nodeHandle(),\n m_highLevelMotorPublisher()\n{\n \/\/bool OMODE = OFF;\n POINTMODE = OFF;\n LINEMODE = OFF;\n \/\/bool Centered = false;\n Begun = false;\n OnLine = false;\n Rotating = false;\n\n start_x = 0;\n start_y = 0;\n start_rot = 0;\n\n m_highLevelMotorPublisher = m_nodeHandle.advertise(\"High_Level_Motion\", 10);\n ros::Subscriber targetPoint = m_nodeHandle.subscribe(\"Center_On_Point\", 1, &NavigationControl::PointCallback, this);\n ros::Subscriber targetLine = m_nodeHandle.subscribe(\"Center_On_Line\", 1, &NavigationControl::LineCallback, this);\n ros::Subscriber enabled = m_nodeHandle.subscribe(\"Module_Enable\", 1, &NavigationControl::EnabledCallback, this);\n}\n\nNavigationControl::~NavigationControl()\n{\n\n}\n\n\/**\n* @brief Translates a percentage to a thrust unit\n*\n* @param percent Percent of the distance\n*\/\nfloat NavigationControl::makeVoltage(float percent)\n{\n \/\/The smallest output is 60\n \/\/The largets output is 255\n \n \/\/map from 100 to 255 and from 60 to 5 percent\n \n return (percent - 5) * (255-60) \/ (100-5) + 60;\n \/\/return (x - in_min) * (out_max - out_min) \/ (in_max - in_min) + out_min;\n\n \n}\n\/\/ Create a thrust for Diving\n\/\/ and send it to the motor\nvoid NavigationControl::setDive(float val)\n{ \n \n float thrust = makeVoltage(val);\n publishMotor(\"Depth\", \"Manual\",thrust);\n \n}\n\nvoid NavigationControl::setStrafe(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Straf\", \"Manual\",thrust);\n}\n\nvoid NavigationControl::setDrive(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Forward\", \"Manual\",thrust);\n\n}\n\nvoid NavigationControl::setTurn(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Turn\", \"Manual\",thrust);\n}\n\nvoid NavigationControl::run()\n{\n \/\/if want to do something between spins\n \/\/change to a while loop with ros::spinOnce() and sleep \n ros::spin(); \n}\n\nvoid NavigationControl::EnabledCallback(const Robosub::ModuleEnableMsg& msg) {\n\tif(msg.Module == \"NavigationControl\")\n\t{\n\t\t\/\/POINTMODE = msg.State;\n\n\t}\n}\n\n\nvoid NavigationControl::PointCallback(const Robosub::Point& msg)\n{\n\t\t\/\/ The speed is created based on the difference between\n \/\/ the target point and the center\n\n \/\/ If the it is the beginning of the process\n \/\/ save the target as the objective\n\n \/\/ Target points\n int target_x = msg.x;\n int target_y = msg.y;\n\n if (!target_x && !target_y ) {\n\/\/ Centered = true;\n Begun = false;\n start_x = 0;\n start_y = 0;\n\n setStrafe(0);\n setDive(0);\n\n return;\n }\n\n\n if (!Begun){ \/\/ First assignment: create starting points\n start_x = msg.x;\n start_y = msg.y;\n Begun = true;\n\/\/ Centered = false;\n }\n\n\n \/\/ Calculate the directions what direction do we have to move?\n\n int dir_x = target_x>0 ? 1 : -1; \/\/Left -1, Right +1\n int dir_y = target_y>0 ? -1 : 1; \/\/Up -1, Down +1\n\n \/\/ Calculate the percentage (OR SIMPLY USE ERROR??)\n\n float per_x = (target_x\/start_x);\n float per_y = (target_y\/start_y);\n\n \/\/ Control Process (calculate the right thrust)\n \/\/ Use less than 100% based on how big the number is.\n\n \/\/ Convert the distance percentage to thrust percentage\n\n \/\/ These are set assuming there is no bias on the voltage\n \/\/ sent to the thrusters\n int minT = 50; \/\/ to avoid sending values under the minimum.\n \/\/maxT = 90; \/\/To avoid moving too fast and sucking too much power\n int range = 40;\n\n\n int thrust_x = 0;\n int thrust_y = 0;\n\n if((per_x) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_x = -60*dir_x;\n } else {\n thrust_x = 0;\n }\n } else {\n thrust_x = (range*per_x+minT)*dir_x;\n }\n\n if((per_y) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_y = -60*dir_y;\n } else {\n thrust_y = 0; \/\/ We zeroed out in this direction\n }\n } else {\n if(dir_y>0) \/\/ && FORWARDCAMERA\n range = 30; \/\/So we don't go up too fast\n thrust_y = (range*per_y+minT)*dir_y;\n }\n\n \/\/Send the calculated speed to the motor\n setStrafe(thrust_x);\n setDive(thrust_y);\n\n}\n\nbool NavigationControl::moveToLine(int x, int y){\n \/\/Returns 1 if on top of the line, 0 otherwise\n\n int target_x = x;\n int target_y = y;\n\n if (!target_x && !target_y ) {\n\/\/ Centered = true;\n Begun = false;\n\n start_x = 0;\n start_y = 0;\n\n setStrafe(0);\n setDrive(0);\n\n return 1; \/\/Centered\n }\n\n\n if (!Begun){ \/\/ First assignment: create starting points\n start_x = x;\n start_y = y;\n Begun = true;\n\/\/ Centered = false;\n }\n\n\n \/\/ Calculate the directions what direction do we have to move?\n\n int dir_x = target_x>0 ? 1 : -1; \/\/Left -1, Right +1\n int dir_y = target_y>0 ? 1 : -1; \/\/Reverse -1, Forward +1\n\n \/\/ Calculate the percentage (OR SIMPLY USE ERROR??)\n\n float per_x = (target_x\/start_x);\n float per_y = (target_y\/start_y);\n\n \/\/ Control Process (calculate the right thrust)\n \/\/ Use less than 100% based on how big the number is.\n\n \/\/ Convert the distance percentage to thrust percentage\n\n \/\/ These are set assuming there is no bias on the voltage\n \/\/ sent to the thrusters\n int minT = 50; \/\/ to avoid sending values under the minimum.\n \/\/maxT = 90; \/\/To avoid moving too fast and sucking too much power\n int range = 40;\n\n\n int thrust_x = 0;\n int thrust_y = 0;\n\n if((per_x) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_x = -60*dir_x;\n } else {\n thrust_x = 0; \/\/ this line may be unnecessary\n }\n } else {\n thrust_x = (range*per_x+minT)*dir_x;\n }\n\n if((per_y) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_y = -60*dir_y;\n } else {\n thrust_y = 0; \/\/ We zeroed out in this direction\n }\n } else {\n if(dir_y>0) \/\/\n range = 30; \/\/So we don't go up too fast\n thrust_y = (range*per_y+minT)*dir_y;\n }\n\n if (!thrust_x && !thrust_y)\n return 1; \/\/No speed means we're <1% away\n\n\n \/\/Send the calculated speed to the motor\n setStrafe(thrust_x);\n setDrive(thrust_y);\n\n return 0;\n\n}\n\nfloat NavigationControl::sanitize(float rot){\n \/\/converts the given rotation to a number between 0-180\n if (rot>=180)\n\treturn rot-360;\n return rot;\n}\n\nvoid NavigationControl::LineCallback(const Robosub::Line msg) {\n\tif(LINEMODE == OFF)\n\t\treturn;\n\n OnLine = moveToLine(msg.x, msg.y);\n \/\/Once it's on top of the line, rotate\n if (!OnLine){\n return; \/\/keep rotating\n }\n\n int target_rot = sanitize(msg.rotation);\n if(!target_rot){\n\t start_rot = 0;\n Rotating = 0;\n\t setTurn(0);\n\t return; \/\/Stoppped by Higher Level\n }\n if(!Rotating){\n start_rot = target_rot;\n }\n\n float per_rot = (target_rot\/start_rot);\n\n\n \/\/This needs to be implemented better (any ideas?)\n \/\/int direction = 1; \/\/always rotate right?\n int direction = target_rot>0 ? 1 : -1; \/\/-1 Rotate left\n\n\n int rate = 0;\n int range=40;\n int minR = 50;\n\n if(abs(per_rot).01)\n rate = -60*direction;\n else\n rate = 0;\n } else {\n rate = (range*per_rot+minR)*direction;\n }\n\n setTurn(rate);\n\n}\n\n\/**\n * @brief plubish to the high level motor controller topic\n *\n * @param direction The direction: Forward, Straf, Turn\n * @param motion The motion type: Manual, Offset\n * @param value The value\n *\/\nvoid NavigationControl::publishMotor(std::string direction, std::string motion, float value)\n{\n Robosub::HighLevelControl msg;\n msg.Direction = direction;\n msg.MotionType = motion;\n msg.Value = value;\n\n m_highLevelMotorPublisher.publish(msg);\n}\nFix brackets on NavigationControl#include \"ros\/ros.h\"\n#include \"NavigationControl.hpp\"\n#include \"Robosub\/HighLevelControl.h\"\n\n\nNavigationControl::NavigationControl()\n : m_nodeHandle(),\n m_highLevelMotorPublisher()\n{\n \/\/bool OMODE = OFF;\n POINTMODE = OFF;\n LINEMODE = OFF;\n \/\/bool Centered = false;\n Begun = false;\n OnLine = false;\n Rotating = false;\n\n start_x = 0;\n start_y = 0;\n start_rot = 0;\n\n m_highLevelMotorPublisher = m_nodeHandle.advertise(\"High_Level_Motion\", 10);\n ros::Subscriber targetPoint = m_nodeHandle.subscribe(\"Center_On_Point\", 1, &NavigationControl::PointCallback, this);\n ros::Subscriber targetLine = m_nodeHandle.subscribe(\"Center_On_Line\", 1, &NavigationControl::LineCallback, this);\n ros::Subscriber enabled = m_nodeHandle.subscribe(\"Module_Enable\", 1, &NavigationControl::EnabledCallback, this);\n}\n\nNavigationControl::~NavigationControl()\n{\n\n}\n\n\/**\n* @brief Translates a percentage to a thrust unit\n*\n* @param percent Percent of the distance\n*\/\nfloat NavigationControl::makeVoltage(float percent)\n{\n \/\/The smallest output is 60\n \/\/The largets output is 255\n \n \/\/map from 100 to 255 and from 60 to 5 percent\n \n return (percent - 5) * (255-60) \/ (100-5) + 60;\n \/\/return (x - in_min) * (out_max - out_min) \/ (in_max - in_min) + out_min;\n\n \n}\n\/\/ Create a thrust for Diving\n\/\/ and send it to the motor\nvoid NavigationControl::setDive(float val)\n{ \n \n float thrust = makeVoltage(val);\n publishMotor(\"Depth\", \"Manual\",thrust);\n \n}\n\nvoid NavigationControl::setStrafe(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Straf\", \"Manual\",thrust);\n}\n\nvoid NavigationControl::setDrive(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Forward\", \"Manual\",thrust);\n\n}\n\nvoid NavigationControl::setTurn(float val)\n{\n float thrust = makeVoltage(val);\n publishMotor(\"Turn\", \"Manual\",thrust);\n}\n\nvoid NavigationControl::run()\n{\n \/\/if want to do something between spins\n \/\/change to a while loop with ros::spinOnce() and sleep \n ros::spin(); \n}\n\nvoid NavigationControl::EnabledCallback(const Robosub::ModuleEnableMsg& msg) {\n\tif(msg.Module == \"NavigationControl\")\n\t{\n\t\t\/\/POINTMODE = msg.State;\n\n\t}\n}\n\n\nvoid NavigationControl::PointCallback(const Robosub::Point& msg)\n{\n\t\t\/\/ The speed is created based on the difference between\n \/\/ the target point and the center\n\n \/\/ If the it is the beginning of the process\n \/\/ save the target as the objective\n\n \/\/ Target points\n int target_x = msg.x;\n int target_y = msg.y;\n\n if (!target_x && !target_y ) {\n\/\/ Centered = true;\n Begun = false;\n start_x = 0;\n start_y = 0;\n\n setStrafe(0);\n setDive(0);\n\n return;\n }\n\n\n if (!Begun){ \/\/ First assignment: create starting points\n start_x = msg.x;\n start_y = msg.y;\n Begun = true;\n\/\/ Centered = false;\n }\n\n\n \/\/ Calculate the directions what direction do we have to move?\n\n int dir_x = target_x>0 ? 1 : -1; \/\/Left -1, Right +1\n int dir_y = target_y>0 ? -1 : 1; \/\/Up -1, Down +1\n\n \/\/ Calculate the percentage (OR SIMPLY USE ERROR??)\n\n float per_x = (target_x\/start_x);\n float per_y = (target_y\/start_y);\n\n \/\/ Control Process (calculate the right thrust)\n \/\/ Use less than 100% based on how big the number is.\n\n \/\/ Convert the distance percentage to thrust percentage\n\n \/\/ These are set assuming there is no bias on the voltage\n \/\/ sent to the thrusters\n int minT = 50; \/\/ to avoid sending values under the minimum.\n \/\/maxT = 90; \/\/To avoid moving too fast and sucking too much power\n int range = 40;\n\n\n int thrust_x = 0;\n int thrust_y = 0;\n\n if((per_x) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_x = -60*dir_x;\n } else {\n thrust_x = 0;\n }\n } else {\n thrust_x = (range*per_x+minT)*dir_x;\n }\n\n if((per_y) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_y = -60*dir_y;\n } else {\n thrust_y = 0; \/\/ We zeroed out in this direction\n }\n } else {\n if(dir_y>0){ \/\/ && FORWARDCAMERA\n range = 30; \/\/So we don't go up too fast\n thrust_y = (range*per_y+minT)*dir_y;\n\t\t}\n }\n\n \/\/Send the calculated speed to the motor\n setStrafe(thrust_x);\n setDive(thrust_y);\n\n}\n\nbool NavigationControl::moveToLine(int x, int y){\n \/\/Returns 1 if on top of the line, 0 otherwise\n\n int target_x = x;\n int target_y = y;\n\n if (!target_x && !target_y ) {\n\/\/ Centered = true;\n Begun = false;\n\n start_x = 0;\n start_y = 0;\n\n setStrafe(0);\n setDrive(0);\n\n return 1; \/\/Centered\n }\n\n\n if (!Begun){ \/\/ First assignment: create starting points\n start_x = x;\n start_y = y;\n Begun = true;\n\/\/ Centered = false;\n }\n\n\n \/\/ Calculate the directions what direction do we have to move?\n\n int dir_x = target_x>0 ? 1 : -1; \/\/Left -1, Right +1\n int dir_y = target_y>0 ? 1 : -1; \/\/Reverse -1, Forward +1\n\n \/\/ Calculate the percentage (OR SIMPLY USE ERROR??)\n\n float per_x = (target_x\/start_x);\n float per_y = (target_y\/start_y);\n\n \/\/ Control Process (calculate the right thrust)\n \/\/ Use less than 100% based on how big the number is.\n\n \/\/ Convert the distance percentage to thrust percentage\n\n \/\/ These are set assuming there is no bias on the voltage\n \/\/ sent to the thrusters\n int minT = 50; \/\/ to avoid sending values under the minimum.\n \/\/maxT = 90; \/\/To avoid moving too fast and sucking too much power\n int range = 40;\n\n\n int thrust_x = 0;\n int thrust_y = 0;\n\n if((per_x) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_x = -60*dir_x;\n } else {\n thrust_x = 0; \/\/ this line may be unnecessary\n }\n } else {\n thrust_x = (range*per_x+minT)*dir_x;\n }\n\n if((per_y) MIN_THRESHOLD){ \/\/Send a negative thrust to decrease the speed\n thrust_y = -60*dir_y;\n } else {\n thrust_y = 0; \/\/ We zeroed out in this direction\n }\n } else {\n if(dir_y>0){ \/\/\n range = 30; \/\/So we don't go up too fast\n thrust_y = (range*per_y+minT)*dir_y;\n\t\t}\n }\n\n if (!thrust_x && !thrust_y)\n return 1; \/\/No speed means we're <1% away\n\n\n \/\/Send the calculated speed to the motor\n setStrafe(thrust_x);\n setDrive(thrust_y);\n\n return 0;\n\n}\n\nfloat NavigationControl::sanitize(float rot){\n \/\/converts the given rotation to a number between 0-180\n if (rot>=180)\n\treturn rot-360;\n return rot;\n}\n\nvoid NavigationControl::LineCallback(const Robosub::Line msg) {\n\tif(LINEMODE == OFF)\n\t\treturn;\n\n OnLine = moveToLine(msg.x, msg.y);\n \/\/Once it's on top of the line, rotate\n if (!OnLine){\n return; \/\/keep rotating\n }\n\n int target_rot = sanitize(msg.rotation);\n if(!target_rot){\n\t start_rot = 0;\n Rotating = 0;\n\t setTurn(0);\n\t return; \/\/Stoppped by Higher Level\n }\n if(!Rotating){\n start_rot = target_rot;\n }\n\n float per_rot = (target_rot\/start_rot);\n\n\n \/\/This needs to be implemented better (any ideas?)\n \/\/int direction = 1; \/\/always rotate right?\n int direction = target_rot>0 ? 1 : -1; \/\/-1 Rotate left\n\n\n int rate = 0;\n int range=40;\n int minR = 50;\n\n if(abs(per_rot).01)\n rate = -60*direction;\n else\n rate = 0;\n } else {\n rate = (range*per_rot+minR)*direction;\n }\n\n setTurn(rate);\n\n}\n\n\/**\n * @brief plubish to the high level motor controller topic\n *\n * @param direction The direction: Forward, Straf, Turn\n * @param motion The motion type: Manual, Offset\n * @param value The value\n *\/\nvoid NavigationControl::publishMotor(std::string direction, std::string motion, float value)\n{\n Robosub::HighLevelControl msg;\n msg.Direction = direction;\n msg.MotionType = motion;\n msg.Value = value;\n\n m_highLevelMotorPublisher.publish(msg);\n}\n<|endoftext|>"} {"text":"\/* http_bidder_interface.cc\n Eric Robert, 2 April 2014\n Copyright (c) 2011 Datacratic. All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"soa\/utils\/generic_utils.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n DefaultDescription desc;\n\n std::string httpErrorString(HttpClientError code) {\n switch (code) {\n #define CASE(code) \\\n case code: \\\n return #code;\n CASE(HttpClientError::NONE)\n CASE(HttpClientError::UNKNOWN)\n CASE(HttpClientError::TIMEOUT)\n CASE(HttpClientError::HOST_NOT_FOUND)\n CASE(HttpClientError::COULD_NOT_CONNECT)\n #undef CASE\n }\n ExcCheck(false, \"Invalid code path\");\n return \"\";\n }\n}\n\nnamespace RTBKIT {\n\nLogging::Category HttpBidderInterface::print(\"HttpBidderInterface\");\nLogging::Category HttpBidderInterface::error(\"HttpBidderInterface Error\", HttpBidderInterface::print);\nLogging::Category HttpBidderInterface::trace(\"HttpBidderInterface Trace\", HttpBidderInterface::print);\n\n}\n\nHttpBidderInterface::HttpBidderInterface(std::string serviceName,\n std::shared_ptr proxies,\n Json::Value const & json)\n : BidderInterface(proxies, serviceName) {\n\n try {\n routerHost = json[\"router\"][\"host\"].asString();\n routerPath = json[\"router\"][\"path\"].asString();\n adserverHost = json[\"adserver\"][\"host\"].asString();\n adserverWinPort = json[\"adserver\"][\"winPort\"].asInt();\n adserverEventPort = json[\"adserver\"][\"eventPort\"].asInt();\n } catch (const std::exception & e) {\n THROW(error) << \"configuration file is invalid\" << std::endl\n << \"usage : \" << std::endl\n << \"{\" << std::endl << \"\\t\\\"router\\\" : {\" << std::endl\n << \"\\t\\t\\\"host\\\" : \" << std::endl \n << \"\\t\\t\\\"path\\\" : \" << std::endl\n << \"\\t}\" << std::endl << \"\\t{\" << std::endl \n << \"\\t{\" << std::endl << \"\\t\\\"adserver\\\" : {\" << std::endl\n << \"\\t\\t\\\"host\\\" : \" << std::endl \n << \"\\t\\t\\\"winPort\\\" : \" << std::endl \n << \"\\t\\t\\\"eventPort\\\" : \" << std::endl\n << \"\\t}\" << std::endl << \"}\";\n }\n\n httpClientRouter.reset(new HttpClient(routerHost));\n loop.addSource(\"HttpBidderInterface::httpClientRouter\", httpClientRouter);\n\n std::string winHost = adserverHost + ':' + std::to_string(adserverWinPort);\n httpClientAdserverWins.reset(new HttpClient(winHost));\n loop.addSource(\"HttpBidderInterface::httpClientAdserverWins\", httpClientAdserverWins);\n\n std::string eventHost = adserverHost + ':' + std::to_string(adserverEventPort);\n httpClientAdserverEvents.reset(new HttpClient(eventHost));\n loop.addSource(\"HttpBidderInterface::httpClientAdserverEvents\", httpClientAdserverEvents);\n\n}\n\nHttpBidderInterface::~HttpBidderInterface()\n{\n shutdown();\n}\n\nvoid HttpBidderInterface::start() {\n loop.start();\n}\n\nvoid HttpBidderInterface::shutdown() {\n loop.shutdown();\n}\n\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr const & auction,\n double timeLeftMs,\n std::map const & bidders) {\n using namespace std;\n\n auto findAgent = [=](uint64_t externalId)\n -> pair> {\n\n auto it =\n find_if(begin(bidders), end(bidders),\n [&](const pair &bidder)\n {\n std::string agent = bidder.first;\n const auto &info = router->agents[agent];\n return info.config->externalId == externalId;\n });\n\n if (it == end(bidders)) {\n return make_pair(\"\", nullptr);\n }\n\n return make_pair(it->first, it->second.agentConfig);\n\n };\n\n BidRequest originalRequest = *auction->request;\n OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);\n bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);\n \/* If we took too much time processing the request, then we don't send it. *\/\n if (!ok) {\n return;\n }\n StructuredJsonPrintingContext context;\n desc.printJson(&openRtbRequest, context);\n auto requestStr = context.output.toString();\n\n \/* We need to capture by copy inside the lambda otherwise we might get\n a dangling reference if we go out of scope before receiving the http response\n *\/\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n router->throwException(\"http\", \"Error requesting %s: %s\",\n routerHost.c_str(),\n httpErrorString(errorCode).c_str());\n }\n \/\/ If we receive a 204 No-bid, we still need to \"re-inject\" it to the\n \/\/ router otherwise we won't expire the inFlights\n else if (statusCode == 204) {\n Bids bids;\n bids.resize(openRtbRequest.imp.size());\n fill(begin(bids), end(bids), Bid());\n for (const auto &bidder: bidders) {\n submitBids(bidder.first, auction->id, bids, WinCostModel());\n }\n }\n\n else if (statusCode == 200) {\n \/\/ cerr << \"Response: \" << body << endl;\n OpenRTB::BidResponse response;\n ML::Parse_Context context(\"payload\",\n body.c_str(), body.size());\n StreamingJsonParsingContext jsonContext(context);\n static DefaultDescription respDesc;\n respDesc.parseJson(&response, jsonContext);\n\n for (const auto &seatbid: response.seatbid) {\n\n for (const auto &bid: seatbid.bid) {\n if (!bid.ext.isMember(\"external-id\")) {\n router->throwException(\"http.response\",\n \"Missing external-id ext field in BidResponse\");\n }\n\n if (!bid.ext.isMember(\"priority\")) {\n router->throwException(\"http.response\",\n \"Missing priority ext field in BidResponse\");\n }\n\n uint64_t externalId = bid.ext[\"external-id\"].asUInt();\n\n string agent;\n shared_ptr config;\n tie(agent, config) = findAgent(externalId);\n if (config == nullptr) {\n router->throwException(\"http.response\",\n \"Couldn't find config for externalId: %lu\",\n externalId);\n }\n\n Bids bids;\n Bid theBid;\n\n int crid = bid.crid.toInt();\n int creativeIndex = indexOf(config->creatives,\n &Creative::id, crid);\n\n if (creativeIndex == -1) {\n router->throwException(\"http.response\",\n \"Unknown creative id: %d\", crid);\n }\n\n theBid.creativeIndex = creativeIndex;\n theBid.price = USD_CPM(bid.price.val);\n theBid.priority = bid.ext[\"priority\"].asDouble();\n\n int spotIndex = indexOf(openRtbRequest.imp,\n &OpenRTB::Impression::id, bid.impid);\n if (spotIndex == -1) {\n router->throwException(\"http.response\",\n \"Unknown impression id: %s\",\n bid.impid.toString().c_str());\n }\n\n theBid.spotIndex = spotIndex;\n\n bids.push_back(std::move(theBid));\n\n WinCostModel wcm =\n auction->exchangeConnector->getWinCostModel(*auction, *config);\n\n submitBids(agent, auction->id, bids, wcm);\n }\n }\n }\n }\n );\n\n HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n \/\/ std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n \/\/ std::cerr << \"Content \" << reqContent.str << std::endl;\n\n httpClientRouter->post(routerPath, callbacks, reqContent,\n { } \/* queryParams *\/, headers);\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n std::string const & id) {\n\n}\n\nvoid HttpBidderInterface::sendWinLossMessage(MatchedWinLoss const & event) {\n if (event.type == MatchedWinLoss::Loss) return;\n\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n throw ML::Exception(\"Error requesting %s:%d '%s'\",\n adserverHost.c_str(),\n adserverWinPort,\n httpErrorString(errorCode).c_str());\n }\n });\n\n Json::Value content;\n\n content[\"timestamp\"] = event.timestamp.secondsSinceEpoch();\n content[\"bidRequestId\"] = event.auctionId.toString();\n content[\"impid\"] = event.impId.toString();\n content[\"userIds\"] = event.uids.toJson();\n \/\/ ratio cannot be casted to json::value ...\n content[\"price\"] = (double) getAmountIn(event.winPrice);\n\n \/\/requestStr[\"passback\"];\n \n HttpRequest::Content reqContent { content, \"application\/json\" };\n httpClientAdserverWins->post(\"\/\", callbacks, reqContent,\n { } \/* queryParams *\/);\n \n}\n\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,\n MatchedCampaignEvent const & event) {\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n throw ML::Exception(\"Error requesting %s:%d '%s'\",\n adserverHost.c_str(),\n adserverEventPort,\n httpErrorString(errorCode).c_str());\n }\n });\n \n Json::Value content;\n\n content[\"timestamp\"] = event.timestamp.secondsSinceEpoch();\n content[\"bidRequestId\"] = event.auctionId.toString();\n content[\"impid\"] = event.impId.toString();\n content[\"type\"] = event.label;\n \n HttpRequest::Content reqContent { content, \"application\/json\" };\n httpClientAdserverEvents->post(\"\/\", callbacks, reqContent,\n { } \/* queryParams *\/);\n \n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n std::string const & reason,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n std::string const & error,\n std::vector const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n int ping) {\n ExcCheck(ping == 0 || ping == 1, \"Bad PING level, must be either 0 or 1\");\n\n auto encodeDate = [](Date date) {\n return ML::format(\"%.5f\", date.secondsSinceEpoch());\n };\n\n const std::string sentTime = encodeDate(Date::now());\n const std::string receivedTime = sentTime;\n const std::string pong = (ping == 0 ? \"PONG0\" : \"PONG1\");\n std::vector message { agent, pong, sentTime, receivedTime };\n router->handleAgentMessage(message);\n}\n\nvoid HttpBidderInterface::tagRequest(OpenRTB::BidRequest &request,\n const std::map &bidders) const\n{\n\n for (const auto &bidder: bidders) {\n const auto &agentConfig = bidder.second.agentConfig;\n const auto &spots = bidder.second.imp;\n\n for (const auto &spot: spots) {\n const int adSpotIndex = spot.first;\n ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),\n \"adSpotIndex out of range\");\n auto &imp = request.imp[adSpotIndex];\n auto &ext = imp.ext;\n\n ext[\"external-ids\"].append(agentConfig->externalId);\n }\n\n }\n\n}\n\nbool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,\n const RTBKIT::BidRequest &originalRequest,\n const std::map &bidders) const {\n tagRequest(request, bidders);\n\n \/\/ We update the tmax value before sending the BidRequest to substract our processing time\n double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;\n int oldTmax = request.tmax.value();\n int newTmax = oldTmax - static_cast(std::round(processingTimeMs));\n if (newTmax <= 0) {\n return false;\n }\n#if 0\n std::cerr << \"old tmax = \" << oldTmax << std::std::endl\n << \"new tmax = \" << newTmax << std::std::endl;\n#endif\n ExcCheck(newTmax <= oldTmax, \"Wrong tmax calculation\");\n request.tmax.val = newTmax;\n return true;\n}\n\nvoid HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,\n const Bids &bids, WinCostModel wcm)\n{\n Json::FastWriter writer;\n std::vector message { agent, \"BID\" };\n message.push_back(auctionId.toString());\n std::string bidsStr = writer.write(bids.toJson());\n std::string wcmStr = writer.write(wcm.toJson());\n message.push_back(std::move(bidsStr));\n message.push_back(std::move(wcmStr));\n\n router->doBid(message);\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nnamespace {\n\nstruct AtInit {\n AtInit()\n {\n BidderInterface::registerFactory(\"http\",\n [](std::string const & serviceName,\n std::shared_ptr const & proxies,\n Json::Value const & json)\n {\n return new HttpBidderInterface(serviceName, proxies, json);\n });\n }\n} atInit;\n\n}\n\nHttpBidderInterface: Making sure to remove the trailing characters that might be introduced by Json::FastWriter\/* http_bidder_interface.cc\n Eric Robert, 2 April 2014\n Copyright (c) 2011 Datacratic. All rights reserved.\n*\/\n\n#include \"http_bidder_interface.h\"\n#include \"jml\/db\/persistent.h\"\n#include \"soa\/service\/http_client.h\"\n#include \"soa\/utils\/generic_utils.h\"\n#include \"rtbkit\/common\/messages.h\"\n#include \"rtbkit\/plugins\/bid_request\/openrtb_bid_request.h\"\n#include \"rtbkit\/openrtb\/openrtb_parsing.h\"\n#include \"rtbkit\/core\/router\/router.h\"\n\nusing namespace Datacratic;\nusing namespace RTBKIT;\n\nnamespace {\n DefaultDescription desc;\n\n std::string httpErrorString(HttpClientError code) {\n switch (code) {\n #define CASE(code) \\\n case code: \\\n return #code;\n CASE(HttpClientError::NONE)\n CASE(HttpClientError::UNKNOWN)\n CASE(HttpClientError::TIMEOUT)\n CASE(HttpClientError::HOST_NOT_FOUND)\n CASE(HttpClientError::COULD_NOT_CONNECT)\n #undef CASE\n }\n ExcCheck(false, \"Invalid code path\");\n return \"\";\n }\n}\n\nnamespace RTBKIT {\n\nLogging::Category HttpBidderInterface::print(\"HttpBidderInterface\");\nLogging::Category HttpBidderInterface::error(\"HttpBidderInterface Error\", HttpBidderInterface::print);\nLogging::Category HttpBidderInterface::trace(\"HttpBidderInterface Trace\", HttpBidderInterface::print);\n\n}\n\nHttpBidderInterface::HttpBidderInterface(std::string serviceName,\n std::shared_ptr proxies,\n Json::Value const & json)\n : BidderInterface(proxies, serviceName) {\n\n try {\n routerHost = json[\"router\"][\"host\"].asString();\n routerPath = json[\"router\"][\"path\"].asString();\n adserverHost = json[\"adserver\"][\"host\"].asString();\n adserverWinPort = json[\"adserver\"][\"winPort\"].asInt();\n adserverEventPort = json[\"adserver\"][\"eventPort\"].asInt();\n } catch (const std::exception & e) {\n THROW(error) << \"configuration file is invalid\" << std::endl\n << \"usage : \" << std::endl\n << \"{\" << std::endl << \"\\t\\\"router\\\" : {\" << std::endl\n << \"\\t\\t\\\"host\\\" : \" << std::endl \n << \"\\t\\t\\\"path\\\" : \" << std::endl\n << \"\\t}\" << std::endl << \"\\t{\" << std::endl \n << \"\\t{\" << std::endl << \"\\t\\\"adserver\\\" : {\" << std::endl\n << \"\\t\\t\\\"host\\\" : \" << std::endl \n << \"\\t\\t\\\"winPort\\\" : \" << std::endl \n << \"\\t\\t\\\"eventPort\\\" : \" << std::endl\n << \"\\t}\" << std::endl << \"}\";\n }\n\n httpClientRouter.reset(new HttpClient(routerHost));\n loop.addSource(\"HttpBidderInterface::httpClientRouter\", httpClientRouter);\n\n std::string winHost = adserverHost + ':' + std::to_string(adserverWinPort);\n httpClientAdserverWins.reset(new HttpClient(winHost));\n loop.addSource(\"HttpBidderInterface::httpClientAdserverWins\", httpClientAdserverWins);\n\n std::string eventHost = adserverHost + ':' + std::to_string(adserverEventPort);\n httpClientAdserverEvents.reset(new HttpClient(eventHost));\n loop.addSource(\"HttpBidderInterface::httpClientAdserverEvents\", httpClientAdserverEvents);\n\n}\n\nHttpBidderInterface::~HttpBidderInterface()\n{\n shutdown();\n}\n\nvoid HttpBidderInterface::start() {\n loop.start();\n}\n\nvoid HttpBidderInterface::shutdown() {\n loop.shutdown();\n}\n\n\nvoid HttpBidderInterface::sendAuctionMessage(std::shared_ptr const & auction,\n double timeLeftMs,\n std::map const & bidders) {\n using namespace std;\n\n auto findAgent = [=](uint64_t externalId)\n -> pair> {\n\n auto it =\n find_if(begin(bidders), end(bidders),\n [&](const pair &bidder)\n {\n std::string agent = bidder.first;\n const auto &info = router->agents[agent];\n return info.config->externalId == externalId;\n });\n\n if (it == end(bidders)) {\n return make_pair(\"\", nullptr);\n }\n\n return make_pair(it->first, it->second.agentConfig);\n\n };\n\n BidRequest originalRequest = *auction->request;\n OpenRTB::BidRequest openRtbRequest = toOpenRtb(originalRequest);\n bool ok = prepareRequest(openRtbRequest, originalRequest, bidders);\n \/* If we took too much time processing the request, then we don't send it. *\/\n if (!ok) {\n return;\n }\n StructuredJsonPrintingContext context;\n desc.printJson(&openRtbRequest, context);\n auto requestStr = context.output.toString();\n\n \/* We need to capture by copy inside the lambda otherwise we might get\n a dangling reference if we go out of scope before receiving the http response\n *\/\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n router->throwException(\"http\", \"Error requesting %s: %s\",\n routerHost.c_str(),\n httpErrorString(errorCode).c_str());\n }\n \/\/ If we receive a 204 No-bid, we still need to \"re-inject\" it to the\n \/\/ router otherwise we won't expire the inFlights\n else if (statusCode == 204) {\n Bids bids;\n bids.resize(openRtbRequest.imp.size());\n fill(begin(bids), end(bids), Bid());\n for (const auto &bidder: bidders) {\n submitBids(bidder.first, auction->id, bids, WinCostModel());\n }\n }\n\n else if (statusCode == 200) {\n \/\/ cerr << \"Response: \" << body << endl;\n OpenRTB::BidResponse response;\n ML::Parse_Context context(\"payload\",\n body.c_str(), body.size());\n StreamingJsonParsingContext jsonContext(context);\n static DefaultDescription respDesc;\n respDesc.parseJson(&response, jsonContext);\n\n for (const auto &seatbid: response.seatbid) {\n\n for (const auto &bid: seatbid.bid) {\n if (!bid.ext.isMember(\"external-id\")) {\n router->throwException(\"http.response\",\n \"Missing external-id ext field in BidResponse\");\n }\n\n if (!bid.ext.isMember(\"priority\")) {\n router->throwException(\"http.response\",\n \"Missing priority ext field in BidResponse\");\n }\n\n uint64_t externalId = bid.ext[\"external-id\"].asUInt();\n\n string agent;\n shared_ptr config;\n tie(agent, config) = findAgent(externalId);\n if (config == nullptr) {\n router->throwException(\"http.response\",\n \"Couldn't find config for externalId: %lu\",\n externalId);\n }\n\n Bids bids;\n Bid theBid;\n\n int crid = bid.crid.toInt();\n int creativeIndex = indexOf(config->creatives,\n &Creative::id, crid);\n\n if (creativeIndex == -1) {\n router->throwException(\"http.response\",\n \"Unknown creative id: %d\", crid);\n }\n\n theBid.creativeIndex = creativeIndex;\n theBid.price = USD_CPM(bid.price.val);\n theBid.priority = bid.ext[\"priority\"].asDouble();\n\n int spotIndex = indexOf(openRtbRequest.imp,\n &OpenRTB::Impression::id, bid.impid);\n if (spotIndex == -1) {\n router->throwException(\"http.response\",\n \"Unknown impression id: %s\",\n bid.impid.toString().c_str());\n }\n\n theBid.spotIndex = spotIndex;\n\n bids.push_back(std::move(theBid));\n\n WinCostModel wcm =\n auction->exchangeConnector->getWinCostModel(*auction, *config);\n\n submitBids(agent, auction->id, bids, wcm);\n }\n }\n }\n }\n );\n\n HttpRequest::Content reqContent { requestStr, \"application\/json\" };\n RestParams headers { { \"x-openrtb-version\", \"2.1\" } };\n \/\/ std::cerr << \"Sending HTTP POST to: \" << host << \" \" << path << std::endl;\n \/\/ std::cerr << \"Content \" << reqContent.str << std::endl;\n\n httpClientRouter->post(routerPath, callbacks, reqContent,\n { } \/* queryParams *\/, headers);\n}\n\nvoid HttpBidderInterface::sendLossMessage(std::string const & agent,\n std::string const & id) {\n\n}\n\nvoid HttpBidderInterface::sendWinLossMessage(MatchedWinLoss const & event) {\n if (event.type == MatchedWinLoss::Loss) return;\n\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n throw ML::Exception(\"Error requesting %s:%d '%s'\",\n adserverHost.c_str(),\n adserverWinPort,\n httpErrorString(errorCode).c_str());\n }\n });\n\n Json::Value content;\n\n content[\"timestamp\"] = event.timestamp.secondsSinceEpoch();\n content[\"bidRequestId\"] = event.auctionId.toString();\n content[\"impid\"] = event.impId.toString();\n content[\"userIds\"] = event.uids.toJson();\n \/\/ ratio cannot be casted to json::value ...\n content[\"price\"] = (double) getAmountIn(event.winPrice);\n\n \/\/requestStr[\"passback\"];\n \n HttpRequest::Content reqContent { content, \"application\/json\" };\n httpClientAdserverWins->post(\"\/\", callbacks, reqContent,\n { } \/* queryParams *\/);\n \n}\n\n\nvoid HttpBidderInterface::sendBidLostMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendCampaignEventMessage(std::string const & agent,\n MatchedCampaignEvent const & event) {\n auto callbacks = std::make_shared(\n [=](const HttpRequest &, HttpClientError errorCode,\n int statusCode, const std::string &, std::string &&body)\n {\n if (errorCode != HttpClientError::NONE) {\n throw ML::Exception(\"Error requesting %s:%d '%s'\",\n adserverHost.c_str(),\n adserverEventPort,\n httpErrorString(errorCode).c_str());\n }\n });\n \n Json::Value content;\n\n content[\"timestamp\"] = event.timestamp.secondsSinceEpoch();\n content[\"bidRequestId\"] = event.auctionId.toString();\n content[\"impid\"] = event.impId.toString();\n content[\"type\"] = event.label;\n \n HttpRequest::Content reqContent { content, \"application\/json\" };\n httpClientAdserverEvents->post(\"\/\", callbacks, reqContent,\n { } \/* queryParams *\/);\n \n}\n\nvoid HttpBidderInterface::sendBidDroppedMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendBidInvalidMessage(std::string const & agent,\n std::string const & reason,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendNoBudgetMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendTooLateMessage(std::string const & agent,\n std::shared_ptr const & auction) {\n}\n\nvoid HttpBidderInterface::sendMessage(std::string const & agent,\n std::string const & message) {\n}\n\nvoid HttpBidderInterface::sendErrorMessage(std::string const & agent,\n std::string const & error,\n std::vector const & payload) {\n}\n\nvoid HttpBidderInterface::sendPingMessage(std::string const & agent,\n int ping) {\n ExcCheck(ping == 0 || ping == 1, \"Bad PING level, must be either 0 or 1\");\n\n auto encodeDate = [](Date date) {\n return ML::format(\"%.5f\", date.secondsSinceEpoch());\n };\n\n const std::string sentTime = encodeDate(Date::now());\n const std::string receivedTime = sentTime;\n const std::string pong = (ping == 0 ? \"PONG0\" : \"PONG1\");\n std::vector message { agent, pong, sentTime, receivedTime };\n router->handleAgentMessage(message);\n}\n\nvoid HttpBidderInterface::tagRequest(OpenRTB::BidRequest &request,\n const std::map &bidders) const\n{\n\n for (const auto &bidder: bidders) {\n const auto &agentConfig = bidder.second.agentConfig;\n const auto &spots = bidder.second.imp;\n\n for (const auto &spot: spots) {\n const int adSpotIndex = spot.first;\n ExcCheck(adSpotIndex >= 0 && adSpotIndex < request.imp.size(),\n \"adSpotIndex out of range\");\n auto &imp = request.imp[adSpotIndex];\n auto &ext = imp.ext;\n\n ext[\"external-ids\"].append(agentConfig->externalId);\n }\n\n }\n\n}\n\nbool HttpBidderInterface::prepareRequest(OpenRTB::BidRequest &request,\n const RTBKIT::BidRequest &originalRequest,\n const std::map &bidders) const {\n tagRequest(request, bidders);\n\n \/\/ We update the tmax value before sending the BidRequest to substract our processing time\n double processingTimeMs = originalRequest.timestamp.secondsUntil(Date::now()) * 1000;\n int oldTmax = request.tmax.value();\n int newTmax = oldTmax - static_cast(std::round(processingTimeMs));\n if (newTmax <= 0) {\n return false;\n }\n#if 0\n std::cerr << \"old tmax = \" << oldTmax << std::std::endl\n << \"new tmax = \" << newTmax << std::std::endl;\n#endif\n ExcCheck(newTmax <= oldTmax, \"Wrong tmax calculation\");\n request.tmax.val = newTmax;\n return true;\n}\n\nvoid HttpBidderInterface::submitBids(const std::string &agent, Id auctionId,\n const Bids &bids, WinCostModel wcm)\n{\n Json::FastWriter writer;\n std::vector message { agent, \"BID\" };\n message.push_back(auctionId.toString());\n\n std::string bidsStr = writer.write(bids.toJson());\n boost::trim(bidsStr);\n\n std::string wcmStr = writer.write(wcm.toJson());\n boost::trim(wcmStr);\n\n message.push_back(std::move(bidsStr));\n message.push_back(std::move(wcmStr));\n\n router->doBid(message);\n}\n\n\/\/\n\/\/ factory\n\/\/\n\nnamespace {\n\nstruct AtInit {\n AtInit()\n {\n BidderInterface::registerFactory(\"http\",\n [](std::string const & serviceName,\n std::shared_ptr const & proxies,\n Json::Value const & json)\n {\n return new HttpBidderInterface(serviceName, proxies, json);\n });\n }\n} atInit;\n\n}\n\n<|endoftext|>"} {"text":"fix iterator issue in client_test<|endoftext|>"} {"text":"\/\/ $Author: benine $\n\/\/\n\/\/ Coded and compiled using c++11 standard\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"contig.hpp\"\n#include \"print_time.hpp\"\n#include \"process.hpp\"\n#include \"read.hpp\"\n#include \"afin_util.hpp\"\n\nusing namespace std;\n\n\/\/ TASK:: create installer with ability to test for presence of zlib? and\/or install zlib\n\/\/ give installer capability to install to default directory or accept input directory to install executable to.. or just leave it in the base directory of the code\n\/\/ TASK:: add signal handling\n\/\/ TASK:: add support for gzipped files\n\/\/ TASK:: give option to suppress output to screen\n\/\/ TASK:: Review what goes into the logfile vs what gets printed to the screen\n\/\/ TASK:: Look into whether N's and misses should be counted together? Or how they should relate to each other\n\/\/ TASK:: Exact matching in the contig_fusion_support() may be too conservative\n\/\/ TASK:: Review check_cov() and use a coverage that incorporates only the matching bp at that position\n\/\/ TASK:: make global variables and options for the variables that need it\n\/\/ TASK:: Change names of any functions that no longer title their function\n\/\/ TASK:: Write up documentation explaining each option, its purpose, and why the default is set the way it is\n\/\/ TASK:: Check limits of readlist size and other limits at all points of the program\n\/\/ TASK:: Clean up functions, break long functions into smaller ones and eliminate unused functions\n\/\/ TASK:: Remove using line from each file and add std:: where necessary\n\/\/\n\/\/ TASK:: Throws out_of_range error when min_overlap < 4.... ? Not that it should ever be that low\n\/\/\n\/\/ TASK:: add long options\n\/\/ TASK:: Add processing for IUPAC DNA ambiguity codes\n\/\/ TASK:: Add processing for differences in reads( ie, create new contig objects for differing sets of matches, add method for splitting matchlist between two new contig objects ), determine which contig is correct\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\\n\/\/ BEGIN MAIN FUNCTION \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main( int argc, char** argv ){\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Process Command Line Options \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n max_search_loops = 10;\n contig_sub_len = 100;\n extend_len = 80;\n max_sort_char = 4;\n min_cov_init = 5;\n min_overlap = 20;\n max_threads = 4;\n initial_trim = 20;\n max_missed = 5;\n mismatch_threshold = 0.1;\n test_run = false;\n int c;\n Process process;\n \n \/\/ prevent output to stderr if erroneous option is found\n opterr = 0;\n\n \/\/ get all options that have been provided on the command line\n while (( c = getopt (argc, argv, \"hr:c:o:s:l:x:m:i:p:t:a:b:d:e:f:g:z\" )) != -1 ) {\n switch( c ) {\n case 'h':\n print_usage( argv[0] );\n exit(0);\n break;\n \/\/ max_sort_char option\n case 'm':\n max_sort_char = atoi(optarg);\n break;\n \/\/ contig_sub_len option\n case 's':\n contig_sub_len = atoi(optarg);\n break;\n \/\/ extend_len option\n case 'x':\n extend_len = atoi(optarg);\n break;\n \/\/ max_sort_char option\n case 'l':\n max_search_loops = atoi(optarg);\n break;\n \/\/ min_cov_init option\n case 'i':\n min_cov_init = atoi(optarg);\n break;\n \/\/ min_overlap option\n case 'p':\n min_overlap = atoi(optarg);\n break;\n \/\/ max_threads option\n case 't':\n max_threads = atoi(optarg);\n break;\n \/\/ initial_trim option\n case 'd':\n initial_trim = atoi(optarg);\n break;\n \/\/ max_missed option\n case 'e':\n max_missed = atoi(optarg);\n break;\n \/\/ mismatch_threshold option\n case 'g':\n mismatch_threshold = atof(optarg);\n break;\n \/\/ outputfile option\n case 'o':\n cout << \"output file: \" << optarg << endl;\n process.outfile = optarg;\n print_time();\n break;\n \/\/ readfile option\n case 'r':\n optind--;\n \/\/ loop through each file\n while ( optind < argc && argv[optind][0] != '-' ) { \n process.readsfiles.append( \",\" );\n process.readsfiles.append( argv[optind] );\n optind++;\n } \n break;\n \/\/ contig file option\n case 'c':\n optind--;\n \/\/ loop through each file\n while ( optind < argc && argv[optind][0] != '-' ) { \n process.contigsfiles.append( \",\" );\n process.contigsfiles.append( argv[optind] );\n optind++;\n } \n break;\n \/\/ test_run option\n case 'z':\n test_run = true;\n break;\n case '?':\n if ( optopt == 'r' ){\n fprintf( stderr, \"%s: Error: Option -r requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( optopt == 'o' ){\n fprintf( stderr, \"%s: Error: Option -o requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( optopt == 'c' ){\n fprintf( stderr, \"%s: Error: Option -c requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( isprint( optopt )){\n fprintf( stderr, \"%s: Error: Unknown option -%c. \\n\", argv[0], optopt );\n print_usage( argv[0] );\n }\n else{\n fprintf( stderr, \"%s: Error: Unknown option character %x.\\n\", argv[0], optopt );\n print_usage( argv[0] );\n }\n return 1;\n default:\n abort();\n }\n }\n \n while ( optind < argc ) {\n cout << argv[optind] << endl;\n optind++;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ End Options \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Test Thread Queue \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ start run\n process.start_run();\n\n int length[process.contigs.size()];\n for( int i=0; ijust a couple of small changes to afin.cpp\/\/ $Author: benine $\n\/\/\n\/\/ Coded and compiled using c++11 standard\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"contig.hpp\"\n#include \"print_time.hpp\"\n#include \"process.hpp\"\n#include \"read.hpp\"\n#include \"afin_util.hpp\"\n\nusing namespace std;\n\n\/\/ TASK:: create installer with ability to test for presence of zlib? and\/or install zlib\n\/\/ give installer capability to install to default directory or accept input directory to install executable to.. or just leave it in the base directory of the code\n\/\/ TASK:: add signal handling\n\/\/ TASK:: add support for gzipped files\n\/\/ TASK:: give option to suppress output to screen\n\/\/ TASK:: Review what goes into the logfile vs what gets printed to the screen\n\/\/ TASK:: Look into whether N's and misses should be counted together? Or how they should relate to each other\n\/\/ TASK:: Exact matching in the contig_fusion_support() may be too conservative\n\/\/ TASK:: Review check_cov() and use a coverage that incorporates only the matching bp at that position\n\/\/ TASK:: make global variables and options for the variables that need it\n\/\/ TASK:: Change names of any functions that no longer title their function\n\/\/ TASK:: Write up documentation explaining each option, its purpose, and why the default is set the way it is\n\/\/ TASK:: Check limits of readlist size and other limits at all points of the program\n\/\/ TASK:: Clean up functions, break long functions into smaller ones and eliminate unused functions\n\/\/ TASK:: Remove using line from each file and add std:: where necessary\n\/\/\n\/\/ TASK:: Throws out_of_range error when min_overlap < 4.... ? Not that it should ever be that low\n\/\/\n\/\/ TASK:: add long options\n\/\/ TASK:: Add processing for IUPAC DNA ambiguity codes\n\/\/ TASK:: Add processing for differences in reads( ie, create new contig objects for differing sets of matches, add method for splitting matchlist between two new contig objects ), determine which contig is correct\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\\\n\/\/ BEGIN MAIN FUNCTION \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/>\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nint main( int argc, char** argv ){\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Process Command Line Options \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n max_search_loops = 10;\n contig_sub_len = 100;\n extend_len = 80;\n max_sort_char = 4;\n min_cov_init = 5;\n min_overlap = 20;\n max_threads = 4;\n initial_trim = 20;\n max_missed = 5;\n mismatch_threshold = 0.1;\n test_run = false;\n int c;\n Process process;\n \n \/\/ prevent output to stderr if erroneous option is found\n opterr = 0;\n\n \/\/ get all options that have been provided on the command line\n while (( c = getopt (argc, argv, \"hr:c:o:s:l:x:m:i:p:t:a:b:d:e:f:g:z\" )) != -1 ) {\n switch( c ) {\n case 'h':\n print_usage( argv[0] );\n exit(0);\n break;\n \/\/ max_sort_char option\n case 'm':\n max_sort_char = atoi(optarg);\n break;\n \/\/ contig_sub_len option\n case 's':\n contig_sub_len = atoi(optarg);\n break;\n \/\/ extend_len option\n case 'x':\n extend_len = atoi(optarg);\n break;\n \/\/ max_sort_char option\n case 'l':\n max_search_loops = atoi(optarg);\n break;\n \/\/ min_cov_init option\n case 'i':\n min_cov_init = atoi(optarg);\n break;\n \/\/ min_overlap option\n case 'p':\n min_overlap = atoi(optarg);\n break;\n \/\/ max_threads option\n case 't':\n max_threads = atoi(optarg);\n break;\n \/\/ initial_trim option\n case 'd':\n initial_trim = atoi(optarg);\n break;\n \/\/ max_missed option\n case 'e':\n max_missed = atoi(optarg);\n break;\n \/\/ mismatch_threshold option\n case 'g':\n mismatch_threshold = atof(optarg);\n break;\n \/\/ outputfile option\n case 'o':\n cout << \"output file: \" << optarg << endl;\n process.outfile = optarg;\n print_time();\n break;\n \/\/ readfile option\n case 'r':\n optind--;\n \/\/ loop through each file\n while ( optind < argc && argv[optind][0] != '-' ) { \n process.readsfiles.append( \",\" );\n process.readsfiles.append( argv[optind] );\n optind++;\n } \n break;\n \/\/ contig file option\n case 'c':\n optind--;\n \/\/ loop through each file\n while ( optind < argc && argv[optind][0] != '-' ) { \n process.contigsfiles.append( \",\" );\n process.contigsfiles.append( argv[optind] );\n optind++;\n } \n break;\n \/\/ test_run option\n case 'z':\n test_run = true;\n break;\n case '?':\n if ( optopt == 'r' ){\n fprintf( stderr, \"%s: Error: Option -r requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( optopt == 'o' ){\n fprintf( stderr, \"%s: Error: Option -o requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( optopt == 'c' ){\n fprintf( stderr, \"%s: Error: Option -c requires an argument. \", argv[0] );\n print_usage( argv[0] );\n }\n else if ( isprint( optopt )){\n fprintf( stderr, \"%s: Error: Unknown option -%c. \\n\", argv[0], optopt );\n print_usage( argv[0] );\n }\n else{\n fprintf( stderr, \"%s: Error: Unknown option character %x.\\n\", argv[0], optopt );\n print_usage( argv[0] );\n }\n return 1;\n default:\n abort();\n }\n }\n \n while ( optind < argc ) {\n cout << argv[optind] << endl;\n optind++;\n }\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ End Options \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Test Thread Queue \/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n \/\/ start run\n process.start_run();\n\n int length[process.contigs.size()];\n for( int i=0; i"} {"text":"\/**\n * Application Context of Session Manager\n *\n * Copyright 2013 Thincast Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"ApplicationContext.h\"\n\n#include \n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tApplicationContext::ApplicationContext()\n\t\t{\n\t\t\twLogLayout* layout;\n\t\t\twLogAppender* appender;\n\n\t\t\tinitPaths();\n\t\t\tconfigureExecutableSearchPath();\n\n\t\t\tWLog_Init();\n\n\t\t\tmWLogRoot = WLog_GetRoot();\n\n\t\t\tWLog_SetLogAppenderType(mWLogRoot, WLOG_APPENDER_CONSOLE);\n\n\t\t\tappender = WLog_GetLogAppender(mWLogRoot);\n\t\t\tWLog_ConsoleAppender_SetOutputStream(mWLogRoot, (wLogConsoleAppender*) appender, WLOG_CONSOLE_STDERR);\n\n\t\t\tlayout = WLog_GetLogLayout(mWLogRoot);\n\t\t\tWLog_Layout_SetPrefixFormat(mWLogRoot, layout, \"[%lv:%mn] [%fl|%fn|%ln] - \");\n\n\t\t\tWLog_OpenAppender(mWLogRoot);\n\t\t\tWLog_SetLogLevel(mWLogRoot, WLOG_TRACE);\n\n\t\t\tsetupTestingPropValues();\n\t\t}\n\n\t\tApplicationContext::~ApplicationContext()\n\t\t{\n\t\t\tWLog_CloseAppender(mWLogRoot);\n\t\t\tWLog_Uninit();\n\t\t}\n\n\t\tstd::string ApplicationContext::getHomePath()\n\t\t{\n\n\t\t\tif (mHomePath.size() == 0)\n\t\t\t{\n\t\t\t\tchar* p;\n\t\t\t\tint length;\n\t\t\t\tchar separator;\n\t\t\t\tchar moduleFileName[4096];\n\n\t\t\t\tseparator = PathGetSeparatorA(PATH_STYLE_NATIVE);\n\t\t\t\tGetModuleFileNameA(NULL, moduleFileName, sizeof(moduleFileName));\n\n\t\t\t\tp = strrchr(moduleFileName, separator);\n\t\t\t\t*p = '\\0';\n\t\t\t\tp = strrchr(moduleFileName, separator);\n\t\t\t\t*p = '\\0';\n\n\t\t\t\tmHomePath.assign(moduleFileName);\n\t\t\t}\n\t\t\treturn mHomePath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getLibraryPath()\n\t\t{\n\t\t\tif (mLibraryPath.size() == 0)\n\t\t\t{\n\t\t\t\tmLibraryPath = getHomePath();\n\t\t\t\tmLibraryPath += \"\/\";\n\t\t\t\tmLibraryPath += FREERDS_INSTALL_LIBDIR;\n\t\t\t}\n\t\t\treturn mLibraryPath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getExecutablePath()\n\t\t{\n\t\t\tif (mExecutablePath.size() == 0)\n\t\t\t{\n\t\t\t\tmExecutablePath = getHomePath();\n\t\t\t\tmExecutablePath += \"\/\";\n\t\t\t\tmExecutablePath += FREERDS_INSTALL_BINDIR;\n\t\t\t}\n\t\t\treturn mExecutablePath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getShareDataPath()\n\t\t{\n\t\t\tif (mShareDataPath.size() == 0)\n\t\t\t{\n\t\t\t\tmShareDataPath = getHomePath();\n\t\t\t\tmShareDataPath += \"\/\";\n\t\t\t\tmShareDataPath += FREERDS_INSTALL_DATAROOTDIR;\n\t\t\t\tmShareDataPath += \"\/\";\n\t\t\t\tmShareDataPath += \"freerds\";\n\t\t\t}\n\t\t\treturn mShareDataPath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getSystemConfigPath()\n\t\t{\n\t\t\tif (mSystemConfigPath.size() == 0)\n\t\t\t{\n\n\t\t\t\tmSystemConfigPath = getHomePath();\n\t\t\t\tmSystemConfigPath += \"\/\";\n\t\t\t\tmSystemConfigPath += FREERDS_INSTALL_SYSCONFDIR;\n\t\t\t\tmSystemConfigPath += \"\/\";\n\t\t\t\tmSystemConfigPath += \"freerds\";\n\t\t\t}\n\t\t\treturn mSystemConfigPath;\n\t\t}\n\n\t\tvoid ApplicationContext::initPaths()\n\t\t{\n\t\t\tgetHomePath();\n\t\t\tgetLibraryPath();\n\t\t\tgetExecutablePath();\n\t\t\tgetShareDataPath();\n\t\t\tgetSystemConfigPath();\n\t\t}\n\n\n\t\tvoid ApplicationContext::configureExecutableSearchPath()\n\t\t{\n\t\t\tint index;\n\t\t\tDWORD nSize;\n\n\t\t\tnSize = GetEnvironmentVariableA(\"PATH\", NULL, 0);\n\n\t\t\tif (nSize)\n\t\t\t{\n\t\t\t\tstd::string pathExtra = \"\";\n\t\t\t\tbool executablePathPresent = false;\n\t\t\t\tbool systemConfigPathPresent = false;\n\n\t\t\t\tchar* lpBuffer = (LPSTR) malloc(nSize);\n\t\t\t\tnSize = GetEnvironmentVariableA(\"PATH\", lpBuffer, nSize);\n\n\t\t\t\tstd::string pathEnv(lpBuffer);\n\t\t\t\tstd::vector pathList = split(pathEnv, \":\");\n\n\t\t\t\tfor (index = 0; index < pathList.size(); index++)\n\t\t\t\t{\n\t\t\t\t\tif (strcmp(mExecutablePath.c_str(), pathList[index].c_str()) == 0)\n\t\t\t\t\t\texecutablePathPresent = true;\n\t\t\t\t\telse if (strcmp(mSystemConfigPath.c_str(), pathList[index].c_str()) == 0)\n\t\t\t\t\t\tsystemConfigPathPresent = true;\n\t\t\t\t}\n\n\t\t\t\tif (!executablePathPresent)\n\t\t\t\t{\n\t\t\t\t\tpathExtra += mExecutablePath;\n\t\t\t\t\tpathExtra += \":\";\n\t\t\t\t}\n\n\t\t\t\tif (!systemConfigPathPresent)\n\t\t\t\t{\n\t\t\t\t\tpathExtra += mSystemConfigPath;\n\t\t\t\t\tpathExtra += \":\";\n\t\t\t\t}\n\n\t\t\t\tif (pathExtra.length() > 0)\n\t\t\t\t{\n\t\t\t\t\tpathEnv = pathExtra + pathEnv;\n\t\t\t\t\tSetEnvironmentVariableA(\"PATH\", pathEnv.c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsessionNS::SessionStore* ApplicationContext::getSessionStore()\n\t\t{\n\t\t\treturn &mSessionStore;\n\t\t}\n\n\t\tsessionNS::ConnectionStore* ApplicationContext::getConnectionStore()\n\t\t{\n\t\t\treturn &mConnectionStore;\n\t\t}\n\n\t\tconfigNS::PropertyManager* ApplicationContext::getPropertyManager()\n\t\t{\n\t\t\treturn &mPropertyManager;\n\t\t}\n\n\t\tint ApplicationContext::startRPCEngine()\n\t\t{\n#ifdef WITH_FDSAPI\n\t\t\tmFDSApiServer.startFDSApi();\n#endif\n\t\t\treturn mRpcEngine.startEngine();\n\t\t}\n\n\t\tint ApplicationContext::stopRPCEngine()\n\t\t{\n#ifdef WITH_FDSAPI\n\t\t\tmFDSApiServer.stopFDSApi();\n#endif\n\t\t\treturn mRpcEngine.stopEngine();\n\t\t}\n\n\t\tSignalingQueue * ApplicationContext::getRpcOutgoingQueue()\n\t\t{\n\t\t\treturn &mRpcOutgoingCalls;\n\t\t}\n\n\t\tint ApplicationContext::loadModulesFromPath(std::string path)\n\t\t{\n\t\t\tLPCSTR pszExt;\n\t\t\tchar pattern[256];\n\n\t\t\tpszExt = PathGetSharedLibraryExtensionA(0);\n\t\t\tsprintf_s(pattern, 256, \"*freerds-module-*.%s\", pszExt);\n\n\t\t\treturn mModuleManager.loadModulesFromPathAndEnv(path, pattern);\n\t\t}\n\n\t\tmoduleNS::ModuleManager* ApplicationContext::getModuleManager()\n\t\t{\n\t\t\treturn &mModuleManager;\n\t\t}\n\n\t\tvoid ApplicationContext::setupTestingPropValues()\n\t\t{\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module\",\"xsession\");\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"auth.module\",\"PAM\");\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"auth.greeter\",\"greeter\");\n\t\t\tmPropertyManager.setPropertyBool(Global, 0, \"session.reconnect\",true);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"session.timeout\",1);\n\n\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.xsession.modulename\",\"X11\");\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.maxXRes\",1920);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.maxYRes\",1200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.minXRes\",320);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.minYRes\",200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.xres\",1024);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.yres\",768);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.colordepth\",24);\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.xsession.startwm\",\"startwm.sh\");\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.greeter.modulename\",\"Qt\");\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.maxXRes\",1920);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.maxYRes\",1200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.minXRes\",320);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.minYRes\",200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.xres\",1024);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.yres\",768);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.colordepth\",24);\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.greeter.cmd\",\"nice_greeter\");\n\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.xres\",800,\"demo1\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.yres\",600,\"demo1\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.xres\",800,\"demo2\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.yres\",600,\"demo2\");\n\t\t\tmPropertyManager.setPropertyBool(User, 0, \"session.reconnect\",false,\"demo1\");\n\t\t\tmPropertyManager.setPropertyString(User, 0, \"module\",\"xsession\",\"demo2\");\n\n\t\t}\n\n\t\tvoid ApplicationContext::startTaskExecutor() {\n\t\t\tmTaskExecutor.start();\n\t\t}\n\n\t\tvoid ApplicationContext::stopTaskExecutor() {\n\t\t\tmTaskExecutor.stop();\n\t\t}\n\n\t\tvoid ApplicationContext::startSessionTimoutMonitor(){\n\t\t\tsessionNS::TaskSessionTimeoutPtr task(new sessionNS::TaskSessionTimeout());\n\t\t\taddTask(task);\n\t\t}\n\n\n\t\tbool ApplicationContext::addTask(taskNS::TaskPtr task) {\n\t\t\treturn mTaskExecutor.addTask(task);\n\t\t}\n\n\t\tvoid ApplicationContext::rpcDisconnected() {\n\t\t\t\/\/ remove all connections\n\t\t\tgetConnectionStore()->reset();\n\t\t\t\/\/ iterate over the session and disconnect them if they are auth sessions.\n\t\t\tstd::list allSessions = getSessionStore()->getAllSessions();\n\n\t\t\tstd::list::iterator iterator;\n\t\t\tfor (iterator = allSessions.begin(); iterator != allSessions.end(); ++iterator) {\n\t\t\t\tsessionNS::SessionPtr currentSession = (*iterator);\n\t\t\t\tif (currentSession->isAuthSession()) {\n\t\t\t\t\tcurrentSession->stopModule();\n\t\t\t\t\tgetSessionStore()->removeSession(currentSession->getSessionID());\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ disconnect the session\n\t\t\t\t\tcurrentSession->setConnectState(WTSDisconnected);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n\nChanged default greeter from Qt\/nice_greeter to X11\/simple_greeter\/**\n * Application Context of Session Manager\n *\n * Copyright 2013 Thincast Technologies GmbH\n * Copyright 2013 DI (FH) Martin Haimberger \n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"ApplicationContext.h\"\n\n#include \n\nnamespace freerds\n{\n\tnamespace sessionmanager\n\t{\n\t\tApplicationContext::ApplicationContext()\n\t\t{\n\t\t\twLogLayout* layout;\n\t\t\twLogAppender* appender;\n\n\t\t\tinitPaths();\n\t\t\tconfigureExecutableSearchPath();\n\n\t\t\tWLog_Init();\n\n\t\t\tmWLogRoot = WLog_GetRoot();\n\n\t\t\tWLog_SetLogAppenderType(mWLogRoot, WLOG_APPENDER_CONSOLE);\n\n\t\t\tappender = WLog_GetLogAppender(mWLogRoot);\n\t\t\tWLog_ConsoleAppender_SetOutputStream(mWLogRoot, (wLogConsoleAppender*) appender, WLOG_CONSOLE_STDERR);\n\n\t\t\tlayout = WLog_GetLogLayout(mWLogRoot);\n\t\t\tWLog_Layout_SetPrefixFormat(mWLogRoot, layout, \"[%lv:%mn] [%fl|%fn|%ln] - \");\n\n\t\t\tWLog_OpenAppender(mWLogRoot);\n\t\t\tWLog_SetLogLevel(mWLogRoot, WLOG_TRACE);\n\n\t\t\tsetupTestingPropValues();\n\t\t}\n\n\t\tApplicationContext::~ApplicationContext()\n\t\t{\n\t\t\tWLog_CloseAppender(mWLogRoot);\n\t\t\tWLog_Uninit();\n\t\t}\n\n\t\tstd::string ApplicationContext::getHomePath()\n\t\t{\n\n\t\t\tif (mHomePath.size() == 0)\n\t\t\t{\n\t\t\t\tchar* p;\n\t\t\t\tint length;\n\t\t\t\tchar separator;\n\t\t\t\tchar moduleFileName[4096];\n\n\t\t\t\tseparator = PathGetSeparatorA(PATH_STYLE_NATIVE);\n\t\t\t\tGetModuleFileNameA(NULL, moduleFileName, sizeof(moduleFileName));\n\n\t\t\t\tp = strrchr(moduleFileName, separator);\n\t\t\t\t*p = '\\0';\n\t\t\t\tp = strrchr(moduleFileName, separator);\n\t\t\t\t*p = '\\0';\n\n\t\t\t\tmHomePath.assign(moduleFileName);\n\t\t\t}\n\t\t\treturn mHomePath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getLibraryPath()\n\t\t{\n\t\t\tif (mLibraryPath.size() == 0)\n\t\t\t{\n\t\t\t\tmLibraryPath = getHomePath();\n\t\t\t\tmLibraryPath += \"\/\";\n\t\t\t\tmLibraryPath += FREERDS_INSTALL_LIBDIR;\n\t\t\t}\n\t\t\treturn mLibraryPath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getExecutablePath()\n\t\t{\n\t\t\tif (mExecutablePath.size() == 0)\n\t\t\t{\n\t\t\t\tmExecutablePath = getHomePath();\n\t\t\t\tmExecutablePath += \"\/\";\n\t\t\t\tmExecutablePath += FREERDS_INSTALL_BINDIR;\n\t\t\t}\n\t\t\treturn mExecutablePath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getShareDataPath()\n\t\t{\n\t\t\tif (mShareDataPath.size() == 0)\n\t\t\t{\n\t\t\t\tmShareDataPath = getHomePath();\n\t\t\t\tmShareDataPath += \"\/\";\n\t\t\t\tmShareDataPath += FREERDS_INSTALL_DATAROOTDIR;\n\t\t\t\tmShareDataPath += \"\/\";\n\t\t\t\tmShareDataPath += \"freerds\";\n\t\t\t}\n\t\t\treturn mShareDataPath;\n\t\t}\n\n\t\tstd::string ApplicationContext::getSystemConfigPath()\n\t\t{\n\t\t\tif (mSystemConfigPath.size() == 0)\n\t\t\t{\n\n\t\t\t\tmSystemConfigPath = getHomePath();\n\t\t\t\tmSystemConfigPath += \"\/\";\n\t\t\t\tmSystemConfigPath += FREERDS_INSTALL_SYSCONFDIR;\n\t\t\t\tmSystemConfigPath += \"\/\";\n\t\t\t\tmSystemConfigPath += \"freerds\";\n\t\t\t}\n\t\t\treturn mSystemConfigPath;\n\t\t}\n\n\t\tvoid ApplicationContext::initPaths()\n\t\t{\n\t\t\tgetHomePath();\n\t\t\tgetLibraryPath();\n\t\t\tgetExecutablePath();\n\t\t\tgetShareDataPath();\n\t\t\tgetSystemConfigPath();\n\t\t}\n\n\n\t\tvoid ApplicationContext::configureExecutableSearchPath()\n\t\t{\n\t\t\tint index;\n\t\t\tDWORD nSize;\n\n\t\t\tnSize = GetEnvironmentVariableA(\"PATH\", NULL, 0);\n\n\t\t\tif (nSize)\n\t\t\t{\n\t\t\t\tstd::string pathExtra = \"\";\n\t\t\t\tbool executablePathPresent = false;\n\t\t\t\tbool systemConfigPathPresent = false;\n\n\t\t\t\tchar* lpBuffer = (LPSTR) malloc(nSize);\n\t\t\t\tnSize = GetEnvironmentVariableA(\"PATH\", lpBuffer, nSize);\n\n\t\t\t\tstd::string pathEnv(lpBuffer);\n\t\t\t\tstd::vector pathList = split(pathEnv, \":\");\n\n\t\t\t\tfor (index = 0; index < pathList.size(); index++)\n\t\t\t\t{\n\t\t\t\t\tif (strcmp(mExecutablePath.c_str(), pathList[index].c_str()) == 0)\n\t\t\t\t\t\texecutablePathPresent = true;\n\t\t\t\t\telse if (strcmp(mSystemConfigPath.c_str(), pathList[index].c_str()) == 0)\n\t\t\t\t\t\tsystemConfigPathPresent = true;\n\t\t\t\t}\n\n\t\t\t\tif (!executablePathPresent)\n\t\t\t\t{\n\t\t\t\t\tpathExtra += mExecutablePath;\n\t\t\t\t\tpathExtra += \":\";\n\t\t\t\t}\n\n\t\t\t\tif (!systemConfigPathPresent)\n\t\t\t\t{\n\t\t\t\t\tpathExtra += mSystemConfigPath;\n\t\t\t\t\tpathExtra += \":\";\n\t\t\t\t}\n\n\t\t\t\tif (pathExtra.length() > 0)\n\t\t\t\t{\n\t\t\t\t\tpathEnv = pathExtra + pathEnv;\n\t\t\t\t\tSetEnvironmentVariableA(\"PATH\", pathEnv.c_str());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tsessionNS::SessionStore* ApplicationContext::getSessionStore()\n\t\t{\n\t\t\treturn &mSessionStore;\n\t\t}\n\n\t\tsessionNS::ConnectionStore* ApplicationContext::getConnectionStore()\n\t\t{\n\t\t\treturn &mConnectionStore;\n\t\t}\n\n\t\tconfigNS::PropertyManager* ApplicationContext::getPropertyManager()\n\t\t{\n\t\t\treturn &mPropertyManager;\n\t\t}\n\n\t\tint ApplicationContext::startRPCEngine()\n\t\t{\n#ifdef WITH_FDSAPI\n\t\t\tmFDSApiServer.startFDSApi();\n#endif\n\t\t\treturn mRpcEngine.startEngine();\n\t\t}\n\n\t\tint ApplicationContext::stopRPCEngine()\n\t\t{\n#ifdef WITH_FDSAPI\n\t\t\tmFDSApiServer.stopFDSApi();\n#endif\n\t\t\treturn mRpcEngine.stopEngine();\n\t\t}\n\n\t\tSignalingQueue * ApplicationContext::getRpcOutgoingQueue()\n\t\t{\n\t\t\treturn &mRpcOutgoingCalls;\n\t\t}\n\n\t\tint ApplicationContext::loadModulesFromPath(std::string path)\n\t\t{\n\t\t\tLPCSTR pszExt;\n\t\t\tchar pattern[256];\n\n\t\t\tpszExt = PathGetSharedLibraryExtensionA(0);\n\t\t\tsprintf_s(pattern, 256, \"*freerds-module-*.%s\", pszExt);\n\n\t\t\treturn mModuleManager.loadModulesFromPathAndEnv(path, pattern);\n\t\t}\n\n\t\tmoduleNS::ModuleManager* ApplicationContext::getModuleManager()\n\t\t{\n\t\t\treturn &mModuleManager;\n\t\t}\n\n\t\tvoid ApplicationContext::setupTestingPropValues()\n\t\t{\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module\",\"xsession\");\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"auth.module\",\"PAM\");\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"auth.greeter\",\"greeter\");\n\t\t\tmPropertyManager.setPropertyBool(Global, 0, \"session.reconnect\",true);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"session.timeout\",1);\n\n\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.xsession.modulename\",\"X11\");\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.maxXRes\",1920);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.maxYRes\",1200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.minXRes\",320);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.minYRes\",200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.xres\",1024);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.yres\",768);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.xsession.colordepth\",24);\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.xsession.startwm\",\"startwm.sh\");\n\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.greeter.modulename\",\"X11\");\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.maxXRes\",1920);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.maxYRes\",1200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.minXRes\",320);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.minYRes\",200);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.xres\",1024);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.yres\",768);\n\t\t\tmPropertyManager.setPropertyNumber(Global, 0, \"module.greeter.colordepth\",24);\n\t\t\tmPropertyManager.setPropertyString(Global, 0, \"module.greeter.cmd\",\"simple_greeter\");\n\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.xres\",800,\"demo1\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.yres\",600,\"demo1\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.xres\",800,\"demo2\");\n\t\t\tmPropertyManager.setPropertyNumber(User, 0, \"module.xsession.yres\",600,\"demo2\");\n\t\t\tmPropertyManager.setPropertyBool(User, 0, \"session.reconnect\",false,\"demo1\");\n\t\t\tmPropertyManager.setPropertyString(User, 0, \"module\",\"xsession\",\"demo2\");\n\n\t\t}\n\n\t\tvoid ApplicationContext::startTaskExecutor() {\n\t\t\tmTaskExecutor.start();\n\t\t}\n\n\t\tvoid ApplicationContext::stopTaskExecutor() {\n\t\t\tmTaskExecutor.stop();\n\t\t}\n\n\t\tvoid ApplicationContext::startSessionTimoutMonitor(){\n\t\t\tsessionNS::TaskSessionTimeoutPtr task(new sessionNS::TaskSessionTimeout());\n\t\t\taddTask(task);\n\t\t}\n\n\n\t\tbool ApplicationContext::addTask(taskNS::TaskPtr task) {\n\t\t\treturn mTaskExecutor.addTask(task);\n\t\t}\n\n\t\tvoid ApplicationContext::rpcDisconnected() {\n\t\t\t\/\/ remove all connections\n\t\t\tgetConnectionStore()->reset();\n\t\t\t\/\/ iterate over the session and disconnect them if they are auth sessions.\n\t\t\tstd::list allSessions = getSessionStore()->getAllSessions();\n\n\t\t\tstd::list::iterator iterator;\n\t\t\tfor (iterator = allSessions.begin(); iterator != allSessions.end(); ++iterator) {\n\t\t\t\tsessionNS::SessionPtr currentSession = (*iterator);\n\t\t\t\tif (currentSession->isAuthSession()) {\n\t\t\t\t\tcurrentSession->stopModule();\n\t\t\t\t\tgetSessionStore()->removeSession(currentSession->getSessionID());\n\t\t\t\t} else {\n\t\t\t\t\t\/\/ disconnect the session\n\t\t\t\t\tcurrentSession->setConnectState(WTSDisconnected);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\n\t}\n}\n\n<|endoftext|>"} {"text":"#ifdef STAN_OPENCL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing stan::math::matrix_cl;\n\nTEST(KernelGenerator, operation_cl_errors) {\n EXPECT_THROW(matrix_cl a = stan::math::as_operation_cl(3.5),\n std::invalid_argument);\n EXPECT_THROW(stan::math::as_operation_cl(3.5).eval(), std::invalid_argument);\n}\n\nTEST(KernelGenerator, kernel_caching) {\n MatrixXd m1(3, 3);\n m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n MatrixXd m2(3, 3);\n m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n matrix_cl m1_cl(m1);\n matrix_cl m2_cl(m2);\n auto tmp = m1_cl + 0.1234 * m2_cl;\n\n using cache = stan::math::internal::multi_result_kernel_internal<\n 0, stan::math::load_&>&&>::inner;\n using unused_cache = stan::math::internal::multi_result_kernel_internal<\n 0, stan::math::load_&>&&>::inner;\n size_t cache_size = cache::kernel_cache_.size();\n size_t unused_cache_size = unused_cache::kernel_cache_.size();\n std::vector uid = {0, 1, 2};\n\n EXPECT_EQ(cache::kernel_cache_.count(uid), 0);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size);\n matrix_cl res_cl = tmp;\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n cl_kernel cached_kernel = cache::kernel_cache_.at(uid)();\n EXPECT_NE(cached_kernel, nullptr);\n\n auto tmp2 = m1_cl + 0.1234 * m2_cl;\n matrix_cl res2_cl = tmp2;\n EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n\n matrix_cl res3_cl = res_cl + 0.1234 * res2_cl;\n EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n\n EXPECT_EQ(unused_cache::kernel_cache_.size(), unused_cache_size);\n}\n\nTEST(MathMatrixCL, events_write_after_write) {\n using stan::math::matrix_cl;\n matrix_cl zero_cl = stan::math::constant(0, 3, 3);\n zero_cl.wait_for_read_write_events();\n\n for (int j = 0; j < 3000; j++) {\n matrix_cl m_cl(3, 3);\n\n for (int i = 0; i < 4; i++) {\n m_cl = zero_cl + i;\n }\n\n Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);\n Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 3);\n\n EXPECT_MATRIX_NEAR(res, correct, 1e-13);\n }\n}\n\nTEST(MathMatrixCL, events_read_after_write_and_write_after_read) {\n using stan::math::matrix_cl;\n int iters = 3000;\n\n matrix_cl m1_cl = stan::math::constant(0, 3, 3);\n matrix_cl m2_cl(3, 3);\n\n for (int j = 0; j < iters; j++) {\n m2_cl = m1_cl + 1;\n m1_cl = m2_cl + 1;\n }\n Eigen::MatrixXd res = stan::math::from_matrix_cl(m1_cl);\n Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 2 * iters);\n\n EXPECT_MATRIX_NEAR(res, correct, 1e-13);\n}\n\nTEST(MathMatrixCL, same_operations_different_inputs) {\n MatrixXd m1(3, 3);\n m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n MatrixXd m2(3, 3);\n m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n matrix_cl m1_cl(m1);\n matrix_cl m2_cl(m2);\n\n auto m1_op = stan::math::as_operation_cl(m1_cl);\n auto m2_op = stan::math::as_operation_cl(m2_cl);\n\n matrix_cl res1_cl = m1_op + m1_op;\n matrix_cl res2_cl = m2_op + m1_op;\n\n EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res1_cl), m1 + m1);\n EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res2_cl), m2 + m1);\n}\n\n#endif\nfix cache test#ifdef STAN_OPENCL\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing Eigen::MatrixXd;\nusing Eigen::MatrixXi;\nusing stan::math::matrix_cl;\n\nTEST(KernelGenerator, operation_cl_errors) {\n EXPECT_THROW(matrix_cl a = stan::math::as_operation_cl(3.5),\n std::invalid_argument);\n EXPECT_THROW(stan::math::as_operation_cl(3.5).eval(), std::invalid_argument);\n}\n\nTEST(KernelGenerator, kernel_caching) {\n MatrixXd m1(3, 3);\n m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n MatrixXd m2(3, 3);\n m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n matrix_cl m1_cl(m1);\n matrix_cl m2_cl(m2);\n auto tmp = m1_cl + 0.1234 * m2_cl;\n\n using cache = stan::math::internal::multi_result_kernel_internal<\n 0, stan::math::load_&>>::inner;\n using unused_cache = stan::math::internal::multi_result_kernel_internal<\n 0, stan::math::load_&>>::inner;\n size_t cache_size = cache::kernel_cache_.size();\n size_t unused_cache_size = unused_cache::kernel_cache_.size();\n std::vector uid = {0, 1, 2};\n\n EXPECT_EQ(cache::kernel_cache_.count(uid), 0);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size);\n matrix_cl res_cl = tmp;\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n cl_kernel cached_kernel = cache::kernel_cache_.at(uid)();\n EXPECT_NE(cached_kernel, nullptr);\n\n auto tmp2 = m1_cl + 0.1234 * m2_cl;\n matrix_cl res2_cl = tmp2;\n EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n\n matrix_cl res3_cl = res_cl + 0.1234 * res2_cl;\n EXPECT_EQ(cache::kernel_cache_.at(uid)(), cached_kernel);\n EXPECT_EQ(cache::kernel_cache_.size(), cache_size + 1);\n\n EXPECT_EQ(unused_cache::kernel_cache_.size(), unused_cache_size);\n}\n\nTEST(MathMatrixCL, events_write_after_write) {\n using stan::math::matrix_cl;\n matrix_cl zero_cl = stan::math::constant(0, 3, 3);\n zero_cl.wait_for_read_write_events();\n\n for (int j = 0; j < 3000; j++) {\n matrix_cl m_cl(3, 3);\n\n for (int i = 0; i < 4; i++) {\n m_cl = zero_cl + i;\n }\n\n Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);\n Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 3);\n\n EXPECT_MATRIX_NEAR(res, correct, 1e-13);\n }\n}\n\nTEST(MathMatrixCL, events_read_after_write_and_write_after_read) {\n using stan::math::matrix_cl;\n int iters = 3000;\n\n matrix_cl m1_cl = stan::math::constant(0, 3, 3);\n matrix_cl m2_cl(3, 3);\n\n for (int j = 0; j < iters; j++) {\n m2_cl = m1_cl + 1;\n m1_cl = m2_cl + 1;\n }\n Eigen::MatrixXd res = stan::math::from_matrix_cl(m1_cl);\n Eigen::MatrixXd correct = Eigen::MatrixXd::Constant(3, 3, 2 * iters);\n\n EXPECT_MATRIX_NEAR(res, correct, 1e-13);\n}\n\nTEST(MathMatrixCL, same_operations_different_inputs) {\n MatrixXd m1(3, 3);\n m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9;\n MatrixXd m2(3, 3);\n m2 << 10, 100, 1000, 0, -10, -12, 2, 4, 8;\n\n matrix_cl m1_cl(m1);\n matrix_cl m2_cl(m2);\n\n auto m1_op = stan::math::as_operation_cl(m1_cl);\n auto m2_op = stan::math::as_operation_cl(m2_cl);\n\n matrix_cl res1_cl = m1_op + m1_op;\n matrix_cl res2_cl = m2_op + m1_op;\n\n EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res1_cl), m1 + m1);\n EXPECT_MATRIX_EQ(stan::math::from_matrix_cl(res2_cl), m2 + m1);\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2010 Stephen F. Booth \n * All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * - Neither the name of Stephen F. Booth nor the names of its \n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n\n#include \"AudioEngineDefines.h\"\n#include \"OggVorbisMetadata.h\"\n#include \"CreateDisplayNameForURL.h\"\n\n\n#pragma mark Static Methods\n\n\nCFArrayRef OggVorbisMetadata::CreateSupportedFileExtensions()\n{\n\tCFStringRef supportedExtensions [] = { CFSTR(\"ogg\"), CFSTR(\"oga\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedExtensions), 2, &kCFTypeArrayCallBacks);\n}\n\nCFArrayRef OggVorbisMetadata::CreateSupportedMIMETypes()\n{\n\tCFStringRef supportedMIMETypes [] = { CFSTR(\"audio\/ogg\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);\n}\n\nbool OggVorbisMetadata::HandlesFilesWithExtension(CFStringRef extension)\n{\n\tassert(NULL != extension);\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"ogg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\telse if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"oga\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\n\treturn false;\n}\n\nbool OggVorbisMetadata::HandlesMIMEType(CFStringRef mimeType)\n{\n\tassert(NULL != mimeType);\t\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR(\"audio\/ogg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\t\n\treturn false;\n}\n\n\n#pragma mark Creation and Destruction\n\n\nOggVorbisMetadata::OggVorbisMetadata(CFURLRef url)\n\t: AudioMetadata(url)\n{}\n\nOggVorbisMetadata::~OggVorbisMetadata()\n{}\n\n\n#pragma mark Functionality\n\n\nbool OggVorbisMetadata::ReadMetadata(CFErrorRef *error)\n{\n\t\/\/ Start from scratch\n\tCFDictionaryRemoveAllValues(mMetadata);\n\t\n\tUInt8 buf [PATH_MAX];\n\tif(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\t\n\tTagLib::Ogg::Vorbis::File file(reinterpret_cast(buf), false);\n\t\n\tif(!file.isValid()) {\n\t\tif(NULL != error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg Vorbis file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not an Ogg Vorbis file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\tif(file.tag()) {\n\t\tCFMutableDictionaryRef additionalMetadata = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\n\t\t\/\/ A map \n\t\tTagLib::Ogg::FieldListMap fieldList = file.tag()->fieldListMap();\n\t\t\n\t\tfor(TagLib::Ogg::FieldListMap::ConstIterator it = fieldList.begin(); it != fieldList.end(); ++it) {\n\t\t\tCFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tit->first.toCString(true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tkCFStringEncodingUTF8);\n\t\t\t\n\t\t\t\/\/ Vorbis allows multiple comments with the same key, but this isn't supported by AudioMetadata\n\t\t\tCFStringRef value = CFStringCreateWithCString(kCFAllocatorDefault,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t it->second.front().toCString(true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t kCFStringEncodingUTF8);\n\t\t\t\n\t\t\tif(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ALBUM\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetAlbumTitle(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ARTIST\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetArtist(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ALBUMARTIST\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetAlbumArtist(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"COMPOSER\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetComposer(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"GENRE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetGenre(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DATE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetReleaseDate(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DESCRIPTION\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetComment(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TITLE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetTitle(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TRACKNUMBER\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetTrackNumber(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TRACKTOTAL\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetTrackTotal(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"COMPILATION\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetCompilation(CFStringGetIntValue(value) ? kCFBooleanTrue : kCFBooleanFalse);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DISCNUMBER\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetDiscNumber(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DISCTOTAL\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetDiscTotal(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ISRC\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetISRC(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"MCN\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetMCN(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_REFERENCE_LOUDNESS\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainReferenceLoudness(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_TRACK_GAIN\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainTrackGain(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_TRACK_PEAK\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainTrackPeak(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_ALBUM_GAIN\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainAlbumGain(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_ALBUM_PEAK\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainAlbumPeak(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\t\/\/ Put all unknown tags into the additional metadata\n\t\t\telse\n\t\t\t\tCFDictionarySetValue(additionalMetadata, key, value);\n\t\t\t\n\t\t\tCFRelease(key), key = NULL;\n\t\t\tCFRelease(value), value = NULL;\n\t\t}\n\n\t\tif(CFDictionaryGetCount(additionalMetadata))\n\t\t\tSetAdditionalMetadata(additionalMetadata);\n\t\t\n\t\tCFRelease(additionalMetadata), additionalMetadata = NULL;\n\t\t\n\t}\n\n\treturn true;\n}\n\nbool OggVorbisMetadata::WriteMetadata(CFErrorRef *error)\n{\n\tUInt8 buf [PATH_MAX];\n\tif(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\n\tTagLib::Ogg::Vorbis::File file(reinterpret_cast(buf), false);\n\t\n\tif(!file.isValid()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg Vorbis file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not an Ogg Vorbis file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\n\tif(!file.save()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg Vorbis file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Unable to write metadata\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\t\n\treturn true;\n}\nRewritten to handle Ogg Vorbis and Ogg FLAC files\/*\n * Copyright (C) 2010 Stephen F. Booth \n * All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * - Neither the name of Stephen F. Booth nor the names of its \n * contributors may be used to endorse or promote products derived\n * from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \n#include \n#include \n\n#include \"AudioEngineDefines.h\"\n#include \"OggVorbisMetadata.h\"\n#include \"CreateDisplayNameForURL.h\"\n\n\n#pragma mark Static Methods\n\n\nCFArrayRef OggVorbisMetadata::CreateSupportedFileExtensions()\n{\n\tCFStringRef supportedExtensions [] = { CFSTR(\"ogg\"), CFSTR(\"oga\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedExtensions), 2, &kCFTypeArrayCallBacks);\n}\n\nCFArrayRef OggVorbisMetadata::CreateSupportedMIMETypes()\n{\n\tCFStringRef supportedMIMETypes [] = { CFSTR(\"audio\/ogg\") };\n\treturn CFArrayCreate(kCFAllocatorDefault, reinterpret_cast(supportedMIMETypes), 1, &kCFTypeArrayCallBacks);\n}\n\nbool OggVorbisMetadata::HandlesFilesWithExtension(CFStringRef extension)\n{\n\tassert(NULL != extension);\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"ogg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\telse if(kCFCompareEqualTo == CFStringCompare(extension, CFSTR(\"oga\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\n\treturn false;\n}\n\nbool OggVorbisMetadata::HandlesMIMEType(CFStringRef mimeType)\n{\n\tassert(NULL != mimeType);\t\n\t\n\tif(kCFCompareEqualTo == CFStringCompare(mimeType, CFSTR(\"audio\/ogg\"), kCFCompareCaseInsensitive))\n\t\treturn true;\n\t\n\treturn false;\n}\n\n\n#pragma mark Creation and Destruction\n\n\nOggVorbisMetadata::OggVorbisMetadata(CFURLRef url)\n\t: AudioMetadata(url)\n{}\n\nOggVorbisMetadata::~OggVorbisMetadata()\n{}\n\n\n#pragma mark Functionality\n\n\nbool OggVorbisMetadata::ReadMetadata(CFErrorRef *error)\n{\n\t\/\/ Start from scratch\n\tCFDictionaryRemoveAllValues(mMetadata);\n\t\n\tUInt8 buf [PATH_MAX];\n\tif(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\t\n\t\/\/ Attempt to open the file as an Ogg Vorbis file, and if it fails, as an Ogg FLAC file\n\tTagLib::Ogg::File *file = new TagLib::Ogg::Vorbis::File(reinterpret_cast(buf), false);\n\t\n\tif(!file->isValid()) {\n\t\tdelete file, file = NULL;\n\t\t\n\t\tfile = new TagLib::Ogg::FLAC::File(reinterpret_cast(buf), false);\n\t}\n\t\n\tif(!file->isValid()) {\n\t\tif(NULL != error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not an Ogg file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\tdelete file, file = NULL;\n\t\t\n\t\treturn false;\n\t}\n\n\tif(file->tag()) {\n\t\tCFMutableDictionaryRef additionalMetadata = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\n\t\t\/\/ A map \n\t\tTagLib::Ogg::XiphComment *xiphComment = dynamic_cast(file->tag());\n\n\t\t\/\/ This shouldn't happen\n\t\tif(!xiphComment) {\n\t\t\tdelete file, file = NULL;\t\t\t\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\tTagLib::Ogg::FieldListMap fieldList = xiphComment->fieldListMap();\n\t\t\n\t\tfor(TagLib::Ogg::FieldListMap::ConstIterator it = fieldList.begin(); it != fieldList.end(); ++it) {\n\t\t\tCFStringRef key = CFStringCreateWithCString(kCFAllocatorDefault,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tit->first.toCString(true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tkCFStringEncodingUTF8);\n\t\t\t\n\t\t\t\/\/ Vorbis allows multiple comments with the same key, but this isn't supported by AudioMetadata\n\t\t\tCFStringRef value = CFStringCreateWithCString(kCFAllocatorDefault,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t it->second.front().toCString(true),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t kCFStringEncodingUTF8);\n\t\t\t\n\t\t\tif(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ALBUM\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetAlbumTitle(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ARTIST\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetArtist(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ALBUMARTIST\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetAlbumArtist(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"COMPOSER\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetComposer(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"GENRE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetGenre(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DATE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetReleaseDate(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DESCRIPTION\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetComment(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TITLE\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetTitle(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TRACKNUMBER\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetTrackNumber(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"TRACKTOTAL\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetTrackTotal(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"COMPILATION\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetCompilation(CFStringGetIntValue(value) ? kCFBooleanTrue : kCFBooleanFalse);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DISCNUMBER\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetDiscNumber(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"DISCTOTAL\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tint num = CFStringGetIntValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &num);\n\t\t\t\tSetDiscTotal(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"ISRC\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetISRC(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"MCN\"), kCFCompareCaseInsensitive))\n\t\t\t\tSetMCN(value);\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_REFERENCE_LOUDNESS\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainReferenceLoudness(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_TRACK_GAIN\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainTrackGain(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_TRACK_PEAK\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainTrackPeak(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_ALBUM_GAIN\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainAlbumGain(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\telse if(kCFCompareEqualTo == CFStringCompare(key, CFSTR(\"REPLAYGAIN_ALBUM_PEAK\"), kCFCompareCaseInsensitive)) {\n\t\t\t\tdouble num = CFStringGetDoubleValue(value);\n\t\t\t\tCFNumberRef number = CFNumberCreate(kCFAllocatorDefault, kCFNumberDoubleType, &num);\n\t\t\t\tSetReplayGainAlbumPeak(number);\n\t\t\t\tCFRelease(number), number = NULL;\n\t\t\t}\n\t\t\t\/\/ Put all unknown tags into the additional metadata\n\t\t\telse\n\t\t\t\tCFDictionarySetValue(additionalMetadata, key, value);\n\t\t\t\n\t\t\tCFRelease(key), key = NULL;\n\t\t\tCFRelease(value), value = NULL;\n\t\t}\n\n\t\tif(CFDictionaryGetCount(additionalMetadata))\n\t\t\tSetAdditionalMetadata(additionalMetadata);\n\t\t\n\t\tCFRelease(additionalMetadata), additionalMetadata = NULL;\n\t\t\n\t}\n\n\tdelete file, file = NULL;\n\n\treturn true;\n}\n\nbool OggVorbisMetadata::WriteMetadata(CFErrorRef *error)\n{\n\tUInt8 buf [PATH_MAX];\n\tif(false == CFURLGetFileSystemRepresentation(mURL, false, buf, PATH_MAX))\n\t\treturn false;\n\n\t\/\/ Attempt to open the file as an Ogg Vorbis file, and if it fails, as an Ogg FLAC file\n\tTagLib::Ogg::File *file = new TagLib::Ogg::Vorbis::File(reinterpret_cast(buf), false);\n\t\n\tif(!file->isValid()) {\n\t\tdelete file, file = NULL;\n\t\t\n\t\tfile = new TagLib::Ogg::FLAC::File(reinterpret_cast(buf), false);\n\t}\n\t\n\tif(!file->isValid()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Not an Ogg file\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\tdelete file, file = NULL;\n\n\t\treturn false;\n\t}\n\n\n\tif(!file->save()) {\n\t\tif(error) {\n\t\t\tCFMutableDictionaryRef errorDictionary = CFDictionaryCreateMutable(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t 32,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryKeyCallBacks,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t &kCFTypeDictionaryValueCallBacks);\n\t\t\t\n\t\t\tCFStringRef displayName = CreateDisplayNameForURL(mURL);\n\t\t\tCFStringRef errorString = CFStringCreateWithFormat(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file \\\"%@\\\" is not a valid Ogg file.\"), \"\"), \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t displayName);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedDescriptionKey, \n\t\t\t\t\t\t\t\t errorString);\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedFailureReasonKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"Unable to write metadata\"), \"\"));\n\t\t\t\n\t\t\tCFDictionarySetValue(errorDictionary, \n\t\t\t\t\t\t\t\t kCFErrorLocalizedRecoverySuggestionKey, \n\t\t\t\t\t\t\t\t CFCopyLocalizedString(CFSTR(\"The file's extension may not match the file's type.\"), \"\"));\n\t\t\t\n\t\t\tCFRelease(errorString), errorString = NULL;\n\t\t\tCFRelease(displayName), displayName = NULL;\n\t\t\t\n\t\t\t*error = CFErrorCreate(kCFAllocatorDefault, \n\t\t\t\t\t\t\t\t AudioMetadataErrorDomain, \n\t\t\t\t\t\t\t\t AudioMetadataInputOutputError, \n\t\t\t\t\t\t\t\t errorDictionary);\n\t\t\t\n\t\t\tCFRelease(errorDictionary), errorDictionary = NULL;\t\t\t\t\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n\n\tdelete file, file = NULL;\n\n\treturn true;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: layerimp.hxx,v $\n *\n * $Revision: 1.1 $\n *\n * last change: $Author: cl $ $Date: 2001-01-19 16:33:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_LAYERIMP_HXX\n#define _XMLOFF_LAYERIMP_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\nclass AnimImpImpl;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ presentations:animations\n\nclass SdXMLLayerSetContext : public SvXMLImportContext\n{\nprivate:\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > mxLayerManager;\n\npublic:\n TYPEINFO();\n\n SdXMLLayerSetContext( SvXMLImport& rImport,\n sal_uInt16 nPrfx,\n const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);\n virtual ~SdXMLLayerSetContext();\n\n virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n};\n\n#endif \/\/ _XMLOFF_ANIMIMP_HXX\n\nINTEGRATION: CWS ooo19126 (1.1.646); FILE MERGED 2005\/09\/05 14:38:44 rt 1.1.646.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: layerimp.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 13:45:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_LAYERIMP_HXX\n#define _XMLOFF_LAYERIMP_HXX\n\n#ifndef _XMLOFF_XMLICTXT_HXX\n#include \"xmlictxt.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_\n#include \n#endif\n\nclass AnimImpImpl;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ presentations:animations\n\nclass SdXMLLayerSetContext : public SvXMLImportContext\n{\nprivate:\n ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > mxLayerManager;\n\npublic:\n TYPEINFO();\n\n SdXMLLayerSetContext( SvXMLImport& rImport,\n sal_uInt16 nPrfx,\n const rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList);\n virtual ~SdXMLLayerSetContext();\n\n virtual SvXMLImportContext * CreateChildContext( USHORT nPrefix, const ::rtl::OUString& rLocalName,\n const com::sun::star::uno::Reference< com::sun::star::xml::sax::XAttributeList>& xAttrList );\n};\n\n#endif \/\/ _XMLOFF_ANIMIMP_HXX\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ .\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"continuous-collision-checking\/dichotomy\/body-pair-collision.hh\"\n\nnamespace hpp {\n namespace core {\n namespace continuousCollisionChecking {\n\n using dichotomy::BodyPairCollision;\n using dichotomy::BodyPairCollisionPtr_t;\n using dichotomy::BodyPairCollisions_t;\n\n bool compareBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,\n\t\t\t const BodyPairCollisionPtr_t& bodyPair2)\n {\n\tassert (!bodyPair1->validSubset ().list ().empty ());\n\tassert (!bodyPair2->validSubset ().list ().empty ());\n\treturn bodyPair1->validSubset ().list ().begin ()->second <\n\t bodyPair2->validSubset ().list ().begin ()->second;\n }\n\n bool compareReverseBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,\n\t\t\t\t const BodyPairCollisionPtr_t& bodyPair2)\n {\n\tassert (!bodyPair1->validSubset ().list ().empty ());\n\tassert (!bodyPair2->validSubset ().list ().empty ());\n\treturn bodyPair1->validSubset ().list ().rbegin ()->first >\n\t bodyPair2->validSubset ().list ().rbegin ()->first;\n }\n\n \/\/ Partially sort a list where only the first element is not sorted\n template \n void partialSort (BodyPairCollisions_t& list, Compare comp)\n {\n\tBodyPairCollisions_t::iterator it1 = list.begin ();\n\tif (it1 == list.end ()) return;\n\tBodyPairCollisions_t::iterator it2 = it1; ++it2;\n\twhile (it2 != list.end ()) {\n\t if (comp (*it2, *it1))\n\t std::iter_swap (it1, it2);\n\t else\n\t return;\n\t it1 = it2;\n\t ++it2;\n\t}\n }\n DichotomyPtr_t\n Dichotomy::create (const DevicePtr_t& robot, const value_type& tolerance)\n {\n\tDichotomy* ptr =\n\t new Dichotomy (robot, tolerance);\n\tDichotomyPtr_t shPtr (ptr);\n\treturn shPtr;\n }\n\n bool Dichotomy::validate (const PathPtr_t& path, bool reverse,\n\t\t\t\tPathPtr_t& validPart,\n\t\t\t\tPathValidationReportPtr_t& report)\n {\n\tCollisionValidationReportPtr_t collisionReport\n\t (new CollisionValidationReport);\n\tif (PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST (PathVector, path)) {\n\t PathVectorPtr_t validPathVector = PathVector::create\n\t (path->outputSize (), path->outputDerivativeSize ());\n\t validPart = validPathVector;\n\t PathPtr_t localValidPart;\n\t if (reverse) {\n\t value_type param = path->length ();\n\t std::deque paths;\n\t for (std::size_t i=pv->numberPaths () + 1; i != 0 ; --i) {\n\t PathPtr_t localPath (pv->pathAtRank (i-1));\n\t if (validate (localPath, reverse, localValidPart, report)) {\n\t\tpaths.push_front (localPath->copy ());\n\t\tparam -= localPath->length ();\n\t } else {\n\t\treport->parameter += param - localPath->length ();\n\t\tpaths.push_front (localValidPart->copy ());\n\t\tfor (std::deque ::const_iterator it = paths.begin ();\n\t\t it != paths.end (); ++it) {\n\t\t validPathVector->appendPath (*it);\n\t\t}\n\t\treturn false;\n\t }\n\t }\n\t return true;\n\t } else {\n\t value_type param = 0;\n\t for (std::size_t i=0; i < pv->numberPaths (); ++i) {\n\t PathPtr_t localPath (pv->pathAtRank (i));\n\t if (validate (localPath, reverse, localValidPart, report)) {\n\t\tvalidPathVector->appendPath (localPath->copy ());\n\t\tparam += localPath->length ();\n\t } else {\n\t\treport->parameter += param;\n\t\tvalidPathVector->appendPath (localValidPart->copy ());\n\t\treturn false;\n\t }\n\t }\n\t return true;\n\t }\n\t}\n\tStraightPathPtr_t straightPath = HPP_DYNAMIC_PTR_CAST\n\t (StraightPath, path);\n\t\/\/ for each BodyPairCollision\n\t\/\/ - set path,\n\t\/\/ - compute valid interval at start (end if reverse)\n\tvalue_type t0 = path->timeRange ().first;\n\tvalue_type t1 = path->timeRange ().second;\n\tif (reverse) {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t (*itPair)->path (straightPath);\n\t \/\/ If collision at end point, return false\n\t if (!(*itPair)->validateInterval (t1, *collisionReport)) {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (t1, collisionReport));\n\t validPart = path->extract (interval_t (t1, t1));\n\t return false;\n\t }\n\t assert ((*itPair)->validSubset ().contains (t1));\n\t }\n\t \/\/ Sort collision pairs\n\t bodyPairCollisions_.sort (compareReverseBodyPairCol);\n\n\t BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());\n\t while (!first->validSubset ().contains (t0, true)) {\n\t \/\/ find middle of first non valid interval\n\t const std::list & intervals =\n\t first->validSubset ().list ();\n\t std::list ::const_reverse_iterator lastInterval =\n\t intervals.rbegin ();\n\t std::list ::const_reverse_iterator beforeLastInterval =\n\t lastInterval; ++beforeLastInterval;\n\t value_type upper = lastInterval->first;\n\t value_type lower;\n\t if (beforeLastInterval != intervals.rend ()) {\n\t lower = beforeLastInterval->second;\n\t } else {\n\t lower = t0;\n\t }\n\t value_type middle = .5 * (lower + upper);\n\t if (first->validateInterval (middle, *collisionReport)) {\n\t partialSort (bodyPairCollisions_, compareReverseBodyPairCol);\n\t } else {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (middle, collisionReport));\n\t validPart = path->extract (interval_t (upper, t1));\n\t return false;\n\t }\n\t first = *(bodyPairCollisions_.begin ());\n\t }\n\t} else {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t (*itPair)->path (straightPath);\n\t \/\/ If collision at start point, return false\n\t bool valid = (*itPair)->validateInterval (t0, *collisionReport);\n\t if (!valid) {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (t0, collisionReport));\n\t validPart = path->extract (interval_t (t0, t0));\n\t hppDout (error, \"Initial position in collision.\");\n\t return false;\n\t }\n\t assert ((*itPair)->validSubset ().contains (t0));\n\t }\n\t \/\/ Sort collision pairs\n\t bodyPairCollisions_.sort (compareBodyPairCol);\n\t BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());\n\t while (!first->validSubset ().contains (t1)) {\n\t \/\/ find middle of first non valid interval\n\t const std::list & intervals =\n\t first->validSubset ().list ();\n\t std::list ::const_iterator firstInterval =\n\t intervals.begin ();\n\t std::list ::const_iterator secondInterval =\n\t firstInterval;\n\t ++secondInterval;\n\t value_type lower = firstInterval->second;\n\t value_type upper;\n\t if (secondInterval != intervals.end ()) {\n\t upper = secondInterval->first;\n\t } else {\n\t upper = t1;\n\t }\n\t value_type middle = .5 * (lower + upper);\n\t if (first->validateInterval (middle, *collisionReport)) {\n\t partialSort (bodyPairCollisions_, compareBodyPairCol);\n\t } else {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (middle, collisionReport));\n\t validPart = path->extract (interval_t (t0, lower));\n\t return false;\n\t }\n\t first = *(bodyPairCollisions_.begin ());\n\t }\n\t}\n\tvalidPart = path;\n\treturn true;\n }\n\n void Dichotomy::addObstacle\n (const CollisionObjectConstPtr_t& object)\n {\n\tpinocchio::JointVector_t& jv = robot_->getJointVector ();\n\tfor (size_type idx = 0; idx < jv.size (); ++idx) {\n JointPtr_t j = jv[idx];\n\t BodyPtr_t body = j->linkedBody ();\n\t bool foundPair = false;\n\t if (body) {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t if (((*itPair)->joint_a () == j) &&\n\t\t (!(*itPair)->joint_b ())) {\n\t\t(*itPair)->addObjectTo_b (object);\n\t\tfoundPair = true;\n\t }\n\t }\n\t if (!foundPair) {\n\t ConstObjectStdVector_t objects;\n\t objects.push_back (object);\n\t bodyPairCollisions_.push_back\n\t\t(BodyPairCollision::create (j, objects, tolerance_));\n\t }\n\t }\n\t}\n }\n\n void Dichotomy::removeObstacleFromJoint\n (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)\n {\n\tbool removed = false;\n\tfor (BodyPairCollisions_t::iterator itPair =\n\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t if (!(*itPair)->joint_b () && (*itPair)->joint_a () == joint) {\n\t if ((*itPair)->removeObjectTo_b (obstacle)) {\n\t removed = true;\n\t if ((*itPair)->objects_b ().empty ()) {\n\t\tbodyPairCollisions_.erase (itPair);\n\t }\n\t }\n\t }\n\t}\n\tif (!removed) {\n\t std::ostringstream oss;\n\t oss << \"Dichotomy::removeObstacleFromJoint: obstacle \\\"\"\n\t << obstacle->name () <<\n\t \"\\\" is not registered as obstacle for joint \\\"\" << joint->name ()\n\t << \"\\\".\";\n\t throw std::runtime_error (oss.str ());\n\t}\n }\n\n Dichotomy::~Dichotomy ()\n {\n }\n\n Dichotomy::Dichotomy\n (const DevicePtr_t& robot, const value_type& tolerance) :\n\trobot_ (robot), tolerance_ (tolerance),\n\tbodyPairCollisions_ ()\n {\n \/\/ Tolerance should be equal to 0, otherwise end of valid\n \/\/ sub-path might be in collision.\n if (tolerance != 0) {\n throw std::runtime_error (\"Dichotomy path validation method does not\"\n \"support penetration.\");\n }\n \/\/ Build body pairs for collision checking\n \/\/ First auto-collision\n \/\/ FIXME The pairs of joint are duplicated\n const se3::GeometryModel& gmodel = robot->geomModel ();\n JointPtr_t joint1, joint2;\n for (std::size_t i = 0; i < gmodel.collisionPairs.size(); ++i)\n {\n const se3::CollisionPair& cp = gmodel.collisionPairs[i];\n joint1 = JointPtr_t(new Joint(robot_,\n gmodel.geometryObjects[cp.first].parentJoint));\n joint2 = JointPtr_t(new Joint(robot_,\n gmodel.geometryObjects[cp.second].parentJoint));\n bodyPairCollisions_.push_back (BodyPairCollision::create\n (joint1, joint2, tolerance_));\n }\n }\n } \/\/ namespace continuousCollisionChecking\n } \/\/ namespace core\n} \/\/ namespace hpp\nccc::Dichotomy avoid duplicated joint pairs\/\/\n\/\/ Copyright (c) 2014 CNRS\n\/\/ Authors: Florent Lamiraux\n\/\/\n\/\/ This file is part of hpp-core\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core If not, see\n\/\/ .\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"continuous-collision-checking\/dichotomy\/body-pair-collision.hh\"\n\nnamespace hpp {\n namespace core {\n namespace continuousCollisionChecking {\n namespace {\n typedef std::pair JointIndexPair_t;\n\n struct JointIndexPairCompare_t {\n bool operator() (const JointIndexPair_t& p0, const JointIndexPair_t& p1) const\n {\n if (p0.first < p1.first) return true;\n if (p0.first > p1.first) return false;\n return (p0.second < p1.second);\n }\n };\n\n typedef std::set JointIndexPairSet_t;\n }\n\n using dichotomy::BodyPairCollision;\n using dichotomy::BodyPairCollisionPtr_t;\n using dichotomy::BodyPairCollisions_t;\n\n bool compareBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,\n\t\t\t const BodyPairCollisionPtr_t& bodyPair2)\n {\n\tassert (!bodyPair1->validSubset ().list ().empty ());\n\tassert (!bodyPair2->validSubset ().list ().empty ());\n\treturn bodyPair1->validSubset ().list ().begin ()->second <\n\t bodyPair2->validSubset ().list ().begin ()->second;\n }\n\n bool compareReverseBodyPairCol (const BodyPairCollisionPtr_t& bodyPair1,\n\t\t\t\t const BodyPairCollisionPtr_t& bodyPair2)\n {\n\tassert (!bodyPair1->validSubset ().list ().empty ());\n\tassert (!bodyPair2->validSubset ().list ().empty ());\n\treturn bodyPair1->validSubset ().list ().rbegin ()->first >\n\t bodyPair2->validSubset ().list ().rbegin ()->first;\n }\n\n \/\/ Partially sort a list where only the first element is not sorted\n template \n void partialSort (BodyPairCollisions_t& list, Compare comp)\n {\n\tBodyPairCollisions_t::iterator it1 = list.begin ();\n\tif (it1 == list.end ()) return;\n\tBodyPairCollisions_t::iterator it2 = it1; ++it2;\n\twhile (it2 != list.end ()) {\n\t if (comp (*it2, *it1))\n\t std::iter_swap (it1, it2);\n\t else\n\t return;\n\t it1 = it2;\n\t ++it2;\n\t}\n }\n DichotomyPtr_t\n Dichotomy::create (const DevicePtr_t& robot, const value_type& tolerance)\n {\n\tDichotomy* ptr =\n\t new Dichotomy (robot, tolerance);\n\tDichotomyPtr_t shPtr (ptr);\n\treturn shPtr;\n }\n\n bool Dichotomy::validate (const PathPtr_t& path, bool reverse,\n\t\t\t\tPathPtr_t& validPart,\n\t\t\t\tPathValidationReportPtr_t& report)\n {\n\tCollisionValidationReportPtr_t collisionReport\n\t (new CollisionValidationReport);\n\tif (PathVectorPtr_t pv = HPP_DYNAMIC_PTR_CAST (PathVector, path)) {\n\t PathVectorPtr_t validPathVector = PathVector::create\n\t (path->outputSize (), path->outputDerivativeSize ());\n\t validPart = validPathVector;\n\t PathPtr_t localValidPart;\n\t if (reverse) {\n\t value_type param = path->length ();\n\t std::deque paths;\n\t for (std::size_t i=pv->numberPaths () + 1; i != 0 ; --i) {\n\t PathPtr_t localPath (pv->pathAtRank (i-1));\n\t if (validate (localPath, reverse, localValidPart, report)) {\n\t\tpaths.push_front (localPath->copy ());\n\t\tparam -= localPath->length ();\n\t } else {\n\t\treport->parameter += param - localPath->length ();\n\t\tpaths.push_front (localValidPart->copy ());\n\t\tfor (std::deque ::const_iterator it = paths.begin ();\n\t\t it != paths.end (); ++it) {\n\t\t validPathVector->appendPath (*it);\n\t\t}\n\t\treturn false;\n\t }\n\t }\n\t return true;\n\t } else {\n\t value_type param = 0;\n\t for (std::size_t i=0; i < pv->numberPaths (); ++i) {\n\t PathPtr_t localPath (pv->pathAtRank (i));\n\t if (validate (localPath, reverse, localValidPart, report)) {\n\t\tvalidPathVector->appendPath (localPath->copy ());\n\t\tparam += localPath->length ();\n\t } else {\n\t\treport->parameter += param;\n\t\tvalidPathVector->appendPath (localValidPart->copy ());\n\t\treturn false;\n\t }\n\t }\n\t return true;\n\t }\n\t}\n\tStraightPathPtr_t straightPath = HPP_DYNAMIC_PTR_CAST\n\t (StraightPath, path);\n\t\/\/ for each BodyPairCollision\n\t\/\/ - set path,\n\t\/\/ - compute valid interval at start (end if reverse)\n\tvalue_type t0 = path->timeRange ().first;\n\tvalue_type t1 = path->timeRange ().second;\n\tif (reverse) {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t (*itPair)->path (straightPath);\n\t \/\/ If collision at end point, return false\n\t if (!(*itPair)->validateInterval (t1, *collisionReport)) {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (t1, collisionReport));\n\t validPart = path->extract (interval_t (t1, t1));\n\t return false;\n\t }\n\t assert ((*itPair)->validSubset ().contains (t1));\n\t }\n\t \/\/ Sort collision pairs\n\t bodyPairCollisions_.sort (compareReverseBodyPairCol);\n\n\t BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());\n\t while (!first->validSubset ().contains (t0, true)) {\n\t \/\/ find middle of first non valid interval\n\t const std::list & intervals =\n\t first->validSubset ().list ();\n\t std::list ::const_reverse_iterator lastInterval =\n\t intervals.rbegin ();\n\t std::list ::const_reverse_iterator beforeLastInterval =\n\t lastInterval; ++beforeLastInterval;\n\t value_type upper = lastInterval->first;\n\t value_type lower;\n\t if (beforeLastInterval != intervals.rend ()) {\n\t lower = beforeLastInterval->second;\n\t } else {\n\t lower = t0;\n\t }\n\t value_type middle = .5 * (lower + upper);\n\t if (first->validateInterval (middle, *collisionReport)) {\n\t partialSort (bodyPairCollisions_, compareReverseBodyPairCol);\n\t } else {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (middle, collisionReport));\n\t validPart = path->extract (interval_t (upper, t1));\n\t return false;\n\t }\n\t first = *(bodyPairCollisions_.begin ());\n\t }\n\t} else {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t (*itPair)->path (straightPath);\n\t \/\/ If collision at start point, return false\n\t bool valid = (*itPair)->validateInterval (t0, *collisionReport);\n\t if (!valid) {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (t0, collisionReport));\n\t validPart = path->extract (interval_t (t0, t0));\n\t hppDout (error, \"Initial position in collision.\");\n\t return false;\n\t }\n\t assert ((*itPair)->validSubset ().contains (t0));\n\t }\n\t \/\/ Sort collision pairs\n\t bodyPairCollisions_.sort (compareBodyPairCol);\n\t BodyPairCollisionPtr_t first = *(bodyPairCollisions_.begin ());\n\t while (!first->validSubset ().contains (t1)) {\n\t \/\/ find middle of first non valid interval\n\t const std::list & intervals =\n\t first->validSubset ().list ();\n\t std::list ::const_iterator firstInterval =\n\t intervals.begin ();\n\t std::list ::const_iterator secondInterval =\n\t firstInterval;\n\t ++secondInterval;\n\t value_type lower = firstInterval->second;\n\t value_type upper;\n\t if (secondInterval != intervals.end ()) {\n\t upper = secondInterval->first;\n\t } else {\n\t upper = t1;\n\t }\n\t value_type middle = .5 * (lower + upper);\n\t if (first->validateInterval (middle, *collisionReport)) {\n\t partialSort (bodyPairCollisions_, compareBodyPairCol);\n\t } else {\n\t report = CollisionPathValidationReportPtr_t\n\t\t(new CollisionPathValidationReport (middle, collisionReport));\n\t validPart = path->extract (interval_t (t0, lower));\n\t return false;\n\t }\n\t first = *(bodyPairCollisions_.begin ());\n\t }\n\t}\n\tvalidPart = path;\n\treturn true;\n }\n\n void Dichotomy::addObstacle\n (const CollisionObjectConstPtr_t& object)\n {\n\tpinocchio::JointVector_t& jv = robot_->getJointVector ();\n\tfor (size_type idx = 0; idx < jv.size (); ++idx) {\n JointPtr_t j = jv[idx];\n\t BodyPtr_t body = j->linkedBody ();\n\t bool foundPair = false;\n\t if (body) {\n\t for (BodyPairCollisions_t::iterator itPair =\n\t\t bodyPairCollisions_.begin ();\n\t\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t if (((*itPair)->joint_a () == j) &&\n\t\t (!(*itPair)->joint_b ())) {\n\t\t(*itPair)->addObjectTo_b (object);\n\t\tfoundPair = true;\n\t }\n\t }\n\t if (!foundPair) {\n\t ConstObjectStdVector_t objects;\n\t objects.push_back (object);\n\t bodyPairCollisions_.push_back\n\t\t(BodyPairCollision::create (j, objects, tolerance_));\n\t }\n\t }\n\t}\n }\n\n void Dichotomy::removeObstacleFromJoint\n (const JointPtr_t& joint, const CollisionObjectConstPtr_t& obstacle)\n {\n\tbool removed = false;\n\tfor (BodyPairCollisions_t::iterator itPair =\n\t bodyPairCollisions_.begin ();\n\t itPair != bodyPairCollisions_.end (); ++itPair) {\n\t if (!(*itPair)->joint_b () && (*itPair)->joint_a () == joint) {\n\t if ((*itPair)->removeObjectTo_b (obstacle)) {\n\t removed = true;\n\t if ((*itPair)->objects_b ().empty ()) {\n\t\tbodyPairCollisions_.erase (itPair);\n\t }\n\t }\n\t }\n\t}\n\tif (!removed) {\n\t std::ostringstream oss;\n\t oss << \"Dichotomy::removeObstacleFromJoint: obstacle \\\"\"\n\t << obstacle->name () <<\n\t \"\\\" is not registered as obstacle for joint \\\"\" << joint->name ()\n\t << \"\\\".\";\n\t throw std::runtime_error (oss.str ());\n\t}\n }\n\n Dichotomy::~Dichotomy ()\n {\n }\n\n Dichotomy::Dichotomy\n (const DevicePtr_t& robot, const value_type& tolerance) :\n\trobot_ (robot), tolerance_ (tolerance),\n\tbodyPairCollisions_ ()\n {\n \/\/ Tolerance should be equal to 0, otherwise end of valid\n \/\/ sub-path might be in collision.\n if (tolerance != 0) {\n throw std::runtime_error (\"Dichotomy path validation method does not\"\n \"support penetration.\");\n }\n \/\/ Build body pairs for collision checking\n \/\/ First auto-collision\n \/\/ FIXME The pairs of joint are duplicated\n const se3::GeometryModel& gmodel = robot->geomModel ();\n JointPtr_t joint1, joint2;\n JointIndexPairSet_t jointPairs;\n std::size_t duplicates = 0;\n for (std::size_t i = 0; i < gmodel.collisionPairs.size(); ++i)\n {\n const se3::CollisionPair& cp = gmodel.collisionPairs[i];\n JointIndexPair_t jp (\n gmodel.geometryObjects[cp.first].parentJoint,\n gmodel.geometryObjects[cp.second].parentJoint);\n if (jointPairs.count(jp) == 0) {\n jointPairs.insert(jp);\n joint1 = JointPtr_t(new Joint(robot_, jp.first));\n joint2 = JointPtr_t(new Joint(robot_, jp.second));\n bodyPairCollisions_.push_back (BodyPairCollision::create\n (joint1, joint2, tolerance_));\n hppDout(info, *bodyPairCollisions_.back());\n } else duplicates++;\n }\n hppDout(info, \"Dichotomy continuous collision checking: Inserted \"\n << jointPairs.size() << \" and filtered \" << duplicates <<\n \" duplicates.\" << std::endl);\n }\n } \/\/ namespace continuousCollisionChecking\n } \/\/ namespace core\n} \/\/ namespace hpp\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"constants.hpp\"\n#include \"grabber_client.hpp\"\n#include \"hid_system_client.hpp\"\n#include \"local_datagram_server.hpp\"\n#include \"logger.hpp\"\n#include \"types.hpp\"\n#include \n\nclass receiver final {\npublic:\n receiver(const receiver&) = delete;\n\n receiver(void) : exit_loop_(false),\n hid_system_client_(logger::get_logger()) {\n \/\/ Ensure that grabber is running.\n grabber_client_ = std::make_unique();\n grabber_client_->connect(krbn::connect_from::event_dispatcher);\n\n const size_t buffer_length = 8 * 1024;\n buffer_.resize(buffer_length);\n\n mkdir(constants::get_tmp_directory(), 0755);\n const char* path = constants::get_event_dispatcher_socket_file_path();\n unlink(path);\n server_ = std::make_unique(path);\n chmod(path, 0600);\n\n exit_loop_ = false;\n thread_ = std::thread([this] { this->worker(); });\n\n logger::get_logger().info(\"receiver is started\");\n }\n\n ~receiver(void) {\n unlink(constants::get_event_dispatcher_socket_file_path());\n\n exit_loop_ = true;\n if (thread_.joinable()) {\n thread_.join();\n }\n\n grabber_client_ = nullptr;\n server_ = nullptr;\n\n logger::get_logger().info(\"receiver is stopped\");\n }\n\nprivate:\n void worker(void) {\n if (!server_) {\n return;\n }\n\n while (!exit_loop_) {\n boost::system::error_code ec;\n std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec);\n\n if (!ec && n > 0) {\n switch (krbn::operation_type(buffer_[0])) {\n case krbn::operation_type::set_caps_lock_state:\n if (n != sizeof(krbn::operation_type_set_caps_lock_state_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::set_caps_lock_state\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.set_caps_lock_state(p->state);\n if (grabber_client_) {\n grabber_client_->set_caps_lock_led_state(p->state ? krbn::led_state::on : krbn::led_state::off);\n }\n }\n break;\n\n case krbn::operation_type::refresh_caps_lock_led:\n if (n != sizeof(krbn::operation_type_refresh_caps_lock_led_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::refresh_caps_lock_led\");\n } else {\n auto state = hid_system_client_.get_caps_lock_state();\n if (!state) {\n logger::get_logger().error(\"hid_system_client_.get_caps_lock_state error @ {0}\", __PRETTY_FUNCTION__);\n } else {\n if (grabber_client_) {\n grabber_client_->set_caps_lock_led_state(*state ? krbn::led_state::on : krbn::led_state::off);\n }\n }\n }\n break;\n\n case krbn::operation_type::post_modifier_flags:\n if (n != sizeof(krbn::operation_type_post_modifier_flags_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::post_modifier_flags\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.post_modifier_flags(p->key_code, p->flags, p->keyboard_type);\n }\n break;\n\n case krbn::operation_type::post_key:\n if (n != sizeof(krbn::operation_type_post_key_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::post_key\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.post_key(p->key_code, p->event_type, p->flags, p->repeat, p->keyboard_type);\n }\n break;\n\n default:\n break;\n }\n }\n }\n }\n\n std::vector buffer_;\n std::unique_ptr server_;\n std::unique_ptr grabber_client_;\n std::thread thread_;\n std::atomic exit_loop_;\n\n hid_system_client hid_system_client_;\n};\nupdate arguments order#pragma once\n\n#include \"constants.hpp\"\n#include \"grabber_client.hpp\"\n#include \"hid_system_client.hpp\"\n#include \"local_datagram_server.hpp\"\n#include \"logger.hpp\"\n#include \"types.hpp\"\n#include \n\nclass receiver final {\npublic:\n receiver(const receiver&) = delete;\n\n receiver(void) : exit_loop_(false),\n hid_system_client_(logger::get_logger()) {\n \/\/ Ensure that grabber is running.\n grabber_client_ = std::make_unique();\n grabber_client_->connect(krbn::connect_from::event_dispatcher);\n\n const size_t buffer_length = 8 * 1024;\n buffer_.resize(buffer_length);\n\n mkdir(constants::get_tmp_directory(), 0755);\n const char* path = constants::get_event_dispatcher_socket_file_path();\n unlink(path);\n server_ = std::make_unique(path);\n chmod(path, 0600);\n\n exit_loop_ = false;\n thread_ = std::thread([this] { this->worker(); });\n\n logger::get_logger().info(\"receiver is started\");\n }\n\n ~receiver(void) {\n unlink(constants::get_event_dispatcher_socket_file_path());\n\n exit_loop_ = true;\n if (thread_.joinable()) {\n thread_.join();\n }\n\n grabber_client_ = nullptr;\n server_ = nullptr;\n\n logger::get_logger().info(\"receiver is stopped\");\n }\n\nprivate:\n void worker(void) {\n if (!server_) {\n return;\n }\n\n while (!exit_loop_) {\n boost::system::error_code ec;\n std::size_t n = server_->receive(boost::asio::buffer(buffer_), boost::posix_time::seconds(1), ec);\n\n if (!ec && n > 0) {\n switch (krbn::operation_type(buffer_[0])) {\n case krbn::operation_type::set_caps_lock_state:\n if (n != sizeof(krbn::operation_type_set_caps_lock_state_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::set_caps_lock_state\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.set_caps_lock_state(p->state);\n if (grabber_client_) {\n grabber_client_->set_caps_lock_led_state(p->state ? krbn::led_state::on : krbn::led_state::off);\n }\n }\n break;\n\n case krbn::operation_type::refresh_caps_lock_led:\n if (n != sizeof(krbn::operation_type_refresh_caps_lock_led_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::refresh_caps_lock_led\");\n } else {\n auto state = hid_system_client_.get_caps_lock_state();\n if (!state) {\n logger::get_logger().error(\"hid_system_client_.get_caps_lock_state error @ {0}\", __PRETTY_FUNCTION__);\n } else {\n if (grabber_client_) {\n grabber_client_->set_caps_lock_led_state(*state ? krbn::led_state::on : krbn::led_state::off);\n }\n }\n }\n break;\n\n case krbn::operation_type::post_modifier_flags:\n if (n != sizeof(krbn::operation_type_post_modifier_flags_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::post_modifier_flags\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.post_modifier_flags(p->key_code, p->flags, p->keyboard_type);\n }\n break;\n\n case krbn::operation_type::post_key:\n if (n != sizeof(krbn::operation_type_post_key_struct)) {\n logger::get_logger().error(\"invalid size for krbn::operation_type::post_key\");\n } else {\n auto p = reinterpret_cast(&(buffer_[0]));\n hid_system_client_.post_key(p->key_code, p->event_type, p->flags, p->keyboard_type, p->repeat);\n }\n break;\n\n default:\n break;\n }\n }\n }\n }\n\n std::vector buffer_;\n std::unique_ptr server_;\n std::unique_ptr grabber_client_;\n std::thread thread_;\n std::atomic exit_loop_;\n\n hid_system_client hid_system_client_;\n};\n<|endoftext|>"} {"text":"\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_SYSTEM_HPP__\n#define __PROCESS_SYSTEM_HPP__\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace process {\n\n\/\/ The System process provides HTTP endpoints for retrieving system metrics,\n\/\/ such as CPU load and memory usage. This is started by default during the\n\/\/ initialization of libprocess.\nclass System : public Process\n{\npublic:\n System()\n : ProcessBase(\"system\"),\n load_1min(\n self().id + \"\/load_1min\",\n defer(self(), &System::_load_1min)),\n load_5min(\n self().id + \"\/load_5min\",\n defer(self(), &System::_load_5min)),\n load_15min(\n self().id + \"\/load_15min\",\n defer(self(), &System::_load_15min)),\n cpus_total(\n self().id + \"\/cpus_total\",\n defer(self(), &System::_cpus_total)),\n mem_total_bytes(\n self().id + \"\/mem_total_bytes\",\n defer(self(), &System::_mem_total_bytes)),\n mem_free_bytes(\n self().id + \"\/mem_free_bytes\",\n defer(self(), &System::_mem_free_bytes)) {}\n\n virtual ~System() {}\n\nprotected:\n virtual void initialize()\n {\n \/\/ TODO(dhamon): Check return values.\n metrics::add(load_1min);\n metrics::add(load_5min);\n metrics::add(load_15min);\n metrics::add(cpus_total);\n metrics::add(mem_total_bytes);\n metrics::add(mem_free_bytes);\n\n route(\"\/stats.json\", statsHelp(), &System::stats);\n }\n\n virtual void finalize()\n {\n metrics::remove(load_1min);\n metrics::remove(load_5min);\n metrics::remove(load_15min);\n metrics::remove(cpus_total);\n metrics::remove(mem_total_bytes);\n metrics::remove(mem_free_bytes);\n }\n\nprivate:\n static std::string statsHelp()\n {\n return HELP(\n TLDR(\n \"Shows local system metrics.\"),\n DESCRIPTION(\n \"> cpus_total Total number of available CPUs\",\n \"> load_1min Average system load for last\"\n \" minute in uptime(1) style\",\n \"> load_5min Average system load for last\"\n \" 5 minutes in uptime(1) style\",\n \"> load_15min Average system load for last\"\n \" 15 minutes in uptime(1) style\",\n \"> memory_total_bytes Total system memory in bytes\",\n \"> memory_free_bytes Free system memory in bytes\"));\n }\n\n \/\/ Gauge handlers.\n Future _load_1min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().one;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _load_5min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().five;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _load_15min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().fifteen;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _cpus_total()\n {\n Try cpus = os::cpus();\n if (cpus.isSome()) {\n return cpus.get();\n }\n return Failure(\"Failed to get cpus: \" + cpus.error());\n }\n\n\n Future _mem_total_bytes()\n {\n Try memory = os::memory();\n if (memory.isSome()) {\n return memory.get().total.bytes();\n }\n return Failure(\"Failed to get memory: \" + memory.error());\n }\n\n\n Future _mem_free_bytes()\n {\n Try memory = os::memory();\n if (memory.isSome()) {\n return memory.get().free.bytes();\n }\n return Failure(\"Failed to get memory: \" + memory.error());\n }\n\n \/\/ HTTP endpoints.\n Future stats(const http::Request& request)\n {\n JSON::Object object;\n Try load = os::loadavg();\n if (load.isSome()) {\n object.values[\"avg_load_1min\"] = load.get().one;\n object.values[\"avg_load_5min\"] = load.get().five;\n object.values[\"avg_load_15min\"] = load.get().fifteen;\n }\n\n Try cpus = os::cpus();\n if (cpus.isSome()) {\n object.values[\"cpus_total\"] = cpus.get();\n }\n\n Try memory = os::memory();\n if (memory.isSome()) {\n object.values[\"mem_total_bytes\"] = memory.get().total.bytes();\n object.values[\"mem_free_bytes\"] = memory.get().free.bytes();\n }\n\n return http::OK(object, request.url.query.get(\"jsonp\"));\n }\n\n metrics::Gauge load_1min;\n metrics::Gauge load_5min;\n metrics::Gauge load_15min;\n\n metrics::Gauge cpus_total;\n\n metrics::Gauge mem_total_bytes;\n metrics::Gauge mem_free_bytes;\n};\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_SYSTEM_HPP__\nFixed warnings in `process\/system.hpp`.\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License\n\n#ifndef __PROCESS_SYSTEM_HPP__\n#define __PROCESS_SYSTEM_HPP__\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nnamespace process {\n\n\/\/ The System process provides HTTP endpoints for retrieving system metrics,\n\/\/ such as CPU load and memory usage. This is started by default during the\n\/\/ initialization of libprocess.\nclass System : public Process\n{\npublic:\n System()\n : ProcessBase(\"system\"),\n load_1min(\n self().id + \"\/load_1min\",\n defer(self(), &System::_load_1min)),\n load_5min(\n self().id + \"\/load_5min\",\n defer(self(), &System::_load_5min)),\n load_15min(\n self().id + \"\/load_15min\",\n defer(self(), &System::_load_15min)),\n cpus_total(\n self().id + \"\/cpus_total\",\n defer(self(), &System::_cpus_total)),\n mem_total_bytes(\n self().id + \"\/mem_total_bytes\",\n defer(self(), &System::_mem_total_bytes)),\n mem_free_bytes(\n self().id + \"\/mem_free_bytes\",\n defer(self(), &System::_mem_free_bytes)) {}\n\n virtual ~System() {}\n\nprotected:\n virtual void initialize()\n {\n \/\/ TODO(dhamon): Check return values.\n metrics::add(load_1min);\n metrics::add(load_5min);\n metrics::add(load_15min);\n metrics::add(cpus_total);\n metrics::add(mem_total_bytes);\n metrics::add(mem_free_bytes);\n\n route(\"\/stats.json\", statsHelp(), &System::stats);\n }\n\n virtual void finalize()\n {\n metrics::remove(load_1min);\n metrics::remove(load_5min);\n metrics::remove(load_15min);\n metrics::remove(cpus_total);\n metrics::remove(mem_total_bytes);\n metrics::remove(mem_free_bytes);\n }\n\nprivate:\n static std::string statsHelp()\n {\n return HELP(\n TLDR(\n \"Shows local system metrics.\"),\n DESCRIPTION(\n \"> cpus_total Total number of available CPUs\",\n \"> load_1min Average system load for last\"\n \" minute in uptime(1) style\",\n \"> load_5min Average system load for last\"\n \" 5 minutes in uptime(1) style\",\n \"> load_15min Average system load for last\"\n \" 15 minutes in uptime(1) style\",\n \"> memory_total_bytes Total system memory in bytes\",\n \"> memory_free_bytes Free system memory in bytes\"));\n }\n\n \/\/ Gauge handlers.\n Future _load_1min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().one;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _load_5min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().five;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _load_15min()\n {\n Try load = os::loadavg();\n if (load.isSome()) {\n return load.get().fifteen;\n }\n return Failure(\"Failed to get loadavg: \" + load.error());\n }\n\n\n Future _cpus_total()\n {\n Try cpus = os::cpus();\n if (cpus.isSome()) {\n return cpus.get();\n }\n return Failure(\"Failed to get cpus: \" + cpus.error());\n }\n\n\n Future _mem_total_bytes()\n {\n Try memory = os::memory();\n if (memory.isSome()) {\n return static_cast(memory.get().total.bytes());\n }\n return Failure(\"Failed to get memory: \" + memory.error());\n }\n\n\n Future _mem_free_bytes()\n {\n Try memory = os::memory();\n if (memory.isSome()) {\n return static_cast(memory.get().free.bytes());\n }\n return Failure(\"Failed to get memory: \" + memory.error());\n }\n\n \/\/ HTTP endpoints.\n Future stats(const http::Request& request)\n {\n JSON::Object object;\n Try load = os::loadavg();\n if (load.isSome()) {\n object.values[\"avg_load_1min\"] = load.get().one;\n object.values[\"avg_load_5min\"] = load.get().five;\n object.values[\"avg_load_15min\"] = load.get().fifteen;\n }\n\n Try cpus = os::cpus();\n if (cpus.isSome()) {\n object.values[\"cpus_total\"] = cpus.get();\n }\n\n Try memory = os::memory();\n if (memory.isSome()) {\n object.values[\"mem_total_bytes\"] = memory.get().total.bytes();\n object.values[\"mem_free_bytes\"] = memory.get().free.bytes();\n }\n\n return http::OK(object, request.url.query.get(\"jsonp\"));\n }\n\n metrics::Gauge load_1min;\n metrics::Gauge load_5min;\n metrics::Gauge load_15min;\n\n metrics::Gauge cpus_total;\n\n metrics::Gauge mem_total_bytes;\n metrics::Gauge mem_free_bytes;\n};\n\n} \/\/ namespace process {\n\n#endif \/\/ __PROCESS_SYSTEM_HPP__\n<|endoftext|>"} {"text":"\/*\r\ngpe_editor_aboutpage.cpp\r\nThis file is part of:\r\nGAME PENCIL ENGINE\r\nhttps:\/\/create.pawbyte.com\r\nCopyright (c) 2014-2020 Nathan Hurde, Chase Lee.\r\n\r\nCopyright (c) 2014-2020 PawByte LLC.\r\nCopyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the “Software”), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\n-Game Pencil Engine \r\n\r\n\r\n*\/\r\n\r\n#include \"gpe_editor_aboutpage.h\"\r\n\r\ngamePencilAboutPageResource * MAIN_ABOUT_PAGE = NULL;\r\n\r\ngamePencilAboutPageResource::gamePencilAboutPageResource()\r\n{\r\n isFullScreenResource = true;\r\n resourceFileName = \"\";\r\n resourceName = \"About Page\";\r\n parentProjectName = \"\";\r\n parentProjectDirectory = \"\";\r\n \/\/GPE_Animation * mainMenuanimation = guiRCM->animation_add(APP_DIRECTORY_NAME+\"resources\/gfx\/animations\/gpe_main_icons_big.png\",70,true,0,0,false);\r\n\r\n sideAreaPanel = new GPE_SelectBoxBasic(\"Mode\");\r\n sideAreaPanel->set_width(256);\r\n sideAreaPanel->set_option_height(64);\r\n sideAreaPanel->add_option(\"Credits\",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+\"resources\/gfx\/iconpacks\/fontawesome\/heart.png\"),NULL,2, false, false);\r\n sideAreaPanel->add_option(\"License\",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+\"resources\/gfx\/iconpacks\/fontawesome\/file-text.png\"),NULL,2, false, false);\r\n sideAreaPanel->add_option(\"3rd Party Licenses\",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+\"resources\/gfx\/iconpacks\/fontawesome\/group.png\"),NULL,2, false, false);\r\n\r\n sidePanelRect = new GPE_Rect();\r\n\r\n aboutPageList = new GPE_GuiElementList();\r\n\r\n pencilCredits = new GPE_TextAreaInputBasic();\r\n pencilCredits->isCodeEditor = false;\r\n pencilCredits->set_read_only();\r\n pencilCredits->clear_all_lines();\r\n pencilCredits->add_line(\"PawByte Development Team\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\"Nathan Hurde: Lead IDE & Engine Developer\");\r\n pencilCredits->add_line(\"Chase Lee: Lead Web Developer & Color Theme Author\");\r\n pencilCredits->add_line(\"Karl Cons: Alpha testing of Version 0.2\");\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Community Contributors (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\"Anthony Manetti: Private Alpha testing of Version 0.2\");\r\n pencilCredits->add_line(\"Clint R Bellenger: Technical advising and help with input systems\");\r\n pencilCredits->add_line(\"Daniel Gump: Technical advising and help with HTML5 engine optimizations\");\r\n pencilCredits->add_line(\"@deadda7a: Helped with creation of new color theming for Version 1.0.1 and beyond.\");\r\n pencilCredits->add_line(\"@GTMalachiasV: Critical feedback and testing for improving Project Browser\");\r\n pencilCredits->add_line(\"@JeZxLee: Located Launcher error for files with spaces\/symbols in their file name.\");\r\n pencilCredits->add_line(\"Mac Carter: Usage of Mac to create & test OSX build.\");\r\n pencilCredits->add_line(\"Russell Johnston: Technical advising and help with syntax highlighting system\");\r\n pencilCredits->add_line(\"Tim C( timchoh585): Updated README.md to a professional level\");\r\n pencilCredits->add_line(\"Toyam Cox( Vaelatern): Created initial makefile\");\r\n pencilCredits->add_line(\"YellowAfterLife: Technical advising and help with collision systems\");\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Artwork (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\"David Gandy: Creator of Font Aesome [ https:\/\/twitter.com\/davegandy ]\");\r\n pencilCredits->add_line(\"Damian Kaczmarek Font-Awesome-SVG-PNG Author [ rush@rushbase.net @Rush ]\");\r\n pencilCredits->add_line(\"Dominykas Blyžė Font-Awesome-SVG-PNG Author [ hello@dominykas.com @dominykas]\");\r\n pencilCredits->add_line(\"@deadda7a: Created 'Game Pencil' logo\");\r\n pencilCredits->add_line(\"Font Awesome: Icons and Buttons [ http:\/\/fontawesome.io\/ ]\");\r\n pencilCredits->add_line(\"The Font Awesome font is licensed under the SIL OFL 1.1:\");\r\n pencilCredits->add_line(\"http:\/\/scripts.sil.org\/OFL \");\r\n pencilCredits->add_line(\"Font-Awesome-SVG-PNG is licensed under the MIT license \");\r\n\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Technologies (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\"Electron[Used for Desktop Exports]: http:\/\/electron.atom.io\/\");\r\n pencilCredits->add_line(\"IsImageOk: http:\/\/blog.sajithmr.me\/javascript-check-an-image-is-loaded-or-not\/\");\r\n pencilCredits->add_line(\"JavaScript FileReader: http:\/\/stackoverflow.com\/questions\/23331546\/how-to-use-javascript-to-read-local-text-file-and-read-line-by-line\");\r\n pencilCredits->add_line(\"RequestFrameAnimation: http:\/\/www.paulirish.com\/2011\/requestanimationframe-for-smart-animating\/\");\r\n pencilCredits->add_line(\"Simple DirectMedia Layer(SDL): http:\/\/www.libsdl.org\");\r\n pencilCredits->add_line(\"SDL_GFX: http:\/\/www.ferzkopp.net\/wordpress\/2016\/01\/02\/sdl_gfx-sdl2_gfx\/\");\n pencilCredits->add_line(\"FPS_CAP & FPS_Calculator functions: https:\/\/davidgow.net\/handmadepenguin\/ch18.html\/\");\r\n\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Patreon Backers (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\" Feral Monk\");\r\n pencilCredits->add_line(\" James Thomas\");\r\n pencilCredits->add_line(\" James Thomas\");\r\n pencilCredits->add_line(\" Joseph Yarrow\");\r\n pencilCredits->add_line(\" Mark Medrano\");\r\n pencilCredits->add_line(\" Keith Thomas\");\r\n pencilCredits->add_line(\" Noel Hurde\");\r\n pencilCredits->add_line(\" Thomas Ingham\");\r\n pencilCredits->add_line(\" Roshin Varghese\");\r\n\r\n pencilCredits->add_line(\"Itch.io Supporters (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\" Aisha Halim\");\r\n pencilCredits->add_line(\" Alessandro Montoli ( funkygallo)\");\r\n pencilCredits->add_line(\" _Auron_\");\r\n pencilCredits->add_line(\" bojjenclon\");\r\n pencilCredits->add_line(\" CammyGamesYT\");\r\n pencilCredits->add_line(\" Chad Davis\");\r\n pencilCredits->add_line(\" DarkLightGames\");\r\n pencilCredits->add_line(\" Davey13\");\r\n pencilCredits->add_line(\" evilemprzurg\");\r\n pencilCredits->add_line(\" F. Keitz\");\r\n pencilCredits->add_line(\" Florian Zwerina\");\r\n pencilCredits->add_line(\" Goldenkitty\");\r\n pencilCredits->add_line(\" Goldenxp\");\r\n pencilCredits->add_line(\" jarrett9999\");\r\n pencilCredits->add_line(\" Mark Henning\");\r\n pencilCredits->add_line(\" microrutter\");\r\n pencilCredits->add_line(\" M. Moy\");\r\n pencilCredits->add_line(\" Kat Leopardess\");\r\n pencilCredits->add_line(\" popcade\");\r\n pencilCredits->add_line(\" raymond13557\");\r\n pencilCredits->add_line(\" RookTKO\");\r\n pencilCredits->add_line(\" Samson194\");\r\n pencilCredits->add_line(\" TH\");\r\n pencilCredits->add_line(\" Veron Hurde Jr.\");\r\n pencilCredits->add_line(\" Woody Stanfield\");\r\n pencilCredits->add_line(\" Zonemaster\");\r\n\r\n\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"KickStarter Backers (Ordered Alphabetically):\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n\r\n pencilCredits->add_line(\" Aisha Halim\");\r\n pencilCredits->add_line(\" Aleksander Kwitakowski\");\r\n pencilCredits->add_line(\" Alex King\");\r\n pencilCredits->add_line(\" Alyssia Ashkevron\");\r\n pencilCredits->add_line(\" Arturas Norkus\");\r\n pencilCredits->add_line(\" Blair Johnson\");\r\n pencilCredits->add_line(\" Christopher Murt\");\r\n pencilCredits->add_line(\" Christopher Pope\");\r\n pencilCredits->add_line(\" Climb Fitness\");\r\n pencilCredits->add_line(\" Curtis Hurde\");\r\n pencilCredits->add_line(\" Daniel Stempniewicz\");\r\n pencilCredits->add_line(\" David Goldsmith\");\r\n pencilCredits->add_line(\" Derek Lawson\");\r\n pencilCredits->add_line(\" James Donachie\");\r\n pencilCredits->add_line(\" Giacomo Russo\");\r\n pencilCredits->add_line(\" Trevor Hayes\");\r\n pencilCredits->add_line(\" Godewijn Perizonius\");\r\n pencilCredits->add_line(\" Greg Polander\");\r\n pencilCredits->add_line(\" HBComics\");\r\n pencilCredits->add_line(\" Henri Niva\");\r\n pencilCredits->add_line(\" Jake Miller\");\r\n pencilCredits->add_line(\" James Bowling\");\r\n pencilCredits->add_line(\" Jason Mason Pierce\");\r\n pencilCredits->add_line(\" Jason Hornbuckle\");\r\n pencilCredits->add_line(\" Jeff Hanson\");\r\n pencilCredits->add_line(\" Joel A. Luellwitz\");\r\n pencilCredits->add_line(\" Johan Brodd\");\r\n pencilCredits->add_line(\" John Isakisson\");\r\n pencilCredits->add_line(\" John Lerchen\");\r\n pencilCredits->add_line(\" John Robertson\");\r\n pencilCredits->add_line(\" Johnathon Stevens\");\r\n pencilCredits->add_line(\" Jonathan Chang\");\r\n pencilCredits->add_line(\" Jose P. Zagal\");\r\n pencilCredits->add_line(\" Joshua Boren\");\r\n pencilCredits->add_line(\" jwilloug\");\r\n pencilCredits->add_line(\" Kelly Samuels\");\r\n pencilCredits->add_line(\" kuroiXiru\");\r\n pencilCredits->add_line(\" Pawel Sowizral\");\r\n pencilCredits->add_line(\" Lukasz Stempniewicz\");\r\n pencilCredits->add_line(\" Eden Caldas\");\r\n pencilCredits->add_line(\" Markus Løtveit\");\r\n pencilCredits->add_line(\" Matthew Schie\");\r\n pencilCredits->add_line(\" Matthew Sutherland\");\r\n pencilCredits->add_line(\" Max Juchheim\");\r\n pencilCredits->add_line(\" Meg Stivison\");\r\n pencilCredits->add_line(\" Michael Grenetz\");\r\n pencilCredits->add_line(\" Michael Parkin-White\");\r\n pencilCredits->add_line(\" Paul Beerkens\");\r\n pencilCredits->add_line(\" Paul Broadhurst\");\r\n pencilCredits->add_line(\" Roy Mwale\");\r\n pencilCredits->add_line(\" Sagi Koren\");\r\n pencilCredits->add_line(\" Seumas Cordell Froemke\");\r\n pencilCredits->add_line(\" Taran Buford\");\r\n pencilCredits->add_line(\" Teresa Ziebarth\");\r\n pencilCredits->add_line(\" Toby Hutton\");\r\n pencilCredits->add_line(\" Andreas Heldt\");\r\n pencilCredits->add_line(\" Zach Underwood\");\r\n\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Thank you for backing Agriduel aka Fields of Fresh which lead to this IDE and engine being developed.\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"-----------------------------------\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"Thank you for using the Game Pencil Engine.\");\r\n pencilCredits->add_line(\"\");\r\n pencilCredits->add_line(\"\");\r\n\r\n pencilDescription = new GPE_TextAreaInputBasic();\r\n pencilDescription->set_read_only();\r\n pencilDescription->isCodeEditor = false;\r\n\r\n pencilDescription->clear_all_lines();\r\n pencilDescription->import_text(APP_DIRECTORY_NAME+\"editor_description.txt\");\r\n pencilDescription->set_height(640);\r\n\r\n pencilMissionStatement = new GPE_TextAreaInputBasic();\r\n pencilMissionStatement->set_read_only();\r\n pencilMissionStatement->isCodeEditor = false;\r\n\r\n pencilLicense = new GPE_TextAreaInputBasic();\r\n pencilLicense->set_read_only();\r\n pencilLicense->isCodeEditor = false;\r\n\r\n \/\/pencilLicense->set_read_only();\r\n pencilLicense->add_line(\"Copyright (c) 2016-2018 PawByte, Nathan Hurde. All rights reserved..\");\r\n pencilLicense->add_line(\".\");\r\n pencilLicense->add_line(\"Redistribution and use in source and binary forms, with or without\");\r\n pencilLicense->add_line(\"modification, are permitted provided that the following conditions are\");\r\n pencilLicense->add_line(\"met:.\");\r\n pencilLicense->add_line(\".\");\r\n pencilLicense->add_line(\"* Redistributions of source code must retain the above copyright\");\r\n pencilLicense->add_line(\"notice, this list of conditions and the following disclaimer.\");\r\n pencilLicense->add_line(\" * Redistributions in binary form must reproduce the above\");\r\n pencilLicense->add_line(\"copyright notice, this list of conditions and the following disclaimer\");\r\n pencilLicense->add_line(\"in the documentation and\/or other materials provided with the\");\r\n pencilLicense->add_line(\"distribution..\");\r\n pencilLicense->add_line(\" * Neither the name of PawByte. nor the names of its\");\r\n pencilLicense->add_line(\"team nor its contributors may be used to endorse or promote products derived from\");\r\n pencilLicense->add_line(\"this software without specific prior written permission..\");\r\n pencilLicense->add_line(\"\");\r\n pencilLicense->add_line(\"THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\");\r\n pencilLicense->add_line(\"'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\");\r\n pencilLicense->add_line(\"LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\");\r\n pencilLicense->add_line(\"A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\");\r\n pencilLicense->add_line(\"OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\");\r\n pencilLicense->add_line(\"SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\");\r\n pencilLicense->add_line(\"LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\");\r\n pencilLicense->add_line(\"DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY.\");\r\n pencilLicense->add_line(\"THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\");\r\n pencilLicense->add_line(\"(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\");\r\n pencilLicense->add_line(\"OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\");\r\n pencilLicense->add_line(\"\");\r\n pencilLicense->set_height(640);\r\n\r\n thirdPartyLicenses = new GPE_TextAreaInputBasic();\r\n thirdPartyLicenses->set_read_only();\r\n thirdPartyLicenses->isCodeEditor = false;\r\n thirdPartyLicenses->import_text(APP_DIRECTORY_NAME+\"third_party_licenses.txt\");\r\n thirdPartyLicenses->set_height(640);\r\n\r\n aboutPageList->barXPadding = GENERAL_GPE_GUI_PADDING;\r\n aboutPageList->barXMargin = 0;\r\n}\r\n\r\ngamePencilAboutPageResource::~gamePencilAboutPageResource()\r\n{\r\n subViewedSpace.x = GENERAL_GPE_GUI_PADDING;\r\n subViewedSpace.y = GENERAL_GPE_GUI_PADDING;\r\n subViewedSpace.w = 400;\r\n subViewedSpace.h = 400;\r\n resourceType = -2;\r\n subResouceId = -2;\r\n parentProjectName = \"\";\r\n\r\n if( aboutPageList!=NULL)\r\n {\r\n delete aboutPageList;\r\n aboutPageList = NULL;\r\n }\r\n if( pencilCredits!=NULL)\r\n {\r\n delete pencilCredits;\r\n pencilCredits = NULL;\r\n }\r\n if( pencilDescription!=NULL)\r\n {\r\n delete pencilDescription;\r\n pencilDescription = NULL;\r\n }\r\n if( pencilLicense!=NULL)\r\n {\r\n delete pencilLicense;\r\n pencilLicense = NULL;\r\n }\r\n if( thirdPartyLicenses!=NULL)\r\n {\r\n delete thirdPartyLicenses;\r\n thirdPartyLicenses = NULL;\r\n }\r\n if( pencilMissionStatement!=NULL)\r\n {\r\n delete pencilMissionStatement;\r\n pencilMissionStatement = NULL;\r\n }\r\n}\r\n\r\nbool gamePencilAboutPageResource::include_local_files( std::string pBuildDir , int buildType )\r\n{\r\n\r\n}\r\n\r\nvoid gamePencilAboutPageResource::prerender_self( )\r\n{\r\n\r\n}\r\n\r\nvoid gamePencilAboutPageResource::preprocess_self(std::string alternatePath)\r\n{\r\n\r\n}\r\n\r\nvoid gamePencilAboutPageResource::process_self(GPE_Rect * viewedSpace, GPE_Rect * cam )\r\n{\r\n viewedSpace = GPE_find_camera(viewedSpace);\r\n cam = GPE_find_camera(cam);\r\n if( viewedSpace!=NULL && aboutPageList!=NULL)\r\n {\r\n int prevTab = sideAreaPanel->get_selection();\r\n if( PANEL_GENERAL_EDITOR!=NULL )\r\n {\r\n subViewedSpace.x = 0;\r\n subViewedSpace.y = 0;\r\n subViewedSpace.w = viewedSpace->w;\r\n subViewedSpace.h = viewedSpace->h;\r\n PANEL_GENERAL_EDITOR->add_gui_element_fullsize( sideAreaPanel );\r\n PANEL_GENERAL_EDITOR->process_self();\r\n\r\n }\r\n else\r\n {\r\n sideAreaPanel->set_coords(0, 0 );\r\n sideAreaPanel->set_height( viewedSpace->h );\r\n sideAreaPanel->process_self( viewedSpace, cam );\r\n subViewedSpace.x = sideAreaPanel->get_x2pos();\r\n subViewedSpace.y = 0;\r\n subViewedSpace.w = viewedSpace->w - sideAreaPanel->get_width();\r\n subViewedSpace.h = viewedSpace->h;\r\n }\r\n\r\n if( prevTab!=sideAreaPanel->get_selection() )\r\n {\r\n aboutPageList->reset_self();\r\n }\r\n\r\n\r\n\r\n aboutPageList->set_coords(subViewedSpace.x,subViewedSpace.y );\r\n aboutPageList->set_width(subViewedSpace.w);\r\n aboutPageList->set_height(subViewedSpace.h );\r\n aboutPageList->barXPadding = GENERAL_GPE_GUI_PADDING;\r\n aboutPageList->barXMargin = subViewedSpace.w\/8;\r\n\r\n aboutPageList->clear_list();\r\n if( sideAreaPanel->get_selected_name()==\"Credits\")\r\n {\r\n aboutPageList->add_gui_element_fullsize(pencilCredits);\r\n }\r\n else if( sideAreaPanel->get_selected_name()==\"Description\" )\r\n {\r\n aboutPageList->add_gui_element_fullsize(pencilDescription);\r\n }\r\n else if( sideAreaPanel->get_selected_name()==\"License\" )\r\n {\r\n aboutPageList->add_gui_element_fullsize(pencilLicense);\r\n }\r\n else if( sideAreaPanel->get_selected_name()==\"3rd Party Licenses\" )\r\n {\r\n aboutPageList->add_gui_element_fullsize(thirdPartyLicenses);\r\n }\r\n aboutPageList->process_self(viewedSpace,cam);\r\n }\r\n}\r\n\r\nvoid gamePencilAboutPageResource::render_self(GPE_Rect * viewedSpace, GPE_Rect * cam )\r\n{\r\n viewedSpace = GPE_find_camera(viewedSpace);\r\n cam = GPE_find_camera(cam);\r\n if( cam!=NULL && viewedSpace!=NULL)\r\n {\r\n if( sideAreaPanel!=NULL && PANEL_GENERAL_EDITOR==NULL )\r\n {\r\n sideAreaPanel->render_self( viewedSpace,cam);\r\n }\r\n if( aboutPageList!=NULL )\r\n {\r\n aboutPageList->render_self( viewedSpace,cam);\r\n }\r\n }\r\n}\r\n\r\nvoid gamePencilAboutPageResource::save_resource(std::string alternatePath, int backupId)\r\n{\r\n bool usingAltSaveSource = false;\r\n isModified = false;\r\n}\r\n\r\nbool gamePencilAboutPageResource::write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn)\r\n{\r\n return true;\r\n}\r\nDelete gpe_editor_aboutpage.cpp<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pe_property.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 18:49:01 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#include \n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\n\nPE_Property::PE_Property( const Ce_id & i_rCurOwner )\n : eState(e_none),\n pCurOwner(&i_rCurOwner),\n pPE_Variable(0),\n nCurParsedType(0),\n sCurParsedName(),\n bIsOptional(false),\n aStereotypes()\n{\n pPE_Variable = new PE_Variable(nCurParsedType, sCurParsedName);\n}\n\nvoid\nPE_Property::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::n22::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);\n pPE_Variable->EstablishContacts(this,io_rRepository,o_rResult);\n}\n\nPE_Property::~PE_Property()\n{\n}\n\nvoid\nPE_Property::ProcessToken( const Token & i_rToken )\n{\n i_rToken.Trigger(*this);\n}\n\nvoid\nPE_Property::Process_Stereotype( const TokStereotype & i_rToken )\n{\n switch (i_rToken.Id())\n {\n case TokStereotype::ste_optional:\n bIsOptional = true;\n break;\n case TokStereotype::ste_readonly:\n aStereotypes.Set_Flag(Stereotypes::readonly);\n break;\n case TokStereotype::ste_bound:\n aStereotypes.Set_Flag(Stereotypes::bound);\n break;\n case TokStereotype::ste_constrained:\n aStereotypes.Set_Flag(Stereotypes::constrained);\n break;\n case TokStereotype::ste_maybeambiguous:\n aStereotypes.Set_Flag(Stereotypes::maybeambiguous);\n break;\n case TokStereotype::ste_maybedefault:\n aStereotypes.Set_Flag(Stereotypes::maybedefault);\n break;\n case TokStereotype::ste_maybevoid:\n aStereotypes.Set_Flag(Stereotypes::maybevoid);\n break;\n case TokStereotype::ste_removable:\n aStereotypes.Set_Flag(Stereotypes::removable);\n break;\n case TokStereotype::ste_transient:\n aStereotypes.Set_Flag(Stereotypes::transient);\n break;\n\n default:\n SetResult(not_done, pop_failure);\n eState = e_none;\n return;\n }\n\n SetResult(done, stay);\n}\n\nvoid\nPE_Property::Process_MetaType( const TokMetaType & i_rToken )\n{\n if (eState == e_start)\n {\n if ( i_rToken.Id() == TokMetaType::mt_property )\n {\n SetResult(done, stay);\n eState = expect_variable;\n return;\n }\n } \/\/ endif (eState == e_start)\n\n SetResult(not_done, pop_failure);\n eState = e_none;\n}\n\nvoid\nPE_Property::Process_Punctuation( const TokPunctuation & i_rToken )\n{\n switch (eState)\n {\n case e_start:\n SetResult(done, stay);\n break;\n case expect_variable:\n if (i_rToken.Id() == TokPunctuation::Semicolon)\n {\n SetResult(done, pop_success);\n eState = e_none;\n }\n else if (i_rToken.Id() == TokPunctuation::Comma)\n SetResult(done, stay);\n else\n SetResult(not_done, pop_failure);\n break;\n default:\n csv_assert(false);\n }\n}\n\nvoid\nPE_Property::Process_Default()\n{\n if (eState == expect_variable)\n {\n SetResult(not_done, push_sure, pPE_Variable.Ptr());\n eState = in_variable;\n }\n else\n SetResult(not_done, pop_failure);\n}\n\nvoid\nPE_Property::InitData()\n{\n eState = e_start;\n\n nCurParsedType = 0;\n sCurParsedName = \"\";\n\n \/\/ bIsOptional and\n \/\/ aStereotypes\n \/\/ may be preset by the PE_Service-(or PE_Interface-)parent\n \/\/ with PresetOptional() or\n \/\/ PresetStereotype()\n \/\/ - therefore it must not be set here!\n}\n\nvoid\nPE_Property::TransferData()\n{\n if (bIsOptional)\n {\n SetOptional();\n bIsOptional = false;\n }\n\n ary::idl::CodeEntity *\n pCe = 0;\n csv_assert(pCurOwner->IsValid());\n\n pCe = &Gate().Ces().Store_Property( *pCurOwner,\n sCurParsedName,\n nCurParsedType,\n aStereotypes );\n\n csv_assert(pCe != 0);\n PassDocuAt(*pCe);\n\n nCurParsedType = 0;\n sCurParsedName.clear();\n aStereotypes = Stereotypes();\n\n eState = e_none;\n}\n\nvoid\nPE_Property::ReceiveData()\n{\n eState = expect_variable;\n}\n\n\nUnoIDL_PE &\nPE_Property::MyPE()\n{\n return *this;\n}\n\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n\nINTEGRATION: CWS pchfix02 (1.3.30); FILE MERGED 2006\/09\/01 17:15:48 kaib 1.3.30.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: pe_property.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 17:10:26 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_autodoc.hxx\"\n\n\n#include \n#include \n\n\n\/\/ NOT FULLY DEFINED SERVICES\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\nnamespace csi\n{\nnamespace uidl\n{\n\n\n\nPE_Property::PE_Property( const Ce_id & i_rCurOwner )\n : eState(e_none),\n pCurOwner(&i_rCurOwner),\n pPE_Variable(0),\n nCurParsedType(0),\n sCurParsedName(),\n bIsOptional(false),\n aStereotypes()\n{\n pPE_Variable = new PE_Variable(nCurParsedType, sCurParsedName);\n}\n\nvoid\nPE_Property::EstablishContacts( UnoIDL_PE * io_pParentPE,\n ary::n22::Repository & io_rRepository,\n TokenProcessing_Result & o_rResult )\n{\n UnoIDL_PE::EstablishContacts(io_pParentPE,io_rRepository,o_rResult);\n pPE_Variable->EstablishContacts(this,io_rRepository,o_rResult);\n}\n\nPE_Property::~PE_Property()\n{\n}\n\nvoid\nPE_Property::ProcessToken( const Token & i_rToken )\n{\n i_rToken.Trigger(*this);\n}\n\nvoid\nPE_Property::Process_Stereotype( const TokStereotype & i_rToken )\n{\n switch (i_rToken.Id())\n {\n case TokStereotype::ste_optional:\n bIsOptional = true;\n break;\n case TokStereotype::ste_readonly:\n aStereotypes.Set_Flag(Stereotypes::readonly);\n break;\n case TokStereotype::ste_bound:\n aStereotypes.Set_Flag(Stereotypes::bound);\n break;\n case TokStereotype::ste_constrained:\n aStereotypes.Set_Flag(Stereotypes::constrained);\n break;\n case TokStereotype::ste_maybeambiguous:\n aStereotypes.Set_Flag(Stereotypes::maybeambiguous);\n break;\n case TokStereotype::ste_maybedefault:\n aStereotypes.Set_Flag(Stereotypes::maybedefault);\n break;\n case TokStereotype::ste_maybevoid:\n aStereotypes.Set_Flag(Stereotypes::maybevoid);\n break;\n case TokStereotype::ste_removable:\n aStereotypes.Set_Flag(Stereotypes::removable);\n break;\n case TokStereotype::ste_transient:\n aStereotypes.Set_Flag(Stereotypes::transient);\n break;\n\n default:\n SetResult(not_done, pop_failure);\n eState = e_none;\n return;\n }\n\n SetResult(done, stay);\n}\n\nvoid\nPE_Property::Process_MetaType( const TokMetaType & i_rToken )\n{\n if (eState == e_start)\n {\n if ( i_rToken.Id() == TokMetaType::mt_property )\n {\n SetResult(done, stay);\n eState = expect_variable;\n return;\n }\n } \/\/ endif (eState == e_start)\n\n SetResult(not_done, pop_failure);\n eState = e_none;\n}\n\nvoid\nPE_Property::Process_Punctuation( const TokPunctuation & i_rToken )\n{\n switch (eState)\n {\n case e_start:\n SetResult(done, stay);\n break;\n case expect_variable:\n if (i_rToken.Id() == TokPunctuation::Semicolon)\n {\n SetResult(done, pop_success);\n eState = e_none;\n }\n else if (i_rToken.Id() == TokPunctuation::Comma)\n SetResult(done, stay);\n else\n SetResult(not_done, pop_failure);\n break;\n default:\n csv_assert(false);\n }\n}\n\nvoid\nPE_Property::Process_Default()\n{\n if (eState == expect_variable)\n {\n SetResult(not_done, push_sure, pPE_Variable.Ptr());\n eState = in_variable;\n }\n else\n SetResult(not_done, pop_failure);\n}\n\nvoid\nPE_Property::InitData()\n{\n eState = e_start;\n\n nCurParsedType = 0;\n sCurParsedName = \"\";\n\n \/\/ bIsOptional and\n \/\/ aStereotypes\n \/\/ may be preset by the PE_Service-(or PE_Interface-)parent\n \/\/ with PresetOptional() or\n \/\/ PresetStereotype()\n \/\/ - therefore it must not be set here!\n}\n\nvoid\nPE_Property::TransferData()\n{\n if (bIsOptional)\n {\n SetOptional();\n bIsOptional = false;\n }\n\n ary::idl::CodeEntity *\n pCe = 0;\n csv_assert(pCurOwner->IsValid());\n\n pCe = &Gate().Ces().Store_Property( *pCurOwner,\n sCurParsedName,\n nCurParsedType,\n aStereotypes );\n\n csv_assert(pCe != 0);\n PassDocuAt(*pCe);\n\n nCurParsedType = 0;\n sCurParsedName.clear();\n aStereotypes = Stereotypes();\n\n eState = e_none;\n}\n\nvoid\nPE_Property::ReceiveData()\n{\n eState = expect_variable;\n}\n\n\nUnoIDL_PE &\nPE_Property::MyPE()\n{\n return *this;\n}\n\n\n} \/\/ namespace uidl\n} \/\/ namespace csi\n\n<|endoftext|>"} {"text":"\/\/==- DeadStores.cpp - Check for stores to dead variables --------*- C++ -*-==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines a DeadStores, a flow-sensitive checker that looks for\n\/\/ stores to variables that are no longer live.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtVisitor.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/Analysis\/PathSensitive\/GRExprEngine.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\nusing namespace clang;\n\nnamespace {\n\nclass VISIBILITY_HIDDEN DeadStoreObs : public LiveVariables::ObserverTy {\n ASTContext &Ctx;\n BugReporter& BR;\n ParentMap& Parents;\n \n enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };\n \npublic:\n DeadStoreObs(ASTContext &ctx, BugReporter& br, ParentMap& parents)\n : Ctx(ctx), BR(br), Parents(parents) {}\n \n virtual ~DeadStoreObs() {}\n \n void Report(VarDecl* V, DeadStoreKind dsk, SourceLocation L, SourceRange R) {\n\n std::string name(V->getName());\n \n const char* BugType = 0;\n std::string msg;\n \n switch (dsk) {\n default:\n assert(false && \"Impossible dead store type.\");\n \n case DeadInit:\n BugType = \"dead initialization\";\n msg = \"Value stored to '\" + name +\n \"' during its initialization is never read\";\n break;\n \n case DeadIncrement:\n BugType = \"dead increment\";\n case Standard:\n if (!BugType) BugType = \"dead store\";\n msg = \"Value stored to '\" + name + \"' is never read\";\n break;\n \n case Enclosing:\n BugType = \"dead store\";\n msg = \"Although the value stored to '\" + name +\n \"' is used in the enclosing expression, the value is never actually\"\n \" read from '\" + name + \"'\";\n break;\n }\n \n BR.EmitBasicReport(BugType, msg.c_str(), L, R); \n }\n \n void CheckVarDecl(VarDecl* VD, Expr* Ex, Expr* Val,\n DeadStoreKind dsk,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n\n if (VD->hasLocalStorage() && !Live(VD, AD) && !VD->getAttr())\n Report(VD, dsk, Ex->getSourceRange().getBegin(),\n Val->getSourceRange()); \n }\n \n void CheckDeclRef(DeclRefExpr* DR, Expr* Val, DeadStoreKind dsk,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n \n if (VarDecl* VD = dyn_cast(DR->getDecl()))\n CheckVarDecl(VD, DR, Val, dsk, AD, Live);\n }\n \n bool isIncrement(VarDecl* VD, BinaryOperator* B) {\n if (B->isCompoundAssignmentOp())\n return true;\n \n Expr* RHS = B->getRHS()->IgnoreParenCasts();\n BinaryOperator* BRHS = dyn_cast(RHS);\n \n if (!BRHS)\n return false;\n \n DeclRefExpr *DR;\n \n if ((DR = dyn_cast(BRHS->getLHS()->IgnoreParenCasts())))\n if (DR->getDecl() == VD)\n return true;\n \n if ((DR = dyn_cast(BRHS->getRHS()->IgnoreParenCasts())))\n if (DR->getDecl() == VD)\n return true;\n \n return false;\n }\n \n virtual void ObserveStmt(Stmt* S,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n \n \/\/ Skip statements in macros.\n if (S->getLocStart().isMacroID())\n return;\n \n if (BinaryOperator* B = dyn_cast(S)) { \n if (!B->isAssignmentOp()) return; \/\/ Skip non-assignments.\n \n if (DeclRefExpr* DR = dyn_cast(B->getLHS()))\n if (VarDecl *VD = dyn_cast(DR->getDecl())) {\n \n \/\/ Special case: check for assigning null to a pointer. This\n \/\/ is a common form of defensive programming.\n \/\/ FIXME: Make this optional?\n \n Expr* Val = B->getRHS();\n llvm::APSInt Result(Ctx.getTypeSize(Val->getType()));\n \n if (VD->getType()->isPointerType() &&\n Val->IgnoreParenCasts()->isIntegerConstantExpr(Result, Ctx, 0))\n if (Result == 0)\n return;\n\n DeadStoreKind dsk = \n Parents.isSubExpr(B)\n ? Enclosing \n : (isIncrement(VD,B) ? DeadIncrement : Standard);\n \n CheckVarDecl(VD, DR, Val, dsk, AD, Live);\n } \n }\n else if (UnaryOperator* U = dyn_cast(S)) {\n if (!U->isIncrementOp())\n return;\n\n Expr *Ex = U->getSubExpr()->IgnoreParenCasts();\n \n if (DeclRefExpr* DR = dyn_cast(Ex))\n CheckDeclRef(DR, U, DeadIncrement, AD, Live);\n } \n else if (DeclStmt* DS = dyn_cast(S))\n \/\/ Iterate through the decls. Warn if any initializers are complex\n \/\/ expressions that are not live (never used).\n for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();\n DI != DE; ++DI) {\n \n VarDecl* V = dyn_cast(*DI);\n\n if (!V)\n continue;\n \n if (V->hasLocalStorage())\n if (Expr* E = V->getInit()) {\n \/\/ A dead initialization is a variable that is dead after it\n \/\/ is initialized. We don't flag warnings for those variables\n \/\/ marked 'unused'.\n if (!Live(V, AD) && V->getAttr() == 0) {\n \/\/ Special case: check for initializations with constants.\n \/\/\n \/\/ e.g. : int x = 0;\n \/\/\n \/\/ If x is EVER assigned a new value later, don't issue\n \/\/ a warning. This is because such initialization can be\n \/\/ due to defensive programming.\n if (!E->isConstantExpr(Ctx,NULL))\n Report(V, DeadInit, V->getLocation(), E->getSourceRange());\n }\n }\n }\n }\n};\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Driver function to invoke the Dead-Stores checker on a CFG.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid clang::CheckDeadStores(LiveVariables& L, BugReporter& BR) { \n DeadStoreObs A(BR.getContext(), BR, BR.getParentMap());\n L.runOnAllBlocks(*BR.getCFG(), &A);\n}\nDon't use Expr::isIntegerConstantExpr just to check if a pointer value is initialize to NULL.\/\/==- DeadStores.cpp - Check for stores to dead variables --------*- C++ -*-==\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines a DeadStores, a flow-sensitive checker that looks for\n\/\/ stores to variables that are no longer live.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/Analysis\/LocalCheckers.h\"\n#include \"clang\/Analysis\/Analyses\/LiveVariables.h\"\n#include \"clang\/Analysis\/Visitors\/CFGRecStmtVisitor.h\"\n#include \"clang\/Analysis\/PathSensitive\/BugReporter.h\"\n#include \"clang\/Analysis\/PathSensitive\/GRExprEngine.h\"\n#include \"clang\/Basic\/Diagnostic.h\"\n#include \"clang\/AST\/ASTContext.h\"\n#include \"clang\/AST\/ParentMap.h\"\n#include \"llvm\/Support\/Compiler.h\"\n\nusing namespace clang;\n\nnamespace {\n\nclass VISIBILITY_HIDDEN DeadStoreObs : public LiveVariables::ObserverTy {\n ASTContext &Ctx;\n BugReporter& BR;\n ParentMap& Parents;\n \n enum DeadStoreKind { Standard, Enclosing, DeadIncrement, DeadInit };\n \npublic:\n DeadStoreObs(ASTContext &ctx, BugReporter& br, ParentMap& parents)\n : Ctx(ctx), BR(br), Parents(parents) {}\n \n virtual ~DeadStoreObs() {}\n \n void Report(VarDecl* V, DeadStoreKind dsk, SourceLocation L, SourceRange R) {\n\n std::string name(V->getName());\n \n const char* BugType = 0;\n std::string msg;\n \n switch (dsk) {\n default:\n assert(false && \"Impossible dead store type.\");\n \n case DeadInit:\n BugType = \"dead initialization\";\n msg = \"Value stored to '\" + name +\n \"' during its initialization is never read\";\n break;\n \n case DeadIncrement:\n BugType = \"dead increment\";\n case Standard:\n if (!BugType) BugType = \"dead store\";\n msg = \"Value stored to '\" + name + \"' is never read\";\n break;\n \n case Enclosing:\n BugType = \"dead store\";\n msg = \"Although the value stored to '\" + name +\n \"' is used in the enclosing expression, the value is never actually\"\n \" read from '\" + name + \"'\";\n break;\n }\n \n BR.EmitBasicReport(BugType, msg.c_str(), L, R); \n }\n \n void CheckVarDecl(VarDecl* VD, Expr* Ex, Expr* Val,\n DeadStoreKind dsk,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n\n if (VD->hasLocalStorage() && !Live(VD, AD) && !VD->getAttr())\n Report(VD, dsk, Ex->getSourceRange().getBegin(),\n Val->getSourceRange()); \n }\n \n void CheckDeclRef(DeclRefExpr* DR, Expr* Val, DeadStoreKind dsk,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n \n if (VarDecl* VD = dyn_cast(DR->getDecl()))\n CheckVarDecl(VD, DR, Val, dsk, AD, Live);\n }\n \n bool isIncrement(VarDecl* VD, BinaryOperator* B) {\n if (B->isCompoundAssignmentOp())\n return true;\n \n Expr* RHS = B->getRHS()->IgnoreParenCasts();\n BinaryOperator* BRHS = dyn_cast(RHS);\n \n if (!BRHS)\n return false;\n \n DeclRefExpr *DR;\n \n if ((DR = dyn_cast(BRHS->getLHS()->IgnoreParenCasts())))\n if (DR->getDecl() == VD)\n return true;\n \n if ((DR = dyn_cast(BRHS->getRHS()->IgnoreParenCasts())))\n if (DR->getDecl() == VD)\n return true;\n \n return false;\n }\n \n virtual void ObserveStmt(Stmt* S,\n const LiveVariables::AnalysisDataTy& AD,\n const LiveVariables::ValTy& Live) {\n \n \/\/ Skip statements in macros.\n if (S->getLocStart().isMacroID())\n return;\n \n if (BinaryOperator* B = dyn_cast(S)) { \n if (!B->isAssignmentOp()) return; \/\/ Skip non-assignments.\n \n if (DeclRefExpr* DR = dyn_cast(B->getLHS()))\n if (VarDecl *VD = dyn_cast(DR->getDecl())) {\n \/\/ Special case: check for assigning null to a pointer.\n \/\/ This is a common form of defensive programming. \n if (VD->getType()->isPointerType()) {\n if (IntegerLiteral* L =\n dyn_cast(B->getRHS()->IgnoreParenCasts()))\n if (L->getValue() == 0)\n return;\n }\n\n DeadStoreKind dsk = \n Parents.isSubExpr(B)\n ? Enclosing \n : (isIncrement(VD,B) ? DeadIncrement : Standard);\n \n CheckVarDecl(VD, DR, B->getRHS(), dsk, AD, Live);\n } \n }\n else if (UnaryOperator* U = dyn_cast(S)) {\n if (!U->isIncrementOp())\n return;\n\n Expr *Ex = U->getSubExpr()->IgnoreParenCasts();\n \n if (DeclRefExpr* DR = dyn_cast(Ex))\n CheckDeclRef(DR, U, DeadIncrement, AD, Live);\n } \n else if (DeclStmt* DS = dyn_cast(S))\n \/\/ Iterate through the decls. Warn if any initializers are complex\n \/\/ expressions that are not live (never used).\n for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();\n DI != DE; ++DI) {\n \n VarDecl* V = dyn_cast(*DI);\n\n if (!V)\n continue;\n \n if (V->hasLocalStorage())\n if (Expr* E = V->getInit()) {\n \/\/ A dead initialization is a variable that is dead after it\n \/\/ is initialized. We don't flag warnings for those variables\n \/\/ marked 'unused'.\n if (!Live(V, AD) && V->getAttr() == 0) {\n \/\/ Special case: check for initializations with constants.\n \/\/\n \/\/ e.g. : int x = 0;\n \/\/\n \/\/ If x is EVER assigned a new value later, don't issue\n \/\/ a warning. This is because such initialization can be\n \/\/ due to defensive programming.\n if (!E->isConstantExpr(Ctx,NULL))\n Report(V, DeadInit, V->getLocation(), E->getSourceRange());\n }\n }\n }\n }\n};\n \n} \/\/ end anonymous namespace\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Driver function to invoke the Dead-Stores checker on a CFG.\n\/\/===----------------------------------------------------------------------===\/\/\n\nvoid clang::CheckDeadStores(LiveVariables& L, BugReporter& BR) { \n DeadStoreObs A(BR.getContext(), BR, BR.getParentMap());\n L.runOnAllBlocks(*BR.getCFG(), &A);\n}\n<|endoftext|>"} {"text":"\/*\\file\n *\n * \\brief Functionality for getting experimental\/empirical atomic data (source)\n*\/\n\n\n#include \n\n#include \"pulsar\/system\/AtomicInfo.hpp\"\n#include \"pulsar\/system\/AtomicInfo_LUT.hpp\"\n#include \"pulsar\/exception\/Exceptions.hpp\"\n\nnamespace pulsar{\nnamespace system {\n\n\/\/ global LUT:\n\/\/ Maps Z to symbol\nusing lut::atomic_Z_sym_;\n\n\/\/ Maps symbol to Z\nusing lut::atomic_sym_Z_;\n\n\/\/ Maps Z to data\nusing lut::atomic_Z_data_;\n\n\nint AtomicZNumberFromSym(const std::string & sym)\n{\n if(atomic_sym_Z_.count(sym))\n return atomic_sym_Z_.at(sym);\n else\n throw exception::SystemException(\"No Z number for this atomic symbol\",\n \"symbol\", sym);\n}\n\n\n\nstd::string AtomicSymFromZ(int Z)\n{\n if(atomic_Z_sym_.count(Z))\n return atomic_Z_sym_.at(Z);\n else\n throw exception::SystemException(\"No symbol for this Z number\",\n \"Z\", Z);\n}\n\n\n\nconst AtomicData & AtomicInfoFromZ(int Z)\n{\n if(atomic_Z_data_.count(Z))\n return atomic_Z_data_.at(Z);\n else\n throw exception::SystemException(\"No atomic data for this Z number\",\n \"Z\", Z);\n}\n\n\n\nconst AtomicData & AtomicInfoFromSym(const std::string & sym)\n{\n return AtomicInfoFromZ(AtomicZNumberFromSym(sym));\n}\n\n\n\nconst IsotopeData & IsotopeInfoFromZ(int Z, int isonum)\n{\n AtomicData ad = AtomicInfoFromZ(Z);\n \n for(const auto & it : ad.isotopes)\n if(it.isonum == isonum)\n return it;\n\n throw exception::SystemException(\"No isotope data for this Z and isotope number\",\n \"Z\", Z,\n \"isotope\", isonum);\n}\n\n\n\nconst IsotopeData & IsotopeInfoFromSym(const std::string & sym, int isonum)\n{\n return IsotopeInfoFromZ(AtomicZNumberFromSym(sym), isonum); \n}\n\n\nint MostCommonIsotopeFromZ(int Z)\n{\n const AtomicData & ad = AtomicInfoFromZ(Z);\n if(ad.isotopes.size() == 0)\n throw exception::SystemException(\"Developer error: No isotopes for this Z number?\",\n \"Z\", Z);\n\n auto maxit = std::max_element(ad.isotopes.begin(), ad.isotopes.end(),\n [](const IsotopeData & idat1, const IsotopeData & idat2)\n { return idat1.abund < idat2.abund; }\n );\n\n return maxit->isonum;\n}\n\nint MostCommonIsotopeFromSym(const std::string & sym)\n{\n return MostCommonIsotopeFromZ(AtomicZNumberFromSym(sym));\n}\n \n\ndouble AtomicMassFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).mass;\n}\n\n\n\ndouble AtomicMassFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).mass;\n}\n\n\n\ndouble IsotopeMassFromZ(int Z, int isonum)\n{\n return IsotopeInfoFromZ(Z, isonum).mass;\n}\n\n\n\ndouble IsotopeMassFromSym(const std::string & sym, int isonum)\n{\n return IsotopeInfoFromSym(sym, isonum).mass;\n}\n\n\n\nstd::string AtomicNameFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).name;\n}\n\n\n\nstd::string AtomicNameFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).name;\n}\n\n\n\nint AtomicMultiplicityFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).multiplicity;\n}\n\n\n\nint AtomicMultiplicityFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).multiplicity;\n}\n\ndouble CovRadiusFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).covradius;\n}\n\ndouble CovRadiusFroSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).covradius;\n}\n\ndouble VDWRadiusFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).vdwradius;\n}\n\ndouble VDWRadiusFroSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).vdwradius;\n}\n\n} \/\/ closing namespace system\n} \/\/ closing namespace pulsar\n\nFix returning of local variable\/*\\file\n *\n * \\brief Functionality for getting experimental\/empirical atomic data (source)\n*\/\n\n\n#include \n\n#include \"pulsar\/system\/AtomicInfo.hpp\"\n#include \"pulsar\/system\/AtomicInfo_LUT.hpp\"\n#include \"pulsar\/exception\/Exceptions.hpp\"\n\nnamespace pulsar{\nnamespace system {\n\n\/\/ global LUT:\n\/\/ Maps Z to symbol\nusing lut::atomic_Z_sym_;\n\n\/\/ Maps symbol to Z\nusing lut::atomic_sym_Z_;\n\n\/\/ Maps Z to data\nusing lut::atomic_Z_data_;\n\n\nint AtomicZNumberFromSym(const std::string & sym)\n{\n if(atomic_sym_Z_.count(sym))\n return atomic_sym_Z_.at(sym);\n else\n throw exception::SystemException(\"No Z number for this atomic symbol\",\n \"symbol\", sym);\n}\n\n\n\nstd::string AtomicSymFromZ(int Z)\n{\n if(atomic_Z_sym_.count(Z))\n return atomic_Z_sym_.at(Z);\n else\n throw exception::SystemException(\"No symbol for this Z number\",\n \"Z\", Z);\n}\n\n\n\nconst AtomicData & AtomicInfoFromZ(int Z)\n{\n if(atomic_Z_data_.count(Z))\n return atomic_Z_data_.at(Z);\n else\n throw exception::SystemException(\"No atomic data for this Z number\",\n \"Z\", Z);\n}\n\n\n\nconst AtomicData & AtomicInfoFromSym(const std::string & sym)\n{\n return AtomicInfoFromZ(AtomicZNumberFromSym(sym));\n}\n\n\n\nconst IsotopeData & IsotopeInfoFromZ(int Z, int isonum)\n{\n const AtomicData & ad = AtomicInfoFromZ(Z);\n \n for(const auto & it : ad.isotopes)\n if(it.isonum == isonum)\n return it;\n\n throw exception::SystemException(\"No isotope data for this Z and isotope number\",\n \"Z\", Z,\n \"isotope\", isonum);\n}\n\n\n\nconst IsotopeData & IsotopeInfoFromSym(const std::string & sym, int isonum)\n{\n return IsotopeInfoFromZ(AtomicZNumberFromSym(sym), isonum); \n}\n\n\nint MostCommonIsotopeFromZ(int Z)\n{\n const AtomicData & ad = AtomicInfoFromZ(Z);\n if(ad.isotopes.size() == 0)\n throw exception::SystemException(\"Developer error: No isotopes for this Z number?\",\n \"Z\", Z);\n\n auto maxit = std::max_element(ad.isotopes.begin(), ad.isotopes.end(),\n [](const IsotopeData & idat1, const IsotopeData & idat2)\n { return idat1.abund < idat2.abund; }\n );\n\n return maxit->isonum;\n}\n\nint MostCommonIsotopeFromSym(const std::string & sym)\n{\n return MostCommonIsotopeFromZ(AtomicZNumberFromSym(sym));\n}\n \n\ndouble AtomicMassFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).mass;\n}\n\n\n\ndouble AtomicMassFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).mass;\n}\n\n\n\ndouble IsotopeMassFromZ(int Z, int isonum)\n{\n return IsotopeInfoFromZ(Z, isonum).mass;\n}\n\n\n\ndouble IsotopeMassFromSym(const std::string & sym, int isonum)\n{\n return IsotopeInfoFromSym(sym, isonum).mass;\n}\n\n\n\nstd::string AtomicNameFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).name;\n}\n\n\n\nstd::string AtomicNameFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).name;\n}\n\n\n\nint AtomicMultiplicityFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).multiplicity;\n}\n\n\n\nint AtomicMultiplicityFromSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).multiplicity;\n}\n\ndouble CovRadiusFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).covradius;\n}\n\ndouble CovRadiusFroSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).covradius;\n}\n\ndouble VDWRadiusFromZ(int Z)\n{\n return AtomicInfoFromZ(Z).vdwradius;\n}\n\ndouble VDWRadiusFroSym(const std::string & sym)\n{\n return AtomicInfoFromSym(sym).vdwradius;\n}\n\n} \/\/ closing namespace system\n} \/\/ closing namespace pulsar\n\n<|endoftext|>"} {"text":"\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\n\nstd::map ProcessorNetworkEvaluator::processorNetworkEvaluators_;\n\nProcessorNetworkEvaluator::ProcessorNetworkEvaluator(ProcessorNetwork* processorNetwork)\n : processorNetwork_(processorNetwork)\n , evaulationQueued_(false)\n , evaluationDisabled_(false)\n , processorStatesDirty_(true) {\n\n initializeNetwork();\n \n ivwAssert(processorNetworkEvaluators_.find(processorNetwork) == processorNetworkEvaluators_.end() ,\n \"A ProcessorNetworkEvaluator for the given ProcessorNetwork is already created\");\n processorNetworkEvaluators_[processorNetwork] = this;\n processorNetwork_->addObserver(this);\n}\n\nProcessorNetworkEvaluator::~ProcessorNetworkEvaluator() {\n std::map::iterator it = processorNetworkEvaluators_.find(processorNetwork_);\n\n if (it != processorNetworkEvaluators_.end())\n processorNetworkEvaluators_.erase(it);\n}\n\nvoid ProcessorNetworkEvaluator::topologyUpdated() {\n processorStatesDirty_ = true;\n}\n\nvoid ProcessorNetworkEvaluator::initializeNetwork() {\n ivwAssert(processorNetwork_!=0, \"processorNetwork_ not initialized, call setProcessorNetwork()\");\n \/\/ initialize network\n std::vector processors = processorNetwork_->getProcessors();\n\n for (size_t i=0; iisInitialized())\n processors[i]->initialize();\n}\n\nvoid ProcessorNetworkEvaluator::saveSnapshotAllCanvases(std::string dir, std::string default_name, std::string ext) {\n std::vector pv = processorNetwork_->getProcessorsByType();\n int i = 0;\n\n for (std::vector::iterator it = pv.begin(); it != pv.end(); it++) {\n std::stringstream ss;\n\n if (default_name == \"\" || default_name == \"UPN\")\n ss << (*it)->getIdentifier();\n else\n ss << default_name << i+1;\n\n std::string path(dir + ss.str() + ext);\n LogInfo(\"Saving canvas to: \" + path);\n (*it)->saveImageLayer(path);\n ++i;\n }\n}\n\nvoid ProcessorNetworkEvaluator::setProcessorVisited(Processor* processor, bool visited) {\n ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end())\n it->second.visited = visited;\n}\n\nbool ProcessorNetworkEvaluator::hasBeenVisited(Processor* processor) const {\n const_ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end())\n return it->second.visited;\n else\n return false;\n}\n\nvoid ProcessorNetworkEvaluator::setPropertyVisited(Property* property, bool visited) {\n PropertyMapIt it = propertiesVisited_.find(property);\n if (it != propertiesVisited_.end())\n it->second.visited = visited;\n}\n\nbool ProcessorNetworkEvaluator::hasBeenVisited(Property* property) const {\n const_PropertyMapIt it = propertiesVisited_.find(property);\n if (it != propertiesVisited_.end())\n return it->second.visited;\n else\n return false;\n}\n\nconst ProcessorNetworkEvaluator::ProcessorList& \nProcessorNetworkEvaluator::getStoredPredecessors(Processor* processor) const {\n const_ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end()) {\n return it->second.pred;\n }\n else {\n \/\/ processor not found, return reference to empty list of dummy element\n return processorStates_.find(nullptr)->second.pred;\n }\n}\n\nProcessorNetworkEvaluator::ProcessorList ProcessorNetworkEvaluator::getDirectPredecessors(Processor* processor, Event* event) const {\n ProcessorList predecessors;\n const std::vector& inports = processor->getInports(event);\n\n for (std::vector::const_iterator portIt = inports.begin(), portItEnd = inports.end(); portIt!=portItEnd; ++portIt) {\n if (!(*portIt)->isConnected())\n continue;\n\n const std::vector& connectedOutPorts = (*portIt)->getConnectedOutports();\n\n for (std::vector::const_iterator connectedPortIt = connectedOutPorts.begin(),\n connectedPortItEnd = connectedOutPorts.end();\n connectedPortIt!=connectedPortItEnd; ++connectedPortIt)\n if(*connectedPortIt)\n predecessors.insert((*connectedPortIt)->getProcessor());\n }\n\n return predecessors;\n}\n\nvoid ProcessorNetworkEvaluator::traversePredecessors(Processor* processor) {\n if (!hasBeenVisited(processor)) {\n setProcessorVisited(processor);\n \n const ProcessorList &directPredecessors = getStoredPredecessors(processor);\n ProcessorList::const_iterator it = directPredecessors.begin();\n while (it != directPredecessors.end()) {\n traversePredecessors(*it);\n ++it;\n }\n processorsSorted_.push_back(processor);\n }\n}\n\nvoid ProcessorNetworkEvaluator::determineProcessingOrder() {\n std::vector processors = processorNetwork_->getProcessors();\n std::vector endProcessors;\n\n for (size_t i=0; iisEndProcessor())\n endProcessors.push_back(processors[i]);\n\n \/\/ perform topological sorting and store processor order\n \/\/ in processorsSorted_\n processorsSorted_.clear();\n resetProcessorVisitedStates();\n\n for (size_t i=0; i processors = processorNetwork_->getProcessors();\n std::vector endProcessors;\n\n processorStates_.clear();\n \/\/ insert dummy processor to be able to return a reference to an \n \/\/ empty predecessor list, if a processor does not exist (getStoredPredecessors())\n processorStates_.insert(ProcMapPair(nullptr, ProcessorState()));\n\n \/\/ update all processor states, i.e. collecting predecessors\n std::vector::const_iterator it = processors.begin();\n while (it != processors.end()) {\n \/\/ register processor in global state map\n if (!processorStates_.insert(ProcMapPair(*it, ProcessorState(getDirectPredecessors(*it)))).second)\n LogError(\"Processor State was already registered.\");\n\n if ((*it)->isEndProcessor())\n endProcessors.push_back(*it);\n ++it;\n }\n\n \/\/ perform topological sorting and store processor order in processorsSorted_\n processorsSorted_.clear();\n it = endProcessors.begin();\n while (it != endProcessors.end()) {\n traversePredecessors(*it);\n ++it;\n }\n}\n\nvoid ProcessorNetworkEvaluator::resetProcessorVisitedStates() {\n ProcMapIt it = processorStates_.begin();\n while (it != processorStates_.end()) {\n it->second.visited = false;\n ++it;\n }\n}\n\nvoid ProcessorNetworkEvaluator::propagateInteractionEventImpl(Processor* processor,\n InteractionEvent* event) {\n if (!hasBeenVisited(processor)) {\n processor->invokeInteractionEvent(event);\n setProcessorVisited(processor);\n if (event->hasBeenUsed()) return;\n\n ProcessorList directPredecessors = getDirectPredecessors(processor, event);\n\n for (ProcessorList::iterator it = directPredecessors.begin(),\n itEnd = directPredecessors.end();\n it != itEnd; ++it) { \n propagateInteractionEventImpl(*it, event);\n if (event->hasBeenUsed()) return;\n }\n }\n}\n\nvoid ProcessorNetworkEvaluator::propagateInteractionEvent(Processor* processor,\n InteractionEvent* event) {\n resetProcessorVisitedStates();\n processorNetwork_->lock();\n propagateInteractionEventImpl(processor, event);\n processorNetwork_->unlock();\n}\n\nbool ProcessorNetworkEvaluator::isPortConnectedToProcessor(Port* port, Processor* processor) {\n bool isConnected = false;\n std::vector portConnections = processorNetwork_->getConnections();\n std::vector outports = processor->getOutports();\n\n for (size_t i=0; igetOutport();\n\n if (curOutport == outports[i]) {\n const Port* connectedInport = portConnections[j]->getInport();\n\n if (connectedInport == port) {\n isConnected = true;\n break;\n }\n }\n }\n }\n\n if (isConnected) return isConnected;\n\n std::vector inports = processor->getInports();\n\n for (size_t i=0; igetInport();\n\n if (curInport == inports[i]) {\n const Outport* connectedOutport = portConnections[j]->getOutport();\n\n if (connectedOutport == port) {\n isConnected = true;\n break;\n }\n }\n }\n }\n\n return isConnected;\n}\n\n\nvoid ProcessorNetworkEvaluator::onProcessorInvalidationEnd(Processor* p) {\n processorNetwork_->onProcessorInvalidationEnd(p);\n p->ProcessorObservable::removeObserver(this);\n\n if (evaulationQueued_) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nvoid ProcessorNetworkEvaluator::onProcessorNetworkEvaluateRequest() {\n \/\/Direct request, thus we don't want to queue the evaluation anymore\n if (evaulationQueued_)\n evaulationQueued_ = false;\n\n requestEvaluate();\n}\n\nvoid ProcessorNetworkEvaluator::onProcessorNetworkUnlocked() {\n \/\/ Only evaluate if an evaluation is queued or the network is modified\n if (evaulationQueued_ || processorNetwork_->isModified()) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nvoid ProcessorNetworkEvaluator::disableEvaluation() {\n evaluationDisabled_ = true;\n}\n\nvoid ProcessorNetworkEvaluator::enableEvaluation() {\n evaluationDisabled_ = false;\n\n if (evaulationQueued_) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nProcessorNetworkEvaluator*\nProcessorNetworkEvaluator::getProcessorNetworkEvaluatorForProcessorNetwork(\n ProcessorNetwork* network) {\n std::map::iterator it =\n processorNetworkEvaluators_.find(network);\n\n if (it == processorNetworkEvaluators_.end()) return new ProcessorNetworkEvaluator(network);\n\n return it->second;\n}\n\nvoid ProcessorNetworkEvaluator::requestEvaluate() {\n \/\/ evaluation has been triggered but is currently queued\n \/\/ requestEvaluate needs to be called with evaulationQueued_ false to continue.\n if (evaulationQueued_) return;\n\n \/\/ wait for linking to finish\n if (processorNetwork_->isLinking()) {\n evaulationQueued_ = true;\n return;\n }\n\n \/\/ evaluation disabled\n if (processorNetwork_->islocked() || evaluationDisabled_) {\n evaulationQueued_ = true;\n return;\n }\n\n \/\/ wait for invalidation to finish before evaluating\n if (processorNetwork_->isInvalidating()) {\n evaulationQueued_ = true;\n return;\n }\n\n evaulationQueued_ = false;\n \/\/if we haven't returned yet, perform evaluation of the network\n evaluate();\n}\n\nvoid ProcessorNetworkEvaluator::evaluate() {\n \/\/ lock processor network to avoid concurrent evaluation\n processorNetwork_->lock();\n RenderContext::getPtr()->activateDefaultRenderContext();\n\n \/\/ if the processor network has changed determine the new processor order\n if (processorNetwork_->isModified()) {\n initializeNetwork();\n processorNetwork_->setModified(false);\n processorStatesDirty_ = true;\n }\n\n if (processorStatesDirty_) {\n \/\/ network topology has changed, update internal processor states\n updateProcessorStates();\n }\n\n for (auto processor : processorsSorted_) {\n if (!processor->isValid()) {\n if (processor->isReady()) {\n \/\/ re-initialize resources (e.g., shaders) if necessary\n if (processor->getInvalidationLevel() >= INVALID_RESOURCES)\n processor->initializeResources();\n\n \/\/ call onChange for all invalid inports\n for (auto inport : processor->getInports()) {\n inport->callOnChangeIfChanged();\n }\n\n #if IVW_PROFILING\n processor->notifyObserversAboutToProcess(processor);\n #endif\n\n try {\n \/\/ do the actual processing\n processor->process();\n } catch (Exception& e) {\n LogError(e.getMessage());\n }\n \/\/ set processor as valid\n processor->setValid();\n\n #if IVW_PROFILING\n processor->notifyObserversFinishedProcess(processor);\n #endif\n } else {\n processor->doIfNotReady();\n }\n }\n }\n resetProcessorVisitedStates();\n\n \/\/ unlock processor network to allow next evaluation\n processorNetwork_->unlock();\n}\n\n} \/\/ namespace\nCore: ProcessorNetworkEvaluator, catch exceptions from initializeResources and callOnChangeIfChanged\/*********************************************************************************\n *\n * Inviwo - Interactive Visualization Workshop\n *\n * Copyright (c) 2012-2015 Inviwo Foundation\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n * \n *********************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace inviwo {\n\n\nstd::map ProcessorNetworkEvaluator::processorNetworkEvaluators_;\n\nProcessorNetworkEvaluator::ProcessorNetworkEvaluator(ProcessorNetwork* processorNetwork)\n : processorNetwork_(processorNetwork)\n , evaulationQueued_(false)\n , evaluationDisabled_(false)\n , processorStatesDirty_(true) {\n\n initializeNetwork();\n \n ivwAssert(processorNetworkEvaluators_.find(processorNetwork) == processorNetworkEvaluators_.end() ,\n \"A ProcessorNetworkEvaluator for the given ProcessorNetwork is already created\");\n processorNetworkEvaluators_[processorNetwork] = this;\n processorNetwork_->addObserver(this);\n}\n\nProcessorNetworkEvaluator::~ProcessorNetworkEvaluator() {\n std::map::iterator it = processorNetworkEvaluators_.find(processorNetwork_);\n\n if (it != processorNetworkEvaluators_.end())\n processorNetworkEvaluators_.erase(it);\n}\n\nvoid ProcessorNetworkEvaluator::topologyUpdated() {\n processorStatesDirty_ = true;\n}\n\nvoid ProcessorNetworkEvaluator::initializeNetwork() {\n ivwAssert(processorNetwork_!=0, \"processorNetwork_ not initialized, call setProcessorNetwork()\");\n \/\/ initialize network\n std::vector processors = processorNetwork_->getProcessors();\n\n for (size_t i=0; iisInitialized())\n processors[i]->initialize();\n}\n\nvoid ProcessorNetworkEvaluator::saveSnapshotAllCanvases(std::string dir, std::string default_name, std::string ext) {\n std::vector pv = processorNetwork_->getProcessorsByType();\n int i = 0;\n\n for (std::vector::iterator it = pv.begin(); it != pv.end(); it++) {\n std::stringstream ss;\n\n if (default_name == \"\" || default_name == \"UPN\")\n ss << (*it)->getIdentifier();\n else\n ss << default_name << i+1;\n\n std::string path(dir + ss.str() + ext);\n LogInfo(\"Saving canvas to: \" + path);\n (*it)->saveImageLayer(path);\n ++i;\n }\n}\n\nvoid ProcessorNetworkEvaluator::setProcessorVisited(Processor* processor, bool visited) {\n ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end())\n it->second.visited = visited;\n}\n\nbool ProcessorNetworkEvaluator::hasBeenVisited(Processor* processor) const {\n const_ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end())\n return it->second.visited;\n else\n return false;\n}\n\nvoid ProcessorNetworkEvaluator::setPropertyVisited(Property* property, bool visited) {\n PropertyMapIt it = propertiesVisited_.find(property);\n if (it != propertiesVisited_.end())\n it->second.visited = visited;\n}\n\nbool ProcessorNetworkEvaluator::hasBeenVisited(Property* property) const {\n const_PropertyMapIt it = propertiesVisited_.find(property);\n if (it != propertiesVisited_.end())\n return it->second.visited;\n else\n return false;\n}\n\nconst ProcessorNetworkEvaluator::ProcessorList& \nProcessorNetworkEvaluator::getStoredPredecessors(Processor* processor) const {\n const_ProcMapIt it = processorStates_.find(processor);\n if (it != processorStates_.end()) {\n return it->second.pred;\n }\n else {\n \/\/ processor not found, return reference to empty list of dummy element\n return processorStates_.find(nullptr)->second.pred;\n }\n}\n\nProcessorNetworkEvaluator::ProcessorList ProcessorNetworkEvaluator::getDirectPredecessors(Processor* processor, Event* event) const {\n ProcessorList predecessors;\n const std::vector& inports = processor->getInports(event);\n\n for (std::vector::const_iterator portIt = inports.begin(), portItEnd = inports.end(); portIt!=portItEnd; ++portIt) {\n if (!(*portIt)->isConnected())\n continue;\n\n const std::vector& connectedOutPorts = (*portIt)->getConnectedOutports();\n\n for (std::vector::const_iterator connectedPortIt = connectedOutPorts.begin(),\n connectedPortItEnd = connectedOutPorts.end();\n connectedPortIt!=connectedPortItEnd; ++connectedPortIt)\n if(*connectedPortIt)\n predecessors.insert((*connectedPortIt)->getProcessor());\n }\n\n return predecessors;\n}\n\nvoid ProcessorNetworkEvaluator::traversePredecessors(Processor* processor) {\n if (!hasBeenVisited(processor)) {\n setProcessorVisited(processor);\n \n const ProcessorList &directPredecessors = getStoredPredecessors(processor);\n ProcessorList::const_iterator it = directPredecessors.begin();\n while (it != directPredecessors.end()) {\n traversePredecessors(*it);\n ++it;\n }\n processorsSorted_.push_back(processor);\n }\n}\n\nvoid ProcessorNetworkEvaluator::determineProcessingOrder() {\n std::vector processors = processorNetwork_->getProcessors();\n std::vector endProcessors;\n\n for (size_t i=0; iisEndProcessor())\n endProcessors.push_back(processors[i]);\n\n \/\/ perform topological sorting and store processor order\n \/\/ in processorsSorted_\n processorsSorted_.clear();\n resetProcessorVisitedStates();\n\n for (size_t i=0; i processors = processorNetwork_->getProcessors();\n std::vector endProcessors;\n\n processorStates_.clear();\n \/\/ insert dummy processor to be able to return a reference to an \n \/\/ empty predecessor list, if a processor does not exist (getStoredPredecessors())\n processorStates_.insert(ProcMapPair(nullptr, ProcessorState()));\n\n \/\/ update all processor states, i.e. collecting predecessors\n std::vector::const_iterator it = processors.begin();\n while (it != processors.end()) {\n \/\/ register processor in global state map\n if (!processorStates_.insert(ProcMapPair(*it, ProcessorState(getDirectPredecessors(*it)))).second)\n LogError(\"Processor State was already registered.\");\n\n if ((*it)->isEndProcessor())\n endProcessors.push_back(*it);\n ++it;\n }\n\n \/\/ perform topological sorting and store processor order in processorsSorted_\n processorsSorted_.clear();\n it = endProcessors.begin();\n while (it != endProcessors.end()) {\n traversePredecessors(*it);\n ++it;\n }\n}\n\nvoid ProcessorNetworkEvaluator::resetProcessorVisitedStates() {\n ProcMapIt it = processorStates_.begin();\n while (it != processorStates_.end()) {\n it->second.visited = false;\n ++it;\n }\n}\n\nvoid ProcessorNetworkEvaluator::propagateInteractionEventImpl(Processor* processor,\n InteractionEvent* event) {\n if (!hasBeenVisited(processor)) {\n processor->invokeInteractionEvent(event);\n setProcessorVisited(processor);\n if (event->hasBeenUsed()) return;\n\n ProcessorList directPredecessors = getDirectPredecessors(processor, event);\n\n for (ProcessorList::iterator it = directPredecessors.begin(),\n itEnd = directPredecessors.end();\n it != itEnd; ++it) { \n propagateInteractionEventImpl(*it, event);\n if (event->hasBeenUsed()) return;\n }\n }\n}\n\nvoid ProcessorNetworkEvaluator::propagateInteractionEvent(Processor* processor,\n InteractionEvent* event) {\n resetProcessorVisitedStates();\n processorNetwork_->lock();\n propagateInteractionEventImpl(processor, event);\n processorNetwork_->unlock();\n}\n\nbool ProcessorNetworkEvaluator::isPortConnectedToProcessor(Port* port, Processor* processor) {\n bool isConnected = false;\n std::vector portConnections = processorNetwork_->getConnections();\n std::vector outports = processor->getOutports();\n\n for (size_t i=0; igetOutport();\n\n if (curOutport == outports[i]) {\n const Port* connectedInport = portConnections[j]->getInport();\n\n if (connectedInport == port) {\n isConnected = true;\n break;\n }\n }\n }\n }\n\n if (isConnected) return isConnected;\n\n std::vector inports = processor->getInports();\n\n for (size_t i=0; igetInport();\n\n if (curInport == inports[i]) {\n const Outport* connectedOutport = portConnections[j]->getOutport();\n\n if (connectedOutport == port) {\n isConnected = true;\n break;\n }\n }\n }\n }\n\n return isConnected;\n}\n\n\nvoid ProcessorNetworkEvaluator::onProcessorInvalidationEnd(Processor* p) {\n processorNetwork_->onProcessorInvalidationEnd(p);\n p->ProcessorObservable::removeObserver(this);\n\n if (evaulationQueued_) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nvoid ProcessorNetworkEvaluator::onProcessorNetworkEvaluateRequest() {\n \/\/Direct request, thus we don't want to queue the evaluation anymore\n if (evaulationQueued_)\n evaulationQueued_ = false;\n\n requestEvaluate();\n}\n\nvoid ProcessorNetworkEvaluator::onProcessorNetworkUnlocked() {\n \/\/ Only evaluate if an evaluation is queued or the network is modified\n if (evaulationQueued_ || processorNetwork_->isModified()) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nvoid ProcessorNetworkEvaluator::disableEvaluation() {\n evaluationDisabled_ = true;\n}\n\nvoid ProcessorNetworkEvaluator::enableEvaluation() {\n evaluationDisabled_ = false;\n\n if (evaulationQueued_) {\n evaulationQueued_ = false;\n requestEvaluate();\n }\n}\n\nProcessorNetworkEvaluator*\nProcessorNetworkEvaluator::getProcessorNetworkEvaluatorForProcessorNetwork(\n ProcessorNetwork* network) {\n std::map::iterator it =\n processorNetworkEvaluators_.find(network);\n\n if (it == processorNetworkEvaluators_.end()) return new ProcessorNetworkEvaluator(network);\n\n return it->second;\n}\n\nvoid ProcessorNetworkEvaluator::requestEvaluate() {\n \/\/ evaluation has been triggered but is currently queued\n \/\/ requestEvaluate needs to be called with evaulationQueued_ false to continue.\n if (evaulationQueued_) return;\n\n \/\/ wait for linking to finish\n if (processorNetwork_->isLinking()) {\n evaulationQueued_ = true;\n return;\n }\n\n \/\/ evaluation disabled\n if (processorNetwork_->islocked() || evaluationDisabled_) {\n evaulationQueued_ = true;\n return;\n }\n\n \/\/ wait for invalidation to finish before evaluating\n if (processorNetwork_->isInvalidating()) {\n evaulationQueued_ = true;\n return;\n }\n\n evaulationQueued_ = false;\n \/\/if we haven't returned yet, perform evaluation of the network\n evaluate();\n}\n\nvoid ProcessorNetworkEvaluator::evaluate() {\n \/\/ lock processor network to avoid concurrent evaluation\n processorNetwork_->lock();\n RenderContext::getPtr()->activateDefaultRenderContext();\n\n \/\/ if the processor network has changed determine the new processor order\n if (processorNetwork_->isModified()) {\n initializeNetwork();\n processorNetwork_->setModified(false);\n processorStatesDirty_ = true;\n }\n\n if (processorStatesDirty_) {\n \/\/ network topology has changed, update internal processor states\n updateProcessorStates();\n }\n\n for (auto processor : processorsSorted_) {\n if (!processor->isValid()) {\n if (processor->isReady()) {\n try {\n \/\/ re-initialize resources (e.g., shaders) if necessary\n if (processor->getInvalidationLevel() >= INVALID_RESOURCES) {\n processor->initializeResources();\n }\n \/\/ call onChange for all invalid inports\n for (auto inport : processor->getInports()) {\n inport->callOnChangeIfChanged();\n }\n } catch (Exception& e) {\n LogError(e.getMessage());\n processor->setValid();\n continue;\n }\n\n #if IVW_PROFILING\n processor->notifyObserversAboutToProcess(processor);\n #endif\n\n try {\n \/\/ do the actual processing\n processor->process();\n } catch (Exception& e) {\n LogError(e.getMessage());\n }\n \/\/ set processor as valid\n processor->setValid();\n\n #if IVW_PROFILING\n processor->notifyObserversFinishedProcess(processor);\n #endif\n } else {\n processor->doIfNotReady();\n }\n }\n }\n resetProcessorVisitedStates();\n\n \/\/ unlock processor network to allow next evaluation\n processorNetwork_->unlock();\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"shell\/common\/platform_util.h\"\n\n#include \/\/ windows.h must be included first\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/task\/post_task.h\"\n#include \"base\/task\/thread_pool.h\"\n#include \"base\/threading\/scoped_blocking_call.h\"\n#include \"base\/win\/registry.h\"\n#include \"base\/win\/scoped_co_mem.h\"\n#include \"base\/win\/scoped_com_initializer.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"content\/public\/browser\/browser_task_traits.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"ui\/base\/win\/shell.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\n\/\/ Required COM implementation of IFileOperationProgressSink so we can\n\/\/ precheck files before deletion to make sure they can be move to the\n\/\/ Recycle Bin.\nclass DeleteFileProgressSink : public IFileOperationProgressSink {\n public:\n DeleteFileProgressSink();\n virtual ~DeleteFileProgressSink() = default;\n\n private:\n ULONG STDMETHODCALLTYPE AddRef(void) override;\n ULONG STDMETHODCALLTYPE Release(void) override;\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,\n LPVOID* ppvObj) override;\n HRESULT STDMETHODCALLTYPE StartOperations(void) override;\n HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT) override;\n HRESULT STDMETHODCALLTYPE PreRenameItem(DWORD, IShellItem*, LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE\n PostRenameItem(DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PostDeleteItem(DWORD,\n IShellItem*,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreNewItem(DWORD, IShellItem*, LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostNewItem(DWORD,\n IShellItem*,\n LPCWSTR,\n LPCWSTR,\n DWORD,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT) override;\n HRESULT STDMETHODCALLTYPE ResetTimer(void) override;\n HRESULT STDMETHODCALLTYPE PauseTimer(void) override;\n HRESULT STDMETHODCALLTYPE ResumeTimer(void) override;\n\n ULONG m_cRef;\n};\n\nDeleteFileProgressSink::DeleteFileProgressSink() {\n m_cRef = 0;\n}\n\nHRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {\n if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {\n \/\/ TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be\n \/\/ recycled. In this case, we abort the delete operation. This bubbles\n \/\/ up and stops the Delete in IFileOperation.\n return E_ABORT;\n }\n \/\/ Returns S_OK if successful, or an error value otherwise. In the case of an\n \/\/ error value, the delete operation and all subsequent operations pending\n \/\/ from the call to IFileOperation are canceled.\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {\n \/\/ Always set out parameter to NULL, validating it first.\n if (!ppvObj)\n return E_INVALIDARG;\n *ppvObj = nullptr;\n if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {\n \/\/ Increment the reference count and return the pointer.\n *ppvObj = reinterpret_cast(this);\n AddRef();\n return NOERROR;\n }\n return E_NOINTERFACE;\n}\n\nULONG DeleteFileProgressSink::AddRef() {\n InterlockedIncrement(&m_cRef);\n return m_cRef;\n}\n\nULONG DeleteFileProgressSink::Release() {\n \/\/ Decrement the object's internal counter.\n ULONG ulRefCount = InterlockedDecrement(&m_cRef);\n if (0 == m_cRef) {\n delete this;\n }\n return ulRefCount;\n}\n\nHRESULT DeleteFileProgressSink::StartOperations() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PostRenameItem(DWORD,\n IShellItem*,\n __RPC__in_string LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PreMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PreCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostDeleteItem(DWORD,\n IShellItem*,\n HRESULT,\n IShellItem*) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PreNewItem(DWORD dwFlags,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostNewItem(DWORD,\n IShellItem*,\n LPCWSTR,\n LPCWSTR,\n DWORD,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::ResetTimer() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PauseTimer() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::ResumeTimer() {\n return S_OK;\n}\n\nstd::string OpenExternalOnWorkerThread(\n const GURL& url,\n const platform_util::OpenExternalOptions& options) {\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n \/\/ Quote the input scheme to be sure that the command does not have\n \/\/ parameters unexpected by the external program. This url should already\n \/\/ have been escaped.\n base::string16 escaped_url = L\"\\\"\" + base::UTF8ToUTF16(url.spec()) + L\"\\\"\";\n base::string16 working_dir = options.working_dir.value();\n\n if (reinterpret_cast(\n ShellExecuteW(nullptr, L\"open\", escaped_url.c_str(), nullptr,\n working_dir.empty() ? nullptr : working_dir.c_str(),\n SW_SHOWNORMAL)) <= 32) {\n return \"Failed to open\";\n }\n return \"\";\n}\n\nvoid ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n base::win::ScopedCOMInitializer com_initializer;\n if (!com_initializer.Succeeded())\n return;\n\n base::FilePath dir = full_path.DirName().AsEndingWithSeparator();\n \/\/ ParseDisplayName will fail if the directory is \"C:\", it must be \"C:\\\\\".\n if (dir.empty())\n return;\n\n Microsoft::WRL::ComPtr desktop;\n HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());\n if (FAILED(hr))\n return;\n\n base::win::ScopedCoMem dir_item;\n hr = desktop->ParseDisplayName(NULL, NULL,\n const_cast(dir.value().c_str()),\n NULL, &dir_item, NULL);\n if (FAILED(hr))\n return;\n\n base::win::ScopedCoMem file_item;\n hr = desktop->ParseDisplayName(\n NULL, NULL, const_cast(full_path.value().c_str()), NULL,\n &file_item, NULL);\n if (FAILED(hr))\n return;\n\n const ITEMIDLIST* highlight[] = {file_item};\n hr = SHOpenFolderAndSelectItems(dir_item, base::size(highlight), highlight,\n NULL);\n if (FAILED(hr)) {\n \/\/ On some systems, the above call mysteriously fails with \"file not\n \/\/ found\" even though the file is there. In these cases, ShellExecute()\n \/\/ seems to work as a fallback (although it won't select the file).\n if (hr == ERROR_FILE_NOT_FOUND) {\n ShellExecute(NULL, L\"open\", dir.value().c_str(), NULL, NULL, SW_SHOW);\n } else {\n LOG(WARNING) << \" \" << __func__ << \"(): Can't open full_path = \\\"\"\n << full_path.value() << \"\\\"\"\n << \" hr = \" << logging::SystemErrorCodeToString(hr);\n }\n }\n}\n\nstd::string OpenPathOnThread(const base::FilePath& full_path) {\n \/\/ May result in an interactive dialog.\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n bool success;\n if (base::DirectoryExists(full_path))\n success = ui::win::OpenFolderViaShell(full_path);\n else\n success = ui::win::OpenFileViaShell(full_path);\n\n return success ? \"\" : \"Failed to open path\";\n}\n\n} \/\/ namespace\n\nnamespace platform_util {\n\nvoid ShowItemInFolder(const base::FilePath& full_path) {\n base::ThreadPool::CreateSingleThreadTaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n ->PostTask(FROM_HERE,\n base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));\n}\n\nvoid OpenPath(const base::FilePath& full_path, OpenCallback callback) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n base::PostTaskAndReplyWithResult(\n base::ThreadPool::CreateCOMSTATaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n .get(),\n FROM_HERE, base::BindOnce(&OpenPathOnThread, full_path),\n std::move(callback));\n}\n\nvoid OpenExternal(const GURL& url,\n const OpenExternalOptions& options,\n OpenCallback callback) {\n base::PostTaskAndReplyWithResult(\n base::ThreadPool::CreateCOMSTATaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n .get(),\n FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url, options),\n std::move(callback));\n}\n\nbool MoveItemToTrash(const base::FilePath& path, bool delete_on_fail) {\n base::win::ScopedCOMInitializer com_initializer;\n if (!com_initializer.Succeeded())\n return false;\n\n Microsoft::WRL::ComPtr pfo;\n if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,\n IID_PPV_ARGS(&pfo))))\n return false;\n\n \/\/ Elevation prompt enabled for UAC protected files. This overrides the\n \/\/ SILENT, NO_UI and NOERRORUI flags.\n\n if (base::win::GetVersion() >= base::win::Version::WIN8) {\n \/\/ Windows 8 introduces the flag RECYCLEONDELETE and deprecates the\n \/\/ ALLOWUNDO in favor of ADDUNDORECORD.\n if (FAILED(pfo->SetOperationFlags(\n FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |\n FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE)))\n return false;\n } else {\n \/\/ For Windows 7 and Vista, RecycleOnDelete is the default behavior.\n if (FAILED(pfo->SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO |\n FOF_NOERRORUI | FOF_SILENT |\n FOFX_SHOWELEVATIONPROMPT)))\n return false;\n }\n\n \/\/ Create an IShellItem from the supplied source path.\n Microsoft::WRL::ComPtr delete_item;\n if (FAILED(SHCreateItemFromParsingName(\n path.value().c_str(), NULL,\n IID_PPV_ARGS(delete_item.GetAddressOf()))))\n return false;\n\n Microsoft::WRL::ComPtr delete_sink(\n new DeleteFileProgressSink);\n if (!delete_sink)\n return false;\n\n \/\/ Processes the queued command DeleteItem. This will trigger\n \/\/ the DeleteFileProgressSink to check for Recycle Bin.\n return SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get())) &&\n SUCCEEDED(pfo->PerformOperations());\n}\n\nvoid Beep() {\n MessageBeep(MB_OK);\n}\n\n} \/\/ namespace platform_util\nchore: ShowItemInFolder should use COMSTA (#22614)\/\/ Copyright (c) 2013 GitHub, Inc.\n\/\/ Use of this source code is governed by the MIT license that can be\n\/\/ found in the LICENSE file.\n\n#include \"shell\/common\/platform_util.h\"\n\n#include \/\/ windows.h must be included first\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/strings\/string_util.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"base\/task\/post_task.h\"\n#include \"base\/task\/thread_pool.h\"\n#include \"base\/threading\/scoped_blocking_call.h\"\n#include \"base\/win\/registry.h\"\n#include \"base\/win\/scoped_co_mem.h\"\n#include \"base\/win\/scoped_com_initializer.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"content\/public\/browser\/browser_task_traits.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"ui\/base\/win\/shell.h\"\n#include \"url\/gurl.h\"\n\nnamespace {\n\n\/\/ Required COM implementation of IFileOperationProgressSink so we can\n\/\/ precheck files before deletion to make sure they can be move to the\n\/\/ Recycle Bin.\nclass DeleteFileProgressSink : public IFileOperationProgressSink {\n public:\n DeleteFileProgressSink();\n virtual ~DeleteFileProgressSink() = default;\n\n private:\n ULONG STDMETHODCALLTYPE AddRef(void) override;\n ULONG STDMETHODCALLTYPE Release(void) override;\n HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid,\n LPVOID* ppvObj) override;\n HRESULT STDMETHODCALLTYPE StartOperations(void) override;\n HRESULT STDMETHODCALLTYPE FinishOperations(HRESULT) override;\n HRESULT STDMETHODCALLTYPE PreRenameItem(DWORD, IShellItem*, LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE\n PostRenameItem(DWORD, IShellItem*, LPCWSTR, HRESULT, IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreDeleteItem(DWORD, IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PostDeleteItem(DWORD,\n IShellItem*,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE PreNewItem(DWORD, IShellItem*, LPCWSTR) override;\n HRESULT STDMETHODCALLTYPE PostNewItem(DWORD,\n IShellItem*,\n LPCWSTR,\n LPCWSTR,\n DWORD,\n HRESULT,\n IShellItem*) override;\n HRESULT STDMETHODCALLTYPE UpdateProgress(UINT, UINT) override;\n HRESULT STDMETHODCALLTYPE ResetTimer(void) override;\n HRESULT STDMETHODCALLTYPE PauseTimer(void) override;\n HRESULT STDMETHODCALLTYPE ResumeTimer(void) override;\n\n ULONG m_cRef;\n};\n\nDeleteFileProgressSink::DeleteFileProgressSink() {\n m_cRef = 0;\n}\n\nHRESULT DeleteFileProgressSink::PreDeleteItem(DWORD dwFlags, IShellItem*) {\n if (!(dwFlags & TSF_DELETE_RECYCLE_IF_POSSIBLE)) {\n \/\/ TSF_DELETE_RECYCLE_IF_POSSIBLE will not be set for items that cannot be\n \/\/ recycled. In this case, we abort the delete operation. This bubbles\n \/\/ up and stops the Delete in IFileOperation.\n return E_ABORT;\n }\n \/\/ Returns S_OK if successful, or an error value otherwise. In the case of an\n \/\/ error value, the delete operation and all subsequent operations pending\n \/\/ from the call to IFileOperation are canceled.\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::QueryInterface(REFIID riid, LPVOID* ppvObj) {\n \/\/ Always set out parameter to NULL, validating it first.\n if (!ppvObj)\n return E_INVALIDARG;\n *ppvObj = nullptr;\n if (riid == IID_IUnknown || riid == IID_IFileOperationProgressSink) {\n \/\/ Increment the reference count and return the pointer.\n *ppvObj = reinterpret_cast(this);\n AddRef();\n return NOERROR;\n }\n return E_NOINTERFACE;\n}\n\nULONG DeleteFileProgressSink::AddRef() {\n InterlockedIncrement(&m_cRef);\n return m_cRef;\n}\n\nULONG DeleteFileProgressSink::Release() {\n \/\/ Decrement the object's internal counter.\n ULONG ulRefCount = InterlockedDecrement(&m_cRef);\n if (0 == m_cRef) {\n delete this;\n }\n return ulRefCount;\n}\n\nHRESULT DeleteFileProgressSink::StartOperations() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::FinishOperations(HRESULT) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PreRenameItem(DWORD, IShellItem*, LPCWSTR) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PostRenameItem(DWORD,\n IShellItem*,\n __RPC__in_string LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PreMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostMoveItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PreCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostCopyItem(DWORD,\n IShellItem*,\n IShellItem*,\n LPCWSTR,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostDeleteItem(DWORD,\n IShellItem*,\n HRESULT,\n IShellItem*) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PreNewItem(DWORD dwFlags,\n IShellItem*,\n LPCWSTR) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::PostNewItem(DWORD,\n IShellItem*,\n LPCWSTR,\n LPCWSTR,\n DWORD,\n HRESULT,\n IShellItem*) {\n return E_NOTIMPL;\n}\n\nHRESULT DeleteFileProgressSink::UpdateProgress(UINT, UINT) {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::ResetTimer() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::PauseTimer() {\n return S_OK;\n}\n\nHRESULT DeleteFileProgressSink::ResumeTimer() {\n return S_OK;\n}\n\nstd::string OpenExternalOnWorkerThread(\n const GURL& url,\n const platform_util::OpenExternalOptions& options) {\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n \/\/ Quote the input scheme to be sure that the command does not have\n \/\/ parameters unexpected by the external program. This url should already\n \/\/ have been escaped.\n base::string16 escaped_url = L\"\\\"\" + base::UTF8ToUTF16(url.spec()) + L\"\\\"\";\n base::string16 working_dir = options.working_dir.value();\n\n if (reinterpret_cast(\n ShellExecuteW(nullptr, L\"open\", escaped_url.c_str(), nullptr,\n working_dir.empty() ? nullptr : working_dir.c_str(),\n SW_SHOWNORMAL)) <= 32) {\n return \"Failed to open\";\n }\n return \"\";\n}\n\nvoid ShowItemInFolderOnWorkerThread(const base::FilePath& full_path) {\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n base::win::ScopedCOMInitializer com_initializer;\n if (!com_initializer.Succeeded())\n return;\n\n base::FilePath dir = full_path.DirName().AsEndingWithSeparator();\n \/\/ ParseDisplayName will fail if the directory is \"C:\", it must be \"C:\\\\\".\n if (dir.empty())\n return;\n\n Microsoft::WRL::ComPtr desktop;\n HRESULT hr = SHGetDesktopFolder(desktop.GetAddressOf());\n if (FAILED(hr))\n return;\n\n base::win::ScopedCoMem dir_item;\n hr = desktop->ParseDisplayName(NULL, NULL,\n const_cast(dir.value().c_str()),\n NULL, &dir_item, NULL);\n if (FAILED(hr))\n return;\n\n base::win::ScopedCoMem file_item;\n hr = desktop->ParseDisplayName(\n NULL, NULL, const_cast(full_path.value().c_str()), NULL,\n &file_item, NULL);\n if (FAILED(hr))\n return;\n\n const ITEMIDLIST* highlight[] = {file_item};\n hr = SHOpenFolderAndSelectItems(dir_item, base::size(highlight), highlight,\n NULL);\n if (FAILED(hr)) {\n \/\/ On some systems, the above call mysteriously fails with \"file not\n \/\/ found\" even though the file is there. In these cases, ShellExecute()\n \/\/ seems to work as a fallback (although it won't select the file).\n if (hr == ERROR_FILE_NOT_FOUND) {\n ShellExecute(NULL, L\"open\", dir.value().c_str(), NULL, NULL, SW_SHOW);\n } else {\n LOG(WARNING) << \" \" << __func__ << \"(): Can't open full_path = \\\"\"\n << full_path.value() << \"\\\"\"\n << \" hr = \" << logging::SystemErrorCodeToString(hr);\n }\n }\n}\n\nstd::string OpenPathOnThread(const base::FilePath& full_path) {\n \/\/ May result in an interactive dialog.\n base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,\n base::BlockingType::MAY_BLOCK);\n bool success;\n if (base::DirectoryExists(full_path))\n success = ui::win::OpenFolderViaShell(full_path);\n else\n success = ui::win::OpenFileViaShell(full_path);\n\n return success ? \"\" : \"Failed to open path\";\n}\n\n} \/\/ namespace\n\nnamespace platform_util {\n\nvoid ShowItemInFolder(const base::FilePath& full_path) {\n base::ThreadPool::CreateCOMSTATaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n ->PostTask(FROM_HERE,\n base::BindOnce(&ShowItemInFolderOnWorkerThread, full_path));\n}\n\nvoid OpenPath(const base::FilePath& full_path, OpenCallback callback) {\n DCHECK_CURRENTLY_ON(content::BrowserThread::UI);\n\n base::PostTaskAndReplyWithResult(\n base::ThreadPool::CreateCOMSTATaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n .get(),\n FROM_HERE, base::BindOnce(&OpenPathOnThread, full_path),\n std::move(callback));\n}\n\nvoid OpenExternal(const GURL& url,\n const OpenExternalOptions& options,\n OpenCallback callback) {\n base::PostTaskAndReplyWithResult(\n base::ThreadPool::CreateCOMSTATaskRunner(\n {base::MayBlock(), base::TaskPriority::USER_BLOCKING})\n .get(),\n FROM_HERE, base::BindOnce(&OpenExternalOnWorkerThread, url, options),\n std::move(callback));\n}\n\nbool MoveItemToTrash(const base::FilePath& path, bool delete_on_fail) {\n base::win::ScopedCOMInitializer com_initializer;\n if (!com_initializer.Succeeded())\n return false;\n\n Microsoft::WRL::ComPtr pfo;\n if (FAILED(::CoCreateInstance(CLSID_FileOperation, nullptr, CLSCTX_ALL,\n IID_PPV_ARGS(&pfo))))\n return false;\n\n \/\/ Elevation prompt enabled for UAC protected files. This overrides the\n \/\/ SILENT, NO_UI and NOERRORUI flags.\n\n if (base::win::GetVersion() >= base::win::Version::WIN8) {\n \/\/ Windows 8 introduces the flag RECYCLEONDELETE and deprecates the\n \/\/ ALLOWUNDO in favor of ADDUNDORECORD.\n if (FAILED(pfo->SetOperationFlags(\n FOF_NO_UI | FOFX_ADDUNDORECORD | FOF_NOERRORUI | FOF_SILENT |\n FOFX_SHOWELEVATIONPROMPT | FOFX_RECYCLEONDELETE)))\n return false;\n } else {\n \/\/ For Windows 7 and Vista, RecycleOnDelete is the default behavior.\n if (FAILED(pfo->SetOperationFlags(FOF_NO_UI | FOF_ALLOWUNDO |\n FOF_NOERRORUI | FOF_SILENT |\n FOFX_SHOWELEVATIONPROMPT)))\n return false;\n }\n\n \/\/ Create an IShellItem from the supplied source path.\n Microsoft::WRL::ComPtr delete_item;\n if (FAILED(SHCreateItemFromParsingName(\n path.value().c_str(), NULL,\n IID_PPV_ARGS(delete_item.GetAddressOf()))))\n return false;\n\n Microsoft::WRL::ComPtr delete_sink(\n new DeleteFileProgressSink);\n if (!delete_sink)\n return false;\n\n \/\/ Processes the queued command DeleteItem. This will trigger\n \/\/ the DeleteFileProgressSink to check for Recycle Bin.\n return SUCCEEDED(pfo->DeleteItem(delete_item.Get(), delete_sink.Get())) &&\n SUCCEEDED(pfo->PerformOperations());\n}\n\nvoid Beep() {\n MessageBeep(MB_OK);\n}\n\n} \/\/ namespace platform_util\n<|endoftext|>"} {"text":"#include \"graphicitemblock.h\"\n\n#include \n#include \n#include \n#include \n\n\nbd::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent)\n{\n this->block = block;\n this->currentBoundingRect = QRectF();\n\n this->giBlockHead = Q_NULLPTR;\n this->giParamsPublic = QList();\n this->updateBlockData();\n}\n\nQRectF bd::GraphicItemBlock::boundingRect() const\n{\n return this->currentBoundingRect;\n}\n\n\nvoid bd::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n Q_UNUSED(option);\n Q_UNUSED(widget);\n Q_UNUSED(painter);\n\n painter->setPen(Qt::red);\n painter->drawLine(-200, 0, 200, 0);\n painter->drawLine(0, -200, 0, 200);\n}\n\nvoid bd::GraphicItemBlock::updateBlockData()\n{\n int widthMaximum = 0;\n int heightMaximum = 0;\n GraphicItemTextBox *gitb;\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Create Sub GraphicIterms\n \/\/ ------------------------------------------------------------------------\n\n \/\/ creeate new header\n if (this->giBlockHead != Q_NULLPTR) {\n delete this->giBlockHead;\n }\n this->giBlockHead = new GraphicItemBlockHeader(this->block, this);\n if (this->giBlockHead->getUsedWidth() > widthMaximum) widthMaximum = this->giBlockHead->getUsedWidth();\n heightMaximum += this->giBlockHead->getUsedHeight();\n this->giBlockHead->setY(this->giBlockHead->getUsedHeight()\/2);\n\n \/\/ create public parameters\n while (this->giParamsPublic.size() > 0) { \/\/ clear current list\n GraphicItemTextBox *tb = this->giParamsPublic.takeLast();\n delete tb;\n }\n for (int i=0; i < this->block->getParameters().size(); ++i) { \/\/ create new list\n Parameter *param = this->block->getParameters().at(i);\n if (param->isPublic()) {\n gitb = new GraphicItemTextBox(this);\n this->giParamsPublic.append(gitb);\n\n \/\/ update\n gitb->setText(param->name(), GraphicItemTextBox::Align::Center);\n\n \/\/ update height\n gitb->setY(gitb->y() + gitb->getUsedHeight()\/2);\n gitb->setY(gitb->y() + heightMaximum);\n heightMaximum += gitb->getUsedHeight();\n\n \/\/ update maximum width\n if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth();\n }\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Update Positon\n \/\/ ------------------------------------------------------------------------\n\n \/\/ update header\n this->giBlockHead->setY(this->giBlockHead->y() - heightMaximum\/2);\n\n \/\/ update public parameters\n for (int i=0; i < this->giParamsPublic.size(); ++i) {\n gitb = this->giParamsPublic.at(i);\n gitb->minWidth = widthMaximum;\n gitb->setY(gitb->y() - heightMaximum\/2);\n }\n}\ntypo in comments#include \"graphicitemblock.h\"\n\n#include \n#include \n#include \n#include \n\n\nbd::GraphicItemBlock::GraphicItemBlock(Block *block, QGraphicsItem *parent) : QGraphicsItem(parent)\n{\n this->block = block;\n this->currentBoundingRect = QRectF();\n\n this->giBlockHead = Q_NULLPTR;\n this->giParamsPublic = QList();\n this->updateBlockData();\n}\n\nQRectF bd::GraphicItemBlock::boundingRect() const\n{\n return this->currentBoundingRect;\n}\n\n\nvoid bd::GraphicItemBlock::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)\n{\n Q_UNUSED(option);\n Q_UNUSED(widget);\n Q_UNUSED(painter);\n\n painter->setPen(Qt::red);\n painter->drawLine(-200, 0, 200, 0);\n painter->drawLine(0, -200, 0, 200);\n}\n\nvoid bd::GraphicItemBlock::updateBlockData()\n{\n int widthMaximum = 0;\n int heightMaximum = 0;\n GraphicItemTextBox *gitb;\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Create Sub GraphicItems\n \/\/ ------------------------------------------------------------------------\n\n \/\/ create new header\n if (this->giBlockHead != Q_NULLPTR) {\n delete this->giBlockHead;\n }\n this->giBlockHead = new GraphicItemBlockHeader(this->block, this);\n if (this->giBlockHead->getUsedWidth() > widthMaximum) widthMaximum = this->giBlockHead->getUsedWidth();\n heightMaximum += this->giBlockHead->getUsedHeight();\n this->giBlockHead->setY(this->giBlockHead->getUsedHeight()\/2);\n\n \/\/ create public parameters\n while (this->giParamsPublic.size() > 0) { \/\/ clear current list\n GraphicItemTextBox *tb = this->giParamsPublic.takeLast();\n delete tb;\n }\n for (int i=0; i < this->block->getParameters().size(); ++i) { \/\/ create new list\n Parameter *param = this->block->getParameters().at(i);\n if (param->isPublic()) {\n gitb = new GraphicItemTextBox(this);\n this->giParamsPublic.append(gitb);\n\n \/\/ update\n gitb->setText(param->name(), GraphicItemTextBox::Align::Center);\n\n \/\/ update height\n gitb->setY(gitb->y() + gitb->getUsedHeight()\/2);\n gitb->setY(gitb->y() + heightMaximum);\n heightMaximum += gitb->getUsedHeight();\n\n \/\/ update maximum width\n if (gitb->getUsedWidth() > widthMaximum) widthMaximum = gitb->getUsedWidth();\n }\n }\n\n \/\/ ------------------------------------------------------------------------\n \/\/ Update Positon\n \/\/ ------------------------------------------------------------------------\n\n \/\/ update header\n this->giBlockHead->setY(this->giBlockHead->y() - heightMaximum\/2);\n\n \/\/ update public parameters\n for (int i=0; i < this->giParamsPublic.size(); ++i) {\n gitb = this->giParamsPublic.at(i);\n gitb->minWidth = widthMaximum;\n gitb->setY(gitb->y() - heightMaximum\/2);\n }\n}\n<|endoftext|>"} {"text":"\/*!\n*\t@file\tface.cpp\n*\t@brief\tFunctions for mesh faces\n*\/\n\n#include \n#include \n#include \n#include \n#include \"face.h\"\n#include \"edge.h\"\n\nnamespace psalm\n{\n\n\/*!\n*\tDefault constructor for the face.\n*\/\n\nface::face()\n{\n\tface_point\t= NULL;\n\tid\t\t= std::numeric_limits::max();\n\tboundary\t= false;\n}\n\n\/*!\n*\tAdds an edge to the face.\n*\n*\t@param result Directed edge to add to face\n*\n*\t@warning Edge is not checked for consistency, i.e., you can add edges\n*\tthat are not part of the face.\n*\/\n\nvoid face::add_edge(const directed_edge& result)\n{\n\tE.push_back(result);\n}\n\n\/*!\n*\t@param\ti Index of edge\n*\t@return Edge at specified index\n*\/\n\ndirected_edge& face::get_edge(size_t i)\n{\n\treturn(const_cast(static_cast(this)->get_edge(i)));\n}\n\n\/*!\n*\t@param\ti Index of edge\n*\t@return\tConst reference to edge at specified index\n*\/\n\nconst directed_edge& face::get_edge(size_t i) const\n{\n\tif(i >= E.size())\n\t\tthrow std::out_of_range(\"face::get_edge(): Invalid edge index\");\n\telse\n\t\treturn(E[i]);\n}\n\n\/*!\n*\tAdds vertex to the face.\n*\n*\t@param v Pointer to new vertex.\n*\t@warning The vertex is not checked for consistency, i.e., you can add\n*\tany vertex to the face (even vertices that are not part of the face at\n*\tall).\n*\/\n\nvoid face::add_vertex(vertex* v)\n{\n\tV.push_back(v);\n}\n\n\/*!\n*\t@param i Index of vertex\n*\t@return Vertex at specified index or NULL if the index is out of range.\n*\/\n\nconst vertex* face::get_vertex(size_t i) const\n{\n\tif(i >= V.size())\n\t\treturn(NULL);\n\telse\n\t\treturn(V[i]);\n}\n\n\/*!\n*\t@return Number of vertices for face, i.e., whether the face is a\n*\ttriangle, a quadrangle, ...\n*\/\n\nsize_t face::num_vertices() const\n{\n\treturn(V.size());\n}\n\n\/*!\n*\t@return Number of edges for face\n*\/\n\nsize_t face::num_edges() const\n{\n\treturn(E.size());\n}\n\n\/*!\n*\tStores a new face vertex that corresponds to a vertex in the mesh.\n*\n*\t@param v Pointer to new vertex.\n*\t@warning The new vertex cannot be checked for consistency, i.e., there\n*\tis no way of finding out whether the new vertex corresponds to a vertex\n*\tof the face.\n*\/\n\nvoid face::add_face_vertex(vertex* v)\n{\n\tV_F.push_back(v);\n}\n\n\/*!\n*\t@param i Index of face vertex.\n*\t@return Face vertex that corresponds to a vertex in the mesh or NULL if\n*\tthe index is out of range.\n*\/\n\nvertex* face::get_face_vertex(size_t i)\n{\n\tif(i >= V_F.size())\n\t\treturn(NULL);\n\telse\n\t\treturn(V_F[i]);\n}\n\n\/*!\n*\tReturns value of flag signalling whether the face is a boundary face.\n*\tValue of flag is supposed to be set by the user.\n*\/\n\nbool face::is_on_boundary() const\n{\n\treturn(boundary);\n}\n\n\/*!\n*\tSets value of flag signalling boundary faces. The parameter is set to\n*\tfalse by default in all constructors.\n*\n*\t@param\tboundary Current value for boundary parameter (true by default)\n*\/\n\nvoid face::set_on_boundary(bool boundary)\n{\n\tthis->boundary = boundary;\n}\n\n\/*!\n*\tReconstructs the face from its edges:\n*\n*\t- Delete vertices\n*\t- Traverse edges\n*\t- Store vertices in the order specified by the edges\n*\/\n\nvoid face::reconstruct_from_edges()\n{\n\tV.clear();\n\tstd::cout << \"HAVE: \";\n\tfor(std::vector::iterator e_it = E.begin(); e_it < E.end(); e_it++)\n\t{\n\t\tif(e_it->inverted)\n\t\t\tstd::cout << \"* \";\n\n\t\tstd::cout << e_it->e->get_u()->get_id() << \" \";\n\t\tstd::cout << e_it->e->get_v()->get_id() << \" \";\n\n\t\t\/\/ Only store the first vertex of an edge -- this will yield\n\t\t\/\/ _all_ vertices upon traversal\n\t\tif(e_it->inverted)\n\t\t\tadd_vertex(const_cast(e_it->e->get_v())); \/\/ XXX: Evil. face::add_vertex() should be fixed\n\t\telse\n\t\t\tadd_vertex(const_cast(e_it->e->get_u()));\n\t}\n\tstd::cout << \"\\n\";\n\n\tstd::set V_IDs;\n\n\tstd::cout << \"\\tRECONSTRUCTED: \";\n\tfor(size_t i = 0; i < V.size(); i++)\n\t{\n\t\tstd::cout << V[i]->get_id() << \" \";\n\t\tV_IDs.insert(V[i]->get_id());\n\t}\n\n\tstd::cout << \" [ SORTED: \";\n\tfor(std::set::iterator it = V_IDs.begin(); it != V_IDs.end(); it++)\n\t{\n\t\tstd::cout << *it << \" \";\n\t}\n\tstd::cout << \"] \" << \"\\n\";\n\n\tif(V_IDs.size() < 3)\n\t\tstd::cout << \"DISASTER.\\n\";\n\n}\n\n} \/\/ end of namespace \"psalm\"\nCleanup: Removed debug output from face::reconstruct_from_edges()\/*!\n*\t@file\tface.cpp\n*\t@brief\tFunctions for mesh faces\n*\/\n\n#include \n#include \n#include \n#include \n#include \"face.h\"\n#include \"edge.h\"\n\nnamespace psalm\n{\n\n\/*!\n*\tDefault constructor for the face.\n*\/\n\nface::face()\n{\n\tface_point\t= NULL;\n\tid\t\t= std::numeric_limits::max();\n\tboundary\t= false;\n}\n\n\/*!\n*\tAdds an edge to the face.\n*\n*\t@param result Directed edge to add to face\n*\n*\t@warning Edge is not checked for consistency, i.e., you can add edges\n*\tthat are not part of the face.\n*\/\n\nvoid face::add_edge(const directed_edge& result)\n{\n\tE.push_back(result);\n}\n\n\/*!\n*\t@param\ti Index of edge\n*\t@return Edge at specified index\n*\/\n\ndirected_edge& face::get_edge(size_t i)\n{\n\treturn(const_cast(static_cast(this)->get_edge(i)));\n}\n\n\/*!\n*\t@param\ti Index of edge\n*\t@return\tConst reference to edge at specified index\n*\/\n\nconst directed_edge& face::get_edge(size_t i) const\n{\n\tif(i >= E.size())\n\t\tthrow std::out_of_range(\"face::get_edge(): Invalid edge index\");\n\telse\n\t\treturn(E[i]);\n}\n\n\/*!\n*\tAdds vertex to the face.\n*\n*\t@param v Pointer to new vertex.\n*\t@warning The vertex is not checked for consistency, i.e., you can add\n*\tany vertex to the face (even vertices that are not part of the face at\n*\tall).\n*\/\n\nvoid face::add_vertex(vertex* v)\n{\n\tV.push_back(v);\n}\n\n\/*!\n*\t@param i Index of vertex\n*\t@return Vertex at specified index or NULL if the index is out of range.\n*\/\n\nconst vertex* face::get_vertex(size_t i) const\n{\n\tif(i >= V.size())\n\t\treturn(NULL);\n\telse\n\t\treturn(V[i]);\n}\n\n\/*!\n*\t@return Number of vertices for face, i.e., whether the face is a\n*\ttriangle, a quadrangle, ...\n*\/\n\nsize_t face::num_vertices() const\n{\n\treturn(V.size());\n}\n\n\/*!\n*\t@return Number of edges for face\n*\/\n\nsize_t face::num_edges() const\n{\n\treturn(E.size());\n}\n\n\/*!\n*\tStores a new face vertex that corresponds to a vertex in the mesh.\n*\n*\t@param v Pointer to new vertex.\n*\t@warning The new vertex cannot be checked for consistency, i.e., there\n*\tis no way of finding out whether the new vertex corresponds to a vertex\n*\tof the face.\n*\/\n\nvoid face::add_face_vertex(vertex* v)\n{\n\tV_F.push_back(v);\n}\n\n\/*!\n*\t@param i Index of face vertex.\n*\t@return Face vertex that corresponds to a vertex in the mesh or NULL if\n*\tthe index is out of range.\n*\/\n\nvertex* face::get_face_vertex(size_t i)\n{\n\tif(i >= V_F.size())\n\t\treturn(NULL);\n\telse\n\t\treturn(V_F[i]);\n}\n\n\/*!\n*\tReturns value of flag signalling whether the face is a boundary face.\n*\tValue of flag is supposed to be set by the user.\n*\/\n\nbool face::is_on_boundary() const\n{\n\treturn(boundary);\n}\n\n\/*!\n*\tSets value of flag signalling boundary faces. The parameter is set to\n*\tfalse by default in all constructors.\n*\n*\t@param\tboundary Current value for boundary parameter (true by default)\n*\/\n\nvoid face::set_on_boundary(bool boundary)\n{\n\tthis->boundary = boundary;\n}\n\n\/*!\n*\tReconstructs the face from its edges:\n*\n*\t- Delete vertices\n*\t- Traverse edges\n*\t- Store vertices in the order specified by the edges\n*\/\n\nvoid face::reconstruct_from_edges()\n{\n\tV.clear();\n\tfor(std::vector::iterator e_it = E.begin(); e_it < E.end(); e_it++)\n\t{\n\t\t\/\/ Only store the first vertex of an edge -- this will yield\n\t\t\/\/ _all_ vertices upon traversal\n\t\tif(e_it->inverted)\n\t\t\tadd_vertex(const_cast(e_it->e->get_v())); \/\/ XXX: Evil. face::add_vertex() should be fixed\n\t\telse\n\t\t\tadd_vertex(const_cast(e_it->e->get_u()));\n\t}\n}\n\n} \/\/ end of namespace \"psalm\"\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace std::string_view_literals;\n\nnamespace{\nnamespace test_compile_time_sorting{\nstruct str_num_pair{\n\tstd::string_view first;\n\tint second;\n\n\tconstexpr bool operator==(const str_num_pair& p)const{\n\t\treturn this->first == p.first && this->second == p.second;\n\t}\n};\n\nconstexpr auto arr = []()constexpr{\n\tstd::array arr = {{\n\t\t\t{\"hello\"sv, 13},\n\t\t\t{\"bye\"sv, 15},\n\t\t\t{\"how\"sv, 33},\n\t\t\t{\"are\"sv, 4},\n\t\t\t{\"you\"sv, 9}\n\t\t}};\n\n\tutki::sort(\n\t\t\tarr.begin(),\n\t\t\tarr.end(),\n\t\t\t[](const auto& a, const auto& b){\n\t\t\t\treturn a.first < b.first;\n\t\t\t}\n\t\t);\n\treturn arr;\n}();\n\nconstexpr decltype(arr) expected = {{\n\t\t{\"are\", 4},\n\t\t{\"bye\", 15},\n\t\t{\"hello\", 13},\n\t\t{\"how\", 33},\n\t\t{\"you\", 9}\n\t}};\n\nstatic_assert(\n\t\t\/\/ the std::array::operator==() is not constexpr in C++17 (it is in C++20), so we need to compare element by element\n\t\t[]{\n\t\t\tif(arr.size() != expected.size()){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor(auto i = arr.begin(), j = expected.begin(); i != arr.end(); ++i, ++j){\n\t\t\t\tif(*i == *j){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}(),\n\t\t\"sorted array is not as expected\"\n\t);\n}\n}\n\nnamespace{\ntst::set set(\"sort\", [](tst::suite& suite){\n\tsuite.add(\"compile_time_sort\", []{\n\t\ttst::check(test_compile_time_sorting::arr == test_compile_time_sorting::expected, SL);\n\t});\n\n\tsuite.add(\"sort_strings_with_default_comparator\", []{\n\t\tstd::array arr = {{\n\t\t\t\"hello\",\n\t\t\t\"bye\",\n\t\t\t\"how\",\n\t\t\t\"are\",\n\t\t\t\"you\",\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end());\n\n\t\tdecltype(arr) expected = {{\n\t\t\t\"are\",\n\t\t\t\"bye\",\n\t\t\t\"hello\",\n\t\t\t\"how\",\n\t\t\t\"you\",\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n\n\tsuite.add(\"sort_strings_with_custom_comparator\", []{\n\t\tstd::array, 5> arr = {{\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9}\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end(), [](const auto& a, const auto& b){return a.first < b.first;});\n\n\t\tdecltype(arr) expected = {{\n\t\t\t{\"are\", 4},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"hello\", 13},\n\t\t\t{\"how\", 33},\n\t\t\t{\"you\", 9}\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n\n\tsuite.add(\"sort_integers_with_custom_comparator\", []{\n\t\tstd::array, 5> arr = {{\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9},\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end(), [](const auto& a, const auto& b){return a.second < b.second;});\n\n\t\tdecltype(arr) expected = {{\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9},\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n});\n}\nfix msvs build#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace std::string_view_literals;\n\n#if M_COMPILER != M_COMPILER_MSVC || M_COMPILER_MSVC_TOOLS_V >= 142\nnamespace{\nnamespace test_compile_time_sorting{\nstruct str_num_pair{\n\tstd::string_view first;\n\tint second;\n\n\tconstexpr bool operator==(const str_num_pair& p)const{\n\t\treturn this->first == p.first && this->second == p.second;\n\t}\n};\n\nconstexpr auto arr = []()constexpr{\n\tstd::array arr = {{\n\t\t\t{\"hello\"sv, 13},\n\t\t\t{\"bye\"sv, 15},\n\t\t\t{\"how\"sv, 33},\n\t\t\t{\"are\"sv, 4},\n\t\t\t{\"you\"sv, 9}\n\t\t}};\n\n\tutki::sort(\n\t\t\tarr.begin(),\n\t\t\tarr.end(),\n\t\t\t[](const auto& a, const auto& b){\n\t\t\t\treturn a.first < b.first;\n\t\t\t}\n\t\t);\n\treturn arr;\n}();\n\nconstexpr decltype(arr) expected = {{\n\t\t{\"are\", 4},\n\t\t{\"bye\", 15},\n\t\t{\"hello\", 13},\n\t\t{\"how\", 33},\n\t\t{\"you\", 9}\n\t}};\n\nstatic_assert(\n\t\t\/\/ the std::array::operator==() is not constexpr in C++17 (it is in C++20), so we need to compare element by element\n\t\t[]{\n\t\t\tif(arr.size() != expected.size()){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tfor(auto i = arr.begin(), j = expected.begin(); i != arr.end(); ++i, ++j){\n\t\t\t\tif(*i == *j){\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn true;\n\t\t}(),\n\t\t\"sorted array is not as expected\"\n\t);\n}\n}\n#endif\n\nnamespace{\ntst::set set(\"sort\", [](tst::suite& suite){\n\tsuite.add(\"compile_time_sort\", []{\n\t\ttst::check(test_compile_time_sorting::arr == test_compile_time_sorting::expected, SL);\n\t});\n\n\tsuite.add(\"sort_strings_with_default_comparator\", []{\n\t\tstd::array arr = {{\n\t\t\t\"hello\",\n\t\t\t\"bye\",\n\t\t\t\"how\",\n\t\t\t\"are\",\n\t\t\t\"you\",\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end());\n\n\t\tdecltype(arr) expected = {{\n\t\t\t\"are\",\n\t\t\t\"bye\",\n\t\t\t\"hello\",\n\t\t\t\"how\",\n\t\t\t\"you\",\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n\n\tsuite.add(\"sort_strings_with_custom_comparator\", []{\n\t\tstd::array, 5> arr = {{\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9}\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end(), [](const auto& a, const auto& b){return a.first < b.first;});\n\n\t\tdecltype(arr) expected = {{\n\t\t\t{\"are\", 4},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"hello\", 13},\n\t\t\t{\"how\", 33},\n\t\t\t{\"you\", 9}\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n\n\tsuite.add(\"sort_integers_with_custom_comparator\", []{\n\t\tstd::array, 5> arr = {{\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9},\n\t\t}};\n\n\t\tutki::sort(arr.begin(), arr.end(), [](const auto& a, const auto& b){return a.second < b.second;});\n\n\t\tdecltype(arr) expected = {{\n\t\t\t{\"are\", 4},\n\t\t\t{\"you\", 9},\n\t\t\t{\"hello\", 13},\n\t\t\t{\"bye\", 15},\n\t\t\t{\"how\", 33},\n\t\t}};\n\n\t\ttst::check(arr == expected, SL);\n\t});\n});\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n\/\/ Compute a projective reconstruction from N views of six points. Based on:\n\/\/\n\/\/ [1] Frederik Schaffalitzky, Andrew Zisserman, Richard I. Hartley, Philip H.\n\/\/ S. Torr. A Six Point Solution for Structure and Motion. Lecture Notes In\n\/\/ Computer Science; Vol. 1842 archive Proceedings of the 6th European\n\/\/ Conference on Computer Vision-Part I pp 632-648, 2000.\n\n#include \"libmv\/base\/vector.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/sixpointnview.h\"\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/numeric\/poly.h\"\n\nnamespace libmv {\n\n\/**\n * Compute a pencil of two cameras that both perfectly project the five points\n * to the five basis points of P^3.\n *\/\ntemplate\nstatic void FivePointCameraPencil(const TMatP &points, TMatA *A, TMatB *B) {\n CHECK_EQ(5, points.cols());\n Mat3 H;\n PreconditionerFromPoints(points, &H);\n Mat35 design = H * points;\n\n Vec5 v1, v2;\n Nullspace2(&design, &v1, &v2);\n\n Mat34 five_points = design.block<3,4>(0, 0);\n Mat34 tmpA = five_points;\n Mat34 tmpB = five_points;\n for (int r = 0; r < 3; ++r) {\n \/\/ The last component of v1 and v2 is ignored, because it is a scale factor.\n tmpA.row(r) = five_points.row(r).cwise() * v1.start(4).transpose();\n tmpB.row(r) = five_points.row(r).cwise() * v2.start(4).transpose();\n }\n Mat3 Hinv = H.inverse();\n *A = Hinv * tmpA;\n *B = Hinv * tmpB;\n}\n\n\/** Calculate the last (sixth) point in projective 4 space. *\/\nstatic Vec4 CalcX6FromDesignMat(\n double a, double b, double c, double d, double e) {\n \/\/ This should match the matrix in step 6 above, equation (9) in [1].\n \/\/ The 6th world point is the nullspace of this matrix.\n Mat X6null(6,4);\n X6null << e-d, 0 , 0 , a-b,\n e-c, 0 , a , 0 ,\n d-c, b , 0 , 0 ,\n 0 , e , 0 , a-c,\n 0 , e-b, a-d, 0 ,\n 0 , 0 , d , b-c;\n Vec4 X6;\n Nullspace(&X6null, &X6);\n return X6;\n}\n\n\/\/ See paragraph after equation 16 in torr97robust for the equation used to\n\/\/ derive the following coefficients.\n#define ACCUMULATE_CUBIC_COEFFICIENTS(x,y,z, sgn) \\\n p = t1[x]*t1[y]; \\\n q = t2[x]*t1[y] + t1[x]*t2[y]; \\\n d += sgn * p*t1[z]; \\\n c += sgn * (q*t1[z] + p*t2[z]); \\\n b += sgn * (t2[x]*t2[y]*t1[z] + q*t2[z]); \\\n a += sgn * t2[x]*t2[y]*t2[z];\n\n\/\/ TODO(keir): Break this up into smaller functions.\n\/\/ TODO(keir): Change 'points' from 2 x 6nviews to be 2n views x 6; this way it\n\/\/ can be directly passed from the robust estimation code without copying.\nvoid SixPointNView(const Mat2X &points,\n vector *reconstructions) {\n CHECK(points.cols() % 6 == 0);\n int nviews = points.cols() \/ 6;\n\n \/\/ Convert to homogeneous coordinates.\n Mat3X hpoints(3, points.cols());\n hpoints.block(0, 0, 2, 6*nviews) = points;\n hpoints.row(2).setOnes();\n\n \/\/ See equation (7.2) p179 of HZ; this is the DLT for solving cameras.\n \/\/ Chose wi = 1, i.e. the homogeneous component of each image location is 1.\n \/\/ Note that As and Bs are on the heap to avoid blowing the stack for a large\n \/\/ number of views.\n Mat34 *As = new Mat34[nviews];\n Mat34 *Bs = new Mat34[nviews];\n Mat ws(nviews,5);\n\n for (int i = 0; i < nviews; ++i) {\n \/\/ Extract pencil of camera matrices.\n FivePointCameraPencil(hpoints.block(0, 6*i, 3, 5), As+i, Bs+i);\n\n \/\/ Calculate Q.\n Vec3 x6 = hpoints.col(6*i+5);\n Mat3 x6cross = CrossProductMatrix(x6);\n Mat4 Qa = As[i].transpose() * x6cross * Bs[i];\n Mat4 Q = Qa + Qa.transpose();\n\n \/\/ Read the coefficients w^i from Q and put into the ws matrix.\n ws(i,0) = Q(0,1);\n ws(i,1) = Q(0,2);\n ws(i,2) = Q(1,2);\n ws(i,3) = Q(1,3);\n ws(i,4) = Q(2,3);\n }\n Vec t1, t2;\n Nullspace2(&ws, &t1, &t2);\n\n \/\/ The svd gives us the basis for the nullspace of ws in which the t vector\n \/\/ lives, such that t = beta*t1+alpha*t2. However, there is a cubic\n \/\/ constraint on the elements of t, such that we can substitute and solve for\n \/\/ alpha. See equation (10) in [1].\n double a, b, c, d, p, q;\n a = b = c = d = 0;\n ACCUMULATE_CUBIC_COEFFICIENTS(0,1,3, 1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,1,4, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,2,4, 1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,3,4, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(1,2,3, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(1,3,4, 1);\n\n \/\/ TODO(keir): Handle case a = 0.\n \/\/ TODO(keir): Handle the case (a=b=c=d=0. If a=b=c=0 and d!=0, then alpha=0;\n \/\/ in that case, find beta instead.\n CHECK(a != 0.0);\n \/\/ Assume beta = 1.\n double a1 = b\/a, b1 = c\/a, c1 = d\/a;\n a = a1;\n b = b1;\n c = c1;\n\n double alpha, alphas[3];\n int nroots = SolveCubicPolynomial(a, b, c, alphas+0, alphas+1, alphas+2);\n\n \/\/ Check each solution for alpha.\n reconstructions->resize(nroots);\n for (int ia=0; ia(0, 0).setIdentity();\n pr.X.col(4).setOnes();\n\n \/\/ Find X6 from the chi vector.\n Vec4 Xp = CalcX6FromDesignMat(a, b, c, d, e);\n pr.X.col(5) = Xp;\n\n \/\/ Find P for each camera by finding suitable values of u,v.\n pr.P.resize(nviews);\n for (int i = 0; i < nviews; ++i) {\n \/\/ Project X6 with A and B. DO NOT NORMALIZE, it breaks the next step.\n Vec3 AX = As[i] * Xp;\n Vec3 BX = Bs[i] * Xp;\n\n \/\/ Find mu and nu with smallest algebraic error; see step 7. For exactly\n \/\/ six points, M will be rank 2. With more than 6 points, measurement\n \/\/ error will make M nonsingular.\n Mat3 M;\n M.col(0) = AX;\n M.col(1) = BX;\n M.col(2) = hpoints.col(6*i+5); \/\/ x6.\n\n Vec3 munu;\n Nullspace(&M, &munu);\n double mu = munu[0];\n double nu = munu[1];\n\n pr.P[i] = mu*As[i] + nu*Bs[i];\n }\n }\n delete [] As;\n delete [] Bs;\n}\n\n} \/\/ namespace libmv\nFix for visual 10 release mode.\/\/ Copyright (c) 2007, 2008 libmv authors.\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to\n\/\/ deal in the Software without restriction, including without limitation the\n\/\/ rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or\n\/\/ sell copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n\/\/ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n\/\/ IN THE SOFTWARE.\n\/\/\n\/\/ Compute a projective reconstruction from N views of six points. Based on:\n\/\/\n\/\/ [1] Frederik Schaffalitzky, Andrew Zisserman, Richard I. Hartley, Philip H.\n\/\/ S. Torr. A Six Point Solution for Structure and Motion. Lecture Notes In\n\/\/ Computer Science; Vol. 1842 archive Proceedings of the 6th European\n\/\/ Conference on Computer Vision-Part I pp 632-648, 2000.\n\n#include \"libmv\/base\/vector.h\"\n#include \"libmv\/logging\/logging.h\"\n#include \"libmv\/multiview\/fundamental.h\"\n#include \"libmv\/multiview\/sixpointnview.h\"\n#include \"libmv\/numeric\/numeric.h\"\n#include \"libmv\/numeric\/poly.h\"\n\nnamespace libmv {\n\n\/**\n * Compute a pencil of two cameras that both perfectly project the five points\n * to the five basis points of P^3.\n *\/\ntemplate\nstatic void FivePointCameraPencil(const TMatP &points, TMatA *A, TMatB *B) {\n CHECK(5 == points.cols());\n Mat3 H;\n PreconditionerFromPoints(points, &H);\n Mat35 design = H * points;\n\n Vec5 v1, v2;\n Nullspace2(&design, &v1, &v2);\n\n Mat34 five_points = design.block<3,4>(0, 0);\n Mat34 tmpA = five_points;\n Mat34 tmpB = five_points;\n for (int r = 0; r < 3; ++r) {\n \/\/ The last component of v1 and v2 is ignored, because it is a scale factor.\n tmpA.row(r) = five_points.row(r).cwise() * v1.start(4).transpose();\n tmpB.row(r) = five_points.row(r).cwise() * v2.start(4).transpose();\n }\n Mat3 Hinv = H.inverse();\n *A = Hinv * tmpA;\n *B = Hinv * tmpB;\n}\n\n\/** Calculate the last (sixth) point in projective 4 space. *\/\nstatic Vec4 CalcX6FromDesignMat(\n double a, double b, double c, double d, double e) {\n \/\/ This should match the matrix in step 6 above, equation (9) in [1].\n \/\/ The 6th world point is the nullspace of this matrix.\n Mat X6null(6,4);\n X6null << e-d, 0 , 0 , a-b,\n e-c, 0 , a , 0 ,\n d-c, b , 0 , 0 ,\n 0 , e , 0 , a-c,\n 0 , e-b, a-d, 0 ,\n 0 , 0 , d , b-c;\n Vec4 X6;\n Nullspace(&X6null, &X6);\n return X6;\n}\n\n\/\/ See paragraph after equation 16 in torr97robust for the equation used to\n\/\/ derive the following coefficients.\n#define ACCUMULATE_CUBIC_COEFFICIENTS(x,y,z, sgn) \\\n p = t1[x]*t1[y]; \\\n q = t2[x]*t1[y] + t1[x]*t2[y]; \\\n d += sgn * p*t1[z]; \\\n c += sgn * (q*t1[z] + p*t2[z]); \\\n b += sgn * (t2[x]*t2[y]*t1[z] + q*t2[z]); \\\n a += sgn * t2[x]*t2[y]*t2[z];\n\n\/\/ TODO(keir): Break this up into smaller functions.\n\/\/ TODO(keir): Change 'points' from 2 x 6nviews to be 2n views x 6; this way it\n\/\/ can be directly passed from the robust estimation code without copying.\nvoid SixPointNView(const Mat2X &points,\n vector *reconstructions) {\n CHECK(points.cols() % 6 == 0);\n int nviews = points.cols() \/ 6;\n\n \/\/ Convert to homogeneous coordinates.\n Mat3X hpoints(3, points.cols());\n hpoints.block(0, 0, 2, 6*nviews) = points;\n hpoints.row(2).setOnes();\n\n \/\/ See equation (7.2) p179 of HZ; this is the DLT for solving cameras.\n \/\/ Chose wi = 1, i.e. the homogeneous component of each image location is 1.\n \/\/ Note that As and Bs are on the heap to avoid blowing the stack for a large\n \/\/ number of views.\n Mat34 *As = new Mat34[nviews];\n Mat34 *Bs = new Mat34[nviews];\n Mat ws(nviews,5);\n\n for (int i = 0; i < nviews; ++i) {\n \/\/ Extract pencil of camera matrices.\n FivePointCameraPencil(hpoints.block(0, 6*i, 3, 5), As+i, Bs+i);\n\n \/\/ Calculate Q.\n Vec3 x6 = hpoints.col(6*i+5);\n Mat3 x6cross = CrossProductMatrix(x6);\n Mat4 Qa = As[i].transpose() * x6cross * Bs[i];\n Mat4 Q = Qa + Qa.transpose();\n\n \/\/ Read the coefficients w^i from Q and put into the ws matrix.\n ws(i,0) = Q(0,1);\n ws(i,1) = Q(0,2);\n ws(i,2) = Q(1,2);\n ws(i,3) = Q(1,3);\n ws(i,4) = Q(2,3);\n }\n Vec t1, t2;\n Nullspace2(&ws, &t1, &t2);\n\n \/\/ The svd gives us the basis for the nullspace of ws in which the t vector\n \/\/ lives, such that t = beta*t1+alpha*t2. However, there is a cubic\n \/\/ constraint on the elements of t, such that we can substitute and solve for\n \/\/ alpha. See equation (10) in [1].\n double a, b, c, d, p, q;\n a = b = c = d = 0;\n ACCUMULATE_CUBIC_COEFFICIENTS(0,1,3, 1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,1,4, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,2,4, 1);\n ACCUMULATE_CUBIC_COEFFICIENTS(0,3,4, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(1,2,3, -1);\n ACCUMULATE_CUBIC_COEFFICIENTS(1,3,4, 1);\n\n \/\/ TODO(keir): Handle case a = 0.\n \/\/ TODO(keir): Handle the case (a=b=c=d=0. If a=b=c=0 and d!=0, then alpha=0;\n \/\/ in that case, find beta instead.\n CHECK(a != 0.0);\n \/\/ Assume beta = 1.\n double a1 = b\/a, b1 = c\/a, c1 = d\/a;\n a = a1;\n b = b1;\n c = c1;\n\n double alpha, alphas[3];\n int nroots = SolveCubicPolynomial(a, b, c, alphas+0, alphas+1, alphas+2);\n\n \/\/ Check each solution for alpha.\n reconstructions->resize(nroots);\n for (int ia=0; ia(0, 0).setIdentity();\n pr.X.col(4).setOnes();\n\n \/\/ Find X6 from the chi vector.\n Vec4 Xp = CalcX6FromDesignMat(a, b, c, d, e);\n pr.X.col(5) = Xp;\n\n \/\/ Find P for each camera by finding suitable values of u,v.\n pr.P.resize(nviews);\n for (int i = 0; i < nviews; ++i) {\n \/\/ Project X6 with A and B. DO NOT NORMALIZE, it breaks the next step.\n Vec3 AX = As[i] * Xp;\n Vec3 BX = Bs[i] * Xp;\n\n \/\/ Find mu and nu with smallest algebraic error; see step 7. For exactly\n \/\/ six points, M will be rank 2. With more than 6 points, measurement\n \/\/ error will make M nonsingular.\n Mat3 M;\n M.col(0) = AX;\n M.col(1) = BX;\n M.col(2) = hpoints.col(6*i+5); \/\/ x6.\n\n Vec3 munu;\n Nullspace(&M, &munu);\n double mu = munu[0];\n double nu = munu[1];\n\n pr.P[i] = mu*As[i] + nu*Bs[i];\n }\n }\n delete [] As;\n delete [] Bs;\n}\n\n} \/\/ namespace libmv\n<|endoftext|>"} {"text":"\/\/ \n\/\/ Copyright (C) 2007 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ Copyright (C) 2007 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Author: Keith Kyzivat \n\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \"mp\/MpidWinMM.h\"\n#include \"mp\/MpInputDeviceManager.h\"\n\n\/\/ EXTERNAL FUNCTIONS\nextern void showWaveError(char *syscall, int e, int N, int line) ; \/\/ dmaTaskWnt.cpp\n\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\/\/ DEFINES\n#if defined(_MSC_VER) && (_MSC_VER < 1300) \/\/ if < msvc7 (2003)\n# define CBTYPE DWORD\n#else\n# define CBTYPE DWORD_PTR\n#endif\n\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\/\/ Default constructor\nMpidWinMM::MpidWinMM(const UtlString& name, \n MpInputDeviceManager& deviceManager,\n unsigned nInputBuffers)\n: MpInputDeviceDriver(name, deviceManager)\n, mWinMMDeviceId(-1)\n, mDevHandle(NULL)\n, mNumInBuffers(nInputBuffers)\n, mWaveBufSize(0) \/\/ Unknown until enableDevice()\n, mIsOpen(FALSE)\n, mnAddBufferFailures(0)\n{\n WAVEINCAPS devCaps;\n \/\/ Grab the number of input devices that are available.\n UINT nInputDevs = waveInGetNumDevs();\n\n \/\/ Search through the input devices looking for the input device specified.\n MMRESULT wavResult = MMSYSERR_NOERROR;\n unsigned i;\n for (i = 0; i < nInputDevs; i++)\n {\n MMRESULT res = waveInGetDevCaps(i, &devCaps, sizeof(devCaps));\n if (res != MMSYSERR_NOERROR)\n {\n wavResult = res;\n } \n else if (strncmp(name, devCaps.szPname, MAXPNAMELEN) == 0)\n {\n mWinMMDeviceId = i;\n break;\n }\n }\n\n \/\/ Allocate the wave headers and buffer pointers for use with \n \/\/ windows audio routines. \n \/\/(This does *not* include allocation of the buffers themselves -\n \/\/ that is handled in enableDevice, as we don't know the \n \/\/ buffer size (#samplesPerFrame) until then.\n mpWaveHeaders = new WAVEHDR[mNumInBuffers];\n mpWaveBuffers = new LPSTR[mNumInBuffers];\n for (i = 0; i < mNumInBuffers; i++)\n {\n mpWaveBuffers[i] = NULL;\n }\n}\n\n\/\/ Destructor\nMpidWinMM::~MpidWinMM() \n{\n \/\/ If we happen to still be enabled at this point, disable the device.\n assert(!isEnabled());\n if (isEnabled())\n {\n disableDevice();\n }\n\n \/\/ Delete the sample headers and sample buffer pointers..\n unsigned i;\n for (i = 0; i < mNumInBuffers; i++)\n {\n assert(mpWaveBuffers[i] == NULL);\n if (mpWaveBuffers[i] != NULL)\n {\n delete[] mpWaveBuffers[i];\n mpWaveBuffers[i] = NULL;\n }\n }\n delete[] mpWaveBuffers;\n delete[] mpWaveHeaders;\n}\n\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nOsStatus MpidWinMM::enableDevice(unsigned samplesPerFrame, \n unsigned samplesPerSec, \n MpFrameTime currentFrameTime)\n{\n OsStatus status = OS_SUCCESS;\n\n \/\/ reset the number of addBuffer failures, as we're starting fresh now.\n mnAddBufferFailures = 0;\n\n \/\/ If the device is not valid, let the user know it's bad.\n if (!isDeviceValid())\n {\n return OS_INVALID_STATE; \/\/ perhaps new OsState of OS_RESOURCE_INVALID?\n }\n\n if (isEnabled())\n {\n return OS_FAILED;\n }\n\n \/\/ Set some wave header stat information.\n mSamplesPerFrame = samplesPerFrame;\n mSamplesPerSec = samplesPerSec;\n mCurrentFrameTime = currentFrameTime;\n\n \/\/ Do stuff to enable device.\n int nChannels = 1;\n WAVEFORMATEX wavFormat;\n wavFormat.wFormatTag = WAVE_FORMAT_PCM;\n wavFormat.nChannels = nChannels;\n wavFormat.nSamplesPerSec = mSamplesPerSec;\n wavFormat.nAvgBytesPerSec = \n nChannels * mSamplesPerSec * sizeof(MpAudioSample);\n wavFormat.nBlockAlign = nChannels * sizeof(MpAudioSample);\n wavFormat.wBitsPerSample = sizeof(MpAudioSample) * 8;\n wavFormat.cbSize = 0;\n\n \/\/ Tell windows to open the input audio device. This doesn't\n \/\/ tell it to send the data to our callback yet, just to get it ready\n \/\/ to do so..\n MMRESULT res = waveInOpen(&mDevHandle, mWinMMDeviceId,\n &wavFormat,\n (CBTYPE)waveInCallbackStatic,\n (CBTYPE)this, \n CALLBACK_FUNCTION);\n if (res != MMSYSERR_NOERROR)\n {\n \/\/ If waveInOpen failed, print out the error info,\n \/\/ invalidate the handle, and the device driver itself,\n status = OS_FAILED;\n showWaveError(\"MpidWinMM::enableDevice\", res, -1, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL; \/\/ Open didn't work, reset device handle to NULL\n mWinMMDeviceId = -1; \/\/ Make device invalid.\n\n \/\/ and return OS_FAILED.\n return status;\n }\n\n\n \/\/ Allocate the buffers we are going to use to receive audio data from\n \/\/ the windows audio input callback.\n \/\/ Calculate the buffer length we're going to use. \n \/\/ number of samples per frame * sample size in bytes\n mWaveBufSize = mSamplesPerFrame * sizeof(MpAudioSample); \n unsigned i;\n for (i = 0; i < mNumInBuffers; i++)\n {\n mpWaveBuffers[i] = new char[mWaveBufSize];\n }\n\n\n \/\/ Setup the buffers so windows can stuff them full of audio\n \/\/ when it becomes available from this audio input device.\n WAVEHDR* pWaveHdr = NULL;\n for (i=0; i < mNumInBuffers; i++) \n {\n pWaveHdr = initWaveHeader(i);\n\n res = waveInPrepareHeader(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInPrepareHeader\", res, i, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInAddBuffer\", res, i, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n }\n\n \/\/ Tell windows to start sending audio data to the callback.\n res = waveInStart(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n \/\/ If waveInStart failed, print out the error info,\n \/\/ invalidate the handle and the device driver itself,\n status = OS_FAILED;\n showWaveError(\"waveInStart\", res, -1, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n\n \/\/ If enableDevice failed, return indicating failure.\n if (status == OS_SUCCESS)\n {\n mIsEnabled = TRUE;\n }\n\n return status;\n}\n\nOsStatus MpidWinMM::disableDevice()\n{\n OsStatus status = OS_SUCCESS;\n MMRESULT res;\n \n if (!isDeviceValid() || !isEnabled())\n {\n return OS_FAILED;\n }\n\n \/\/ Indicate we are no longer enabled -- Do this first,\n \/\/ since we'll be partially disabled from here on out.\n \/\/ It is very important that this happen *before* waveInReset,\n \/\/ as the callback will continue to add and process buffers\n \/\/ while waveInReset is called causing a deadlock.\n mIsEnabled = FALSE;\n\n \/\/ Cleanup\n if (mDevHandle == NULL)\n {\n return OS_INVALID_STATE;\n }\n\n \/\/ Reset performs a stop, resets the buffers, and marks them\n \/\/ for being sent to the callback.\n \/\/ The remaining data in the windows buffers *IS* sent to the callback,\n \/\/ So be sure to watch for it and drop it on the floor.\n res = waveInReset(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInReset\", res, -1, __LINE__);\n } \n\n \/\/ Must unprepare the headers after a reset, but before the device is closed\n \/\/ (if this is done after waveInClose, mDevHandle will be invalid and \n \/\/ MMSYSERR_INVALHANDLE will be returned.\n unsigned i;\n for (i=0; i < mNumInBuffers; i++) \n {\n res = waveInUnprepareHeader(mDevHandle, &mpWaveHeaders[i], sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInUnprepareHeader\", res, i, __LINE__);\n }\n }\n\n res = waveInClose(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInClose\", res, -1, __LINE__);\n }\n\n \/\/ Delete the buffers that were allocated in enableDevice()\n for (i = 0; i < mNumInBuffers; i++)\n {\n delete[] mpWaveBuffers[i];\n mpWaveBuffers[i] = NULL;\n }\n\n \/\/ set the device handle to NULL, since it no longer is valid.\n mDevHandle = NULL;\n\n \/\/ Clear out all the wave header information.\n mSamplesPerFrame = 0;\n mSamplesPerSec = 0;\n mCurrentFrameTime = 0;\n\n return status;\n}\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC STATIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\nUtlString MpidWinMM::getDefaultDeviceName()\n{\n UtlString devName = \"\";\n\n \/\/ Get windows default input device name\n unsigned nDevs = waveInGetNumDevs();\n if (nDevs == 0)\n {\n OsSysLog::add(FAC_AUDIO, PRI_ERR, \n \"MpidWinMM::getDefaultDeviceName: \"\n \"No input audio devices present!\");\n }\n assert(nDevs != 0);\n\n MMRESULT wavResult = MMSYSERR_NOERROR;\n WAVEINCAPS devCaps;\n int defaultWinDeviceId = 0;\n wavResult = \n waveInGetDevCaps(defaultWinDeviceId, &devCaps, sizeof(devCaps));\n if (wavResult != MMSYSERR_NOERROR)\n {\n OsSysLog::add(FAC_AUDIO, PRI_ERR, \n \"MpodWinMM::getDefaultDeviceName: \"\n \"Couldn't get default input device capabilities!\");\n showWaveError(\"WINDOWS_DEFAULT_DEVICE_HACK\",\n wavResult, -1, __LINE__);\n }\n else\n {\n devName = devCaps.szPname;\n }\n assert(wavResult == MMSYSERR_NOERROR);\n return devName;\n}\n\n\n\/* ============================ INQUIRY =================================== *\/\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\nWAVEHDR* MpidWinMM::initWaveHeader(int n)\n{\n assert((n >= 0) && (n < (int)mNumInBuffers));\n assert(mpWaveHeaders != NULL);\n assert((mpWaveBuffers != NULL) && (mpWaveBuffers[n] != NULL));\n WAVEHDR* pWave_hdr = &(mpWaveHeaders[n]);\n LPSTR wave_data(mpWaveBuffers[n]);\n\n \/\/ zero out the wave buffer.\n memset(wave_data, 0, mWaveBufSize);\n\n \/\/ Set wave header data to initial values.\n pWave_hdr->lpData = wave_data;\n pWave_hdr->dwBufferLength = mWaveBufSize;\n pWave_hdr->dwBytesRecorded = 0; \/\/ Filled in by wave functions\n pWave_hdr->dwUser = n;\n pWave_hdr->dwFlags = 0;\n pWave_hdr->dwLoops = 0;\n pWave_hdr->lpNext = NULL;\n pWave_hdr->reserved = 0;\n\n return pWave_hdr;\n}\nvoid MpidWinMM::processAudioInput(HWAVEIN hwi,\n UINT uMsg,\n void* dwParam1)\n{\n if (!mIsOpen)\n {\n assert(uMsg == WIM_OPEN);\n if (uMsg == WIM_OPEN)\n {\n \/\/printf(\"received WIM_OPEN\\n\");\n mIsOpen = TRUE;\n }\n }\n if (uMsg == WIM_DATA)\n {\n \/\/printf(\"received WIM_DATA\\n\");\n assert(mIsOpen);\n WAVEHDR* pWaveHdr = (WAVEHDR*)dwParam1;\n assert(pWaveHdr->dwBufferLength \n == (mSamplesPerFrame*sizeof(MpAudioSample)));\n assert(pWaveHdr->lpData != NULL);\n\n \/\/ Only process if we're enabled..\n if(mIsEnabled)\n {\n mpInputDeviceManager->pushFrame(mDeviceId,\n mSamplesPerFrame,\n (MpAudioSample*)pWaveHdr->lpData,\n mCurrentFrameTime);\n \/\/ Ok, we have received and pushed a frame to the manager,\n \/\/ Now we advance the frame time.\n mCurrentFrameTime += (mSamplesPerFrame*1000)\/mSamplesPerSec;\n }\n\n if(mIsEnabled)\n {\n \/\/ Put the wave header back in the pool..\n MMRESULT res = MMSYSERR_NOERROR;\n\n res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInAddBuffer\", res, -1, __LINE__);\n mnAddBufferFailures++;\n if(mnAddBufferFailures >= mNumInBuffers)\n {\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n }\n }\n }\n }\n else if (uMsg == WIM_CLOSE)\n {\n printf(\"received WIM_CLOSE\\n\");\n mIsOpen = FALSE;\n }\n}\n\nvoid CALLBACK \nMpidWinMM::waveInCallbackStatic(HWAVEIN hwi,\n UINT uMsg, \n void* dwInstance,\n void* dwParam1, \n void* dwParam2)\n{\n assert(dwInstance != NULL);\n MpidWinMM* iddWntPtr = (MpidWinMM*)dwInstance;\n assert((uMsg == WIM_OPEN) || (hwi == iddWntPtr->mDevHandle));\n iddWntPtr->processAudioInput(hwi, uMsg, dwParam1);\n}\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\nMinor cleanup and disabling of debug output in MpidWinMM.\/\/ \n\/\/ Copyright (C) 2007 SIPez LLC. \n\/\/ Licensed to SIPfoundry under a Contributor Agreement. \n\/\/\n\/\/ Copyright (C) 2007 SIPfoundry Inc.\n\/\/ Licensed by SIPfoundry under the LGPL license.\n\/\/\n\/\/ $$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ Author: Keith Kyzivat \n\n\n\/\/ SYSTEM INCLUDES\n#include \n\n\/\/ APPLICATION INCLUDES\n#include \"mp\/MpidWinMM.h\"\n#include \"mp\/MpInputDeviceManager.h\"\n\n\/\/ EXTERNAL FUNCTIONS\nextern void showWaveError(char *syscall, int e, int N, int line) ; \/\/ dmaTaskWnt.cpp\n\n\/\/ EXTERNAL VARIABLES\n\/\/ CONSTANTS\n\/\/ STATIC VARIABLE INITIALIZATIONS\n\/\/ DEFINES\n#if defined(_MSC_VER) && (_MSC_VER < 1300) \/\/ if < msvc7 (2003)\n# define CBTYPE DWORD\n#else\n# define CBTYPE DWORD_PTR\n#endif\n\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\/* ============================ CREATORS ================================== *\/\n\/\/ Default constructor\nMpidWinMM::MpidWinMM(const UtlString& name, \n MpInputDeviceManager& deviceManager,\n unsigned nInputBuffers)\n: MpInputDeviceDriver(name, deviceManager)\n, mWinMMDeviceId(-1)\n, mDevHandle(NULL)\n, mNumInBuffers(nInputBuffers)\n, mWaveBufSize(0) \/\/ Unknown until enableDevice()\n, mIsOpen(FALSE)\n, mnAddBufferFailures(0)\n{\n WAVEINCAPS devCaps;\n \/\/ Grab the number of input devices that are available.\n UINT nInputDevs = waveInGetNumDevs();\n\n \/\/ Search through the input devices looking for the input device specified.\n MMRESULT wavResult = MMSYSERR_NOERROR;\n unsigned i;\n for (i = 0; i < nInputDevs; i++)\n {\n MMRESULT res = waveInGetDevCaps(i, &devCaps, sizeof(devCaps));\n if (res != MMSYSERR_NOERROR)\n {\n wavResult = res;\n } \n else if (strncmp(name, devCaps.szPname, MAXPNAMELEN) == 0)\n {\n mWinMMDeviceId = i;\n break;\n }\n }\n\n \/\/ Allocate the wave headers and buffer pointers for use with \n \/\/ windows audio routines. \n \/\/(This does *not* include allocation of the buffers themselves -\n \/\/ that is handled in enableDevice, as we don't know the \n \/\/ buffer size (#samplesPerFrame) until then.\n mpWaveHeaders = new WAVEHDR[mNumInBuffers];\n mpWaveBuffers = new LPSTR[mNumInBuffers];\n for (i = 0; i < mNumInBuffers; i++)\n {\n mpWaveBuffers[i] = NULL;\n }\n}\n\n\/\/ Destructor\nMpidWinMM::~MpidWinMM() \n{\n \/\/ If we happen to still be enabled at this point, disable the device.\n assert(!isEnabled());\n if (isEnabled())\n {\n disableDevice();\n }\n\n \/\/ Delete the sample headers and sample buffer pointers..\n unsigned i;\n for (i = 0; i < mNumInBuffers; i++)\n {\n assert(mpWaveBuffers[i] == NULL);\n if (mpWaveBuffers[i] != NULL)\n {\n delete[] mpWaveBuffers[i];\n mpWaveBuffers[i] = NULL;\n }\n }\n delete[] mpWaveBuffers;\n delete[] mpWaveHeaders;\n}\n\n\n\/* ============================ MANIPULATORS ============================== *\/\n\nOsStatus MpidWinMM::enableDevice(unsigned samplesPerFrame, \n unsigned samplesPerSec, \n MpFrameTime currentFrameTime)\n{\n OsStatus status = OS_SUCCESS;\n\n \/\/ reset the number of addBuffer failures, as we're starting fresh now.\n mnAddBufferFailures = 0;\n\n \/\/ If the device is not valid, let the user know it's bad.\n if (!isDeviceValid())\n {\n return OS_INVALID_STATE; \/\/ perhaps new OsState of OS_RESOURCE_INVALID?\n }\n\n if (isEnabled())\n {\n return OS_FAILED;\n }\n\n \/\/ Set some wave header stat information.\n mSamplesPerFrame = samplesPerFrame;\n mSamplesPerSec = samplesPerSec;\n mCurrentFrameTime = currentFrameTime;\n\n \/\/ Do stuff to enable device.\n int nChannels = 1;\n WAVEFORMATEX wavFormat;\n wavFormat.wFormatTag = WAVE_FORMAT_PCM;\n wavFormat.nChannels = nChannels;\n wavFormat.nSamplesPerSec = mSamplesPerSec;\n wavFormat.nAvgBytesPerSec = \n nChannels * mSamplesPerSec * sizeof(MpAudioSample);\n wavFormat.nBlockAlign = nChannels * sizeof(MpAudioSample);\n wavFormat.wBitsPerSample = sizeof(MpAudioSample) * 8;\n wavFormat.cbSize = 0;\n\n \/\/ Tell windows to open the input audio device. This doesn't\n \/\/ tell it to send the data to our callback yet, just to get it ready\n \/\/ to do so..\n MMRESULT res = waveInOpen(&mDevHandle, mWinMMDeviceId,\n &wavFormat,\n (CBTYPE)waveInCallbackStatic,\n (CBTYPE)this, \n CALLBACK_FUNCTION);\n if (res != MMSYSERR_NOERROR)\n {\n \/\/ If waveInOpen failed, print out the error info,\n \/\/ invalidate the handle, and the device driver itself,\n status = OS_FAILED;\n showWaveError(\"MpidWinMM::enableDevice\", res, -1, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL; \/\/ Open didn't work, reset device handle to NULL\n mWinMMDeviceId = -1; \/\/ Make device invalid.\n\n \/\/ and return OS_FAILED.\n return status;\n }\n\n\n \/\/ Allocate the buffers we are going to use to receive audio data from\n \/\/ the windows audio input callback.\n \/\/ Calculate the buffer length we're going to use. \n \/\/ number of samples per frame * sample size in bytes\n mWaveBufSize = mSamplesPerFrame * sizeof(MpAudioSample); \n unsigned i;\n for (i = 0; i < mNumInBuffers; i++)\n {\n mpWaveBuffers[i] = new char[mWaveBufSize];\n }\n\n\n \/\/ Setup the buffers so windows can stuff them full of audio\n \/\/ when it becomes available from this audio input device.\n WAVEHDR* pWaveHdr = NULL;\n for (i=0; i < mNumInBuffers; i++) \n {\n pWaveHdr = initWaveHeader(i);\n\n res = waveInPrepareHeader(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInPrepareHeader\", res, i, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInAddBuffer\", res, i, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n }\n\n \/\/ Tell windows to start sending audio data to the callback.\n res = waveInStart(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n \/\/ If waveInStart failed, print out the error info,\n \/\/ invalidate the handle and the device driver itself,\n status = OS_FAILED;\n showWaveError(\"waveInStart\", res, -1, __LINE__);\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n\n \/\/ and return OS_FAILED.\n return status;\n }\n\n \/\/ If enableDevice failed, return indicating failure.\n if (status == OS_SUCCESS)\n {\n mIsEnabled = TRUE;\n }\n\n return status;\n}\n\nOsStatus MpidWinMM::disableDevice()\n{\n OsStatus status = OS_SUCCESS;\n MMRESULT res;\n \n if (!isDeviceValid() || !isEnabled())\n {\n return OS_FAILED;\n }\n\n \/\/ Indicate we are no longer enabled -- Do this first,\n \/\/ since we'll be partially disabled from here on out.\n \/\/ It is very important that this happen *before* waveInReset,\n \/\/ as the callback will continue to add and process buffers\n \/\/ while waveInReset is called causing a deadlock.\n mIsEnabled = FALSE;\n\n \/\/ Cleanup\n if (mDevHandle == NULL)\n {\n return OS_INVALID_STATE;\n }\n\n \/\/ Reset performs a stop, resets the buffers, and marks them\n \/\/ for being sent to the callback.\n \/\/ The remaining data in the windows buffers *IS* sent to the callback,\n \/\/ So be sure to watch for it and drop it on the floor.\n res = waveInReset(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInReset\", res, -1, __LINE__);\n } \n\n \/\/ Must unprepare the headers after a reset, but before the device is closed\n \/\/ (if this is done after waveInClose, mDevHandle will be invalid and \n \/\/ MMSYSERR_INVALHANDLE will be returned.\n unsigned i;\n for (i=0; i < mNumInBuffers; i++) \n {\n res = waveInUnprepareHeader(mDevHandle, &mpWaveHeaders[i], sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInUnprepareHeader\", res, i, __LINE__);\n }\n }\n\n res = waveInClose(mDevHandle);\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInClose\", res, -1, __LINE__);\n }\n\n \/\/ Delete the buffers that were allocated in enableDevice()\n for (i = 0; i < mNumInBuffers; i++)\n {\n delete[] mpWaveBuffers[i];\n mpWaveBuffers[i] = NULL;\n }\n\n \/\/ set the device handle to NULL, since it no longer is valid.\n mDevHandle = NULL;\n\n \/\/ Clear out all the wave header information.\n mSamplesPerFrame = 0;\n mSamplesPerSec = 0;\n mCurrentFrameTime = 0;\n\n return status;\n}\n\n\/* ============================ ACCESSORS ================================= *\/\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PUBLIC STATIC \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\nUtlString MpidWinMM::getDefaultDeviceName()\n{\n UtlString devName = \"\";\n\n \/\/ Get windows default input device name\n unsigned nDevs = waveInGetNumDevs();\n if (nDevs == 0)\n {\n OsSysLog::add(FAC_AUDIO, PRI_ERR, \n \"MpidWinMM::getDefaultDeviceName: \"\n \"No input audio devices present!\");\n }\n assert(nDevs != 0);\n\n MMRESULT wavResult = MMSYSERR_NOERROR;\n WAVEINCAPS devCaps;\n int defaultWinDeviceId = 0;\n wavResult = \n waveInGetDevCaps(defaultWinDeviceId, &devCaps, sizeof(devCaps));\n if (wavResult != MMSYSERR_NOERROR)\n {\n OsSysLog::add(FAC_AUDIO, PRI_ERR, \n \"MpodWinMM::getDefaultDeviceName: \"\n \"Couldn't get default input device capabilities!\");\n showWaveError(\"WINDOWS_DEFAULT_DEVICE_HACK\",\n wavResult, -1, __LINE__);\n }\n else\n {\n devName = devCaps.szPname;\n }\n assert(wavResult == MMSYSERR_NOERROR);\n return devName;\n}\n\n\n\/* ============================ INQUIRY =================================== *\/\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PROTECTED \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\nWAVEHDR* MpidWinMM::initWaveHeader(int n)\n{\n assert((n >= 0) && (n < (int)mNumInBuffers));\n assert(mpWaveHeaders != NULL);\n assert((mpWaveBuffers != NULL) && (mpWaveBuffers[n] != NULL));\n WAVEHDR* pWave_hdr = &(mpWaveHeaders[n]);\n\n \/\/ zero out the wave buffer.\n memset(mpWaveBuffers[n], 0, mWaveBufSize);\n\n \/\/ Set wave header data to initial values.\n pWave_hdr->lpData = mpWaveBuffers[n];\n pWave_hdr->dwBufferLength = mWaveBufSize;\n pWave_hdr->dwBytesRecorded = 0; \/\/ Filled in by wave functions\n pWave_hdr->dwUser = n;\n pWave_hdr->dwFlags = 0;\n pWave_hdr->dwLoops = 0;\n pWave_hdr->lpNext = NULL;\n pWave_hdr->reserved = 0;\n\n return pWave_hdr;\n}\nvoid MpidWinMM::processAudioInput(HWAVEIN hwi,\n UINT uMsg,\n void* dwParam1)\n{\n if (!mIsOpen)\n {\n assert(uMsg == WIM_OPEN);\n if (uMsg == WIM_OPEN)\n {\n\/\/ printf(\"received WIM_OPEN\\n\"); fflush(stdout);\n mIsOpen = TRUE;\n }\n }\n if (uMsg == WIM_DATA)\n {\n\/\/ printf(\"received WIM_DATA\\n\"); fflush(stdout);\n assert(mIsOpen);\n WAVEHDR* pWaveHdr = (WAVEHDR*)dwParam1;\n assert(pWaveHdr->dwBufferLength \n == (mSamplesPerFrame*sizeof(MpAudioSample)));\n assert(pWaveHdr->lpData != NULL);\n\n \/\/ Only process if we're enabled..\n if(mIsEnabled)\n {\n mpInputDeviceManager->pushFrame(mDeviceId,\n mSamplesPerFrame,\n (MpAudioSample*)pWaveHdr->lpData,\n mCurrentFrameTime);\n \/\/ Ok, we have received and pushed a frame to the manager,\n \/\/ Now we advance the frame time.\n mCurrentFrameTime += (mSamplesPerFrame*1000)\/mSamplesPerSec;\n }\n\n if(mIsEnabled)\n {\n \/\/ Put the wave header back in the pool..\n MMRESULT res = MMSYSERR_NOERROR;\n\n res = waveInAddBuffer(mDevHandle, pWaveHdr, sizeof(WAVEHDR));\n if (res != MMSYSERR_NOERROR)\n {\n showWaveError(\"waveInAddBuffer\", res, -1, __LINE__);\n mnAddBufferFailures++;\n if(mnAddBufferFailures >= mNumInBuffers)\n {\n waveInClose(mDevHandle);\n mDevHandle = NULL;\n mWinMMDeviceId = -1;\n }\n }\n }\n }\n else if (uMsg == WIM_CLOSE)\n {\n\/\/ printf(\"received WIM_CLOSE\\n\"); fflush(stdout);\n mIsOpen = FALSE;\n }\n}\n\nvoid CALLBACK \nMpidWinMM::waveInCallbackStatic(HWAVEIN hwi,\n UINT uMsg, \n void* dwInstance,\n void* dwParam1, \n void* dwParam2)\n{\n assert(dwInstance != NULL);\n MpidWinMM* iddWntPtr = (MpidWinMM*)dwInstance;\n assert((uMsg == WIM_OPEN) || (hwi == iddWntPtr->mDevHandle));\n iddWntPtr->processAudioInput(hwi, uMsg, dwParam1);\n}\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ PRIVATE \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n<|endoftext|>"} {"text":"[fix] use Add for full bit prime (now not used)<|endoftext|>"} {"text":"ReadUniStringLine never called without explicit length<|endoftext|>"} {"text":"record the ESS before resampling, which is more useful<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: srchdlg.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 22:53:39 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef _SFX_SRCHDLG_HXX_\n#define _SFX_SRCHDLG_HXX_\n\n#ifndef _VCL_BUTTON_HXX\n#include \n#endif\n#ifndef _SV_COMBOBOX_HXX\n#include \n#endif\n#ifndef _VCL_EDIT_HXX\n#include \n#endif\n#ifndef _VCL_FIXED_HXX\n#include \n#endif\n\n#ifndef _BASEDLGS_HXX\n#include \n#endif\n\n\/\/ ============================================================================\n\nnamespace sfx2 {\n\n\/\/ ============================================================================\n\/\/ SearchDialog\n\/\/ ============================================================================\n\nclass SearchDialog : public ModelessDialog\n{\nprivate:\n FixedText m_aSearchLabel;\n ComboBox m_aSearchEdit;\n CheckBox m_aWholeWordsBox;\n CheckBox m_aMatchCaseBox;\n CheckBox m_aWrapAroundBox;\n CheckBox m_aBackwardsBox;\n PushButton m_aFindBtn;\n CancelButton m_aCancelBtn;\n\n Link m_aFindHdl;\n Link m_aCloseHdl;\n\n String m_sToggleText;\n ::rtl::OUString m_sConfigName;\n ByteString m_sWinState;\n\n bool m_bIsConstructed;\n\n void LoadConfig();\n void SaveConfig();\n\n DECL_LINK( FindHdl, PushButton* );\n DECL_LINK( ToggleHdl, CheckBox* );\n\npublic:\n SearchDialog( Window* pWindow, const ::rtl::OUString& rConfigName );\n ~SearchDialog();\n\n inline void SetFindHdl( const Link& rLink ) { m_aFindHdl = rLink; }\n inline void SetCloseHdl( const Link& rLink ) { m_aCloseHdl = rLink; }\n\n inline String GetSearchText() const { return m_aSearchEdit.GetText(); }\n inline void SetSearchText( const String& _rText ) { m_aSearchEdit.SetText( _rText ); }\n inline bool IsOnlyWholeWords() const { return ( m_aWholeWordsBox.IsChecked() != FALSE ); }\n inline bool IsMarchCase() const { return ( m_aMatchCaseBox.IsChecked() != FALSE ); }\n inline bool IsWrapAround() const { return ( m_aWrapAroundBox.IsChecked() != FALSE ); }\n inline bool IsSearchBackwards() const { return ( m_aBackwardsBox.IsChecked() != FALSE ); }\n\n void SetFocusOnEdit();\n\n virtual BOOL Close();\n virtual void Move();\n virtual void StateChanged( StateChangedType nStateChange );\n};\n\n\/\/ ============================================================================\n\n} \/\/ namespace sfx2\n\n\/\/ ============================================================================\n\n#endif \/\/ _SFX_SRCHDLG_HXX_\n\nINTEGRATION: CWS changefileheader (1.4.216); FILE MERGED 2008\/04\/01 15:38:17 thb 1.4.216.3: #i85898# Stripping all external header guards 2008\/04\/01 12:40:33 thb 1.4.216.2: #i85898# Stripping all external header guards 2008\/03\/31 13:37:54 rt 1.4.216.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: srchdlg.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef _SFX_SRCHDLG_HXX_\n#define _SFX_SRCHDLG_HXX_\n\n#ifndef _VCL_BUTTON_HXX\n#include \n#endif\n#include \n#ifndef _VCL_EDIT_HXX\n#include \n#endif\n#ifndef _VCL_FIXED_HXX\n#include \n#endif\n#include \n\n\/\/ ============================================================================\n\nnamespace sfx2 {\n\n\/\/ ============================================================================\n\/\/ SearchDialog\n\/\/ ============================================================================\n\nclass SearchDialog : public ModelessDialog\n{\nprivate:\n FixedText m_aSearchLabel;\n ComboBox m_aSearchEdit;\n CheckBox m_aWholeWordsBox;\n CheckBox m_aMatchCaseBox;\n CheckBox m_aWrapAroundBox;\n CheckBox m_aBackwardsBox;\n PushButton m_aFindBtn;\n CancelButton m_aCancelBtn;\n\n Link m_aFindHdl;\n Link m_aCloseHdl;\n\n String m_sToggleText;\n ::rtl::OUString m_sConfigName;\n ByteString m_sWinState;\n\n bool m_bIsConstructed;\n\n void LoadConfig();\n void SaveConfig();\n\n DECL_LINK( FindHdl, PushButton* );\n DECL_LINK( ToggleHdl, CheckBox* );\n\npublic:\n SearchDialog( Window* pWindow, const ::rtl::OUString& rConfigName );\n ~SearchDialog();\n\n inline void SetFindHdl( const Link& rLink ) { m_aFindHdl = rLink; }\n inline void SetCloseHdl( const Link& rLink ) { m_aCloseHdl = rLink; }\n\n inline String GetSearchText() const { return m_aSearchEdit.GetText(); }\n inline void SetSearchText( const String& _rText ) { m_aSearchEdit.SetText( _rText ); }\n inline bool IsOnlyWholeWords() const { return ( m_aWholeWordsBox.IsChecked() != FALSE ); }\n inline bool IsMarchCase() const { return ( m_aMatchCaseBox.IsChecked() != FALSE ); }\n inline bool IsWrapAround() const { return ( m_aWrapAroundBox.IsChecked() != FALSE ); }\n inline bool IsSearchBackwards() const { return ( m_aBackwardsBox.IsChecked() != FALSE ); }\n\n void SetFocusOnEdit();\n\n virtual BOOL Close();\n virtual void Move();\n virtual void StateChanged( StateChangedType nStateChange );\n};\n\n\/\/ ============================================================================\n\n} \/\/ namespace sfx2\n\n\/\/ ============================================================================\n\n#endif \/\/ _SFX_SRCHDLG_HXX_\n\n<|endoftext|>"} {"text":"\/\/===- lib\/ReaderWriter\/FileArchive.cpp -----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/Core\/ArchiveLibraryFile.h\"\n#include \"lld\/Core\/LLVM.h\"\n#include \"lld\/Core\/LinkingContext.h\"\n#include \"lld\/Core\/Parallel.h\"\n#include \"llvm\/ADT\/Hashing.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Object\/Archive.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \n#include \n#include \n#include \n\nusing llvm::object::Archive;\nusing llvm::object::ObjectFile;\nusing llvm::object::SymbolRef;\nusing llvm::object::symbol_iterator;\nusing llvm::object::object_error;\n\nnamespace lld {\n\nnamespace {\n\n\/\/\/ \\brief The FileArchive class represents an Archive Library file\nclass FileArchive : public lld::ArchiveLibraryFile {\npublic:\n FileArchive(std::unique_ptr mb, const Registry ®,\n StringRef path, bool logLoading)\n : ArchiveLibraryFile(path), _mb(std::shared_ptr(mb.release())),\n _registry(reg), _logLoading(logLoading) {}\n\n \/\/\/ \\brief Check if any member of the archive contains an Atom with the\n \/\/\/ specified name and return the File object for that member, or nullptr.\n File *find(StringRef name, bool dataSymbolOnly) override {\n auto member = _symbolMemberMap.find(name);\n if (member == _symbolMemberMap.end())\n return nullptr;\n Archive::child_iterator ci = member->second;\n\n \/\/ Don't return a member already returned\n const char *memberStart = ci->getBuffer().data();\n if (_membersInstantiated.count(memberStart))\n return nullptr;\n if (dataSymbolOnly && !isDataSymbol(ci, name))\n return nullptr;\n\n _membersInstantiated.insert(memberStart);\n\n \/\/ Check if a file is preloaded.\n {\n std::lock_guard lock(_mutex);\n auto it = _preloaded.find(memberStart);\n if (it != _preloaded.end()) {\n std::unique_ptr> &p = it->second;\n Future *future = p.get();\n return future->get();\n }\n }\n\n std::unique_ptr result;\n if (instantiateMember(ci, result))\n return nullptr;\n\n \/\/ give up the pointer so that this object no longer manages it\n return result.release();\n }\n\n \/\/ Instantiate a member file containing a given symbol name.\n void preload(TaskGroup &group, StringRef name) override {\n auto member = _symbolMemberMap.find(name);\n if (member == _symbolMemberMap.end())\n return;\n Archive::child_iterator ci = member->second;\n\n \/\/ Do nothing if a member is already instantiated.\n const char *memberStart = ci->getBuffer().data();\n if (_membersInstantiated.count(memberStart))\n return;\n\n std::lock_guard lock(_mutex);\n if (_preloaded.find(memberStart) != _preloaded.end())\n return;\n\n \/\/ Instantiate the member\n auto *future = new Future();\n _preloaded[memberStart] = std::unique_ptr>(future);\n\n group.spawn([=] {\n std::unique_ptr result;\n std::error_code ec = instantiateMember(ci, result);\n future->set(ec ? nullptr : result.release());\n });\n }\n\n \/\/\/ \\brief parse each member\n std::error_code\n parseAllMembers(std::vector> &result) override {\n if (std::error_code ec = parse())\n return ec;\n for (auto mf = _archive->child_begin(), me = _archive->child_end();\n mf != me; ++mf) {\n std::unique_ptr file;\n if (std::error_code ec = instantiateMember(mf, file))\n return ec;\n result.push_back(std::move(file));\n }\n return std::error_code();\n }\n\n const AtomVector &defined() const override {\n return _noDefinedAtoms;\n }\n\n const AtomVector &undefined() const override {\n return _noUndefinedAtoms;\n }\n\n const AtomVector &sharedLibrary() const override {\n return _noSharedLibraryAtoms;\n }\n\n const AtomVector &absolute() const override {\n return _noAbsoluteAtoms;\n }\n\n \/\/\/ Returns a set of all defined symbols in the archive.\n std::set getDefinedSymbols() override {\n parse();\n std::set ret;\n for (const auto &e : _symbolMemberMap)\n ret.insert(e.first);\n return ret;\n }\n\nprotected:\n std::error_code doParse() override {\n \/\/ Make Archive object which will be owned by FileArchive object.\n std::error_code ec;\n _archive.reset(new Archive(_mb->getMemBufferRef(), ec));\n if (ec)\n return ec;\n if ((ec = buildTableOfContents()))\n return ec;\n return std::error_code();\n }\n\nprivate:\n std::error_code\n instantiateMember(Archive::child_iterator member,\n std::unique_ptr &result) const {\n ErrorOr mbOrErr = member->getMemoryBufferRef();\n if (std::error_code ec = mbOrErr.getError())\n return ec;\n llvm::MemoryBufferRef mb = mbOrErr.get();\n std::string memberPath = (_archive->getFileName() + \"(\"\n + mb.getBufferIdentifier() + \")\").str();\n\n if (_logLoading)\n llvm::errs() << memberPath << \"\\n\";\n\n std::unique_ptr memberMB(MemoryBuffer::getMemBuffer(\n mb.getBuffer(), mb.getBufferIdentifier(), false));\n\n ErrorOr> fileOrErr =\n _registry.loadFile(std::move(memberMB));\n if (std::error_code ec = fileOrErr.getError())\n return ec;\n result = std::move(fileOrErr.get());\n if (std::error_code ec = result->parse())\n return ec;\n result->setArchivePath(_archive->getFileName());\n\n \/\/ The memory buffer is co-owned by the archive file and the children,\n \/\/ so that the bufffer is deallocated when all the members are destructed.\n result->setSharedMemoryBuffer(_mb);\n return std::error_code();\n }\n\n \/\/ Parses the given memory buffer as an object file, and returns true\n \/\/ code if the given symbol is a data symbol. If the symbol is not a data\n \/\/ symbol or does not exist, returns false.\n bool isDataSymbol(Archive::child_iterator member, StringRef symbol) const {\n ErrorOr buf = member->getMemoryBufferRef();\n if (buf.getError())\n return false;\n std::unique_ptr mb(MemoryBuffer::getMemBuffer(\n buf.get().getBuffer(), buf.get().getBufferIdentifier(), false));\n\n auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef()));\n if (objOrErr.getError())\n return false;\n std::unique_ptr obj = std::move(objOrErr.get());\n\n for (SymbolRef sym : obj->symbols()) {\n \/\/ Skip until we find the symbol.\n ErrorOr name = sym.getName();\n if (!name)\n return false;\n if (*name != symbol)\n continue;\n uint32_t flags = sym.getFlags();\n if (flags <= SymbolRef::SF_Undefined)\n continue;\n\n \/\/ Returns true if it's a data symbol.\n SymbolRef::Type type = sym.getType();\n if (type == SymbolRef::ST_Data)\n return true;\n }\n return false;\n }\n\n std::error_code buildTableOfContents() {\n DEBUG_WITH_TYPE(\"FileArchive\", llvm::dbgs()\n << \"Table of contents for archive '\"\n << _archive->getFileName() << \"':\\n\");\n for (const Archive::Symbol &sym : _archive->symbols()) {\n StringRef name = sym.getName();\n ErrorOr memberOrErr = sym.getMember();\n if (std::error_code ec = memberOrErr.getError())\n return ec;\n Archive::child_iterator member = memberOrErr.get();\n DEBUG_WITH_TYPE(\n \"FileArchive\",\n llvm::dbgs() << llvm::format(\"0x%08llX \", member->getBuffer().data())\n << \"'\" << name << \"'\\n\");\n _symbolMemberMap[name] = member;\n }\n return std::error_code();\n }\n\n typedef std::unordered_map MemberMap;\n typedef std::set InstantiatedSet;\n\n std::shared_ptr _mb;\n const Registry &_registry;\n std::unique_ptr _archive;\n MemberMap _symbolMemberMap;\n InstantiatedSet _membersInstantiated;\n bool _logLoading;\n std::vector> _memberBuffers;\n std::map>> _preloaded;\n std::mutex _mutex;\n};\n\nclass ArchiveReader : public Reader {\npublic:\n ArchiveReader(bool logLoading) : _logLoading(logLoading) {}\n\n bool canParse(file_magic magic, MemoryBufferRef) const override {\n return magic == llvm::sys::fs::file_magic::archive;\n }\n\n ErrorOr> loadFile(std::unique_ptr mb,\n const Registry ®) const override {\n StringRef path = mb->getBufferIdentifier();\n std::unique_ptr ret =\n llvm::make_unique(std::move(mb), reg, path, _logLoading);\n return std::move(ret);\n }\n\nprivate:\n bool _logLoading;\n};\n\n} \/\/ anonymous namespace\n\nvoid Registry::addSupportArchives(bool logLoading) {\n add(std::unique_ptr(new ArchiveReader(logLoading)));\n}\n\n} \/\/ end namespace lld\nUpdate for upcoming llvm change.\/\/===- lib\/ReaderWriter\/FileArchive.cpp -----------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"lld\/Core\/ArchiveLibraryFile.h\"\n#include \"lld\/Core\/LLVM.h\"\n#include \"lld\/Core\/LinkingContext.h\"\n#include \"lld\/Core\/Parallel.h\"\n#include \"llvm\/ADT\/Hashing.h\"\n#include \"llvm\/ADT\/StringRef.h\"\n#include \"llvm\/Object\/Archive.h\"\n#include \"llvm\/Object\/ObjectFile.h\"\n#include \"llvm\/Support\/Debug.h\"\n#include \"llvm\/Support\/Format.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \n#include \n#include \n#include \n\nusing llvm::object::Archive;\nusing llvm::object::ObjectFile;\nusing llvm::object::SymbolRef;\nusing llvm::object::symbol_iterator;\nusing llvm::object::object_error;\n\nnamespace lld {\n\nnamespace {\n\n\/\/\/ \\brief The FileArchive class represents an Archive Library file\nclass FileArchive : public lld::ArchiveLibraryFile {\npublic:\n FileArchive(std::unique_ptr mb, const Registry ®,\n StringRef path, bool logLoading)\n : ArchiveLibraryFile(path), _mb(std::shared_ptr(mb.release())),\n _registry(reg), _logLoading(logLoading) {}\n\n \/\/\/ \\brief Check if any member of the archive contains an Atom with the\n \/\/\/ specified name and return the File object for that member, or nullptr.\n File *find(StringRef name, bool dataSymbolOnly) override {\n auto member = _symbolMemberMap.find(name);\n if (member == _symbolMemberMap.end())\n return nullptr;\n Archive::child_iterator ci = member->second;\n\n \/\/ Don't return a member already returned\n const char *memberStart = ci->getBuffer().data();\n if (_membersInstantiated.count(memberStart))\n return nullptr;\n if (dataSymbolOnly && !isDataSymbol(ci, name))\n return nullptr;\n\n _membersInstantiated.insert(memberStart);\n\n \/\/ Check if a file is preloaded.\n {\n std::lock_guard lock(_mutex);\n auto it = _preloaded.find(memberStart);\n if (it != _preloaded.end()) {\n std::unique_ptr> &p = it->second;\n Future *future = p.get();\n return future->get();\n }\n }\n\n std::unique_ptr result;\n if (instantiateMember(ci, result))\n return nullptr;\n\n \/\/ give up the pointer so that this object no longer manages it\n return result.release();\n }\n\n \/\/ Instantiate a member file containing a given symbol name.\n void preload(TaskGroup &group, StringRef name) override {\n auto member = _symbolMemberMap.find(name);\n if (member == _symbolMemberMap.end())\n return;\n Archive::child_iterator ci = member->second;\n\n \/\/ Do nothing if a member is already instantiated.\n const char *memberStart = ci->getBuffer().data();\n if (_membersInstantiated.count(memberStart))\n return;\n\n std::lock_guard lock(_mutex);\n if (_preloaded.find(memberStart) != _preloaded.end())\n return;\n\n \/\/ Instantiate the member\n auto *future = new Future();\n _preloaded[memberStart] = std::unique_ptr>(future);\n\n group.spawn([=] {\n std::unique_ptr result;\n std::error_code ec = instantiateMember(ci, result);\n future->set(ec ? nullptr : result.release());\n });\n }\n\n \/\/\/ \\brief parse each member\n std::error_code\n parseAllMembers(std::vector> &result) override {\n if (std::error_code ec = parse())\n return ec;\n for (auto mf = _archive->child_begin(), me = _archive->child_end();\n mf != me; ++mf) {\n std::unique_ptr file;\n if (std::error_code ec = instantiateMember(mf, file))\n return ec;\n result.push_back(std::move(file));\n }\n return std::error_code();\n }\n\n const AtomVector &defined() const override {\n return _noDefinedAtoms;\n }\n\n const AtomVector &undefined() const override {\n return _noUndefinedAtoms;\n }\n\n const AtomVector &sharedLibrary() const override {\n return _noSharedLibraryAtoms;\n }\n\n const AtomVector &absolute() const override {\n return _noAbsoluteAtoms;\n }\n\n \/\/\/ Returns a set of all defined symbols in the archive.\n std::set getDefinedSymbols() override {\n parse();\n std::set ret;\n for (const auto &e : _symbolMemberMap)\n ret.insert(e.first);\n return ret;\n }\n\nprotected:\n std::error_code doParse() override {\n \/\/ Make Archive object which will be owned by FileArchive object.\n std::error_code ec;\n _archive.reset(new Archive(_mb->getMemBufferRef(), ec));\n if (ec)\n return ec;\n if ((ec = buildTableOfContents()))\n return ec;\n return std::error_code();\n }\n\nprivate:\n std::error_code\n instantiateMember(Archive::child_iterator member,\n std::unique_ptr &result) const {\n ErrorOr mbOrErr = member->getMemoryBufferRef();\n if (std::error_code ec = mbOrErr.getError())\n return ec;\n llvm::MemoryBufferRef mb = mbOrErr.get();\n std::string memberPath = (_archive->getFileName() + \"(\"\n + mb.getBufferIdentifier() + \")\").str();\n\n if (_logLoading)\n llvm::errs() << memberPath << \"\\n\";\n\n std::unique_ptr memberMB(MemoryBuffer::getMemBuffer(\n mb.getBuffer(), mb.getBufferIdentifier(), false));\n\n ErrorOr> fileOrErr =\n _registry.loadFile(std::move(memberMB));\n if (std::error_code ec = fileOrErr.getError())\n return ec;\n result = std::move(fileOrErr.get());\n if (std::error_code ec = result->parse())\n return ec;\n result->setArchivePath(_archive->getFileName());\n\n \/\/ The memory buffer is co-owned by the archive file and the children,\n \/\/ so that the bufffer is deallocated when all the members are destructed.\n result->setSharedMemoryBuffer(_mb);\n return std::error_code();\n }\n\n \/\/ Parses the given memory buffer as an object file, and returns true\n \/\/ code if the given symbol is a data symbol. If the symbol is not a data\n \/\/ symbol or does not exist, returns false.\n bool isDataSymbol(Archive::child_iterator member, StringRef symbol) const {\n ErrorOr buf = member->getMemoryBufferRef();\n if (buf.getError())\n return false;\n std::unique_ptr mb(MemoryBuffer::getMemBuffer(\n buf.get().getBuffer(), buf.get().getBufferIdentifier(), false));\n\n auto objOrErr(ObjectFile::createObjectFile(mb->getMemBufferRef()));\n if (objOrErr.getError())\n return false;\n std::unique_ptr obj = std::move(objOrErr.get());\n\n for (SymbolRef sym : obj->symbols()) {\n \/\/ Skip until we find the symbol.\n ErrorOr name = sym.getName();\n if (!name)\n return false;\n if (*name != symbol)\n continue;\n uint32_t flags = sym.getFlags();\n if (flags <= SymbolRef::SF_Undefined)\n continue;\n\n \/\/ Returns true if it's a data symbol.\n SymbolRef::Type type = sym.getType();\n if (type == SymbolRef::ST_Data)\n return true;\n }\n return false;\n }\n\n std::error_code buildTableOfContents() {\n DEBUG_WITH_TYPE(\"FileArchive\", llvm::dbgs()\n << \"Table of contents for archive '\"\n << _archive->getFileName() << \"':\\n\");\n for (const Archive::Symbol &sym : _archive->symbols()) {\n StringRef name = sym.getName();\n ErrorOr memberOrErr = sym.getMember();\n if (std::error_code ec = memberOrErr.getError())\n return ec;\n Archive::child_iterator member = memberOrErr.get();\n DEBUG_WITH_TYPE(\n \"FileArchive\",\n llvm::dbgs() << llvm::format(\"0x%08llX \", member->getBuffer().data())\n << \"'\" << name << \"'\\n\");\n _symbolMemberMap.insert(std::make_pair(name, member));\n }\n return std::error_code();\n }\n\n typedef std::unordered_map MemberMap;\n typedef std::set InstantiatedSet;\n\n std::shared_ptr _mb;\n const Registry &_registry;\n std::unique_ptr _archive;\n MemberMap _symbolMemberMap;\n InstantiatedSet _membersInstantiated;\n bool _logLoading;\n std::vector> _memberBuffers;\n std::map>> _preloaded;\n std::mutex _mutex;\n};\n\nclass ArchiveReader : public Reader {\npublic:\n ArchiveReader(bool logLoading) : _logLoading(logLoading) {}\n\n bool canParse(file_magic magic, MemoryBufferRef) const override {\n return magic == llvm::sys::fs::file_magic::archive;\n }\n\n ErrorOr> loadFile(std::unique_ptr mb,\n const Registry ®) const override {\n StringRef path = mb->getBufferIdentifier();\n std::unique_ptr ret =\n llvm::make_unique(std::move(mb), reg, path, _logLoading);\n return std::move(ret);\n }\n\nprivate:\n bool _logLoading;\n};\n\n} \/\/ anonymous namespace\n\nvoid Registry::addSupportArchives(bool logLoading) {\n add(std::unique_ptr(new ArchiveReader(logLoading)));\n}\n\n} \/\/ end namespace lld\n<|endoftext|>"} {"text":"#include \"hecl\/Runtime.hpp\"\n\n#include \"hecl\/hecl.hpp\"\n\n#include \n\n#if _WIN32\n#include \n#endif\n\n#if WINDOWS_STORE\nusing namespace Windows::Storage;\n#endif\n\nnamespace hecl::Runtime {\nstatic logvisor::Module Log(\"FileStoreManager\");\n\nFileStoreManager::FileStoreManager(SystemStringView domain) : m_domain(domain) {\n#if _WIN32\n#if !WINDOWS_STORE\n WCHAR home[MAX_PATH];\n if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, home)))\n Log.report(logvisor::Fatal, fmt(_SYS_STR(\"unable to locate profile for file store\")));\n\n SystemString path(home);\n#else\n StorageFolder ^ cacheFolder = ApplicationData::Current->LocalCacheFolder;\n SystemString path(cacheFolder->Path->Data());\n#endif\n path += _SYS_STR(\"\/.heclrun\");\n\n hecl::MakeDir(path.c_str());\n path += _SYS_STR('\/');\n path += domain.data();\n\n hecl::MakeDir(path.c_str());\n m_storeRoot = path;\n#else\n const char* xdg_data_home = getenv(\"XDG_DATA_HOME\");\n std::string path;\n if (xdg_data_home) {\n if (xdg_data_home[0] != '\/')\n Log.report(logvisor::Fatal, fmt(\"invalid $XDG_DATA_HOME for file store (must be absolute)\"));\n path = xdg_data_home;\n } else {\n const char* home = getenv(\"HOME\");\n if (!home)\n Log.report(logvisor::Fatal, fmt(\"unable to locate $HOME for file store\"));\n path = home;\n path += \"\/.local\/share\"\n }\n path += \"\/hecl\";\n if (mkdir(path.c_str(), 0755) && errno != EEXIST)\n Log.report(logvisor::Fatal, fmt(\"unable to mkdir at {}\"), path);\n path += '\/';\n path += domain.data();\n if (mkdir(path.c_str(), 0755) && errno != EEXIST)\n Log.report(logvisor::Fatal, fmt(\"unable to mkdir at {}\"), path);\n m_storeRoot = path;\n#endif\n}\n\n} \/\/ namespace hecl::Runtime\nCompile fix#include \"hecl\/Runtime.hpp\"\n\n#include \"hecl\/hecl.hpp\"\n\n#include \n\n#if _WIN32\n#include \n#endif\n\n#if WINDOWS_STORE\nusing namespace Windows::Storage;\n#endif\n\nnamespace hecl::Runtime {\nstatic logvisor::Module Log(\"FileStoreManager\");\n\nFileStoreManager::FileStoreManager(SystemStringView domain) : m_domain(domain) {\n#if _WIN32\n#if !WINDOWS_STORE\n WCHAR home[MAX_PATH];\n if (!SUCCEEDED(SHGetFolderPathW(NULL, CSIDL_PROFILE, NULL, 0, home)))\n Log.report(logvisor::Fatal, fmt(_SYS_STR(\"unable to locate profile for file store\")));\n\n SystemString path(home);\n#else\n StorageFolder ^ cacheFolder = ApplicationData::Current->LocalCacheFolder;\n SystemString path(cacheFolder->Path->Data());\n#endif\n path += _SYS_STR(\"\/.heclrun\");\n\n hecl::MakeDir(path.c_str());\n path += _SYS_STR('\/');\n path += domain.data();\n\n hecl::MakeDir(path.c_str());\n m_storeRoot = path;\n#else\n const char* xdg_data_home = getenv(\"XDG_DATA_HOME\");\n std::string path;\n if (xdg_data_home) {\n if (xdg_data_home[0] != '\/')\n Log.report(logvisor::Fatal, fmt(\"invalid $XDG_DATA_HOME for file store (must be absolute)\"));\n path = xdg_data_home;\n } else {\n const char* home = getenv(\"HOME\");\n if (!home)\n Log.report(logvisor::Fatal, fmt(\"unable to locate $HOME for file store\"));\n path = home;\n path += \"\/.local\/share\";\n }\n path += \"\/hecl\";\n if (mkdir(path.c_str(), 0755) && errno != EEXIST)\n Log.report(logvisor::Fatal, fmt(\"unable to mkdir at {}\"), path);\n path += '\/';\n path += domain.data();\n if (mkdir(path.c_str(), 0755) && errno != EEXIST)\n Log.report(logvisor::Fatal, fmt(\"unable to mkdir at {}\"), path);\n m_storeRoot = path;\n#endif\n}\n\n} \/\/ namespace hecl::Runtime\n<|endoftext|>"} {"text":"Updated GMM training seed in mex wrapper to be different each run<|endoftext|>"} {"text":"\/\/===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This transform is designed to eliminate unreachable internal globals from the\n\/\/ program. It uses an aggressive algorithm, searching out globals that are\n\/\/ known to be alive. After it finds all of the globals which are needed, it\n\/\/ deletes whatever is left over. This allows it to delete recursive chunks of\n\/\/ the program which are unreachable.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"globaldce\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \nusing namespace llvm;\n\nSTATISTIC(NumFunctions, \"Number of functions removed\");\nSTATISTIC(NumVariables, \"Number of global variables removed\");\n\nnamespace {\n struct VISIBILITY_HIDDEN GlobalDCE : public ModulePass {\n static char ID; \/\/ Pass identification, replacement for typeid\n GlobalDCE() : ModulePass(&ID) {}\n \n \/\/ run - Do the GlobalDCE pass on the specified module, optionally updating\n \/\/ the specified callgraph to reflect the changes.\n \/\/\n bool runOnModule(Module &M);\n\n private:\n std::set AliveGlobals;\n\n \/\/\/ MarkGlobalIsNeeded - the specific global value as needed, and\n \/\/\/ recursively mark anything that it uses as also needed.\n void GlobalIsNeeded(GlobalValue *GV);\n void MarkUsedGlobalsAsNeeded(Constant *C);\n\n bool SafeToDestroyConstant(Constant* C);\n bool RemoveUnusedGlobalValue(GlobalValue &GV);\n };\n}\n\nchar GlobalDCE::ID = 0;\nstatic RegisterPass X(\"globaldce\", \"Dead Global Elimination\");\n\nModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }\n\nbool GlobalDCE::runOnModule(Module &M) {\n bool Changed = false;\n \/\/ Loop over the module, adding globals which are obviously necessary.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {\n Changed |= RemoveUnusedGlobalValue(*I);\n \/\/ Functions with external linkage are needed if they have a body\n if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&\n !I->isDeclaration())\n GlobalIsNeeded(I);\n }\n\n for (Module::global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I) {\n Changed |= RemoveUnusedGlobalValue(*I);\n \/\/ Externally visible & appending globals are needed, if they have an\n \/\/ initializer.\n if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&\n !I->isDeclaration())\n GlobalIsNeeded(I);\n }\n\n\n for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();\n I != E; ++I) {\n \/\/ Aliases are always needed even if they are not used.\n MarkUsedGlobalsAsNeeded(I->getAliasee());\n }\n\n \/\/ Now that all globals which are needed are in the AliveGlobals set, we loop\n \/\/ through the program, deleting those which are not alive.\n \/\/\n\n \/\/ The first pass is to drop initializers of global variables which are dead.\n std::vector DeadGlobalVars; \/\/ Keep track of dead globals\n for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)\n if (!AliveGlobals.count(I)) {\n DeadGlobalVars.push_back(I); \/\/ Keep track of dead globals\n I->setInitializer(0);\n }\n\n\n \/\/ The second pass drops the bodies of functions which are dead...\n std::vector DeadFunctions;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!AliveGlobals.count(I)) {\n DeadFunctions.push_back(I); \/\/ Keep track of dead globals\n if (!I->isDeclaration())\n I->deleteBody();\n }\n\n if (!DeadFunctions.empty()) {\n \/\/ Now that all interreferences have been dropped, delete the actual objects\n \/\/ themselves.\n for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {\n RemoveUnusedGlobalValue(*DeadFunctions[i]);\n M.getFunctionList().erase(DeadFunctions[i]);\n }\n NumFunctions += DeadFunctions.size();\n Changed = true;\n }\n\n if (!DeadGlobalVars.empty()) {\n for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {\n RemoveUnusedGlobalValue(*DeadGlobalVars[i]);\n M.getGlobalList().erase(DeadGlobalVars[i]);\n }\n NumVariables += DeadGlobalVars.size();\n Changed = true;\n }\n\n \/\/ Make sure that all memory is released\n AliveGlobals.clear();\n return Changed;\n}\n\n\/\/\/ MarkGlobalIsNeeded - the specific global value as needed, and\n\/\/\/ recursively mark anything that it uses as also needed.\nvoid GlobalDCE::GlobalIsNeeded(GlobalValue *G) {\n std::set::iterator I = AliveGlobals.find(G);\n\n \/\/ If the global is already in the set, no need to reprocess it.\n if (I != AliveGlobals.end()) return;\n\n \/\/ Otherwise insert it now, so we do not infinitely recurse\n AliveGlobals.insert(I, G);\n\n if (GlobalVariable *GV = dyn_cast(G)) {\n \/\/ If this is a global variable, we must make sure to add any global values\n \/\/ referenced by the initializer to the alive set.\n if (GV->hasInitializer())\n MarkUsedGlobalsAsNeeded(GV->getInitializer());\n } else if (!isa(G)) {\n \/\/ Otherwise this must be a function object. We have to scan the body of\n \/\/ the function looking for constants and global values which are used as\n \/\/ operands. Any operands of these types must be processed to ensure that\n \/\/ any globals used will be marked as needed.\n Function *F = cast(G);\n \/\/ For all basic blocks...\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n \/\/ For all instructions...\n for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n \/\/ For all operands...\n for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)\n if (GlobalValue *GV = dyn_cast(*U))\n GlobalIsNeeded(GV);\n else if (Constant *C = dyn_cast(*U))\n MarkUsedGlobalsAsNeeded(C);\n }\n}\n\nvoid GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {\n if (GlobalValue *GV = dyn_cast(C))\n GlobalIsNeeded(GV);\n else {\n \/\/ Loop over all of the operands of the constant, adding any globals they\n \/\/ use to the list of needed globals.\n for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I)\n MarkUsedGlobalsAsNeeded(cast(*I));\n }\n}\n\n\/\/ RemoveUnusedGlobalValue - Loop over all of the uses of the specified\n\/\/ GlobalValue, looking for the constant pointer ref that may be pointing to it.\n\/\/ If found, check to see if the constant pointer ref is safe to destroy, and if\n\/\/ so, nuke it. This will reduce the reference count on the global value, which\n\/\/ might make it deader.\n\/\/\nbool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {\n if (GV.use_empty()) return false;\n GV.removeDeadConstantUsers();\n return GV.use_empty();\n}\n\n\/\/ SafeToDestroyConstant - It is safe to destroy a constant iff it is only used\n\/\/ by constants itself. Note that constants cannot be cyclic, so this test is\n\/\/ pretty easy to implement recursively.\n\/\/\nbool GlobalDCE::SafeToDestroyConstant(Constant *C) {\n for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)\n if (Constant *User = dyn_cast(*I)) {\n if (!SafeToDestroyConstant(User)) return false;\n } else {\n return false;\n }\n return true;\n}\nUse actual function name in comments.\/\/===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This transform is designed to eliminate unreachable internal globals from the\n\/\/ program. It uses an aggressive algorithm, searching out globals that are\n\/\/ known to be alive. After it finds all of the globals which are needed, it\n\/\/ deletes whatever is left over. This allows it to delete recursive chunks of\n\/\/ the program which are unreachable.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"globaldce\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/Pass.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \"llvm\/Support\/Compiler.h\"\n#include \nusing namespace llvm;\n\nSTATISTIC(NumFunctions, \"Number of functions removed\");\nSTATISTIC(NumVariables, \"Number of global variables removed\");\n\nnamespace {\n struct VISIBILITY_HIDDEN GlobalDCE : public ModulePass {\n static char ID; \/\/ Pass identification, replacement for typeid\n GlobalDCE() : ModulePass(&ID) {}\n \n \/\/ run - Do the GlobalDCE pass on the specified module, optionally updating\n \/\/ the specified callgraph to reflect the changes.\n \/\/\n bool runOnModule(Module &M);\n\n private:\n std::set AliveGlobals;\n\n \/\/\/ GlobalIsNeeded - the specific global value as needed, and\n \/\/\/ recursively mark anything that it uses as also needed.\n void GlobalIsNeeded(GlobalValue *GV);\n void MarkUsedGlobalsAsNeeded(Constant *C);\n\n bool SafeToDestroyConstant(Constant* C);\n bool RemoveUnusedGlobalValue(GlobalValue &GV);\n };\n}\n\nchar GlobalDCE::ID = 0;\nstatic RegisterPass X(\"globaldce\", \"Dead Global Elimination\");\n\nModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }\n\nbool GlobalDCE::runOnModule(Module &M) {\n bool Changed = false;\n \/\/ Loop over the module, adding globals which are obviously necessary.\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {\n Changed |= RemoveUnusedGlobalValue(*I);\n \/\/ Functions with external linkage are needed if they have a body\n if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&\n !I->isDeclaration())\n GlobalIsNeeded(I);\n }\n\n for (Module::global_iterator I = M.global_begin(), E = M.global_end();\n I != E; ++I) {\n Changed |= RemoveUnusedGlobalValue(*I);\n \/\/ Externally visible & appending globals are needed, if they have an\n \/\/ initializer.\n if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&\n !I->isDeclaration())\n GlobalIsNeeded(I);\n }\n\n\n for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();\n I != E; ++I) {\n \/\/ Aliases are always needed even if they are not used.\n MarkUsedGlobalsAsNeeded(I->getAliasee());\n }\n\n \/\/ Now that all globals which are needed are in the AliveGlobals set, we loop\n \/\/ through the program, deleting those which are not alive.\n \/\/\n\n \/\/ The first pass is to drop initializers of global variables which are dead.\n std::vector DeadGlobalVars; \/\/ Keep track of dead globals\n for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)\n if (!AliveGlobals.count(I)) {\n DeadGlobalVars.push_back(I); \/\/ Keep track of dead globals\n I->setInitializer(0);\n }\n\n\n \/\/ The second pass drops the bodies of functions which are dead...\n std::vector DeadFunctions;\n for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)\n if (!AliveGlobals.count(I)) {\n DeadFunctions.push_back(I); \/\/ Keep track of dead globals\n if (!I->isDeclaration())\n I->deleteBody();\n }\n\n if (!DeadFunctions.empty()) {\n \/\/ Now that all interreferences have been dropped, delete the actual objects\n \/\/ themselves.\n for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {\n RemoveUnusedGlobalValue(*DeadFunctions[i]);\n M.getFunctionList().erase(DeadFunctions[i]);\n }\n NumFunctions += DeadFunctions.size();\n Changed = true;\n }\n\n if (!DeadGlobalVars.empty()) {\n for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {\n RemoveUnusedGlobalValue(*DeadGlobalVars[i]);\n M.getGlobalList().erase(DeadGlobalVars[i]);\n }\n NumVariables += DeadGlobalVars.size();\n Changed = true;\n }\n\n \/\/ Make sure that all memory is released\n AliveGlobals.clear();\n return Changed;\n}\n\n\/\/\/ GlobalIsNeeded - the specific global value as needed, and\n\/\/\/ recursively mark anything that it uses as also needed.\nvoid GlobalDCE::GlobalIsNeeded(GlobalValue *G) {\n std::set::iterator I = AliveGlobals.find(G);\n\n \/\/ If the global is already in the set, no need to reprocess it.\n if (I != AliveGlobals.end()) return;\n\n \/\/ Otherwise insert it now, so we do not infinitely recurse\n AliveGlobals.insert(I, G);\n\n if (GlobalVariable *GV = dyn_cast(G)) {\n \/\/ If this is a global variable, we must make sure to add any global values\n \/\/ referenced by the initializer to the alive set.\n if (GV->hasInitializer())\n MarkUsedGlobalsAsNeeded(GV->getInitializer());\n } else if (!isa(G)) {\n \/\/ Otherwise this must be a function object. We have to scan the body of\n \/\/ the function looking for constants and global values which are used as\n \/\/ operands. Any operands of these types must be processed to ensure that\n \/\/ any globals used will be marked as needed.\n Function *F = cast(G);\n \/\/ For all basic blocks...\n for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n \/\/ For all instructions...\n for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)\n \/\/ For all operands...\n for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)\n if (GlobalValue *GV = dyn_cast(*U))\n GlobalIsNeeded(GV);\n else if (Constant *C = dyn_cast(*U))\n MarkUsedGlobalsAsNeeded(C);\n }\n}\n\nvoid GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {\n if (GlobalValue *GV = dyn_cast(C))\n GlobalIsNeeded(GV);\n else {\n \/\/ Loop over all of the operands of the constant, adding any globals they\n \/\/ use to the list of needed globals.\n for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I)\n MarkUsedGlobalsAsNeeded(cast(*I));\n }\n}\n\n\/\/ RemoveUnusedGlobalValue - Loop over all of the uses of the specified\n\/\/ GlobalValue, looking for the constant pointer ref that may be pointing to it.\n\/\/ If found, check to see if the constant pointer ref is safe to destroy, and if\n\/\/ so, nuke it. This will reduce the reference count on the global value, which\n\/\/ might make it deader.\n\/\/\nbool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {\n if (GV.use_empty()) return false;\n GV.removeDeadConstantUsers();\n return GV.use_empty();\n}\n\n\/\/ SafeToDestroyConstant - It is safe to destroy a constant iff it is only used\n\/\/ by constants itself. Note that constants cannot be cyclic, so this test is\n\/\/ pretty easy to implement recursively.\n\/\/\nbool GlobalDCE::SafeToDestroyConstant(Constant *C) {\n for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)\n if (Constant *User = dyn_cast(*I)) {\n if (!SafeToDestroyConstant(User)) return false;\n } else {\n return false;\n }\n return true;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief console input using linenoise\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"LinenoiseShell.h\"\n\nextern \"C\" {\n#include \n}\n\n#include \"Utilities\/Completer.h\"\n#include \"Utilities\/LineEditor.h\"\n\nusing namespace std;\nusing namespace arangodb;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief active completer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic Completer* COMPLETER = nullptr;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief completer generator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void LinenoiseCompletionGenerator (char const* text, \n linenoiseCompletions* lc) {\n if (COMPLETER) {\n std::vector alternatives = COMPLETER->alternatives(text);\n ShellBase::sortAlternatives(alternatives);\n\n for (auto& it : alternatives) {\n linenoiseAddCompletion(lc, it.c_str());\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class LinenoiseShell\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLinenoiseShell::LinenoiseShell (std::string const& history, \n Completer* completer)\n : ShellBase(history, completer) {\n COMPLETER = completer;\n linenoiseSetMultiLine(1);\n linenoiseSetCompletionCallback(LinenoiseCompletionGenerator);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLinenoiseShell::~LinenoiseShell() {\n COMPLETER = nullptr;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::open (bool) {\n linenoiseHistoryLoad(_historyFilename.c_str());\n _state = STATE_OPENED;\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::close () {\n\n \/\/ avoid duplicate saving of history\n if (_state != STATE_OPENED) {\n return true;\n }\n\n _state = STATE_CLOSED;\n return writeHistory();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid LinenoiseShell::addHistory (std::string const& str) {\n if (str.empty()) {\n return;\n }\n\n linenoiseHistoryAdd(str.c_str());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::writeHistory () {\n linenoiseHistorySave(_historyFilename.c_str());\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string LinenoiseShell::getLine (std::string const& prompt, bool& eof) {\n char* line = linenoise(prompt.c_str());\n\n if (line != nullptr) {\n eof = false;\n std::string const stringValue(line);\n ::free(line);\n return stringValue;\n }\n\n eof = true;\n return \"\";\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\nyawe: yet another windows exception\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief console input using linenoise\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2014 ArangoDB GmbH, Cologne, Germany\n\/\/\/ Copyright 2004-2014 triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is ArangoDB GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Dr. Frank Celler\n\/\/\/ @author Copyright 2014, ArangoDB GmbH, Cologne, Germany\n\/\/\/ @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"LinenoiseShell.h\"\n\nextern \"C\" {\n#include \n}\n\n#include \"Utilities\/Completer.h\"\n#include \"Utilities\/LineEditor.h\"\n\nusing namespace std;\nusing namespace arangodb;\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private functions\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief active completer\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic Completer* COMPLETER = nullptr;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief completer generator\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic void LinenoiseCompletionGenerator (char const* text, \n linenoiseCompletions* lc) {\n if (COMPLETER) {\n std::vector alternatives = COMPLETER->alternatives(text);\n ShellBase::sortAlternatives(alternatives);\n\n for (auto& it : alternatives) {\n linenoiseAddCompletion(lc, it.c_str());\n }\n }\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- class LinenoiseShell\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- constructors and destructors\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief constructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLinenoiseShell::LinenoiseShell (std::string const& history, \n Completer* completer)\n : ShellBase(history, completer) {\n COMPLETER = completer;\n#ifndef _WIN32\n linenoiseSetMultiLine(1);\n#endif\n linenoiseSetCompletionCallback(LinenoiseCompletionGenerator);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief destructor\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nLinenoiseShell::~LinenoiseShell() {\n COMPLETER = nullptr;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- public methods\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::open (bool) {\n linenoiseHistoryLoad(_historyFilename.c_str());\n _state = STATE_OPENED;\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::close () {\n\n \/\/ avoid duplicate saving of history\n if (_state != STATE_OPENED) {\n return true;\n }\n\n _state = STATE_CLOSED;\n return writeHistory();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid LinenoiseShell::addHistory (std::string const& str) {\n if (str.empty()) {\n return;\n }\n\n linenoiseHistoryAdd(str.c_str());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nbool LinenoiseShell::writeHistory () {\n linenoiseHistorySave(_historyFilename.c_str());\n\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ {@inheritDoc}\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string LinenoiseShell::getLine (std::string const& prompt, bool& eof) {\n char* line = linenoise(prompt.c_str());\n\n if (line != nullptr) {\n eof = false;\n std::string const stringValue(line);\n ::free(line);\n return stringValue;\n }\n\n eof = true;\n return \"\";\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- END-OF-FILE\n\/\/ -----------------------------------------------------------------------------\n<|endoftext|>"} {"text":"Missing GL_PROGRAM_POINT_SIZE in Contex.enable \/ disable<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPickingManager.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/*==============================================================================\n\n Library: MSVTK\n\n Copyright (c) Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n==============================================================================*\/\n\n\/\/ VTK includes\n#include \"vtkAbstractPicker.h\"\n#include \"vtkAbstractPropPicker.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCallbackCommand.h\"\n#include \"vtkCommand.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPickingManager.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTimeStamp.h\"\n\n\/\/ STL includes\n#include \n#include \n#include \n#include \n\n\/\/------------------------------------------------------------------------------\nvtkStandardNewMacro(vtkPickingManager);\n\n\/\/------------------------------------------------------------------------------\nclass vtkPickingManager::vtkInternal\n{\npublic:\n vtkInternal(vtkPickingManager* external);\n ~vtkInternal();\n\n \/\/ Callback used to update the current time\n \/\/ of the manager when an event occurs in the RenderWindowInteractor.\n \/\/ Time is used to know if the cached information is still valid or obsolete.\n static void UpdateTime(vtkObject *caller,\n unsigned long event,\n void *clientData,\n void *callData);\n\n \/\/ Select the best picker based on various criterias such as z-depth,\n \/\/ 2D overlay and\/or distance to picked point.\n vtkAbstractPicker* SelectPicker();\n\n \/\/ Compute the selection. The current implementation use the distance\n \/\/ between the world coordinates of a pick to the camera's ones.\n vtkAbstractPicker* ComputePickerSelection(double X, double Y, double Z,\n vtkRenderer* renderer);\n\n \/\/ Check if a given Observator is associated with a given Picker\n bool IsObjectLinked(vtkAbstractPicker* picker, vtkObject* object);\n\n \/\/ Create a new list of associated observers\n void CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object);\n\n \/\/ Instead of a vtkCollection we are using a vector of a vtkSmartPointer\n \/\/ containing vtkObject to allow using 0 as a valid value because it is\n \/\/ allowed the return a picker event if he is not associated to a specific\n \/\/ object.\n \/\/ This is related with the capacity when a picker associated with a given\n \/\/ object does not manage others object,\n \/\/ it will automatically be removed from the list as well.\n typedef std::vector > CollectionType;\n\n \/\/ For code clearance and performances during the computation std::map is\n \/\/ used instead of a vector of pair. Nevertheless, it makes internally use of\n \/\/ vtkSmartPointer and this class does not overload the order operators;\n \/\/ therefore to following functor has to be implemented to keep the data\n \/\/ structure consistent.\n struct less_smartPtrPicker\n {\n bool operator () (const vtkSmartPointer& first,\n const vtkSmartPointer& second) const\n {\n return first.GetPointer() < second.GetPointer();\n }\n };\n\n typedef std::map,\n CollectionType, less_smartPtrPicker > PickerObjectsType;\n\n typedef std::pair,\n CollectionType> PickerObjectsPairType;\n\n \/\/ Associate a given vtkObject to a particular picker.\n void LinkPickerObject(const PickerObjectsType::iterator& it,\n vtkObject* object);\n\n \/\/ Predicate comparing a vtkAbstractPicker*\n \/\/ and a vtkSmartPointer using the PickerObjectsType.\n \/\/ As we use a vtkSmartPointer, this predicate allows to compare the equality\n \/\/ of a pointer on a vtkAbstractPicker with the adress contained in\n \/\/ a corresponding vtkSmartPointer.\n struct equal_smartPtrPicker\n {\n equal_smartPtrPicker(vtkAbstractPicker* picker) : Picker(picker) {}\n\n bool operator () (const PickerObjectsPairType& pickerObjs) const\n {\n return this->Picker == pickerObjs.first.GetPointer();\n }\n\n vtkAbstractPicker* Picker;\n };\n\n \/\/ Predicate comparing a vtkObject*\n \/\/ and a vtkSmartPointer using the PickerObjectsType.\n \/\/ As we use a vtkSmartPointer, this predicate allows to compare the equality\n \/\/ of a pointer on a vtkObject with the adress contained in\n \/\/ a corresponding vtkSmartPointer.\n struct equal_smartPtrObject\n {\n equal_smartPtrObject(vtkObject* object) : Object(object) {}\n\n bool operator () (const vtkSmartPointer& smartObj) const\n {\n return this->Object == smartObj.GetPointer();\n }\n\n vtkObject* Object;\n };\n\n PickerObjectsType Pickers; \/\/ Map the picker with the objects\n vtkTimeStamp CurrentInteractionTime; \/\/ Time of the last interaction event\n vtkTimeStamp LastPickingTime; \/\/ Time of the last picking process\n vtkSmartPointer LastSelectedPicker;\n\n \/\/ Define callback to keep track of the CurrentTime and the LastPickingTime.\n \/\/ The timeStamp is use to avoid repeating the picking process if the\n \/\/ vtkWindowInteractor has not been modified, it is a huge optimization\n \/\/ avoiding each picker to relaunch the whole mechanisme to determine which\n \/\/ picker has been selected at a state of the rendering.\n vtkSmartPointer TimerCallback;\n\n vtkPickingManager* External;\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ vtkInternal methods\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkInternal::vtkInternal(vtkPickingManager* external)\n{\n this->External = external;\n\n this->TimerCallback = vtkSmartPointer::New();\n this->TimerCallback->SetClientData(this);\n this->TimerCallback->SetCallback(UpdateTime);\n\n}\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkInternal::~vtkInternal()\n{}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::\nCreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object)\n{\n CollectionType objects;\n objects.push_back(object);\n\n this->Pickers.insert(PickerObjectsPairType(picker, objects));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::\nLinkPickerObject(const PickerObjectsType::iterator& it, vtkObject* object)\n{\n CollectionType::iterator itObj = std::find_if(it->second.begin(),\n it->second.end(),\n equal_smartPtrObject(object));\n\n if (itObj != it->second.end() && object)\n {\n vtkDebugWithObjectMacro(\n this->External, \"vtkPickingtManager::Internal::LinkPickerObject: \"\n << \"Current object already linked with the given picker.\");\n\n return;\n }\n\n it->second.push_back(object);\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::vtkInternal::\nIsObjectLinked(vtkAbstractPicker* picker, vtkObject* obj)\n{\n if(!picker || !obj)\n {\n return false;\n }\n\n PickerObjectsType::iterator itPick = std::find_if(\n this->Pickers.begin(), this->Pickers.end(), equal_smartPtrPicker(picker));\n if(itPick == this->Pickers.end())\n {\n return false;\n }\n\n CollectionType::iterator itObj = std::find_if(itPick->second.begin(),\n itPick->second.end(),\n equal_smartPtrObject(obj));\n return (itObj != itPick->second.end());\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAbstractPicker* vtkPickingManager::vtkInternal::SelectPicker()\n{\n if (!this->External->Interactor)\n {\n return 0;\n }\n else if (this->External->GetOptimizeOnInteractorEvents() &&\n this->CurrentInteractionTime.GetMTime() == this->LastPickingTime)\n {\n return this->LastSelectedPicker;\n }\n\n \/\/ Get the event position\n double X = this->External->Interactor->GetEventPosition()[0];\n double Y = this->External->Interactor->GetEventPosition()[1];\n\n \/\/ Get the poked renderer\n vtkRenderer* renderer = this->External->Interactor->FindPokedRenderer(X, Y);\n vtkAbstractPicker* selectedPicker =\n this->ComputePickerSelection(X, Y, 0., renderer);\n\n \/\/ Keep track of the lastet picker choosen & last picking time.\n this->LastSelectedPicker = selectedPicker;\n this->LastPickingTime = this->CurrentInteractionTime;\n\n return selectedPicker;\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAbstractPicker* vtkPickingManager::vtkInternal::\nComputePickerSelection(double X, double Y, double Z, vtkRenderer* renderer)\n{\n vtkAbstractPicker* closestPicker = 0;\n if (!renderer)\n {\n return closestPicker;\n }\n\n double* camPos = renderer->GetActiveCamera()->GetPosition();\n double smallestDistance2 = std::numeric_limits::max();\n\n for(PickerObjectsType::iterator it = this->Pickers.begin();\n it != this->Pickers.end(); ++it)\n {\n int pickResult = it->first->Pick(X, Y, Z, renderer);\n double* pPos = it->first->GetPickPosition();\n\n if(pickResult > 0) \/\/ Keep closest object picked.\n {\n double distance2 = vtkMath::Distance2BetweenPoints(camPos, pPos);\n\n if(smallestDistance2 > distance2)\n {\n smallestDistance2 = distance2;\n closestPicker = it->first;\n }\n }\n }\n\n return closestPicker;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::UpdateTime(vtkObject *vtkNotUsed(caller),\n unsigned long vtkNotUsed(event),\n void *clientData,\n void *vtkNotUsed(calldata))\n{\n vtkPickingManager::vtkInternal* self =\n reinterpret_cast(clientData);\n if (!self)\n {\n return;\n }\n\n self->CurrentInteractionTime.Modified();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ vtkPickingManager methods\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkPickingManager()\n : Interactor(0)\n , Enabled(false)\n , OptimizeOnInteractorEvents(true)\n , Internal(0)\n{\n this->Internal = new vtkInternal(this);\n}\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::~vtkPickingManager()\n{\n this->SetInteractor(0);\n delete this->Internal;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::SetInteractor(vtkRenderWindowInteractor* rwi)\n{\n if (rwi == this->Interactor)\n {\n return;\n }\n if (this->Interactor)\n {\n this->Interactor->RemoveObserver(this->Internal->TimerCallback);\n }\n\n this->Interactor = rwi;\n if (this->Interactor)\n {\n this->Interactor->AddObserver(\n vtkCommand::ModifiedEvent, this->Internal->TimerCallback);\n }\n\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::SetOptimizeOnInteractorEvents(bool optimize)\n{\n if (this->OptimizeOnInteractorEvents == optimize)\n {\n return;\n }\n\n this->OptimizeOnInteractorEvents = optimize;\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::AddPicker(vtkAbstractPicker* picker,\n vtkObject* object)\n{\n if (!picker)\n {\n return;\n }\n\n \/\/ Linke the object if the picker is already registered\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n if (it != this->Internal->Pickers.end() )\n {\n vtkDebugMacro(\"vtkPickingtManager::AddPicker: \"\n << \"Picker already in the manager, the object will be linked\");\n\n this->Internal->LinkPickerObject(it, object);\n return;\n }\n\n \/\/ The picker does not exists in the manager yet.\n \/\/ Create the list of associated objects\n this->Internal->CreateDefaultCollection(picker, object);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::RemovePicker(vtkAbstractPicker* picker,\n vtkObject* object)\n{\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n \/\/ The Picker does not exist\n if (it == this->Internal->Pickers.end())\n {\n return;\n }\n\n vtkPickingManager::vtkInternal::CollectionType::iterator itObj =\n std::find_if(it->second.begin(),\n it->second.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrObject(object));\n\n \/\/ The object is not associated with the given picker.\n if (itObj == it->second.end())\n {\n return;\n }\n\n it->second.erase(itObj);\n\n \/\/ Delete the picker when it is not associated with any object anymore.\n if(it->second.size() == 0)\n {\n this->Internal->Pickers.erase(it);\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::RemoveObject(vtkObject* object)\n{\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n this->Internal->Pickers.begin();\n\n for(; it != this->Internal->Pickers.end();)\n {\n vtkPickingManager::vtkInternal::CollectionType::iterator itObj =\n std::find_if(it->second.begin(),\n it->second.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrObject(object));\n\n if (itObj != it->second.end())\n {\n it->second.erase(itObj);\n\n if (it->second.size() == 0)\n {\n this->Internal->Pickers.erase(it);\n continue;\n }\n }\n\n ++it;\n }\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkAbstractPicker* picker, vtkObject* obj)\n{\n if (!this->Internal->IsObjectLinked(picker, obj))\n {\n return false;\n }\n\n return (this->Pick(picker));\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkObject* obj)\n{\n vtkAbstractPicker* picker = this->Internal->SelectPicker();\n if(!picker)\n {\n return false;\n }\n \/\/ If the object is not contained in the list of the associated active pickers\n \/\/ return false\n return (this->Internal->IsObjectLinked(picker, obj));\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkAbstractPicker* picker)\n{\n return (picker == this->Internal->SelectPicker());\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAssemblyPath* vtkPickingManager::\nGetAssemblyPath(double X, double Y, double Z,\n vtkAbstractPropPicker* picker,\n vtkRenderer* renderer,\n vtkObject* obj)\n{\n if (this->Enabled)\n {\n \/\/ Return 0 when the Picker is not selected\n if (!this->Pick(picker, obj))\n {\n return 0;\n }\n }\n else\n {\n picker->Pick(X, Y, Z, renderer);\n }\n\n return picker->GetPath();\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkPickingManager::GetNumberOfPickers()\n{\n return static_cast(this->Internal->Pickers.size());\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkPickingManager::GetNumberOfObjectsLinked(vtkAbstractPicker* picker)\n{\n if (!picker)\n {\n return 0;\n }\n\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n if (it == this->Internal->Pickers.end())\n {\n return 0;\n }\n\n return static_cast(it->second.size());\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n\n os << indent << \"RenderWindowInteractor: \" << this->Interactor << \"\\n\";\n os << indent << \"NumberOfPickers: \" << this->Internal->Pickers.size() << \"\\n\";\n\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n this->Internal->Pickers.begin();\n\n for(; it != this->Internal->Pickers.end(); ++it)\n {\n os << indent << indent << \"Picker: \" << it->first.GetPointer() << \"\\n\";\n os << indent << indent << \"NumberOfObjectsLinked: \" << it->second.size()\n << \"\\n\";\n }\n}\nFix invalid iterator access after erase().\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkPickingManager.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n\/*==============================================================================\n\n Library: MSVTK\n\n Copyright (c) Kitware Inc.\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\n==============================================================================*\/\n\n\/\/ VTK includes\n#include \"vtkAbstractPicker.h\"\n#include \"vtkAbstractPropPicker.h\"\n#include \"vtkCamera.h\"\n#include \"vtkCallbackCommand.h\"\n#include \"vtkCommand.h\"\n#include \"vtkMath.h\"\n#include \"vtkNew.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPickingManager.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkRenderWindowInteractor.h\"\n#include \"vtkSmartPointer.h\"\n#include \"vtkTimeStamp.h\"\n\n\/\/ STL includes\n#include \n#include \n#include \n#include \n\n\/\/------------------------------------------------------------------------------\nvtkStandardNewMacro(vtkPickingManager);\n\n\/\/------------------------------------------------------------------------------\nclass vtkPickingManager::vtkInternal\n{\npublic:\n vtkInternal(vtkPickingManager* external);\n ~vtkInternal();\n\n \/\/ Callback used to update the current time\n \/\/ of the manager when an event occurs in the RenderWindowInteractor.\n \/\/ Time is used to know if the cached information is still valid or obsolete.\n static void UpdateTime(vtkObject *caller,\n unsigned long event,\n void *clientData,\n void *callData);\n\n \/\/ Select the best picker based on various criterias such as z-depth,\n \/\/ 2D overlay and\/or distance to picked point.\n vtkAbstractPicker* SelectPicker();\n\n \/\/ Compute the selection. The current implementation use the distance\n \/\/ between the world coordinates of a pick to the camera's ones.\n vtkAbstractPicker* ComputePickerSelection(double X, double Y, double Z,\n vtkRenderer* renderer);\n\n \/\/ Check if a given Observator is associated with a given Picker\n bool IsObjectLinked(vtkAbstractPicker* picker, vtkObject* object);\n\n \/\/ Create a new list of associated observers\n void CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object);\n\n \/\/ Instead of a vtkCollection we are using a vector of a vtkSmartPointer\n \/\/ containing vtkObject to allow using 0 as a valid value because it is\n \/\/ allowed the return a picker event if he is not associated to a specific\n \/\/ object.\n \/\/ This is related with the capacity when a picker associated with a given\n \/\/ object does not manage others object,\n \/\/ it will automatically be removed from the list as well.\n typedef std::vector > CollectionType;\n\n \/\/ For code clearance and performances during the computation std::map is\n \/\/ used instead of a vector of pair. Nevertheless, it makes internally use of\n \/\/ vtkSmartPointer and this class does not overload the order operators;\n \/\/ therefore to following functor has to be implemented to keep the data\n \/\/ structure consistent.\n struct less_smartPtrPicker\n {\n bool operator () (const vtkSmartPointer& first,\n const vtkSmartPointer& second) const\n {\n return first.GetPointer() < second.GetPointer();\n }\n };\n\n typedef std::map,\n CollectionType, less_smartPtrPicker > PickerObjectsType;\n\n typedef std::pair,\n CollectionType> PickerObjectsPairType;\n\n \/\/ Associate a given vtkObject to a particular picker.\n void LinkPickerObject(const PickerObjectsType::iterator& it,\n vtkObject* object);\n\n \/\/ Predicate comparing a vtkAbstractPicker*\n \/\/ and a vtkSmartPointer using the PickerObjectsType.\n \/\/ As we use a vtkSmartPointer, this predicate allows to compare the equality\n \/\/ of a pointer on a vtkAbstractPicker with the adress contained in\n \/\/ a corresponding vtkSmartPointer.\n struct equal_smartPtrPicker\n {\n equal_smartPtrPicker(vtkAbstractPicker* picker) : Picker(picker) {}\n\n bool operator () (const PickerObjectsPairType& pickerObjs) const\n {\n return this->Picker == pickerObjs.first.GetPointer();\n }\n\n vtkAbstractPicker* Picker;\n };\n\n \/\/ Predicate comparing a vtkObject*\n \/\/ and a vtkSmartPointer using the PickerObjectsType.\n \/\/ As we use a vtkSmartPointer, this predicate allows to compare the equality\n \/\/ of a pointer on a vtkObject with the adress contained in\n \/\/ a corresponding vtkSmartPointer.\n struct equal_smartPtrObject\n {\n equal_smartPtrObject(vtkObject* object) : Object(object) {}\n\n bool operator () (const vtkSmartPointer& smartObj) const\n {\n return this->Object == smartObj.GetPointer();\n }\n\n vtkObject* Object;\n };\n\n PickerObjectsType Pickers; \/\/ Map the picker with the objects\n vtkTimeStamp CurrentInteractionTime; \/\/ Time of the last interaction event\n vtkTimeStamp LastPickingTime; \/\/ Time of the last picking process\n vtkSmartPointer LastSelectedPicker;\n\n \/\/ Define callback to keep track of the CurrentTime and the LastPickingTime.\n \/\/ The timeStamp is use to avoid repeating the picking process if the\n \/\/ vtkWindowInteractor has not been modified, it is a huge optimization\n \/\/ avoiding each picker to relaunch the whole mechanisme to determine which\n \/\/ picker has been selected at a state of the rendering.\n vtkSmartPointer TimerCallback;\n\n vtkPickingManager* External;\n};\n\n\/\/------------------------------------------------------------------------------\n\/\/ vtkInternal methods\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkInternal::vtkInternal(vtkPickingManager* external)\n{\n this->External = external;\n\n this->TimerCallback = vtkSmartPointer::New();\n this->TimerCallback->SetClientData(this);\n this->TimerCallback->SetCallback(UpdateTime);\n\n}\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkInternal::~vtkInternal()\n{}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::\nCreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object)\n{\n CollectionType objects;\n objects.push_back(object);\n\n this->Pickers.insert(PickerObjectsPairType(picker, objects));\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::\nLinkPickerObject(const PickerObjectsType::iterator& it, vtkObject* object)\n{\n CollectionType::iterator itObj = std::find_if(it->second.begin(),\n it->second.end(),\n equal_smartPtrObject(object));\n\n if (itObj != it->second.end() && object)\n {\n vtkDebugWithObjectMacro(\n this->External, \"vtkPickingtManager::Internal::LinkPickerObject: \"\n << \"Current object already linked with the given picker.\");\n\n return;\n }\n\n it->second.push_back(object);\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::vtkInternal::\nIsObjectLinked(vtkAbstractPicker* picker, vtkObject* obj)\n{\n if(!picker || !obj)\n {\n return false;\n }\n\n PickerObjectsType::iterator itPick = std::find_if(\n this->Pickers.begin(), this->Pickers.end(), equal_smartPtrPicker(picker));\n if(itPick == this->Pickers.end())\n {\n return false;\n }\n\n CollectionType::iterator itObj = std::find_if(itPick->second.begin(),\n itPick->second.end(),\n equal_smartPtrObject(obj));\n return (itObj != itPick->second.end());\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAbstractPicker* vtkPickingManager::vtkInternal::SelectPicker()\n{\n if (!this->External->Interactor)\n {\n return 0;\n }\n else if (this->External->GetOptimizeOnInteractorEvents() &&\n this->CurrentInteractionTime.GetMTime() == this->LastPickingTime)\n {\n return this->LastSelectedPicker;\n }\n\n \/\/ Get the event position\n double X = this->External->Interactor->GetEventPosition()[0];\n double Y = this->External->Interactor->GetEventPosition()[1];\n\n \/\/ Get the poked renderer\n vtkRenderer* renderer = this->External->Interactor->FindPokedRenderer(X, Y);\n vtkAbstractPicker* selectedPicker =\n this->ComputePickerSelection(X, Y, 0., renderer);\n\n \/\/ Keep track of the lastet picker choosen & last picking time.\n this->LastSelectedPicker = selectedPicker;\n this->LastPickingTime = this->CurrentInteractionTime;\n\n return selectedPicker;\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAbstractPicker* vtkPickingManager::vtkInternal::\nComputePickerSelection(double X, double Y, double Z, vtkRenderer* renderer)\n{\n vtkAbstractPicker* closestPicker = 0;\n if (!renderer)\n {\n return closestPicker;\n }\n\n double* camPos = renderer->GetActiveCamera()->GetPosition();\n double smallestDistance2 = std::numeric_limits::max();\n\n for(PickerObjectsType::iterator it = this->Pickers.begin();\n it != this->Pickers.end(); ++it)\n {\n int pickResult = it->first->Pick(X, Y, Z, renderer);\n double* pPos = it->first->GetPickPosition();\n\n if(pickResult > 0) \/\/ Keep closest object picked.\n {\n double distance2 = vtkMath::Distance2BetweenPoints(camPos, pPos);\n\n if(smallestDistance2 > distance2)\n {\n smallestDistance2 = distance2;\n closestPicker = it->first;\n }\n }\n }\n\n return closestPicker;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::vtkInternal::UpdateTime(vtkObject *vtkNotUsed(caller),\n unsigned long vtkNotUsed(event),\n void *clientData,\n void *vtkNotUsed(calldata))\n{\n vtkPickingManager::vtkInternal* self =\n reinterpret_cast(clientData);\n if (!self)\n {\n return;\n }\n\n self->CurrentInteractionTime.Modified();\n}\n\n\/\/------------------------------------------------------------------------------\n\/\/ vtkPickingManager methods\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::vtkPickingManager()\n : Interactor(0)\n , Enabled(false)\n , OptimizeOnInteractorEvents(true)\n , Internal(0)\n{\n this->Internal = new vtkInternal(this);\n}\n\n\/\/------------------------------------------------------------------------------\nvtkPickingManager::~vtkPickingManager()\n{\n this->SetInteractor(0);\n delete this->Internal;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::SetInteractor(vtkRenderWindowInteractor* rwi)\n{\n if (rwi == this->Interactor)\n {\n return;\n }\n if (this->Interactor)\n {\n this->Interactor->RemoveObserver(this->Internal->TimerCallback);\n }\n\n this->Interactor = rwi;\n if (this->Interactor)\n {\n this->Interactor->AddObserver(\n vtkCommand::ModifiedEvent, this->Internal->TimerCallback);\n }\n\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::SetOptimizeOnInteractorEvents(bool optimize)\n{\n if (this->OptimizeOnInteractorEvents == optimize)\n {\n return;\n }\n\n this->OptimizeOnInteractorEvents = optimize;\n this->Modified();\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::AddPicker(vtkAbstractPicker* picker,\n vtkObject* object)\n{\n if (!picker)\n {\n return;\n }\n\n \/\/ Linke the object if the picker is already registered\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n if (it != this->Internal->Pickers.end() )\n {\n vtkDebugMacro(\"vtkPickingtManager::AddPicker: \"\n << \"Picker already in the manager, the object will be linked\");\n\n this->Internal->LinkPickerObject(it, object);\n return;\n }\n\n \/\/ The picker does not exists in the manager yet.\n \/\/ Create the list of associated objects\n this->Internal->CreateDefaultCollection(picker, object);\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::RemovePicker(vtkAbstractPicker* picker,\n vtkObject* object)\n{\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n \/\/ The Picker does not exist\n if (it == this->Internal->Pickers.end())\n {\n return;\n }\n\n vtkPickingManager::vtkInternal::CollectionType::iterator itObj =\n std::find_if(it->second.begin(),\n it->second.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrObject(object));\n\n \/\/ The object is not associated with the given picker.\n if (itObj == it->second.end())\n {\n return;\n }\n\n it->second.erase(itObj);\n\n \/\/ Delete the picker when it is not associated with any object anymore.\n if(it->second.size() == 0)\n {\n this->Internal->Pickers.erase(it);\n }\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::RemoveObject(vtkObject* object)\n{\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n this->Internal->Pickers.begin();\n\n for(; it != this->Internal->Pickers.end();)\n {\n vtkPickingManager::vtkInternal::CollectionType::iterator itObj =\n std::find_if(it->second.begin(),\n it->second.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrObject(object));\n\n if (itObj != it->second.end())\n {\n it->second.erase(itObj);\n\n if (it->second.size() == 0)\n {\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator\n toRemove = it;\n it++;\n this->Internal->Pickers.erase(toRemove);\n continue;\n }\n }\n\n ++it;\n }\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkAbstractPicker* picker, vtkObject* obj)\n{\n if (!this->Internal->IsObjectLinked(picker, obj))\n {\n return false;\n }\n\n return (this->Pick(picker));\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkObject* obj)\n{\n vtkAbstractPicker* picker = this->Internal->SelectPicker();\n if(!picker)\n {\n return false;\n }\n \/\/ If the object is not contained in the list of the associated active pickers\n \/\/ return false\n return (this->Internal->IsObjectLinked(picker, obj));\n}\n\n\/\/------------------------------------------------------------------------------\nbool vtkPickingManager::Pick(vtkAbstractPicker* picker)\n{\n return (picker == this->Internal->SelectPicker());\n}\n\n\/\/------------------------------------------------------------------------------\nvtkAssemblyPath* vtkPickingManager::\nGetAssemblyPath(double X, double Y, double Z,\n vtkAbstractPropPicker* picker,\n vtkRenderer* renderer,\n vtkObject* obj)\n{\n if (this->Enabled)\n {\n \/\/ Return 0 when the Picker is not selected\n if (!this->Pick(picker, obj))\n {\n return 0;\n }\n }\n else\n {\n picker->Pick(X, Y, Z, renderer);\n }\n\n return picker->GetPath();\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkPickingManager::GetNumberOfPickers()\n{\n return static_cast(this->Internal->Pickers.size());\n}\n\n\/\/------------------------------------------------------------------------------\nint vtkPickingManager::GetNumberOfObjectsLinked(vtkAbstractPicker* picker)\n{\n if (!picker)\n {\n return 0;\n }\n\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n std::find_if( this->Internal->Pickers.begin(),\n this->Internal->Pickers.end(),\n vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));\n\n if (it == this->Internal->Pickers.end())\n {\n return 0;\n }\n\n return static_cast(it->second.size());\n}\n\n\/\/------------------------------------------------------------------------------\nvoid vtkPickingManager::PrintSelf(ostream& os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n\n os << indent << \"RenderWindowInteractor: \" << this->Interactor << \"\\n\";\n os << indent << \"NumberOfPickers: \" << this->Internal->Pickers.size() << \"\\n\";\n\n vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =\n this->Internal->Pickers.begin();\n\n for(; it != this->Internal->Pickers.end(); ++it)\n {\n os << indent << indent << \"Picker: \" << it->first.GetPointer() << \"\\n\";\n os << indent << indent << \"NumberOfObjectsLinked: \" << it->second.size()\n << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdentColoredPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkIdentColoredPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkConfigure.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolygon.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkTriangle.h\"\n#include \"vtkIdTypeArray.h\"\n\n#ifndef VTK_IMPLEMENT_MESA_CXX\n# include \"vtkOpenGL.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkIdentColoredPainter, \"1.18\");\nvtkStandardNewMacro(vtkIdentColoredPainter);\n\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)? \n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)? \n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)? \n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)? \n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::vtkIdentColoredPainter()\n{\n this->ColorMode = COLORBYIDENT;\n this->ResetCurrentId();\n\n this->ActorIds = NULL;\n this->PropAddrs = NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::~vtkIdentColoredPainter()\n{\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByConstant(unsigned int constant)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n this->CurrentIdPlane0 = constant;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByVertex()\n{\n this->ColorMode = COLORBYVERTEX;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkProp* vtkIdentColoredPainter::GetActorFromId(vtkIdType id)\n{\n vtkIdType numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i < numIds; i++)\n {\n if (this->ActorIds->GetValue(i) == id)\n {\n return this->PropAddrs[i];\n }\n }\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)\n{\n \/\/free whatever we were given before this\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n \n \/\/sanity checking\n if (props == NULL || \n ids == NULL || \n (ids->GetNumberOfComponents() != 1) ||\n (ids->GetNumberOfTuples() == 0))\n {\n vtkWarningMacro(\"Invalid actor-id lookup table supplied.\");\n return;\n }\n\n \/\/copy over the new lookup table\n this->ActorIds = ids;\n this->ActorIds->Register(this);\n this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];\n for (int i = 0; i < ids->GetNumberOfTuples(); i++)\n {\n this->PropAddrs[i] = props[i];\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n\n vtkIdType maxId = 0;\n int numIds = 0;\n if (this->ActorIds != NULL)\n {\n numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i< numIds; i++)\n {\n vtkIdType nextId = this->ActorIds->GetValue(i);\n if (actorAddr == this->PropAddrs[i])\n {\n this->CurrentIdPlane0 = nextId + 1; \n return;\n }\n if (nextId > maxId)\n {\n maxId = nextId;\n }\n }\n }\n\n \/\/we didn't find the actor in the table, make up an ID and add it\n \/\/cerr << \"ID not found for actor \" << actorAddr \n \/\/ << \" using \" << maxId+1 << endl;\n vtkIdTypeArray *arr = vtkIdTypeArray::New();\n arr->SetNumberOfComponents(1);\n arr->SetNumberOfTuples(numIds+1);\n vtkProp **SaveProps = new vtkProp*[numIds+1];\n if (this->ActorIds != NULL)\n {\n for (int i = 0; i< numIds; i++)\n {\n arr->SetValue(i, this->ActorIds->GetValue(i));\n SaveProps[i] = this->PropAddrs[i];\n }\n }\n arr->SetValue(numIds, maxId+1);\n SaveProps[numIds] = actorAddr;\n this->MakeActorLookupTable(SaveProps, arr);\n arr->Delete();\n\n this->CurrentIdPlane0 = maxId+2;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)\n{\n this->ColorMode = COLORBYIDENT;\n this->Plane = (plane < 3)?plane:2;\n this->ResetCurrentId();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ResetCurrentId() \n{\n \/\/do not use 0, it is reserved for miss\n this->CurrentIdPlane0 = 1;\n this->CurrentIdPlane1 = 1;\n this->CurrentIdPlane2 = 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::IncrementCurrentId()\n{\n if (this->ColorMode == COLORBYCONST)\n {\n return;\n }\n\n \/\/the limits are set up assuming 24 bits total for each for RGB pixel\n \/\/do not use A because the parallel compositing code does not support Alpha\n this->CurrentIdPlane0++;\n if (this->CurrentIdPlane0 >= 0x01000000)\n {\n this->CurrentIdPlane0 = 0x00000001;\n this->CurrentIdPlane1++;\n if (this->CurrentIdPlane1 >= 0x01000000)\n {\n this->CurrentIdPlane1 = 0x00000001;\n this->CurrentIdPlane2++;\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)\n{\n unsigned int val = this->CurrentIdPlane0;\n if (this->ColorMode == COLORBYIDENT)\n {\n if (this->Plane == 1)\n {\n val = this->CurrentIdPlane1;\n }\n else if (this->Plane == 2)\n {\n val = this->CurrentIdPlane2;\n }\n }\n\n \/\/cerr << \"Curr Color is \" \n \/\/ << this->ColorMode << \" \"\n \/\/ << this->CurrentIdPlane2 << \":\"\n \/\/ << this->CurrentIdPlane1 << \":\"\n \/\/ << this->CurrentIdPlane0 << endl;\n\n RGB[0] = (val & 0x00FF0000)>>16;\n RGB[1] = (val & 0x0000FF00)>>8;\n RGB[2] = (val & 0x000000FF);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer, \n vtkActor* actor, \n unsigned long typeflags)\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n if (!device)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n this->TotalCells = \n vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);\n\n this->Timer->StartTimer();\n\n \/\/turn off antialising and lighting so that the colors we draw will be the\n \/\/colors we read back\n int origMultisample = device->QueryMultisampling();\n int origLighting = device->QueryLighting();\n int origBlending = device->QueryBlending();\n\n device->MakeMultisampling(0);\n device->MakeLighting(0);\n device->MakeBlending(0);\n\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfVerts();\n\n if (typeflags & vtkPainter::LINES)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n \/\/for point selection, draw twice to hide occluded verts\n this->ColorByConstant(0);\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfLines();\n\n if (typeflags & vtkPainter::POLYS)\n {\n#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))\n if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(0);\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n else\n#endif\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(0);\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n } \n startCell += this->PolyData->GetNumberOfPolys();\n\n if (typeflags & vtkPainter::STRIPS)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(4);\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfStrips();\n\n \/\/reset lighting back to the default\n device->MakeBlending(origBlending);\n device->MakeLighting(origLighting);\n device->MakeMultisampling(origMultisample);\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n\n \/\/ let the superclass pass on the request to delegate painter.\n \/\/ Ofcouse, more than likely, this call will never have a delegate,\n \/\/ but anyways.\n this->Superclass::RenderInternal(renderer, actor, typeflags);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,\n vtkIdType startCellId, \n vtkRenderer *renderer)\n{\n if (!this->PolyData)\n {\n vtkWarningMacro(\"No polydata to render!\");\n return;\n }\n\n if (this->ColorMode == COLORBYVERTEX)\n {\n mode = VTK_POLY_VERTEX;\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n device->MakeVertexEmphasis(1); \/\/draw verts larger and nearer to be on top\n \/\/of their associated polygons\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = this->PolyData->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n \n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ResetCurrentId();\n }\n this->GetCurrentColor(color);\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n if (this->ColorMode == COLORBYVERTEX && cellpointi > 0)\n {\n this->IncrementCurrentId();\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n } \n\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, \n pointtype, voidpoints, 3*pointId);\n }\n\n this->IncrementCurrentId();\n\n device->EndPrimitive();\n\n cellId++;\n\n if (count == 10000) \n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n device->MakeVertexEmphasis(0);\n }\n return;\n }\n }\n\n }\n\n if (this->ColorMode == COLORBYVERTEX)\n {\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n device->MakeVertexEmphasis(0);\n }\n\n\n}\n \n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\nCOMP: fix reused declaration warning.\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkIdentColoredPainter.cxx\n\n Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen\n All rights reserved.\n See Copyright.txt or http:\/\/www.kitware.com\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notice for more information.\n\n=========================================================================*\/\n\n#include \"vtkIdentColoredPainter.h\"\n\n#include \"vtkActor.h\"\n#include \"vtkCellArray.h\"\n#include \"vtkCellData.h\"\n#include \"vtkConfigure.h\"\n#include \"vtkDataArray.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkPainterDeviceAdapter.h\"\n#include \"vtkPointData.h\"\n#include \"vtkPolyData.h\"\n#include \"vtkPolygon.h\"\n#include \"vtkProperty.h\"\n#include \"vtkRenderer.h\"\n#include \"vtkRenderWindow.h\"\n#include \"vtkTimerLog.h\"\n#include \"vtkTriangle.h\"\n#include \"vtkIdTypeArray.h\"\n\n#ifndef VTK_IMPLEMENT_MESA_CXX\n# include \"vtkOpenGL.h\"\n#endif\n\n\/\/-----------------------------------------------------------------------------\nvtkCxxRevisionMacro(vtkIdentColoredPainter, \"1.19\");\nvtkStandardNewMacro(vtkIdentColoredPainter);\n\n\/\/-----------------------------------------------------------------------------\nstatic inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,\n unsigned long typeflags)\n{\n int total_cells = 0;\n total_cells += (typeflags & vtkPainter::VERTS)? \n pd->GetNumberOfVerts() : 0;\n total_cells += (typeflags & vtkPainter::LINES)? \n pd->GetNumberOfLines() : 0;\n total_cells += (typeflags & vtkPainter::POLYS)? \n pd->GetNumberOfPolys() : 0;\n total_cells += (typeflags & vtkPainter::STRIPS)? \n pd->GetNumberOfStrips() : 0;\n return total_cells;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::vtkIdentColoredPainter()\n{\n this->ColorMode = COLORBYIDENT;\n this->ResetCurrentId();\n\n this->ActorIds = NULL;\n this->PropAddrs = NULL;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkIdentColoredPainter::~vtkIdentColoredPainter()\n{\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByConstant(unsigned int constant)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n this->CurrentIdPlane0 = constant;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByVertex()\n{\n this->ColorMode = COLORBYVERTEX;\n}\n\n\/\/-----------------------------------------------------------------------------\nvtkProp* vtkIdentColoredPainter::GetActorFromId(vtkIdType id)\n{\n vtkIdType numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i < numIds; i++)\n {\n if (this->ActorIds->GetValue(i) == id)\n {\n return this->PropAddrs[i];\n }\n }\n return 0;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)\n{\n \/\/free whatever we were given before this\n if (this->ActorIds != NULL)\n {\n this->ActorIds->Delete();\n this->ActorIds = NULL;\n delete[] this->PropAddrs;\n this->PropAddrs = NULL;\n }\n \n \/\/sanity checking\n if (props == NULL || \n ids == NULL || \n (ids->GetNumberOfComponents() != 1) ||\n (ids->GetNumberOfTuples() == 0))\n {\n vtkWarningMacro(\"Invalid actor-id lookup table supplied.\");\n return;\n }\n\n \/\/copy over the new lookup table\n this->ActorIds = ids;\n this->ActorIds->Register(this);\n this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];\n for (int i = 0; i < ids->GetNumberOfTuples(); i++)\n {\n this->PropAddrs[i] = props[i];\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)\n{\n this->ColorMode = COLORBYCONST;\n this->ResetCurrentId();\n\n vtkIdType maxId = 0;\n int numIds = 0;\n if (this->ActorIds != NULL)\n {\n numIds = this->ActorIds->GetNumberOfTuples();\n for (int i = 0; i< numIds; i++)\n {\n vtkIdType nextId = this->ActorIds->GetValue(i);\n if (actorAddr == this->PropAddrs[i])\n {\n this->CurrentIdPlane0 = nextId + 1; \n return;\n }\n if (nextId > maxId)\n {\n maxId = nextId;\n }\n }\n }\n\n \/\/we didn't find the actor in the table, make up an ID and add it\n \/\/cerr << \"ID not found for actor \" << actorAddr \n \/\/ << \" using \" << maxId+1 << endl;\n vtkIdTypeArray *arr = vtkIdTypeArray::New();\n arr->SetNumberOfComponents(1);\n arr->SetNumberOfTuples(numIds+1);\n vtkProp **SaveProps = new vtkProp*[numIds+1];\n if (this->ActorIds != NULL)\n {\n for (int i = 0; i< numIds; i++)\n {\n arr->SetValue(i, this->ActorIds->GetValue(i));\n SaveProps[i] = this->PropAddrs[i];\n }\n }\n arr->SetValue(numIds, maxId+1);\n SaveProps[numIds] = actorAddr;\n this->MakeActorLookupTable(SaveProps, arr);\n arr->Delete();\n\n this->CurrentIdPlane0 = maxId+2;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)\n{\n this->ColorMode = COLORBYIDENT;\n this->Plane = (plane < 3)?plane:2;\n this->ResetCurrentId();\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::ResetCurrentId() \n{\n \/\/do not use 0, it is reserved for miss\n this->CurrentIdPlane0 = 1;\n this->CurrentIdPlane1 = 1;\n this->CurrentIdPlane2 = 1;\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::IncrementCurrentId()\n{\n if (this->ColorMode == COLORBYCONST)\n {\n return;\n }\n\n \/\/the limits are set up assuming 24 bits total for each for RGB pixel\n \/\/do not use A because the parallel compositing code does not support Alpha\n this->CurrentIdPlane0++;\n if (this->CurrentIdPlane0 >= 0x01000000)\n {\n this->CurrentIdPlane0 = 0x00000001;\n this->CurrentIdPlane1++;\n if (this->CurrentIdPlane1 >= 0x01000000)\n {\n this->CurrentIdPlane1 = 0x00000001;\n this->CurrentIdPlane2++;\n }\n }\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)\n{\n unsigned int val = this->CurrentIdPlane0;\n if (this->ColorMode == COLORBYIDENT)\n {\n if (this->Plane == 1)\n {\n val = this->CurrentIdPlane1;\n }\n else if (this->Plane == 2)\n {\n val = this->CurrentIdPlane2;\n }\n }\n\n \/\/cerr << \"Curr Color is \" \n \/\/ << this->ColorMode << \" \"\n \/\/ << this->CurrentIdPlane2 << \":\"\n \/\/ << this->CurrentIdPlane1 << \":\"\n \/\/ << this->CurrentIdPlane0 << endl;\n\n RGB[0] = (val & 0x00FF0000)>>16;\n RGB[1] = (val & 0x0000FF00)>>8;\n RGB[2] = (val & 0x000000FF);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer, \n vtkActor* actor, \n unsigned long typeflags)\n{\n if (typeflags == 0)\n {\n \/\/ No primitive to render.\n return;\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n if (!device)\n {\n vtkErrorMacro(\"Painter Device Adapter missing!\");\n return;\n }\n\n this->TotalCells = \n vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);\n\n this->Timer->StartTimer();\n\n \/\/turn off antialising and lighting so that the colors we draw will be the\n \/\/colors we read back\n int origMultisample = device->QueryMultisampling();\n int origLighting = device->QueryLighting();\n int origBlending = device->QueryBlending();\n\n device->MakeMultisampling(0);\n device->MakeLighting(0);\n device->MakeBlending(0);\n\n vtkIdType startCell = 0;\n\n if (typeflags & vtkPainter::VERTS)\n {\n this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfVerts();\n\n if (typeflags & vtkPainter::LINES)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n \/\/for point selection, draw twice to hide occluded verts\n this->ColorByConstant(0);\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfLines();\n\n if (typeflags & vtkPainter::POLYS)\n {\n#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))\n if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(0);\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n else\n#endif\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(0);\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,\n renderer);\n }\n } \n startCell += this->PolyData->GetNumberOfPolys();\n\n if (typeflags & vtkPainter::STRIPS)\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ColorByConstant(4);\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n this->ColorByVertex();\n }\n this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,\n renderer);\n }\n startCell += this->PolyData->GetNumberOfStrips();\n\n \/\/reset lighting back to the default\n device->MakeBlending(origBlending);\n device->MakeLighting(origLighting);\n device->MakeMultisampling(origMultisample);\n\n this->Timer->StopTimer();\n this->TimeToDraw = this->Timer->GetElapsedTime();\n\n \/\/ let the superclass pass on the request to delegate painter.\n \/\/ Ofcouse, more than likely, this call will never have a delegate,\n \/\/ but anyways.\n this->Superclass::RenderInternal(renderer, actor, typeflags);\n}\n\n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,\n vtkIdType startCellId, \n vtkRenderer *renderer)\n{\n if (!this->PolyData)\n {\n vtkWarningMacro(\"No polydata to render!\");\n return;\n }\n\n if (this->ColorMode == COLORBYVERTEX)\n {\n mode = VTK_POLY_VERTEX;\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n device->MakeVertexEmphasis(1); \/\/draw verts larger and nearer to be on top\n \/\/of their associated polygons\n }\n\n vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->\n GetPainterDeviceAdapter();\n\n vtkPoints* p = this->PolyData->GetPoints();\n vtkIdType npts, *pts;\n vtkIdType cellId = startCellId;\n\n int pointtype = p->GetDataType();\n void* voidpoints = p->GetVoidPointer(0);\n int count = 0;\n\n unsigned char color[3];\n for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)\n {\n device->BeginPrimitive(mode);\n \n if (this->ColorMode == COLORBYVERTEX)\n {\n this->ResetCurrentId();\n }\n this->GetCurrentColor(color);\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n\n for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)\n {\n vtkIdType pointId = pts[cellpointi];\n if (this->ColorMode == COLORBYVERTEX && cellpointi > 0)\n {\n this->IncrementCurrentId();\n this->GetCurrentColor(color);\n\n device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);\n } \n\n device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3, \n pointtype, voidpoints, 3*pointId);\n }\n\n this->IncrementCurrentId();\n\n device->EndPrimitive();\n\n cellId++;\n\n if (count == 10000) \n {\n count = 0;\n \/\/ report progress\n this->UpdateProgress(static_cast(cellId - startCellId)\/this->TotalCells);\n \/\/ Abort render.\n if (renderer->GetRenderWindow()->CheckAbortStatus())\n {\n if (this->ColorMode == COLORBYVERTEX)\n {\n device->MakeVertexEmphasis(0);\n }\n return;\n }\n }\n\n }\n\n if (this->ColorMode == COLORBYVERTEX)\n {\n device->MakeVertexEmphasis(0);\n }\n\n\n}\n \n\/\/-----------------------------------------------------------------------------\nvoid vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)\n{\n this->Superclass::PrintSelf(os, indent);\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n *\n * Copyright 2009-2011 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sub license, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice (including the\n * next paragraph) shall be included in all copies or substantial portions\n * of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n * IN NO EVENT SHALL VMWARE AND\/OR ITS SUPPLIERS BE LIABLE FOR\n * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#if HAVE_LLVM >= 0x0303\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#if HAVE_LLVM >= 0x0305\n#define OwningPtr std::unique_ptr\n#elif HAVE_LLVM >= 0x0303\n#include \n#endif\n\n#if HAVE_LLVM >= 0x0305\n#include \n#endif\n\n#include \"util\/u_math.h\"\n#include \"util\/u_debug.h\"\n\n#include \"lp_bld_debug.h\"\n\n#ifdef __linux__\n#include \n#include \n#endif\n\n\n\n\/**\n * Check alignment.\n *\n * It is important that this check is not implemented as a macro or inlined\n * function, as the compiler assumptions in respect to alignment of global\n * and stack variables would often make the check a no op, defeating the\n * whole purpose of the exercise.\n *\/\nextern \"C\" boolean\nlp_check_alignment(const void *ptr, unsigned alignment)\n{\n assert(util_is_power_of_two(alignment));\n return ((uintptr_t)ptr & (alignment - 1)) == 0;\n}\n\n\nclass raw_debug_ostream :\n public llvm::raw_ostream\n{\nprivate:\n uint64_t pos;\n\npublic:\n raw_debug_ostream() : pos(0) { }\n\n void write_impl(const char *Ptr, size_t Size);\n\n uint64_t current_pos() const { return pos; }\n size_t preferred_buffer_size() const { return 512; }\n};\n\n\nvoid\nraw_debug_ostream::write_impl(const char *Ptr, size_t Size)\n{\n if (Size > 0) {\n char *lastPtr = (char *)&Ptr[Size];\n char last = *lastPtr;\n *lastPtr = 0;\n _debug_printf(\"%*s\", Size, Ptr);\n *lastPtr = last;\n pos += Size;\n }\n}\n\n\nextern \"C\" const char *\nlp_get_module_id(LLVMModuleRef module)\n{\n return llvm::unwrap(module)->getModuleIdentifier().c_str();\n}\n\n\n\/**\n * Same as LLVMDumpValue, but through our debugging channels.\n *\/\nextern \"C\" void\nlp_debug_dump_value(LLVMValueRef value)\n{\n#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)\n raw_debug_ostream os;\n llvm::unwrap(value)->print(os);\n os.flush();\n#else\n LLVMDumpValue(value);\n#endif\n}\n\n\n\/*\n * MemoryObject wrapper around a buffer of memory, to be used by MC\n * disassembler.\n *\/\nclass BufferMemoryObject:\n public llvm::MemoryObject\n{\nprivate:\n const uint8_t *Bytes;\n uint64_t Length;\npublic:\n BufferMemoryObject(const uint8_t *bytes, uint64_t length) :\n Bytes(bytes), Length(length)\n {\n }\n\n uint64_t getBase() const\n {\n return 0;\n }\n\n uint64_t getExtent() const\n {\n return Length;\n }\n\n int readByte(uint64_t addr, uint8_t *byte) const\n {\n if (addr > getExtent())\n return -1;\n *byte = Bytes[addr];\n return 0;\n }\n};\n\n\n\/*\n * Disassemble a function, using the LLVM MC disassembler.\n *\n * See also:\n * - http:\/\/blog.llvm.org\/2010\/01\/x86-disassembler.html\n * - http:\/\/blog.llvm.org\/2010\/04\/intro-to-llvm-mc-project.html\n *\/\nstatic size_t\ndisassemble(const void* func, llvm::raw_ostream & Out)\n{\n using namespace llvm;\n\n const uint8_t *bytes = (const uint8_t *)func;\n\n \/*\n * Limit disassembly to this extent\n *\/\n const uint64_t extent = 96 * 1024;\n\n uint64_t max_pc = 0;\n\n \/*\n * Initialize all used objects.\n *\/\n\n std::string Triple = sys::getDefaultTargetTriple();\n\n std::string Error;\n const Target *T = TargetRegistry::lookupTarget(Triple, Error);\n\n#if HAVE_LLVM >= 0x0304\n OwningPtr AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));\n#else\n OwningPtr AsmInfo(T->createMCAsmInfo(Triple));\n#endif\n\n if (!AsmInfo) {\n Out << \"error: no assembly info for target \" << Triple << \"\\n\";\n Out.flush();\n return 0;\n }\n\n unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();\n\n OwningPtr MRI(T->createMCRegInfo(Triple));\n if (!MRI) {\n Out << \"error: no register info for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n OwningPtr MII(T->createMCInstrInfo());\n if (!MII) {\n Out << \"error: no instruction info for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n#if HAVE_LLVM >= 0x0305\n OwningPtr STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), \"\"));\n OwningPtr MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));\n OwningPtr DisAsm(T->createMCDisassembler(*STI, *MCCtx));\n#else\n OwningPtr STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), \"\"));\n OwningPtr DisAsm(T->createMCDisassembler(*STI));\n#endif\n if (!DisAsm) {\n Out << \"error: no disassembler for target \" << Triple << \"\\n\";\n Out.flush();\n return 0;\n }\n\n\n OwningPtr Printer(\n T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));\n if (!Printer) {\n Out << \"error: no instruction printer for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n TargetOptions options;\n#if defined(DEBUG)\n options.JITEmitDebugInfo = true;\n#endif\n#if defined(PIPE_ARCH_X86)\n options.StackAlignmentOverride = 4;\n#endif\n#if defined(DEBUG) || defined(PROFILE)\n options.NoFramePointerElim = true;\n#endif\n OwningPtr TM(T->createTargetMachine(Triple, sys::getHostCPUName(), \"\", options));\n\n const TargetInstrInfo *TII = TM->getInstrInfo();\n\n \/*\n * Wrap the data in a MemoryObject\n *\/\n BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);\n\n uint64_t pc;\n pc = 0;\n while (true) {\n MCInst Inst;\n uint64_t Size;\n\n \/*\n * Print address. We use addresses relative to the start of the function,\n * so that between runs.\n *\/\n\n Out << llvm::format(\"%6lu:\\t\", (unsigned long)pc);\n\n if (!DisAsm->getInstruction(Inst, Size, memoryObject,\n pc,\n\t\t\t\t nulls(), nulls())) {\n Out << \"invalid\";\n pc += 1;\n }\n\n \/*\n * Output the bytes in hexidecimal format.\n *\/\n\n if (0) {\n unsigned i;\n for (i = 0; i < Size; ++i) {\n Out << llvm::format(\"%02x \", ((const uint8_t*)bytes)[pc + i]);\n }\n for (; i < 16; ++i) {\n Out << \" \";\n }\n }\n\n \/*\n * Print the instruction.\n *\/\n Printer->printInst(&Inst, Out, \"\");\n\n \/*\n * Advance.\n *\/\n\n pc += Size;\n\n const MCInstrDesc &TID = TII->get(Inst.getOpcode());\n\n \/*\n * Keep track of forward jumps to a nearby address.\n *\/\n\n if (TID.isBranch()) {\n for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {\n const MCOperand &operand = Inst.getOperand(i);\n if (operand.isImm()) {\n uint64_t jump;\n\n \/*\n * FIXME: Handle both relative and absolute addresses correctly.\n * EDInstInfo actually has this info, but operandTypes and\n * operandFlags enums are not exposed in the public interface.\n *\/\n\n if (1) {\n \/*\n * PC relative addr.\n *\/\n\n jump = pc + operand.getImm();\n } else {\n \/*\n * Absolute addr.\n *\/\n\n jump = (uint64_t)operand.getImm();\n }\n\n \/*\n * Output the address relative to the function start, given\n * that MC will print the addresses relative the current pc.\n *\/\n Out << \"\\t\\t; \" << jump;\n\n \/*\n * Ignore far jumps given it could be actually a tail return to\n * a random address.\n *\/\n\n if (jump > max_pc &&\n jump < extent) {\n max_pc = jump;\n }\n }\n }\n }\n\n Out << \"\\n\";\n\n \/*\n * Stop disassembling on return statements, if there is no record of a\n * jump to a successive address.\n *\/\n\n if (TID.isReturn()) {\n if (pc > max_pc) {\n break;\n }\n }\n }\n\n \/*\n * Print GDB command, useful to verify output.\n *\/\n\n if (0) {\n _debug_printf(\"disassemble %p %p\\n\", bytes, bytes + pc);\n }\n\n Out << \"\\n\";\n Out.flush();\n\n return pc;\n}\n\n\nextern \"C\" void\nlp_disassemble(LLVMValueRef func, const void *code) {\n raw_debug_ostream Out;\n disassemble(code, Out);\n}\n\n\n\/*\n * Linux perf profiler integration.\n *\n * See also:\n * - http:\/\/penberg.blogspot.co.uk\/2009\/06\/jato-has-profiler.html\n * - https:\/\/github.com\/penberg\/jato\/commit\/73ad86847329d99d51b386f5aba692580d1f8fdc\n * - http:\/\/git.kernel.org\/?p=linux\/kernel\/git\/torvalds\/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d\n *\/\nextern \"C\" void\nlp_profile(LLVMValueRef func, const void *code)\n{\n#if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))\n static boolean first_time = TRUE;\n static FILE *perf_map_file = NULL;\n static int perf_asm_fd = -1;\n if (first_time) {\n \/*\n * We rely on the disassembler for determining a function's size, but\n * the disassembly is a leaky and slow operation, so avoid running\n * this except when running inside linux perf, which can be inferred\n * by the PERF_BUILDID_DIR environment variable.\n *\/\n if (getenv(\"PERF_BUILDID_DIR\")) {\n pid_t pid = getpid();\n char filename[256];\n util_snprintf(filename, sizeof filename, \"\/tmp\/perf-%llu.map\", (unsigned long long)pid);\n perf_map_file = fopen(filename, \"wt\");\n util_snprintf(filename, sizeof filename, \"\/tmp\/perf-%llu.map.asm\", (unsigned long long)pid);\n mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;\n perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);\n }\n first_time = FALSE;\n }\n if (perf_map_file) {\n const char *symbol = LLVMGetValueName(func);\n unsigned long addr = (uintptr_t)code;\n llvm::raw_fd_ostream Out(perf_asm_fd, false);\n Out << symbol << \":\\n\";\n unsigned long size = disassemble(code, Out);\n fprintf(perf_map_file, \"%lx %lx %s\\n\", addr, size, symbol);\n fflush(perf_map_file);\n }\n#else\n (void)func;\n (void)code;\n#endif\n}\n\n\ngallivm: Fix build with latest LLVM\/**************************************************************************\n *\n * Copyright 2009-2011 VMware, Inc.\n * All Rights Reserved.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a\n * copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sub license, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice (including the\n * next paragraph) shall be included in all copies or substantial portions\n * of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.\n * IN NO EVENT SHALL VMWARE AND\/OR ITS SUPPLIERS BE LIABLE FOR\n * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n **************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if HAVE_LLVM >= 0x0306\n#include \n#endif\n\n#include \n#include \n\n#include \n\n#if HAVE_LLVM >= 0x0303\n#include \n#else\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#if HAVE_LLVM >= 0x0305\n#define OwningPtr std::unique_ptr\n#elif HAVE_LLVM >= 0x0303\n#include \n#endif\n\n#if HAVE_LLVM >= 0x0305\n#include \n#endif\n\n#include \"util\/u_math.h\"\n#include \"util\/u_debug.h\"\n\n#include \"lp_bld_debug.h\"\n\n#ifdef __linux__\n#include \n#include \n#endif\n\n\n\n\/**\n * Check alignment.\n *\n * It is important that this check is not implemented as a macro or inlined\n * function, as the compiler assumptions in respect to alignment of global\n * and stack variables would often make the check a no op, defeating the\n * whole purpose of the exercise.\n *\/\nextern \"C\" boolean\nlp_check_alignment(const void *ptr, unsigned alignment)\n{\n assert(util_is_power_of_two(alignment));\n return ((uintptr_t)ptr & (alignment - 1)) == 0;\n}\n\n\nclass raw_debug_ostream :\n public llvm::raw_ostream\n{\nprivate:\n uint64_t pos;\n\npublic:\n raw_debug_ostream() : pos(0) { }\n\n void write_impl(const char *Ptr, size_t Size);\n\n uint64_t current_pos() const { return pos; }\n size_t preferred_buffer_size() const { return 512; }\n};\n\n\nvoid\nraw_debug_ostream::write_impl(const char *Ptr, size_t Size)\n{\n if (Size > 0) {\n char *lastPtr = (char *)&Ptr[Size];\n char last = *lastPtr;\n *lastPtr = 0;\n _debug_printf(\"%*s\", Size, Ptr);\n *lastPtr = last;\n pos += Size;\n }\n}\n\n\nextern \"C\" const char *\nlp_get_module_id(LLVMModuleRef module)\n{\n return llvm::unwrap(module)->getModuleIdentifier().c_str();\n}\n\n\n\/**\n * Same as LLVMDumpValue, but through our debugging channels.\n *\/\nextern \"C\" void\nlp_debug_dump_value(LLVMValueRef value)\n{\n#if (defined(PIPE_OS_WINDOWS) && !defined(PIPE_CC_MSVC)) || defined(PIPE_OS_EMBDDED)\n raw_debug_ostream os;\n llvm::unwrap(value)->print(os);\n os.flush();\n#else\n LLVMDumpValue(value);\n#endif\n}\n\n\n\/*\n * MemoryObject wrapper around a buffer of memory, to be used by MC\n * disassembler.\n *\/\nclass BufferMemoryObject:\n public llvm::MemoryObject\n{\nprivate:\n const uint8_t *Bytes;\n uint64_t Length;\npublic:\n BufferMemoryObject(const uint8_t *bytes, uint64_t length) :\n Bytes(bytes), Length(length)\n {\n }\n\n uint64_t getBase() const\n {\n return 0;\n }\n\n uint64_t getExtent() const\n {\n return Length;\n }\n\n int readByte(uint64_t addr, uint8_t *byte) const\n {\n if (addr > getExtent())\n return -1;\n *byte = Bytes[addr];\n return 0;\n }\n};\n\n\n\/*\n * Disassemble a function, using the LLVM MC disassembler.\n *\n * See also:\n * - http:\/\/blog.llvm.org\/2010\/01\/x86-disassembler.html\n * - http:\/\/blog.llvm.org\/2010\/04\/intro-to-llvm-mc-project.html\n *\/\nstatic size_t\ndisassemble(const void* func, llvm::raw_ostream & Out)\n{\n using namespace llvm;\n\n const uint8_t *bytes = (const uint8_t *)func;\n\n \/*\n * Limit disassembly to this extent\n *\/\n const uint64_t extent = 96 * 1024;\n\n uint64_t max_pc = 0;\n\n \/*\n * Initialize all used objects.\n *\/\n\n std::string Triple = sys::getDefaultTargetTriple();\n\n std::string Error;\n const Target *T = TargetRegistry::lookupTarget(Triple, Error);\n\n#if HAVE_LLVM >= 0x0304\n OwningPtr AsmInfo(T->createMCAsmInfo(*T->createMCRegInfo(Triple), Triple));\n#else\n OwningPtr AsmInfo(T->createMCAsmInfo(Triple));\n#endif\n\n if (!AsmInfo) {\n Out << \"error: no assembly info for target \" << Triple << \"\\n\";\n Out.flush();\n return 0;\n }\n\n unsigned int AsmPrinterVariant = AsmInfo->getAssemblerDialect();\n\n OwningPtr MRI(T->createMCRegInfo(Triple));\n if (!MRI) {\n Out << \"error: no register info for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n OwningPtr MII(T->createMCInstrInfo());\n if (!MII) {\n Out << \"error: no instruction info for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n#if HAVE_LLVM >= 0x0305\n OwningPtr STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), \"\"));\n OwningPtr MCCtx(new MCContext(AsmInfo.get(), MRI.get(), 0));\n OwningPtr DisAsm(T->createMCDisassembler(*STI, *MCCtx));\n#else\n OwningPtr STI(T->createMCSubtargetInfo(Triple, sys::getHostCPUName(), \"\"));\n OwningPtr DisAsm(T->createMCDisassembler(*STI));\n#endif\n if (!DisAsm) {\n Out << \"error: no disassembler for target \" << Triple << \"\\n\";\n Out.flush();\n return 0;\n }\n\n\n OwningPtr Printer(\n T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));\n if (!Printer) {\n Out << \"error: no instruction printer for target \" << Triple.c_str() << \"\\n\";\n Out.flush();\n return 0;\n }\n\n TargetOptions options;\n#if defined(DEBUG)\n options.JITEmitDebugInfo = true;\n#endif\n#if defined(PIPE_ARCH_X86)\n options.StackAlignmentOverride = 4;\n#endif\n#if defined(DEBUG) || defined(PROFILE)\n options.NoFramePointerElim = true;\n#endif\n OwningPtr TM(T->createTargetMachine(Triple, sys::getHostCPUName(), \"\", options));\n\n#if HAVE_LLVM >= 0x0306\n const TargetInstrInfo *TII = TM->getSubtargetImpl()->getInstrInfo();\n#else\n const TargetInstrInfo *TII = TM->getInstrInfo();\n#endif\n\n \/*\n * Wrap the data in a MemoryObject\n *\/\n BufferMemoryObject memoryObject((const uint8_t *)bytes, extent);\n\n uint64_t pc;\n pc = 0;\n while (true) {\n MCInst Inst;\n uint64_t Size;\n\n \/*\n * Print address. We use addresses relative to the start of the function,\n * so that between runs.\n *\/\n\n Out << llvm::format(\"%6lu:\\t\", (unsigned long)pc);\n\n if (!DisAsm->getInstruction(Inst, Size, memoryObject,\n pc,\n\t\t\t\t nulls(), nulls())) {\n Out << \"invalid\";\n pc += 1;\n }\n\n \/*\n * Output the bytes in hexidecimal format.\n *\/\n\n if (0) {\n unsigned i;\n for (i = 0; i < Size; ++i) {\n Out << llvm::format(\"%02x \", ((const uint8_t*)bytes)[pc + i]);\n }\n for (; i < 16; ++i) {\n Out << \" \";\n }\n }\n\n \/*\n * Print the instruction.\n *\/\n Printer->printInst(&Inst, Out, \"\");\n\n \/*\n * Advance.\n *\/\n\n pc += Size;\n\n const MCInstrDesc &TID = TII->get(Inst.getOpcode());\n\n \/*\n * Keep track of forward jumps to a nearby address.\n *\/\n\n if (TID.isBranch()) {\n for (unsigned i = 0; i < Inst.getNumOperands(); ++i) {\n const MCOperand &operand = Inst.getOperand(i);\n if (operand.isImm()) {\n uint64_t jump;\n\n \/*\n * FIXME: Handle both relative and absolute addresses correctly.\n * EDInstInfo actually has this info, but operandTypes and\n * operandFlags enums are not exposed in the public interface.\n *\/\n\n if (1) {\n \/*\n * PC relative addr.\n *\/\n\n jump = pc + operand.getImm();\n } else {\n \/*\n * Absolute addr.\n *\/\n\n jump = (uint64_t)operand.getImm();\n }\n\n \/*\n * Output the address relative to the function start, given\n * that MC will print the addresses relative the current pc.\n *\/\n Out << \"\\t\\t; \" << jump;\n\n \/*\n * Ignore far jumps given it could be actually a tail return to\n * a random address.\n *\/\n\n if (jump > max_pc &&\n jump < extent) {\n max_pc = jump;\n }\n }\n }\n }\n\n Out << \"\\n\";\n\n \/*\n * Stop disassembling on return statements, if there is no record of a\n * jump to a successive address.\n *\/\n\n if (TID.isReturn()) {\n if (pc > max_pc) {\n break;\n }\n }\n }\n\n \/*\n * Print GDB command, useful to verify output.\n *\/\n\n if (0) {\n _debug_printf(\"disassemble %p %p\\n\", bytes, bytes + pc);\n }\n\n Out << \"\\n\";\n Out.flush();\n\n return pc;\n}\n\n\nextern \"C\" void\nlp_disassemble(LLVMValueRef func, const void *code) {\n raw_debug_ostream Out;\n disassemble(code, Out);\n}\n\n\n\/*\n * Linux perf profiler integration.\n *\n * See also:\n * - http:\/\/penberg.blogspot.co.uk\/2009\/06\/jato-has-profiler.html\n * - https:\/\/github.com\/penberg\/jato\/commit\/73ad86847329d99d51b386f5aba692580d1f8fdc\n * - http:\/\/git.kernel.org\/?p=linux\/kernel\/git\/torvalds\/linux.git;a=commitdiff;h=80d496be89ed7dede5abee5c057634e80a31c82d\n *\/\nextern \"C\" void\nlp_profile(LLVMValueRef func, const void *code)\n{\n#if defined(__linux__) && (defined(DEBUG) || defined(PROFILE))\n static boolean first_time = TRUE;\n static FILE *perf_map_file = NULL;\n static int perf_asm_fd = -1;\n if (first_time) {\n \/*\n * We rely on the disassembler for determining a function's size, but\n * the disassembly is a leaky and slow operation, so avoid running\n * this except when running inside linux perf, which can be inferred\n * by the PERF_BUILDID_DIR environment variable.\n *\/\n if (getenv(\"PERF_BUILDID_DIR\")) {\n pid_t pid = getpid();\n char filename[256];\n util_snprintf(filename, sizeof filename, \"\/tmp\/perf-%llu.map\", (unsigned long long)pid);\n perf_map_file = fopen(filename, \"wt\");\n util_snprintf(filename, sizeof filename, \"\/tmp\/perf-%llu.map.asm\", (unsigned long long)pid);\n mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;\n perf_asm_fd = open(filename, O_WRONLY | O_CREAT, mode);\n }\n first_time = FALSE;\n }\n if (perf_map_file) {\n const char *symbol = LLVMGetValueName(func);\n unsigned long addr = (uintptr_t)code;\n llvm::raw_fd_ostream Out(perf_asm_fd, false);\n Out << symbol << \":\\n\";\n unsigned long size = disassemble(code, Out);\n fprintf(perf_map_file, \"%lx %lx %s\\n\", addr, size, symbol);\n fflush(perf_map_file);\n }\n#else\n (void)func;\n (void)code;\n#endif\n}\n\n\n<|endoftext|>"} {"text":"tools\/scylla-sstable: update general description<|endoftext|>"} {"text":"\/\/ TODO(dkorolev): Factor out fncas.h, add a proper test.\n\/\/ TODO(dkorolev): Use BFS instead of DFS for evaluating and printing.\n\n\/\/ TODO(dkorolev): Readme, build instructions and a reference from this file.\n\/\/\n\/\/ Requires:\n\/\/ * C++0X, use g++ --std=c++0x\n\/\/ * Boost, sudo apt-get install libboost-dev\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define BOOST_TEST_MODULE FNCAS\n#include \n\nnamespace fncas {\n\ntypedef double fncas_value_type;\n\n\/\/ Parsed expression are stored in an array of node_impl objects.\n\/\/ Instances of node_impl take 10 bytes each and are packed.\n\/\/ Each node_impl refers to a value, an input variable, an operation or math function invocation.\n\/\/ Singleton vector is the allocator, therefore the code is single-threaded.\n\nenum type_t : uint8_t { var, value, op };\nenum op_t : uint8_t { add = 0, subtract = 1, multiply = 2, end = 3 };\n\nstd::string op_as_string(op_t op) {\n static std::string represenatation[op_t::end] = { \"+\", \"-\", \"*\" };\n return (op >= 0 && op < static_cast(op_t::end)) ? represenatation[op] : \"?\";\n}\n\ntemplate T apply_op(op_t op, T lhs, T rhs) {\n static boost::function evaluator[op_t::end] = {\n std::plus(),\n std::minus(),\n std::multiplies(),\n };\n return\n (op >= 0 && op < static_cast(op_t::end))\n ? evaluator[op](lhs, rhs)\n : std::numeric_limits::quiet_NaN();\n}\n\nBOOST_STATIC_ASSERT(sizeof(type_t) == 1);\nBOOST_STATIC_ASSERT(sizeof(op_t) == 1);\n\n\/\/ Counting on \"double\", comment if trying other data type.\nBOOST_STATIC_ASSERT(sizeof(fncas_value_type) == 8);\n\nstruct node_impl {\n uint8_t data_[10];\n type_t& type() {\n return *reinterpret_cast(&data_[0]);\n }\n uint32_t& var_index() {\n BOOST_ASSERT(type() == type_t::var); \n return *reinterpret_cast(&data_[2]);\n }\n op_t& op() {\n BOOST_ASSERT(type() == type_t::op);\n return *reinterpret_cast(&data_[1]);\n }\n uint32_t& lhs_index() { \n BOOST_ASSERT(type() == type_t::op); \n return *reinterpret_cast(&data_[2]);\n }\n uint32_t& rhs_index() { \n BOOST_ASSERT(type() == type_t::op);\n return *reinterpret_cast(&data_[6]);\n }\n fncas_value_type& value() { \n BOOST_ASSERT(type() == type_t::value); \n return *reinterpret_cast(&data_[2]);\n }\n};\nBOOST_STATIC_ASSERT(sizeof(node_impl) == 10);\n\ninline std::vector& node_vector_singleton() {\n static std::vector storage;\n return storage;\n}\n\n\/\/ The code that deals with nodes directly uses class node as a wrapper to node_impl.\n\/\/ Since the storage for node_impl-s is global, class node just holds an index of node_impl.\n\/\/ User code that defines the function to work with is effectively dealing with class node objects:\n\/\/ arithmetical and mathematical operations are overloaded for class node.\n\nstruct node_constructor {\n mutable uint64_t index_;\n explicit node_constructor(uint64_t index) : index_(static_cast(index)) {}\n explicit node_constructor() : index_(node_vector_singleton().size()) {\n node_vector_singleton().resize(index_ + 1);\n }\n};\n\nstruct node : node_constructor {\n private:\n node() : node_constructor() {}\n node(const node_constructor& instance) : node_constructor(instance) {}\n public:\n node(fncas_value_type x) : node_constructor() { type() = type_t::value; value() = x; }\n type_t& type() const { return node_vector_singleton()[index_].type(); }\n uint32_t& var_index() const { return node_vector_singleton()[index_].var_index(); }\n op_t& op() const { return node_vector_singleton()[index_].op(); }\n uint32_t& lhs_index() const { return node_vector_singleton()[index_].lhs_index(); }\n uint32_t& rhs_index() const { return node_vector_singleton()[index_].rhs_index(); }\n node lhs() const { return node_constructor(node_vector_singleton()[index_].lhs_index()); }\n node rhs() const { return node_constructor(node_vector_singleton()[index_].rhs_index()); }\n fncas_value_type& value() const { return node_vector_singleton()[index_].value(); }\n static node alloc() { return node(); }\n static node var(uint32_t index) {\n node result;\n result.type() = type_t::var;\n result.var_index() = index;\n return result;\n }\n std::string debug_as_string() const {\n if (type() == type_t::var) {\n return \"x[\" + std::to_string(var_index()) + \"]\";\n } else if (type() == type_t::value) {\n return std::to_string(value());\n } else if (type() == type_t::op) {\n return \"(\" + lhs().debug_as_string() + op_as_string(op()) + rhs().debug_as_string() + \")\";\n } else {\n return \"?\";\n }\n }\n fncas_value_type eval(const std::vector& x) const {\n if (type() == type_t::var) {\n uint32_t i = var_index();\n BOOST_ASSERT(i >= 0 && i < x.size());\n return x[i];\n } else if (type() == type_t::value) {\n return value();\n } else if (type() == type_t::op) {\n return apply_op(op(), lhs().eval(x), rhs().eval(x));\n } else {\n return std::numeric_limits::quiet_NaN();\n }\n }\n};\nBOOST_STATIC_ASSERT(sizeof(node) == 8);\n\n\/\/ Class \"x\" is the placeholder class an instance of which is to be passed to the user function\n\/\/ to record the computation rather than perform it.\n\nstruct x : boost::noncopyable {\n int dim;\n explicit x(int dim) : dim(dim) {\n BOOST_ASSERT(dim > 0);\n }\n node operator[](int i) const {\n BOOST_ASSERT(i >= 0);\n BOOST_ASSERT(i < dim);\n return node::var(i);\n }\n};\n\n\/\/ Helper code to allow writing polymorphic function that can be both evaluated and recorded.\n\/\/ Synopsis: template typename fncas::output::type f(const T& x);\n\ntemplate struct output {};\ntemplate<> struct output > { typedef fncas_value_type type; };\ntemplate<> struct output { typedef fncas::node type; };\n\n} \/\/ namespace fncas\n\n#define DECLARE_OP(OP,NAME) \\\ninline fncas::node operator OP(const fncas::node& lhs, const fncas::node& rhs) { \\\n fncas::node result = fncas::node::alloc(); \\\n result.type() = fncas::type_t::op; \\\n result.op() = fncas::op_t::NAME; \\\n result.lhs_index() = lhs.index_; \\\n result.rhs_index() = rhs.index_; \\\n return result; \\\n}\nDECLARE_OP(+,add);\nDECLARE_OP(-,subtract);\nDECLARE_OP(*,multiply);\n\ntemplate typename fncas::output::type f(const T& x) {\n return 1 + x[0] * x[1] + x[2] - x[3] + 1;\n}\n\nBOOST_AUTO_TEST_CASE(SimpleTest) {\n std::vector x({5,8,9,7});\n BOOST_CHECK_EQUAL(f(x), 44);\n auto e = f(fncas::x(4));\n BOOST_CHECK_EQUAL(e.debug_as_string(), \"((((1.000000+(x[0]*x[1]))+x[2])-x[3])+1.000000)\");\n BOOST_CHECK_EQUAL(e.eval(x), 44);\n}\nComment nits.\/\/ TODO(dkorolev): Factor out fncas.h, add a proper test.\n\/\/ TODO(dkorolev): Use BFS instead of DFS for evaluating and printing.\n\n\/\/ TODO(dkorolev): Readme, build instructions and a reference from this file.\n\/\/\n\/\/ Requires:\n\/\/ * C++0X, use g++ --std=c++0x\n\/\/ * Boost, sudo apt-get install libboost-dev\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#define BOOST_TEST_MODULE FNCAS\n#include \n\nnamespace fncas {\n\ntypedef double fncas_value_type;\n\n\/\/ Parsed expressions are stored in an array of node_impl objects.\n\/\/ Instances of node_impl take 10 bytes each and are packed.\n\/\/ Each node_impl refers to a value, an input variable, an operation or math function invocation.\n\/\/ Singleton vector is the allocator, therefore the code is single-threaded.\n\nenum type_t : uint8_t { var, value, op };\nenum op_t : uint8_t { add = 0, subtract = 1, multiply = 2, end = 3 };\n\nstd::string op_as_string(op_t op) {\n static std::string represenatation[op_t::end] = { \"+\", \"-\", \"*\" };\n return (op >= 0 && op < static_cast(op_t::end)) ? represenatation[op] : \"?\";\n}\n\ntemplate T apply_op(op_t op, T lhs, T rhs) {\n static boost::function evaluator[op_t::end] = {\n std::plus(),\n std::minus(),\n std::multiplies(),\n };\n return\n (op >= 0 && op < static_cast(op_t::end))\n ? evaluator[op](lhs, rhs)\n : std::numeric_limits::quiet_NaN();\n}\n\nBOOST_STATIC_ASSERT(sizeof(type_t) == 1);\nBOOST_STATIC_ASSERT(sizeof(op_t) == 1);\n\n\/\/ Counting on \"double\", comment out if trying other data type.\nBOOST_STATIC_ASSERT(sizeof(fncas_value_type) == 8);\n\nstruct node_impl {\n uint8_t data_[10];\n type_t& type() {\n return *reinterpret_cast(&data_[0]);\n }\n uint32_t& var_index() {\n BOOST_ASSERT(type() == type_t::var); \n return *reinterpret_cast(&data_[2]);\n }\n op_t& op() {\n BOOST_ASSERT(type() == type_t::op);\n return *reinterpret_cast(&data_[1]);\n }\n uint32_t& lhs_index() { \n BOOST_ASSERT(type() == type_t::op); \n return *reinterpret_cast(&data_[2]);\n }\n uint32_t& rhs_index() { \n BOOST_ASSERT(type() == type_t::op);\n return *reinterpret_cast(&data_[6]);\n }\n fncas_value_type& value() { \n BOOST_ASSERT(type() == type_t::value); \n return *reinterpret_cast(&data_[2]);\n }\n};\nBOOST_STATIC_ASSERT(sizeof(node_impl) == 10);\n\ninline std::vector& node_vector_singleton() {\n static std::vector storage;\n return storage;\n}\n\n\/\/ The code that deals with nodes directly uses class node as a wrapper to node_impl.\n\/\/ Since the storage for node_impl-s is global, class node just holds an index of node_impl.\n\/\/ User code that defines the function to work with is effectively dealing with class node objects:\n\/\/ arithmetical and mathematical operations are overloaded for class node.\n\nstruct node_constructor {\n mutable uint64_t index_;\n explicit node_constructor(uint64_t index) : index_(static_cast(index)) {}\n explicit node_constructor() : index_(node_vector_singleton().size()) {\n node_vector_singleton().resize(index_ + 1);\n }\n};\n\nstruct node : node_constructor {\n private:\n node() : node_constructor() {}\n node(const node_constructor& instance) : node_constructor(instance) {}\n public:\n node(fncas_value_type x) : node_constructor() { type() = type_t::value; value() = x; }\n type_t& type() const { return node_vector_singleton()[index_].type(); }\n uint32_t& var_index() const { return node_vector_singleton()[index_].var_index(); }\n op_t& op() const { return node_vector_singleton()[index_].op(); }\n uint32_t& lhs_index() const { return node_vector_singleton()[index_].lhs_index(); }\n uint32_t& rhs_index() const { return node_vector_singleton()[index_].rhs_index(); }\n node lhs() const { return node_constructor(node_vector_singleton()[index_].lhs_index()); }\n node rhs() const { return node_constructor(node_vector_singleton()[index_].rhs_index()); }\n fncas_value_type& value() const { return node_vector_singleton()[index_].value(); }\n static node alloc() { return node(); }\n static node var(uint32_t index) {\n node result;\n result.type() = type_t::var;\n result.var_index() = index;\n return result;\n }\n std::string debug_as_string() const {\n if (type() == type_t::var) {\n return \"x[\" + std::to_string(var_index()) + \"]\";\n } else if (type() == type_t::value) {\n return std::to_string(value());\n } else if (type() == type_t::op) {\n return \"(\" + lhs().debug_as_string() + op_as_string(op()) + rhs().debug_as_string() + \")\";\n } else {\n return \"?\";\n }\n }\n fncas_value_type eval(const std::vector& x) const {\n if (type() == type_t::var) {\n uint32_t i = var_index();\n BOOST_ASSERT(i >= 0 && i < x.size());\n return x[i];\n } else if (type() == type_t::value) {\n return value();\n } else if (type() == type_t::op) {\n return apply_op(op(), lhs().eval(x), rhs().eval(x));\n } else {\n return std::numeric_limits::quiet_NaN();\n }\n }\n};\nBOOST_STATIC_ASSERT(sizeof(node) == 8);\n\n\/\/ Class \"x\" is the placeholder class an instance of which is to be passed to the user function\n\/\/ to record the computation rather than perform it.\n\nstruct x : boost::noncopyable {\n int dim;\n explicit x(int dim) : dim(dim) {\n BOOST_ASSERT(dim > 0);\n }\n node operator[](int i) const {\n BOOST_ASSERT(i >= 0);\n BOOST_ASSERT(i < dim);\n return node::var(i);\n }\n};\n\n\/\/ Helper code to allow writing polymorphic function that can be both evaluated and recorded.\n\/\/ Synopsis: template typename fncas::output::type f(const T& x);\n\ntemplate struct output {};\ntemplate<> struct output > { typedef fncas_value_type type; };\ntemplate<> struct output { typedef fncas::node type; };\n\n} \/\/ namespace fncas\n\n\/\/ Aritmetical operations and mathematical functions are defined outside namespace fncas.\n\n#define DECLARE_OP(OP,NAME) \\\ninline fncas::node operator OP(const fncas::node& lhs, const fncas::node& rhs) { \\\n fncas::node result = fncas::node::alloc(); \\\n result.type() = fncas::type_t::op; \\\n result.op() = fncas::op_t::NAME; \\\n result.lhs_index() = lhs.index_; \\\n result.rhs_index() = rhs.index_; \\\n return result; \\\n}\nDECLARE_OP(+,add);\nDECLARE_OP(-,subtract);\nDECLARE_OP(*,multiply);\n\ntemplate typename fncas::output::type f(const T& x) {\n return 1 + x[0] * x[1] + x[2] - x[3] + 1;\n}\n\nBOOST_AUTO_TEST_CASE(SimpleTest) {\n std::vector x({5,8,9,7});\n BOOST_CHECK_EQUAL(f(x), 44);\n auto e = f(fncas::x(4));\n BOOST_CHECK_EQUAL(e.debug_as_string(), \"((((1.000000+(x[0]*x[1]))+x[2])-x[3])+1.000000)\");\n BOOST_CHECK_EQUAL(e.eval(x), 44);\n}\n<|endoftext|>"} {"text":"Support ls without a path<|endoftext|>"} {"text":"\/*\n * FilenameParsingGroundTruthLayer.cpp\n *\n * Created on: Nov 10, 2014\n * Author: wchavez\n *\/\n\n#include \"FilenameParsingGroundTruthLayer.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace PV {\nFilenameParsingGroundTruthLayer::FilenameParsingGroundTruthLayer(const char *name, HyPerCol *hc) {\n initialize(name, hc);\n}\n\nFilenameParsingGroundTruthLayer::~FilenameParsingGroundTruthLayer() { free(mInputLayerName); }\n\nint FilenameParsingGroundTruthLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n int status = ANNLayer::ioParamsFillGroup(ioFlag);\n ioParam_classes(ioFlag);\n ioParam_inputLayerName(ioFlag);\n ioParam_gtClassTrueValue(ioFlag);\n ioParam_gtClassFalseValue(ioFlag);\n return status;\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_gtClassTrueValue(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"gtClassTrueValue\", &mGtClassTrueValue, 1.0f, false);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_gtClassFalseValue(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"gtClassFalseValue\", &mGtClassFalseValue, -1.0f, false);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_inputLayerName(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamStringRequired(ioFlag, name, \"inputLayerName\", &mInputLayerName);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_classes(enum ParamsIOFlag ioFlag) {\n std::string outPath = parent->getOutputPath();\n outPath = outPath + \"\/classes.txt\";\n mInputFile.open(outPath.c_str(), std::ifstream::in);\n pvErrorIf(!mInputFile.is_open(), \"%s: Unable to open file %s\\n\", getName(), outPath.c_str());\n\n mClasses.clear();\n std::string line;\n while (getline(mInputFile, line)) {\n mClasses.push_back(line);\n }\n mInputFile.close();\n}\n\nint FilenameParsingGroundTruthLayer::communicateInitInfo() {\n mInputLayer = dynamic_cast(parent->getLayerFromName(mInputLayerName));\n pvErrorIf(mInputLayer == nullptr && parent->columnId() == 0,\n \"%s: inputLayerName \\\"%s\\\" is not a layer in the HyPerCol.\\n\",\n getDescription_c(),\n mInputLayerName);\n pvErrorIf(mInputLayer->getPhase() >= getPhase(),\n \"%s: The phase of layer %s (%d) must be less than the phase of the \"\n \"FilenameParsingGroundTruthLayer (%d)\\n\",\n getName(),\n mInputLayerName,\n mInputLayer->getPhase(),\n getPhase());\n return PV_SUCCESS;\n}\n\nbool FilenameParsingGroundTruthLayer::needUpdate(double time, double dt) {\n return mInputLayer->needUpdate(parent->simulationTime(), parent->getDeltaTime());\n}\n\nint FilenameParsingGroundTruthLayer::updateState(double time, double dt) {\n update_timer->start();\n pvdata_t *A = getCLayer()->activity->data;\n const PVLayerLoc *loc = getLayerLoc();\n int num_neurons = getNumNeurons();\n pvErrorIf(\n num_neurons != mClasses.size(),\n \"The number of neurons in %s is not equal to the number of classes specified in \"\n \"%s\/classes.txt\\n\",\n getName(),\n parent->getOutputPath());\n\n for (int b = 0; b < loc->nbatch; ++b) {\n char *currentFilename = nullptr;\n int filenameLen = 0;\n if (parent->getCommunicator()->commRank() == 0) {\n currentFilename = strdup(mInputLayer->getFileName(b).c_str());\n int filenameLen = (int)strlen(currentFilename) + 1; \/\/ +1 for the null terminator\n MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());\n \/\/ Braodcast filename to all other local processes\n MPI_Bcast(\n currentFilename,\n filenameLen,\n MPI_CHAR,\n 0,\n parent->getCommunicator()->communicator());\n }\n else {\n \/\/ Receive broadcast about length of filename\n MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());\n currentFilename = (char *)calloc(sizeof(char), filenameLen);\n \/\/ Receive filename\n MPI_Bcast(\n currentFilename,\n filenameLen,\n MPI_CHAR,\n 0,\n parent->getCommunicator()->communicator());\n }\n\n std::string fil = currentFilename;\n pvdata_t *ABatch = A + b * getNumExtended();\n for (int i = 0; i < num_neurons; i++) {\n int nExt = kIndexExtended(\n i,\n loc->nx,\n loc->ny,\n loc->nf,\n loc->halo.lt,\n loc->halo.rt,\n loc->halo.dn,\n loc->halo.up);\n int fi = featureIndex(\n nExt,\n loc->nx + loc->halo.rt + loc->halo.lt,\n loc->ny + loc->halo.dn + loc->halo.up,\n loc->nf);\n int match = fil.find(mClasses.at(i));\n if (0 <= match) {\n ABatch[nExt] = mGtClassTrueValue;\n }\n else {\n ABatch[nExt] = mGtClassFalseValue;\n }\n }\n free(currentFilename);\n }\n update_timer->stop();\n return PV_SUCCESS;\n}\n}\nHotfix for previous error message. Functions correctly now.\/*\n * FilenameParsingGroundTruthLayer.cpp\n *\n * Created on: Nov 10, 2014\n * Author: wchavez\n *\/\n\n#include \"FilenameParsingGroundTruthLayer.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace PV {\nFilenameParsingGroundTruthLayer::FilenameParsingGroundTruthLayer(const char *name, HyPerCol *hc) {\n initialize(name, hc);\n}\n\nFilenameParsingGroundTruthLayer::~FilenameParsingGroundTruthLayer() { free(mInputLayerName); }\n\nint FilenameParsingGroundTruthLayer::ioParamsFillGroup(enum ParamsIOFlag ioFlag) {\n int status = ANNLayer::ioParamsFillGroup(ioFlag);\n ioParam_classes(ioFlag);\n ioParam_inputLayerName(ioFlag);\n ioParam_gtClassTrueValue(ioFlag);\n ioParam_gtClassFalseValue(ioFlag);\n return status;\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_gtClassTrueValue(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"gtClassTrueValue\", &mGtClassTrueValue, 1.0f, false);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_gtClassFalseValue(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamValue(\n ioFlag, name, \"gtClassFalseValue\", &mGtClassFalseValue, -1.0f, false);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_inputLayerName(enum ParamsIOFlag ioFlag) {\n parent->parameters()->ioParamStringRequired(ioFlag, name, \"inputLayerName\", &mInputLayerName);\n}\n\nvoid FilenameParsingGroundTruthLayer::ioParam_classes(enum ParamsIOFlag ioFlag) {\n std::string outPath = parent->getOutputPath();\n outPath = outPath + \"\/classes.txt\";\n mInputFile.open(outPath.c_str(), std::ifstream::in);\n pvErrorIf(!mInputFile.is_open(), \"%s: Unable to open file %s\\n\", getName(), outPath.c_str());\n\n mClasses.clear();\n std::string line;\n while (getline(mInputFile, line)) {\n mClasses.push_back(line);\n }\n mInputFile.close();\n}\n\nint FilenameParsingGroundTruthLayer::communicateInitInfo() {\n mInputLayer = dynamic_cast(parent->getLayerFromName(mInputLayerName));\n pvErrorIf(mInputLayer == nullptr && parent->columnId() == 0,\n \"%s: inputLayerName \\\"%s\\\" is not a layer in the HyPerCol.\\n\",\n getDescription_c(),\n mInputLayerName);\n pvErrorIf(mInputLayer->getPhase() <= getPhase(),\n \"%s: The phase of layer %s (%d) must be greater than the phase of the \"\n \"FilenameParsingGroundTruthLayer (%d)\\n\",\n getName(),\n mInputLayerName,\n mInputLayer->getPhase(),\n getPhase());\n return PV_SUCCESS;\n}\n\nbool FilenameParsingGroundTruthLayer::needUpdate(double time, double dt) {\n return mInputLayer->needUpdate(parent->simulationTime(), parent->getDeltaTime());\n}\n\nint FilenameParsingGroundTruthLayer::updateState(double time, double dt) {\n update_timer->start();\n pvdata_t *A = getCLayer()->activity->data;\n const PVLayerLoc *loc = getLayerLoc();\n int num_neurons = getNumNeurons();\n pvErrorIf(\n num_neurons != mClasses.size(),\n \"The number of neurons in %s is not equal to the number of classes specified in \"\n \"%s\/classes.txt\\n\",\n getName(),\n parent->getOutputPath());\n\n for (int b = 0; b < loc->nbatch; ++b) {\n char *currentFilename = nullptr;\n int filenameLen = 0;\n if (parent->getCommunicator()->commRank() == 0) {\n currentFilename = strdup(mInputLayer->getFileName(b).c_str());\n int filenameLen = (int)strlen(currentFilename) + 1; \/\/ +1 for the null terminator\n MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());\n \/\/ Braodcast filename to all other local processes\n MPI_Bcast(\n currentFilename,\n filenameLen,\n MPI_CHAR,\n 0,\n parent->getCommunicator()->communicator());\n }\n else {\n \/\/ Receive broadcast about length of filename\n MPI_Bcast(&filenameLen, 1, MPI_INT, 0, parent->getCommunicator()->communicator());\n currentFilename = (char *)calloc(sizeof(char), filenameLen);\n \/\/ Receive filename\n MPI_Bcast(\n currentFilename,\n filenameLen,\n MPI_CHAR,\n 0,\n parent->getCommunicator()->communicator());\n }\n\n std::string fil = currentFilename;\n pvdata_t *ABatch = A + b * getNumExtended();\n for (int i = 0; i < num_neurons; i++) {\n int nExt = kIndexExtended(\n i,\n loc->nx,\n loc->ny,\n loc->nf,\n loc->halo.lt,\n loc->halo.rt,\n loc->halo.dn,\n loc->halo.up);\n int fi = featureIndex(\n nExt,\n loc->nx + loc->halo.rt + loc->halo.lt,\n loc->ny + loc->halo.dn + loc->halo.up,\n loc->nf);\n int match = fil.find(mClasses.at(i));\n if (0 <= match) {\n ABatch[nExt] = mGtClassTrueValue;\n }\n else {\n ABatch[nExt] = mGtClassFalseValue;\n }\n }\n free(currentFilename);\n }\n update_timer->stop();\n return PV_SUCCESS;\n}\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file FlightTaskManual.cpp\n *\n * Linear and exponential map from stick inputs to range -1 and 1.\n *\n *\/\n\n#include \"FlightTaskManual.hpp\"\n#include \n#include \n\nusing namespace matrix;\n\nFlightTaskManual::FlightTaskManual(control::SuperBlock *parent, const char *name) :\n\tFlightTask(parent, name),\n\t_hold_dz(parent, \"MPC_HOLD_DZ\", false),\n\t_xy_vel_man_expo(parent, \"MPC_XY_MAN_EXPO\", false),\n\t_z_vel_man_expo(parent, \"MPC_Z_MAN_EXPO\", false)\n{\n}\n\nbool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array)\n{\n\tif (!FlightTask::initializeSubscriptions(subscription_array)) {\n\t\treturn false;\n\t}\n\n\tif (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool FlightTaskManual::activate()\n{\n\tbool ret = FlightTask::activate();\n\t_hold_position = Vector3f(NAN, NAN, NAN);\n\t_hold_yaw = NAN;\n\treturn ret;\n}\n\nbool FlightTaskManual::updateInitialize()\n{\n\tbool ret = FlightTask::updateInitialize();\n\tconst bool sticks_available = _evaluateSticks();\n\n\tif (_sticks_data_required) {\n\t\tret = ret && sticks_available;\n\t}\n\n\treturn ret;\n}\n\nbool FlightTaskManual::update()\n{\n\t\/* TODO\n\t * FlightTask setpoint interface and Position Controller need to be updated to include\n\t * thrust setpoint. With thrust setpoint FlightTaskManual can be used as manual flight mode.\n\t *\/\n\treturn true;\n}\n\nfloat FlightTaskManual::_get_input_frame_yaw()\n{\n\t\/* using constant yaw angle from setpoint here to prevent sideways oscillation in fast forward flight *\/\n\tif (PX4_ISFINITE(_hold_yaw)) {\n\t\treturn _hold_yaw;\n\n\t} else {\n\t\treturn _yaw;\n\t}\n}\n\nvoid FlightTaskManual::_updateYaw()\n{\n\tconst float yaw_speed = _sticks(3) * math::radians(_man_yaw_max.get());\n\t_setYawspeedSetpoint(yaw_speed);\n\n\tconst bool stick_yaw_zero = fabsf(yaw_speed) <= FLT_EPSILON;\n\n\tif (stick_yaw_zero && !PX4_ISFINITE(_hold_yaw)) {\n\t\t_hold_yaw = _yaw;\n\n\t} else if (!stick_yaw_zero) {\n\t\t_hold_yaw = NAN;\n\t}\n\n\t_setYawSetpoint(_hold_yaw);\n}\n\nbool FlightTaskManual::_evaluateSticks()\n{\n\t\/* Sticks are rescaled linearly and exponentially from [0,1] to [-1,1] *\/\n\tif ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) {\n\n\t\t\/* Linear scale *\/\n\t\t_sticks(0) = _sub_manual_control_setpoint->get().x; \/* NED x, \"pitch\" [-1,1] *\/\n\t\t_sticks(1) = _sub_manual_control_setpoint->get().y; \/* NED y, \"roll\" [-1,1] *\/\n\t\t_sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; \/* NED z, \"thrust\" resacaled from [0,1] to [-1,1] *\/\n\t\t_sticks(3) = _sub_manual_control_setpoint->get().r; \/* \"yaw\" [-1,1] *\/\n\n\t\t\/* Exponential scale *\/\n\t\t_sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _hold_dz.get());\n\t\t_sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _hold_dz.get());\n\t\t_sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _hold_dz.get());\n\n\t\treturn true;\n\n\t} else {\n\t\t\/* Timeout: set all sticks to zero *\/\n\t\t_sticks.zero();\n\t\t_sticks_expo.zero();\n\t\treturn false;\n\t}\n}\nFlightTaskManual: remove unused methods\/****************************************************************************\n *\n * Copyright (c) 2017 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\/**\n * @file FlightTaskManual.cpp\n *\n * Linear and exponential map from stick inputs to range -1 and 1.\n *\n *\/\n\n#include \"FlightTaskManual.hpp\"\n#include \n#include \n\nusing namespace matrix;\n\nFlightTaskManual::FlightTaskManual(control::SuperBlock *parent, const char *name) :\n\tFlightTask(parent, name),\n\t_hold_dz(parent, \"MPC_HOLD_DZ\", false),\n\t_xy_vel_man_expo(parent, \"MPC_XY_MAN_EXPO\", false),\n\t_z_vel_man_expo(parent, \"MPC_Z_MAN_EXPO\", false)\n{\n}\n\nbool FlightTaskManual::initializeSubscriptions(SubscriptionArray &subscription_array)\n{\n\tif (!FlightTask::initializeSubscriptions(subscription_array)) {\n\t\treturn false;\n\t}\n\n\tif (!subscription_array.get(ORB_ID(manual_control_setpoint), _sub_manual_control_setpoint)) {\n\t\treturn false;\n\t}\n\n\treturn true;\n}\n\nbool FlightTaskManual::activate()\n{\n\tbool ret = FlightTask::activate();\n\treturn ret;\n}\n\nbool FlightTaskManual::updateInitialize()\n{\n\tbool ret = FlightTask::updateInitialize();\n\tconst bool sticks_available = _evaluateSticks();\n\n\tif (_sticks_data_required) {\n\t\tret = ret && sticks_available;\n\t}\n\n\treturn ret;\n}\n\nbool FlightTaskManual::update()\n{\n\t\/* TODO\n\t * FlightTask setpoint interface and Position Controller need to be updated to include\n\t * thrust setpoint. With thrust setpoint FlightTaskManual can be used as manual flight mode.\n\t *\/\n\treturn true;\n}\n\nbool FlightTaskManual::_evaluateSticks()\n{\n\t\/* Sticks are rescaled linearly and exponentially from [0,1] to [-1,1] *\/\n\tif ((_time_stamp_current - _sub_manual_control_setpoint->get().timestamp) < _timeout) {\n\n\t\t\/* Linear scale *\/\n\t\t_sticks(0) = _sub_manual_control_setpoint->get().x; \/* NED x, \"pitch\" [-1,1] *\/\n\t\t_sticks(1) = _sub_manual_control_setpoint->get().y; \/* NED y, \"roll\" [-1,1] *\/\n\t\t_sticks(2) = -(_sub_manual_control_setpoint->get().z - 0.5f) * 2.f; \/* NED z, \"thrust\" resacaled from [0,1] to [-1,1] *\/\n\t\t_sticks(3) = _sub_manual_control_setpoint->get().r; \/* \"yaw\" [-1,1] *\/\n\n\t\t\/* Exponential scale *\/\n\t\t_sticks_expo(0) = math::expo_deadzone(_sticks(0), _xy_vel_man_expo.get(), _hold_dz.get());\n\t\t_sticks_expo(1) = math::expo_deadzone(_sticks(1), _xy_vel_man_expo.get(), _hold_dz.get());\n\t\t_sticks_expo(2) = math::expo_deadzone(_sticks(2), _z_vel_man_expo.get(), _hold_dz.get());\n\n\t\treturn true;\n\n\t} else {\n\t\t\/* Timeout: set all sticks to zero *\/\n\t\t_sticks.zero();\n\t\t_sticks_expo.zero();\n\t\treturn false;\n\t}\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"texture.h\"\n#include \"texture_pack.h\"\n#include \"font_renderer.h\"\n#include \"ball.h\"\n#include \"paddle.h\"\n#include \"constants.h\"\n#include \"collision.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/The window we'll be rendering to\nSDL_Window* window = nullptr;\n\n\/\/The window renderer\nSDL_Renderer* renderer = nullptr;\n\nMix_Chunk* bop = nullptr;\nMix_Chunk* boop = nullptr;\n\nbool Init(TexturePack* textures) {\n \/\/Initialization flag\n bool success = true;\n\n \/\/Initialize SDL\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {\n printf(\"SDL could not initialize! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Set texture filtering to linear\n if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, \"1\")) {\n printf(\"Warning: Linear texture filtering not enabled!\");\n }\n\n \/\/Create window\n window = SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, constants::SCREEN_WIDTH, constants::SCREEN_HEIGHT, SDL_WINDOW_SHOWN);\n if (window == nullptr) {\n printf(\"Window could not be created! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Create vsynced renderer for window\n renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n if (renderer == nullptr) {\n printf(\"Renderer could not be created! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Initialize renderer color\n SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n\n \/\/Initialize PNG loading\n int img_flags = IMG_INIT_PNG;\n if (!(IMG_Init(img_flags) & img_flags)) {\n printf(\"SDL_image could not initialize! SDL_image Error: %s\\n\", IMG_GetError());\n return false;\n }\n\n \/\/Initialize SDL_ttf\n if(TTF_Init() == -1) {\n printf(\"SDL_ttf could not initialize! SDL_ttf Error: %s\\n\", TTF_GetError());\n return false;\n }\n \n \/\/Initialize SDL_mixer\n if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) {\n printf(\"SDL_mixer could not initialize! SDL_mixer Error: %s\\n\", Mix_GetError());\n return false;\n }\n\n \/\/TODO: use seperate texture pack for fonts\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n textures->InitTexture(static_cast(i), renderer);\n }\n\n return success;\n}\n\nbool LoadMedia(TexturePack* textures) {\n \/\/Loading success flag\n bool success = true;\n\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n Texture* current = textures->GetTexture(static_cast(i));\n std::string path = textures->TexturePath(static_cast(i));\n if (!current->LoadFromFile(path)) {\n printf(\"Failed to load texture: %s\\n\", path.c_str());\n success = false;\n }\n }\n\n bop = Mix_LoadWAV(\"assets\/sfx\/blip-fs5.wav\");\n if(bop == nullptr) {\n\t\tprintf( \"Failed to load bop sound effect! SDL_mixer Error: %s\\n\", Mix_GetError() );\n\t\tsuccess = false;\n }\n \n boop = Mix_LoadWAV(\"assets\/sfx\/blip-fs4.wav\");\n if(boop == nullptr) {\n\t\tprintf( \"Failed to load boop sound effect! SDL_mixer Error: %s\\n\", Mix_GetError() );\n\t\tsuccess = false;\n }\n\n return success;\n}\n\nvoid Close(TexturePack* textures) {\n \/\/Free loaded images\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n Texture* current = textures->GetTexture(static_cast(i));\n current->Free(); \n }\n\n \/\/Destroy window\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(window);\n window = nullptr;\n renderer = nullptr;\n\n Mix_FreeChunk(bop);\n bop = nullptr;\n\n Mix_FreeChunk(boop);\n boop = nullptr;\n\n \/\/Quit SDL subsystems\n Mix_Quit();\n TTF_Quit();\n IMG_Quit();\n SDL_Quit();\n}\n\nvoid PrintRect(SDL_Rect* rect) {\n printf(\"Rect - x: %d, y: %d, w: %d, h: %d\\n\", rect->x, rect->y, rect->w, rect->h);\n}\n\nvoid GameLoop(TexturePack* textures) {\n bool quit = false;\n\n SDL_Event e;\n\n Ball ball;\n\n Paddle player(true);\n Paddle ai(false);\n\n int player_score = 0;\n int ai_score = 0;\n\n std::vector ball_colliders;\n\n ball_colliders.push_back(player.GetCollider());\n ball_colliders.push_back(ai.GetCollider());\n\n Uint64 time_now = SDL_GetPerformanceCounter();\n Uint64 time_last = 0;\n double delta_time = 0;\n\n SDL_Color text_color = { 255, 255, 255, 255 };\n\n FontRenderer font_renderer;\n\n while (!quit) {\n time_last = time_now;\n time_now = SDL_GetPerformanceCounter();\n \n delta_time = ((time_now - time_last)*1000 \/ (double)SDL_GetPerformanceFrequency());\n\n \/\/Handle events on queue\n while(SDL_PollEvent(&e) != 0) {\n \/\/User requests quit\n if(e.type == SDL_QUIT) {\n quit = true;\n }\n\n player.HandleEvent(e);\n }\n\n ai.Autopilot(ball.GetCollider());\n\n \/\/ Paddles must move before ball!\n ai.Move(delta_time);\n player.Move(delta_time);\n CollisionType collision = ball.Move(delta_time, ball_colliders, &player_score, &ai_score);\n\n \/\/Clear screen\n SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_RenderClear(renderer);\n\n \/\/Render bg\n textures->GetTexture(TextureName::BG)->Render(0, 0);\n \n \/\/ Render paddles\n ai.Render(textures->GetTexture(TextureName::PADDLE));\n player.Render(textures->GetTexture(TextureName::PADDLE));\n\n \/\/Render dot\n ball.Render(textures->GetTexture(TextureName::BALL));\n\n \/\/ Render text\n int text_width = 0;\n int text_height = 0;\n std::ostringstream score_stream;\n score_stream << player_score << \" \" << ai_score;\n\n std::string score_text = score_stream.str();\n \n if (font_renderer.SizeFont(FontName::FORWARD, 42, score_text, &text_width, &text_height) != 0) {\n printf(\"Failure to size font!\\n\");\n }\n\n font_renderer.RenderFont(renderer, FontName::FORWARD, 42, \n \/*x=*\/(constants::SCREEN_WIDTH - text_width) \/ 2, \/*y=*\/10, score_text, text_color);\n\n \/\/ This is a terrible hack due to the font rendering being broken\n if (player_score == -1) {\n player_score = 0;\n }\n\n switch (collision) {\n case CollisionType::WALL:\n case CollisionType::PADDLE:\n Mix_PlayChannel( -1, bop, 0 );\n break; \n case CollisionType::SCORE:\n Mix_PlayChannel(-1, boop, 0);\n break;\n default: break;\n }\n\n \/\/Update screen\n SDL_RenderPresent(renderer);\n }\n}\n\nint main(int argc, char *args[]) {\n TexturePack textures;\n\n if (!Init(&textures)) {\n printf(\"Failed to initialize main game!\\n\");\n return -1;\n }\n\n if (!LoadMedia(&textures)) {\n printf(\"Failed to load media!\\n\");\n return -1;\n }\n\n GameLoop(&textures);\n\n Close(&textures);\n\n return 0;\n}\nRemove the hack to make font rendering work#include \n\n#include \"texture.h\"\n#include \"texture_pack.h\"\n#include \"font_renderer.h\"\n#include \"ball.h\"\n#include \"paddle.h\"\n#include \"constants.h\"\n#include \"collision.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/The window we'll be rendering to\nSDL_Window* window = nullptr;\n\n\/\/The window renderer\nSDL_Renderer* renderer = nullptr;\n\nMix_Chunk* bop = nullptr;\nMix_Chunk* boop = nullptr;\n\nbool Init(TexturePack* textures) {\n \/\/Initialization flag\n bool success = true;\n\n \/\/Initialize SDL\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {\n printf(\"SDL could not initialize! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Set texture filtering to linear\n if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, \"1\")) {\n printf(\"Warning: Linear texture filtering not enabled!\");\n }\n\n \/\/Create window\n window = SDL_CreateWindow(\"Pong\", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, constants::SCREEN_WIDTH, constants::SCREEN_HEIGHT, SDL_WINDOW_SHOWN);\n if (window == nullptr) {\n printf(\"Window could not be created! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Create vsynced renderer for window\n renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);\n if (renderer == nullptr) {\n printf(\"Renderer could not be created! SDL Error: %s\\n\", SDL_GetError());\n return false;\n }\n\n \/\/Initialize renderer color\n SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n\n \/\/Initialize PNG loading\n int img_flags = IMG_INIT_PNG;\n if (!(IMG_Init(img_flags) & img_flags)) {\n printf(\"SDL_image could not initialize! SDL_image Error: %s\\n\", IMG_GetError());\n return false;\n }\n\n \/\/Initialize SDL_ttf\n if(TTF_Init() == -1) {\n printf(\"SDL_ttf could not initialize! SDL_ttf Error: %s\\n\", TTF_GetError());\n return false;\n }\n \n \/\/Initialize SDL_mixer\n if(Mix_OpenAudio( 44100, MIX_DEFAULT_FORMAT, 2, 2048 ) < 0) {\n printf(\"SDL_mixer could not initialize! SDL_mixer Error: %s\\n\", Mix_GetError());\n return false;\n }\n\n \/\/TODO: use seperate texture pack for fonts\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n textures->InitTexture(static_cast(i), renderer);\n }\n\n return success;\n}\n\nbool LoadMedia(TexturePack* textures) {\n \/\/Loading success flag\n bool success = true;\n\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n Texture* current = textures->GetTexture(static_cast(i));\n std::string path = textures->TexturePath(static_cast(i));\n if (!current->LoadFromFile(path)) {\n printf(\"Failed to load texture: %s\\n\", path.c_str());\n success = false;\n }\n }\n\n bop = Mix_LoadWAV(\"assets\/sfx\/blip-fs5.wav\");\n if(bop == nullptr) {\n\t\tprintf( \"Failed to load bop sound effect! SDL_mixer Error: %s\\n\", Mix_GetError() );\n\t\tsuccess = false;\n }\n \n boop = Mix_LoadWAV(\"assets\/sfx\/blip-fs4.wav\");\n if(boop == nullptr) {\n\t\tprintf( \"Failed to load boop sound effect! SDL_mixer Error: %s\\n\", Mix_GetError() );\n\t\tsuccess = false;\n }\n\n return success;\n}\n\nvoid Close(TexturePack* textures) {\n \/\/Free loaded images\n for (int i = 0; i < static_cast(TextureName::TOTAL_NUM_TEXTURES); ++i) {\n Texture* current = textures->GetTexture(static_cast(i));\n current->Free(); \n }\n\n \/\/Destroy window\n SDL_DestroyRenderer(renderer);\n SDL_DestroyWindow(window);\n window = nullptr;\n renderer = nullptr;\n\n Mix_FreeChunk(bop);\n bop = nullptr;\n\n Mix_FreeChunk(boop);\n boop = nullptr;\n\n \/\/Quit SDL subsystems\n Mix_Quit();\n TTF_Quit();\n IMG_Quit();\n SDL_Quit();\n}\n\nvoid PrintRect(SDL_Rect* rect) {\n printf(\"Rect - x: %d, y: %d, w: %d, h: %d\\n\", rect->x, rect->y, rect->w, rect->h);\n}\n\nvoid GameLoop(TexturePack* textures) {\n bool quit = false;\n\n SDL_Event e;\n\n Ball ball;\n\n Paddle player(true);\n Paddle ai(false);\n\n int player_score = 0;\n int ai_score = 0;\n\n std::vector ball_colliders;\n\n ball_colliders.push_back(player.GetCollider());\n ball_colliders.push_back(ai.GetCollider());\n\n Uint64 time_now = SDL_GetPerformanceCounter();\n Uint64 time_last = 0;\n double delta_time = 0;\n\n SDL_Color text_color = { 255, 255, 255, 255 };\n\n FontRenderer font_renderer;\n\n while (!quit) {\n time_last = time_now;\n time_now = SDL_GetPerformanceCounter();\n \n delta_time = ((time_now - time_last)*1000 \/ (double)SDL_GetPerformanceFrequency());\n\n \/\/Handle events on queue\n while(SDL_PollEvent(&e) != 0) {\n \/\/User requests quit\n if(e.type == SDL_QUIT) {\n quit = true;\n }\n\n player.HandleEvent(e);\n }\n\n ai.Autopilot(ball.GetCollider());\n\n \/\/ Paddles must move before ball!\n ai.Move(delta_time);\n player.Move(delta_time);\n CollisionType collision = ball.Move(delta_time, ball_colliders, &player_score, &ai_score);\n\n \/\/Clear screen\n SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);\n SDL_RenderClear(renderer);\n\n \/\/Render bg\n textures->GetTexture(TextureName::BG)->Render(0, 0);\n \n \/\/ Render paddles\n ai.Render(textures->GetTexture(TextureName::PADDLE));\n player.Render(textures->GetTexture(TextureName::PADDLE));\n\n \/\/Render dot\n ball.Render(textures->GetTexture(TextureName::BALL));\n\n \/\/ Render text\n int text_width = 0;\n int text_height = 0;\n std::ostringstream score_stream;\n score_stream << player_score << \" \" << ai_score;\n\n std::string score_text = score_stream.str();\n \n if (font_renderer.SizeFont(FontName::FORWARD, 42, score_text, &text_width, &text_height) != 0) {\n printf(\"Failure to size font!\\n\");\n }\n\n font_renderer.RenderFont(renderer, FontName::FORWARD, 42, \n \/*x=*\/(constants::SCREEN_WIDTH - text_width) \/ 2, \/*y=*\/10, score_text, text_color);\n\n switch (collision) {\n case CollisionType::WALL:\n case CollisionType::PADDLE:\n Mix_PlayChannel( -1, bop, 0 );\n break; \n case CollisionType::SCORE:\n Mix_PlayChannel(-1, boop, 0);\n break;\n default: break;\n }\n\n \/\/Update screen\n SDL_RenderPresent(renderer);\n }\n}\n\nint main(int argc, char *args[]) {\n TexturePack textures;\n\n if (!Init(&textures)) {\n printf(\"Failed to initialize main game!\\n\");\n return -1;\n }\n\n if (!LoadMedia(&textures)) {\n printf(\"Failed to load media!\\n\");\n return -1;\n }\n\n GameLoop(&textures);\n\n Close(&textures);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace raintk\n{\n \/\/ ============================================================= \/\/\n \/\/ ============================================================= \/\/\n\n using InputType = InputArea::Point::Type;\n\n class InputListener : public ks::Object\n {\n public:\n using base_type = ks::Object;\n\n InputListener(ks::Object::Key const &key,\n shared_ptr event_loop) :\n ks::Object(key,event_loop)\n {\n std::pair pressed_point;\n pressed_point.first = false;\n\n\/\/ list_lk_pressed_by_type.resize(\n\/\/ uint(InputArea::Point::Type::TypeCount),\n\/\/ pressed_point);\n }\n\n void Init(ks::Object::Key const &,\n shared_ptr const &)\n {}\n\n ~InputListener()\n {}\n\n void OnMouseInput(ks::gui::MouseEvent mouse_event)\n {\n\/\/ uint const mouse_type_idx = uint(InputArea::Point::Type::Mouse);\n\n InputArea::Point mouse_point {\n InputArea::Point::Type::Mouse,\n static_cast(mouse_event.button),\n static_cast(mouse_event.action),\n px(mouse_event.x),\n px(mouse_event.y),\n mouse_event.timestamp\n };\n\n list_points.push_back(mouse_point);\n\n \/\/ NOTE: We no longer do this, see InputSystem\n \/\/ comments for more details\n\/\/ \/\/ Save the most recent mouse_event if any mouse\n\/\/ \/\/ buttons are being pressed so that the InputSystem\n\/\/ \/\/ can repeat last pressed events\n\/\/ if(mouse_point.action == InputArea::Point::Action::Press)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].first = true;\n\/\/ }\n\/\/ else if(mouse_point.action == InputArea::Point::Action::Release)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].first = false;\n\/\/ }\n\n\/\/ if(list_lk_pressed_by_type[mouse_type_idx].first)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].second = mouse_point;\n\/\/ }\n }\n\n void ResampleInputs(TimePoint const &prev_upd_time,\n TimePoint const &curr_upd_time)\n {\n \/\/ For some inputs (mouse) on SDL it seems like\n \/\/ the timestamp reflects when the event is polled\n \/\/ rather than when it actually occurs\n\n \/\/ So we just assign the timestamp to always mean\n \/\/ when its polled\n\n \/\/ This means the timestamp of the event represents\n \/\/ *the end of the interval the event occured in*\n\n \/\/ To convert the timestamps to reflect when the\n \/\/ event occured, we resample by linearly interpolating\n \/\/ the events over the interval (this is a guess)\n\n \/\/ @prev_upd_time: start of the interval\n \/\/ @curr_upd_time: end of the interval\n\n \/\/ We assume that list_points is cleared between\n \/\/ each call to ResampleInputs\n\n if(list_points.empty())\n {\n return;\n }\n\n uint const point_count = list_points.size();\n\n Microseconds avg_interval =\n ks::CalcDuration(\n prev_upd_time,\n curr_upd_time);\n\n avg_interval = Microseconds(avg_interval.count()\/(point_count+1));\n\n for(uint i=0; i < point_count; i++)\n {\n list_points[i].timestamp =\n prev_upd_time +\n Microseconds(avg_interval.count()*(i+1));\n }\n }\n\n\n std::vector list_points;\n\n\/\/ std::vector<\n\/\/ std::pair\n\/\/ > list_lk_pressed_by_type;\n };\n\n \/\/ ============================================================= \/\/\n \/\/ ============================================================= \/\/\n\n InputSystem::InputSystem(Scene* scene,\n ks::gui::Application* app) :\n m_scene(scene)\n {\n \/\/ Get the InputData mask\n m_inputable_mask =\n m_scene->template GetComponentMask();\n\n \/\/ Create the InputData component list\n m_scene->template RegisterComponentList(\n make_unique(*m_scene));\n\n m_cmlist_input_data =\n static_cast(\n m_scene->template GetComponentList());\n\n \/\/ Create the InputListener\n m_input_listener =\n ks::MakeObject(\n scene->GetEventLoop());\n\n app->signal_mouse_input->Connect(\n m_input_listener,\n &InputListener::OnMouseInput,\n ks::ConnectionType::Direct);\n }\n\n InputSystem::~InputSystem()\n {\n\n }\n\n std::string InputSystem::GetDesc() const\n {\n return \"raintk InputSystem\";\n }\n\n void InputSystem::Update(TimePoint const &prev_upd_time,\n TimePoint const &curr_upd_time)\n {\n auto& list_entities = m_scene->GetEntityList();\n auto& list_input_data = m_cmlist_input_data->GetSparseList();\n\n auto const & list_xf_data =\n static_cast(\n m_scene->template GetComponentList())->\n GetSparseList();\n\n m_list_input_areas_by_depth.clear();\n\n for(uint ent_id=0; ent_id < list_entities.size(); ent_id++)\n {\n if((list_entities[ent_id].mask & m_inputable_mask)==m_inputable_mask)\n {\n auto& input_data = list_input_data[ent_id];\n auto const &xf_data = list_xf_data[ent_id];\n\n \/\/ NOTE: We need to check if the transform data is valid.\n \/\/ TransformData is invalid until the TransformSystem has\n \/\/ updated it for the first time.\n if(input_data.enabled && xf_data.valid)\n {\n m_list_input_areas_by_depth.emplace_back(\n xf_data.world_xf[3].z,\n input_data.input_area);\n }\n }\n }\n\n \/\/ Sort the InputAreas by height \/\/ TODO rename height --> depth!\n std::sort(\n m_list_input_areas_by_depth.begin(),\n m_list_input_areas_by_depth.end(),\n [](std::pair const &a,\n std::pair const &b) {\n return(a.first > b.first);\n });\n\n \/\/ Resample input times\n m_input_listener->ResampleInputs(\n prev_upd_time,curr_upd_time);\n\n auto& list_points = m_input_listener->list_points;\n\n \/\/ NOTE (start)\n \/\/ We initially repeated inputs that were previously\n \/\/ pressed but hadn't been released to be able to\n \/\/ detect input speed continuously. This is currently\n \/\/ disabled and current widgets will probably break\n \/\/ if its reenabled (ie ScrollArea)\n\n\/\/ \/\/ If list_points is empty, fill it with any inputs\n\/\/ \/\/ that were previously pressed but haven't yet been\n\/\/ \/\/ released\n\n\/\/ if(list_points.empty())\n\/\/ {\n\/\/ for(auto& pressed_point : m_input_listener->list_lk_pressed_by_type)\n\/\/ {\n\/\/ if(pressed_point.first)\n\/\/ {\n\/\/ list_points.push_back(pressed_point.second);\n\/\/ list_points.back().timestamp = curr_upd_time;\n\/\/ }\n\/\/ }\n\/\/ }\n\n \/\/ NOTE (end)\n\n while(list_points.empty()==false)\n {\n for(uint i=0; i < m_list_input_areas_by_depth.size();)\n {\n auto input_area = m_list_input_areas_by_depth[i].second;\n auto const &world_pt = list_points[0];\n\n glm::vec2 world_xy(world_pt.x,world_pt.y);\n glm::vec2 local_xy = Widget::CalcLocalCoords(input_area,world_xy);\n bool inside = Widget::CalcPointInside(input_area,world_xy,local_xy);\n\n auto local_pt = world_pt;\n local_pt.x = local_xy.x;\n local_pt.y = local_xy.y;\n\n auto const response = input_area->handleInput(local_pt,inside);\n\n if(response == InputArea::Response::Accept)\n {\n list_points.erase(list_points.begin());\n\n if(list_points.empty())\n {\n break;\n }\n else\n {\n \/\/ Start back at the beginning\n i=0;\n }\n }\n else\n {\n \/\/ Try the current point with\n \/\/ the next InputArea\n i++;\n }\n }\n\n if(list_points.empty())\n {\n break;\n }\n\n \/\/ When we get here the first entry in list_points\n \/\/ has been rejected by all InputAreas. Discard it\n \/\/ and try from the beginning with the next point.\n list_points.erase(list_points.begin());\n }\n }\n\n InputDataComponentList*\n InputSystem::GetInputDataComponentList() const\n {\n return m_cmlist_input_data;\n }\n\n std::vector> const &\n InputSystem::GetInputAreasByDepth() const\n {\n return m_list_input_areas_by_depth;\n }\n}\nInputSystem: Added touch event listener\/*\n Copyright (C) 2015 Preet Desai (preet.desai@gmail.com)\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace raintk\n{\n \/\/ ============================================================= \/\/\n \/\/ ============================================================= \/\/\n\n using InputType = InputArea::Point::Type;\n\n class InputListener : public ks::Object\n {\n public:\n using base_type = ks::Object;\n\n InputListener(ks::Object::Key const &key,\n shared_ptr event_loop) :\n ks::Object(key,event_loop)\n {\n std::pair pressed_point;\n pressed_point.first = false;\n\n\/\/ list_lk_pressed_by_type.resize(\n\/\/ uint(InputArea::Point::Type::TypeCount),\n\/\/ pressed_point);\n }\n\n void Init(ks::Object::Key const &,\n shared_ptr const &)\n {}\n\n ~InputListener()\n {}\n\n void OnMouseInput(ks::gui::MouseEvent mouse_event)\n {\n\/\/ uint const mouse_type_idx = uint(InputArea::Point::Type::Mouse);\n\n InputArea::Point mouse_point {\n InputArea::Point::Type::Mouse,\n static_cast(mouse_event.button),\n static_cast(mouse_event.action),\n px(mouse_event.x),\n px(mouse_event.y),\n mouse_event.timestamp\n };\n\n list_points.push_back(mouse_point);\n\n \/\/ NOTE: We no longer do this, see InputSystem\n \/\/ comments for more details\n\/\/ \/\/ Save the most recent mouse_event if any mouse\n\/\/ \/\/ buttons are being pressed so that the InputSystem\n\/\/ \/\/ can repeat last pressed events\n\/\/ if(mouse_point.action == InputArea::Point::Action::Press)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].first = true;\n\/\/ }\n\/\/ else if(mouse_point.action == InputArea::Point::Action::Release)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].first = false;\n\/\/ }\n\n\/\/ if(list_lk_pressed_by_type[mouse_type_idx].first)\n\/\/ {\n\/\/ list_lk_pressed_by_type[mouse_type_idx].second = mouse_point;\n\/\/ }\n }\n\n void OnTouchInput(ks::gui::TouchEvent touch_event)\n {\n \/\/ TODO support additional touch points\n if(touch_event.index > 2)\n {\n return;\n }\n\n InputArea::Point touch_point{\n \/\/ Type=0 is Mouse, Type=1 is Touch0, etc\n static_cast(touch_event.index+1),\n InputArea::Point::Button::None,\n static_cast(touch_event.action),\n px(touch_event.x),\n px(touch_event.y),\n touch_event.timestamp\n };\n\n list_points.push_back(touch_point);\n }\n\n void ResampleInputs(TimePoint const &prev_upd_time,\n TimePoint const &curr_upd_time)\n {\n \/\/ For some inputs (mouse) on SDL it seems like\n \/\/ the timestamp reflects when the event is polled\n \/\/ rather than when it actually occurs\n\n \/\/ So we just assign the timestamp to always mean\n \/\/ when its polled\n\n \/\/ This means the timestamp of the event represents\n \/\/ *the end of the interval the event occured in*\n\n \/\/ To convert the timestamps to reflect when the\n \/\/ event occured, we resample by linearly interpolating\n \/\/ the events over the interval (this is a guess)\n\n \/\/ @prev_upd_time: start of the interval\n \/\/ @curr_upd_time: end of the interval\n\n \/\/ We assume that list_points is cleared between\n \/\/ each call to ResampleInputs\n\n if(list_points.empty())\n {\n return;\n }\n\n uint const point_count = list_points.size();\n\n Microseconds avg_interval =\n ks::CalcDuration(\n prev_upd_time,\n curr_upd_time);\n\n avg_interval = Microseconds(avg_interval.count()\/(point_count+1));\n\n for(uint i=0; i < point_count; i++)\n {\n list_points[i].timestamp =\n prev_upd_time +\n Microseconds(avg_interval.count()*(i+1));\n }\n }\n\n\n std::vector list_points;\n\n\/\/ std::vector<\n\/\/ std::pair\n\/\/ > list_lk_pressed_by_type;\n };\n\n \/\/ ============================================================= \/\/\n \/\/ ============================================================= \/\/\n\n InputSystem::InputSystem(Scene* scene,\n ks::gui::Application* app) :\n m_scene(scene)\n {\n \/\/ Get the InputData mask\n m_inputable_mask =\n m_scene->template GetComponentMask();\n\n \/\/ Create the InputData component list\n m_scene->template RegisterComponentList(\n make_unique(*m_scene));\n\n m_cmlist_input_data =\n static_cast(\n m_scene->template GetComponentList());\n\n \/\/ Create the InputListener\n m_input_listener =\n ks::MakeObject(\n scene->GetEventLoop());\n\n app->signal_mouse_input->Connect(\n m_input_listener,\n &InputListener::OnMouseInput,\n ks::ConnectionType::Direct);\n\n app->signal_touch_input->Connect(\n m_input_listener,\n &InputListener::OnTouchInput,\n ks::ConnectionType::Direct);\n }\n\n InputSystem::~InputSystem()\n {\n\n }\n\n std::string InputSystem::GetDesc() const\n {\n return \"raintk InputSystem\";\n }\n\n void InputSystem::Update(TimePoint const &prev_upd_time,\n TimePoint const &curr_upd_time)\n {\n auto& list_entities = m_scene->GetEntityList();\n auto& list_input_data = m_cmlist_input_data->GetSparseList();\n\n auto const & list_xf_data =\n static_cast(\n m_scene->template GetComponentList())->\n GetSparseList();\n\n m_list_input_areas_by_depth.clear();\n\n for(uint ent_id=0; ent_id < list_entities.size(); ent_id++)\n {\n if((list_entities[ent_id].mask & m_inputable_mask)==m_inputable_mask)\n {\n auto& input_data = list_input_data[ent_id];\n auto const &xf_data = list_xf_data[ent_id];\n\n \/\/ NOTE: We need to check if the transform data is valid.\n \/\/ TransformData is invalid until the TransformSystem has\n \/\/ updated it for the first time.\n if(input_data.enabled && xf_data.valid)\n {\n m_list_input_areas_by_depth.emplace_back(\n xf_data.world_xf[3].z,\n input_data.input_area);\n }\n }\n }\n\n \/\/ Sort the InputAreas by height \/\/ TODO rename height --> depth!\n std::sort(\n m_list_input_areas_by_depth.begin(),\n m_list_input_areas_by_depth.end(),\n [](std::pair const &a,\n std::pair const &b) {\n return(a.first > b.first);\n });\n\n \/\/ Resample input times\n m_input_listener->ResampleInputs(\n prev_upd_time,curr_upd_time);\n\n auto& list_points = m_input_listener->list_points;\n\n \/\/ NOTE (start)\n \/\/ We initially repeated inputs that were previously\n \/\/ pressed but hadn't been released to be able to\n \/\/ detect input speed continuously. This is currently\n \/\/ disabled and current widgets will probably break\n \/\/ if its reenabled (ie ScrollArea)\n\n\/\/ \/\/ If list_points is empty, fill it with any inputs\n\/\/ \/\/ that were previously pressed but haven't yet been\n\/\/ \/\/ released\n\n\/\/ if(list_points.empty())\n\/\/ {\n\/\/ for(auto& pressed_point : m_input_listener->list_lk_pressed_by_type)\n\/\/ {\n\/\/ if(pressed_point.first)\n\/\/ {\n\/\/ list_points.push_back(pressed_point.second);\n\/\/ list_points.back().timestamp = curr_upd_time;\n\/\/ }\n\/\/ }\n\/\/ }\n\n \/\/ NOTE (end)\n\n while(list_points.empty()==false)\n {\n for(uint i=0; i < m_list_input_areas_by_depth.size();)\n {\n auto input_area = m_list_input_areas_by_depth[i].second;\n auto const &world_pt = list_points[0];\n\n glm::vec2 world_xy(world_pt.x,world_pt.y);\n glm::vec2 local_xy = Widget::CalcLocalCoords(input_area,world_xy);\n bool inside = Widget::CalcPointInside(input_area,world_xy,local_xy);\n\n auto local_pt = world_pt;\n local_pt.x = local_xy.x;\n local_pt.y = local_xy.y;\n\n auto const response = input_area->handleInput(local_pt,inside);\n\n if(response == InputArea::Response::Accept)\n {\n list_points.erase(list_points.begin());\n\n if(list_points.empty())\n {\n break;\n }\n else\n {\n \/\/ Start back at the beginning\n i=0;\n }\n }\n else\n {\n \/\/ Try the current point with\n \/\/ the next InputArea\n i++;\n }\n }\n\n if(list_points.empty())\n {\n break;\n }\n\n \/\/ When we get here the first entry in list_points\n \/\/ has been rejected by all InputAreas. Discard it\n \/\/ and try from the beginning with the next point.\n list_points.erase(list_points.begin());\n }\n }\n\n InputDataComponentList*\n InputSystem::GetInputDataComponentList() const\n {\n return m_cmlist_input_data;\n }\n\n std::vector> const &\n InputSystem::GetInputAreasByDepth() const\n {\n return m_list_input_areas_by_depth;\n }\n}\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright (c) 2008-2015 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:addmember\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"..\/Precompiled.h\"\r\n\r\n#include \"..\/Core\/Context.h\"\r\n#include \"..\/IO\/Log.h\"\r\n#include \"..\/Resource\/JSONValue.h\"\r\n\r\n#include \"..\/DebugNew.h\"\r\n\r\nnamespace Urho3D\r\n{\r\n\r\nconst JSONValue JSONValue::EMPTY;\r\nconst JSONArray JSONValue::emptyArray;\r\nconst JSONObject JSONValue::emptyObject;\r\n\r\nJSONValue& JSONValue::operator =(bool rhs)\r\n{\r\n SetType(JSON_BOOL);\r\n boolValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(int rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_INT);\r\n numberValue_ = rhs; \r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(unsigned rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_UINT);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(float rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(double rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const String& rhs)\r\n{\r\n SetType(JSON_STRING);\r\n *stringValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const char* rhs)\r\n{\r\n SetType(JSON_STRING);\r\n *stringValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONArray& rhs)\r\n{\r\n SetType(JSON_ARRAY);\r\n *arrayValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONObject& rhs)\r\n{\r\n SetType(JSON_OBJECT);\r\n *objectValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONValue& rhs)\r\n{\r\n if (this == &rhs)\r\n return *this;\r\n\r\n SetType(rhs.GetValueType(), rhs.GetNumberType());\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_BOOL:\r\n boolValue_ = rhs.boolValue_;\r\n break;\r\n\r\n case JSON_NUMBER:\r\n numberValue_ = rhs.numberValue_;\r\n break;\r\n\r\n case JSON_STRING:\r\n *stringValue_ = *rhs.stringValue_;\r\n break;\r\n\r\n case JSON_ARRAY:\r\n *arrayValue_ = *rhs.arrayValue_;\r\n break;\r\n\r\n case JSON_OBJECT:\r\n *objectValue_ = *rhs.objectValue_;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n return *this;\r\n}\r\n\r\nJSONValueType JSONValue::GetValueType() const\r\n{\r\n return (JSONValueType)(type_ >> 16);\r\n}\r\n\r\nJSONNumberType JSONValue::GetNumberType() const\r\n{\r\n return (JSONNumberType)(type_ & 0xffff);\r\n}\r\n\r\nJSONValue& JSONValue::operator [](unsigned index)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n return (*arrayValue_)[index];\r\n}\r\n\r\nconst JSONValue& JSONValue::operator [](unsigned index) const\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return EMPTY;\r\n\r\n return (*arrayValue_)[index];\r\n}\r\n\r\nvoid JSONValue::Push(const JSONValue& value)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n arrayValue_->Push(value);\r\n}\r\n\r\nvoid JSONValue::Pop()\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Pop();\r\n}\r\n\r\nvoid JSONValue::Insert(unsigned pos, const JSONValue& value)\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Insert(pos, value);\r\n}\r\n\r\nvoid JSONValue::Erase(unsigned pos, unsigned length)\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Erase(pos, length);\r\n}\r\n\r\nvoid JSONValue::Resize(unsigned newSize)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n arrayValue_->Resize(newSize);\r\n}\r\n\r\nunsigned JSONValue::Size() const\r\n{\r\n if (GetValueType() == JSON_ARRAY)\r\n return arrayValue_->Size();\r\n\r\n return 0;\r\n}\r\n\r\nJSONValue& JSONValue::operator [](const String& key)\r\n{\r\n \/\/ Convert to object type\r\n SetType(JSON_OBJECT);\r\n\r\n return (*objectValue_)[key];\r\n}\r\n\r\nconst JSONValue& JSONValue::operator [](const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return EMPTY;\r\n\r\n return (*objectValue_)[key];\r\n}\r\n\r\nvoid JSONValue::Set(const String& key, const JSONValue& value)\r\n{\r\n \/\/ Convert to object type\r\n SetType(JSON_OBJECT);\r\n\r\n (*objectValue_)[key] = value;\r\n}\r\n\r\nconst JSONValue& JSONValue::Get(const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return EMPTY;\r\n\r\n JSONObject::ConstIterator i = objectValue_->Find(key);\r\n if (i == objectValue_->End())\r\n return EMPTY;\r\n\r\n return i->second_;\r\n}\r\n\r\nbool JSONValue::Erase(const String& key)\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return false;\r\n\r\n return objectValue_->Erase(key);\r\n}\r\n\r\nbool JSONValue::Contains(const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return false;\r\n\r\n return objectValue_->Contains(key);\r\n}\r\n\r\nJSONObjectIterator JSONValue::Begin()\r\n{\r\n \/\/ Convert to object type.\r\n SetType(JSON_OBJECT);\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nConstJSONObjectIterator JSONValue::Begin() const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return emptyObject.Begin();\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nJSONObjectIterator JSONValue::End()\r\n{\r\n \/\/ Convert to object type.\r\n SetType(JSON_OBJECT);\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nConstJSONObjectIterator JSONValue::End() const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return emptyObject.End();\r\n\r\n return objectValue_->End();\r\n}\r\n\r\nvoid JSONValue::Clear()\r\n{\r\n if (GetValueType() == JSON_ARRAY)\r\n arrayValue_->Clear();\r\n else if (GetValueType() == JSON_OBJECT)\r\n objectValue_->Clear();\r\n}\r\n\r\nvoid JSONValue::SetType(JSONValueType valueType, JSONNumberType numberType)\r\n{\r\n int type = (valueType << 16) | numberType;\r\n if (type == type_)\r\n return;\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_STRING:\r\n delete stringValue_;\r\n break;\r\n\r\n case JSON_ARRAY:\r\n delete arrayValue_;\r\n break;\r\n\r\n case JSON_OBJECT:\r\n delete objectValue_;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n type_ = type;\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_STRING:\r\n stringValue_ = new String();\r\n break;\r\n\r\n case JSON_ARRAY:\r\n arrayValue_ = new JSONArray();\r\n break;\r\n\r\n case JSON_OBJECT:\r\n objectValue_ = new JSONObject();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n}\r\n\r\nvoid JSONValue::SetVariant(const Variant& variant, Context* context)\r\n{\r\n if (!IsNull())\r\n {\r\n URHO3D_LOGWARNING(\"JsonValue is not null\");\r\n }\r\n\r\n (*this)[\"type\"] = variant.GetTypeName();\r\n (*this)[\"value\"].SetVariantValue(variant, context);\r\n}\r\n\r\nVariant JSONValue::GetVariant() const\r\n{\r\n VariantType type = Variant::GetTypeFromName((*this)[\"type\"].GetString());\r\n return (*this)[\"value\"].GetVariantValue(type);\r\n}\r\n\r\nvoid JSONValue::SetVariantValue(const Variant& variant, Context* context)\r\n{\r\n if (!IsNull())\r\n {\r\n URHO3D_LOGWARNING(\"JsonValue is not null\");\r\n }\r\n\r\n switch (variant.GetType())\r\n {\r\n case VAR_BOOL:\r\n *this = variant.GetBool();\r\n return;\r\n \r\n case VAR_INT:\r\n *this = variant.GetInt();\r\n return;\r\n\r\n case VAR_FLOAT:\r\n *this = variant.GetFloat();\r\n return;\r\n\r\n case VAR_DOUBLE:\r\n *this = variant.GetDouble();\r\n return;\r\n\r\n case VAR_STRING:\r\n *this = variant.GetString();\r\n return;\r\n\r\n case VAR_VARIANTVECTOR:\r\n SetVariantVector(variant.GetVariantVector(), context);\r\n return;\r\n\r\n case VAR_VARIANTMAP:\r\n SetVariantMap(variant.GetVariantMap(), context);\r\n return;\r\n\r\n case VAR_RESOURCEREF:\r\n {\r\n if (!context)\r\n {\r\n URHO3D_LOGERROR(\"Context must not be null for ResourceRef\");\r\n return;\r\n }\r\n\r\n const ResourceRef& ref = variant.GetResourceRef();\r\n *this = String(context->GetTypeName(ref.type_)) + \";\" + ref.name_;\r\n }\r\n return;\r\n\r\n case VAR_RESOURCEREFLIST:\r\n {\r\n if (!context)\r\n {\r\n URHO3D_LOGERROR(\"Context must not be null for ResourceRefList\");\r\n return;\r\n }\r\n\r\n const ResourceRefList& refList = variant.GetResourceRefList();\r\n String str(context->GetTypeName(refList.type_));\r\n for (unsigned i = 0; i < refList.names_.Size(); ++i)\r\n {\r\n str += \";\";\r\n str += refList.names_[i];\r\n }\r\n *this = str;\r\n }\r\n return;\r\n\r\n case VAR_STRINGVECTOR:\r\n {\r\n const StringVector& vector = variant.GetStringVector();\r\n Resize(vector.Size());\r\n for (unsigned i = 0; i < vector.Size(); ++i)\r\n (*this)[i] = vector[i];\r\n }\r\n return;\r\n\r\n default:\r\n *this = variant.ToString();\r\n }\r\n}\r\n\r\nVariant JSONValue::GetVariantValue(VariantType type) const\r\n{\r\n Variant variant;\r\n switch (type)\r\n {\r\n case VAR_BOOL:\r\n variant = GetBool();\r\n break;\r\n\r\n case VAR_INT:\r\n variant = GetInt();\r\n break;\r\n\r\n case VAR_FLOAT:\r\n variant = GetFloat();\r\n break;\r\n\r\n case VAR_DOUBLE:\r\n variant = GetDouble();\r\n break;\r\n\r\n case VAR_STRING:\r\n variant = GetString();\r\n break;\r\n\r\n case VAR_VARIANTVECTOR:\r\n variant = GetVariantVector();\r\n break;\r\n\r\n case VAR_VARIANTMAP:\r\n variant = GetVariantMap();\r\n break;\r\n\r\n case VAR_RESOURCEREF:\r\n {\r\n ResourceRef ref;\r\n Vector values = GetString().Split(';');\r\n if (values.Size() == 2)\r\n {\r\n ref.type_ = values[0];\r\n ref.name_ = values[1];\r\n }\r\n variant = ref;\r\n }\r\n break;\r\n\r\n case VAR_RESOURCEREFLIST:\r\n {\r\n ResourceRefList refList;\r\n Vector values = GetString().Split(';', true);\r\n if (values.Size() >= 1)\r\n {\r\n refList.type_ = values[0];\r\n refList.names_.Resize(values.Size() - 1);\r\n for (unsigned i = 1; i < values.Size(); ++i)\r\n refList.names_[i - 1] = values[i];\r\n }\r\n variant = refList;\r\n }\r\n break;\r\n\r\n case VAR_STRINGVECTOR:\r\n {\r\n StringVector vector;\r\n for (unsigned i = 0; i < Size(); ++i)\r\n vector.Push((*this)[i].GetString());\r\n variant = vector;\r\n }\r\n break;\r\n\r\n default:\r\n variant.FromString(type, GetString());\r\n }\r\n\r\n return variant;\r\n}\r\n\r\nvoid JSONValue::SetVariantMap(const VariantMap& variantMap, Context* context)\r\n{\r\n SetType(JSON_OBJECT);\r\n for (VariantMap::ConstIterator i = variantMap.Begin(); i != variantMap.End(); ++i)\r\n (*this)[i->first_.ToString()].SetVariant(i->second_);\r\n}\r\n\r\nVariantMap JSONValue::GetVariantMap() const\r\n{\r\n VariantMap variantMap;\r\n if (!IsObject())\r\n {\r\n URHO3D_LOGERROR(\"JSONValue is not a object\");\r\n return variantMap;\r\n }\r\n\r\n for (ConstJSONObjectIterator i = Begin(); i != End(); ++i)\r\n {\r\n StringHash key(ToUInt(i->first_));\r\n Variant variant = i->second_.GetVariant();\r\n variantMap[key] = variant;\r\n }\r\n\r\n return variantMap;\r\n}\r\n\r\nvoid JSONValue::SetVariantVector(const VariantVector& variantVector, Context* context)\r\n{\r\n SetType(JSON_ARRAY);\r\n for (unsigned i = 0; i < variantVector.Size(); ++i)\r\n (*this)[i].SetVariant(variantVector[i]);\r\n}\r\n\r\nVariantVector JSONValue::GetVariantVector() const\r\n{\r\n VariantVector variantVector;\r\n if (!IsArray())\r\n {\r\n URHO3D_LOGERROR(\"JSONValue is not a array\");\r\n return variantVector;\r\n }\r\n\r\n for (unsigned i = 0; i < Size(); ++i)\r\n {\r\n Variant variant = (*this)[i].GetVariant();\r\n variantVector.Push(variant);\r\n }\r\n\r\n return variantVector;\r\n}\r\n\r\n}Squashed commit of the following:\/\/\r\n\/\/ Copyright (c) 2008-2015 the Urho3D project.\r\n\/\/\r\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\r\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\r\n\/\/ in the Software without restriction, including without limitation the rights\r\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n\/\/ copies of the Software, and to permit persons to whom the Software is\r\n\/\/ furnished to do so, subject to the following conditions:addmember\r\n\/\/\r\n\/\/ The above copyright notice and this permission notice shall be included in\r\n\/\/ all copies or substantial portions of the Software.\r\n\/\/\r\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n\/\/ THE SOFTWARE.\r\n\/\/\r\n\r\n#include \"..\/Precompiled.h\"\r\n\r\n#include \"..\/Core\/Context.h\"\r\n#include \"..\/IO\/Log.h\"\r\n#include \"..\/Resource\/JSONValue.h\"\r\n\r\n#include \"..\/DebugNew.h\"\r\n\r\nnamespace Urho3D\r\n{\r\n\r\nconst JSONValue JSONValue::EMPTY;\r\nconst JSONArray JSONValue::emptyArray;\r\nconst JSONObject JSONValue::emptyObject;\r\n\r\nJSONValue& JSONValue::operator =(bool rhs)\r\n{\r\n SetType(JSON_BOOL);\r\n boolValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(int rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_INT);\r\n numberValue_ = rhs; \r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(unsigned rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_UINT);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(float rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(double rhs)\r\n{\r\n SetType(JSON_NUMBER, JSONNT_FLOAT_DOUBLE);\r\n numberValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const String& rhs)\r\n{\r\n SetType(JSON_STRING);\r\n *stringValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const char* rhs)\r\n{\r\n SetType(JSON_STRING);\r\n *stringValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONArray& rhs)\r\n{\r\n SetType(JSON_ARRAY);\r\n *arrayValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONObject& rhs)\r\n{\r\n SetType(JSON_OBJECT);\r\n *objectValue_ = rhs;\r\n\r\n return *this;\r\n}\r\n\r\nJSONValue& JSONValue::operator =(const JSONValue& rhs)\r\n{\r\n if (this == &rhs)\r\n return *this;\r\n\r\n SetType(rhs.GetValueType(), rhs.GetNumberType());\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_BOOL:\r\n boolValue_ = rhs.boolValue_;\r\n break;\r\n\r\n case JSON_NUMBER:\r\n numberValue_ = rhs.numberValue_;\r\n break;\r\n\r\n case JSON_STRING:\r\n *stringValue_ = *rhs.stringValue_;\r\n break;\r\n\r\n case JSON_ARRAY:\r\n *arrayValue_ = *rhs.arrayValue_;\r\n break;\r\n\r\n case JSON_OBJECT:\r\n *objectValue_ = *rhs.objectValue_;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n return *this;\r\n}\r\n\r\nJSONValueType JSONValue::GetValueType() const\r\n{\r\n return (JSONValueType)(type_ >> 16);\r\n}\r\n\r\nJSONNumberType JSONValue::GetNumberType() const\r\n{\r\n return (JSONNumberType)(type_ & 0xffff);\r\n}\r\n\r\nJSONValue& JSONValue::operator [](unsigned index)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n return (*arrayValue_)[index];\r\n}\r\n\r\nconst JSONValue& JSONValue::operator [](unsigned index) const\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return EMPTY;\r\n\r\n return (*arrayValue_)[index];\r\n}\r\n\r\nvoid JSONValue::Push(const JSONValue& value)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n arrayValue_->Push(value);\r\n}\r\n\r\nvoid JSONValue::Pop()\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Pop();\r\n}\r\n\r\nvoid JSONValue::Insert(unsigned pos, const JSONValue& value)\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Insert(pos, value);\r\n}\r\n\r\nvoid JSONValue::Erase(unsigned pos, unsigned length)\r\n{\r\n if (GetValueType() != JSON_ARRAY)\r\n return;\r\n\r\n arrayValue_->Erase(pos, length);\r\n}\r\n\r\nvoid JSONValue::Resize(unsigned newSize)\r\n{\r\n \/\/ Convert to array type\r\n SetType(JSON_ARRAY);\r\n\r\n arrayValue_->Resize(newSize);\r\n}\r\n\r\nunsigned JSONValue::Size() const\r\n{\r\n if (GetValueType() == JSON_ARRAY)\r\n return arrayValue_->Size();\r\n\r\n return 0;\r\n}\r\n\r\nJSONValue& JSONValue::operator [](const String& key)\r\n{\r\n \/\/ Convert to object type\r\n SetType(JSON_OBJECT);\r\n\r\n return (*objectValue_)[key];\r\n}\r\n\r\nconst JSONValue& JSONValue::operator [](const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return EMPTY;\r\n\r\n return (*objectValue_)[key];\r\n}\r\n\r\nvoid JSONValue::Set(const String& key, const JSONValue& value)\r\n{\r\n \/\/ Convert to object type\r\n SetType(JSON_OBJECT);\r\n\r\n (*objectValue_)[key] = value;\r\n}\r\n\r\nconst JSONValue& JSONValue::Get(const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return EMPTY;\r\n\r\n JSONObject::ConstIterator i = objectValue_->Find(key);\r\n if (i == objectValue_->End())\r\n return EMPTY;\r\n\r\n return i->second_;\r\n}\r\n\r\nbool JSONValue::Erase(const String& key)\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return false;\r\n\r\n return objectValue_->Erase(key);\r\n}\r\n\r\nbool JSONValue::Contains(const String& key) const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return false;\r\n\r\n return objectValue_->Contains(key);\r\n}\r\n\r\nJSONObjectIterator JSONValue::Begin()\r\n{\r\n \/\/ Convert to object type.\r\n SetType(JSON_OBJECT);\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nConstJSONObjectIterator JSONValue::Begin() const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return emptyObject.Begin();\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nJSONObjectIterator JSONValue::End()\r\n{\r\n \/\/ Convert to object type.\r\n SetType(JSON_OBJECT);\r\n\r\n return objectValue_->Begin();\r\n}\r\n\r\nConstJSONObjectIterator JSONValue::End() const\r\n{\r\n if (GetValueType() != JSON_OBJECT)\r\n return emptyObject.End();\r\n\r\n return objectValue_->End();\r\n}\r\n\r\nvoid JSONValue::Clear()\r\n{\r\n if (GetValueType() == JSON_ARRAY)\r\n arrayValue_->Clear();\r\n else if (GetValueType() == JSON_OBJECT)\r\n objectValue_->Clear();\r\n}\r\n\r\nvoid JSONValue::SetType(JSONValueType valueType, JSONNumberType numberType)\r\n{\r\n int type = (valueType << 16) | numberType;\r\n if (type == type_)\r\n return;\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_STRING:\r\n delete stringValue_;\r\n break;\r\n\r\n case JSON_ARRAY:\r\n delete arrayValue_;\r\n break;\r\n\r\n case JSON_OBJECT:\r\n delete objectValue_;\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n\r\n type_ = type;\r\n\r\n switch (GetValueType())\r\n {\r\n case JSON_STRING:\r\n stringValue_ = new String();\r\n break;\r\n\r\n case JSON_ARRAY:\r\n arrayValue_ = new JSONArray();\r\n break;\r\n\r\n case JSON_OBJECT:\r\n objectValue_ = new JSONObject();\r\n break;\r\n\r\n default:\r\n break;\r\n }\r\n}\r\n\r\nvoid JSONValue::SetVariant(const Variant& variant, Context* context)\r\n{\r\n if (!IsNull())\r\n {\r\n URHO3D_LOGWARNING(\"JsonValue is not null\");\r\n }\r\n\r\n (*this)[\"type\"] = variant.GetTypeName();\r\n (*this)[\"value\"].SetVariantValue(variant, context);\r\n}\r\n\r\nVariant JSONValue::GetVariant() const\r\n{\r\n VariantType type = Variant::GetTypeFromName((*this)[\"type\"].GetString());\r\n return (*this)[\"value\"].GetVariantValue(type);\r\n}\r\n\r\nvoid JSONValue::SetVariantValue(const Variant& variant, Context* context)\r\n{\r\n if (!IsNull())\r\n {\r\n URHO3D_LOGWARNING(\"JsonValue is not null\");\r\n }\r\n\r\n switch (variant.GetType())\r\n {\r\n case VAR_BOOL:\r\n *this = variant.GetBool();\r\n return;\r\n \r\n case VAR_INT:\r\n *this = variant.GetInt();\r\n return;\r\n\r\n case VAR_FLOAT:\r\n *this = variant.GetFloat();\r\n return;\r\n\r\n case VAR_DOUBLE:\r\n *this = variant.GetDouble();\r\n return;\r\n\r\n case VAR_STRING:\r\n *this = variant.GetString();\r\n return;\r\n\r\n case VAR_VARIANTVECTOR:\r\n SetVariantVector(variant.GetVariantVector(), context);\r\n return;\r\n\r\n case VAR_VARIANTMAP:\r\n SetVariantMap(variant.GetVariantMap(), context);\r\n return;\r\n\r\n case VAR_RESOURCEREF:\r\n {\r\n if (!context)\r\n {\r\n URHO3D_LOGERROR(\"Context must not be null for ResourceRef\");\r\n return;\r\n }\r\n\r\n const ResourceRef& ref = variant.GetResourceRef();\r\n *this = String(context->GetTypeName(ref.type_)) + \";\" + ref.name_;\r\n }\r\n return;\r\n\r\n case VAR_RESOURCEREFLIST:\r\n {\r\n if (!context)\r\n {\r\n URHO3D_LOGERROR(\"Context must not be null for ResourceRefList\");\r\n return;\r\n }\r\n\r\n const ResourceRefList& refList = variant.GetResourceRefList();\r\n String str(context->GetTypeName(refList.type_));\r\n for (unsigned i = 0; i < refList.names_.Size(); ++i)\r\n {\r\n str += \";\";\r\n str += refList.names_[i];\r\n }\r\n *this = str;\r\n }\r\n return;\r\n\r\n case VAR_STRINGVECTOR:\r\n {\r\n const StringVector& vector = variant.GetStringVector();\r\n Resize(vector.Size());\r\n for (unsigned i = 0; i < vector.Size(); ++i)\r\n (*this)[i] = vector[i];\r\n }\r\n return;\r\n\r\n default:\r\n *this = variant.ToString();\r\n }\r\n}\r\n\r\nVariant JSONValue::GetVariantValue(VariantType type) const\r\n{\r\n Variant variant;\r\n switch (type)\r\n {\r\n case VAR_BOOL:\r\n variant = GetBool();\r\n break;\r\n\r\n case VAR_INT:\r\n variant = GetInt();\r\n break;\r\n\r\n case VAR_FLOAT:\r\n variant = GetFloat();\r\n break;\r\n\r\n case VAR_DOUBLE:\r\n variant = GetDouble();\r\n break;\r\n\r\n case VAR_STRING:\r\n variant = GetString();\r\n break;\r\n\r\n case VAR_VARIANTVECTOR:\r\n variant = GetVariantVector();\r\n break;\r\n\r\n case VAR_VARIANTMAP:\r\n variant = GetVariantMap();\r\n break;\r\n\r\n case VAR_RESOURCEREF:\r\n {\r\n ResourceRef ref;\r\n Vector values = GetString().Split(';');\r\n if (values.Size() == 2)\r\n {\r\n ref.type_ = values[0];\r\n ref.name_ = values[1];\r\n }\r\n variant = ref;\r\n }\r\n break;\r\n\r\n case VAR_RESOURCEREFLIST:\r\n {\r\n ResourceRefList refList;\r\n Vector values = GetString().Split(';', true);\r\n if (values.Size() >= 1)\r\n {\r\n refList.type_ = values[0];\r\n refList.names_.Resize(values.Size() - 1);\r\n for (unsigned i = 1; i < values.Size(); ++i)\r\n refList.names_[i - 1] = values[i];\r\n }\r\n variant = refList;\r\n }\r\n break;\r\n\r\n case VAR_STRINGVECTOR:\r\n {\r\n StringVector vector;\r\n for (unsigned i = 0; i < Size(); ++i)\r\n vector.Push((*this)[i].GetString());\r\n variant = vector;\r\n }\r\n break;\r\n\r\n default:\r\n variant.FromString(type, GetString());\r\n }\r\n\r\n return variant;\r\n}\r\n\r\nvoid JSONValue::SetVariantMap(const VariantMap& variantMap, Context* context)\r\n{\r\n SetType(JSON_OBJECT);\r\n for (VariantMap::ConstIterator i = variantMap.Begin(); i != variantMap.End(); ++i)\r\n (*this)[i->first_.ToString()].SetVariant(i->second_);\r\n}\r\n\r\nVariantMap JSONValue::GetVariantMap() const\r\n{\r\n VariantMap variantMap;\r\n if (!IsObject())\r\n {\r\n URHO3D_LOGERROR(\"JSONValue is not a object\");\r\n return variantMap;\r\n }\r\n\r\n for (ConstJSONObjectIterator i = Begin(); i != End(); ++i)\r\n {\r\n StringHash key(ToUInt(i->first_));\r\n Variant variant = i->second_.GetVariant();\r\n variantMap[key] = variant;\r\n }\r\n\r\n return variantMap;\r\n}\r\n\r\nvoid JSONValue::SetVariantVector(const VariantVector& variantVector, Context* context)\r\n{\r\n SetType(JSON_ARRAY);\r\n arrayValue_->Reserve(variantVector.Size());\r\n for (unsigned i = 0; i < variantVector.Size(); ++i)\r\n {\r\n JSONValue val;\r\n val.SetVariant(variantVector[i], context);\r\n arrayValue_->Push(val);\r\n }\r\n}\r\n\r\nVariantVector JSONValue::GetVariantVector() const\r\n{\r\n VariantVector variantVector;\r\n if (!IsArray())\r\n {\r\n URHO3D_LOGERROR(\"JSONValue is not a array\");\r\n return variantVector;\r\n }\r\n\r\n for (unsigned i = 0; i < Size(); ++i)\r\n {\r\n Variant variant = (*this)[i].GetVariant();\r\n variantVector.Push(variant);\r\n }\r\n\r\n return variantVector;\r\n}\r\n\r\n}\r\n<|endoftext|>"} {"text":"\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n\nusing namespace SCIRun::Gui;\n\nNetworkExecutionProgressBar::NetworkExecutionProgressBar(QWidget* parent) : numModulesDone_(0), totalModules_(0)\n{\n barAction_ = new QWidgetAction(parent);\n barAction_->setDefaultWidget(progressBar_ = new QProgressBar(parent));\n barAction_->setVisible(true);\n\n counterAction_ = new QWidgetAction(parent);\n counterAction_->setDefaultWidget(counterLabel_ = new QLabel(counterLabelString(), parent));\n counterAction_->setVisible(true);\n}\n\nQList NetworkExecutionProgressBar::actions() const\n{\n return QList() << barAction_ << counterAction_;\n}\n\nvoid NetworkExecutionProgressBar::updateTotalModules(int count)\n{\n \/\/std::cout << \"updateTotalModules: \" << count << std::endl;\n if (count >= 0 && count != totalModules_)\n {\n totalModules_ = count;\n numModulesDone_ = 0;\n counterLabel_->setText(counterLabelString());\n progressBar_->setMaximum(count);\n progressBar_->setValue(0);\n }\n}\nvoid NetworkExecutionProgressBar::incrementModulesDone()\n{\n \/\/std::cout << \"incrementModulesDone: \" << numModulesDone_ << std::endl;\n if (numModulesDone_ < totalModules_)\n {\n numModulesDone_++;\n counterLabel_->setText(counterLabelString());\n progressBar_->setValue(numModulesDone_);\n }\n}\n\nvoid NetworkExecutionProgressBar::resetModulesDone()\n{\n \/\/std::cout << \"resetModulesDone: \" << std::endl;\n numModulesDone_ = 0;\n counterLabel_->setText(counterLabelString());\n progressBar_->setValue(numModulesDone_);\n}\n\nQString NetworkExecutionProgressBar::counterLabelString() const\n{\n return QString(\" %1 \/ %2 \").arg(numModulesDone_).arg(totalModules_);\n}Closes #83.\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2012 Scientific Computing and Imaging Institute,\n University of Utah.\n\n License for the specific language governing rights and limitations under\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n#include \n#include \n\nusing namespace SCIRun::Gui;\n\nNetworkExecutionProgressBar::NetworkExecutionProgressBar(QWidget* parent) : numModulesDone_(0), totalModules_(0)\n{\n barAction_ = new QWidgetAction(parent);\n barAction_->setDefaultWidget(progressBar_ = new QProgressBar(parent));\n barAction_->setVisible(true);\n\n counterAction_ = new QWidgetAction(parent);\n counterAction_->setDefaultWidget(counterLabel_ = new QLabel(counterLabelString(), parent));\n counterAction_->setVisible(true);\n}\n\nQList NetworkExecutionProgressBar::actions() const\n{\n return QList() << barAction_ << counterAction_;\n}\n\nvoid NetworkExecutionProgressBar::updateTotalModules(int count)\n{\n \/\/std::cout << \"updateTotalModules: \" << count << std::endl;\n if (count >= 0 && count != totalModules_)\n {\n totalModules_ = count;\n numModulesDone_ = 0;\n counterLabel_->setText(counterLabelString());\n if (0 != count)\n progressBar_->setMaximum(count);\n progressBar_->setValue(0);\n }\n}\nvoid NetworkExecutionProgressBar::incrementModulesDone()\n{\n \/\/std::cout << \"incrementModulesDone: \" << numModulesDone_ << std::endl;\n if (numModulesDone_ < totalModules_)\n {\n numModulesDone_++;\n counterLabel_->setText(counterLabelString());\n progressBar_->setValue(numModulesDone_);\n }\n}\n\nvoid NetworkExecutionProgressBar::resetModulesDone()\n{\n \/\/std::cout << \"resetModulesDone: \" << std::endl;\n numModulesDone_ = 0;\n counterLabel_->setText(counterLabelString());\n progressBar_->setValue(numModulesDone_);\n}\n\nQString NetworkExecutionProgressBar::counterLabelString() const\n{\n return QString(\" %1 \/ %2 \").arg(numModulesDone_).arg(totalModules_);\n}<|endoftext|>"} {"text":"\/\/ smallpt, a Path Tracer by Kevin Beason, 2008\n\/\/\n\/\/ Modified by Peter uek\n\/\/ For the original code, see github.com\/munificient\/smallpt\n\/\/ For the original license, see smallpt.LICENSE.txt\n\n#include \n#include \n#include \n\n#include \n\n#include \"classes.h\"\n#include \"msvc.h\"\n\nnamespace ns_sycl_gtx {\n\nstatic const int numSpheres = 9;\nSphere spheres[numSpheres] = {\/\/Scene: radius, position, emission, color, material\n\tSphere(1e5, Vec(1e5 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),\/\/Left\n\tSphere(1e5, Vec(-1e5 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),\/\/Rght\n\tSphere(1e5, Vec(50, 40.8, 1e5), Vec(), Vec(.75, .75, .75), DIFF),\/\/Back\n\tSphere(1e5, Vec(50, 40.8, -1e5 + 170), Vec(), Vec(), DIFF),\/\/Frnt\n\tSphere(1e5, Vec(50, 1e5, 81.6), Vec(), Vec(.75, .75, .75), DIFF),\/\/Botm\n\tSphere(1e5, Vec(50, -1e5 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),\/\/Top\n\tSphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),\/\/Mirr\n\tSphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),\/\/Glas\n\tSphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) \/\/Lite\n};\n\ninline bool intersect(const Ray& r, double& t, int& id) {\n\tdouble d;\n\tdouble inf = t = 1e20;\n\tfor(int i = numSpheres; i > 0;) {\n\t\t--i;\n\t\tif((d = spheres[i].intersect(r)) && d < t) {\n\t\t\tt = d;\n\t\t\tid = i;\n\t\t}\n\t}\n\treturn t < inf;\n}\n\nenum class DoNext {\n\tReturn, ContinueLoop, Proceed\n};\n\nDoNext radianceInner(\n\tRay& r, int& depth, unsigned short* Xi,\t\/\/ Original parameters\n\tdouble& t, int& id, Vec& cl, Vec& cf,\t\/\/ Passed references\n\t\/\/ Output references\n\tdouble& Re, double& Tr, double& P, double& RP, double& TP, Ray& reflRay, Vec& x, Vec& tdir\n) {\n\tif(!intersect(r, t, id)) {\n\t\t\/\/ if miss, don't add anything\n\t\treturn DoNext::Return;\n\t}\n\tconst Sphere& obj = spheres[id]; \/\/ the hit object\n\tx = r.o + r.d*t;\n\tVec n = (x - obj.p).norm();\n\tVec nl = n;\n\tif(n.dot(r.d) > 0) {\n\t\tnl = nl * -1;\n\t}\n\tVec f = obj.c;\n\tdouble p;\t\/\/ max refl\n\tif(f.x > f.y && f.x > f.z) {\n\t\tp = f.x;\n\t}\n\telse if(f.y > f.z) {\n\t\tp = f.y;\n\t}\n\telse {\n\t\tp = f.z;\n\t}\n\n\tcl = cl + cf.mult(obj.e);\n\n\tdepth += 1;\n\tif(depth > 5) {\n\t\tif(erand48(Xi) < p) {\n\t\t\tf = f*(1 \/ p);\n\t\t}\n\t\telse {\n\t\t\treturn DoNext::Return;\n\t\t}\n\t}\n\n\tcf = cf.mult(f);\n\n\tif(obj.refl == DIFF) {\t\/\/ Ideal DIFFUSE reflection\n\t\tdouble r1 = 2 * M_PI*erand48(Xi), r2 = erand48(Xi), r2s = sqrt(r2);\n\t\tVec w = nl;\n\t\tVec u;\n\t\tif(fabs(w.x) > .1) {\n\t\t\tu.y = 1;\n\t\t}\n\t\telse {\n\t\t\tu.x = 1;\n\t\t}\n\t\tu = (u % w).norm();\n\t\tVec v = w%u;\n\t\tVec d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1 - r2)).norm();\n\n\t\t\/\/ Recursion\n\t\tr = Ray(x, d);\n\t\treturn DoNext::ContinueLoop;\n\t}\n\telse if(obj.refl == SPEC) {\t\/\/ Ideal SPECULAR reflection\n\t\t\/\/ Recursion\n\t\tr = Ray(x, r.d - n * 2 * n.dot(r.d));\n\t\treturn DoNext::ContinueLoop;\n\t}\n\treflRay = Ray(x, r.d - n * 2 * n.dot(r.d));\t\/\/ Ideal dielectric REFRACTION\n\tbool into = n.dot(nl) > 0;\t\/\/ Ray from outside going in?\n\tdouble nc = 1;\n\tdouble nt = 1.5;\n\tdouble nnt;\n\tif(into) {\n\t\tnnt = nc \/ nt;\n\t}\n\telse {\n\t\tnnt = nt \/ nc;\n\t}\n\tdouble ddn = r.d.dot(nl);\n\tdouble cos2t;\n\tif((cos2t = 1 - nnt*nnt*(1 - ddn*ddn)) < 0) {\t\/\/ Total internal reflection\n\t\t\/\/ Recursion\n\t\tr = reflRay;\n\t\treturn DoNext::ContinueLoop;\n\t}\n\tdouble tmp = 1;\n\tif(!into) {\n\t\ttmp = -1;\n\t}\n\ttdir = (r.d*nnt - n*(tmp*(ddn*nnt + sqrt(cos2t)))).norm();\n\tdouble a = nt - nc;\n\tdouble b = nt + nc;\n\tdouble R0 = a*a \/ (b*b);\n\tdouble c = 1;\n\tif(into) {\n\t\tc += ddn;\n\t}\n\telse {\n\t\tc -= tdir.dot(n);\n\t}\n\tRe = R0 + (1 - R0)*c*c*c*c*c;\n\tTr = 1 - Re;\n\tP = .25 + .5*Re;\n\tRP = Re \/ P;\n\tTP = Tr \/ (1 - P);\n\n\treturn DoNext::Proceed;\n}\n\nvoid radiance(Ray r, int depth, unsigned short* Xi, Vec& cl, Vec& cf) {\n\tdouble t;\t\/\/ distance to intersection\n\tint id = 0;\t\/\/ id of intersected object\n\n\tdouble Re, Tr, P, RP, TP;\n\tRay reflRay(0, 0);\n\tVec x, tdir;\n\n\twhile(true) {\n\t\tauto doNext = radianceInner(\n\t\t\tr, depth, Xi,\n\t\t\tt, id, cl, cf,\n\t\t\tRe, Tr, P, RP, TP, reflRay, x, tdir\n\t\t);\n\n\t\tif(doNext == DoNext::ContinueLoop) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(doNext == DoNext::Return) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(erand48(Xi) < P) {\n\t\t\tcf = cf * RP;\n\t\t\tr = reflRay;\n\t\t}\n\t\telse {\n\t\t\tcf = cf * TP;\n\t\t\tr = Ray(x, tdir);\n\t\t}\n\t}\n}\n\ntemplate \nVec radiance(Ray r, unsigned short* Xi, Vec cl = { 0, 0, 0 }, Vec cf = {1, 1, 1}) {\n\tdouble t;\t\/\/ distance to intersection\n\tint id = 0;\t\/\/ id of intersected object\n\tint depth = depth_;\n\n\t\/\/ cl is accumulated color\n\t\/\/ cf is accumulated reflectance\n\n\tdouble Re, Tr, P, RP, TP;\n\tRay reflRay(0, 0);\n\tVec x, tdir;\n\n\twhile(true) {\n\t\tauto doNext = radianceInner(\n\t\t\tr, depth, Xi,\n\t\t\tt, id, cl, cf,\n\t\t\tRe, Tr, P, RP, TP, reflRay, x, tdir\n\t\t);\n\n\t\tif(doNext == DoNext::ContinueLoop) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(doNext == DoNext::Return) {\n\t\t\treturn cl;\n\t\t}\n\n\t\tif(depth == 1) {\n\t\t\treturn radiance<1>(reflRay, Xi, cl, cf * Re) + radiance<1>(Ray(x, tdir), Xi, cl, cf * Tr);\n\t\t}\n\t\telse if(depth == 2) {\n\t\t\treturn radiance<2>(reflRay, Xi, cl, cf * Re) + radiance<2>(Ray(x, tdir), Xi, cl, cf * Tr);\n\t\t}\n\t\telse {\n\t\t\tradiance(r, depth, Xi, cl, cf);\n\t\t\treturn cl;\n\t\t}\n\t}\n}\n\n} \/\/ namespace ns_sycl_gtx\n\ninline double clamp(double x) {\n\tif(x < 0) {\n\t\treturn 0;\n\t}\n\tif(x > 1) {\n\t\treturn 1;\n\t}\n\treturn x;\n}\n\nvoid compute_sycl_gtx_openmp(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\t#pragma omp parallel for schedule(dynamic, 1) private(r)\n\tfor(int y = 0; y < h; y++) {\t\t\t\t\t\t\/\/ Loop over image rows\n\t\tfprintf(stderr, \"\\rRendering (%d spp) %5.2f%%\", samps * 4, 100.*y \/ (h - 1));\n\t\tfor(unsigned short x = 0, Xi[3] = { 0, 0, y*y*y }; x < w; x++) {\t\/\/ Loop cols\n\t\t\tfor(int sy = 0, i = (h - y - 1)*w + x; sy < 2; sy++) {\t \/\/ 2x2 subpixel rows\n\t\t\t\tfor(int sx = 0; sx < 2; sx++, r = Vec()) {\t\t\/\/ 2x2 subpixel cols\n\t\t\t\t\tfor(int s = 0; s < samps; s++) {\n\t\t\t\t\t\tdouble r1 = 2 * erand48(Xi);\n\t\t\t\t\t\tdouble r2 = 2 * erand48(Xi);\n\n\t\t\t\t\t\tdouble dx, dy;\n\t\t\t\t\t\tif(r1 < 1) {\n\t\t\t\t\t\t\tdx = sqrt(r1) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdx = 1 - sqrt(2 - r1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(r2 < 1) {\n\t\t\t\t\t\t\tdy = sqrt(r2) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdy = 1 - sqrt(2 - r2);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tVec d = cx*(((sx + .5 + dx) \/ 2 + x) \/ w - .5) + cy*(((sy + .5 + dy) \/ 2 + y) \/ h - .5) + cam.d;\n\t\t\t\t\t\tr = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. \/ samps);\n\t\t\t\t\t} \/\/ Camera rays are pushed ^^^^^ forward to start in interior\n\n\t\t\t\t\tc[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nvoid compute_sycl_gtx(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c, cl::sycl::device_selector& selector) {\n\tusing namespace cl::sycl;\n\n\tqueue q(selector);\n\n\tbuffer colors(c, range<1>(w*h));\n\n\tq.submit([&](handler& cgh) {\n\t\t\/\/ TODO\n\t});\n}\n\nvoid compute_sycl_gtx_cpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\tcl::sycl::cpu_selector cpu;\n\tcompute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, cpu);\n}\n\nvoid compute_sycl_gtx_gpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\tcl::sycl::gpu_selector gpu;\n\tcompute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, gpu);\n}\nBasic kernel.\/\/ smallpt, a Path Tracer by Kevin Beason, 2008\n\/\/\n\/\/ Modified by Peter uek\n\/\/ For the original code, see github.com\/munificient\/smallpt\n\/\/ For the original license, see smallpt.LICENSE.txt\n\n#include \n#include \n#include \n\n#include \n\n#include \"classes.h\"\n#include \"msvc.h\"\n\nnamespace ns_sycl_gtx {\n\nstatic const int numSpheres = 9;\nSphere spheres[numSpheres] = {\/\/Scene: radius, position, emission, color, material\n\tSphere(1e5, Vec(1e5 + 1, 40.8, 81.6), Vec(), Vec(.75, .25, .25), DIFF),\/\/Left\n\tSphere(1e5, Vec(-1e5 + 99, 40.8, 81.6), Vec(), Vec(.25, .25, .75), DIFF),\/\/Rght\n\tSphere(1e5, Vec(50, 40.8, 1e5), Vec(), Vec(.75, .75, .75), DIFF),\/\/Back\n\tSphere(1e5, Vec(50, 40.8, -1e5 + 170), Vec(), Vec(), DIFF),\/\/Frnt\n\tSphere(1e5, Vec(50, 1e5, 81.6), Vec(), Vec(.75, .75, .75), DIFF),\/\/Botm\n\tSphere(1e5, Vec(50, -1e5 + 81.6, 81.6), Vec(), Vec(.75, .75, .75), DIFF),\/\/Top\n\tSphere(16.5, Vec(27, 16.5, 47), Vec(), Vec(1, 1, 1)*.999, SPEC),\/\/Mirr\n\tSphere(16.5, Vec(73, 16.5, 78), Vec(), Vec(1, 1, 1)*.999, REFR),\/\/Glas\n\tSphere(600, Vec(50, 681.6 - .27, 81.6), Vec(12, 12, 12), Vec(), DIFF) \/\/Lite\n};\n\ninline bool intersect(const Ray& r, double& t, int& id) {\n\tdouble d;\n\tdouble inf = t = 1e20;\n\tfor(int i = numSpheres; i > 0;) {\n\t\t--i;\n\t\tif((d = spheres[i].intersect(r)) && d < t) {\n\t\t\tt = d;\n\t\t\tid = i;\n\t\t}\n\t}\n\treturn t < inf;\n}\n\nenum class DoNext {\n\tReturn, ContinueLoop, Proceed\n};\n\nDoNext radianceInner(\n\tRay& r, int& depth, unsigned short* Xi,\t\/\/ Original parameters\n\tdouble& t, int& id, Vec& cl, Vec& cf,\t\/\/ Passed references\n\t\/\/ Output references\n\tdouble& Re, double& Tr, double& P, double& RP, double& TP, Ray& reflRay, Vec& x, Vec& tdir\n) {\n\tif(!intersect(r, t, id)) {\n\t\t\/\/ if miss, don't add anything\n\t\treturn DoNext::Return;\n\t}\n\tconst Sphere& obj = spheres[id]; \/\/ the hit object\n\tx = r.o + r.d*t;\n\tVec n = (x - obj.p).norm();\n\tVec nl = n;\n\tif(n.dot(r.d) > 0) {\n\t\tnl = nl * -1;\n\t}\n\tVec f = obj.c;\n\tdouble p;\t\/\/ max refl\n\tif(f.x > f.y && f.x > f.z) {\n\t\tp = f.x;\n\t}\n\telse if(f.y > f.z) {\n\t\tp = f.y;\n\t}\n\telse {\n\t\tp = f.z;\n\t}\n\n\tcl = cl + cf.mult(obj.e);\n\n\tdepth += 1;\n\tif(depth > 5) {\n\t\tif(erand48(Xi) < p) {\n\t\t\tf = f*(1 \/ p);\n\t\t}\n\t\telse {\n\t\t\treturn DoNext::Return;\n\t\t}\n\t}\n\n\tcf = cf.mult(f);\n\n\tif(obj.refl == DIFF) {\t\/\/ Ideal DIFFUSE reflection\n\t\tdouble r1 = 2 * M_PI*erand48(Xi), r2 = erand48(Xi), r2s = sqrt(r2);\n\t\tVec w = nl;\n\t\tVec u;\n\t\tif(fabs(w.x) > .1) {\n\t\t\tu.y = 1;\n\t\t}\n\t\telse {\n\t\t\tu.x = 1;\n\t\t}\n\t\tu = (u % w).norm();\n\t\tVec v = w%u;\n\t\tVec d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1 - r2)).norm();\n\n\t\t\/\/ Recursion\n\t\tr = Ray(x, d);\n\t\treturn DoNext::ContinueLoop;\n\t}\n\telse if(obj.refl == SPEC) {\t\/\/ Ideal SPECULAR reflection\n\t\t\/\/ Recursion\n\t\tr = Ray(x, r.d - n * 2 * n.dot(r.d));\n\t\treturn DoNext::ContinueLoop;\n\t}\n\treflRay = Ray(x, r.d - n * 2 * n.dot(r.d));\t\/\/ Ideal dielectric REFRACTION\n\tbool into = n.dot(nl) > 0;\t\/\/ Ray from outside going in?\n\tdouble nc = 1;\n\tdouble nt = 1.5;\n\tdouble nnt;\n\tif(into) {\n\t\tnnt = nc \/ nt;\n\t}\n\telse {\n\t\tnnt = nt \/ nc;\n\t}\n\tdouble ddn = r.d.dot(nl);\n\tdouble cos2t;\n\tif((cos2t = 1 - nnt*nnt*(1 - ddn*ddn)) < 0) {\t\/\/ Total internal reflection\n\t\t\/\/ Recursion\n\t\tr = reflRay;\n\t\treturn DoNext::ContinueLoop;\n\t}\n\tdouble tmp = 1;\n\tif(!into) {\n\t\ttmp = -1;\n\t}\n\ttdir = (r.d*nnt - n*(tmp*(ddn*nnt + sqrt(cos2t)))).norm();\n\tdouble a = nt - nc;\n\tdouble b = nt + nc;\n\tdouble R0 = a*a \/ (b*b);\n\tdouble c = 1;\n\tif(into) {\n\t\tc += ddn;\n\t}\n\telse {\n\t\tc -= tdir.dot(n);\n\t}\n\tRe = R0 + (1 - R0)*c*c*c*c*c;\n\tTr = 1 - Re;\n\tP = .25 + .5*Re;\n\tRP = Re \/ P;\n\tTP = Tr \/ (1 - P);\n\n\treturn DoNext::Proceed;\n}\n\nvoid radiance(Ray r, int depth, unsigned short* Xi, Vec& cl, Vec& cf) {\n\tdouble t;\t\/\/ distance to intersection\n\tint id = 0;\t\/\/ id of intersected object\n\n\tdouble Re, Tr, P, RP, TP;\n\tRay reflRay(0, 0);\n\tVec x, tdir;\n\n\twhile(true) {\n\t\tauto doNext = radianceInner(\n\t\t\tr, depth, Xi,\n\t\t\tt, id, cl, cf,\n\t\t\tRe, Tr, P, RP, TP, reflRay, x, tdir\n\t\t);\n\n\t\tif(doNext == DoNext::ContinueLoop) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(doNext == DoNext::Return) {\n\t\t\treturn;\n\t\t}\n\n\t\tif(erand48(Xi) < P) {\n\t\t\tcf = cf * RP;\n\t\t\tr = reflRay;\n\t\t}\n\t\telse {\n\t\t\tcf = cf * TP;\n\t\t\tr = Ray(x, tdir);\n\t\t}\n\t}\n}\n\ntemplate \nVec radiance(Ray r, unsigned short* Xi, Vec cl = { 0, 0, 0 }, Vec cf = {1, 1, 1}) {\n\tdouble t;\t\/\/ distance to intersection\n\tint id = 0;\t\/\/ id of intersected object\n\tint depth = depth_;\n\n\t\/\/ cl is accumulated color\n\t\/\/ cf is accumulated reflectance\n\n\tdouble Re, Tr, P, RP, TP;\n\tRay reflRay(0, 0);\n\tVec x, tdir;\n\n\twhile(true) {\n\t\tauto doNext = radianceInner(\n\t\t\tr, depth, Xi,\n\t\t\tt, id, cl, cf,\n\t\t\tRe, Tr, P, RP, TP, reflRay, x, tdir\n\t\t);\n\n\t\tif(doNext == DoNext::ContinueLoop) {\n\t\t\tcontinue;\n\t\t}\n\t\tif(doNext == DoNext::Return) {\n\t\t\treturn cl;\n\t\t}\n\n\t\tif(depth == 1) {\n\t\t\treturn radiance<1>(reflRay, Xi, cl, cf * Re) + radiance<1>(Ray(x, tdir), Xi, cl, cf * Tr);\n\t\t}\n\t\telse if(depth == 2) {\n\t\t\treturn radiance<2>(reflRay, Xi, cl, cf * Re) + radiance<2>(Ray(x, tdir), Xi, cl, cf * Tr);\n\t\t}\n\t\telse {\n\t\t\tradiance(r, depth, Xi, cl, cf);\n\t\t\treturn cl;\n\t\t}\n\t}\n}\n\n} \/\/ namespace ns_sycl_gtx\n\ninline double clamp(double x) {\n\tif(x < 0) {\n\t\treturn 0;\n\t}\n\tif(x > 1) {\n\t\treturn 1;\n\t}\n\treturn x;\n}\n\nvoid compute_sycl_gtx_openmp(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\t#pragma omp parallel for schedule(dynamic, 1) private(r)\n\tfor(int y = 0; y < h; y++) {\t\t\t\t\t\t\/\/ Loop over image rows\n\t\tfprintf(stderr, \"\\rRendering (%d spp) %5.2f%%\", samps * 4, 100.*y \/ (h - 1));\n\t\tfor(unsigned short x = 0, Xi[3] = { 0, 0, y*y*y }; x < w; x++) {\t\/\/ Loop cols\n\t\t\tfor(int sy = 0, i = (h - y - 1)*w + x; sy < 2; sy++) {\t \/\/ 2x2 subpixel rows\n\t\t\t\tfor(int sx = 0; sx < 2; sx++, r = Vec()) {\t\t\/\/ 2x2 subpixel cols\n\t\t\t\t\tfor(int s = 0; s < samps; s++) {\n\t\t\t\t\t\tdouble r1 = 2 * erand48(Xi);\n\t\t\t\t\t\tdouble r2 = 2 * erand48(Xi);\n\n\t\t\t\t\t\tdouble dx, dy;\n\t\t\t\t\t\tif(r1 < 1) {\n\t\t\t\t\t\t\tdx = sqrt(r1) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdx = 1 - sqrt(2 - r1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(r2 < 1) {\n\t\t\t\t\t\t\tdy = sqrt(r2) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tdy = 1 - sqrt(2 - r2);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tVec d = cx*(((sx + .5 + dx) \/ 2 + x) \/ w - .5) + cy*(((sy + .5 + dy) \/ 2 + y) \/ h - .5) + cam.d;\n\t\t\t\t\t\tr = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. \/ samps);\n\t\t\t\t\t} \/\/ Camera rays are pushed ^^^^^ forward to start in interior\n\n\t\t\t\t\tc[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nvoid compute_sycl_gtx(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* clrs, cl::sycl::device_selector& selector) {\n\tusing namespace cl::sycl;\n\n\tqueue q(selector);\n\n\tbuffer colors(clrs, range<1>(w*h));\n\n\tq.submit([&](handler& cgh) {\n\t\tauto c = colors.get_access();\n\n\t\t\/\/ TODO: Should not be mutable\n\t\tcgh.parallel_for(range<2>(w, h), [=](id<2> index) mutable {\n\t\t\tauto x = index[0];\n\t\t\tauto y = index[1];\n\t\t\tunsigned short Xi[3] = { 0, 0, (size_t)y*y*y };\t\/\/ TODO\n\t\t\tint1 i = (h - y - 1)*w + x;\n\n\t\t\t\/\/ 2x2 subpixel rows\n\t\t\tSYCL_FOR(int1 sy = 0, sy < 2, sy++)\n\t\t\tSYCL_BEGIN {\n\t\t\t\t\/\/ 2x2 subpixel cols\n\t\t\t\tSYCL_FOR(int1 sx = 0, sx < 2, sx++)\n\t\t\t\tSYCL_BEGIN {\n\t\t\t\t\tSYCL_FOR(int1 s = 0, s < samps, s++) {\n\t\t\t\t\t\tdouble2 rnew;\n\t\t\t\t\t\trnew.x = 2 * erand48(Xi);\n\t\t\t\t\t\trnew.y = 2 * erand48(Xi);\n\n\t\t\t\t\t\tdouble2 dd;\n\n\t\t\t\t\t\tSYCL_IF(rnew.x < 1)\n\t\t\t\t\t\tSYCL_BEGIN {\n\t\t\t\t\t\t\tdd.x = sqrt(rnew.x) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSYCL_END\n\t\t\t\t\t\tSYCL_ELSE\n\t\t\t\t\t\tSYCL_BEGIN {\n\t\t\t\t\t\t\tdd.x = 1 - sqrt(2 - rnew.x);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSYCL_END\n\n\t\t\t\t\t\tSYCL_IF(rnew.y < 1)\n\t\t\t\t\t\tSYCL_BEGIN {\n\t\t\t\t\t\t\tdd.y = sqrt(rnew.y) - 1;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSYCL_END\n\t\t\t\t\t\tSYCL_ELSE\n\t\t\t\t\t\tSYCL_BEGIN {\n\t\t\t\t\t\t\tdd.y = 1 - sqrt(2 - rnew.y);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tSYCL_END\n\n\t\t\t\t\t\tVec d = cx * (((sx + .5 + rnew.x) \/ 2 + x) \/ w - .5) +\n\t\t\t\t\t\t\t\tcy * (((sy + .5 + rnew.y) \/ 2 + y) \/ h - .5) +\n\t\t\t\t\t\t\t\tcam.d;\n\n\t\t\t\t\t\t\/\/ TODO:\n\t\t\t\t\t\t\/\/r = r + ns_sycl_gtx::radiance(Ray(cam.o + d * 140, d.norm()), Xi)*(1. \/ samps);\n\t\t\t\t\t} \/\/ Camera rays are pushed ^^^^^ forward to start in interior\n\n\t\t\t\t\tc[i] = c[i] + Vec(clamp(r.x), clamp(r.y), clamp(r.z))*.25;\n\n\t\t\t\t\tr = Vec();\n\t\t\t\t}\n\t\t\t\tSYCL_END\n\t\t\t}\n\t\t\tSYCL_END\n\t\t});\n\t});\n}\n\nvoid compute_sycl_gtx_cpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\tcl::sycl::cpu_selector cpu;\n\tcompute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, cpu);\n}\n\nvoid compute_sycl_gtx_gpu(int w, int h, int samps, Ray& cam, Vec& cx, Vec& cy, Vec r, Vec* c) {\n\tcl::sycl::gpu_selector gpu;\n\tcompute_sycl_gtx(w, h, samps, cam, cx, cy, r, c, gpu);\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n*\n* Copyright NumFOCUS\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n#include \"sitkMacro.h\"\n\n#include \"SimpleITKTestHarness.h\"\n\nstatic const char * DESCRIPTION = \"We expect this exception\";\n\nclass sitkExceptionsTest\n : public ::testing::Test\n{\npublic:\n\n void ThrowsitkException( )\n {\n sitkExceptionMacro( << DESCRIPTION );\n }\n};\n\nTEST_F(sitkExceptionsTest, Test1) {\n ASSERT_THROW( ThrowsitkException(), ::itk::simple::GenericException );\n\n try\n {\n ThrowsitkException();\n }\n catch ( ::itk::simple::GenericException &e )\n {\n \/\/ could do some nifty testing here too\n EXPECT_EQ ( e.GetNameOfClass(), std::string(\"GenericException\") );\n \/\/EXPECT_NE ( std::string ( e.GetLocation() ), \"\" ); HACK FIXME\n \/\/ exception revision\n return;\n }\n\n \/\/ should gotten that exception\n FAIL();\n}\n\nTEST_F(sitkExceptionsTest, Test2) {\n\n \/\/ this can only be tested when true, if it was false the file won't compile\n static_assert( true, \"this is just a test\" );\n\n SUCCEED();\n}\n\nTEST_F(sitkExceptionsTest, Test3) {\n\n \/\/ This test is designed to improve coverage of the GenericException class\n\n \/\/ Default constructor\n const itk::simple::GenericException empty;\n itk::simple::GenericException e0;\n\n\n itk::simple::GenericException e1( __FILE__, __LINE__ );\n\n itk::simple::GenericException e2( __FILE__, __LINE__, \"testing yet another constructor\" );\n\n \/\/ copy constructor\n itk::simple::GenericException e3( e2 );\n\n\n \/\/ asignment\n e0 = e2;\n e0 = e1;\n e0 = empty;\n\n\n sitkClangDiagnosticPush();\n sitkClangWarningIgnore(\"-Wself-assign-overloaded\");\n \/\/ test self assignment too\n e0 = e0;\n sitkClangDiagnosticPop();\n\n EXPECT_TRUE( e1 == e1 );\n EXPECT_TRUE( empty == empty );\n EXPECT_FALSE( e2 == e1 );\n\n EXPECT_NO_THROW( e2.ToString() );\n EXPECT_NO_THROW( e2.GetLocation() );\n EXPECT_NO_THROW( e2.GetDescription() );\n EXPECT_NO_THROW( e2.GetFile() );\n EXPECT_NO_THROW( e2.GetLine() );\n EXPECT_NO_THROW( e2.what() );\n\n \/\/ check accessor for empty\/null\n EXPECT_NO_THROW( empty.ToString() );\n EXPECT_NO_THROW( empty.GetLocation() );\n EXPECT_NO_THROW( empty.GetDescription() );\n EXPECT_NO_THROW( empty.GetFile() );\n EXPECT_NO_THROW( empty.GetLine() );\n EXPECT_NO_THROW( empty.what() );\n\n}\nAdd `sitkExceptionsTest.TestDestructionAfterAssignment` unit test\/*=========================================================================\n*\n* Copyright NumFOCUS\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n*=========================================================================*\/\n#include \"sitkMacro.h\"\n\n#include \"SimpleITKTestHarness.h\"\n\nstatic const char * DESCRIPTION = \"We expect this exception\";\n\nclass sitkExceptionsTest\n : public ::testing::Test\n{\npublic:\n\n void ThrowsitkException( )\n {\n sitkExceptionMacro( << DESCRIPTION );\n }\n};\n\nTEST_F(sitkExceptionsTest, Test1) {\n ASSERT_THROW( ThrowsitkException(), ::itk::simple::GenericException );\n\n try\n {\n ThrowsitkException();\n }\n catch ( ::itk::simple::GenericException &e )\n {\n \/\/ could do some nifty testing here too\n EXPECT_EQ ( e.GetNameOfClass(), std::string(\"GenericException\") );\n \/\/EXPECT_NE ( std::string ( e.GetLocation() ), \"\" ); HACK FIXME\n \/\/ exception revision\n return;\n }\n\n \/\/ should gotten that exception\n FAIL();\n}\n\nTEST_F(sitkExceptionsTest, Test2) {\n\n \/\/ this can only be tested when true, if it was false the file won't compile\n static_assert( true, \"this is just a test\" );\n\n SUCCEED();\n}\n\nTEST_F(sitkExceptionsTest, Test3) {\n\n \/\/ This test is designed to improve coverage of the GenericException class\n\n \/\/ Default constructor\n const itk::simple::GenericException empty;\n itk::simple::GenericException e0;\n\n\n itk::simple::GenericException e1( __FILE__, __LINE__ );\n\n itk::simple::GenericException e2( __FILE__, __LINE__, \"testing yet another constructor\" );\n\n \/\/ copy constructor\n itk::simple::GenericException e3( e2 );\n\n\n \/\/ asignment\n e0 = e2;\n e0 = e1;\n e0 = empty;\n\n\n sitkClangDiagnosticPush();\n sitkClangWarningIgnore(\"-Wself-assign-overloaded\");\n \/\/ test self assignment too\n e0 = e0;\n sitkClangDiagnosticPop();\n\n EXPECT_TRUE( e1 == e1 );\n EXPECT_TRUE( empty == empty );\n EXPECT_FALSE( e2 == e1 );\n\n EXPECT_NO_THROW( e2.ToString() );\n EXPECT_NO_THROW( e2.GetLocation() );\n EXPECT_NO_THROW( e2.GetDescription() );\n EXPECT_NO_THROW( e2.GetFile() );\n EXPECT_NO_THROW( e2.GetLine() );\n EXPECT_NO_THROW( e2.what() );\n\n \/\/ check accessor for empty\/null\n EXPECT_NO_THROW( empty.ToString() );\n EXPECT_NO_THROW( empty.GetLocation() );\n EXPECT_NO_THROW( empty.GetDescription() );\n EXPECT_NO_THROW( empty.GetFile() );\n EXPECT_NO_THROW( empty.GetLine() );\n EXPECT_NO_THROW( empty.what() );\n\n}\n\n\nTEST_F(sitkExceptionsTest, TestDestructionAfterAssignment) {\n\n \/\/ Test that the program does not crash when two GenericException\n \/\/ variables get destructed (automatically, by getting out of scope),\n \/\/ when one of them is assigned to the other. (Such a crash might occur\n \/\/ with previous versions of SimpleITK, version <= v2.2rc3.)\n\n const itk::simple::GenericException source(__FILE__, __LINE__);\n itk::simple::GenericException target;\n\n target = source;\n\n \/\/ After assignment, the variables should compare equal, but moreover,\n \/\/ when they get out of scope, their destructors should not crash.\n EXPECT_EQ(target, source);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: LocaleNode.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2004-01-20 13:41:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _LOCALE_NODE_\n#define _LOCALE_NODE_\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace ::rtl;\nusing namespace ::std;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::io;\n\nclass OFileWriter\n{\npublic:\n\nOFileWriter(const char *pcFile, const char *locale );\n~OFileWriter();\n virtual void writeStringCharacters(const ::rtl::OUString& str) const;\n virtual void writeAsciiString(const char *str)const ;\n virtual void writeInt(sal_Int16 nb) const;\n virtual void writeFunction(const char *func, const char *count, const char *array) const;\n virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;\n virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;\n virtual void writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;\n virtual void writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;\n virtual void writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;\n virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;\n virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;\n virtual void flush(void) const ;\n virtual void closeOutput(void) const;\nprivate:\n char m_pcFile[1024];\n char theLocale[50];\n FILE *m_f;\n};\n\nclass Attr {\n Sequence name;\n Sequence value;\n\npublic:\n Attr (const Reference< XAttributeList > & attr);\n OUString getValueByName (const sal_Char *str) const;\n sal_Int32 getLength() const;\n OUString getTypeByIndex (sal_Int32 idx) const;\n OUString getValueByIndex (sal_Int32 idx) const ;\n};\n\nclass LocaleNode{\n OUString aName;\n Attr * xAttribs;\n OUString aValue;\n LocaleNode * parent;\n LocaleNode* * children;\n void setParent ( LocaleNode* node);\n sal_Int32 nChildren;\n sal_Int32 childArrSize;\n \/\/inline LocaleNode() { ; }\npublic:\n LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);\n inline void setValue(const OUString &oValue) { aValue += oValue; };\n inline const OUString getName() { return aName; };\n inline const OUString getValue() { return aValue; };\n inline const Attr* getAttr() { return xAttribs; };\n inline const sal_Int32 getNumberOfChildren () { return nChildren; };\n inline LocaleNode * getChildAt (sal_Int32 idx) { return children[idx] ; };\n LocaleNode * findNode ( const sal_Char *name);\n void print () ;\n void printR () ;\n ~LocaleNode();\n void addChild ( LocaleNode * node);\n virtual void generateCode (const OFileWriter &of);\n static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);\n};\n\nclass LCInfoNode : public LocaleNode {\npublic:\n inline LCInfoNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n virtual void generateCode (const OFileWriter &of);\n};\n\n\nclass LCCTYPENode : public LocaleNode {\npublic:\n inline LCCTYPENode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCFormatNode : public LocaleNode {\npublic:\n inline LCFormatNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCollationNode : public LocaleNode {\npublic:\n inline LCCollationNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCSearchNode : public LocaleNode {\npublic:\n inline LCSearchNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCalendarNode : public LocaleNode {\npublic:\n inline LCCalendarNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCurrencyNode : public LocaleNode {\npublic:\n inline LCCurrencyNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCTransliterationNode : public LocaleNode {\npublic:\n inline LCTransliterationNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCMiscNode : public LocaleNode {\npublic:\n inline LCMiscNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCNumberingLevelNode : public LocaleNode {\npublic:\n inline LCNumberingLevelNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCOutlineNumberingLevelNode : public LocaleNode {\npublic:\n inline LCOutlineNumberingLevelNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\n#endif\nINTEGRATION: CWS i18n12 (1.5.2); FILE MERGED 2004\/04\/30 14:30:27 er 1.5.2.2: #i25323# add virtual to dtors 2004\/04\/09 20:06:27 khong 1.5.2.1: #i25323# put index page information into localedata for each langauges\/*************************************************************************\n *\n * $RCSfile: LocaleNode.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2004-05-28 16:40:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef _LOCALE_NODE_\n#define _LOCALE_NODE_\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing namespace ::rtl;\nusing namespace ::std;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::cppu;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::lang;\nusing namespace ::com::sun::star::registry;\nusing namespace ::com::sun::star::xml::sax;\nusing namespace ::com::sun::star::io;\n\nclass OFileWriter\n{\npublic:\n\nOFileWriter(const char *pcFile, const char *locale );\nvirtual ~OFileWriter();\n virtual void writeStringCharacters(const ::rtl::OUString& str) const;\n virtual void writeAsciiString(const char *str)const ;\n virtual void writeInt(sal_Int16 nb) const;\n virtual void writeFunction(const char *func, const char *count, const char *array) const;\n virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeFunction(const char *func, const char *count, const char *array, const char *from, const char *to) const;\n virtual void writeRefFunction(const char *func, const ::rtl::OUString& useLocale, const char *to) const;\n virtual void writeFunction2(const char *func, const char *style, const char* attr, const char *array) const;\n virtual void writeRefFunction2(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeFunction3(const char *func, const char *style, const char* levels, const char* attr, const char *array) const;\n virtual void writeRefFunction3(const char *func, const ::rtl::OUString& useLocale) const;\n virtual void writeIntParameter(const sal_Char* pAsciiStr, const sal_Int16 count, sal_Int16 val) const;\n virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str, sal_Int16 count) const;\n virtual void writeDefaultParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& str) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count) const;\n virtual void writeParameter(const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, const sal_Int16 count) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars) const;\n virtual void writeParameter(const sal_Char* pTagStr, const sal_Char* pAsciiStr, const ::rtl::OUString& aChars, sal_Int16 count0, sal_Int16 count1) const;\n virtual void flush(void) const ;\n virtual void closeOutput(void) const;\nprivate:\n char m_pcFile[1024];\n char theLocale[50];\n FILE *m_f;\n};\n\nclass Attr {\n Sequence name;\n Sequence value;\n\npublic:\n Attr (const Reference< XAttributeList > & attr);\n OUString getValueByName (const sal_Char *str) const;\n sal_Int32 getLength() const;\n OUString getTypeByIndex (sal_Int32 idx) const;\n OUString getValueByIndex (sal_Int32 idx) const ;\n};\n\nclass LocaleNode{\n OUString aName;\n Attr * xAttribs;\n OUString aValue;\n LocaleNode * parent;\n LocaleNode* * children;\n void setParent ( LocaleNode* node);\n sal_Int32 nChildren;\n sal_Int32 childArrSize;\n \/\/inline LocaleNode() { ; }\npublic:\n LocaleNode (const OUString& name, const Reference< XAttributeList > & attr);\n inline void setValue(const OUString &oValue) { aValue += oValue; };\n inline const OUString getName() { return aName; };\n inline const OUString getValue() { return aValue; };\n inline const Attr* getAttr() { return xAttribs; };\n inline const sal_Int32 getNumberOfChildren () { return nChildren; };\n inline LocaleNode * getChildAt (sal_Int32 idx) { return children[idx] ; };\n LocaleNode * findNode ( const sal_Char *name);\n void print () ;\n void printR () ;\n virtual ~LocaleNode();\n void addChild ( LocaleNode * node);\n virtual void generateCode (const OFileWriter &of);\n static LocaleNode* createNode (const OUString& name,const Reference< XAttributeList > & attr);\n};\n\nclass LCInfoNode : public LocaleNode {\npublic:\n inline LCInfoNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n virtual void generateCode (const OFileWriter &of);\n};\n\n\nclass LCCTYPENode : public LocaleNode {\npublic:\n inline LCCTYPENode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCFormatNode : public LocaleNode {\npublic:\n inline LCFormatNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCollationNode : public LocaleNode {\npublic:\n inline LCCollationNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCIndexNode : public LocaleNode {\npublic:\n inline LCIndexNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCSearchNode : public LocaleNode {\npublic:\n inline LCSearchNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCalendarNode : public LocaleNode {\npublic:\n inline LCCalendarNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCCurrencyNode : public LocaleNode {\npublic:\n inline LCCurrencyNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCTransliterationNode : public LocaleNode {\npublic:\n inline LCTransliterationNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCMiscNode : public LocaleNode {\npublic:\n inline LCMiscNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCNumberingLevelNode : public LocaleNode {\npublic:\n inline LCNumberingLevelNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\nclass LCOutlineNumberingLevelNode : public LocaleNode {\npublic:\n inline LCOutlineNumberingLevelNode (const OUString& name,\n const Reference< XAttributeList > & attr) : LocaleNode (name, attr) { ; };\n\n virtual void generateCode (const OFileWriter &of);\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \"mbed.h\"\n#include \"SDFileSystem.h\"\n#include \"test_env.h\"\n\n#if defined(TARGET_KL25Z)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTD0, \"sd\");\n\n#elif defined(TARGET_KL46Z)\nSDFileSystem sd(PTD6, PTD7, PTD5, PTD4, \"sd\");\n\n#elif defined(TARGET_K64F)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTD0, \"sd\");\n\n#elif defined(TARGET_K22F)\nSDFileSystem sd(PTD6, PTD7, PTD5, PTD4, \"sd\");\n\n#elif defined(TARGET_K20D50M)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTC2, \"sd\");\n\n#elif defined(TARGET_nRF51822)\nSDFileSystem sd(p12, p13, p15, p14, \"sd\");\n\n#elif defined(TARGET_NUCLEO_F030R8) || \\\n defined(TARGET_NUCLEO_F070RB) || \\\n defined(TARGET_NUCLEO_F072RB) || \\\n defined(TARGET_NUCLEO_F091RC) || \\\n defined(TARGET_NUCLEO_F103RB) || \\\n defined(TARGET_NUCLEO_F302R8) || \\\n defined(TARGET_NUCLEO_F303RE) || \\\n defined(TARGET_NUCLEO_F334R8) || \\\n defined(TARGET_NUCLEO_F401RE) || \\\n defined(TARGET_NUCLEO_F411RE) || \\\n defined(TARGET_NUCLEO_L053R8) || \\\n defined(TARGET_NUCLEO_L152RE)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_DISCO_F051R8)\nSDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, \"sd\");\n\n#elif defined(TARGET_LPC2368)\nSDFileSystem sd(p11, p12, p13, p14, \"sd\");\n\n#elif defined(TARGET_LPC11U68)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_LPC1549)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_RZ_A1H)\nSDFileSystem sd(P8_5, P8_6, P8_3, P8_4, \"sd\");\n\n#else\nSDFileSystem sd(p11, p12, p13, p14, \"sd\");\n#endif\n\nnamespace {\nconst char *sd_file_path = \"\/sd\/out.txt\";\nconst int DATA_SIZE = 256;\n}\n\nint main()\n{\n uint8_t data_written[DATA_SIZE] = { 0 };\n bool result = true;\n\n \/\/ Fill data_written buffer with random data\n \/\/ Write these data into the file\n {\n FILE *f = fopen(sd_file_path, \"w\");\n\n printf(\"SD: Writing ... \");\n for (int i = 0; i < DATA_SIZE; i++) {\n data_written[i] = rand() % 0XFF;\n fprintf(f, \"%c\", data_written[i]);\n }\n printf(\"[OK]\\r\\n\");\n fclose(f);\n }\n\n \/\/ Read back the data from the file and store them in data_read\n {\n FILE *f = fopen(sd_file_path, \"r\");\n printf(\"SD: Reading data ... \");\n for (int i = 0; i < DATA_SIZE; i++) {\n uint8_t data = fgetc(f);\n if (data != data_written[i]) {\n result = false;\n break;\n }\n }\n printf(\"[%s]\\r\\n\", result ? \"OK\" : \"FAIL\");\n fclose(f);\n }\n\n notify_completion(result);\n}\nRefactored SD card basic test#include \"mbed.h\"\n#include \"SDFileSystem.h\"\n#include \"test_env.h\"\n\n#if defined(TARGET_KL25Z)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTD0, \"sd\");\n\n#elif defined(TARGET_KL46Z)\nSDFileSystem sd(PTD6, PTD7, PTD5, PTD4, \"sd\");\n\n#elif defined(TARGET_K64F)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTD0, \"sd\");\n\n#elif defined(TARGET_K22F)\nSDFileSystem sd(PTD6, PTD7, PTD5, PTD4, \"sd\");\n\n#elif defined(TARGET_K20D50M)\nSDFileSystem sd(PTD2, PTD3, PTD1, PTC2, \"sd\");\n\n#elif defined(TARGET_nRF51822)\nSDFileSystem sd(p12, p13, p15, p14, \"sd\");\n\n#elif defined(TARGET_NUCLEO_F030R8) || \\\n defined(TARGET_NUCLEO_F070RB) || \\\n defined(TARGET_NUCLEO_F072RB) || \\\n defined(TARGET_NUCLEO_F091RC) || \\\n defined(TARGET_NUCLEO_F103RB) || \\\n defined(TARGET_NUCLEO_F302R8) || \\\n defined(TARGET_NUCLEO_F303RE) || \\\n defined(TARGET_NUCLEO_F334R8) || \\\n defined(TARGET_NUCLEO_F401RE) || \\\n defined(TARGET_NUCLEO_F411RE) || \\\n defined(TARGET_NUCLEO_L053R8) || \\\n defined(TARGET_NUCLEO_L152RE)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_DISCO_F051R8)\nSDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, \"sd\");\n\n#elif defined(TARGET_LPC2368)\nSDFileSystem sd(p11, p12, p13, p14, \"sd\");\n\n#elif defined(TARGET_LPC11U68)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_LPC1549)\nSDFileSystem sd(D11, D12, D13, D10, \"sd\");\n\n#elif defined(TARGET_RZ_A1H)\nSDFileSystem sd(P8_5, P8_6, P8_3, P8_4, \"sd\");\n\n#else\nSDFileSystem sd(p11, p12, p13, p14, \"sd\");\n#endif\n\nnamespace {\nconst char *sd_file_path = \"\/sd\/out.txt\";\nconst int DATA_SIZE = 256;\n}\n\nint main()\n{\n uint8_t data_written[DATA_SIZE] = { 0 };\n bool result = false;\n\n \/\/ Fill data_written buffer with random data\n \/\/ Write these data into the file\n bool write_result = false;\n {\n printf(\"SD: Writing ... \");\n FILE *f = fopen(sd_file_path, \"w\");\n if (f) {\n for (int i = 0; i < DATA_SIZE; i++) {\n data_written[i] = rand() % 0XFF;\n fprintf(f, \"%c\", data_written[i]);\n }\n write_result = true;\n fclose(f);\n }\n printf(\"[%s]\\r\\n\", write_result ? \"OK\" : \"FAIL\");\n }\n\n \/\/ Read back the data from the file and store them in data_read\n bool read_result = false;\n {\n printf(\"SD: Reading data ... \");\n FILE *f = fopen(sd_file_path, \"r\");\n if (f) {\n for (int i = 0; i < DATA_SIZE; i++) {\n uint8_t data = fgetc(f);\n if (data != data_written[i]) {\n read_result = false;\n break;\n }\n }\n fclose(f);\n }\n printf(\"[%s]\\r\\n\", read_result ? \"OK\" : \"FAIL\");\n }\n\n result = write_result && read_result;\n notify_completion(result);\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mat::const_row_col_iterator implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator()\n : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)\n {\n \/\/ Technically this iterator is invalid (it may not point to a real element)\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const row_col_iterator& it)\n : M(it.M), current_pos(it.current_pos), internal_col(it.col()), internal_row(it.row())\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const const_row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n } \n \n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const Mat& in_M, const uword row, const uword col)\n : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator&\nMat::const_row_col_iterator::operator++()\n {\n current_pos++;\n internal_row++;\n\n \/\/ Check to see if we moved a column.\n if(internal_row == M->n_rows)\n {\n internal_col++;\n internal_row = 0;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::const_row_col_iterator::operator++(int)\n {\n typename Mat::const_row_col_iterator temp(*this);\n\n ++(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator&\nMat::const_row_col_iterator::operator--()\n {\n if(internal_row > 0)\n {\n current_pos--;\n internal_row--;\n }\n else if(internal_col > 0)\n {\n current_pos--;\n internal_col--;\n internal_row = M->n_rows - 1;\n }\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::const_row_col_iterator::operator--(int)\n {\n typename Mat::const_row_col_iterator temp(*this);\n\n --(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n \n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n \n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mat::row_col_iterator implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator()\n : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)\n {\n \/\/ Technically this iterator is invalid (it may not point to a real element)\n }\n\n\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator(const row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator(Mat& in_M, const uword row, const uword col)\n : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator&\nMat::row_col_iterator::operator++()\n {\n current_pos++;\n internal_row++;\n\n \/\/ Check to see if we moved a column.\n if(internal_row == M->n_rows)\n {\n internal_col++;\n internal_row = 0;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::row_col_iterator::operator++(int)\n {\n typename Mat::row_col_iterator temp(*this);\n\n ++(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator&\nMat::row_col_iterator::operator--()\n {\n if(internal_row != 0)\n {\n current_pos--;\n internal_row--;\n }\n else if(internal_col != 0)\n {\n current_pos--;\n internal_col--;\n internal_row = M->n_rows - 1;\n }\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::row_col_iterator::operator--(int)\n {\n typename Mat::row_col_iterator temp(*this);\n\n --(*this);\n\n return temp;\n } \n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n } \n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ extended Mat functionality implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::begin_row_col() const\n {\n return const_row_col_iterator(*this);\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::begin_row_col()\n {\n return row_col_iterator(*this);\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::end_row_col() const\n {\n return ++const_row_col_iterator(*this, n_rows - 1, n_cols - 1);\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::end_row_col()\n {\n return ++row_col_iterator(*this, n_rows - 1, n_cols - 1);\n }\nReturn *this for operator--().\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mat::const_row_col_iterator implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator()\n : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)\n {\n \/\/ Technically this iterator is invalid (it may not point to a real element)\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const row_col_iterator& it)\n : M(it.M), current_pos(it.current_pos), internal_col(it.col()), internal_row(it.row())\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const const_row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::const_row_col_iterator::const_row_col_iterator(const Mat& in_M, const uword row, const uword col)\n : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator&\nMat::const_row_col_iterator::operator++()\n {\n current_pos++;\n internal_row++;\n\n \/\/ Check to see if we moved a column.\n if(internal_row == M->n_rows)\n {\n internal_col++;\n internal_row = 0;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::const_row_col_iterator::operator++(int)\n {\n typename Mat::const_row_col_iterator temp(*this);\n\n ++(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator&\nMat::const_row_col_iterator::operator--()\n {\n if(internal_row > 0)\n {\n current_pos--;\n internal_row--;\n }\n else if(internal_col > 0)\n {\n current_pos--;\n internal_col--;\n internal_row = M->n_rows - 1;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::const_row_col_iterator::operator--(int)\n {\n typename Mat::const_row_col_iterator temp(*this);\n\n --(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator==(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::const_row_col_iterator::operator!=(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Mat::row_col_iterator implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator()\n : M(NULL), current_pos(NULL), internal_col(0), internal_row(0)\n {\n \/\/ Technically this iterator is invalid (it may not point to a real element)\n }\n\n\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator(const row_iterator& it)\n : M(&it.M), current_pos(&it.M(it.row, it.col)), internal_col(it.col), internal_row(it.row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline\nMat::row_col_iterator::row_col_iterator(Mat& in_M, const uword row, const uword col)\n : M(&in_M), current_pos(&in_M(row,col)), internal_col(col), internal_row(row)\n {\n \/\/ Nothing to do.\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator&\nMat::row_col_iterator::operator++()\n {\n current_pos++;\n internal_row++;\n\n \/\/ Check to see if we moved a column.\n if(internal_row == M->n_rows)\n {\n internal_col++;\n internal_row = 0;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::row_col_iterator::operator++(int)\n {\n typename Mat::row_col_iterator temp(*this);\n\n ++(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator&\nMat::row_col_iterator::operator--()\n {\n if(internal_row != 0)\n {\n current_pos--;\n internal_row--;\n }\n else if(internal_col != 0)\n {\n current_pos--;\n internal_col--;\n internal_row = M->n_rows - 1;\n }\n\n return *this;\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::row_col_iterator::operator--(int)\n {\n typename Mat::row_col_iterator temp(*this);\n\n --(*this);\n\n return temp;\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const row_col_iterator& rhs) const\n {\n return (rhs.current_pos != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const iterator& rhs) const\n {\n return (rhs == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const iterator& rhs) const\n {\n return (rhs != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const const_row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator==(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) == current_pos);\n }\n\n\n\ntemplate\ninline bool\nMat::row_col_iterator::operator!=(const row_iterator& rhs) const\n {\n return (&rhs.M(rhs.row, rhs.col) != current_pos);\n }\n\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ extended Mat functionality implementation \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::begin_row_col() const\n {\n return const_row_col_iterator(*this);\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::begin_row_col()\n {\n return row_col_iterator(*this);\n }\n\n\n\ntemplate\ninline typename Mat::const_row_col_iterator\nMat::end_row_col() const\n {\n return ++const_row_col_iterator(*this, n_rows - 1, n_cols - 1);\n }\n\n\n\ntemplate\ninline typename Mat::row_col_iterator\nMat::end_row_col()\n {\n return ++row_col_iterator(*this, n_rows - 1, n_cols - 1);\n }\n<|endoftext|>"} {"text":"\/*\n * producer_glaxnimate.cpp -- a Glaxnimate\/Qt based producer for MLT\n * Copyright (C) 2022 Meltytech, LLC\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"io\/io_registry.hpp\"\nusing namespace glaxnimate;\n\n\nclass Glaxnimate\n{\nprivate:\n mlt_producer m_producer = nullptr;\n std::unique_ptr m_document;\n\npublic:\n mlt_profile m_profile = nullptr;\n\n void setProducer( mlt_producer producer )\n { m_producer = producer; }\n\n mlt_producer producer() const\n { return m_producer; }\n\n mlt_service service() const\n { return MLT_PRODUCER_SERVICE(m_producer); }\n\n mlt_properties properties() const\n { return MLT_PRODUCER_PROPERTIES(m_producer); }\n\n QSize size() const { return m_document->size(); }\n\n int duration() const {\n auto frames = m_document->main()->animation->last_frame.get() - m_document->main()->animation->first_frame.get() + 1.f;\n return toMltFps(frames);\n }\n\n int toMltFps(float frame) const {\n return qRound(frame \/ fps() * m_profile->frame_rate_num \/ m_profile->frame_rate_den);\n }\n\n float toGlaxnimateFps(float frame) const {\n return frame * fps() * m_profile->frame_rate_den \/ m_profile->frame_rate_num;\n }\n\n int firstFrame() const {\n return toMltFps(m_document->main()->animation->first_frame.get());\n }\n\n float fps() const {\n return m_document->main()->get_fps();\n }\n\n int getImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable)\n {\n int error = 0;\n auto pos = mlt_frame_original_position(frame);\n if (mlt_properties_get(properties(), \"eof\") && !::strcmp(\"loop\", mlt_properties_get(properties(), \"eof\"))) {\n pos %= duration();\n }\n auto bg = mlt_properties_get_color(properties(), \"background\");\n auto background = QColor(bg.r, bg.g, bg.b, bg.a);\n pos += toMltFps(m_document->main()->animation->first_frame.get());\n auto image = m_document->render_image(toGlaxnimateFps(pos), {*width, *height}, background);\n\n *format = mlt_image_rgba;\n int size = mlt_image_format_size(*format, *width, *height, NULL);\n *buffer = static_cast(mlt_pool_alloc(size));\n memcpy(*buffer, image.constBits(), size);\n error = mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);\n\n return error;\n }\n\n bool open(const char* fileName)\n {\n auto filename = QString::fromUtf8(fileName);\n auto importer = io::IoRegistry::instance().from_filename(filename, io::ImportExport::Import);\n if (!importer || !importer->can_open()) {\n mlt_log_error(service(), \"Unknown importer\\n\");\n return false;\n }\n\n QFile file(filename);\n if (!file.open(QIODevice::ReadOnly)) {\n mlt_log_error(service(), \"Could not open input file for reading\\n\");\n return false;\n }\n\n m_document.reset(new model::Document(filename));\n QVariantMap settings;\n if (!importer->open(file, filename, m_document.get(), settings)) {\n mlt_log_error(service(), \"Error loading input file\\n\");\n return false;\n }\n\n return true;\n }\n};\n\nextern \"C\" {\n\nstatic int get_image(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable)\n{\n auto producer = static_cast(mlt_frame_pop_service(frame));\n auto glax = static_cast(producer->child);\n\n if (mlt_properties_get_int(glax->properties(), \"refresh\")) {\n mlt_properties_clear(glax->properties(), \"refresh\");\n glax->open(mlt_properties_get(glax->properties(), \"resource\"));\n if (glax->duration() > mlt_properties_get_int(glax->properties(), \"length\")) {\n mlt_properties_set_int(glax->properties(), \"length\", glax->duration());\n }\n }\n\n return glax->getImage(frame, buffer, format, width, height, writable);\n}\n\nstatic int get_frame(mlt_producer producer, mlt_frame_ptr frame, int index)\n{\n *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));\n mlt_properties frame_properties = MLT_FRAME_PROPERTIES( *frame );\n\n \/\/ Set frame properties\n mlt_properties_set_int(frame_properties, \"progressive\", 1);\n double force_ratio = mlt_properties_get_double(MLT_PRODUCER_PROPERTIES(producer), \"force_aspect_ratio\");\n if (force_ratio > 0.0)\n mlt_properties_set_double(frame_properties, \"aspect_ratio\", force_ratio);\n else\n mlt_properties_set_double(frame_properties, \"aspect_ratio\", 1.0);\n\n mlt_frame_set_position(*frame, mlt_producer_position(producer));\n mlt_frame_push_service(*frame, producer);\n mlt_frame_push_get_image(*frame, get_image);\n mlt_producer_prepare_next(producer);\n return 0;\n}\n\nstatic void producer_close(mlt_producer producer)\n{\n delete static_cast(producer->child);\n producer->close = nullptr;\n mlt_producer_close(producer);\n}\n\nmlt_producer producer_glaxnimate_init(mlt_profile profile, mlt_service_type type, const char *id, char *arg)\n{\n \/\/ Allocate the producer\n Glaxnimate* glax = new Glaxnimate();\n mlt_producer producer = (mlt_producer) calloc(1, sizeof( *producer ));\n\n \/\/ If allocated and initializes\n if (glax && !mlt_producer_init(producer, glax) && glax->open(arg)) {\n glax->setProducer(producer);\n glax->m_profile = profile;\n producer->close = (mlt_destructor) producer_close;\n producer->get_frame = get_frame;\n\n auto properties = glax->properties();\n mlt_properties_set(properties, \"resource\", arg);\n mlt_properties_set(properties, \"background\", \"#00000000\");\n mlt_properties_set_int(properties, \"aspect_ratio\", 1);\n mlt_properties_set_int(properties, \"progressive\", 1);\n mlt_properties_set_int(properties, \"seekable\", 1);\n mlt_properties_set_int(properties, \"meta.media.width\", glax->size().width());\n mlt_properties_set_int(properties, \"meta.media.height\", glax->size().height());\n mlt_properties_set_int(properties, \"meta.media.sample_aspect_num\", 1);\n mlt_properties_set_int(properties, \"meta.media.sample_aspect_den\", 1);\n mlt_properties_set_double(properties, \"meta.media.frame_rate\", glax->fps());\n mlt_properties_set_int(properties, \"out\", glax->duration() - 1);\n mlt_properties_set_int(properties, \"length\", glax->duration());\n mlt_properties_set_int(properties, \"first_frame\", glax->firstFrame());\n mlt_properties_set(properties, \"eof\", \"loop\");\n }\n return producer;\n}\n\nstatic mlt_properties metadata(mlt_service_type type, const char *id, void *data)\n{\n char file[PATH_MAX];\n const char *service_type = NULL;\n switch (type) {\n case mlt_service_producer_type:\n service_type = \"producer\";\n break;\n default:\n return NULL;\n }\n snprintf(file, PATH_MAX, \"%s\/glaxnimate\/%s_%s.yml\", mlt_environment(\"MLT_DATA\"), service_type, id);\n return mlt_properties_parse_yaml(file);\n}\n\nMLT_REPOSITORY\n{\n MLT_REGISTER(mlt_service_producer_type, \"glaxnimate\", producer_glaxnimate_init);\n MLT_REGISTER_METADATA(mlt_service_producer_type, \"glaxnimate\", metadata, NULL);\n}\n\n} \/\/ extern C\nglaxnimate: fix melt may fail without QApplication\/*\n * producer_glaxnimate.cpp -- a Glaxnimate\/Qt based producer for MLT\n * Copyright (C) 2022 Meltytech, LLC\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"io\/io_registry.hpp\"\nusing namespace glaxnimate;\n\n\nclass Glaxnimate\n{\nprivate:\n mlt_producer m_producer = nullptr;\n std::unique_ptr m_document;\n\npublic:\n mlt_profile m_profile = nullptr;\n\n void setProducer( mlt_producer producer )\n { m_producer = producer; }\n\n mlt_producer producer() const\n { return m_producer; }\n\n mlt_service service() const\n { return MLT_PRODUCER_SERVICE(m_producer); }\n\n mlt_properties properties() const\n { return MLT_PRODUCER_PROPERTIES(m_producer); }\n\n QSize size() const { return m_document->size(); }\n\n int duration() const {\n auto frames = m_document->main()->animation->last_frame.get() - m_document->main()->animation->first_frame.get() + 1.f;\n return toMltFps(frames);\n }\n\n int toMltFps(float frame) const {\n return qRound(frame \/ fps() * m_profile->frame_rate_num \/ m_profile->frame_rate_den);\n }\n\n float toGlaxnimateFps(float frame) const {\n return frame * fps() * m_profile->frame_rate_den \/ m_profile->frame_rate_num;\n }\n\n int firstFrame() const {\n return toMltFps(m_document->main()->animation->first_frame.get());\n }\n\n float fps() const {\n return m_document->main()->get_fps();\n }\n\n int getImage(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable)\n {\n int error = 0;\n auto pos = mlt_frame_original_position(frame);\n if (mlt_properties_get(properties(), \"eof\") && !::strcmp(\"loop\", mlt_properties_get(properties(), \"eof\"))) {\n pos %= duration();\n }\n auto bg = mlt_properties_get_color(properties(), \"background\");\n auto background = QColor(bg.r, bg.g, bg.b, bg.a);\n pos += toMltFps(m_document->main()->animation->first_frame.get());\n auto image = m_document->render_image(toGlaxnimateFps(pos), {*width, *height}, background);\n\n *format = mlt_image_rgba;\n int size = mlt_image_format_size(*format, *width, *height, NULL);\n *buffer = static_cast(mlt_pool_alloc(size));\n memcpy(*buffer, image.constBits(), size);\n error = mlt_frame_set_image(frame, *buffer, size, mlt_pool_release);\n\n return error;\n }\n\n bool open(const char* fileName)\n {\n auto filename = QString::fromUtf8(fileName);\n auto importer = io::IoRegistry::instance().from_filename(filename, io::ImportExport::Import);\n if (!importer || !importer->can_open()) {\n mlt_log_error(service(), \"Unknown importer\\n\");\n return false;\n }\n\n QFile file(filename);\n if (!file.open(QIODevice::ReadOnly)) {\n mlt_log_error(service(), \"Could not open input file for reading\\n\");\n return false;\n }\n\n m_document.reset(new model::Document(filename));\n QVariantMap settings;\n if (!importer->open(file, filename, m_document.get(), settings)) {\n mlt_log_error(service(), \"Error loading input file\\n\");\n return false;\n }\n\n return true;\n }\n};\n\nstatic bool createQApplicationIfNeeded(mlt_service service)\n{\n if (!qApp) {\n#if defined(Q_OS_WIN) && defined(NODEPLOY)\n QCoreApplication::addLibraryPath(QString(mlt_environment(\"MLT_APPDIR\"))+QStringLiteral(\"\/bin\"));\n QCoreApplication::addLibraryPath(QString(mlt_environment(\"MLT_APPDIR\"))+QStringLiteral(\"\/plugins\"));\n#endif\n#if defined(Q_OS_UNIX) && !defined(Q_OS_MAC)\n if (getenv(\"DISPLAY\") == 0) {\n mlt_log_error(service,\n \"The MLT Qt module requires a X11 environment.\\n\"\n \"Please either run melt from an X session or use a fake X server like xvfb:\\n\"\n \"xvfb-run -a melt (...)\\n\" );\n return false;\n }\n#endif\n if (!mlt_properties_get(mlt_global_properties(), \"qt_argv\"))\n mlt_properties_set(mlt_global_properties(), \"qt_argv\", \"MLT\");\n static int argc = 1;\n static char* argv[] = { mlt_properties_get(mlt_global_properties(), \"qt_argv\") };\n new QApplication(argc, argv);\n const char *localename = mlt_properties_get_lcnumeric(MLT_SERVICE_PROPERTIES(service));\n QLocale::setDefault(QLocale(localename));\n }\n return true;\n}\n\nextern \"C\" {\n\nstatic int get_image(mlt_frame frame, uint8_t **buffer, mlt_image_format *format, int *width, int *height, int writable)\n{\n auto producer = static_cast(mlt_frame_pop_service(frame));\n auto glax = static_cast(producer->child);\n\n if (mlt_properties_get_int(glax->properties(), \"refresh\")) {\n mlt_properties_clear(glax->properties(), \"refresh\");\n glax->open(mlt_properties_get(glax->properties(), \"resource\"));\n if (glax->duration() > mlt_properties_get_int(glax->properties(), \"length\")) {\n mlt_properties_set_int(glax->properties(), \"length\", glax->duration());\n }\n }\n\n return glax->getImage(frame, buffer, format, width, height, writable);\n}\n\nstatic int get_frame(mlt_producer producer, mlt_frame_ptr frame, int index)\n{\n *frame = mlt_frame_init(MLT_PRODUCER_SERVICE(producer));\n mlt_properties frame_properties = MLT_FRAME_PROPERTIES( *frame );\n\n \/\/ Set frame properties\n mlt_properties_set_int(frame_properties, \"progressive\", 1);\n double force_ratio = mlt_properties_get_double(MLT_PRODUCER_PROPERTIES(producer), \"force_aspect_ratio\");\n if (force_ratio > 0.0)\n mlt_properties_set_double(frame_properties, \"aspect_ratio\", force_ratio);\n else\n mlt_properties_set_double(frame_properties, \"aspect_ratio\", 1.0);\n\n mlt_frame_set_position(*frame, mlt_producer_position(producer));\n mlt_frame_push_service(*frame, producer);\n mlt_frame_push_get_image(*frame, get_image);\n mlt_producer_prepare_next(producer);\n return 0;\n}\n\nstatic void producer_close(mlt_producer producer)\n{\n delete static_cast(producer->child);\n producer->close = nullptr;\n mlt_producer_close(producer);\n}\n\nmlt_producer producer_glaxnimate_init(mlt_profile profile, mlt_service_type type, const char *id, char *arg)\n{\n \/\/ Allocate the producer\n Glaxnimate* glax = new Glaxnimate();\n mlt_producer producer = (mlt_producer) calloc(1, sizeof( *producer ));\n\n createQApplicationIfNeeded(MLT_PRODUCER_SERVICE(producer));\n\n \/\/ If allocated and initializes\n if (glax && !mlt_producer_init(producer, glax) && glax->open(arg)) {\n glax->setProducer(producer);\n glax->m_profile = profile;\n producer->close = (mlt_destructor) producer_close;\n producer->get_frame = get_frame;\n\n auto properties = glax->properties();\n mlt_properties_set(properties, \"resource\", arg);\n mlt_properties_set(properties, \"background\", \"#00000000\");\n mlt_properties_set_int(properties, \"aspect_ratio\", 1);\n mlt_properties_set_int(properties, \"progressive\", 1);\n mlt_properties_set_int(properties, \"seekable\", 1);\n mlt_properties_set_int(properties, \"meta.media.width\", glax->size().width());\n mlt_properties_set_int(properties, \"meta.media.height\", glax->size().height());\n mlt_properties_set_int(properties, \"meta.media.sample_aspect_num\", 1);\n mlt_properties_set_int(properties, \"meta.media.sample_aspect_den\", 1);\n mlt_properties_set_double(properties, \"meta.media.frame_rate\", glax->fps());\n mlt_properties_set_int(properties, \"out\", glax->duration() - 1);\n mlt_properties_set_int(properties, \"length\", glax->duration());\n mlt_properties_set_int(properties, \"first_frame\", glax->firstFrame());\n mlt_properties_set(properties, \"eof\", \"loop\");\n }\n return producer;\n}\n\nstatic mlt_properties metadata(mlt_service_type type, const char *id, void *data)\n{\n char file[PATH_MAX];\n const char *service_type = NULL;\n switch (type) {\n case mlt_service_producer_type:\n service_type = \"producer\";\n break;\n default:\n return NULL;\n }\n snprintf(file, PATH_MAX, \"%s\/glaxnimate\/%s_%s.yml\", mlt_environment(\"MLT_DATA\"), service_type, id);\n return mlt_properties_parse_yaml(file);\n}\n\nMLT_REPOSITORY\n{\n MLT_REGISTER(mlt_service_producer_type, \"glaxnimate\", producer_glaxnimate_init);\n MLT_REGISTER_METADATA(mlt_service_producer_type, \"glaxnimate\", metadata, NULL);\n}\n\n} \/\/ extern C\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright 2019 Sergei Blagodarin\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \n#include \n#include \"..\/formats.h\"\n\n#include \n#include \/\/ requires FILE declaration.\n\n#include \/\/ TODO: Load JPEG without libjpeg.\n\n#ifndef NDEBUG\n#\tinclude \n#\tinclude \n#endif\n\nnamespace\n{\n\tstruct JpegErrorHandler\n\t{\n\t\tjpeg_error_mgr _error_mgr;\n\t\tstd::jmp_buf _jmp_buf;\n\t};\n\n\t[[noreturn]] void error_callback(jpeg_common_struct* cinfo) {\n\t\tstd::longjmp(reinterpret_cast(cinfo->err)->_jmp_buf, 1);\n\t}\n\n#ifndef NDEBUG\n\tenum : std::uint8_t {\n\t\tTEM = 0x01, \/\/ Temporary.\n\t\tSOF0 = 0xc0, \/\/ Start-of-Frame (baseline DCT).\n\t\tSOF2 = 0xc2, \/\/ Start-of-Frame (progressive DCT).\n\t\tDHT = 0xc4, \/\/ Define-Huffman-Tables.\n\t\tDAC = 0xcc, \/\/ Define-Arithmetic-Coding.\n\t\tRST = 0xd0, \/\/ Restart (0-7).\n\t\tRST_mask = 0xf8, \/\/\n\t\tRST_value = 0x07, \/\/\n\t\tSOI = 0xd8, \/\/ Start-of-Image.\n\t\tEOI = 0xd9, \/\/ End-of-Image.\n\t\tSOS = 0xda, \/\/ Start-of-Scan.\n\t\tDQT = 0xdb, \/\/ Defile-Quantization-Tables.\n\t\tDNL = 0xdc, \/\/ Define-Number-of-Lines.\n\t\tDRI = 0xdd, \/\/ Define-Restart-Interval.\n\t\tDHP = 0xde, \/\/\n\t\tEXP = 0xdf, \/\/\n\t\tAPP = 0xe0, \/\/ Application (0-15).\n\t\tAPP_mask = 0xf0, \/\/\n\t\tAPP_value = 0x0f, \/\/\n\t\tCOM = 0xfe, \/\/ Comment.\n\t};\n\n\tclass JpegDecoder\n\t{\n\tpublic:\n\t\tbool decode(const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tif (!decode_jpeg(data, size))\n\t\t\t{\n\t\t\t\tstd::cerr << \"\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/ TODO: Convert the loaded image to BGRA.\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstd::size_t skip_segment(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\t<\" << segment_size << \" bytes>\\n\";\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_app(int type, const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"APP\" << type << \"\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_com(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"COM\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_dht(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DHT\\n\";\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size || segment_size < 3)\n\t\t\t\treturn 0;\n\t\t\tconst auto type = data[2] >> 4;\n\t\t\tconst auto id = data[2] & 0xf;\n\t\t\tif (type > 1 || id > 1)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\ttype=\" << (type ? \"ac\" : \"dc\") << '\\n';\n\t\t\tstd::cerr << \"\\tid=\" << id << '\\n';\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_dqt(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DQT\\n\";\n\t\t\tif (size < 67)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size != 67)\n\t\t\t\treturn 0;\n\t\t\tconst auto id = data[2];\n\t\t\tif (id > 1)\n\t\t\t\treturn 0;\n\t\t\tfor (std::size_t i = 0; i < 64; ++i)\n\t\t\t\t_quantization_tables[id][_dezigzag_table[i]] = data[3 + i];\n\t\t\tstd::cerr << \"\\tid=\" << int{ id } << '\\n';\n\t\t\tstd::cerr << \"\\tqt=\\n\";\n\t\t\tfor (int i = 0; i < 8; ++i)\n\t\t\t{\n\t\t\t\tstd::cerr << '\\t';\n\t\t\t\tfor (int j = 0; j < 8; ++j)\n\t\t\t\t\tstd::cerr << '\\t' << int{ _quantization_tables[id][i * 8 + j] };\n\t\t\t\tstd::cerr << '\\n';\n\t\t\t}\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_dri(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DRI\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_sof0(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"SOF0\\n\";\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size || segment_size < 8)\n\t\t\t\treturn 0;\n\t\t\tconst auto color_bits = data[2];\n\t\t\tconst auto width = data[3] << 8 | data[4];\n\t\t\tconst auto height = data[5] << 8 | data[6];\n\t\t\tconst auto components = std::size_t{ data[7] };\n\t\t\tif (segment_size != 8 + 3 * components)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\tcolor_bits=\" << int{ color_bits } << '\\n';\n\t\t\tstd::cerr << \"\\twidth=\" << width << '\\n';\n\t\t\tstd::cerr << \"\\theight=\" << height << '\\n';\n\t\t\tstd::cerr << \"\\tcomponents=\" << components << '\\n';\n\t\t\tfor (std::size_t i = 0; i < components; ++i)\n\t\t\t{\n\t\t\t\tconst auto id = data[8 + 3 * i];\n\t\t\t\tconst auto h = data[8 + 3 * i + 1] >> 4;\n\t\t\t\tconst auto v = data[8 + 3 * i + 1] & 0xf;\n\t\t\t\tconst auto qt = data[8 + 3 * i + 2];\n\t\t\t\tstd::cerr << \"\\t[\" << int{ id } << \"]\\n\";\n\t\t\t\tstd::cerr << \"\\t\\th=\" << h << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\tv=\" << v << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\tqt=\" << int{ qt } << '\\n';\n\t\t\t}\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_sos(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"SOS\\n\";\n\t\t\tif (size < 3)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size)\n\t\t\t\treturn 0;\n\t\t\tconst auto components = std::size_t{ data[2] };\n\t\t\tif (segment_size != 6 + 2 * components)\n\t\t\t\treturn 0;\n\t\t\tfor (std::size_t i = 0; i < components; ++i)\n\t\t\t{\n\t\t\t\tconst auto id = data[3 + 2 * i];\n\t\t\t\tconst auto dc = data[3 + 2 * i + 1] >> 4;\n\t\t\t\tconst auto ac = data[3 + 2 * i + 1] & 0xf;\n\t\t\t\tstd::cerr << \"\\t[\" << int{ id } << \"]\\n\";\n\t\t\t\tstd::cerr << \"\\t\\tdc=\" << dc << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\tac=\" << ac << '\\n';\n\t\t\t}\n\t\t\tif (data[3 + 2 * components] != 0 || data[3 + 2 * components + 1] != 63 || data[3 + 2 * components + 2] != 0)\n\t\t\t\treturn 0;\n\t\t\tconst auto payload_size = decode_payload(data + segment_size, size - segment_size);\n\t\t\tif (!payload_size)\n\t\t\t\treturn 0;\n\t\t\treturn segment_size + payload_size;\n\t\t}\n\n\t\tstd::size_t decode_payload(const std::uint8_t*, std::size_t)\n\t\t{\n\t\t\tstd::cerr << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\n\t\tstd::size_t decode_segment(std::uint8_t marker, const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tswitch (marker)\n\t\t\t{\n\t\t\tcase SOF0: return decode_sof0(data, size);\n\t\t\tcase DHT: return decode_dht(data, size);\n\t\t\tcase SOS: return decode_sos(data, size);\n\t\t\tcase DQT: return decode_dqt(data, size);\n\t\t\tcase DRI: return decode_dri(data, size);\n\t\t\tcase COM: return decode_com(data, size);\n\t\t\tdefault:\n\t\t\t\tif ((marker & APP_mask) == APP)\n\t\t\t\t\treturn decode_app(marker & APP_value, data, size);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\tbool decode_jpeg(const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tif (size < 2 || data[0] != 0xff || data[1] != SOI)\n\t\t\t\treturn false;\n\t\t\tdata += 2;\n\t\t\tsize -= 2;\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (size < 2 || data[0] != 0xff)\n\t\t\t\t\treturn false;\n\t\t\t\tconst auto marker = data[1];\n\t\t\t\tif (marker == EOI)\n\t\t\t\t\treturn true; \/\/ TODO: Return false if the buffer hasn't been decoded.\n\t\t\t\tdata += 2;\n\t\t\t\tsize -= 2;\n\t\t\t\tconst auto segment_size = decode_segment(marker, data, size);\n\t\t\t\tif (!segment_size)\n\t\t\t\t\treturn false; \/\/ TODO: Return true if the buffer has been decoded.\n\t\t\t\tdata += segment_size;\n\t\t\t\tsize -= segment_size;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\tprivate:\n\t\tstd::uint8_t _quantization_tables[2][64];\n\n\t\tstatic const std::uint8_t _dezigzag_table[64];\n\t};\n\n\tconst std::uint8_t JpegDecoder::_dezigzag_table[64]{\n\t\t0, 1, 8, 16, 9, 2, 3, 10,\n\t\t17, 24, 32, 25, 18, 11, 4, 5,\n\t\t12, 19, 26, 33, 40, 48, 41, 34,\n\t\t27, 20, 13, 6, 7, 14, 21, 28,\n\t\t35, 42, 49, 56, 57, 50, 43, 36,\n\t\t29, 22, 15, 23, 30, 37, 44, 51,\n\t\t58, 59, 52, 45, 38, 31, 39, 46,\n\t\t53, 60, 61, 54, 47, 55, 62, 63\n\t};\n#endif\n}\n\nnamespace Yttrium\n{\n\tbool read_jpeg(const Source& source, ImageInfo& info, Buffer& buffer)\n\t{\n#ifndef NDEBUG\n\t\t{\n\t\t\tconst auto jpeg = source.to_buffer();\n\t\t\tJpegDecoder{}.decode(jpeg.begin(), jpeg.size());\n\t\t}\n#endif\n\n\t\tauto source_buffer = source.to_buffer(); \/\/ Some JPEG libraries require non-const source buffer.\n\t\tif (source_buffer.size() > std::numeric_limits::max())\n\t\t\treturn false;\n\n\t\tJpegErrorHandler error_handler;\n\t\terror_handler._error_mgr.error_exit = ::error_callback;\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t\treturn false;\n\n\t\tjpeg_decompress_struct decompressor;\n\t\tdecompressor.err = ::jpeg_std_error(&error_handler._error_mgr);\n\t\t::jpeg_create_decompress(&decompressor);\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t{\n\t\t\t::jpeg_destroy_decompress(&decompressor);\n\t\t\treturn false;\n\t\t}\n\n\t\t::jpeg_mem_src(&decompressor, &source_buffer[0], static_cast(source_buffer.size()));\n\n\t\t::jpeg_read_header(&decompressor, TRUE);\n\n\t\tdecompressor.out_color_space = JCS_RGB;\n\n\t\t::jpeg_calc_output_dimensions(&decompressor);\n\n\t\tinfo = { decompressor.output_width, decompressor.output_height, PixelFormat::Rgb24 };\n\n\t\ttry\n\t\t{\n\t\t\tbuffer.reset(info.frame_size());\n\t\t}\n\t\tcatch (const std::bad_alloc&)\n\t\t{\n\t\t\t::jpeg_destroy_decompress(&decompressor);\n\t\t\tthrow;\n\t\t}\n\n\t\t::jpeg_start_decompress(&decompressor);\n\t\tfor (auto scanline = &buffer[0]; decompressor.output_scanline < decompressor.output_height; scanline += info.stride())\n\t\t\t::jpeg_read_scanlines(&decompressor, &scanline, 1);\n\t\t::jpeg_finish_decompress(&decompressor);\n\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t\treturn false;\n\n\t\t::jpeg_destroy_decompress(&decompressor);\n\n\t\treturn true;\n\t}\n}\nImprove JPEG analysis\/\/\n\/\/ Copyright 2019 Sergei Blagodarin\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#include \n#include \n#include \"..\/formats.h\"\n\n#include \n#include \/\/ requires FILE declaration.\n\n#include \/\/ TODO: Load JPEG without libjpeg.\n\n#ifndef NDEBUG\n#\tinclude \n#\tinclude \n#endif\n\nnamespace\n{\n\tstruct JpegErrorHandler\n\t{\n\t\tjpeg_error_mgr _error_mgr;\n\t\tstd::jmp_buf _jmp_buf;\n\t};\n\n\t[[noreturn]] void error_callback(jpeg_common_struct* cinfo) {\n\t\tstd::longjmp(reinterpret_cast(cinfo->err)->_jmp_buf, 1);\n\t}\n\n#ifndef NDEBUG\n\tenum : std::uint8_t {\n\t\tTEM = 0x01, \/\/ Temporary.\n\t\tSOF0 = 0xc0, \/\/ Start-of-Frame (baseline DCT).\n\t\tSOF2 = 0xc2, \/\/ Start-of-Frame (progressive DCT).\n\t\tDHT = 0xc4, \/\/ Define-Huffman-Tables.\n\t\tDAC = 0xcc, \/\/ Define-Arithmetic-Coding.\n\t\tRST = 0xd0, \/\/ Restart (0-7).\n\t\tRST_mask = 0xf8, \/\/\n\t\tRST_value = 0x07, \/\/\n\t\tSOI = 0xd8, \/\/ Start-of-Image.\n\t\tEOI = 0xd9, \/\/ End-of-Image.\n\t\tSOS = 0xda, \/\/ Start-of-Scan.\n\t\tDQT = 0xdb, \/\/ Defile-Quantization-Tables.\n\t\tDNL = 0xdc, \/\/ Define-Number-of-Lines.\n\t\tDRI = 0xdd, \/\/ Define-Restart-Interval.\n\t\tDHP = 0xde, \/\/\n\t\tEXP = 0xdf, \/\/\n\t\tAPP = 0xe0, \/\/ Application (0-15).\n\t\tAPP_mask = 0xf0, \/\/\n\t\tAPP_value = 0x0f, \/\/\n\t\tCOM = 0xfe, \/\/ Comment.\n\t};\n\n\tclass JpegDecoder\n\t{\n\tpublic:\n\t\tbool decode(const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tif (!decode_jpeg(data, size))\n\t\t\t{\n\t\t\t\tstd::cerr << \"\\n\";\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\/\/ TODO: Convert the loaded image to BGRA.\n\t\t\treturn true;\n\t\t}\n\n\tprivate:\n\t\tstd::size_t skip_segment(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\t<\" << segment_size << \" bytes>\\n\";\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_app(int type, const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"APP\" << type << \":\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_com(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"COM:\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_dht(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DHT:\\n\";\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size || segment_size < 19)\n\t\t\t\treturn 0;\n\t\t\tconst auto type = data[2] >> 4;\n\t\t\tconst auto id = data[2] & 0xf;\n\t\t\tif (type > 1 || id > 1)\n\t\t\t\treturn 0;\n\t\t\tconst std::uint8_t* bits = data + 3;\n\t\t\tstd::size_t length = 0;\n\t\t\tfor (std::size_t i = 0; i < 16; ++i)\n\t\t\t\tlength += bits[i];\n\t\t\tif (segment_size != 19 + length)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\ttype=\" << (type ? \"ac\" : \"dc\") << '\\n';\n\t\t\tstd::cerr << \"\\tid=\" << id << '\\n';\n\t\t\tstd::cerr << \"\\tbits\";\n\t\t\tfor (std::size_t i = 0; i < 16; ++i)\n\t\t\t\tstd::cerr << (i ? ',' : '=') << int{ bits[i] };\n\t\t\tstd::cerr << '\\n';\n\t\t\tauto huffman_values = bits + 16;\n\t\t\tfor (std::size_t i = 0; i < 16; ++i)\n\t\t\t{\n\t\t\t\tif (!bits[i])\n\t\t\t\t\tcontinue;\n\t\t\t\tstd::cerr << '\\t';\n\t\t\t\tfor (std::size_t j = 0; j < bits[i]; ++j)\n\t\t\t\t\tstd::cerr << (j ? ',' : '\\t') << int{ huffman_values[j] };\n\t\t\t\thuffman_values += bits[i];\n\t\t\t\tstd::cerr << '\\n';\n\t\t\t}\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_dqt(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DQT:\\n\";\n\t\t\tif (size < 67)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size != 67)\n\t\t\t\treturn 0;\n\t\t\tconst auto id = data[2];\n\t\t\tif (id > 1)\n\t\t\t\treturn 0;\n\t\t\tfor (std::size_t i = 0; i < 64; ++i)\n\t\t\t\t_quantization_tables[id][_dezigzag_table[i]] = data[3 + i];\n\t\t\tstd::cerr << \"\\tid=\" << int{ id } << '\\n';\n\t\t\tstd::cerr << \"\\tqt:\\n\";\n\t\t\tfor (int i = 0; i < 8; ++i)\n\t\t\t{\n\t\t\t\tstd::cerr << '\\t';\n\t\t\t\tfor (int j = 0; j < 8; ++j)\n\t\t\t\t\tstd::cerr << '\\t' << int{ _quantization_tables[id][i * 8 + j] };\n\t\t\t\tstd::cerr << '\\n';\n\t\t\t}\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_dri(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"DRI\\n\";\n\t\t\treturn skip_segment(data, size);\n\t\t}\n\n\t\tstd::size_t decode_sof0(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"SOF0:\\n\";\n\t\t\tif (size < 2)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size || segment_size < 8)\n\t\t\t\treturn 0;\n\t\t\tconst auto color_bits = data[2];\n\t\t\tconst auto width = data[3] << 8 | data[4];\n\t\t\tconst auto height = data[5] << 8 | data[6];\n\t\t\tconst auto components = std::size_t{ data[7] };\n\t\t\tif (segment_size != 8 + 3 * components)\n\t\t\t\treturn 0;\n\t\t\tstd::cerr << \"\\tcolor_bits=\" << int{ color_bits } << '\\n';\n\t\t\tstd::cerr << \"\\twidth=\" << width << '\\n';\n\t\t\tstd::cerr << \"\\theight=\" << height << '\\n';\n\t\t\tstd::cerr << \"\\tcomponents=\" << components << '\\n';\n\t\t\tfor (std::size_t i = 0; i < components; ++i)\n\t\t\t{\n\t\t\t\tconst auto id = data[8 + 3 * i];\n\t\t\t\tconst auto h = data[8 + 3 * i + 1] >> 4;\n\t\t\t\tconst auto v = data[8 + 3 * i + 1] & 0xf;\n\t\t\t\tconst auto qt = data[8 + 3 * i + 2];\n\t\t\t\tstd::cerr << \"\\t\\t\" << int{ id } << \":\\n\";\n\t\t\t\tstd::cerr << \"\\t\\t\\th=\" << h << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\t\\tv=\" << v << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\t\\tqt=\" << int{ qt } << '\\n';\n\t\t\t}\n\t\t\treturn segment_size;\n\t\t}\n\n\t\tstd::size_t decode_sos(const std::uint8_t* data, const std::size_t size)\n\t\t{\n\t\t\tstd::cerr << \"SOS:\\n\";\n\t\t\tif (size < 3)\n\t\t\t\treturn 0;\n\t\t\tconst auto segment_size = static_cast(data[0] << 8 | data[1]);\n\t\t\tif (segment_size > size)\n\t\t\t\treturn 0;\n\t\t\tconst auto components = std::size_t{ data[2] };\n\t\t\tif (segment_size != 6 + 2 * components)\n\t\t\t\treturn 0;\n\t\t\tfor (std::size_t i = 0; i < components; ++i)\n\t\t\t{\n\t\t\t\tconst auto id = data[3 + 2 * i];\n\t\t\t\tconst auto dc = data[3 + 2 * i + 1] >> 4;\n\t\t\t\tconst auto ac = data[3 + 2 * i + 1] & 0xf;\n\t\t\t\tstd::cerr << '\\t' << int{ id } << \":\\n\";\n\t\t\t\tstd::cerr << \"\\t\\tdc=\" << dc << '\\n';\n\t\t\t\tstd::cerr << \"\\t\\tac=\" << ac << '\\n';\n\t\t\t}\n\t\t\tif (data[3 + 2 * components] != 0 || data[3 + 2 * components + 1] != 63 || data[3 + 2 * components + 2] != 0)\n\t\t\t\treturn 0;\n\t\t\tconst auto payload_size = decode_payload(data + segment_size, size - segment_size);\n\t\t\tif (!payload_size)\n\t\t\t\treturn 0;\n\t\t\treturn segment_size + payload_size;\n\t\t}\n\n\t\tstd::size_t decode_payload(const std::uint8_t*, std::size_t)\n\t\t{\n\t\t\tstd::cerr << \"\\n\";\n\t\t\treturn 0;\n\t\t}\n\n\t\tstd::size_t decode_segment(std::uint8_t marker, const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tswitch (marker)\n\t\t\t{\n\t\t\tcase SOF0: return decode_sof0(data, size);\n\t\t\tcase DHT: return decode_dht(data, size);\n\t\t\tcase SOS: return decode_sos(data, size);\n\t\t\tcase DQT: return decode_dqt(data, size);\n\t\t\tcase DRI: return decode_dri(data, size);\n\t\t\tcase COM: return decode_com(data, size);\n\t\t\tdefault:\n\t\t\t\tif ((marker & APP_mask) == APP)\n\t\t\t\t\treturn decode_app(marker & APP_value, data, size);\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\n\t\tbool decode_jpeg(const std::uint8_t* data, std::size_t size)\n\t\t{\n\t\t\tif (size < 2 || data[0] != 0xff || data[1] != SOI)\n\t\t\t\treturn false;\n\t\t\tdata += 2;\n\t\t\tsize -= 2;\n\t\t\twhile (size > 0)\n\t\t\t{\n\t\t\t\tif (size < 2 || data[0] != 0xff)\n\t\t\t\t\treturn false;\n\t\t\t\tconst auto marker = data[1];\n\t\t\t\tif (marker == EOI)\n\t\t\t\t\treturn true; \/\/ TODO: Return false if the buffer hasn't been decoded.\n\t\t\t\tdata += 2;\n\t\t\t\tsize -= 2;\n\t\t\t\tconst auto segment_size = decode_segment(marker, data, size);\n\t\t\t\tif (!segment_size)\n\t\t\t\t\treturn false; \/\/ TODO: Return true if the buffer has been decoded.\n\t\t\t\tdata += segment_size;\n\t\t\t\tsize -= segment_size;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\n\tprivate:\n\t\tstd::uint8_t _quantization_tables[2][64];\n\n\t\tstatic const std::uint8_t _dezigzag_table[64];\n\t};\n\n\tconst std::uint8_t JpegDecoder::_dezigzag_table[64]{\n\t\t0, 1, 8, 16, 9, 2, 3, 10,\n\t\t17, 24, 32, 25, 18, 11, 4, 5,\n\t\t12, 19, 26, 33, 40, 48, 41, 34,\n\t\t27, 20, 13, 6, 7, 14, 21, 28,\n\t\t35, 42, 49, 56, 57, 50, 43, 36,\n\t\t29, 22, 15, 23, 30, 37, 44, 51,\n\t\t58, 59, 52, 45, 38, 31, 39, 46,\n\t\t53, 60, 61, 54, 47, 55, 62, 63\n\t};\n#endif\n}\n\nnamespace Yttrium\n{\n\tbool read_jpeg(const Source& source, ImageInfo& info, Buffer& buffer)\n\t{\n#ifndef NDEBUG\n\t\t{\n\t\t\tconst auto jpeg = source.to_buffer();\n\t\t\tJpegDecoder{}.decode(jpeg.begin(), jpeg.size());\n\t\t}\n#endif\n\n\t\tauto source_buffer = source.to_buffer(); \/\/ Some JPEG libraries require non-const source buffer.\n\t\tif (source_buffer.size() > std::numeric_limits::max())\n\t\t\treturn false;\n\n\t\tJpegErrorHandler error_handler;\n\t\terror_handler._error_mgr.error_exit = ::error_callback;\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t\treturn false;\n\n\t\tjpeg_decompress_struct decompressor;\n\t\tdecompressor.err = ::jpeg_std_error(&error_handler._error_mgr);\n\t\t::jpeg_create_decompress(&decompressor);\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t{\n\t\t\t::jpeg_destroy_decompress(&decompressor);\n\t\t\treturn false;\n\t\t}\n\n\t\t::jpeg_mem_src(&decompressor, &source_buffer[0], static_cast(source_buffer.size()));\n\n\t\t::jpeg_read_header(&decompressor, TRUE);\n\n\t\tdecompressor.out_color_space = JCS_RGB;\n\n\t\t::jpeg_calc_output_dimensions(&decompressor);\n\n\t\tinfo = { decompressor.output_width, decompressor.output_height, PixelFormat::Rgb24 };\n\n\t\ttry\n\t\t{\n\t\t\tbuffer.reset(info.frame_size());\n\t\t}\n\t\tcatch (const std::bad_alloc&)\n\t\t{\n\t\t\t::jpeg_destroy_decompress(&decompressor);\n\t\t\tthrow;\n\t\t}\n\n\t\t::jpeg_start_decompress(&decompressor);\n\t\tfor (auto scanline = &buffer[0]; decompressor.output_scanline < decompressor.output_height; scanline += info.stride())\n\t\t\t::jpeg_read_scanlines(&decompressor, &scanline, 1);\n\t\t::jpeg_finish_decompress(&decompressor);\n\n\t\tif (setjmp(error_handler._jmp_buf))\n\t\t\treturn false;\n\n\t\t::jpeg_destroy_decompress(&decompressor);\n\n\t\treturn true;\n\t}\n}\n<|endoftext|>"} {"text":"\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include \n#include \n#include \n\n#define TBB_PREVIEW_GLOBAL_CONTROL 1\n#define TBB_PREVIEW_FLOW_GRAPH_TRACE 1\n#include \n#include \n#include \n#include \"ngraph\/op\/experimental\/compiled_kernel.hpp\"\n\n#ifdef NGRAPH_MLIR_ENABLE\n#include \"contrib\/mlir\/compiler.hpp\"\n#endif\n\nnamespace mkldnn\n{\n class primitive;\n}\n\nnamespace ngraph\n{\n namespace runtime\n {\n class AlignedBuffer;\n }\n class State;\n}\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n typedef std::chrono::high_resolution_clock Clock;\n typedef std::chrono::time_point Timestamp;\n typedef std::chrono::microseconds Timescale;\n\n extern \"C\" {\n struct CPURuntimeContext\n {\n int64_t* op_durations;\n bool* p_en;\n bool first_iteration;\n \/\/ stores tensor pointers\n std::vector buffer_data;\n std::vector mkldnn_primitives;\n std::vector memory_buffers;\n std::vector mkldnn_workspaces;\n tbb::flow::graph* G;\n tbb::global_control* c;\n State* const* states;\n std::set breakpoints;\n size_t pc;\n#ifdef NGRAPH_MLIR_ENABLE\n \/\/\/ Maps CompiledKernel nodes to their MLIR compiler\n \/\/\/ The MLIR compiler caches the compiled code on the first invocation, \n \/\/\/ and may in the future support re-compilation\n std::unordered_map\n mlir_compilers;\n#endif\n };\n }\n\n struct CPUExecutionContext\n {\n int arena;\n };\n\n typedef std::function CPUKernelFunctor;\n }\n }\n}\nstyle-apply\/\/*****************************************************************************\n\/\/ Copyright 2017-2019 Intel Corporation\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/*****************************************************************************\n\n#pragma once\n\n#include \n#include \n#include \n\n#define TBB_PREVIEW_GLOBAL_CONTROL 1\n#define TBB_PREVIEW_FLOW_GRAPH_TRACE 1\n#include \n#include \n#include \n#include \"ngraph\/op\/experimental\/compiled_kernel.hpp\"\n\n#ifdef NGRAPH_MLIR_ENABLE\n#include \"contrib\/mlir\/compiler.hpp\"\n#endif\n\nnamespace mkldnn\n{\n class primitive;\n}\n\nnamespace ngraph\n{\n namespace runtime\n {\n class AlignedBuffer;\n }\n class State;\n}\n\nnamespace ngraph\n{\n namespace runtime\n {\n namespace cpu\n {\n typedef std::chrono::high_resolution_clock Clock;\n typedef std::chrono::time_point Timestamp;\n typedef std::chrono::microseconds Timescale;\n\n extern \"C\" {\n struct CPURuntimeContext\n {\n int64_t* op_durations;\n bool* p_en;\n bool first_iteration;\n \/\/ stores tensor pointers\n std::vector buffer_data;\n std::vector mkldnn_primitives;\n std::vector memory_buffers;\n std::vector mkldnn_workspaces;\n tbb::flow::graph* G;\n tbb::global_control* c;\n State* const* states;\n std::set breakpoints;\n size_t pc;\n#ifdef NGRAPH_MLIR_ENABLE\n \/\/\/ Maps CompiledKernel nodes to their MLIR compiler\n \/\/\/ The MLIR compiler caches the compiled code on the first invocation,\n \/\/\/ and may in the future support re-compilation\n std::unordered_map\n mlir_compilers;\n#endif\n };\n }\n\n struct CPUExecutionContext\n {\n int arena;\n };\n\n typedef std::function CPUKernelFunctor;\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"elements\/element.h\"\n\n#include \n#include \n\n#include \"elements\/package.h\"\n\nnamespace elements {\n\nvoid Element::serialize(Element::Json &a_json)\n{\n a_json[\"id\"] = m_id;\n a_json[\"name\"] = m_name;\n a_json[\"type\"] = type();\n auto &node = a_json[\"node\"];\n node[\"position\"][\"x\"] = m_position.x;\n node[\"position\"][\"y\"] = m_position.y;\n node[\"iconify\"] = m_isIconified;\n auto &sockets = a_json[\"sockets\"];\n auto &inputs = sockets[\"inputs\"];\n inputs[\"min\"] = m_minInputs;\n inputs[\"max\"] = m_maxInputs;\n auto &outputs = sockets[\"outputs\"];\n outputs[\"min\"] = m_minOutputs;\n outputs[\"max\"] = m_maxOutputs;\n}\n\nvoid Element::deserialize(Json const &a_json)\n{\n std::cout << __PRETTY_FUNCTION__ << '>' << std::endl;\n\n auto const tempId = a_json[\"id\"].get();\n auto const tempName = a_json[\"name\"].get();\n auto const tempPosition = a_json[\"position\"];\n auto const tempIconify = a_json[\"iconify\"].get();\n auto const tempPositionX = tempPosition[\"x\"].get();\n auto const tempPositionY = tempPosition[\"y\"].get();\n auto const tempInputs = a_json[\"inputs\"];\n auto const tempMinInputs = tempInputs[\"min\"].get();\n auto const tempMaxInputs = tempInputs[\"max\"].get();\n auto const tempInputsSockets = tempInputs[\"sockets\"];\n auto const tempOutputs = a_json[\"outputs\"];\n auto const tempMinOutputs = tempOutputs[\"min\"].get();\n auto const tempMaxOutputs = tempOutputs[\"max\"].get();\n auto const tempOutputsSockets = tempOutputs[\"sockets\"];\n\n assert(id() == tempId);\n setName(tempName);\n setPosition(tempPositionX, tempPositionY);\n clearInputs();\n clearOutputs();\n setMinInputs(tempMinInputs);\n setMaxInputs(tempMaxInputs);\n setMinOutputs(tempMinOutputs);\n setMaxOutputs(tempMaxOutputs);\n iconify(tempIconify);\n\n auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) {\n auto const socketId = a_socket[\"socket\"].get();\n auto const socketStringType = a_socket[\"type\"].get();\n auto const socketName = a_socket[\"name\"].get();\n\n assert(a_socketCount == socketId);\n\n ValueType const socketType = [](std::string_view const a_type) {\n if (a_type == \"bool\")\n return ValueType::eBool;\n else if (a_type == \"int\")\n return ValueType::eInt;\n else if (a_type == \"float\")\n return ValueType::eFloat;\n assert(false && \"Wrong socket type\");\n }(socketStringType);\n\n a_input ? addInput(socketType, socketName) : addOutput(socketType, socketName);\n a_socketCount++;\n };\n\n uint8_t inputsCount{}, outputsCount{};\n for (auto &&socket : tempInputsSockets) add_socket(socket, true, inputsCount);\n for (auto &&socket : tempOutputsSockets) add_socket(socket, false, outputsCount);\n\n std::cout << __PRETTY_FUNCTION__ << '<' << std::endl;\n}\n\nbool Element::addInput(Element::ValueType const a_type, std::string const a_name)\n{\n if (m_inputs.size() + 1 > m_maxInputs) return false;\n\n Input input{};\n input.name = a_name;\n input.type = a_type;\n m_inputs.emplace_back(input);\n\n return true;\n}\n\nvoid Element::clearInputs()\n{\n m_inputs.clear();\n}\n\nbool Element::addOutput(Element::ValueType const a_type, std::string const a_name)\n{\n if (m_outputs.size() + 1 > m_maxOutputs) return false;\n\n Output output{};\n output.name = a_name;\n output.type = a_type;\n m_outputs.emplace_back(output);\n\n return true;\n}\n\nvoid Element::clearOutputs()\n{\n m_outputs.clear();\n}\n\nbool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId)\n{\n return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId);\n}\n\nvoid Element::setMinInputs(uint8_t const a_min)\n{\n if (a_min > m_maxInputs) return;\n m_minInputs = a_min;\n}\n\nvoid Element::setMaxInputs(uint8_t const a_max)\n{\n if (a_max < m_minInputs) return;\n m_maxInputs = a_max;\n}\n\nvoid Element::setMinOutputs(uint8_t const a_min)\n{\n if (a_min > m_maxOutputs) return;\n m_minOutputs = a_min;\n}\n\nvoid Element::setMaxOutputs(uint8_t const a_max)\n{\n if (a_max < m_minOutputs) return;\n m_maxOutputs = a_max;\n}\n\n} \/\/ namespace elements\nSilence GCC on MinGW\/\/ MIT License\n\/\/\n\/\/ Copyright (c) 2017 Artur Wyszyński, aljen at hitomi dot pl\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"elements\/element.h\"\n\n#include \n#include \n\n#include \"elements\/package.h\"\n\nnamespace elements {\n\nvoid Element::serialize(Element::Json &a_json)\n{\n a_json[\"id\"] = m_id;\n a_json[\"name\"] = m_name;\n a_json[\"type\"] = type();\n auto &node = a_json[\"node\"];\n node[\"position\"][\"x\"] = m_position.x;\n node[\"position\"][\"y\"] = m_position.y;\n node[\"iconify\"] = m_isIconified;\n auto &sockets = a_json[\"sockets\"];\n auto &inputs = sockets[\"inputs\"];\n inputs[\"min\"] = m_minInputs;\n inputs[\"max\"] = m_maxInputs;\n auto &outputs = sockets[\"outputs\"];\n outputs[\"min\"] = m_minOutputs;\n outputs[\"max\"] = m_maxOutputs;\n}\n\nvoid Element::deserialize(Json const &a_json)\n{\n std::cout << __PRETTY_FUNCTION__ << '>' << std::endl;\n\n auto const tempId = a_json[\"id\"].get();\n auto const tempName = a_json[\"name\"].get();\n auto const tempPosition = a_json[\"position\"];\n auto const tempIconify = a_json[\"iconify\"].get();\n auto const tempPositionX = tempPosition[\"x\"].get();\n auto const tempPositionY = tempPosition[\"y\"].get();\n auto const tempInputs = a_json[\"inputs\"];\n auto const tempMinInputs = tempInputs[\"min\"].get();\n auto const tempMaxInputs = tempInputs[\"max\"].get();\n auto const tempInputsSockets = tempInputs[\"sockets\"];\n auto const tempOutputs = a_json[\"outputs\"];\n auto const tempMinOutputs = tempOutputs[\"min\"].get();\n auto const tempMaxOutputs = tempOutputs[\"max\"].get();\n auto const tempOutputsSockets = tempOutputs[\"sockets\"];\n\n assert(id() == tempId);\n setName(tempName);\n setPosition(tempPositionX, tempPositionY);\n clearInputs();\n clearOutputs();\n setMinInputs(tempMinInputs);\n setMaxInputs(tempMaxInputs);\n setMinOutputs(tempMinOutputs);\n setMaxOutputs(tempMaxOutputs);\n iconify(tempIconify);\n\n auto add_socket = [&](Json const &a_socket, bool const a_input, uint8_t &a_socketCount) {\n auto const socketId = a_socket[\"socket\"].get();\n auto const socketStringType = a_socket[\"type\"].get();\n auto const socketName = a_socket[\"name\"].get();\n\n assert(a_socketCount == socketId);\n\n ValueType const socketType = [](std::string_view const a_type) {\n if (a_type == \"bool\")\n return ValueType::eBool;\n else if (a_type == \"int\")\n return ValueType::eInt;\n else if (a_type == \"float\")\n return ValueType::eFloat;\n assert(false && \"Wrong socket type\");\n return ValueType::eBool;\n }(socketStringType);\n\n a_input ? addInput(socketType, socketName) : addOutput(socketType, socketName);\n a_socketCount++;\n };\n\n uint8_t inputsCount{}, outputsCount{};\n for (auto &&socket : tempInputsSockets) add_socket(socket, true, inputsCount);\n for (auto &&socket : tempOutputsSockets) add_socket(socket, false, outputsCount);\n\n std::cout << __PRETTY_FUNCTION__ << '<' << std::endl;\n}\n\nbool Element::addInput(Element::ValueType const a_type, std::string const a_name)\n{\n if (m_inputs.size() + 1 > m_maxInputs) return false;\n\n Input input{};\n input.name = a_name;\n input.type = a_type;\n m_inputs.emplace_back(input);\n\n return true;\n}\n\nvoid Element::clearInputs()\n{\n m_inputs.clear();\n}\n\nbool Element::addOutput(Element::ValueType const a_type, std::string const a_name)\n{\n if (m_outputs.size() + 1 > m_maxOutputs) return false;\n\n Output output{};\n output.name = a_name;\n output.type = a_type;\n m_outputs.emplace_back(output);\n\n return true;\n}\n\nvoid Element::clearOutputs()\n{\n m_outputs.clear();\n}\n\nbool Element::connect(size_t const a_sourceId, uint8_t const a_outputId, uint8_t const a_inputId)\n{\n return m_package->connect(a_sourceId, a_outputId, m_id, a_inputId);\n}\n\nvoid Element::setMinInputs(uint8_t const a_min)\n{\n if (a_min > m_maxInputs) return;\n m_minInputs = a_min;\n}\n\nvoid Element::setMaxInputs(uint8_t const a_max)\n{\n if (a_max < m_minInputs) return;\n m_maxInputs = a_max;\n}\n\nvoid Element::setMinOutputs(uint8_t const a_min)\n{\n if (a_min > m_maxOutputs) return;\n m_minOutputs = a_min;\n}\n\nvoid Element::setMaxOutputs(uint8_t const a_max)\n{\n if (a_max < m_minOutputs) return;\n m_maxOutputs = a_max;\n}\n\n} \/\/ namespace elements\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 Bernhard Firner and Rutgers University\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n * or visit http:\/\/www.gnu.org\/licenses\/gpl-2.0.html\n *\/\n\n\/*******************************************************************************\n * Helper classes that make it easier for world models to support standing\n * queries.\n ******************************************************************************\/\n\n#ifndef __STANDING_QUERY_HPP__\n#define __STANDING_QUERY_HPP__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/TODO In the future C++11 support for regex should be used over these POSIX\n\/\/regex c headers.\n#include \n#include \n\n\/**\n * Standing queries are used when the same query would be repeated many times.\n * The standing query call returns an object that can be used to retrieve\n * any updates to the query since the last time it was checked. If this object\n * is destroyed then it ends the standing query.\n *\/\nclass StandingQuery {\n public:\n typedef std::map> world_state;\n private:\n \/\/Need to lock this mutex before changing the current state\n std::mutex data_mutex;\n \/\/Place where the world model will store data for this standing query.\n world_state cur_state;\n \/\/Remember which URIs and attributes match this query\n \/\/For attributes remember which of the desired attributes they matched\n std::map uri_accepted;\n std::map> uri_matches;\n \/\/Remember accepted attributes so that the standing query can notify\n \/\/the subscriber when identifiers and attributes are expired or deleted\n \/\/The data_mutex must be locked before modifying this structure\n std::map> current_matches;\n \/\/\/This contains empty sets for entries without matches\n std::map> attribute_accepted;\n world_model::URI uri_pattern;\n std::vector desired_attributes;\n regex_t uri_regex;\n std::map attr_regex;\n bool get_data;\n bool regex_valid;\n\n \/\/\/Mutex for the origin_attributes map\n static std::mutex origin_attr_mutex;\n \/\/\/Attributes that different origin's will offer\n static std::map> origin_attributes;\n\n \/\/No copying or assignment. Deleting the copy constructor prevents passing\n \/\/by value which would cause trouble with the compiled regex and the mutex.\n StandingQuery& operator=(const StandingQuery&) = delete;\n StandingQuery(const StandingQuery&) = delete;\n\n \/\/Partial matches (some attributes matched, but not all)\n \/\/Partial matches are stored so that when a complete match is made they\n \/\/can be sent and also so that a match can be quickly rechecked if\n \/\/attributes are deleted or expired.\n world_state partial;\n public:\n \/**\n * Update the list of attributes provided by origins.\n *\/\n static void addOriginAttributes(std::u16string& origin, std::set& attributes);\n\n StandingQuery(const world_model::URI& uri,\n const std::vector& desired_attributes, bool get_data = true);\n\n \/\/\/Free memory from regular expressions\n ~StandingQuery();\n\n \/\/\/r-value copy constructor\n StandingQuery(StandingQuery&& other);\n\n \/\/\/r-value assignment\n StandingQuery& operator=(StandingQuery&& other);\n\n \/**\n * Return true if this origin has data that this standing query might\n * be interested in and false otherwise.\n *\/\n bool interestingOrigin(std::u16string& origin);\n\n \/**\n * Return a subset of the world state that this query is interested in.\n * Also remember partial matches so that later calls to showInterested\n * do not need to provide the entire world state. This call can\n * quickly check if any data is interesting by seeing if the origin\n * itself is interesting, but will skip this if the world state\n * contains data from multiple origins.\n *\/\n world_state showInterested(world_state& ws, bool multiple_origins = false);\n\n \/**\n * Return a subset of the world state that this query is interested in.\n * This is similar to showInterested but enforced exact string matches\n * for transient names and does not store transients as partial results.\n * This call can * quickly check if any data is interesting by seeing if\n * the origin itself is interesting, but will skip this if the world state\n * contains data from multiple origins.\n *\/\n world_state showInterestedTransient(world_state& ws, bool multiple_origins = false);\n\n \/**\n * Return a subset of the world state that would be modified if the\n * supplied URI is expired or deleted.\n *\/\n void expireURI(world_model::URI uri, world_model::grail_time);\n\n \/**\n * Return a subset of the world state that would be modified if the\n * supplied URI attributes are expired or deleted.\n *\/\n void expireURIAttributes(world_model::URI uri,\n const std::vector& entries,\n world_model::grail_time);\n\n \/**\n * Insert data in a thread safe way\n * Data is not checked to see if it matches the given\n * query first so the caller must check that first, on their own\n * or with the showInterested function call.\n *\/\n void insertData(world_state& ws);\n\n \/\/\/Clear the current data and return what it stored. Thread safe.\n world_state getData();\n};\n\nclass QueryAccessor {\n private:\n \/**\n * Need to remember the source list to remove the iterator\n * when this object is destroyed.\n *\/\n std::list* source;\n std::mutex* list_mutex;\n \/\/\/List iterators are safe to changes in the underlying list\n std::list::iterator data;\n\n \/\/No copying or assignment. Deleting the copy constructor prevents passing\n \/\/by value would cause trouble when the destructor removes this iterator\n \/\/from the source list.\n QueryAccessor& operator=(const QueryAccessor&) = delete;\n QueryAccessor(const QueryAccessor&) = delete;\n\n public:\n \/**\n * Gets updates and clears the current state\n * This should be thread safe in the StandingQuery class\n *\/\n StandingQuery::world_state getUpdates();\n\n QueryAccessor(std::list* source, std::mutex* list_mutex,\n std::list::iterator data);\n\n \/\/\/Remove the iterator from the source list.\n ~QueryAccessor();\n\n \/\/\/r-value copy constructor\n QueryAccessor(QueryAccessor&& other);\n\n \/\/\/r-value assignment\n QueryAccessor& operator=(QueryAccessor&& other);\n};\n\n#endif \/\/ifndef __STANDING_QUERY_HPP__\n\n\nPutting in scaffolding for mergine the StandingQuery and QueryAccessor classes.\/*\n * Copyright (c) 2012 Bernhard Firner and Rutgers University\n * All rights reserved.\n *\n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU General Public License\n * as published by the Free Software Foundation; either version 2\n * of the License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n * or visit http:\/\/www.gnu.org\/licenses\/gpl-2.0.html\n *\/\n\n\/*******************************************************************************\n * Helper classes that make it easier for world models to support standing\n * queries.\n ******************************************************************************\/\n\n#ifndef __STANDING_QUERY_HPP__\n#define __STANDING_QUERY_HPP__\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/Lock-free queue for pushing and consuming data\n#include \n\n\/\/TODO In the future C++11 support for regex should be used over these POSIX\n\/\/regex c headers.\n#include \n#include \n\n\/**\n * Standing queries are used when the same query would be repeated many times.\n * The standing query call returns an object that can be used to retrieve\n * any updates to the query since the last time it was checked. If this object\n * is destroyed then it ends the standing query.\n *\/\nclass StandingQuery {\n public:\n typedef std::map> world_state;\n private:\n \/\/Need to lock this mutex before changing the current state\n std::mutex data_mutex;\n \/\/Place where the world model will store data for this standing query.\n world_state cur_state;\n \/\/Remember which URIs and attributes match this query\n \/\/For attributes remember which of the desired attributes they matched\n std::map uri_accepted;\n std::map> uri_matches;\n \/\/Remember accepted attributes so that the standing query can notify\n \/\/the subscriber when identifiers and attributes are expired or deleted\n \/\/The data_mutex must be locked before modifying this structure\n std::map> current_matches;\n \/\/\/This contains empty sets for entries without matches\n std::map> attribute_accepted;\n world_model::URI uri_pattern;\n std::vector desired_attributes;\n regex_t uri_regex;\n std::map attr_regex;\n bool get_data;\n bool regex_valid;\n\n \/\/\/Mutex for the origin_attributes map\n static std::mutex origin_attr_mutex;\n \/\/\/Attributes that different origin's will offer\n static std::map> origin_attributes;\n\n \/\/No copying or assignment. Deleting the copy constructor prevents passing\n \/\/by value which would cause trouble with the compiled regex and the mutex.\n StandingQuery& operator=(const StandingQuery&) = delete;\n StandingQuery(const StandingQuery&) = delete;\n\n \/\/Partial matches (some attributes matched, but not all)\n \/\/Partial matches are stored so that when a complete match is made they\n \/\/can be sent and also so that a match can be quickly rechecked if\n \/\/attributes are deleted or expired.\n world_state partial;\n public:\n \/**\n * Update the list of attributes provided by origins.\n *\/\n static void addOriginAttributes(std::u16string& origin, std::set& attributes);\n\n StandingQuery(const world_model::URI& uri,\n const std::vector& desired_attributes, bool get_data = true);\n\n \/\/\/Free memory from regular expressions\n ~StandingQuery();\n\n \/\/\/r-value copy constructor\n StandingQuery(StandingQuery&& other);\n\n \/\/\/r-value assignment\n StandingQuery& operator=(StandingQuery&& other);\n\n \/**\n * Return true if this origin has data that this standing query might\n * be interested in and false otherwise.\n *\/\n bool interestingOrigin(std::u16string& origin);\n\n \/**\n * Return a subset of the world state that this query is interested in.\n * Also remember partial matches so that later calls to showInterested\n * do not need to provide the entire world state. This call can\n * quickly check if any data is interesting by seeing if the origin\n * itself is interesting, but will skip this if the world state\n * contains data from multiple origins.\n *\/\n world_state showInterested(world_state& ws, bool multiple_origins = false);\n\n \/**\n * Return a subset of the world state that this query is interested in.\n * This is similar to showInterested but enforced exact string matches\n * for transient names and does not store transients as partial results.\n * This call can * quickly check if any data is interesting by seeing if\n * the origin itself is interesting, but will skip this if the world state\n * contains data from multiple origins.\n *\/\n world_state showInterestedTransient(world_state& ws, bool multiple_origins = false);\n\n \/**\n * Return a subset of the world state that would be modified if the\n * supplied URI is expired or deleted.\n *\/\n void expireURI(world_model::URI uri, world_model::grail_time);\n\n \/**\n * Return a subset of the world state that would be modified if the\n * supplied URI attributes are expired or deleted.\n *\/\n void expireURIAttributes(world_model::URI uri,\n const std::vector& entries,\n world_model::grail_time);\n\n \/**\n * Insert data in a thread safe way\n * Data is not checked to see if it matches the given\n * query first so the caller must check that first, on their own\n * or with the showInterested function call.\n *\/\n void insertData(world_state& ws);\n\n \/\/\/Clear the current data and return what it stored. Thread safe.\n world_state getData();\n};\n\n\/\/TODO Merge into standing query class, make standing query functions static\nclass QueryAccessor {\n private:\n \/\/\/Incoming data from solvers, disseminated by the pushThread function\n static boost::lockfree::queue incoming_data;\n\n std::mutex subscription_mutex;\n static std::set subscriptions;\n\n \/**\n * Need to remember the source list to remove the iterator\n * when this object is destroyed.\n *\/\n std::list* source;\n std::mutex* list_mutex;\n \/\/\/List iterators are safe to changes in the underlying list\n std::list::iterator data;\n\n \/\/No copying or assignment. Deleting the copy constructor prevents passing\n \/\/by value would cause trouble when the destructor removes this iterator\n \/\/from the source list.\n QueryAccessor& operator=(const QueryAccessor&) = delete;\n QueryAccessor(const QueryAccessor&) = delete;\n\n public:\n \/**\n * Gets updates and clears the current state\n * This should be thread safe in the StandingQuery class\n *\/\n StandingQuery::world_state getUpdates();\n\n \/**\n * TODO Create a new standing query, adding itself to the list of\n * subscriptions.\n *\/\n QueryAccessor(const world_model::URI& uri,\n const std::vector& desired_attributes, bool get_data = true);\n\n \/\/\/Remove this accessor from the subscription list\n ~QueryAccessor();\n\n \/\/\/r-value copy constructor\n QueryAccessor(QueryAccessor&& other);\n\n \/\/\/r-value assignment\n QueryAccessor& operator=(QueryAccessor&& other);\n\n \/**\n * Function that moves incoming data to the queues of class instances\n * from the incoming data queue.\n *\/ \n static void pushThread();\n\n \/**\n * Expire the supplied URI at the given time.\n *\/\n static bool expireURI(world_model::URI uri, world_model::grail_time);\n\n \/**\n * Expire the given URI's specified attributes at the given time.\n *\/\n static bool expireURIAttributes(world_model::URI uri,\n const std::vector& entries,\n world_model::grail_time);\n\n \/**\n * Push new data from a solver to any interested standing queries.\n *\/\n static bool pushData(world_state& ws);\n};\n\n#endif \/\/ifndef __STANDING_QUERY_HPP__\n\n\n<|endoftext|>"} {"text":"Fix for PointsPolygons with out of order indice lists.<|endoftext|>"} {"text":"\/*=========================================================================\n\nLibrary: TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ It is important to use OrientedImages\n#include \"itkOrientedImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n\/\/ The following three should be used in every CLI application\n#include \"tubeMessage.h\"\n#include \"tubeCLIFilterWatcher.h\"\n#include \"tubeCLIProgressReporter.h\"\n#include \"itkTimeProbesCollectorBase.h\"\n\n\/\/ Includes specific to this CLI application\n#include \"itkImageRegionIteratorWithIndex.h\"\n\n\/\/ Must do a forward declaraction of DoIt before including\n\/\/ tubeCLIHelperFunctions\ntemplate< class pixelT, unsigned int dimensionT >\nint DoIt( int argc, char * argv[] );\n\n\/\/ Must include CLP before including tubeCLIHleperFunctions\n#include \"MergeCLP.h\"\n\n\/\/ Includes tube::ParseArgsAndCallDoIt function\n#include \"tubeCLIHelperFunctions.h\"\n\n\/\/ Your code should be within the DoIt function...\ntemplate< class pixelT, unsigned int dimensionT >\nint DoIt( int argc, char * argv[] )\n{\n PARSE_ARGS;\n\n \/\/ The timeCollector is used to perform basic profiling of the components\n \/\/ of your algorithm.\n itk::TimeProbesCollectorBase timeCollector;\n \n \/\/ CLIProgressReporter is used to communicate progress with the Slicer GUI\n tube::CLIProgressReporter progressReporter( \"Merge\",\n CLPProcessInformation );\n progressReporter.Start();\n\n typedef pixelT PixelType;\n typedef itk::Image< PixelType, dimensionT > ImageType;\n typedef itk::ImageFileReader< ImageType > ReaderType;\n \n timeCollector.Start(\"Load data\");\n\n typename ReaderType::Pointer reader1 = ReaderType::New();\n reader1->SetFileName( inputVolume1.c_str() );\n try\n {\n reader1->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n\n timeCollector.Stop(\"Load data\");\n\n typename ImageType::Pointer curImage1 = reader1->GetOutput();\n typename ImageType::Pointer outImage = ImageType::New();\n outImage->CopyInformation( curImage1 );\n typename ImageType::PointType origin = curImage1->GetOrigin();\n typename ImageType::SpacingType spacing = curImage1->GetSpacing();\n\n typename ImageType::PointType pointX;\n typename ImageType::IndexType indexX;\n \n typename ImageType::IndexType minX1Org;\n minX1Org = curImage1->GetLargestPossibleRegion().GetIndex();\n typename ImageType::SizeType size1 = curImage1->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX1Org;\n for( unsigned int i=0; iSetFileName( inputVolume2[imageNum].c_str() );\n try\n {\n reader2->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Stop(\"Load data\");\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n timeCollector.Stop(\"Load data\");\n\n progress += 1.0\/(double)inputVolume2.size() * 0.4;\n progressReporter.Report( progress );\n \n typename ImageType::Pointer curImage2 = reader2->GetOutput();\n \n typename ImageType::IndexType minX2;\n typename ImageType::IndexType minX2Org;\n minX2Org = curImage2->GetLargestPossibleRegion().GetIndex();\n curImage2->TransformIndexToPhysicalPoint( minX2Org, pointX );\n curImage1->TransformPhysicalPointToIndex( pointX, minX2 );\n typename ImageType::SizeType size2 = curImage2->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX2;\n typename ImageType::IndexType maxX2Org;\n for( unsigned int i=0; iTransformIndexToPhysicalPoint( maxX2Org, pointX );\n curImage1->TransformPhysicalPointToIndex( pointX, maxX2 );\n\n for( unsigned int i=0; i maxXOut[i] )\n {\n maxXOut[i] = minX2[i];\n }\n if( maxX2[i] > maxXOut[i] )\n {\n maxXOut[i] = maxX2[i];\n }\n }\n\n for( unsigned int i=0; i\n GetLargestPossibleRegion();\n regionOut.SetSize( sizeOut );\n regionOut.SetIndex( minXOut );\n outImage->SetRegions( regionOut );\n outImage->Allocate();\n outImage->FillBuffer( background );\n\n if( useBoundary )\n {\n for( unsigned int i=0; i iter( curImage1,\n curImage1->GetLargestPossibleRegion() );\n while( !iter.IsAtEnd() )\n {\n indexX = iter.GetIndex();\n bool useTf1 = true;\n if( !firstImageSpecial && useBoundary )\n {\n for( unsigned int i=0; imaxX1Org[i] )\n {\n useTf1 = false;\n break;\n }\n }\n }\n if( useTf1 )\n {\n outImage->SetPixel( indexX, iter.Get() );\n }\n ++iter;\n }\n progress += 0.1;\n progressReporter.Report( progress );\n\n for( unsigned int imageNum=0; imageNumSetFileName( inputVolume2[imageNum].c_str() );\n try\n {\n reader2->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Stop(\"Load data\");\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n typename ImageType::Pointer curImage2 = reader2->GetOutput();\n timeCollector.Stop(\"Load data\");\n\n typename ImageType::IndexType minX2Org;\n minX2Org = curImage2->GetLargestPossibleRegion().GetIndex();\n typename ImageType::SizeType size2 = curImage2->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX2Org;\n for( unsigned int i=0; i iter2( curImage2,\n curImage2->GetLargestPossibleRegion() );\n iter2.GoToBegin();\n typename ImageType::IndexType indexX2;\n while( !iter2.IsAtEnd() )\n {\n indexX2 = iter2.GetIndex();\n bool useTf2 = true;\n if( useBoundary )\n {\n for( unsigned int i=0; imaxX2Org[i] )\n {\n useTf2 = false;\n break;\n }\n }\n }\n if( useTf2 )\n {\n double tf2 = iter2.Get();\n curImage2->TransformIndexToPhysicalPoint( indexX2, pointX );\n if( outImage->TransformPhysicalPointToIndex( pointX, indexX ) )\n {\n if( average )\n {\n double tf1 = outImage->GetPixel( indexX );\n if( tf1 != background )\n {\n tf1 = ( tf2 + tf1 ) \/ 2.0;\n }\n else\n {\n tf1 = tf2;\n }\n outImage->SetPixel( indexX, tf1 );\n }\n else\n {\n outImage->SetPixel( indexX, tf2 );\n }\n }\n }\n ++iter2;\n }\n progress += 1.0\/(double)inputVolume2.size() * 0.19;\n progressReporter.Report( progress );\n }\n\n timeCollector.Start(\"Save data\");\n typedef itk::ImageFileWriter< ImageType > ImageWriterType;\n typename ImageWriterType::Pointer writer = ImageWriterType::New();\n writer->SetFileName( outputVolume.c_str() );\n writer->SetInput( outImage );\n writer->SetUseCompression( true );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Writing volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n timeCollector.Stop(\"Save data\");\n progress = 1.0;\n progressReporter.Report( progress );\n progressReporter.End( );\n \n timeCollector.Report();\n return EXIT_SUCCESS;\n}\n\n\/\/ Main\nint main( int argc, char **argv )\n{\n PARSE_ARGS;\n\n \/\/ You may need to update this line if, in the project's .xml CLI file,\n \/\/ you change the variable name for the inputVolume.\n return tube::ParseArgsAndCallDoIt( inputVolume1, argc, argv );\n}\nBUG: Possible uninitialized variable (if only merging one image).\/*=========================================================================\n\nLibrary: TubeTK\n\nCopyright 2010 Kitware Inc. 28 Corporate Drive,\nClifton Park, NY, 12065, USA.\n\nAll rights reserved. \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n=========================================================================*\/\n\n#if defined(_MSC_VER)\n#pragma warning ( disable : 4786 )\n#endif\n\n#ifdef __BORLANDC__\n#define ITK_LEAN_AND_MEAN\n#endif\n\n\/\/ It is important to use OrientedImages\n#include \"itkOrientedImage.h\"\n#include \"itkImageFileReader.h\"\n#include \"itkImageFileWriter.h\"\n\n\/\/ The following three should be used in every CLI application\n#include \"tubeMessage.h\"\n#include \"tubeCLIFilterWatcher.h\"\n#include \"tubeCLIProgressReporter.h\"\n#include \"itkTimeProbesCollectorBase.h\"\n\n\/\/ Includes specific to this CLI application\n#include \"itkImageRegionIteratorWithIndex.h\"\n\n\/\/ Must do a forward declaraction of DoIt before including\n\/\/ tubeCLIHelperFunctions\ntemplate< class pixelT, unsigned int dimensionT >\nint DoIt( int argc, char * argv[] );\n\n\/\/ Must include CLP before including tubeCLIHleperFunctions\n#include \"MergeCLP.h\"\n\n\/\/ Includes tube::ParseArgsAndCallDoIt function\n#include \"tubeCLIHelperFunctions.h\"\n\n\/\/ Your code should be within the DoIt function...\ntemplate< class pixelT, unsigned int dimensionT >\nint DoIt( int argc, char * argv[] )\n{\n PARSE_ARGS;\n\n \/\/ The timeCollector is used to perform basic profiling of the components\n \/\/ of your algorithm.\n itk::TimeProbesCollectorBase timeCollector;\n \n \/\/ CLIProgressReporter is used to communicate progress with the Slicer GUI\n tube::CLIProgressReporter progressReporter( \"Merge\",\n CLPProcessInformation );\n progressReporter.Start();\n\n typedef pixelT PixelType;\n typedef itk::Image< PixelType, dimensionT > ImageType;\n typedef itk::ImageFileReader< ImageType > ReaderType;\n \n timeCollector.Start(\"Load data\");\n\n typename ReaderType::Pointer reader1 = ReaderType::New();\n reader1->SetFileName( inputVolume1.c_str() );\n try\n {\n reader1->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n\n timeCollector.Stop(\"Load data\");\n\n typename ImageType::Pointer curImage1 = reader1->GetOutput();\n typename ImageType::Pointer outImage = ImageType::New();\n outImage->CopyInformation( curImage1 );\n typename ImageType::PointType origin = curImage1->GetOrigin();\n typename ImageType::SpacingType spacing = curImage1->GetSpacing();\n\n typename ImageType::PointType pointX;\n typename ImageType::IndexType indexX;\n \n typename ImageType::IndexType minX1Org;\n minX1Org = curImage1->GetLargestPossibleRegion().GetIndex();\n typename ImageType::SizeType size1 = curImage1->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX1Org;\n for( unsigned int i=0; iSetFileName( inputVolume2[imageNum].c_str() );\n try\n {\n reader2->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Stop(\"Load data\");\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n timeCollector.Stop(\"Load data\");\n\n progress += 1.0\/(double)inputVolume2.size() * 0.4;\n progressReporter.Report( progress );\n \n typename ImageType::Pointer curImage2 = reader2->GetOutput();\n \n typename ImageType::IndexType minX2;\n typename ImageType::IndexType minX2Org;\n minX2Org = curImage2->GetLargestPossibleRegion().GetIndex();\n curImage2->TransformIndexToPhysicalPoint( minX2Org, pointX );\n curImage1->TransformPhysicalPointToIndex( pointX, minX2 );\n typename ImageType::SizeType size2 = curImage2->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX2;\n typename ImageType::IndexType maxX2Org;\n for( unsigned int i=0; iTransformIndexToPhysicalPoint( maxX2Org, pointX );\n curImage1->TransformPhysicalPointToIndex( pointX, maxX2 );\n\n for( unsigned int i=0; i maxXOut[i] )\n {\n maxXOut[i] = minX2[i];\n }\n if( maxX2[i] > maxXOut[i] )\n {\n maxXOut[i] = maxX2[i];\n }\n }\n\n for( unsigned int i=0; i\n GetLargestPossibleRegion();\n regionOut.SetSize( sizeOut );\n regionOut.SetIndex( minXOut );\n outImage->SetRegions( regionOut );\n outImage->Allocate();\n outImage->FillBuffer( background );\n\n if( useBoundary )\n {\n for( unsigned int i=0; i iter( curImage1,\n curImage1->GetLargestPossibleRegion() );\n while( !iter.IsAtEnd() )\n {\n indexX = iter.GetIndex();\n bool useTf1 = true;\n if( !firstImageSpecial && useBoundary )\n {\n for( unsigned int i=0; imaxX1Org[i] )\n {\n useTf1 = false;\n break;\n }\n }\n }\n if( useTf1 )\n {\n outImage->SetPixel( indexX, iter.Get() );\n }\n ++iter;\n }\n progress += 0.1;\n progressReporter.Report( progress );\n\n for( unsigned int imageNum=0; imageNumSetFileName( inputVolume2[imageNum].c_str() );\n try\n {\n reader2->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Reading volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Stop(\"Load data\");\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n typename ImageType::Pointer curImage2 = reader2->GetOutput();\n timeCollector.Stop(\"Load data\");\n\n typename ImageType::IndexType minX2Org;\n minX2Org = curImage2->GetLargestPossibleRegion().GetIndex();\n typename ImageType::SizeType size2 = curImage2->\n GetLargestPossibleRegion().\n GetSize();\n typename ImageType::IndexType maxX2Org;\n for( unsigned int i=0; i iter2( curImage2,\n curImage2->GetLargestPossibleRegion() );\n iter2.GoToBegin();\n typename ImageType::IndexType indexX2;\n while( !iter2.IsAtEnd() )\n {\n indexX2 = iter2.GetIndex();\n bool useTf2 = true;\n if( useBoundary )\n {\n for( unsigned int i=0; imaxX2Org[i] )\n {\n useTf2 = false;\n break;\n }\n }\n }\n if( useTf2 )\n {\n double tf2 = iter2.Get();\n curImage2->TransformIndexToPhysicalPoint( indexX2, pointX );\n if( outImage->TransformPhysicalPointToIndex( pointX, indexX ) )\n {\n if( average )\n {\n double tf1 = outImage->GetPixel( indexX );\n if( tf1 != background )\n {\n tf1 = ( tf2 + tf1 ) \/ 2.0;\n }\n else\n {\n tf1 = tf2;\n }\n outImage->SetPixel( indexX, tf1 );\n }\n else\n {\n outImage->SetPixel( indexX, tf2 );\n }\n }\n }\n ++iter2;\n }\n progress += 1.0\/(double)inputVolume2.size() * 0.19;\n progressReporter.Report( progress );\n }\n\n timeCollector.Start(\"Save data\");\n typedef itk::ImageFileWriter< ImageType > ImageWriterType;\n typename ImageWriterType::Pointer writer = ImageWriterType::New();\n writer->SetFileName( outputVolume.c_str() );\n writer->SetInput( outImage );\n writer->SetUseCompression( true );\n try\n {\n writer->Update();\n }\n catch( itk::ExceptionObject & err )\n {\n tube::ErrorMessage( \"Writing volume: Exception caught: \" \n + std::string(err.GetDescription()) );\n timeCollector.Report();\n return EXIT_FAILURE;\n }\n timeCollector.Stop(\"Save data\");\n progress = 1.0;\n progressReporter.Report( progress );\n progressReporter.End( );\n \n timeCollector.Report();\n return EXIT_SUCCESS;\n}\n\n\/\/ Main\nint main( int argc, char **argv )\n{\n PARSE_ARGS;\n\n \/\/ You may need to update this line if, in the project's .xml CLI file,\n \/\/ you change the variable name for the inputVolume.\n return tube::ParseArgsAndCallDoIt( inputVolume1, argc, argv );\n}\n<|endoftext|>"} {"text":"\/*\n Copyright 2016 Nervana Systems Inc.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#pragma once\n\n#include \"manifest.hpp\"\n#include \"buffer.hpp\"\n#include \"batch_loader.hpp\"\n\n\/* BatchFileLoader\n *\n * Loads blocks of files from a manifest into a Buffer.\n *\n * TODO: rename to BatchFileLoader since there is no temporal blocking\n * being done here, only a batch of file loads\n *\/\nclass BatchFileLoader : public BatchLoader {\npublic:\n BatchFileLoader(Manifest* manifest);\n\n void loadBlock(BufferPair& dest, uint block_num, uint block_size);\n void loadFile(Buffer* buff, const string& filename);\n\nprivate:\n off_t getSize(const string& filename);\n \n const Manifest* _manifest;\n};\nremove completed TODO\/*\n Copyright 2016 Nervana Systems Inc.\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#pragma once\n\n#include \"manifest.hpp\"\n#include \"buffer.hpp\"\n#include \"batch_loader.hpp\"\n\n\/* BatchFileLoader\n *\n * Loads blocks of files from a manifest into a Buffer.\n *\n *\/\nclass BatchFileLoader : public BatchLoader {\npublic:\n BatchFileLoader(Manifest* manifest);\n\n void loadBlock(BufferPair& dest, uint block_num, uint block_size);\n void loadFile(Buffer* buff, const string& filename);\n\nprivate:\n off_t getSize(const string& filename);\n \n const Manifest* _manifest;\n};\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n\nnamespace storm {\n\nnamespace {\n\n\/\/ glTexImage*D functions require pixel format and pixel type even when no\n\/\/ pixel data is specified.\n\nstruct PixelDescription {\n GLenum format;\n GLenum type;\n};\n\nPixelDescription getCompatiblePixelDescription( GLenum internalFormat ) {\n static const std::map mapping = {\n {GL_R8, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_R8_SNORM, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_R16, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_R16_SNORM, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_RG8, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_RG8_SNORM, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_RG16, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_RG16_SNORM, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_R3_G3_B2, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB4, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB5, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB8, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB8_SNORM, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB10, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB12, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB16_SNORM, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGBA2, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGBA4, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB5_A1, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGBA8, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGBA8_SNORM, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGB10_A2, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGB10_A2UI, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGBA12, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGBA16, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_SRGB8, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_SRGB8_ALPHA8, {GL_RGBA, GL_UNSIGNED_BYTE}},\n\n {GL_R16F, {GL_RED, GL_FLOAT}},\n {GL_RG16F, {GL_RG, GL_FLOAT}},\n {GL_RGB16F, {GL_RGB, GL_FLOAT}},\n {GL_RGBA16F, {GL_RGBA, GL_FLOAT}},\n {GL_R32F, {GL_RED, GL_FLOAT}},\n {GL_RG32F, {GL_RG, GL_FLOAT}},\n {GL_RGB32F, {GL_RGB, GL_FLOAT}},\n {GL_RGBA32F, {GL_RGBA, GL_FLOAT}},\n {GL_R11F_G11F_B10F, {GL_RGB, GL_FLOAT}},\n {GL_RGB9_E5, {GL_RGB, GL_FLOAT}},\n\n {GL_R8I, {GL_RED_INTEGER, GL_INT}},\n {GL_R8UI, {GL_RED_INTEGER, GL_UNSIGNED_INT}},\n {GL_R16I, {GL_RED_INTEGER, GL_INT}},\n {GL_R16UI, {GL_RED_INTEGER, GL_UNSIGNED_INT}},\n {GL_R32I, {GL_RED_INTEGER, GL_INT}},\n {GL_R32UI, {GL_RED_INTEGER, GL_UNSIGNED_INT}},\n {GL_RG8I, {GL_RG_INTEGER, GL_INT}},\n {GL_RG8UI, {GL_RG_INTEGER, GL_UNSIGNED_INT}},\n {GL_RG16I, {GL_RG_INTEGER, GL_INT}},\n {GL_RG16UI, {GL_RG_INTEGER, GL_UNSIGNED_INT}},\n {GL_RG32I, {GL_RG_INTEGER, GL_INT}},\n {GL_RG32UI, {GL_RG_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGB8I, {GL_RGB_INTEGER, GL_INT}},\n {GL_RGB8UI, {GL_RGB_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGB16I, {GL_RGB_INTEGER, GL_INT}},\n {GL_RGB16UI, {GL_RGB_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGB32I, {GL_RGB_INTEGER, GL_INT}},\n {GL_RGB32UI, {GL_RGB_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGBA8I, {GL_RGBA_INTEGER, GL_INT}},\n {GL_RGBA8UI, {GL_RGBA_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGBA16I, {GL_RGBA_INTEGER, GL_INT}},\n {GL_RGBA16UI, {GL_RGBA_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGBA32I, {GL_RGBA_INTEGER, GL_INT}},\n {GL_RGBA32UI, {GL_RGBA_INTEGER, GL_UNSIGNED_INT}},\n\n {GL_DEPTH_COMPONENT16, {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}},\n {GL_DEPTH_COMPONENT24, {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}},\n {GL_DEPTH_COMPONENT32, {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}},\n {GL_DEPTH_COMPONENT32F, {GL_DEPTH_COMPONENT, GL_FLOAT}},\n {GL_DEPTH24_STENCIL8, {GL_DEPTH_STENCIL, GL_UNSIGNED_INT}},\n {GL_DEPTH32F_STENCIL8, {GL_DEPTH_STENCIL, GL_FLOAT}},\n {GL_STENCIL_INDEX8, {GL_STENCIL_INDEX, GL_UNSIGNED_INT}},\n\n {GL_COMPRESSED_RED, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RG, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RGB, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RGBA, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_SRGB, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_SRGB_ALPHA, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RED_RGTC1, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_SIGNED_RED_RGTC1, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RG_RGTC2, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_SIGNED_RG_RGTC2, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RGBA_BPTC_UNORM, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, {GL_RGB, GL_FLOAT}},\n {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, {GL_RGB, GL_FLOAT}},\n \/\/ {GL_COMPRESSED_RGB_S3TC_DXT1_EXT, {GL_RGB, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, {GL_RGB, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}},\n \/\/ {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, {GL_RGBA, GL_UNSIGNED_BYTE}}\n };\n storm_assert( mapping.count(internalFormat) );\n return mapping.at( internalFormat );\n}\n\n}\n\nvoid APIENTRY glTexStorage1D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage1D( target, level, internalFormat, width, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage1D\" );\n\n width = std::max( 1, (width \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage2D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width, GLsizei height )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage2D( target, level, internalFormat, width, height, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage2D\" );\n\n width = std::max( 1, (width \/ 2) );\n if( target != GL_TEXTURE_1D_ARRAY )\n height = std::max( 1, (height \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage3D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage3D( target, level, internalFormat, width, height, depth, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage3D\" );\n\n width = std::max( 1, (width \/ 2) );\n height = std::max( 1, (height \/ 2) );\n if( target != GL_TEXTURE_2D_ARRAY )\n depth = std::max( 1, (depth \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage2DMultisample( GLenum target,\n GLsizei samples,\n GLenum internalFormat,\n GLsizei width,\n GLsizei height,\n GLboolean fixedSampleLocations )\n{\n ::glTexImage2DMultisample(\n target, samples, internalFormat, width, height, fixedSampleLocations );\n}\n\nvoid APIENTRY glTexStorage3DMultisample( GLenum target,\n GLsizei samples,\n GLenum internalFormat,\n GLsizei width,\n GLsizei height,\n GLsizei depth,\n GLboolean fixedSampleLocations )\n{\n ::glTexStorage3DMultisample( target, samples, internalFormat,\n width, height, depth, fixedSampleLocations );\n}\n\n}\nFixed texture format to pixel format mapping#include \n\n#include \n#include \n\n#include \n\nnamespace storm {\n\nnamespace {\n\n\/\/ glTexImage*D functions require pixel format and pixel type even when no\n\/\/ pixel data is specified.\n\nstruct PixelDescription {\n GLenum format;\n GLenum type;\n};\n\nPixelDescription getCompatiblePixelDescription( GLenum internalFormat ) {\n static const std::map mapping = {\n {GL_R8, {GL_RED, GL_UNSIGNED_BYTE}},\n {GL_R8_SNORM, {GL_RED, GL_BYTE}},\n {GL_R16, {GL_RED, GL_UNSIGNED_SHORT}},\n {GL_R16_SNORM, {GL_RED, GL_SHORT}},\n {GL_RG8, {GL_RG, GL_UNSIGNED_BYTE}},\n {GL_RG8_SNORM, {GL_RG, GL_BYTE}},\n {GL_RG16, {GL_RG, GL_UNSIGNED_SHORT}},\n {GL_RG16_SNORM, {GL_RG, GL_SHORT}},\n {GL_R3_G3_B2, {GL_RGB, GL_UNSIGNED_BYTE_3_3_2}},\n {GL_RGB4, {GL_RGB, GL_UNSIGNED_SHORT_5_6_5}},\n {GL_RGB5, {GL_RGB, GL_UNSIGNED_SHORT_5_6_5}},\n {GL_RGB8, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_RGB8_SNORM, {GL_RGB, GL_BYTE}},\n {GL_RGB10, {GL_RGB, GL_UNSIGNED_SHORT}},\n {GL_RGB12, {GL_RGB, GL_UNSIGNED_SHORT}},\n {GL_RGB16_SNORM, {GL_RGB, GL_SHORT}},\n {GL_RGBA2, {GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4}},\n {GL_RGBA4, {GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4}},\n {GL_RGB5_A1, {GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1}},\n {GL_RGBA8, {GL_RGBA, GL_UNSIGNED_BYTE}},\n {GL_RGBA8_SNORM, {GL_RGBA, GL_BYTE}},\n {GL_RGB10_A2, {GL_RGBA, GL_UNSIGNED_INT_10_10_10_2}},\n {GL_RGB10_A2UI, {GL_RGBA_INTEGER, GL_UNSIGNED_INT_10_10_10_2}},\n {GL_RGBA12, {GL_RGBA, GL_UNSIGNED_SHORT}},\n {GL_RGBA16, {GL_RGBA, GL_UNSIGNED_SHORT}},\n {GL_SRGB8, {GL_RGB, GL_UNSIGNED_BYTE}},\n {GL_SRGB8_ALPHA8, {GL_RGBA, GL_UNSIGNED_BYTE}},\n\n {GL_R16F, {GL_RED, GL_HALF_FLOAT}},\n {GL_RG16F, {GL_RG, GL_HALF_FLOAT}},\n {GL_RGB16F, {GL_RGB, GL_HALF_FLOAT}},\n {GL_RGBA16F, {GL_RGBA, GL_HALF_FLOAT}},\n {GL_R32F, {GL_RED, GL_FLOAT}},\n {GL_RG32F, {GL_RG, GL_FLOAT}},\n {GL_RGB32F, {GL_RGB, GL_FLOAT}},\n {GL_RGBA32F, {GL_RGBA, GL_FLOAT}},\n {GL_R11F_G11F_B10F, {GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV}},\n {GL_RGB9_E5, {GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV}},\n\n {GL_R8I, {GL_RED_INTEGER, GL_BYTE}},\n {GL_R8UI, {GL_RED_INTEGER, GL_UNSIGNED_BYTE}},\n {GL_R16I, {GL_RED_INTEGER, GL_SHORT}},\n {GL_R16UI, {GL_RED_INTEGER, GL_UNSIGNED_SHORT}},\n {GL_R32I, {GL_RED_INTEGER, GL_INT}},\n {GL_R32UI, {GL_RED_INTEGER, GL_UNSIGNED_INT}},\n {GL_RG8I, {GL_RG_INTEGER, GL_BYTE}},\n {GL_RG8UI, {GL_RG_INTEGER, GL_UNSIGNED_BYTE}},\n {GL_RG16I, {GL_RG_INTEGER, GL_SHORT}},\n {GL_RG16UI, {GL_RG_INTEGER, GL_UNSIGNED_SHORT}},\n {GL_RG32I, {GL_RG_INTEGER, GL_INT}},\n {GL_RG32UI, {GL_RG_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGB8I, {GL_RGB_INTEGER, GL_BYTE}},\n {GL_RGB8UI, {GL_RGB_INTEGER, GL_UNSIGNED_BYTE}},\n {GL_RGB16I, {GL_RGB_INTEGER, GL_SHORT}},\n {GL_RGB16UI, {GL_RGB_INTEGER, GL_UNSIGNED_SHORT}},\n {GL_RGB32I, {GL_RGB_INTEGER, GL_INT}},\n {GL_RGB32UI, {GL_RGB_INTEGER, GL_UNSIGNED_INT}},\n {GL_RGBA8I, {GL_RGBA_INTEGER, GL_BYTE}},\n {GL_RGBA8UI, {GL_RGBA_INTEGER, GL_UNSIGNED_BYTE}},\n {GL_RGBA16I, {GL_RGBA_INTEGER, GL_SHORT}},\n {GL_RGBA16UI, {GL_RGBA_INTEGER, GL_UNSIGNED_SHORT}},\n {GL_RGBA32I, {GL_RGBA_INTEGER, GL_INT}},\n {GL_RGBA32UI, {GL_RGBA_INTEGER, GL_UNSIGNED_INT}},\n\n {GL_DEPTH_COMPONENT16, {GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT}},\n {GL_DEPTH_COMPONENT24, {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}},\n {GL_DEPTH_COMPONENT32, {GL_DEPTH_COMPONENT, GL_UNSIGNED_INT}},\n {GL_DEPTH_COMPONENT32F, {GL_DEPTH_COMPONENT, GL_FLOAT}},\n {GL_DEPTH24_STENCIL8, {GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8}},\n {GL_DEPTH32F_STENCIL8, {GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV}},\n {GL_STENCIL_INDEX8, {GL_STENCIL_INDEX, GL_UNSIGNED_BYTE}}\n };\n storm_assert( mapping.count(internalFormat) );\n return mapping.at( internalFormat );\n}\n\n\/\/ TODO: support compressed texture formats\n\/\/ GL_COMPRESSED_RED\n\/\/ GL_COMPRESSED_RG\n\/\/ GL_COMPRESSED_RGB\n\/\/ GL_COMPRESSED_RGBA\n\/\/ GL_COMPRESSED_SRGB\n\/\/ GL_COMPRESSED_SRGB_ALPHA\n\/\/ GL_COMPRESSED_RED_RGTC1\n\/\/ GL_COMPRESSED_SIGNED_RED_RGTC1\n\/\/ GL_COMPRESSED_RG_RGTC2\n\/\/ GL_COMPRESSED_SIGNED_RG_RGTC2\n\/\/ GL_COMPRESSED_RGBA_BPTC_UNORM\n\/\/ GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM\n\/\/ GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT\n\/\/ GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT\n\/\/ GL_COMPRESSED_RGB_S3TC_DXT1_EXT\n\/\/ GL_COMPRESSED_SRGB_S3TC_DXT1_EXT\n\/\/ GL_COMPRESSED_RGBA_S3TC_DXT1_EXT\n\/\/ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT\n\/\/ GL_COMPRESSED_RGBA_S3TC_DXT3_EXT\n\/\/ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT\n\/\/ GL_COMPRESSED_RGBA_S3TC_DXT5_EXT\n\/\/ GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT\n\n}\n\nvoid APIENTRY glTexStorage1D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage1D( target, level, internalFormat, width, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage1D\" );\n\n width = std::max( 1, (width \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage2D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width, GLsizei height )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage2D( target, level, internalFormat, width, height, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage2D\" );\n\n width = std::max( 1, (width \/ 2) );\n if( target != GL_TEXTURE_1D_ARRAY )\n height = std::max( 1, (height \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage3D( GLenum target, GLsizei levels,\n GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth )\n{\n for( GLsizei level = 0; level < levels; ++level ) {\n const PixelDescription pixelDescription =\n getCompatiblePixelDescription( internalFormat );\n\n ::glTexImage3D( target, level, internalFormat, width, height, depth, 0,\n pixelDescription.format, pixelDescription.type, nullptr );\n checkResult( \"::glTexImage3D\" );\n\n width = std::max( 1, (width \/ 2) );\n height = std::max( 1, (height \/ 2) );\n if( target != GL_TEXTURE_2D_ARRAY )\n depth = std::max( 1, (depth \/ 2) );\n }\n}\n\nvoid APIENTRY glTexStorage2DMultisample( GLenum target,\n GLsizei samples,\n GLenum internalFormat,\n GLsizei width,\n GLsizei height,\n GLboolean fixedSampleLocations )\n{\n ::glTexImage2DMultisample(\n target, samples, internalFormat, width, height, fixedSampleLocations );\n}\n\nvoid APIENTRY glTexStorage3DMultisample( GLenum target,\n GLsizei samples,\n GLenum internalFormat,\n GLsizei width,\n GLsizei height,\n GLsizei depth,\n GLboolean fixedSampleLocations )\n{\n ::glTexStorage3DMultisample( target, samples, internalFormat,\n width, height, depth, fixedSampleLocations );\n}\n\n}\n<|endoftext|>"} {"text":"\/**\n * @file pycantera.cpp\n *\n * This is the main file for the Python interface module.\n *\n *\/\n\n\/\/ turn off warnings about long names under Windows\n#ifdef WIN32\n#pragma warning(disable:4786)\n#pragma warning(disable:4503)\n#endif\n\n#include \"cantera\/kernel\/config.h\"\n\n#include \"Python.h\"\n\n#ifdef HAS_NUMERIC\n#include \"Numeric\/arrayobject.h\"\n#else\n#ifdef HAS_NUMARRAY\n#include \"numarray\/arrayobject.h\"\n#else\n#ifdef HAS_NUMPY\n#include \"numpy\/arrayobject.h\"\n#else\n\/\/ Create a compilation error to cause the program to bomb\n#include \"Numeric\/arrayobject.h\"\n#include \"numarray\/arrayobject.h\"\n#include \"numpy\/libnumarray.h\"\n#include \"numpy\/arrayobject.h\"\n#endif\n#endif\n#endif\n\n#include \"clib\/ct.h\"\n#include \"clib\/ctxml.h\"\n#include \"clib\/ctsurf.h\"\n#include \"clib\/ctbdry.h\"\n#include \"clib\/ctrpath.h\"\n#include \"clib\/ctreactor.h\"\n#include \"clib\/ctfunc.h\"\n#include \"clib\/ctonedim.h\"\n#include \"clib\/ctmultiphase.h\"\n\n#include \nusing namespace std;\n\n\/\/ constants defined in the module\nstatic PyObject *ErrorObject;\n\n\/\/ local includes\n#include \"pyutils.h\"\n\n#include \"ctphase_methods.cpp\"\n#include \"ctthermo_methods.cpp\"\n#include \"ctkinetics_methods.cpp\" \n#include \"cttransport_methods.cpp\"\n#include \"ctxml_methods.cpp\"\n#include \"ctfuncs.cpp\"\n#include \"ctsurf_methods.cpp\"\n\/\/#include \"ctbndry_methods.cpp\"\n#include \"ctrpath_methods.cpp\"\n#include \"ctreactor_methods.cpp\"\n#include \"ctfunc_methods.cpp\"\n#include \"ctonedim_methods.cpp\"\n#include \"ctmultiphase_methods.cpp\"\n\n#ifdef INCL_USER_PYTHON\n#include \"ctuser.h\"\n#include \"ctuser_methods.cpp\"\n#endif\n\nstatic PyObject*\npyct_appdelete(PyObject *self, PyObject *args) {\n return Py_BuildValue(\"i\",ct_appdelete()); \n}\n\n#include \"methods.h\"\n#include \"pylogger.h\"\n\/\/#include \"..\/..\/src\/global.h\"\nextern \"C\" {\n\n \/* Initialization function for the module *\/\n\n DL_EXPORT(void) init_cantera(void)\n {\n PyObject *m, *d;\n\n \/* Initialize the type of the new type object here; doing it here\n * is required for portability to Windows without requiring C++. *\/\n \n \/* Create the module and add the functions *\/\n m = Py_InitModule(\"_cantera\", ct_methods);\n import_array();\n Cantera::Logger* pylog = new Cantera::Py_Logger;\n setLogWriter(pylog);\n \n \/* Add some symbolic constants to the module *\/\n d = PyModule_GetDict(m);\n ErrorObject = PyErr_NewException((char *)\"cantera.error\", NULL, NULL);\n PyDict_SetItemString(d, \"error\", ErrorObject);\n#ifdef HAS_NUMERIC\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"Numeric\"));\n#else\n#ifdef HAS_NUMARRAY\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"numarray\"));\n#else\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"numpy\"));\n#endif\n#endif\n }\n\n}\n\nSimplified numpy\/numarray include to avoid confusing SCons\/**\n * @file pycantera.cpp\n *\n * This is the main file for the Python interface module.\n *\n *\/\n\n\/\/ turn off warnings about long names under Windows\n#ifdef WIN32\n#pragma warning(disable:4786)\n#pragma warning(disable:4503)\n#endif\n\n#include \"cantera\/kernel\/config.h\"\n\n#include \"Python.h\"\n\n#ifdef HAS_NUMERIC\n#include \"Numeric\/arrayobject.h\"\n#endif\n\n#ifdef HAS_NUMARRAY\n#include \"numarray\/arrayobject.h\"\n#endif\n\n#ifdef HAS_NUMPY\n#include \"numpy\/arrayobject.h\"\n#endif\n\n#include \"clib\/ct.h\"\n#include \"clib\/ctxml.h\"\n#include \"clib\/ctsurf.h\"\n#include \"clib\/ctbdry.h\"\n#include \"clib\/ctrpath.h\"\n#include \"clib\/ctreactor.h\"\n#include \"clib\/ctfunc.h\"\n#include \"clib\/ctonedim.h\"\n#include \"clib\/ctmultiphase.h\"\n\n#include \nusing namespace std;\n\n\/\/ constants defined in the module\nstatic PyObject *ErrorObject;\n\n\/\/ local includes\n#include \"pyutils.h\"\n\n#include \"ctphase_methods.cpp\"\n#include \"ctthermo_methods.cpp\"\n#include \"ctkinetics_methods.cpp\" \n#include \"cttransport_methods.cpp\"\n#include \"ctxml_methods.cpp\"\n#include \"ctfuncs.cpp\"\n#include \"ctsurf_methods.cpp\"\n\/\/#include \"ctbndry_methods.cpp\"\n#include \"ctrpath_methods.cpp\"\n#include \"ctreactor_methods.cpp\"\n#include \"ctfunc_methods.cpp\"\n#include \"ctonedim_methods.cpp\"\n#include \"ctmultiphase_methods.cpp\"\n\n#ifdef INCL_USER_PYTHON\n#include \"ctuser.h\"\n#include \"ctuser_methods.cpp\"\n#endif\n\nstatic PyObject*\npyct_appdelete(PyObject *self, PyObject *args) {\n return Py_BuildValue(\"i\",ct_appdelete()); \n}\n\n#include \"methods.h\"\n#include \"pylogger.h\"\n\/\/#include \"..\/..\/src\/global.h\"\nextern \"C\" {\n\n \/* Initialization function for the module *\/\n\n DL_EXPORT(void) init_cantera(void)\n {\n PyObject *m, *d;\n\n \/* Initialize the type of the new type object here; doing it here\n * is required for portability to Windows without requiring C++. *\/\n \n \/* Create the module and add the functions *\/\n m = Py_InitModule(\"_cantera\", ct_methods);\n import_array();\n Cantera::Logger* pylog = new Cantera::Py_Logger;\n setLogWriter(pylog);\n \n \/* Add some symbolic constants to the module *\/\n d = PyModule_GetDict(m);\n ErrorObject = PyErr_NewException((char *)\"cantera.error\", NULL, NULL);\n PyDict_SetItemString(d, \"error\", ErrorObject);\n#ifdef HAS_NUMERIC\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"Numeric\"));\n#else\n#ifdef HAS_NUMARRAY\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"numarray\"));\n#else\n PyDict_SetItemString(d, \"nummod\",PyString_FromString(\"numpy\"));\n#endif\n#endif\n }\n\n}\n\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageWriter.h\"\n\n#include \"mitkItkPictureWrite.h\"\n#include \"mitkImage.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageReadAccessor.h\"\n\n#include \n#include \n\n\nmitk::ImageWriter::ImageWriter()\n{\n this->SetNumberOfRequiredInputs( 1 );\n m_MimeType = \"\";\n SetDefaultExtension();\n}\n\nmitk::ImageWriter::~ImageWriter()\n{\n}\n\nvoid mitk::ImageWriter::SetFileName(const char* fileName)\n{\n if ( fileName && ( fileName == this->m_FileName ) )\n {\n return;\n }\n if ( fileName )\n {\n this->m_FileName = fileName;\n this->m_FileNameWithoutExtension = this->m_FileName;\n this->m_Extension.clear();\n std::size_t pos = this->m_FileName.find_last_of(\"\/\\\\\");\n if (pos != std::string::npos)\n {\n std::size_t ppos = this->m_FileName.find_first_of('.', pos);\n if (ppos != std::string::npos)\n {\n this->m_FileNameWithoutExtension = this->m_FileName.substr(0, ppos);\n this->m_Extension = this->m_FileName.substr(ppos);\n }\n }\n }\n else\n {\n this->m_FileName.clear();\n this->m_FileNameWithoutExtension.clear();\n this->m_Extension.clear();\n }\n this->Modified();\n}\n\nvoid mitk::ImageWriter::SetFileName(const std::string & fileName)\n{\n this->SetFileName( fileName.c_str() );\n}\n\nvoid mitk::ImageWriter::SetExtension(const char* extension)\n{\n if ( extension && ( extension == this->m_Extension ) )\n {\n return;\n }\n if ( extension )\n {\n this->m_Extension = extension;\n this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension;\n }\n else\n {\n this->m_Extension.clear();\n this->m_FileName = this->m_FileNameWithoutExtension;\n }\n this->Modified();\n}\n\nvoid mitk::ImageWriter::SetExtension(const std::string & extension)\n{\n this->SetFileName( extension.c_str() );\n}\n\nvoid mitk::ImageWriter::SetDefaultExtension()\n{\n this->m_Extension = \".mhd\";\n this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension;\n this->Modified();\n}\n\n#include \n#include \n#include \nstatic void writeVti(const char * filename, mitk::Image* image, int t=0)\n{\n vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New();\n vtkwriter->SetFileName( filename );\n vtkwriter->SetInput(image->GetVtkImageData(t));\n vtkwriter->Write();\n vtkwriter->Delete();\n}\n\n#include \n\nvoid mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& fileName)\n{\n MITK_INFO << \"Writing image: \" << fileName << std::endl;\n \/\/ Pictures and picture series like .png are written via a different mechanism then volume images.\n \/\/ So, they are still multiplexed and thus not support vector images.\n if (fileName.find(\".png\") != std::string::npos || fileName.find(\".tif\") != std::string::npos || fileName.find(\".jpg\") != std::string::npos)\n {\n try\n {\n \/\/ switch processing of single\/multi-component images\n if( image->GetPixelType(0).GetNumberOfComponents() == 1)\n {\n AccessByItk_1( image, _mitkItkPictureWrite, fileName );\n }\n else\n {\n AccessFixedPixelTypeByItk_1( image, _mitkItkPictureWriteComposite, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ , fileName);\n }\n }\n catch(itk::ExceptionObject &e)\n {\n std::cerr << \"Caught \" << e.what() << std::endl;\n }\n catch(std::exception &e)\n {\n std::cerr << \"Caught std::exception \" << e.what() << std::endl;\n }\n\n return;\n }\n\n \/\/ Implementation of writer using itkImageIO directly. This skips the use\n \/\/ of templated itkImageFileWriter, which saves the multiplexing on MITK side.\n\n unsigned int dimension = image->GetDimension();\n unsigned int* dimensions = image->GetDimensions();\n mitk::PixelType pixelType = image->GetPixelType();\n mitk::Vector3D spacing = image->GetGeometry()->GetSpacing();\n mitk::Point3D origin = image->GetGeometry()->GetOrigin();\n\n itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( fileName.c_str(),\n itk::ImageIOFactory::WriteMode );\n\n if(imageIO.IsNull())\n {\n itkExceptionMacro(<< \"Error: Could not create itkImageIO via factory for file \" << fileName);\n }\n\n \/\/ Set the necessary information for imageIO\n imageIO->SetNumberOfDimensions(dimension);\n imageIO->SetPixelType( pixelType.GetPixelType() );\n imageIO->SetComponentType( pixelType.GetComponentType() < PixelComponentUserType ?\n static_cast(pixelType.GetComponentType()) :\n itk::ImageIOBase::UNKNOWNCOMPONENTTYPE);\n imageIO->SetNumberOfComponents( pixelType.GetNumberOfComponents() );\n\n itk::ImageIORegion ioRegion( dimension );\n\n for(unsigned int i=0; iSetDimensions(i,dimensions[i]);\n imageIO->SetSpacing(i,spacing[i]);\n imageIO->SetOrigin(i,origin[i]);\n\n mitk::Vector3D direction;\n direction.SetVnlVector(image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i));\n vnl_vector< double > axisDirection(dimension);\n for(unsigned int j=0; jSetDirection( i, axisDirection );\n\n ioRegion.SetSize(i, image->GetLargestPossibleRegion().GetSize(i) );\n ioRegion.SetIndex(i, image->GetLargestPossibleRegion().GetIndex(i) );\n }\n\n \/\/use compression if available\n imageIO->UseCompressionOn();\n\n imageIO->SetIORegion(ioRegion);\n imageIO->SetFileName(fileName);\n\n ImageReadAccessor imageAccess(image);\n imageIO->Write(imageAccess.GetData());\n}\n\nvoid mitk::ImageWriter::GenerateData()\n{\n const std::string& locale = \"C\";\n const std::string& currLocale = setlocale( LC_ALL, NULL );\n\n if ( locale.compare(currLocale)!=0 )\n {\n try\n {\n setlocale(LC_ALL, locale.c_str());\n }\n catch(...)\n {\n MITK_INFO << \"Could not set locale \" << locale;\n }\n }\n\n if ( m_FileName == \"\" )\n {\n itkWarningMacro( << \"Sorry, filename has not been set!\" );\n return ;\n }\n\n FILE* tempFile = fopen(m_FileName.c_str(),\"w\");\n if (tempFile==NULL)\n {\n itkExceptionMacro(<<\"File location not writeable\");\n return;\n }\n fclose(tempFile);\n remove(m_FileName.c_str());\n\n \/\/ Creating clone of input image, since i might change the geometry\n mitk::Image::Pointer input = const_cast(this->GetInput())->Clone();\n\n \/\/ Check if geometry information will be lost\n if (input->GetDimension() == 2)\n {\n if (!input->GetGeometry()->Is2DConvertable())\n {\n MITK_WARN << \"Saving a 2D image with 3D geometry information. Geometry information will be lost! You might consider using Convert2Dto3DImageFilter before saving.\";\n\n \/\/ set matrix to identity\n mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New();\n affTrans->SetIdentity();\n mitk::Vector3D spacing = input->GetGeometry()->GetSpacing();\n mitk::Point3D origin = input->GetGeometry()->GetOrigin();\n input->GetGeometry()->SetIndexToWorldTransform(affTrans);\n input->GetGeometry()->SetSpacing(spacing);\n input->GetGeometry()->SetOrigin(origin);\n }\n }\n\n bool vti = (m_Extension.find(\".vti\") != std::string::npos);\n\n \/\/ If the extension is NOT .pic and NOT .nrrd and NOT .nii and NOT .nii.gz the following block is entered\n if ( m_Extension.find(\".pic\") == std::string::npos\n && m_Extension.find(\".nrrd\") == std::string::npos\n && m_Extension.find(\".nii\") == std::string::npos\n && m_Extension.find(\".nii.gz\") == std::string::npos\n )\n {\n if(input->GetDimension() > 3)\n {\n int t, timesteps;\n\n timesteps = input->GetDimension(3);\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(input);\n mitk::Image::Pointer image = timeSelector->GetOutput();\n for(t = 0; t < timesteps; ++t)\n {\n std::ostringstream filename;\n timeSelector->SetTimeNr(t);\n timeSelector->Update();\n if(input->GetTimeSlicedGeometry()->IsValidTime(t))\n {\n const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds();\n filename << m_FileNameWithoutExtension << \"_S\" << std::setprecision(0) << timebounds[0] << \"_E\" << std::setprecision(0) << timebounds[1] << \"_T\" << t << m_Extension;\n }\n else\n {\n itkWarningMacro(<<\"Error on write: TimeSlicedGeometry invalid of image \" << filename << \".\");\n filename << m_FileNameWithoutExtension << \"_T\" << t << m_Extension;\n }\n if ( vti )\n {\n writeVti(filename.str().c_str(), input, t);\n }\n else\n {\n WriteByITK(image, filename.str());\n }\n }\n }\n else if ( vti )\n {\n writeVti(m_FileName.c_str(), input);\n }\n else\n {\n WriteByITK(input, m_FileName);\n }\n }\n else\n {\n \/\/ use the PicFileWriter for the .pic data type\n if( m_Extension.find(\".pic\") != std::string::npos )\n {\n\/* PicFileWriter::Pointer picWriter = PicFileWriter::New();\n size_t found;\n found = m_FileName.find( m_Extension ); \/\/ !!! HAS to be at the very end of the filename (not somewhere in the middle)\n if( m_FileName.length() > 3 && found != m_FileName.length() - 4 )\n {\n \/\/if Extension not in Filename\n std::ostringstream filename;\n filename << m_FileName.c_str() << m_Extension;\n picWriter->SetFileName( filename.str().c_str() );\n }\n else\n {\n picWriter->SetFileName( m_FileName.c_str() );\n }\n picWriter->SetInputImage( input );\n picWriter->Write();\n*\/ }\n\n \/\/ use the ITK .nrrd Image writer\n if( m_Extension.find(\".nrrd\") != std::string::npos\n || m_Extension.find(\".nii\") != std::string::npos\n || m_Extension.find(\".nii.gz\") != std::string::npos\n )\n {\n WriteByITK(input, this->m_FileName);\n }\n }\n m_MimeType = \"application\/MITK.Pic\";\n\n try\n {\n setlocale(LC_ALL, currLocale.c_str());\n }\n catch(...)\n {\n MITK_INFO << \"Could not reset locale \" << currLocale;\n }\n}\n\nbool mitk::ImageWriter::CanWriteDataType( DataNode* input )\n{\n if ( input )\n {\n return this->CanWriteBaseDataType(input->GetData());\n }\n return false;\n}\n\nvoid mitk::ImageWriter::SetInput( DataNode* input )\n{\n if( input && CanWriteDataType( input ) )\n this->ProcessObject::SetNthInput( 0, dynamic_cast( input->GetData() ) );\n}\n\nstd::string mitk::ImageWriter::GetWritenMIMEType()\n{\n return m_MimeType;\n}\n\nstd::vector mitk::ImageWriter::GetPossibleFileExtensions()\n{\n std::vector possibleFileExtensions;\n possibleFileExtensions.push_back(\".pic\");\n possibleFileExtensions.push_back(\".pic.gz\");\n possibleFileExtensions.push_back(\".bmp\");\n possibleFileExtensions.push_back(\".dcm\");\n possibleFileExtensions.push_back(\".DCM\");\n possibleFileExtensions.push_back(\".dicom\");\n possibleFileExtensions.push_back(\".DICOM\");\n possibleFileExtensions.push_back(\".gipl\");\n possibleFileExtensions.push_back(\".gipl.gz\");\n possibleFileExtensions.push_back(\".mha\");\n possibleFileExtensions.push_back(\".nii\");\n possibleFileExtensions.push_back(\".nii.gz\");\n possibleFileExtensions.push_back(\".nrrd\");\n possibleFileExtensions.push_back(\".nhdr\");\n possibleFileExtensions.push_back(\".png\");\n possibleFileExtensions.push_back(\".PNG\");\n possibleFileExtensions.push_back(\".spr\");\n possibleFileExtensions.push_back(\".mhd\");\n possibleFileExtensions.push_back(\".vtk\");\n possibleFileExtensions.push_back(\".vti\");\n possibleFileExtensions.push_back(\".hdr\");\n possibleFileExtensions.push_back(\".png\");\n possibleFileExtensions.push_back(\".tif\");\n possibleFileExtensions.push_back(\".jpg\");\n return possibleFileExtensions;\n}\n\nstd::string mitk::ImageWriter::GetFileExtension()\n{\n return m_Extension;\n}\n\nvoid mitk::ImageWriter::SetInput( mitk::Image* image )\n{\n this->ProcessObject::SetNthInput( 0, image );\n}\n\nconst mitk::Image* mitk::ImageWriter::GetInput()\n{\n if ( this->GetNumberOfInputs() < 1 )\n {\n return NULL;\n }\n else\n {\n return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) );\n }\n}\n\nconst char* mitk::ImageWriter::GetDefaultFilename()\n{\n return \"Image.nrrd\";\n}\n\nconst char* mitk::ImageWriter::GetFileDialogPattern()\n{\n return \"Image (*.pic, *.pic.gz, *.bmp, *.dcm, *.DCM, *.dicom, *.DICOM, *.gipl, *.gipl.gz, *.mha, \"\n \"*.nii, *.nii.gz, *.nrrd, *.nhdr, *.png, *.PNG, *.spr, *.mhd, *.vtk, *.vti, *.hdr, *.png, \"\n \"*.tif, *.jpg)\";\n}\n\nconst char *mitk::ImageWriter::GetDefaultExtension()\n{\n return \".nrrd\";\n}\n\nbool mitk::ImageWriter::CanWriteBaseDataType(BaseData::Pointer data)\n{\n return dynamic_cast( data.GetPointer() );\n}\n\nvoid mitk::ImageWriter::DoWrite(BaseData::Pointer data)\n{\n if (this->CanWriteBaseDataType(data))\n {\n this->SetInput(dynamic_cast(data.GetPointer()));\n this->Update();\n }\n}\nRemove unsupproted image extensions and misleading \",\" in file dialog pattern.\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \"mitkImageWriter.h\"\n\n#include \"mitkItkPictureWrite.h\"\n#include \"mitkImage.h\"\n#include \"mitkImageTimeSelector.h\"\n#include \"mitkImageAccessByItk.h\"\n#include \"mitkImageReadAccessor.h\"\n\n#include \n#include \n\n\nmitk::ImageWriter::ImageWriter()\n{\n this->SetNumberOfRequiredInputs( 1 );\n m_MimeType = \"\";\n SetDefaultExtension();\n}\n\nmitk::ImageWriter::~ImageWriter()\n{\n}\n\nvoid mitk::ImageWriter::SetFileName(const char* fileName)\n{\n if ( fileName && ( fileName == this->m_FileName ) )\n {\n return;\n }\n if ( fileName )\n {\n this->m_FileName = fileName;\n this->m_FileNameWithoutExtension = this->m_FileName;\n this->m_Extension.clear();\n std::size_t pos = this->m_FileName.find_last_of(\"\/\\\\\");\n if (pos != std::string::npos)\n {\n std::size_t ppos = this->m_FileName.find_first_of('.', pos);\n if (ppos != std::string::npos)\n {\n this->m_FileNameWithoutExtension = this->m_FileName.substr(0, ppos);\n this->m_Extension = this->m_FileName.substr(ppos);\n }\n }\n }\n else\n {\n this->m_FileName.clear();\n this->m_FileNameWithoutExtension.clear();\n this->m_Extension.clear();\n }\n this->Modified();\n}\n\nvoid mitk::ImageWriter::SetFileName(const std::string & fileName)\n{\n this->SetFileName( fileName.c_str() );\n}\n\nvoid mitk::ImageWriter::SetExtension(const char* extension)\n{\n if ( extension && ( extension == this->m_Extension ) )\n {\n return;\n }\n if ( extension )\n {\n this->m_Extension = extension;\n this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension;\n }\n else\n {\n this->m_Extension.clear();\n this->m_FileName = this->m_FileNameWithoutExtension;\n }\n this->Modified();\n}\n\nvoid mitk::ImageWriter::SetExtension(const std::string & extension)\n{\n this->SetFileName( extension.c_str() );\n}\n\nvoid mitk::ImageWriter::SetDefaultExtension()\n{\n this->m_Extension = \".mhd\";\n this->m_FileName = this->m_FileNameWithoutExtension + this->m_Extension;\n this->Modified();\n}\n\n#include \n#include \n#include \nstatic void writeVti(const char * filename, mitk::Image* image, int t=0)\n{\n vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New();\n vtkwriter->SetFileName( filename );\n vtkwriter->SetInput(image->GetVtkImageData(t));\n vtkwriter->Write();\n vtkwriter->Delete();\n}\n\n#include \n\nvoid mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& fileName)\n{\n MITK_INFO << \"Writing image: \" << fileName << std::endl;\n \/\/ Pictures and picture series like .png are written via a different mechanism then volume images.\n \/\/ So, they are still multiplexed and thus not support vector images.\n if (fileName.find(\".png\") != std::string::npos || fileName.find(\".tif\") != std::string::npos || fileName.find(\".jpg\") != std::string::npos)\n {\n try\n {\n \/\/ switch processing of single\/multi-component images\n if( image->GetPixelType(0).GetNumberOfComponents() == 1)\n {\n AccessByItk_1( image, _mitkItkPictureWrite, fileName );\n }\n else\n {\n AccessFixedPixelTypeByItk_1( image, _mitkItkPictureWriteComposite, MITK_ACCESSBYITK_PIXEL_TYPES_SEQ MITK_ACCESSBYITK_COMPOSITE_PIXEL_TYPES_SEQ , fileName);\n }\n }\n catch(itk::ExceptionObject &e)\n {\n std::cerr << \"Caught \" << e.what() << std::endl;\n }\n catch(std::exception &e)\n {\n std::cerr << \"Caught std::exception \" << e.what() << std::endl;\n }\n\n return;\n }\n\n \/\/ Implementation of writer using itkImageIO directly. This skips the use\n \/\/ of templated itkImageFileWriter, which saves the multiplexing on MITK side.\n\n unsigned int dimension = image->GetDimension();\n unsigned int* dimensions = image->GetDimensions();\n mitk::PixelType pixelType = image->GetPixelType();\n mitk::Vector3D spacing = image->GetGeometry()->GetSpacing();\n mitk::Point3D origin = image->GetGeometry()->GetOrigin();\n\n itk::ImageIOBase::Pointer imageIO = itk::ImageIOFactory::CreateImageIO( fileName.c_str(),\n itk::ImageIOFactory::WriteMode );\n\n if(imageIO.IsNull())\n {\n itkExceptionMacro(<< \"Error: Could not create itkImageIO via factory for file \" << fileName);\n }\n\n \/\/ Set the necessary information for imageIO\n imageIO->SetNumberOfDimensions(dimension);\n imageIO->SetPixelType( pixelType.GetPixelType() );\n imageIO->SetComponentType( pixelType.GetComponentType() < PixelComponentUserType ?\n static_cast(pixelType.GetComponentType()) :\n itk::ImageIOBase::UNKNOWNCOMPONENTTYPE);\n imageIO->SetNumberOfComponents( pixelType.GetNumberOfComponents() );\n\n itk::ImageIORegion ioRegion( dimension );\n\n for(unsigned int i=0; iSetDimensions(i,dimensions[i]);\n imageIO->SetSpacing(i,spacing[i]);\n imageIO->SetOrigin(i,origin[i]);\n\n mitk::Vector3D direction;\n direction.SetVnlVector(image->GetGeometry()->GetIndexToWorldTransform()->GetMatrix().GetVnlMatrix().get_column(i));\n vnl_vector< double > axisDirection(dimension);\n for(unsigned int j=0; jSetDirection( i, axisDirection );\n\n ioRegion.SetSize(i, image->GetLargestPossibleRegion().GetSize(i) );\n ioRegion.SetIndex(i, image->GetLargestPossibleRegion().GetIndex(i) );\n }\n\n \/\/use compression if available\n imageIO->UseCompressionOn();\n\n imageIO->SetIORegion(ioRegion);\n imageIO->SetFileName(fileName);\n\n ImageReadAccessor imageAccess(image);\n imageIO->Write(imageAccess.GetData());\n}\n\nvoid mitk::ImageWriter::GenerateData()\n{\n const std::string& locale = \"C\";\n const std::string& currLocale = setlocale( LC_ALL, NULL );\n\n if ( locale.compare(currLocale)!=0 )\n {\n try\n {\n setlocale(LC_ALL, locale.c_str());\n }\n catch(...)\n {\n MITK_INFO << \"Could not set locale \" << locale;\n }\n }\n\n if ( m_FileName == \"\" )\n {\n itkWarningMacro( << \"Sorry, filename has not been set!\" );\n return ;\n }\n\n FILE* tempFile = fopen(m_FileName.c_str(),\"w\");\n if (tempFile==NULL)\n {\n itkExceptionMacro(<<\"File location not writeable\");\n return;\n }\n fclose(tempFile);\n remove(m_FileName.c_str());\n\n \/\/ Creating clone of input image, since i might change the geometry\n mitk::Image::Pointer input = const_cast(this->GetInput())->Clone();\n\n \/\/ Check if geometry information will be lost\n if (input->GetDimension() == 2)\n {\n if (!input->GetGeometry()->Is2DConvertable())\n {\n MITK_WARN << \"Saving a 2D image with 3D geometry information. Geometry information will be lost! You might consider using Convert2Dto3DImageFilter before saving.\";\n\n \/\/ set matrix to identity\n mitk::AffineTransform3D::Pointer affTrans = mitk::AffineTransform3D::New();\n affTrans->SetIdentity();\n mitk::Vector3D spacing = input->GetGeometry()->GetSpacing();\n mitk::Point3D origin = input->GetGeometry()->GetOrigin();\n input->GetGeometry()->SetIndexToWorldTransform(affTrans);\n input->GetGeometry()->SetSpacing(spacing);\n input->GetGeometry()->SetOrigin(origin);\n }\n }\n\n bool vti = (m_Extension.find(\".vti\") != std::string::npos);\n\n \/\/ If the extension is NOT .pic and NOT .nrrd and NOT .nii and NOT .nii.gz the following block is entered\n if ( m_Extension.find(\".pic\") == std::string::npos\n && m_Extension.find(\".nrrd\") == std::string::npos\n && m_Extension.find(\".nii\") == std::string::npos\n && m_Extension.find(\".nii.gz\") == std::string::npos\n )\n {\n if(input->GetDimension() > 3)\n {\n int t, timesteps;\n\n timesteps = input->GetDimension(3);\n ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New();\n timeSelector->SetInput(input);\n mitk::Image::Pointer image = timeSelector->GetOutput();\n for(t = 0; t < timesteps; ++t)\n {\n std::ostringstream filename;\n timeSelector->SetTimeNr(t);\n timeSelector->Update();\n if(input->GetTimeSlicedGeometry()->IsValidTime(t))\n {\n const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds();\n filename << m_FileNameWithoutExtension << \"_S\" << std::setprecision(0) << timebounds[0] << \"_E\" << std::setprecision(0) << timebounds[1] << \"_T\" << t << m_Extension;\n }\n else\n {\n itkWarningMacro(<<\"Error on write: TimeSlicedGeometry invalid of image \" << filename << \".\");\n filename << m_FileNameWithoutExtension << \"_T\" << t << m_Extension;\n }\n if ( vti )\n {\n writeVti(filename.str().c_str(), input, t);\n }\n else\n {\n WriteByITK(image, filename.str());\n }\n }\n }\n else if ( vti )\n {\n writeVti(m_FileName.c_str(), input);\n }\n else\n {\n WriteByITK(input, m_FileName);\n }\n }\n else\n {\n \/\/ use the PicFileWriter for the .pic data type\n if( m_Extension.find(\".pic\") != std::string::npos )\n {\n\/* PicFileWriter::Pointer picWriter = PicFileWriter::New();\n size_t found;\n found = m_FileName.find( m_Extension ); \/\/ !!! HAS to be at the very end of the filename (not somewhere in the middle)\n if( m_FileName.length() > 3 && found != m_FileName.length() - 4 )\n {\n \/\/if Extension not in Filename\n std::ostringstream filename;\n filename << m_FileName.c_str() << m_Extension;\n picWriter->SetFileName( filename.str().c_str() );\n }\n else\n {\n picWriter->SetFileName( m_FileName.c_str() );\n }\n picWriter->SetInputImage( input );\n picWriter->Write();\n*\/ }\n\n \/\/ use the ITK .nrrd Image writer\n if( m_Extension.find(\".nrrd\") != std::string::npos\n || m_Extension.find(\".nii\") != std::string::npos\n || m_Extension.find(\".nii.gz\") != std::string::npos\n )\n {\n WriteByITK(input, this->m_FileName);\n }\n }\n m_MimeType = \"application\/MITK.Pic\";\n\n try\n {\n setlocale(LC_ALL, currLocale.c_str());\n }\n catch(...)\n {\n MITK_INFO << \"Could not reset locale \" << currLocale;\n }\n}\n\nbool mitk::ImageWriter::CanWriteDataType( DataNode* input )\n{\n if ( input )\n {\n return this->CanWriteBaseDataType(input->GetData());\n }\n return false;\n}\n\nvoid mitk::ImageWriter::SetInput( DataNode* input )\n{\n if( input && CanWriteDataType( input ) )\n this->ProcessObject::SetNthInput( 0, dynamic_cast( input->GetData() ) );\n}\n\nstd::string mitk::ImageWriter::GetWritenMIMEType()\n{\n return m_MimeType;\n}\n\nstd::vector mitk::ImageWriter::GetPossibleFileExtensions()\n{\n std::vector possibleFileExtensions;\n possibleFileExtensions.push_back(\".pic\");\n possibleFileExtensions.push_back(\".pic.gz\");\n possibleFileExtensions.push_back(\".bmp\");\n possibleFileExtensions.push_back(\".dcm\");\n possibleFileExtensions.push_back(\".DCM\");\n possibleFileExtensions.push_back(\".dicom\");\n possibleFileExtensions.push_back(\".DICOM\");\n possibleFileExtensions.push_back(\".gipl\");\n possibleFileExtensions.push_back(\".gipl.gz\");\n possibleFileExtensions.push_back(\".mha\");\n possibleFileExtensions.push_back(\".nii\");\n possibleFileExtensions.push_back(\".nii.gz\");\n possibleFileExtensions.push_back(\".nrrd\");\n possibleFileExtensions.push_back(\".nhdr\");\n possibleFileExtensions.push_back(\".png\");\n possibleFileExtensions.push_back(\".PNG\");\n possibleFileExtensions.push_back(\".spr\");\n possibleFileExtensions.push_back(\".mhd\");\n possibleFileExtensions.push_back(\".vtk\");\n possibleFileExtensions.push_back(\".vti\");\n possibleFileExtensions.push_back(\".hdr\");\n possibleFileExtensions.push_back(\".png\");\n possibleFileExtensions.push_back(\".tif\");\n possibleFileExtensions.push_back(\".jpg\");\n return possibleFileExtensions;\n}\n\nstd::string mitk::ImageWriter::GetFileExtension()\n{\n return m_Extension;\n}\n\nvoid mitk::ImageWriter::SetInput( mitk::Image* image )\n{\n this->ProcessObject::SetNthInput( 0, image );\n}\n\nconst mitk::Image* mitk::ImageWriter::GetInput()\n{\n if ( this->GetNumberOfInputs() < 1 )\n {\n return NULL;\n }\n else\n {\n return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) );\n }\n}\n\nconst char* mitk::ImageWriter::GetDefaultFilename()\n{\n return \"Image.nrrd\";\n}\n\nconst char* mitk::ImageWriter::GetFileDialogPattern()\n{\n return \"Image (*.bmp *.dcm *.DCM *.dicom *.DICOM *.gipl *.gipl.gz *.mha \"\n \"*.nii *.nii.gz *.nrrd *.nhdr *.png *.PNG *.spr *.mhd *.vtk *.vti *.hdr *.png \"\n \"*.tif *.jpg)\";\n}\n\nconst char *mitk::ImageWriter::GetDefaultExtension()\n{\n return \".nrrd\";\n}\n\nbool mitk::ImageWriter::CanWriteBaseDataType(BaseData::Pointer data)\n{\n return dynamic_cast( data.GetPointer() );\n}\n\nvoid mitk::ImageWriter::DoWrite(BaseData::Pointer data)\n{\n if (this->CanWriteBaseDataType(data))\n {\n this->SetInput(dynamic_cast(data.GetPointer()));\n this->Update();\n }\n}\n<|endoftext|>"} {"text":"#include \"mitkParRecFileReader.h\"\n#include \n\n#ifdef __GNUC__\n#define stricmp strcasecmp \n#endif\n\nvoid mitk::ParRecFileReader::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n \n if ((output->IsInitialized()) && (this->GetMTime() <= m_ReadHeaderTime.GetMTime()))\n return;\n \n itkDebugMacro(<<\"Reading PAR file for GenerateOutputInformation()\" << m_FileName);\n \n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" && m_FilePrefix == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n \n m_RecFileName = \"\";\n if( m_FileName != \"\")\n {\n int extPos=m_FileName.find_last_of(\".\");\n if(extPos>=-1)\n {\n const char *ext=m_FileName.c_str()+extPos+1;\n if(stricmp(ext,\"par\")==0)\n m_RecFileName = m_FileName.substr(0,extPos);\n else\n m_RecFileName = m_FileName;\n }\n else\n m_RecFileName = m_FileName;\n\n m_RecFileName.append(\".rec\");\n\n bool headerRead = false;\n\n mitk::PixelType type;\n unsigned int dimension=0;\n unsigned int dimensions[4]={0,0,1,1};\n float sliceThickness=0.0;\n float sliceGap=0.0;\n float sliceSpacing=0.0;\n mitk::Vector3D thickness(1.0,1.0,1.0);\n mitk::Vector3D gap(0.0,0.0,0.0);\n mitk::Vector3D spacing;\n\n FILE *f;\n f=fopen(m_FileName.c_str(), \"r\");\n if(f!=NULL)\n {\n while(!feof(f))\n {\n char s[300], *p;\n fgets(s,200,f);\n if(strstr(s,\"Max. number of cardiac phases\"))\n {\n p=strchr(s,':')+1;\n dimensions[3]=atoi(p);\n if(dimensions[3]>1)\n dimension=4;\n }\n else\n if(strstr(s,\"Max. number of slices\/locations\"))\n {\n p=strchr(s,':')+1;\n dimensions[2]=atoi(p);\n if(dimension==0)\n {\n if(dimensions[2]>1)\n dimension=3;\n else\n dimension=2;\n }\n }\n else\n if(strstr(s,\"Image pixel size\"))\n {\n p=strchr(s,':')+1;\n int bpe=atoi(p);\n if(bpe==8)\n type=typeid(ipUInt1_t);\n else\n type=typeid(ipUInt2_t);\n }\n else\n if(strstr(s,\"Recon resolution\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%u %u\", dimensions, dimensions+1);\n }\n else\n if(strstr(s,\"FOV (ap,fh,rl) [mm]\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%f %f %f\", &thickness.x, &thickness.y, &thickness.z);\n }\n else\n if(strstr(s,\"Slice thickness [mm]\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%f\", &sliceThickness);\n }\n else\n if(strstr(s,\"Slice gap [mm]\"))\n {\n p=s+strcspn(s,\"-0123456789\");\n sscanf(p,\"%f\", &sliceGap);\n }\n }\n fclose(f);\n\n\/\/C:\\home\\ivo\\data\\coronaries\\ucsf-wholeheart-2.par\n sliceSpacing = sliceThickness+sliceGap;\n if(fabs(thickness.x\/dimensions[2]-sliceSpacing)<0.0001)\n thickness.x=thickness.y;\n else\n if(fabs(thickness.y\/dimensions[2]-sliceSpacing)<0.0001)\n thickness.y=thickness.x;\n thickness.z=sliceSpacing;\n\n thickness.x\/=dimensions[0];\n thickness.y\/=dimensions[1];\n spacing=thickness+gap;\n\n if((dimension>0) && (dimensions[0]>0) && (dimensions[1]>0))\n headerRead = true;\n }\n \n if( headerRead == false)\n {\n itk::ImageFileReaderException e(__FILE__, __LINE__);\n itk::OStringStream msg;\n msg << \" Could not read file \"\n << m_FileName.c_str();\n e.SetDescription(msg.str().c_str());\n throw e;\n return;\n }\n \n output->Initialize(type, dimension, dimensions);\n output->GetSlicedGeometry()->SetSpacing(spacing);\n\n output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), dimensions).GetPointer(), 0);\n output->GetSlicedGeometry()->SetEvenlySpaced();\n }\n \n m_ReadHeaderTime.Modified();\n}\n\nvoid mitk::ParRecFileReader::GenerateData()\n{\n mitk::Image::Pointer output = this->GetOutput();\n \n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_RecFileName == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"FileName for rec-file empty\");\n }\n \n if( m_RecFileName != \"\")\n {\n FILE *f = fopen(m_RecFileName.c_str(), \"r\");\n if(f==NULL)\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"Could not open rec-file.\");\n }\n\n int zstart, zmax;\n int tstart, tmax;\n\n zstart=output->GetRequestedRegion().GetIndex(2);\n tstart=output->GetRequestedRegion().GetIndex(3);\n\n zmax=zstart+output->GetRequestedRegion().GetSize(2);\n tmax=tstart+output->GetRequestedRegion().GetSize(3);\n\n bool ignore4Dtopogram=false;\n {\n int slicePlusTimeSize=output->GetDimension(0)*output->GetDimension(1)*output->GetDimension(3)*output->GetPixelType().GetBpe()\/8;\n if(output->GetDimension(3)>1)\n ignore4Dtopogram=true;\n\n int z,t;\n for(t=tstart;tSetSlice(data,z,t,0);\n }\n }\n \/\/else\n \/\/{\n \/\/ for(;zSetSlice(data,z,0,0);\n \/\/ }\n \/\/}\n free(data);\n }\n}\n\nmitk::ParRecFileReader::ParRecFileReader()\n: m_FileName(\"\"), m_FilePrefix(\"\"), m_FilePattern(\"\")\n{\n}\n\nmitk::ParRecFileReader::~ParRecFileReader()\n{\n}\nfixed the fix#include \"mitkParRecFileReader.h\"\n#include \n\n#ifdef __GNUC__\n#define stricmp strcasecmp \n#endif\n\nvoid mitk::ParRecFileReader::GenerateOutputInformation()\n{\n mitk::Image::Pointer output = this->GetOutput();\n \n if ((output->IsInitialized()) && (this->GetMTime() <= m_ReadHeaderTime.GetMTime()))\n return;\n \n itkDebugMacro(<<\"Reading PAR file for GenerateOutputInformation()\" << m_FileName);\n \n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_FileName == \"\" && m_FilePrefix == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"One of FileName or FilePrefix must be non-empty\");\n }\n \n m_RecFileName = \"\";\n if( m_FileName != \"\")\n {\n int extPos=m_FileName.find_last_of(\".\");\n if(extPos>=-1)\n {\n const char *ext=m_FileName.c_str()+extPos+1;\n if(stricmp(ext,\"par\")==0)\n m_RecFileName = m_FileName.substr(0,extPos);\n else\n m_RecFileName = m_FileName;\n }\n else\n m_RecFileName = m_FileName;\n\n m_RecFileName.append(\".rec\");\n\n bool headerRead = false;\n\n mitk::PixelType type;\n unsigned int dimension=0;\n unsigned int dimensions[4]={0,0,1,1};\n float sliceThickness=0.0;\n float sliceGap=0.0;\n float sliceSpacing=0.0;\n mitk::Vector3D thickness(1.0,1.0,1.0);\n mitk::Vector3D gap(0.0,0.0,0.0);\n mitk::Vector3D spacing;\n\n FILE *f;\n f=fopen(m_FileName.c_str(), \"r\");\n if(f!=NULL)\n {\n while(!feof(f))\n {\n char s[300], *p;\n fgets(s,200,f);\n if(strstr(s,\"Max. number of cardiac phases\"))\n {\n p=strchr(s,':')+1;\n dimensions[3]=atoi(p);\n if(dimensions[3]>1)\n dimension=4;\n }\n else\n if(strstr(s,\"Max. number of slices\/locations\"))\n {\n p=strchr(s,':')+1;\n dimensions[2]=atoi(p);\n if(dimension==0)\n {\n if(dimensions[2]>1)\n dimension=3;\n else\n dimension=2;\n }\n }\n else\n if(strstr(s,\"Image pixel size\"))\n {\n p=strchr(s,':')+1;\n int bpe=atoi(p);\n if(bpe==8)\n type=typeid(ipUInt1_t);\n else\n type=typeid(ipUInt2_t);\n }\n else\n if(strstr(s,\"Recon resolution\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%u %u\", dimensions, dimensions+1);\n }\n else\n if(strstr(s,\"FOV (ap,fh,rl) [mm]\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%f %f %f\", &thickness.x, &thickness.y, &thickness.z);\n }\n else\n if(strstr(s,\"Slice thickness [mm]\"))\n {\n p=s+strcspn(s,\"0123456789\");\n sscanf(p,\"%f\", &sliceThickness);\n }\n else\n if(strstr(s,\"Slice gap [mm]\"))\n {\n p=s+strcspn(s,\"-0123456789\");\n sscanf(p,\"%f\", &sliceGap);\n }\n }\n fclose(f);\n\n\/\/C:\\home\\ivo\\data\\coronaries\\ucsf-wholeheart-2.par\n sliceSpacing = sliceThickness+sliceGap;\n if(fabs(thickness.x\/dimensions[2]-sliceSpacing)<0.0001)\n thickness.x=thickness.y;\n else\n if(fabs(thickness.y\/dimensions[2]-sliceSpacing)<0.0001)\n thickness.y=thickness.x;\n thickness.z=sliceSpacing;\n\n thickness.x\/=dimensions[0];\n thickness.y\/=dimensions[1];\n spacing=thickness+gap;\n\n if((dimension>0) && (dimensions[0]>0) && (dimensions[1]>0))\n headerRead = true;\n }\n \n if( headerRead == false)\n {\n itk::ImageFileReaderException e(__FILE__, __LINE__);\n itk::OStringStream msg;\n msg << \" Could not read file \"\n << m_FileName.c_str();\n e.SetDescription(msg.str().c_str());\n throw e;\n return;\n }\n \n output->Initialize(type, dimension, dimensions);\n output->GetSlicedGeometry()->SetSpacing(spacing);\n\n output->GetSlicedGeometry()->SetGeometry2D(mitk::Image::BuildStandardPlaneGeometry2D(output->GetSlicedGeometry(), dimensions).GetPointer(), 0);\n output->GetSlicedGeometry()->SetEvenlySpaced();\n }\n \n m_ReadHeaderTime.Modified();\n}\n\nvoid mitk::ParRecFileReader::GenerateData()\n{\n mitk::Image::Pointer output = this->GetOutput();\n \n \/\/ Check to see if we can read the file given the name or prefix\n \/\/\n if ( m_RecFileName == \"\" )\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"FileName for rec-file empty\");\n }\n \n if( m_RecFileName != \"\")\n {\n FILE *f = fopen(m_RecFileName.c_str(), \"r\");\n if(f==NULL)\n {\n throw itk::ImageFileReaderException(__FILE__, __LINE__, \"Could not open rec-file.\");\n }\n\n int zstart, zmax;\n int tstart, tmax;\n\n zstart=output->GetRequestedRegion().GetIndex(2);\n tstart=output->GetRequestedRegion().GetIndex(3);\n\n zmax=zstart+output->GetRequestedRegion().GetSize(2);\n tmax=tstart+output->GetRequestedRegion().GetSize(3);\n\n int sliceSize=output->GetDimension(0)*output->GetDimension(1)*output->GetPixelType().GetBpe()\/8; \t \n void *data = malloc(sliceSize);\n\n bool ignore4Dtopogram=false;\n {\n int slicePlusTimeSize=output->GetDimension(0)*output->GetDimension(1)*output->GetDimension(3)*output->GetPixelType().GetBpe()\/8;\n if(output->GetDimension(3)>1)\n ignore4Dtopogram=true;\n\n int z,t;\n for(t=tstart;tSetSlice(data,z,t,0);\n }\n }\n \/\/else\n \/\/{\n \/\/ for(;zSetSlice(data,z,0,0);\n \/\/ }\n \/\/}\n free(data);\n }\n}\n\nmitk::ParRecFileReader::ParRecFileReader()\n: m_FileName(\"\"), m_FilePrefix(\"\"), m_FilePattern(\"\")\n{\n}\n\nmitk::ParRecFileReader::~ParRecFileReader()\n{\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"Image.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"..\/graphics\/Filterfliprgb.h\"\n\n#include \"SDLDisplayEngine.h\"\n#include \"OGLSurface.h\"\n\n#include \n\n#include \n#include \n\nusing namespace std;\n\nnamespace avg {\n\nImage::Image(OGLSurface * pSurface, const string& sFilename)\n : m_sFilename(sFilename),\n m_pBmp(createDefaultBitmap()),\n m_pSurface(pSurface),\n m_pEngine(0),\n m_State(NOT_AVAILABLE)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n load();\n}\n\nImage::~Image()\n{\n if (m_State == GPU) {\n m_pSurface->destroy();\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n \nvoid Image::setBitmap(const Bitmap * pBmp)\n{\n if(!pBmp) {\n throw Exception(AVG_ERR_UNSUPPORTED, \"setBitmap(): bitmap must not be None!\");\n }\n PixelFormat pf = calcSurfacePF(*pBmp);\n if (m_pEngine) {\n if (m_State == NOT_AVAILABLE || m_pSurface->getSize() != pBmp->getSize() || \n m_pSurface->getPixelFormat() != pf)\n {\n m_pSurface->create(pBmp->getSize(), pf);\n } \n BitmapPtr pSurfaceBmp = m_pSurface->lockBmp();\n pSurfaceBmp->copyPixels(*pBmp);\n m_pSurface->unlockBmps();\n m_pBmp=BitmapPtr(createDefaultBitmap());\n m_State = GPU;\n } else {\n m_pBmp = BitmapPtr(new Bitmap(pBmp->getSize(), pf, \"\"));\n m_pBmp->copyPixels(*pBmp);\n m_State = CPU;\n }\n m_sFilename = \"\";\n\n}\n\nvoid Image::moveToGPU(SDLDisplayEngine* pEngine)\n{\n m_pEngine = pEngine;\n if (m_pScene) {\n m_pSurface->create(m_pScene->getSize(), B8G8R8X8);\n m_pSurface->setTexID(m_pScene->getTexID());\n m_State = GPU;\n } else {\n if (m_State == CPU) {\n m_State = GPU;\n setupSurface();\n }\n }\n}\n\nvoid Image::moveToCPU()\n{\n if (m_State != GPU) {\n return;\n }\n\n if (!m_pScene) {\n m_pBmp = m_pSurface->readbackBmp();\n }\n discardOnCPU();\n}\n\nvoid Image::discardOnCPU()\n{\n if (m_State != GPU) {\n return;\n }\n\n m_pEngine = 0;\n m_pSurface->destroy();\n if (!m_pScene) {\n m_sFilename = \"\";\n m_pBmp = BitmapPtr(createDefaultBitmap());\n m_State = CPU;\n }\n}\n\nvoid Image::setFilename(const std::string& sFilename)\n{\n if (m_State == GPU) {\n m_pSurface->destroy();\n }\n m_pScene = OffscreenScenePtr();\n m_State = NOT_AVAILABLE;\n m_pBmp = BitmapPtr(createDefaultBitmap());\n m_sFilename = sFilename;\n load();\n if (m_pEngine) {\n moveToGPU(m_pEngine);\n }\n}\n\nvoid Image::setScene(OffscreenScenePtr pScene)\n{\n if (pScene == m_pScene) {\n return;\n }\n if (!pScene) {\n m_sFilename = \"\";\n switch(m_State) {\n case CPU:\n m_pBmp = BitmapPtr(createDefaultBitmap());\n break;\n case GPU:\n m_pSurface->destroy();\n break;\n default:\n break;\n }\n }\n m_pScene = pScene;\n m_State = CPU;\n if (m_pEngine) {\n m_pSurface->create(m_pScene->getSize(), B8G8R8X8);\n m_pSurface->setTexID(m_pScene->getTexID());\n moveToGPU(m_pEngine);\n }\n}\n\nOffscreenScenePtr Image::getScene() const\n{\n return m_pScene;\n}\n\nconst string& Image::getFilename() const\n{\n return m_sFilename;\n}\n\nBitmapPtr Image::getBitmap()\n{\n if (m_State == GPU) {\n return m_pSurface->readbackBmp();\n } else {\n if (m_pScene) {\n return BitmapPtr();\n } else {\n return BitmapPtr(new Bitmap(*m_pBmp));\n }\n }\n}\n\nIntPoint Image::getSize()\n{\n if (m_State == GPU) {\n return m_pSurface->getSize();\n } else {\n if (m_pScene) {\n return m_pScene->getSize();\n } else {\n return m_pBmp->getSize();\n }\n }\n}\n\nPixelFormat Image::getPixelFormat()\n{\n if (m_State == GPU) {\n return m_pSurface->getPixelFormat();\n } else {\n if (m_pScene) {\n return B8G8R8X8;\n } else {\n return m_pBmp->getPixelFormat();\n }\n }\n}\n\nOGLSurface* Image::getSurface()\n{\n AVG_ASSERT(m_State != CPU);\n return m_pSurface;\n}\n\nImage::State Image::getState()\n{\n return m_State;\n}\n\nSDLDisplayEngine* Image::getEngine()\n{\n return m_pEngine;\n}\n\nvoid Image::load()\n{\n if (m_sFilename == \"\") {\n return;\n }\n AVG_TRACE(Logger::MEMORY, \"Loading \" << m_sFilename);\n m_pBmp = BitmapPtr(new Bitmap(m_sFilename));\n m_State = CPU;\n}\n\nvoid Image::setupSurface()\n{\n PixelFormat pf = calcSurfacePF(*m_pBmp);\n m_pSurface->create(m_pBmp->getSize(), pf);\n BitmapPtr pSurfaceBmp = m_pSurface->lockBmp();\n pSurfaceBmp->copyPixels(*m_pBmp);\n m_pSurface->unlockBmps();\n m_pBmp=BitmapPtr(createDefaultBitmap());\n}\n\nPixelFormat Image::calcSurfacePF(const Bitmap& bmp)\n{\n PixelFormat pf;\n pf = B8G8R8X8;\n if (bmp.hasAlpha()) {\n pf = B8G8R8A8;\n }\n if (bmp.getPixelFormat() == I8) {\n pf = I8;\n }\n return pf;\n}\n\nBitmap* Image::createDefaultBitmap() const\n{\n return new Bitmap(IntPoint(1,1), B8G8R8X8);\n}\n\n}\nFixed discarding of images on unlink(false) (Bug #127).\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\n#include \"Image.h\"\n\n#include \"..\/base\/Logger.h\"\n#include \"..\/base\/Exception.h\"\n#include \"..\/base\/ObjectCounter.h\"\n\n#include \"..\/graphics\/Filterfliprgb.h\"\n\n#include \"SDLDisplayEngine.h\"\n#include \"OGLSurface.h\"\n\n#include \n\n#include \n#include \n\nusing namespace std;\n\nnamespace avg {\n\nImage::Image(OGLSurface * pSurface, const string& sFilename)\n : m_sFilename(sFilename),\n m_pBmp(createDefaultBitmap()),\n m_pSurface(pSurface),\n m_pEngine(0),\n m_State(NOT_AVAILABLE)\n{\n ObjectCounter::get()->incRef(&typeid(*this));\n load();\n}\n\nImage::~Image()\n{\n if (m_State == GPU) {\n m_pSurface->destroy();\n }\n ObjectCounter::get()->decRef(&typeid(*this));\n}\n \nvoid Image::setBitmap(const Bitmap * pBmp)\n{\n if(!pBmp) {\n throw Exception(AVG_ERR_UNSUPPORTED, \"setBitmap(): bitmap must not be None!\");\n }\n PixelFormat pf = calcSurfacePF(*pBmp);\n if (m_pEngine) {\n if (m_State == NOT_AVAILABLE || m_pSurface->getSize() != pBmp->getSize() || \n m_pSurface->getPixelFormat() != pf)\n {\n m_pSurface->create(pBmp->getSize(), pf);\n } \n BitmapPtr pSurfaceBmp = m_pSurface->lockBmp();\n pSurfaceBmp->copyPixels(*pBmp);\n m_pSurface->unlockBmps();\n m_pBmp=BitmapPtr(createDefaultBitmap());\n m_State = GPU;\n } else {\n m_pBmp = BitmapPtr(new Bitmap(pBmp->getSize(), pf, \"\"));\n m_pBmp->copyPixels(*pBmp);\n m_State = CPU;\n }\n m_sFilename = \"\";\n\n}\n\nvoid Image::moveToGPU(SDLDisplayEngine* pEngine)\n{\n m_pEngine = pEngine;\n if (m_pScene) {\n m_pSurface->create(m_pScene->getSize(), B8G8R8X8);\n m_pSurface->setTexID(m_pScene->getTexID());\n m_State = GPU;\n } else {\n if (m_State == CPU) {\n m_State = GPU;\n setupSurface();\n }\n }\n}\n\nvoid Image::moveToCPU()\n{\n if (m_State != GPU) {\n return;\n }\n\n if (!m_pScene) {\n m_pBmp = m_pSurface->readbackBmp();\n m_State = CPU;\n }\n m_pEngine = 0;\n m_pSurface->destroy();\n}\n\nvoid Image::discardOnCPU()\n{\n if (m_State != GPU) {\n return;\n }\n\n m_pEngine = 0;\n m_pSurface->destroy();\n if (!m_pScene) {\n m_sFilename = \"\";\n m_pBmp = BitmapPtr(createDefaultBitmap());\n m_State = CPU;\n }\n}\n\nvoid Image::setFilename(const std::string& sFilename)\n{\n if (m_State == GPU) {\n m_pSurface->destroy();\n }\n m_pScene = OffscreenScenePtr();\n m_State = NOT_AVAILABLE;\n m_pBmp = BitmapPtr(createDefaultBitmap());\n m_sFilename = sFilename;\n load();\n if (m_pEngine) {\n moveToGPU(m_pEngine);\n }\n}\n\nvoid Image::setScene(OffscreenScenePtr pScene)\n{\n if (pScene == m_pScene) {\n return;\n }\n if (!pScene) {\n m_sFilename = \"\";\n switch(m_State) {\n case CPU:\n m_pBmp = BitmapPtr(createDefaultBitmap());\n break;\n case GPU:\n m_pSurface->destroy();\n break;\n default:\n break;\n }\n }\n m_pScene = pScene;\n m_State = CPU;\n if (m_pEngine) {\n m_pSurface->create(m_pScene->getSize(), B8G8R8X8);\n m_pSurface->setTexID(m_pScene->getTexID());\n moveToGPU(m_pEngine);\n }\n}\n\nOffscreenScenePtr Image::getScene() const\n{\n return m_pScene;\n}\n\nconst string& Image::getFilename() const\n{\n return m_sFilename;\n}\n\nBitmapPtr Image::getBitmap()\n{\n if (m_State == GPU) {\n return m_pSurface->readbackBmp();\n } else {\n if (m_pScene) {\n return BitmapPtr();\n } else {\n return BitmapPtr(new Bitmap(*m_pBmp));\n }\n }\n}\n\nIntPoint Image::getSize()\n{\n if (m_State == GPU) {\n return m_pSurface->getSize();\n } else {\n if (m_pScene) {\n return m_pScene->getSize();\n } else {\n return m_pBmp->getSize();\n }\n }\n}\n\nPixelFormat Image::getPixelFormat()\n{\n if (m_State == GPU) {\n return m_pSurface->getPixelFormat();\n } else {\n if (m_pScene) {\n return B8G8R8X8;\n } else {\n return m_pBmp->getPixelFormat();\n }\n }\n}\n\nOGLSurface* Image::getSurface()\n{\n AVG_ASSERT(m_State != CPU);\n return m_pSurface;\n}\n\nImage::State Image::getState()\n{\n return m_State;\n}\n\nSDLDisplayEngine* Image::getEngine()\n{\n return m_pEngine;\n}\n\nvoid Image::load()\n{\n if (m_sFilename == \"\") {\n return;\n }\n AVG_TRACE(Logger::MEMORY, \"Loading \" << m_sFilename);\n m_pBmp = BitmapPtr(new Bitmap(m_sFilename));\n m_State = CPU;\n}\n\nvoid Image::setupSurface()\n{\n PixelFormat pf = calcSurfacePF(*m_pBmp);\n m_pSurface->create(m_pBmp->getSize(), pf);\n BitmapPtr pSurfaceBmp = m_pSurface->lockBmp();\n pSurfaceBmp->copyPixels(*m_pBmp);\n m_pSurface->unlockBmps();\n m_pBmp=BitmapPtr(createDefaultBitmap());\n}\n\nPixelFormat Image::calcSurfacePF(const Bitmap& bmp)\n{\n PixelFormat pf;\n pf = B8G8R8X8;\n if (bmp.hasAlpha()) {\n pf = B8G8R8A8;\n }\n if (bmp.getPixelFormat() == I8) {\n pf = I8;\n }\n return pf;\n}\n\nBitmap* Image::createDefaultBitmap() const\n{\n return new Bitmap(IntPoint(1,1), B8G8R8X8);\n}\n\n}\n<|endoftext|>"} {"text":"\n#include \"openmc\/progress_bar.h\"\n\n#include \n#include \n#include \n\n#define BAR_WIDTH 72\n\nProgressBar::ProgressBar() {\n \/\/ bar = \"???% | |\";\n\n set_value(0.0);\n}\n\nvoid\nProgressBar::set_value(double val) {\n \/\/ set the bar percentage\n if (val >= 100.0) {\n bar.append(\"100\");\n } else if (val <= 0.0) {\n bar.append(\" 0\");\n } else {\n std::stringstream ss;\n ss << std::setfill(' ') << std::setw(3) << (int)val;\n bar.append(ss.str());\n }\n\n bar.append(\"% |\");\n\n \/\/ remaining width of the bar\n int remain = BAR_WIDTH - bar.size() - 1;\n \n \/\/ set the bar width\n if (val >= 100.0) {\n bar.append(remain, '=');\n } else {\n int width = (int)(65*val\/100);\n std::cout << \"Setting width: \" << width;\n bar.append(width, '=');\n bar.append(1, '>');\n bar.append(remain-width-1, ' ');\n }\n\n bar.append(\"|\");\n \n \/\/ write the bar\n std::cout << '\\r' << bar << std::flush;\n\n \/\/ reset the bar value\n bar = \"\"; \/\/???% | |\";\n}\nRemoving unused code and print.\n#include \"openmc\/progress_bar.h\"\n\n#include \n#include \n#include \n\n#define BAR_WIDTH 72\n\nProgressBar::ProgressBar() {\n bar = \"\";\n set_value(0.0);\n}\n\nvoid\nProgressBar::set_value(double val) {\n \/\/ set the bar percentage\n if (val >= 100.0) {\n bar.append(\"100\");\n } else if (val <= 0.0) {\n bar.append(\" 0\");\n } else {\n std::stringstream ss;\n ss << std::setfill(' ') << std::setw(3) << (int)val;\n bar.append(ss.str());\n }\n\n bar.append(\"% |\");\n\n \/\/ remaining width of the bar\n int remain = BAR_WIDTH - bar.size() - 1;\n \n \/\/ set the bar width\n if (val >= 100.0) {\n bar.append(remain, '=');\n } else {\n int width = (int)(65*val\/100);\n bar.append(width, '=');\n bar.append(1, '>');\n bar.append(remain-width-1, ' ');\n }\n\n bar.append(\"|\");\n \n \/\/ write the bar\n std::cout << '\\r' << bar << std::flush;\n\n \/\/ reset the bar value\n bar = \"\";\n}\n<|endoftext|>"} {"text":"\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | Copyright (c) 2012-2017 The Swoole Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Tianfeng Han |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"swoole.h\"\n#include \"swoole_string.h\"\n#include \"swoole_socket.h\"\n#include \"swoole_protocol.h\"\n#include \"swoole_log.h\"\n\nnamespace swoole {\n\/**\n * return the package total length\n *\/\nssize_t Protocol::default_length_func(Protocol *protocol, network::Socket *socket, const char *data, uint32_t size) {\n uint16_t length_offset = protocol->package_length_offset;\n uint8_t package_length_size =\n protocol->get_package_length_size ? protocol->get_package_length_size(socket) : protocol->package_length_size;\n int32_t body_length;\n\n if (package_length_size == 0) {\n \/\/ protocol error\n return SW_ERR;\n }\n \/**\n * no have length field, wait more data\n *\/\n if (size < length_offset + package_length_size) {\n protocol->real_header_length = length_offset + package_length_size;\n return 0;\n }\n body_length = swoole_unpack(protocol->package_length_type, data + length_offset);\n \/\/ Length error\n \/\/ Protocol length is not legitimate, out of bounds or exceed the allocated length\n if (body_length < 0) {\n swWarn(\"invalid package (size=%d) from socket#%u<%s:%d>\",\n size,\n socket->fd,\n socket->info.get_ip(),\n socket->info.get_port());\n return SW_ERR;\n }\n swDebug(\"length=%d\", protocol->package_body_offset + body_length);\n\n \/\/ total package length\n return protocol->package_body_offset + body_length;\n}\n\nint Protocol::recv_split_by_eof(network::Socket *socket, String *buffer) {\n if (buffer->length < package_eof_len) {\n return SW_CONTINUE;\n }\n\n int retval;\n\n size_t n = buffer->split(package_eof, package_eof_len, [&](const char *data, size_t length) -> int {\n if (onPackage(this, socket, data, length) < 0) {\n retval = SW_CLOSE;\n return false;\n }\n if (socket->removed) {\n return false;\n }\n return true;\n });\n\n if (socket->removed) {\n return SW_CLOSE;\n }\n\n if (n < 0) {\n return retval;\n } else if (n == 0) {\n return SW_CONTINUE;\n } else if (n < buffer->length) {\n off_t offset;\n buffer->reduce(n);\n offset = buffer->length - package_eof_len;\n buffer->offset = offset > 0 ? offset : 0;\n } else {\n swString_clear(buffer);\n }\n\n#ifdef SW_USE_OPENSSL\n if (socket->ssl) {\n return SW_CONTINUE;\n }\n#endif\n\n return SW_OK;\n}\n\n\/**\n * @return SW_ERR: close the connection\n * @return SW_OK: continue\n *\/\nint Protocol::recv_with_length_protocol(network::Socket *socket, String *buffer) {\n ssize_t package_length;\n uint8_t _package_length_size = get_package_length_size ? get_package_length_size(socket) : package_length_size;\n uint32_t recv_size;\n ssize_t recv_n = 0;\n\n if (_package_length_size == 0) {\n \/\/ protocol error\n return SW_ERR;\n }\n\n if (socket->skip_recv) {\n socket->skip_recv = 0;\n goto _do_get_length;\n }\n\n_do_recv:\n if (socket->removed) {\n return SW_OK;\n }\n if (buffer->offset > 0) {\n recv_size = buffer->offset - buffer->length;\n } else {\n recv_size = package_length_offset + _package_length_size;\n }\n\n recv_n = socket->recv(buffer->str + buffer->length, recv_size, 0);\n if (recv_n < 0) {\n switch (socket->catch_error(errno)) {\n case SW_ERROR:\n swSysWarn(\"recv(%d, %d) failed\", socket->fd, recv_size);\n return SW_OK;\n case SW_CLOSE:\n return SW_ERR;\n default:\n return SW_OK;\n }\n } else if (recv_n == 0) {\n return SW_ERR;\n } else {\n buffer->length += recv_n;\n\n if (socket->recv_wait) {\n if (buffer->length >= (size_t) buffer->offset) {\n _do_dispatch:\n if (onPackage(this, socket, buffer->str, buffer->offset) < 0) {\n return SW_ERR;\n }\n if (socket->removed) {\n return SW_OK;\n }\n socket->recv_wait = 0;\n\n if (buffer->length > (size_t) buffer->offset) {\n buffer->reduce(buffer->offset);\n goto _do_get_length;\n } else {\n swString_clear(buffer);\n }\n }\n#ifdef SW_USE_OPENSSL\n if (socket->ssl) {\n goto _do_recv;\n }\n#endif\n return SW_OK;\n } else {\n _do_get_length:\n package_length = get_package_length(this, socket, buffer->str, buffer->length);\n \/\/ invalid package, close connection.\n if (package_length < 0) {\n return SW_ERR;\n }\n \/\/ no length\n else if (package_length == 0) {\n if (buffer->length == package_length_offset + package_length_size) {\n swoole_error_log(SW_LOG_WARNING,\n SW_ERROR_PACKAGE_LENGTH_NOT_FOUND,\n \"bad request, No length found in %ld bytes\",\n buffer->length);\n return SW_ERR;\n } else {\n return SW_OK;\n }\n } else if (package_length > package_max_length) {\n swoole_error_log(SW_LOG_WARNING,\n SW_ERROR_PACKAGE_LENGTH_TOO_LARGE,\n \"package is too big, remote_addr=%s:%d, length=%zu\",\n socket->info.get_ip(),\n socket->info.get_port(),\n package_length);\n return SW_ERR;\n }\n \/\/ get length success\n else {\n if (buffer->size < (size_t) package_length) {\n if (swString_extend(buffer, package_length) < 0) {\n return SW_ERR;\n }\n }\n socket->recv_wait = 1;\n buffer->offset = package_length;\n\n if (buffer->length >= (size_t) package_length) {\n goto _do_dispatch;\n } else {\n goto _do_recv;\n }\n }\n }\n }\n return SW_OK;\n}\n\n\/**\n * @return SW_ERR: close the connection\n * @return SW_OK: continue\n *\/\nint Protocol::recv_with_eof_protocol(network::Socket *socket, String *buffer) {\n bool recv_again = false;\n int buf_size;\n\n_recv_data:\n buf_size = buffer->size - buffer->length;\n char *buf_ptr = buffer->str + buffer->length;\n\n if (buf_size > SW_BUFFER_SIZE_STD) {\n buf_size = SW_BUFFER_SIZE_STD;\n }\n\n int n = socket->recv(buf_ptr, buf_size, 0);\n if (n < 0) {\n switch (socket->catch_error(errno)) {\n case SW_ERROR:\n swSysWarn(\"recv from socket#%d failed\", socket->fd);\n return SW_OK;\n case SW_CLOSE:\n return SW_ERR;\n default:\n return SW_OK;\n }\n } else if (n == 0) {\n return SW_ERR;\n } else {\n buffer->length += n;\n\n if (buffer->length < package_eof_len) {\n return SW_OK;\n }\n\n if (split_by_eof) {\n int retval = recv_split_by_eof(socket, buffer);\n if (retval == SW_CONTINUE) {\n recv_again = true;\n } else if (retval == SW_CLOSE) {\n return SW_ERR;\n } else {\n return SW_OK;\n }\n } else if (memcmp(buffer->str + buffer->length - package_eof_len,\n package_eof,\n package_eof_len) == 0) {\n buffer->offset = buffer->length;\n if (onPackage(this, socket, buffer->str, buffer->length) < 0) {\n return SW_ERR;\n }\n if (socket->removed) {\n return SW_OK;\n }\n swString_clear(buffer);\n#ifdef SW_USE_OPENSSL\n if (socket->ssl && SSL_pending(socket->ssl) > 0) {\n goto _recv_data;\n }\n#endif\n return SW_OK;\n }\n\n \/\/ over max length, will discard\n if (buffer->length == package_max_length) {\n swWarn(\"Package is too big. package_length=%d\", (int) buffer->length);\n return SW_ERR;\n }\n\n \/\/ buffer is full, may have not read data\n if (buffer->length == buffer->size) {\n recv_again = true;\n if (buffer->size < package_max_length) {\n uint32_t extend_size = swoole_size_align(buffer->size * 2, SwooleG.pagesize);\n if (extend_size > package_max_length) {\n extend_size = package_max_length;\n }\n if (swString_extend(buffer, extend_size) < 0) {\n return SW_ERR;\n }\n }\n }\n \/\/ no eof\n if (recv_again) {\n goto _recv_data;\n }\n }\n return SW_OK;\n}\n\n}\nFixed: fix type-limits error (#3560)\/*\n +----------------------------------------------------------------------+\n | Swoole |\n +----------------------------------------------------------------------+\n | Copyright (c) 2012-2017 The Swoole Group |\n +----------------------------------------------------------------------+\n | This source file is subject to version 2.0 of the Apache license, |\n | that is bundled with this package in the file LICENSE, and is |\n | available through the world-wide-web at the following url: |\n | http:\/\/www.apache.org\/licenses\/LICENSE-2.0.html |\n | If you did not receive a copy of the Apache2.0 license and are unable|\n | to obtain it through the world-wide-web, please send a note to |\n | license@swoole.com so we can mail you a copy immediately. |\n +----------------------------------------------------------------------+\n | Author: Tianfeng Han |\n +----------------------------------------------------------------------+\n *\/\n\n#include \"swoole.h\"\n#include \"swoole_string.h\"\n#include \"swoole_socket.h\"\n#include \"swoole_protocol.h\"\n#include \"swoole_log.h\"\n\nnamespace swoole {\n\/**\n * return the package total length\n *\/\nssize_t Protocol::default_length_func(Protocol *protocol, network::Socket *socket, const char *data, uint32_t size) {\n uint16_t length_offset = protocol->package_length_offset;\n uint8_t package_length_size =\n protocol->get_package_length_size ? protocol->get_package_length_size(socket) : protocol->package_length_size;\n int32_t body_length;\n\n if (package_length_size == 0) {\n \/\/ protocol error\n return SW_ERR;\n }\n \/**\n * no have length field, wait more data\n *\/\n if (size < length_offset + package_length_size) {\n protocol->real_header_length = length_offset + package_length_size;\n return 0;\n }\n body_length = swoole_unpack(protocol->package_length_type, data + length_offset);\n \/\/ Length error\n \/\/ Protocol length is not legitimate, out of bounds or exceed the allocated length\n if (body_length < 0) {\n swWarn(\"invalid package (size=%d) from socket#%u<%s:%d>\",\n size,\n socket->fd,\n socket->info.get_ip(),\n socket->info.get_port());\n return SW_ERR;\n }\n swDebug(\"length=%d\", protocol->package_body_offset + body_length);\n\n \/\/ total package length\n return protocol->package_body_offset + body_length;\n}\n\nint Protocol::recv_split_by_eof(network::Socket *socket, String *buffer) {\n if (buffer->length < package_eof_len) {\n return SW_CONTINUE;\n }\n\n int retval;\n\n ssize_t n = buffer->split(package_eof, package_eof_len, [&](const char *data, size_t length) -> int {\n if (onPackage(this, socket, data, length) < 0) {\n retval = SW_CLOSE;\n return false;\n }\n if (socket->removed) {\n return false;\n }\n return true;\n });\n\n if (socket->removed) {\n return SW_CLOSE;\n }\n\n if (n < 0) {\n return retval;\n } else if (n == 0) {\n return SW_CONTINUE;\n } else if (n < buffer->length) {\n off_t offset;\n buffer->reduce(n);\n offset = buffer->length - package_eof_len;\n buffer->offset = offset > 0 ? offset : 0;\n } else {\n swString_clear(buffer);\n }\n\n#ifdef SW_USE_OPENSSL\n if (socket->ssl) {\n return SW_CONTINUE;\n }\n#endif\n\n return SW_OK;\n}\n\n\/**\n * @return SW_ERR: close the connection\n * @return SW_OK: continue\n *\/\nint Protocol::recv_with_length_protocol(network::Socket *socket, String *buffer) {\n ssize_t package_length;\n uint8_t _package_length_size = get_package_length_size ? get_package_length_size(socket) : package_length_size;\n uint32_t recv_size;\n ssize_t recv_n = 0;\n\n if (_package_length_size == 0) {\n \/\/ protocol error\n return SW_ERR;\n }\n\n if (socket->skip_recv) {\n socket->skip_recv = 0;\n goto _do_get_length;\n }\n\n_do_recv:\n if (socket->removed) {\n return SW_OK;\n }\n if (buffer->offset > 0) {\n recv_size = buffer->offset - buffer->length;\n } else {\n recv_size = package_length_offset + _package_length_size;\n }\n\n recv_n = socket->recv(buffer->str + buffer->length, recv_size, 0);\n if (recv_n < 0) {\n switch (socket->catch_error(errno)) {\n case SW_ERROR:\n swSysWarn(\"recv(%d, %d) failed\", socket->fd, recv_size);\n return SW_OK;\n case SW_CLOSE:\n return SW_ERR;\n default:\n return SW_OK;\n }\n } else if (recv_n == 0) {\n return SW_ERR;\n } else {\n buffer->length += recv_n;\n\n if (socket->recv_wait) {\n if (buffer->length >= (size_t) buffer->offset) {\n _do_dispatch:\n if (onPackage(this, socket, buffer->str, buffer->offset) < 0) {\n return SW_ERR;\n }\n if (socket->removed) {\n return SW_OK;\n }\n socket->recv_wait = 0;\n\n if (buffer->length > (size_t) buffer->offset) {\n buffer->reduce(buffer->offset);\n goto _do_get_length;\n } else {\n swString_clear(buffer);\n }\n }\n#ifdef SW_USE_OPENSSL\n if (socket->ssl) {\n goto _do_recv;\n }\n#endif\n return SW_OK;\n } else {\n _do_get_length:\n package_length = get_package_length(this, socket, buffer->str, buffer->length);\n \/\/ invalid package, close connection.\n if (package_length < 0) {\n return SW_ERR;\n }\n \/\/ no length\n else if (package_length == 0) {\n if (buffer->length == package_length_offset + package_length_size) {\n swoole_error_log(SW_LOG_WARNING,\n SW_ERROR_PACKAGE_LENGTH_NOT_FOUND,\n \"bad request, No length found in %ld bytes\",\n buffer->length);\n return SW_ERR;\n } else {\n return SW_OK;\n }\n } else if (package_length > package_max_length) {\n swoole_error_log(SW_LOG_WARNING,\n SW_ERROR_PACKAGE_LENGTH_TOO_LARGE,\n \"package is too big, remote_addr=%s:%d, length=%zu\",\n socket->info.get_ip(),\n socket->info.get_port(),\n package_length);\n return SW_ERR;\n }\n \/\/ get length success\n else {\n if (buffer->size < (size_t) package_length) {\n if (swString_extend(buffer, package_length) < 0) {\n return SW_ERR;\n }\n }\n socket->recv_wait = 1;\n buffer->offset = package_length;\n\n if (buffer->length >= (size_t) package_length) {\n goto _do_dispatch;\n } else {\n goto _do_recv;\n }\n }\n }\n }\n return SW_OK;\n}\n\n\/**\n * @return SW_ERR: close the connection\n * @return SW_OK: continue\n *\/\nint Protocol::recv_with_eof_protocol(network::Socket *socket, String *buffer) {\n bool recv_again = false;\n int buf_size;\n\n_recv_data:\n buf_size = buffer->size - buffer->length;\n char *buf_ptr = buffer->str + buffer->length;\n\n if (buf_size > SW_BUFFER_SIZE_STD) {\n buf_size = SW_BUFFER_SIZE_STD;\n }\n\n int n = socket->recv(buf_ptr, buf_size, 0);\n if (n < 0) {\n switch (socket->catch_error(errno)) {\n case SW_ERROR:\n swSysWarn(\"recv from socket#%d failed\", socket->fd);\n return SW_OK;\n case SW_CLOSE:\n return SW_ERR;\n default:\n return SW_OK;\n }\n } else if (n == 0) {\n return SW_ERR;\n } else {\n buffer->length += n;\n\n if (buffer->length < package_eof_len) {\n return SW_OK;\n }\n\n if (split_by_eof) {\n int retval = recv_split_by_eof(socket, buffer);\n if (retval == SW_CONTINUE) {\n recv_again = true;\n } else if (retval == SW_CLOSE) {\n return SW_ERR;\n } else {\n return SW_OK;\n }\n } else if (memcmp(buffer->str + buffer->length - package_eof_len,\n package_eof,\n package_eof_len) == 0) {\n buffer->offset = buffer->length;\n if (onPackage(this, socket, buffer->str, buffer->length) < 0) {\n return SW_ERR;\n }\n if (socket->removed) {\n return SW_OK;\n }\n swString_clear(buffer);\n#ifdef SW_USE_OPENSSL\n if (socket->ssl && SSL_pending(socket->ssl) > 0) {\n goto _recv_data;\n }\n#endif\n return SW_OK;\n }\n\n \/\/ over max length, will discard\n if (buffer->length == package_max_length) {\n swWarn(\"Package is too big. package_length=%d\", (int) buffer->length);\n return SW_ERR;\n }\n\n \/\/ buffer is full, may have not read data\n if (buffer->length == buffer->size) {\n recv_again = true;\n if (buffer->size < package_max_length) {\n uint32_t extend_size = swoole_size_align(buffer->size * 2, SwooleG.pagesize);\n if (extend_size > package_max_length) {\n extend_size = package_max_length;\n }\n if (swString_extend(buffer, extend_size) < 0) {\n return SW_ERR;\n }\n }\n }\n \/\/ no eof\n if (recv_again) {\n goto _recv_data;\n }\n }\n return SW_OK;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2015 CNRS\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ .\n\n#ifndef __se3_python_model_hpp__\n#define __se3_python_model_hpp__\n\n#include \n#include \n#include \n\n#include \"pinocchio\/multibody\/model.hpp\"\n#include \"pinocchio\/multibody\/parser\/sample-models.hpp\"\n#include \"pinocchio\/python\/se3.hpp\"\n#include \"pinocchio\/python\/eigen_container.hpp\"\n#include \"pinocchio\/python\/handler.hpp\"\n\n\nnamespace se3\n{\n namespace python\n {\n namespace bp = boost::python;\n\n typedef Handler ModelHandler;\n\n struct ModelPythonVisitor\n : public boost::python::def_visitor< ModelPythonVisitor >\n {\n public:\n typedef Model::Index Index;\n typedef eigenpy::UnalignedEquivalent::type Motion_fx;\n typedef eigenpy::UnalignedEquivalent::type SE3_fx;\n typedef eigenpy::UnalignedEquivalent::type Inertia_fx;\n\n struct add_body_visitor : public boost::static_visitor\n {\n ModelHandler & _model;\n Model::Index & _index;\n const SE3_fx & _placement;\n const Inertia_fx & _inertia;\n const std::string & _jName;\n const std::string & _bName;\n bool _visual;\n\n add_body_visitor( ModelHandler & model,\n Model::Index & idx, const SE3_fx & placement,\n const Inertia_fx & Y, const std::string & jointName,\n const std::string & bodyName, bool visual)\n : _model(model)\n , _index(idx)\n , _placement(placement)\n , _inertia(Y)\n , _jName(jointName)\n , _bName(bodyName)\n , _visual(visual)\n {}\n\n template Model::Index operator()( T & operand ) const\n {\n return _model->addBody(_index, operand, _placement, _inertia, _jName, _bName, _visual);\n }\n };\n\n public:\n\n \/* --- Convert From C++ to Python ------------------------------------- *\/\n \/\/ static PyObject* convert(Model const& modelConstRef)\n \/\/ {\n \/\/ \tModel * ptr = const_cast(&modelConstRef);\n \/\/ \treturn boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());\n \/\/ }\n static PyObject* convert(ModelHandler::SmartPtr_t const& ptr)\n {\n\treturn boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());\n }\n\n \/* --- Exposing C++ API to python through the handler ----------------- *\/\n template\n void visit(PyClass& cl) const \n {\n\tcl\n\t .def(\"getBodyId\",&ModelPythonVisitor::getBodyId)\n\t .def(\"createData\",&ModelPythonVisitor::createData)\n\n\t .def(\"__str__\",&ModelPythonVisitor::toString)\n\n\t .add_property(\"nq\", &ModelPythonVisitor::nq)\n\t .add_property(\"nv\", &ModelPythonVisitor::nv)\n\t .add_property(\"nbody\", &ModelPythonVisitor::nbody)\n\t .add_property(\"inertias\",\n\t\t\tbp::make_function(&ModelPythonVisitor::inertias,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n\t .add_property(\"jointPlacements\",\n\t\t\tbp::make_function(&ModelPythonVisitor::jointPlacements,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n .add_property(\"joints\",\n bp::make_function(&ModelPythonVisitor::joints,\n bp::return_internal_reference<>()) )\n\t .add_property(\"parents\", \n\t\t\tbp::make_function(&ModelPythonVisitor::parents,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n\t .add_property(\"names\",\n\t\t\tbp::make_function(&ModelPythonVisitor::names,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n .add_property(\"bodyNames\",\n\t\t bp::make_function(&ModelPythonVisitor::bodyNames,\n bp::return_internal_reference<>()) )\n .add_property(\"hasVisual\",\n bp::make_function(&ModelPythonVisitor::hasVisual,\n bp::return_internal_reference<>()) )\n\n .def(\"addBody\",&ModelPythonVisitor::addJointToModel)\n\n .add_property(\"nFixBody\", &ModelPythonVisitor::nFixBody)\n .add_property(\"fix_lmpMi\", bp::make_function(&ModelPythonVisitor::fix_lmpMi, bp::return_internal_reference<>()) )\n .add_property(\"fix_lastMovingParent\",bp::make_function(&ModelPythonVisitor::fix_lastMovingParent,bp::return_internal_reference<>()) )\n .add_property(\"fix_hasVisual\", bp::make_function(&ModelPythonVisitor::fix_hasVisual, bp::return_internal_reference<>()) )\n .add_property(\"fix_bodyNames\", bp::make_function(&ModelPythonVisitor::fix_bodyNames, bp::return_internal_reference<>()) )\n\n\n .add_property(\"gravity\",&ModelPythonVisitor::gravity,&ModelPythonVisitor::setGravity)\n\t .def(\"BuildEmptyModel\",&ModelPythonVisitor::maker_empty)\n\t .staticmethod(\"BuildEmptyModel\")\n\t .def(\"BuildHumanoidSimple\",&ModelPythonVisitor::maker_humanoidSimple)\n\t .staticmethod(\"BuildHumanoidSimple\")\n\t ;\n }\n\n static Model::Index getBodyId( const ModelHandler & modelPtr, const std::string & name )\n { return modelPtr->getBodyId(name); }\n static boost::shared_ptr createData(const ModelHandler& m )\n {\treturn boost::shared_ptr( new Data(*m) ); } \n \n static int nq( ModelHandler & m ) { return m->nq; }\n static int nv( ModelHandler & m ) { return m->nv; }\n static int nbody( ModelHandler & m ) { return m->nbody; }\n static std::vector & inertias( ModelHandler & m ) { return m->inertias; }\n static std::vector & jointPlacements( ModelHandler & m ) { return m->jointPlacements; }\n static JointModelVector & joints( ModelHandler & m ) { return m->joints; }\n static std::vector & parents( ModelHandler & m ) { return m->parents; }\n static std::vector & names ( ModelHandler & m ) { return m->names; }\n static std::vector & bodyNames ( ModelHandler & m ) { return m->bodyNames; }\n static std::vector & hasVisual ( ModelHandler & m ) { return m->hasVisual; }\n\n static Model::Index addJointToModel( ModelHandler & modelPtr,\n Model::Index idx, bp::object joint,\n const SE3_fx & placement,\n const Inertia_fx & Y,\n const std::string & jointName,\n const std::string & bodyName,\n bool visual=false)\n { \n JointModelVariant variant = bp::extract (joint);\n return boost::apply_visitor(add_body_visitor(modelPtr, idx, placement, Y, jointName, bodyName, visual), variant);\n }\n\n static int nFixBody( ModelHandler & m ) { return m->nFixBody; }\n static std::vector & fix_lmpMi ( ModelHandler & m ) { return m->fix_lmpMi; }\n static std::vector & fix_lastMovingParent( ModelHandler & m ) { return m->fix_lastMovingParent; }\n static std::vector & fix_hasVisual ( ModelHandler & m ) { return m->fix_hasVisual; }\n static std::vector & fix_bodyNames ( ModelHandler & m ) { return m->fix_bodyNames; }\n\n static Motion gravity( ModelHandler & m ) { return m->gravity; }\n static void setGravity( ModelHandler & m,const Motion_fx & g ) { m->gravity = g; }\n\n\n static ModelHandler maker_empty()\n {\n\treturn ModelHandler( new Model(),true );\n }\n static ModelHandler maker_humanoidSimple()\n {\n\tModel * model = new Model();\n\tbuildModels::humanoidSimple(*model);\n\treturn ModelHandler( model,true );\n }\n\n static std::string toString(const ModelHandler& m) \n {\t std::ostringstream s; s << *m; return s.str(); }\n\n \/* --- Expose --------------------------------------------------------- *\/\n static void expose()\n {\n\tbp::class_< std::vector >(\"StdVec_Index\")\n\t .def(bp::vector_indexing_suite< std::vector >());\n\tbp::class_< std::vector >(\"StdVec_StdString\")\n\t .def(bp::vector_indexing_suite< std::vector >());\n\tbp::class_< std::vector >(\"StdVec_Bool\")\n\t .def(bp::vector_indexing_suite< std::vector >());\n\tbp::class_< std::vector >(\"StdVec_double\")\n\t .def(bp::vector_indexing_suite< std::vector >());\n bp::class_< JointModelVector >(\"StdVec_JointModelVector\")\n .def(bp::vector_indexing_suite< JointModelVector, true >());\n \n bp::class_(\"Model\",\n \"Articulated rigid body model (const)\",\n bp::no_init)\n .def(ModelPythonVisitor());\n \n\t\/* Not sure if it is a good idea to enable automatic\n\t * conversion. Prevent it for now *\/\n\t\/\/bp::to_python_converter< Model,ModelPythonVisitor >();\n\tbp::to_python_converter< ModelHandler::SmartPtr_t,ModelPythonVisitor >();\n }\n\n\n };\n \n\n\n }} \/\/ namespace se3::python\n\n#endif \/\/ ifndef __se3_python_model_hpp__\n\n[Python] Add StdVec::index binding to emulate python list behavior.\/\/\n\/\/ Copyright (c) 2015 CNRS\n\/\/ Copyright (c) 2015 Wandercraft, 86 rue de Paris 91400 Orsay, France.\n\/\/\n\/\/ This file is part of Pinocchio\n\/\/ Pinocchio is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ Pinocchio is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ Pinocchio If not, see\n\/\/ .\n\n#ifndef __se3_python_model_hpp__\n#define __se3_python_model_hpp__\n\n#include \n#include \n#include \n\n#include \"pinocchio\/multibody\/model.hpp\"\n#include \"pinocchio\/multibody\/parser\/sample-models.hpp\"\n#include \"pinocchio\/python\/se3.hpp\"\n#include \"pinocchio\/python\/eigen_container.hpp\"\n#include \"pinocchio\/python\/handler.hpp\"\n\n\nnamespace se3\n{\n namespace python\n {\n namespace bp = boost::python;\n\n typedef Handler ModelHandler;\n\n struct ModelPythonVisitor\n : public boost::python::def_visitor< ModelPythonVisitor >\n {\n public:\n typedef Model::Index Index;\n typedef eigenpy::UnalignedEquivalent::type Motion_fx;\n typedef eigenpy::UnalignedEquivalent::type SE3_fx;\n typedef eigenpy::UnalignedEquivalent::type Inertia_fx;\n\n struct add_body_visitor : public boost::static_visitor\n {\n ModelHandler & _model;\n Model::Index & _index;\n const SE3_fx & _placement;\n const Inertia_fx & _inertia;\n const std::string & _jName;\n const std::string & _bName;\n bool _visual;\n\n add_body_visitor( ModelHandler & model,\n Model::Index & idx, const SE3_fx & placement,\n const Inertia_fx & Y, const std::string & jointName,\n const std::string & bodyName, bool visual)\n : _model(model)\n , _index(idx)\n , _placement(placement)\n , _inertia(Y)\n , _jName(jointName)\n , _bName(bodyName)\n , _visual(visual)\n {}\n\n template Model::Index operator()( T & operand ) const\n {\n return _model->addBody(_index, operand, _placement, _inertia, _jName, _bName, _visual);\n }\n };\n\n public:\n\n \/* --- Convert From C++ to Python ------------------------------------- *\/\n \/\/ static PyObject* convert(Model const& modelConstRef)\n \/\/ {\n \/\/ \tModel * ptr = const_cast(&modelConstRef);\n \/\/ \treturn boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());\n \/\/ }\n static PyObject* convert(ModelHandler::SmartPtr_t const& ptr)\n {\n\treturn boost::python::incref(boost::python::object(ModelHandler(ptr)).ptr());\n }\n\n \/* --- Exposing C++ API to python through the handler ----------------- *\/\n template\n void visit(PyClass& cl) const \n {\n\tcl\n\t .def(\"getBodyId\",&ModelPythonVisitor::getBodyId)\n\t .def(\"createData\",&ModelPythonVisitor::createData)\n\n\t .def(\"__str__\",&ModelPythonVisitor::toString)\n\n\t .add_property(\"nq\", &ModelPythonVisitor::nq)\n\t .add_property(\"nv\", &ModelPythonVisitor::nv)\n\t .add_property(\"nbody\", &ModelPythonVisitor::nbody)\n\t .add_property(\"inertias\",\n\t\t\tbp::make_function(&ModelPythonVisitor::inertias,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n\t .add_property(\"jointPlacements\",\n\t\t\tbp::make_function(&ModelPythonVisitor::jointPlacements,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n .add_property(\"joints\",\n bp::make_function(&ModelPythonVisitor::joints,\n bp::return_internal_reference<>()) )\n\t .add_property(\"parents\", \n\t\t\tbp::make_function(&ModelPythonVisitor::parents,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n\t .add_property(\"names\",\n\t\t\tbp::make_function(&ModelPythonVisitor::names,\n\t\t\t\t\t bp::return_internal_reference<>()) )\n .add_property(\"bodyNames\",\n\t\t bp::make_function(&ModelPythonVisitor::bodyNames,\n bp::return_internal_reference<>()) )\n .add_property(\"hasVisual\",\n bp::make_function(&ModelPythonVisitor::hasVisual,\n bp::return_internal_reference<>()) )\n\n .def(\"addBody\",&ModelPythonVisitor::addJointToModel)\n\n .add_property(\"nFixBody\", &ModelPythonVisitor::nFixBody)\n .add_property(\"fix_lmpMi\", bp::make_function(&ModelPythonVisitor::fix_lmpMi, bp::return_internal_reference<>()) )\n .add_property(\"fix_lastMovingParent\",bp::make_function(&ModelPythonVisitor::fix_lastMovingParent,bp::return_internal_reference<>()) )\n .add_property(\"fix_hasVisual\", bp::make_function(&ModelPythonVisitor::fix_hasVisual, bp::return_internal_reference<>()) )\n .add_property(\"fix_bodyNames\", bp::make_function(&ModelPythonVisitor::fix_bodyNames, bp::return_internal_reference<>()) )\n\n\n .add_property(\"gravity\",&ModelPythonVisitor::gravity,&ModelPythonVisitor::setGravity)\n\t .def(\"BuildEmptyModel\",&ModelPythonVisitor::maker_empty)\n\t .staticmethod(\"BuildEmptyModel\")\n\t .def(\"BuildHumanoidSimple\",&ModelPythonVisitor::maker_humanoidSimple)\n\t .staticmethod(\"BuildHumanoidSimple\")\n\t ;\n }\n\n static Model::Index getBodyId( const ModelHandler & modelPtr, const std::string & name )\n { return modelPtr->getBodyId(name); }\n static boost::shared_ptr createData(const ModelHandler& m )\n {\treturn boost::shared_ptr( new Data(*m) ); } \n \n static int nq( ModelHandler & m ) { return m->nq; }\n static int nv( ModelHandler & m ) { return m->nv; }\n static int nbody( ModelHandler & m ) { return m->nbody; }\n static std::vector & inertias( ModelHandler & m ) { return m->inertias; }\n static std::vector & jointPlacements( ModelHandler & m ) { return m->jointPlacements; }\n static JointModelVector & joints( ModelHandler & m ) { return m->joints; }\n static std::vector & parents( ModelHandler & m ) { return m->parents; }\n static std::vector & names ( ModelHandler & m ) { return m->names; }\n static std::vector & bodyNames ( ModelHandler & m ) { return m->bodyNames; }\n static std::vector & hasVisual ( ModelHandler & m ) { return m->hasVisual; }\n\n static Model::Index addJointToModel( ModelHandler & modelPtr,\n Model::Index idx, bp::object joint,\n const SE3_fx & placement,\n const Inertia_fx & Y,\n const std::string & jointName,\n const std::string & bodyName,\n bool visual=false)\n { \n JointModelVariant variant = bp::extract (joint);\n return boost::apply_visitor(add_body_visitor(modelPtr, idx, placement, Y, jointName, bodyName, visual), variant);\n }\n\n static int nFixBody( ModelHandler & m ) { return m->nFixBody; }\n static std::vector & fix_lmpMi ( ModelHandler & m ) { return m->fix_lmpMi; }\n static std::vector & fix_lastMovingParent( ModelHandler & m ) { return m->fix_lastMovingParent; }\n static std::vector & fix_hasVisual ( ModelHandler & m ) { return m->fix_hasVisual; }\n static std::vector & fix_bodyNames ( ModelHandler & m ) { return m->fix_bodyNames; }\n\n static Motion gravity( ModelHandler & m ) { return m->gravity; }\n static void setGravity( ModelHandler & m,const Motion_fx & g ) { m->gravity = g; }\n\n\n static ModelHandler maker_empty()\n {\n\treturn ModelHandler( new Model(),true );\n }\n static ModelHandler maker_humanoidSimple()\n {\n\tModel * model = new Model();\n\tbuildModels::humanoidSimple(*model);\n\treturn ModelHandler( model,true );\n }\n\n static std::string toString(const ModelHandler& m) \n {\t std::ostringstream s; s << *m; return s.str(); }\n\n \/\/\/\n \/\/\/ \\brief Provide equivalent to python list index function for\n \/\/\/ vectors.\n \/\/\/\n \/\/\/ \\param[in] x The input vector.\n \/\/\/ \\param[in] v The value of to look for in the vector.\n \/\/\/\n \/\/\/ \\return The index of the matching element of the vector. If\n \/\/\/ no element is found, return -1.\n \/\/\/\n template\n static Model::Index index(std::vector const& x,\n typename std::vector::value_type const& v)\n {\n Model::Index i = 0;\n for(typename std::vector::const_iterator it = x.begin(); it != x.end(); ++it, ++i)\n {\n if(*it == v)\n {\n return i;\n }\n }\n return -1;\n }\n\n \/* --- Expose --------------------------------------------------------- *\/\n static void expose()\n {\n bp::class_< std::vector >(\"StdVec_Index\")\n .def(bp::vector_indexing_suite< std::vector >());\n bp::class_< std::vector >(\"StdVec_StdString\")\n .def(bp::vector_indexing_suite< std::vector >())\n .def(\"index\", &ModelPythonVisitor::index);\n bp::class_< std::vector >(\"StdVec_Bool\")\n .def(bp::vector_indexing_suite< std::vector >());\n bp::class_< std::vector >(\"StdVec_double\")\n .def(bp::vector_indexing_suite< std::vector >());\n bp::class_< JointModelVector >(\"StdVec_JointModelVector\")\n .def(bp::vector_indexing_suite< JointModelVector, true >());\n\n bp::class_(\"Model\",\n \"Articulated rigid body model (const)\",\n bp::no_init)\n .def(ModelPythonVisitor());\n \n\t\/* Not sure if it is a good idea to enable automatic\n\t * conversion. Prevent it for now *\/\n\t\/\/bp::to_python_converter< Model,ModelPythonVisitor >();\n\tbp::to_python_converter< ModelHandler::SmartPtr_t,ModelPythonVisitor >();\n }\n\n\n };\n \n\n\n }} \/\/ namespace se3::python\n\n#endif \/\/ ifndef __se3_python_model_hpp__\n\n<|endoftext|>"} {"text":"#include \"Mongo_Storage.h\"\n#include \n\n#ifdef _WIN32\n#include \n#include \n#endif\n\n#include \n#include \n\nnamespace fpcollect {\n\nclass Mongo_Init\n{\n public:\n\n Mongo_Init()\n {\n mongo::client::initialize();\n }\n};\n\nMongo_Storage::~Mongo_Storage()\n{\n disconnect();\n delete connection_;\n}\n\nvoid Mongo_Storage::connect(const Params& params)\n{\n try\n {\n static Mongo_Init init;\n std::string ip, port, collection;\n\n for (auto item : params)\n {\n if(generic_util::find_str_no_case(item.first, \"ip\"))\n ip = item.second;\n \n if(generic_util::find_str_no_case(item.first, \"port\"))\n port = item.second;\n\n if(generic_util::find_str_no_case(item.first, \"collection\"))\n collection = item.second;\n }\n\n if (ip.empty())\n THROWM(fplog::exceptions::Connect_Failed, \"IP not provided.\");\n\n if (port.empty())\n port = \"27017\"; \/\/default\n\n if (collection.empty())\n collection = \"fplog.logs\"; \/\/default\n\n collection_ = collection;\n\n if (!connection_)\n connection_ = new mongo::DBClientConnection();\n\n connection_->connect(ip + \":\" + port);\n }\n catch (mongo::DBException& e)\n {\n THROWM(fplog::exceptions::Connect_Failed, e.what());\n }\n}\n\nvoid Mongo_Storage::disconnect()\n{\n}\n\nsize_t Mongo_Storage::write(const void* buf, size_t buf_size, size_t timeout)\n{\n if (!buf || (buf_size == 0))\n return 0;\n\n if (((const char*)buf)[buf_size - 1] != 0)\n THROWM(fplog::exceptions::Write_Failed, \"Only null-terminated strings are supported by the storage.\");\n\n try\n {\n mongo::BSONObj bson(mongo::fromjson((const char*)buf));\n connection_->insert(collection_, bson);\n }\n catch (mongo::DBException& e)\n {\n THROWM(fplog::exceptions::Write_Failed, e.what());\n }\n\n return buf_size;\n}\n\n};\nFix for #81, need to test on the next Jenkins build.#include \"Mongo_Storage.h\"\n#include \n\n#ifdef _WIN32\n#include \n#include \n#endif\n\n#include \n#include \n\nnamespace fpcollect {\n\nclass Mongo_Init\n{\n public:\n\n Mongo_Init()\n {\n mongo::client::initialize();\n }\n};\n\nMongo_Storage::~Mongo_Storage()\n{\n disconnect();\n delete connection_;\n}\n\nvoid Mongo_Storage::connect(const Params& params)\n{\n try\n {\n static std::auto_ptr init(new Mongo_Init());\n std::string ip, port, collection;\n\n for (auto item : params)\n {\n if(generic_util::find_str_no_case(item.first, \"ip\"))\n ip = item.second;\n \n if(generic_util::find_str_no_case(item.first, \"port\"))\n port = item.second;\n\n if(generic_util::find_str_no_case(item.first, \"collection\"))\n collection = item.second;\n }\n\n if (ip.empty())\n THROWM(fplog::exceptions::Connect_Failed, \"IP not provided.\");\n\n if (port.empty())\n port = \"27017\"; \/\/default\n\n if (collection.empty())\n collection = \"fplog.logs\"; \/\/default\n\n collection_ = collection;\n\n if (!connection_)\n connection_ = new mongo::DBClientConnection();\n\n connection_->connect(ip + \":\" + port);\n }\n catch (mongo::DBException& e)\n {\n THROWM(fplog::exceptions::Connect_Failed, e.what());\n }\n}\n\nvoid Mongo_Storage::disconnect()\n{\n}\n\nsize_t Mongo_Storage::write(const void* buf, size_t buf_size, size_t timeout)\n{\n if (!buf || (buf_size == 0))\n return 0;\n\n if (((const char*)buf)[buf_size - 1] != 0)\n THROWM(fplog::exceptions::Write_Failed, \"Only null-terminated strings are supported by the storage.\");\n\n try\n {\n mongo::BSONObj bson(mongo::fromjson((const char*)buf));\n connection_->insert(collection_, bson);\n }\n catch (mongo::DBException& e)\n {\n THROWM(fplog::exceptions::Write_Failed, e.what());\n }\n\n return buf_size;\n}\n\n};\n<|endoftext|>"} {"text":"\/*************************************************************************\n * \n * TIGHTDB CONFIDENTIAL\n * __________________\n * \n * [2011] - [2012] TightDB Inc\n * All Rights Reserved.\n * \n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n#ifndef __TIGHTDB_ENGINE_HPP\n#define __TIGHTDB_ENGINE_HPP\n\n#include \n#include \"table.hpp\"\n#include \"column_string.hpp\"\n#include \"column_string_enum.hpp\"\n\n#include \"utf8.hpp\"\n#include \"query_conditions.hpp\"\n\nnamespace tightdb {\n\nclass ParentNode {\npublic:\n ParentNode() : m_table(NULL) {}\n virtual ~ParentNode() {}\n virtual void Init(const Table& table) {m_table = &table; if (m_child) m_child->Init(table);}\n virtual size_t find_first(size_t start, size_t end) = 0;\n\n virtual std::string Verify(void)\n {\n if(error_code != \"\")\n return error_code;\n if(m_child == 0)\n return \"\";\n else\n return m_child->Verify();\n };\n\n ParentNode* m_child;\n\nprotected:\n const Table* m_table;\n std::string error_code;\n};\n\n\n\n\/*\ntemplate class NODE: public ParentNode {\npublic:\n NODE(T v, size_t column) : m_value(v), m_column(column) {m_child = 0;}\n ~NODE() {delete m_child; }\n\n size_t find_first(size_t start, size_t end, const Table& table)\n {\n const C& column = (C&)(table.GetColumnBase(m_column));\n const F function = {};\n for (size_t s = start; s < end; ++s) {\n const T t = column.Get(s);\n if (function(t, m_value)) {\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end, table);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\nprotected:\n T m_value;\n size_t m_column;\n};\n*\/\n\n\/\/ Not finished\nclass SUBTABLE: public ParentNode {\npublic:\n SUBTABLE(size_t column): m_column(column) {m_child = 0; m_child2 = 0;}\n SUBTABLE() {};\n\n void Init(const Table& table)\n {\n m_table = &table;\n\n if (m_child) m_child->Init(table);\n if (m_child2) m_child2->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n assert(m_child);\n\n for (size_t s = start; s < end; ++s) {\n const TableRef subtable = ((Table*)m_table)->get_subtable(m_column, s);\n\n m_child->Init(*subtable);\n const size_t subsize = subtable->size();\n const size_t sub = m_child->find_first(0, subsize);\n\n if(sub != subsize) {\n if (m_child2 == 0)\n return s;\n else {\n const size_t a = m_child2->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\/\/protected:\n ParentNode* m_child2;\n size_t m_column;\n};\n\n\ntemplate class NODE: public ParentNode {\npublic:\n NODE(T v, size_t column) : m_value(v), m_column_id(column) {m_child = 0;}\n ~NODE() {delete m_child; }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = (C*)&table.GetColumnBase(m_column_id);\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n\n for (size_t s = start; s < end; ++s) {\n s = m_column->template TreeFind(m_value, s, end);\n if (s == (size_t)-1)\n s = end;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\nprotected:\n C* m_column;\n T m_value;\n size_t m_column_id;\n};\n\n\n\ntemplate class STRINGNODE: public ParentNode {\npublic:\n STRINGNODE(const char* v, size_t column): m_column_id(column)\n {\n m_child = 0;\n\n m_value = (char *)malloc(strlen(v)*6);\n memcpy(m_value, v, strlen(v) + 1);\n m_ucase = (char *)malloc(strlen(v)*6);\n m_lcase = (char *)malloc(strlen(v)*6);\n\n const bool b1 = utf8case(v, m_lcase, false);\n const bool b2 = utf8case(v, m_ucase, true);\n if (!b1 || !b2)\n error_code = \"Malformed UTF-8: \" + std::string(m_value);\n }\n ~STRINGNODE() {delete m_child; free((void*)m_value); free((void*)m_ucase); free((void*)m_lcase); }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = &table.GetColumnBase(m_column_id);\n m_column_type = table.GetRealColumnType(m_column_id);\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n F function;\/\/ = {};\n\n for (size_t s = start; s < end; ++s) {\n const char* t;\n\n \/\/ todo, can be optimized by placing outside loop\n if (m_column_type == COLUMN_TYPE_STRING)\n t = ((const AdaptiveStringColumn*)m_column)->Get(s);\n else {\n \/\/TODO: First check if string is in key list\n t = ((const ColumnStringEnum*)m_column)->Get(s);\n }\n\n if (function(m_value, m_ucase, m_lcase, t)) {\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\nprotected:\n char* m_value;\n char* m_lcase;\n char* m_ucase;\n size_t m_column_id;\n const ColumnBase* m_column;\n ColumnType m_column_type;\n};\n\n\n\ntemplate <> class STRINGNODE: public ParentNode {\npublic:\n STRINGNODE(const char* v, size_t column): m_column_id(column), m_key_ndx((size_t)-1) {\n m_child = 0;\n m_value = (char *)malloc(strlen(v)*6);\n memcpy(m_value, v, strlen(v) + 1);\n }\n ~STRINGNODE() {delete m_child; free((void*)m_value); }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = &table.GetColumnBase(m_column_id);\n m_column_type = table.GetRealColumnType(m_column_id);\n\n if (m_column_type == COLUMN_TYPE_STRING_ENUM) {\n m_key_ndx = ((const ColumnStringEnum*)m_column)->GetKeyNdx(m_value);\n }\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n\n for (size_t s = start; s < end; ++s) {\n \/\/ todo, can be optimized by placing outside loop\n if (m_column_type == COLUMN_TYPE_STRING)\n s = ((const AdaptiveStringColumn*)m_column)->find_first(m_value, s, end);\n else {\n if (m_key_ndx == size_t(-1)) s = end; \/\/ not in key set\n else {\n const ColumnStringEnum* const cse = (const ColumnStringEnum*)m_column;\n s = cse->find_first(m_key_ndx, s, end);\n }\n }\n\n if (s == (size_t)-1)\n s = end;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\nprotected:\n char* m_value;\n size_t m_column_id;\n\nprivate:\n const ColumnBase* m_column;\n ColumnType m_column_type;\n size_t m_key_ndx;\n};\n\n\nclass OR_NODE: public ParentNode {\npublic:\n OR_NODE(ParentNode* p1) {m_child = 0; m_cond1 = p1; m_cond2 = 0;};\n ~OR_NODE()\n {\n delete m_cond1;\n delete m_cond2;\n delete m_child;\n }\n\n void Init(const Table& table)\n {\n m_cond1->Init(table);\n m_cond2->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n for (size_t s = start; s < end; ++s) {\n \/\/ Todo, redundant searches can occur\n const size_t f1 = m_cond1->find_first(s, end);\n const size_t f2 = m_cond2->find_first(s, f1);\n s = f1 < f2 ? f1 : f2;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_cond2->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\n virtual std::string Verify(void)\n {\n if(error_code != \"\")\n return error_code;\n if(m_cond1 == 0)\n return \"Missing left-hand side of OR\";\n if(m_cond2 == 0)\n return \"Missing right-hand side of OR\";\n std::string s;\n if(m_child != 0)\n s = m_child->Verify();\n if(s != \"\")\n return s;\n s = m_cond1->Verify();\n if(s != \"\")\n return s;\n s = m_cond2->Verify();\n if(s != \"\")\n return s;\n return \"\";\n }\n\n ParentNode* m_cond1;\n ParentNode* m_cond2;\n};\n\n}\n\n#endif __TIGHTDB_ENGINE_HPPAdded closing comment\/*************************************************************************\n * \n * TIGHTDB CONFIDENTIAL\n * __________________\n * \n * [2011] - [2012] TightDB Inc\n * All Rights Reserved.\n * \n * NOTICE: All information contained herein is, and remains\n * the property of TightDB Incorporated and its suppliers,\n * if any. The intellectual and technical concepts contained\n * herein are proprietary to TightDB Incorporated\n * and its suppliers and may be covered by U.S. and Foreign Patents,\n * patents in process, and are protected by trade secret or copyright law.\n * Dissemination of this information or reproduction of this material\n * is strictly forbidden unless prior written permission is obtained\n * from TightDB Incorporated.\n *\n **************************************************************************\/\n#ifndef __TIGHTDB_ENGINE_HPP\n#define __TIGHTDB_ENGINE_HPP\n\n#include \n#include \"table.hpp\"\n#include \"column_string.hpp\"\n#include \"column_string_enum.hpp\"\n\n#include \"utf8.hpp\"\n#include \"query_conditions.hpp\"\n\nnamespace tightdb {\n\nclass ParentNode {\npublic:\n ParentNode() : m_table(NULL) {}\n virtual ~ParentNode() {}\n virtual void Init(const Table& table) {m_table = &table; if (m_child) m_child->Init(table);}\n virtual size_t find_first(size_t start, size_t end) = 0;\n\n virtual std::string Verify(void)\n {\n if(error_code != \"\")\n return error_code;\n if(m_child == 0)\n return \"\";\n else\n return m_child->Verify();\n };\n\n ParentNode* m_child;\n\nprotected:\n const Table* m_table;\n std::string error_code;\n};\n\n\n\n\/*\ntemplate class NODE: public ParentNode {\npublic:\n NODE(T v, size_t column) : m_value(v), m_column(column) {m_child = 0;}\n ~NODE() {delete m_child; }\n\n size_t find_first(size_t start, size_t end, const Table& table)\n {\n const C& column = (C&)(table.GetColumnBase(m_column));\n const F function = {};\n for (size_t s = start; s < end; ++s) {\n const T t = column.Get(s);\n if (function(t, m_value)) {\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end, table);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\nprotected:\n T m_value;\n size_t m_column;\n};\n*\/\n\n\/\/ Not finished\nclass SUBTABLE: public ParentNode {\npublic:\n SUBTABLE(size_t column): m_column(column) {m_child = 0; m_child2 = 0;}\n SUBTABLE() {};\n\n void Init(const Table& table)\n {\n m_table = &table;\n\n if (m_child) m_child->Init(table);\n if (m_child2) m_child2->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n assert(m_child);\n\n for (size_t s = start; s < end; ++s) {\n const TableRef subtable = ((Table*)m_table)->get_subtable(m_column, s);\n\n m_child->Init(*subtable);\n const size_t subsize = subtable->size();\n const size_t sub = m_child->find_first(0, subsize);\n\n if(sub != subsize) {\n if (m_child2 == 0)\n return s;\n else {\n const size_t a = m_child2->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\/\/protected:\n ParentNode* m_child2;\n size_t m_column;\n};\n\n\ntemplate class NODE: public ParentNode {\npublic:\n NODE(T v, size_t column) : m_value(v), m_column_id(column) {m_child = 0;}\n ~NODE() {delete m_child; }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = (C*)&table.GetColumnBase(m_column_id);\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n\n for (size_t s = start; s < end; ++s) {\n s = m_column->template TreeFind(m_value, s, end);\n if (s == (size_t)-1)\n s = end;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\nprotected:\n C* m_column;\n T m_value;\n size_t m_column_id;\n};\n\n\n\ntemplate class STRINGNODE: public ParentNode {\npublic:\n STRINGNODE(const char* v, size_t column): m_column_id(column)\n {\n m_child = 0;\n\n m_value = (char *)malloc(strlen(v)*6);\n memcpy(m_value, v, strlen(v) + 1);\n m_ucase = (char *)malloc(strlen(v)*6);\n m_lcase = (char *)malloc(strlen(v)*6);\n\n const bool b1 = utf8case(v, m_lcase, false);\n const bool b2 = utf8case(v, m_ucase, true);\n if (!b1 || !b2)\n error_code = \"Malformed UTF-8: \" + std::string(m_value);\n }\n ~STRINGNODE() {delete m_child; free((void*)m_value); free((void*)m_ucase); free((void*)m_lcase); }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = &table.GetColumnBase(m_column_id);\n m_column_type = table.GetRealColumnType(m_column_id);\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n F function;\/\/ = {};\n\n for (size_t s = start; s < end; ++s) {\n const char* t;\n\n \/\/ todo, can be optimized by placing outside loop\n if (m_column_type == COLUMN_TYPE_STRING)\n t = ((const AdaptiveStringColumn*)m_column)->Get(s);\n else {\n \/\/TODO: First check if string is in key list\n t = ((const ColumnStringEnum*)m_column)->Get(s);\n }\n\n if (function(m_value, m_ucase, m_lcase, t)) {\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n }\n return end;\n }\n\nprotected:\n char* m_value;\n char* m_lcase;\n char* m_ucase;\n size_t m_column_id;\n const ColumnBase* m_column;\n ColumnType m_column_type;\n};\n\n\n\ntemplate <> class STRINGNODE: public ParentNode {\npublic:\n STRINGNODE(const char* v, size_t column): m_column_id(column), m_key_ndx((size_t)-1) {\n m_child = 0;\n m_value = (char *)malloc(strlen(v)*6);\n memcpy(m_value, v, strlen(v) + 1);\n }\n ~STRINGNODE() {delete m_child; free((void*)m_value); }\n\n void Init(const Table& table)\n {\n m_table = &table;\n m_column = &table.GetColumnBase(m_column_id);\n m_column_type = table.GetRealColumnType(m_column_id);\n\n if (m_column_type == COLUMN_TYPE_STRING_ENUM) {\n m_key_ndx = ((const ColumnStringEnum*)m_column)->GetKeyNdx(m_value);\n }\n\n if (m_child) m_child->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n assert(m_table);\n\n for (size_t s = start; s < end; ++s) {\n \/\/ todo, can be optimized by placing outside loop\n if (m_column_type == COLUMN_TYPE_STRING)\n s = ((const AdaptiveStringColumn*)m_column)->find_first(m_value, s, end);\n else {\n if (m_key_ndx == size_t(-1)) s = end; \/\/ not in key set\n else {\n const ColumnStringEnum* const cse = (const ColumnStringEnum*)m_column;\n s = cse->find_first(m_key_ndx, s, end);\n }\n }\n\n if (s == (size_t)-1)\n s = end;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_child->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\nprotected:\n char* m_value;\n size_t m_column_id;\n\nprivate:\n const ColumnBase* m_column;\n ColumnType m_column_type;\n size_t m_key_ndx;\n};\n\n\nclass OR_NODE: public ParentNode {\npublic:\n OR_NODE(ParentNode* p1) {m_child = 0; m_cond1 = p1; m_cond2 = 0;};\n ~OR_NODE()\n {\n delete m_cond1;\n delete m_cond2;\n delete m_child;\n }\n\n void Init(const Table& table)\n {\n m_cond1->Init(table);\n m_cond2->Init(table);\n }\n\n size_t find_first(size_t start, size_t end)\n {\n for (size_t s = start; s < end; ++s) {\n \/\/ Todo, redundant searches can occur\n const size_t f1 = m_cond1->find_first(s, end);\n const size_t f2 = m_cond2->find_first(s, f1);\n s = f1 < f2 ? f1 : f2;\n\n if (m_child == 0)\n return s;\n else {\n const size_t a = m_cond2->find_first(s, end);\n if (s == a)\n return s;\n else\n s = a - 1;\n }\n }\n return end;\n }\n\n virtual std::string Verify(void)\n {\n if(error_code != \"\")\n return error_code;\n if(m_cond1 == 0)\n return \"Missing left-hand side of OR\";\n if(m_cond2 == 0)\n return \"Missing right-hand side of OR\";\n std::string s;\n if(m_child != 0)\n s = m_child->Verify();\n if(s != \"\")\n return s;\n s = m_cond1->Verify();\n if(s != \"\")\n return s;\n s = m_cond2->Verify();\n if(s != \"\")\n return s;\n return \"\";\n }\n\n ParentNode* m_cond1;\n ParentNode* m_cond2;\n};\n\n}\n\n#endif \/\/__TIGHTDB_ENGINE_HPP<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: chart2uno.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-02-11 09:55:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SC_CHART2UNO_HXX\n#define SC_CHART2UNO_HXX\n\n#ifndef SC_RANGELST_HXX\n#include \"rangelst.hxx\"\n#endif\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATAPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATASOURCE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATASEQUENCE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_DATASEQUENCEROLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nclass ScDocShell;\n\n\n\/\/ DataProvider ==============================================================\n\nclass ScChart2DataProvider : public\n ::cppu::WeakImplHelper2<\n ::com::sun::star::chart2::XDataProvider,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataProvider( ScDocShell* pDocSh);\n virtual ~ScChart2DataProvider();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataProvider ---------------------------------------------------------\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource> SAL_CALL\n getDataByRangeRepresentation(\n const ::rtl::OUString& rRangeRepresentation)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> SAL_CALL\n getDataSequenceByRangeIdentifier(\n const ::rtl::OUString& rRangeIdentifier)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> SAL_CALL replaceRange(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence>& rSeq)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addDataChangeListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataChangeListener>& rListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource>& rData)\n throw( ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeDataChangeListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataChangeListener>& rListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource>& rData)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n ScDocShell* pDocShell;\n\n};\n\n\n\/\/ DataSource ================================================================\n\nclass ScChart2DataSource : public\n ::cppu::WeakImplHelper2<\n ::com::sun::star::chart2::XDataSource,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataSource( ScDocShell* pDocSh, const ScRangeListRef&\n rRangeList);\n virtual ~ScChart2DataSource();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataSource -----------------------------------------------------------\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> > SAL_CALL\n getDataSequences() throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n ScRangeListRef xRanges;\n ScDocShell* pDocShell;\n\n};\n\n\n\/\/ DataSequence ==============================================================\n\nclass ScChart2DataSequence : public\n ::cppu::WeakImplHelper3<\n ::com::sun::star::chart2::XDataSequence,\n ::com::sun::star::beans::XPropertySet,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataSequence( ScDocShell* pDocSh,\n const ScRangeListRef& rRangeList );\n virtual ~ScChart2DataSequence();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataSequence ---------------------------------------------------------\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>\n SAL_CALL getData() throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::rtl::OUString SAL_CALL getSourceIdentifier() throw (\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet ----------------------------------------------------------\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySetInfo> SAL_CALL\n getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL setPropertyValue(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Any& rValue)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::beans::PropertyVetoException,\n ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(\n const ::rtl::OUString& rPropertyName)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addPropertyChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertyChangeListener>& xListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removePropertyChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertyChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addVetoableChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XVetoableChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeVetoableChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XVetoableChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n \/\/ properties\n ::com::sun::star::chart2::DataSequenceRole aRole;\n sal_Bool bHidden;\n \/\/ internals\n ScRangeListRef xRanges;\n ::rtl::OUString aIdentifier;\n ScDocShell* pDocShell;\n\n};\n\n#endif \/\/ SC_CHART2UNO_HXX\nINTEGRATION: CWS ooo19126 (1.2.526); FILE MERGED 2005\/09\/05 15:00:34 rt 1.2.526.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: chart2uno.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 17:25:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef SC_CHART2UNO_HXX\n#define SC_CHART2UNO_HXX\n\n#ifndef SC_RANGELST_HXX\n#include \"rangelst.hxx\"\n#endif\n#ifndef _SFXLSTNER_HXX\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATAPROVIDER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATASOURCE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_XDATASEQUENCE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CHART2_DATASEQUENCEROLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX_\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include \n#endif\n#ifndef _RTL_USTRING_HXX_\n#include \n#endif\n\nclass ScDocShell;\n\n\n\/\/ DataProvider ==============================================================\n\nclass ScChart2DataProvider : public\n ::cppu::WeakImplHelper2<\n ::com::sun::star::chart2::XDataProvider,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataProvider( ScDocShell* pDocSh);\n virtual ~ScChart2DataProvider();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataProvider ---------------------------------------------------------\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource> SAL_CALL\n getDataByRangeRepresentation(\n const ::rtl::OUString& rRangeRepresentation)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> SAL_CALL\n getDataSequenceByRangeIdentifier(\n const ::rtl::OUString& rRangeIdentifier)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> SAL_CALL replaceRange(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence>& rSeq)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addDataChangeListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataChangeListener>& rListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource>& rData)\n throw( ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeDataChangeListener(\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataChangeListener>& rListener,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSource>& rData)\n throw( ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n ScDocShell* pDocShell;\n\n};\n\n\n\/\/ DataSource ================================================================\n\nclass ScChart2DataSource : public\n ::cppu::WeakImplHelper2<\n ::com::sun::star::chart2::XDataSource,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataSource( ScDocShell* pDocSh, const ScRangeListRef&\n rRangeList);\n virtual ~ScChart2DataSource();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataSource -----------------------------------------------------------\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference<\n ::com::sun::star::chart2::XDataSequence> > SAL_CALL\n getDataSequences() throw( ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n ScRangeListRef xRanges;\n ScDocShell* pDocShell;\n\n};\n\n\n\/\/ DataSequence ==============================================================\n\nclass ScChart2DataSequence : public\n ::cppu::WeakImplHelper3<\n ::com::sun::star::chart2::XDataSequence,\n ::com::sun::star::beans::XPropertySet,\n ::com::sun::star::lang::XServiceInfo>,\n SfxListener\n{\npublic:\n\n explicit ScChart2DataSequence( ScDocShell* pDocSh,\n const ScRangeListRef& rRangeList );\n virtual ~ScChart2DataSequence();\n virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );\n\n \/\/ XDataSequence ---------------------------------------------------------\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any>\n SAL_CALL getData() throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::rtl::OUString SAL_CALL getSourceIdentifier() throw (\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XPropertySet ----------------------------------------------------------\n\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertySetInfo> SAL_CALL\n getPropertySetInfo() throw( ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL setPropertyValue(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Any& rValue)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::beans::PropertyVetoException,\n ::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue(\n const ::rtl::OUString& rPropertyName)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addPropertyChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertyChangeListener>& xListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removePropertyChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XPropertyChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL addVetoableChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XVetoableChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n virtual void SAL_CALL removeVetoableChangeListener(\n const ::rtl::OUString& rPropertyName,\n const ::com::sun::star::uno::Reference<\n ::com::sun::star::beans::XVetoableChangeListener>& rListener)\n throw( ::com::sun::star::beans::UnknownPropertyException,\n ::com::sun::star::lang::WrappedTargetException,\n ::com::sun::star::uno::RuntimeException);\n\n \/\/ XServiceInfo ----------------------------------------------------------\n\n virtual ::rtl::OUString SAL_CALL getImplementationName() throw(\n ::com::sun::star::uno::RuntimeException);\n\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString&\n rServiceName) throw( ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::rtl::OUString> SAL_CALL\n getSupportedServiceNames() throw(\n ::com::sun::star::uno::RuntimeException);\n\nprivate:\n\n \/\/ properties\n ::com::sun::star::chart2::DataSequenceRole aRole;\n sal_Bool bHidden;\n \/\/ internals\n ScRangeListRef xRanges;\n ::rtl::OUString aIdentifier;\n ScDocShell* pDocShell;\n\n};\n\n#endif \/\/ SC_CHART2UNO_HXX\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/ Author:\t\tMartin Klemsa\n\/\/----------------------------------------------------------------------------\n#ifndef _ctoolhu_thread_proxy_included_\n#define _ctoolhu_thread_proxy_included_\n\nnamespace Ctoolhu::Thread {\n\n\t\/\/Provides object-level locking for any lockable class.\n\t\/\/If used in conjunction with inheriting from Lockable the client class internals needn't be touched\n\t\/\/(indeed this is the same implementation as appears in Modern C++ design by Alexandrescu)\n\ttemplate \n\tclass LockingProxy {\n\n\t public:\n\n\t\texplicit LockingProxy(T *client) : _client(client)\n\t\t{\n\t\t\t_client->Lock();\n\t\t}\n\n\t\tLockingProxy(LockingProxy &&src)\n\t\t{\n\t\t\t_client = src._client;\n\t\t\tsrc._client = nullptr;\n\t\t}\n\n\t\t~LockingProxy()\n\t\t{\n\t\t\tif (_client)\n\t\t\t\t_client->Unlock();\n\t\t}\n\n\t\tT *operator ->() const\n\t\t{\n\t\t\treturn _client;\n\t\t}\n\n\t\tLockingProxy(const LockingProxy &) = delete;\n\t\tLockingProxy &operator =(const LockingProxy &) = delete;\n\n\t private:\n\n\t\tT *_client;\n\t};\n\n} \/\/ns Ctoolhu::Thread\n\n#endif \/\/file guard\nAdded move constructor to locking proxy class\/\/----------------------------------------------------------------------------\n\/\/ Author:\t\tMartin Klemsa\n\/\/----------------------------------------------------------------------------\n#ifndef _ctoolhu_thread_proxy_included_\n#define _ctoolhu_thread_proxy_included_\n\n#include \n\nnamespace Ctoolhu::Thread {\n\n\t\/\/Provides object-level locking for any lockable class.\n\t\/\/If used in conjunction with inheriting from Lockable the client class internals needn't be touched\n\t\/\/(indeed this is the same implementation as appears in Modern C++ design by Alexandrescu)\n\ttemplate \n\tclass LockingProxy {\n\n\t public:\n\n\t\texplicit LockingProxy(T *client) : _client(client)\n\t\t{\n\t\t\t_client->Lock();\n\t\t}\n\n\t\tLockingProxy(LockingProxy &&src)\n\t\t{\n\t\t\t_client = std::exchange(src._client, nullptr);\n\t\t}\n\n\t\tLockingProxy &operator =(LockingProxy &&src)\n\t\t{\n\t\t\t_client = std::exchange(src._client, nullptr);\n\t\t\treturn *this;\n\t\t}\n\n\t\t~LockingProxy()\n\t\t{\n\t\t\tif (_client)\n\t\t\t\t_client->Unlock();\n\t\t}\n\n\t\tT *operator ->() const\n\t\t{\n\t\t\treturn _client;\n\t\t}\n\n\t\tLockingProxy(const LockingProxy &) = delete;\n\t\tLockingProxy &operator =(const LockingProxy &) = delete;\n\n\t private:\n\n\t\tT *_client;\n\t};\n\n} \/\/ns Ctoolhu::Thread\n\n#endif \/\/file guard\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"EasyServer.h\"\n#include \"PacketType.h\"\n#include \"ClientSession.h\"\n#include \"ClientManager.h\"\n#include \"DatabaseJobContext.h\"\n#include \"DatabaseJobManager.h\"\n\nClientManager* GClientManager = nullptr ;\n\nClientSession* ClientManager::CreateClient(SOCKET sock)\n{\n\tClientSession* client = new ClientSession(sock) ;\n\tmClientList.insert(ClientList::value_type(sock, client)) ;\n\n\treturn client ;\n}\n\n\n\nvoid ClientManager::BroadcastPacket(ClientSession* from, PacketHeader* pkt)\n{\n\t\/\/\/FYI: C++ STL iterator Ÿ \n\tfor (ClientList::const_iterator it=mClientList.begin() ; it!=mClientList.end() ; ++it)\n\t{\n\t\tClientSession* client = it->second ;\n\t\t\n\t\tif ( from == client )\n\t\t\tcontinue ;\n\t\t\n\t\tclient->Send(pkt) ;\n\t}\n}\n\nvoid ClientManager::OnPeriodWork()\n{\n\t\/\/\/ ǵ ֱ (1 )\n\tDWORD currTick = GetTickCount() ;\n\tif ( currTick - mLastGCTick >= 1000 )\n\t{\n\t\tCollectGarbageSessions() ;\n\t\tmLastGCTick = currTick ;\n\t}\n\n\t\/\/\/ ӵ Ŭ̾Ʈ Ǻ ֱ ϴ (ֱ ˾Ƽ ϸ - 1ʷ )\n\tif ( currTick - mLastClientWorkTick >= 1000 )\n\t{\n\t\tClientPeriodWork() ;\n\t\tmLastClientWorkTick = currTick ;\n\t}\n\n\t\/\/\/ ó Ϸ DB ۾ Client dispatch\n\tDispatchDatabaseJobResults() ;\n\t\t\n}\n\nvoid ClientManager::CollectGarbageSessions()\n{\n\tstd::vector disconnectedSessions ;\n\t\n\t\/\/\/FYI: C++ 11 ٸ ̿ Ÿ\n\tstd::for_each(mClientList.begin(), mClientList.end(),\n\t\t[&](ClientList::const_reference it)\n\t\t{\n\t\t\tClientSession* client = it.second ;\n\n\t\t\tif ( false == client->IsConnected() && false == client->DoingOverlappedOperation() )\n\t\t\t\tdisconnectedSessions.push_back(client) ;\n\t\t}\n\t) ;\n\t\n\n\t\/\/\/FYI: C Ÿ \n\tfor (size_t i=0 ; imSocket) ;\n\t\tdelete client ;\n\t}\n\n}\n\nvoid ClientManager::ClientPeriodWork()\n{\n\tGPlayerManager->UpdatePlayers();\n\t\n\t\/\/\/ FYI: C++ 11 Ÿ \n\tfor (auto& it : mClientList)\n\t{\n\t\tClientSession* client = it.second ;\n\t\tclient->OnTick() ;\n\t}\n}\n\nvoid ClientManager::DispatchDatabaseJobResults()\n{\n\t\/\/\/ ׿ ִ DB ۾ ó Ŭ󿡰 ѱ\n\tDatabaseJobContext* dbResult = nullptr ;\n\twhile ( GDatabaseJobManager->PopDatabaseJobResult(dbResult) )\n\t{\n\t\tif ( false == dbResult->mSuccess )\n\t\t{\n\t\t\tprintf(\"DB JOB FAIL \\n\") ;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( typeid(*dbResult) == typeid(CreatePlayerDataContext) )\n\t\t\t{\n\t\t\t\tCreatePlayerDone(dbResult) ;\n\t\t\t}\n\t\t\telse if ( typeid(*dbResult) == typeid(DeletePlayerDataContext) )\n\t\t\t{\n\t\t\t\tDeletePlayerDone(dbResult) ;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/\/ ش DBû ߴ Ŭ̾Ʈ \n\t\t\t\tauto& it = mClientList.find(dbResult->mSockKey) ;\n\n\t\t\t\tif ( it != mClientList.end() && it->second->IsConnected() )\n\t\t\t\t{\n\t\t\t\t\t\/\/\/ dispatch here....\n\t\t\t\t\tit->second->DatabaseJobDone(dbResult) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\n\t\t\/\/\/ Ϸ DB ۾ ؽƮ \n\t\tDatabaseJobContext* toBeDelete = dbResult ;\n\t\tdelete toBeDelete ;\n\t}\n}\n\nvoid ClientManager::CreatePlayer(int pid, double x, double y, double z, const char* name, const char* comment)\n{\n\tCreatePlayerDataContext* newPlayerJob = new CreatePlayerDataContext() ;\n\tnewPlayerJob->mPlayerId = pid ;\n\tnewPlayerJob->mPosX = x ;\n\tnewPlayerJob->mPosY = y ;\n\tnewPlayerJob->mPosZ = z ;\n\tstrcpy_s(newPlayerJob->mPlayerName, name) ;\n\tstrcpy_s(newPlayerJob->mComment, comment) ;\n\n\tGDatabaseJobManager->PushDatabaseJobRequest(newPlayerJob) ;\n\n}\n\nvoid ClientManager::DeletePlayer(int pid)\n{\n\tDeletePlayerDataContext* delPlayerJob = new DeletePlayerDataContext(pid) ;\n\tGDatabaseJobManager->PushDatabaseJobRequest(delPlayerJob) ;\n}\n\nvoid ClientManager::CreatePlayerDone(DatabaseJobContext* dbJob)\n{\n\tCreatePlayerDataContext* createJob = dynamic_cast(dbJob) ;\n\n\tprintf(\"PLAYER[%d] CREATED: %s \\n\", createJob->mPlayerId, createJob->mPlayerName) ;\n}\n\nvoid ClientManager::DeletePlayerDone(DatabaseJobContext* dbJob)\n{\n\tDeletePlayerDataContext* deleteJob = dynamic_cast(dbJob) ;\n\t\n\tprintf(\"PLAYER [%d] DELETED\\n\", deleteJob->mPlayerId) ;\n\n}플레이어 시뮬레이션이 매순간 되도록#include \"stdafx.h\"\n#include \"EasyServer.h\"\n#include \"PacketType.h\"\n#include \"ClientSession.h\"\n#include \"ClientManager.h\"\n#include \"DatabaseJobContext.h\"\n#include \"DatabaseJobManager.h\"\n\nClientManager* GClientManager = nullptr ;\n\nClientSession* ClientManager::CreateClient(SOCKET sock)\n{\n\tClientSession* client = new ClientSession(sock) ;\n\tmClientList.insert(ClientList::value_type(sock, client)) ;\n\n\treturn client ;\n}\n\n\n\nvoid ClientManager::BroadcastPacket(ClientSession* from, PacketHeader* pkt)\n{\n\t\/\/\/FYI: C++ STL iterator Ÿ \n\tfor (ClientList::const_iterator it=mClientList.begin() ; it!=mClientList.end() ; ++it)\n\t{\n\t\tClientSession* client = it->second ;\n\t\t\n\t\tif ( from == client )\n\t\t\tcontinue ;\n\t\t\n\t\tclient->Send(pkt) ;\n\t}\n}\n\nvoid ClientManager::OnPeriodWork()\n{\n\t\/\/\/ ǵ ֱ (1 )\n\tDWORD currTick = GetTickCount() ;\n\tif ( currTick - mLastGCTick >= 1000 )\n\t{\n\t\tCollectGarbageSessions() ;\n\t\tmLastGCTick = currTick ;\n\t}\n\n\t\/\/\/ ӵ Ŭ̾Ʈ Ǻ ֱ ϴ (ֱ ˾Ƽ ϸ - 0ʷ )\n\tif ( currTick - mLastClientWorkTick >= 0 )\n\t{\n\t\tClientPeriodWork() ;\n\t\tmLastClientWorkTick = currTick ;\n\t}\n\n\t\/\/\/ ó Ϸ DB ۾ Client dispatch\n\tDispatchDatabaseJobResults() ;\n\t\t\n}\n\nvoid ClientManager::CollectGarbageSessions()\n{\n\tstd::vector disconnectedSessions ;\n\t\n\t\/\/\/FYI: C++ 11 ٸ ̿ Ÿ\n\tstd::for_each(mClientList.begin(), mClientList.end(),\n\t\t[&](ClientList::const_reference it)\n\t\t{\n\t\t\tClientSession* client = it.second ;\n\n\t\t\tif ( false == client->IsConnected() && false == client->DoingOverlappedOperation() )\n\t\t\t\tdisconnectedSessions.push_back(client) ;\n\t\t}\n\t) ;\n\t\n\n\t\/\/\/FYI: C Ÿ \n\tfor (size_t i=0 ; imSocket) ;\n\t\tdelete client ;\n\t}\n\n}\n\nvoid ClientManager::ClientPeriodWork()\n{\n\tGPlayerManager->UpdatePlayers();\n\t\n\t\/\/\/ FYI: C++ 11 Ÿ \n\tfor (auto& it : mClientList)\n\t{\n\t\tClientSession* client = it.second ;\n\t\tclient->OnTick() ;\n\t}\n}\n\nvoid ClientManager::DispatchDatabaseJobResults()\n{\n\t\/\/\/ ׿ ִ DB ۾ ó Ŭ󿡰 ѱ\n\tDatabaseJobContext* dbResult = nullptr ;\n\twhile ( GDatabaseJobManager->PopDatabaseJobResult(dbResult) )\n\t{\n\t\tif ( false == dbResult->mSuccess )\n\t\t{\n\t\t\tprintf(\"DB JOB FAIL \\n\") ;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( typeid(*dbResult) == typeid(CreatePlayerDataContext) )\n\t\t\t{\n\t\t\t\tCreatePlayerDone(dbResult) ;\n\t\t\t}\n\t\t\telse if ( typeid(*dbResult) == typeid(DeletePlayerDataContext) )\n\t\t\t{\n\t\t\t\tDeletePlayerDone(dbResult) ;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/\/ ش DBû ߴ Ŭ̾Ʈ \n\t\t\t\tauto& it = mClientList.find(dbResult->mSockKey) ;\n\n\t\t\t\tif ( it != mClientList.end() && it->second->IsConnected() )\n\t\t\t\t{\n\t\t\t\t\t\/\/\/ dispatch here....\n\t\t\t\t\tit->second->DatabaseJobDone(dbResult) ;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\n\t\t\/\/\/ Ϸ DB ۾ ؽƮ \n\t\tDatabaseJobContext* toBeDelete = dbResult ;\n\t\tdelete toBeDelete ;\n\t}\n}\n\nvoid ClientManager::CreatePlayer(int pid, double x, double y, double z, const char* name, const char* comment)\n{\n\tCreatePlayerDataContext* newPlayerJob = new CreatePlayerDataContext() ;\n\tnewPlayerJob->mPlayerId = pid ;\n\tnewPlayerJob->mPosX = x ;\n\tnewPlayerJob->mPosY = y ;\n\tnewPlayerJob->mPosZ = z ;\n\tstrcpy_s(newPlayerJob->mPlayerName, name) ;\n\tstrcpy_s(newPlayerJob->mComment, comment) ;\n\n\tGDatabaseJobManager->PushDatabaseJobRequest(newPlayerJob) ;\n\n}\n\nvoid ClientManager::DeletePlayer(int pid)\n{\n\tDeletePlayerDataContext* delPlayerJob = new DeletePlayerDataContext(pid) ;\n\tGDatabaseJobManager->PushDatabaseJobRequest(delPlayerJob) ;\n}\n\nvoid ClientManager::CreatePlayerDone(DatabaseJobContext* dbJob)\n{\n\tCreatePlayerDataContext* createJob = dynamic_cast(dbJob) ;\n\n\tprintf(\"PLAYER[%d] CREATED: %s \\n\", createJob->mPlayerId, createJob->mPlayerName) ;\n}\n\nvoid ClientManager::DeletePlayerDone(DatabaseJobContext* dbJob)\n{\n\tDeletePlayerDataContext* deleteJob = dynamic_cast(dbJob) ;\n\t\n\tprintf(\"PLAYER [%d] DELETED\\n\", deleteJob->mPlayerId) ;\n\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium OS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \n#include \n\n#include \"update_engine\/marshal.glibmarshal.h\"\n#include \"update_engine\/dbus_constants.h\"\n#include \"update_engine\/subprocess.h\"\n#include \"update_engine\/utils.h\"\n\nextern \"C\" {\n#include \"update_engine\/update_engine.dbusclient.h\"\n}\n\nusing chromeos_update_engine::kUpdateEngineServiceName;\nusing chromeos_update_engine::kUpdateEngineServicePath;\nusing chromeos_update_engine::kUpdateEngineServiceInterface;\nusing chromeos_update_engine::utils::GetAndFreeGError;\nusing std::string;\n\nDEFINE_string(app_version, \"\", \"Force the current app version.\");\nDEFINE_bool(check_for_update, false, \"Initiate check for updates.\");\nDEFINE_string(omaha_url, \"\", \"The URL of the Omaha update server.\");\nDEFINE_bool(reboot, false, \"Initiate a reboot if needed.\");\nDEFINE_bool(show_track, false, \"Show the update track.\");\nDEFINE_bool(status, false, \"Print the status to stdout.\");\nDEFINE_bool(reset_status, false, \"Sets the status in update_engine to idle.\");\nDEFINE_string(track, \"\", \"Permanently change the update track.\");\nDEFINE_bool(update, false, \"Forces an update and waits for its completion. \"\n \"Exit status is 0 if the update succeeded, and 1 otherwise.\");\nDEFINE_bool(watch_for_updates, false,\n \"Listen for status updates and print them to the screen.\");\n\nnamespace {\n\nbool GetProxy(DBusGProxy** out_proxy) {\n DBusGConnection* bus;\n DBusGProxy* proxy = NULL;\n GError* error = NULL;\n const int kTries = 4;\n const int kRetrySeconds = 10;\n\n bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);\n if (bus == NULL) {\n LOG(ERROR) << \"Failed to get bus: \" << GetAndFreeGError(&error);\n exit(1);\n }\n for (int i = 0; !proxy && i < kTries; ++i) {\n if (i > 0) {\n LOG(INFO) << \"Retrying to get dbus proxy. Try \"\n << (i + 1) << \"\/\" << kTries;\n g_usleep(kRetrySeconds * G_USEC_PER_SEC);\n }\n proxy = dbus_g_proxy_new_for_name_owner(bus,\n kUpdateEngineServiceName,\n kUpdateEngineServicePath,\n kUpdateEngineServiceInterface,\n &error);\n LOG_IF(WARNING, !proxy) << \"Error getting dbus proxy for \"\n << kUpdateEngineServiceName << \": \"\n << GetAndFreeGError(&error);\n }\n if (proxy == NULL) {\n LOG(ERROR) << \"Giving up -- unable to get dbus proxy for \"\n << kUpdateEngineServiceName;\n exit(1);\n }\n *out_proxy = proxy;\n return true;\n}\n\nstatic void StatusUpdateSignalHandler(DBusGProxy* proxy,\n int64_t last_checked_time,\n double progress,\n gchar* current_operation,\n gchar* new_version,\n int64_t new_size,\n void* user_data) {\n LOG(INFO) << \"Got status update:\";\n LOG(INFO) << \" last_checked_time: \" << last_checked_time;\n LOG(INFO) << \" progress: \" << progress;\n LOG(INFO) << \" current_operation: \" << current_operation;\n LOG(INFO) << \" new_version: \" << new_version;\n LOG(INFO) << \" new_size: \" << new_size;\n}\n\nbool ResetStatus() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_reset_status(proxy, &error);\n return rc;\n}\n\n\n\/\/ If |op| is non-NULL, sets it to the current operation string or an\n\/\/ empty string if unable to obtain the current status.\nbool GetStatus(string* op) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gint64 last_checked_time = 0;\n gdouble progress = 0.0;\n char* current_op = NULL;\n char* new_version = NULL;\n gint64 new_size = 0;\n\n gboolean rc = org_chromium_UpdateEngineInterface_get_status(\n proxy,\n &last_checked_time,\n &progress,\n ¤t_op,\n &new_version,\n &new_size,\n &error);\n if (rc == FALSE) {\n LOG(INFO) << \"Error getting status: \" << GetAndFreeGError(&error);\n }\n printf(\"LAST_CHECKED_TIME=%\" PRIi64 \"\\nPROGRESS=%f\\nCURRENT_OP=%s\\n\"\n \"NEW_VERSION=%s\\nNEW_SIZE=%\" PRIi64 \"\\n\",\n last_checked_time,\n progress,\n current_op,\n new_version,\n new_size);\n if (op) {\n *op = current_op ? current_op : \"\";\n }\n return true;\n}\n\n\/\/ Should never return.\nvoid WatchForUpdates() {\n DBusGProxy* proxy;\n\n CHECK(GetProxy(&proxy));\n\n \/\/ Register marshaller\n dbus_g_object_register_marshaller(\n update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,\n G_TYPE_NONE,\n G_TYPE_INT64,\n G_TYPE_DOUBLE,\n G_TYPE_STRING,\n G_TYPE_STRING,\n G_TYPE_INT64,\n G_TYPE_INVALID);\n\n static const char kStatusUpdate[] = \"StatusUpdate\";\n dbus_g_proxy_add_signal(proxy,\n kStatusUpdate,\n G_TYPE_INT64,\n G_TYPE_DOUBLE,\n G_TYPE_STRING,\n G_TYPE_STRING,\n G_TYPE_INT64,\n G_TYPE_INVALID);\n GMainLoop* loop = g_main_loop_new (NULL, TRUE);\n dbus_g_proxy_connect_signal(proxy,\n kStatusUpdate,\n G_CALLBACK(StatusUpdateSignalHandler),\n NULL,\n NULL);\n g_main_loop_run(loop);\n g_main_loop_unref(loop);\n}\n\nbool CheckForUpdates(const string& app_version, const string& omaha_url) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_attempt_update(proxy,\n app_version.c_str(),\n omaha_url.c_str(),\n &error);\n CHECK_EQ(rc, TRUE) << \"Error checking for update: \"\n << GetAndFreeGError(&error);\n return true;\n}\n\nbool RebootIfNeeded() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_reboot_if_needed(proxy, &error);\n \/\/ Reboot error code doesn't necessarily mean that a reboot\n \/\/ failed. For example, D-Bus may be shutdown before we receive the\n \/\/ result.\n LOG_IF(INFO, !rc) << \"Reboot error message: \" << GetAndFreeGError(&error);\n return true;\n}\n\nvoid SetTrack(const string& track) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_set_track(proxy,\n track.c_str(),\n &error);\n CHECK_EQ(rc, true) << \"Error setting the track: \"\n << GetAndFreeGError(&error);\n LOG(INFO) << \"Track permanently set to: \" << track;\n}\n\nstring GetTrack() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n char* track = NULL;\n gboolean rc =\n org_chromium_UpdateEngineInterface_get_track(proxy,\n &track,\n &error);\n CHECK_EQ(rc, true) << \"Error getting the track: \" << GetAndFreeGError(&error);\n string output = track;\n g_free(track);\n return output;\n}\n\nstatic gboolean CompleteUpdateSource(gpointer data) {\n string current_op;\n if (!GetStatus(¤t_op) || current_op == \"UPDATE_STATUS_IDLE\") {\n LOG(ERROR) << \"Update failed.\";\n exit(1);\n }\n if (current_op == \"UPDATE_STATUS_UPDATED_NEED_REBOOT\") {\n LOG(INFO) << \"Update succeeded -- reboot needed.\";\n exit(0);\n }\n return TRUE;\n}\n\n\/\/ This is similar to watching for updates but rather than registering\n\/\/ a signal watch, activelly poll the daemon just in case it stops\n\/\/ sending notifications.\nvoid CompleteUpdate() {\n GMainLoop* loop = g_main_loop_new (NULL, TRUE);\n g_timeout_add_seconds(5, CompleteUpdateSource, NULL);\n g_main_loop_run(loop);\n g_main_loop_unref(loop);\n}\n\n} \/\/ namespace {}\n\nint main(int argc, char** argv) {\n \/\/ Boilerplate init commands.\n g_type_init();\n g_thread_init(NULL);\n dbus_g_thread_init();\n chromeos_update_engine::Subprocess::Init();\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n \/\/ Update the status if requested.\n if (FLAGS_reset_status) {\n LOG(INFO) << \"Setting Update Engine status to idle ...\";\n if (!ResetStatus()) {\n LOG(ERROR) << \"ResetStatus failed.\";\n return 1;\n }\n\n LOG(INFO) << \"ResetStatus succeeded.\";\n return 0;\n }\n\n\n if (FLAGS_status) {\n LOG(INFO) << \"Querying Update Engine status...\";\n if (!GetStatus(NULL)) {\n LOG(FATAL) << \"GetStatus failed.\";\n return 1;\n }\n return 0;\n }\n\n \/\/ First, update the track if requested.\n if (!FLAGS_track.empty()) {\n SetTrack(FLAGS_track);\n }\n\n \/\/ Show the track if requested.\n if (FLAGS_show_track) {\n LOG(INFO) << \"Track: \" << GetTrack();\n }\n\n \/\/ Initiate an update check, if necessary.\n if (FLAGS_check_for_update ||\n FLAGS_update ||\n !FLAGS_app_version.empty() ||\n !FLAGS_omaha_url.empty()) {\n LOG_IF(WARNING, FLAGS_reboot) << \"-reboot flag ignored.\";\n string app_version = FLAGS_app_version;\n if (FLAGS_update && app_version.empty()) {\n app_version = \"ForcedUpdate\";\n LOG(INFO) << \"Forcing an update by setting app_version to ForcedUpdate.\";\n }\n LOG(INFO) << \"Initiating update check and install.\";\n CHECK(CheckForUpdates(app_version, FLAGS_omaha_url))\n << \"Update check\/initiate update failed.\";\n\n \/\/ Wait for an update to complete.\n if (FLAGS_update) {\n LOG(INFO) << \"Waiting for update to complete.\";\n CompleteUpdate(); \/\/ Should never return.\n return 1;\n }\n return 0;\n }\n\n \/\/ Start watching for updates.\n if (FLAGS_watch_for_updates) {\n LOG_IF(WARNING, FLAGS_reboot) << \"-reboot flag ignored.\";\n LOG(INFO) << \"Watching for status updates.\";\n WatchForUpdates(); \/\/ Should never return.\n return 1;\n }\n\n if (FLAGS_reboot) {\n LOG(INFO) << \"Requesting a reboot...\";\n CHECK(RebootIfNeeded());\n return 0;\n }\n\n LOG(INFO) << \"Done.\";\n return 0;\n}\nAU: recommend cgpt undo on update_engine_client -reset_status\/\/ Copyright (c) 2012 The Chromium OS Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n\n#include \n#include \n\n#include \"update_engine\/marshal.glibmarshal.h\"\n#include \"update_engine\/dbus_constants.h\"\n#include \"update_engine\/subprocess.h\"\n#include \"update_engine\/utils.h\"\n\nextern \"C\" {\n#include \"update_engine\/update_engine.dbusclient.h\"\n}\n\nusing chromeos_update_engine::kUpdateEngineServiceName;\nusing chromeos_update_engine::kUpdateEngineServicePath;\nusing chromeos_update_engine::kUpdateEngineServiceInterface;\nusing chromeos_update_engine::utils::GetAndFreeGError;\nusing std::string;\n\nDEFINE_string(app_version, \"\", \"Force the current app version.\");\nDEFINE_bool(check_for_update, false, \"Initiate check for updates.\");\nDEFINE_string(omaha_url, \"\", \"The URL of the Omaha update server.\");\nDEFINE_bool(reboot, false, \"Initiate a reboot if needed.\");\nDEFINE_bool(show_track, false, \"Show the update track.\");\nDEFINE_bool(status, false, \"Print the status to stdout.\");\nDEFINE_bool(reset_status, false, \"Sets the status in update_engine to idle.\");\nDEFINE_string(track, \"\", \"Permanently change the update track.\");\nDEFINE_bool(update, false, \"Forces an update and waits for its completion. \"\n \"Exit status is 0 if the update succeeded, and 1 otherwise.\");\nDEFINE_bool(watch_for_updates, false,\n \"Listen for status updates and print them to the screen.\");\n\nnamespace {\n\nbool GetProxy(DBusGProxy** out_proxy) {\n DBusGConnection* bus;\n DBusGProxy* proxy = NULL;\n GError* error = NULL;\n const int kTries = 4;\n const int kRetrySeconds = 10;\n\n bus = dbus_g_bus_get(DBUS_BUS_SYSTEM, &error);\n if (bus == NULL) {\n LOG(ERROR) << \"Failed to get bus: \" << GetAndFreeGError(&error);\n exit(1);\n }\n for (int i = 0; !proxy && i < kTries; ++i) {\n if (i > 0) {\n LOG(INFO) << \"Retrying to get dbus proxy. Try \"\n << (i + 1) << \"\/\" << kTries;\n g_usleep(kRetrySeconds * G_USEC_PER_SEC);\n }\n proxy = dbus_g_proxy_new_for_name_owner(bus,\n kUpdateEngineServiceName,\n kUpdateEngineServicePath,\n kUpdateEngineServiceInterface,\n &error);\n LOG_IF(WARNING, !proxy) << \"Error getting dbus proxy for \"\n << kUpdateEngineServiceName << \": \"\n << GetAndFreeGError(&error);\n }\n if (proxy == NULL) {\n LOG(ERROR) << \"Giving up -- unable to get dbus proxy for \"\n << kUpdateEngineServiceName;\n exit(1);\n }\n *out_proxy = proxy;\n return true;\n}\n\nstatic void StatusUpdateSignalHandler(DBusGProxy* proxy,\n int64_t last_checked_time,\n double progress,\n gchar* current_operation,\n gchar* new_version,\n int64_t new_size,\n void* user_data) {\n LOG(INFO) << \"Got status update:\";\n LOG(INFO) << \" last_checked_time: \" << last_checked_time;\n LOG(INFO) << \" progress: \" << progress;\n LOG(INFO) << \" current_operation: \" << current_operation;\n LOG(INFO) << \" new_version: \" << new_version;\n LOG(INFO) << \" new_size: \" << new_size;\n}\n\nbool ResetStatus() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_reset_status(proxy, &error);\n return rc;\n}\n\n\n\/\/ If |op| is non-NULL, sets it to the current operation string or an\n\/\/ empty string if unable to obtain the current status.\nbool GetStatus(string* op) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gint64 last_checked_time = 0;\n gdouble progress = 0.0;\n char* current_op = NULL;\n char* new_version = NULL;\n gint64 new_size = 0;\n\n gboolean rc = org_chromium_UpdateEngineInterface_get_status(\n proxy,\n &last_checked_time,\n &progress,\n ¤t_op,\n &new_version,\n &new_size,\n &error);\n if (rc == FALSE) {\n LOG(INFO) << \"Error getting status: \" << GetAndFreeGError(&error);\n }\n printf(\"LAST_CHECKED_TIME=%\" PRIi64 \"\\nPROGRESS=%f\\nCURRENT_OP=%s\\n\"\n \"NEW_VERSION=%s\\nNEW_SIZE=%\" PRIi64 \"\\n\",\n last_checked_time,\n progress,\n current_op,\n new_version,\n new_size);\n if (op) {\n *op = current_op ? current_op : \"\";\n }\n return true;\n}\n\n\/\/ Should never return.\nvoid WatchForUpdates() {\n DBusGProxy* proxy;\n\n CHECK(GetProxy(&proxy));\n\n \/\/ Register marshaller\n dbus_g_object_register_marshaller(\n update_engine_VOID__INT64_DOUBLE_STRING_STRING_INT64,\n G_TYPE_NONE,\n G_TYPE_INT64,\n G_TYPE_DOUBLE,\n G_TYPE_STRING,\n G_TYPE_STRING,\n G_TYPE_INT64,\n G_TYPE_INVALID);\n\n static const char kStatusUpdate[] = \"StatusUpdate\";\n dbus_g_proxy_add_signal(proxy,\n kStatusUpdate,\n G_TYPE_INT64,\n G_TYPE_DOUBLE,\n G_TYPE_STRING,\n G_TYPE_STRING,\n G_TYPE_INT64,\n G_TYPE_INVALID);\n GMainLoop* loop = g_main_loop_new (NULL, TRUE);\n dbus_g_proxy_connect_signal(proxy,\n kStatusUpdate,\n G_CALLBACK(StatusUpdateSignalHandler),\n NULL,\n NULL);\n g_main_loop_run(loop);\n g_main_loop_unref(loop);\n}\n\nbool CheckForUpdates(const string& app_version, const string& omaha_url) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_attempt_update(proxy,\n app_version.c_str(),\n omaha_url.c_str(),\n &error);\n CHECK_EQ(rc, TRUE) << \"Error checking for update: \"\n << GetAndFreeGError(&error);\n return true;\n}\n\nbool RebootIfNeeded() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_reboot_if_needed(proxy, &error);\n \/\/ Reboot error code doesn't necessarily mean that a reboot\n \/\/ failed. For example, D-Bus may be shutdown before we receive the\n \/\/ result.\n LOG_IF(INFO, !rc) << \"Reboot error message: \" << GetAndFreeGError(&error);\n return true;\n}\n\nvoid SetTrack(const string& track) {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n gboolean rc =\n org_chromium_UpdateEngineInterface_set_track(proxy,\n track.c_str(),\n &error);\n CHECK_EQ(rc, true) << \"Error setting the track: \"\n << GetAndFreeGError(&error);\n LOG(INFO) << \"Track permanently set to: \" << track;\n}\n\nstring GetTrack() {\n DBusGProxy* proxy;\n GError* error = NULL;\n\n CHECK(GetProxy(&proxy));\n\n char* track = NULL;\n gboolean rc =\n org_chromium_UpdateEngineInterface_get_track(proxy,\n &track,\n &error);\n CHECK_EQ(rc, true) << \"Error getting the track: \" << GetAndFreeGError(&error);\n string output = track;\n g_free(track);\n return output;\n}\n\nstatic gboolean CompleteUpdateSource(gpointer data) {\n string current_op;\n if (!GetStatus(¤t_op) || current_op == \"UPDATE_STATUS_IDLE\") {\n LOG(ERROR) << \"Update failed.\";\n exit(1);\n }\n if (current_op == \"UPDATE_STATUS_UPDATED_NEED_REBOOT\") {\n LOG(INFO) << \"Update succeeded -- reboot needed.\";\n exit(0);\n }\n return TRUE;\n}\n\n\/\/ This is similar to watching for updates but rather than registering\n\/\/ a signal watch, activelly poll the daemon just in case it stops\n\/\/ sending notifications.\nvoid CompleteUpdate() {\n GMainLoop* loop = g_main_loop_new (NULL, TRUE);\n g_timeout_add_seconds(5, CompleteUpdateSource, NULL);\n g_main_loop_run(loop);\n g_main_loop_unref(loop);\n}\n\n} \/\/ namespace {}\n\nint main(int argc, char** argv) {\n \/\/ Boilerplate init commands.\n g_type_init();\n g_thread_init(NULL);\n dbus_g_thread_init();\n chromeos_update_engine::Subprocess::Init();\n google::ParseCommandLineFlags(&argc, &argv, true);\n\n \/\/ Update the status if requested.\n if (FLAGS_reset_status) {\n LOG(INFO) << \"Setting Update Engine status to idle ...\";\n if (!ResetStatus()) {\n LOG(ERROR) << \"ResetStatus failed.\";\n return 1;\n }\n\n LOG(INFO) << \"ResetStatus succeeded; to undo partition table changes run:\\n\"\n \"(D=$(rootdev -d) P=$(rootdev -s); cgpt p -i$(($(echo ${P#$D} \"\n \"| sed 's\/^[^0-9]*\/\/')-1)) $D;)\";\n return 0;\n }\n\n\n if (FLAGS_status) {\n LOG(INFO) << \"Querying Update Engine status...\";\n if (!GetStatus(NULL)) {\n LOG(FATAL) << \"GetStatus failed.\";\n return 1;\n }\n return 0;\n }\n\n \/\/ First, update the track if requested.\n if (!FLAGS_track.empty()) {\n SetTrack(FLAGS_track);\n }\n\n \/\/ Show the track if requested.\n if (FLAGS_show_track) {\n LOG(INFO) << \"Track: \" << GetTrack();\n }\n\n \/\/ Initiate an update check, if necessary.\n if (FLAGS_check_for_update ||\n FLAGS_update ||\n !FLAGS_app_version.empty() ||\n !FLAGS_omaha_url.empty()) {\n LOG_IF(WARNING, FLAGS_reboot) << \"-reboot flag ignored.\";\n string app_version = FLAGS_app_version;\n if (FLAGS_update && app_version.empty()) {\n app_version = \"ForcedUpdate\";\n LOG(INFO) << \"Forcing an update by setting app_version to ForcedUpdate.\";\n }\n LOG(INFO) << \"Initiating update check and install.\";\n CHECK(CheckForUpdates(app_version, FLAGS_omaha_url))\n << \"Update check\/initiate update failed.\";\n\n \/\/ Wait for an update to complete.\n if (FLAGS_update) {\n LOG(INFO) << \"Waiting for update to complete.\";\n CompleteUpdate(); \/\/ Should never return.\n return 1;\n }\n return 0;\n }\n\n \/\/ Start watching for updates.\n if (FLAGS_watch_for_updates) {\n LOG_IF(WARNING, FLAGS_reboot) << \"-reboot flag ignored.\";\n LOG(INFO) << \"Watching for status updates.\";\n WatchForUpdates(); \/\/ Should never return.\n return 1;\n }\n\n if (FLAGS_reboot) {\n LOG(INFO) << \"Requesting a reboot...\";\n CHECK(RebootIfNeeded());\n return 0;\n }\n\n LOG(INFO) << \"Done.\";\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include \n\n\/\/ System includes\n#include \n#include \n\n#include \n\n#include \"IECore\/bindings\/ImathQuatBinding.h\"\n#include \"IECore\/bindings\/IECoreBinding.h\"\n\nusing namespace boost::python;\nusing namespace Imath;\n\nnamespace IECore \n{\n\t\ntemplate\nvoid bindQuat(const char *bindName);\n\nvoid bindImathQuat()\n{\t\n\tbindQuat(\"Quatf\");\n\tbindQuat(\"Quatd\");\t\n}\n\ntemplate\nstruct QuatIndexer\n{\t\n\tstatic T get(const Quat &x, int i)\n\t{\t\n\t\t\/\/ Do we want to handle backward indexing?\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\treturn x[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\t\n\t\t}\n\t\t\n\t}\n\t\n\tstatic void set(Quat &x, int i, const T &v)\n\t{\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\tx[i] = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\n\t\t}\n\t}\n\t\n\n};\n\n#define DEFINEQUATSTRSPECIALISATION( QUAT )\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string repr( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\ts << #QUAT << \"( \";\t\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \", \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\ts << \" )\";\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string str( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \" \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\nDEFINEQUATSTRSPECIALISATION( Quatf );\nDEFINEQUATSTRSPECIALISATION( Quatd );\n\ntemplate\nvoid bindQuat(const char *bindName)\n{\n\tclass_< Quat >(bindName)\t\n\t\t.def_readwrite(\"r\", &Quat::r)\n\t\t.def_readwrite(\"v\", &Quat::v)\n\t\n\t\t\/\/ [] operator support\n\t\t.def(\"__getitem__\", &QuatIndexer::get)\n\t\t.def(\"__setitem__\", &QuatIndexer::set)\n\t\n\t\t.def(init<>())\n\t\t.def(init >())\n\t\t.def(init())\n\t\t.def(init >())\n\t\n\t\t.def(\"identity\", &Quat::identity).staticmethod(\"identity\")\n\t\t\n\t\t.def(self ^ self)\n\t\n\t\t.def(self *= self)\n\t\t.def(self *= T())\n\t\t.def(self \/= self)\n\t\t.def(self \/= T())\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\n\t\t.def(\"invert\", &Quat::invert, return_self<>())\n\t\t.def(\"inverse\", &Quat::inverse)\t\t\n\t\t.def(\"normalize\", &Quat::normalize, return_self<>())\n\t\t.def(\"normalized\", &Quat::normalized)\n\t\t.def(\"length\", &Quat::length)\n\t\t\n\t\t.def(\"setAxisAngle\", &Quat::setAxisAngle, return_self<>())\n\t\t.def(\"setRotation\", &Quat::setRotation, return_self<>())\n\t\t\n\t\t.def(\"angle\", &Quat::angle)\n\t\t.def(\"axis\", &Quat::axis)\n\t\t\n\t\t.def(\"toMatrix33\", &Quat::toMatrix33)\n\t\t.def(\"toMatrix44\", &Quat::toMatrix44)\n\t\t\n\t\t.def(\"log\", &Quat::log)\n\t\t.def(\"exp\", &Quat::exp)\n\t\t\n\t\t.def(\"__str__\", IECore::str >)\n\t\t.def(\"__repr__\", IECore::repr >)\n\t;\n\t\t\t\n\tdef(\"slerp\", slerp);\n\tdef(\"squad\", squad);\n\tdef(\"spline\", spline);\n}\n\n}\nAdded more quaternion operators.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include \n\n\/\/ System includes\n#include \n#include \n\n#include \n\n#include \"IECore\/bindings\/ImathQuatBinding.h\"\n#include \"IECore\/bindings\/IECoreBinding.h\"\n\nusing namespace boost::python;\nusing namespace Imath;\n\nnamespace IECore \n{\n\t\ntemplate\nvoid bindQuat(const char *bindName);\n\nvoid bindImathQuat()\n{\t\n\tbindQuat(\"Quatf\");\n\tbindQuat(\"Quatd\");\t\n}\n\ntemplate\nstruct QuatIndexer\n{\t\n\tstatic T get(const Quat &x, int i)\n\t{\t\n\t\t\/\/ Do we want to handle backward indexing?\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\treturn x[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\t\n\t\t}\n\t\t\n\t}\n\t\n\tstatic void set(Quat &x, int i, const T &v)\n\t{\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\tx[i] = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\n\t\t}\n\t}\n\t\n\n};\n\n#define DEFINEQUATSTRSPECIALISATION( QUAT )\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string repr( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\ts << #QUAT << \"( \";\t\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \", \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\ts << \" )\";\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string str( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \" \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\nDEFINEQUATSTRSPECIALISATION( Quatf );\nDEFINEQUATSTRSPECIALISATION( Quatd );\n\ntemplate\nvoid bindQuat(const char *bindName)\n{\n\tclass_< Quat >(bindName)\t\n\t\t.def_readwrite(\"r\", &Quat::r)\n\t\t.def_readwrite(\"v\", &Quat::v)\n\t\n\t\t\/\/ [] operator support\n\t\t.def(\"__getitem__\", &QuatIndexer::get)\n\t\t.def(\"__setitem__\", &QuatIndexer::set)\n\t\n\t\t.def(init<>())\n\t\t.def(init >())\n\t\t.def(init())\n\t\t.def(init >())\n\t\n\t\t.def(\"identity\", &Quat::identity).staticmethod(\"identity\")\n\t\t\n\t\t.def(self ^ self)\n\t\n\t\t.def(self *= self)\n\t\t.def(self *= T())\n\t\t.def(self \/= self)\n\t\t.def(self \/= T())\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t\n\t\t.def( self * self )\n\t\n\t\t.def( ~self )\n\t\n\t\t.def(\"invert\", &Quat::invert, return_self<>())\n\t\t.def(\"inverse\", &Quat::inverse)\t\t\n\t\t.def(\"normalize\", &Quat::normalize, return_self<>())\n\t\t.def(\"normalized\", &Quat::normalized)\n\t\t.def(\"length\", &Quat::length)\n\t\t\n\t\t.def(\"setAxisAngle\", &Quat::setAxisAngle, return_self<>())\n\t\t.def(\"setRotation\", &Quat::setRotation, return_self<>())\n\t\t\n\t\t.def(\"angle\", &Quat::angle)\n\t\t.def(\"axis\", &Quat::axis)\n\t\t\n\t\t.def(\"toMatrix33\", &Quat::toMatrix33)\n\t\t.def(\"toMatrix44\", &Quat::toMatrix44)\n\t\t\n\t\t.def(\"log\", &Quat::log)\n\t\t.def(\"exp\", &Quat::exp)\n\t\t\n\t\t.def(\"__str__\", IECore::str >)\n\t\t.def(\"__repr__\", IECore::repr >)\n\t;\n\t\t\t\n\tdef(\"slerp\", slerp);\n\tdef(\"squad\", squad);\n\tdef(\"spline\", spline);\n}\n\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include \n\n\/\/ System includes\n#include \n#include \n\n#include \n\n#include \"IECore\/bindings\/ImathQuatBinding.h\"\n#include \"IECore\/bindings\/IECoreBinding.h\"\n\nusing namespace boost::python;\nusing namespace Imath;\n\nnamespace IECore \n{\n\t\ntemplate\nvoid bindQuat(const char *bindName);\n\nvoid bindImathQuat()\n{\t\n\tbindQuat(\"Quatf\");\n\tbindQuat(\"Quatd\");\t\n}\n\ntemplate\nstruct QuatIndexer\n{\t\n\tstatic T get(const Quat &x, int i)\n\t{\t\n\t\t\/\/ Do we want to handle backward indexing?\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\treturn x[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\t\n\t\t}\n\t\t\n\t}\n\t\n\tstatic void set(Quat &x, int i, const T &v)\n\t{\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\tx[i] = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\n\t\t}\n\t}\n\t\n\n};\n\n#define DEFINEQUATSTRSPECIALISATION( QUAT )\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string repr( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\ts << #QUAT << \"( \";\t\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \", \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\ts << \" )\";\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string str( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \" \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\nDEFINEQUATSTRSPECIALISATION( Quatf );\nDEFINEQUATSTRSPECIALISATION( Quatd );\n\ntemplate\nvoid bindQuat(const char *bindName)\n{\n\tclass_< Quat >(bindName)\t\n\t\t.def_readwrite(\"r\", &Quat::r)\n\t\t.def_readwrite(\"v\", &Quat::v)\n\t\n\t\t\/\/ [] operator support\n\t\t.def(\"__getitem__\", &QuatIndexer::get)\n\t\t.def(\"__setitem__\", &QuatIndexer::set)\n\t\n\t\t.def(init<>())\n\t\t.def(init >())\n\t\t.def(init())\n\t\t.def(init >())\n\t\n\t\t.def(\"identity\", &Quat::identity).staticmethod(\"identity\")\n\t\t\n\t\t.def(self ^ self)\n\t\n\t\t.def(self *= self)\n\t\t.def(self *= T())\n\t\t.def(self \/= self)\n\t\t.def(self \/= T())\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\n\t\t.def(\"invert\", &Quat::invert, return_self<>())\n\t\t.def(\"inverse\", &Quat::inverse)\t\t\n\t\t.def(\"normalize\", &Quat::normalize, return_self<>())\n\t\t.def(\"normalized\", &Quat::normalized)\n\t\t.def(\"length\", &Quat::length)\n\t\t\n\t\t.def(\"setAxisAngle\", &Quat::setAxisAngle, return_self<>())\n\t\t.def(\"setRotation\", &Quat::setRotation, return_self<>())\n\t\t\n\t\t.def(\"angle\", &Quat::angle)\n\t\t.def(\"axis\", &Quat::axis)\n\t\t\n\t\t.def(\"toMatrix33\", &Quat::toMatrix33)\n\t\t.def(\"toMatrix44\", &Quat::toMatrix44)\n\t\t\n\t\t.def(\"log\", &Quat::log)\n\t\t.def(\"exp\", &Quat::exp)\n\t\t\n\t\t.def(\"__str__\", IECore::str >)\n\t\t.def(\"__repr__\", IECore::repr >)\n\t;\n\t\t\t\n\tdef(\"slerp\", slerp);\n\tdef(\"squad\", squad);\n\tdef(\"spline\", spline);\n}\n\n}\nAdded more quaternion operators.\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2007, Image Engine Design Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of Image Engine Design nor the names of any\n\/\/ other contributors to this software may be used to endorse or\n\/\/ promote products derived from this software without specific prior\n\/\/ written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n\/\/ IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n\/\/ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n\/\/ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR\n\/\/ CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n\/\/ EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n\/\/ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n\/\/ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n\/\/ LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n\/\/ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n\/\/ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\/\/ This include needs to be the very first to prevent problems with warnings \n\/\/ regarding redefinition of _POSIX_C_SOURCE\n#include \n\n\/\/ System includes\n#include \n#include \n\n#include \n\n#include \"IECore\/bindings\/ImathQuatBinding.h\"\n#include \"IECore\/bindings\/IECoreBinding.h\"\n\nusing namespace boost::python;\nusing namespace Imath;\n\nnamespace IECore \n{\n\t\ntemplate\nvoid bindQuat(const char *bindName);\n\nvoid bindImathQuat()\n{\t\n\tbindQuat(\"Quatf\");\n\tbindQuat(\"Quatd\");\t\n}\n\ntemplate\nstruct QuatIndexer\n{\t\n\tstatic T get(const Quat &x, int i)\n\t{\t\n\t\t\/\/ Do we want to handle backward indexing?\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\treturn x[i];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\t\n\t\t}\n\t\t\n\t}\n\t\n\tstatic void set(Quat &x, int i, const T &v)\n\t{\n\t\tif ( i >= 0 && i < 4 ) \n\t\t{\n\t\t\tx[i] = v;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthrow std::out_of_range(\"\");\n\t\t}\n\t}\n\t\n\n};\n\n#define DEFINEQUATSTRSPECIALISATION( QUAT )\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string repr( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\ts << #QUAT << \"( \";\t\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \", \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\ts << \" )\";\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\ntemplate<>\t\t\t\t\t\t\t\t\t\t\t\t\\\nstd::string str( QUAT &x )\t\t\t\t\t\t\\\n{\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\tstd::stringstream s;\t\t\t\t\t\t\t\t\\\n\tfor( unsigned i=0; i<4; i++ )\t\t\t\t\t\t\\\n\t{\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\ts << x[i];\t\t\t\t\t\t\t\t\t\t\\\n\t\tif( i!=3 )\t\t\t\t\t\t\t\t\t\t\\\n\t\t{\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t\t\ts << \" \";\t\t\t\t\t\t\t\t\t\\\n\t\t}\t\t\t\t\t\t\t\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\treturn s.str();\t\t\t\t\t\t\t\t\t\t\\\n}\t\t\t\t\t\t\t\t\t\t\t\t\t\t\\\n\nDEFINEQUATSTRSPECIALISATION( Quatf );\nDEFINEQUATSTRSPECIALISATION( Quatd );\n\ntemplate\nvoid bindQuat(const char *bindName)\n{\n\tclass_< Quat >(bindName)\t\n\t\t.def_readwrite(\"r\", &Quat::r)\n\t\t.def_readwrite(\"v\", &Quat::v)\n\t\n\t\t\/\/ [] operator support\n\t\t.def(\"__getitem__\", &QuatIndexer::get)\n\t\t.def(\"__setitem__\", &QuatIndexer::set)\n\t\n\t\t.def(init<>())\n\t\t.def(init >())\n\t\t.def(init())\n\t\t.def(init >())\n\t\n\t\t.def(\"identity\", &Quat::identity).staticmethod(\"identity\")\n\t\t\n\t\t.def(self ^ self)\n\t\n\t\t.def(self *= self)\n\t\t.def(self *= T())\n\t\t.def(self \/= self)\n\t\t.def(self \/= T())\n\t\t.def(self += self)\n\t\t.def(self -= self)\n\t\n\t\t.def(self == self)\n\t\t.def(self != self)\n\t\t\n\t\t.def( self * self )\n\t\n\t\t.def( ~self )\n\t\n\t\t.def(\"invert\", &Quat::invert, return_self<>())\n\t\t.def(\"inverse\", &Quat::inverse)\t\t\n\t\t.def(\"normalize\", &Quat::normalize, return_self<>())\n\t\t.def(\"normalized\", &Quat::normalized)\n\t\t.def(\"length\", &Quat::length)\n\t\t\n\t\t.def(\"setAxisAngle\", &Quat::setAxisAngle, return_self<>())\n\t\t.def(\"setRotation\", &Quat::setRotation, return_self<>())\n\t\t\n\t\t.def(\"angle\", &Quat::angle)\n\t\t.def(\"axis\", &Quat::axis)\n\t\t\n\t\t.def(\"toMatrix33\", &Quat::toMatrix33)\n\t\t.def(\"toMatrix44\", &Quat::toMatrix44)\n\t\t\n\t\t.def(\"log\", &Quat::log)\n\t\t.def(\"exp\", &Quat::exp)\n\t\t\n\t\t.def(\"__str__\", IECore::str >)\n\t\t.def(\"__repr__\", IECore::repr >)\n\t;\n\t\t\t\n\tdef(\"slerp\", slerp);\n\tdef(\"squad\", squad);\n\tdef(\"spline\", spline);\n}\n\n}\n<|endoftext|>"} {"text":"#include \"ROOT\/TDataFrame.hxx\"\n#include \"Compression.h\"\n#include \"TFile.h\"\n#include \"TInterpreter.h\"\n#include \"TRandom.h\"\n\n#include \"gtest\/gtest.h\"\n\nusing namespace ROOT::Experimental;\n\nnamespace TEST_CATEGORY {\n\nint DefineFunction()\n{\n return 1;\n}\n\nstruct DefineStruct {\n int operator()() { return 1; }\n};\n\nvoid FillTree(const char *filename, const char *treeName, int nevents = 0)\n{\n TFile f(filename, \"RECREATE\");\n TTree t(treeName, treeName);\n t.SetAutoFlush(1); \/\/ yes, one event per cluster: to make MT more meaningful\n double b1;\n int b2;\n t.Branch(\"b1\", &b1);\n t.Branch(\"b2\", &b2);\n for (int i = 0; i < nevents; ++i) {\n b1 = i;\n b2 = i * i;\n t.Fill();\n }\n t.Write();\n f.Close();\n}\n}\n\nTEST(TEST_CATEGORY, CreateEmpty)\n{\n TDataFrame tdf(10);\n auto c = tdf.Count();\n EXPECT_EQ(10U, *c);\n}\n\nTEST(TEST_CATEGORY, CreateZeroEntries)\n{\n TDataFrame tdf(0);\n auto c = tdf.Count();\n EXPECT_EQ(0U, *c);\n}\n\nTEST(TEST_CATEGORY, CreateZeroEntriesWithBranches)\n{\n auto filename = \"dataframe_simple_0.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_0_CREATED\n#define testTDF_simple_0_CREATED\n TEST_CATEGORY::FillTree(filename, treename);\n#endif\n TDataFrame tdf(treename, filename);\n auto c = tdf.Count();\n auto m = tdf.Mean(\"b1\");\n EXPECT_EQ(0U, *c);\n EXPECT_EQ(0., *m);\n}\n\nTEST(TEST_CATEGORY, BuildWithTDirectory)\n{\n auto filename = \"dataframe_simple_1.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_1_CREATED\n#define testTDF_simple_1_CREATED\n TEST_CATEGORY::FillTree(filename, treename, 50);\n#endif\n TFile f(filename);\n TDataFrame tdf(treename, &f);\n auto c = tdf.Count();\n EXPECT_EQ(50U, *c);\n}\n\n\/\/ Jitting of column types\nTEST(TEST_CATEGORY, TypeGuessing)\n{\n auto filename = \"dataframe_simple_2.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_2_CREATED\n#define testTDF_simple_2_CREATED\n TEST_CATEGORY::FillTree(filename, treename, 50);\n#endif\n TDataFrame tdf(treename, filename, {\"b1\"});\n auto hcompiled = tdf.Histo1D();\n auto hjitted = tdf.Histo1D();\n EXPECT_EQ(50, hcompiled->GetEntries());\n EXPECT_EQ(50, hjitted->GetEntries());\n EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean());\n}\n\n\/\/ Define\n\nTEST(TEST_CATEGORY, Define_lambda)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", []() { return 1; });\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_function)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", TEST_CATEGORY::DefineFunction);\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_functor)\n{\n TDataFrame tdf(10);\n TEST_CATEGORY::DefineStruct def;\n auto d = tdf.Define(\"i\", def);\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", \"1\");\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_complex)\n{\n\/\/ The test can be run in sequential and MT mode.\n#ifndef RNDM_GEN_CREATED\n#define RNDM_GEN_CREATED\n gInterpreter->ProcessLine(\"TRandom r;\");\n#endif\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"i\", \"r.Uniform(0.,8.)\");\n auto m = d.Max(\"i\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\n\/\/ Define + Filters\nTEST(TEST_CATEGORY, Define_Filter)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"});\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_jitted)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter(\"r>5\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_named)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"}, \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_named_jitted)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter(\"r>5\", \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\n\/\/ jitted Define + Filters\nTEST(TEST_CATEGORY, Define_jitted_Filter)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"});\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_jitted)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter(\"r>5\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_named)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"}, \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter(\"r>5\", \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, DefineSlot)\n{\n std::array values;\n for (auto i = 0u; i < NSLOTS; ++i)\n values[i] = i;\n TDataFrame df(NSLOTS);\n auto ddf = df.DefineSlot(\"s\", [values](unsigned int slot) { return values[slot]; });\n auto m = ddf.Max(\"s\");\n EXPECT_EQ(*m, NSLOTS-1); \/\/ no matter the order of processing, the higher slot number is always taken at least once\n}\n\nTEST(TEST_CATEGORY, Snapshot_update)\n{\n using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;\n\n SnapshotOptions opts;\n\n opts.fMode = \"UPDATE\";\n\n TDataFrame tdf1(1000);\n auto s1 = tdf1.Define(\"one\", []() { return 1.0; })\n .Snapshot(\"mytree1\", \"snapshot_test_update.root\", {\"one\"});\n\n EXPECT_EQ(1000U, *s1.Count());\n\n EXPECT_EQ(1.0, *s1.Min(\"one\"));\n EXPECT_EQ(1.0, *s1.Max(\"one\"));\n EXPECT_EQ(1.0, *s1.Mean(\"one\"));\n\n TDataFrame tdf2(1000);\n auto s2 = tdf2.Define(\"two\", []() { return 2.0; })\n .Snapshot(\"mytree2\", \"snapshot_test_update.root\", {\"two\"}, opts);\n\n EXPECT_EQ(1000U, *s2.Count());\n\n EXPECT_EQ(2.0, *s2.Min(\"two\"));\n EXPECT_EQ(2.0, *s2.Max(\"two\"));\n EXPECT_EQ(2.0, *s2.Mean(\"two\"));\n\n TFile *f = TFile::Open(\"snapshot_test_update.root\", \"READ\");\n auto mytree1 = (TTree*) f->Get(\"mytree1\");\n auto mytree2 = (TTree*) f->Get(\"mytree2\");\n\n EXPECT_NE(nullptr, mytree1);\n EXPECT_NE(nullptr, mytree2);\n\n f->Close();\n delete f;\n}\n\nTEST(TEST_CATEGORY, Snapshot_action_with_options)\n{\n using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;\n\n SnapshotOptions opts;\n opts.fAutoFlush = 10;\n opts.fMode = \"RECREATE\";\n\n for (auto algorithm : { ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4 }) {\n TDataFrame tdf(1000);\n\n opts.fCompressionLevel = 6;\n opts.fCompressionAlgorithm = algorithm;\n\n auto s = tdf.Define(\"one\", []() { return 1.0; })\n .Snapshot(\"mytree\", \"snapshot_test_opts.root\", {\"one\"}, opts);\n\n EXPECT_EQ(1000U, *s.Count());\n EXPECT_EQ(1.0, *s.Min(\"one\"));\n EXPECT_EQ(1.0, *s.Max(\"one\"));\n EXPECT_EQ(1.0, *s.Mean(\"one\"));\n\n TFile *f = TFile::Open(\"snapshot_test_opts.root\", \"READ\");\n\n EXPECT_EQ(algorithm, f->GetCompressionAlgorithm());\n EXPECT_EQ(6, f->GetCompressionLevel());\n\n f->Close();\n delete f;\n }\n}\n\n\/\/ This tests the interface but we need to run it both w\/ and w\/o implicit mt\n#ifdef R__USE_IMT\nTEST(TEST_CATEGORY, GetNSlots)\n{\n EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots());\n}\n#endif\n[TDF] More tests of DefineSlot#include \"ROOT\/TDataFrame.hxx\"\n#include \"Compression.h\"\n#include \"TFile.h\"\n#include \"TInterpreter.h\"\n#include \"TRandom.h\"\n\n#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n\nusing namespace ROOT::Experimental;\n\nnamespace TEST_CATEGORY {\n\nint DefineFunction()\n{\n return 1;\n}\n\nstruct DefineStruct {\n int operator()() { return 1; }\n};\n\nvoid FillTree(const char *filename, const char *treeName, int nevents = 0)\n{\n TFile f(filename, \"RECREATE\");\n TTree t(treeName, treeName);\n t.SetAutoFlush(1); \/\/ yes, one event per cluster: to make MT more meaningful\n double b1;\n int b2;\n t.Branch(\"b1\", &b1);\n t.Branch(\"b2\", &b2);\n for (int i = 0; i < nevents; ++i) {\n b1 = i;\n b2 = i * i;\n t.Fill();\n }\n t.Write();\n f.Close();\n}\n}\n\nTEST(TEST_CATEGORY, CreateEmpty)\n{\n TDataFrame tdf(10);\n auto c = tdf.Count();\n EXPECT_EQ(10U, *c);\n}\n\nTEST(TEST_CATEGORY, CreateZeroEntries)\n{\n TDataFrame tdf(0);\n auto c = tdf.Count();\n EXPECT_EQ(0U, *c);\n}\n\nTEST(TEST_CATEGORY, CreateZeroEntriesWithBranches)\n{\n auto filename = \"dataframe_simple_0.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_0_CREATED\n#define testTDF_simple_0_CREATED\n TEST_CATEGORY::FillTree(filename, treename);\n#endif\n TDataFrame tdf(treename, filename);\n auto c = tdf.Count();\n auto m = tdf.Mean(\"b1\");\n EXPECT_EQ(0U, *c);\n EXPECT_EQ(0., *m);\n}\n\nTEST(TEST_CATEGORY, BuildWithTDirectory)\n{\n auto filename = \"dataframe_simple_1.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_1_CREATED\n#define testTDF_simple_1_CREATED\n TEST_CATEGORY::FillTree(filename, treename, 50);\n#endif\n TFile f(filename);\n TDataFrame tdf(treename, &f);\n auto c = tdf.Count();\n EXPECT_EQ(50U, *c);\n}\n\n\/\/ Jitting of column types\nTEST(TEST_CATEGORY, TypeGuessing)\n{\n auto filename = \"dataframe_simple_2.root\";\n auto treename = \"t\";\n#ifndef testTDF_simple_2_CREATED\n#define testTDF_simple_2_CREATED\n TEST_CATEGORY::FillTree(filename, treename, 50);\n#endif\n TDataFrame tdf(treename, filename, {\"b1\"});\n auto hcompiled = tdf.Histo1D();\n auto hjitted = tdf.Histo1D();\n EXPECT_EQ(50, hcompiled->GetEntries());\n EXPECT_EQ(50, hjitted->GetEntries());\n EXPECT_DOUBLE_EQ(hcompiled->GetMean(), hjitted->GetMean());\n}\n\n\/\/ Define\n\nTEST(TEST_CATEGORY, Define_lambda)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", []() { return 1; });\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_function)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", TEST_CATEGORY::DefineFunction);\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_functor)\n{\n TDataFrame tdf(10);\n TEST_CATEGORY::DefineStruct def;\n auto d = tdf.Define(\"i\", def);\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted)\n{\n TDataFrame tdf(10);\n auto d = tdf.Define(\"i\", \"1\");\n auto m = d.Mean(\"i\");\n EXPECT_DOUBLE_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_complex)\n{\n\/\/ The test can be run in sequential and MT mode.\n#ifndef RNDM_GEN_CREATED\n#define RNDM_GEN_CREATED\n gInterpreter->ProcessLine(\"TRandom r;\");\n#endif\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"i\", \"r.Uniform(0.,8.)\");\n auto m = d.Max(\"i\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\n\/\/ Define + Filters\nTEST(TEST_CATEGORY, Define_Filter)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"});\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_jitted)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter(\"r>5\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_named)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"}, \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_Filter_named_jitted)\n{\n TRandom r(1);\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", [&r]() { return r.Uniform(0., 8.); });\n auto df = d.Filter(\"r>5\", \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\n\/\/ jitted Define + Filters\nTEST(TEST_CATEGORY, Define_jitted_Filter)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"});\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_jitted)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter(\"r>5\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_named)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter([](double x) { return x > 5; }, {\"r\"}, \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, Define_jitted_Filter_named_jitted)\n{\n gInterpreter->ProcessLine(\"r.SetSeed(1);\");\n TDataFrame tdf(50);\n auto d = tdf.Define(\"r\", \"r.Uniform(0.,8.)\");\n auto df = d.Filter(\"r>5\", \"myFilter\");\n auto m = df.Max(\"r\");\n EXPECT_EQ(7.867497533559811628, *m);\n}\n\nTEST(TEST_CATEGORY, DefineSlotConsistency)\n{\n TDataFrame df(8);\n auto m = df.DefineSlot(\"x\", [](unsigned int ) { return 1.; }).Max(\"x\");\n EXPECT_EQ(1., *m);\n}\n\nTEST(TEST_CATEGORY, DefineSlot)\n{\n std::array values;\n for (auto i = 0u; i < NSLOTS; ++i)\n values[i] = i;\n TDataFrame df(NSLOTS);\n auto ddf = df.DefineSlot(\"s\", [values](unsigned int slot) { return values[slot]; });\n auto m = ddf.Max(\"s\");\n EXPECT_EQ(*m, NSLOTS-1); \/\/ no matter the order of processing, the higher slot number is always taken at least once\n}\n\nTEST(TEST_CATEGORY, DefineSlotCheckMT)\n{\n auto nSlots = NSLOTS;\n\n std::hash hasher;\n using H_t = decltype(hasher(std::this_thread::get_id()));\n\n std::vector ids(nSlots, 0);\n TDataFrame d(nSlots);\n auto m = d.DefineSlot(\"x\", [&](unsigned int slot) {\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n ids[slot] = hasher(std::this_thread::get_id());\n return 1.; }).Max(\"x\");\n\n EXPECT_EQ(1, *m); \/\/ just in case\n\n std::set s(ids.begin(), ids.end());\n EXPECT_EQ(nSlots, s.size());\n EXPECT_TRUE(s.end() == s.find(0));\n}\n\nTEST(TEST_CATEGORY, Snapshot_update)\n{\n using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;\n\n SnapshotOptions opts;\n\n opts.fMode = \"UPDATE\";\n\n TDataFrame tdf1(1000);\n auto s1 = tdf1.Define(\"one\", []() { return 1.0; })\n .Snapshot(\"mytree1\", \"snapshot_test_update.root\", {\"one\"});\n\n EXPECT_EQ(1000U, *s1.Count());\n\n EXPECT_EQ(1.0, *s1.Min(\"one\"));\n EXPECT_EQ(1.0, *s1.Max(\"one\"));\n EXPECT_EQ(1.0, *s1.Mean(\"one\"));\n\n TDataFrame tdf2(1000);\n auto s2 = tdf2.Define(\"two\", []() { return 2.0; })\n .Snapshot(\"mytree2\", \"snapshot_test_update.root\", {\"two\"}, opts);\n\n EXPECT_EQ(1000U, *s2.Count());\n\n EXPECT_EQ(2.0, *s2.Min(\"two\"));\n EXPECT_EQ(2.0, *s2.Max(\"two\"));\n EXPECT_EQ(2.0, *s2.Mean(\"two\"));\n\n TFile *f = TFile::Open(\"snapshot_test_update.root\", \"READ\");\n auto mytree1 = (TTree*) f->Get(\"mytree1\");\n auto mytree2 = (TTree*) f->Get(\"mytree2\");\n\n EXPECT_NE(nullptr, mytree1);\n EXPECT_NE(nullptr, mytree2);\n\n f->Close();\n delete f;\n}\n\nTEST(TEST_CATEGORY, Snapshot_action_with_options)\n{\n using SnapshotOptions = ROOT::Experimental::TDF::SnapshotOptions;\n\n SnapshotOptions opts;\n opts.fAutoFlush = 10;\n opts.fMode = \"RECREATE\";\n\n for (auto algorithm : { ROOT::kZLIB, ROOT::kLZMA, ROOT::kLZ4 }) {\n TDataFrame tdf(1000);\n\n opts.fCompressionLevel = 6;\n opts.fCompressionAlgorithm = algorithm;\n\n auto s = tdf.Define(\"one\", []() { return 1.0; })\n .Snapshot(\"mytree\", \"snapshot_test_opts.root\", {\"one\"}, opts);\n\n EXPECT_EQ(1000U, *s.Count());\n EXPECT_EQ(1.0, *s.Min(\"one\"));\n EXPECT_EQ(1.0, *s.Max(\"one\"));\n EXPECT_EQ(1.0, *s.Mean(\"one\"));\n\n TFile *f = TFile::Open(\"snapshot_test_opts.root\", \"READ\");\n\n EXPECT_EQ(algorithm, f->GetCompressionAlgorithm());\n EXPECT_EQ(6, f->GetCompressionLevel());\n\n f->Close();\n delete f;\n }\n}\n\n\/\/ This tests the interface but we need to run it both w\/ and w\/o implicit mt\n#ifdef R__USE_IMT\nTEST(TEST_CATEGORY, GetNSlots)\n{\n EXPECT_EQ(NSLOTS, ROOT::Internal::TDF::GetNSlots());\n}\n#endif\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2002, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n#include \n#include \n#include \n#include \n#include \n\n#if defined (__GNUC__) && __GNUC__ == 2\n#include \n#else\n#include \n#endif\n\nusing namespace std;\nusing namespace Imf;\n\nnamespace {\n\n\nstruct CharIO\n{\n static void\n writeChars (ostream &os, const char c[], int n)\n {\n\tos.write (c, n);\n }\n\n static bool\n readChars (istream &is, char c[], int n)\n {\n\tis.read (c, n);\n\treturn true;\n }\n};\n\n\nvoid\nwriteData (ostream &os)\n{\n Xdr::write (os, (bool) true);\n Xdr::write (os, (bool) false);\n Xdr::write (os, (char) 'r');\n Xdr::write (os, (char) 'e');\n Xdr::write (os, (signed char) 'u');\n Xdr::write (os, (signed char) 'c');\n Xdr::write (os, (unsigned char) 'k');\n Xdr::write (os, (unsigned char) 'y');\n Xdr::write (os, (signed short) 8765);\n Xdr::write (os, (signed short) -9876);\n Xdr::write (os, (unsigned short) 6543);\n Xdr::write (os, (unsigned short) 17432);\n Xdr::write (os, (signed int) 2023456789);\n Xdr::write (os, (signed int) -2012345678);\n Xdr::write (os, (unsigned int) 1234567890u);\n Xdr::write (os, (unsigned int) 2345678901u);\n Xdr::write (os, (signed long) 2034567890);\n Xdr::write (os, (signed long) -2045678901);\n Xdr::write (os, (unsigned long) 1345678901u);\n Xdr::write (os, (unsigned long) 2456789012u);\n Xdr::write (os, (Int64) 0x1122334455667788ll);\n Xdr::write (os, (Int64) 0xf1f2f3f4f5f6f7f8ll);\n Xdr::write (os, (float) 0.0f);\n Xdr::write (os, (float) 3.141592653589793f);\n Xdr::write (os, (float) 6.141592653589793f);\n Xdr::write (os, (double) 0);\n Xdr::write (os, (double) 1.41421356237309504880);\n Xdr::write (os, (double) 2.41421356237309504880);\n Xdr::write (os, (half) 0);\n Xdr::write (os, (half) 3.4142);\n Xdr::write (os, (half) 4.4142);\n Xdr::write (os, \"abcdefgh\", 4);\t\/\/ fixed-size char array\n Xdr::write (os, \"rstuvwxy\", 5);\n Xdr::write (os, \"qwerty\");\t\/\/ zero-terminated string\n Xdr::write (os, \"asdfghjkl\");\n Xdr::write (os, \"\");\t\n Xdr::pad (os, 17);\n Xdr::write (os, (int) 1);\n Xdr::pad (os, 0);\n Xdr::write (os, (int) 2);\n Xdr::pad (os, 17);\n Xdr::write (os, (int) 3);\n\n assert (!os == false);\n}\n\ntemplate \nvoid\ncheck (istream &is, T c)\n{\n T v;\n\n Xdr::read (is, v);\n cout << typeid(v).name() << \": expected \" << c << \", got \" << v << endl;\n assert (c == v);\n}\n\n\ntemplate <>\nvoid\ncheck (istream &is, const char * c)\n{\n char v[1024];\n\n Xdr::read (is, sizeof (v), v);\n\n cout << \"zero-terminated string: \"\n\t \"expected \\\"\" << c << \"\\\", \"\n\t \"got \\\"\" << v << \"\\\"\" << endl;\n\n assert (!strcmp (c, v));\n}\n\n\nvoid\ncheck (istream &is, const char c[\/*n*\/], int n)\n{\n char v[1024];\n\n assert (n <= (int) sizeof (v));\n\n Xdr::read (is, v, n);\n\n cout << \"char[\" << n << \"]: expected \\\"\";\n\n for (int i = 0; i < n; i++)\n\tcout << c[i];\n\n cout << \"\\\", got \\\"\";\n\n for (int i = 0; i < n; i++)\n\tcout << v[i];\n\n cout << \"\\\"\" << endl;\n\n for (int i = 0; i < n; i++)\n\tassert (c[i] == v[i]);\n}\n\n\nvoid\nreadData (istream &is)\n{\n check (is, (bool) true);\n check (is, (bool) false);\n check (is, (char) 'r');\n check (is, (char) 'e');\n check (is, (signed char) 'u');\n check (is, (signed char) 'c');\n check (is, (unsigned char) 'k');\n check (is, (unsigned char) 'y');\n check (is, (signed short) 8765);\n check (is, (signed short) -9876);\n check (is, (unsigned short) 6543);\n check (is, (unsigned short) 17432);\n check (is, (signed int) 2023456789);\n check (is, (signed int) -2012345678);\n check (is, (unsigned int) 1234567890u);\n check (is, (unsigned int) 2345678901u);\n check (is, (signed long) 2034567890);\n check (is, (signed long) -2045678901);\n check (is, (unsigned long) 1345678901u);\n check (is, (unsigned long) 2456789012u);\n check (is, (Int64) 0x1122334455667788ll);\n check (is, (Int64) 0xf1f2f3f4f5f6f7f8ll);\n check (is, (float) 0.0f);\n check (is, (float) 3.141592653589793f);\n check (is, (float) 6.141592653589793f);\n check (is, (double) 0.0);\n check (is, (double) 1.41421356237309504880);\n check (is, (double) 2.41421356237309504880);\n check (is, (half) 0);\n check (is, (half) 3.4142);\n check (is, (half) 4.4142);\n check (is, (const char *) \"abcdefgh\", 4);\n check (is, (const char *) \"rstuvwxy\", 5);\n check (is, (const char *) \"qwerty\");\n check (is, (const char *) \"asdfghjkl\");\n check (is, (const char *) \"\");\t\n Xdr::skip (is, 17);\n check (is, (int) 1);\n Xdr::skip (is, 0);\n check (is, (int) 2);\n Xdr::skip (is, 17);\n check (is, (int) 3);\n\n assert (!is == false);\n}\n\n\n} \/\/ namespace\n\n\nvoid\ntestXdr ()\n{\n cout << \"Testing Xdr\" << endl;\n\n try\n {\n#if defined (__GNUC__) && __GNUC__ == 2\n\tstrstream s;\n#else\n\tstringstream s;\n#endif\n\n\twriteData (s);\n\ts.seekg (0);\n\treadData (s);\n }\n catch (const std::exception &e)\n {\n\tcout << \"unexpected exception: \" << e.what() << endl;\n\tassert (false);\n }\n catch (...)\n {\n\tcout << \"unexpected exception\" << endl;\n\tassert (false);\n }\n\n cout << \"ok\\n\" << endl;\n}\nadded BROKEN_ISTREAM_HACK check to routines that bypass StdIO\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright (c) 2002, Industrial Light & Magic, a division of Lucas\n\/\/ Digital Ltd. LLC\n\/\/ \n\/\/ All rights reserved.\n\/\/ \n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Industrial Light & Magic nor the names of\n\/\/ its contributors may be used to endorse or promote products derived\n\/\/ from this software without specific prior written permission. \n\/\/ \n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\n#include \n#include \n#include \n#include \n#include \n\n#if defined (__GNUC__) && __GNUC__ == 2\n#include \n#else\n#include \n#endif\n\nusing namespace std;\nusing namespace Imf;\n\nnamespace {\n\n\nstruct CharIO\n{\n static void\n writeChars (ostream &os, const char c[], int n)\n {\n\tos.write (c, n);\n }\n\n static bool\n readChars (istream &is, char c[], int n)\n {\n\tis.read (c, n);\n\treturn true;\n }\n};\n\n\nvoid\nwriteData (ostream &os)\n{\n Xdr::write (os, (bool) true);\n Xdr::write (os, (bool) false);\n Xdr::write (os, (char) 'r');\n Xdr::write (os, (char) 'e');\n Xdr::write (os, (signed char) 'u');\n Xdr::write (os, (signed char) 'c');\n Xdr::write (os, (unsigned char) 'k');\n Xdr::write (os, (unsigned char) 'y');\n Xdr::write (os, (signed short) 8765);\n Xdr::write (os, (signed short) -9876);\n Xdr::write (os, (unsigned short) 6543);\n Xdr::write (os, (unsigned short) 17432);\n Xdr::write (os, (signed int) 2023456789);\n Xdr::write (os, (signed int) -2012345678);\n Xdr::write (os, (unsigned int) 1234567890u);\n Xdr::write (os, (unsigned int) 2345678901u);\n Xdr::write (os, (signed long) 2034567890);\n Xdr::write (os, (signed long) -2045678901);\n Xdr::write (os, (unsigned long) 1345678901u);\n Xdr::write (os, (unsigned long) 2456789012u);\n Xdr::write (os, (Int64) 0x1122334455667788ll);\n Xdr::write (os, (Int64) 0xf1f2f3f4f5f6f7f8ll);\n Xdr::write (os, (float) 0.0f);\n Xdr::write (os, (float) 3.141592653589793f);\n Xdr::write (os, (float) 6.141592653589793f);\n Xdr::write (os, (double) 0);\n Xdr::write (os, (double) 1.41421356237309504880);\n Xdr::write (os, (double) 2.41421356237309504880);\n Xdr::write (os, (half) 0);\n Xdr::write (os, (half) 3.4142);\n Xdr::write (os, (half) 4.4142);\n Xdr::write (os, \"abcdefgh\", 4);\t\/\/ fixed-size char array\n Xdr::write (os, \"rstuvwxy\", 5);\n Xdr::write (os, \"qwerty\");\t\/\/ zero-terminated string\n Xdr::write (os, \"asdfghjkl\");\n Xdr::write (os, \"\");\t\n Xdr::pad (os, 17);\n Xdr::write (os, (int) 1);\n Xdr::pad (os, 0);\n Xdr::write (os, (int) 2);\n Xdr::pad (os, 17);\n Xdr::write (os, (int) 3);\n\n assert (!os == false);\n}\n\ntemplate \nvoid\ncheck (istream &is, T c)\n{\n T v;\n\n Xdr::read (is, v);\n cout << typeid(v).name() << \": expected \" << c << \", got \" << v << endl;\n assert (c == v);\n}\n\n\ntemplate <>\nvoid\ncheck (istream &is, const char * c)\n{\n char v[1024];\n\n Xdr::read (is, sizeof (v), v);\n\n cout << \"zero-terminated string: \"\n\t \"expected \\\"\" << c << \"\\\", \"\n\t \"got \\\"\" << v << \"\\\"\" << endl;\n\n assert (!strcmp (c, v));\n}\n\n\nvoid\ncheck (istream &is, const char c[\/*n*\/], int n)\n{\n char v[1024];\n\n assert (n <= (int) sizeof (v));\n\n Xdr::read (is, v, n);\n\n cout << \"char[\" << n << \"]: expected \\\"\";\n\n for (int i = 0; i < n; i++)\n\tcout << c[i];\n\n cout << \"\\\", got \\\"\";\n\n for (int i = 0; i < n; i++)\n\tcout << v[i];\n\n cout << \"\\\"\" << endl;\n\n for (int i = 0; i < n; i++)\n\tassert (c[i] == v[i]);\n}\n\n\nvoid\nreadData (istream &is)\n{\n check (is, (bool) true);\n check (is, (bool) false);\n check (is, (char) 'r');\n check (is, (char) 'e');\n check (is, (signed char) 'u');\n check (is, (signed char) 'c');\n check (is, (unsigned char) 'k');\n check (is, (unsigned char) 'y');\n check (is, (signed short) 8765);\n check (is, (signed short) -9876);\n check (is, (unsigned short) 6543);\n check (is, (unsigned short) 17432);\n check (is, (signed int) 2023456789);\n check (is, (signed int) -2012345678);\n check (is, (unsigned int) 1234567890u);\n check (is, (unsigned int) 2345678901u);\n check (is, (signed long) 2034567890);\n check (is, (signed long) -2045678901);\n check (is, (unsigned long) 1345678901u);\n check (is, (unsigned long) 2456789012u);\n check (is, (Int64) 0x1122334455667788ll);\n check (is, (Int64) 0xf1f2f3f4f5f6f7f8ll);\n check (is, (float) 0.0f);\n check (is, (float) 3.141592653589793f);\n check (is, (float) 6.141592653589793f);\n check (is, (double) 0.0);\n check (is, (double) 1.41421356237309504880);\n check (is, (double) 2.41421356237309504880);\n check (is, (half) 0);\n check (is, (half) 3.4142);\n check (is, (half) 4.4142);\n check (is, (const char *) \"abcdefgh\", 4);\n check (is, (const char *) \"rstuvwxy\", 5);\n check (is, (const char *) \"qwerty\");\n check (is, (const char *) \"asdfghjkl\");\n check (is, (const char *) \"\");\t\n Xdr::skip (is, 17);\n check (is, (int) 1);\n Xdr::skip (is, 0);\n check (is, (int) 2);\n Xdr::skip (is, 17);\n check (is, (int) 3);\n\n\t\/\/ HACK - this is a workaround for a bug in Apple's\n\t\/\/ implementation of istream::read. It's present in\n\t\/\/ gcc 3.1, but fixed in gcc 3.3 and later.\n\n#if !(BROKEN_ISTREAM_HACK)\t\n assert (!is == false);\n#endif\n}\n\n\n} \/\/ namespace\n\n\nvoid\ntestXdr ()\n{\n cout << \"Testing Xdr\" << endl;\n\n try\n {\n#if defined (__GNUC__) && __GNUC__ == 2\n\tstrstream s;\n#else\n\tstringstream s;\n#endif\n\n\twriteData (s);\n\ts.seekg (0);\n\treadData (s);\n }\n catch (const std::exception &e)\n {\n\tcout << \"unexpected exception: \" << e.what() << endl;\n\tassert (false);\n }\n catch (...)\n {\n\tcout << \"unexpected exception\" << endl;\n\tassert (false);\n }\n\n cout << \"ok\\n\" << endl;\n}\n<|endoftext|>"} {"text":"add missing DeleteTab in test<|endoftext|>"} {"text":"#pragma once\n\n#include \n\nnamespace blackhole {\ninline namespace v1 {\nnamespace detail {\n\nclass spinlock_t {\n OSSpinLock mutex;\n\npublic:\n constexpr spinlock_t() noexcept:\n mutex(0)\n {}\n\n auto lock() noexcept -> void {\n OSSpinLockLock(&mutex);\n }\n\n auto unlock() noexcept -> void {\n OSSpinLockUnlock(&mutex);\n }\n\n auto trylock() noexcept -> bool {\n return OSSpinLockTry(&mutex);\n }\n};\n\n} \/\/ namespace detail\n} \/\/ namespace v1\n} \/\/ namespace blackhole\nfeat: replace deprecated OSX stuff with modern one#pragma once\n\n#include \n\nnamespace blackhole {\ninline namespace v1 {\nnamespace detail {\n\nclass spinlock_t {\n os_unfair_lock mutex;\n\npublic:\n constexpr spinlock_t() noexcept:\n mutex({0})\n {}\n\n auto lock() noexcept -> void {\n os_unfair_lock_lock(&mutex);\n }\n\n auto unlock() noexcept -> void {\n os_unfair_lock_unlock(&mutex);\n }\n\n auto trylock() noexcept -> bool {\n return os_unfair_lock_trylock(&mutex);\n }\n};\n\n} \/\/ namespace detail\n} \/\/ namespace v1\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"#include \"engine\/selene\/selene.h\"\n#include \"engine\/Game.hpp\"\n\nusing namespace std;\nusing namespace sf;\n\nclass TestState : public GameState\n{\npublic:\n\tTestState() : _main_open(false)\n\t{ }\n\n\tvirtual void init() override\n\t{ }\n\n\tvirtual void load_resources() override\n\t{ }\n\n\tvirtual void unload_resources() override\n\t{ }\n\n\tvirtual void update(Seconds) override\n\t{\n\t\tImGui::Begin(\"Main\", &_main_open, ImGuiWindowFlags_NoResize);\n\t\tImGui::Text(\"Hello, world!\");\n\t\tif (ImGui::Button(\"Exit\"))\n\t\t\tgame().quit(0);\n\t\tImGui::End();\n\t}\n\n\tvirtual void render() override\n\t{ }\n\nprotected:\n\tbool _main_open;\n};\n\nclass TestGame : public Game\n{\npublic:\n\tTestGame() : _stack(this)\n\t{ }\n\n\tvirtual void init(int argc, char** argv) override\n\t{\n\t\tGame::init(argc, argv);\n\t\t_stack.push();\n\t}\n\n\tvirtual void frame_start() override\n\t{\n\t\tGame::frame_start();\n\t}\n\n\tvirtual void process_event(sf::Event& e) override\n\t{\n\t\tGame::process_event(e);\n\t}\n\n\tvirtual void update(Seconds delta_time) override\n\t{\n\t\tGame::update(delta_time);\n\t\t_stack.update(delta_time);\n\t}\n\n\tvirtual void frame_end() override\n\t{\n\t\t_stack.render();\n\t\tGame::frame_end();\n\t}\n\nprivate:\n\tGameStateStack _stack;\n};\n\nint main(int argc, char** argv)\n{ return run(argc, argv); }\nAdded a simple Lua test#include \"engine\/selene\/selene.h\"\n#include \"engine\/Game.hpp\"\n\nusing namespace std;\nusing namespace sf;\n\nclass TestState : public GameState\n{\npublic:\n\tTestState() : _main_open(false)\n\t{ }\n\n\tvirtual void init() override;\n\n\tvirtual void load_resources() override;\n\n\tvirtual void unload_resources() override;\n\n\tvirtual void update(Seconds) override;\n\n\tvirtual void render() override;\n\nprotected:\n\tbool _main_open;\n};\n\nclass TestGame : public Game\n{\npublic:\n\tTestGame() : _lua(true), _stack(this)\n\t{ }\n\n\tvirtual void init(int argc, char** argv) override\n\t{\n\t\tGame::init(argc, argv);\n\t\t_stack.push();\n\t}\n\n\tvirtual void frame_start() override\n\t{\n\t\tGame::frame_start();\n\t}\n\n\tvirtual void process_event(sf::Event& e) override\n\t{\n\t\tGame::process_event(e);\n\t}\n\n\tvirtual void update(Seconds delta_time) override\n\t{\n\t\tGame::update(delta_time);\n\t\t_stack.update(delta_time);\n\t}\n\n\tvirtual void frame_end() override\n\t{\n\t\t_stack.render();\n\t\tGame::frame_end();\n\t}\n\n\tsel::State& lua()\n\t{ return _lua; }\n\nprivate:\n\tsel::State _lua;\n\tGameStateStack _stack;\n};\n\nint main(int argc, char** argv)\n{ return run(argc, argv); }\n\nvoid TestState::init()\n{\n\tgame().lua()(\"print('Hello Lua!')\");\n}\n\nvoid TestState::load_resources()\n{ }\n\nvoid TestState::unload_resources()\n{ }\n\nvoid TestState::update(Seconds)\n{\n\tImGui::Begin(\"Main\", &_main_open, ImGuiWindowFlags_NoResize);\n\tImGui::Text(\"Hello, world!\");\n\tif (ImGui::Button(\"Exit\"))\n\t\tgame().quit(0);\n\tImGui::End();\n}\n\nvoid TestState::render()\n{ }\n<|endoftext|>"} {"text":"\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Elliptic \/\/ NOLINT(whitespace\/line_length)\n\n#include \n#include \n\n#include \"base\/tags.hpp\"\n#include \"benchmark\/benchmark.h\"\n#include \"numerics\/elliptic_integrals.hpp\"\n#include \"quantities\/numbers.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\n\nusing base::uninitialized;\nusing quantities::Angle;\nusing quantities::si::Radian;\n\nnamespace numerics {\n\nvoid BM_EllipticFEΠ(benchmark::State& state) {\n constexpr int size = 20;\n\n std::mt19937_64 random(42);\n std::uniform_real_distribution<> distribution_φ(0.0, π \/ 2);\n std::uniform_real_distribution<> distribution_n(0.0, 1.0);\n std::uniform_real_distribution<> distribution_mc(0.0, 1.0);\n std::vector φs;\n std::vector ns;\n std::vector mcs;\n for (int i = 0; i < size; ++i) {\n φs.push_back(distribution_φ(random) * Radian);\n ns.push_back(distribution_n(random));\n mcs.push_back(distribution_mc(random));\n }\n\n while (state.KeepRunningBatch(size * size * size)) {\n Angle e{uninitialized};\n Angle f{uninitialized};\n Angle ᴨ{uninitialized};\n for (Angle const φ : φs) {\n for (double const n : ns) {\n for (double const mc : mcs) {\n EllipticFEΠ(φ, n, mc, f, e, ᴨ);\n }\n }\n }\n benchmark::DoNotOptimize(e);\n benchmark::DoNotOptimize(f);\n benchmark::DoNotOptimize(ᴨ);\n }\n}\n\nvoid BM_FukushimaEllipticBDJ(benchmark::State& state) {\n constexpr int size = 20;\n\n std::mt19937_64 random(42);\n std::uniform_real_distribution<> distribution_φ(0.0, π \/ 2);\n std::uniform_real_distribution<> distribution_n(0.0, 1.0);\n std::uniform_real_distribution<> distribution_mc(0.0, 1.0);\n std::vector φs;\n std::vector ns;\n std::vector mcs;\n for (int i = 0; i < size; ++i) {\n φs.push_back(distribution_φ(random) * Radian);\n ns.push_back(distribution_n(random));\n mcs.push_back(distribution_mc(random));\n }\n\n while (state.KeepRunningBatch(size * size * size)) {\n Angle b{uninitialized};\n Angle d{uninitialized};\n Angle j{uninitialized};\n for (Angle const φ : φs) {\n for (double const n : ns) {\n for (double const mc : mcs) {\n FukushimaEllipticBDJ(φ, n, mc, b, d, j);\n }\n }\n }\n benchmark::DoNotOptimize(b);\n benchmark::DoNotOptimize(d);\n benchmark::DoNotOptimize(j);\n }\n}\n\nBENCHMARK(BM_EllipticFEΠ);\nBENCHMARK(BM_FukushimaEllipticBDJ);\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\nbenchmark\n\/\/ .\\Release\\x64\\benchmarks.exe --benchmark_repetitions=10 --benchmark_min_time=2 --benchmark_filter=Elliptic \/\/ NOLINT(whitespace\/line_length)\n\n#include \n#include \n\n#include \"base\/tags.hpp\"\n#include \"benchmark\/benchmark.h\"\n#include \"numerics\/elliptic_integrals.hpp\"\n#include \"quantities\/numbers.hpp\"\n#include \"quantities\/si.hpp\"\n\nnamespace principia {\n\nusing base::uninitialized;\nusing quantities::Angle;\nusing quantities::si::Radian;\n\nnamespace numerics {\n\nvoid BM_EllipticF(benchmark::State& state) {\n constexpr int size = 20;\n\n std::mt19937_64 random(42);\n std::uniform_real_distribution<> distribution_φ(0.0, π \/ 2);\n std::uniform_real_distribution<> distribution_n(0.0, 1.0);\n std::uniform_real_distribution<> distribution_mc(0.0, 1.0);\n std::vector φs;\n std::vector ns;\n std::vector mcs;\n for (int i = 0; i < size; ++i) {\n φs.push_back(distribution_φ(random) * Radian);\n ns.push_back(distribution_n(random));\n mcs.push_back(distribution_mc(random));\n }\n\n while (state.KeepRunningBatch(size * size * size)) {\n Angle f;\n for (Angle const φ : φs) {\n for (double const n : ns) {\n for (double const mc : mcs) {\n f += EllipticF(φ, mc);\n }\n }\n }\n benchmark::DoNotOptimize(f);\n }\n}\n\nvoid BM_EllipticFEΠ(benchmark::State& state) {\n constexpr int size = 20;\n\n std::mt19937_64 random(42);\n std::uniform_real_distribution<> distribution_φ(0.0, π \/ 2);\n std::uniform_real_distribution<> distribution_n(0.0, 1.0);\n std::uniform_real_distribution<> distribution_mc(0.0, 1.0);\n std::vector φs;\n std::vector ns;\n std::vector mcs;\n for (int i = 0; i < size; ++i) {\n φs.push_back(distribution_φ(random) * Radian);\n ns.push_back(distribution_n(random));\n mcs.push_back(distribution_mc(random));\n }\n\n while (state.KeepRunningBatch(size * size * size)) {\n Angle e{uninitialized};\n Angle f{uninitialized};\n Angle ᴨ{uninitialized};\n for (Angle const φ : φs) {\n for (double const n : ns) {\n for (double const mc : mcs) {\n EllipticFEΠ(φ, n, mc, f, e, ᴨ);\n }\n }\n }\n benchmark::DoNotOptimize(e);\n benchmark::DoNotOptimize(f);\n benchmark::DoNotOptimize(ᴨ);\n }\n}\n\nvoid BM_FukushimaEllipticBDJ(benchmark::State& state) {\n constexpr int size = 20;\n\n std::mt19937_64 random(42);\n std::uniform_real_distribution<> distribution_φ(0.0, π \/ 2);\n std::uniform_real_distribution<> distribution_n(0.0, 1.0);\n std::uniform_real_distribution<> distribution_mc(0.0, 1.0);\n std::vector φs;\n std::vector ns;\n std::vector mcs;\n for (int i = 0; i < size; ++i) {\n φs.push_back(distribution_φ(random) * Radian);\n ns.push_back(distribution_n(random));\n mcs.push_back(distribution_mc(random));\n }\n\n while (state.KeepRunningBatch(size * size * size)) {\n Angle b{uninitialized};\n Angle d{uninitialized};\n Angle j{uninitialized};\n for (Angle const φ : φs) {\n for (double const n : ns) {\n for (double const mc : mcs) {\n FukushimaEllipticBDJ(φ, n, mc, b, d, j);\n }\n }\n }\n benchmark::DoNotOptimize(b);\n benchmark::DoNotOptimize(d);\n benchmark::DoNotOptimize(j);\n }\n}\n\nBENCHMARK(BM_EllipticF);\nBENCHMARK(BM_EllipticFEΠ);\nBENCHMARK(BM_FukushimaEllipticBDJ);\n\n} \/\/ namespace numerics\n} \/\/ namespace principia\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2010-2013 Joshua Boyce.\n\/\/ See the file COPYING for copying permission.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ TODO: Extra sanity checking in all components. E.g. Check\n\/\/ NumberOfRvaAndSizes in NtHeaders before attempting to retrieve a data dir.\n\n\/\/ TODO: Helper functions such as FindExport, FindImport, HasDataDir,\n\/\/ GetArchitecture, IsDotNet, GetPDB, etc.\n\n\/\/ TODO: Move PeLib code into PeLib namespace.\n\n\/\/ TODO: Rewrite PeLib to allow writes from scratch (building new PE file\n\/\/ sections, data, etc. or even an entire mew PE file). This includes full\n\/\/ support for writing back to existing PE files also, including automatically\n\/\/ performing adjustments where required to fit in new data or remove\n\/\/ unnecessary space.\n\n\/\/ TODO: Decouple PeFile from Process. It should use a generic interface\n\/\/ instead.\tAnother potential alternative would be policy classes. Needs\n\/\/ investigation.\n\n\/\/ TODO: Decouple PeLib from the architecture being compiled for. Required\n\/\/ for cross-architecture support in hadesmem.\n\n\/\/ TODO: Support more of the PE file format.\n\/\/ Overlay data.\n\/\/ Resource directory.\n\/\/ Exception directory.\n\/\/ Relocation directory.\n\/\/ Security directory.\n\/\/ Debug directory.\n\/\/ Load config directory.\n\/\/ Delay import directory.\n\/\/ Bound import directory.\n\/\/ IAT(as opposed to Import) directory.\n\/\/ CLR runtime directory support.\n\/\/ DOS stub.\n\/\/ Rich header.\n\/\/ Checksum.\n\/\/ etc.\n\n\/\/ TODO: Improve PeLib support for pathological cases like Corkami tests. We\n\/\/ should not only ensure we don't crash, but we should also ensure we're\n\/\/ actually getting the right data out!\n\n\/\/ TODO: Where possible, document the SHA1 of example files which prompted the\n\/\/ addition of corner cases.\n\nnamespace hadesmem\n{\n\n\/\/ TODO: Investigate whether there is a better way to implement this.\nenum class PeFileType\n{\n Image,\n Data\n};\n\nclass PeFile\n{\npublic:\n explicit PeFile(Process const& process,\n PVOID address,\n PeFileType type,\n DWORD size)\n : base_(static_cast(address)), type_(type), size_(size)\n {\n HADESMEM_DETAIL_ASSERT(base_ != 0);\n if (type == PeFileType::Data && !size)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid file size.\"));\n }\n\n \/\/ Process is not actually used but we take it anyway for\n \/\/ interface symetry and in case we want to change the\n \/\/ implementation to use it later without breaking the interface.\n (void)process;\n }\n\n PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT\n {\n return base_;\n }\n\n PeFileType GetType() const HADESMEM_DETAIL_NOEXCEPT\n {\n return type_;\n }\n\n DWORD GetSize() const HADESMEM_DETAIL_NOEXCEPT\n {\n return size_;\n }\n\nprivate:\n PBYTE base_;\n PeFileType type_;\n DWORD size_;\n};\n\ninline bool operator==(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() == rhs.GetBase();\n}\n\ninline bool operator!=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return !(lhs == rhs);\n}\n\ninline bool operator<(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() < rhs.GetBase();\n}\n\ninline bool operator<=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() <= rhs.GetBase();\n}\n\ninline bool operator>(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() > rhs.GetBase();\n}\n\ninline bool operator>=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() >= rhs.GetBase();\n}\n\ninline std::ostream& operator<<(std::ostream& lhs, PeFile const& rhs)\n{\n std::locale const old = lhs.imbue(std::locale::classic());\n lhs << static_cast(rhs.GetBase());\n lhs.imbue(old);\n return lhs;\n}\n\ninline std::wostream& operator<<(std::wostream& lhs, PeFile const& rhs)\n{\n std::locale const old = lhs.imbue(std::locale::classic());\n lhs << static_cast(rhs.GetBase());\n lhs.imbue(old);\n return lhs;\n}\n\ninline PVOID RvaToVa(Process const& process, PeFile const& pe_file, DWORD rva)\n{\n PeFileType const type = pe_file.GetType();\n PBYTE base = static_cast(pe_file.GetBase());\n\n if (type == PeFileType::Data)\n {\n if (!rva)\n {\n return nullptr;\n }\n\n IMAGE_DOS_HEADER dos_header = Read(process, base);\n if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid DOS header.\"));\n }\n\n BYTE* ptr_nt_headers = base + dos_header.e_lfanew;\n IMAGE_NT_HEADERS nt_headers =\n Read(process, ptr_nt_headers);\n if (nt_headers.Signature != IMAGE_NT_SIGNATURE)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid NT headers.\"));\n }\n\n \/\/ Windows will load specially crafted images with no sections.\n \/\/ TODO: Improve the logic here using the information in \"Zero section PE\n \/\/ file\" in ReversingLabs \"Undocumented PECOFF\" whitepaper.\n WORD num_sections = nt_headers.FileHeader.NumberOfSections;\n if (!num_sections)\n {\n \/\/ In cases where the PE file has no sections it can apparently also have\n \/\/ all sorts of messed up RVAs for data dirs etc... Make sure that none of\n \/\/ them lie outside the file, because otherwise simply returning a direct\n \/\/ offset from the base wouldn't work anyway...\n if (rva > pe_file.GetSize())\n {\n return nullptr;\n }\n else\n {\n return base + rva;\n }\n }\n\n \/\/ SizeOfHeaders can be arbitrarily large, including the size of the\n \/\/ entire file. RVAs inside the headers are treated as an offset from\n \/\/ zero, rather than finding the 'true' location in a section.\n if (rva < nt_headers.OptionalHeader.SizeOfHeaders)\n {\n return base + rva;\n }\n\n \/\/ Apparently on XP it's possible to load a PE with a SizeOfImage of only\n \/\/ 0x2e. Treat anything outside of that as invalid. For an example see\n \/\/ foldedhdr.exe from the Corkami PE corpus.\n \/\/ TODO: According to ReversingLabs \"Undocumented PECOFF\" whitepaper,\n \/\/ SizeOfImage should be rounded up using SectionAlignment. Investigate\n \/\/ this.\n if (rva > nt_headers.OptionalHeader.SizeOfImage)\n {\n return nullptr;\n }\n\n IMAGE_SECTION_HEADER* ptr_section_header =\n reinterpret_cast(\n ptr_nt_headers + offsetof(IMAGE_NT_HEADERS, OptionalHeader) +\n nt_headers.FileHeader.SizeOfOptionalHeader);\n IMAGE_SECTION_HEADER section_header =\n Read(process, ptr_section_header);\n\n bool in_header = true;\n for (WORD i = 0; i < num_sections; ++i)\n {\n DWORD const virtual_beg = section_header.VirtualAddress;\n DWORD const virtual_size = section_header.Misc.VirtualSize;\n DWORD const raw_size = section_header.SizeOfRawData;\n \/\/ If VirtualSize is zero then SizeOfRawData is used.\n DWORD const virtual_end =\n virtual_beg + (virtual_size ? virtual_size : raw_size);\n if (virtual_beg <= rva && rva < virtual_end)\n {\n rva -= virtual_beg;\n\n \/\/ If the RVA is outside the raw data (which would put it in the\n \/\/ zero-fill of the virtual data) just return nullptr because it's\n \/\/ invalid. Technically files like this will work when loaded by the\n \/\/ PE loader due to the sections being mapped differention in memory\n \/\/ to on disk, but if you want to inspect the file in that manner you\n \/\/ should just use LoadLibrary with the appropriate flags for your\n \/\/ scenario and then use PeFileType::Image.\n if (rva > raw_size)\n {\n return nullptr;\n }\n\n \/\/ If PointerToRawData is less than 0x200 it is rounded\n \/\/ down to 0. Safe to mask it off unconditionally because\n \/\/ it must be a multiple of FileAlignment.\n rva +=\n section_header.PointerToRawData &\n ~((std::max)(0x200UL, nt_headers.OptionalHeader.FileAlignment) - 1);\n\n \/\/ If the RVA now lies outside the actual file just return nullptr\n \/\/ because it's invalid.\n if (rva >= pe_file.GetSize())\n {\n return nullptr;\n }\n\n return base + rva;\n }\n\n \/\/ This should be the 'normal' case. However sometimes the RVA is at a\n \/\/ lower address than any of the sections, so we want to detect this so we\n \/\/ can just treat the RVA as an offset from the module base (similar to\n \/\/ when the image is loaded).\n if (virtual_beg <= rva)\n {\n in_header = false;\n }\n\n section_header =\n Read(process, ++ptr_section_header);\n }\n\n if (in_header && rva < pe_file.GetSize())\n {\n return base + rva;\n }\n\n return nullptr;\n }\n else if (type == PeFileType::Image)\n {\n return rva ? (base + rva) : nullptr;\n }\n else\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Unhandled file type.\"));\n }\n}\n}\n* [PeFile] Note to self.\/\/ Copyright (C) 2010-2013 Joshua Boyce.\n\/\/ See the file COPYING for copying permission.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/\/ TODO: Extra sanity checking in all components. E.g. Check\n\/\/ NumberOfRvaAndSizes in NtHeaders before attempting to retrieve a data dir.\n\n\/\/ TODO: Helper functions such as FindExport, FindImport, HasDataDir,\n\/\/ GetArchitecture, IsDotNet, GetPDB, etc.\n\n\/\/ TODO: Move PeLib code into PeLib namespace.\n\n\/\/ TODO: Rewrite PeLib to allow writes from scratch (building new PE file\n\/\/ sections, data, etc. or even an entire mew PE file). This includes full\n\/\/ support for writing back to existing PE files also, including automatically\n\/\/ performing adjustments where required to fit in new data or remove\n\/\/ unnecessary space.\n\n\/\/ TODO: Decouple PeFile from Process (and other memory APIs). It should use a\n\/\/ generic interface instead.\tAnother potential alternative would be policy\n\/\/ classes. Needs investigation.\n\n\/\/ TODO: Decouple PeLib from the architecture being compiled for. Required\n\/\/ for cross-architecture support in hadesmem.\n\n\/\/ TODO: Support more of the PE file format.\n\/\/ Overlay data.\n\/\/ Resource directory.\n\/\/ Exception directory.\n\/\/ Relocation directory.\n\/\/ Security directory.\n\/\/ Debug directory.\n\/\/ Load config directory.\n\/\/ Delay import directory.\n\/\/ Bound import directory.\n\/\/ IAT(as opposed to Import) directory.\n\/\/ CLR runtime directory support.\n\/\/ DOS stub.\n\/\/ Rich header.\n\/\/ Checksum.\n\/\/ etc.\n\n\/\/ TODO: Improve PeLib support for pathological cases like Corkami tests. We\n\/\/ should not only ensure we don't crash, but we should also ensure we're\n\/\/ actually getting the right data out!\n\n\/\/ TODO: Where possible, document the SHA1 of example files which prompted the\n\/\/ addition of corner cases.\n\nnamespace hadesmem\n{\n\n\/\/ TODO: Investigate whether there is a better way to implement this.\nenum class PeFileType\n{\n Image,\n Data\n};\n\nclass PeFile\n{\npublic:\n explicit PeFile(Process const& process,\n PVOID address,\n PeFileType type,\n DWORD size)\n : base_(static_cast(address)), type_(type), size_(size)\n {\n HADESMEM_DETAIL_ASSERT(base_ != 0);\n if (type == PeFileType::Data && !size)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid file size.\"));\n }\n\n \/\/ Process is not actually used but we take it anyway for\n \/\/ interface symetry and in case we want to change the\n \/\/ implementation to use it later without breaking the interface.\n (void)process;\n }\n\n PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT\n {\n return base_;\n }\n\n PeFileType GetType() const HADESMEM_DETAIL_NOEXCEPT\n {\n return type_;\n }\n\n DWORD GetSize() const HADESMEM_DETAIL_NOEXCEPT\n {\n return size_;\n }\n\nprivate:\n PBYTE base_;\n PeFileType type_;\n DWORD size_;\n};\n\ninline bool operator==(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() == rhs.GetBase();\n}\n\ninline bool operator!=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return !(lhs == rhs);\n}\n\ninline bool operator<(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() < rhs.GetBase();\n}\n\ninline bool operator<=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() <= rhs.GetBase();\n}\n\ninline bool operator>(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() > rhs.GetBase();\n}\n\ninline bool operator>=(PeFile const& lhs, PeFile const& rhs)\n HADESMEM_DETAIL_NOEXCEPT\n{\n return lhs.GetBase() >= rhs.GetBase();\n}\n\ninline std::ostream& operator<<(std::ostream& lhs, PeFile const& rhs)\n{\n std::locale const old = lhs.imbue(std::locale::classic());\n lhs << static_cast(rhs.GetBase());\n lhs.imbue(old);\n return lhs;\n}\n\ninline std::wostream& operator<<(std::wostream& lhs, PeFile const& rhs)\n{\n std::locale const old = lhs.imbue(std::locale::classic());\n lhs << static_cast(rhs.GetBase());\n lhs.imbue(old);\n return lhs;\n}\n\ninline PVOID RvaToVa(Process const& process, PeFile const& pe_file, DWORD rva)\n{\n PeFileType const type = pe_file.GetType();\n PBYTE base = static_cast(pe_file.GetBase());\n\n if (type == PeFileType::Data)\n {\n if (!rva)\n {\n return nullptr;\n }\n\n IMAGE_DOS_HEADER dos_header = Read(process, base);\n if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid DOS header.\"));\n }\n\n BYTE* ptr_nt_headers = base + dos_header.e_lfanew;\n IMAGE_NT_HEADERS nt_headers =\n Read(process, ptr_nt_headers);\n if (nt_headers.Signature != IMAGE_NT_SIGNATURE)\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Invalid NT headers.\"));\n }\n\n \/\/ Windows will load specially crafted images with no sections.\n \/\/ TODO: Improve the logic here using the information in \"Zero section PE\n \/\/ file\" in ReversingLabs \"Undocumented PECOFF\" whitepaper.\n WORD num_sections = nt_headers.FileHeader.NumberOfSections;\n if (!num_sections)\n {\n \/\/ In cases where the PE file has no sections it can apparently also have\n \/\/ all sorts of messed up RVAs for data dirs etc... Make sure that none of\n \/\/ them lie outside the file, because otherwise simply returning a direct\n \/\/ offset from the base wouldn't work anyway...\n if (rva > pe_file.GetSize())\n {\n return nullptr;\n }\n else\n {\n return base + rva;\n }\n }\n\n \/\/ SizeOfHeaders can be arbitrarily large, including the size of the\n \/\/ entire file. RVAs inside the headers are treated as an offset from\n \/\/ zero, rather than finding the 'true' location in a section.\n if (rva < nt_headers.OptionalHeader.SizeOfHeaders)\n {\n return base + rva;\n }\n\n \/\/ Apparently on XP it's possible to load a PE with a SizeOfImage of only\n \/\/ 0x2e. Treat anything outside of that as invalid. For an example see\n \/\/ foldedhdr.exe from the Corkami PE corpus.\n \/\/ TODO: According to ReversingLabs \"Undocumented PECOFF\" whitepaper,\n \/\/ SizeOfImage should be rounded up using SectionAlignment. Investigate\n \/\/ this.\n if (rva > nt_headers.OptionalHeader.SizeOfImage)\n {\n return nullptr;\n }\n\n IMAGE_SECTION_HEADER* ptr_section_header =\n reinterpret_cast(\n ptr_nt_headers + offsetof(IMAGE_NT_HEADERS, OptionalHeader) +\n nt_headers.FileHeader.SizeOfOptionalHeader);\n IMAGE_SECTION_HEADER section_header =\n Read(process, ptr_section_header);\n\n bool in_header = true;\n for (WORD i = 0; i < num_sections; ++i)\n {\n DWORD const virtual_beg = section_header.VirtualAddress;\n DWORD const virtual_size = section_header.Misc.VirtualSize;\n DWORD const raw_size = section_header.SizeOfRawData;\n \/\/ If VirtualSize is zero then SizeOfRawData is used.\n DWORD const virtual_end =\n virtual_beg + (virtual_size ? virtual_size : raw_size);\n if (virtual_beg <= rva && rva < virtual_end)\n {\n rva -= virtual_beg;\n\n \/\/ If the RVA is outside the raw data (which would put it in the\n \/\/ zero-fill of the virtual data) just return nullptr because it's\n \/\/ invalid. Technically files like this will work when loaded by the\n \/\/ PE loader due to the sections being mapped differention in memory\n \/\/ to on disk, but if you want to inspect the file in that manner you\n \/\/ should just use LoadLibrary with the appropriate flags for your\n \/\/ scenario and then use PeFileType::Image.\n if (rva > raw_size)\n {\n return nullptr;\n }\n\n \/\/ If PointerToRawData is less than 0x200 it is rounded\n \/\/ down to 0. Safe to mask it off unconditionally because\n \/\/ it must be a multiple of FileAlignment.\n rva +=\n section_header.PointerToRawData &\n ~((std::max)(0x200UL, nt_headers.OptionalHeader.FileAlignment) - 1);\n\n \/\/ If the RVA now lies outside the actual file just return nullptr\n \/\/ because it's invalid.\n if (rva >= pe_file.GetSize())\n {\n return nullptr;\n }\n\n return base + rva;\n }\n\n \/\/ This should be the 'normal' case. However sometimes the RVA is at a\n \/\/ lower address than any of the sections, so we want to detect this so we\n \/\/ can just treat the RVA as an offset from the module base (similar to\n \/\/ when the image is loaded).\n if (virtual_beg <= rva)\n {\n in_header = false;\n }\n\n section_header =\n Read(process, ++ptr_section_header);\n }\n\n if (in_header && rva < pe_file.GetSize())\n {\n return base + rva;\n }\n\n return nullptr;\n }\n else if (type == PeFileType::Image)\n {\n return rva ? (base + rva) : nullptr;\n }\n else\n {\n HADESMEM_DETAIL_THROW_EXCEPTION(Error()\n << ErrorString(\"Unhandled file type.\"));\n }\n}\n}\n<|endoftext|>"} {"text":"\/\/\/\n\/\/\/ @file PushBackPrimes.hpp\n\/\/\/ @brief This file contains classes needed to store primes in\n\/\/\/ std::vector objects. These classes derive from\n\/\/\/ PrimeSieveCallback and call PrimeSieve's callbackPrimes()\n\/\/\/ method, the primes are then pushed back into the vector\n\/\/\/ inside the callback method.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PUSHBACKPRIMES_HPP\n#define PUSHBACKPRIMES_HPP\n\n#include \"PrimeSieve.hpp\"\n#include \"PrimeSieveCallback.hpp\"\n#include \"cancel_callback.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace soe {\n\n\/\/\/ approximate_prime_count(x) > pi(x)\ninline uint64_t approximate_prime_count(uint64_t start, uint64_t stop)\n{\n if (start > stop)\n return 0;\n if (stop < 10)\n return 10;\n return static_cast((stop - start) \/ (std::log(static_cast(stop)) - 1.1));\n}\n\ntemplate \nclass PushBackPrimes : public PrimeSieveCallback\n{\npublic:\n PushBackPrimes(std::vector& primes)\n : primes_(primes)\n { }\n void pushBackPrimes(uint64_t start, uint64_t stop)\n {\n if (start <= stop)\n {\n uint64_t prime_count = approximate_prime_count(start, stop);\n uint64_t limit = std::numeric_limits::max();\n primes_.reserve(primes_.size() + static_cast(std::min(prime_count, limit)));\n PrimeSieve ps;\n ps.callbackPrimes(start, stop, this);\n }\n }\n void callback(uint64_t prime)\n {\n primes_.push_back(static_cast(prime));\n }\nprivate:\n PushBackPrimes(const PushBackPrimes&);\n void operator=(const PushBackPrimes&);\n std::vector& primes_;\n};\n\ntemplate \nclass PushBack_N_Primes : public PrimeSieveCallback\n{\npublic:\n PushBack_N_Primes(std::vector& primes) \n : primes_(primes)\n { }\n void pushBack_N_Primes(uint64_t n, uint64_t start)\n {\n n_ = n;\n primes_.reserve(primes_.size() + n_);\n PrimeSieve ps;\n try\n {\n while (n_ > 0)\n {\n uint64_t logn = 50;\n \/\/ choose stop > nth prime\n uint64_t stop = start + n_ * logn + 10000;\n ps.callbackPrimes(start, stop, this);\n start = stop + 1;\n }\n }\n catch (cancel_callback&) { }\n }\n void callback(uint64_t prime)\n {\n primes_.push_back(static_cast(prime));\n if (--n_ == 0)\n throw cancel_callback();\n }\n private:\n PushBack_N_Primes(const PushBack_N_Primes&);\n void operator=(const PushBack_N_Primes&);\n std::vector& primes_;\n uint64_t n_;\n};\n\n} \/\/ namespace soe\n\n#endif\nSilence sunCC warning\/\/\/\n\/\/\/ @file PushBackPrimes.hpp\n\/\/\/ @brief This file contains classes needed to store primes in\n\/\/\/ std::vector objects. These classes derive from\n\/\/\/ PrimeSieveCallback and call PrimeSieve's callbackPrimes()\n\/\/\/ method, the primes are then pushed back into the vector\n\/\/\/ inside the callback method.\n\/\/\/\n\/\/\/ Copyright (C) 2013 Kim Walisch, \n\/\/\/\n\/\/\/ This file is distributed under the BSD License. See the COPYING\n\/\/\/ file in the top level directory.\n\/\/\/\n\n#ifndef PUSHBACKPRIMES_HPP\n#define PUSHBACKPRIMES_HPP\n\n#include \"PrimeSieve.hpp\"\n#include \"PrimeSieveCallback.hpp\"\n#include \"cancel_callback.hpp\"\n#include \"primesieve_error.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace soe {\n\n\/\/\/ approximate_prime_count(x) > pi(x)\ninline uint64_t approximate_prime_count(uint64_t start, uint64_t stop)\n{\n if (start > stop)\n return 0;\n if (stop < 10)\n return 10;\n return static_cast((stop - start) \/ (std::log(static_cast(stop)) - 1.1));\n}\n\ntemplate \nclass PushBackPrimes : public PrimeSieveCallback\n{\npublic:\n PushBackPrimes(std::vector& primes)\n : primes_(primes)\n { }\n void pushBackPrimes(uint64_t start, uint64_t stop)\n {\n if (start <= stop)\n {\n uint64_t prime_count = approximate_prime_count(start, stop);\n if (prime_count > std::numeric_limits::max())\n throw primesieve_error(\"cannot generate number of primes > SIZE_MAX (max(size_t))\");\n primes_.reserve(primes_.size() + static_cast(prime_count));\n PrimeSieve ps;\n ps.callbackPrimes(start, stop, this);\n }\n }\n void callback(uint64_t prime)\n {\n primes_.push_back(static_cast(prime));\n }\nprivate:\n PushBackPrimes(const PushBackPrimes&);\n void operator=(const PushBackPrimes&);\n std::vector& primes_;\n};\n\ntemplate \nclass PushBack_N_Primes : public PrimeSieveCallback\n{\npublic:\n PushBack_N_Primes(std::vector& primes) \n : primes_(primes)\n { }\n void pushBack_N_Primes(uint64_t n, uint64_t start)\n {\n n_ = n;\n if (n_ > std::numeric_limits::max())\n throw primesieve_error(\"cannot generate number of primes > SIZE_MAX (max(size_t))\");\n primes_.reserve(primes_.size() + static_cast(n_));\n PrimeSieve ps;\n try\n {\n while (n_ > 0)\n {\n uint64_t logn = 50;\n \/\/ choose stop > nth prime\n uint64_t stop = start + n_ * logn + 10000;\n ps.callbackPrimes(start, stop, this);\n start = stop + 1;\n }\n }\n catch (cancel_callback&) { }\n }\n void callback(uint64_t prime)\n {\n primes_.push_back(static_cast(prime));\n if (--n_ == 0)\n throw cancel_callback();\n }\n private:\n PushBack_N_Primes(const PushBack_N_Primes&);\n void operator=(const PushBack_N_Primes&);\n std::vector& primes_;\n uint64_t n_;\n};\n\n} \/\/ namespace soe\n\n#endif\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"indices_2d.hxx\"\n#include \"..\/math\/circular_modulus.hxx\"\n\n#include \n#include \n#include \n\nnamespace usagi\n{\n namespace container\n {\n template\n < typename T >\n class circular_tile\n : boost::circular_buffer< boost::circular_buffer< T > >\n {\n public:\n using type = circular_tile;\n \n using cols_type = boost::circular_buffer< T >;\n using rows_type = boost::circular_buffer< cols_type >;\n \n using operate_cols_functor_signature = auto ( cols_type& ) -> void;\n using operate_cols_functor_type = std::function< operate_cols_functor_signature >;\n \n using apply_functor_signature = auto ( T& ) -> void;\n using apply_functor_type = std::function< apply_functor_signature >;\n \n using on_arris_resize_functor_signature = auto ( const type& ref, std::size_t new_size ) -> void;\n using on_arris_resize_functor_type = std::function< on_arris_resize_functor_signature >;\n\n protected:\n\n inline static auto make_cols( const std::size_t size, const T& default_value = T() )\n { return cols_type( size, default_value ); }\n\n auto make_cols( const T& default_value = T() )\n { return make_cols( rows_type::front().size(), default_value ); }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto make_cols( const DATA_TYPE& data )\n {\n cols_type cols( rows_type::front().size() );\n for ( const auto& datum : data )\n cols.push_back( datum );\n return cols;\n }\n\n template < typename VALUE_TYPE, typename MESSAGE_TYPE >\n inline static auto throw_if_zero( const VALUE_TYPE value, const MESSAGE_TYPE& message )\n {\n if ( value == 0 )\n throw std::logic_error( message );\n }\n\n public:\n\n on_arris_resize_functor_type on_cols_resize_before;\n on_arris_resize_functor_type on_cols_resize_after;\n \n on_arris_resize_functor_type on_rows_resize_before;\n on_arris_resize_functor_type on_rows_resize_after;\n\n circular_tile( const std::size_t cols_size, const std::size_t rows_size, const T& default_value = T() )\n : rows_type( rows_size, make_cols( cols_size, default_value ) )\n , on_cols_resize_before( get_nothing_functor_on_arris_resize() )\n , on_cols_resize_after ( get_nothing_functor_on_arris_resize() )\n , on_rows_resize_before( get_nothing_functor_on_arris_resize() )\n , on_rows_resize_after ( get_nothing_functor_on_arris_resize() )\n {\n throw_if_zero( cols_size, \"cols_size == 0\" );\n throw_if_zero( rows_size, \"rows_size == 0\" );\n }\n\n circular_tile( const std::size_t size, const T& default_value = T() )\n : circular_tile( size, size, default_value )\n { }\n\n static inline auto get_nothing_functor_on_arris_resize()\n { return []( const auto&, auto& ){ }; }\n \n auto cols_size() const { return this->front().size(); }\n auto rows_size() const { return rows_type::size(); }\n \n auto size() const { return cols_size() * rows_size(); }\n\n auto resize_rows( const std::size_t size, const T& default_value = T() )\n {\n on_rows_resize_before( *this, size );\n \n throw_if_zero( size, \"the new rows size is 0; circular_tile cannot use 0 size rows.\" );\n rows_type::resize( size, make_cols( default_value ) );\n \n on_rows_resize_after( *this, size );\n }\n \n auto resize_cols( const std::size_t size, const T& default_value = T() )\n {\n on_cols_resize_before( *this, size );\n \n throw_if_zero( size, \"the new cols size is 0; circular_tile cannot use 0 size cols.\" );\n for ( auto i = rows_type::begin(), e = rows_type::end(); i != e; ++i )\n i->resize( size, default_value );\n \n on_cols_resize_after( *this, size );\n }\n\n auto resize( const std::size_t cols_size, const std::size_t rows_size, const T& default_value = T() )\n {\n resize_rows( rows_size, default_value );\n resize_cols( cols_size, default_value );\n }\n\n auto resize ( const std::size_t size, const T& default_value = T() )\n { resize( size, size, default_value ); }\n\n auto begin() const -> decltype( rows_type::begin() ) { return rows_type::begin(); }\n auto end() const -> decltype( rows_type::end() ){ return rows_type::end(); }\n \n auto get_center_index_x()\n { return cols_size() >> 1; }\n\n auto get_center_index_y()\n { return rows_size() >> 1; }\n\n auto get_center_indices()\n { return indices_2d{ get_center_index_x(), get_center_index_y() }; }\n\n template < typename INDEX_TYPE >\n decltype(auto) operator()( const INDEX_TYPE col, const INDEX_TYPE row )\n { return (*this)[ math::circular_modulus( row, rows_size() ) ][ math::circular_modulus( col, cols_size() ) ]; }\n\n template < typename INDICES_TYPE >\n decltype(auto) operator()( const INDICES_TYPE& indices )\n { return operator()( indices.x, indices.y ); }\n\n template < typename INDEX_TYPE >\n decltype(auto) from_center( const INDEX_TYPE delta_col, const INDEX_TYPE delta_row )\n { return operator()( get_center_index_x() + delta_col, get_center_index_y() + delta_row ); }\n\n template < typename INDICES_TYPE >\n decltype(auto) from_center( const INDICES_TYPE& delta_indices )\n { return operator()( get_center_index_x() + delta_indices.x, get_center_index_y() + delta_indices.y() ); }\n\n auto operate_cols( const operate_cols_functor_type& f )\n {\n for ( auto i = rows_type::begin(), e = rows_type::end(); i != e; ++i )\n f( *i );\n }\n\n auto apply( const apply_functor_type& f )\n {\n for ( auto ir = rows_type::begin(), er = rows_type::end(); ir != er; ++ir )\n for ( auto ic = ir->begin(), ec = ir->end(); ic != ec; ++ic )\n f( *ic );\n }\n\n auto shift_to_right( const T& default_value = T() )\n { operate_cols( [&]( auto& c ){ c.push_back( default_value ); } ); }\n \n auto shift_to_left( const T& default_value = T() )\n { operate_cols( [&]( auto& c ){ c.push_front( default_value ); } ); }\n \n auto shift_to_top( const T& default_value = T() )\n { rows_type::push_front( make_cols( default_value ) ); }\n \n auto shift_to_bottom( const T& default_value = T() )\n { rows_type::push_back( make_cols( default_value ) ); }\n\n auto throw_if_ne_rows_size( const std::size_t size )\n {\n if ( size != rows_size() )\n throw std::runtime_error( \"size != rows_size()\" );\n }\n \n auto throw_if_ne_cols_size( const std::size_t size )\n {\n if ( size != cols_size() )\n throw std::runtime_error( \"size != cols_size()\" );\n }\n\n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_right( const DATA_TYPE& data )\n {\n throw_if_ne_rows_size( data.size() );\n \n auto i = data.begin();\n operate_cols( [&]( auto& c ){ c.push_back( *i++ ); } );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_left( const DATA_TYPE& data )\n {\n throw_if_ne_rows_size( data.size() );\n \n auto i = data.begin();\n operate_cols( [&]( auto& c ){ c.push_front( *i++ ); } );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_top( const DATA_TYPE& data )\n {\n throw_if_ne_cols_size( data.size() );\n\n rows_type::push_front( make_cols( data ) );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_bottom( const DATA_TYPE& data )\n {\n throw_if_ne_cols_size( data.size() );\n\n rows_type::push_back( make_cols( data ) );\n }\n };\n\n template < typename T >\n static decltype(auto) operator<<( std::ostream& o , const circular_tile& tiles )\n {\n for ( const auto& cols : tiles )\n {\n for ( const auto& value : cols )\n o << value << \" \";\n o << \"\\n\";\n }\n\n return o;\n }\n }\n}\nGCCがautoを解決できずに翻訳できない問題に対応#pragma once\n\n#include \"indices_2d.hxx\"\n#include \"..\/math\/circular_modulus.hxx\"\n\n#include \n#include \n#include \n\nnamespace usagi\n{\n namespace container\n {\n template\n < typename T >\n class circular_tile\n : boost::circular_buffer< boost::circular_buffer< T > >\n {\n public:\n using type = circular_tile;\n \n using cols_type = boost::circular_buffer< T >;\n using rows_type = boost::circular_buffer< cols_type >;\n \n using operate_cols_functor_signature = auto ( cols_type& ) -> void;\n using operate_cols_functor_type = std::function< operate_cols_functor_signature >;\n \n using apply_functor_signature = auto ( T& ) -> void;\n using apply_functor_type = std::function< apply_functor_signature >;\n \n using on_arris_resize_functor_signature = auto ( const type& ref, std::size_t new_size ) -> void;\n using on_arris_resize_functor_type = std::function< on_arris_resize_functor_signature >;\n\n protected:\n\n inline static auto make_cols( const std::size_t size, const T& default_value = T() )\n { return cols_type( size, default_value ); }\n\n auto make_cols( const T& default_value = T() )\n { return make_cols( rows_type::front().size(), default_value ); }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto make_cols( const DATA_TYPE& data )\n {\n cols_type cols( rows_type::front().size() );\n for ( const auto& datum : data )\n cols.push_back( datum );\n return cols;\n }\n\n template < typename VALUE_TYPE, typename MESSAGE_TYPE >\n inline static auto throw_if_zero( const VALUE_TYPE value, const MESSAGE_TYPE& message )\n {\n if ( value == 0 )\n throw std::logic_error( message );\n }\n\n public:\n\n on_arris_resize_functor_type on_cols_resize_before;\n on_arris_resize_functor_type on_cols_resize_after;\n \n on_arris_resize_functor_type on_rows_resize_before;\n on_arris_resize_functor_type on_rows_resize_after;\n\n circular_tile( const std::size_t cols_size, const std::size_t rows_size, const T& default_value = T() )\n : rows_type( rows_size, make_cols( cols_size, default_value ) )\n , on_cols_resize_before( get_nothing_functor_on_arris_resize() )\n , on_cols_resize_after ( get_nothing_functor_on_arris_resize() )\n , on_rows_resize_before( get_nothing_functor_on_arris_resize() )\n , on_rows_resize_after ( get_nothing_functor_on_arris_resize() )\n {\n throw_if_zero( cols_size, \"cols_size == 0\" );\n throw_if_zero( rows_size, \"rows_size == 0\" );\n }\n\n circular_tile( const std::size_t size, const T& default_value = T() )\n : circular_tile( size, size, default_value )\n { }\n\n static inline auto get_nothing_functor_on_arris_resize()\n { return []( const type&, std::size_t ){ }; }\n \n auto cols_size() const { return this->front().size(); }\n auto rows_size() const { return rows_type::size(); }\n \n auto size() const { return cols_size() * rows_size(); }\n\n auto resize_rows( const std::size_t size, const T& default_value = T() )\n {\n on_rows_resize_before( *this, size );\n \n throw_if_zero( size, \"the new rows size is 0; circular_tile cannot use 0 size rows.\" );\n rows_type::resize( size, make_cols( default_value ) );\n \n on_rows_resize_after( *this, size );\n }\n \n auto resize_cols( const std::size_t size, const T& default_value = T() )\n {\n on_cols_resize_before( *this, size );\n \n throw_if_zero( size, \"the new cols size is 0; circular_tile cannot use 0 size cols.\" );\n for ( auto i = rows_type::begin(), e = rows_type::end(); i != e; ++i )\n i->resize( size, default_value );\n \n on_cols_resize_after( *this, size );\n }\n\n auto resize( const std::size_t cols_size, const std::size_t rows_size, const T& default_value = T() )\n {\n resize_rows( rows_size, default_value );\n resize_cols( cols_size, default_value );\n }\n\n auto resize ( const std::size_t size, const T& default_value = T() )\n { resize( size, size, default_value ); }\n\n auto begin() const -> decltype( rows_type::begin() ) { return rows_type::begin(); }\n auto end() const -> decltype( rows_type::end() ){ return rows_type::end(); }\n \n auto get_center_index_x()\n { return cols_size() >> 1; }\n\n auto get_center_index_y()\n { return rows_size() >> 1; }\n\n auto get_center_indices()\n { return indices_2d{ get_center_index_x(), get_center_index_y() }; }\n\n template < typename INDEX_TYPE >\n decltype(auto) operator()( const INDEX_TYPE col, const INDEX_TYPE row )\n { return (*this)[ math::circular_modulus( row, rows_size() ) ][ math::circular_modulus( col, cols_size() ) ]; }\n\n template < typename INDICES_TYPE >\n decltype(auto) operator()( const INDICES_TYPE& indices )\n { return operator()( indices.x, indices.y ); }\n\n template < typename INDEX_TYPE >\n decltype(auto) from_center( const INDEX_TYPE delta_col, const INDEX_TYPE delta_row )\n { return operator()( get_center_index_x() + delta_col, get_center_index_y() + delta_row ); }\n\n template < typename INDICES_TYPE >\n decltype(auto) from_center( const INDICES_TYPE& delta_indices )\n { return operator()( get_center_index_x() + delta_indices.x, get_center_index_y() + delta_indices.y() ); }\n\n auto operate_cols( const operate_cols_functor_type& f )\n {\n for ( auto i = rows_type::begin(), e = rows_type::end(); i != e; ++i )\n f( *i );\n }\n\n auto apply( const apply_functor_type& f )\n {\n for ( auto ir = rows_type::begin(), er = rows_type::end(); ir != er; ++ir )\n for ( auto ic = ir->begin(), ec = ir->end(); ic != ec; ++ic )\n f( *ic );\n }\n\n auto shift_to_right( const T& default_value = T() )\n { operate_cols( [&]( auto& c ){ c.push_back( default_value ); } ); }\n \n auto shift_to_left( const T& default_value = T() )\n { operate_cols( [&]( auto& c ){ c.push_front( default_value ); } ); }\n \n auto shift_to_top( const T& default_value = T() )\n { rows_type::push_front( make_cols( default_value ) ); }\n \n auto shift_to_bottom( const T& default_value = T() )\n { rows_type::push_back( make_cols( default_value ) ); }\n\n auto throw_if_ne_rows_size( const std::size_t size )\n {\n if ( size != rows_size() )\n throw std::runtime_error( \"size != rows_size()\" );\n }\n \n auto throw_if_ne_cols_size( const std::size_t size )\n {\n if ( size != cols_size() )\n throw std::runtime_error( \"size != cols_size()\" );\n }\n\n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_right( const DATA_TYPE& data )\n {\n throw_if_ne_rows_size( data.size() );\n \n auto i = data.begin();\n operate_cols( [&]( auto& c ){ c.push_back( *i++ ); } );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_left( const DATA_TYPE& data )\n {\n throw_if_ne_rows_size( data.size() );\n \n auto i = data.begin();\n operate_cols( [&]( auto& c ){ c.push_front( *i++ ); } );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_top( const DATA_TYPE& data )\n {\n throw_if_ne_cols_size( data.size() );\n\n rows_type::push_front( make_cols( data ) );\n }\n \n template < typename DATA_TYPE = std::initializer_list >\n auto shift_to_bottom( const DATA_TYPE& data )\n {\n throw_if_ne_cols_size( data.size() );\n\n rows_type::push_back( make_cols( data ) );\n }\n };\n\n template < typename T >\n static decltype(auto) operator<<( std::ostream& o , const circular_tile& tiles )\n {\n for ( const auto& cols : tiles )\n {\n for ( const auto& value : cols )\n o << value << \" \";\n o << \"\\n\";\n }\n\n return o;\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#pragma once\n\n#ifndef VSNRAY_DETAIL_PATHTRACING_INL\n#define VSNRAY_DETAIL_PATHTRACING_INL 1\n\n#include \n#include \n#include \n#include \n\nnamespace visionaray\n{\nnamespace pathtracing\n{\n\ntemplate \nstruct kernel\n{\n\n Params params;\n\n template \n VSNRAY_FUNC result_record operator()(\n Intersector& isect,\n R ray,\n Generator& gen\n ) const\n {\n using S = typename R::scalar_type;\n using I = simd::int_type_t;\n using V = typename result_record::vec_type;\n using C = spectrum;\n\n simd::mask_type_t active_rays = true;\n\n C dst(1.0);\n\n result_record result;\n result.color = params.bg_color;\n\n for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce)\n {\n auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);\n\n \/\/ Handle rays that just exited\n auto exited = active_rays & !hit_rec.hit;\n dst = mul( dst, C(from_rgba(params.ambient_color)), exited, dst );\n\n\n \/\/ Exit if no ray is active anymore\n active_rays &= hit_rec.hit;\n\n if (!any(active_rays))\n {\n break;\n }\n\n \/\/ Special handling for first bounce\n if (bounce == 0)\n {\n result.hit = hit_rec.hit;\n result.isect_pos = ray.ori + ray.dir * hit_rec.t;\n }\n\n\n \/\/ Process the current bounce\n\n V refl_dir;\n V view_dir = -ray.dir;\n\n hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;\n\n auto surf = get_surface(hit_rec, params);\n\n S pdf(0.0);\n I inter = 0;\n\n auto src = surf.sample(view_dir, refl_dir, pdf, inter, gen);\n\n auto zero_pdf = pdf <= S(0.0);\n\n dst = mul( dst, src, active_rays && !zero_pdf, dst );\n dst = select( zero_pdf && active_rays, C(0.0), dst );\n\n active_rays &= inter != I(surface_interaction::Emission);\n active_rays &= !zero_pdf;\n\n\n if (!any(active_rays))\n {\n break;\n }\n\n ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon);\n ray.dir = refl_dir;\n }\n\n \/\/ Terminate paths that are still active\n dst = select(active_rays, C(0.0), dst);\n\n result.color = select( result.hit, to_rgba(dst), result.color );\n\n return result;\n }\n\n template \n VSNRAY_FUNC result_record operator()(\n R ray,\n Generator& gen\n ) const\n {\n default_intersector ignore;\n return (*this)(ignore, ray, gen);\n }\n};\n\n} \/\/ pathtracing\n} \/\/ visionaray\n\n#endif \/\/ VSNRAY_DETAIL_PATHTRACING_INL\nUnnecessary cast\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#pragma once\n\n#ifndef VSNRAY_DETAIL_PATHTRACING_INL\n#define VSNRAY_DETAIL_PATHTRACING_INL 1\n\n#include \n#include \n#include \n#include \n\nnamespace visionaray\n{\nnamespace pathtracing\n{\n\ntemplate \nstruct kernel\n{\n\n Params params;\n\n template \n VSNRAY_FUNC result_record operator()(\n Intersector& isect,\n R ray,\n Generator& gen\n ) const\n {\n using S = typename R::scalar_type;\n using I = simd::int_type_t;\n using V = typename result_record::vec_type;\n using C = spectrum;\n\n simd::mask_type_t active_rays = true;\n\n C dst(1.0);\n\n result_record result;\n result.color = params.bg_color;\n\n for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce)\n {\n auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect);\n\n \/\/ Handle rays that just exited\n auto exited = active_rays & !hit_rec.hit;\n dst = mul( dst, C(from_rgba(params.ambient_color)), exited, dst );\n\n\n \/\/ Exit if no ray is active anymore\n active_rays &= hit_rec.hit;\n\n if (!any(active_rays))\n {\n break;\n }\n\n \/\/ Special handling for first bounce\n if (bounce == 0)\n {\n result.hit = hit_rec.hit;\n result.isect_pos = ray.ori + ray.dir * hit_rec.t;\n }\n\n\n \/\/ Process the current bounce\n\n V refl_dir;\n V view_dir = -ray.dir;\n\n hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t;\n\n auto surf = get_surface(hit_rec, params);\n\n S pdf(0.0);\n I inter = 0;\n\n auto src = surf.sample(view_dir, refl_dir, pdf, inter, gen);\n\n auto zero_pdf = pdf <= S(0.0);\n\n dst = mul( dst, src, active_rays && !zero_pdf, dst );\n dst = select( zero_pdf && active_rays, C(0.0), dst );\n\n active_rays &= inter != surface_interaction::Emission;\n active_rays &= !zero_pdf;\n\n\n if (!any(active_rays))\n {\n break;\n }\n\n ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon);\n ray.dir = refl_dir;\n }\n\n \/\/ Terminate paths that are still active\n dst = select(active_rays, C(0.0), dst);\n\n result.color = select( result.hit, to_rgba(dst), result.color );\n\n return result;\n }\n\n template \n VSNRAY_FUNC result_record operator()(\n R ray,\n Generator& gen\n ) const\n {\n default_intersector ignore;\n return (*this)(ignore, ray, gen);\n }\n};\n\n} \/\/ pathtracing\n} \/\/ visionaray\n\n#endif \/\/ VSNRAY_DETAIL_PATHTRACING_INL\n<|endoftext|>"} {"text":"\/\/-------------------------------------------------------------------\n\/\/ MetaInfo Framework (MIF)\n\/\/ https:\/\/github.com\/tdv\/mif\n\/\/ Created: 11.2020\n\/\/ Copyright (C) 2016-2020 tdv\n\/\/-------------------------------------------------------------------\n\n\/\/ STD\n#include \n#include \n\n\/\/ BOOST\n#include \n#include \n\n\/\/ MIF\n#include \"mif\/common\/log.h\"\n#include \"mif\/common\/unused.h\"\n#include \"mif\/net\/http\/constants.h\"\n\n\/\/ THIS\n#include \"input_pack.h\"\n#include \"output_pack.h\"\n#include \"session.h\"\n#include \"utility.h\"\n\nnamespace Mif\n{\n namespace Net\n {\n namespace Http\n {\n namespace Detail\n {\n\n class Session::Queue final\n {\n public:\n Queue(Session &session, std::size_t limit)\n : m_session{session}\n , m_limit{limit}\n {\n }\n\n bool IsFull() const noexcept\n {\n return m_tasks.size() >= m_limit;\n }\n\n template \n using Response = boost::beast::http::response;\n\n template \n void Post(Response &&response)\n {\n auto resp = std::make_shared>(std::move(response));\n\n auto task = [this, resp]\n {\n boost::beast::http::async_write(m_session.m_stream, *resp,\n boost::beast::bind_front_handler(&Session::OnWrite,\n m_session.shared_from_this(), resp->need_eof()));\n };\n\n m_tasks.emplace_back(std::move(task));\n\n if (m_tasks.size() == 1)\n m_tasks.front()();\n }\n\n bool Pop()\n {\n if (m_tasks.empty())\n {\n throw std::runtime_error{\"[Mif::Net::Http::Detail::Session::Queue::Pop] \"\n \"Empty queue.\"};\n }\n\n auto const wasFull = IsFull();\n\n m_tasks.pop_front();\n\n if (!m_tasks.empty())\n m_tasks.front()();\n\n return wasFull;\n }\n\n private:\n Session &m_session;\n std::size_t const m_limit;\n\n std::deque> m_tasks;\n };\n\n Session::Session(boost::asio::ip::tcp::socket &&socket, Params const ¶ms)\n : m_stream{std::move(socket)}\n , m_params{params}\n , m_queue{boost::make_unique(*this,\n std::max(m_params.pipelineLimit, 1))\n }\n {\n }\n\n Session::~Session()\n {\n }\n\n void Session::Run()\n {\n boost::asio::dispatch(m_stream.get_executor(),\n boost::beast::bind_front_handler(&Session::Read,\n shared_from_this())\n );\n }\n\n void Session::Read()\n {\n m_parser.emplace();\n\n m_parser->header_limit(m_params.headersSize);\n m_parser->body_limit(m_params.bodySize);\n m_stream.expires_after(m_params.requestTimeout);\n\n boost::beast::http::async_read(m_stream, m_buffer, *m_parser,\n boost::beast::bind_front_handler(&Session::OnRead,\n shared_from_this())\n );\n }\n\n void Session::OnRead(boost::beast::error_code ec, std::size_t bytes)\n {\n Common::Unused(bytes);\n\n if (ec == boost::beast::http::error::end_of_stream)\n {\n Close();\n return;\n }\n\n if (ec)\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::OnRead] \"\n << \"Failed to read data. Error: \" << ec.message();\n\n return;\n }\n\n if (boost::beast::websocket::is_upgrade(m_parser->get()))\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::OnRead] \"\n << \"Failed to upgrade for starting websocket. Error: it has not implemented yet.\";\n\n Close();\n return;\n }\n\n HandleRequest(m_parser->release());\n \/\/ TODO:\n }\n\n void Session::OnWrite(bool close, boost::beast::error_code ec, std::size_t bytes)\n {\n Common::Unused(bytes);\n\n if (ec)\n {\n MIF_LOG(Info) << \"[Mif::Net::Http::Detail::Session::OnWrite] \"\n << \"Failed to write data. Error: \" << ec.message();\n\n return;\n }\n\n if (close)\n {\n Close();\n return;\n }\n\n if (m_queue->Pop())\n Read();\n }\n\n void Session::Close()\n {\n boost::beast::error_code ec;\n m_stream.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);\n\n if (ec)\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::Close] \"\n << \"Failed to close socket. Error: \" << ec.message();\n }\n }\n\n template \n void Session::HandleRequest(Request &&request)\n {\n try\n {\n auto const &path = request.target();\n\n if (path.empty() || path[0] != '\/' ||\n path.find(\"..\") != boost::beast::string_view::npos)\n {\n ReplyError(boost::beast::http::status::bad_request, \"Bad path.\", request.keep_alive());\n return;\n }\n\n if (m_params.allowedMethods.find(\n Utility::ConvertMethodType(request.method())) ==\n std::end(m_params.allowedMethods))\n {\n ReplyError(boost::beast::http::status::method_not_allowed, \"The method is not allowed.\",\n request.keep_alive());\n return;\n }\n\n if (m_params.handlers.empty())\n {\n ReplyError(boost::beast::http::status::method_not_allowed,\n \"There is no any method for handling the request.\",\n request.keep_alive());\n\n return;\n }\n\n Response response;\n\n std::shared_ptr in = std::make_shared>>(request);\n auto out = std::make_shared>(response);\n\n auto process = [this, &in, &out] (std::string const &path)\n {\n auto iter = m_params.handlers.find(path);\n if (iter != std::end(m_params.handlers))\n {\n iter->second(*in, *out);\n return true;\n }\n return false;\n };\n\n auto handled = false;\n std::string url{in->GetPath()};\n\n if (process(url))\n handled = true;\n else\n {\n if (!url.empty() && url.back() != '\/')\n url.append(\"\/\");\n\n for (auto pos = url.find_last_of('\/') ; pos != std::string::npos ; pos = url.find_last_of('\/'))\n {\n url = url.substr(0, pos);\n auto const path = url.empty() ? std::string{\"\/\"} : url;\n\n if (process(path))\n {\n handled = true;\n break;\n }\n }\n }\n\n if (!handled)\n {\n ReplyError(boost::beast::http::status::method_not_allowed,\n \"Handler for the request processing was not found.\",\n request.keep_alive());\n\n return;\n }\n\n Reply(std::move(response), request.keep_alive());\n }\n catch (std::exception const &e)\n {\n MIF_LOG(Error) << \"[Mif::Net::Http::Detail::Session::HandleRequest] \"\n << \"Failed to process request. Error: \" << e.what();\n\n ReplyError(boost::beast::http::status::internal_server_error, \"An internal error has occurred.\",\n request.keep_alive());\n }\n }\n\n void Session::ReplyError(boost::beast::http::status status, std::string const &reason,\n bool isKeepAlive)\n {\n boost::beast::http::response response;\n\n response.result(status);\n \/\/response.set(boost::beast::http::field::server, \"Mif\");\n response.set(boost::beast::http::field::content_type, \"text\/plain\");\n response.set(boost::beast::http::field::date, Utility::CreateTimestamp());\n response.keep_alive(isKeepAlive);\n response.version(11);\n response.body() = std::string(reason);\n\n response.prepare_payload();\n\n m_queue->Post(std::move(response));\n }\n\n void Session::Reply(Response &&response, bool isKeepAlive)\n {\n response.result(boost::beast::http::status::ok);\n \/\/response.set(boost::beast::http::field::server, \"Mif\");\n response.set(boost::beast::http::field::date, Utility::CreateTimestamp());\n response.version(11);\n response.keep_alive(isKeepAlive);\n\n response.prepare_payload();\n\n m_queue->Post(std::move(response));\n }\n\n } \/\/ namespace Detail\n } \/\/ namespace Http\n } \/\/ namespace Net\n} \/\/ namespace Mif\nHttp server session has fixed.\/\/-------------------------------------------------------------------\n\/\/ MetaInfo Framework (MIF)\n\/\/ https:\/\/github.com\/tdv\/mif\n\/\/ Created: 11.2020\n\/\/ Copyright (C) 2016-2020 tdv\n\/\/-------------------------------------------------------------------\n\n\/\/ STD\n#include \n#include \n\n\/\/ BOOST\n#include \n#include \n\n\/\/ MIF\n#include \"mif\/common\/log.h\"\n#include \"mif\/common\/unused.h\"\n#include \"mif\/net\/http\/constants.h\"\n\n\/\/ THIS\n#include \"input_pack.h\"\n#include \"output_pack.h\"\n#include \"session.h\"\n#include \"utility.h\"\n\nnamespace Mif\n{\n namespace Net\n {\n namespace Http\n {\n namespace Detail\n {\n\n class Session::Queue final\n {\n public:\n Queue(Session &session, std::size_t limit)\n : m_session{session}\n , m_limit{limit}\n {\n }\n\n bool IsFull() const noexcept\n {\n return m_tasks.size() >= m_limit;\n }\n\n template \n using Response = boost::beast::http::response;\n\n template \n void Post(Response &&response)\n {\n auto resp = std::make_shared>(std::move(response));\n\n auto task = [this, resp]\n {\n boost::beast::http::async_write(m_session.m_stream, *resp,\n boost::beast::bind_front_handler(&Session::OnWrite,\n m_session.shared_from_this(), resp->need_eof()));\n };\n\n m_tasks.emplace_back(std::move(task));\n\n if (m_tasks.size() == 1)\n m_tasks.front()();\n }\n\n bool Pop()\n {\n if (m_tasks.empty())\n {\n throw std::runtime_error{\"[Mif::Net::Http::Detail::Session::Queue::Pop] \"\n \"Empty queue.\"};\n }\n\n auto const wasFull = IsFull();\n\n m_tasks.pop_front();\n\n if (!m_tasks.empty())\n m_tasks.front()();\n\n return wasFull;\n }\n\n private:\n Session &m_session;\n std::size_t const m_limit;\n\n std::deque> m_tasks;\n };\n\n Session::Session(boost::asio::ip::tcp::socket &&socket, Params const ¶ms)\n : m_stream{std::move(socket)}\n , m_params{params}\n , m_queue{boost::make_unique(*this,\n std::max(m_params.pipelineLimit, 1))\n }\n {\n }\n\n Session::~Session()\n {\n }\n\n void Session::Run()\n {\n boost::asio::dispatch(m_stream.get_executor(),\n boost::beast::bind_front_handler(&Session::Read,\n shared_from_this())\n );\n }\n\n void Session::Read()\n {\n m_parser.emplace();\n\n m_parser->header_limit(m_params.headersSize);\n m_parser->body_limit(m_params.bodySize);\n m_stream.expires_after(m_params.requestTimeout);\n\n boost::beast::http::async_read(m_stream, m_buffer, *m_parser,\n boost::beast::bind_front_handler(&Session::OnRead,\n shared_from_this())\n );\n }\n\n void Session::OnRead(boost::beast::error_code ec, std::size_t bytes)\n {\n Common::Unused(bytes);\n\n if (ec == boost::beast::http::error::end_of_stream)\n {\n Close();\n return;\n }\n\n if (ec)\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::OnRead] \"\n << \"Failed to read data. Error: \" << ec.message();\n\n return;\n }\n\n if (boost::beast::websocket::is_upgrade(m_parser->get()))\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::OnRead] \"\n << \"Failed to upgrade for starting websocket. Error: it has not implemented yet.\";\n\n Close();\n return;\n }\n\n HandleRequest(m_parser->release());\n \/\/ TODO:\n }\n\n void Session::OnWrite(bool close, boost::beast::error_code ec, std::size_t bytes)\n {\n Common::Unused(bytes);\n\n if (ec)\n {\n MIF_LOG(Info) << \"[Mif::Net::Http::Detail::Session::OnWrite] \"\n << \"Failed to write data. Error: \" << ec.message();\n\n return;\n }\n\n if (close)\n {\n Close();\n return;\n }\n\n if (m_queue->Pop())\n Read();\n }\n\n void Session::Close()\n {\n boost::beast::error_code ec;\n m_stream.socket().shutdown(boost::asio::ip::tcp::socket::shutdown_send, ec);\n\n if (ec)\n {\n MIF_LOG(Warning) << \"[Mif::Net::Http::Detail::Session::Close] \"\n << \"Failed to close socket. Error: \" << ec.message();\n }\n }\n\n template \n void Session::HandleRequest(Request &&request)\n {\n try\n {\n auto const &path = request.target();\n\n if (path.empty() || path[0] != '\/' ||\n path.find(\"..\") != boost::beast::string_view::npos)\n {\n ReplyError(boost::beast::http::status::bad_request, \"Bad path.\", request.keep_alive());\n return;\n }\n\n if (m_params.allowedMethods.find(\n Utility::ConvertMethodType(request.method())) ==\n std::end(m_params.allowedMethods))\n {\n ReplyError(boost::beast::http::status::method_not_allowed, \"The method is not allowed.\",\n request.keep_alive());\n return;\n }\n\n if (m_params.handlers.empty())\n {\n ReplyError(boost::beast::http::status::method_not_allowed,\n \"There is no any method for handling the request.\",\n request.keep_alive());\n\n return;\n }\n\n Response response;\n\n std::shared_ptr in = std::make_shared>>(request);\n auto out = std::make_shared>(response);\n\n auto process = [this, &in, &out] (std::string const &path)\n {\n auto iter = m_params.handlers.find(path);\n if (iter != std::end(m_params.handlers))\n {\n iter->second(*in, *out);\n return true;\n }\n return false;\n };\n\n auto handled = false;\n std::string url{in->GetPath()};\n\n if (process(url))\n handled = true;\n else\n {\n if (!url.empty() && url.back() != '\/')\n url.append(\"\/\");\n\n for (auto pos = url.find_last_of('\/') ; pos != std::string::npos ; pos = url.find_last_of('\/'))\n {\n url = url.substr(0, pos);\n auto const path = url.empty() ? std::string{\"\/\"} : url;\n\n if (process(path))\n {\n handled = true;\n break;\n }\n }\n }\n\n if (!handled)\n {\n ReplyError(boost::beast::http::status::method_not_allowed,\n \"Handler for the request processing was not found.\",\n request.keep_alive());\n\n return;\n }\n\n Reply(std::move(response), request.keep_alive());\n }\n catch (std::exception const &e)\n {\n MIF_LOG(Error) << \"[Mif::Net::Http::Detail::Session::HandleRequest] \"\n << \"Failed to process request. Error: \" << e.what();\n\n ReplyError(boost::beast::http::status::internal_server_error, \"An internal error has occurred.\",\n request.keep_alive());\n }\n }\n\n void Session::ReplyError(boost::beast::http::status status, std::string const &reason,\n bool isKeepAlive)\n {\n boost::beast::http::response response;\n\n response.result(status);\n \/\/response.set(boost::beast::http::field::server, \"Mif\");\n response.set(boost::beast::http::field::content_type, \"text\/plain\");\n response.set(boost::beast::http::field::date, Utility::CreateTimestamp());\n response.keep_alive(isKeepAlive);\n response.version(11);\n response.body() = std::string(reason);\n\n response.prepare_payload();\n\n m_queue->Post(std::move(response));\n }\n\n void Session::Reply(Response &&response, bool isKeepAlive)\n {\n \/\/response.result(boost::beast::http::status::ok);\n \/\/response.set(boost::beast::http::field::server, \"Mif\");\n response.set(boost::beast::http::field::date, Utility::CreateTimestamp());\n response.version(11);\n response.keep_alive(isKeepAlive);\n\n response.prepare_payload();\n\n m_queue->Post(std::move(response));\n }\n\n } \/\/ namespace Detail\n } \/\/ namespace Http\n } \/\/ namespace Net\n} \/\/ namespace Mif\n<|endoftext|>"} {"text":"\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file gmm_main.cpp\n *\n * This program trains a mixture of Gaussians on a given data matrix.\n *\/\n#include \"gmm.hpp\"\n\nPROGRAM_INFO(\"Gaussian Mixture Model (GMM) Training\",\n \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n \" using the EM algorithm to find the maximum likelihood estimate. The \"\n \"model is saved to an XML file, which contains information about each \"\n \"Gaussian.\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing the data on which the model \"\n \"will be fit.\", \"i\");\nPARAM_INT(\"gaussians\", \"Number of Gaussians in the GMM.\", \"g\", 1);\nPARAM_STRING(\"output_file\", \"The file to write the trained GMM parameters into \"\n \"(as XML).\", \"o\", \"gmm.xml\");\nPARAM_INT(\"seed\", \"Random seed. If 0, 'std::time(NULL)' is used.\", \"s\", 0);\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\nusing namespace mlpack::util;\n\nint main(int argc, char* argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check parameters and load data.\n if (CLI::GetParam(\"seed\") != 0)\n math::RandomSeed((size_t) CLI::GetParam(\"seed\"));\n else\n math::RandomSeed((size_t) std::time(NULL));\n\n arma::mat dataPoints;\n data::Load(CLI::GetParam(\"input_file\").c_str(), dataPoints,\n true);\n\n int gaussians = CLI::GetParam(\"gaussians\");\n if (gaussians <= 0)\n {\n Log::Fatal << \"Invalid number of Gaussians (\" << gaussians << \"); must \"\n \"be greater than or equal to 1.\" << std::endl;\n }\n\n \/\/ Calculate mixture of Gaussians.\n GMM<> gmm(size_t(gaussians), dataPoints.n_rows);\n\n \/\/\/\/\/\/ Computing the parameters of the model using the EM algorithm \/\/\/\/\/\/\n Timer::Start(\"em\");\n double likelihood = gmm.Estimate(dataPoints);\n Timer::Stop(\"em\");\n\n Log::Info << \"Log-likelihood of estimate: \" << likelihood << \".\\n\";\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n SaveRestoreUtility save;\n save.SaveParameter(gmm.Gaussians(), \"gaussians\");\n save.SaveParameter(gmm.Dimensionality(), \"dimensionality\");\n save.SaveParameter(trans(gmm.Weights()), \"weights\");\n for (size_t i = 0; i < gmm.Gaussians(); ++i)\n {\n \/\/ Generate names for the XML nodes.\n std::stringstream o;\n o << i;\n std::string meanName = \"mean\" + o.str();\n std::string covName = \"covariance\" + o.str();\n\n \/\/ Now save them.\n save.SaveParameter(trans(gmm.Means()[i]), meanName);\n save.SaveParameter(gmm.Covariances()[i], covName);\n }\n\n save.WriteFile(CLI::GetParam(\"output_file\").c_str());\n}\nSuperfluous c_str().\/**\n * @author Parikshit Ram (pram@cc.gatech.edu)\n * @file gmm_main.cpp\n *\n * This program trains a mixture of Gaussians on a given data matrix.\n *\/\n#include \"gmm.hpp\"\n\nPROGRAM_INFO(\"Gaussian Mixture Model (GMM) Training\",\n \"This program takes a parametric estimate of a Gaussian mixture model (GMM)\"\n \" using the EM algorithm to find the maximum likelihood estimate. The \"\n \"model is saved to an XML file, which contains information about each \"\n \"Gaussian.\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing the data on which the model \"\n \"will be fit.\", \"i\");\nPARAM_INT(\"gaussians\", \"Number of Gaussians in the GMM.\", \"g\", 1);\nPARAM_STRING(\"output_file\", \"The file to write the trained GMM parameters into \"\n \"(as XML).\", \"o\", \"gmm.xml\");\nPARAM_INT(\"seed\", \"Random seed. If 0, 'std::time(NULL)' is used.\", \"s\", 0);\n\nusing namespace mlpack;\nusing namespace mlpack::gmm;\nusing namespace mlpack::util;\n\nint main(int argc, char* argv[])\n{\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Check parameters and load data.\n if (CLI::GetParam(\"seed\") != 0)\n math::RandomSeed((size_t) CLI::GetParam(\"seed\"));\n else\n math::RandomSeed((size_t) std::time(NULL));\n\n arma::mat dataPoints;\n data::Load(CLI::GetParam(\"input_file\").c_str(), dataPoints,\n true);\n\n int gaussians = CLI::GetParam(\"gaussians\");\n if (gaussians <= 0)\n {\n Log::Fatal << \"Invalid number of Gaussians (\" << gaussians << \"); must \"\n \"be greater than or equal to 1.\" << std::endl;\n }\n\n \/\/ Calculate mixture of Gaussians.\n GMM<> gmm(size_t(gaussians), dataPoints.n_rows);\n\n \/\/\/\/\/\/ Computing the parameters of the model using the EM algorithm \/\/\/\/\/\/\n Timer::Start(\"em\");\n double likelihood = gmm.Estimate(dataPoints);\n Timer::Stop(\"em\");\n\n Log::Info << \"Log-likelihood of estimate: \" << likelihood << \".\\n\";\n\n \/\/\/\/\/\/ OUTPUT RESULTS \/\/\/\/\/\/\n SaveRestoreUtility save;\n save.SaveParameter(gmm.Gaussians(), \"gaussians\");\n save.SaveParameter(gmm.Dimensionality(), \"dimensionality\");\n save.SaveParameter(trans(gmm.Weights()), \"weights\");\n for (size_t i = 0; i < gmm.Gaussians(); ++i)\n {\n \/\/ Generate names for the XML nodes.\n std::stringstream o;\n o << i;\n std::string meanName = \"mean\" + o.str();\n std::string covName = \"covariance\" + o.str();\n\n \/\/ Now save them.\n save.SaveParameter(trans(gmm.Means()[i]), meanName);\n save.SaveParameter(gmm.Covariances()[i], covName);\n }\n\n save.WriteFile(CLI::GetParam(\"output_file\"));\n}\n<|endoftext|>"} {"text":"#ifdef WIN32\n#define UNICODE\n#define _UNICODE\n\n#include \n\n#include \"win32bindings.h\"\n#include \"javasigar.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJNIEXPORT jint JNICALL SIGAR_JNI(win32_RegistryKey_RegCloseKey)\n(JNIEnv *, jclass, jlong hkey)\n{\n return RegCloseKey((HKEY)hkey);\n}\n\nJNIEXPORT jlong JNICALL SIGAR_JNI(win32_RegistryKey_RegCreateKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n HKEY hkeyResult = NULL;\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n \n RegCreateKeyEx((HKEY)hkey, lpSubkey, 0, NULL, \n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, \n NULL, &hkeyResult, NULL);\n\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n\n return (jlong)hkeyResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n LONG lResult = RegDeleteKey((HKEY)hkey, lpSubkey);\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n\n return lResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteValue)\n(JNIEnv *env, jclass, jlong hkey, jstring valueName)\n{\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n LONG lResult = RegDeleteValue((HKEY)hkey, lpValueName);\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n\n return lResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumKey)\n(JNIEnv *env, jclass, jlong hkey, jint index)\n{\n jstring strResult;\n TCHAR szBuffer[MAX_PATH + 1];\n\n if(RegEnumKey((HKEY)hkey, index, szBuffer, \n sizeof(szBuffer)) == ERROR_SUCCESS)\n strResult = env->NewString((const jchar *)szBuffer, \n lstrlen(szBuffer));\n else\n strResult = NULL;\n\n return strResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumValueName)\n(JNIEnv *env, jclass, jlong hkey, jint index)\n{\n jstring strResult;\n TCHAR szValueName[MAX_PATH + 1];\n DWORD cbValueName = sizeof(szValueName);\n\n if(RegEnumValue((HKEY)hkey, index, szValueName, \n &cbValueName, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)\n strResult = env->NewString((const jchar *)szValueName, \n lstrlen(szValueName));\n else\n strResult = NULL;\n\n return strResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegFlushKey)\n(JNIEnv *env, jclass, long hkey)\n{\n return RegFlushKey((HKEY)hkey);\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegLoadKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey, jstring file)\n{\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n LPCTSTR lpFile = (LPCTSTR)env->GetStringChars(file, NULL);\n\n LONG lResult = RegLoadKey((HKEY)hkey, lpSubkey, lpFile);\n\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n env->ReleaseStringChars(file, (const jchar *)lpFile);\n\n return lResult;\n}\n\nJNIEXPORT jlong SIGAR_JNI(win32_RegistryKey_RegOpenKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n HKEY hkeyResult = NULL;\n jsize len = env->GetStringLength(subkey);\n LPTSTR lpSubkey = (LPTSTR)env->GetStringChars(subkey, NULL);\n char orig = lpSubkey[len];\n \/* required under IBM\/WebSphere 4.0 for certain keys *\/\n lpSubkey[len] = '\\0';\n RegOpenKey((HKEY)hkey, lpSubkey, &hkeyResult);\n lpSubkey[len] = orig;\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n\n return (jlong)hkeyResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegQueryIntValue)\n(JNIEnv *env, jclass, jlong hkey, jstring valueName)\n{\n DWORD dwResult;\n DWORD dwType;\n LPBYTE lpValue;\n DWORD cbValue;\n\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n LONG lErr = RegQueryValueEx((HKEY)hkey, lpValueName, \n NULL, (LPDWORD)&dwType, \n NULL, &cbValue);\n \n if(lErr == ERROR_SUCCESS) {\n lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), \n HEAP_ZERO_MEMORY, cbValue);\n\n if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, \n NULL, lpValue, &cbValue) == ERROR_SUCCESS)\n {\n switch(dwType) {\n case REG_DWORD:\n dwResult = *(LPDWORD)lpValue;\n break;\n case REG_SZ:\n dwResult = _ttol((LPCTSTR)lpValue);\n break;\n default:\n lErr = ERROR_SUCCESS - 1; \/\/ Make an error\n }\n }\n\n HeapFree(GetProcessHeap(), 0, lpValue);\n }\n else\n \/\/ Make an error out of not seeing a REG_DWORD\n lErr = ERROR_SUCCESS - 1;\n\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n \n if(lErr != ERROR_SUCCESS)\n {\n jclass cls = \n env->FindClass(WIN32_PACKAGE \"Win32Exception\");\n env->ThrowNew(cls, NULL);\n }\n\n return dwResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegQueryStringValue)\n(JNIEnv *env, jclass, jlong hkey, jstring name)\n{\n jstring strResult;\n DWORD dwType;\n LPBYTE lpValue;\n DWORD cbValue;\n\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(name, NULL);\n LONG lErr = RegQueryValueEx((HKEY)hkey, \n lpValueName, NULL, \n (LPDWORD)&dwType, NULL, &cbValue);\n\n if(lErr == ERROR_SUCCESS)\n {\n lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), \n HEAP_ZERO_MEMORY, cbValue);\n\n if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, NULL, \n lpValue, &cbValue) == ERROR_SUCCESS)\n {\n switch(dwType) {\n case REG_DWORD:\n TCHAR szBuf[20];\n _ltot(*(LPDWORD)lpValue, szBuf, 10);\n strResult = env->NewString((const jchar *)szBuf, \n lstrlen(szBuf));\n break;\n case REG_SZ:\n case REG_EXPAND_SZ: {\n DWORD len;\n LPTSTR dest = NULL;\n len = ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, 0);\n dest = (LPTSTR)malloc(len * sizeof(TCHAR));\n ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, len);\n strResult = env->NewString((const jchar *)dest, len);\n free(dest);\n break;\n }\n default:\n lErr = ERROR_SUCCESS - 1; \/\/ Make an error\n }\n }\n\n HeapFree(GetProcessHeap(), 0, lpValue);\n }\n\n env->ReleaseStringChars(name, (const jchar *)lpValueName);\n \n if(lErr == ERROR_SUCCESS)\n return strResult;\n else\n {\n jclass cls = env->FindClass(WIN32_PACKAGE \"Win32Exception\");\n env->ThrowNew(cls, \"\");\n return NULL;\n }\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetIntValue)\n(JNIEnv * env, jclass, jlong hkey, jstring valueName, jint value)\n{\n LPCTSTR lpValueName;\n \n if(valueName != NULL)\n lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n else\n lpValueName = NULL;\n\n int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, \n REG_DWORD, (LPBYTE)&value, sizeof(value));\n\n if(valueName != NULL)\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n\n return iResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetStringValue)\n(JNIEnv *env, jclass, jlong hkey, jstring name, jstring value)\n{\n LPCTSTR lpValueName;\n\n if(name != NULL)\n lpValueName = (LPCTSTR)env->GetStringChars(name, NULL);\n else\n lpValueName = NULL;\n\n LPCTSTR lpValue = (LPCTSTR)env->GetStringChars(value, NULL);\n\n int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, \n REG_SZ, (LPBYTE)lpValue, \n (lstrlen(lpValue) + 1) * sizeof(TCHAR));\n \n if(name != NULL)\n env->ReleaseStringChars(name, (const jchar *)lpValueName);\n env->ReleaseStringChars(value, (const jchar *)lpValue);\n\n return iResult;\n}\n\n#ifdef __cplusplus\n}\n#endif\n#endif \/* WIN32 *\/\nbetter to make a copy than modify the const string#ifdef WIN32\n#define UNICODE\n#define _UNICODE\n\n#include \n\n#include \"win32bindings.h\"\n#include \"javasigar.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\nJNIEXPORT jint JNICALL SIGAR_JNI(win32_RegistryKey_RegCloseKey)\n(JNIEnv *, jclass, jlong hkey)\n{\n return RegCloseKey((HKEY)hkey);\n}\n\nJNIEXPORT jlong JNICALL SIGAR_JNI(win32_RegistryKey_RegCreateKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n HKEY hkeyResult = NULL;\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n \n RegCreateKeyEx((HKEY)hkey, lpSubkey, 0, NULL, \n REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, \n NULL, &hkeyResult, NULL);\n\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n\n return (jlong)hkeyResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n LONG lResult = RegDeleteKey((HKEY)hkey, lpSubkey);\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n\n return lResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegDeleteValue)\n(JNIEnv *env, jclass, jlong hkey, jstring valueName)\n{\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n LONG lResult = RegDeleteValue((HKEY)hkey, lpValueName);\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n\n return lResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumKey)\n(JNIEnv *env, jclass, jlong hkey, jint index)\n{\n jstring strResult;\n TCHAR szBuffer[MAX_PATH + 1];\n\n if(RegEnumKey((HKEY)hkey, index, szBuffer, \n sizeof(szBuffer)) == ERROR_SUCCESS)\n strResult = env->NewString((const jchar *)szBuffer, \n lstrlen(szBuffer));\n else\n strResult = NULL;\n\n return strResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegEnumValueName)\n(JNIEnv *env, jclass, jlong hkey, jint index)\n{\n jstring strResult;\n TCHAR szValueName[MAX_PATH + 1];\n DWORD cbValueName = sizeof(szValueName);\n\n if(RegEnumValue((HKEY)hkey, index, szValueName, \n &cbValueName, NULL, NULL, NULL, NULL) == ERROR_SUCCESS)\n strResult = env->NewString((const jchar *)szValueName, \n lstrlen(szValueName));\n else\n strResult = NULL;\n\n return strResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegFlushKey)\n(JNIEnv *env, jclass, long hkey)\n{\n return RegFlushKey((HKEY)hkey);\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegLoadKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey, jstring file)\n{\n LPCTSTR lpSubkey = (LPCTSTR)env->GetStringChars(subkey, NULL);\n LPCTSTR lpFile = (LPCTSTR)env->GetStringChars(file, NULL);\n\n LONG lResult = RegLoadKey((HKEY)hkey, lpSubkey, lpFile);\n\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n env->ReleaseStringChars(file, (const jchar *)lpFile);\n\n return lResult;\n}\n\nJNIEXPORT jlong SIGAR_JNI(win32_RegistryKey_RegOpenKey)\n(JNIEnv *env, jclass, jlong hkey, jstring subkey)\n{\n HKEY hkeyResult = NULL;\n jsize len = env->GetStringLength(subkey);\n LPTSTR lpSubkey = (LPTSTR)env->GetStringChars(subkey, NULL);\n LPTSTR copy;\n\n \/* required under IBM\/WebSphere 4.0 for certain keys *\/\n if (lpSubkey[len] != '\\0') {\n copy = wcsdup(lpSubkey);\n copy[len] = '\\0';\n }\n else {\n copy = lpSubkey;\n }\n RegOpenKey((HKEY)hkey, copy, &hkeyResult);\n\n env->ReleaseStringChars(subkey, (const jchar *)lpSubkey);\n if (copy != lpSubkey) {\n free(copy);\n }\n return (jlong)hkeyResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegQueryIntValue)\n(JNIEnv *env, jclass, jlong hkey, jstring valueName)\n{\n DWORD dwResult;\n DWORD dwType;\n LPBYTE lpValue;\n DWORD cbValue;\n\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n LONG lErr = RegQueryValueEx((HKEY)hkey, lpValueName, \n NULL, (LPDWORD)&dwType, \n NULL, &cbValue);\n \n if(lErr == ERROR_SUCCESS) {\n lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), \n HEAP_ZERO_MEMORY, cbValue);\n\n if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, \n NULL, lpValue, &cbValue) == ERROR_SUCCESS)\n {\n switch(dwType) {\n case REG_DWORD:\n dwResult = *(LPDWORD)lpValue;\n break;\n case REG_SZ:\n dwResult = _ttol((LPCTSTR)lpValue);\n break;\n default:\n lErr = ERROR_SUCCESS - 1; \/\/ Make an error\n }\n }\n\n HeapFree(GetProcessHeap(), 0, lpValue);\n }\n else\n \/\/ Make an error out of not seeing a REG_DWORD\n lErr = ERROR_SUCCESS - 1;\n\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n \n if(lErr != ERROR_SUCCESS)\n {\n jclass cls = \n env->FindClass(WIN32_PACKAGE \"Win32Exception\");\n env->ThrowNew(cls, NULL);\n }\n\n return dwResult;\n}\n\nJNIEXPORT jstring SIGAR_JNI(win32_RegistryKey_RegQueryStringValue)\n(JNIEnv *env, jclass, jlong hkey, jstring name)\n{\n jstring strResult;\n DWORD dwType;\n LPBYTE lpValue;\n DWORD cbValue;\n\n LPCTSTR lpValueName = (LPCTSTR)env->GetStringChars(name, NULL);\n LONG lErr = RegQueryValueEx((HKEY)hkey, \n lpValueName, NULL, \n (LPDWORD)&dwType, NULL, &cbValue);\n\n if(lErr == ERROR_SUCCESS)\n {\n lpValue = (LPBYTE)HeapAlloc(GetProcessHeap(), \n HEAP_ZERO_MEMORY, cbValue);\n\n if(RegQueryValueEx((HKEY)hkey, lpValueName, NULL, NULL, \n lpValue, &cbValue) == ERROR_SUCCESS)\n {\n switch(dwType) {\n case REG_DWORD:\n TCHAR szBuf[20];\n _ltot(*(LPDWORD)lpValue, szBuf, 10);\n strResult = env->NewString((const jchar *)szBuf, \n lstrlen(szBuf));\n break;\n case REG_SZ:\n case REG_EXPAND_SZ: {\n DWORD len;\n LPTSTR dest = NULL;\n len = ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, 0);\n dest = (LPTSTR)malloc(len * sizeof(TCHAR));\n ExpandEnvironmentStrings((LPCTSTR)lpValue, dest, len);\n strResult = env->NewString((const jchar *)dest, len);\n free(dest);\n break;\n }\n default:\n lErr = ERROR_SUCCESS - 1; \/\/ Make an error\n }\n }\n\n HeapFree(GetProcessHeap(), 0, lpValue);\n }\n\n env->ReleaseStringChars(name, (const jchar *)lpValueName);\n \n if(lErr == ERROR_SUCCESS)\n return strResult;\n else\n {\n jclass cls = env->FindClass(WIN32_PACKAGE \"Win32Exception\");\n env->ThrowNew(cls, \"\");\n return NULL;\n }\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetIntValue)\n(JNIEnv * env, jclass, jlong hkey, jstring valueName, jint value)\n{\n LPCTSTR lpValueName;\n \n if(valueName != NULL)\n lpValueName = (LPCTSTR)env->GetStringChars(valueName, NULL);\n else\n lpValueName = NULL;\n\n int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, \n REG_DWORD, (LPBYTE)&value, sizeof(value));\n\n if(valueName != NULL)\n env->ReleaseStringChars(valueName, (const jchar *)lpValueName);\n\n return iResult;\n}\n\nJNIEXPORT jint SIGAR_JNI(win32_RegistryKey_RegSetStringValue)\n(JNIEnv *env, jclass, jlong hkey, jstring name, jstring value)\n{\n LPCTSTR lpValueName;\n\n if(name != NULL)\n lpValueName = (LPCTSTR)env->GetStringChars(name, NULL);\n else\n lpValueName = NULL;\n\n LPCTSTR lpValue = (LPCTSTR)env->GetStringChars(value, NULL);\n\n int iResult = RegSetValueEx((HKEY)hkey, lpValueName, 0, \n REG_SZ, (LPBYTE)lpValue, \n (lstrlen(lpValue) + 1) * sizeof(TCHAR));\n \n if(name != NULL)\n env->ReleaseStringChars(name, (const jchar *)lpValueName);\n env->ReleaseStringChars(value, (const jchar *)lpValue);\n\n return iResult;\n}\n\n#ifdef __cplusplus\n}\n#endif\n#endif \/* WIN32 *\/\n<|endoftext|>"} {"text":"\/**\n * @file nca_main.cpp\n * @author Ryan Curtin\n *\n * Executable for Neighborhood Components Analysis.\n *\/\n#include \n#include \n\n#include \"nca.hpp\"\n\n\/\/ Define parameters.\nPROGRAM_INFO(\"Neighborhood Components Analysis (NCA)\",\n \"This program implements Neighborhood Components Analysis, both a linear \"\n \"dimensionality reduction technique and a distance learning technique. The\"\n \" method seeks to improve k-nearest-neighbor classification on a dataset \"\n \"by scaling the dimensions. The method is nonparametric, and does not \"\n \"require a value of k. It works by using stochastic (\\\"soft\\\") neighbor \"\n \"assignments and using optimization techniques over the gradient of the \"\n \"accuracy of the neighbor assignments.\\n\"\n \"\\n\"\n \"For more details, see the following published paper:\\n\\n\"\n \"@inproceedings{\\n\"\n \" author = {Goldberge, Jacob and Roweis, Sam and Hinton, Geoff and\\n\"\n \" Salakhutdinov, Ruslan},\\n\"\n \" booktitle = {Advances in Neural Information Processing Systems 17},\\n\"\n \" pages = {513--520},\\n\"\n \" publisher = {MIT Press},\\n\"\n \" title = {{Neighbourhood Components Analysis}},\\n\"\n \" year = {2004}\\n\"\n \"}\\n\"\n \"\\n\"\n \"To work, this algorithm needs labeled data. It can be given as the last \"\n \"row of the input dataset (--input_file), or alternatively in a separate \"\n \"file (--labels_file).\");\n\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to run NCA on.\", \"i\");\nPARAM_STRING_REQ(\"output_file\", \"Output file for learned distance matrix.\",\n \"o\");\nPARAM_STRING(\"labels_file\", \"File of labels for input dataset.\", \"l\", \"\");\n\nusing namespace mlpack;\nusing namespace mlpack::nca;\nusing namespace mlpack::metric;\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char* argv[])\n{\n \/\/ Parse command line.\n CLI::ParseCommandLine(argc, argv);\n\n const string inputFile = CLI::GetParam(\"input_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string outputFile = CLI::GetParam(\"output_file\");\n\n \/\/ Load data.\n mat data;\n data::Load(inputFile.c_str(), data, true);\n\n \/\/ Do we want to load labels separately?\n umat labels(data.n_cols, 1);\n if (labelsFile != \"\")\n {\n data::Load(labelsFile.c_str(), labels, true);\n\n if (labels.n_rows == 1)\n labels = trans(labels);\n\n if (labels.n_cols > 1)\n Log::Fatal << \"Labels must have only one column or row!\" << endl;\n }\n else\n {\n for (size_t i = 0; i < data.n_cols; i++)\n labels[i] = (int) data(data.n_rows - 1, i);\n\n data.shed_row(data.n_rows - 1);\n }\n\n \/\/ Now create the NCA object and run the optimization.\n NCA > nca(data, labels.unsafe_col(0));\n\n mat distance;\n nca.LearnDistance(distance);\n\n \/\/ Save the output.\n data::Save(CLI::GetParam(\"output_file\").c_str(), distance, true);\n}\nFix spelling error.\/**\n * @file nca_main.cpp\n * @author Ryan Curtin\n *\n * Executable for Neighborhood Components Analysis.\n *\/\n#include \n#include \n\n#include \"nca.hpp\"\n\n\/\/ Define parameters.\nPROGRAM_INFO(\"Neighborhood Components Analysis (NCA)\",\n \"This program implements Neighborhood Components Analysis, both a linear \"\n \"dimensionality reduction technique and a distance learning technique. The\"\n \" method seeks to improve k-nearest-neighbor classification on a dataset \"\n \"by scaling the dimensions. The method is nonparametric, and does not \"\n \"require a value of k. It works by using stochastic (\\\"soft\\\") neighbor \"\n \"assignments and using optimization techniques over the gradient of the \"\n \"accuracy of the neighbor assignments.\\n\"\n \"\\n\"\n \"For more details, see the following published paper:\\n\\n\"\n \"@inproceedings{\\n\"\n \" author = {Goldberger, Jacob and Roweis, Sam and Hinton, Geoff and\\n\"\n \" Salakhutdinov, Ruslan},\\n\"\n \" booktitle = {Advances in Neural Information Processing Systems 17},\\n\"\n \" pages = {513--520},\\n\"\n \" publisher = {MIT Press},\\n\"\n \" title = {{Neighbourhood Components Analysis}},\\n\"\n \" year = {2004}\\n\"\n \"}\\n\"\n \"\\n\"\n \"To work, this algorithm needs labeled data. It can be given as the last \"\n \"row of the input dataset (--input_file), or alternatively in a separate \"\n \"file (--labels_file).\");\n\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to run NCA on.\", \"i\");\nPARAM_STRING_REQ(\"output_file\", \"Output file for learned distance matrix.\",\n \"o\");\nPARAM_STRING(\"labels_file\", \"File of labels for input dataset.\", \"l\", \"\");\n\nusing namespace mlpack;\nusing namespace mlpack::nca;\nusing namespace mlpack::metric;\nusing namespace std;\nusing namespace arma;\n\nint main(int argc, char* argv[])\n{\n \/\/ Parse command line.\n CLI::ParseCommandLine(argc, argv);\n\n const string inputFile = CLI::GetParam(\"input_file\");\n const string labelsFile = CLI::GetParam(\"labels_file\");\n const string outputFile = CLI::GetParam(\"output_file\");\n\n \/\/ Load data.\n mat data;\n data::Load(inputFile.c_str(), data, true);\n\n \/\/ Do we want to load labels separately?\n umat labels(data.n_cols, 1);\n if (labelsFile != \"\")\n {\n data::Load(labelsFile.c_str(), labels, true);\n\n if (labels.n_rows == 1)\n labels = trans(labels);\n\n if (labels.n_cols > 1)\n Log::Fatal << \"Labels must have only one column or row!\" << endl;\n }\n else\n {\n for (size_t i = 0; i < data.n_cols; i++)\n labels[i] = (int) data(data.n_rows - 1, i);\n\n data.shed_row(data.n_rows - 1);\n }\n\n \/\/ Now create the NCA object and run the optimization.\n NCA > nca(data, labels.unsafe_col(0));\n\n mat distance;\n nca.LearnDistance(distance);\n\n \/\/ Save the output.\n data::Save(CLI::GetParam(\"output_file\").c_str(), distance, true);\n}\n<|endoftext|>"} {"text":"\/**\n * @file pca_main.cpp\n * @author Ryan Curtin\n *\n * Main executable to run PCA.\n *\/\n#include \n\n#include \"pca.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::pca;\nusing namespace std;\n\n\/\/ Document program.\nPROGRAM_INFO(\"Principal Components Analysis\", \"This program performs principal \"\n \"components analysis on the given dataset. It will transform the data \"\n \"onto its principal components, optionally performing dimensionality \"\n \"reduction by ignoring the principal components with the smallest \"\n \"eigenvalues.\", \"\");\n\n\/\/ Parameters for program.\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to perform PCA on.\", \"\");\nPARAM_STRING_REQ(\"output_file\", \"Output dataset to perform PCA on.\", \"\");\nPARAM_INT(\"new_dimensionality\", \"Desired dimensionality of output dataset.\",\n \"\", 0);\n\nint main(int argc, char** argv)\n{\n \/\/ Parse commandline.\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Load input dataset.\n string inputFile = CLI::GetParam(\"input_file\");\n arma::mat dataset;\n data::Load(inputFile.c_str(), dataset);\n\n \/\/ Find out what dimension we want.\n size_t newDimension = dataset.n_rows; \/\/ No reduction, by default.\n if (CLI::HasParam(\"new_dimensionality\"))\n {\n \/\/ Validate the parameter.\n newDimension = (size_t) CLI::GetParam(\"new_dimensionality\");\n if (newDimension < 1);\n {\n Log::Fatal << \"Invalid value for new dimensionality (\" << newDimension\n << \")! Must be greater than or equal to 1.\" << std::endl;\n }\n }\n\n \/\/ Perform PCA.\n PCA p;\n Log::Info << \"Performing PCA on dataset...\" << std::endl;\n p.Apply(dataset, newDimension);\n\n \/\/ Now save the results.\n string outputFile = CLI::GetParam(\"output_file\");\n data::Save(outputFile.c_str(), dataset);\n}\nFix for integer parameter.\/**\n * @file pca_main.cpp\n * @author Ryan Curtin\n *\n * Main executable to run PCA.\n *\/\n#include \n\n#include \"pca.hpp\"\n\nusing namespace mlpack;\nusing namespace mlpack::pca;\nusing namespace std;\n\n\/\/ Document program.\nPROGRAM_INFO(\"Principal Components Analysis\", \"This program performs principal \"\n \"components analysis on the given dataset. It will transform the data \"\n \"onto its principal components, optionally performing dimensionality \"\n \"reduction by ignoring the principal components with the smallest \"\n \"eigenvalues.\", \"\");\n\n\/\/ Parameters for program.\nPARAM_STRING_REQ(\"input_file\", \"Input dataset to perform PCA on.\", \"\");\nPARAM_STRING_REQ(\"output_file\", \"Output dataset to perform PCA on.\", \"\");\nPARAM_INT(\"new_dimensionality\", \"Desired dimensionality of output dataset.\",\n \"\", 0);\n\nint main(int argc, char** argv)\n{\n \/\/ Parse commandline.\n CLI::ParseCommandLine(argc, argv);\n\n \/\/ Load input dataset.\n string inputFile = CLI::GetParam(\"input_file\");\n arma::mat dataset;\n data::Load(inputFile.c_str(), dataset);\n\n \/\/ Find out what dimension we want.\n size_t newDimension = dataset.n_rows; \/\/ No reduction, by default.\n if (CLI::GetParam(\"new_dimensionality\") != 0)\n {\n \/\/ Validate the parameter.\n newDimension = (size_t) CLI::GetParam(\"new_dimensionality\");\n if (newDimension < 1);\n {\n Log::Fatal << \"Invalid value for new dimensionality (\" << newDimension\n << \")! Must be greater than or equal to 1.\" << std::endl;\n }\n }\n\n \/\/ Perform PCA.\n PCA p;\n Log::Info << \"Performing PCA on dataset...\" << std::endl;\n p.Apply(dataset, newDimension);\n\n \/\/ Now save the results.\n string outputFile = CLI::GetParam(\"output_file\");\n data::Save(outputFile.c_str(), dataset);\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#include \n#include \"cppa\/network\/middleman_event_handler.hpp\"\n\n#ifndef POLLRDHUP\n#define POLLRDHUP POLLHUP\n#endif\n\nnamespace cppa { namespace network {\n\nnamespace {\n\nbool pollfd_less(const pollfd& lhs, native_socket_type rhs) {\n return lhs.fd < rhs;\n}\n\nshort to_poll_bitmask(event_bitmask mask) {\n switch (mask) {\n case event::read: return POLLIN;\n case event::write: return POLLOUT;\n case event::both: return (POLLIN|POLLOUT);\n default: CPPA_CRITICAL(\"invalid event bitmask\");\n }\n}\n\nclass middleman_event_handler_impl : public middleman_event_handler {\n\n public:\n\n void init() { }\n\n protected:\n\n void poll_impl() {\n CPPA_REQUIRE(m_pollset.empty() == false);\n CPPA_REQUIRE(m_pollset.size() == m_meta.size());\n int presult;\n do {\n presult = ::poll(m_pollset.data(), m_pollset.size(), -1);\n CPPA_LOGMF(CPPA_DEBUG, self, \"poll() on \" << num_sockets()\n << \" sockets returned \" << presult);\n if (presult < 0) {\n switch (errno) {\n \/\/ a signal was caught\n case EINTR: {\n \/\/ just try again\n break;\n }\n case ENOMEM: {\n CPPA_LOGMF(CPPA_ERROR, self, \"poll() failed for reason ENOMEM\");\n \/\/ there's not much we can do other than try again\n \/\/ in hope someone releases memory\n \/\/this_thread::yield();\n break;\n }\n default: {\n perror(\"poll() failed\");\n CPPA_CRITICAL(\"poll() failed\");\n }\n }\n }\n else {\n for (size_t i = 0; i < m_pollset.size(); ++i) {\n event_bitmask eb = event::none;\n auto& revents = m_pollset[i].revents;\n if (revents & (POLLRDHUP | POLLERR | POLLHUP | POLLNVAL)) {\n eb = event::error;\n }\n else {\n if (revents & (POLLIN | POLLPRI)) eb |= event::read;\n if (revents & POLLOUT) eb |= event::write;\n }\n revents = 0;\n m_events.emplace_back(eb, m_meta[i].ptr.get());\n }\n }\n } while (presult < 0);\n }\n\n void handle_event(fd_meta_event me,\n native_socket_type fd,\n event_bitmask,\n event_bitmask new_bitmask,\n continuable_io*) {\n auto last = m_pollset.end();\n auto iter = std::lower_bound(m_pollset.begin(), last, fd, pollfd_less);\n switch (me) {\n case fd_meta_event::add: {\n pollfd tmp;\n tmp.fd = fd;\n tmp.events = to_poll_bitmask(new_bitmask);\n tmp.revents = 0;\n m_pollset.insert(iter, tmp);\n CPPA_LOGMF(CPPA_DEBUG, self, \"inserted new element\");\n break;\n }\n case fd_meta_event::erase: {\n CPPA_LOG_ERROR_IF(iter == last || iter->fd != fd,\n \"m_meta and m_pollset out of sync; \"\n \"no element found for fd (cannot erase)\");\n if (iter != last && iter->fd == fd) {\n CPPA_LOGMF(CPPA_DEBUG, self, \"erased element\");\n m_pollset.erase(iter);\n }\n break;\n }\n case fd_meta_event::mod: {\n CPPA_LOG_ERROR_IF(iter == last || iter->fd != fd,\n \"m_meta and m_pollset out of sync; \"\n \"no element found for fd (cannot erase)\");\n if (iter != last && iter->fd == fd) {\n CPPA_LOGMF(CPPA_DEBUG, self, \"updated bitmask\");\n iter->events = to_poll_bitmask(new_bitmask);\n }\n break;\n }\n }\n }\n\n private:\n\n std::vector m_pollset; \/\/ always in sync with m_meta\n\n};\n\n} \/\/ namespace \n\nstd::unique_ptr middleman_event_handler::create() {\n return std::unique_ptr{new middleman_event_handler_impl};\n}\n\n} } \/\/ namespace cppa::network\nignore POLLHUP until there's no more data to read\/******************************************************************************\\\n * ___ __ *\n * \/\\_ \\ __\/\\ \\ *\n * \\\/\/\\ \\ \/\\_\\ \\ \\____ ___ _____ _____ __ *\n * \\ \\ \\ \\\/\\ \\ \\ '__`\\ \/'___\\\/\\ '__`\\\/\\ '__`\\ \/'__`\\ *\n * \\_\\ \\_\\ \\ \\ \\ \\L\\ \\\/\\ \\__\/\\ \\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\.\\_ *\n * \/\\____\\\\ \\_\\ \\_,__\/\\ \\____\\\\ \\ ,__\/\\ \\ ,__\/\\ \\__\/.\\_\\ *\n * \\\/____\/ \\\/_\/\\\/___\/ \\\/____\/ \\ \\ \\\/ \\ \\ \\\/ \\\/__\/\\\/_\/ *\n * \\ \\_\\ \\ \\_\\ *\n * \\\/_\/ \\\/_\/ *\n * *\n * Copyright (C) 2011-2013 *\n * Dominik Charousset *\n * *\n * This file is part of libcppa. *\n * libcppa is free software: you can redistribute it and\/or modify it under *\n * the terms of the GNU Lesser General Public License as published by the *\n * Free Software Foundation; either version 2.1 of the License, *\n * or (at your option) any later version. *\n * *\n * libcppa is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n * See the GNU Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU Lesser General Public License *\n * along with libcppa. If not, see . *\n\\******************************************************************************\/\n\n\n#include \n#include \"cppa\/network\/middleman_event_handler.hpp\"\n\n#ifndef POLLRDHUP\n#define POLLRDHUP POLLHUP\n#endif\n\nnamespace cppa { namespace network {\n\nnamespace {\n\nbool pollfd_less(const pollfd& lhs, native_socket_type rhs) {\n return lhs.fd < rhs;\n}\n\nshort to_poll_bitmask(event_bitmask mask) {\n switch (mask) {\n case event::read: return POLLIN;\n case event::write: return POLLOUT;\n case event::both: return (POLLIN|POLLOUT);\n default: CPPA_CRITICAL(\"invalid event bitmask\");\n }\n}\n\nclass middleman_event_handler_impl : public middleman_event_handler {\n\n public:\n\n void init() { }\n\n protected:\n\n void poll_impl() {\n CPPA_REQUIRE(m_pollset.empty() == false);\n CPPA_REQUIRE(m_pollset.size() == m_meta.size());\n int presult;\n do {\n presult = ::poll(m_pollset.data(), m_pollset.size(), -1);\n CPPA_LOG_DEBUG(\"poll() on \" << num_sockets()\n << \" sockets returned \" << presult);\n if (presult < 0) {\n switch (errno) {\n \/\/ a signal was caught\n case EINTR: {\n \/\/ just try again\n break;\n }\n case ENOMEM: {\n CPPA_LOGMF(CPPA_ERROR, self, \"poll() failed for reason ENOMEM\");\n \/\/ there's not much we can do other than try again\n \/\/ in hope someone releases memory\n \/\/this_thread::yield();\n break;\n }\n default: {\n perror(\"poll() failed\");\n CPPA_CRITICAL(\"poll() failed\");\n }\n }\n }\n else {\n for (size_t i = 0; i < m_pollset.size(); ++i) {\n event_bitmask eb = event::none;\n auto& revents = m_pollset[i].revents;\n \/\/ read as long as possible, ignore POLLHUP as long as\n \/\/ there is still data available\n if (revents & (POLLIN | POLLPRI)) eb |= event::read;\n else if (revents & (POLLRDHUP | POLLERR | POLLHUP | POLLNVAL)) {\n CPPA_LOG_DEBUG_IF(revents & POLLRDHUP, \"POLLRDHUP\");\n CPPA_LOG_DEBUG_IF(revents & POLLERR, \"POLLERR\");\n CPPA_LOG_DEBUG_IF(revents & POLLHUP, \"POLLHUP\");\n CPPA_LOG_DEBUG_IF(revents & POLLNVAL, \"POLLNVAL\");\n eb = event::error;\n }\n \/\/ POLLOUT and POLLHUP are mutually exclusive:\n \/\/ no need to check wheter event::error has been set\n if (revents & POLLOUT) eb |= event::write;\n revents = 0;\n m_events.emplace_back(eb, m_meta[i].ptr.get());\n }\n }\n } while (presult < 0);\n }\n\n void handle_event(fd_meta_event me,\n native_socket_type fd,\n event_bitmask,\n event_bitmask new_bitmask,\n continuable_io*) {\n auto last = m_pollset.end();\n auto iter = std::lower_bound(m_pollset.begin(), last, fd, pollfd_less);\n switch (me) {\n case fd_meta_event::add: {\n pollfd tmp;\n tmp.fd = fd;\n tmp.events = to_poll_bitmask(new_bitmask);\n tmp.revents = 0;\n m_pollset.insert(iter, tmp);\n CPPA_LOGMF(CPPA_DEBUG, self, \"inserted new element\");\n break;\n }\n case fd_meta_event::erase: {\n CPPA_LOG_ERROR_IF(iter == last || iter->fd != fd,\n \"m_meta and m_pollset out of sync; \"\n \"no element found for fd (cannot erase)\");\n if (iter != last && iter->fd == fd) {\n CPPA_LOGMF(CPPA_DEBUG, self, \"erased element\");\n m_pollset.erase(iter);\n }\n break;\n }\n case fd_meta_event::mod: {\n CPPA_LOG_ERROR_IF(iter == last || iter->fd != fd,\n \"m_meta and m_pollset out of sync; \"\n \"no element found for fd (cannot erase)\");\n if (iter != last && iter->fd == fd) {\n CPPA_LOGMF(CPPA_DEBUG, self, \"updated bitmask\");\n iter->events = to_poll_bitmask(new_bitmask);\n }\n break;\n }\n }\n }\n\n private:\n\n std::vector m_pollset; \/\/ always in sync with m_meta\n\n};\n\n} \/\/ namespace \n\nstd::unique_ptr middleman_event_handler::create() {\n return std::unique_ptr{new middleman_event_handler_impl};\n}\n\n} } \/\/ namespace cppa::network\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: clang -shared %S\/call_lib.c -o%T\/libcall_lib%shlibext && ls %T\/libcall_lib%shlibext && cat %s | %cling -L%T | FileCheck %s\n\n.L libcall_lib\nextern \"C\" int cling_testlibrary_function();\nint i = cling_testlibrary_function();\nextern \"C\" int printf(const char* fmt, ...);\nprintf(\"got i=%d\\n\", i); \/\/ CHECK: got i=66\n.q\nChanging output name call.C test.\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: clang -shared %S\/call_lib.c -o%T\/libcall_lib2%shlibext\n\/\/ RUN: cat %s | %cling -L%T | FileCheck %s\n\n.L libcall_lib2\nextern \"C\" int cling_testlibrary_function();\nint i = cling_testlibrary_function();\nextern \"C\" int printf(const char* fmt, ...);\nprintf(\"got i=%d\\n\", i); \/\/ CHECK: got i=66\n.q\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef ARRAY_MAP_HH_\n#define ARRAY_MAP_HH_\n\n#include \n\n\/\/ unordered_map implemented as a simple array\n\ntemplate \nclass array_map {\n std::array _a;\npublic:\n array_map(std::initializer_list> i) {\n for (auto kv : i) {\n _a[kv.first] = kv.second;\n }\n }\n Value& operator[](size_t key) { return _a[key]; }\n const Value& operator[](size_t key) const { return _a[key]; }\n};\n\n\n\n#endif \/* ARRAY_MAP_HH_ *\/\narray_map: introduce at()\/*\n * Copyright (C) 2014 Cloudius Systems, Ltd.\n *\/\n\n#ifndef ARRAY_MAP_HH_\n#define ARRAY_MAP_HH_\n\n#include \n\n\/\/ unordered_map implemented as a simple array\n\ntemplate \nclass array_map {\n std::array _a;\npublic:\n array_map(std::initializer_list> i) {\n for (auto kv : i) {\n _a[kv.first] = kv.second;\n }\n }\n Value& operator[](size_t key) { return _a[key]; }\n const Value& operator[](size_t key) const { return _a[key]; }\n\n Value& at(size_t key) {\n if (key >= Max) {\n throw std::out_of_range(std::to_string(key) + \" >= \" + std::to_string(Max));\n }\n return _a[key];\n }\n};\n\n\n\n#endif \/* ARRAY_MAP_HH_ *\/\n<|endoftext|>"} {"text":"Len() != isEmpty()<|endoftext|>"} {"text":"\/*!\n@file\n\n@copyright Edouard Alligand and Joel Falcou 2015-2017\n(See accompanying file LICENSE.md or copy at http:\/\/boost.org\/LICENSE_1_0.txt)\n*\/\n#ifndef BOOST_BRIGAND_TYPES_NO_SUCH_TYPE_HPP\n#define BOOST_BRIGAND_TYPES_NO_SUCH_TYPE_HPP\n\nnamespace brigand\n{\n \/\/ type to return when finding something fails\n \/\/ I wanted to call it \"not sure if type\" but Joel didn't want to :(\n struct no_such_type_ {};\n}\n#endif\nDelete no_such_type.hpp<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n#include \n\n#include \"base\/bind.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"dbus\/bus.h\"\n#include \"dbus\/message.h\"\n#include \"dbus\/object_proxy.h\"\n#include \"dbus\/test_service.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ The end-to-end test exercises the asynchronous APIs in ObjectProxy and\n\/\/ ExportedObject.\nclass EndToEndAsyncTest : public testing::Test {\n public:\n EndToEndAsyncTest() {\n }\n\n virtual void SetUp() {\n \/\/ Make the main thread not to allow IO.\n base::ThreadRestrictions::SetIOAllowed(false);\n\n \/\/ Start the D-Bus thread.\n dbus_thread_.reset(new base::Thread(\"D-Bus Thread\"));\n base::Thread::Options thread_options;\n thread_options.message_loop_type = MessageLoop::TYPE_IO;\n ASSERT_TRUE(dbus_thread_->StartWithOptions(thread_options));\n\n \/\/ Start the test service, using the D-Bus thread.\n dbus::TestService::Options options;\n options.dbus_thread_message_loop_proxy = dbus_thread_->message_loop_proxy();\n test_service_.reset(new dbus::TestService(options));\n ASSERT_TRUE(test_service_->StartService());\n ASSERT_TRUE(test_service_->WaitUntilServiceIsStarted());\n ASSERT_TRUE(test_service_->HasDBusThread());\n\n \/\/ Create the client, using the D-Bus thread.\n dbus::Bus::Options bus_options;\n bus_options.bus_type = dbus::Bus::SESSION;\n bus_options.connection_type = dbus::Bus::PRIVATE;\n bus_options.dbus_thread_message_loop_proxy =\n dbus_thread_->message_loop_proxy();\n bus_ = new dbus::Bus(bus_options);\n object_proxy_ = bus_->GetObjectProxy(\"org.chromium.TestService\",\n \"\/org\/chromium\/TestObject\");\n ASSERT_TRUE(bus_->HasDBusThread());\n\n \/\/ Connect to the \"Test\" signal of \"org.chromium.TestInterface\" from\n \/\/ the remote object.\n object_proxy_->ConnectToSignal(\n \"org.chromium.TestInterface\",\n \"Test\",\n base::Bind(&EndToEndAsyncTest::OnTestSignal,\n base::Unretained(this)),\n base::Bind(&EndToEndAsyncTest::OnConnected,\n base::Unretained(this)));\n \/\/ Connect to the \"Test2\" signal of \"org.chromium.TestInterface\" from\n \/\/ the remote object. There was a bug where we were emitting error\n \/\/ messages like \"Requested to remove an unknown match rule: ...\" at\n \/\/ the shutdown of Bus when an object proxy is connected to more than\n \/\/ one signal of the same interface. See crosbug.com\/23382 for details.\n object_proxy_->ConnectToSignal(\n \"org.chromium.TestInterface\",\n \"Test2\",\n base::Bind(&EndToEndAsyncTest::OnTest2Signal,\n base::Unretained(this)),\n base::Bind(&EndToEndAsyncTest::OnConnected,\n base::Unretained(this)));\n \/\/ Wait until the object proxy is connected to the signal.\n message_loop_.Run();\n }\n\n virtual void TearDown() {\n bus_->ShutdownOnDBusThreadAndBlock();\n\n \/\/ Shut down the service.\n test_service_->ShutdownAndBlock();\n\n \/\/ Reset to the default.\n base::ThreadRestrictions::SetIOAllowed(true);\n\n \/\/ Stopping a thread is considered an IO operation, so do this after\n \/\/ allowing IO.\n test_service_->Stop();\n }\n\n protected:\n \/\/ Calls the method asynchronously. OnResponse() will be called once the\n \/\/ response is received.\n void CallMethod(dbus::MethodCall* method_call,\n int timeout_ms) {\n object_proxy_->CallMethod(method_call,\n timeout_ms,\n base::Bind(&EndToEndAsyncTest::OnResponse,\n base::Unretained(this)));\n }\n\n \/\/ Wait for the give number of responses.\n void WaitForResponses(size_t num_responses) {\n while (response_strings_.size() < num_responses) {\n message_loop_.Run();\n }\n }\n\n \/\/ Called when the response is received.\n void OnResponse(dbus::Response* response) {\n \/\/ |response| will be deleted on exit of the function. Copy the\n \/\/ payload to |response_strings_|.\n if (response) {\n dbus::MessageReader reader(response);\n std::string response_string;\n ASSERT_TRUE(reader.PopString(&response_string));\n response_strings_.push_back(response_string);\n } else {\n response_strings_.push_back(\"\");\n }\n message_loop_.Quit();\n };\n\n \/\/ Called when the \"Test\" signal is received, in the main thread.\n \/\/ Copy the string payload to |test_signal_string_|.\n void OnTestSignal(dbus::Signal* signal) {\n dbus::MessageReader reader(signal);\n ASSERT_TRUE(reader.PopString(&test_signal_string_));\n message_loop_.Quit();\n }\n\n \/\/ Called when the \"Test2\" signal is received, in the main thread.\n void OnTest2Signal(dbus::Signal* signal) {\n dbus::MessageReader reader(signal);\n message_loop_.Quit();\n }\n\n \/\/ Called when connected to the signal.\n void OnConnected(const std::string& interface_name,\n const std::string& signal_name,\n bool success) {\n ASSERT_TRUE(success);\n message_loop_.Quit();\n }\n\n \/\/ Wait for the hey signal to be received.\n void WaitForTestSignal() {\n \/\/ OnTestSignal() will quit the message loop.\n message_loop_.Run();\n }\n\n MessageLoop message_loop_;\n std::vector response_strings_;\n scoped_ptr dbus_thread_;\n scoped_refptr bus_;\n dbus::ObjectProxy* object_proxy_;\n scoped_ptr test_service_;\n \/\/ Text message from \"Test\" signal.\n std::string test_signal_string_;\n};\n\nTEST_F(EndToEndAsyncTest, Echo) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n\n \/\/ Check the response.\n WaitForResponses(1);\n EXPECT_EQ(kHello, response_strings_[0]);\n}\n\n\/\/ Call Echo method three times.\nTEST_F(EndToEndAsyncTest, EchoThreeTimes) {\n const char* kMessages[] = { \"foo\", \"bar\", \"baz\" };\n\n for (size_t i = 0; i < arraysize(kMessages); ++i) {\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kMessages[i]);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n }\n\n \/\/ Check the responses.\n WaitForResponses(3);\n \/\/ Sort as the order of the returned messages is not deterministic.\n std::sort(response_strings_.begin(), response_strings_.end());\n EXPECT_EQ(\"bar\", response_strings_[0]);\n EXPECT_EQ(\"baz\", response_strings_[1]);\n EXPECT_EQ(\"foo\", response_strings_[2]);\n}\n\nTEST_F(EndToEndAsyncTest, Timeout) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"SlowEcho\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method with timeout of 0ms.\n const int timeout_ms = 0;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because of timeout.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\n\/\/ Tests calling a method that sends its reply asynchronously.\nTEST_F(EndToEndAsyncTest, AsyncEcho) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"AsyncEcho\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n\n \/\/ Check the response.\n WaitForResponses(1);\n EXPECT_EQ(kHello, response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, NonexistentMethod) {\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Nonexistent\");\n\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because the method is nonexistent.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, BrokenMethod) {\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"BrokenMethod\");\n\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because the method is broken.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, EmptyResponseCallback) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method with an empty callback.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n object_proxy_->CallMethod(&method_call,\n timeout_ms,\n dbus::ObjectProxy::EmptyResponseCallback());\n \/\/ Post a delayed task to quit the message loop.\n message_loop_.PostDelayedTask(FROM_HERE,\n MessageLoop::QuitClosure(),\n TestTimeouts::tiny_timeout_ms());\n message_loop_.Run();\n \/\/ We cannot tell if the empty callback is called, but at least we can\n \/\/ check if the test does not crash.\n}\n\nTEST_F(EndToEndAsyncTest, TestSignal) {\n const char kMessage[] = \"hello, world\";\n \/\/ Send the test signal from the exported object.\n test_service_->SendTestSignal(kMessage);\n \/\/ Receive the signal with the object proxy. The signal is handled in\n \/\/ EndToEndAsyncTest::OnTestSignal() in the main thread.\n WaitForTestSignal();\n ASSERT_EQ(kMessage, test_signal_string_);\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/106796\nTEST_F(EndToEndAsyncTest, FLAKY_TestSignalFromRoot) {\n const char kMessage[] = \"hello, world\";\n \/\/ Send the test signal from the root object path, to see if we can\n \/\/ handle signals sent from \"\/\", like dbus-send does.\n test_service_->SendTestSignalFromRoot(kMessage);\n \/\/ Receive the signal with the object proxy. The signal is handled in\n \/\/ EndToEndAsyncTest::OnTestSignal() in the main thread.\n WaitForTestSignal();\n ASSERT_EQ(kMessage, test_signal_string_);\n}\nMark EndToEndAsyncTest.TestSignal as flaky\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n#include \n\n#include \"base\/bind.h\"\n#include \"base\/memory\/scoped_ptr.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/stl_util.h\"\n#include \"base\/test\/test_timeouts.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/threading\/thread_restrictions.h\"\n#include \"dbus\/bus.h\"\n#include \"dbus\/message.h\"\n#include \"dbus\/object_proxy.h\"\n#include \"dbus\/test_service.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\n\/\/ The end-to-end test exercises the asynchronous APIs in ObjectProxy and\n\/\/ ExportedObject.\nclass EndToEndAsyncTest : public testing::Test {\n public:\n EndToEndAsyncTest() {\n }\n\n virtual void SetUp() {\n \/\/ Make the main thread not to allow IO.\n base::ThreadRestrictions::SetIOAllowed(false);\n\n \/\/ Start the D-Bus thread.\n dbus_thread_.reset(new base::Thread(\"D-Bus Thread\"));\n base::Thread::Options thread_options;\n thread_options.message_loop_type = MessageLoop::TYPE_IO;\n ASSERT_TRUE(dbus_thread_->StartWithOptions(thread_options));\n\n \/\/ Start the test service, using the D-Bus thread.\n dbus::TestService::Options options;\n options.dbus_thread_message_loop_proxy = dbus_thread_->message_loop_proxy();\n test_service_.reset(new dbus::TestService(options));\n ASSERT_TRUE(test_service_->StartService());\n ASSERT_TRUE(test_service_->WaitUntilServiceIsStarted());\n ASSERT_TRUE(test_service_->HasDBusThread());\n\n \/\/ Create the client, using the D-Bus thread.\n dbus::Bus::Options bus_options;\n bus_options.bus_type = dbus::Bus::SESSION;\n bus_options.connection_type = dbus::Bus::PRIVATE;\n bus_options.dbus_thread_message_loop_proxy =\n dbus_thread_->message_loop_proxy();\n bus_ = new dbus::Bus(bus_options);\n object_proxy_ = bus_->GetObjectProxy(\"org.chromium.TestService\",\n \"\/org\/chromium\/TestObject\");\n ASSERT_TRUE(bus_->HasDBusThread());\n\n \/\/ Connect to the \"Test\" signal of \"org.chromium.TestInterface\" from\n \/\/ the remote object.\n object_proxy_->ConnectToSignal(\n \"org.chromium.TestInterface\",\n \"Test\",\n base::Bind(&EndToEndAsyncTest::OnTestSignal,\n base::Unretained(this)),\n base::Bind(&EndToEndAsyncTest::OnConnected,\n base::Unretained(this)));\n \/\/ Connect to the \"Test2\" signal of \"org.chromium.TestInterface\" from\n \/\/ the remote object. There was a bug where we were emitting error\n \/\/ messages like \"Requested to remove an unknown match rule: ...\" at\n \/\/ the shutdown of Bus when an object proxy is connected to more than\n \/\/ one signal of the same interface. See crosbug.com\/23382 for details.\n object_proxy_->ConnectToSignal(\n \"org.chromium.TestInterface\",\n \"Test2\",\n base::Bind(&EndToEndAsyncTest::OnTest2Signal,\n base::Unretained(this)),\n base::Bind(&EndToEndAsyncTest::OnConnected,\n base::Unretained(this)));\n \/\/ Wait until the object proxy is connected to the signal.\n message_loop_.Run();\n }\n\n virtual void TearDown() {\n bus_->ShutdownOnDBusThreadAndBlock();\n\n \/\/ Shut down the service.\n test_service_->ShutdownAndBlock();\n\n \/\/ Reset to the default.\n base::ThreadRestrictions::SetIOAllowed(true);\n\n \/\/ Stopping a thread is considered an IO operation, so do this after\n \/\/ allowing IO.\n test_service_->Stop();\n }\n\n protected:\n \/\/ Calls the method asynchronously. OnResponse() will be called once the\n \/\/ response is received.\n void CallMethod(dbus::MethodCall* method_call,\n int timeout_ms) {\n object_proxy_->CallMethod(method_call,\n timeout_ms,\n base::Bind(&EndToEndAsyncTest::OnResponse,\n base::Unretained(this)));\n }\n\n \/\/ Wait for the give number of responses.\n void WaitForResponses(size_t num_responses) {\n while (response_strings_.size() < num_responses) {\n message_loop_.Run();\n }\n }\n\n \/\/ Called when the response is received.\n void OnResponse(dbus::Response* response) {\n \/\/ |response| will be deleted on exit of the function. Copy the\n \/\/ payload to |response_strings_|.\n if (response) {\n dbus::MessageReader reader(response);\n std::string response_string;\n ASSERT_TRUE(reader.PopString(&response_string));\n response_strings_.push_back(response_string);\n } else {\n response_strings_.push_back(\"\");\n }\n message_loop_.Quit();\n };\n\n \/\/ Called when the \"Test\" signal is received, in the main thread.\n \/\/ Copy the string payload to |test_signal_string_|.\n void OnTestSignal(dbus::Signal* signal) {\n dbus::MessageReader reader(signal);\n ASSERT_TRUE(reader.PopString(&test_signal_string_));\n message_loop_.Quit();\n }\n\n \/\/ Called when the \"Test2\" signal is received, in the main thread.\n void OnTest2Signal(dbus::Signal* signal) {\n dbus::MessageReader reader(signal);\n message_loop_.Quit();\n }\n\n \/\/ Called when connected to the signal.\n void OnConnected(const std::string& interface_name,\n const std::string& signal_name,\n bool success) {\n ASSERT_TRUE(success);\n message_loop_.Quit();\n }\n\n \/\/ Wait for the hey signal to be received.\n void WaitForTestSignal() {\n \/\/ OnTestSignal() will quit the message loop.\n message_loop_.Run();\n }\n\n MessageLoop message_loop_;\n std::vector response_strings_;\n scoped_ptr dbus_thread_;\n scoped_refptr bus_;\n dbus::ObjectProxy* object_proxy_;\n scoped_ptr test_service_;\n \/\/ Text message from \"Test\" signal.\n std::string test_signal_string_;\n};\n\nTEST_F(EndToEndAsyncTest, Echo) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n\n \/\/ Check the response.\n WaitForResponses(1);\n EXPECT_EQ(kHello, response_strings_[0]);\n}\n\n\/\/ Call Echo method three times.\nTEST_F(EndToEndAsyncTest, EchoThreeTimes) {\n const char* kMessages[] = { \"foo\", \"bar\", \"baz\" };\n\n for (size_t i = 0; i < arraysize(kMessages); ++i) {\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kMessages[i]);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n }\n\n \/\/ Check the responses.\n WaitForResponses(3);\n \/\/ Sort as the order of the returned messages is not deterministic.\n std::sort(response_strings_.begin(), response_strings_.end());\n EXPECT_EQ(\"bar\", response_strings_[0]);\n EXPECT_EQ(\"baz\", response_strings_[1]);\n EXPECT_EQ(\"foo\", response_strings_[2]);\n}\n\nTEST_F(EndToEndAsyncTest, Timeout) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"SlowEcho\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method with timeout of 0ms.\n const int timeout_ms = 0;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because of timeout.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\n\/\/ Tests calling a method that sends its reply asynchronously.\nTEST_F(EndToEndAsyncTest, AsyncEcho) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"AsyncEcho\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n\n \/\/ Check the response.\n WaitForResponses(1);\n EXPECT_EQ(kHello, response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, NonexistentMethod) {\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Nonexistent\");\n\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because the method is nonexistent.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, BrokenMethod) {\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"BrokenMethod\");\n\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n CallMethod(&method_call, timeout_ms);\n WaitForResponses(1);\n\n \/\/ Should fail because the method is broken.\n ASSERT_EQ(\"\", response_strings_[0]);\n}\n\nTEST_F(EndToEndAsyncTest, EmptyResponseCallback) {\n const char* kHello = \"hello\";\n\n \/\/ Create the method call.\n dbus::MethodCall method_call(\"org.chromium.TestInterface\", \"Echo\");\n dbus::MessageWriter writer(&method_call);\n writer.AppendString(kHello);\n\n \/\/ Call the method with an empty callback.\n const int timeout_ms = dbus::ObjectProxy::TIMEOUT_USE_DEFAULT;\n object_proxy_->CallMethod(&method_call,\n timeout_ms,\n dbus::ObjectProxy::EmptyResponseCallback());\n \/\/ Post a delayed task to quit the message loop.\n message_loop_.PostDelayedTask(FROM_HERE,\n MessageLoop::QuitClosure(),\n TestTimeouts::tiny_timeout_ms());\n message_loop_.Run();\n \/\/ We cannot tell if the empty callback is called, but at least we can\n \/\/ check if the test does not crash.\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/107301\nTEST_F(EndToEndAsyncTest, FLAKY_TestSignal) {\n const char kMessage[] = \"hello, world\";\n \/\/ Send the test signal from the exported object.\n test_service_->SendTestSignal(kMessage);\n \/\/ Receive the signal with the object proxy. The signal is handled in\n \/\/ EndToEndAsyncTest::OnTestSignal() in the main thread.\n WaitForTestSignal();\n ASSERT_EQ(kMessage, test_signal_string_);\n}\n\n\/\/ Flaky, http:\/\/crbug.com\/106796\nTEST_F(EndToEndAsyncTest, FLAKY_TestSignalFromRoot) {\n const char kMessage[] = \"hello, world\";\n \/\/ Send the test signal from the root object path, to see if we can\n \/\/ handle signals sent from \"\/\", like dbus-send does.\n test_service_->SendTestSignalFromRoot(kMessage);\n \/\/ Receive the signal with the object proxy. The signal is handled in\n \/\/ EndToEndAsyncTest::OnTestSignal() in the main thread.\n WaitForTestSignal();\n ASSERT_EQ(kMessage, test_signal_string_);\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"CompressIndices.h\"\n\n#include \n#include \n#include \n\n#include \"Magnum\/Math\/Functions.h\"\n\nnamespace Magnum { namespace MeshTools {\n\nnamespace {\n\ntemplate inline Containers::Array compress(const std::vector& indices) {\n Containers::Array buffer(indices.size()*sizeof(T));\n for(std::size_t i = 0; i != indices.size(); ++i) {\n T index = static_cast(indices[i]);\n std::memcpy(buffer.begin()+i*sizeof(T), &index, sizeof(T));\n }\n\n return buffer;\n}\n\n}\n\nstd::tuple, Mesh::IndexType, UnsignedInt, UnsignedInt> compressIndices(const std::vector& indices) {\n \/** @todo Performance hint when range can be represented by smaller value? *\/\n const auto minmax = std::minmax_element(indices.begin(), indices.end());\n Containers::Array data;\n Mesh::IndexType type;\n switch(Math::log(256, *minmax.second)) {\n case 0:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedByte;\n break;\n case 1:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedShort;\n break;\n case 2:\n case 3:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedInt;\n break;\n\n default:\n CORRADE_ASSERT(false, \"MeshTools::compressIndices(): no type able to index\" << *minmax.second << \"elements.\", {});\n }\n\n return std::make_tuple(std::move(data), type, *minmax.first, *minmax.second);\n}\n\ntemplate Containers::Array compressIndicesAs(const std::vector& indices) {\n #if !defined(CORRADE_NO_ASSERT) || defined(CORRADE_GRACEFUL_ASSERT)\n const auto max = std::max_element(indices.begin(), indices.end());\n CORRADE_ASSERT(Math::log(256, *max) < sizeof(T), \"MeshTools::compressIndicesAs(): type too small to represent value\" << *max, {});\n #endif\n\n Containers::Array buffer(indices.size());\n for(std::size_t i = 0; i != indices.size(); ++i)\n buffer[i] = indices[i];\n\n return buffer;\n}\n\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\n\n}}\nMeshTools: silence conversion warning on MSVC.\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"CompressIndices.h\"\n\n#include \n#include \n#include \n\n#include \"Magnum\/Math\/Functions.h\"\n\nnamespace Magnum { namespace MeshTools {\n\nnamespace {\n\ntemplate inline Containers::Array compress(const std::vector& indices) {\n Containers::Array buffer(indices.size()*sizeof(T));\n for(std::size_t i = 0; i != indices.size(); ++i) {\n T index = static_cast(indices[i]);\n std::memcpy(buffer.begin()+i*sizeof(T), &index, sizeof(T));\n }\n\n return buffer;\n}\n\n}\n\nstd::tuple, Mesh::IndexType, UnsignedInt, UnsignedInt> compressIndices(const std::vector& indices) {\n \/** @todo Performance hint when range can be represented by smaller value? *\/\n const auto minmax = std::minmax_element(indices.begin(), indices.end());\n Containers::Array data;\n Mesh::IndexType type;\n switch(Math::log(256, *minmax.second)) {\n case 0:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedByte;\n break;\n case 1:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedShort;\n break;\n case 2:\n case 3:\n data = compress(indices);\n type = Mesh::IndexType::UnsignedInt;\n break;\n\n default:\n CORRADE_ASSERT(false, \"MeshTools::compressIndices(): no type able to index\" << *minmax.second << \"elements.\", {});\n }\n\n return std::make_tuple(std::move(data), type, *minmax.first, *minmax.second);\n}\n\ntemplate Containers::Array compressIndicesAs(const std::vector& indices) {\n #if !defined(CORRADE_NO_ASSERT) || defined(CORRADE_GRACEFUL_ASSERT)\n const auto max = std::max_element(indices.begin(), indices.end());\n CORRADE_ASSERT(Math::log(256, *max) < sizeof(T), \"MeshTools::compressIndicesAs(): type too small to represent value\" << *max, {});\n #endif\n\n Containers::Array buffer(indices.size());\n for(std::size_t i = 0; i != indices.size(); ++i)\n buffer[i] = T(indices[i]);\n\n return buffer;\n}\n\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\ntemplate Containers::Array compressIndicesAs(const std::vector& indices);\n\n}}\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n* @file main.cpp\n* @author Lorenz Esch ;\n* Matti Hamalainen \n* @version 1.0\n* @date April, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Lorenz Esch and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Example of using the MNE-CPP Connectivity library\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace CONNECTIVITYLIB;\nusing namespace Eigen;\nusing namespace UTILSLIB;\nusing namespace MNELIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Global Defines\n\/\/=============================================================================================================\n\nQString m_sCurrentDir;\nint m_iCurrentIteration = 0;\nint m_iNumberTrials;\nint m_iNumberChannels;\nint m_iNumberSamples;\n\nvoid customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)\n{\n Q_UNUSED(context);\n\n QString dt = QDateTime::currentDateTime().toString(\"dd\/MM\/yyyy hh:mm:ss\");\n QString txt;\/\/ = QString(\"[%1] \").arg(dt);\n\n bool writeToLog = false;\n\n switch (type) {\n case QtWarningMsg:\n \/\/txt += QString(\"{Warning} \\t %1\").arg(msg);\n txt += QString(\"%1\").arg(msg);\n writeToLog=true;\n break;\n }\n\n if(!writeToLog) {\n return;\n }\n\n QString sFileName = m_sCurrentDir + \"\/\" + QString::number(m_iNumberChannels) + \"_\" + QString::number(m_iNumberSamples) + \"_\" + QString::number(m_iNumberTrials) + \".log\";\n\n QFile outFile(sFileName);\n outFile.open(QIODevice::WriteOnly | QIODevice::Append);\n\n QTextStream textStream(&outFile);\n textStream << txt << endl;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\n\/\/=============================================================================================================\n\/**\n* The function main marks the entry point of the program.\n* By default, main has the storage class extern.\n*\n* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n* @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n*\/\nint main(int argc, char *argv[])\n{\n qInstallMessageHandler(customMessageHandler);\n\n\/\/ printf(\"globalInstance()->maxThreadCount(): %d\\n\",QThreadPool::globalInstance()->maxThreadCount());\n\/\/ QThreadPool::globalInstance()->setMaxThreadCount(24);\n\n \/\/Parameters for performance test\n QStringList sConnectivityMethodList = QStringList() << \"COR\" << \"XCOR\" << \"COH\" << \"IMAGCOH\" << \"PLI\" << \"WPLI\" << \"USPLI\" << \"DSWPLI\" << \"PLV\";\n QList lNumberTrials = QList() << 1 << 5 << 10 << 20 << 50 << 100 << 200;\n QList lNumberChannels = QList() << 32 << 64 << 128 << 256;\n QList lNumberSamples = QList() << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800 << 900 << 1000 << 2000 << 3000 << 4000 << 5000 << 6000 << 7000 << 8000 << 9000 << 10000 << 20000 << 30000 << 40000 << 50000 << 60000 << 70000 << 80000 << 90000 << 100000;\n\n int iNumberRepeats = 5;\n int iStorageModeActive = 0;\n\n AbstractMetric::m_bStorageModeIsActive = iStorageModeActive;\n AbstractMetric::m_iNumberBinStart = 8;\n AbstractMetric::m_iNumberBinAmount = 4;\n\n \/\/ Create sensor level data\n QElapsedTimer timer;\n qint64 iTime = 0;\n timer.start();\n\n QString sRaw = \"\/cluster\/fusion\/lesch\/Git\/mne-cpp-lorenze\/bin\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw.fif\";\n MatrixXd matDataOrig, matData;\n MatrixXd times;\n QFile t_fileRaw(sRaw);\n FiffRawData raw(t_fileRaw);\n\n raw.read_raw_segment(matDataOrig, times, raw.first_samp, raw.first_samp+100001);\n\n \/\/Perform connectivity performance tests\n Connectivity connectivityObj;\n\n ConnectivitySettings connectivitySettings;\n connectivitySettings.setSamplingFrequency(raw.info.sfreq);\n connectivitySettings.setWindowType(\"hanning\");\n\n QMap > matInputData;\n\n for(int j = 0; j < lNumberChannels.size(); ++j) {\n QMap mapChannelsSamples;\n\n for(int i = 0; i < lNumberSamples.size(); ++i) {\n mapChannelsSamples[lNumberSamples.at(i)] = matDataOrig.block(0,0,lNumberChannels.at(j), lNumberSamples.at(i));\n }\n\n matInputData[lNumberChannels.at(j)] = mapChannelsSamples;\n }\n\n iTime = timer.elapsed();\n printf(\"Prepare data %d\\n\", iTime);\n timer.restart();\n\n qWarning() << \"matInputData[256][40000].first().rows()\" << matInputData[256][40000].rows();\n qWarning() << \"matInputData[256][40000].first().cols()\" << matInputData[256][40000].cols();\n qWarning() << \"matInputData[32][500].rows()\" << matInputData[32][500].rows();\n qWarning() << \"matInputData[32][500].cols()\" << matInputData[32][500].cols();\n qWarning() << \"matInputData[64][100000].rows()\" << matInputData[64][100000].rows();\n qWarning() << \"matInputData[64][100000].cols()\" << matInputData[64][100000].cols();\n\n for(int j = 0; j < lNumberSamples.size(); ++j) {\n for(int k = 0; k < lNumberChannels.size(); ++k) {\n connectivitySettings.clearAllData();\n\n matData = matInputData[lNumberChannels.at(k)][lNumberSamples.at(j)];\n\n RowVectorXi picks = RowVectorXi::LinSpaced(lNumberChannels.at(k),1,lNumberChannels.at(k)+1);\n connectivitySettings.setNodePositions(raw.info, picks);\n\n for(int l = 0; l < lNumberTrials.size(); ++l) {\n \/\/Create data to work on\n\n while(connectivitySettings.size() < lNumberTrials.at(l)) {\n connectivitySettings.append(matData);\n }\n\n for(int i = 0; i < sConnectivityMethodList.size(); ++i) {\n m_iNumberTrials = lNumberTrials.at(l);\n m_iNumberChannels = lNumberChannels.at(k);\n m_iNumberSamples = lNumberSamples.at(j);\n\n \/\/Create new folder\n m_sCurrentDir = QString(\"\/cluster\/fusion\/lesch\/connectivity_performance_%1_%2_%3\/%4\/%5_%6_%7\").arg(QHostInfo::localHostName()).arg(AbstractMetric::m_iNumberBinAmount).arg(iStorageModeActive).arg(sConnectivityMethodList.at(i)).arg(QString::number(lNumberChannels.at(k))).arg(QString::number(lNumberSamples.at(j))).arg(QString::number(lNumberTrials.at(l)));\n QDir().mkpath(m_sCurrentDir);\n\n \/\/Write basic information to file\n qWarning() << \"sConnectivityMethod\" << sConnectivityMethodList.at(i);\n qWarning() << \"sRaw\" << sRaw;\n qWarning() << \"storageModeActive\" << iStorageModeActive;\n qWarning() << \"iNumberSamples\" << lNumberSamples.at(j);\n qWarning() << \"iNumberChannels\" << lNumberChannels.at(k);\n qWarning() << \"iNumberTrials\" << lNumberTrials.at(l);\n qWarning() << \"iNumberCSDFreqBins\" << AbstractMetric::m_iNumberBinAmount;\n qWarning() << \"rows\" << matData.rows();\n qWarning() << \"cols\" << matData.cols();\n qWarning() << \"numberNodes\" << connectivitySettings.getNodePositions().rows();\n\n \/\/ Check that iNfft >= signal length\n int iSignalLength = lNumberSamples.at(j);\n int iNfft = int(raw.info.sfreq\/1.0);\n if(iNfft > iSignalLength) {\n iNfft = iSignalLength;\n }\n\n qWarning() << \"iNfft\" << iNfft;\n\n int iNFreqs = int(floor(iNfft \/ 2.0)) + 1;\n qWarning() << \"iNFreqs\" << iNFreqs;\n\n connectivitySettings.setConnectivityMethods(QStringList() << sConnectivityMethodList.at(i));\n\n m_iCurrentIteration = 0;\n for(int u = 0; u < iNumberRepeats; ++u) {\n connectivitySettings.clearIntermediateData();\n\n qWarning() << \"iteration\" << m_iCurrentIteration;\n\n \/\/Do connectivity estimation\n connectivityObj.calculate(connectivitySettings);\n\n printf(\"Iteration %d: Calculating %s for %d trials, %d channels, %d samples\\n\", m_iCurrentIteration, sConnectivityMethodList.at(i).toLatin1().data(), connectivitySettings.size(), lNumberChannels.at(k), lNumberSamples.at(j));\n\n m_iCurrentIteration++;\n }\n }\n }\n }\n }\n\n return 0;\n}\nchanged printf to qDebug for var of type long long\/\/=============================================================================================================\n\/**\n* @file main.cpp\n* @author Lorenz Esch ;\n* Matti Hamalainen \n* @version 1.0\n* @date April, 2019\n*\n* @section LICENSE\n*\n* Copyright (C) 2019, Lorenz Esch and Matti Hamalainen. All rights reserved.\n*\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n* the following conditions are met:\n* * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n* following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n* the following disclaimer in the documentation and\/or other materials provided with the distribution.\n* * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n* to endorse or promote products derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n* POSSIBILITY OF SUCH DAMAGE.\n*\n*\n* @brief Example of using the MNE-CPP Connectivity library\n*\n*\/\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace Eigen;\nusing namespace FIFFLIB;\nusing namespace CONNECTIVITYLIB;\nusing namespace Eigen;\nusing namespace UTILSLIB;\nusing namespace MNELIB;\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ Global Defines\n\/\/=============================================================================================================\n\nQString m_sCurrentDir;\nint m_iCurrentIteration = 0;\nint m_iNumberTrials;\nint m_iNumberChannels;\nint m_iNumberSamples;\n\nvoid customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)\n{\n Q_UNUSED(context);\n\n QString dt = QDateTime::currentDateTime().toString(\"dd\/MM\/yyyy hh:mm:ss\");\n QString txt;\/\/ = QString(\"[%1] \").arg(dt);\n\n bool writeToLog = false;\n\n switch (type) {\n case QtWarningMsg:\n \/\/txt += QString(\"{Warning} \\t %1\").arg(msg);\n txt += QString(\"%1\").arg(msg);\n writeToLog=true;\n break;\n }\n\n if(!writeToLog) {\n return;\n }\n\n QString sFileName = m_sCurrentDir + \"\/\" + QString::number(m_iNumberChannels) + \"_\" + QString::number(m_iNumberSamples) + \"_\" + QString::number(m_iNumberTrials) + \".log\";\n\n QFile outFile(sFileName);\n outFile.open(QIODevice::WriteOnly | QIODevice::Append);\n\n QTextStream textStream(&outFile);\n textStream << txt << endl;\n}\n\n\n\/\/*************************************************************************************************************\n\/\/=============================================================================================================\n\/\/ MAIN\n\/\/=============================================================================================================\n\n\n\/\/=============================================================================================================\n\/**\n* The function main marks the entry point of the program.\n* By default, main has the storage class extern.\n*\n* @param [in] argc (argument count) is an integer that indicates how many arguments were entered on the command line when the program was started.\n* @param [in] argv (argument vector) is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.\n* @return the value that was set to exit() (which is 0 if exit() is called via quit()).\n*\/\nint main(int argc, char *argv[])\n{\n qInstallMessageHandler(customMessageHandler);\n\n\/\/ printf(\"globalInstance()->maxThreadCount(): %d\\n\",QThreadPool::globalInstance()->maxThreadCount());\n\/\/ QThreadPool::globalInstance()->setMaxThreadCount(24);\n\n \/\/Parameters for performance test\n QStringList sConnectivityMethodList = QStringList() << \"COR\" << \"XCOR\" << \"COH\" << \"IMAGCOH\" << \"PLI\" << \"WPLI\" << \"USPLI\" << \"DSWPLI\" << \"PLV\";\n QList lNumberTrials = QList() << 1 << 5 << 10 << 20 << 50 << 100 << 200;\n QList lNumberChannels = QList() << 32 << 64 << 128 << 256;\n QList lNumberSamples = QList() << 100 << 200 << 300 << 400 << 500 << 600 << 700 << 800 << 900 << 1000 << 2000 << 3000 << 4000 << 5000 << 6000 << 7000 << 8000 << 9000 << 10000 << 20000 << 30000 << 40000 << 50000 << 60000 << 70000 << 80000 << 90000 << 100000;\n\n int iNumberRepeats = 5;\n int iStorageModeActive = 0;\n\n AbstractMetric::m_bStorageModeIsActive = iStorageModeActive;\n AbstractMetric::m_iNumberBinStart = 8;\n AbstractMetric::m_iNumberBinAmount = 4;\n\n \/\/ Create sensor level data\n QElapsedTimer timer;\n qint64 iTime = 0;\n timer.start();\n\n QString sRaw = \"\/cluster\/fusion\/lesch\/Git\/mne-cpp-lorenze\/bin\/MNE-sample-data\/MEG\/sample\/sample_audvis_raw.fif\";\n MatrixXd matDataOrig, matData;\n MatrixXd times;\n QFile t_fileRaw(sRaw);\n FiffRawData raw(t_fileRaw);\n\n raw.read_raw_segment(matDataOrig, times, raw.first_samp, raw.first_samp+100001);\n\n \/\/Perform connectivity performance tests\n Connectivity connectivityObj;\n\n ConnectivitySettings connectivitySettings;\n connectivitySettings.setSamplingFrequency(raw.info.sfreq);\n connectivitySettings.setWindowType(\"hanning\");\n\n QMap > matInputData;\n\n for(int j = 0; j < lNumberChannels.size(); ++j) {\n QMap mapChannelsSamples;\n\n for(int i = 0; i < lNumberSamples.size(); ++i) {\n mapChannelsSamples[lNumberSamples.at(i)] = matDataOrig.block(0,0,lNumberChannels.at(j), lNumberSamples.at(i));\n }\n\n matInputData[lNumberChannels.at(j)] = mapChannelsSamples;\n }\n\n iTime = timer.elapsed();\n qDebug() << \"Prepare data \" << iTime;\n timer.restart();\n\n qWarning() << \"matInputData[256][40000].first().rows()\" << matInputData[256][40000].rows();\n qWarning() << \"matInputData[256][40000].first().cols()\" << matInputData[256][40000].cols();\n qWarning() << \"matInputData[32][500].rows()\" << matInputData[32][500].rows();\n qWarning() << \"matInputData[32][500].cols()\" << matInputData[32][500].cols();\n qWarning() << \"matInputData[64][100000].rows()\" << matInputData[64][100000].rows();\n qWarning() << \"matInputData[64][100000].cols()\" << matInputData[64][100000].cols();\n\n for(int j = 0; j < lNumberSamples.size(); ++j) {\n for(int k = 0; k < lNumberChannels.size(); ++k) {\n connectivitySettings.clearAllData();\n\n matData = matInputData[lNumberChannels.at(k)][lNumberSamples.at(j)];\n\n RowVectorXi picks = RowVectorXi::LinSpaced(lNumberChannels.at(k),1,lNumberChannels.at(k)+1);\n connectivitySettings.setNodePositions(raw.info, picks);\n\n for(int l = 0; l < lNumberTrials.size(); ++l) {\n \/\/Create data to work on\n\n while(connectivitySettings.size() < lNumberTrials.at(l)) {\n connectivitySettings.append(matData);\n }\n\n for(int i = 0; i < sConnectivityMethodList.size(); ++i) {\n m_iNumberTrials = lNumberTrials.at(l);\n m_iNumberChannels = lNumberChannels.at(k);\n m_iNumberSamples = lNumberSamples.at(j);\n\n \/\/Create new folder\n m_sCurrentDir = QString(\"\/cluster\/fusion\/lesch\/connectivity_performance_%1_%2_%3\/%4\/%5_%6_%7\").arg(QHostInfo::localHostName()).arg(AbstractMetric::m_iNumberBinAmount).arg(iStorageModeActive).arg(sConnectivityMethodList.at(i)).arg(QString::number(lNumberChannels.at(k))).arg(QString::number(lNumberSamples.at(j))).arg(QString::number(lNumberTrials.at(l)));\n QDir().mkpath(m_sCurrentDir);\n\n \/\/Write basic information to file\n qWarning() << \"sConnectivityMethod\" << sConnectivityMethodList.at(i);\n qWarning() << \"sRaw\" << sRaw;\n qWarning() << \"storageModeActive\" << iStorageModeActive;\n qWarning() << \"iNumberSamples\" << lNumberSamples.at(j);\n qWarning() << \"iNumberChannels\" << lNumberChannels.at(k);\n qWarning() << \"iNumberTrials\" << lNumberTrials.at(l);\n qWarning() << \"iNumberCSDFreqBins\" << AbstractMetric::m_iNumberBinAmount;\n qWarning() << \"rows\" << matData.rows();\n qWarning() << \"cols\" << matData.cols();\n qWarning() << \"numberNodes\" << connectivitySettings.getNodePositions().rows();\n\n \/\/ Check that iNfft >= signal length\n int iSignalLength = lNumberSamples.at(j);\n int iNfft = int(raw.info.sfreq\/1.0);\n if(iNfft > iSignalLength) {\n iNfft = iSignalLength;\n }\n\n qWarning() << \"iNfft\" << iNfft;\n\n int iNFreqs = int(floor(iNfft \/ 2.0)) + 1;\n qWarning() << \"iNFreqs\" << iNFreqs;\n\n connectivitySettings.setConnectivityMethods(QStringList() << sConnectivityMethodList.at(i));\n\n m_iCurrentIteration = 0;\n for(int u = 0; u < iNumberRepeats; ++u) {\n connectivitySettings.clearIntermediateData();\n\n qWarning() << \"iteration\" << m_iCurrentIteration;\n\n \/\/Do connectivity estimation\n connectivityObj.calculate(connectivitySettings);\n\n printf(\"Iteration %d: Calculating %s for %d trials, %d channels, %d samples\\n\", m_iCurrentIteration, sConnectivityMethodList.at(i).toLatin1().data(), connectivitySettings.size(), lNumberChannels.at(k), lNumberSamples.at(j));\n\n m_iCurrentIteration++;\n }\n }\n }\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * [ Copyright (C) 2011 August Sodora (initial developer) ]\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \"baside2.hxx\"\n#include \"linenumberwindow.hxx\"\n\n#include \n#include \n\nnamespace basctl\n{\n\nLineNumberWindow::LineNumberWindow (Window* pParent, ModulWindow* pModulWindow) :\n Window(pParent, WB_BORDER),\n m_pModulWindow(pModulWindow),\n m_nCurYOffset(0)\n{\n SetBackground(Wallpaper(GetSettings().GetStyleSettings().GetFieldColor()));\n m_nBaseWidth = GetTextWidth('8');\n m_nWidth = m_nBaseWidth * 3 + m_nBaseWidth \/ 2;\n}\n\nLineNumberWindow::~LineNumberWindow()\n{ }\n\nvoid LineNumberWindow::Paint( const Rectangle& )\n{\n if(SyncYOffset())\n return;\n\n ExtTextEngine* txtEngine = m_pModulWindow->GetEditEngine();\n if(!txtEngine)\n return;\n\n TextView* txtView = m_pModulWindow->GetEditView();\n if(!txtView)\n return;\n\n GetParent()->Resize();\n\n int windowHeight = GetOutputSize().Height();\n int nLineHeight = GetTextHeight();\n\n int startY = txtView->GetStartDocPos().Y();\n int nStartLine = startY \/ nLineHeight + 1;\n int nEndLine = (startY + windowHeight) \/ nLineHeight + 1;\n\n if(txtEngine->GetParagraphCount() + 1 < (unsigned int)nEndLine)\n nEndLine = txtEngine->GetParagraphCount() + 1;\n\n \/\/ FIXME: it would be best if we could get notified of a font change\n \/\/ rather than doing that re-calculation at each Paint event\n m_nBaseWidth = GetTextWidth(OUString('8'));\n\n \/\/ reserve enough for 3 sigit minimum, with a bit to spare for confort\n m_nWidth = m_nBaseWidth * 3 + m_nBaseWidth \/ 2;\n int i = (nEndLine + 1) \/ 1000;\n while(i)\n {\n i \/= 10;\n m_nWidth += m_nBaseWidth;\n }\n\n sal_Int64 y = (nStartLine - 1) * nLineHeight;\n for(sal_Int32 n = nStartLine; n <= nEndLine; ++n, y += nLineHeight)\n DrawText(Point(0, y - m_nCurYOffset), OUString::valueOf(n));\n}\n\nvoid LineNumberWindow::DataChanged(DataChangedEvent const & rDCEvt)\n{\n Window::DataChanged(rDCEvt);\n if (rDCEvt.GetType() == DATACHANGED_SETTINGS\n && (rDCEvt.GetFlags() & SETTINGS_STYLE) != 0)\n {\n Color aColor(GetSettings().GetStyleSettings().GetFieldColor());\n const AllSettings* pOldSettings = rDCEvt.GetOldSettings();\n if (!pOldSettings || aColor != pOldSettings->GetStyleSettings().GetFieldColor())\n {\n SetBackground(Wallpaper(aColor));\n Invalidate();\n }\n }\n}\n\nvoid LineNumberWindow::DoScroll(long nHorzScroll, long nVertScroll)\n{\n m_nCurYOffset -= nVertScroll;\n Window::Scroll(nHorzScroll, nVertScroll);\n}\n\nlong& LineNumberWindow::GetCurYOffset()\n{\n return m_nCurYOffset;\n}\n\nbool LineNumberWindow::SyncYOffset()\n{\n TextView* pView = m_pModulWindow->GetEditView();\n if (!pView)\n return false;\n\n long nViewYOffset = pView->GetStartDocPos().Y();\n if (m_nCurYOffset == nViewYOffset)\n return false;\n\n m_nCurYOffset = nViewYOffset;\n Invalidate();\n return true;\n}\n\nint LineNumberWindow::GetWidth()\n{\n return m_nWidth;\n}\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\ncoverity#735601 coverity#736164\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * Version: MPL 1.1 \/ GPLv3+ \/ LGPLv3+\n *\n * The contents of this file are subject to the Mozilla Public License Version\n * 1.1 (the \"License\"); you may not use this file except in compliance with\n * the License or as specified alternatively below. You may obtain a copy of\n * the License at http:\/\/www.mozilla.org\/MPL\/\n *\n * Software distributed under the License is distributed on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License\n * for the specific language governing rights and limitations under the\n * License.\n *\n * Major Contributor(s):\n * [ Copyright (C) 2011 August Sodora (initial developer) ]\n *\n * All Rights Reserved.\n *\n * For minor contributions see the git repository.\n *\n * Alternatively, the contents of this file may be used under the terms of\n * either the GNU General Public License Version 3 or later (the \"GPLv3+\"), or\n * the GNU Lesser General Public License Version 3 or later (the \"LGPLv3+\"),\n * in which case the provisions of the GPLv3+ or the LGPLv3+ are applicable\n * instead of those above.\n *\/\n\n#include \"baside2.hxx\"\n#include \"linenumberwindow.hxx\"\n\n#include \n#include \n\nnamespace basctl\n{\n\nLineNumberWindow::LineNumberWindow (Window* pParent, ModulWindow* pModulWindow) :\n Window(pParent, WB_BORDER),\n m_pModulWindow(pModulWindow),\n m_nCurYOffset(0)\n{\n SetBackground(Wallpaper(GetSettings().GetStyleSettings().GetFieldColor()));\n m_nBaseWidth = GetTextWidth('8');\n m_nWidth = m_nBaseWidth * 3 + m_nBaseWidth \/ 2;\n}\n\nLineNumberWindow::~LineNumberWindow()\n{ }\n\nvoid LineNumberWindow::Paint( const Rectangle& )\n{\n if(SyncYOffset())\n return;\n\n ExtTextEngine* txtEngine = m_pModulWindow->GetEditEngine();\n if(!txtEngine)\n return;\n\n TextView* txtView = m_pModulWindow->GetEditView();\n if(!txtView)\n return;\n\n GetParent()->Resize();\n\n int windowHeight = GetOutputSize().Height();\n int nLineHeight = GetTextHeight();\n if(!nLineHeight)\n {\n return;\n }\n\n int startY = txtView->GetStartDocPos().Y();\n int nStartLine = startY \/ nLineHeight + 1;\n int nEndLine = (startY + windowHeight) \/ nLineHeight + 1;\n\n if(txtEngine->GetParagraphCount() + 1 < (unsigned int)nEndLine)\n nEndLine = txtEngine->GetParagraphCount() + 1;\n\n \/\/ FIXME: it would be best if we could get notified of a font change\n \/\/ rather than doing that re-calculation at each Paint event\n m_nBaseWidth = GetTextWidth(OUString('8'));\n\n \/\/ reserve enough for 3 sigit minimum, with a bit to spare for confort\n m_nWidth = m_nBaseWidth * 3 + m_nBaseWidth \/ 2;\n int i = (nEndLine + 1) \/ 1000;\n while(i)\n {\n i \/= 10;\n m_nWidth += m_nBaseWidth;\n }\n\n sal_Int64 y = (nStartLine - 1) * (sal_Int64)nLineHeight;\n for(sal_Int32 n = nStartLine; n <= nEndLine; ++n, y += nLineHeight)\n DrawText(Point(0, y - m_nCurYOffset), OUString::valueOf(n));\n}\n\nvoid LineNumberWindow::DataChanged(DataChangedEvent const & rDCEvt)\n{\n Window::DataChanged(rDCEvt);\n if (rDCEvt.GetType() == DATACHANGED_SETTINGS\n && (rDCEvt.GetFlags() & SETTINGS_STYLE) != 0)\n {\n Color aColor(GetSettings().GetStyleSettings().GetFieldColor());\n const AllSettings* pOldSettings = rDCEvt.GetOldSettings();\n if (!pOldSettings || aColor != pOldSettings->GetStyleSettings().GetFieldColor())\n {\n SetBackground(Wallpaper(aColor));\n Invalidate();\n }\n }\n}\n\nvoid LineNumberWindow::DoScroll(long nHorzScroll, long nVertScroll)\n{\n m_nCurYOffset -= nVertScroll;\n Window::Scroll(nHorzScroll, nVertScroll);\n}\n\nlong& LineNumberWindow::GetCurYOffset()\n{\n return m_nCurYOffset;\n}\n\nbool LineNumberWindow::SyncYOffset()\n{\n TextView* pView = m_pModulWindow->GetEditView();\n if (!pView)\n return false;\n\n long nViewYOffset = pView->GetStartDocPos().Y();\n if (m_nCurYOffset == nViewYOffset)\n return false;\n\n m_nCurYOffset = nViewYOffset;\n Invalidate();\n return true;\n}\n\nint LineNumberWindow::GetWidth()\n{\n return m_nWidth;\n}\n\n} \/\/ namespace basctl\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"Ext2Node.h\"\n#include \"Ext2Filesystem.h\"\n#include \n#include \n\nExt2Node::Ext2Node(uintptr_t inode_num, Inode *pInode, Ext2Filesystem *pFs) :\n m_pInode(pInode), m_InodeNumber(inode_num), m_pExt2Fs(pFs), m_pBlocks(0),\n m_nBlocks(LITTLE_TO_HOST32(pInode->i_blocks)), m_nSize(LITTLE_TO_HOST32(pInode->i_size))\n{\n m_pBlocks = new uint32_t[m_nBlocks];\n memset(m_pBlocks, ~0, sizeof(uint32_t)*m_nBlocks);\n\n for (size_t i = 0; i < 12 && i < m_nBlocks; i++)\n m_pBlocks[i] = LITTLE_TO_HOST32(m_pInode->i_block[i]);\n}\n\nExt2Node::~Ext2Node()\n{\n}\n\nuint64_t Ext2Node::read(uint64_t location, uint64_t size, uintptr_t buffer)\n{\n \/\/ Reads get clamped to the filesize.\n if (location >= m_nSize) return 0;\n if ( (location+size) >= m_nSize) size = m_nSize - location;\n\n if (size == 0) return 0;\n\n \/\/ Special case for symlinks - if we have no blocks but have positive size,\n \/\/ We interpret the i_blocks member as data.\n if (m_pInode->i_blocks == 0 && m_nSize > 0)\n {\n memcpy(reinterpret_cast(buffer+location),\n reinterpret_cast(m_pInode->i_block),\n size);\n return size;\n }\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n size_t nBytes = size;\n uint32_t nBlock = location \/ nBs;\n while (nBytes)\n {\n \/\/ If the current location is block-aligned and we have to read at least a\n \/\/ block in, we can read directly to the buffer.\n if ( (location % nBs) == 0 && nBytes >= nBs )\n {\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n memcpy(reinterpret_cast(buffer),\n reinterpret_cast(buf),\n nBs);\n buffer += nBs;\n location += nBs;\n nBytes -= nBs;\n nBlock++;\n }\n \/\/ Else we have to read in a partial block.\n else\n {\n \/\/ Create a buffer for the block.\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n \/\/ memcpy the relevant block area.\n uintptr_t start = location % nBs;\n uintptr_t size = (start+nBytes >= nBs) ? nBs-start : nBytes;\n memcpy(reinterpret_cast(buffer),\n reinterpret_cast(buf+start),\n size);\n buffer += size;\n location += size;\n nBytes -= size;\n nBlock++;\n }\n }\n\n return size;\n}\n\nuint64_t Ext2Node::write(uint64_t location, uint64_t size, uintptr_t buffer)\n{\n ensureLargeEnough(location+size);\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n size_t nBytes = size;\n uint32_t nBlock = location \/ nBs;\n while (nBytes)\n {\n \/\/ If the current location is block-aligned and we have to write at least a\n \/\/ block out, we can write directly to the buffer.\n if ( (location % nBs) == 0 && nBytes >= nBs )\n {\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n memcpy(reinterpret_cast(buf),\n reinterpret_cast(buffer),\n nBs);\n buffer += nBs;\n location += nBs;\n nBytes -= nBs;\n nBlock++;\n }\n \/\/ Else we have to read in a block, partially edit it and write back.\n else\n {\n \/\/ Create a buffer for the block.\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n \/\/ memcpy the relevant block area.\n uintptr_t start = location % nBs;\n uintptr_t size = (start+nBytes >= nBs) ? nBs-start : nBytes;\n memcpy(reinterpret_cast(buf+start),\n reinterpret_cast(buffer), size);\n buffer += size;\n location += size;\n nBytes -= size;\n nBlock++;\n }\n }\n\n return size;\n}\n\nuintptr_t Ext2Node::readBlock(uint64_t location)\n{\n ensureLargeEnough(location+m_pExt2Fs->m_BlockSize);\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n uint32_t nBlock = location \/ nBs;\n\n ensureBlockLoaded(nBlock);\n return m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n}\n\nvoid Ext2Node::truncate()\n{\n for (size_t i = 0; i < m_nBlocks; i++)\n {\n ensureBlockLoaded(i);\n m_pExt2Fs->releaseBlock(m_pBlocks[i]);\n }\n\n m_nSize = 0;\n m_nBlocks = 0;\n \n m_pInode->i_size = 0;\n m_pInode->i_blocks = 0;\n}\n\nbool Ext2Node::ensureLargeEnough(size_t size)\n{\n if (size > m_nSize)\n {\n m_nSize = size;\n fileAttributeChanged(m_nSize, LITTLE_TO_HOST32(m_pInode->i_atime),\n LITTLE_TO_HOST32(m_pInode->i_mtime),\n LITTLE_TO_HOST32(m_pInode->i_ctime));\n }\n\n while (size > m_nBlocks*m_pExt2Fs->m_BlockSize)\n {\n uint32_t block = m_pExt2Fs->findFreeBlock(m_InodeNumber);\n if (block == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n if (!addBlock(block)) return false;\n \/\/ Load the block and zero it.\n uint8_t *pBuffer = reinterpret_cast(m_pExt2Fs->readBlock(block));\n memset(pBuffer, 0, m_pExt2Fs->m_BlockSize);\n }\n return true;\n}\n\nbool Ext2Node::ensureBlockLoaded(size_t nBlock)\n{\n if (nBlock >= m_nBlocks)\n {\n FATAL(\"EXT2: ensureBlockLoaded: Algorithmic error.\");\n }\n if (m_pBlocks[nBlock] == ~0U)\n getBlockNumber(nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumber(size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n assert (nBlock >= 12);\n\n if (nBlock < nPerBlock+12)\n {\n getBlockNumberIndirect(LITTLE_TO_HOST32(m_pInode->i_block[12]), 12, nBlock);\n return true;\n }\n\n if (nBlock < (nPerBlock*nPerBlock)+nPerBlock+12)\n {\n getBlockNumberBiindirect(LITTLE_TO_HOST32(m_pInode->i_block[13]), nPerBlock+12, nBlock);\n return true;\n }\n\n getBlockNumberTriindirect(LITTLE_TO_HOST32(m_pInode->i_block[14]),\n (nPerBlock*nPerBlock)+nPerBlock+12, nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberIndirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n for (size_t i = 0; i < m_pExt2Fs->m_BlockSize\/4 && nBlocks < m_nBlocks; i++)\n {\n m_pBlocks[nBlocks++] = LITTLE_TO_HOST32(buffer[i]);\n }\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberBiindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n \/\/ What indirect block does nBlock exist on?\n size_t nIndirectBlock = (nBlock-nBlocks) \/ nPerBlock;\n\n getBlockNumberIndirect(LITTLE_TO_HOST32(buffer[nIndirectBlock]),\n nBlocks+nIndirectBlock*nPerBlock, nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberTriindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n \/\/ What biindirect block does nBlock exist on?\n size_t nBiBlock = (nBlock-nBlocks) \/ (nPerBlock*nPerBlock);\n\n getBlockNumberBiindirect(LITTLE_TO_HOST32(buffer[nBiBlock]),\n nBlocks+nBiBlock*nPerBlock*nPerBlock, nBlock);\n\n delete [] buffer;\n\n return true;\n}\n\nbool Ext2Node::addBlock(uint32_t blockValue)\n{\n size_t nEntriesPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n \/\/ Calculate whether direct, indirect or tri-indirect addressing is needed.\n if (m_nBlocks < 12)\n {\n \/\/ Direct addressing is possible.\n m_pInode->i_block[m_nBlocks] = HOST_TO_LITTLE32(blockValue);\n }\n else if (m_nBlocks < 12 + nEntriesPerBlock)\n {\n \/\/ Indirect addressing needed.\n\n \/\/ If this is the first indirect block, we need to reserve a new table block.\n if (m_nBlocks == 12)\n {\n m_pInode->i_block[12] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (m_pInode->i_block[12] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Now we can set the block.\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(LITTLE_TO_HOST32(m_pInode->i_block[12])));\n\n buffer[m_nBlocks-12] = HOST_TO_LITTLE32(blockValue);\n }\n else if (m_nBlocks < 12 + nEntriesPerBlock + nEntriesPerBlock*nEntriesPerBlock)\n {\n \/\/ Bi-indirect addressing required.\n\n \/\/ Index from the start of the bi-indirect block (i.e. ignore the 12 direct entries and one indirect block).\n size_t biIdx = m_nBlocks - 12 - nEntriesPerBlock;\n \/\/ Block number inside the bi-indirect table of where to find the indirect block table.\n size_t indirectBlock = biIdx \/ nEntriesPerBlock;\n \/\/ Index inside the indirect block table.\n size_t indirectIdx = biIdx % nEntriesPerBlock;\n\n \/\/ If this is the first bi-indirect block, we need to reserve a bi-indirect table block.\n if (biIdx == 0)\n {\n m_pInode->i_block[13] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (m_pInode->i_block[13] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Now we can safely read the bi-indirect block.\n uint32_t *pBlock = reinterpret_cast(m_pExt2Fs->readBlock(LITTLE_TO_HOST32(m_pInode->i_block[13])));\n\n \/\/ Do we need to start a new indirect block?\n if (indirectIdx == 0)\n {\n pBlock[indirectBlock] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (pBlock[indirectBlock] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Cache this as it gets clobbered by the readBlock call (using the same buffer).\n uint32_t nIndirectBlockNum = LITTLE_TO_HOST32(pBlock[indirectBlock]);\n\n \/\/ Grab the indirect block.\n pBlock = reinterpret_cast(m_pExt2Fs->readBlock(nIndirectBlockNum));\n\n \/\/ Set the correct entry.\n pBlock[indirectIdx] = HOST_TO_LITTLE32(blockValue);\n\n \/\/ Done.\n delete [] pBlock;\n }\n else\n {\n \/\/ Tri-indirect addressing required.\n FATAL(\"EXT2: Tri-indirect addressing required, but not implemented.\");\n return false;\n }\n\n uint32_t *pTmp = new uint32_t[m_nBlocks+1];\n memcpy(pTmp, m_pBlocks, m_nBlocks*4);\n delete [] m_pBlocks;\n m_pBlocks = pTmp;\n m_pBlocks[m_nBlocks] = blockValue;\n\n m_nBlocks++;\n m_pInode->i_blocks = HOST_TO_LITTLE32(m_nBlocks);\n\n return true;\n}\n\nvoid Ext2Node::fileAttributeChanged(size_t size, size_t atime, size_t mtime, size_t ctime)\n{\n \/\/ Reconstruct the inode from the cached fields.\n m_pInode->i_blocks = HOST_TO_LITTLE32(m_nBlocks);\n m_pInode->i_size = HOST_TO_LITTLE32(size); \/\/\/ \\todo 4GB files.\n m_pInode->i_atime = HOST_TO_LITTLE32(atime);\n m_pInode->i_mtime = HOST_TO_LITTLE32(mtime);\n m_pInode->i_ctime = HOST_TO_LITTLE32(ctime);\n}\nCommented a line that caused a assertion failed in SlamAllocator when copying some file on a ext2 volume.\/*\n * Copyright (c) 2008 James Molloy, Jörg Pfähler, Matthew Iselin\n *\n * Permission to use, copy, modify, and distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#include \"Ext2Node.h\"\n#include \"Ext2Filesystem.h\"\n#include \n#include \n\nExt2Node::Ext2Node(uintptr_t inode_num, Inode *pInode, Ext2Filesystem *pFs) :\n m_pInode(pInode), m_InodeNumber(inode_num), m_pExt2Fs(pFs), m_pBlocks(0),\n m_nBlocks(LITTLE_TO_HOST32(pInode->i_blocks)), m_nSize(LITTLE_TO_HOST32(pInode->i_size))\n{\n m_pBlocks = new uint32_t[m_nBlocks];\n memset(m_pBlocks, ~0, sizeof(uint32_t)*m_nBlocks);\n\n for (size_t i = 0; i < 12 && i < m_nBlocks; i++)\n m_pBlocks[i] = LITTLE_TO_HOST32(m_pInode->i_block[i]);\n}\n\nExt2Node::~Ext2Node()\n{\n}\n\nuint64_t Ext2Node::read(uint64_t location, uint64_t size, uintptr_t buffer)\n{\n \/\/ Reads get clamped to the filesize.\n if (location >= m_nSize) return 0;\n if ( (location+size) >= m_nSize) size = m_nSize - location;\n\n if (size == 0) return 0;\n\n \/\/ Special case for symlinks - if we have no blocks but have positive size,\n \/\/ We interpret the i_blocks member as data.\n if (m_pInode->i_blocks == 0 && m_nSize > 0)\n {\n memcpy(reinterpret_cast(buffer+location),\n reinterpret_cast(m_pInode->i_block),\n size);\n return size;\n }\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n size_t nBytes = size;\n uint32_t nBlock = location \/ nBs;\n while (nBytes)\n {\n \/\/ If the current location is block-aligned and we have to read at least a\n \/\/ block in, we can read directly to the buffer.\n if ( (location % nBs) == 0 && nBytes >= nBs )\n {\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n memcpy(reinterpret_cast(buffer),\n reinterpret_cast(buf),\n nBs);\n buffer += nBs;\n location += nBs;\n nBytes -= nBs;\n nBlock++;\n }\n \/\/ Else we have to read in a partial block.\n else\n {\n \/\/ Create a buffer for the block.\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n \/\/ memcpy the relevant block area.\n uintptr_t start = location % nBs;\n uintptr_t size = (start+nBytes >= nBs) ? nBs-start : nBytes;\n memcpy(reinterpret_cast(buffer),\n reinterpret_cast(buf+start),\n size);\n buffer += size;\n location += size;\n nBytes -= size;\n nBlock++;\n }\n }\n\n return size;\n}\n\nuint64_t Ext2Node::write(uint64_t location, uint64_t size, uintptr_t buffer)\n{\n ensureLargeEnough(location+size);\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n size_t nBytes = size;\n uint32_t nBlock = location \/ nBs;\n while (nBytes)\n {\n \/\/ If the current location is block-aligned and we have to write at least a\n \/\/ block out, we can write directly to the buffer.\n if ( (location % nBs) == 0 && nBytes >= nBs )\n {\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n memcpy(reinterpret_cast(buf),\n reinterpret_cast(buffer),\n nBs);\n buffer += nBs;\n location += nBs;\n nBytes -= nBs;\n nBlock++;\n }\n \/\/ Else we have to read in a block, partially edit it and write back.\n else\n {\n \/\/ Create a buffer for the block.\n ensureBlockLoaded(nBlock);\n uintptr_t buf = m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n \/\/ memcpy the relevant block area.\n uintptr_t start = location % nBs;\n uintptr_t size = (start+nBytes >= nBs) ? nBs-start : nBytes;\n memcpy(reinterpret_cast(buf+start),\n reinterpret_cast(buffer), size);\n buffer += size;\n location += size;\n nBytes -= size;\n nBlock++;\n }\n }\n\n return size;\n}\n\nuintptr_t Ext2Node::readBlock(uint64_t location)\n{\n ensureLargeEnough(location+m_pExt2Fs->m_BlockSize);\n\n size_t nBs = m_pExt2Fs->m_BlockSize;\n\n uint32_t nBlock = location \/ nBs;\n\n ensureBlockLoaded(nBlock);\n return m_pExt2Fs->readBlock(m_pBlocks[nBlock]);\n}\n\nvoid Ext2Node::truncate()\n{\n for (size_t i = 0; i < m_nBlocks; i++)\n {\n ensureBlockLoaded(i);\n m_pExt2Fs->releaseBlock(m_pBlocks[i]);\n }\n\n m_nSize = 0;\n m_nBlocks = 0;\n\n m_pInode->i_size = 0;\n m_pInode->i_blocks = 0;\n}\n\nbool Ext2Node::ensureLargeEnough(size_t size)\n{\n if (size > m_nSize)\n {\n m_nSize = size;\n fileAttributeChanged(m_nSize, LITTLE_TO_HOST32(m_pInode->i_atime),\n LITTLE_TO_HOST32(m_pInode->i_mtime),\n LITTLE_TO_HOST32(m_pInode->i_ctime));\n }\n\n while (size > m_nBlocks*m_pExt2Fs->m_BlockSize)\n {\n uint32_t block = m_pExt2Fs->findFreeBlock(m_InodeNumber);\n if (block == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n if (!addBlock(block)) return false;\n \/\/ Load the block and zero it.\n uint8_t *pBuffer = reinterpret_cast(m_pExt2Fs->readBlock(block));\n memset(pBuffer, 0, m_pExt2Fs->m_BlockSize);\n }\n return true;\n}\n\nbool Ext2Node::ensureBlockLoaded(size_t nBlock)\n{\n if (nBlock >= m_nBlocks)\n {\n FATAL(\"EXT2: ensureBlockLoaded: Algorithmic error.\");\n }\n if (m_pBlocks[nBlock] == ~0U)\n getBlockNumber(nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumber(size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n assert (nBlock >= 12);\n\n if (nBlock < nPerBlock+12)\n {\n getBlockNumberIndirect(LITTLE_TO_HOST32(m_pInode->i_block[12]), 12, nBlock);\n return true;\n }\n\n if (nBlock < (nPerBlock*nPerBlock)+nPerBlock+12)\n {\n getBlockNumberBiindirect(LITTLE_TO_HOST32(m_pInode->i_block[13]), nPerBlock+12, nBlock);\n return true;\n }\n\n getBlockNumberTriindirect(LITTLE_TO_HOST32(m_pInode->i_block[14]),\n (nPerBlock*nPerBlock)+nPerBlock+12, nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberIndirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n for (size_t i = 0; i < m_pExt2Fs->m_BlockSize\/4 && nBlocks < m_nBlocks; i++)\n {\n m_pBlocks[nBlocks++] = LITTLE_TO_HOST32(buffer[i]);\n }\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberBiindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n \/\/ What indirect block does nBlock exist on?\n size_t nIndirectBlock = (nBlock-nBlocks) \/ nPerBlock;\n\n getBlockNumberIndirect(LITTLE_TO_HOST32(buffer[nIndirectBlock]),\n nBlocks+nIndirectBlock*nPerBlock, nBlock);\n\n return true;\n}\n\nbool Ext2Node::getBlockNumberTriindirect(uint32_t inode_block, size_t nBlocks, size_t nBlock)\n{\n size_t nPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(inode_block));\n\n \/\/ What biindirect block does nBlock exist on?\n size_t nBiBlock = (nBlock-nBlocks) \/ (nPerBlock*nPerBlock);\n\n getBlockNumberBiindirect(LITTLE_TO_HOST32(buffer[nBiBlock]),\n nBlocks+nBiBlock*nPerBlock*nPerBlock, nBlock);\n\n delete [] buffer;\n\n return true;\n}\n\nbool Ext2Node::addBlock(uint32_t blockValue)\n{\n size_t nEntriesPerBlock = m_pExt2Fs->m_BlockSize\/4;\n\n \/\/ Calculate whether direct, indirect or tri-indirect addressing is needed.\n if (m_nBlocks < 12)\n {\n \/\/ Direct addressing is possible.\n m_pInode->i_block[m_nBlocks] = HOST_TO_LITTLE32(blockValue);\n }\n else if (m_nBlocks < 12 + nEntriesPerBlock)\n {\n \/\/ Indirect addressing needed.\n\n \/\/ If this is the first indirect block, we need to reserve a new table block.\n if (m_nBlocks == 12)\n {\n m_pInode->i_block[12] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (m_pInode->i_block[12] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Now we can set the block.\n uint32_t *buffer = reinterpret_cast(m_pExt2Fs->readBlock(LITTLE_TO_HOST32(m_pInode->i_block[12])));\n\n buffer[m_nBlocks-12] = HOST_TO_LITTLE32(blockValue);\n }\n else if (m_nBlocks < 12 + nEntriesPerBlock + nEntriesPerBlock*nEntriesPerBlock)\n {\n \/\/ Bi-indirect addressing required.\n\n \/\/ Index from the start of the bi-indirect block (i.e. ignore the 12 direct entries and one indirect block).\n size_t biIdx = m_nBlocks - 12 - nEntriesPerBlock;\n \/\/ Block number inside the bi-indirect table of where to find the indirect block table.\n size_t indirectBlock = biIdx \/ nEntriesPerBlock;\n \/\/ Index inside the indirect block table.\n size_t indirectIdx = biIdx % nEntriesPerBlock;\n\n \/\/ If this is the first bi-indirect block, we need to reserve a bi-indirect table block.\n if (biIdx == 0)\n {\n m_pInode->i_block[13] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (m_pInode->i_block[13] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Now we can safely read the bi-indirect block.\n uint32_t *pBlock = reinterpret_cast(m_pExt2Fs->readBlock(LITTLE_TO_HOST32(m_pInode->i_block[13])));\n\n \/\/ Do we need to start a new indirect block?\n if (indirectIdx == 0)\n {\n pBlock[indirectBlock] = HOST_TO_LITTLE32(m_pExt2Fs->findFreeBlock(m_InodeNumber));\n if (pBlock[indirectBlock] == 0)\n {\n \/\/ We had a problem.\n SYSCALL_ERROR(NoSpaceLeftOnDevice);\n return false;\n }\n }\n\n \/\/ Cache this as it gets clobbered by the readBlock call (using the same buffer).\n uint32_t nIndirectBlockNum = LITTLE_TO_HOST32(pBlock[indirectBlock]);\n\n \/\/ Grab the indirect block.\n pBlock = reinterpret_cast(m_pExt2Fs->readBlock(nIndirectBlockNum));\n\n \/\/ Set the correct entry.\n pBlock[indirectIdx] = HOST_TO_LITTLE32(blockValue);\n\n \/\/\/ This causes a assertion failed in SlamAllocator when copying some file on a ext2 volume\n \/\/\/ (eddyb)\n \/\/ Done.\n \/\/delete [] pBlock;\n }\n else\n {\n \/\/ Tri-indirect addressing required.\n FATAL(\"EXT2: Tri-indirect addressing required, but not implemented.\");\n return false;\n }\n\n uint32_t *pTmp = new uint32_t[m_nBlocks+1];\n memcpy(pTmp, m_pBlocks, m_nBlocks*4);\n delete [] m_pBlocks;\n m_pBlocks = pTmp;\n m_pBlocks[m_nBlocks] = blockValue;\n\n m_nBlocks++;\n m_pInode->i_blocks = HOST_TO_LITTLE32(m_nBlocks);\n\n return true;\n}\n\nvoid Ext2Node::fileAttributeChanged(size_t size, size_t atime, size_t mtime, size_t ctime)\n{\n \/\/ Reconstruct the inode from the cached fields.\n m_pInode->i_blocks = HOST_TO_LITTLE32(m_nBlocks);\n m_pInode->i_size = HOST_TO_LITTLE32(size); \/\/\/ \\todo 4GB files.\n m_pInode->i_atime = HOST_TO_LITTLE32(atime);\n m_pInode->i_mtime = HOST_TO_LITTLE32(mtime);\n m_pInode->i_ctime = HOST_TO_LITTLE32(ctime);\n}\n<|endoftext|>"} {"text":"Remove incorrect comment from GetInfoFromDataURL<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tbool IsSupported(const String& extension)\n\t\t{\n\t\t\treturn (extension == \"md2\");\n\t\t}\n\n\t\tTernary Check(Stream& stream, const MeshParams& parameters)\n\t\t{\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeMD2Loader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\tUInt32 magic[2];\n\t\t\tif (stream.Read(&magic[0], 2*sizeof(UInt32)) == 2*sizeof(UInt32))\n\t\t\t{\n\t\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\t\tSwapBytes(&magic[0], sizeof(UInt32));\n\t\t\t\tSwapBytes(&magic[1], sizeof(UInt32));\n\t\t\t\t#endif\n\n\t\t\t\tif (magic[0] == md2Ident && magic[1] == 8)\n\t\t\t\t\treturn Ternary_True;\n\t\t\t}\n\n\t\t\treturn Ternary_False;\n\t\t}\n\n\t\tbool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters)\n\t\t{\n\t\t\tMD2_Header header;\n\t\t\tif (stream.Read(&header, sizeof(MD2_Header)) != sizeof(MD2_Header))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to read header\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tSwapBytes(&header.skinwidth, sizeof(UInt32));\n\t\t\tSwapBytes(&header.skinheight, sizeof(UInt32));\n\t\t\tSwapBytes(&header.framesize, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_skins, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_vertices, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_st, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_tris, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_glcmds, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_frames, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_skins, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_st, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_tris, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_frames, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_glcmds, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_end, sizeof(UInt32));\n\t\t\t#endif\n\n\t\t\tif (stream.GetSize() < header.offset_end)\n\t\t\t{\n\t\t\t\tNazaraError(\"Incomplete MD2 file\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Création du mesh\n\t\t\t\/\/ Le moteur ne supporte plus les animations image-clé, nous ne pouvons charger qu'en statique\n\t\t\tif (!mesh->CreateStatic()) \/\/ Ne devrait jamais échouer\n\t\t\t{\n\t\t\t\tNazaraInternalError(\"Failed to create mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des skins\n\t\t\tif (header.num_skins > 0)\n\t\t\t{\n\t\t\t\tmesh->SetMaterialCount(header.num_skins);\n\t\t\t\tstream.SetCursorPos(header.offset_skins);\n\t\t\t\t{\n\t\t\t\t\tString baseDir = stream.GetDirectory();\n\t\t\t\t\tchar skin[68];\n\t\t\t\t\tfor (unsigned int i = 0; i < header.num_skins; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tstream.Read(skin, 68*sizeof(char));\n\n\t\t\t\t\t\tParameterList matData;\n\t\t\t\t\t\tmatData.SetParameter(MaterialData::FilePath, baseDir + skin);\n\n\t\t\t\t\t\tmesh->SetMaterialData(i, std::move(matData));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des submesh\n\t\t\t\/\/ Actuellement le loader ne charge qu'un submesh\n\t\t\tIndexBufferRef indexBuffer = IndexBuffer::New(false, header.num_tris*3, parameters.storage, BufferUsage_Static);\n\n\t\t\t\/\/\/ Lecture des triangles\n\t\t\tstd::vector triangles(header.num_tris);\n\n\t\t\tstream.SetCursorPos(header.offset_tris);\n\t\t\tstream.Read(&triangles[0], header.num_tris*sizeof(MD2_Triangle));\n\n\t\t\tBufferMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite);\n\t\t\tUInt16* index = static_cast(indexMapper.GetPointer());\n\n\t\t\tfor (unsigned int i = 0; i < header.num_tris; ++i)\n\t\t\t{\n\t\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\t\tSwapBytes(&triangles[i].vertices[0], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[0], sizeof(UInt16));\n\n\t\t\t\tSwapBytes(&triangles[i].vertices[1], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[1], sizeof(UInt16));\n\n\t\t\t\tSwapBytes(&triangles[i].vertices[2], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[2], sizeof(UInt16));\n\t\t\t\t#endif\n\n\t\t\t\t\/\/ On respécifie le triangle dans l'ordre attendu\n\t\t\t\t*index++ = triangles[i].vertices[0];\n\t\t\t\t*index++ = triangles[i].vertices[2];\n\t\t\t\t*index++ = triangles[i].vertices[1];\n\t\t\t}\n\n\t\t\tindexMapper.Unmap();\n\n\t\t\tif (parameters.optimizeIndexBuffers)\n\t\t\t\tindexBuffer->Optimize();\n\n\t\t\t\/\/\/ Lecture des coordonnées de texture\n\t\t\tstd::vector texCoords(header.num_st);\n\n\t\t\tstream.SetCursorPos(header.offset_st);\n\t\t\tstream.Read(&texCoords[0], header.num_st*sizeof(MD2_TexCoord));\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tfor (unsigned int i = 0; i < header.num_st; ++i)\n\t\t\t{\n\t\t\t\tSwapBytes(&texCoords[i].u, sizeof(Int16));\n\t\t\t\tSwapBytes(&texCoords[i].v, sizeof(Int16));\n\t\t\t}\n\t\t\t#endif\n\n\t\t\tVertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), header.num_vertices, parameters.storage, BufferUsage_Static);\n\t\t\tStaticMeshRef subMesh = StaticMesh::New(mesh);\n\t\t\tif (!subMesh->Create(vertexBuffer))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create SubMesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des vertices\n\t\t\tstream.SetCursorPos(header.offset_frames);\n\n\t\t\tstd::unique_ptr vertices(new MD2_Vertex[header.num_vertices]);\n\t\t\tVector3f scale, translate;\n\t\t\tstream.Read(scale, sizeof(Vector3f));\n\t\t\tstream.Read(translate, sizeof(Vector3f));\n\t\t\tstream.Read(nullptr, 16*sizeof(char)); \/\/ Nom de la frame, inutile ici\n\t\t\tstream.Read(vertices.get(), header.num_vertices*sizeof(MD2_Vertex));\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tSwapBytes(&scale.x, sizeof(float));\n\t\t\tSwapBytes(&scale.y, sizeof(float));\n\t\t\tSwapBytes(&scale.z, sizeof(float));\n\n\t\t\tSwapBytes(&translate.x, sizeof(float));\n\t\t\tSwapBytes(&translate.y, sizeof(float));\n\t\t\tSwapBytes(&translate.z, sizeof(float));\n\t\t\t#endif\n\n\t\t\tconstexpr float ScaleAdjust = 1.f \/ 27.8f; \/\/ Make a 50 Quake 2 units character a 1.8 unit long\n\n\t\t\tscale *= ScaleAdjust;\n\t\t\ttranslate *= ScaleAdjust;\n\n\t\t\tBufferMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite);\n\t\t\tMeshVertex* vertex = static_cast(vertexMapper.GetPointer());\n\n\t\t\t\/\/\/ Chargement des coordonnées de texture\n\t\t\tconst unsigned int indexFix[3] = {0, 2, 1}; \/\/ Pour respécifier les indices dans le bon ordre\n\t\t\tfor (unsigned int i = 0; i < header.num_tris; ++i)\n\t\t\t{\n\t\t\t\tfor (unsigned int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tconst unsigned int fixedIndex = indexFix[j];\n\t\t\t\t\tconst MD2_TexCoord& texC = texCoords[triangles[i].texCoords[fixedIndex]];\n\t\t\t\t\tfloat u = static_cast(texC.u) \/ header.skinwidth;\n\t\t\t\t\tfloat v = static_cast(texC.v) \/ header.skinheight;\n\n\t\t\t\t\tvertex[triangles[i].vertices[fixedIndex]].uv.Set(u, (parameters.flipUVs) ? 1.f - v : v);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des positions\n\t\t\t\/\/ Pour que le modèle soit correctement aligné, on génère un quaternion que nous appliquerons à chacune des vertices\n\t\t\tQuaternionf rotationQuat = EulerAnglesf(-90.f, 90.f, 0.f);\n\t\t\tNz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale);\n\t\t\tmatrix *= parameters.matrix;\n\n\t\t\tfor (unsigned int v = 0; v < header.num_vertices; ++v)\n\t\t\t{\n\t\t\t\tconst MD2_Vertex& vert = vertices[v];\n\t\t\t\tVector3f position = matrix * Vector3f(vert.x, vert.y, vert.z);\n\n\t\t\t\tvertex->position = position;\n\t\t\t\tvertex->normal = rotationQuat * md2Normals[vert.n];\n\n\t\t\t\tvertex++;\n\t\t\t}\n\n\t\t\tvertexMapper.Unmap();\n\n\t\t\tsubMesh->SetIndexBuffer(indexBuffer);\n\t\t\tsubMesh->SetMaterialIndex(0);\n\n\t\t\tsubMesh->GenerateAABB();\n\t\t\tsubMesh->GenerateTangents();\n\n\t\t\tmesh->AddSubMesh(subMesh);\n\n\t\t\tif (parameters.center)\n\t\t\t\tmesh->Recenter();\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tnamespace Loaders\n\t{\n\t\tvoid RegisterMD2()\n\t\t{\n\t\t\tMeshLoader::RegisterLoader(IsSupported, Check, Load);\n\t\t}\n\n\t\tvoid UnregisterMD2()\n\t\t{\n\t\t\tMeshLoader::UnregisterLoader(IsSupported, Check, Load);\n\t\t}\n\t}\n}\nUtility\/Formats: Make MD2Loader specify diffuse texture path instead of material filepath\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Engine - Utility module\"\n\/\/ For conditions of distribution and use, see copyright notice in Config.hpp\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace Nz\n{\n\tnamespace\n\t{\n\t\tbool IsSupported(const String& extension)\n\t\t{\n\t\t\treturn (extension == \"md2\");\n\t\t}\n\n\t\tTernary Check(Stream& stream, const MeshParams& parameters)\n\t\t{\n\t\t\tbool skip;\n\t\t\tif (parameters.custom.GetBooleanParameter(\"SkipNativeMD2Loader\", &skip) && skip)\n\t\t\t\treturn Ternary_False;\n\n\t\t\tUInt32 magic[2];\n\t\t\tif (stream.Read(&magic[0], 2*sizeof(UInt32)) == 2*sizeof(UInt32))\n\t\t\t{\n\t\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\t\tSwapBytes(&magic[0], sizeof(UInt32));\n\t\t\t\tSwapBytes(&magic[1], sizeof(UInt32));\n\t\t\t\t#endif\n\n\t\t\t\tif (magic[0] == md2Ident && magic[1] == 8)\n\t\t\t\t\treturn Ternary_True;\n\t\t\t}\n\n\t\t\treturn Ternary_False;\n\t\t}\n\n\t\tbool Load(Mesh* mesh, Stream& stream, const MeshParams& parameters)\n\t\t{\n\t\t\tMD2_Header header;\n\t\t\tif (stream.Read(&header, sizeof(MD2_Header)) != sizeof(MD2_Header))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to read header\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tSwapBytes(&header.skinwidth, sizeof(UInt32));\n\t\t\tSwapBytes(&header.skinheight, sizeof(UInt32));\n\t\t\tSwapBytes(&header.framesize, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_skins, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_vertices, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_st, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_tris, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_glcmds, sizeof(UInt32));\n\t\t\tSwapBytes(&header.num_frames, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_skins, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_st, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_tris, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_frames, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_glcmds, sizeof(UInt32));\n\t\t\tSwapBytes(&header.offset_end, sizeof(UInt32));\n\t\t\t#endif\n\n\t\t\tif (stream.GetSize() < header.offset_end)\n\t\t\t{\n\t\t\t\tNazaraError(\"Incomplete MD2 file\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Création du mesh\n\t\t\t\/\/ Le moteur ne supporte plus les animations image-clé, nous ne pouvons charger qu'en statique\n\t\t\tif (!mesh->CreateStatic()) \/\/ Ne devrait jamais échouer\n\t\t\t{\n\t\t\t\tNazaraInternalError(\"Failed to create mesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des skins\n\t\t\tif (header.num_skins > 0)\n\t\t\t{\n\t\t\t\tmesh->SetMaterialCount(header.num_skins);\n\t\t\t\tstream.SetCursorPos(header.offset_skins);\n\t\t\t\t{\n\t\t\t\t\tString baseDir = stream.GetDirectory();\n\t\t\t\t\tchar skin[68];\n\t\t\t\t\tfor (unsigned int i = 0; i < header.num_skins; ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tstream.Read(skin, 68*sizeof(char));\n\n\t\t\t\t\t\tParameterList matData;\n\t\t\t\t\t\tmatData.SetParameter(MaterialData::CustomDefined, true);\n\t\t\t\t\t\tmatData.SetParameter(MaterialData::DiffuseTexturePath, baseDir + skin);\n\n\t\t\t\t\t\tmesh->SetMaterialData(i, std::move(matData));\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des submesh\n\t\t\t\/\/ Actuellement le loader ne charge qu'un submesh\n\t\t\tIndexBufferRef indexBuffer = IndexBuffer::New(false, header.num_tris*3, parameters.storage, BufferUsage_Static);\n\n\t\t\t\/\/\/ Lecture des triangles\n\t\t\tstd::vector triangles(header.num_tris);\n\n\t\t\tstream.SetCursorPos(header.offset_tris);\n\t\t\tstream.Read(&triangles[0], header.num_tris*sizeof(MD2_Triangle));\n\n\t\t\tBufferMapper indexMapper(indexBuffer, BufferAccess_DiscardAndWrite);\n\t\t\tUInt16* index = static_cast(indexMapper.GetPointer());\n\n\t\t\tfor (unsigned int i = 0; i < header.num_tris; ++i)\n\t\t\t{\n\t\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\t\tSwapBytes(&triangles[i].vertices[0], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[0], sizeof(UInt16));\n\n\t\t\t\tSwapBytes(&triangles[i].vertices[1], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[1], sizeof(UInt16));\n\n\t\t\t\tSwapBytes(&triangles[i].vertices[2], sizeof(UInt16));\n\t\t\t\tSwapBytes(&triangles[i].texCoords[2], sizeof(UInt16));\n\t\t\t\t#endif\n\n\t\t\t\t\/\/ On respécifie le triangle dans l'ordre attendu\n\t\t\t\t*index++ = triangles[i].vertices[0];\n\t\t\t\t*index++ = triangles[i].vertices[2];\n\t\t\t\t*index++ = triangles[i].vertices[1];\n\t\t\t}\n\n\t\t\tindexMapper.Unmap();\n\n\t\t\tif (parameters.optimizeIndexBuffers)\n\t\t\t\tindexBuffer->Optimize();\n\n\t\t\t\/\/\/ Lecture des coordonnées de texture\n\t\t\tstd::vector texCoords(header.num_st);\n\n\t\t\tstream.SetCursorPos(header.offset_st);\n\t\t\tstream.Read(&texCoords[0], header.num_st*sizeof(MD2_TexCoord));\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tfor (unsigned int i = 0; i < header.num_st; ++i)\n\t\t\t{\n\t\t\t\tSwapBytes(&texCoords[i].u, sizeof(Int16));\n\t\t\t\tSwapBytes(&texCoords[i].v, sizeof(Int16));\n\t\t\t}\n\t\t\t#endif\n\n\t\t\tVertexBufferRef vertexBuffer = VertexBuffer::New(VertexDeclaration::Get(VertexLayout_XYZ_Normal_UV_Tangent), header.num_vertices, parameters.storage, BufferUsage_Static);\n\t\t\tStaticMeshRef subMesh = StaticMesh::New(mesh);\n\t\t\tif (!subMesh->Create(vertexBuffer))\n\t\t\t{\n\t\t\t\tNazaraError(\"Failed to create SubMesh\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des vertices\n\t\t\tstream.SetCursorPos(header.offset_frames);\n\n\t\t\tstd::unique_ptr vertices(new MD2_Vertex[header.num_vertices]);\n\t\t\tVector3f scale, translate;\n\t\t\tstream.Read(scale, sizeof(Vector3f));\n\t\t\tstream.Read(translate, sizeof(Vector3f));\n\t\t\tstream.Read(nullptr, 16*sizeof(char)); \/\/ Nom de la frame, inutile ici\n\t\t\tstream.Read(vertices.get(), header.num_vertices*sizeof(MD2_Vertex));\n\n\t\t\t#ifdef NAZARA_BIG_ENDIAN\n\t\t\tSwapBytes(&scale.x, sizeof(float));\n\t\t\tSwapBytes(&scale.y, sizeof(float));\n\t\t\tSwapBytes(&scale.z, sizeof(float));\n\n\t\t\tSwapBytes(&translate.x, sizeof(float));\n\t\t\tSwapBytes(&translate.y, sizeof(float));\n\t\t\tSwapBytes(&translate.z, sizeof(float));\n\t\t\t#endif\n\n\t\t\tconstexpr float ScaleAdjust = 1.f \/ 27.8f; \/\/ Make a 50 Quake 2 units character a 1.8 unit long\n\n\t\t\tscale *= ScaleAdjust;\n\t\t\ttranslate *= ScaleAdjust;\n\n\t\t\tBufferMapper vertexMapper(vertexBuffer, BufferAccess_DiscardAndWrite);\n\t\t\tMeshVertex* vertex = static_cast(vertexMapper.GetPointer());\n\n\t\t\t\/\/\/ Chargement des coordonnées de texture\n\t\t\tconst unsigned int indexFix[3] = {0, 2, 1}; \/\/ Pour respécifier les indices dans le bon ordre\n\t\t\tfor (unsigned int i = 0; i < header.num_tris; ++i)\n\t\t\t{\n\t\t\t\tfor (unsigned int j = 0; j < 3; ++j)\n\t\t\t\t{\n\t\t\t\t\tconst unsigned int fixedIndex = indexFix[j];\n\t\t\t\t\tconst MD2_TexCoord& texC = texCoords[triangles[i].texCoords[fixedIndex]];\n\t\t\t\t\tfloat u = static_cast(texC.u) \/ header.skinwidth;\n\t\t\t\t\tfloat v = static_cast(texC.v) \/ header.skinheight;\n\n\t\t\t\t\tvertex[triangles[i].vertices[fixedIndex]].uv.Set(u, (parameters.flipUVs) ? 1.f - v : v);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t\/\/\/ Chargement des positions\n\t\t\t\/\/ Pour que le modèle soit correctement aligné, on génère un quaternion que nous appliquerons à chacune des vertices\n\t\t\tQuaternionf rotationQuat = EulerAnglesf(-90.f, 90.f, 0.f);\n\t\t\tNz::Matrix4f matrix = Matrix4f::Transform(translate, rotationQuat, scale);\n\t\t\tmatrix *= parameters.matrix;\n\n\t\t\tfor (unsigned int v = 0; v < header.num_vertices; ++v)\n\t\t\t{\n\t\t\t\tconst MD2_Vertex& vert = vertices[v];\n\t\t\t\tVector3f position = matrix * Vector3f(vert.x, vert.y, vert.z);\n\n\t\t\t\tvertex->position = position;\n\t\t\t\tvertex->normal = rotationQuat * md2Normals[vert.n];\n\n\t\t\t\tvertex++;\n\t\t\t}\n\n\t\t\tvertexMapper.Unmap();\n\n\t\t\tsubMesh->SetIndexBuffer(indexBuffer);\n\t\t\tsubMesh->SetMaterialIndex(0);\n\n\t\t\tsubMesh->GenerateAABB();\n\t\t\tsubMesh->GenerateTangents();\n\n\t\t\tmesh->AddSubMesh(subMesh);\n\n\t\t\tif (parameters.center)\n\t\t\t\tmesh->Recenter();\n\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tnamespace Loaders\n\t{\n\t\tvoid RegisterMD2()\n\t\t{\n\t\t\tMeshLoader::RegisterLoader(IsSupported, Check, Load);\n\t\t}\n\n\t\tvoid UnregisterMD2()\n\t\t{\n\t\t\tMeshLoader::UnregisterLoader(IsSupported, Check, Load);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"utilities.hpp\"\n\nnamespace mtconnect {\n namespace observation {\n class ChangeSignaler;\n class ChangeObserver\n {\n public:\n ChangeObserver(boost::asio::io_context::strand &strand)\n : m_strand(strand), m_timer(strand.context())\n {}\n\n virtual ~ChangeObserver();\n\n bool wait(std::chrono::milliseconds duration,\n std::function handler)\n {\n std::unique_lock lock(m_mutex);\n\n if (m_sequence != UINT64_MAX)\n {\n boost::asio::post(boost::asio::bind_executor(\n m_strand, boost::bind(handler, boost::system::error_code {})));\n }\n else\n {\n m_timer.expires_from_now(duration);\n m_timer.async_wait(handler);\n }\n return true;\n }\n\n void signal(uint64_t sequence)\n {\n std::lock_guard scopedLock(m_mutex);\n\n if (m_sequence > sequence && sequence)\n m_sequence = sequence;\n\n m_timer.cancel();\n }\n\n uint64_t getSequence() const { return m_sequence; }\n\n bool wasSignaled() const { return m_sequence != UINT64_MAX; }\n\n void reset()\n {\n std::lock_guard scopedLock(m_mutex);\n m_sequence = UINT64_MAX;\n }\n\n private:\n boost::asio::io_context::strand &m_strand;\n mutable std::recursive_mutex m_mutex;\n boost::asio::steady_timer m_timer;\n\n std::list m_signalers;\n volatile uint64_t m_sequence = UINT64_MAX;\n\n protected:\n friend class ChangeSignaler;\n void addSignaler(ChangeSignaler *sig);\n bool removeSignaler(ChangeSignaler *sig);\n };\n\n class ChangeSignaler\n {\n public:\n \/\/ Observer Management\n void addObserver(ChangeObserver *observer);\n bool removeObserver(ChangeObserver *observer);\n bool hasObserver(ChangeObserver *observer) const;\n void signalObservers(uint64_t sequence) const;\n\n virtual ~ChangeSignaler();\n\n protected:\n \/\/ Observer Lists\n mutable std::recursive_mutex m_observerMutex;\n std::list m_observers;\n };\n } \/\/ namespace observation\n} \/\/ namespace mtconnect\nRemoved include of boost\/bind. Corrected\/\/\n\/\/ Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n#pragma once\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"utilities.hpp\"\n\nnamespace mtconnect {\n namespace observation {\n class ChangeSignaler;\n class ChangeObserver\n {\n public:\n ChangeObserver(boost::asio::io_context::strand &strand)\n : m_strand(strand), m_timer(strand.context())\n {}\n\n virtual ~ChangeObserver();\n\n bool wait(std::chrono::milliseconds duration,\n std::function handler)\n {\n std::unique_lock lock(m_mutex);\n\n if (m_sequence != UINT64_MAX)\n {\n boost::asio::post(boost::asio::bind_executor(\n m_strand, boost::bind(handler, boost::system::error_code {})));\n }\n else\n {\n m_timer.expires_from_now(duration);\n m_timer.async_wait(handler);\n }\n return true;\n }\n\n void signal(uint64_t sequence)\n {\n std::lock_guard scopedLock(m_mutex);\n\n if (m_sequence > sequence && sequence)\n m_sequence = sequence;\n\n m_timer.cancel();\n }\n\n uint64_t getSequence() const { return m_sequence; }\n\n bool wasSignaled() const { return m_sequence != UINT64_MAX; }\n\n void reset()\n {\n std::lock_guard scopedLock(m_mutex);\n m_sequence = UINT64_MAX;\n }\n\n private:\n boost::asio::io_context::strand &m_strand;\n mutable std::recursive_mutex m_mutex;\n boost::asio::steady_timer m_timer;\n\n std::list m_signalers;\n volatile uint64_t m_sequence = UINT64_MAX;\n\n protected:\n friend class ChangeSignaler;\n void addSignaler(ChangeSignaler *sig);\n bool removeSignaler(ChangeSignaler *sig);\n };\n\n class ChangeSignaler\n {\n public:\n \/\/ Observer Management\n void addObserver(ChangeObserver *observer);\n bool removeObserver(ChangeObserver *observer);\n bool hasObserver(ChangeObserver *observer) const;\n void signalObservers(uint64_t sequence) const;\n\n virtual ~ChangeSignaler();\n\n protected:\n \/\/ Observer Lists\n mutable std::recursive_mutex m_observerMutex;\n std::list m_observers;\n };\n } \/\/ namespace observation\n} \/\/ namespace mtconnect\n<|endoftext|>"} {"text":"\/*$Id$\n *\n * This source file is a part of the Fresco Project.\n * Copyright (C) 1999 Stefan Seefeld \n * http:\/\/www.fresco.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include \"TextDemo.hh\"\n\nusing namespace Fresco;\n\nTextDemo::TextDemo(Application *a)\n : Demo(a)\n{\n TextKit_var text = application->resolve(\"IDL:fresco.org\/Fresco\/TextKit:1.0\");\n ToolKit_var tools = application->resolve(\"IDL:fresco.org\/Fresco\/ToolKit:1.0\");\n\n Babylon::Char chars[] =\n {\n 0x004d, 0x0061, 0x0067, 0x0079, 0x0061, 0x0072, 0x0020, 0x0420,\n 0x0443, 0x0441, 0x0441, 0x043a, 0x0438, 0x0439, 0x0020, 0x0395,\n 0x039b, 0x039b, 0x0397, 0x039d, 0x0399, 0x039a, 0x0391, 0x0020,\n 0x65e5, 0x672c, 0x8a9e, 0x0020, 0x4e2d, 0x6587, 0x0020, 0xd55c,\n 0xad6d, 0xc5b4\n };\n\n Babylon::String str(34, chars);\n Graphic_var txt = text->chunk(Unicode::to_CORBA(str));\n Controller_var group = tools->group(Graphic_var(tools->rgb(txt, 0.7, 0.8, 1.0)));\n application->append(group, Babylon::String(\"text\"));\n};\nUpdate colour of text to something legible.\/*$Id$\n *\n * This source file is a part of the Fresco Project.\n * Copyright (C) 1999 Stefan Seefeld \n * http:\/\/www.fresco.org\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the\n * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,\n * MA 02139, USA.\n *\/\n\n#include \"TextDemo.hh\"\n\nusing namespace Fresco;\n\nTextDemo::TextDemo(Application *a)\n : Demo(a)\n{\n TextKit_var text = application->resolve(\"IDL:fresco.org\/Fresco\/TextKit:1.0\");\n ToolKit_var tools = application->resolve(\"IDL:fresco.org\/Fresco\/ToolKit:1.0\");\n\n Babylon::Char chars[] =\n {\n 0x004d, 0x0061, 0x0067, 0x0079, 0x0061, 0x0072, 0x0020, 0x0420,\n 0x0443, 0x0441, 0x0441, 0x043a, 0x0438, 0x0439, 0x0020, 0x0395,\n 0x039b, 0x039b, 0x0397, 0x039d, 0x0399, 0x039a, 0x0391, 0x0020,\n 0x65e5, 0x672c, 0x8a9e, 0x0020, 0x4e2d, 0x6587, 0x0020, 0xd55c,\n 0xad6d, 0xc5b4\n };\n\n Babylon::String str(34, chars);\n Graphic_var txt = text->chunk(Unicode::to_CORBA(str));\n Controller_var group = tools->group(Graphic_var(tools->rgb(txt, 0.2, 0.3, 0.5)));\n application->append(group, Babylon::String(\"text\"));\n};\n<|endoftext|>"} {"text":"\/*!\r\n\t@file\r\n\t@author\t\tAlbert Semenov\r\n\t@date\t\t08\/2010\r\n*\/\r\n#include \"precompiled.h\"\r\n#include \"SkinListControl.h\"\r\n#include \"SkinManager.h\"\r\n#include \"ActionManager.h\"\r\n#include \r\n\r\nnamespace tools\r\n{\r\n\r\n\tSkinListControl::SkinListControl(MyGUI::Widget* _parent) :\r\n\t\twraps::BaseLayout(\"SkinListControl.layout\", _parent),\r\n\t\tmList(nullptr),\r\n\t\tmCreate(nullptr),\r\n\t\tmRename(nullptr),\r\n\t\tmDelete(nullptr),\r\n\t\tmTextFieldControl(nullptr)\r\n\t{\r\n\t\tassignWidget(mList, \"List\");\r\n\t\tassignWidget(mCreate, \"Create\");\r\n\t\tassignWidget(mRename, \"Rename\");\r\n\t\tassignWidget(mDelete, \"Delete\");\r\n\r\n\t\tmList->eventListChangePosition += MyGUI::newDelegate(this, &SkinListControl::notifyChangePosition);\r\n\t\tmCreate->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyCreate);\r\n\t\tmRename->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyRename);\r\n\t\tmDelete->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyDelete);\r\n\r\n\t\tSkinManager::getInstance().eventChangeList += MyGUI::newDelegate(this, &SkinListControl::notifyChangeList);\r\n\t}\r\n\r\n\tSkinListControl::~SkinListControl()\r\n\t{\r\n\t\tSkinManager::getInstance().eventChangeList -= MyGUI::newDelegate(this, &SkinListControl::notifyChangeList);\r\n\r\n\t\thideTextField();\r\n\r\n\t\tmCreate->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyCreate);\r\n\t\tmRename->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyRename);\r\n\t\tmDelete->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyDelete);\r\n\t\tmList->eventListChangePosition -= MyGUI::newDelegate(this, &SkinListControl::notifyChangePosition);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyChangePosition(MyGUI::List* _sender, size_t _index)\r\n\t{\r\n\t\tSkinItem* item = nullptr;\r\n\r\n\t\tif (_index != MyGUI::ITEM_NONE)\r\n\t\t\titem = *mList->getItemDataAt(_index);\r\n\r\n\t\tSkinManager::getInstance().setItemSelected(item);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyCreate(MyGUI::Widget* _sender)\r\n\t{\r\n\t\t\/\/showTextField(nullptr);\r\n\t\tcreateItem(getNextFreeName());\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyRename(MyGUI::Widget* _sender)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\t\tif (item != nullptr)\r\n\t\t\tshowTextField(item);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyDelete(MyGUI::Widget* _sender)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\t\tif (item != nullptr)\r\n\t\t{\r\n\t\t\tMyGUI::Message* message = MyGUI::Message::createMessageBox(\r\n\t\t\t\t\"Message\",\r\n\t\t\t\tL\"Внимание\",\r\n\t\t\t\tL\"Вы уверены?\",\r\n\t\t\t\tMyGUI::MessageBoxStyle::IconQuest | MyGUI::MessageBoxStyle::Yes | MyGUI::MessageBoxStyle::No);\r\n\t\t\tmessage->eventMessageBoxResult += MyGUI::newDelegate(this, &SkinListControl::notifyDeleteMessageBoxResult);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyDeleteMessageBoxResult(MyGUI::Message* _sender, MyGUI::MessageBoxStyle _style)\r\n\t{\r\n\t\tif (_style == MyGUI::MessageBoxStyle::Yes)\r\n\t\t{\r\n\t\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\r\n\t\t\t\/\/ выделяем следующий за удаляемым\r\n\t\t\tSkinItem* prev = nullptr;\r\n\t\t\tSkinItem* next = nullptr;\r\n\r\n\t\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\t\twhile (items.next())\r\n\t\t\t{\r\n\t\t\t\tSkinItem* current = items.current();\r\n\t\t\t\tif (current == item)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (items.next())\r\n\t\t\t\t\t\tnext = items.current();\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tprev = current;\r\n\t\t\t}\r\n\r\n\t\t\tif (next != nullptr)\r\n\t\t\t\tSkinManager::getInstance().setItemSelected(next);\r\n\t\t\telse if (prev != nullptr)\r\n\t\t\t\tSkinManager::getInstance().setItemSelected(prev);\r\n\r\n\t\t\tSkinManager::getInstance().destroyChild(item);\r\n\r\n\t\t\tupdateList();\r\n\r\n\t\t\tActionManager::getInstance().setChanges(true);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::updateList()\r\n\t{\r\n\t\tmList->setIndexSelected(MyGUI::ITEM_NONE);\r\n\t\tmList->removeAllItems();\r\n\r\n\t\tSkinItem* selectedItem = SkinManager::getInstance().getItemSelected();\r\n\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tsize_t index = mList->getItemCount();\r\n\r\n\t\t\tSkinItem* item = items.current();\r\n\r\n\t\t\tsize_t count = getNameCount(item->getName());\r\n\t\t\tif (count == 1)\r\n\t\t\t\tmList->addItem(item->getName());\r\n\t\t\telse\r\n\t\t\t\tmList->addItem(\"#FF0000\" + item->getName());\r\n\r\n\t\t\tmList->setItemDataAt(index, item);\r\n\t\t\tif (item == selectedItem)\r\n\t\t\t\tmList->setIndexSelected(index);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::hideTextField()\r\n\t{\r\n\t\tif (mTextFieldControl != nullptr)\r\n\t\t{\r\n\t\t\tmTextFieldControl->hide();\r\n\r\n\t\t\tmTextFieldControl->eventResult = nullptr;\r\n\r\n\t\t\tdelete mTextFieldControl;\r\n\t\t\tmTextFieldControl = nullptr;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::showTextField(SkinItem* _item)\r\n\t{\r\n\t\thideTextField();\r\n\r\n\t\tmTextFieldControl = new TextFieldControl();\r\n\t\tmTextFieldControl->setCaption(_item == nullptr ? \"Create\" : \"Rename\");\r\n\t\tmTextFieldControl->setTextField(_item == nullptr ? getNextFreeName() : _item->getName());\r\n\t\tmTextFieldControl->setUserData(_item);\r\n\t\tmTextFieldControl->show();\r\n\r\n\t\tmTextFieldControl->eventResult = MyGUI::newDelegate(this, &SkinListControl::notifyTextFieldResult);\r\n\t}\r\n\r\n\tMyGUI::UString SkinListControl::getNextFreeName()\r\n\t{\r\n\t\tMyGUI::UString pattern = \"SkinName\";\r\n\r\n\t\tfor (size_t index=0; index::max(); index++)\r\n\t\t{\r\n\t\t\tMyGUI::UString name = MyGUI::utility::toString(pattern, index);\r\n\t\t\tif (!isNameExist(name))\r\n\t\t\t\treturn name;\r\n\t\t}\r\n\r\n\t\treturn \"\";\r\n\t}\r\n\r\n\tbool SkinListControl::isNameExist(const MyGUI::UString& _value)\r\n\t{\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tSkinItem* item = items.current();\r\n\t\t\tif (item->getName() == _value)\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tsize_t SkinListControl::getNameCount(const MyGUI::UString& _value)\r\n\t{\r\n\t\tsize_t result = 0;\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tSkinItem* item = items.current();\r\n\t\t\tif (item->getName() == _value)\r\n\t\t\t\t++result;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyTextFieldResult(bool _result)\r\n\t{\r\n\t\tif (_result)\r\n\t\t{\r\n\t\t\tSkinItem* item = *mTextFieldControl->getUserData();\r\n\t\t\tif (item != nullptr)\r\n\t\t\t\trenameItem(item, mTextFieldControl->getTextField());\r\n\t\t\telse\r\n\t\t\t\tcreateItem(mTextFieldControl->getTextField());\r\n\t\t}\r\n\r\n\t\thideTextField();\r\n\t}\r\n\r\n\tvoid SkinListControl::renameItem(SkinItem* _item, const MyGUI::UString& _value)\r\n\t{\r\n\t\t_item->setName(_value);\r\n\t\tupdateList();\r\n\r\n\t\tActionManager::getInstance().setChanges(true);\r\n\t}\r\n\r\n\tvoid SkinListControl::createItem(const MyGUI::UString& _value)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().createChild();\r\n\t\titem->setName(_value);\r\n\t\tSkinManager::getInstance().setItemSelected(item);\r\n\r\n\t\tupdateList();\r\n\r\n\t\tActionManager::getInstance().setChanges(true);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyChangeList()\r\n\t{\r\n\t\tupdateList();\r\n\t}\r\n\r\n} \/\/ namespace tools\r\nSE: convert to anci\/*!\r\n\t@file\r\n\t@author\t\tAlbert Semenov\r\n\t@date\t\t08\/2010\r\n*\/\r\n#include \"precompiled.h\"\r\n#include \"SkinListControl.h\"\r\n#include \"SkinManager.h\"\r\n#include \"ActionManager.h\"\r\n#include \r\n\r\nnamespace tools\r\n{\r\n\r\n\tSkinListControl::SkinListControl(MyGUI::Widget* _parent) :\r\n\t\twraps::BaseLayout(\"SkinListControl.layout\", _parent),\r\n\t\tmList(nullptr),\r\n\t\tmCreate(nullptr),\r\n\t\tmRename(nullptr),\r\n\t\tmDelete(nullptr),\r\n\t\tmTextFieldControl(nullptr)\r\n\t{\r\n\t\tassignWidget(mList, \"List\");\r\n\t\tassignWidget(mCreate, \"Create\");\r\n\t\tassignWidget(mRename, \"Rename\");\r\n\t\tassignWidget(mDelete, \"Delete\");\r\n\r\n\t\tmList->eventListChangePosition += MyGUI::newDelegate(this, &SkinListControl::notifyChangePosition);\r\n\t\tmCreate->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyCreate);\r\n\t\tmRename->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyRename);\r\n\t\tmDelete->eventMouseButtonClick += MyGUI::newDelegate(this, &SkinListControl::notifyDelete);\r\n\r\n\t\tSkinManager::getInstance().eventChangeList += MyGUI::newDelegate(this, &SkinListControl::notifyChangeList);\r\n\t}\r\n\r\n\tSkinListControl::~SkinListControl()\r\n\t{\r\n\t\tSkinManager::getInstance().eventChangeList -= MyGUI::newDelegate(this, &SkinListControl::notifyChangeList);\r\n\r\n\t\thideTextField();\r\n\r\n\t\tmCreate->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyCreate);\r\n\t\tmRename->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyRename);\r\n\t\tmDelete->eventMouseButtonClick -= MyGUI::newDelegate(this, &SkinListControl::notifyDelete);\r\n\t\tmList->eventListChangePosition -= MyGUI::newDelegate(this, &SkinListControl::notifyChangePosition);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyChangePosition(MyGUI::List* _sender, size_t _index)\r\n\t{\r\n\t\tSkinItem* item = nullptr;\r\n\r\n\t\tif (_index != MyGUI::ITEM_NONE)\r\n\t\t\titem = *mList->getItemDataAt(_index);\r\n\r\n\t\tSkinManager::getInstance().setItemSelected(item);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyCreate(MyGUI::Widget* _sender)\r\n\t{\r\n\t\t\/\/showTextField(nullptr);\r\n\t\tcreateItem(getNextFreeName());\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyRename(MyGUI::Widget* _sender)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\t\tif (item != nullptr)\r\n\t\t\tshowTextField(item);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyDelete(MyGUI::Widget* _sender)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\t\tif (item != nullptr)\r\n\t\t{\r\n\t\t\tMyGUI::Message* message = MyGUI::Message::createMessageBox(\r\n\t\t\t\t\"Message\",\r\n\t\t\t\tL\"\",\r\n\t\t\t\tL\" ?\",\r\n\t\t\t\tMyGUI::MessageBoxStyle::IconQuest | MyGUI::MessageBoxStyle::Yes | MyGUI::MessageBoxStyle::No);\r\n\t\t\tmessage->eventMessageBoxResult += MyGUI::newDelegate(this, &SkinListControl::notifyDeleteMessageBoxResult);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyDeleteMessageBoxResult(MyGUI::Message* _sender, MyGUI::MessageBoxStyle _style)\r\n\t{\r\n\t\tif (_style == MyGUI::MessageBoxStyle::Yes)\r\n\t\t{\r\n\t\t\tSkinItem* item = SkinManager::getInstance().getItemSelected();\r\n\r\n\t\t\t\/\/ \r\n\t\t\tSkinItem* prev = nullptr;\r\n\t\t\tSkinItem* next = nullptr;\r\n\r\n\t\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\t\twhile (items.next())\r\n\t\t\t{\r\n\t\t\t\tSkinItem* current = items.current();\r\n\t\t\t\tif (current == item)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (items.next())\r\n\t\t\t\t\t\tnext = items.current();\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t\tprev = current;\r\n\t\t\t}\r\n\r\n\t\t\tif (next != nullptr)\r\n\t\t\t\tSkinManager::getInstance().setItemSelected(next);\r\n\t\t\telse if (prev != nullptr)\r\n\t\t\t\tSkinManager::getInstance().setItemSelected(prev);\r\n\r\n\t\t\tSkinManager::getInstance().destroyChild(item);\r\n\r\n\t\t\tupdateList();\r\n\r\n\t\t\tActionManager::getInstance().setChanges(true);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::updateList()\r\n\t{\r\n\t\tmList->setIndexSelected(MyGUI::ITEM_NONE);\r\n\t\tmList->removeAllItems();\r\n\r\n\t\tSkinItem* selectedItem = SkinManager::getInstance().getItemSelected();\r\n\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tsize_t index = mList->getItemCount();\r\n\r\n\t\t\tSkinItem* item = items.current();\r\n\r\n\t\t\tsize_t count = getNameCount(item->getName());\r\n\t\t\tif (count == 1)\r\n\t\t\t\tmList->addItem(item->getName());\r\n\t\t\telse\r\n\t\t\t\tmList->addItem(\"#FF0000\" + item->getName());\r\n\r\n\t\t\tmList->setItemDataAt(index, item);\r\n\t\t\tif (item == selectedItem)\r\n\t\t\t\tmList->setIndexSelected(index);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::hideTextField()\r\n\t{\r\n\t\tif (mTextFieldControl != nullptr)\r\n\t\t{\r\n\t\t\tmTextFieldControl->hide();\r\n\r\n\t\t\tmTextFieldControl->eventResult = nullptr;\r\n\r\n\t\t\tdelete mTextFieldControl;\r\n\t\t\tmTextFieldControl = nullptr;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid SkinListControl::showTextField(SkinItem* _item)\r\n\t{\r\n\t\thideTextField();\r\n\r\n\t\tmTextFieldControl = new TextFieldControl();\r\n\t\tmTextFieldControl->setCaption(_item == nullptr ? \"Create\" : \"Rename\");\r\n\t\tmTextFieldControl->setTextField(_item == nullptr ? getNextFreeName() : _item->getName());\r\n\t\tmTextFieldControl->setUserData(_item);\r\n\t\tmTextFieldControl->show();\r\n\r\n\t\tmTextFieldControl->eventResult = MyGUI::newDelegate(this, &SkinListControl::notifyTextFieldResult);\r\n\t}\r\n\r\n\tMyGUI::UString SkinListControl::getNextFreeName()\r\n\t{\r\n\t\tMyGUI::UString pattern = \"SkinName\";\r\n\r\n\t\tfor (size_t index=0; index::max(); index++)\r\n\t\t{\r\n\t\t\tMyGUI::UString name = MyGUI::utility::toString(pattern, index);\r\n\t\t\tif (!isNameExist(name))\r\n\t\t\t\treturn name;\r\n\t\t}\r\n\r\n\t\treturn \"\";\r\n\t}\r\n\r\n\tbool SkinListControl::isNameExist(const MyGUI::UString& _value)\r\n\t{\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tSkinItem* item = items.current();\r\n\t\t\tif (item->getName() == _value)\r\n\t\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tsize_t SkinListControl::getNameCount(const MyGUI::UString& _value)\r\n\t{\r\n\t\tsize_t result = 0;\r\n\t\tItemHolder::EnumeratorItem items = SkinManager::getInstance().getChildsEnumerator();\r\n\t\twhile (items.next())\r\n\t\t{\r\n\t\t\tSkinItem* item = items.current();\r\n\t\t\tif (item->getName() == _value)\r\n\t\t\t\t++result;\r\n\t\t}\r\n\t\treturn result;\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyTextFieldResult(bool _result)\r\n\t{\r\n\t\tif (_result)\r\n\t\t{\r\n\t\t\tSkinItem* item = *mTextFieldControl->getUserData();\r\n\t\t\tif (item != nullptr)\r\n\t\t\t\trenameItem(item, mTextFieldControl->getTextField());\r\n\t\t\telse\r\n\t\t\t\tcreateItem(mTextFieldControl->getTextField());\r\n\t\t}\r\n\r\n\t\thideTextField();\r\n\t}\r\n\r\n\tvoid SkinListControl::renameItem(SkinItem* _item, const MyGUI::UString& _value)\r\n\t{\r\n\t\t_item->setName(_value);\r\n\t\tupdateList();\r\n\r\n\t\tActionManager::getInstance().setChanges(true);\r\n\t}\r\n\r\n\tvoid SkinListControl::createItem(const MyGUI::UString& _value)\r\n\t{\r\n\t\tSkinItem* item = SkinManager::getInstance().createChild();\r\n\t\titem->setName(_value);\r\n\t\tSkinManager::getInstance().setItemSelected(item);\r\n\r\n\t\tupdateList();\r\n\r\n\t\tActionManager::getInstance().setChanges(true);\r\n\t}\r\n\r\n\tvoid SkinListControl::notifyChangeList()\r\n\t{\r\n\t\tupdateList();\r\n\t}\r\n\r\n} \/\/ namespace tools\r\n<|endoftext|>"} {"text":"\/*\n * PrimeSieveProcess.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \"PrimeSieveProcess.h\"\n\n#include \n#include \n#include \n#if defined(Q_OS_WIN)\n# include \n#else\n# include \n#endif\n\nPrimeSieveProcess::PrimeSieveProcess(QObject* parent = 0) : \n QProcess(parent) {\n sharedMemory_.setParent(parent);\n sharedMemory_.setKey(QString::number(this->getProcessId()));\n}\n\nPrimeSieveProcess::~PrimeSieveProcess() {\n \/\/ disconnect all signals, must be used to avoid zombie processes\n this->disconnect();\n \/\/ kill() and terminate() = trouble, close() works fine\n this->close();\n sharedMemory_.detach();\n}\n\n\/**\n * Get the process ID of the current process. I tried to use\n * QProcess::pid() but got a lot of trouble on Windows and Mac OS X,\n * also it is not portable.\n *\/\nint PrimeSieveProcess::getProcessId() {\n#if defined(Q_OS_WIN)\n return static_cast (GetCurrentProcessId());\n#else\n return static_cast (getpid());\n#endif\n}\n\n\/**\n * Create a shared memory segement for communication with the\n * ParallelPrimeSieve process.\n *\/\nvoid PrimeSieveProcess::createSharedMemory() {\n \/\/ attach the shared memory\n if (!sharedMemory_.isAttached() &&\n !sharedMemory_.create(sizeof(shm_))) {\n throw std::runtime_error(\n \"Interprocess communication error, could not allocate shared memory.\");\n }\n \/\/ map the attached shared memory to the shm_ segment\n shm_ = static_cast (sharedMemory_.data());\n}\n\n\/**\n * Start a new ParallelPrimeSieve process that sieves the\n * prime numbers and\/or k-tuplets between startNumber and stopNumber.\n *\/\nvoid PrimeSieveProcess::start(qulonglong startNumber, qulonglong stopNumber,\n int sieveSize, int flags, int threads) {\n this->createSharedMemory();\n \/\/ initialize the shared memory segment\n shm_->startNumber = startNumber;\n shm_->stopNumber = stopNumber;\n shm_->sieveSize = sieveSize;\n shm_->flags = flags;\n shm_->threads = threads;\n for (int i = 0; i < COUNTS_SIZE; i++)\n shm_->counts[i] = 0;\n shm_->status = 0.0;\n shm_->timeElapsed = 0.0;\n \/\/ path + file name of the aplication\n QString path = QCoreApplication::applicationFilePath();\n \/\/ process arguments, see main.cpp\n QStringList args;\n args << \"PrimeSieveProcess\" << sharedMemory_.key();\n \/\/\/ start a new ParallelPrimeSieve process\n \/\/\/ @see main.cpp\n QProcess::start(path, args, QIODevice::ReadOnly);\n}\n\nbool PrimeSieveProcess::isFinished() {\n return (shm_->status == 100.0);\n}\n\n\/**\n * @return The count of prime numbers or prime k-tuplets between\n * startNumber and stopNumber.\n * @param index 0 = Count of prime numbers\n * 1 = Count of twin primes\n * 2 = Count of prime triplets\n * 3 = Count of prime quadruplets\n * 4 = Count of prime quintuplets\n * 5 = Count of prime sextuplets\n * 6 = Count of prime septuplets\n *\/\nqlonglong PrimeSieveProcess::getCounts(unsigned int index) const {\n return shm_->counts[index];\n}\n\n\/**\n * @return The sieving status in percent.\n *\/\ndouble PrimeSieveProcess::getStatus() const {\n return shm_->status;\n}\n\n\/**\n * @return The time elapsed in seconds (if sieving is finished).\n *\/\ndouble PrimeSieveProcess::getTimeElapsed() const {\n return shm_->timeElapsed;\n}\nminor changes\/*\n * PrimeSieveProcess.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2011 Kim Walisch, \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \"PrimeSieveProcess.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n\n#include \n#include \n#include \n#include \n#if defined(Q_OS_WIN)\n# include \n#else\n# include \n#endif\n\nPrimeSieveProcess::PrimeSieveProcess(QObject* parent = 0) : \n QProcess(parent) {\n sharedMemory_.setParent(parent);\n sharedMemory_.setKey(QString::number(this->getProcessId()));\n}\n\nPrimeSieveProcess::~PrimeSieveProcess() {\n \/\/ disconnect all signals, must be used to avoid zombie processes\n this->disconnect();\n \/\/ kill() and terminate() = trouble, close() works fine\n this->close();\n sharedMemory_.detach();\n}\n\n\/**\n * Get the process ID of the current process. I tried to use\n * QProcess::pid() but got a lot of trouble on Windows and Mac OS X,\n * also it is not portable.\n *\/\nint PrimeSieveProcess::getProcessId() {\n#if defined(Q_OS_WIN)\n return static_cast (GetCurrentProcessId());\n#else\n return static_cast (getpid());\n#endif\n}\n\n\/**\n * Create a shared memory segement for communication with the\n * ParallelPrimeSieve process.\n *\/\nvoid PrimeSieveProcess::createSharedMemory() {\n \/\/ attach the shared memory\n if (!sharedMemory_.isAttached() &&\n !sharedMemory_.create(sizeof(shm_))) {\n throw std::runtime_error(\n \"Interprocess communication error, could not allocate shared memory.\");\n }\n \/\/ map the attached shared memory to the shm_ segment\n shm_ = static_cast (sharedMemory_.data());\n}\n\n\/**\n * Start a new ParallelPrimeSieve process that sieves the\n * prime numbers and\/or k-tuplets between startNumber and stopNumber.\n *\/\nvoid PrimeSieveProcess::start(quint64 startNumber, quint64 stopNumber,\n int sieveSize, int flags, int threads) {\n this->createSharedMemory();\n \/\/ initialize the shared memory segment\n shm_->startNumber = startNumber;\n shm_->stopNumber = stopNumber;\n shm_->sieveSize = static_cast (sieveSize);\n shm_->flags = static_cast (flags);\n shm_->threads = threads;\n for (int i = 0; i < ParallelPrimeSieve::COUNTS_SIZE; i++)\n shm_->counts[i] = 0;\n shm_->status = 0.0;\n shm_->timeElapsed = 0.0;\n \/\/ path + file name of the aplication\n QString path = QCoreApplication::applicationFilePath();\n \/\/ process arguments, see main.cpp\n QStringList args;\n args << \"PrimeSieveProcess\" << sharedMemory_.key();\n \/\/\/ start a new ParallelPrimeSieve process\n \/\/\/ @see main.cpp\n QProcess::start(path, args, QIODevice::ReadOnly);\n}\n\nbool PrimeSieveProcess::isFinished() {\n return (shm_->status == 100.0);\n}\n\n\/**\n * @return The count of prime numbers or prime k-tuplets between\n * startNumber and stopNumber.\n * @param index <= 6\n *\/\nquint64 PrimeSieveProcess::getCounts(unsigned int index) const {\n return shm_->counts[index];\n}\n\n\/**\n * @return The sieving status in percent.\n *\/\ndouble PrimeSieveProcess::getStatus() const {\n return shm_->status;\n}\n\n\/**\n * @return The time elapsed in seconds (if sieving is finished).\n *\/\ndouble PrimeSieveProcess::getTimeElapsed() const {\n return shm_->timeElapsed;\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/unsteady_visualization.h\"\n\n\/\/ GRINS\n#include \"grins\/multiphysics_sys.h\"\n#include \"grins\/composite_qoi.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/parameter_vector.h\"\n#include \"libmesh\/steady_solver.h\"\n\nnamespace GRINS\n{\n\n UnsteadyVisualization::UnsteadyVisualization\n ( const GetPot& input,\n const libMesh::Parallel::Communicator &comm )\n : Visualization(input, comm)\n {\n return;\n }\n\n UnsteadyVisualization::~UnsteadyVisualization()\n {\n return;\n }\n\n void UnsteadyVisualization::output_residual\n ( SharedPtr equation_system,\n MultiphysicsSystem* system,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::string filename = this->_vis_output_file_prefix+\"_unsteady_residual\";\n\n filename+=\".\"+suffix.str();\n\n \/\/ For the unsteady residual, we just want to evaluate F(u) from\n \/\/ dU\/dt = F(u). What we do is swap out the time solver to a\n \/\/ SteadySolver and reassemble the residual. Then, we'll need to swap\n \/\/ the solution and the rhs vector stashed in the system. Once we're done,\n \/\/ we'll reset the time solver pointer back to the original guy.\n\n libMesh::UniquePtr prev_time_solver(system->time_solver);\n\n libMesh::SteadySolver* steady_solver = new libMesh::SteadySolver( *(system) );\n\n system->time_solver = libMesh::UniquePtr(steady_solver);\n\n system->assembly( true \/*residual*\/, false \/*jacobian*\/ );\n system->rhs->close();\n\n \/\/ Swap solution with newly computed residual\n system->solution->swap( *(system->rhs) );\n \/\/ Update equation systems\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap( *(system->rhs) );\n equation_system->update();\n\n system->time_solver = prev_time_solver;\n\n return;\n }\n\n void UnsteadyVisualization::output_residual_sensitivities\n (SharedPtr equation_system,\n MultiphysicsSystem* system,\n const libMesh::ParameterVector & params,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n for (unsigned int p=0; p != params.size(); ++p)\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::stringstream pstr;\n pstr << p;\n\n std::string filename =\n this->_vis_output_file_prefix + \"_unsteady_dRdp\" +\n pstr.str() + '.' + suffix.str();\n\n \/\/ Swap solution with precomputed sensitivity rhs\n system->solution->swap(system->get_sensitivity_rhs(p));\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap(system->get_sensitivity_rhs(p));\n equation_system->update();\n }\n }\n\n void UnsteadyVisualization::output_adjoint\n ( SharedPtr equation_system,\n MultiphysicsSystem* system,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n std::stringstream suffix;\n suffix << time_step;\n\n const libMesh::DifferentiableQoI* raw_qoi = system->get_qoi();\n const CompositeQoI* qoi = dynamic_cast( raw_qoi );\n\n unsigned int n_qois = qoi->n_qois();\n\n for( unsigned int q = 0; q < n_qois; q++ )\n {\n libMesh::NumericVector& dual_solution = system->get_adjoint_solution(q);\n\n const std::string& qoi_name = qoi->get_qoi(q).name();\n std::string filename = this->_vis_output_file_prefix+\"_unsteady_adjoint_\"+qoi_name;\n filename+=\".\"+suffix.str();\n\n system->solution->swap( dual_solution );\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap( dual_solution );\n equation_system->update();\n }\n }\n\n void UnsteadyVisualization::output_solution_sensitivities\n (SharedPtr equation_system,\n MultiphysicsSystem* system,\n const libMesh::ParameterVector & params,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n for (unsigned int p=0; p != params.size(); ++p)\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::stringstream pstr;\n pstr << p;\n\n std::string filename =\n this->_vis_output_file_prefix + \"_unsteady_dudp\" +\n pstr.str() + '.' + suffix.str();\n\n \/\/ Swap solution with precomputed sensitivity solution\n system->solution->swap(system->get_sensitivity_solution(p));\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap(system->get_sensitivity_solution(p));\n equation_system->update();\n }\n }\n\n\n} \/\/ namespace GRINS\nProper pointer handling for outputing du\/dt\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/unsteady_visualization.h\"\n\n\/\/ GRINS\n#include \"grins\/multiphysics_sys.h\"\n#include \"grins\/composite_qoi.h\"\n\n\/\/ libMesh\n#include \"libmesh\/getpot.h\"\n#include \"libmesh\/parameter_vector.h\"\n#include \"libmesh\/steady_solver.h\"\n\nnamespace GRINS\n{\n\n UnsteadyVisualization::UnsteadyVisualization\n ( const GetPot& input,\n const libMesh::Parallel::Communicator &comm )\n : Visualization(input, comm)\n {\n return;\n }\n\n UnsteadyVisualization::~UnsteadyVisualization()\n {\n return;\n }\n\n void UnsteadyVisualization::output_residual\n ( SharedPtr equation_system,\n MultiphysicsSystem* system,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::string filename = this->_vis_output_file_prefix+\"_unsteady_residual\";\n\n filename+=\".\"+suffix.str();\n\n \/\/ For the unsteady residual, we just want to evaluate F(u) from\n \/\/ dU\/dt = F(u). What we do is swap out the time solver to a\n \/\/ SteadySolver and reassemble the residual. Then, we'll need to swap\n \/\/ the solution and the rhs vector stashed in the system. Once we're done,\n \/\/ we'll reset the time solver pointer back to the original guy.\n\n libMesh::TimeSolver* prev_time_solver = system->time_solver.get();\n\n libMesh::SteadySolver* steady_solver = new libMesh::SteadySolver( *(system) );\n\n system->time_solver = libMesh::UniquePtr(steady_solver);\n\n system->assembly( true \/*residual*\/, false \/*jacobian*\/ );\n system->rhs->close();\n\n \/\/ Swap solution with newly computed residual\n system->solution->swap( *(system->rhs) );\n \/\/ Update equation systems\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap( *(system->rhs) );\n equation_system->update();\n\n system->time_solver.reset(prev_time_solver);\n }\n\n void UnsteadyVisualization::output_residual_sensitivities\n (SharedPtr equation_system,\n MultiphysicsSystem* system,\n const libMesh::ParameterVector & params,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n for (unsigned int p=0; p != params.size(); ++p)\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::stringstream pstr;\n pstr << p;\n\n std::string filename =\n this->_vis_output_file_prefix + \"_unsteady_dRdp\" +\n pstr.str() + '.' + suffix.str();\n\n \/\/ Swap solution with precomputed sensitivity rhs\n system->solution->swap(system->get_sensitivity_rhs(p));\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap(system->get_sensitivity_rhs(p));\n equation_system->update();\n }\n }\n\n void UnsteadyVisualization::output_adjoint\n ( SharedPtr equation_system,\n MultiphysicsSystem* system,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n std::stringstream suffix;\n suffix << time_step;\n\n const libMesh::DifferentiableQoI* raw_qoi = system->get_qoi();\n const CompositeQoI* qoi = dynamic_cast( raw_qoi );\n\n unsigned int n_qois = qoi->n_qois();\n\n for( unsigned int q = 0; q < n_qois; q++ )\n {\n libMesh::NumericVector& dual_solution = system->get_adjoint_solution(q);\n\n const std::string& qoi_name = qoi->get_qoi(q).name();\n std::string filename = this->_vis_output_file_prefix+\"_unsteady_adjoint_\"+qoi_name;\n filename+=\".\"+suffix.str();\n\n system->solution->swap( dual_solution );\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap( dual_solution );\n equation_system->update();\n }\n }\n\n void UnsteadyVisualization::output_solution_sensitivities\n (SharedPtr equation_system,\n MultiphysicsSystem* system,\n const libMesh::ParameterVector & params,\n const unsigned int time_step,\n const libMesh::Real time )\n {\n for (unsigned int p=0; p != params.size(); ++p)\n {\n std::stringstream suffix;\n suffix << time_step;\n\n std::stringstream pstr;\n pstr << p;\n\n std::string filename =\n this->_vis_output_file_prefix + \"_unsteady_dudp\" +\n pstr.str() + '.' + suffix.str();\n\n \/\/ Swap solution with precomputed sensitivity solution\n system->solution->swap(system->get_sensitivity_solution(p));\n equation_system->update();\n\n this->dump_visualization( equation_system, filename, time );\n\n \/\/ Now swap back and reupdate\n system->solution->swap(system->get_sensitivity_solution(p));\n equation_system->update();\n }\n }\n\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"riegeli\/bytes\/zlib_writer.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"absl\/base\/optimization.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"riegeli\/base\/base.h\"\n#include \"riegeli\/base\/recycling_pool.h\"\n#include \"riegeli\/base\/status.h\"\n#include \"riegeli\/bytes\/buffered_writer.h\"\n#include \"riegeli\/bytes\/writer.h\"\n#include \"zconf.h\"\n#include \"zlib.h\"\n\nnamespace riegeli {\n\n\/\/ Before C++17 if a constexpr static data member is ODR-used, its definition at\n\/\/ namespace scope is required. Since C++17 these definitions are deprecated:\n\/\/ http:\/\/en.cppreference.com\/w\/cpp\/language\/static\n#if __cplusplus < 201703\nconstexpr int ZlibWriterBase::Options::kMinCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kMaxCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kDefaultCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kMinWindowLog;\nconstexpr int ZlibWriterBase::Options::kMaxWindowLog;\nconstexpr int ZlibWriterBase::Options::kDefaultWindowLog;\nconstexpr ZlibWriterBase::Header ZlibWriterBase::Options::kDefaultHeader;\n#endif\n\nvoid ZlibWriterBase::Initialize(Writer* dest, int compression_level,\n int window_bits) {\n RIEGELI_ASSERT(dest != nullptr)\n << \"Failed precondition of ZlibWriter: null Writer pointer\";\n if (ABSL_PREDICT_FALSE(!dest->healthy())) {\n Fail(*dest);\n return;\n }\n compressor_ =\n RecyclingPool::global().Get(\n ZStreamKey{compression_level, window_bits},\n [&] {\n std::unique_ptr ptr(new z_stream());\n if (ABSL_PREDICT_FALSE(deflateInit2(ptr.get(), compression_level,\n Z_DEFLATED, window_bits, 8,\n Z_DEFAULT_STRATEGY) != Z_OK)) {\n FailOperation(\"deflateInit2()\");\n }\n return ptr;\n },\n [&](z_stream* ptr) {\n if (ABSL_PREDICT_FALSE(deflateReset(ptr) != Z_OK)) {\n FailOperation(\"deflateReset()\");\n }\n });\n}\n\nvoid ZlibWriterBase::Done() {\n if (ABSL_PREDICT_TRUE(healthy())) {\n Writer& dest = *dest_writer();\n const absl::string_view data(start(), written_to_buffer());\n set_buffer();\n WriteInternal(data, dest, Z_FINISH);\n }\n compressor_.reset();\n BufferedWriter::Done();\n}\n\ninline bool ZlibWriterBase::FailOperation(absl::string_view operation) {\n RIEGELI_ASSERT(!closed())\n << \"Failed precondition of ZlibWriterBase::FailOperation(): \"\n \"Object closed\";\n Writer& dest = *dest_writer();\n std::string message = absl::StrCat(operation, \" failed\");\n if (compressor_->msg != nullptr) {\n absl::StrAppend(&message, \": \", compressor_->msg);\n }\n return Fail(Annotate(absl::InternalError(message),\n absl::StrCat(\"at byte \", dest.pos())));\n}\n\nbool ZlibWriterBase::Fail(absl::Status status) {\n RIEGELI_ASSERT(!status.ok())\n << \"Failed precondition of Object::Fail(): status not failed\";\n return FailWithoutAnnotation(\n Annotate(status, absl::StrCat(\"at uncompressed byte \", pos())));\n}\n\nbool ZlibWriterBase::WriteInternal(absl::string_view src) {\n RIEGELI_ASSERT(!src.empty())\n << \"Failed precondition of BufferedWriter::WriteInternal(): \"\n \"nothing to write\";\n RIEGELI_ASSERT(healthy())\n << \"Failed precondition of BufferedWriter::WriteInternal(): \" << status();\n RIEGELI_ASSERT_EQ(written_to_buffer(), 0u)\n << \"Failed precondition of BufferedWriter::WriteInternal(): \"\n \"buffer not empty\";\n Writer& dest = *dest_writer();\n return WriteInternal(src, dest, Z_NO_FLUSH);\n}\n\ninline bool ZlibWriterBase::WriteInternal(absl::string_view src, Writer& dest,\n int flush) {\n RIEGELI_ASSERT(healthy())\n << \"Failed precondition of ZlibWriterBase::WriteInternal(): \" << status();\n RIEGELI_ASSERT_EQ(written_to_buffer(), 0u)\n << \"Failed precondition of ZlibWriterBase::WriteInternal(): \"\n \"buffer not empty\";\n if (ABSL_PREDICT_FALSE(src.size() >\n std::numeric_limits::max() - limit_pos())) {\n return FailOverflow();\n }\n compressor_->next_in =\n const_cast(reinterpret_cast(src.data()));\n for (;;) {\n \/\/ If `compressor_->avail_out == 0` then `deflate()` returns `Z_BUF_ERROR`,\n \/\/ so `dest.Push()` first.\n if (ABSL_PREDICT_FALSE(!dest.Push())) return Fail(dest);\n size_t avail_in =\n PtrDistance(reinterpret_cast(compressor_->next_in),\n src.data() + src.size());\n int op = flush;\n if (ABSL_PREDICT_FALSE(avail_in > std::numeric_limits::max())) {\n avail_in = size_t{std::numeric_limits::max()};\n op = Z_NO_FLUSH;\n }\n compressor_->avail_in = IntCast(avail_in);\n compressor_->next_out = reinterpret_cast(dest.cursor());\n compressor_->avail_out = SaturatingIntCast(dest.available());\n const int result = deflate(compressor_.get(), op);\n dest.set_cursor(reinterpret_cast(compressor_->next_out));\n const size_t length_written = PtrDistance(\n src.data(), reinterpret_cast(compressor_->next_in));\n switch (result) {\n case Z_OK:\n if (compressor_->avail_out == 0 ||\n ABSL_PREDICT_FALSE(length_written < src.size())) {\n continue;\n }\n break;\n case Z_STREAM_END:\n break;\n case Z_BUF_ERROR:\n RIEGELI_ASSERT_EQ(op, Z_PARTIAL_FLUSH)\n << \"deflate() returned an unexpected Z_BUF_ERROR\";\n break;\n default:\n return FailOperation(\"deflate()\");\n }\n RIEGELI_ASSERT_EQ(length_written, src.size())\n << \"deflate() returned but there are still input data\";\n move_start_pos(length_written);\n return true;\n }\n}\n\nbool ZlibWriterBase::Flush(FlushType flush_type) {\n if (ABSL_PREDICT_FALSE(!healthy())) return false;\n Writer& dest = *dest_writer();\n const absl::string_view data(start(), written_to_buffer());\n set_buffer();\n if (ABSL_PREDICT_FALSE(!WriteInternal(data, dest, Z_PARTIAL_FLUSH))) {\n return false;\n }\n if (ABSL_PREDICT_FALSE(!dest.Flush(flush_type))) return Fail(dest);\n return true;\n}\n\n} \/\/ namespace riegeli\nUse `Z_SYNC_FLUSH` instead of `Z_PARTIAL_FLUSH` in `ZlibWriterBase::Flush()`.\/\/ Copyright 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"riegeli\/bytes\/zlib_writer.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"absl\/base\/optimization.h\"\n#include \"absl\/status\/status.h\"\n#include \"absl\/strings\/str_cat.h\"\n#include \"absl\/strings\/string_view.h\"\n#include \"riegeli\/base\/base.h\"\n#include \"riegeli\/base\/recycling_pool.h\"\n#include \"riegeli\/base\/status.h\"\n#include \"riegeli\/bytes\/buffered_writer.h\"\n#include \"riegeli\/bytes\/writer.h\"\n#include \"zconf.h\"\n#include \"zlib.h\"\n\nnamespace riegeli {\n\n\/\/ Before C++17 if a constexpr static data member is ODR-used, its definition at\n\/\/ namespace scope is required. Since C++17 these definitions are deprecated:\n\/\/ http:\/\/en.cppreference.com\/w\/cpp\/language\/static\n#if __cplusplus < 201703\nconstexpr int ZlibWriterBase::Options::kMinCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kMaxCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kDefaultCompressionLevel;\nconstexpr int ZlibWriterBase::Options::kMinWindowLog;\nconstexpr int ZlibWriterBase::Options::kMaxWindowLog;\nconstexpr int ZlibWriterBase::Options::kDefaultWindowLog;\nconstexpr ZlibWriterBase::Header ZlibWriterBase::Options::kDefaultHeader;\n#endif\n\nvoid ZlibWriterBase::Initialize(Writer* dest, int compression_level,\n int window_bits) {\n RIEGELI_ASSERT(dest != nullptr)\n << \"Failed precondition of ZlibWriter: null Writer pointer\";\n if (ABSL_PREDICT_FALSE(!dest->healthy())) {\n Fail(*dest);\n return;\n }\n compressor_ =\n RecyclingPool::global().Get(\n ZStreamKey{compression_level, window_bits},\n [&] {\n std::unique_ptr ptr(new z_stream());\n if (ABSL_PREDICT_FALSE(deflateInit2(ptr.get(), compression_level,\n Z_DEFLATED, window_bits, 8,\n Z_DEFAULT_STRATEGY) != Z_OK)) {\n FailOperation(\"deflateInit2()\");\n }\n return ptr;\n },\n [&](z_stream* ptr) {\n if (ABSL_PREDICT_FALSE(deflateReset(ptr) != Z_OK)) {\n FailOperation(\"deflateReset()\");\n }\n });\n}\n\nvoid ZlibWriterBase::Done() {\n if (ABSL_PREDICT_TRUE(healthy())) {\n Writer& dest = *dest_writer();\n const absl::string_view data(start(), written_to_buffer());\n set_buffer();\n WriteInternal(data, dest, Z_FINISH);\n }\n compressor_.reset();\n BufferedWriter::Done();\n}\n\ninline bool ZlibWriterBase::FailOperation(absl::string_view operation) {\n RIEGELI_ASSERT(!closed())\n << \"Failed precondition of ZlibWriterBase::FailOperation(): \"\n \"Object closed\";\n Writer& dest = *dest_writer();\n std::string message = absl::StrCat(operation, \" failed\");\n if (compressor_->msg != nullptr) {\n absl::StrAppend(&message, \": \", compressor_->msg);\n }\n return Fail(Annotate(absl::InternalError(message),\n absl::StrCat(\"at byte \", dest.pos())));\n}\n\nbool ZlibWriterBase::Fail(absl::Status status) {\n RIEGELI_ASSERT(!status.ok())\n << \"Failed precondition of Object::Fail(): status not failed\";\n return FailWithoutAnnotation(\n Annotate(status, absl::StrCat(\"at uncompressed byte \", pos())));\n}\n\nbool ZlibWriterBase::WriteInternal(absl::string_view src) {\n RIEGELI_ASSERT(!src.empty())\n << \"Failed precondition of BufferedWriter::WriteInternal(): \"\n \"nothing to write\";\n RIEGELI_ASSERT(healthy())\n << \"Failed precondition of BufferedWriter::WriteInternal(): \" << status();\n RIEGELI_ASSERT_EQ(written_to_buffer(), 0u)\n << \"Failed precondition of BufferedWriter::WriteInternal(): \"\n \"buffer not empty\";\n Writer& dest = *dest_writer();\n return WriteInternal(src, dest, Z_NO_FLUSH);\n}\n\ninline bool ZlibWriterBase::WriteInternal(absl::string_view src, Writer& dest,\n int flush) {\n RIEGELI_ASSERT(healthy())\n << \"Failed precondition of ZlibWriterBase::WriteInternal(): \" << status();\n RIEGELI_ASSERT_EQ(written_to_buffer(), 0u)\n << \"Failed precondition of ZlibWriterBase::WriteInternal(): \"\n \"buffer not empty\";\n if (ABSL_PREDICT_FALSE(src.size() >\n std::numeric_limits::max() - limit_pos())) {\n return FailOverflow();\n }\n compressor_->next_in =\n const_cast(reinterpret_cast(src.data()));\n for (;;) {\n \/\/ If `compressor_->avail_out == 0` then `deflate()` returns `Z_BUF_ERROR`,\n \/\/ so `dest.Push()` first.\n if (ABSL_PREDICT_FALSE(!dest.Push())) return Fail(dest);\n size_t avail_in =\n PtrDistance(reinterpret_cast(compressor_->next_in),\n src.data() + src.size());\n int op = flush;\n if (ABSL_PREDICT_FALSE(avail_in > std::numeric_limits::max())) {\n avail_in = size_t{std::numeric_limits::max()};\n op = Z_NO_FLUSH;\n }\n compressor_->avail_in = IntCast(avail_in);\n compressor_->next_out = reinterpret_cast(dest.cursor());\n compressor_->avail_out = SaturatingIntCast(dest.available());\n const int result = deflate(compressor_.get(), op);\n dest.set_cursor(reinterpret_cast(compressor_->next_out));\n const size_t length_written = PtrDistance(\n src.data(), reinterpret_cast(compressor_->next_in));\n switch (result) {\n case Z_OK:\n if (compressor_->avail_out == 0 ||\n ABSL_PREDICT_FALSE(length_written < src.size())) {\n continue;\n }\n break;\n case Z_STREAM_END:\n break;\n case Z_BUF_ERROR:\n RIEGELI_ASSERT_EQ(op, Z_SYNC_FLUSH)\n << \"deflate() returned an unexpected Z_BUF_ERROR\";\n break;\n default:\n return FailOperation(\"deflate()\");\n }\n RIEGELI_ASSERT_EQ(length_written, src.size())\n << \"deflate() returned but there are still input data\";\n move_start_pos(length_written);\n return true;\n }\n}\n\nbool ZlibWriterBase::Flush(FlushType flush_type) {\n if (ABSL_PREDICT_FALSE(!healthy())) return false;\n Writer& dest = *dest_writer();\n const absl::string_view data(start(), written_to_buffer());\n set_buffer();\n if (ABSL_PREDICT_FALSE(!WriteInternal(data, dest, Z_SYNC_FLUSH))) {\n return false;\n }\n if (ABSL_PREDICT_FALSE(!dest.Flush(flush_type))) return Fail(dest);\n return true;\n}\n\n} \/\/ namespace riegeli\n<|endoftext|>"} {"text":"Roughness error.<|endoftext|>"} {"text":"\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n#include \"args.h\"\n#include \"app.h\"\n#include \"debug.h\"\n#include \"version.h\"\n\n#define HELP_WIDTH 80\n\n#define HELP_PURPOSE_INDENT 0, 4\n#define HELP_ARG_INDENT 8, 20\n#define HELP_OPTION_INDENT 2, 20\n\nnamespace MR\n{\n namespace App\n {\n\n const char* project_version = NULL;\n const char* build_date = __DATE__;\n\n namespace\n {\n\n inline size_t size (const std::string& text)\n {\n return text.size() - 2*std::count (text.begin(), text.end(), 0x08U);\n }\n\n inline void resize (std::string& text, size_t new_size, char fill)\n {\n text.resize (text.size() + new_size - size(text), fill);\n }\n\n\n\n std::string paragraph (\n const std::string& header,\n const std::string& text,\n size_t header_indent,\n size_t indent)\n {\n std::string out, line = std::string (header_indent, ' ') + header + \" \";\n if (size (line) < indent)\n resize (line, indent, ' ');\n\n std::vector paragraphs = split (text, \"\\n\");\n\n for (size_t n = 0; n < paragraphs.size(); ++n) {\n size_t i = 0;\n std::vector words = split (paragraphs[n]);\n while (i < words.size()) {\n do {\n line += \" \" + words[i++];\n if (i >= words.size())\n break;\n }\n while (size (line) + 1 + size (words[i]) < HELP_WIDTH);\n out += line + \"\\n\";\n line = std::string (indent, ' ');\n }\n }\n return out;\n }\n\n\n\n std::string bold (const std::string& text)\n {\n std::string retval (3*text.size(), '\\0');\n for (size_t n = 0; n < text.size(); ++n) {\n retval[3*n] = retval[3*n+2] = text[n];\n retval[3*n+1] = 0x08U;\n }\n return retval;\n }\n\n\n std::string underline (const std::string& text)\n {\n std::string retval (3*text.size(), '\\0');\n for (size_t n = 0; n < text.size(); ++n) {\n retval[3*n] = '_';\n retval[3*n+1] = 0x08U;\n retval[3*n+2] = text[n];\n }\n return retval;\n }\n\n }\n\n\n\n\n\n const char* argtype_description (ArgType type)\n {\n switch (type) {\n case Integer:\n return (\"integer\");\n case Float:\n return (\"float\");\n case Text:\n return (\"string\");\n case ArgFile:\n return (\"file\");\n case ImageIn:\n return (\"image in\");\n case ImageOut:\n return (\"image out\");\n case Choice:\n return (\"choice\");\n case IntSeq:\n return (\"int seq\");\n case FloatSeq:\n return (\"float seq\");\n default:\n return (\"undefined\");\n }\n }\n\n\n\n std::string help_head (int format) \n {\n std::string cmd_version = \n ( project_version ? std::string (\"version \") + project_version + \", external module\" : std::string(\"part\") ) +\n \" of the MRtrix package\\n\\n\";\n\n if (!format) \n return std::string (NAME) + \": \" + cmd_version;\n\n std::string mrtrix_version = \"MRtrix \" MRTRIX_GIT_VERSION;\n std::string date (build_date);\n\n std::string topline = mrtrix_version + std::string (40-size(mrtrix_version)-size(App::NAME)\/2, ' ') + bold (App::NAME);\n topline += std::string (80-size(topline)-size(date), ' ') + date;\n \n return topline + \"\\n\\n \" + bold (NAME) + \": \" + cmd_version;\n }\n\n\n\n\n std::string help_tail (int format) \n {\n std::string retval;\n if (!format) \n return retval;\n\n return bold (\"AUTHOR\") + \"\\n\" \n + paragraph (\"\", AUTHOR, HELP_PURPOSE_INDENT) + \"\\n\"\n + bold (\"COPYRIGHT\") + \"\\n\" \n + paragraph (\"\", COPYRIGHT, HELP_PURPOSE_INDENT) + \"\\n\";\n }\n\n\n\n\n\n\n\n std::string Description::syntax (int format) const\n {\n std::string s;\n if (format) \n s += bold (\"DESCRIPTION\") + \"\\n\\n\";\n for (size_t i = 0; i < size(); ++i) \n s += paragraph (\"\", (*this)[i], HELP_PURPOSE_INDENT) + \"\\n\";\n return s;\n }\n\n\n\n\n std::string help_syntax (int format)\n {\n std::string s = \"SYNOPSIS\";\n if (format)\n s = bold (s) + \"\\n\\n \";\n else \n s += \": \";\n s += ( format ? underline (NAME) : NAME ) + \" [ options ]\";\n\n for (size_t i = 0; i < ARGUMENTS.size(); ++i) {\n\n if (ARGUMENTS[i].flags & Optional)\n s += \"[\";\n s += std::string(\" \") + ARGUMENTS[i].id;\n\n if (ARGUMENTS[i].flags & AllowMultiple) {\n if (! (ARGUMENTS[i].flags & Optional))\n s += std::string(\" [ \") + ARGUMENTS[i].id;\n s += \" ...\";\n }\n if (ARGUMENTS[i].flags & (Optional | AllowMultiple))\n s += \" ]\";\n }\n return s + \"\\n\\n\";\n }\n\n\n\n\n std::string Argument::syntax (int format) const\n {\n std::string retval = paragraph (( format ? underline (id) : id ), desc, HELP_ARG_INDENT);\n if (format) \n retval += \"\\n\";\n return retval;\n }\n\n\n\n\n\n std::string ArgumentList::syntax (int format) const\n {\n std::string s;\n for (size_t i = 0; i < size(); ++i)\n s += (*this)[i].syntax (format);\n return s + \"\\n\";\n }\n\n\n\n\n\n std::string Option::syntax (int format) const\n {\n std::string opt (\"-\");\n opt += id;\n\n if (format)\n opt = underline (opt);\n\n for (size_t i = 0; i < size(); ++i)\n opt += std::string (\" \") + (*this)[i].id;\n\n if (format) \n opt = \" \" + opt + \"\\n\" + paragraph (\"\", desc, HELP_PURPOSE_INDENT);\n else\n opt = paragraph (opt, desc, HELP_OPTION_INDENT);\n if (format) \n opt += \"\\n\";\n return opt;\n }\n\n\n\n\n std::string OptionGroup::header (int format) const\n {\n return format ? bold (name) + \"\\n\\n\" : std::string (name) + \":\\n\";\n }\n\n std::string OptionGroup::contents (int format) const\n {\n std::string s;\n for (size_t i = 0; i < size(); ++i) \n s += (*this)[i].syntax (format);\n return s;\n }\n\n std::string OptionGroup::footer (int format)\n {\n return format ? \"\" : \"\\n\";\n }\n\n\n\n std::string OptionList::syntax (int format) const\n {\n std::vector group_names;\n for (size_t i = 0; i < size(); ++i) {\n if (std::find (group_names.begin(), group_names.end(), (*this)[i].name) == group_names.end()) \n group_names.push_back ((*this)[i].name);\n }\n\n std::string s;\n for (size_t i = 0; i < group_names.size(); ++i) {\n size_t n = i;\n while ((*this)[n].name != group_names[i])\n ++n;\n s += (*this)[n].header (format);\n while (n < size()) {\n if ((*this)[n].name == group_names[i])\n s += (*this)[n].contents (format);\n ++n;\n }\n s += OptionGroup::footer (format);\n }\n\n return s;\n }\n\n\n\n\n\n\n\n\n std::string Argument::usage () const\n {\n std::ostringstream stream;\n stream << \"ARGUMENT \" << id << \" \"\n << (flags & Optional ? '1' : '0') << \" \"\n << (flags & AllowMultiple ? '1' : '0') << \" \";\n\n switch (type) {\n case Integer:\n stream << \"INT \" << defaults.i.min << \" \" << defaults.i.max << \" \" << defaults.i.def;\n break;\n case Float:\n stream << \"FLOAT \" << defaults.f.min << \" \" << defaults.f.max << \" \" << defaults.f.def;\n break;\n case Text:\n stream << \"TEXT\";\n if (defaults.text)\n stream << \" \" << defaults.text;\n break;\n case ArgFile:\n stream << \"FILE\";\n break;\n case Choice:\n stream << \"CHOICE\";\n for (const char* const* p = defaults.choices.list; *p; ++p)\n stream << \" \" << *p;\n stream << \" \" << defaults.choices.def;\n break;\n case ImageIn:\n stream << \"IMAGEIN\";\n break;\n case ImageOut:\n stream << \"IMAGEOUT\";\n break;\n case IntSeq:\n stream << \"ISEQ\";\n break;\n case FloatSeq:\n stream << \"FSEQ\";\n break;\n default:\n assert (0);\n }\n stream << \"\\n\";\n if (desc.size())\n stream << desc << \"\\n\";\n\n return stream.str();\n }\n\n\n\n\n std::string Option::usage () const\n {\n std::ostringstream stream;\n stream << \"OPTION \" << id << \" \"\n << (flags & Optional ? '1' : '0') << \" \"\n << (flags & AllowMultiple ? '1' : '0') << \"\\n\";\n\n if (desc.size())\n stream << desc << \"\\n\";\n\n for (size_t i = 0; i < size(); ++i)\n stream << (*this)[i].usage ();\n \n return stream.str();\n }\n\n\n }\n}\n\n\nChange help page display to prevent crash with long command names\/*\n Copyright 2008 Brain Research Institute, Melbourne, Australia\n\n Written by J-Donald Tournier, 27\/06\/08.\n\n This file is part of MRtrix.\n\n MRtrix is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n MRtrix is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with MRtrix. If not, see .\n\n*\/\n\n#include \"args.h\"\n#include \"app.h\"\n#include \"debug.h\"\n#include \"version.h\"\n\n#define HELP_WIDTH 80\n\n#define HELP_PURPOSE_INDENT 0, 4\n#define HELP_ARG_INDENT 8, 20\n#define HELP_OPTION_INDENT 2, 20\n\nnamespace MR\n{\n namespace App\n {\n\n const char* project_version = NULL;\n const char* build_date = __DATE__;\n\n namespace\n {\n\n inline size_t size (const std::string& text)\n {\n return text.size() - 2*std::count (text.begin(), text.end(), 0x08U);\n }\n\n inline void resize (std::string& text, size_t new_size, char fill)\n {\n text.resize (text.size() + new_size - size(text), fill);\n }\n\n\n\n std::string paragraph (\n const std::string& header,\n const std::string& text,\n size_t header_indent,\n size_t indent)\n {\n std::string out, line = std::string (header_indent, ' ') + header + \" \";\n if (size (line) < indent)\n resize (line, indent, ' ');\n\n std::vector paragraphs = split (text, \"\\n\");\n\n for (size_t n = 0; n < paragraphs.size(); ++n) {\n size_t i = 0;\n std::vector words = split (paragraphs[n]);\n while (i < words.size()) {\n do {\n line += \" \" + words[i++];\n if (i >= words.size())\n break;\n }\n while (size (line) + 1 + size (words[i]) < HELP_WIDTH);\n out += line + \"\\n\";\n line = std::string (indent, ' ');\n }\n }\n return out;\n }\n\n\n\n std::string bold (const std::string& text)\n {\n std::string retval (3*text.size(), '\\0');\n for (size_t n = 0; n < text.size(); ++n) {\n retval[3*n] = retval[3*n+2] = text[n];\n retval[3*n+1] = 0x08U;\n }\n return retval;\n }\n\n\n std::string underline (const std::string& text)\n {\n std::string retval (3*text.size(), '\\0');\n for (size_t n = 0; n < text.size(); ++n) {\n retval[3*n] = '_';\n retval[3*n+1] = 0x08U;\n retval[3*n+2] = text[n];\n }\n return retval;\n }\n\n }\n\n\n\n\n\n const char* argtype_description (ArgType type)\n {\n switch (type) {\n case Integer:\n return (\"integer\");\n case Float:\n return (\"float\");\n case Text:\n return (\"string\");\n case ArgFile:\n return (\"file\");\n case ImageIn:\n return (\"image in\");\n case ImageOut:\n return (\"image out\");\n case Choice:\n return (\"choice\");\n case IntSeq:\n return (\"int seq\");\n case FloatSeq:\n return (\"float seq\");\n default:\n return (\"undefined\");\n }\n }\n\n\n\n std::string help_head (int format) \n {\n std::string cmd_version = \n ( project_version ? std::string (\"version \") + project_version + \", external module\" : std::string(\"part\") ) +\n \" of the MRtrix package\";\n\n if (!format) \n return std::string (NAME) + \": \" + cmd_version + \"\\n\\n\";\n\n std::string mrtrix_version = \"MRtrix \" MRTRIX_GIT_VERSION;\n std::string date (build_date);\n\n std::string topline = mrtrix_version + std::string (80-size(mrtrix_version)-size(date), ' ') + date;\n \n return topline + \"\\n\\n\" + std::string (40-size(NAME)\/2, ' ') + bold (NAME) + \"\\n\\n\" \n + std::string (40-size(cmd_version)\/2, ' ') + cmd_version + \"\\n\\n\";\n }\n\n\n\n\n std::string help_tail (int format) \n {\n std::string retval;\n if (!format) \n return retval;\n\n return bold (\"AUTHOR\") + \"\\n\" \n + paragraph (\"\", AUTHOR, HELP_PURPOSE_INDENT) + \"\\n\"\n + bold (\"COPYRIGHT\") + \"\\n\" \n + paragraph (\"\", COPYRIGHT, HELP_PURPOSE_INDENT) + \"\\n\";\n }\n\n\n\n\n\n\n\n std::string Description::syntax (int format) const\n {\n std::string s;\n if (format) \n s += bold (\"DESCRIPTION\") + \"\\n\\n\";\n for (size_t i = 0; i < size(); ++i) \n s += paragraph (\"\", (*this)[i], HELP_PURPOSE_INDENT) + \"\\n\";\n return s;\n }\n\n\n\n\n std::string help_syntax (int format)\n {\n std::string s = \"SYNOPSIS\";\n if (format)\n s = bold (s) + \"\\n\\n \";\n else \n s += \": \";\n s += ( format ? underline (NAME) : NAME ) + \" [ options ]\";\n\n for (size_t i = 0; i < ARGUMENTS.size(); ++i) {\n\n if (ARGUMENTS[i].flags & Optional)\n s += \"[\";\n s += std::string(\" \") + ARGUMENTS[i].id;\n\n if (ARGUMENTS[i].flags & AllowMultiple) {\n if (! (ARGUMENTS[i].flags & Optional))\n s += std::string(\" [ \") + ARGUMENTS[i].id;\n s += \" ...\";\n }\n if (ARGUMENTS[i].flags & (Optional | AllowMultiple))\n s += \" ]\";\n }\n return s + \"\\n\\n\";\n }\n\n\n\n\n std::string Argument::syntax (int format) const\n {\n std::string retval = paragraph (( format ? underline (id) : id ), desc, HELP_ARG_INDENT);\n if (format) \n retval += \"\\n\";\n return retval;\n }\n\n\n\n\n\n std::string ArgumentList::syntax (int format) const\n {\n std::string s;\n for (size_t i = 0; i < size(); ++i)\n s += (*this)[i].syntax (format);\n return s + \"\\n\";\n }\n\n\n\n\n\n std::string Option::syntax (int format) const\n {\n std::string opt (\"-\");\n opt += id;\n\n if (format)\n opt = underline (opt);\n\n for (size_t i = 0; i < size(); ++i)\n opt += std::string (\" \") + (*this)[i].id;\n\n if (format) \n opt = \" \" + opt + \"\\n\" + paragraph (\"\", desc, HELP_PURPOSE_INDENT);\n else\n opt = paragraph (opt, desc, HELP_OPTION_INDENT);\n if (format) \n opt += \"\\n\";\n return opt;\n }\n\n\n\n\n std::string OptionGroup::header (int format) const\n {\n return format ? bold (name) + \"\\n\\n\" : std::string (name) + \":\\n\";\n }\n\n std::string OptionGroup::contents (int format) const\n {\n std::string s;\n for (size_t i = 0; i < size(); ++i) \n s += (*this)[i].syntax (format);\n return s;\n }\n\n std::string OptionGroup::footer (int format)\n {\n return format ? \"\" : \"\\n\";\n }\n\n\n\n std::string OptionList::syntax (int format) const\n {\n std::vector group_names;\n for (size_t i = 0; i < size(); ++i) {\n if (std::find (group_names.begin(), group_names.end(), (*this)[i].name) == group_names.end()) \n group_names.push_back ((*this)[i].name);\n }\n\n std::string s;\n for (size_t i = 0; i < group_names.size(); ++i) {\n size_t n = i;\n while ((*this)[n].name != group_names[i])\n ++n;\n s += (*this)[n].header (format);\n while (n < size()) {\n if ((*this)[n].name == group_names[i])\n s += (*this)[n].contents (format);\n ++n;\n }\n s += OptionGroup::footer (format);\n }\n\n return s;\n }\n\n\n\n\n\n\n\n\n std::string Argument::usage () const\n {\n std::ostringstream stream;\n stream << \"ARGUMENT \" << id << \" \"\n << (flags & Optional ? '1' : '0') << \" \"\n << (flags & AllowMultiple ? '1' : '0') << \" \";\n\n switch (type) {\n case Integer:\n stream << \"INT \" << defaults.i.min << \" \" << defaults.i.max << \" \" << defaults.i.def;\n break;\n case Float:\n stream << \"FLOAT \" << defaults.f.min << \" \" << defaults.f.max << \" \" << defaults.f.def;\n break;\n case Text:\n stream << \"TEXT\";\n if (defaults.text)\n stream << \" \" << defaults.text;\n break;\n case ArgFile:\n stream << \"FILE\";\n break;\n case Choice:\n stream << \"CHOICE\";\n for (const char* const* p = defaults.choices.list; *p; ++p)\n stream << \" \" << *p;\n stream << \" \" << defaults.choices.def;\n break;\n case ImageIn:\n stream << \"IMAGEIN\";\n break;\n case ImageOut:\n stream << \"IMAGEOUT\";\n break;\n case IntSeq:\n stream << \"ISEQ\";\n break;\n case FloatSeq:\n stream << \"FSEQ\";\n break;\n default:\n assert (0);\n }\n stream << \"\\n\";\n if (desc.size())\n stream << desc << \"\\n\";\n\n return stream.str();\n }\n\n\n\n\n std::string Option::usage () const\n {\n std::ostringstream stream;\n stream << \"OPTION \" << id << \" \"\n << (flags & Optional ? '1' : '0') << \" \"\n << (flags & AllowMultiple ? '1' : '0') << \"\\n\";\n\n if (desc.size())\n stream << desc << \"\\n\";\n\n for (size_t i = 0; i < size(); ++i)\n stream << (*this)[i].usage ();\n \n return stream.str();\n }\n\n\n }\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sky\/shell\/ui\/engine.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/trace_event\/trace_event.h\"\n#include \"mojo\/data_pipe_utils\/data_pipe_utils.h\"\n#include \"mojo\/public\/cpp\/application\/connect.h\"\n#include \"services\/asset_bundle\/zip_asset_bundle.h\"\n#include \"sky\/engine\/bindings\/mojo_services.h\"\n#include \"sky\/engine\/core\/script\/dart_init.h\"\n#include \"sky\/engine\/core\/script\/ui_dart_state.h\"\n#include \"sky\/engine\/public\/platform\/WebInputEvent.h\"\n#include \"sky\/engine\/public\/web\/Sky.h\"\n#include \"sky\/shell\/dart\/dart_library_provider_files.h\"\n#include \"sky\/shell\/shell.h\"\n#include \"sky\/shell\/ui\/animator.h\"\n#include \"sky\/shell\/ui\/flutter_font_selector.h\"\n#include \"sky\/shell\/ui\/platform_impl.h\"\n#include \"third_party\/skia\/include\/core\/SkCanvas.h\"\n#include \"third_party\/skia\/include\/core\/SkPictureRecorder.h\"\n\nnamespace sky {\nnamespace shell {\nnamespace {\n\nPlatformImpl* g_platform_impl = nullptr;\n\n} \/\/ namespace\n\nusing mojo::asset_bundle::ZipAssetBundle;\nusing mojo::asset_bundle::ZipAssetService;\n\nEngine::Config::Config() {}\n\nEngine::Config::~Config() {}\n\nEngine::Engine(const Config& config, rasterizer::RasterizerPtr rasterizer)\n : config_(config),\n animator_(new Animator(config, rasterizer.Pass(), this)),\n binding_(this),\n activity_running_(false),\n have_surface_(false),\n weak_factory_(this) {}\n\nEngine::~Engine() {}\n\nbase::WeakPtr Engine::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\nvoid Engine::Init() {\n TRACE_EVENT0(\"flutter\", \"Engine::Init\");\n\n DCHECK(!g_platform_impl);\n g_platform_impl = new PlatformImpl();\n blink::initialize(g_platform_impl);\n}\n\nstd::unique_ptr Engine::BeginFrame(\n base::TimeTicks frame_time) {\n TRACE_EVENT0(\"flutter\", \"Engine::BeginFrame\");\n\n if (!sky_view_)\n return nullptr;\n\n auto begin_time = base::TimeTicks::Now();\n std::unique_ptr layer_tree =\n sky_view_->BeginFrame(frame_time);\n if (layer_tree) {\n layer_tree->set_scene_version(viewport_metrics_->scene_version);\n layer_tree->set_frame_size(SkISize::Make(viewport_metrics_->physical_width,\n viewport_metrics_->physical_height));\n layer_tree->set_construction_time(base::TimeTicks::Now() - begin_time);\n }\n return layer_tree;\n}\n\nvoid Engine::ConnectToEngine(mojo::InterfaceRequest request) {\n binding_.Bind(request.Pass());\n}\n\nvoid Engine::OnOutputSurfaceCreated(const base::Closure& gpu_continuation) {\n config_.gpu_task_runner->PostTask(FROM_HERE, gpu_continuation);\n have_surface_ = true;\n StartAnimatorIfPossible();\n if (sky_view_)\n ScheduleFrame();\n}\n\nvoid Engine::OnOutputSurfaceDestroyed(const base::Closure& gpu_continuation) {\n have_surface_ = false;\n StopAnimator();\n config_.gpu_task_runner->PostTask(FROM_HERE, gpu_continuation);\n}\n\nvoid Engine::SetServices(ServicesDataPtr services) {\n services_ = services.Pass();\n\n if (services_->incoming_services) {\n incoming_services_ = mojo::ServiceProviderPtr::Create(\n services_->incoming_services.Pass());\n service_provider_impl_.set_fallback_service_provider(\n incoming_services_.get());\n }\n\n if (services_->scene_scheduler) {\n animator_->Reset();\n animator_->set_scene_scheduler(services_->scene_scheduler.Pass());\n } else {\n#if defined(OS_ANDROID) || defined(OS_IOS)\n vsync::VSyncProviderPtr vsync_provider;\n if (services_->shell) {\n \/\/ We bind and unbind our Shell here, since this is the only place we use\n \/\/ it in this class.\n auto shell = mojo::ShellPtr::Create(services_->shell.Pass());\n mojo::ConnectToService(shell.get(), \"mojo:vsync\", &vsync_provider);\n services_->shell = shell.Pass();\n } else {\n mojo::ConnectToService(incoming_services_.get(), &vsync_provider);\n }\n animator_->Reset();\n animator_->set_vsync_provider(vsync_provider.Pass());\n#endif\n }\n}\n\nvoid Engine::OnViewportMetricsChanged(ViewportMetricsPtr metrics) {\n viewport_metrics_ = metrics.Pass();\n if (sky_view_)\n sky_view_->SetViewportMetrics(viewport_metrics_);\n}\n\nvoid Engine::OnLocaleChanged(const mojo::String& language_code,\n const mojo::String& country_code) {\n language_code_ = language_code;\n country_code_ = country_code;\n if (sky_view_)\n sky_view_->SetLocale(language_code_, country_code_);\n}\n\nvoid Engine::OnPointerPacket(pointer::PointerPacketPtr packet) {\n TRACE_EVENT0(\"flutter\", \"Engine::OnPointerPacket\");\n\n \/\/ Convert the pointers' x and y coordinates to logical pixels.\n for (auto it = packet->pointers.begin(); it != packet->pointers.end(); ++it) {\n (*it)->x \/= viewport_metrics_->device_pixel_ratio;\n (*it)->y \/= viewport_metrics_->device_pixel_ratio;\n }\n\n if (sky_view_)\n sky_view_->HandlePointerPacket(packet);\n}\n\nvoid Engine::RunFromLibrary(const std::string& name) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromLibrary\");\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(name);\n sky_view_->RunFromLibrary(name, dart_library_provider_.get());\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::RunFromSnapshotStream(\n const std::string& script_uri,\n mojo::ScopedDataPipeConsumerHandle snapshot) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromSnapshotStream\");\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(script_uri);\n sky_view_->RunFromSnapshot(snapshot.Pass());\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::ConfigureZipAssetBundle(const mojo::String& path) {\n zip_asset_bundle_ = new ZipAssetBundle(base::FilePath(std::string{path}),\n base::WorkerPool::GetTaskRunner(true));\n ZipAssetService::Create(mojo::GetProxy(&root_bundle_), zip_asset_bundle_);\n}\n\nvoid Engine::RunFromPrecompiledSnapshot(const mojo::String& bundle_path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromPrecompiledSnapshot\");\n\n ConfigureZipAssetBundle(bundle_path);\n\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(\"http:\/\/localhost\");\n sky_view_->RunFromPrecompiledSnapshot();\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::RunFromFile(const mojo::String& main,\n const mojo::String& packages,\n const mojo::String& bundle) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromFile\");\n std::string main_str(main);\n if (bundle.size() != 0) {\n \/\/ The specification of an FLX bundle is optional.\n ConfigureZipAssetBundle(bundle);\n }\n base::FilePath packages_path = base::FilePath(std::string(packages));\n if (packages_path.empty()) {\n base::FilePath main_dir = base::FilePath(main_str).DirName();\n packages_path = main_dir.Append(FILE_PATH_LITERAL(\".packages\"));\n if (!base::PathExists(packages_path)) {\n packages_path = main_dir\n .Append(base::FilePath::kParentDirectory)\n .Append(FILE_PATH_LITERAL(\".packages\"));\n if (!base::PathExists(packages_path))\n packages_path = base::FilePath();\n }\n }\n DartLibraryProviderFiles* provider = new DartLibraryProviderFiles();\n dart_library_provider_.reset(provider);\n if (!packages_path.empty())\n provider->LoadPackagesMap(packages_path);\n RunFromLibrary(main_str);\n}\n\nvoid Engine::RunFromBundle(const mojo::String& script_uri,\n const mojo::String& path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromBundle\");\n\n ConfigureZipAssetBundle(path);\n\n root_bundle_->GetAsStream(\n blink::kSnapshotAssetKey,\n base::Bind(&Engine::RunFromSnapshotStream, weak_factory_.GetWeakPtr(),\n script_uri));\n}\n\nvoid Engine::RunFromBundleAndSnapshot(const mojo::String& script_uri,\n const mojo::String& bundle_path,\n const mojo::String& snapshot_path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromBundleAndSnapshot\");\n\n ConfigureZipAssetBundle(bundle_path);\n\n std::string snapshot_path_str = snapshot_path;\n zip_asset_bundle_->AddOverlayFile(blink::kSnapshotAssetKey,\n base::FilePath(snapshot_path_str));\n\n root_bundle_->GetAsStream(\n blink::kSnapshotAssetKey,\n base::Bind(&Engine::RunFromSnapshotStream, weak_factory_.GetWeakPtr(),\n script_uri));\n}\n\nvoid Engine::PushRoute(const mojo::String& route) {\n if (sky_view_)\n sky_view_->PushRoute(route);\n else\n initial_route_ = route;\n}\n\nvoid Engine::PopRoute() {\n if (sky_view_)\n sky_view_->PopRoute();\n}\n\nvoid Engine::OnAppLifecycleStateChanged(sky::AppLifecycleState state) {\n switch (state) {\n case sky::AppLifecycleState::PAUSED:\n activity_running_ = false;\n StopAnimator();\n break;\n\n case sky::AppLifecycleState::RESUMED:\n activity_running_ = true;\n StartAnimatorIfPossible();\n break;\n }\n\n if (sky_view_)\n sky_view_->OnAppLifecycleStateChanged(state);\n}\n\nvoid Engine::DidCreateMainIsolate(Dart_Isolate isolate) {\n mojo::ServiceProviderPtr services_from_embedder;\n service_provider_bindings_.AddBinding(\n &service_provider_impl_, mojo::GetProxy(&services_from_embedder));\n\n blink::MojoServices::Create(\n isolate, services_.Pass(), services_from_embedder.Pass(),\n root_bundle_.Pass());\n\n if (zip_asset_bundle_) {\n FlutterFontSelector::install(zip_asset_bundle_);\n }\n}\n\nvoid Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {\n mojo::ServiceProviderPtr services_from_embedder;\n mojo::InterfaceRequest request =\n mojo::GetProxy(&services_from_embedder);\n blink::Platform::current()->GetUITaskRunner()->PostTask(FROM_HERE,\n base::Bind(&Engine::BindToServiceProvider,\n weak_factory_.GetWeakPtr(),\n base::Passed(&request)));\n\n blink::MojoServices::Create(\n isolate, nullptr, services_from_embedder.Pass(), nullptr);\n}\n\nvoid Engine::BindToServiceProvider(\n mojo::InterfaceRequest request) {\n service_provider_bindings_.AddBinding(&service_provider_impl_,\n request.Pass());\n}\n\nvoid Engine::StopAnimator() {\n animator_->Stop();\n}\n\nvoid Engine::StartAnimatorIfPossible() {\n if (activity_running_ && have_surface_)\n animator_->Start();\n}\n\nvoid Engine::ScheduleFrame() {\n animator_->RequestFrame();\n}\n\nvoid Engine::FlushRealTimeEvents() {\n animator_->FlushRealTimeEvents();\n}\n\nvoid Engine::Render(std::unique_ptr layer_tree) {}\n\n} \/\/ namespace shell\n} \/\/ namespace sky\nFix Mozart crash\/\/ Copyright 2015 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"sky\/shell\/ui\/engine.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_util.h\"\n#include \"base\/threading\/worker_pool.h\"\n#include \"base\/time\/time.h\"\n#include \"base\/trace_event\/trace_event.h\"\n#include \"mojo\/data_pipe_utils\/data_pipe_utils.h\"\n#include \"mojo\/public\/cpp\/application\/connect.h\"\n#include \"services\/asset_bundle\/zip_asset_bundle.h\"\n#include \"sky\/engine\/bindings\/mojo_services.h\"\n#include \"sky\/engine\/core\/script\/dart_init.h\"\n#include \"sky\/engine\/core\/script\/ui_dart_state.h\"\n#include \"sky\/engine\/public\/platform\/WebInputEvent.h\"\n#include \"sky\/engine\/public\/web\/Sky.h\"\n#include \"sky\/shell\/dart\/dart_library_provider_files.h\"\n#include \"sky\/shell\/shell.h\"\n#include \"sky\/shell\/ui\/animator.h\"\n#include \"sky\/shell\/ui\/flutter_font_selector.h\"\n#include \"sky\/shell\/ui\/platform_impl.h\"\n#include \"third_party\/skia\/include\/core\/SkCanvas.h\"\n#include \"third_party\/skia\/include\/core\/SkPictureRecorder.h\"\n\nnamespace sky {\nnamespace shell {\nnamespace {\n\nPlatformImpl* g_platform_impl = nullptr;\n\n} \/\/ namespace\n\nusing mojo::asset_bundle::ZipAssetBundle;\nusing mojo::asset_bundle::ZipAssetService;\n\nEngine::Config::Config() {}\n\nEngine::Config::~Config() {}\n\nEngine::Engine(const Config& config, rasterizer::RasterizerPtr rasterizer)\n : config_(config),\n animator_(new Animator(config, rasterizer.Pass(), this)),\n binding_(this),\n activity_running_(false),\n have_surface_(false),\n weak_factory_(this) {}\n\nEngine::~Engine() {}\n\nbase::WeakPtr Engine::GetWeakPtr() {\n return weak_factory_.GetWeakPtr();\n}\n\nvoid Engine::Init() {\n TRACE_EVENT0(\"flutter\", \"Engine::Init\");\n\n DCHECK(!g_platform_impl);\n g_platform_impl = new PlatformImpl();\n blink::initialize(g_platform_impl);\n}\n\nstd::unique_ptr Engine::BeginFrame(\n base::TimeTicks frame_time) {\n TRACE_EVENT0(\"flutter\", \"Engine::BeginFrame\");\n\n if (!sky_view_)\n return nullptr;\n\n auto begin_time = base::TimeTicks::Now();\n std::unique_ptr layer_tree =\n sky_view_->BeginFrame(frame_time);\n if (layer_tree) {\n if (viewport_metrics_) {\n layer_tree->set_scene_version(viewport_metrics_->scene_version);\n layer_tree->set_frame_size(SkISize::Make(viewport_metrics_->physical_width,\n viewport_metrics_->physical_height));\n } else {\n layer_tree->set_scene_version(0);\n layer_tree->set_frame_size(SkISize::Make(0, 0));\n }\n layer_tree->set_construction_time(base::TimeTicks::Now() - begin_time);\n }\n return layer_tree;\n}\n\nvoid Engine::ConnectToEngine(mojo::InterfaceRequest request) {\n binding_.Bind(request.Pass());\n}\n\nvoid Engine::OnOutputSurfaceCreated(const base::Closure& gpu_continuation) {\n config_.gpu_task_runner->PostTask(FROM_HERE, gpu_continuation);\n have_surface_ = true;\n StartAnimatorIfPossible();\n if (sky_view_)\n ScheduleFrame();\n}\n\nvoid Engine::OnOutputSurfaceDestroyed(const base::Closure& gpu_continuation) {\n have_surface_ = false;\n StopAnimator();\n config_.gpu_task_runner->PostTask(FROM_HERE, gpu_continuation);\n}\n\nvoid Engine::SetServices(ServicesDataPtr services) {\n services_ = services.Pass();\n\n if (services_->incoming_services) {\n incoming_services_ = mojo::ServiceProviderPtr::Create(\n services_->incoming_services.Pass());\n service_provider_impl_.set_fallback_service_provider(\n incoming_services_.get());\n }\n\n if (services_->scene_scheduler) {\n animator_->Reset();\n animator_->set_scene_scheduler(services_->scene_scheduler.Pass());\n } else {\n#if defined(OS_ANDROID) || defined(OS_IOS)\n vsync::VSyncProviderPtr vsync_provider;\n if (services_->shell) {\n \/\/ We bind and unbind our Shell here, since this is the only place we use\n \/\/ it in this class.\n auto shell = mojo::ShellPtr::Create(services_->shell.Pass());\n mojo::ConnectToService(shell.get(), \"mojo:vsync\", &vsync_provider);\n services_->shell = shell.Pass();\n } else {\n mojo::ConnectToService(incoming_services_.get(), &vsync_provider);\n }\n animator_->Reset();\n animator_->set_vsync_provider(vsync_provider.Pass());\n#endif\n }\n}\n\nvoid Engine::OnViewportMetricsChanged(ViewportMetricsPtr metrics) {\n viewport_metrics_ = metrics.Pass();\n if (sky_view_)\n sky_view_->SetViewportMetrics(viewport_metrics_);\n}\n\nvoid Engine::OnLocaleChanged(const mojo::String& language_code,\n const mojo::String& country_code) {\n language_code_ = language_code;\n country_code_ = country_code;\n if (sky_view_)\n sky_view_->SetLocale(language_code_, country_code_);\n}\n\nvoid Engine::OnPointerPacket(pointer::PointerPacketPtr packet) {\n TRACE_EVENT0(\"flutter\", \"Engine::OnPointerPacket\");\n\n \/\/ Convert the pointers' x and y coordinates to logical pixels.\n for (auto it = packet->pointers.begin(); it != packet->pointers.end(); ++it) {\n (*it)->x \/= viewport_metrics_->device_pixel_ratio;\n (*it)->y \/= viewport_metrics_->device_pixel_ratio;\n }\n\n if (sky_view_)\n sky_view_->HandlePointerPacket(packet);\n}\n\nvoid Engine::RunFromLibrary(const std::string& name) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromLibrary\");\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(name);\n sky_view_->RunFromLibrary(name, dart_library_provider_.get());\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::RunFromSnapshotStream(\n const std::string& script_uri,\n mojo::ScopedDataPipeConsumerHandle snapshot) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromSnapshotStream\");\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(script_uri);\n sky_view_->RunFromSnapshot(snapshot.Pass());\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::ConfigureZipAssetBundle(const mojo::String& path) {\n zip_asset_bundle_ = new ZipAssetBundle(base::FilePath(std::string{path}),\n base::WorkerPool::GetTaskRunner(true));\n ZipAssetService::Create(mojo::GetProxy(&root_bundle_), zip_asset_bundle_);\n}\n\nvoid Engine::RunFromPrecompiledSnapshot(const mojo::String& bundle_path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromPrecompiledSnapshot\");\n\n ConfigureZipAssetBundle(bundle_path);\n\n sky_view_ = blink::SkyView::Create(this);\n sky_view_->CreateView(\"http:\/\/localhost\");\n sky_view_->RunFromPrecompiledSnapshot();\n sky_view_->SetViewportMetrics(viewport_metrics_);\n sky_view_->SetLocale(language_code_, country_code_);\n if (!initial_route_.empty())\n sky_view_->PushRoute(initial_route_);\n}\n\nvoid Engine::RunFromFile(const mojo::String& main,\n const mojo::String& packages,\n const mojo::String& bundle) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromFile\");\n std::string main_str(main);\n if (bundle.size() != 0) {\n \/\/ The specification of an FLX bundle is optional.\n ConfigureZipAssetBundle(bundle);\n }\n base::FilePath packages_path = base::FilePath(std::string(packages));\n if (packages_path.empty()) {\n base::FilePath main_dir = base::FilePath(main_str).DirName();\n packages_path = main_dir.Append(FILE_PATH_LITERAL(\".packages\"));\n if (!base::PathExists(packages_path)) {\n packages_path = main_dir\n .Append(base::FilePath::kParentDirectory)\n .Append(FILE_PATH_LITERAL(\".packages\"));\n if (!base::PathExists(packages_path))\n packages_path = base::FilePath();\n }\n }\n DartLibraryProviderFiles* provider = new DartLibraryProviderFiles();\n dart_library_provider_.reset(provider);\n if (!packages_path.empty())\n provider->LoadPackagesMap(packages_path);\n RunFromLibrary(main_str);\n}\n\nvoid Engine::RunFromBundle(const mojo::String& script_uri,\n const mojo::String& path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromBundle\");\n\n ConfigureZipAssetBundle(path);\n\n root_bundle_->GetAsStream(\n blink::kSnapshotAssetKey,\n base::Bind(&Engine::RunFromSnapshotStream, weak_factory_.GetWeakPtr(),\n script_uri));\n}\n\nvoid Engine::RunFromBundleAndSnapshot(const mojo::String& script_uri,\n const mojo::String& bundle_path,\n const mojo::String& snapshot_path) {\n TRACE_EVENT0(\"flutter\", \"Engine::RunFromBundleAndSnapshot\");\n\n ConfigureZipAssetBundle(bundle_path);\n\n std::string snapshot_path_str = snapshot_path;\n zip_asset_bundle_->AddOverlayFile(blink::kSnapshotAssetKey,\n base::FilePath(snapshot_path_str));\n\n root_bundle_->GetAsStream(\n blink::kSnapshotAssetKey,\n base::Bind(&Engine::RunFromSnapshotStream, weak_factory_.GetWeakPtr(),\n script_uri));\n}\n\nvoid Engine::PushRoute(const mojo::String& route) {\n if (sky_view_)\n sky_view_->PushRoute(route);\n else\n initial_route_ = route;\n}\n\nvoid Engine::PopRoute() {\n if (sky_view_)\n sky_view_->PopRoute();\n}\n\nvoid Engine::OnAppLifecycleStateChanged(sky::AppLifecycleState state) {\n switch (state) {\n case sky::AppLifecycleState::PAUSED:\n activity_running_ = false;\n StopAnimator();\n break;\n\n case sky::AppLifecycleState::RESUMED:\n activity_running_ = true;\n StartAnimatorIfPossible();\n break;\n }\n\n if (sky_view_)\n sky_view_->OnAppLifecycleStateChanged(state);\n}\n\nvoid Engine::DidCreateMainIsolate(Dart_Isolate isolate) {\n mojo::ServiceProviderPtr services_from_embedder;\n service_provider_bindings_.AddBinding(\n &service_provider_impl_, mojo::GetProxy(&services_from_embedder));\n\n blink::MojoServices::Create(\n isolate, services_.Pass(), services_from_embedder.Pass(),\n root_bundle_.Pass());\n\n if (zip_asset_bundle_) {\n FlutterFontSelector::install(zip_asset_bundle_);\n }\n}\n\nvoid Engine::DidCreateSecondaryIsolate(Dart_Isolate isolate) {\n mojo::ServiceProviderPtr services_from_embedder;\n mojo::InterfaceRequest request =\n mojo::GetProxy(&services_from_embedder);\n blink::Platform::current()->GetUITaskRunner()->PostTask(FROM_HERE,\n base::Bind(&Engine::BindToServiceProvider,\n weak_factory_.GetWeakPtr(),\n base::Passed(&request)));\n\n blink::MojoServices::Create(\n isolate, nullptr, services_from_embedder.Pass(), nullptr);\n}\n\nvoid Engine::BindToServiceProvider(\n mojo::InterfaceRequest request) {\n service_provider_bindings_.AddBinding(&service_provider_impl_,\n request.Pass());\n}\n\nvoid Engine::StopAnimator() {\n animator_->Stop();\n}\n\nvoid Engine::StartAnimatorIfPossible() {\n if (activity_running_ && have_surface_)\n animator_->Start();\n}\n\nvoid Engine::ScheduleFrame() {\n animator_->RequestFrame();\n}\n\nvoid Engine::FlushRealTimeEvents() {\n animator_->FlushRealTimeEvents();\n}\n\nvoid Engine::Render(std::unique_ptr layer_tree) {}\n\n} \/\/ namespace shell\n} \/\/ namespace sky\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"resource_cache.h\"\n\n#include \n\n#include \"core\/cc\/assert.h\"\n#include \"replay_connection.h\"\n\nnamespace gapir {\n\nResourceCache::ResourceCache(std::unique_ptr fallbackProvider)\n : mFallbackProvider(std::move(fallbackProvider)) {}\n\nbool ResourceCache::get(const Resource* resources, size_t count,\n ReplayConnection* conn, void* target, size_t size) {\n uint8_t* dst = reinterpret_cast(target);\n Batch batch(dst, size);\n for (size_t i = 0; i < count; i++) {\n const Resource& resource = resources[i];\n if (size < resource.size) {\n return false; \/\/ Not enough space\n }\n \/\/ Try fetching the resource from the cache.\n if (getCache(resource, dst)) {\n \/\/ In cache. Flush the pending requests.\n \/\/ Note: This implementation can result in many round trips to the\n \/\/ GAPIS, because whenever a cache hit happens, all the pending\n \/\/ resources accumulated before this resource must be fetched and\n \/\/ loaded prior to the cached resource to be loaded. The original\n \/\/ design was based around the idea that we could load the resource\n \/\/ directly into the destination buffer without temporary copies.\n \/\/ As gRPC forces us to have temporary copies, this implementation\n \/\/ should be changed to have a single fetch.\n \/\/ TODO: Update this batching logic to reduce the number of resource\n \/\/ fetching calls.\n if (!batch.flush(*this, conn)) {\n return false; \/\/ Failed to get resources from fallback provider.\n }\n batch = Batch(dst, size);\n } else {\n \/\/ Not in cache.\n \/\/ Add this to the batch we need to request from the fallback provider.\n batch.append(resource);\n }\n dst += resource.size;\n size -= resource.size;\n }\n return batch.flush(*this, conn);\n}\n\nResourceCache::Batch::Batch(void* target, size_t size)\n : mTarget(reinterpret_cast(target)), mSize(0), mSpace(size) {\n GAPID_ASSERT(target != nullptr);\n}\n\nbool ResourceCache::Batch::append(const Resource& resource) {\n if (mTarget == nullptr) {\n GAPID_FATAL(\"Cannot append after flush.\");\n }\n if (mSpace < resource.size) {\n return false;\n }\n mResources.push_back(resource);\n mSize += resource.size;\n mSpace -= resource.size;\n return true;\n}\n\nbool ResourceCache::Batch::flush(ResourceCache& cache, ReplayConnection* conn) {\n uint8_t* ptr = mTarget;\n mTarget = nullptr; \/\/ nullptr is used for detecting append-after-flush.\n size_t count = mResources.size();\n if (count == 0) {\n return true;\n }\n if (!cache.mFallbackProvider) {\n return false;\n }\n if (!cache.mFallbackProvider->get(mResources.data(), count, conn, ptr,\n mSize)) {\n return false;\n }\n for (auto resource : mResources) {\n cache.putCache(resource, ptr);\n ptr += resource.size;\n }\n return true;\n}\n\n} \/\/ namespace gapir\nLimit the size of replay resource data chunks to reduce memory usage (#2171)\/*\n * Copyright (C) 2017 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"resource_cache.h\"\n\n#include \n\n#include \"core\/cc\/assert.h\"\n#include \"replay_connection.h\"\n\nnamespace gapir {\n\nResourceCache::ResourceCache(std::unique_ptr fallbackProvider)\n : mFallbackProvider(std::move(fallbackProvider)) {}\n\nbool ResourceCache::get(const Resource* resources, size_t count,\n ReplayConnection* conn, void* target, size_t size) {\n uint8_t* dst = reinterpret_cast(target);\n Batch batch(dst, size);\n for (size_t i = 0; i < count; i++) {\n const Resource& resource = resources[i];\n if (size < resource.size) {\n return false; \/\/ Not enough space\n }\n \/\/ Try fetching the resource from the cache.\n if (getCache(resource, dst)) {\n \/\/ In cache. Flush the pending requests.\n \/\/ Note: This implementation can result in many round trips to the\n \/\/ GAPIS, because whenever a cache hit happens, all the pending\n \/\/ resources accumulated before this resource must be fetched and\n \/\/ loaded prior to the cached resource to be loaded. The original\n \/\/ design was based around the idea that we could load the resource\n \/\/ directly into the destination buffer without temporary copies.\n \/\/ As gRPC forces us to have temporary copies, this implementation\n \/\/ should be changed to have a single fetch.\n \/\/ TODO: Update this batching logic to reduce the number of resource\n \/\/ fetching calls.\n if (!batch.flush(*this, conn)) {\n return false; \/\/ Failed to get resources from fallback provider.\n }\n batch = Batch(dst, size);\n } else {\n \/\/ Not in cache.\n \/\/ Add this to the batch we need to request from the fallback provider.\n batch.append(resource);\n }\n dst += resource.size;\n size -= resource.size;\n }\n return batch.flush(*this, conn);\n}\n\nResourceCache::Batch::Batch(void* target, size_t size)\n : mTarget(reinterpret_cast(target)), mSize(0), mSpace(size) {\n GAPID_ASSERT(target != nullptr);\n}\n\nbool ResourceCache::Batch::append(const Resource& resource) {\n if (mTarget == nullptr) {\n GAPID_FATAL(\"Cannot append after flush.\");\n }\n if (mSpace < resource.size) {\n return false;\n }\n mResources.push_back(resource);\n mSize += resource.size;\n mSpace -= resource.size;\n return true;\n}\n\nbool ResourceCache::Batch::flush(ResourceCache& cache, ReplayConnection* conn) {\n uint8_t* ptr = mTarget;\n mTarget = nullptr; \/\/ nullptr is used for detecting append-after-flush.\n size_t count = mResources.size();\n if (count == 0) {\n return true;\n }\n if (!cache.mFallbackProvider) {\n return false;\n }\n size_t one_req_limit =\n 100 * 1024 * 1024; \/\/ limit 100MB unless there is only resource\n size_t i = 0;\n size_t j = 0;\n size_t one_req_size = 0;\n while (i < count) {\n if (((i != j) && (one_req_size + mResources[j].size > one_req_limit)) ||\n (j == mResources.size())) {\n if (!cache.mFallbackProvider->get(&mResources[i], j - i, conn, ptr,\n one_req_size)) {\n return false;\n }\n while (i < j) {\n cache.putCache(mResources[i], ptr);\n ptr += mResources[i].size;\n i++;\n }\n one_req_size = 0;\n }\n if (j < mResources.size()) {\n one_req_size += mResources[j].size;\n j++;\n }\n }\n return true;\n}\n\n} \/\/ namespace gapir\n<|endoftext|>"} {"text":"\/\/ Copyright © 2010-2015 The CefSharp Project. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n#pragma once\n\n#include \"Stdafx.h\"\n\n#include \"CefBrowserWrapper.h\"\n#include \"CefAppUnmanagedWrapper.h\"\n#include \"JavascriptRootObjectWrapper.h\"\n#include \"Serialization\\V8Serialization.h\"\n#include \"..\\CefSharp.Core\\Internals\\Messaging\\Messages.h\"\n#include \"..\\CefSharp.Core\\Internals\\Serialization\\Primitives.h\"\n\nusing namespace System;\nusing namespace System::Diagnostics;\nusing namespace System::Collections::Generic;\nusing namespace CefSharp::Internals::Messaging;\nusing namespace CefSharp::Internals::Serialization;\n\nnamespace CefSharp\n{\n CefRefPtr CefAppUnmanagedWrapper::GetRenderProcessHandler()\n {\n return this;\n };\n\n \/\/ CefRenderProcessHandler\n void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr browser)\n {\n auto wrapper = gcnew CefBrowserWrapper(browser);\n _onBrowserCreated->Invoke(wrapper);\n\n \/\/Multiple CefBrowserWrappers created when opening popups\n _browserWrappers->Add(browser->GetIdentifier(), wrapper);\n }\n\n void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr browser)\n {\n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);\n\n if (wrapper != nullptr)\n {\n _browserWrappers->Remove(wrapper->BrowserId);\n _onBrowserDestroyed->Invoke(wrapper);\n delete wrapper;\n }\n };\n\n void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context)\n {\n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);\n\n if (wrapper->JavascriptRootObject != nullptr)\n {\n auto window = context->GetGlobal();\n\n wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);\n\n wrapper->JavascriptRootObjectWrapper->V8Value = window;\n wrapper->JavascriptRootObjectWrapper->Bind();\n }\n };\n\n void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr browser, CefRefPtr frame, CefRefPtr context)\n { \n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);\n\n if (wrapper->JavascriptRootObjectWrapper != nullptr)\n {\n delete wrapper->JavascriptRootObjectWrapper;\n wrapper->JavascriptRootObjectWrapper = nullptr;\n }\n };\n\n CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)\n {\n CefBrowserWrapper^ wrapper = nullptr;\n\n _browserWrappers->TryGetValue(browserId, wrapper);\n\n if (mustExist && wrapper == nullptr)\n {\n throw gcnew InvalidOperationException(String::Format(\"Failed to identify BrowserWrapper in OnContextCreated. : {0}\", browserId));\n }\n\n return wrapper;\n }\n\n bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr browser, CefProcessId sourceProcessId, CefRefPtr message)\n {\n auto handled = false;\n auto name = message->GetName();\n auto argList = message->GetArgumentList();\n\n auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);\n\n \/\/Error handling for missing\/closed browser\n if (browserWrapper == nullptr)\n {\n if (name == kJavascriptCallbackDestroyRequest)\n {\n \/\/If we can't find the browser wrapper then we'll just\n \/\/ignore this as it's likely already been disposed of\n return true;\n }\n\n CefString responseName;\n if (name == kEvaluateJavascriptRequest)\n {\n responseName = kEvaluateJavascriptResponse;\n }\n else if (name == kJavascriptCallbackRequest)\n {\n responseName = kJavascriptCallbackResponse;\n }\n else\n {\n throw gcnew Exception(\"Unsupported message type\");\n }\n\n auto callbackId = GetInt64(argList, 1);\n auto response = CefProcessMessage::Create(responseName);\n auto responseArgList = response->GetArgumentList();\n auto errorMessage = String::Format(\"Request BrowserId : {0} not found it's likely the browser is already closed\", browser->GetIdentifier());\n\n \/\/success: false\n responseArgList->SetBool(0, false);\n SetInt64(callbackId, responseArgList, 1);\n responseArgList->SetString(2, StringUtils::ToNative(errorMessage));\n browser->SendProcessMessage(sourceProcessId, response);\n\n return true;\n }\n \n \/\/these messages are roughly handled the same way\n if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)\n {\n bool success;\n CefRefPtr result;\n CefString errorMessage;\n CefRefPtr response;\n \/\/both messages have the callbackid stored at index 1\n int64 callbackId = GetInt64(argList, 1);\n\n if (name == kEvaluateJavascriptRequest)\n {\n auto frameId = GetInt64(argList, 0);\n auto script = argList->GetString(2);\n\n response = CefProcessMessage::Create(kEvaluateJavascriptResponse);\n\n auto frame = browser->GetFrame(frameId);\n if (frame.get())\n {\n auto context = frame->GetV8Context();\n \n if (context.get() && context->Enter())\n {\n try\n {\n CefRefPtr exception;\n success = context->Eval(script, result, exception);\n \n \/\/we need to do this here to be able to store the v8context\n if (success)\n {\n auto responseArgList = response->GetArgumentList();\n SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);\n }\n else\n {\n errorMessage = exception->GetMessage();\n }\n }\n finally\n {\n context->Exit();\n }\n }\n else\n {\n errorMessage = \"Unable to Enter Context\";\n }\n }\n else\n {\n errorMessage = \"Unable to Get Frame matching Id\";\n }\n }\n else\n {\n auto jsCallbackId = GetInt64(argList, 0);\n auto parameterList = argList->GetList(2);\n CefV8ValueList params;\n for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)\n {\n params.push_back(DeserializeV8Object(parameterList, static_cast(i)));\n }\n\n response = CefProcessMessage::Create(kJavascriptCallbackResponse);\n\n auto callbackRegistry = browserWrapper->CallbackRegistry;\n auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);\n auto context = callbackWrapper->GetContext();\n auto value = callbackWrapper->GetValue();\n \n if (context.get() && context->Enter())\n {\n try\n {\n result = value->ExecuteFunction(nullptr, params);\n success = result.get() != nullptr;\n \n \/\/we need to do this here to be able to store the v8context\n if (success)\n {\n auto responseArgList = response->GetArgumentList();\n SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);\n }\n else\n {\n auto exception = value->GetException();\n if(exception.get())\n {\n errorMessage = exception->GetMessage();\n }\n }\n }\n finally\n {\n context->Exit();\n }\n }\n else\n {\n errorMessage = \"Unable to Enter Context\";\t\t\t\n } \n }\n\n if (response.get())\n {\n auto responseArgList = response->GetArgumentList();\n responseArgList->SetBool(0, success);\n SetInt64(callbackId, responseArgList, 1);\n if (!success)\n {\n responseArgList->SetString(2, errorMessage);\n }\n browser->SendProcessMessage(sourceProcessId, response);\n }\n\n handled = true;\n }\n else if (name == kJavascriptCallbackDestroyRequest)\n {\n auto jsCallbackId = GetInt64(argList, 1);\n browserWrapper->CallbackRegistry->Deregister(jsCallbackId);\n\n handled = true;\n }\n\n return handled;\n };\n}Add TODO about throwing exception in CefAppUnmanagedWrapper\/\/ Copyright © 2010-2015 The CefSharp Project. All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.\n#pragma once\n\n#include \"Stdafx.h\"\n\n#include \"CefBrowserWrapper.h\"\n#include \"CefAppUnmanagedWrapper.h\"\n#include \"JavascriptRootObjectWrapper.h\"\n#include \"Serialization\\V8Serialization.h\"\n#include \"..\\CefSharp.Core\\Internals\\Messaging\\Messages.h\"\n#include \"..\\CefSharp.Core\\Internals\\Serialization\\Primitives.h\"\n\nusing namespace System;\nusing namespace System::Diagnostics;\nusing namespace System::Collections::Generic;\nusing namespace CefSharp::Internals::Messaging;\nusing namespace CefSharp::Internals::Serialization;\n\nnamespace CefSharp\n{\n CefRefPtr CefAppUnmanagedWrapper::GetRenderProcessHandler()\n {\n return this;\n };\n\n \/\/ CefRenderProcessHandler\n void CefAppUnmanagedWrapper::OnBrowserCreated(CefRefPtr browser)\n {\n auto wrapper = gcnew CefBrowserWrapper(browser);\n _onBrowserCreated->Invoke(wrapper);\n\n \/\/Multiple CefBrowserWrappers created when opening popups\n _browserWrappers->Add(browser->GetIdentifier(), wrapper);\n }\n\n void CefAppUnmanagedWrapper::OnBrowserDestroyed(CefRefPtr browser)\n {\n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), false);\n\n if (wrapper != nullptr)\n {\n _browserWrappers->Remove(wrapper->BrowserId);\n _onBrowserDestroyed->Invoke(wrapper);\n delete wrapper;\n }\n };\n\n void CefAppUnmanagedWrapper::OnContextCreated(CefRefPtr browser, CefRefPtr frame, CefRefPtr context)\n {\n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);\n\n if (wrapper->JavascriptRootObject != nullptr)\n {\n auto window = context->GetGlobal();\n\n wrapper->JavascriptRootObjectWrapper = gcnew JavascriptRootObjectWrapper(wrapper->JavascriptRootObject, wrapper->BrowserProcess);\n\n wrapper->JavascriptRootObjectWrapper->V8Value = window;\n wrapper->JavascriptRootObjectWrapper->Bind();\n }\n };\n\n void CefAppUnmanagedWrapper::OnContextReleased(CefRefPtr browser, CefRefPtr frame, CefRefPtr context)\n { \n auto wrapper = FindBrowserWrapper(browser->GetIdentifier(), true);\n\n if (wrapper->JavascriptRootObjectWrapper != nullptr)\n {\n delete wrapper->JavascriptRootObjectWrapper;\n wrapper->JavascriptRootObjectWrapper = nullptr;\n }\n };\n\n CefBrowserWrapper^ CefAppUnmanagedWrapper::FindBrowserWrapper(int browserId, bool mustExist)\n {\n CefBrowserWrapper^ wrapper = nullptr;\n\n _browserWrappers->TryGetValue(browserId, wrapper);\n\n if (mustExist && wrapper == nullptr)\n {\n throw gcnew InvalidOperationException(String::Format(\"Failed to identify BrowserWrapper in OnContextCreated. : {0}\", browserId));\n }\n\n return wrapper;\n }\n\n bool CefAppUnmanagedWrapper::OnProcessMessageReceived(CefRefPtr browser, CefProcessId sourceProcessId, CefRefPtr message)\n {\n auto handled = false;\n auto name = message->GetName();\n auto argList = message->GetArgumentList();\n\n auto browserWrapper = FindBrowserWrapper(browser->GetIdentifier(), false);\n\n \/\/Error handling for missing\/closed browser\n if (browserWrapper == nullptr)\n {\n if (name == kJavascriptCallbackDestroyRequest)\n {\n \/\/If we can't find the browser wrapper then we'll just\n \/\/ignore this as it's likely already been disposed of\n return true;\n }\n\n CefString responseName;\n if (name == kEvaluateJavascriptRequest)\n {\n responseName = kEvaluateJavascriptResponse;\n }\n else if (name == kJavascriptCallbackRequest)\n {\n responseName = kJavascriptCallbackResponse;\n }\n else\n {\n \/\/TODO: Should be throw an exception here? It's likely that only a CefSharp developer would see this\n \/\/ when they added a new message and havn't yet implemented the render process functionality.\n throw gcnew Exception(\"Unsupported message type\");\n }\n\n auto callbackId = GetInt64(argList, 1);\n auto response = CefProcessMessage::Create(responseName);\n auto responseArgList = response->GetArgumentList();\n auto errorMessage = String::Format(\"Request BrowserId : {0} not found it's likely the browser is already closed\", browser->GetIdentifier());\n\n \/\/success: false\n responseArgList->SetBool(0, false);\n SetInt64(callbackId, responseArgList, 1);\n responseArgList->SetString(2, StringUtils::ToNative(errorMessage));\n browser->SendProcessMessage(sourceProcessId, response);\n\n return true;\n }\n \n \/\/these messages are roughly handled the same way\n if (name == kEvaluateJavascriptRequest || name == kJavascriptCallbackRequest)\n {\n bool success;\n CefRefPtr result;\n CefString errorMessage;\n CefRefPtr response;\n \/\/both messages have the callbackid stored at index 1\n int64 callbackId = GetInt64(argList, 1);\n\n if (name == kEvaluateJavascriptRequest)\n {\n auto frameId = GetInt64(argList, 0);\n auto script = argList->GetString(2);\n\n response = CefProcessMessage::Create(kEvaluateJavascriptResponse);\n\n auto frame = browser->GetFrame(frameId);\n if (frame.get())\n {\n auto context = frame->GetV8Context();\n \n if (context.get() && context->Enter())\n {\n try\n {\n CefRefPtr exception;\n success = context->Eval(script, result, exception);\n \n \/\/we need to do this here to be able to store the v8context\n if (success)\n {\n auto responseArgList = response->GetArgumentList();\n SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);\n }\n else\n {\n errorMessage = exception->GetMessage();\n }\n }\n finally\n {\n context->Exit();\n }\n }\n else\n {\n errorMessage = \"Unable to Enter Context\";\n }\n }\n else\n {\n errorMessage = \"Unable to Get Frame matching Id\";\n }\n }\n else\n {\n auto jsCallbackId = GetInt64(argList, 0);\n auto parameterList = argList->GetList(2);\n CefV8ValueList params;\n for (CefV8ValueList::size_type i = 0; i < parameterList->GetSize(); i++)\n {\n params.push_back(DeserializeV8Object(parameterList, static_cast(i)));\n }\n\n response = CefProcessMessage::Create(kJavascriptCallbackResponse);\n\n auto callbackRegistry = browserWrapper->CallbackRegistry;\n auto callbackWrapper = callbackRegistry->FindWrapper(jsCallbackId);\n auto context = callbackWrapper->GetContext();\n auto value = callbackWrapper->GetValue();\n \n if (context.get() && context->Enter())\n {\n try\n {\n result = value->ExecuteFunction(nullptr, params);\n success = result.get() != nullptr;\n \n \/\/we need to do this here to be able to store the v8context\n if (success)\n {\n auto responseArgList = response->GetArgumentList();\n SerializeV8Object(result, responseArgList, 2, browserWrapper->CallbackRegistry);\n }\n else\n {\n auto exception = value->GetException();\n if(exception.get())\n {\n errorMessage = exception->GetMessage();\n }\n }\n }\n finally\n {\n context->Exit();\n }\n }\n else\n {\n errorMessage = \"Unable to Enter Context\";\t\t\t\n } \n }\n\n if (response.get())\n {\n auto responseArgList = response->GetArgumentList();\n responseArgList->SetBool(0, success);\n SetInt64(callbackId, responseArgList, 1);\n if (!success)\n {\n responseArgList->SetString(2, errorMessage);\n }\n browser->SendProcessMessage(sourceProcessId, response);\n }\n\n handled = true;\n }\n else if (name == kJavascriptCallbackDestroyRequest)\n {\n auto jsCallbackId = GetInt64(argList, 1);\n browserWrapper->CallbackRegistry->Deregister(jsCallbackId);\n\n handled = true;\n }\n\n return handled;\n };\n}<|endoftext|>"} {"text":"#ifndef __AIDA_CXXSTUB_CLIENT_CC__\n#define __AIDA_CXXSTUB_CLIENT_CC__\n\n#include \n\nnamespace { \/\/ Anon\n\nnamespace __AIDA_Local__ {\nusing namespace Aida;\n\nstatic inline sem_t*\nthread_semaphore()\n{\n class DeletableSemaphore {\n DeletableSemaphore (const DeletableSemaphore&) = delete; \/\/ disable copy ctor\n DeletableSemaphore& operator= (const DeletableSemaphore&) = delete; \/\/ disable copy assignment\n public:\n sem_t semaphore = sem_t();\n DeletableSemaphore()\n {\n const int ret = sem_init (&semaphore, 0 \/*pshared*\/, 0 \/*value*\/);\n AIDA_ASSERT_RETURN (ret == 0);\n }\n ~DeletableSemaphore()\n {\n sem_destroy (&semaphore);\n }\n };\n static thread_local DeletableSemaphore thread_local_semaphore;\n return &thread_local_semaphore.semaphore;\n}\n\ntemplate void\nremote_callv (Aida::RemoteHandle &h, void (T::*const mfp) (I...), A... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (h.__iface_ptr__().get());\n std::function wrapper = [semp, self, mfp, &args...] () {\n (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n}\n\ntemplate R\nremote_callr (Aida::RemoteHandle &h, R (T::*const mfp) (I...), A... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (h.__iface_ptr__().get());\n R r {};\n std::function wrapper = [semp, self, mfp, &args..., &r] () {\n r = (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n return r;\n}\n\ntemplate R\nremote_callc (const Aida::RemoteHandle &h, R (T::*const mfp) (I...) const, A... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (const_cast (h).__iface_ptr__().get());\n R r {};\n std::function wrapper = [semp, self, mfp, &args..., &r] () {\n r = (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n return r;\n}\n\n\/\/ helper\nstatic inline ProtoMsg*\nnew_emit_result (const ProtoMsg *fb, uint64 h, uint64 l, uint32 n)\n{\n return ProtoMsg::renew_into_result (const_cast (fb), Aida::MSGID_EMIT_RESULT, h, l, n);\n}\n\n} } \/\/ Anon::__AIDA_Local__\n\n#endif \/\/ __AIDA_CXXSTUB_CLIENT_CC__\nAIDACC: CxxStub-client: remote_call*(): avoid copying instances#ifndef __AIDA_CXXSTUB_CLIENT_CC__\n#define __AIDA_CXXSTUB_CLIENT_CC__\n\n#include \n\nnamespace { \/\/ Anon\n\nnamespace __AIDA_Local__ {\nusing namespace Aida;\n\nstatic inline sem_t*\nthread_semaphore()\n{\n class DeletableSemaphore {\n DeletableSemaphore (const DeletableSemaphore&) = delete; \/\/ disable copy ctor\n DeletableSemaphore& operator= (const DeletableSemaphore&) = delete; \/\/ disable copy assignment\n public:\n sem_t semaphore = sem_t();\n DeletableSemaphore()\n {\n const int ret = sem_init (&semaphore, 0 \/*pshared*\/, 0 \/*value*\/);\n AIDA_ASSERT_RETURN (ret == 0);\n }\n ~DeletableSemaphore()\n {\n sem_destroy (&semaphore);\n }\n };\n static thread_local DeletableSemaphore thread_local_semaphore;\n return &thread_local_semaphore.semaphore;\n}\n\ntemplate void\nremote_callv (Aida::RemoteHandle &h, void (T::*const mfp) (I...), A&... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (h.__iface_ptr__().get());\n std::function wrapper = [semp, self, mfp, &args...] () {\n (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n}\n\ntemplate R\nremote_callr (Aida::RemoteHandle &h, R (T::*const mfp) (I...), A&... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (h.__iface_ptr__().get());\n R r {};\n std::function wrapper = [semp, self, mfp, &args..., &r] () {\n r = (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n return r;\n}\n\ntemplate R\nremote_callc (const Aida::RemoteHandle &h, R (T::*const mfp) (I...) const, A&... args)\n{\n sem_t *const semp = thread_semaphore();\n T *const self = dynamic_cast (const_cast (h).__iface_ptr__().get());\n R r {};\n std::function wrapper = [semp, self, mfp, &args..., &r] () {\n r = (self->*mfp) (args...);\n sem_post (semp);\n };\n self->__execution_context_mt__()->enqueue_mt (&wrapper);\n sem_wait (semp);\n return r;\n}\n\n\/\/ helper\nstatic inline ProtoMsg*\nnew_emit_result (const ProtoMsg *fb, uint64 h, uint64 l, uint32 n)\n{\n return ProtoMsg::renew_into_result (const_cast (fb), Aida::MSGID_EMIT_RESULT, h, l, n);\n}\n\n} } \/\/ Anon::__AIDA_Local__\n\n#endif \/\/ __AIDA_CXXSTUB_CLIENT_CC__\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cfg\/cfg_init.h\"\n#include \"cfg\/cfg_interface.h\"\n#include \"oper\/operdb_init.h\"\n#include \"controller\/controller_init.h\"\n#include \"pkt\/pkt_init.h\"\n#include \"services\/services_init.h\"\n#include \"ksync\/ksync_init.h\"\n#include \"oper\/agent_route_walker.h\"\n#include \"openstack\/instance_service_server.h\"\n#include \"test_cmn_util.h\"\n#include \"kstate\/test\/test_kstate_util.h\"\n#include \"vr_types.h\"\n\nusing namespace std;\n\nvoid RouterIdDepInit() {\n}\n\nstatic void ValidateSandeshResponse(Sandesh *sandesh, vector &result) {\n \/\/TBD\n \/\/Validate the response by the expectation\n}\n\nstruct PortInfo input_1[] = {\n {\"vnet1\", 1, \"1.1.1.10\", \"00:00:01:01:01:10\", 1, 1},\n};\n\nstruct PortInfo input_2[] = {\n {\"vnet2\", 2, \"2.2.2.20\", \"00:00:02:02:02:20\", 2, 2},\n};\n\nclass AgentRouteWalkerTest : public AgentRouteWalker, public ::testing::Test {\npublic: \n AgentRouteWalkerTest() : AgentRouteWalker(AgentRouteWalker::ALL),\n default_tunnel_type_(TunnelType::MPLS_GRE) {\n vrf_name_1_ = \"vrf1\";\n vrf_name_2_ = \"vrf2\";\n server_ip_ = Ip4Address::from_string(\"10.1.1.11\");\n local_vm_ip_1_ = Ip4Address::from_string(\"1.1.1.10\");\n local_vm_ip_2_ = Ip4Address::from_string(\"2.2.2.20\");\n remote_vm_ip_ = Ip4Address::from_string(\"1.1.1.11\");\n local_vm_mac_1_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n local_vm_mac_2_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n remote_vm_mac_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n memcpy (local_vm_mac_1_, ether_aton(\"00:00:01:01:01:10\"), \n sizeof(struct ether_addr));\n memcpy (local_vm_mac_2_, ether_aton(\"00:00:02:02:02:20\"), \n sizeof(struct ether_addr));\n memcpy (remote_vm_mac_, ether_aton(\"00:00:01:01:01:11\"), \n sizeof(struct ether_addr));\n route_notifications_ = 0;\n vrf_notifications_ = vrf_notifications_count_ = 0;\n total_rt_vrf_walk_done_ = 0;\n };\n ~AgentRouteWalkerTest() { };\n\n virtual void SetUp() {\n client->Reset();\n VxLanNetworkIdentifierMode(false);\n client->WaitForIdle();\n AddEncapList(\"MPLSoGRE\", \"MPLSoUDP\", \"VXLAN\");\n client->WaitForIdle();\n\n \/\/Create a VRF\n VrfAddReq(vrf_name_1_.c_str());\n VrfAddReq(vrf_name_2_.c_str());\n Agent::GetInstance()->GetDefaultInet4UnicastRouteTable()->AddResolveRoute(\n Agent::GetInstance()->GetDefaultVrf(), server_ip_, 24);\n client->WaitForIdle();\n client->WaitForIdle();\n CreateVmportEnv(input_1, 1);\n CreateVmportEnv(input_2, 1);\n client->WaitForIdle();\n client->Reset();\n }\n\n virtual void TearDown() {\n client->Reset();\n DeleteVmportEnv(input_1, 1, true);\n DeleteVmportEnv(input_2, 1, true);\n client->WaitForIdle();\n DelEncapList();\n client->WaitForIdle();\n\n VrfDelReq(vrf_name_1_.c_str());\n VrfDelReq(vrf_name_2_.c_str());\n client->WaitForIdle();\n WAIT_FOR(100, 100, (VrfFind(vrf_name_1_.c_str()) != true));\n WAIT_FOR(100, 100, (VrfFind(vrf_name_2_.c_str()) != true));\n }\n\n virtual bool RouteWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {\n \/\/Fabric VRF\n \/\/0.0.0.0\/32; 10.1.1.0\/24; 10.1.1.1\/32; 10.1.1.254\/3; 10.1.1.255\/32;\n \/\/169.254.1.3\/32; 169.254.2.4\/32; 255.255.255.255\n \/\/vrf1\n \/\/1.1.1.10\/32; 255.255.255.255; 0:0:1:1:1:10; ff:ff:ff:ff:ff:ff\n \/\/vrf2\n \/\/2.2.2.20\/32; 255.255.255.255; 0:0:2:2:2:20; ff:ff:ff:ff:ff:ff\n route_notifications_++;\n return true;\n }\n\n virtual void RouteWalkDone(DBTableBase *part) {\n total_rt_vrf_walk_done_++;\n }\n\n virtual bool VrfWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {\n vrf_notifications_++;\n VrfEntry *vrf = static_cast(e);\n StartRouteWalk(vrf);\n return true;\n }\n\n virtual void VrfWalkDone(DBTableBase *part) {\n vrf_notifications_count_++;\n }\n\n void VerifyNotifications(uint32_t route_notifications,\n uint32_t vrf_notifications,\n uint32_t vrf_notifications_count,\n uint32_t total_rt_vrf_walk_done) {\n client->WaitForIdle(10);\n WAIT_FOR(100, 1000, (route_notifications_ == route_notifications_));\n ASSERT_TRUE(route_notifications_ == route_notifications);\n ASSERT_TRUE(vrf_notifications_ == vrf_notifications);\n ASSERT_TRUE(vrf_notifications_count_ == vrf_notifications_count);\n ASSERT_TRUE(total_rt_vrf_walk_done_ == total_rt_vrf_walk_done);\n }\n\n TunnelType::Type default_tunnel_type_;\n std::string vrf_name_1_;\n std::string vrf_name_2_;\n Ip4Address local_vm_ip_1_;\n Ip4Address local_vm_ip_2_;\n Ip4Address remote_vm_ip_;\n Ip4Address server_ip_;\n struct ether_addr *local_vm_mac_1_;\n struct ether_addr *local_vm_mac_2_;\n struct ether_addr *remote_vm_mac_;\n static TunnelType::Type type_;\n uint32_t route_notifications_;\n uint32_t vrf_notifications_;\n uint32_t vrf_notifications_count_;\n uint32_t total_rt_vrf_walk_done_;\n RouteTableTypeWalkid route_table_type_walkid_;\n};\n\nTEST_F(AgentRouteWalkerTest, walk_all_routes) {\n client->Reset();\n StartVrfWalk();\n VerifyNotifications(16, 3, 1, 9);\n}\n\nint main(int argc, char **argv) {\n GETUSERARGS();\n\n client = TestInit(init_file, ksync_init);\n int ret = RUN_ALL_TESTS();\n client->WaitForIdle();\n TestShutdown();\n delete client;\n return ret;\n}\nfix test case\/*\n * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \"cfg\/cfg_init.h\"\n#include \"cfg\/cfg_interface.h\"\n#include \"oper\/operdb_init.h\"\n#include \"controller\/controller_init.h\"\n#include \"pkt\/pkt_init.h\"\n#include \"services\/services_init.h\"\n#include \"ksync\/ksync_init.h\"\n#include \"oper\/agent_route_walker.h\"\n#include \"openstack\/instance_service_server.h\"\n#include \"test_cmn_util.h\"\n#include \"kstate\/test\/test_kstate_util.h\"\n#include \"vr_types.h\"\n\nusing namespace std;\n\nvoid RouterIdDepInit() {\n}\n\nstatic void ValidateSandeshResponse(Sandesh *sandesh, vector &result) {\n \/\/TBD\n \/\/Validate the response by the expectation\n}\n\nstruct PortInfo input_1[] = {\n {\"vnet1\", 1, \"1.1.1.10\", \"00:00:01:01:01:10\", 1, 1},\n};\n\nstruct PortInfo input_2[] = {\n {\"vnet2\", 2, \"2.2.2.20\", \"00:00:02:02:02:20\", 2, 2},\n};\n\nclass AgentRouteWalkerTest : public AgentRouteWalker, public ::testing::Test {\npublic: \n AgentRouteWalkerTest() : AgentRouteWalker(AgentRouteWalker::ALL),\n default_tunnel_type_(TunnelType::MPLS_GRE) {\n vrf_name_1_ = \"vrf1\";\n vrf_name_2_ = \"vrf2\";\n server_ip_ = Ip4Address::from_string(\"10.1.1.11\");\n local_vm_ip_1_ = Ip4Address::from_string(\"1.1.1.10\");\n local_vm_ip_2_ = Ip4Address::from_string(\"2.2.2.20\");\n remote_vm_ip_ = Ip4Address::from_string(\"1.1.1.11\");\n local_vm_mac_1_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n local_vm_mac_2_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n remote_vm_mac_ = (struct ether_addr *)malloc(sizeof(struct ether_addr));\n memcpy (local_vm_mac_1_, ether_aton(\"00:00:01:01:01:10\"), \n sizeof(struct ether_addr));\n memcpy (local_vm_mac_2_, ether_aton(\"00:00:02:02:02:20\"), \n sizeof(struct ether_addr));\n memcpy (remote_vm_mac_, ether_aton(\"00:00:01:01:01:11\"), \n sizeof(struct ether_addr));\n route_notifications_ = 0;\n vrf_notifications_ = vrf_notifications_count_ = 0;\n total_rt_vrf_walk_done_ = 0;\n };\n ~AgentRouteWalkerTest() { };\n\n virtual void SetUp() {\n client->Reset();\n VxLanNetworkIdentifierMode(false);\n client->WaitForIdle();\n AddEncapList(\"MPLSoGRE\", \"MPLSoUDP\", \"VXLAN\");\n client->WaitForIdle();\n\n \/\/Create a VRF\n VrfAddReq(vrf_name_1_.c_str());\n VrfAddReq(vrf_name_2_.c_str());\n Agent::GetInstance()->GetDefaultInet4UnicastRouteTable()->AddResolveRoute(\n Agent::GetInstance()->GetDefaultVrf(), server_ip_, 24);\n client->WaitForIdle();\n client->WaitForIdle();\n CreateVmportEnv(input_1, 1);\n CreateVmportEnv(input_2, 1);\n client->WaitForIdle();\n client->Reset();\n }\n\n virtual void TearDown() {\n client->Reset();\n DeleteVmportEnv(input_1, 1, true);\n DeleteVmportEnv(input_2, 1, true);\n client->WaitForIdle();\n DelEncapList();\n client->WaitForIdle();\n\n VrfDelReq(vrf_name_1_.c_str());\n VrfDelReq(vrf_name_2_.c_str());\n client->WaitForIdle();\n WAIT_FOR(100, 100, (VrfFind(vrf_name_1_.c_str()) != true));\n WAIT_FOR(100, 100, (VrfFind(vrf_name_2_.c_str()) != true));\n }\n\n virtual bool RouteWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {\n \/\/Fabric VRF\n \/\/0.0.0.0\/32; 10.1.1.0\/24; 10.1.1.1\/32; 10.1.1.254\/3; 10.1.1.255\/32;\n \/\/169.254.1.3\/32; 169.254.2.4\/32; 255.255.255.255\n \/\/vrf1\n \/\/1.1.1.10\/32; 255.255.255.255; 0:0:1:1:1:10; ff:ff:ff:ff:ff:ff\n \/\/vrf2\n \/\/2.2.2.20\/32; 255.255.255.255; 0:0:2:2:2:20; ff:ff:ff:ff:ff:ff\n route_notifications_++;\n return true;\n }\n\n virtual void RouteWalkDone(DBTableBase *part) {\n total_rt_vrf_walk_done_++;\n }\n\n virtual bool VrfWalkNotify(DBTablePartBase *partition, DBEntryBase *e) {\n vrf_notifications_++;\n VrfEntry *vrf = static_cast(e);\n StartRouteWalk(vrf);\n return true;\n }\n\n virtual void VrfWalkDone(DBTableBase *part) {\n vrf_notifications_count_++;\n }\n\n void VerifyNotifications(uint32_t route_notifications,\n uint32_t vrf_notifications,\n uint32_t vrf_notifications_count,\n uint32_t total_rt_vrf_walk_done) {\n client->WaitForIdle(10);\n WAIT_FOR(100, 1000, (route_notifications_ == route_notifications_));\n ASSERT_TRUE(route_notifications_ == route_notifications);\n ASSERT_TRUE(vrf_notifications_ == vrf_notifications);\n ASSERT_TRUE(vrf_notifications_count_ == vrf_notifications_count);\n ASSERT_TRUE(total_rt_vrf_walk_done_ == total_rt_vrf_walk_done);\n }\n\n TunnelType::Type default_tunnel_type_;\n std::string vrf_name_1_;\n std::string vrf_name_2_;\n Ip4Address local_vm_ip_1_;\n Ip4Address local_vm_ip_2_;\n Ip4Address remote_vm_ip_;\n Ip4Address server_ip_;\n struct ether_addr *local_vm_mac_1_;\n struct ether_addr *local_vm_mac_2_;\n struct ether_addr *remote_vm_mac_;\n static TunnelType::Type type_;\n uint32_t route_notifications_;\n uint32_t vrf_notifications_;\n uint32_t vrf_notifications_count_;\n uint32_t total_rt_vrf_walk_done_;\n RouteWalkerIdList route_table_type_walkid_;\n};\n\nTEST_F(AgentRouteWalkerTest, walk_all_routes) {\n client->Reset();\n StartVrfWalk();\n VerifyNotifications(16, 3, 1, 9);\n}\n\nint main(int argc, char **argv) {\n GETUSERARGS();\n\n client = TestInit(init_file, ksync_init);\n int ret = RUN_ALL_TESTS();\n client->WaitForIdle();\n TestShutdown();\n delete client;\n return ret;\n}\n<|endoftext|>"} {"text":"Modern loop<|endoftext|>"} {"text":"\/\/\n\/\/\n\/\/ C++ Implementation: $MODULE$\n\/\/\n\/\/ Description:\n\/\/\n\/\/\n\/\/ Author: sven , (C) 2003\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n\n#include \"CMetabNameInterface.h\"\n\n#include \"report\/CCopasiContainer.h\"\n#include \"model\/CModel.h\"\n#include \"report\/CKeyFactory.h\" \n\/\/#include \"utilities\/CCopasiVector.h\"\n\nstd::string CMetabNameInterface::empty_string = \"\";\n\nCMetabNameInterface::~CMetabNameInterface()\n{}\n\nconst std::string & CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key)\n{\n CMetab * metab = (CMetab*)(CCopasiContainer*)CKeyFactory::get(key);\n if (metab)\n return getDisplayName(model, *metab);\n else\n return empty_string;\n}\n\nconst std::string & CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab)\n{\n return metab.getName();\n}\n\nstd::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & name)\n{\n CMetab * metab = getMetabolite(model, name);\n if (metab)\n return metab->getKey();\n else\n return empty_string;\n}\n\nCMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & name)\n{\n C_INT32 index = model->findMetabByName(name);\n if (index == -1)\n return NULL;\n else\n return model->getMetabolites()[index];\n}\n\nbool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)\n{\n bool unique = true;\n unsigned C_INT32 i;\n CCopasiVector< CMetab > metabs = model->getMetabolites();\n std::string metabName;\n\n for (i = 0; i < metabs.size(); i++)\n {\n metabName = metabs[i]->getName();\n if (metabName == name)\n {\n if (unique)\n unique = false;\n else\n return true;\n }\n }\n\n return unique;\n}\n\nbool CMetabNameInterface::doesExist(const CModel* model, const std::string & name)\n{\n C_INT32 pos = name.find('{'), i;\n CCompartment *comp;\n CCopasiVectorNS metabs;\n\n if (pos >= 0) \/\/compartment specified, so check if the metabolite exists in this compartment\n {\n if (!pos)\n return false;\n\n std::string metabName = name. substr(0, pos), s;\n C_INT32 len = name.find('}') - pos - 1;\n\n C_INT32 index = model -> findCompartment(name.substr(pos + 1, len));\n if (index < 0) \/\/ the specified compartment does not exist\n return false;\n\n comp = (model->getCompartments())[index];\n metabs = comp->getMetabolites();\n\n for (i = 0; i < metabs.size(); i++)\n {\n s = metabs[i]->getName();\n if (s == metabName)\n return true;\n }\n\n return false;\n }\n else\n \/\/model->findMetab returns -1 if the metabolite is not found and a non-negative integer otherwise\n return (model->findMetabByName(name) + 1);\n}\n\nstd::string CMetabNameInterface::extractCompartmentName(const CModel* model, const std::string & name)\n{\n \/\/ name is expected to be in the format of \"metabolite{compartment}\" or simply \"metabolite\"\n C_INT32 pos1 = name.find('{'), pos2;\n const CCompartment *comp;\n\n if (pos1 > 0) \/\/ extract the compartment name from the string if specified\n {\n pos2 = name.find('}');\n return name.substr(pos1 + 1, pos2 - pos1 - 1);\n }\n else\n {\n CCopasiVector< CMetab > metabs = model->getMetabolites();\n C_INT32 index = model->findMetabByName(name);\n\n if (index < 0) \/\/ the metabolite doesn't exist, so return the first compartment of the model\n {\n CCopasiVectorNS< CCompartment > comps = model->getCompartments();\n comp = comps[0];\n return comp->getName();\n }\n else \/\/return the first compartment where the metabolite is present\n {\n CMetab *metb = metabs[index];\n comp = metb->getCompartment();\n return comp->getName();\n }\n }\n}\n\nstd::string CMetabNameInterface::extractMetabName(const CModel* model, const std::string & name)\n{\n \/\/ name is expected to be in the format of \"metabolite{compartment}\" or simply \"metabolite\"\n C_INT32 namelength = name.find('{');\n\n if (namelength >= 0) \/\/ compartment is specified, so strip that off\n return name.substr(0, namelength);\n else \/\/compartment is not specified\n return name;\n}\n\nbool CMetabNameInterface::isValidMetabName(const std::string name)\n{\n \/\/ a valid name does not contain white spaces, and contains either matching or no curly braces\n C_INT32 pos1, pos2, pos3;\n\n \/\/ make sure the name is not an empty string\n unsigned C_INT32 len = name.length();\n if (len < 1)\n return false;\n\n \/\/ check for white spaces\n pos1 = name.find(\" \");\n if (pos1 >= 0)\n return false;\n\n \/\/ curly braces: '{' is not the first character in the string, and appears before '}'\n \/\/ if present, '}' should be the last character in the string\n pos1 = name.find('{');\n pos2 = name.find('}');\n pos3 = name.rfind('{');\n\n \/\/ ok if no braces appear\n if ((pos1 < 0) && (pos2 < 0))\n return true;\n\n \/\/ ok if only one '{' and one '}', braces match, compartment name is not an empty string, and '}' is the last character\n if ((pos1 > 0) && (pos1 == pos3) && (pos2 > pos1 + 1) && (pos2 + 1 == len))\n return true;\n\n \/\/ otherwise the name is not valid\n return false;\n}\nimplemented the getMetab() method.\/\/\n\/\/\n\/\/ C++ Implementation: $MODULE$\n\/\/\n\/\/ Description:\n\/\/\n\/\/\n\/\/ Author: sven , (C) 2003\n\/\/\n\/\/ Copyright: See COPYING file that comes with this distribution\n\/\/\n\/\/\n\n#include \"CMetabNameInterface.h\"\n\n#include \"report\/CCopasiContainer.h\"\n#include \"model\/CModel.h\"\n#include \"report\/CKeyFactory.h\" \n\/\/#include \"utilities\/CCopasiVector.h\"\n\nstd::string CMetabNameInterface::empty_string = \"\";\n\nCMetabNameInterface::~CMetabNameInterface()\n{}\n\nconst std::string & CMetabNameInterface::getDisplayName(const CModel* model, const std::string & key)\n{\n CMetab * metab = (CMetab*)(CCopasiContainer*)CKeyFactory::get(key);\n if (metab)\n return getDisplayName(model, *metab);\n else\n return empty_string;\n}\n\nconst std::string & CMetabNameInterface::getDisplayName(const CModel* model, const CMetab & metab)\n{\n return metab.getName();\n}\n\nstd::string CMetabNameInterface::getMetaboliteKey(const CModel* model, const std::string & name)\n{\n CMetab * metab = getMetabolite(model, name);\n if (metab)\n return metab->getKey();\n else\n return empty_string;\n}\n\nCMetab * CMetabNameInterface::getMetabolite(const CModel* model, const std::string & name)\n{\n C_INT32 pos = name.find('{');\n\n if (pos >= 0)\n {\n std::string metabName = CMetabNameInterface::extractMetabName(model, name);\n std::string compName = CMetabNameInterface::extractCompartmentName(model, name);\n return (model->getCompartments()[compName])->getMetabolites()[metabName];\n }\n else\n {\n C_INT32 index = model->findMetabByName(name);\n if (index == -1)\n return NULL;\n else\n return model->getMetabolites()[index];\n }\n\n std::string metabName = CMetabNameInterface::extractMetabName(model, name);\n C_INT32 index = model->findMetabByName(name);\n if (index == -1)\n return NULL;\n else\n return model->getMetabolites()[index];\n}\n\nbool CMetabNameInterface::isUnique(const CModel* model, const std::string & name)\n{\n bool unique = true;\n unsigned C_INT32 i;\n CCopasiVector< CMetab > metabs = model->getMetabolites();\n std::string metabName;\n\n for (i = 0; i < metabs.size(); i++)\n {\n metabName = metabs[i]->getName();\n if (metabName == name)\n {\n if (unique)\n unique = false;\n else\n return true;\n }\n }\n\n return unique;\n}\n\nbool CMetabNameInterface::doesExist(const CModel* model, const std::string & name)\n{\n C_INT32 pos = name.find('{'), i;\n CCompartment *comp;\n CCopasiVectorNS metabs;\n\n if (pos >= 0) \/\/compartment specified, so check if the metabolite exists in this compartment\n {\n if (!pos)\n return false;\n\n std::string metabName = name. substr(0, pos), s;\n C_INT32 len = name.find('}') - pos - 1;\n\n C_INT32 index = model -> findCompartment(name.substr(pos + 1, len));\n if (index < 0) \/\/ the specified compartment does not exist\n return false;\n\n comp = (model->getCompartments())[index];\n metabs = comp->getMetabolites();\n\n for (i = 0; i < metabs.size(); i++)\n {\n s = metabs[i]->getName();\n if (s == metabName)\n return true;\n }\n\n return false;\n }\n else\n \/\/model->findMetab returns -1 if the metabolite is not found and a non-negative integer otherwise\n return (model->findMetabByName(name) + 1);\n}\n\nstd::string CMetabNameInterface::extractCompartmentName(const CModel* model, const std::string & name)\n{\n \/\/ name is expected to be in the format of \"metabolite{compartment}\" or simply \"metabolite\"\n C_INT32 pos1 = name.find('{'), pos2;\n const CCompartment *comp;\n\n if (pos1 > 0) \/\/ extract the compartment name from the string if specified\n {\n pos2 = name.find('}');\n return name.substr(pos1 + 1, pos2 - pos1 - 1);\n }\n else\n {\n CCopasiVector< CMetab > metabs = model->getMetabolites();\n C_INT32 index = model->findMetabByName(name);\n\n if (index < 0) \/\/ the metabolite doesn't exist, so return the first compartment of the model\n {\n CCopasiVectorNS< CCompartment > comps = model->getCompartments();\n comp = comps[0];\n return comp->getName();\n }\n else \/\/return the first compartment where the metabolite is present\n {\n CMetab *metb = metabs[index];\n comp = metb->getCompartment();\n return comp->getName();\n }\n }\n}\n\nstd::string CMetabNameInterface::extractMetabName(const CModel* model, const std::string & name)\n{\n \/\/ name is expected to be in the format of \"metabolite{compartment}\" or simply \"metabolite\"\n C_INT32 namelength = name.find('{');\n\n if (namelength >= 0) \/\/ compartment is specified, so strip that off\n return name.substr(0, namelength);\n else \/\/compartment is not specified\n return name;\n}\n\nbool CMetabNameInterface::isValidMetabName(const std::string name)\n{\n \/\/ a valid name does not contain white spaces, and contains either matching or no curly braces\n C_INT32 pos1, pos2, pos3;\n\n \/\/ make sure the name is not an empty string\n unsigned C_INT32 len = name.length();\n if (len < 1)\n return false;\n\n \/\/ check for white spaces\n pos1 = name.find(\" \");\n if (pos1 >= 0)\n return false;\n\n \/\/ curly braces: '{' is not the first character in the string, and appears before '}'\n \/\/ if present, '}' should be the last character in the string\n pos1 = name.find('{');\n pos2 = name.find('}');\n pos3 = name.rfind('{');\n\n \/\/ ok if no braces appear\n if ((pos1 < 0) && (pos2 < 0))\n return true;\n\n \/\/ ok if only one '{' and one '}', braces match, compartment name is not an empty string, and '}' is the last character\n if ((pos1 > 0) && (pos1 == pos3) && (pos2 > pos1 + 1) && (pos2 + 1 == len))\n return true;\n\n \/\/ otherwise the name is not valid\n return false;\n}\n<|endoftext|>"} {"text":"\t\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\/\/ Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).\n\/\/\n\n#include \n#include \n\n#include \"..\/Node.h\"\n#include \"..\/NodeDefinition.h\"\n\n#include \"..\/..\/base\/Logger.h\"\n#include \"..\/..\/graphics\/Pixel32.h\"\n#include \"..\/..\/wrapper\/WrapHelper.h\"\n\nusing namespace std;\nusing namespace boost::python;\n\nnamespace avg {\n\nclass ColorNode : public Node {\npublic:\n\tstatic NodePtr create(const ArgList& Args, bool bFromXML);\n\tstatic NodeDefinition createNodeDefinition();\n\t\n\tColorNode(const ArgList& Args, bool bFromXML);\n\tvirtual ~ColorNode() {}\n\n\tvoid setFillColor(const std::string& sColor);\n const std::string& getFillColor() const;\nprivate:\n\tstd::string m_sFillColorName;\n Pixel32 m_FillColor;\n};\n\nColorNode::ColorNode(const ArgList& Args, bool bFromXML) :\n\tm_sFillColorName(\"FFFFFF\")\n{\n\n ArgMap am = Args.getArgMap();\n ArgMap::iterator i = am.begin();\n while(i != am.end()) {\n string key = i->first;\n string value = Args.getArgVal(key);\n AVG_TRACE(Logger::PLUGIN, \"ColorNode constructed with key=\" << key << \" value=\" << value);\t\n ++i;\n };\n \n\tArgs.setMembers(this);\n\tAVG_TRACE(Logger::PLUGIN, \"ColorNode constructed with \" << m_sFillColorName);\t\n\n m_FillColor = colorStringToColor(m_sFillColorName);\n}\n\nvoid ColorNode::setFillColor(const string& sFillColor)\n{\n\tAVG_TRACE(Logger::PLUGIN, \"setFillColor called with \" << sFillColor);\t\n if (sFillColor != m_sFillColorName) {\n \tm_sFillColorName = sFillColor;\n m_FillColor = colorStringToColor(m_sFillColorName);\n \/\/setDrawNeeded(true);\n }\n}\n\nconst std::string& ColorNode::getFillColor() const\n{\n return m_sFillColorName;\n}\n\nNodePtr ColorNode::create(const ArgList& Args, bool bFromXML)\n{\n\treturn NodePtr(new ColorNode(Args, bFromXML));\n}\n\nNodeDefinition ColorNode::createNodeDefinition()\n{\n\tclass_, boost::noncopyable>(\"ColorNode\", no_init)\n .add_property(\"fillcolor\", make_function(&ColorNode::getFillColor,\n\t\treturn_value_policy()), &ColorNode::setFillColor);\n \n\treturn NodeDefinition(\"colornode\", (NodeBuilder)ColorNode::create)\n\t\t.extendDefinition(Node::createDefinition())\n\t\t.addArg(Arg(\"fillcolor\", \"FFFFFF\", false, \n offsetof(ColorNode, m_sFillColorName)));\n}\n \n}\n\nextern \"C\" avg::NodeDefinition getNodeDefinition() {\n\treturn avg::ColorNode::createNodeDefinition();\n}\n\nstrange test result: ColorNode c'tor gets wrong value for fillcolor from XML parser (on linux only)\t\/\/\n\/\/ libavg - Media Playback Engine. \n\/\/ Copyright (C) 2003-2008 Ulrich von Zadow\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\/\/\n\/\/ Current versions can be found at www.libavg.de\n\/\/\n\/\/ Original author of this file is Jan Boelsche (regular.gonzales@googlemail.com).\n\/\/\n\n#include \n#include \n\n#include \"..\/Node.h\"\n#include \"..\/NodeDefinition.h\"\n\n#include \"..\/..\/base\/Logger.h\"\n#include \"..\/..\/graphics\/Pixel32.h\"\n#include \"..\/..\/wrapper\/WrapHelper.h\"\n\nusing namespace std;\nusing namespace boost::python;\n\nnamespace avg {\n\nclass ColorNode : public Node {\npublic:\n\tstatic NodePtr create(const ArgList& Args, bool bFromXML);\n\tstatic NodeDefinition createNodeDefinition();\n\t\n\tColorNode(const ArgList& Args, bool bFromXML);\n\tvirtual ~ColorNode() {}\n\n\tvoid setFillColor(const std::string& sColor);\n const std::string& getFillColor() const;\nprivate:\n\tstd::string m_sFillColorName;\n Pixel32 m_FillColor;\n};\n\nColorNode::ColorNode(const ArgList& Args, bool bFromXML) :\n\tm_sFillColorName(\"FFFFFF\")\n{\n\n \/* this crashes on mac and linux\n \/\/ probalby the iterator becomes invalid\n ArgMap am = Args.getArgMap();\n ArgMap::iterator i = am.begin();\n while(i != am.end()) {\n string key = i->first;\n string value = Args.getArgVal(key);\n AVG_TRACE(Logger::PLUGIN, \"ColorNode constructed with key=\" << key << \" value=\" << value);\t\n ++i;\n };\n *\/\n \n AVG_TRACE(Logger::PLUGIN, \"ColorNode c'tor gets Argument fillcolor= \" << Args.getArgVal(\"fillcolor\"));\t\n \n\tArgs.setMembers(this);\n\tAVG_TRACE(Logger::PLUGIN, \"ColorNode constructed with \" << m_sFillColorName);\t\n\n m_FillColor = colorStringToColor(m_sFillColorName);\n}\n\nvoid ColorNode::setFillColor(const string& sFillColor)\n{\n\tAVG_TRACE(Logger::PLUGIN, \"setFillColor called with \" << sFillColor);\t\n if (sFillColor != m_sFillColorName) {\n \tm_sFillColorName = sFillColor;\n m_FillColor = colorStringToColor(m_sFillColorName);\n \/\/setDrawNeeded(true);\n }\n}\n\nconst std::string& ColorNode::getFillColor() const\n{\n return m_sFillColorName;\n}\n\nNodePtr ColorNode::create(const ArgList& Args, bool bFromXML)\n{\n\treturn NodePtr(new ColorNode(Args, bFromXML));\n}\n\nNodeDefinition ColorNode::createNodeDefinition()\n{\n\tclass_, boost::noncopyable>(\"ColorNode\", no_init)\n .add_property(\"fillcolor\", make_function(&ColorNode::getFillColor,\n\t\treturn_value_policy()), &ColorNode::setFillColor);\n \n\treturn NodeDefinition(\"colornode\", (NodeBuilder)ColorNode::create)\n\t\t.extendDefinition(Node::createDefinition())\n\t\t.addArg(Arg(\"fillcolor\", \"FFFFFF\", false, \n offsetof(ColorNode, m_sFillColorName)));\n}\n \n}\n\nextern \"C\" avg::NodeDefinition getNodeDefinition() {\n\treturn avg::ColorNode::createNodeDefinition();\n}\n\n<|endoftext|>"} {"text":"\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006, 2007 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/FIXME: can probably trim down these headers\n\/\/ GDAL Headers\n#include \"gdal.h\"\n#include \"gdal_priv.h\"\n#include \"cpl_string.h\"\n#include \"ogr_spatialref.h\"\n#include \"ogr_api.h\"\n\n\/\/ For boost::split\n#include \n\nnamespace vw {\nnamespace cartography {\n\n void read_gdal_georeference( GeoReference& georef, DiskImageResourceGDAL const& resource ) {\n GDALDataset *dataset = static_cast(resource.get_read_dataset_ptr()); \n if (!dataset) \n vw_throw( LogicErr() << \"read_gdal_georeference: Could not read georeference. No file has been opened.\" );\n \n \/\/ Pull the projection and datum information out of the file if available\n if( dataset->GetProjectionRef() != NULL ) {\n\n \/\/ Create a GDAL spatial ref object\n OGRSpatialReference gdal_spatial_ref;\n const char* wkt = dataset->GetProjectionRef();\n char** wkt_ptr = (char**)(&wkt);\n gdal_spatial_ref.importFromWkt(wkt_ptr);\n\n \n \/\/ Read projection information out of the file\n char* proj_str_tmp;\n gdal_spatial_ref.exportToProj4(&proj_str_tmp);\n std::string proj4_str = proj_str_tmp;\n CPLFree( proj_str_tmp );\n \/\/ For debugging:\n \/\/ vw_out(0) << \"PROJ in --> \" << proj4_str << \"\\n\";\n\n std::vector input_strings;\n std::vector output_strings;\n std::vector datum_strings;\n std::string trimmed_proj4_str = boost::trim_copy(proj4_str);\n boost::split( input_strings, trimmed_proj4_str, boost::is_any_of(\" \") ); \n for (unsigned int i = 0; i < input_strings.size(); ++i) {\n\n \/\/ Pick out the parts of the projection string that pertain to\n \/\/ map projections. We essentially want to eliminate all of\n \/\/ the strings that have to do with the datum, since those are\n \/\/ handled by interacting directly with the\n \/\/ OGRSpatialReference below. This is sort of messy, but it's\n \/\/ the easiest way to do this, as far as I can tell.\n if ((input_strings[i].find(\"+proj=\") == 0) || \n (input_strings[i].find(\"+x_0=\") == 0) || \n (input_strings[i].find(\"+y_0=\") == 0) ||\n (input_strings[i].find(\"+lon\") == 0) || \n (input_strings[i].find(\"+lat\") == 0) || \n (input_strings[i].find(\"+k=\") == 0) || \n (input_strings[i].find(\"+lat_ts=\") == 0) || \n (input_strings[i].find(\"+ns\") == 0) || \n (input_strings[i].find(\"+no_cut\") == 0) || \n (input_strings[i].find(\"+h=\") == 0) || \n (input_strings[i].find(\"+W=\") == 0) || \n (input_strings[i].find(\"+units=\") == 0) ||\n (input_strings[i].find(\"+zone=\") == 0)) {\n output_strings.push_back(input_strings[i]);\n } else if ((input_strings[i].find(\"+ellps=\") == 0) ||\n (input_strings[i].find(\"+datum=\") == 0)) {\n \/\/ We put these in the proj4_str for the Datum class.\n datum_strings.push_back(input_strings[i]);\n }\n }\n std::ostringstream strm;\n for (unsigned int i = 0; i < output_strings.size(); ++i) {\n strm << output_strings[i] << \" \";\n }\n \/\/ For debugging:\n \/\/ vw_out(0) << \" out --> \" << strm.str() << \"\\n\";\n\n \/\/ If the file contains no projection related information, we\n \/\/ supply proj.4 with a \"default\" interpretation that the file\n \/\/ is in geographic (unprojected) coordinates.\n if (output_strings.size() == 0) \n georef.set_proj4_projection_str(\"+proj=longlat\");\n else\n georef.set_proj4_projection_str(strm.str());\n \n \/\/ Read in the datum information\n Datum datum;\n const char* datum_name = gdal_spatial_ref.GetAttrValue(\"DATUM\");\n if (datum_name) { datum.name() = datum_name; }\n const char* spheroid_name = gdal_spatial_ref.GetAttrValue(\"SPHEROID\");\n if (spheroid_name) { datum.spheroid_name() = spheroid_name; }\n const char* meridian_name = gdal_spatial_ref.GetAttrValue(\"PRIMEM\");\n if (meridian_name) { datum.meridian_name() = meridian_name; }\n OGRErr e1, e2;\n double semi_major = gdal_spatial_ref.GetSemiMajor(&e1);\n double semi_minor = gdal_spatial_ref.GetSemiMinor(&e2);\n if (e1 != OGRERR_FAILURE && e2 != OGRERR_FAILURE) { \n datum.set_semi_major_axis(semi_major);\n datum.set_semi_minor_axis(semi_minor);\n }\n datum.meridian_offset() = gdal_spatial_ref.GetPrimeMeridian();\n \/\/ Set the proj4 string for datum.\n std::stringstream datum_proj4_ss;\n for(unsigned i=0; i < datum_strings.size(); i++)\n datum_proj4_ss << datum_strings[i] << ' ';\n \/\/ Add the current proj4 string in the case that our ellipse\/datum \n \/\/ values are empty.\n if(boost::trim_copy(datum_proj4_ss.str()) == \"\")\n datum_proj4_ss << datum.proj4_str();\n datum.proj4_str() = boost::trim_copy(datum_proj4_ss.str());\n georef.set_datum(datum);\n }\n \n double geo_transform[6];\n Matrix transform;\n if( dataset->GetGeoTransform( geo_transform ) == CE_None ) {\n transform.set_identity();\n transform(0,0) = geo_transform[1];\n transform(0,1) = geo_transform[2];\n transform(0,2) = geo_transform[0];\n transform(1,0) = geo_transform[4];\n transform(1,1) = geo_transform[5];\n transform(1,2) = geo_transform[3];\n georef.set_transform(transform);\n\n \/\/ Determine the pixel interpretation for the image. See the\n \/\/ comments in GeoReference for more information. If nothing is\n \/\/ encoded in the file, the default is to assume PixelAsArea.\n georef.set_pixel_interpretation(GeoReference::PixelAsArea);\n char **metadata = dataset->GetMetadata();\n if( CSLCount(metadata) > 0 ) {\n for( int i = 0; metadata[i] != NULL; i++ ) {\n std::vector split_vec;\n boost::split(split_vec, metadata[i], boost::is_any_of(\"=\") );\n if (split_vec[0] == GDALMD_AREA_OR_POINT && split_vec.size() >= 2) \n if (boost::trim_copy(split_vec[1]) == GDALMD_AOP_POINT)\n georef.set_pixel_interpretation(GeoReference::PixelAsPoint);\n }\n }\n }\n\n \/\/ Georeference functions need not be invertible. When we perform a reverse \n \/\/ lookup (e.g. during a geotransformation) we rely on PROJ.4 to pick one \n \/\/ possible value. However, the georeference might actually place the image \n \/\/ at another (equivalent) location in the projected space. This is hard to \n \/\/ recover from at run-time, and we currently have no generic solution to this \n \/\/ problem. In the mean time, we at least test whether the georefernce is \n \/\/ likely to run into this problem (and warn the user) by checking whether \n \/\/ forward- and reverse-projecting the origin pixel lands us back at the origin.\n Vector2 origin = georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );\n if( origin.x()*origin.x() + origin.y()*origin.y() > 0.1 ) {\n vw_out(WarningMessage) << \"read_gdal_georeference(): WARNING! Resource file \" <<\n\tresource.filename() << \" contains a non-normal georeference. Bad things \"\n\t\"may happen: puppies dying, rainbows fading, mortage foreclosures, etc.\" << std::endl;\n }\n }\n\n \n void write_gdal_georeference( DiskImageResourceGDAL& resource, GeoReference const& georef ) {\n\n GDALDataset *dataset = static_cast(resource.get_write_dataset_ptr());\n if (!dataset) \n vw_throw( LogicErr() << \"GeoReferenceHelperGDAL: Could not write georeference. No file has been opened.\" );\n\n \/\/ Store the transform matrix\n double geo_transform[6] = { georef.transform()(0,2), georef.transform()(0,0), georef.transform()(0,1), \n georef.transform()(1,2), georef.transform()(1,0), georef.transform()(1,1) };\n dataset->SetGeoTransform( geo_transform );\n\n \/\/ This is a little ridiculous, but GDAL can't write geotiffs\n \/\/ without a string of Well Known Text (WKT), so we must conjure\n \/\/ up an OGRSpatialReference here and use it to convert from\n \/\/ proj.4 to WKT.\n \/\/ \n \/\/ However, we first set the datum parameters in the\n \/\/ ORGSpatialReference object directly.\n OGRSpatialReference gdal_spatial_ref;\n gdal_spatial_ref.importFromProj4(georef.proj4_str().c_str());\n gdal_spatial_ref.SetGeogCS( \"Geographic Coordinate System\",\n georef.datum().name().c_str(),\n georef.datum().spheroid_name().c_str(),\n georef.datum().semi_major_axis(),\n georef.datum().inverse_flattening(),\n georef.datum().meridian_name().c_str(),\n georef.datum().meridian_offset() );\n\n char* wkt_str_tmp;\n gdal_spatial_ref.exportToWkt(&wkt_str_tmp);\n std::string wkt_str = wkt_str_tmp;\n OGRFree(wkt_str_tmp);\n\n dataset->SetProjection( wkt_str.c_str() );\n\n \/\/ Set the pixel interpretation for the image. See the comments\n \/\/ in GeoReference for more information.\n if (georef.pixel_interpretation() == GeoReference::PixelAsArea) \n dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_AREA);\n else \/\/ PixelAsPoint\n dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_POINT);\n }\n\n}} \/\/ namespace vw::cartography\ngdal UTM zone fix\/\/ __BEGIN_LICENSE__\n\/\/ Copyright (C) 2006, 2007 United States Government as represented by\n\/\/ the Administrator of the National Aeronautics and Space Administration.\n\/\/ All Rights Reserved.\n\/\/ __END_LICENSE__\n\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/FIXME: can probably trim down these headers\n\/\/ GDAL Headers\n#include \"gdal.h\"\n#include \"gdal_priv.h\"\n#include \"cpl_string.h\"\n#include \"ogr_spatialref.h\"\n#include \"ogr_api.h\"\n\n\/\/ For boost::split\n#include \n\nnamespace vw {\nnamespace cartography {\n\n void read_gdal_georeference( GeoReference& georef, DiskImageResourceGDAL const& resource ) {\n GDALDataset *dataset = static_cast(resource.get_read_dataset_ptr()); \n if (!dataset) \n vw_throw( LogicErr() << \"read_gdal_georeference: Could not read georeference. No file has been opened.\" );\n \n \/\/ Pull the projection and datum information out of the file if available\n if( dataset->GetProjectionRef() != NULL ) {\n\n \/\/ Create a GDAL spatial ref object\n OGRSpatialReference gdal_spatial_ref;\n const char* wkt = dataset->GetProjectionRef();\n char** wkt_ptr = (char**)(&wkt);\n gdal_spatial_ref.importFromWkt(wkt_ptr);\n\n \n \/\/ Read projection information out of the file\n char* proj_str_tmp;\n gdal_spatial_ref.exportToProj4(&proj_str_tmp);\n std::string proj4_str = proj_str_tmp;\n CPLFree( proj_str_tmp );\n \/\/ For debugging:\n \/\/ vw_out(0) << \"PROJ in --> \" << proj4_str << \"\\n\";\n\n std::vector input_strings;\n std::vector output_strings;\n std::vector datum_strings;\n std::string trimmed_proj4_str = boost::trim_copy(proj4_str);\n boost::split( input_strings, trimmed_proj4_str, boost::is_any_of(\" \") ); \n for (unsigned int i = 0; i < input_strings.size(); ++i) {\n\n \/\/ Pick out the parts of the projection string that pertain to\n \/\/ map projections. We essentially want to eliminate all of\n \/\/ the strings that have to do with the datum, since those are\n \/\/ handled by interacting directly with the\n \/\/ OGRSpatialReference below. This is sort of messy, but it's\n \/\/ the easiest way to do this, as far as I can tell.\n if ((input_strings[i].find(\"+proj=\") == 0) || \n (input_strings[i].find(\"+x_0=\") == 0) || \n (input_strings[i].find(\"+y_0=\") == 0) ||\n (input_strings[i].find(\"+lon\") == 0) || \n (input_strings[i].find(\"+lat\") == 0) || \n (input_strings[i].find(\"+k=\") == 0) || \n (input_strings[i].find(\"+lat_ts=\") == 0) || \n (input_strings[i].find(\"+ns\") == 0) || \n (input_strings[i].find(\"+no_cut\") == 0) || \n (input_strings[i].find(\"+h=\") == 0) || \n (input_strings[i].find(\"+W=\") == 0) || \n (input_strings[i].find(\"+units=\") == 0) ||\n (input_strings[i].find(\"+zone=\") == 0)) {\n output_strings.push_back(input_strings[i]);\n } else if ((input_strings[i].find(\"+ellps=\") == 0) ||\n (input_strings[i].find(\"+datum=\") == 0)) {\n \/\/ We put these in the proj4_str for the Datum class.\n datum_strings.push_back(input_strings[i]);\n }\n }\n std::ostringstream strm;\n for (unsigned int i = 0; i < output_strings.size(); ++i) {\n strm << output_strings[i] << \" \";\n }\n \/\/ For debugging:\n \/\/ vw_out(0) << \" out --> \" << strm.str() << \"\\n\";\n\n \/\/ If the file contains no projection related information, we\n \/\/ supply proj.4 with a \"default\" interpretation that the file\n \/\/ is in geographic (unprojected) coordinates.\n if (output_strings.size() == 0) \n georef.set_proj4_projection_str(\"+proj=longlat\");\n else\n georef.set_proj4_projection_str(strm.str());\n \n int utm_north = 0;\n int utm_zone = gdal_spatial_ref.GetUTMZone(&utm_north);\n if (utm_zone)\n georef.set_UTM(utm_zone, utm_north);\n\n \/\/ Read in the datum information\n Datum datum;\n const char* datum_name = gdal_spatial_ref.GetAttrValue(\"DATUM\");\n if (datum_name) { datum.name() = datum_name; }\n const char* spheroid_name = gdal_spatial_ref.GetAttrValue(\"SPHEROID\");\n if (spheroid_name) { datum.spheroid_name() = spheroid_name; }\n const char* meridian_name = gdal_spatial_ref.GetAttrValue(\"PRIMEM\");\n if (meridian_name) { datum.meridian_name() = meridian_name; }\n OGRErr e1, e2;\n double semi_major = gdal_spatial_ref.GetSemiMajor(&e1);\n double semi_minor = gdal_spatial_ref.GetSemiMinor(&e2);\n if (e1 != OGRERR_FAILURE && e2 != OGRERR_FAILURE) { \n datum.set_semi_major_axis(semi_major);\n datum.set_semi_minor_axis(semi_minor);\n }\n datum.meridian_offset() = gdal_spatial_ref.GetPrimeMeridian();\n \/\/ Set the proj4 string for datum.\n std::stringstream datum_proj4_ss;\n for(unsigned i=0; i < datum_strings.size(); i++)\n datum_proj4_ss << datum_strings[i] << ' ';\n \/\/ Add the current proj4 string in the case that our ellipse\/datum \n \/\/ values are empty.\n if(boost::trim_copy(datum_proj4_ss.str()) == \"\")\n datum_proj4_ss << datum.proj4_str();\n datum.proj4_str() = boost::trim_copy(datum_proj4_ss.str());\n georef.set_datum(datum);\n }\n \n double geo_transform[6];\n Matrix transform;\n if( dataset->GetGeoTransform( geo_transform ) == CE_None ) {\n transform.set_identity();\n transform(0,0) = geo_transform[1];\n transform(0,1) = geo_transform[2];\n transform(0,2) = geo_transform[0];\n transform(1,0) = geo_transform[4];\n transform(1,1) = geo_transform[5];\n transform(1,2) = geo_transform[3];\n georef.set_transform(transform);\n\n \/\/ Determine the pixel interpretation for the image. See the\n \/\/ comments in GeoReference for more information. If nothing is\n \/\/ encoded in the file, the default is to assume PixelAsArea.\n georef.set_pixel_interpretation(GeoReference::PixelAsArea);\n char **metadata = dataset->GetMetadata();\n if( CSLCount(metadata) > 0 ) {\n for( int i = 0; metadata[i] != NULL; i++ ) {\n std::vector split_vec;\n boost::split(split_vec, metadata[i], boost::is_any_of(\"=\") );\n if (split_vec[0] == GDALMD_AREA_OR_POINT && split_vec.size() >= 2) \n if (boost::trim_copy(split_vec[1]) == GDALMD_AOP_POINT)\n georef.set_pixel_interpretation(GeoReference::PixelAsPoint);\n }\n }\n }\n\n \/\/ Georeference functions need not be invertible. When we perform a reverse \n \/\/ lookup (e.g. during a geotransformation) we rely on PROJ.4 to pick one \n \/\/ possible value. However, the georeference might actually place the image \n \/\/ at another (equivalent) location in the projected space. This is hard to \n \/\/ recover from at run-time, and we currently have no generic solution to this \n \/\/ problem. In the mean time, we at least test whether the georefernce is \n \/\/ likely to run into this problem (and warn the user) by checking whether \n \/\/ forward- and reverse-projecting the origin pixel lands us back at the origin.\n Vector2 origin = georef.lonlat_to_pixel( georef.pixel_to_lonlat( Vector2() ) );\n if( origin.x()*origin.x() + origin.y()*origin.y() > 0.1 ) {\n vw_out(WarningMessage) << \"read_gdal_georeference(): WARNING! Resource file \" <<\n\tresource.filename() << \" contains a non-normal georeference. Bad things \"\n\t\"may happen: puppies dying, rainbows fading, mortage foreclosures, etc.\" << std::endl;\n }\n }\n\n \n void write_gdal_georeference( DiskImageResourceGDAL& resource, GeoReference const& georef ) {\n\n GDALDataset *dataset = static_cast(resource.get_write_dataset_ptr());\n if (!dataset) \n vw_throw( LogicErr() << \"GeoReferenceHelperGDAL: Could not write georeference. No file has been opened.\" );\n\n \/\/ Store the transform matrix\n double geo_transform[6] = { georef.transform()(0,2), georef.transform()(0,0), georef.transform()(0,1), \n georef.transform()(1,2), georef.transform()(1,0), georef.transform()(1,1) };\n dataset->SetGeoTransform( geo_transform );\n\n \/\/ This is a little ridiculous, but GDAL can't write geotiffs\n \/\/ without a string of Well Known Text (WKT), so we must conjure\n \/\/ up an OGRSpatialReference here and use it to convert from\n \/\/ proj.4 to WKT.\n \/\/ \n \/\/ However, we first set the datum parameters in the\n \/\/ ORGSpatialReference object directly.\n OGRSpatialReference gdal_spatial_ref;\n gdal_spatial_ref.importFromProj4(georef.proj4_str().c_str());\n gdal_spatial_ref.SetGeogCS( \"Geographic Coordinate System\",\n georef.datum().name().c_str(),\n georef.datum().spheroid_name().c_str(),\n georef.datum().semi_major_axis(),\n georef.datum().inverse_flattening(),\n georef.datum().meridian_name().c_str(),\n georef.datum().meridian_offset() );\n\n char* wkt_str_tmp;\n gdal_spatial_ref.exportToWkt(&wkt_str_tmp);\n std::string wkt_str = wkt_str_tmp;\n OGRFree(wkt_str_tmp);\n\n dataset->SetProjection( wkt_str.c_str() );\n\n \/\/ Set the pixel interpretation for the image. See the comments\n \/\/ in GeoReference for more information.\n if (georef.pixel_interpretation() == GeoReference::PixelAsArea) \n dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_AREA);\n else \/\/ PixelAsPoint\n dataset->SetMetadataItem(GDALMD_AREA_OR_POINT, GDALMD_AOP_POINT);\n }\n\n}} \/\/ namespace vw::cartography\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"Commit.h\"\n\nnamespace FilePersistence {\n\nSignature::Signature()\n{\n\tdateTime_ = QDateTime::currentDateTimeUtc();\n\ttimeZone_ = QTimeZone(QTimeZone::systemTimeZoneId());\n}\n\nCommitFile::CommitFile()\n{\n\trelativePath_ = QString();\n\tsize_ = 0;\n\tcontent_ = nullptr;\n}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, const char* content)\n{\n\trelativePath_ = relativePath;\n\tsize_ = size;\n\tcontent_ = content;\n}\n\nCommitFile::~CommitFile()\n{\n\tdelete[] content_;\n}\n\nCommit::Commit() {}\n\nCommit::~Commit()\n{\n\tfor (auto file : files_.values())\n\t\tdelete file;\n}\n\nvoid Commit::setMetaData(CommitMetaData data)\n{\n\tinformation_ = data;\n}\n\nCommitMetaData Commit::metaData() const\n{\n\treturn information_;\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, const char* content)\n{\n\tfiles_.insert(relativePath, new CommitFile(relativePath, size, content));\n}\n\nbool Commit::getFileContent(QString fileName, const char*& content, int& contentSize) const\n{\n\tQHash::const_iterator iter = files_.find(fileName);\n\tif (iter != files_.constEnd())\n\t{\n\t\tcontentSize = iter.value()->size_;\n\t\tcontent = iter.value()->content_;\n\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\n} \/* namespace FilePersistence *\/\nUse SAFE_DELETE in destructor of Commit\/***********************************************************************************************************************\n**\n** Copyright (c) 2011, 2014 ETH Zurich\n** All rights reserved.\n**\n** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n** following conditions are met:\n**\n** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following\n** disclaimer.\n** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n** following disclaimer in the documentation and\/or other materials provided with the distribution.\n** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n** derived from this software without specific prior written permission.\n**\n**\n** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n**\n***********************************************************************************************************************\/\n\n#include \"Commit.h\"\n\nnamespace FilePersistence {\n\nSignature::Signature()\n{\n\tdateTime_ = QDateTime::currentDateTimeUtc();\n\ttimeZone_ = QTimeZone(QTimeZone::systemTimeZoneId());\n}\n\nCommitFile::CommitFile()\n{\n\trelativePath_ = QString();\n\tsize_ = 0;\n\tcontent_ = nullptr;\n}\n\nCommitFile::CommitFile(QString relativePath, qint64 size, const char* content)\n{\n\trelativePath_ = relativePath;\n\tsize_ = size;\n\tcontent_ = content;\n}\n\nCommitFile::~CommitFile()\n{\n\tdelete[] content_;\n}\n\nCommit::Commit() {}\n\nCommit::~Commit()\n{\n\tfor (auto file : files_.values())\n\t\tSAFE_DELETE(file);\n}\n\nvoid Commit::setMetaData(CommitMetaData data)\n{\n\tinformation_ = data;\n}\n\nCommitMetaData Commit::metaData() const\n{\n\treturn information_;\n}\n\nvoid Commit::addFile(QString relativePath, qint64 size, const char* content)\n{\n\tfiles_.insert(relativePath, new CommitFile(relativePath, size, content));\n}\n\nbool Commit::getFileContent(QString fileName, const char*& content, int& contentSize) const\n{\n\tQHash::const_iterator iter = files_.find(fileName);\n\tif (iter != files_.constEnd())\n\t{\n\t\tcontentSize = iter.value()->size_;\n\t\tcontent = iter.value()->content_;\n\n\t\treturn true;\n\t}\n\telse\n\t\treturn false;\n}\n\n} \/* namespace FilePersistence *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n *\n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see .\n *\/\n\n#include \n\n#include \"Pid.h\"\n#include \"SetPoint.h\"\n#include \n#include \n#include \"TempSensorMock.h\"\n#include \"Actuator.h\"\n#include \"ActuatorPwm.h\"\n#include \"ActuatorTimeLimited.h\"\n#include \"ActuatorSetPoint.h\"\n#include \"runner.h\"\n#include \n#include \n\nstruct StaticSetup{\npublic:\n StaticSetup(){\n BOOST_TEST_MESSAGE( \"setup PID test fixture\" );\n\n beerSensor = new TempSensorMock(20.0);\n fridgeSensor = new TempSensorMock(20.0);\n\n heaterPin = new ActuatorBool();\n heater = new ActuatorPwm(heaterPin, 4); \/\/ period 4s\n\n coolerPin = new ActuatorBool();\n coolerTimeLimited = new ActuatorTimeLimited(coolerPin, 120, 180); \/\/ 2 min minOn time, 3 min minOff\n cooler = new ActuatorPwm(coolerTimeLimited, 600); \/\/ period 10 min\n\n beerSet = new SetPointSimple(20.0);\n fridgeSet = new SetPointSimple(20.0);\n\n heaterPid = new Pid();\n coolerPid = new Pid();\n beerToFridgePid = new Pid();\n\n fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, beerSet);\n\n heaterPid->setOutputActuator(heater);\n coolerPid->setOutputActuator(cooler);\n coolerPid->setActuatorIsNegative(true);\n\n }\n ~StaticSetup(){\n BOOST_TEST_MESSAGE( \"tear down PID test fixture\" );\n delete beerSensor;\n delete fridgeSensor;\n\n delete coolerPin;\n delete coolerTimeLimited;\n delete heaterPin;\n delete cooler;\n delete heater;\n\n delete heaterPid;\n delete coolerPid;\n delete beerToFridgePid;\n\n delete beerSet;\n delete fridgeSet;\n }\n\n TempSensorMock * beerSensor;\n TempSensorMock * fridgeSensor;\n\n ActuatorDigital * coolerPin;\n ActuatorDigital * coolerTimeLimited;\n ActuatorDigital * heaterPin;\n ActuatorRange * cooler;\n ActuatorRange * heater;\n ActuatorRange * fridgeSetPointActuator;\n\n\n Pid * heaterPid;\n Pid * coolerPid;\n Pid * beerToFridgePid;\n\n SetPoint * beerSet;\n SetPoint * fridgeSet;\n};\n\n\/* This class simulates a fridge is a simple way:\n * There are 3 heat capacities: the beer itself, the air in the fridge and the fridge walls.\n * The heater heats the air in the fridge directly.\n * The cooler cools the fridge walls, which in turn cool the fridge air.\n * This causes an extra delay when cooling and a potential source of overshoot\n *\/\n\n\nstruct Simulation{\n Simulation(){\n beerTemp = 20.0;\n airTemp = 20.0;\n wallTemp = 20.0;\n envTemp = 18.0;\n\n beerCapacity = 4.2 * 1.0 * 20; \/\/ heat capacity water * density of water * 20L volume (in kJ per kelvin).\n airCapacity = 5 * 1.0035 * 1.225 * 0.200; \/\/ 5 * heat capacity of dry air * density of air * 200L volume (in kJ per kelvin).\n \/\/ Moist air is much more complex, should calculate using enthalpy. Now just multiplied by 5.\n wallCapacity = 5.0; \/\/ just a guess\n\n heaterPower = 0.3; \/\/ 300W, in kW.\n coolerPower = 0.3; \/\/ 300W, in kW.\n\n airBeerTransfer= 0.02;\n wallAirTransfer= 0.04;\n envWallTransfer = 0.01;\n\n }\n virtual ~Simulation(){}\n\n void update(temp_t heaterValue, temp_t coolerValue){\n double beerTempNew = beerTemp;\n double airTempNew = airTemp;\n double wallTempNew = wallTemp;\n\n beerTempNew += (airTemp - beerTemp) * airBeerTransfer \/ beerCapacity;\n\n airTempNew += heaterPower * double(heaterValue) \/ (100.0 * airCapacity);\n airTempNew += (wallTemp - airTemp) * wallAirTransfer \/ airCapacity;\n airTempNew += (beerTemp - airTemp) * airBeerTransfer \/ airCapacity;\n\n wallTempNew -= coolerPower * double(coolerValue) \/ (100.0 * wallCapacity);\n wallTempNew += (envTemp - wallTemp) * envWallTransfer \/ wallCapacity;\n wallTempNew += (airTemp - wallTemp) * wallAirTransfer\/ wallCapacity;\n\n airTemp = airTempNew;\n beerTemp = beerTempNew;\n wallTemp = wallTempNew;\n }\n\n double beerTemp;\n double airTemp;\n double wallTemp;\n double envTemp;\n\n double beerCapacity;\n double airCapacity;\n double wallCapacity;\n\n double heaterPower;\n double coolerPower;\n\n double airBeerTransfer;\n double wallAirTransfer;\n double envWallTransfer;\n};\n\n\/* Below are a few static setups that show how control can be set up.\n * The first 4 are simple: a single actuator, acting on beer or fridge temperature\n *\/\n\n\/\/ Just a heater, acting on beer temperature directly\nstruct SimBeerHeater : public StaticSetup {\n Simulation sim;\n SimBeerHeater(){\n heaterPid->setInputSensor(beerSensor);\n heaterPid->setSetPoint(beerSet);\n heaterPid->setInputFilter(0);\n heaterPid->setDerivativeFilter(4);\n heaterPid->setConstants(100.0, 5.0, -100.0);\n }\n\n void update(){\n sim.update(heater->getValue(), cooler->getValue());\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n heaterPid->update();\n }\n};\n\n\/\/ Just a heater, acting on fridge temperature directly\nstruct SimFridgeHeater : public StaticSetup {\n Simulation sim;\n SimFridgeHeater(){\n heaterPid->setInputSensor(fridgeSensor);\n heaterPid->setSetPoint(fridgeSet);\n heaterPid->setInputFilter(0);\n heaterPid->setDerivativeFilter(2);\n heaterPid->setConstants(20.0, 10.0, -3.0);\n }\n\n void update(){\n sim.update(heater->getValue(), cooler->getValue());\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n heaterPid->update();\n }\n};\n\n\/\/ Just a cooler, acting on beer temperature directly\nstruct SimBeerCooler : public StaticSetup {\n Simulation sim;\n SimBeerCooler(){\n coolerPid->setInputSensor(beerSensor);\n coolerPid->setSetPoint(beerSet);\n coolerPid->setInputFilter(0);\n coolerPid->setDerivativeFilter(4);\n coolerPid->setConstants(100.0, 5.0, -100.0);\n\n }\n\n void update(){\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n coolerPid->update();\n cooler->update();\n \/\/ because cooler is time limited, get actual output from pin\n if(coolerPin->isActive()){\n sim.update(heater->getValue(), 100.0);\n } else{\n sim.update(heater->getValue(), 0.0);\n }\n delay(1000); \/\/ simulate actual time passing for pin state of cooler, which is time limited\n }\n};\n\n\/\/ Just a cooler, acting on fridge temperature directly\nstruct SimFridgeCooler : public StaticSetup {\n Simulation sim;\n SimFridgeCooler(){\n coolerPid->setInputSensor(fridgeSensor);\n coolerPid->setSetPoint(fridgeSet);\n coolerPid->setInputFilter(0);\n coolerPid->setDerivativeFilter(2);\n coolerPid->setConstants(20.0, 5.0, -5.0);\n }\n\n void update(){\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n coolerPid->update();\n cooler->update();\n\n \/\/ because cooler is time limited, get actual output from pin\n if(coolerPin->isActive()){\n sim.update(heater->getValue(), 100.0);\n } else{\n sim.update(heater->getValue(), 0.0);\n }\n delay(1000); \/\/ simulate actual time passing for pin state of cooler, which is time limited\n }\n};\n\nBOOST_AUTO_TEST_SUITE( simulation_test)\n\n\/\/ Test heating fridge air based on beer temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Heater_Acts_On_Beer, SimBeerHeater)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, heater pwm, p, i, d\" << endl;\n double SetPointDouble = 19;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 21;\n }\n if(t==2500){\n SetPointDouble = 24;\n }\n beerSet->write(SetPointDouble);\n update();\n\n csv << beerSet->read() << \",\" \/\/ setpoint\n << heaterPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << heater->getValue() << \",\" \/\/ actuator output\n << heaterPid->p << \",\" \/\/ proportional action\n << heaterPid->i << \",\" \/\/ integral action\n << heaterPid->d \/\/ derivative action\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test heating fridge air based on fridge air temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Heater_Acts_On_Fridge_Air, SimFridgeHeater)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, heater pwm, p, i, d\" << endl;\n double SetPointDouble = 19;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 24;\n }\n if(t==2500){\n SetPointDouble = 28;\n }\n fridgeSet->write(SetPointDouble);\n update();\n\n csv << fridgeSet->read() << \",\" \/\/ setpoint\n << heaterPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << heater->getValue() << \",\" \/\/ actuator output\n << heaterPid->p << \",\" \/\/ proportional action\n << heaterPid->i << \",\" \/\/ integral action\n << heaterPid->d \/\/ derivative action\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test cooling fridge air (via wall) based on beer temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Cooler_Acts_On_Beer, SimBeerCooler)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, cooler pwm, p, i, d, cooler pin\" << endl;\n double SetPointDouble = 21;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 19;\n }\n if(t==2500){\n SetPointDouble = 18.5;\n }\n beerSet->write(SetPointDouble);\n update();\n\n csv << beerSet->read() << \",\" \/\/ setpoint\n << coolerPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << cooler->getValue() << \",\" \/\/ actuator output\n << coolerPid->p << \",\" \/\/ proportional action\n << coolerPid->i << \",\" \/\/ integral action\n << coolerPid->d << \",\" \/\/ derivative action\n << coolerPin->isActive() \/\/ actual cooler pin state\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test cooling fridge air (via wall) based on fridge air temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Cooler_Acts_On_Fridge_Air, SimFridgeCooler)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, cooler pwm, p, i, d, cooler pin\" << endl;\n double SetPointDouble = 21;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 19;\n }\n if(t==2500){\n SetPointDouble = 15;\n }\n fridgeSet->write(SetPointDouble);\n update();\n\n csv << fridgeSet->read() << \",\" \/\/ setpoint\n << coolerPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << cooler->getValue() << \",\" \/\/ actuator output\n << coolerPid->p << \",\" \/\/ proportional action\n << coolerPid->i << \",\" \/\/ integral action\n << coolerPid->d << \",\" \/\/ derivative action\n << coolerPin->isActive() \/\/ actual cooler pin state\n << endl;\n }\n csv.close();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\nWIP testing with cooler\/*\n * Copyright 2015 BrewPi\/Elco Jacobs.\n *\n * This file is part of BrewPi.\n *\n * BrewPi is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * BrewPi is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with BrewPi. If not, see .\n *\/\n\n#include \n\n#include \"Pid.h\"\n#include \"SetPoint.h\"\n#include \n#include \n#include \"TempSensorMock.h\"\n#include \"Actuator.h\"\n#include \"ActuatorPwm.h\"\n#include \"ActuatorTimeLimited.h\"\n#include \"ActuatorSetPoint.h\"\n#include \"runner.h\"\n#include \n#include \n\nstruct StaticSetup{\npublic:\n StaticSetup(){\n BOOST_TEST_MESSAGE( \"setup PID test fixture\" );\n\n beerSensor = new TempSensorMock(20.0);\n fridgeSensor = new TempSensorMock(20.0);\n\n heaterPin = new ActuatorBool();\n heater = new ActuatorPwm(heaterPin, 4); \/\/ period 4s\n\n coolerPin = new ActuatorBool();\n coolerTimeLimited = new ActuatorTimeLimited(coolerPin, 120, 180); \/\/ 2 min minOn time, 3 min minOff\n cooler = new ActuatorPwm(coolerTimeLimited, 600); \/\/ period 10 min\n\n beerSet = new SetPointSimple(20.0);\n fridgeSet = new SetPointSimple(20.0);\n\n heaterPid = new Pid();\n coolerPid = new Pid();\n beerToFridgePid = new Pid();\n\n fridgeSetPointActuator = new ActuatorSetPoint(fridgeSet, beerSet);\n\n heaterPid->setOutputActuator(heater);\n coolerPid->setOutputActuator(cooler);\n coolerPid->setActuatorIsNegative(true);\n\n }\n ~StaticSetup(){\n BOOST_TEST_MESSAGE( \"tear down PID test fixture\" );\n delete beerSensor;\n delete fridgeSensor;\n\n delete coolerPin;\n delete coolerTimeLimited;\n delete heaterPin;\n delete cooler;\n delete heater;\n\n delete heaterPid;\n delete coolerPid;\n delete beerToFridgePid;\n\n delete beerSet;\n delete fridgeSet;\n }\n\n TempSensorMock * beerSensor;\n TempSensorMock * fridgeSensor;\n\n ActuatorDigital * coolerPin;\n ActuatorDigital * coolerTimeLimited;\n ActuatorDigital * heaterPin;\n ActuatorRange * cooler;\n ActuatorRange * heater;\n ActuatorRange * fridgeSetPointActuator;\n\n\n Pid * heaterPid;\n Pid * coolerPid;\n Pid * beerToFridgePid;\n\n SetPoint * beerSet;\n SetPoint * fridgeSet;\n};\n\n\/* This class simulates a fridge is a simple way:\n * There are 3 heat capacities: the beer itself, the air in the fridge and the fridge walls.\n * The heater heats the air in the fridge directly.\n * The cooler cools the fridge walls, which in turn cool the fridge air.\n * This causes an extra delay when cooling and a potential source of overshoot\n *\/\n\n\nstruct Simulation{\n Simulation(){\n beerTemp = 20.0;\n airTemp = 20.0;\n wallTemp = 20.0;\n envTemp = 18.0;\n\n beerCapacity = 4.2 * 1.0 * 20; \/\/ heat capacity water * density of water * 20L volume (in kJ per kelvin).\n airCapacity = 5 * 1.0035 * 1.225 * 0.200; \/\/ 5 * heat capacity of dry air * density of air * 200L volume (in kJ per kelvin).\n \/\/ Moist air is much more complex, should calculate using enthalpy. Now just multiplied by 5.\n wallCapacity = 5.0; \/\/ just a guess\n\n heaterPower = 0.3; \/\/ 300W, in kW.\n coolerPower = 0.3; \/\/ 300W, in kW.\n\n airBeerTransfer= 0.02;\n wallAirTransfer= 0.04;\n envWallTransfer = 0.01;\n\n }\n virtual ~Simulation(){}\n\n void update(temp_t heaterValue, temp_t coolerValue){\n double beerTempNew = beerTemp;\n double airTempNew = airTemp;\n double wallTempNew = wallTemp;\n\n beerTempNew += (airTemp - beerTemp) * airBeerTransfer \/ beerCapacity;\n\n airTempNew += heaterPower * double(heaterValue) \/ (100.0 * airCapacity);\n airTempNew += (wallTemp - airTemp) * wallAirTransfer \/ airCapacity;\n airTempNew += (beerTemp - airTemp) * airBeerTransfer \/ airCapacity;\n\n wallTempNew -= coolerPower * double(coolerValue) \/ (100.0 * wallCapacity);\n wallTempNew += (envTemp - wallTemp) * envWallTransfer \/ wallCapacity;\n wallTempNew += (airTemp - wallTemp) * wallAirTransfer\/ wallCapacity;\n\n airTemp = airTempNew;\n beerTemp = beerTempNew;\n wallTemp = wallTempNew;\n }\n\n double beerTemp;\n double airTemp;\n double wallTemp;\n double envTemp;\n\n double beerCapacity;\n double airCapacity;\n double wallCapacity;\n\n double heaterPower;\n double coolerPower;\n\n double airBeerTransfer;\n double wallAirTransfer;\n double envWallTransfer;\n};\n\n\/* Below are a few static setups that show how control can be set up.\n * The first 4 are simple: a single actuator, acting on beer or fridge temperature\n *\/\n\n\/\/ Just a heater, acting on beer temperature directly\nstruct SimBeerHeater : public StaticSetup {\n Simulation sim;\n SimBeerHeater(){\n heaterPid->setInputSensor(beerSensor);\n heaterPid->setSetPoint(beerSet);\n heaterPid->setInputFilter(0);\n heaterPid->setDerivativeFilter(4);\n heaterPid->setConstants(100.0, 5.0, -100.0);\n }\n\n void update(){\n sim.update(heater->getValue(), cooler->getValue());\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n heaterPid->update();\n }\n};\n\n\/\/ Just a heater, acting on fridge temperature directly\nstruct SimFridgeHeater : public StaticSetup {\n Simulation sim;\n SimFridgeHeater(){\n heaterPid->setInputSensor(fridgeSensor);\n heaterPid->setSetPoint(fridgeSet);\n heaterPid->setInputFilter(0);\n heaterPid->setDerivativeFilter(2);\n heaterPid->setConstants(20.0, 10.0, -3.0);\n }\n\n void update(){\n sim.update(heater->getValue(), cooler->getValue());\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n heaterPid->update();\n }\n};\n\n\/\/ Just a cooler, acting on beer temperature directly\nstruct SimBeerCooler : public StaticSetup {\n Simulation sim;\n SimBeerCooler(){\n coolerPid->setInputSensor(beerSensor);\n coolerPid->setSetPoint(beerSet);\n coolerPid->setInputFilter(0);\n coolerPid->setDerivativeFilter(4);\n coolerPid->setConstants(100.0, 0.0, -100.0);\n\n }\n\n void update(){\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n coolerPid->update();\n cooler->update();\n \/\/ because cooler is time limited, get actual output from pin\n if(coolerPin->isActive()){\n sim.update(heater->getValue(), 100.0);\n } else{\n sim.update(heater->getValue(), 0.0);\n }\n delay(1000); \/\/ simulate actual time passing for pin state of cooler, which is time limited\n }\n};\n\n\/\/ Just a cooler, acting on fridge temperature directly\nstruct SimFridgeCooler : public StaticSetup {\n Simulation sim;\n SimFridgeCooler(){\n coolerPid->setInputSensor(fridgeSensor);\n coolerPid->setSetPoint(fridgeSet);\n coolerPid->setInputFilter(0);\n coolerPid->setDerivativeFilter(2);\n coolerPid->setConstants(20.0, 5.0, -5.0);\n }\n\n void update(){\n beerSensor->setTemp(sim.beerTemp);\n fridgeSensor->setTemp(sim.airTemp);\n coolerPid->update();\n cooler->update();\n\n \/\/ because cooler is time limited, get actual output from pin\n if(coolerPin->isActive()){\n sim.update(heater->getValue(), 100.0);\n } else{\n sim.update(heater->getValue(), 0.0);\n }\n delay(1000); \/\/ simulate actual time passing for pin state of cooler, which is time limited\n }\n};\n\nBOOST_AUTO_TEST_SUITE( simulation_test)\n\n\/\/ Test heating fridge air based on beer temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Heater_Acts_On_Beer, SimBeerHeater)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, heater pwm, p, i, d\" << endl;\n double SetPointDouble = 19;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 21;\n }\n if(t==2500){\n SetPointDouble = 24;\n }\n beerSet->write(SetPointDouble);\n update();\n\n csv << beerSet->read() << \",\" \/\/ setpoint\n << heaterPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << heater->getValue() << \",\" \/\/ actuator output\n << heaterPid->p << \",\" \/\/ proportional action\n << heaterPid->i << \",\" \/\/ integral action\n << heaterPid->d \/\/ derivative action\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test heating fridge air based on fridge air temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Heater_Acts_On_Fridge_Air, SimFridgeHeater)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, heater pwm, p, i, d\" << endl;\n double SetPointDouble = 19;\n for(int t = 0; t < 6000; t++){\n if(t==500){\n SetPointDouble = 24;\n }\n if(t==2500){\n SetPointDouble = 28;\n }\n fridgeSet->write(SetPointDouble);\n update();\n\n csv << fridgeSet->read() << \",\" \/\/ setpoint\n << heaterPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << heater->getValue() << \",\" \/\/ actuator output\n << heaterPid->p << \",\" \/\/ proportional action\n << heaterPid->i << \",\" \/\/ integral action\n << heaterPid->d \/\/ derivative action\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test cooling fridge air (via wall) based on beer temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Cooler_Acts_On_Beer, SimBeerCooler)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, cooler pwm, p, i, d, cooler pin\" << endl;\n double SetPointDouble = 21;\n for(int t = 0; t < 10000; t++){\n if(t==1000){\n SetPointDouble = 19;\n }\n if(t==4000){\n SetPointDouble = 18.5;\n }\n beerSet->write(SetPointDouble);\n update();\n if(t==7000){\n update();\n }\n\n csv << beerSet->read() << \",\" \/\/ setpoint\n << coolerPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << cooler->getValue() << \",\" \/\/ actuator output\n << coolerPid->p << \",\" \/\/ proportional action\n << coolerPid->i << \",\" \/\/ integral action\n << coolerPid->d << \",\" \/\/ derivative action\n << coolerPin->isActive() \/\/ actual cooler pin state\n << endl;\n }\n csv.close();\n}\n\n\/\/ Test cooling fridge air (via wall) based on fridge air temperature (non-cascaded control)\nBOOST_FIXTURE_TEST_CASE(Simulate_Air_Cooler_Acts_On_Fridge_Air, SimFridgeCooler)\n{\n ofstream csv(\".\/test_results\/\" + boost_test_name() + \".csv\");\n csv << \"setPoint, error, beer sensor, fridge air sensor, fridge wall temp, cooler pwm, p, i, d, cooler pin\" << endl;\n double SetPointDouble = 21;\n for(int t = 0; t < 10000; t++){\n if(t==1000){\n SetPointDouble = 19;\n }\n if(t==4000){\n SetPointDouble = 15;\n }\n fridgeSet->write(SetPointDouble);\n update();\n\n csv << fridgeSet->read() << \",\" \/\/ setpoint\n << coolerPid->inputError << \",\" \/\/error\n << beerSensor->read() << \",\" \/\/ beer temp\n << fridgeSensor->read() << \",\" \/\/ air temp\n << sim.wallTemp << \",\" \/\/ fridge wall temperature\n << cooler->getValue() << \",\" \/\/ actuator output\n << coolerPid->p << \",\" \/\/ proportional action\n << coolerPid->i << \",\" \/\/ integral action\n << coolerPid->d << \",\" \/\/ derivative action\n << coolerPin->isActive() \/\/ actual cooler pin state\n << endl;\n }\n csv.close();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"#include \"Environment.h\"\n#include \"Logger.h\"\n#include \"SceneLoadContext.h\"\n#include \"shader\/INodePlugin.h\"\n\n#include \n#include \n#include \n\n#include \n\nnamespace PR {\nconstexpr char POSITION_VARIABLE[]\t = \"p\";\nconstexpr char WAVELENGTH_VARIABLE[] = \"w\";\nconstexpr char TEXTURE_VARIABLE[]\t = \"uv\";\n\nstruct ScalarVariable : public SeExpr2::ExprVarRef {\n\tScalarVariable(bool isConst)\n\t\t: SeExpr2::ExprVarRef(isConst ? SeExpr2::ExprType().FP(1).Constant()\n\t\t\t\t\t\t\t\t\t : SeExpr2::ExprType().FP(1).Varying())\n\t\t, Value{ 0 }\n\t{\n\t}\n\n\tfloat Value;\n\n\tvoid eval(double* result) { result[0] = Value; }\n\tvoid eval(const char**) { PR_ASSERT(false, \"eval on string not implemented!\"); }\n};\n\nstruct SpectralVariable : public SeExpr2::ExprVarRef {\n\tSpectralVariable(bool isConst)\n\t\t: SeExpr2::ExprVarRef(isConst ? SeExpr2::ExprType().FP(1).Constant()\n\t\t\t\t\t\t\t\t\t : SeExpr2::ExprType().FP(1).Varying())\n\t\t, Value(SpectralBlob::Zero())\n\t\t, CurrentEntry(0)\n\t{\n\t}\n\n\tSpectralBlob Value;\n\tint CurrentEntry;\n\n\tvoid eval(double* result) { result[0] = Value(CurrentEntry); }\n\tvoid eval(const char**) { PR_ASSERT(false, \"eval on string not implemented!\"); }\n};\n\nstruct VectorVariable : public SeExpr2::ExprVarRef {\n\tVectorVariable(int d, bool isConst)\n\t\t: SeExpr2::ExprVarRef(isConst ? SeExpr2::ExprType().FP(d).Constant()\n\t\t\t\t\t\t\t\t\t : SeExpr2::ExprType().FP(d).Varying())\n\t\t, Value{ 0, 0, 0 }\n\t\t, Dim(d)\n\t{\n\t\tPR_ASSERT(d > 0 && d <= 3, \"Expected valid dimension\");\n\t}\n\n\tfloat Value[3];\n\tconst int Dim;\n\n\tvoid eval(double* result)\n\t{\n\t\tfor (int i = 0; i < Dim; ++i)\n\t\t\tresult[i] = Value[i];\n\t}\n\n\tvoid eval(const char**) { PR_ASSERT(false, \"eval on string not implemented!\"); }\n};\n\nclass PrExpression : public SeExpr2::Expression {\npublic:\n\tPrExpression(const std::string& expr, bool isVec)\n\t\t: SeExpr2::Expression(expr, SeExpr2::ExprType().FP(isVec ? 3 : 1))\n\t{\n\t}\n\n\tPrExpression(PrExpression&& other) = default;\n\n\tstd::unordered_map> ScalarNodes;\n\tstd::unordered_map> SpectralNodes;\n\tstd::unordered_map> VectorNodes;\n\n\tmutable std::unordered_map> ScalarVariableReferences;\n\tmutable std::unordered_map> SpectralVariableReferences;\n\tmutable std::unordered_map> VectorVariableReferences;\n\n\tmutable std::unique_ptr PositionVariable;\n\tmutable std::unique_ptr TextureVariable;\n\tmutable std::unique_ptr WavelengthVariable;\n\n\tSeExpr2::ExprVarRef* resolveVar(const std::string& name) const\n\t{\n\t\tif (POSITION_VARIABLE == name)\n\t\t\treturn PositionVariable.get();\n\t\telse if (TEXTURE_VARIABLE == name)\n\t\t\treturn TextureVariable.get();\n\t\telse if (WAVELENGTH_VARIABLE == name)\n\t\t\treturn WavelengthVariable.get();\n\t\telse {\n\t\t\tconst auto i1 = ScalarVariableReferences.find(name);\n\t\t\tif (i1 != ScalarVariableReferences.end())\n\t\t\t\treturn i1->second.get();\n\n\t\t\tconst auto i2 = SpectralVariableReferences.find(name);\n\t\t\tif (i2 != SpectralVariableReferences.end())\n\t\t\t\treturn i2->second.get();\n\n\t\t\tconst auto i3 = VectorVariableReferences.find(name);\n\t\t\tif (i3 != VectorVariableReferences.end())\n\t\t\t\treturn i3->second.get();\n\t\t\treturn nullptr;\n\t\t}\n\t}\n};\n\n\/\/ No Spectrals\ninline static void updateBasicNodes(const ShadingContext& ctx, const std::shared_ptr& expr)\n{\n\tfor (auto entry : expr->ScalarNodes)\n\t\tentry.first->Value = entry.second->eval(ctx);\n\n\tfor (auto entry : expr->VectorNodes) {\n\t\tauto vec\t\t\t = entry.second->eval(ctx);\n\t\tentry.first->Value[0] = vec(0);\n\t\tentry.first->Value[1] = vec(1);\n\t\tentry.first->Value[2] = vec(2);\n\t}\n\n\tif (expr->TextureVariable) {\n\t\texpr->TextureVariable->Value[0] = ctx.UV[0];\n\t\texpr->TextureVariable->Value[1] = ctx.UV[1];\n\t}\n}\n\nclass ScalarExpressionNode : public FloatScalarNode {\npublic:\n\texplicit ScalarExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\tfloat eval(const ShadingContext& ctx) const override\n\t{\n\t\t\/\/ Update nodes\n\t\tupdateBasicNodes(ctx, mExpr);\n\n\t\tconst double* result = mExpr->evalFP();\n\t\treturn result[0];\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Scalar Expression (\" << mExpr->getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tstd::shared_ptr mExpr;\n};\n\nclass SpectralExpressionNode : public FloatSpectralNode {\npublic:\n\texplicit SpectralExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\t\/\/ TODO: Better way?\n\tSpectralBlob eval(const ShadingContext& ctx) const override\n\t{\n\t\t\/\/ Update nodes\n\t\tupdateBasicNodes(ctx, mExpr);\n\n\t\t\/\/ Update spectral nodes\n\t\tfor (auto entry : mExpr->SpectralNodes)\n\t\t\tentry.first->Value = entry.second->eval(ctx);\n\n\t\tif (mExpr->WavelengthVariable)\n\t\t\tmExpr->WavelengthVariable->Value = ctx.WavelengthNM;\n\n\t\t\/\/ Calculate each wavelength (not really the best solution)\n\t\tSpectralBlob output;\n\t\tfor (size_t i = 0; i < PR_SPECTRAL_BLOB_SIZE; ++i) {\n\t\t\tfor (auto entry : mExpr->SpectralNodes)\n\t\t\t\tentry.first->CurrentEntry = i;\n\n\t\t\tif (mExpr->WavelengthVariable)\n\t\t\t\tmExpr->WavelengthVariable->CurrentEntry = i;\n\n\t\t\tconst double* result = mExpr->evalFP();\n\t\t\toutput[i]\t\t\t = result[0];\n\t\t}\n\t\treturn output;\n\t}\n\n\t\/\/ TODO: Get a better way to achieve this!\n\tVector2i queryRecommendedSize() const override\n\t{\n\t\treturn Vector2i(1, 1);\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Spectral Expression (\" << mExpr->getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tstd::shared_ptr mExpr;\n};\n\nclass VectorExpressionNode : public FloatVectorNode {\npublic:\n\texplicit VectorExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\tVector3f eval(const ShadingContext& ctx) const override\n\t{\n\t\t\/\/ Update nodes\n\t\tupdateBasicNodes(ctx, mExpr);\n\n\t\tconst double* result = mExpr->evalFP();\n\t\treturn Vector3f(result[0], result[1], result[2]);\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Vector3f Expression (\" << mExpr->getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tstd::shared_ptr mExpr;\n};\n\nclass ExpressionPlugin : public INodePlugin {\npublic:\n\tstd::shared_ptr create(uint32, const std::string& type_name, const SceneLoadContext& ctx) override\n\t{\n\t\tstd::string expr_str;\n\t\tif (type_name == \"expr\" || type_name == \"vexpr\") {\n\t\t\texpr_str = ctx.Parameters.getString(\"expression\", \"\");\n\t\t\tif (expr_str.empty())\n\t\t\t\texpr_str = ctx.Parameters.getString(0, \"\");\n\t\t} else {\n\t\t\tstd::string path = ctx.Parameters.getString(\"file\", \"\");\n\t\t\tif (path.empty())\n\t\t\t\tpath = ctx.Parameters.getString(0, \"\");\n\n\t\t\tstd::ifstream stream(path, std::ios::in);\n\t\t\tif (!stream.good()) {\n\t\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] Can not load file \" << path << std::endl;\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\texpr_str = std::string((std::istreambuf_iterator(stream)), std::istreambuf_iterator());\n\t\t}\n\n\t\tconst bool isVec = (type_name == \"vexpr\" || type_name == \"fvexpr\");\n\t\tauto expr\t\t = std::make_shared(expr_str, isVec);\n\n\t\t\/\/ Setup user variables\n\t\tfor (const auto& entry : ctx.Parameters.parameters()) {\n\t\t\tconst auto& param = entry.second;\n\n\t\t\tswitch (param.type()) {\n\t\t\tcase PT_Invalid:\n\t\t\t\tcontinue;\n\t\t\tcase PT_Bool: {\n\t\t\t\tstd::unique_ptr constant\t= std::make_unique(true);\n\t\t\t\tconstant->Value\t\t\t\t\t\t\t\t= param.getBool(false) ? 1.0f : 0.0f;\n\t\t\t\texpr->ScalarVariableReferences[entry.first] = std::move(constant);\n\t\t\t} break;\n\t\t\tcase PT_Int:\n\t\t\tcase PT_UInt:\n\t\t\tcase PT_Number: {\n\t\t\t\tstd::unique_ptr constant\t= std::make_unique(true);\n\t\t\t\tconstant->Value\t\t\t\t\t\t\t\t= param.getNumber(0.0f);\n\t\t\t\texpr->ScalarVariableReferences[entry.first] = std::move(constant);\n\t\t\t} break;\n\t\t\tcase PT_String:\n\t\t\tcase PT_Reference: {\n\t\t\t\tauto node = ctx.Env->lookupRawNode(param);\n\t\t\t\tswitch (node->type()) {\n\t\t\t\tcase NT_FloatScalar: {\n\t\t\t\t\tauto var\t\t\t\t\t\t\t\t\t= std::make_unique(false);\n\t\t\t\t\texpr->ScalarNodes[var.get()]\t\t\t\t= std::reinterpret_pointer_cast(node);\n\t\t\t\t\texpr->ScalarVariableReferences[entry.first] = std::move(var);\n\t\t\t\t} break;\n\t\t\t\tcase NT_FloatSpectral: {\n\t\t\t\t\tauto var\t\t\t\t\t\t\t\t\t = std::make_unique(false);\n\t\t\t\t\texpr->SpectralNodes[var.get()]\t\t\t\t = std::reinterpret_pointer_cast(node);\n\t\t\t\t\texpr->SpectralVariableReferences[entry.first] = std::move(var);\n\t\t\t\t} break;\n\t\t\t\tcase NT_FloatVector: {\n\t\t\t\t\tauto var\t\t\t\t\t\t\t\t\t= std::make_unique(3, false);\n\t\t\t\t\texpr->VectorNodes[var.get()]\t\t\t\t= std::reinterpret_pointer_cast(node);\n\t\t\t\t\texpr->VectorVariableReferences[entry.first] = std::move(var);\n\t\t\t\t} break;\n\t\t\t\t}\n\t\t\t} break;\n\t\t\t}\n\t\t}\n\n\t\t\/\/ Setup standard variables\n\t\tif (expr->usesVar(POSITION_VARIABLE))\n\t\t\texpr->PositionVariable = std::make_unique(3, false);\n\t\tif (expr->usesVar(TEXTURE_VARIABLE))\n\t\t\texpr->TextureVariable = std::make_unique(2, false);\n\t\tif (expr->usesVar(WAVELENGTH_VARIABLE))\n\t\t\texpr->WavelengthVariable = std::make_unique(false);\n\n\t\t\/\/ const bool isSpatialVarying\t = expr->PositionVariable || expr->TextureVariable;\n\t\tconst bool isSpectralVarying = (expr->WavelengthVariable != nullptr) || !expr->SpectralVariableReferences.empty();\n\n\t\tif (!expr->isValid()) {\n\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] Parsing Error: \" << expr->parseError() << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tif (isSpectralVarying && isVec) {\n\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] A spectral varying expression can not be combined with a vector expression\" << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tif (isVec) {\n\t\t\treturn std::make_shared(expr);\n\t\t} else if (isSpectralVarying) {\n\t\t\treturn std::make_shared(expr);\n\t\t} else {\n\t\t\treturn std::make_shared(expr);\n\t\t}\n\t}\n\n\tconst std::vector& getNames() const override\n\t{\n\t\tconst static std::vector names({ \"expr\", \"vexpr\", \"fexpr\", \"fvexpr\" });\n\t\treturn names;\n\t}\n\n\tbool init() override\n\t{\n\t\treturn true;\n\t}\n};\n} \/\/ namespace PR\n\nPR_PLUGIN_INIT(PR::ExpressionPlugin, _PR_PLUGIN_NAME, PR_PLUGIN_VERSION)Improved thread safety#include \"Environment.h\"\n#include \"Logger.h\"\n#include \"SceneLoadContext.h\"\n#include \"renderer\/RenderContext.h\"\n#include \"shader\/INodePlugin.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace PR {\nconstexpr char POSITION_VARIABLE[]\t = \"P\";\nconstexpr char WAVELENGTH_VARIABLE[] = \"w\";\nconstexpr char TEXTURE_U_VARIABLE[]\t = \"u\";\nconstexpr char TEXTURE_V_VARIABLE[]\t = \"v\";\n\nstatic inline bool usesVariable(const std::string& expr, const std::string& var)\n{\n\treturn std::regex_search(expr, std::regex(\"\\\\b\" + var + \"\\\\b\"));\n}\n\nstruct ExpressionContainer {\n\tSeExpr2::Expression Expr;\n\tSeExpr2::VarBlockCreator Creator;\n\tstd::vector VarBlocks;\n\n\tstd::vector>> ScalarNodes;\n\tstd::vector>>> SpectralNodes;\n\tstd::vector>> VectorNodes;\n\tstd::vector> NumberConstants;\n\tstd::vector> VectorConstants;\n\n\tint PositionVariable = -1;\n\tint WavelengthVariable = -1;\n\tint TextureUVariable = -1;\n\tint TextureVVariable = -1;\n\n\tinline ExpressionContainer(const std::string& str, bool isVec)\n\t\t: Expr(str)\n\t{\n\t\tExpr.setDesiredReturnType(SeExpr2::TypeVec(isVec ? 3 : 1));\n\t\tExpr.setVarBlockCreator(&Creator);\n\n\t\t\/\/ Setup standard variables\n\t\tif (usesVariable(str, POSITION_VARIABLE))\n\t\t\tPositionVariable = Creator.registerVariable(POSITION_VARIABLE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSeExpr2::ExprType().FP(3).Varying());\n\t\tif (usesVariable(str, TEXTURE_U_VARIABLE))\n\t\t\tTextureUVariable = Creator.registerVariable(TEXTURE_U_VARIABLE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSeExpr2::ExprType().FP(1).Varying());\n\t\tif (usesVariable(str, TEXTURE_V_VARIABLE))\n\t\t\tTextureVVariable = Creator.registerVariable(TEXTURE_V_VARIABLE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tSeExpr2::ExprType().FP(1).Varying());\n\t\tif (usesVariable(str, WAVELENGTH_VARIABLE))\n\t\t\tWavelengthVariable = Creator.registerVariable(WAVELENGTH_VARIABLE,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t SeExpr2::ExprType().FP(1).Varying());\n\t}\n\n\tinline void updateConstants(SeExpr2::VarBlock* block) const\n\t{\n\t\tfor (const auto& entry : NumberConstants)\n\t\t\t*block->Pointer(entry.first) = entry.second;\n\n\t\tfor (const auto& entry : VectorConstants) {\n\t\t\tVector3f var = entry.second;\n\t\t\tauto* ptr\t = block->Pointer(entry.first);\n\t\t\tptr[0]\t\t = var(0);\n\t\t\tptr[1]\t\t = var(1);\n\t\t\tptr[2]\t\t = var(2);\n\t\t}\n\t}\n\n\tinline void setupThreadData(size_t thread_count)\n\t{\n\t\tfor (size_t i = 0; i < thread_count; ++i) {\n\t\t\tSeExpr2::VarBlock block = Creator.create(true);\n\t\t\tupdateConstants(&block);\n\t\t\tVarBlocks.push_back(std::move(block));\n\t\t}\n\t}\n\n\tinline void updateVaryings(const ShadingContext& ctx)\n\t{\n\t\tauto* varblock = &VarBlocks[ctx.ThreadIndex];\n\n\t\tfor (const auto& entry : ScalarNodes)\n\t\t\t*varblock->Pointer(entry.first) = entry.second->eval(ctx);\n\n\t\tfor (auto& entry : SpectralNodes)\n\t\t\tentry.second.first = entry.second.second->eval(ctx);\n\n\t\tfor (const auto& entry : VectorNodes) {\n\t\t\tVector3f var = entry.second->eval(ctx);\n\t\t\tauto* ptr\t = varblock->Pointer(entry.first);\n\t\t\tptr[0]\t\t = var(0);\n\t\t\tptr[1]\t\t = var(1);\n\t\t\tptr[2]\t\t = var(2);\n\t\t}\n\n\t\t\/*if (PositionVariable >= 0) {\n\t\t\tauto* ptr = VarBlock->Pointer(PositionVariable);\n\t\t\tptr[0]\t = ctx.Position[0];\n\t\t\tptr[1]\t = ctx.Position[1];\n\t\t\tptr[2]\t = ctx.Position[2];\n\t\t}*\/\n\n\t\tif (TextureUVariable >= 0)\n\t\t\t*varblock->Pointer(TextureUVariable) = ctx.UV(0);\n\n\t\tif (TextureVVariable >= 0)\n\t\t\t*varblock->Pointer(TextureVVariable) = ctx.UV(1);\n\t}\n\n\tinline void updateSpectralVaryings(size_t i, const ShadingContext& ctx)\n\t{\n\t\tauto* varblock = &VarBlocks[ctx.ThreadIndex];\n\t\tfor (auto& entry : SpectralNodes)\n\t\t\t*varblock->Pointer(entry.first) = entry.second.first[i];\n\n\t\tif (WavelengthVariable >= 0)\n\t\t\t*varblock->Pointer(WavelengthVariable) = ctx.WavelengthNM[i];\n\t}\n\n\tinline void registerConstant(const std::string& name, float constant)\n\t{\n\t\tint handle = Creator.registerVariable(name, SeExpr2::ExprType().FP(1).Constant());\n\t\tNumberConstants.emplace_back(handle, constant);\n\t}\n\n\tinline void registerConstant(const std::string& name, const Vector3f& constant)\n\t{\n\t\tint handle = Creator.registerVariable(name, SeExpr2::ExprType().FP(3).Constant());\n\t\tVectorConstants.emplace_back(handle, constant);\n\t}\n\n\tinline void registerVarying(const std::string& name, const std::shared_ptr& node)\n\t{\n\t\tint handle = Creator.registerVariable(name, SeExpr2::ExprType().FP(1).Varying());\n\t\tScalarNodes.emplace_back(handle, node);\n\t}\n\n\tinline void registerVarying(const std::string& name, const std::shared_ptr& node)\n\t{\n\t\tint handle = Creator.registerVariable(name, SeExpr2::ExprType().FP(1).Varying());\n\t\tSpectralNodes.emplace_back(handle, std::make_pair(SpectralBlob(), node));\n\t}\n\n\tinline void registerVarying(const std::string& name, const std::shared_ptr& node)\n\t{\n\t\tint handle = Creator.registerVariable(name, SeExpr2::ExprType().FP(3).Varying());\n\t\tVectorNodes.emplace_back(handle, node);\n\t}\n\n\tinline bool isSpectralVarying() const\n\t{\n\t\treturn WavelengthVariable >= 0 || !SpectralNodes.empty();\n\t}\n};\n\nclass ScalarExpressionNode : public FloatScalarNode {\npublic:\n\texplicit ScalarExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\tfloat eval(const ShadingContext& ctx) const override\n\t{\n\t\tmExpr->updateVaryings(ctx);\n\t\tconst double* result = mExpr->Expr.evalFP(&mExpr->VarBlocks[ctx.ThreadIndex]);\n\t\treturn result[0];\n\t}\n\n\tvoid beforeRender(RenderContext* ctx) override\n\t{\n\t\tFloatScalarNode::beforeRender(ctx);\n\t\tmExpr->setupThreadData(ctx->threads());\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Scalar Expression (\" << mExpr->Expr.getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tmutable std::shared_ptr mExpr;\n};\n\nclass SpectralExpressionNode : public FloatSpectralNode {\npublic:\n\texplicit SpectralExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\t\/\/ TODO: Better way?\n\tSpectralBlob eval(const ShadingContext& ctx) const override\n\t{\n\t\tmExpr->updateVaryings(ctx);\n\n\t\t\/\/ Calculate each wavelength (not really the best solution)\n\t\tSpectralBlob output;\n\t\tfor (size_t i = 0; i < PR_SPECTRAL_BLOB_SIZE; ++i) {\n\t\t\tmExpr->updateSpectralVaryings(i, ctx);\n\n\t\t\tconst double* result = mExpr->Expr.evalFP(&mExpr->VarBlocks[ctx.ThreadIndex]);\n\t\t\toutput[i]\t\t\t = result[0];\n\t\t}\n\t\treturn output;\n\t}\n\n\t\/\/ TODO: Get a better way to achieve this!\n\tVector2i queryRecommendedSize() const override\n\t{\n\t\treturn Vector2i(1, 1);\n\t}\n\n\tvoid beforeRender(RenderContext* ctx) override\n\t{\n\t\tFloatSpectralNode::beforeRender(ctx);\n\t\tmExpr->setupThreadData(ctx->threads());\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Spectral Expression (\" << mExpr->Expr.getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tmutable std::shared_ptr mExpr;\n};\n\nclass VectorExpressionNode : public FloatVectorNode {\npublic:\n\texplicit VectorExpressionNode(const std::shared_ptr& expr)\n\t\t: mExpr(expr)\n\t{\n\t}\n\n\tVector3f eval(const ShadingContext& ctx) const override\n\t{\n\t\tmExpr->updateVaryings(ctx);\n\t\tconst double* result = mExpr->Expr.evalFP(&mExpr->VarBlocks[ctx.ThreadIndex]);\n\t\treturn Vector3f(result[0], result[1], result[2]);\n\t}\n\n\tvoid beforeRender(RenderContext* ctx) override\n\t{\n\t\tFloatVectorNode::beforeRender(ctx);\n\t\tmExpr->setupThreadData(ctx->threads());\n\t}\n\n\tstd::string dumpInformation() const override\n\t{\n\t\tstd::stringstream sstream;\n\t\tsstream << \"Vector3f Expression (\" << mExpr->Expr.getExpr() << \")\";\n\t\treturn sstream.str();\n\t}\n\nprivate:\n\tmutable std::shared_ptr mExpr;\n};\n\nclass ExpressionPlugin : public INodePlugin {\npublic:\n\tstd::shared_ptr create(uint32, const std::string& type_name, const SceneLoadContext& ctx) override\n\t{\n\t\tstd::string expr_str;\n\t\tif (type_name == \"expr\" || type_name == \"vexpr\") {\n\t\t\texpr_str = ctx.Parameters.getString(\"expression\", \"\");\n\t\t\tif (expr_str.empty())\n\t\t\t\texpr_str = ctx.Parameters.getString(0, \"\");\n\t\t} else {\n\t\t\tstd::string path = ctx.Parameters.getString(\"file\", \"\");\n\t\t\tif (path.empty())\n\t\t\t\tpath = ctx.Parameters.getString(0, \"\");\n\n\t\t\tstd::ifstream stream(path, std::ios::in);\n\t\t\tif (!stream.good()) {\n\t\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] Can not load file \" << path << std::endl;\n\t\t\t\treturn nullptr;\n\t\t\t}\n\t\t\texpr_str = std::string((std::istreambuf_iterator(stream)), std::istreambuf_iterator());\n\t\t}\n\n\t\tconst bool isVec = (type_name == \"vexpr\" || type_name == \"fvexpr\");\n\t\tauto expr\t\t = std::make_shared(expr_str, isVec);\n\n\t\t\/\/ Setup user variables\n\t\tfor (const auto& entry : ctx.Parameters.parameters()) {\n\t\t\tconst auto& param = entry.second;\n\n\t\t\tswitch (param.type()) {\n\t\t\tcase PT_Invalid:\n\t\t\t\tcontinue;\n\t\t\tcase PT_Bool:\n\t\t\t\texpr->registerConstant(entry.first, param.getBool(false) ? 1.0f : 0.0f);\n\t\t\t\tbreak;\n\t\t\tcase PT_Int:\n\t\t\tcase PT_UInt:\n\t\t\tcase PT_Number:\n\t\t\t\texpr->registerConstant(entry.first, param.getNumber(0.0f));\n\t\t\t\tbreak;\n\t\t\tcase PT_String:\n\t\t\tcase PT_Reference: {\n\t\t\t\tauto node = ctx.Env->lookupRawNode(param);\n\t\t\t\tswitch (node->type()) {\n\t\t\t\tcase NT_FloatScalar:\n\t\t\t\t\texpr->registerVarying(entry.first, std::reinterpret_pointer_cast(node));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NT_FloatSpectral:\n\t\t\t\t\texpr->registerVarying(entry.first, std::reinterpret_pointer_cast(node));\n\t\t\t\t\tbreak;\n\t\t\t\tcase NT_FloatVector:\n\t\t\t\t\texpr->registerVarying(entry.first, std::reinterpret_pointer_cast(node));\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} break;\n\t\t\t}\n\t\t}\n\n\t\tif (!expr->Expr.isValid()) {\n\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] Parsing Error: \" << expr->Expr.parseError() << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tif (expr->isSpectralVarying() && isVec) {\n\t\t\tPR_LOG(L_ERROR) << \"[SeExpr2] A spectral varying expression can not be combined with a vector expression\" << std::endl;\n\t\t\treturn nullptr;\n\t\t}\n\n\t\tif (isVec) {\n\t\t\treturn std::make_shared(expr);\n\t\t} else if (expr->isSpectralVarying()) {\n\t\t\treturn std::make_shared(expr);\n\t\t} else {\n\t\t\treturn std::make_shared(expr);\n\t\t}\n\t}\n\n\tconst std::vector& getNames() const override\n\t{\n\t\tconst static std::vector names({ \"expr\", \"vexpr\", \"fexpr\", \"fvexpr\" });\n\t\treturn names;\n\t}\n\n\tbool init() override\n\t{\n\t\treturn true;\n\t}\n};\n} \/\/ namespace PR\n\nPR_PLUGIN_INIT(PR::ExpressionPlugin, _PR_PLUGIN_NAME, PR_PLUGIN_VERSION)<|endoftext|>"} {"text":"Ignore PixMap::plane_bytes<|endoftext|>"} {"text":"#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\nnamespace Ra {\r\nnamespace Engine {\r\n\r\n\/\/ Template parameter must be a Core::VectorNArray\r\ntemplate \r\ninline void sendGLData( Ra::Engine::Mesh* mesh, const Ra::Core::VectorArray& arr,\r\n const uint vboIdx ) {\r\n using VecArray = Ra::Core::VectorArray;\r\n#ifdef CORE_USE_DOUBLE\r\n GLenum type = GL_DOUBLE;\r\n#else\r\n GLenum type = GL_FLOAT;\r\n#endif\r\n constexpr GLuint size = VecArray::Vector::RowsAtCompileTime;\r\n const GLboolean normalized = GL_FALSE;\r\n constexpr GLint64 ptr = 0;\r\n\r\n \/\/ This vbo has not been created yet\r\n if ( mesh->m_vbos[vboIdx] == 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &( mesh->m_vbos[vboIdx] ) ) );\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, mesh->m_vbos[vboIdx] ) );\r\n\r\n \/\/ Use (vboIdx - 1) as attribute index because vbo 0 is actually ibo.\r\n GL_ASSERT( glVertexAttribPointer( vboIdx - 1, size, type, normalized,\r\n sizeof( typename VecArray::Vector ), (GLvoid*)ptr ) );\r\n\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n \/\/ Set dirty as true to send data, see below\r\n mesh->m_dataDirty[vboIdx] = true;\r\n }\r\n\r\n if ( mesh->m_dataDirty[vboIdx] == true && mesh->m_vbos[vboIdx] != 0 )\r\n {\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, mesh->m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBufferData( GL_ARRAY_BUFFER, arr.size() * sizeof( typename VecArray::Vector ),\r\n arr.data(), GL_DYNAMIC_DRAW ) );\r\n mesh->m_dataDirty[vboIdx] = false;\r\n\r\n if ( arr.size() > 0 )\r\n {\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n } else\r\n { GL_ASSERT( glDisableVertexAttribArray( vboIdx - 1 ) ); }\r\n }\r\n} \/\/ sendGLData\r\n\r\n\/\/ Dirty is initializes as false so that we do not create the vao while\r\n\/\/ we have no data to send to the gpu.\r\nMesh::Mesh( const std::string& name, MeshRenderMode renderMode ) :\r\n m_name( name ),\r\n m_vao( 0 ),\r\n m_renderMode( renderMode ),\r\n m_numElements( 0 ),\r\n m_isDirty( false ) {\r\n CORE_ASSERT( m_renderMode == RM_POINTS || m_renderMode == RM_LINES ||\r\n m_renderMode == RM_LINE_LOOP || m_renderMode == RM_LINE_STRIP ||\r\n m_renderMode == RM_TRIANGLES || m_renderMode == RM_TRIANGLE_STRIP ||\r\n m_renderMode == RM_TRIANGLE_FAN || m_renderMode == RM_LINES_ADJACENCY ||\r\n m_renderMode == RM_LINE_STRIP_ADJACENCY,\r\n \"Unsupported render mode\" );\r\n}\r\n\r\nMesh::~Mesh() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glDeleteVertexArrays( 1, &m_vao ) );\r\n\r\n for ( auto& vbo : m_vbos )\r\n {\r\n if ( vbo != 0 )\r\n {\r\n glDeleteBuffers( 1, &vbo );\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Mesh::render() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n GL_ASSERT( glDrawElements( static_cast( m_renderMode ), m_numElements,\r\n GL_UNSIGNED_INT, (void*)0 ) );\r\n }\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::TriangleMesh& mesh ) {\r\n m_mesh = mesh;\r\n\r\n if ( m_mesh.m_triangles.empty() )\r\n {\r\n m_numElements = m_mesh.vertices().size();\r\n m_renderMode = RM_POINTS;\r\n } else\r\n m_numElements = m_mesh.m_triangles.size() * 3;\r\n\r\n for ( uint i = 0; i < MAX_VEC3; ++i )\r\n {\r\n m_v3DataHandle[i] = m_mesh.getAttribHandle( std::string( \"Vec3_attr_\" ) +\r\n std::to_string( i ) );\r\n }\r\n\r\n for ( uint i = 0; i < MAX_VEC4; ++i )\r\n {\r\n m_v4DataHandle[i] = m_mesh.getAttribHandle( std::string( \"Vec4_attr_\" ) +\r\n std::to_string( i ) );\r\n }\r\n \r\n for ( uint i = 0; i < MAX_DATA; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::updateMeshGeometry( MeshData type, const Core::Vector3Array& data ) {\r\n if ( type == VERTEX_POSITION )\r\n m_mesh.vertices() = data;\r\n if ( type == VERTEX_NORMAL )\r\n m_mesh.normals() = data;\r\n m_dataDirty[static_cast( type )] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::Vector3Array& vertices, const std::vector& indices ) {\r\n \/\/ Do not remove this function to force everyone to use triangle mesh.\r\n \/\/ ... because we have some line meshes as well...\r\n const uint nIdx = indices.size();\r\n\r\n if ( indices.empty() )\r\n {\r\n m_numElements = vertices.size();\r\n m_renderMode = RM_POINTS;\r\n } else\r\n m_numElements = nIdx;\r\n m_mesh.vertices() = vertices;\r\n\r\n \/\/ Check that when loading a triangle mesh we actually have triangles or lines.\r\n CORE_ASSERT( m_renderMode != GL_TRIANGLES || nIdx % 3 == 0,\r\n \"There should be 3 indices per triangle \" );\r\n CORE_ASSERT( m_renderMode != GL_LINES || nIdx % 2 == 0, \"There should be 2 indices per line\" );\r\n CORE_ASSERT( m_renderMode != GL_LINES_ADJACENCY || nIdx % 4 == 0,\r\n \"There should be 4 indices per line adjacency\" );\r\n\r\n for ( uint i = 0; i < indices.size(); i = i + 3 )\r\n {\r\n \/\/ We store all indices in order. This means that for lines we have\r\n \/\/ (L00, L01, L10), (L11, L20, L21) etc. We fill the missing by wrapping around indices.\r\n m_mesh.m_triangles.push_back(\r\n {indices[i], indices[( i + 1 ) % nIdx], indices[( i + 2 ) % nIdx]} );\r\n }\r\n\r\n \/\/ Mark mesh as dirty.\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec3Data& type, const Core::Vector3Array& data ) {\r\n const int index = static_cast( type );\r\n auto& handle = m_v3DataHandle[index];\r\n\r\n \/\/ if it's the first time this handle is used, add it to m_mesh.\r\n if ( data.size() != 0 && !m_mesh.isValid( handle ) )\r\n {\r\n handle =\r\n m_mesh.addAttrib( std::string( \"Vec3_attr_\" ) + std::to_string( type ) );\r\n }\r\n\r\n \/\/ if ( data.size() != 0 && m_mesh.isValid( handle ) )\r\n if ( m_mesh.isValid( handle ) )\r\n {\r\n m_mesh.getAttrib( handle ).data() = data;\r\n\r\n m_dataDirty[MAX_MESH + index] = true;\r\n m_isDirty = true;\r\n }\r\n}\r\n\r\nvoid Mesh::addData( const Vec4Data& type, const Core::Vector4Array& data ) {\r\n\r\n const int index = static_cast( type );\r\n auto& handle = m_v4DataHandle[index];\r\n\r\n \/\/ if it's the first time this handle is used, add it to m_mesh.\r\n if ( data.size() != 0 && !m_mesh.isValid( handle ) )\r\n {\r\n handle =\r\n m_mesh.addAttrib( std::string( \"Vec4_attr_\" ) + std::to_string( type ) );\r\n }\r\n\r\n \/\/ if ( data.size() != 0 && m_mesh.isValid( handle ) )\r\n if ( m_mesh.isValid( handle ) )\r\n {\r\n m_mesh.getAttrib( handle ).data() = data;\r\n m_dataDirty[MAX_MESH + MAX_VEC3 + index] = true;\r\n m_isDirty = true;\r\n }\r\n}\r\n\r\nvoid Mesh::updateGL() {\r\n if ( m_isDirty )\r\n {\r\n \/\/ Check that our dirty bits are consistent.\r\n ON_ASSERT( bool dirtyTest = false; for ( const auto& d\r\n : m_dataDirty ) { dirtyTest = dirtyTest || d; } );\r\n CORE_ASSERT( dirtyTest == m_isDirty, \"Dirty flags inconsistency\" );\r\n\r\n CORE_ASSERT( !( m_mesh.vertices().empty() ), \"No vertex.\" );\r\n\r\n if ( m_vao == 0 )\r\n {\r\n \/\/ Create VAO if it does not exist\r\n GL_ASSERT( glGenVertexArrays( 1, &m_vao ) );\r\n }\r\n\r\n \/\/ Bind it\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n\r\n if ( m_vbos[INDEX] == 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[INDEX] ) );\r\n GL_ASSERT( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vbos[INDEX] ) );\r\n }\r\n if ( m_dataDirty[INDEX] )\r\n {\r\n if ( m_renderMode == RM_POINTS )\r\n {\r\n std::vector indices( m_numElements );\r\n std::iota( indices.begin(), indices.end(), 0 );\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_numElements * sizeof( int ),\r\n indices.data(), GL_DYNAMIC_DRAW ) );\r\n } else\r\n {\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER,\r\n m_mesh.m_triangles.size() * sizeof( Ra::Core::Triangle ),\r\n m_mesh.m_triangles.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n m_dataDirty[INDEX] = false;\r\n }\r\n\r\n \/\/ Geometry data\r\n sendGLData( this, m_mesh.vertices(), VERTEX_POSITION );\r\n sendGLData( this, m_mesh.normals(), VERTEX_NORMAL );\r\n\r\n for ( int i = 0; i < MAX_VEC3; i++ )\r\n {\r\n if ( m_mesh.isValid( m_v3DataHandle[i] ) )\r\n {\r\n sendGLData( this, m_mesh.getAttrib( m_v3DataHandle[i] ).data(), MAX_MESH + i );\r\n }\r\n }\r\n\r\n for ( int i = 0; i < MAX_VEC4; i++ )\r\n {\r\n if ( m_mesh.isValid( m_v4DataHandle[i] ) )\r\n {\r\n sendGLData( this, m_mesh.getAttrib( m_v4DataHandle[i] ).data(),\r\n MAX_MESH + MAX_VEC3 + i );\r\n }\r\n }\r\n\r\n GL_ASSERT( glBindVertexArray( 0 ) );\r\n GL_CHECK_ERROR;\r\n m_isDirty = false;\r\n }\r\n}\r\n\r\n} \/\/ namespace Engine\r\n} \/\/ namespace Ra\r\nInitialize data dirty bits to false in constructor ;#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\n\r\n#include \r\nnamespace Ra {\r\nnamespace Engine {\r\n\r\n\/\/ Template parameter must be a Core::VectorNArray\r\ntemplate \r\ninline void sendGLData( Ra::Engine::Mesh* mesh, const Ra::Core::VectorArray& arr,\r\n const uint vboIdx ) {\r\n using VecArray = Ra::Core::VectorArray;\r\n#ifdef CORE_USE_DOUBLE\r\n GLenum type = GL_DOUBLE;\r\n#else\r\n GLenum type = GL_FLOAT;\r\n#endif\r\n constexpr GLuint size = VecArray::Vector::RowsAtCompileTime;\r\n const GLboolean normalized = GL_FALSE;\r\n constexpr GLint64 ptr = 0;\r\n\r\n \/\/ This vbo has not been created yet\r\n if ( mesh->m_vbos[vboIdx] == 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &( mesh->m_vbos[vboIdx] ) ) );\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, mesh->m_vbos[vboIdx] ) );\r\n\r\n \/\/ Use (vboIdx - 1) as attribute index because vbo 0 is actually ibo.\r\n GL_ASSERT( glVertexAttribPointer( vboIdx - 1, size, type, normalized,\r\n sizeof( typename VecArray::Vector ), (GLvoid*)ptr ) );\r\n\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n \/\/ Set dirty as true to send data, see below\r\n mesh->m_dataDirty[vboIdx] = true;\r\n }\r\n\r\n if ( mesh->m_dataDirty[vboIdx] == true && mesh->m_vbos[vboIdx] != 0 )\r\n {\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, mesh->m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBufferData( GL_ARRAY_BUFFER, arr.size() * sizeof( typename VecArray::Vector ),\r\n arr.data(), GL_DYNAMIC_DRAW ) );\r\n mesh->m_dataDirty[vboIdx] = false;\r\n\r\n if ( arr.size() > 0 )\r\n {\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n } else\r\n { GL_ASSERT( glDisableVertexAttribArray( vboIdx - 1 ) ); }\r\n }\r\n} \/\/ sendGLData\r\n\r\n\/\/ Dirty is initializes as false so that we do not create the vao while\r\n\/\/ we have no data to send to the gpu.\r\nMesh::Mesh( const std::string& name, MeshRenderMode renderMode ) :\r\n m_name( name ),\r\n m_vao( 0 ),\r\n m_renderMode( renderMode ),\r\n m_numElements( 0 ),\r\n m_isDirty( false ) {\r\n CORE_ASSERT( m_renderMode == RM_POINTS || m_renderMode == RM_LINES ||\r\n m_renderMode == RM_LINE_LOOP || m_renderMode == RM_LINE_STRIP ||\r\n m_renderMode == RM_TRIANGLES || m_renderMode == RM_TRIANGLE_STRIP ||\r\n m_renderMode == RM_TRIANGLE_FAN || m_renderMode == RM_LINES_ADJACENCY ||\r\n m_renderMode == RM_LINE_STRIP_ADJACENCY,\r\n \"Unsupported render mode\" );\r\n\r\n \/\/ Mark mesh data as up-to-date.\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = false;\r\n }\r\n}\r\n\r\nMesh::~Mesh() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glDeleteVertexArrays( 1, &m_vao ) );\r\n\r\n for ( auto& vbo : m_vbos )\r\n {\r\n if ( vbo != 0 )\r\n {\r\n glDeleteBuffers( 1, &vbo );\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Mesh::render() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n GL_ASSERT( glDrawElements( static_cast( m_renderMode ), m_numElements,\r\n GL_UNSIGNED_INT, (void*)0 ) );\r\n }\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::TriangleMesh& mesh ) {\r\n m_mesh = mesh;\r\n\r\n if ( m_mesh.m_triangles.empty() )\r\n {\r\n m_numElements = m_mesh.vertices().size();\r\n m_renderMode = RM_POINTS;\r\n } else\r\n m_numElements = m_mesh.m_triangles.size() * 3;\r\n\r\n for ( uint i = 0; i < MAX_VEC3; ++i )\r\n {\r\n m_v3DataHandle[i] = m_mesh.getAttribHandle( std::string( \"Vec3_attr_\" ) +\r\n std::to_string( i ) );\r\n }\r\n\r\n for ( uint i = 0; i < MAX_VEC4; ++i )\r\n {\r\n m_v4DataHandle[i] = m_mesh.getAttribHandle( std::string( \"Vec4_attr_\" ) +\r\n std::to_string( i ) );\r\n }\r\n \r\n for ( uint i = 0; i < MAX_DATA; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::updateMeshGeometry( MeshData type, const Core::Vector3Array& data ) {\r\n if ( type == VERTEX_POSITION )\r\n m_mesh.vertices() = data;\r\n if ( type == VERTEX_NORMAL )\r\n m_mesh.normals() = data;\r\n m_dataDirty[static_cast( type )] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::Vector3Array& vertices, const std::vector& indices ) {\r\n \/\/ Do not remove this function to force everyone to use triangle mesh.\r\n \/\/ ... because we have some line meshes as well...\r\n const uint nIdx = indices.size();\r\n\r\n if ( indices.empty() )\r\n {\r\n m_numElements = vertices.size();\r\n m_renderMode = RM_POINTS;\r\n } else\r\n m_numElements = nIdx;\r\n m_mesh.vertices() = vertices;\r\n\r\n \/\/ Check that when loading a triangle mesh we actually have triangles or lines.\r\n CORE_ASSERT( m_renderMode != GL_TRIANGLES || nIdx % 3 == 0,\r\n \"There should be 3 indices per triangle \" );\r\n CORE_ASSERT( m_renderMode != GL_LINES || nIdx % 2 == 0, \"There should be 2 indices per line\" );\r\n CORE_ASSERT( m_renderMode != GL_LINES_ADJACENCY || nIdx % 4 == 0,\r\n \"There should be 4 indices per line adjacency\" );\r\n\r\n for ( uint i = 0; i < indices.size(); i = i + 3 )\r\n {\r\n \/\/ We store all indices in order. This means that for lines we have\r\n \/\/ (L00, L01, L10), (L11, L20, L21) etc. We fill the missing by wrapping around indices.\r\n m_mesh.m_triangles.push_back(\r\n {indices[i], indices[( i + 1 ) % nIdx], indices[( i + 2 ) % nIdx]} );\r\n }\r\n\r\n \/\/ Mark mesh as dirty.\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec3Data& type, const Core::Vector3Array& data ) {\r\n const int index = static_cast( type );\r\n auto& handle = m_v3DataHandle[index];\r\n\r\n \/\/ if it's the first time this handle is used, add it to m_mesh.\r\n if ( data.size() != 0 && !m_mesh.isValid( handle ) )\r\n {\r\n handle =\r\n m_mesh.addAttrib( std::string( \"Vec3_attr_\" ) + std::to_string( type ) );\r\n }\r\n\r\n \/\/ if ( data.size() != 0 && m_mesh.isValid( handle ) )\r\n if ( m_mesh.isValid( handle ) )\r\n {\r\n m_mesh.getAttrib( handle ).data() = data;\r\n\r\n m_dataDirty[MAX_MESH + index] = true;\r\n m_isDirty = true;\r\n }\r\n}\r\n\r\nvoid Mesh::addData( const Vec4Data& type, const Core::Vector4Array& data ) {\r\n\r\n const int index = static_cast( type );\r\n auto& handle = m_v4DataHandle[index];\r\n\r\n \/\/ if it's the first time this handle is used, add it to m_mesh.\r\n if ( data.size() != 0 && !m_mesh.isValid( handle ) )\r\n {\r\n handle =\r\n m_mesh.addAttrib( std::string( \"Vec4_attr_\" ) + std::to_string( type ) );\r\n }\r\n\r\n \/\/ if ( data.size() != 0 && m_mesh.isValid( handle ) )\r\n if ( m_mesh.isValid( handle ) )\r\n {\r\n m_mesh.getAttrib( handle ).data() = data;\r\n m_dataDirty[MAX_MESH + MAX_VEC3 + index] = true;\r\n m_isDirty = true;\r\n }\r\n}\r\n\r\nvoid Mesh::updateGL() {\r\n if ( m_isDirty )\r\n {\r\n \/\/ Check that our dirty bits are consistent.\r\n ON_ASSERT( bool dirtyTest = false; for ( const auto& d\r\n : m_dataDirty ) { dirtyTest = dirtyTest || d; } );\r\n CORE_ASSERT( dirtyTest == m_isDirty, \"Dirty flags inconsistency\" );\r\n\r\n CORE_ASSERT( !( m_mesh.vertices().empty() ), \"No vertex.\" );\r\n\r\n if ( m_vao == 0 )\r\n {\r\n \/\/ Create VAO if it does not exist\r\n GL_ASSERT( glGenVertexArrays( 1, &m_vao ) );\r\n }\r\n\r\n \/\/ Bind it\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n\r\n if ( m_vbos[INDEX] == 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[INDEX] ) );\r\n GL_ASSERT( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vbos[INDEX] ) );\r\n }\r\n if ( m_dataDirty[INDEX] )\r\n {\r\n if ( m_renderMode == RM_POINTS )\r\n {\r\n std::vector indices( m_numElements );\r\n std::iota( indices.begin(), indices.end(), 0 );\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_numElements * sizeof( int ),\r\n indices.data(), GL_DYNAMIC_DRAW ) );\r\n } else\r\n {\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER,\r\n m_mesh.m_triangles.size() * sizeof( Ra::Core::Triangle ),\r\n m_mesh.m_triangles.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n m_dataDirty[INDEX] = false;\r\n }\r\n\r\n \/\/ Geometry data\r\n sendGLData( this, m_mesh.vertices(), VERTEX_POSITION );\r\n sendGLData( this, m_mesh.normals(), VERTEX_NORMAL );\r\n\r\n for ( int i = 0; i < MAX_VEC3; i++ )\r\n {\r\n if ( m_mesh.isValid( m_v3DataHandle[i] ) )\r\n {\r\n sendGLData( this, m_mesh.getAttrib( m_v3DataHandle[i] ).data(), MAX_MESH + i );\r\n }\r\n }\r\n\r\n for ( int i = 0; i < MAX_VEC4; i++ )\r\n {\r\n if ( m_mesh.isValid( m_v4DataHandle[i] ) )\r\n {\r\n sendGLData( this, m_mesh.getAttrib( m_v4DataHandle[i] ).data(),\r\n MAX_MESH + MAX_VEC3 + i );\r\n }\r\n }\r\n\r\n GL_ASSERT( glBindVertexArray( 0 ) );\r\n GL_CHECK_ERROR;\r\n m_isDirty = false;\r\n }\r\n}\r\n\r\n} \/\/ namespace Engine\r\n} \/\/ namespace Ra\r\n<|endoftext|>"} {"text":"SVN_SILENT This should make SK to compile without -DQT3_SUPPORT<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"clonewizardpage.h\"\n#include \"gitplugin.h\"\n#include \"gitclient.h\"\n\n#include \n\nnamespace Git {\n\nstruct CloneWizardPagePrivate {\n CloneWizardPagePrivate();\n\n bool urlIsLocal(const QString &url);\n\n const QString mainLinePostfix;\n const QString gitPostFix;\n const QString protocolDelimiter;\n};\n\nCloneWizardPagePrivate::CloneWizardPagePrivate() :\n mainLinePostfix(QLatin1String(\"\/mainline.git\")),\n gitPostFix(QLatin1String(\".git\")),\n protocolDelimiter(QLatin1String(\":\/\/\"))\n{\n}\n\nbool CloneWizardPagePrivate::urlIsLocal(const QString &url)\n{\n if (url.startsWith(QLatin1String(\"file:\/\/\"))\n || url.startsWith(QLatin1Char('\/'))\n || (url.at(0).isLetter() && url.at(1) == QLatin1Char(':') && url.at(2) == QLatin1Char('\\\\')))\n return true;\n return false;\n}\n\nCloneWizardPage::CloneWizardPage(QWidget *parent) :\n VcsBase::BaseCheckoutWizardPage(parent),\n d(new CloneWizardPagePrivate)\n{\n setTitle(tr(\"Location\"));\n setSubTitle(tr(\"Specify repository URL, checkout directory and path.\"));\n setRepositoryLabel(tr(\"Clone URL:\"));\n}\n\nCloneWizardPage::~CloneWizardPage()\n{\n delete d;\n}\n\nQString CloneWizardPage::directoryFromRepository(const QString &urlIn) const\n{\n \/* Try to figure out a good directory name from something like:\n * 'user@host:qt\/qt.git', 'http:\/\/host\/qt\/qt.git' 'local repo'\n * ------> 'qt' . *\/\n const QChar slash = QLatin1Char('\/');\n QString url = urlIn.trimmed().replace(QLatin1Char('\\\\'), slash);\n\n \/\/ remove host\n const int protocolDelimiterPos = url.indexOf(d->protocolDelimiter); \/\/ \":\/\/\"\n const int startRepoSearchPos = protocolDelimiterPos == -1 ? 0 : protocolDelimiterPos + d->protocolDelimiter.size();\n int repoPos = url.indexOf(QLatin1Char(':'), startRepoSearchPos);\n if (repoPos == -1)\n repoPos = url.indexOf(slash, startRepoSearchPos);\n if (repoPos != -1)\n url.remove(0, repoPos + 1);\n \/\/ Remove postfixes\n if (url.endsWith(d->mainLinePostfix)) {\n url.truncate(url.size() - d->mainLinePostfix.size());\n } else {\n if (url.endsWith(d->gitPostFix))\n url.truncate(url.size() - d->gitPostFix.size());\n }\n \/\/ Check for equal parts, something like \"qt\/qt\" -> \"qt\"\n const int slashPos = url.indexOf(slash);\n if (slashPos != -1 && slashPos == (url.size() - 1) \/ 2) {\n if (url.leftRef(slashPos) == url.rightRef(slashPos))\n url.truncate(slashPos);\n }\n \/\/ fix invalid characters\n const QChar dash = QLatin1Char('-');\n url.replace(QRegExp(QLatin1String(\"[^0-9a-zA-Z_.-]\")), dash);\n \/\/ trim leading dashes (they are annoying and get created when using local pathes)\n url.replace(QRegExp(QLatin1String(\"^-+\")), QString());\n return url;\n}\n\nVcsBase::Command *CloneWizardPage::createCheckoutJob(QString *checkoutPath) const\n{\n const Internal::GitClient *client = Internal::GitPlugin::instance()->gitClient();\n const QString workingDirectory = path();\n const QString checkoutDir = directory();\n *checkoutPath = workingDirectory + QLatin1Char('\/') + checkoutDir;\n\n const QString checkoutBranch = branch();\n\n QStringList args(QLatin1String(\"clone\"));\n if (!checkoutBranch.isEmpty())\n args << QLatin1String(\"--branch\") << checkoutBranch;\n args << repository() << checkoutDir;\n VcsBase::Command *command = new VcsBase::Command(client->gitBinaryPath(), workingDirectory,\n client->processEnvironment());\n command->addFlags(VcsBase::VcsBasePlugin::MergeOutputChannels);\n command->addJob(args, -1);\n return command;\n}\n\nQStringList CloneWizardPage::branches(const QString &repository, int *current)\n{\n \/\/ Run git on remote repository if an URL was specified.\n *current = -1;\n\n if (repository.isEmpty())\n return QStringList();\n const QStringList branches = Internal::GitPlugin::instance()->gitClient()->synchronousRepositoryBranches(repository);\n if (!branches.isEmpty())\n *current = 0; \/\/ default branch is always returned first!\n return branches;\n}\n\n} \/\/ namespace Git\nGit: Show progress on clone\/****************************************************************************\n**\n** Copyright (C) 2013 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"clonewizardpage.h\"\n#include \"gitplugin.h\"\n#include \"gitclient.h\"\n\n#include \n\nnamespace Git {\n\nstruct CloneWizardPagePrivate {\n CloneWizardPagePrivate();\n\n bool urlIsLocal(const QString &url);\n\n const QString mainLinePostfix;\n const QString gitPostFix;\n const QString protocolDelimiter;\n};\n\nCloneWizardPagePrivate::CloneWizardPagePrivate() :\n mainLinePostfix(QLatin1String(\"\/mainline.git\")),\n gitPostFix(QLatin1String(\".git\")),\n protocolDelimiter(QLatin1String(\":\/\/\"))\n{\n}\n\nbool CloneWizardPagePrivate::urlIsLocal(const QString &url)\n{\n if (url.startsWith(QLatin1String(\"file:\/\/\"))\n || url.startsWith(QLatin1Char('\/'))\n || (url.at(0).isLetter() && url.at(1) == QLatin1Char(':') && url.at(2) == QLatin1Char('\\\\')))\n return true;\n return false;\n}\n\nCloneWizardPage::CloneWizardPage(QWidget *parent) :\n VcsBase::BaseCheckoutWizardPage(parent),\n d(new CloneWizardPagePrivate)\n{\n setTitle(tr(\"Location\"));\n setSubTitle(tr(\"Specify repository URL, checkout directory and path.\"));\n setRepositoryLabel(tr(\"Clone URL:\"));\n}\n\nCloneWizardPage::~CloneWizardPage()\n{\n delete d;\n}\n\nQString CloneWizardPage::directoryFromRepository(const QString &urlIn) const\n{\n \/* Try to figure out a good directory name from something like:\n * 'user@host:qt\/qt.git', 'http:\/\/host\/qt\/qt.git' 'local repo'\n * ------> 'qt' . *\/\n const QChar slash = QLatin1Char('\/');\n QString url = urlIn.trimmed().replace(QLatin1Char('\\\\'), slash);\n\n \/\/ remove host\n const int protocolDelimiterPos = url.indexOf(d->protocolDelimiter); \/\/ \":\/\/\"\n const int startRepoSearchPos = protocolDelimiterPos == -1 ? 0 : protocolDelimiterPos + d->protocolDelimiter.size();\n int repoPos = url.indexOf(QLatin1Char(':'), startRepoSearchPos);\n if (repoPos == -1)\n repoPos = url.indexOf(slash, startRepoSearchPos);\n if (repoPos != -1)\n url.remove(0, repoPos + 1);\n \/\/ Remove postfixes\n if (url.endsWith(d->mainLinePostfix)) {\n url.truncate(url.size() - d->mainLinePostfix.size());\n } else {\n if (url.endsWith(d->gitPostFix))\n url.truncate(url.size() - d->gitPostFix.size());\n }\n \/\/ Check for equal parts, something like \"qt\/qt\" -> \"qt\"\n const int slashPos = url.indexOf(slash);\n if (slashPos != -1 && slashPos == (url.size() - 1) \/ 2) {\n if (url.leftRef(slashPos) == url.rightRef(slashPos))\n url.truncate(slashPos);\n }\n \/\/ fix invalid characters\n const QChar dash = QLatin1Char('-');\n url.replace(QRegExp(QLatin1String(\"[^0-9a-zA-Z_.-]\")), dash);\n \/\/ trim leading dashes (they are annoying and get created when using local pathes)\n url.replace(QRegExp(QLatin1String(\"^-+\")), QString());\n return url;\n}\n\nVcsBase::Command *CloneWizardPage::createCheckoutJob(QString *checkoutPath) const\n{\n const Internal::GitClient *client = Internal::GitPlugin::instance()->gitClient();\n const QString workingDirectory = path();\n const QString checkoutDir = directory();\n *checkoutPath = workingDirectory + QLatin1Char('\/') + checkoutDir;\n\n const QString checkoutBranch = branch();\n\n QStringList args(QLatin1String(\"clone\"));\n if (!checkoutBranch.isEmpty())\n args << QLatin1String(\"--branch\") << checkoutBranch;\n args << QLatin1String(\"--progress\") << repository() << checkoutDir;\n VcsBase::Command *command = new VcsBase::Command(client->gitBinaryPath(), workingDirectory,\n client->processEnvironment());\n command->addFlags(VcsBase::VcsBasePlugin::MergeOutputChannels);\n command->addJob(args, -1);\n return command;\n}\n\nQStringList CloneWizardPage::branches(const QString &repository, int *current)\n{\n \/\/ Run git on remote repository if an URL was specified.\n *current = -1;\n\n if (repository.isEmpty())\n return QStringList();\n const QStringList branches = Internal::GitPlugin::instance()->gitClient()->synchronousRepositoryBranches(repository);\n if (!branches.isEmpty())\n *current = 0; \/\/ default branch is always returned first!\n return branches;\n}\n\n} \/\/ namespace Git\n<|endoftext|>"} {"text":"#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\nnamespace Ra {\r\nnamespace Engine {\r\n\r\n\/\/ Dirty is initializes as false so that we do not create the vao while\r\n\/\/ we have no data to send to the gpu.\r\nMesh::Mesh( const std::string& name, MeshRenderMode renderMode ) :\r\n m_name( name ),\r\n m_vao( 0 ),\r\n m_renderMode( renderMode ),\r\n m_numElements( 0 ),\r\n m_isDirty( false ) {\r\n CORE_ASSERT( m_renderMode == RM_POINTS || m_renderMode == RM_LINES ||\r\n m_renderMode == RM_LINE_LOOP || m_renderMode == RM_LINE_STRIP ||\r\n m_renderMode == RM_TRIANGLES || m_renderMode == RM_TRIANGLE_STRIP ||\r\n m_renderMode == RM_TRIANGLE_FAN || m_renderMode == RM_LINES_ADJACENCY ||\r\n m_renderMode == RM_LINE_STRIP_ADJACENCY,\r\n \"Unsupported render mode\" );\r\n}\r\n\r\nMesh::~Mesh() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glDeleteVertexArrays( 1, &m_vao ) );\r\n for ( auto& vbo : m_vbos )\r\n {\r\n glDeleteBuffers( 1, &vbo );\r\n }\r\n }\r\n}\r\n\r\nvoid Mesh::render() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n GL_ASSERT( glDrawElements( static_cast( m_renderMode ), m_numElements,\r\n GL_UNSIGNED_INT, (void*)0 ) );\r\n }\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::TriangleMesh& mesh ) {\r\n m_mesh = mesh;\r\n\r\n if ( m_mesh.m_triangles.empty() )\r\n {\r\n m_numElements = mesh.vertices().size();\r\n m_renderMode = RM_POINTS;\r\n }\r\n else\r\n m_numElements = mesh.m_triangles.size() * 3;\r\n\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::updateMeshGeometry( MeshData type, const Core::Vector3Array& data ) {\r\n if ( type == VERTEX_POSITION )\r\n m_mesh.vertices() = data;\r\n if ( type == VERTEX_NORMAL )\r\n m_mesh.normals() = data;\r\n m_dataDirty[static_cast( type )] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::Vector3Array& vertices, const std::vector& indices ) {\r\n \/\/ Do not remove this function to force everyone to use triangle mesh.\r\n \/\/ ... because we have some line meshes as well...\r\n const uint nIdx = indices.size();\r\n\r\n if ( indices.empty() )\r\n {\r\n m_numElements = vertices.size();\r\n m_renderMode = RM_POINTS;\r\n }\r\n else\r\n m_numElements = nIdx;\r\n m_mesh.vertices() = vertices;\r\n\r\n \/\/ Check that when loading a triangle mesh we actually have triangles or lines.\r\n CORE_ASSERT( m_renderMode != GL_TRIANGLES || nIdx % 3 == 0,\r\n \"There should be 3 indices per triangle \" );\r\n CORE_ASSERT( m_renderMode != GL_LINES || nIdx % 2 == 0, \"There should be 2 indices per line\" );\r\n CORE_ASSERT( m_renderMode != GL_LINES_ADJACENCY || nIdx % 4 == 0,\r\n \"There should be 4 indices per line adjacency\" );\r\n\r\n for ( uint i = 0; i < indices.size(); i = i + 3 )\r\n {\r\n \/\/ We store all indices in order. This means that for lines we have\r\n \/\/ (L00, L01, L10), (L11, L20, L21) etc. We fill the missing by wrapping around indices.\r\n m_mesh.m_triangles.push_back(\r\n {indices[i], indices[( i + 1 ) % nIdx], indices[( i + 2 ) % nIdx]} );\r\n }\r\n\r\n \/\/ Mark mesh as dirty.\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec3Data& type, const Core::Vector3Array& data ) {\r\n const int index = static_cast( type );\r\n if ( !m_v3DataHandle[index].isValid() )\r\n {\r\n m_v3DataHandle[index] =\r\n m_mesh.attribManager().addAttrib( std::to_string( MAX_MESH + index ) );\r\n }\r\n m_mesh.attribManager().getAttrib( m_v3DataHandle[index] ).data() = data;\r\n m_dataDirty[MAX_MESH + index] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec4Data& type, const Core::Vector4Array& data ) {\r\n const int index = static_cast( type );\r\n\r\n \/\/\/ to handle dummy set, if not valid, and dummy data, do nothing\r\n if ( data.size() == 0 && !m_v4DataHandle[index].isValid() )\r\n {\r\n return;\r\n }\r\n if ( !m_v4DataHandle[index].isValid() )\r\n {\r\n m_v4DataHandle[index] = m_mesh.attribManager().addAttrib(\r\n std::to_string( MAX_MESH + MAX_VEC3 + index ) );\r\n }\r\n m_mesh.attribManager().getAttrib( m_v4DataHandle[index] ).data() = data;\r\n m_dataDirty[MAX_MESH + MAX_VEC3 + index] = true;\r\n m_isDirty = true;\r\n}\r\n\r\n\/\/ Template parameter must be a Core::VectorNArray\r\ntemplate \r\nvoid Mesh::sendGLData( const VecArray& arr, const uint vboIdx ) {\r\n\r\n#ifdef CORE_USE_DOUBLE\r\n GLenum type = GL_DOUBLE;\r\n#else\r\n GLenum type = GL_FLOAT;\r\n#endif\r\n constexpr GLuint size = VecArray::Vector::RowsAtCompileTime;\r\n const GLboolean normalized = GL_FALSE;\r\n constexpr GLint64 ptr = 0;\r\n\r\n \/\/ This vbo has not been created yet\r\n if ( m_vbos[vboIdx] == 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, m_vbos[vboIdx] ) );\r\n\r\n \/\/ Use (vboIdx - 1) as attribute index because vbo 0 is actually ibo.\r\n GL_ASSERT( glVertexAttribPointer( vboIdx - 1, size, type, normalized,\r\n sizeof( typename VecArray::Vector ), (GLvoid*)ptr ) );\r\n\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n \/\/ Set dirty as true to send data, see below\r\n m_dataDirty[vboIdx] = true;\r\n }\r\n\r\n if ( m_dataDirty[vboIdx] == true && m_vbos[vboIdx] != 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBufferData( GL_ARRAY_BUFFER, arr.size() * sizeof( typename VecArray::Vector ),\r\n arr.data(), GL_DYNAMIC_DRAW ) );\r\n m_dataDirty[vboIdx] = false;\r\n }\r\n}\r\n\r\nvoid Mesh::updateGL() {\r\n if ( m_isDirty )\r\n {\r\n \/\/ Check that our dirty bits are consistent.\r\n ON_ASSERT( bool dirtyTest = false; for ( const auto& d\r\n : m_dataDirty ) { dirtyTest = dirtyTest || d; } );\r\n CORE_ASSERT( dirtyTest == m_isDirty, \"Dirty flags inconsistency\" );\r\n\r\n CORE_ASSERT( !( m_mesh.vertices().empty() ), \"No vertex.\" );\r\n\r\n if ( m_vao == 0 )\r\n {\r\n \/\/ Create VAO if it does not exist\r\n GL_ASSERT( glGenVertexArrays( 1, &m_vao ) );\r\n }\r\n\r\n \/\/ Bind it\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n\r\n if ( m_vbos[INDEX] == 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[INDEX] ) );\r\n GL_ASSERT( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vbos[INDEX] ) );\r\n }\r\n if ( m_dataDirty[INDEX] )\r\n {\r\n if ( m_renderMode == RM_POINTS )\r\n {\r\n std::vector indices( m_numElements );\r\n std::iota( indices.begin(), indices.end(), 0 );\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_numElements * sizeof( int ),\r\n indices.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n else\r\n {\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER,\r\n m_mesh.m_triangles.size() * sizeof( Ra::Core::Triangle ),\r\n m_mesh.m_triangles.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n m_dataDirty[INDEX] = false;\r\n }\r\n\r\n \/\/ Geometry data\r\n sendGLData( m_mesh.vertices(), VERTEX_POSITION );\r\n sendGLData( m_mesh.normals(), VERTEX_NORMAL );\r\n\r\n \/\/ Vec3 data\r\n\r\n if ( m_v3DataHandle[VERTEX_TANGENT].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_TANGENT] ).data(),\r\n MAX_MESH + VERTEX_TANGENT );\r\n if ( m_v3DataHandle[VERTEX_BITANGENT].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_BITANGENT] ).data(),\r\n MAX_MESH + VERTEX_BITANGENT );\r\n if ( m_v3DataHandle[VERTEX_TEXCOORD].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_TEXCOORD] ).data(),\r\n MAX_MESH + VERTEX_TEXCOORD );\r\n\r\n \/\/ Vec4 data\r\n if ( m_v4DataHandle[VERTEX_COLOR].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_COLOR] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_COLOR );\r\n\r\n if ( m_v4DataHandle[VERTEX_WEIGHTS].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_WEIGHTS] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_WEIGHTS );\r\n\r\n if ( m_v4DataHandle[VERTEX_WEIGHT_IDX].isValid() )\r\n sendGLData(\r\n m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_WEIGHT_IDX] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_WEIGHT_IDX );\r\n GL_ASSERT( glBindVertexArray( 0 ) );\r\n GL_CHECK_ERROR;\r\n m_isDirty = false;\r\n }\r\n}\r\n\r\n} \/\/ namespace Engine\r\n} \/\/ namespace Ra\r\nCleaning#include \r\n\r\n#include \r\n\r\n#include \r\n#include \r\n#include \r\nnamespace Ra {\r\nnamespace Engine {\r\n\r\n\/\/ Dirty is initializes as false so that we do not create the vao while\r\n\/\/ we have no data to send to the gpu.\r\nMesh::Mesh( const std::string& name, MeshRenderMode renderMode ) :\r\n m_name( name ),\r\n m_vao( 0 ),\r\n m_renderMode( renderMode ),\r\n m_numElements( 0 ),\r\n m_isDirty( false ) {\r\n CORE_ASSERT( m_renderMode == RM_POINTS || m_renderMode == RM_LINES ||\r\n m_renderMode == RM_LINE_LOOP || m_renderMode == RM_LINE_STRIP ||\r\n m_renderMode == RM_TRIANGLES || m_renderMode == RM_TRIANGLE_STRIP ||\r\n m_renderMode == RM_TRIANGLE_FAN || m_renderMode == RM_LINES_ADJACENCY ||\r\n m_renderMode == RM_LINE_STRIP_ADJACENCY,\r\n \"Unsupported render mode\" );\r\n}\r\n\r\nMesh::~Mesh() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glDeleteVertexArrays( 1, &m_vao ) );\r\n\r\n for ( auto& vbo : m_vbos )\r\n {\r\n if ( vbo != 0 )\r\n {\r\n glDeleteBuffers( 1, &vbo );\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Mesh::render() {\r\n if ( m_vao != 0 )\r\n {\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n GL_ASSERT( glDrawElements( static_cast( m_renderMode ), m_numElements,\r\n GL_UNSIGNED_INT, (void*)0 ) );\r\n }\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::TriangleMesh& mesh ) {\r\n m_mesh = mesh;\r\n\r\n if ( m_mesh.m_triangles.empty() )\r\n {\r\n m_numElements = mesh.vertices().size();\r\n m_renderMode = RM_POINTS;\r\n }\r\n else\r\n m_numElements = mesh.m_triangles.size() * 3;\r\n\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::updateMeshGeometry( MeshData type, const Core::Vector3Array& data ) {\r\n if ( type == VERTEX_POSITION )\r\n m_mesh.vertices() = data;\r\n if ( type == VERTEX_NORMAL )\r\n m_mesh.normals() = data;\r\n m_dataDirty[static_cast( type )] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::loadGeometry( const Core::Vector3Array& vertices, const std::vector& indices ) {\r\n \/\/ Do not remove this function to force everyone to use triangle mesh.\r\n \/\/ ... because we have some line meshes as well...\r\n const uint nIdx = indices.size();\r\n\r\n if ( indices.empty() )\r\n {\r\n m_numElements = vertices.size();\r\n m_renderMode = RM_POINTS;\r\n }\r\n else\r\n m_numElements = nIdx;\r\n m_mesh.vertices() = vertices;\r\n\r\n \/\/ Check that when loading a triangle mesh we actually have triangles or lines.\r\n CORE_ASSERT( m_renderMode != GL_TRIANGLES || nIdx % 3 == 0,\r\n \"There should be 3 indices per triangle \" );\r\n CORE_ASSERT( m_renderMode != GL_LINES || nIdx % 2 == 0, \"There should be 2 indices per line\" );\r\n CORE_ASSERT( m_renderMode != GL_LINES_ADJACENCY || nIdx % 4 == 0,\r\n \"There should be 4 indices per line adjacency\" );\r\n\r\n for ( uint i = 0; i < indices.size(); i = i + 3 )\r\n {\r\n \/\/ We store all indices in order. This means that for lines we have\r\n \/\/ (L00, L01, L10), (L11, L20, L21) etc. We fill the missing by wrapping around indices.\r\n m_mesh.m_triangles.push_back(\r\n {indices[i], indices[( i + 1 ) % nIdx], indices[( i + 2 ) % nIdx]} );\r\n }\r\n\r\n \/\/ Mark mesh as dirty.\r\n for ( uint i = 0; i < MAX_MESH; ++i )\r\n {\r\n m_dataDirty[i] = true;\r\n }\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec3Data& type, const Core::Vector3Array& data ) {\r\n const int index = static_cast( type );\r\n if ( !m_v3DataHandle[index].isValid() )\r\n {\r\n m_v3DataHandle[index] =\r\n m_mesh.attribManager().addAttrib( std::to_string( MAX_MESH + index ) );\r\n }\r\n m_mesh.attribManager().getAttrib( m_v3DataHandle[index] ).data() = data;\r\n m_dataDirty[MAX_MESH + index] = true;\r\n m_isDirty = true;\r\n}\r\n\r\nvoid Mesh::addData( const Vec4Data& type, const Core::Vector4Array& data ) {\r\n const int index = static_cast( type );\r\n\r\n \/\/\/ to handle dummy set, if not valid, and dummy data, do nothing\r\n if ( data.size() == 0 && !m_v4DataHandle[index].isValid() )\r\n {\r\n return;\r\n }\r\n if ( !m_v4DataHandle[index].isValid() )\r\n {\r\n m_v4DataHandle[index] = m_mesh.attribManager().addAttrib(\r\n std::to_string( MAX_MESH + MAX_VEC3 + index ) );\r\n }\r\n m_mesh.attribManager().getAttrib( m_v4DataHandle[index] ).data() = data;\r\n m_dataDirty[MAX_MESH + MAX_VEC3 + index] = true;\r\n m_isDirty = true;\r\n}\r\n\r\n\/\/ Template parameter must be a Core::VectorNArray\r\ntemplate \r\nvoid Mesh::sendGLData( const VecArray& arr, const uint vboIdx ) {\r\n\r\n#ifdef CORE_USE_DOUBLE\r\n GLenum type = GL_DOUBLE;\r\n#else\r\n GLenum type = GL_FLOAT;\r\n#endif\r\n constexpr GLuint size = VecArray::Vector::RowsAtCompileTime;\r\n const GLboolean normalized = GL_FALSE;\r\n constexpr GLint64 ptr = 0;\r\n\r\n \/\/ This vbo has not been created yet\r\n if ( m_vbos[vboIdx] == 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, m_vbos[vboIdx] ) );\r\n\r\n \/\/ Use (vboIdx - 1) as attribute index because vbo 0 is actually ibo.\r\n GL_ASSERT( glVertexAttribPointer( vboIdx - 1, size, type, normalized,\r\n sizeof( typename VecArray::Vector ), (GLvoid*)ptr ) );\r\n\r\n GL_ASSERT( glEnableVertexAttribArray( vboIdx - 1 ) );\r\n \/\/ Set dirty as true to send data, see below\r\n m_dataDirty[vboIdx] = true;\r\n }\r\n\r\n if ( m_dataDirty[vboIdx] == true && m_vbos[vboIdx] != 0 && arr.size() > 0 )\r\n {\r\n GL_ASSERT( glBindBuffer( GL_ARRAY_BUFFER, m_vbos[vboIdx] ) );\r\n GL_ASSERT( glBufferData( GL_ARRAY_BUFFER, arr.size() * sizeof( typename VecArray::Vector ),\r\n arr.data(), GL_DYNAMIC_DRAW ) );\r\n m_dataDirty[vboIdx] = false;\r\n }\r\n}\r\n\r\nvoid Mesh::updateGL() {\r\n if ( m_isDirty )\r\n {\r\n \/\/ Check that our dirty bits are consistent.\r\n ON_ASSERT( bool dirtyTest = false; for ( const auto& d\r\n : m_dataDirty ) { dirtyTest = dirtyTest || d; } );\r\n CORE_ASSERT( dirtyTest == m_isDirty, \"Dirty flags inconsistency\" );\r\n\r\n CORE_ASSERT( !( m_mesh.vertices().empty() ), \"No vertex.\" );\r\n\r\n if ( m_vao == 0 )\r\n {\r\n \/\/ Create VAO if it does not exist\r\n GL_ASSERT( glGenVertexArrays( 1, &m_vao ) );\r\n }\r\n\r\n \/\/ Bind it\r\n GL_ASSERT( glBindVertexArray( m_vao ) );\r\n\r\n if ( m_vbos[INDEX] == 0 )\r\n {\r\n GL_ASSERT( glGenBuffers( 1, &m_vbos[INDEX] ) );\r\n GL_ASSERT( glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_vbos[INDEX] ) );\r\n }\r\n if ( m_dataDirty[INDEX] )\r\n {\r\n if ( m_renderMode == RM_POINTS )\r\n {\r\n std::vector indices( m_numElements );\r\n std::iota( indices.begin(), indices.end(), 0 );\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_numElements * sizeof( int ),\r\n indices.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n else\r\n {\r\n GL_ASSERT( glBufferData( GL_ELEMENT_ARRAY_BUFFER,\r\n m_mesh.m_triangles.size() * sizeof( Ra::Core::Triangle ),\r\n m_mesh.m_triangles.data(), GL_DYNAMIC_DRAW ) );\r\n }\r\n m_dataDirty[INDEX] = false;\r\n }\r\n\r\n \/\/ Geometry data\r\n sendGLData( m_mesh.vertices(), VERTEX_POSITION );\r\n sendGLData( m_mesh.normals(), VERTEX_NORMAL );\r\n\r\n \/\/ Vec3 data\r\n\r\n if ( m_v3DataHandle[VERTEX_TANGENT].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_TANGENT] ).data(),\r\n MAX_MESH + VERTEX_TANGENT );\r\n if ( m_v3DataHandle[VERTEX_BITANGENT].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_BITANGENT] ).data(),\r\n MAX_MESH + VERTEX_BITANGENT );\r\n if ( m_v3DataHandle[VERTEX_TEXCOORD].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v3DataHandle[VERTEX_TEXCOORD] ).data(),\r\n MAX_MESH + VERTEX_TEXCOORD );\r\n\r\n \/\/ Vec4 data\r\n if ( m_v4DataHandle[VERTEX_COLOR].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_COLOR] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_COLOR );\r\n\r\n if ( m_v4DataHandle[VERTEX_WEIGHTS].isValid() )\r\n sendGLData( m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_WEIGHTS] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_WEIGHTS );\r\n\r\n if ( m_v4DataHandle[VERTEX_WEIGHT_IDX].isValid() )\r\n sendGLData(\r\n m_mesh.attribManager().getAttrib( m_v4DataHandle[VERTEX_WEIGHT_IDX] ).data(),\r\n MAX_MESH + MAX_VEC3 + VERTEX_WEIGHT_IDX );\r\n GL_ASSERT( glBindVertexArray( 0 ) );\r\n GL_CHECK_ERROR;\r\n m_isDirty = false;\r\n }\r\n}\r\n\r\n} \/\/ namespace Engine\r\n} \/\/ namespace Ra\r\n<|endoftext|>"} {"text":"#include \"Firmware.h\"\r\n#include \r\n#include \r\n\r\n#define VERSION_POINT_LOCATION 0x67F6\r\n#define CRC_LOCATION_FLASH 0x67FE\r\n#define CRC_LOCATION_EEPROM (EEPROM_SIZE - 2) \/\/write crc to last eeprom location\r\n\r\nbool checkNewRevision() {\r\n\r\n \/\/current app crc is written to last flash location\r\n \/\/previous crc is stored into eeprom\r\n \/\/if two differ, app has changed\r\n\r\n uint16_t crc_eeprom = eeprom_read_word((uint16_t*)CRC_LOCATION_EEPROM);\r\n uint16_t crc_flash = pgm_read_word_near(CRC_LOCATION_FLASH);\r\n\r\n if (crc_eeprom != crc_flash) {\r\n\r\n eeprom_update_word((uint16_t*)CRC_LOCATION_EEPROM, crc_flash);\r\n return true;\r\n\r\n } return false;\r\n\r\n return false;\r\n\r\n}\r\n\r\nuint8_t getSWversion(swVersion_t point) {\r\n\r\n switch(point) {\r\n\r\n case swVersion_major:\r\n case swVersion_minor:\r\n case swVersion_revision:\r\n case swVersion_development:\r\n return (uint8_t)pgm_read_word_far(VERSION_POINT_LOCATION+(uint8_t)point*2);\r\n\r\n default:\r\n return 0;\r\n\r\n }\r\n\r\n}use addresses specified as symbols#include \"Firmware.h\"\r\n#include \r\n#include \r\n\r\n#define VERSION_POINT_LOCATION (FLASH_SIZE - 10) \/\/8 bytes for version, 2 bytes for crc\r\n#define CRC_LOCATION_FLASH (FLASH_SIZE - 2)\r\n#define CRC_LOCATION_EEPROM (EEPROM_SIZE - 2) \/\/write crc to last eeprom location\r\n\r\n\/\/bool checkNewRevision() {\r\n\/\/\r\n \/\/\/\/current app crc is written to last flash location\r\n \/\/\/\/previous crc is stored into eeprom\r\n \/\/\/\/if two differ, app has changed\r\n\/\/\r\n \/\/uint16_t crc_eeprom = eeprom_read_word((uint16_t*)CRC_LOCATION_EEPROM);\r\n \/\/uint16_t crc_flash = pgm_read_word_near(CRC_LOCATION_FLASH);\r\n\/\/\r\n \/\/if (crc_eeprom != crc_flash) {\r\n\/\/\r\n \/\/eeprom_update_word((uint16_t*)CRC_LOCATION_EEPROM, crc_flash);\r\n \/\/return true;\r\n\/\/\r\n \/\/} return false;\r\n\/\/\r\n \/\/return false;\r\n\/\/\r\n\/\/}\r\n\r\nuint8_t getSWversion(swVersion_t point) {\r\n\r\n switch(point) {\r\n\r\n case swVersion_major:\r\n case swVersion_minor:\r\n case swVersion_revision:\r\n case swVersion_development:\r\n return (uint8_t)pgm_read_word_far(VERSION_POINT_LOCATION+(uint8_t)point*2);\r\n\r\n default:\r\n return 0;\r\n\r\n }\r\n\r\n}<|endoftext|>"} {"text":"\/\/ -*- C++ -*-\n\n\/**\n * @file gnuwrapper.cpp\n * @brief Replaces malloc family on GNU\/Linux with custom versions.\n * @author Emery Berger \n * @note Copyright (C) 2010 by Emery Berger, University of Massachusetts Amherst.\n *\/\n\n\n#ifndef __GNUC__\n#error \"This file requires the GNU compiler.\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n\/*\n To use this library,\n you only need to define the following allocation functions:\n \n - xxmalloc\n - xxfree\n - xxmalloc_usable_size\n \n See the extern \"C\" block below for function prototypes and more\n details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO\n SUPPORT ANY ALLOCATOR.\n\n\n LIMITATIONS:\n\n - This wrapper assumes that the underlying allocator will do \"the\n right thing\" when xxfree() is called with a pointer internal to an\n allocated object. Header-based allocators, for example, need not\n apply.\n\n*\/\n\nstatic bool initialized = false;\n\nextern \"C\" {\n\n void * xxmalloc (size_t);\n void xxfree (void *);\n\n \/\/ Takes a pointer and returns how much space it holds.\n size_t xxmalloc_usable_size (void *);\n\n\n static void my_init_hook (void);\n\n \/\/ New hooks for allocation functions.\n static void * my_malloc_hook (size_t, const void *);\n static void my_free_hook (void *, const void *);\n static void * my_realloc_hook (void *, size_t, const void *);\n static void * my_memalign_hook (size_t, size_t, const void *);\n\n \/\/ Store the old hooks just in case.\n static void * (*old_malloc_hook) (size_t, const void *);\n static void (*old_free_hook) (void *, const void *);\n static void * (*old_realloc_hook)(void *ptr, size_t size, const void *caller);\n static void * (*old_memalign_hook)(size_t alignment, size_t size, const void *caller);\n\n\/\/ From GNU libc 2.14 this macro is defined, to declare\n\/\/ hook variables as volatile. Define it as empty for\n\/\/ older glibc versions\n#ifndef __MALLOC_HOOK_VOLATILE\n #define __MALLOC_HOOK_VOLATILE\n#endif\n\n void (*__MALLOC_HOOK_VOLATILE __malloc_initialize_hook) (void) = my_init_hook;\n\n static void my_init_hook (void) {\n \/\/ Store the old hooks.\n old_malloc_hook = __malloc_hook;\n old_free_hook = __free_hook;\n old_realloc_hook = __realloc_hook;\n old_memalign_hook = __memalign_hook;\n\n \/\/ Point the hooks to the replacement functions.\n __malloc_hook = my_malloc_hook;\n __free_hook = my_free_hook;\n __realloc_hook = my_realloc_hook;\n __memalign_hook = my_memalign_hook;\n\n initialized = true;\n }\n\n static void * my_malloc_hook (size_t size, const void *) {\n return xxmalloc(size);\n }\n\n static void my_free_hook (void * ptr, const void *) {\n xxfree(ptr);\n }\n\n static void * my_realloc_hook (void * ptr, size_t sz, const void *) {\n \/\/ NULL ptr = malloc.\n if (ptr == NULL) {\n return xxmalloc(sz);\n }\n\n if (sz == 0) {\n xxfree (ptr);\n#if defined(__APPLE__)\n \/\/ 0 size = free. We return a small object. This behavior is\n \/\/ apparently required under Mac OS X and optional under POSIX.\n return xxmalloc(1);\n#else\n \/\/ For POSIX, don't return anything.\n return NULL;\n#endif\n }\n\n size_t objSize = xxmalloc_usable_size(ptr);\n\n#if 0\n \/\/ Custom logic here to ensure we only do a logarithmic number of\n \/\/ reallocations (with a constant space overhead).\n\n \/\/ Don't change size if the object is shrinking by less than half.\n if ((objSize \/ 2 < sz) && (sz <= objSize)) {\n \/\/ Do nothing.\n return ptr;\n }\n \/\/ If the object is growing by less than 2X, double it.\n if ((objSize < sz) && (sz < objSize * 2)) {\n sz = objSize * 2;\n }\n#endif\n\n void * buf = xxmalloc(sz);\n\n if (buf != NULL) {\n \/\/ Successful malloc.\n \/\/ Copy the contents of the original object\n \/\/ up to the size of the new block.\n size_t minSize = (objSize < sz) ? objSize : sz;\n memcpy (buf, ptr, minSize);\n xxfree (ptr);\n }\n\n \/\/ Return a pointer to the new one.\n return buf;\n }\n\n static void * my_memalign_hook (size_t size, size_t alignment, const void *) {\n \/\/ Check for non power-of-two alignment, or mistake in size.\n if ((alignment == 0) ||\n\t(alignment & (alignment - 1)))\n {\n\treturn NULL;\n }\n\n \/\/ Try to just allocate an object of the requested size.\n \/\/ If it happens to be aligned properly, just return it.\n void * ptr = xxmalloc (size);\n if (((size_t) ptr & (alignment - 1)) == (size_t) ptr) {\n \/\/ It is already aligned just fine; return it.\n return ptr;\n }\n\n \/\/ It was not aligned as requested: free the object.\n xxfree (ptr);\n\n \/\/ Now get a big chunk of memory and align the object within it.\n \/\/ NOTE: this REQUIRES that the underlying allocator be able\n \/\/ to free the aligned object, or ignore the free request.\n void * buf = xxmalloc (2 * alignment + size);\n void * alignedPtr = (void *) (((size_t) buf + alignment - 1) & ~(alignment - 1));\n\n return alignedPtr;\n }\n\n\n \/\/ This is here because, for some reason, the GNU hooks don't\n \/\/ necessarily replace all memory operations as they should.\n\n int posix_memalign (void **memptr, size_t alignment, size_t size) throw()\n {\n if (!initialized) {\n my_init_hook();\n }\n \/\/ Check for non power-of-two alignment.\n if ((alignment == 0) ||\n\t(alignment & (alignment - 1)))\n {\n\treturn EINVAL;\n }\n void * ptr = my_memalign_hook (size, alignment, NULL);\n if (!ptr) {\n return ENOMEM;\n } else {\n *memptr = ptr;\n return 0;\n }\n }\n\n size_t malloc_usable_size (void * ptr) throw() {\n return xxmalloc_usable_size (ptr);\n }\n\n}\n\nAdded checks to make sure we are initialized. Added new interception.\/\/ -*- C++ -*-\n\n\/**\n * @file gnuwrapper.cpp\n * @brief Replaces malloc family on GNU\/Linux with custom versions.\n * @author Emery Berger \n * @note Copyright (C) 2010 by Emery Berger, University of Massachusetts Amherst.\n *\/\n\n\n#ifndef __GNUC__\n#error \"This file requires the GNU compiler.\"\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/*\n To use this library,\n you only need to define the following allocation functions:\n \n - xxmalloc\n - xxfree\n - xxmalloc_usable_size\n \n See the extern \"C\" block below for function prototypes and more\n details. YOU SHOULD NOT NEED TO MODIFY ANY OF THE CODE HERE TO\n SUPPORT ANY ALLOCATOR.\n\n\n LIMITATIONS:\n\n - This wrapper assumes that the underlying allocator will do \"the\n right thing\" when xxfree() is called with a pointer internal to an\n allocated object. Header-based allocators, for example, need not\n apply.\n\n*\/\n\nstatic bool initialized = false;\n\nextern \"C\" {\n\n void * xxmalloc (size_t);\n void xxfree (void *);\n\n \/\/ Takes a pointer and returns how much space it holds.\n size_t xxmalloc_usable_size (void *);\n\n\n static void my_init_hook (void);\n\n \/\/ New hooks for allocation functions.\n static void * my_malloc_hook (size_t, const void *);\n static void my_free_hook (void *, const void *);\n static void * my_realloc_hook (void *, size_t, const void *);\n static void * my_memalign_hook (size_t, size_t, const void *);\n\n \/\/ Store the old hooks just in case.\n static void * (*old_malloc_hook) (size_t, const void *);\n static void (*old_free_hook) (void *, const void *);\n static void * (*old_realloc_hook)(void *ptr, size_t size, const void *caller);\n static void * (*old_memalign_hook)(size_t alignment, size_t size, const void *caller);\n\n\/\/ From GNU libc 2.14 this macro is defined, to declare\n\/\/ hook variables as volatile. Define it as empty for\n\/\/ older glibc versions\n#ifndef __MALLOC_HOOK_VOLATILE\n #define __MALLOC_HOOK_VOLATILE\n#endif\n\n void (*__MALLOC_HOOK_VOLATILE __malloc_initialize_hook) (void) = my_init_hook;\n\n static void my_init_hook (void) {\n \/\/ Store the old hooks.\n old_malloc_hook = __malloc_hook;\n old_free_hook = __free_hook;\n old_realloc_hook = __realloc_hook;\n old_memalign_hook = __memalign_hook;\n\n \/\/ Point the hooks to the replacement functions.\n __malloc_hook = my_malloc_hook;\n __free_hook = my_free_hook;\n __realloc_hook = my_realloc_hook;\n __memalign_hook = my_memalign_hook;\n\n initialized = true;\n }\n\n static void * my_malloc_hook (size_t size, const void *) {\n if (!initialized) {\n my_init_hook();\n }\n return xxmalloc(size);\n }\n\n static void my_free_hook (void * ptr, const void *) {\n if (!initialized) {\n my_init_hook();\n }\n xxfree(ptr);\n }\n\n static void * my_realloc_hook (void * ptr, size_t sz, const void *) {\n if (!initialized) {\n my_init_hook();\n }\n \/\/ NULL ptr = malloc.\n if (ptr == NULL) {\n return xxmalloc(sz);\n }\n\n if (sz == 0) {\n xxfree (ptr);\n#if defined(__APPLE__)\n \/\/ 0 size = free. We return a small object. This behavior is\n \/\/ apparently required under Mac OS X and optional under POSIX.\n return xxmalloc(1);\n#else\n \/\/ For POSIX, don't return anything.\n return NULL;\n#endif\n }\n\n size_t objSize = xxmalloc_usable_size(ptr);\n\n#if 0\n \/\/ Custom logic here to ensure we only do a logarithmic number of\n \/\/ reallocations (with a constant space overhead).\n\n \/\/ Don't change size if the object is shrinking by less than half.\n if ((objSize \/ 2 < sz) && (sz <= objSize)) {\n \/\/ Do nothing.\n return ptr;\n }\n \/\/ If the object is growing by less than 2X, double it.\n if ((objSize < sz) && (sz < objSize * 2)) {\n sz = objSize * 2;\n }\n#endif\n\n void * buf = xxmalloc(sz);\n\n if (buf != NULL) {\n \/\/ Successful malloc.\n \/\/ Copy the contents of the original object\n \/\/ up to the size of the new block.\n size_t minSize = (objSize < sz) ? objSize : sz;\n memcpy (buf, ptr, minSize);\n xxfree (ptr);\n }\n\n \/\/ Return a pointer to the new one.\n return buf;\n }\n\n static void * my_memalign_hook (size_t size, size_t alignment, const void *) {\n if (!initialized) {\n my_init_hook();\n }\n \/\/ Check for non power-of-two alignment, or mistake in size.\n if ((alignment == 0) ||\n\t(alignment & (alignment - 1)))\n {\n\treturn NULL;\n }\n\n \/\/ Try to just allocate an object of the requested size.\n \/\/ If it happens to be aligned properly, just return it.\n void * ptr = xxmalloc (size);\n if (((size_t) ptr & (alignment - 1)) == (size_t) ptr) {\n \/\/ It is already aligned just fine; return it.\n return ptr;\n }\n\n \/\/ It was not aligned as requested: free the object.\n xxfree (ptr);\n\n \/\/ Now get a big chunk of memory and align the object within it.\n \/\/ NOTE: this REQUIRES that the underlying allocator be able\n \/\/ to free the aligned object, or ignore the free request.\n void * buf = xxmalloc (2 * alignment + size);\n void * alignedPtr = (void *) (((size_t) buf + alignment - 1) & ~(alignment - 1));\n\n return alignedPtr;\n }\n\n\n \/\/ This is here because, for some reason, the GNU hooks don't\n \/\/ necessarily replace all memory operations as they should.\n\n int posix_memalign (void **memptr, size_t alignment, size_t size) throw()\n {\n if (!initialized) {\n my_init_hook();\n }\n \/\/ Check for non power-of-two alignment.\n if ((alignment == 0) ||\n\t(alignment & (alignment - 1)))\n {\n\treturn EINVAL;\n }\n void * ptr = my_memalign_hook (size, alignment, NULL);\n if (!ptr) {\n return ENOMEM;\n } else {\n *memptr = ptr;\n return 0;\n }\n }\n\n size_t malloc_usable_size (void * ptr) throw() {\n if (!initialized) {\n my_init_hook();\n }\n return xxmalloc_usable_size (ptr);\n }\n\n int mallopt (int param, int value) throw() {\n \/\/ NOP.\n return 1; \/\/ success.\n }\n\n int malloc_trim (size_t pad) throw() {\n \/\/ NOP.\n return 0; \/\/ no memory returned to OS.\n }\n\n void malloc_stats (void) throw() {\n \/\/ NOP.\n }\n\n void * malloc_get_state (void) throw() {\n return NULL; \/\/ always returns \"error\".\n }\n\n int malloc_set_state (void * ptr) throw() {\n return 0; \/\/ success.\n }\n\n struct mallinfo mallinfo(void) throw() {\n \/\/ For now, we return useless stats.\n struct mallinfo m;\n m.arena = 0;\n m.ordblks = 0;\n m.smblks = 0;\n m.hblks = 0;\n m.hblkhd = 0;\n m.usmblks = 0;\n m.fsmblks = 0;\n m.uordblks = 0;\n m.fordblks = 0;\n m.keepcost = 0;\n return m;\n }\n\n}\n\n\nvoid * operator new (size_t sz) throw (std::bad_alloc)\n{\n void * ptr = xxmalloc (sz);\n if (ptr == NULL) {\n throw std::bad_alloc();\n } else {\n return ptr;\n }\n}\n\nvoid operator delete (void * ptr)\n throw ()\n{\n xxfree (ptr);\n}\n\nvoid * operator new (size_t sz, const std::nothrow_t&) throw() {\n return xxmalloc(sz);\n} \n\nvoid * operator new[] (size_t size) \n throw (std::bad_alloc)\n{\n void * ptr = xxmalloc(size);\n if (ptr == NULL) {\n throw std::bad_alloc();\n } else {\n return ptr;\n }\n}\n\nvoid * operator new[] (size_t sz, const std::nothrow_t&)\n throw()\n {\n return xxmalloc(sz);\n} \n\nvoid operator delete[] (void * ptr)\n throw ()\n{\n xxfree (ptr);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ exploitability_win.cc: Windows specific exploitability engine.\n\/\/\n\/\/ Provides a guess at the exploitability of the crash for the Windows\n\/\/ platform given a minidump and process_state.\n\/\/\n\/\/ Author: Cris Neckar\n\n#include \n\n#include \"processor\/exploitability_win.h\"\n\n#include \"common\/scoped_ptr.h\"\n#include \"google_breakpad\/common\/minidump_exception_win32.h\"\n#include \"google_breakpad\/processor\/minidump.h\"\n#include \"processor\/disassembler_x86.h\"\n#include \"processor\/logging.h\"\n\n#include \"third_party\/libdisasm\/libdis.h\"\n\nnamespace google_breakpad {\n\n\/\/ The cutoff that we use to judge if and address is likely an offset\n\/\/ from various interesting addresses.\nstatic const uint64_t kProbableNullOffset = 4096;\nstatic const uint64_t kProbableStackOffset = 8192;\n\n\/\/ The various cutoffs for the different ratings.\nstatic const size_t kHighCutoff = 100;\nstatic const size_t kMediumCutoff = 80;\nstatic const size_t kLowCutoff = 50;\nstatic const size_t kInterestingCutoff = 25;\n\n\/\/ Predefined incremental values for conditional weighting.\nstatic const size_t kTinyBump = 5;\nstatic const size_t kSmallBump = 20;\nstatic const size_t kMediumBump = 50;\nstatic const size_t kLargeBump = 70;\nstatic const size_t kHugeBump = 90;\n\n\/\/ The maximum number of bytes to disassemble past the program counter.\nstatic const size_t kDisassembleBytesBeyondPC = 2048;\n\nExploitabilityWin::ExploitabilityWin(Minidump *dump,\n ProcessState *process_state)\n : Exploitability(dump, process_state) { }\n\nExploitabilityRating ExploitabilityWin::CheckPlatformExploitability() {\n MinidumpException *exception = dump_->GetException();\n if (!exception) {\n BPLOG(INFO) << \"Minidump does not have exception record.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n const MDRawExceptionStream *raw_exception = exception->exception();\n if (!raw_exception) {\n BPLOG(INFO) << \"Could not obtain raw exception info.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n const MinidumpContext *context = exception->GetContext();\n if (!context) {\n BPLOG(INFO) << \"Could not obtain exception context.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n MinidumpMemoryList *memory_list = dump_->GetMemoryList();\n bool memory_available = true;\n if (!memory_list) {\n BPLOG(INFO) << \"Minidump memory segments not available.\";\n memory_available = false;\n }\n uint64_t address = process_state_->crash_address();\n uint32_t exception_code = raw_exception->exception_record.exception_code;\n\n uint32_t exploitability_weight = 0;\n\n uint64_t stack_ptr = 0;\n uint64_t instruction_ptr = 0;\n uint64_t this_ptr = 0;\n\n switch (context->GetContextCPU()) {\n case MD_CONTEXT_X86:\n stack_ptr = context->GetContextX86()->esp;\n instruction_ptr = context->GetContextX86()->eip;\n this_ptr = context->GetContextX86()->ecx;\n break;\n case MD_CONTEXT_AMD64:\n stack_ptr = context->GetContextAMD64()->rsp;\n instruction_ptr = context->GetContextAMD64()->rip;\n this_ptr = context->GetContextAMD64()->rcx;\n break;\n default:\n BPLOG(INFO) << \"Unsupported architecture.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n \/\/ Check if we are executing on the stack.\n if (instruction_ptr <= (stack_ptr + kProbableStackOffset) &&\n instruction_ptr >= (stack_ptr - kProbableStackOffset))\n exploitability_weight += kHugeBump;\n\n switch (exception_code) {\n \/\/ This is almost certainly recursion.\n case MD_EXCEPTION_CODE_WIN_STACK_OVERFLOW:\n exploitability_weight += kTinyBump;\n break;\n\n \/\/ These exceptions tend to be benign and we can generally ignore them.\n case MD_EXCEPTION_CODE_WIN_INTEGER_DIVIDE_BY_ZERO:\n case MD_EXCEPTION_CODE_WIN_INTEGER_OVERFLOW:\n case MD_EXCEPTION_CODE_WIN_FLOAT_DIVIDE_BY_ZERO:\n case MD_EXCEPTION_CODE_WIN_FLOAT_INEXACT_RESULT:\n case MD_EXCEPTION_CODE_WIN_FLOAT_OVERFLOW:\n case MD_EXCEPTION_CODE_WIN_FLOAT_UNDERFLOW:\n case MD_EXCEPTION_CODE_WIN_IN_PAGE_ERROR:\n exploitability_weight += kTinyBump;\n break;\n\n \/\/ These exceptions will typically mean that we have jumped where we\n \/\/ shouldn't.\n case MD_EXCEPTION_CODE_WIN_ILLEGAL_INSTRUCTION:\n case MD_EXCEPTION_CODE_WIN_FLOAT_INVALID_OPERATION:\n case MD_EXCEPTION_CODE_WIN_PRIVILEGED_INSTRUCTION:\n exploitability_weight += kLargeBump;\n break;\n\n \/\/ These represent bugs in exception handlers.\n case MD_EXCEPTION_CODE_WIN_INVALID_DISPOSITION:\n case MD_EXCEPTION_CODE_WIN_NONCONTINUABLE_EXCEPTION:\n exploitability_weight += kSmallBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_HEAP_CORRUPTION:\n case MD_EXCEPTION_CODE_WIN_STACK_BUFFER_OVERRUN:\n exploitability_weight += kHugeBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_GUARD_PAGE_VIOLATION:\n exploitability_weight += kLargeBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_ACCESS_VIOLATION:\n bool near_null = (address <= kProbableNullOffset);\n bool bad_read = false;\n bool bad_write = false;\n if (raw_exception->exception_record.number_parameters >= 1) {\n MDAccessViolationTypeWin av_type =\n static_cast\n (raw_exception->exception_record.exception_information[0]);\n switch (av_type) {\n case MD_ACCESS_VIOLATION_WIN_READ:\n bad_read = true;\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kMediumBump;\n break;\n case MD_ACCESS_VIOLATION_WIN_WRITE:\n bad_write = true;\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kHugeBump;\n break;\n case MD_ACCESS_VIOLATION_WIN_EXEC:\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kHugeBump;\n break;\n default:\n BPLOG(INFO) << \"Unrecognized access violation type.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n break;\n }\n MinidumpMemoryRegion *instruction_region = 0;\n if (memory_available) {\n instruction_region =\n memory_list->GetMemoryRegionForAddress(instruction_ptr);\n }\n if (!near_null && instruction_region &&\n context->GetContextCPU() == MD_CONTEXT_X86 &&\n (bad_read || bad_write)) {\n \/\/ Perform checks related to memory around instruction pointer.\n uint32_t memory_offset =\n instruction_ptr - instruction_region->GetBase();\n uint32_t available_memory =\n instruction_region->GetSize() - memory_offset;\n available_memory = available_memory > kDisassembleBytesBeyondPC ?\n kDisassembleBytesBeyondPC : available_memory;\n if (available_memory) {\n const uint8_t *raw_memory =\n instruction_region->GetMemory() + memory_offset;\n DisassemblerX86 disassembler(raw_memory,\n available_memory,\n instruction_ptr);\n disassembler.NextInstruction();\n if (bad_read)\n disassembler.setBadRead();\n else\n disassembler.setBadWrite();\n if (disassembler.currentInstructionValid()) {\n \/\/ Check if the faulting instruction falls into one of\n \/\/ several interesting groups.\n switch (disassembler.currentInstructionGroup()) {\n case libdis::insn_controlflow:\n exploitability_weight += kLargeBump;\n break;\n case libdis::insn_string:\n exploitability_weight += kHugeBump;\n break;\n default:\n break;\n }\n \/\/ Loop the disassembler through the code and check if it\n \/\/ IDed any interesting conditions in the near future.\n \/\/ Multiple flags may be set so treat each equally.\n while (disassembler.NextInstruction() &&\n disassembler.currentInstructionValid() &&\n !disassembler.endOfBlock())\n continue;\n if (disassembler.flags() & DISX86_BAD_BRANCH_TARGET)\n exploitability_weight += kLargeBump;\n if (disassembler.flags() & DISX86_BAD_ARGUMENT_PASSED)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_WRITE)\n exploitability_weight += kMediumBump;\n if (disassembler.flags() & DISX86_BAD_BLOCK_WRITE)\n exploitability_weight += kMediumBump;\n if (disassembler.flags() & DISX86_BAD_READ)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_BLOCK_READ)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_COMPARISON)\n exploitability_weight += kTinyBump;\n }\n }\n }\n if (!near_null && AddressIsAscii(address))\n exploitability_weight += kMediumBump;\n } else {\n BPLOG(INFO) << \"Access violation type parameter missing.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n }\n\n \/\/ Based on the calculated weight we return a simplified classification.\n BPLOG(INFO) << \"Calculated exploitability weight: \" << exploitability_weight;\n if (exploitability_weight >= kHighCutoff)\n return EXPLOITABILITY_HIGH;\n if (exploitability_weight >= kMediumCutoff)\n return EXPLOITABLITY_MEDIUM;\n if (exploitability_weight >= kLowCutoff)\n return EXPLOITABILITY_LOW;\n if (exploitability_weight >= kInterestingCutoff)\n return EXPLOITABILITY_INTERESTING;\n\n return EXPLOITABILITY_NONE;\n}\n\n} \/\/ namespace google_breakpad\nFix an \"unused variable\" compiler warning in exploitability_win.cc\/\/ Copyright (c) 2010 Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ exploitability_win.cc: Windows specific exploitability engine.\n\/\/\n\/\/ Provides a guess at the exploitability of the crash for the Windows\n\/\/ platform given a minidump and process_state.\n\/\/\n\/\/ Author: Cris Neckar\n\n#include \n\n#include \"processor\/exploitability_win.h\"\n\n#include \"common\/scoped_ptr.h\"\n#include \"google_breakpad\/common\/minidump_exception_win32.h\"\n#include \"google_breakpad\/processor\/minidump.h\"\n#include \"processor\/disassembler_x86.h\"\n#include \"processor\/logging.h\"\n\n#include \"third_party\/libdisasm\/libdis.h\"\n\nnamespace google_breakpad {\n\n\/\/ The cutoff that we use to judge if and address is likely an offset\n\/\/ from various interesting addresses.\nstatic const uint64_t kProbableNullOffset = 4096;\nstatic const uint64_t kProbableStackOffset = 8192;\n\n\/\/ The various cutoffs for the different ratings.\nstatic const size_t kHighCutoff = 100;\nstatic const size_t kMediumCutoff = 80;\nstatic const size_t kLowCutoff = 50;\nstatic const size_t kInterestingCutoff = 25;\n\n\/\/ Predefined incremental values for conditional weighting.\nstatic const size_t kTinyBump = 5;\nstatic const size_t kSmallBump = 20;\nstatic const size_t kMediumBump = 50;\nstatic const size_t kLargeBump = 70;\nstatic const size_t kHugeBump = 90;\n\n\/\/ The maximum number of bytes to disassemble past the program counter.\nstatic const size_t kDisassembleBytesBeyondPC = 2048;\n\nExploitabilityWin::ExploitabilityWin(Minidump *dump,\n ProcessState *process_state)\n : Exploitability(dump, process_state) { }\n\nExploitabilityRating ExploitabilityWin::CheckPlatformExploitability() {\n MinidumpException *exception = dump_->GetException();\n if (!exception) {\n BPLOG(INFO) << \"Minidump does not have exception record.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n const MDRawExceptionStream *raw_exception = exception->exception();\n if (!raw_exception) {\n BPLOG(INFO) << \"Could not obtain raw exception info.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n const MinidumpContext *context = exception->GetContext();\n if (!context) {\n BPLOG(INFO) << \"Could not obtain exception context.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n MinidumpMemoryList *memory_list = dump_->GetMemoryList();\n bool memory_available = true;\n if (!memory_list) {\n BPLOG(INFO) << \"Minidump memory segments not available.\";\n memory_available = false;\n }\n uint64_t address = process_state_->crash_address();\n uint32_t exception_code = raw_exception->exception_record.exception_code;\n\n uint32_t exploitability_weight = 0;\n\n uint64_t stack_ptr = 0;\n uint64_t instruction_ptr = 0;\n\n switch (context->GetContextCPU()) {\n case MD_CONTEXT_X86:\n stack_ptr = context->GetContextX86()->esp;\n instruction_ptr = context->GetContextX86()->eip;\n break;\n case MD_CONTEXT_AMD64:\n stack_ptr = context->GetContextAMD64()->rsp;\n instruction_ptr = context->GetContextAMD64()->rip;\n break;\n default:\n BPLOG(INFO) << \"Unsupported architecture.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n\n \/\/ Check if we are executing on the stack.\n if (instruction_ptr <= (stack_ptr + kProbableStackOffset) &&\n instruction_ptr >= (stack_ptr - kProbableStackOffset))\n exploitability_weight += kHugeBump;\n\n switch (exception_code) {\n \/\/ This is almost certainly recursion.\n case MD_EXCEPTION_CODE_WIN_STACK_OVERFLOW:\n exploitability_weight += kTinyBump;\n break;\n\n \/\/ These exceptions tend to be benign and we can generally ignore them.\n case MD_EXCEPTION_CODE_WIN_INTEGER_DIVIDE_BY_ZERO:\n case MD_EXCEPTION_CODE_WIN_INTEGER_OVERFLOW:\n case MD_EXCEPTION_CODE_WIN_FLOAT_DIVIDE_BY_ZERO:\n case MD_EXCEPTION_CODE_WIN_FLOAT_INEXACT_RESULT:\n case MD_EXCEPTION_CODE_WIN_FLOAT_OVERFLOW:\n case MD_EXCEPTION_CODE_WIN_FLOAT_UNDERFLOW:\n case MD_EXCEPTION_CODE_WIN_IN_PAGE_ERROR:\n exploitability_weight += kTinyBump;\n break;\n\n \/\/ These exceptions will typically mean that we have jumped where we\n \/\/ shouldn't.\n case MD_EXCEPTION_CODE_WIN_ILLEGAL_INSTRUCTION:\n case MD_EXCEPTION_CODE_WIN_FLOAT_INVALID_OPERATION:\n case MD_EXCEPTION_CODE_WIN_PRIVILEGED_INSTRUCTION:\n exploitability_weight += kLargeBump;\n break;\n\n \/\/ These represent bugs in exception handlers.\n case MD_EXCEPTION_CODE_WIN_INVALID_DISPOSITION:\n case MD_EXCEPTION_CODE_WIN_NONCONTINUABLE_EXCEPTION:\n exploitability_weight += kSmallBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_HEAP_CORRUPTION:\n case MD_EXCEPTION_CODE_WIN_STACK_BUFFER_OVERRUN:\n exploitability_weight += kHugeBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_GUARD_PAGE_VIOLATION:\n exploitability_weight += kLargeBump;\n break;\n\n case MD_EXCEPTION_CODE_WIN_ACCESS_VIOLATION:\n bool near_null = (address <= kProbableNullOffset);\n bool bad_read = false;\n bool bad_write = false;\n if (raw_exception->exception_record.number_parameters >= 1) {\n MDAccessViolationTypeWin av_type =\n static_cast\n (raw_exception->exception_record.exception_information[0]);\n switch (av_type) {\n case MD_ACCESS_VIOLATION_WIN_READ:\n bad_read = true;\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kMediumBump;\n break;\n case MD_ACCESS_VIOLATION_WIN_WRITE:\n bad_write = true;\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kHugeBump;\n break;\n case MD_ACCESS_VIOLATION_WIN_EXEC:\n if (near_null)\n exploitability_weight += kSmallBump;\n else\n exploitability_weight += kHugeBump;\n break;\n default:\n BPLOG(INFO) << \"Unrecognized access violation type.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n break;\n }\n MinidumpMemoryRegion *instruction_region = 0;\n if (memory_available) {\n instruction_region =\n memory_list->GetMemoryRegionForAddress(instruction_ptr);\n }\n if (!near_null && instruction_region &&\n context->GetContextCPU() == MD_CONTEXT_X86 &&\n (bad_read || bad_write)) {\n \/\/ Perform checks related to memory around instruction pointer.\n uint32_t memory_offset =\n instruction_ptr - instruction_region->GetBase();\n uint32_t available_memory =\n instruction_region->GetSize() - memory_offset;\n available_memory = available_memory > kDisassembleBytesBeyondPC ?\n kDisassembleBytesBeyondPC : available_memory;\n if (available_memory) {\n const uint8_t *raw_memory =\n instruction_region->GetMemory() + memory_offset;\n DisassemblerX86 disassembler(raw_memory,\n available_memory,\n instruction_ptr);\n disassembler.NextInstruction();\n if (bad_read)\n disassembler.setBadRead();\n else\n disassembler.setBadWrite();\n if (disassembler.currentInstructionValid()) {\n \/\/ Check if the faulting instruction falls into one of\n \/\/ several interesting groups.\n switch (disassembler.currentInstructionGroup()) {\n case libdis::insn_controlflow:\n exploitability_weight += kLargeBump;\n break;\n case libdis::insn_string:\n exploitability_weight += kHugeBump;\n break;\n default:\n break;\n }\n \/\/ Loop the disassembler through the code and check if it\n \/\/ IDed any interesting conditions in the near future.\n \/\/ Multiple flags may be set so treat each equally.\n while (disassembler.NextInstruction() &&\n disassembler.currentInstructionValid() &&\n !disassembler.endOfBlock())\n continue;\n if (disassembler.flags() & DISX86_BAD_BRANCH_TARGET)\n exploitability_weight += kLargeBump;\n if (disassembler.flags() & DISX86_BAD_ARGUMENT_PASSED)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_WRITE)\n exploitability_weight += kMediumBump;\n if (disassembler.flags() & DISX86_BAD_BLOCK_WRITE)\n exploitability_weight += kMediumBump;\n if (disassembler.flags() & DISX86_BAD_READ)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_BLOCK_READ)\n exploitability_weight += kTinyBump;\n if (disassembler.flags() & DISX86_BAD_COMPARISON)\n exploitability_weight += kTinyBump;\n }\n }\n }\n if (!near_null && AddressIsAscii(address))\n exploitability_weight += kMediumBump;\n } else {\n BPLOG(INFO) << \"Access violation type parameter missing.\";\n return EXPLOITABILITY_ERR_PROCESSING;\n }\n }\n\n \/\/ Based on the calculated weight we return a simplified classification.\n BPLOG(INFO) << \"Calculated exploitability weight: \" << exploitability_weight;\n if (exploitability_weight >= kHighCutoff)\n return EXPLOITABILITY_HIGH;\n if (exploitability_weight >= kMediumCutoff)\n return EXPLOITABLITY_MEDIUM;\n if (exploitability_weight >= kLowCutoff)\n return EXPLOITABILITY_LOW;\n if (exploitability_weight >= kInterestingCutoff)\n return EXPLOITABILITY_INTERESTING;\n\n return EXPLOITABILITY_NONE;\n}\n\n} \/\/ namespace google_breakpad\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nusing namespace boost::interprocess;\n\n\/\/Typedefs of allocators and containers\ntypedef managed_shared_memory::segment_manager segment_manager_t;\ntypedef allocator void_allocator;\ntypedef allocator int_allocator;\ntypedef vector int_vector;\ntypedef allocator char_allocator;\ntypedef basic_string, char_allocator> char_string;\n\nclass complex_data {\npublic:\n int id_;\n char_string char_string_;\n int_vector int_vector_;\n\n \/\/Since void_allocator is convertible to any other allocator, we can simplify\n \/\/the initialization taking just one allocator for all inner containers.\n complex_data ( const void_allocator &void_alloc )\n : id_ ( -1 ), char_string_ ( void_alloc ), int_vector_ ( void_alloc )\n {}\n \/\/ copy constructor\n complex_data ( const complex_data &o )\n : id_ ( o.id_ ), char_string_ ( o.char_string_, o.char_string_.get_allocator() ), int_vector_ ( o.int_vector_, o.int_vector_.get_allocator() )\n {}\n \/\/ copy assignment operator\n complex_data& operator= ( const complex_data& o ) {\n id_ = o.id_;\n char_string_ = o.char_string_;\n int_vector_ = o.int_vector_;\n return *this;\n }\n friend std::ostream &operator << ( std::ostream &os, const complex_data &o ) {\n os << \"[\" << o.id_ << \", \" << o.char_string_ << \", \";\n for ( size_t i = 0; i < o.int_vector_.size(); i++ ) {\n os << ( i==0?\"[ \": \", \" ) << o.int_vector_[i] << ( i==o.int_vector_.size()-1?\"]\":\"\" );\n }\n return os;\n };\n};\n\n\ntypedef allocator complex_data_allocator;\ntypedef vector complex_data_vector;\n\ntemplate\nForwardIt next(ForwardIt it, typename std::iterator_traits::difference_type n = 1)\n{\n std::advance(it, n);\n return it;\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize, Element const& element ) {\n if ( vect.size() < newsize ) {\n vect.insert (\n vect.end(),\n newsize - vect.size(),\n element\n );\n } else {\n vect.erase (\n next ( vect.begin(), newsize ),\n vect.end()\n );\n }\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize, typename V::allocator_type const& alloc_inst ) {\n resize ( vect, newsize, typename V::value_type ( alloc_inst ) );\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize ) {\n resize ( vect, newsize, typename V::value_type ( vect.get_allocator() ) );\n}\n\nint main () {\n \/\/Remove shared memory on construction and destruction\n\n struct shm_remove {\n shm_remove() {\n shared_memory_object::remove ( \"MySharedMemory\" );\n }\n ~shm_remove() {\n shared_memory_object::remove ( \"MySharedMemory\" );\n }\n } remover;\n\n \/\/Create shared memory\n managed_shared_memory segment;\n \/\/A managed shared memory where we can construct objects\n \/\/associated with a c-string\n try {\n segment = managed_shared_memory ( create_only, \"MySharedMemory\", 65536 );\n } catch ( ... ) {\n segment = managed_shared_memory ( open_only, \"MySharedMemory\" );\n }\n\n \/\/An allocator convertible to any allocator type\n void_allocator alloc_inst ( segment.get_segment_manager() );\n\n \/\/Construct the shared memory map and fill it\n complex_data *complex_data0_ = segment.find_or_construct ( \"MyCompexData\" ) ( alloc_inst );\n\n complex_data0_->char_string_ = \"Hello World\";\n complex_data0_->int_vector_.push_back ( 3 );\n\n complex_data *complex_data1_ = segment.find_or_construct ( \"MyCompexData\" ) ( alloc_inst );\n complex_data1_->int_vector_.push_back ( 6 );\n\n std::cout << *complex_data1_ << std::endl;\n\n\n complex_data_vector *complex_data_vector0 = segment.find_or_construct ( \"MyCompexDataVector\" ) ( alloc_inst );\n complex_data_vector *complex_data_vector1 = segment.find_or_construct ( \"MyCompexDataVector\" ) ( alloc_inst );\n\n \/**\n * Problem\n * How to I resize or add new elements?\n **\/\n \/\/complex_data_vector0->resize(3); \/\/ --> still not working\n complex_data_vector0->clear();\n complex_data_vector0->insert ( complex_data_vector0->end(), 3, complex_data ( alloc_inst ) );\n complex_data_vector0->at ( 0 ) = *complex_data0_;\n for ( size_t i = 0; i < complex_data_vector0->size(); i++ ) {\n std::cout << complex_data_vector0->at ( i ) << std::endl;\n }\n std::cout << \"--------------\" << std::endl;\n resize(*complex_data_vector1, 5, complex_data(alloc_inst));\n complex_data_vector0->at ( 4 ).id_ = 4;\n for ( size_t i = 0; i < complex_data_vector1->size(); i++ ) {\n std::cout << complex_data_vector1->at ( i ) << std::endl;\n }\n return 0;\n}\n\niostream include added\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nusing namespace boost::interprocess;\n\n\/\/Typedefs of allocators and containers\ntypedef managed_shared_memory::segment_manager segment_manager_t;\ntypedef allocator void_allocator;\ntypedef allocator int_allocator;\ntypedef vector int_vector;\ntypedef allocator char_allocator;\ntypedef basic_string, char_allocator> char_string;\n\nclass complex_data {\npublic:\n int id_;\n char_string char_string_;\n int_vector int_vector_;\n\n \/\/Since void_allocator is convertible to any other allocator, we can simplify\n \/\/the initialization taking just one allocator for all inner containers.\n complex_data ( const void_allocator &void_alloc )\n : id_ ( -1 ), char_string_ ( void_alloc ), int_vector_ ( void_alloc )\n {}\n \/\/ copy constructor\n complex_data ( const complex_data &o )\n : id_ ( o.id_ ), char_string_ ( o.char_string_, o.char_string_.get_allocator() ), int_vector_ ( o.int_vector_, o.int_vector_.get_allocator() )\n {}\n \/\/ copy assignment operator\n complex_data& operator= ( const complex_data& o ) {\n id_ = o.id_;\n char_string_ = o.char_string_;\n int_vector_ = o.int_vector_;\n return *this;\n }\n friend std::ostream &operator << ( std::ostream &os, const complex_data &o ) {\n os << \"[\" << o.id_ << \", \" << o.char_string_ << \", \";\n for ( size_t i = 0; i < o.int_vector_.size(); i++ ) {\n os << ( i==0?\"[ \": \", \" ) << o.int_vector_[i] << ( i==o.int_vector_.size()-1?\"]\":\"\" );\n }\n return os;\n };\n};\n\n\ntypedef allocator complex_data_allocator;\ntypedef vector complex_data_vector;\n\ntemplate\nForwardIt next(ForwardIt it, typename std::iterator_traits::difference_type n = 1)\n{\n std::advance(it, n);\n return it;\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize, Element const& element ) {\n if ( vect.size() < newsize ) {\n vect.insert (\n vect.end(),\n newsize - vect.size(),\n element\n );\n } else {\n vect.erase (\n next ( vect.begin(), newsize ),\n vect.end()\n );\n }\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize, typename V::allocator_type const& alloc_inst ) {\n resize ( vect, newsize, typename V::value_type ( alloc_inst ) );\n}\n\ntemplate \nstatic inline void resize ( V& vect, size_t newsize ) {\n resize ( vect, newsize, typename V::value_type ( vect.get_allocator() ) );\n}\n\nint main () {\n \/\/Remove shared memory on construction and destruction\n\n struct shm_remove {\n shm_remove() {\n shared_memory_object::remove ( \"MySharedMemory\" );\n }\n ~shm_remove() {\n shared_memory_object::remove ( \"MySharedMemory\" );\n }\n } remover;\n\n \/\/Create shared memory\n managed_shared_memory segment;\n \/\/A managed shared memory where we can construct objects\n \/\/associated with a c-string\n try {\n segment = managed_shared_memory ( create_only, \"MySharedMemory\", 65536 );\n } catch ( ... ) {\n segment = managed_shared_memory ( open_only, \"MySharedMemory\" );\n }\n\n \/\/An allocator convertible to any allocator type\n void_allocator alloc_inst ( segment.get_segment_manager() );\n\n \/\/Construct the shared memory map and fill it\n complex_data *complex_data0_ = segment.find_or_construct ( \"MyCompexData\" ) ( alloc_inst );\n\n complex_data0_->char_string_ = \"Hello World\";\n complex_data0_->int_vector_.push_back ( 3 );\n\n complex_data *complex_data1_ = segment.find_or_construct ( \"MyCompexData\" ) ( alloc_inst );\n complex_data1_->int_vector_.push_back ( 6 );\n\n std::cout << *complex_data1_ << std::endl;\n\n\n complex_data_vector *complex_data_vector0 = segment.find_or_construct ( \"MyCompexDataVector\" ) ( alloc_inst );\n complex_data_vector *complex_data_vector1 = segment.find_or_construct ( \"MyCompexDataVector\" ) ( alloc_inst );\n\n \/**\n * Problem\n * How to I resize or add new elements?\n **\/\n \/\/complex_data_vector0->resize(3); \/\/ --> still not working\n complex_data_vector0->clear();\n complex_data_vector0->insert ( complex_data_vector0->end(), 3, complex_data ( alloc_inst ) );\n complex_data_vector0->at ( 0 ) = *complex_data0_;\n for ( size_t i = 0; i < complex_data_vector0->size(); i++ ) {\n std::cout << complex_data_vector0->at ( i ) << std::endl;\n }\n std::cout << \"--------------\" << std::endl;\n resize(*complex_data_vector1, 5, complex_data(alloc_inst));\n complex_data_vector0->at ( 4 ).id_ = 4;\n for ( size_t i = 0; i < complex_data_vector1->size(); i++ ) {\n std::cout << complex_data_vector1->at ( i ) << std::endl;\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"Related fdo#60338: do not call umask(3) in a MT program<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: npshell.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: mba $ $Date: 2004-09-02 14:01:05 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define PLUGIN_NAME \"StarOffice Plugin\"\n#define PLUGIN_DESCRIPTION \"The StarOffice plugin handles all staroffice documents\"\n\n#ifdef UNIX\n\n#define MOZ_X11\n\n#include \n#include \n\ntypedef struct _PluginInstance\n{\n uint16 mode;\n#ifdef MOZ_X11\n Window window;\n Display *display;\n#endif\n uint32 x, y;\n uint32 width, height;\n NPMIMEType type;\n char *message;\n\n NPP instance;\n char *pluginsPageUrl;\n char *pluginsFileUrl;\n NPBool pluginsHidden;\n#ifdef MOZ_X11\n Visual* visual;\n Colormap colormap;\n#endif\n unsigned int depth;\n GtkWidget* dialogBox;\n\n NPBool exists; \/* Does the widget already exist? *\/\n int action; \/* What action should we take? (GET or REFRESH) *\/\n\n} PluginInstance;\n\ntypedef struct _MimeTypeElement\n{\n PluginInstance *pinst;\n struct _MimeTypeElement *next;\n} MimeTypeElement;\n\n#endif \/\/end of UNIX\n\n\n#ifdef WNT\n\n#include \n\ntypedef struct _PluginInstance\n{\n NPWindow* fWindow;\n uint16 fMode;\n\n HWND fhWnd;\n WNDPROC fDefaultWindowProc;\n} PluginInstance;\n\n#endif \/\/end of WNT\n\n\n\/* Extern functions *\/\nextern \"C\" NPMIMEType dupMimeType(NPMIMEType type);\nINTEGRATION: CWS nsplugin3 (1.3.24); FILE MERGED 2004\/10\/12 03:10:22 jmeng 1.3.24.1: add dynamic OpenOffice.org \/ StarOffice support\/*************************************************************************\n *\n * $RCSfile: npshell.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2004-11-26 16:00:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef UNIX\n\n#define MOZ_X11\n\n#include \n#include \n\ntypedef struct _PluginInstance\n{\n uint16 mode;\n#ifdef MOZ_X11\n Window window;\n Display *display;\n#endif\n uint32 x, y;\n uint32 width, height;\n NPMIMEType type;\n char *message;\n\n NPP instance;\n char *pluginsPageUrl;\n char *pluginsFileUrl;\n NPBool pluginsHidden;\n#ifdef MOZ_X11\n Visual* visual;\n Colormap colormap;\n#endif\n unsigned int depth;\n GtkWidget* dialogBox;\n\n NPBool exists; \/* Does the widget already exist? *\/\n int action; \/* What action should we take? (GET or REFRESH) *\/\n\n} PluginInstance;\n\ntypedef struct _MimeTypeElement\n{\n PluginInstance *pinst;\n struct _MimeTypeElement *next;\n} MimeTypeElement;\n\n#endif \/\/end of UNIX\n\n\n#ifdef WNT\n\n#include \n\ntypedef struct _PluginInstance\n{\n NPWindow* fWindow;\n uint16 fMode;\n\n HWND fhWnd;\n WNDPROC fDefaultWindowProc;\n} PluginInstance;\n\n#endif \/\/end of WNT\n\n\n\/* Extern functions *\/\nextern \"C\" NPMIMEType dupMimeType(NPMIMEType type);\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test suite for json.c\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2012 triagens GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"BasicsC\/json.h\"\n#include \"BasicsC\/string-buffer.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private macros\n\/\/ -----------------------------------------------------------------------------\n \n#define INIT_BUFFER TRI_string_buffer_t* sb = TRI_CreateStringBuffer(TRI_UNKNOWN_MEM_ZONE);\n#define FREE_BUFFER TRI_FreeStringBuffer(TRI_UNKNOWN_MEM_ZONE, sb);\n#define STRINGIFY TRI_StringifyJson(sb, json);\n#define STRING_VALUE sb->_buffer\n#define FREE_JSON TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- setup \/ tear-down\n\/\/ -----------------------------------------------------------------------------\n\nstruct CJsonSetup {\n CJsonSetup () {\n BOOST_TEST_MESSAGE(\"setup json\");\n }\n\n ~CJsonSetup () {\n BOOST_TEST_MESSAGE(\"tear-down json\");\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- test suite\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief setup\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_FIXTURE_TEST_SUITE(CJsonTest, CJsonSetup)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test null value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_null) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNullJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"null\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test true value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_true) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, true);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"true\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test false value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_false) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, false);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"false\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value 0\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number0) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 0.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"0\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (positive)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_positive1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 1.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"1\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (positive)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_positive2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 46281);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"46281\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (negative)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_negative1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, -1.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"-1\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (negative)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_negative2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, -2342);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"-2342\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (empty)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"the quick brown fox\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"the quick brown fox\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"The Quick Brown Fox\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"The Quick Brown Fox\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (escaped)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_escaped) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"\\\"the quick \\\"fox\\\" jumped over the \\\\brown\\\\ dog '\\n\\\\\\\" \\\\' \\\\\\\\ lazy\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\\\\\"the quick \\\\\\\"fox\\\\\\\" jumped over the \\\\\\\\brown\\\\\\\\ dog '\\\\n\\\\\\\\\\\\\\\" \\\\\\\\' \\\\\\\\\\\\\\\\ lazy\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test empty json list\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_list_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateListJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"[]\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test empty json array\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_array_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateArrayJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"{}\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generate tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_SUITE_END ()\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"^\\\\(\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\\\\)\"\n\/\/ End:\nsome more tests\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test suite for json.c\n\/\/\/\n\/\/\/ @file\n\/\/\/\n\/\/\/ DISCLAIMER\n\/\/\/\n\/\/\/ Copyright 2012 triagens GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/\/ you may not use this file except in compliance with the License.\n\/\/\/ You may obtain a copy of the License at\n\/\/\/\n\/\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\/\n\/\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/\/ See the License for the specific language governing permissions and\n\/\/\/ limitations under the License.\n\/\/\/\n\/\/\/ Copyright holder is triAGENS GmbH, Cologne, Germany\n\/\/\/\n\/\/\/ @author Jan Steemann\n\/\/\/ @author Copyright 2012, triAGENS GmbH, Cologne, Germany\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \n\n#include \"BasicsC\/json.h\"\n#include \"BasicsC\/string-buffer.h\"\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- private macros\n\/\/ -----------------------------------------------------------------------------\n \n#define INIT_BUFFER TRI_string_buffer_t* sb = TRI_CreateStringBuffer(TRI_UNKNOWN_MEM_ZONE);\n#define FREE_BUFFER TRI_FreeStringBuffer(TRI_UNKNOWN_MEM_ZONE, sb);\n#define STRINGIFY TRI_StringifyJson(sb, json);\n#define STRING_VALUE sb->_buffer\n#define FREE_JSON TRI_FreeJson(TRI_UNKNOWN_MEM_ZONE, json);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- setup \/ tear-down\n\/\/ -----------------------------------------------------------------------------\n\nstruct CJsonSetup {\n CJsonSetup () {\n BOOST_TEST_MESSAGE(\"setup json\");\n }\n\n ~CJsonSetup () {\n BOOST_TEST_MESSAGE(\"tear-down json\");\n }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ --SECTION-- test suite\n\/\/ -----------------------------------------------------------------------------\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief setup\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_FIXTURE_TEST_SUITE(CJsonTest, CJsonSetup)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test null value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_null) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNullJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"null\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test true value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_true) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, true);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"true\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test false value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_false) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, false);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"false\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value 0\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number0) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 0.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"0\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (positive)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_positive1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 1.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"1\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (positive)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_positive2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 46281);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"46281\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (negative)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_negative1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, -1.0);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"-1\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test number value (negative)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_number_negative2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, -2342);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"-2342\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (empty)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"the quick brown fox\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"the quick brown fox\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"The Quick Brown Fox\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"The Quick Brown Fox\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (escaped)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_escaped) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"\\\"the quick \\\"fox\\\" jumped over the \\\\brown\\\\ dog '\\n\\\\\\\" \\\\' \\\\\\\\ lazy\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\\\\\"the quick \\\\\\\"fox\\\\\\\" jumped over the \\\\\\\\brown\\\\\\\\ dog '\\\\n\\\\\\\\\\\\\\\" \\\\\\\\' \\\\\\\\\\\\\\\\ lazy\\\"\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (special chars)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_utf8_1) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"코리아닷컴 메일알리미 서비스 중단안내 [안내] 개인정보취급방침 변경 안내 회사소개 | 광고안내 | 제휴안내 | 개인정보취급방침 | 청소년보호정책 | 스팸방지정책 | 사이버고객센터 | 약관안내 | 이메일 무단수집거부 | 서비스 전체보기\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\\uCF54\\\\uB9AC\\\\uC544\\\\uB2F7\\\\uCEF4 \\\\uBA54\\\\uC77C\\\\uC54C\\\\uB9AC\\\\uBBF8 \\\\uC11C\\\\uBE44\\\\uC2A4 \\\\uC911\\\\uB2E8\\\\uC548\\\\uB0B4 [\\\\uC548\\\\uB0B4] \\\\uAC1C\\\\uC778\\\\uC815\\\\uBCF4\\\\uCDE8\\\\uAE09\\\\uBC29\\\\uCE68 \\\\uBCC0\\\\uACBD \\\\uC548\\\\uB0B4 \\\\uD68C\\\\uC0AC\\\\uC18C\\\\uAC1C | \\\\uAD11\\\\uACE0\\\\uC548\\\\uB0B4 | \\\\uC81C\\\\uD734\\\\uC548\\\\uB0B4 | \\\\uAC1C\\\\uC778\\\\uC815\\\\uBCF4\\\\uCDE8\\\\uAE09\\\\uBC29\\\\uCE68 | \\\\uCCAD\\\\uC18C\\\\uB144\\\\uBCF4\\\\uD638\\\\uC815\\\\uCC45 | \\\\uC2A4\\\\uD338\\\\uBC29\\\\uC9C0\\\\uC815\\\\uCC45 | \\\\uC0AC\\\\uC774\\\\uBC84\\\\uACE0\\\\uAC1D\\\\uC13C\\\\uD130 | \\\\uC57D\\\\uAD00\\\\uC548\\\\uB0B4 | \\\\uC774\\\\uBA54\\\\uC77C \\\\uBB34\\\\uB2E8\\\\uC218\\\\uC9D1\\\\uAC70\\\\uBD80 | \\\\uC11C\\\\uBE44\\\\uC2A4 \\\\uC804\\\\uCCB4\\\\uBCF4\\\\uAE30\\\"\", STRING_VALUE); \n \n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test string value (special chars)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_string_utf8_2) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"äöüßÄÖÜ€µ\");\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"\\\"\\\\u00E4\\\\u00F6\\\\u00FC\\\\u00DF\\\\u00C4\\\\u00D6\\\\u00DC\\\\u20AC\\\\u00B5\\\"\", STRING_VALUE);\n \n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test empty json list\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_list_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateListJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"[]\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test empty json list mixed\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_list_mixed) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateListJson(TRI_UNKNOWN_MEM_ZONE);\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateNullJson(TRI_UNKNOWN_MEM_ZONE));\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, true));\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateBooleanJson(TRI_UNKNOWN_MEM_ZONE, false));\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, -8093));\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateNumberJson(TRI_UNKNOWN_MEM_ZONE, 1.5));\n TRI_PushBack3ListJson(TRI_UNKNOWN_MEM_ZONE, json, TRI_CreateStringCopyJson(TRI_UNKNOWN_MEM_ZONE, (char*) \"the quick brown fox\"));\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"[null,true,false,-8093,1.5,\\\"the quick brown fox\\\"]\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief test empty json array\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_CASE (tst_json_array_empty) {\n INIT_BUFFER\n\n TRI_json_t* json = TRI_CreateArrayJson(TRI_UNKNOWN_MEM_ZONE);\n\n STRINGIFY\n BOOST_CHECK_EQUAL(\"{}\", STRING_VALUE);\n FREE_JSON\n FREE_BUFFER\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ @brief generate tests\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nBOOST_AUTO_TEST_SUITE_END ()\n\n\/\/ Local Variables:\n\/\/ mode: outline-minor\n\/\/ outline-regexp: \"^\\\\(\/\/\/ @brief\\\\|\/\/\/ {@inheritDoc}\\\\|\/\/\/ @addtogroup\\\\|\/\/ --SECTION--\\\\|\/\/\/ @\\\\}\\\\)\"\n\/\/ End:\n<|endoftext|>"} {"text":"#include \n#include \n#include \"OmahaHighHandEvaluator.h\"\n\nusing namespace pokerstove;\nusing namespace std;\n\nTEST(OmahaHighHandEvaluator, Construct) {\n OmahaHighHandEvaluator eval;\n EXPECT_EQ(true, eval.usesSuits());\n EXPECT_EQ(5, eval.boardSize());\n}\n\nTEST(OmahaHighHandEvaluator, RankEval) {\n OmahaHighHandEvaluator oeval;\n CardSet hand(\"2c3c\");\n CardSet board(\"2c3c4c\");\n PokerEvaluation eval = oeval.evaluateRanks(hand, board);\n EXPECT_EQ(TWO_PAIR, eval.type());\n EXPECT_EQ(Rank(\"3\"), eval.majorRank());\n EXPECT_EQ(Rank(\"2\"), eval.minorRank());\n}\nuse omaha hand for omaha test#include \n#include \n#include \"OmahaHighHandEvaluator.h\"\n\nusing namespace pokerstove;\nusing namespace std;\n\nTEST(OmahaHighHandEvaluator, Construct) {\n OmahaHighHandEvaluator eval;\n EXPECT_EQ(true, eval.usesSuits());\n EXPECT_EQ(5, eval.boardSize());\n}\n\nTEST(OmahaHighHandEvaluator, RankEval) {\n OmahaHighHandEvaluator oeval;\n CardSet hand(\"2c3cKhQd\");\n CardSet board(\"2c3c4c\");\n PokerEvaluation eval = oeval.evaluateRanks(hand, board);\n EXPECT_EQ(TWO_PAIR, eval.type());\n EXPECT_EQ(Rank(\"3\"), eval.majorRank());\n EXPECT_EQ(Rank(\"2\"), eval.minorRank());\n}\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Chiyuan Zhang\n * Copyright (C) 2012 Chiyuan Zhang\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nCShareBoost::CShareBoost()\n\t:CLinearMulticlassMachine(), m_nonzero_feas(0)\n{\n\tinit_sb_params();\n}\n\nCShareBoost::CShareBoost(CDenseFeatures *features, CMulticlassLabels *labs, int32_t num_nonzero_feas)\n\t:CLinearMulticlassMachine(new CMulticlassOneVsRestStrategy(), features, NULL, labs), m_nonzero_feas(num_nonzero_feas)\n{\n\tinit_sb_params();\n}\n\nvoid CShareBoost::init_sb_params()\n{\n\tSG_ADD(&m_nonzero_feas, \"m_nonzero_feas\", \"Number of non-zero features\", MS_NOT_AVAILABLE);\n}\n\nSGVector CShareBoost::get_activeset()\n{\n\treturn m_activeset.clone();\n}\n\nbool CShareBoost::train_machine(CFeatures* data)\n{\n\tif (data)\n\t\tset_features(data);\n\n\tif (m_features == NULL)\n\t\tSG_ERROR(\"No features given for training\\n\")\n\tif (m_labels == NULL)\n\t\tSG_ERROR(\"No labels given for training\\n\")\n\n\tif (m_nonzero_feas <= 0)\n\t\tSG_ERROR(\"Set a valid (> 0) number of non-zero features to seek before training\\n\")\n\tif (m_nonzero_feas >= dynamic_cast*>(m_features)->get_num_features())\n\t\tSG_ERROR(\"It doesn't make sense to use ShareBoost with num non-zero features >= num features in the data\\n\")\n\n\tm_fea = dynamic_cast *>(m_features)->get_feature_matrix();\n\tm_rho = SGMatrix(m_multiclass_strategy->get_num_classes(), m_fea.num_cols);\n\tm_rho_norm = SGVector(m_fea.num_cols);\n\tm_pred = SGMatrix(m_fea.num_cols, m_multiclass_strategy->get_num_classes());\n\tm_pred.zero();\n\n\tm_activeset = SGVector(m_fea.num_rows);\n\tm_activeset.vlen = 0;\n\n\tm_machines->reset_array();\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t\tm_machines->push_back(new CLinearMachine());\n\n\tCTime *timer = new CTime();\n\n\tfloat64_t t_compute_pred = 0; \/\/ t of 1st round is 0, since no pred to compute\n\tfor (int32_t t=0; t < m_nonzero_feas; ++t)\n\t{\n\t\ttimer->start();\n\t\tcompute_rho();\n\t\tint32_t i_fea = choose_feature();\n\t\tm_activeset.vector[m_activeset.vlen] = i_fea;\n\t\tm_activeset.vlen += 1;\n\t\tfloat64_t t_choose_feature = timer->cur_time_diff();\n\t\ttimer->start();\n\t\toptimize_coefficients();\n\t\tfloat64_t t_optimize = timer->cur_time_diff();\n\n\t\tSG_SPRINT(\" SB[round %03d]: (%8.4f + %8.4f) sec.\\n\", t,\n\t\t\t\tt_compute_pred + t_choose_feature, t_optimize);\n\n\t\ttimer->start();\n\t\tcompute_pred();\n\t\tt_compute_pred = timer->cur_time_diff();\n\t}\n\n\tSG_UNREF(timer);\n\n\t\/\/ release memory\n\tm_fea = SGMatrix();\n\tm_rho = SGMatrix();\n\tm_rho_norm = SGVector();\n\tm_pred = SGMatrix();\n\n\treturn true;\n}\n\nvoid CShareBoost::compute_pred()\n{\n\tCDenseFeatures *fea = dynamic_cast *>(m_features);\n\tCDenseSubsetFeatures *subset_fea = new CDenseSubsetFeatures(fea, m_activeset);\n\tSG_REF(subset_fea);\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t{\n\t\tCLinearMachine *machine = dynamic_cast(m_machines->get_element(i));\n\t\tCRegressionLabels *lab = machine->apply_regression(subset_fea);\n\t\tSGVector lab_raw = lab->get_labels();\n\t\tstd::copy(lab_raw.vector, lab_raw.vector + lab_raw.vlen, m_pred.get_column_vector(i));\n\t\tSG_UNREF(machine);\n\t\tSG_UNREF(lab);\n\t}\n\tSG_UNREF(subset_fea);\n}\n\nvoid CShareBoost::compute_pred(const float64_t *W)\n{\n\tint32_t w_len = m_activeset.vlen;\n\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t{\n\t\tCLinearMachine *machine = dynamic_cast(m_machines->get_element(i));\n\t\tSGVector w(w_len);\n\t\tstd::copy(W + i*w_len, W + (i+1)*w_len, w.vector);\n\t\tmachine->set_w(w);\n\t\tSG_UNREF(machine);\n\t}\n\tcompute_pred();\n}\n\nvoid CShareBoost::compute_rho()\n{\n\tCMulticlassLabels *lab = dynamic_cast(m_labels);\n\tfor (int32_t i=0; i < m_rho.num_rows; ++i)\n\t{ \/\/ i loop classes\n\t\tfor (int32_t j=0; j < m_rho.num_cols; ++j)\n\t\t{ \/\/ j loop samples\n\t\t\tint32_t label = lab->get_int_label(j);\n\n\t\t\tm_rho(i,j) = CMath::exp((label == i) - m_pred(j, label) + m_pred(j, i));\n\t\t}\n\t}\n\n\t\/\/ normalize\n\tfor (int32_t j=0; j < m_rho.num_cols; ++j)\n\t{\n\t\tm_rho_norm[j] = 0;\n\t\tfor (int32_t i=0; i < m_rho.num_rows; ++i)\n\t\t\tm_rho_norm[j] += m_rho(i,j);\n\t}\n}\n\nint32_t CShareBoost::choose_feature()\n{\n\tSGVector l1norm(m_fea.num_rows);\n\tfor (int32_t j=0; j < m_fea.num_rows; ++j)\n\t{\n\t\tif (std::find(&m_activeset[0], &m_activeset[m_activeset.vlen], j) !=\n\t\t\t\t&m_activeset[m_activeset.vlen])\n\t\t{\n\t\t\tl1norm[j] = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tl1norm[j] = 0;\n\t\t\tCMulticlassLabels *lab = dynamic_cast(m_labels);\n\t\t\tfor (int32_t k=0; k < m_multiclass_strategy->get_num_classes(); ++k)\n\t\t\t{\n\t\t\t\tfloat64_t abssum = 0;\n\t\t\t\tfor (int32_t ii=0; ii < m_fea.num_cols; ++ii)\n\t\t\t\t{\n\t\t\t\t\tabssum += m_fea(j, ii)*(m_rho(k, ii)\/m_rho_norm[ii] - \n\t\t\t\t\t\t\t(j == lab->get_int_label(ii)));\n\t\t\t\t}\n\t\t\t\tl1norm[j] += CMath::abs(abssum);\n\t\t\t}\n\t\t\tl1norm[j] \/= m_fea.num_cols;\n\t\t}\n\t}\n\n\treturn SGVector::arg_max(l1norm.vector, 1, l1norm.vlen);\n}\n\nvoid CShareBoost::optimize_coefficients()\n{\n\tShareBoostOptimizer optimizer(this, false);\n\toptimizer.optimize();\n}\n\nvoid CShareBoost::set_features(CFeatures *f)\n{\n\tCDenseFeatures *fea = dynamic_cast *>(f);\n\tif (fea == NULL)\n\t\tSG_ERROR(\"Require DenseFeatures\\n\")\n\tCLinearMulticlassMachine::set_features(fea);\n}\nshareboost: don't print progress if not in debug mode\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2012 Chiyuan Zhang\n * Copyright (C) 2012 Chiyuan Zhang\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nCShareBoost::CShareBoost()\n\t:CLinearMulticlassMachine(), m_nonzero_feas(0)\n{\n\tinit_sb_params();\n}\n\nCShareBoost::CShareBoost(CDenseFeatures *features, CMulticlassLabels *labs, int32_t num_nonzero_feas)\n\t:CLinearMulticlassMachine(new CMulticlassOneVsRestStrategy(), features, NULL, labs), m_nonzero_feas(num_nonzero_feas)\n{\n\tinit_sb_params();\n}\n\nvoid CShareBoost::init_sb_params()\n{\n\tSG_ADD(&m_nonzero_feas, \"m_nonzero_feas\", \"Number of non-zero features\", MS_NOT_AVAILABLE);\n}\n\nSGVector CShareBoost::get_activeset()\n{\n\treturn m_activeset.clone();\n}\n\nbool CShareBoost::train_machine(CFeatures* data)\n{\n\tif (data)\n\t\tset_features(data);\n\n\tif (m_features == NULL)\n\t\tSG_ERROR(\"No features given for training\\n\")\n\tif (m_labels == NULL)\n\t\tSG_ERROR(\"No labels given for training\\n\")\n\n\tif (m_nonzero_feas <= 0)\n\t\tSG_ERROR(\"Set a valid (> 0) number of non-zero features to seek before training\\n\")\n\tif (m_nonzero_feas >= dynamic_cast*>(m_features)->get_num_features())\n\t\tSG_ERROR(\"It doesn't make sense to use ShareBoost with num non-zero features >= num features in the data\\n\")\n\n\tm_fea = dynamic_cast *>(m_features)->get_feature_matrix();\n\tm_rho = SGMatrix(m_multiclass_strategy->get_num_classes(), m_fea.num_cols);\n\tm_rho_norm = SGVector(m_fea.num_cols);\n\tm_pred = SGMatrix(m_fea.num_cols, m_multiclass_strategy->get_num_classes());\n\tm_pred.zero();\n\n\tm_activeset = SGVector(m_fea.num_rows);\n\tm_activeset.vlen = 0;\n\n\tm_machines->reset_array();\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t\tm_machines->push_back(new CLinearMachine());\n\n\tCTime *timer = new CTime();\n\n\tfloat64_t t_compute_pred = 0; \/\/ t of 1st round is 0, since no pred to compute\n\tfor (int32_t t=0; t < m_nonzero_feas; ++t)\n\t{\n\t\ttimer->start();\n\t\tcompute_rho();\n\t\tint32_t i_fea = choose_feature();\n\t\tm_activeset.vector[m_activeset.vlen] = i_fea;\n\t\tm_activeset.vlen += 1;\n\t\tfloat64_t t_choose_feature = timer->cur_time_diff();\n\t\ttimer->start();\n\t\toptimize_coefficients();\n\t\tfloat64_t t_optimize = timer->cur_time_diff();\n\n\t\tSG_SDEBUG(\" SB[round %03d]: (%8.4f + %8.4f) sec.\\n\", t,\n\t\t\t\tt_compute_pred + t_choose_feature, t_optimize);\n\n\t\ttimer->start();\n\t\tcompute_pred();\n\t\tt_compute_pred = timer->cur_time_diff();\n\t}\n\n\tSG_UNREF(timer);\n\n\t\/\/ release memory\n\tm_fea = SGMatrix();\n\tm_rho = SGMatrix();\n\tm_rho_norm = SGVector();\n\tm_pred = SGMatrix();\n\n\treturn true;\n}\n\nvoid CShareBoost::compute_pred()\n{\n\tCDenseFeatures *fea = dynamic_cast *>(m_features);\n\tCDenseSubsetFeatures *subset_fea = new CDenseSubsetFeatures(fea, m_activeset);\n\tSG_REF(subset_fea);\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t{\n\t\tCLinearMachine *machine = dynamic_cast(m_machines->get_element(i));\n\t\tCRegressionLabels *lab = machine->apply_regression(subset_fea);\n\t\tSGVector lab_raw = lab->get_labels();\n\t\tstd::copy(lab_raw.vector, lab_raw.vector + lab_raw.vlen, m_pred.get_column_vector(i));\n\t\tSG_UNREF(machine);\n\t\tSG_UNREF(lab);\n\t}\n\tSG_UNREF(subset_fea);\n}\n\nvoid CShareBoost::compute_pred(const float64_t *W)\n{\n\tint32_t w_len = m_activeset.vlen;\n\n\tfor (int32_t i=0; i < m_multiclass_strategy->get_num_classes(); ++i)\n\t{\n\t\tCLinearMachine *machine = dynamic_cast(m_machines->get_element(i));\n\t\tSGVector w(w_len);\n\t\tstd::copy(W + i*w_len, W + (i+1)*w_len, w.vector);\n\t\tmachine->set_w(w);\n\t\tSG_UNREF(machine);\n\t}\n\tcompute_pred();\n}\n\nvoid CShareBoost::compute_rho()\n{\n\tCMulticlassLabels *lab = dynamic_cast(m_labels);\n\tfor (int32_t i=0; i < m_rho.num_rows; ++i)\n\t{ \/\/ i loop classes\n\t\tfor (int32_t j=0; j < m_rho.num_cols; ++j)\n\t\t{ \/\/ j loop samples\n\t\t\tint32_t label = lab->get_int_label(j);\n\n\t\t\tm_rho(i,j) = CMath::exp((label == i) - m_pred(j, label) + m_pred(j, i));\n\t\t}\n\t}\n\n\t\/\/ normalize\n\tfor (int32_t j=0; j < m_rho.num_cols; ++j)\n\t{\n\t\tm_rho_norm[j] = 0;\n\t\tfor (int32_t i=0; i < m_rho.num_rows; ++i)\n\t\t\tm_rho_norm[j] += m_rho(i,j);\n\t}\n}\n\nint32_t CShareBoost::choose_feature()\n{\n\tSGVector l1norm(m_fea.num_rows);\n\tfor (int32_t j=0; j < m_fea.num_rows; ++j)\n\t{\n\t\tif (std::find(&m_activeset[0], &m_activeset[m_activeset.vlen], j) !=\n\t\t\t\t&m_activeset[m_activeset.vlen])\n\t\t{\n\t\t\tl1norm[j] = 0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tl1norm[j] = 0;\n\t\t\tCMulticlassLabels *lab = dynamic_cast(m_labels);\n\t\t\tfor (int32_t k=0; k < m_multiclass_strategy->get_num_classes(); ++k)\n\t\t\t{\n\t\t\t\tfloat64_t abssum = 0;\n\t\t\t\tfor (int32_t ii=0; ii < m_fea.num_cols; ++ii)\n\t\t\t\t{\n\t\t\t\t\tabssum += m_fea(j, ii)*(m_rho(k, ii)\/m_rho_norm[ii] - \n\t\t\t\t\t\t\t(j == lab->get_int_label(ii)));\n\t\t\t\t}\n\t\t\t\tl1norm[j] += CMath::abs(abssum);\n\t\t\t}\n\t\t\tl1norm[j] \/= m_fea.num_cols;\n\t\t}\n\t}\n\n\treturn SGVector::arg_max(l1norm.vector, 1, l1norm.vlen);\n}\n\nvoid CShareBoost::optimize_coefficients()\n{\n\tShareBoostOptimizer optimizer(this, false);\n\toptimizer.optimize();\n}\n\nvoid CShareBoost::set_features(CFeatures *f)\n{\n\tCDenseFeatures *fea = dynamic_cast *>(f);\n\tif (fea == NULL)\n\t\tSG_ERROR(\"Require DenseFeatures\\n\")\n\tCLinearMulticlassMachine::set_features(fea);\n}\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \"core\/Scaled.h\"\n\nTEST(ScaledTest, CanRetrieveInteger)\n{\n\tScaled s1(5);\n\n\tEXPECT_EQ(5, (int)s1);\n}\n\nTEST(ScaledTest, FloatCast)\n{\n\tScaled s1(1.5);\n\n\tEXPECT_FLOAT_EQ(1.5, (float)s1);\n\tEXPECT_FLOAT_EQ(1.5, (double)s1);\n}\n\nTEST(ScaledTest, ComparisonOperators)\n{\n\tScaled s1(5);\n\tScaled s2(5);\n\tScaled s3(3);\n\tScaled s4(8);\n\tScaled s5(0);\n\n\tEXPECT_TRUE(s1 == s2);\n\tEXPECT_FALSE(s1 == s3);\n\n\tEXPECT_FALSE(s1 != s2);\n\tEXPECT_TRUE(s1 != s4);\n\n\tEXPECT_FALSE(s1 < s2);\n\tEXPECT_FALSE(s1 < s3);\n\tEXPECT_TRUE(s1 < s4);\n\n\tEXPECT_FALSE(s1 > s2);\n\tEXPECT_TRUE(s1 > s3);\n\tEXPECT_FALSE(s1 > s4);\n\n\tEXPECT_TRUE(s1 <= s2);\n\tEXPECT_FALSE(s1 <= s3);\n\tEXPECT_TRUE(s1 <= s4);\n\n\tEXPECT_TRUE(s1 >= s2);\n\tEXPECT_TRUE(s1 >= s3);\n\tEXPECT_FALSE(s1 >= s4);\n\n\tEXPECT_FALSE(!s1);\n\tEXPECT_TRUE(!s5);\n}\n\nTEST(ScaledTest, BasicAddition)\n{\n\tScaled s1(2);\n\tScaled s2(4);\n\n\tScaled s3 = s1 + s2;\n\n\tEXPECT_EQ(6, (int)s3);\n}\n\nTEST(ScaledTest, BasicSubtraction)\n{\n\tScaled s1(6);\n\tScaled s2(4);\n\n\tScaled s3 = s1 - s2;\n\n\tEXPECT_EQ(2, (int)s3);\n}\n\nTEST(ScaledTest, AddInt)\n{\n\tScaled s1(2);\n\n\tScaled s2 = s1 + 4;\n\n\tEXPECT_EQ(6, (int)s2);\n}\n\nTEST(ScaledTest, SubtractInt)\n{\n\tScaled s1(6);\n\n\tScaled s2 = s1 - 4;\n\n\tEXPECT_EQ(2, (int)s2);\n}\n\nTEST(ScaledTest, BasicMultiplication)\n{\n\tScaled s1(2);\n\tScaled s2(4);\n\n\tScaled s3 = s1 * s2;\n\n\tEXPECT_EQ(8, (int)s3);\n}\n\nTEST(ScaledTest, BasicDivision)\n{\n\tScaled s1(6);\n\tScaled s2(3);\n\n\tScaled s3 = s1 \/ s2;\n\n\tEXPECT_EQ(2, (int)s3);\n}\n\nTEST(ScaledTest, MultiplyInt)\n{\n\tScaled s1(2);\n\n\tScaled s2 = s1 * 4;\n\n\tEXPECT_EQ(8, (int)s2);\n}\n\nTEST(ScaledTest, DivideInt)\n{\n\tScaled s1(6);\n\n\tScaled s2 = s1 \/ 3;\n\n\tEXPECT_EQ(2, (int)s2);\n}\n\nTests for int and double\/float comparisons#include \"gtest\/gtest.h\"\n#include \"core\/Scaled.h\"\n\nTEST(ScaledTest, IntCast)\n{\n\tScaled s1(5);\n\n\tEXPECT_EQ(5, (int)s1);\n}\n\nTEST(ScaledTest, FloatCast)\n{\n\tScaled s1(1.5);\n\n\tEXPECT_FLOAT_EQ(1.5, (float)s1);\n\tEXPECT_FLOAT_EQ(1.5, (double)s1);\n}\n\nTEST(ScaledTest, ScaledComparisons)\n{\n\tScaled s1(5);\n\tScaled s2(5);\n\tScaled s3(3);\n\tScaled s4(8);\n\tScaled s5(0);\n\n\tEXPECT_TRUE(s1 == s2);\n\tEXPECT_FALSE(s1 == s3);\n\n\tEXPECT_FALSE(s1 != s2);\n\tEXPECT_TRUE(s1 != s4);\n\n\tEXPECT_FALSE(s1 < s2);\n\tEXPECT_FALSE(s1 < s3);\n\tEXPECT_TRUE(s1 < s4);\n\n\tEXPECT_FALSE(s1 > s2);\n\tEXPECT_TRUE(s1 > s3);\n\tEXPECT_FALSE(s1 > s4);\n\n\tEXPECT_TRUE(s1 <= s2);\n\tEXPECT_FALSE(s1 <= s3);\n\tEXPECT_TRUE(s1 <= s4);\n\n\tEXPECT_TRUE(s1 >= s2);\n\tEXPECT_TRUE(s1 >= s3);\n\tEXPECT_FALSE(s1 >= s4);\n\n\tEXPECT_FALSE(!s1);\n\tEXPECT_TRUE(!s5);\n}\n\nTEST(ScaledTest, IntComparisons)\n{\n\tScaled s1(5);\n\tScaled s2(5);\n\tScaled s3(3);\n\tScaled s4(8);\n\tScaled s5(0);\n\n\tEXPECT_TRUE(s1 == 5);\n\tEXPECT_FALSE(s1 == 4);\n\n\tEXPECT_FALSE(s1 != 5);\n\tEXPECT_TRUE(s1 != 4);\n\n\tEXPECT_FALSE(s1 < 5);\n\tEXPECT_FALSE(s1 < 3);\n\tEXPECT_TRUE(s1 < 8);\n\n\tEXPECT_FALSE(s1 > 5);\n\tEXPECT_TRUE(s1 > 3);\n\tEXPECT_FALSE(s1 > 8);\n\n\tEXPECT_TRUE(s1 <= 5);\n\tEXPECT_FALSE(s1 <= 3);\n\tEXPECT_TRUE(s1 <= 8);\n\n\tEXPECT_TRUE(s1 >= 5);\n\tEXPECT_TRUE(s1 >= 3);\n\tEXPECT_FALSE(s1 >= 8);\n}\n\nTEST(ScaledTest, DoubleComparisons)\n{\n\tScaled s1(5.6);\n\tScaled s2(5.6);\n\tScaled s3(3.2);\n\tScaled s4(8.78);\n\tScaled s5(0.2);\n\n\tEXPECT_TRUE(s1 == 5.6);\n\tEXPECT_FALSE(s1 == 5.5);\n\n\tEXPECT_FALSE(s1 != 5.6);\n\tEXPECT_TRUE(s1 != 5.5);\n\n\tEXPECT_FALSE(s1 < 5.6);\n\tEXPECT_FALSE(s1 < 3.2);\n\tEXPECT_TRUE(s1 < 8.78);\n\n\tEXPECT_FALSE(s1 > 5.6);\n\tEXPECT_TRUE(s1 > 3.2);\n\tEXPECT_FALSE(s1 > 8.78);\n\n\tEXPECT_TRUE(s1 <= 5.6);\n\tEXPECT_FALSE(s1 <= 3.2);\n\tEXPECT_TRUE(s1 <= 8.78);\n\n\tEXPECT_TRUE(s1 >= 5.6);\n\tEXPECT_TRUE(s1 >= 3.2);\n\tEXPECT_FALSE(s1 >= 8.78);\n}\n\nTEST(ScaledTest, BasicAddition)\n{\n\tScaled s1(2);\n\tScaled s2(4);\n\n\tScaled s3 = s1 + s2;\n\n\tEXPECT_EQ(6, (int)s3);\n}\n\nTEST(ScaledTest, BasicSubtraction)\n{\n\tScaled s1(6);\n\tScaled s2(4);\n\n\tScaled s3 = s1 - s2;\n\n\tEXPECT_EQ(2, (int)s3);\n}\n\nTEST(ScaledTest, AddInt)\n{\n\tScaled s1(2);\n\n\tScaled s2 = s1 + 4;\n\n\tEXPECT_EQ(6, (int)s2);\n}\n\nTEST(ScaledTest, SubtractInt)\n{\n\tScaled s1(6);\n\n\tScaled s2 = s1 - 4;\n\n\tEXPECT_EQ(2, (int)s2);\n}\n\nTEST(ScaledTest, BasicMultiplication)\n{\n\tScaled s1(2);\n\tScaled s2(4);\n\n\tScaled s3 = s1 * s2;\n\n\tEXPECT_EQ(8, (int)s3);\n}\n\nTEST(ScaledTest, BasicDivision)\n{\n\tScaled s1(6);\n\tScaled s2(3);\n\n\tScaled s3 = s1 \/ s2;\n\n\tEXPECT_EQ(2, (int)s3);\n}\n\nTEST(ScaledTest, MultiplyInt)\n{\n\tScaled s1(2);\n\n\tScaled s2 = s1 * 4;\n\n\tEXPECT_EQ(8, (int)s2);\n}\n\nTEST(ScaledTest, DivideInt)\n{\n\tScaled s1(6);\n\n\tScaled s2 = s1 \/ 3;\n\n\tEXPECT_EQ(2, (int)s2);\n}\n\n<|endoftext|>"} {"text":"#define WIN32_LEAN_AND_MEAN\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/worker_platform.h\"\n#include \"..\/worker_thread.h\"\n#include \"..\/..\/message.h\"\n#include \"..\/..\/log.h\"\n#include \"..\/..\/lock.h\"\n\nusing std::string;\nusing std::wstring;\nusing std::ostringstream;\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::default_delete;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::vector;\nusing std::move;\nusing std::endl;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nstatic void CALLBACK command_perform_helper(__in ULONG_PTR payload);\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);\n\nstatic Result to_utf8(const wstring &in);\n\nstatic Result to_wchar(const string &in);\n\ntemplate < class V = void* >\nstatic Result windows_error_result(const string &prefix);\n\ntemplate < class V = void* >\nstatic Result windows_error_result(const string &prefix, DWORD error_code);\n\nclass WindowsWorkerPlatform;\n\nclass Subscription {\npublic:\n Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n {\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n }\n\n ~Subscription()\n {\n CloseHandle(root);\n }\n\n Result<> schedule()\n {\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n &event_helper \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n }\n\n Result<> use_network_size()\n {\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n }\n\n ChannelID get_channel() const {\n return channel;\n }\n\n WindowsWorkerPlatform* get_platform() const {\n return platform;\n }\n\n BYTE *get_written(DWORD written_size) {\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n }\n\n string make_absolute(const string &sub_path)\n {\n ostringstream out;\n\n out << path;\n if (path.back() != '\\\\' && sub_path.front() != '\\\\') {\n out << '\\\\';\n }\n out << sub_path;\n\n return out.str();\n }\n\nprivate:\n ChannelID channel;\n WindowsWorkerPlatform *platform;\n\n string path;\n HANDLE root;\n OVERLAPPED overlapped;\n\n DWORD buffer_size;\n unique_ptr buffer;\n unique_ptr written;\n};\n\nclass WindowsWorkerPlatform : public WorkerPlatform {\npublic:\n WindowsWorkerPlatform(WorkerThread *thread) :\n WorkerPlatform(thread),\n thread_handle{0}\n {\n int err;\n\n err = uv_mutex_init(&thread_handle_mutex);\n if (err) {\n report_uv_error(err);\n }\n };\n\n ~WindowsWorkerPlatform() override\n {\n uv_mutex_destroy(&thread_handle_mutex);\n }\n\n Result<> wake() override\n {\n Lock lock(thread_handle_mutex);\n\n if (!thread_handle) {\n return ok_result();\n }\n\n BOOL success = QueueUserAPC(\n command_perform_helper,\n thread_handle,\n reinterpret_cast(this)\n );\n if (!success) {\n return windows_error_result<>(\"Unable to queue APC\");\n }\n\n return ok_result();\n }\n\n Result<> listen() override\n {\n {\n Lock lock(thread_handle_mutex);\n\n HANDLE pseudo_handle = GetCurrentThread();\n BOOL success = DuplicateHandle(\n GetCurrentProcess(), \/\/ Source process\n pseudo_handle, \/\/ Source handle\n GetCurrentProcess(), \/\/ Destination process\n &thread_handle, \/\/ Destination handle\n 0, \/\/ Desired access\n FALSE, \/\/ Inheritable by new processes\n DUPLICATE_SAME_ACCESS \/\/ options\n );\n if (!success) {\n Result<> r = windows_error_result<>(\"Unable to duplicate thread handle\");\n report_error(\"Unable to acquire thread handle\");\n return r;\n }\n }\n\n while (true) {\n SleepEx(INFINITE, true);\n }\n\n report_error(\"listen loop ended unexpectedly\");\n return health_err_result();\n }\n\n Result<> handle_add_command(const ChannelID channel, const string &root_path)\n {\n LOGGER << \"Watching: \" << root_path << endl;\n\n \/\/ Convert the path to a wide-character array\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result<>(\"Unable to measure UTF-16 buffer\");\n }\n unique_ptr root_path_w{new WCHAR[wlen]};\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n root_path.data(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n root_path_w.get(), \/\/ output buffer\n wlen \/\/ output buffer size\n );\n if (!conv_success) {\n return windows_error_result<>(\"Unable to convert root path to UTF-16\");\n }\n\n \/\/ Open a directory handle\n HANDLE root = CreateFileW(\n root_path_w.get(), \/\/ file name\n FILE_LIST_DIRECTORY, \/\/ desired access\n FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, \/\/ share mode\n NULL, \/\/ security attributes\n OPEN_EXISTING, \/\/ creation disposition\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, \/\/ flags and attributes\n NULL \/\/ template file\n );\n if (root == INVALID_HANDLE_VALUE) {\n return windows_error_result<>(\"Unable to open directory handle\");\n }\n\n \/\/ Allocate and persist the subscription\n Subscription *sub = new Subscription(channel, root, root_path, this);\n auto insert_result = subscriptions.insert(make_pair(channel, sub));\n if (!insert_result.second) {\n delete sub;\n\n ostringstream msg(\"Channel collision: \");\n msg << channel;\n return error_result(msg.str());\n }\n\n LOGGER << \"Now watching directory \" << root_path << \".\" << endl;\n\n return sub->schedule();\n }\n\n Result<> handle_remove_command(const ChannelID channel)\n {\n return ok_result();\n }\n\n Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)\n {\n \/\/ Ensure that the subscription is valid.\n ChannelID channel = sub->get_channel();\n auto it = subscriptions.find(channel);\n if (it == subscriptions.end() || it->second != sub) {\n return ok_result();\n }\n\n \/\/ Handle errors.\n if (error_code == ERROR_OPERATION_ABORTED) {\n LOGGER << \"Operation aborted.\" << endl;\n\n subscriptions.erase(it);\n delete sub;\n\n return ok_result();\n }\n\n if (error_code == ERROR_INVALID_PARAMETER) {\n Result<> resize = sub->use_network_size();\n if (resize.is_error()) return resize;\n\n return sub->schedule();\n }\n\n if (error_code == ERROR_NOTIFY_ENUM_DIR) {\n LOGGER << \"Change buffer overflow. Some events may have been lost.\" << endl;\n return sub->schedule();\n }\n\n if (error_code != ERROR_SUCCESS) {\n return windows_error_result<>(\"Completion callback error\", error_code);\n }\n\n \/\/ Schedule the next completion callback.\n BYTE *base = sub->get_written(num_bytes);\n Result<> next = sub->schedule();\n if (next.is_error()) {\n report_error(string(next.get_error()));\n }\n\n \/\/ Process received events.\n vector messages;\n bool old_path_seen = false;\n string old_path;\n\n while (true) {\n PFILE_NOTIFY_INFORMATION info = reinterpret_cast(base);\n\n wstring wpath{info->FileName, info->FileNameLength};\n Result u8r = to_utf8(wpath);\n if (u8r.is_error()) {\n LOGGER << \"Skipping path: \" << u8r << \".\" << endl;\n } else {\n string path = sub->make_absolute(u8r.get_value());\n\n switch (info->Action) {\n case FILE_ACTION_ADDED:\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_MODIFIED:\n {\n FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_REMOVED:\n {\n FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_RENAMED_OLD_NAME:\n old_path_seen = true;\n old_path = move(path);\n break;\n case FILE_ACTION_RENAMED_NEW_NAME:\n if (old_path_seen) {\n \/\/ Old name received first\n {\n FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n\n old_path_seen = false;\n } else {\n \/\/ No old name. Treat it as a creation\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n }\n break;\n default:\n LOGGER << \"Skipping unexpected action \" << info->Action << \".\" << endl;\n break;\n }\n }\n\n if (info->NextEntryOffset == 0) {\n break;\n }\n base += info->NextEntryOffset;\n }\n\n if (!messages.empty()) {\n Result<> er = emit_all(messages.begin(), messages.end());\n if (er.is_error()) {\n LOGGER << \"Unable to emit messages: \" << er << \".\" << endl;\n }\n }\n\n return next;\n }\n\nprivate:\n uv_mutex_t thread_handle_mutex;\n HANDLE thread_handle;\n\n map subscriptions;\n};\n\nunique_ptr WorkerPlatform::for_worker(WorkerThread *thread)\n{\n return unique_ptr(new WindowsWorkerPlatform(thread));\n}\n\nvoid CALLBACK command_perform_helper(__in ULONG_PTR payload)\n{\n WindowsWorkerPlatform *platform = reinterpret_cast(payload);\n platform->handle_commands();\n}\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)\n{\n Subscription *sub = static_cast(overlapped->hEvent);\n Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);\n if (r.is_error()) {\n LOGGER << \"Unable to handle filesystem events: \" << r << \".\" << endl;\n }\n}\n\nResult to_utf8(const wstring &in)\n{\n size_t len = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n nullptr, \/\/ destination string, null to measure\n 0, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!len) {\n return windows_error_result(\"Unable to measure string as UTF-8\");\n }\n\n unique_ptr payload(new char[len]);\n size_t copied = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n payload.get(), \/\/ destination string\n len, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!copied) {\n return windows_error_result(\"Unable to convert string to UTF-8\");\n }\n\n return ok_result(string(payload.get(), len));\n}\n\nResult to_wchar(const string &in)\n{\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result(\"Unable to measure string as wide string\");\n }\n\n unique_ptr payload(new WCHAR[wlen]);\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n payload.get(), \/\/ output buffer\n wlen \/\/ output buffer size (in bytes)\n );\n if (!conv_success) {\n return windows_error_result(\"Unable to convert string to wide string\");\n }\n\n return ok_result(wstring(payload.get(), wlen - 1));\n}\n\ntemplate < class V >\nResult windows_error_result(const string &prefix)\n{\n return windows_error_result(prefix, GetLastError());\n}\n\ntemplate < class V >\nResult windows_error_result(const string &prefix, DWORD error_code)\n{\n LPVOID msg_buffer;\n\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, \/\/ source\n error_code, \/\/ message ID\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ language ID\n (LPSTR) &msg_buffer, \/\/ output buffer\n 0, \/\/ size\n NULL \/\/ arguments\n );\n\n ostringstream msg;\n msg << prefix << \"\\n (\" << error_code << \") \" << (char*) msg_buffer;\n LocalFree(msg_buffer);\n\n return Result::make_error(msg.str());\n}\nUse the string => wstring conversion function#define WIN32_LEAN_AND_MEAN\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"..\/worker_platform.h\"\n#include \"..\/worker_thread.h\"\n#include \"..\/..\/message.h\"\n#include \"..\/..\/log.h\"\n#include \"..\/..\/lock.h\"\n\nusing std::string;\nusing std::wstring;\nusing std::ostringstream;\nusing std::unique_ptr;\nusing std::shared_ptr;\nusing std::default_delete;\nusing std::map;\nusing std::pair;\nusing std::make_pair;\nusing std::vector;\nusing std::move;\nusing std::endl;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nstatic void CALLBACK command_perform_helper(__in ULONG_PTR payload);\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped);\n\nstatic Result to_utf8(const wstring &in);\n\nstatic Result to_wchar(const string &in);\n\ntemplate < class V = void* >\nstatic Result windows_error_result(const string &prefix);\n\ntemplate < class V = void* >\nstatic Result windows_error_result(const string &prefix, DWORD error_code);\n\nclass WindowsWorkerPlatform;\n\nclass Subscription {\npublic:\n Subscription(ChannelID channel, HANDLE root, const string &path, WindowsWorkerPlatform *platform) :\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n {\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n }\n\n ~Subscription()\n {\n CloseHandle(root);\n }\n\n Result<> schedule()\n {\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n &event_helper \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n }\n\n Result<> use_network_size()\n {\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n }\n\n ChannelID get_channel() const {\n return channel;\n }\n\n WindowsWorkerPlatform* get_platform() const {\n return platform;\n }\n\n BYTE *get_written(DWORD written_size) {\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n }\n\n string make_absolute(const string &sub_path)\n {\n ostringstream out;\n\n out << path;\n if (path.back() != '\\\\' && sub_path.front() != '\\\\') {\n out << '\\\\';\n }\n out << sub_path;\n\n return out.str();\n }\n\nprivate:\n ChannelID channel;\n WindowsWorkerPlatform *platform;\n\n string path;\n HANDLE root;\n OVERLAPPED overlapped;\n\n DWORD buffer_size;\n unique_ptr buffer;\n unique_ptr written;\n};\n\nclass WindowsWorkerPlatform : public WorkerPlatform {\npublic:\n WindowsWorkerPlatform(WorkerThread *thread) :\n WorkerPlatform(thread),\n thread_handle{0}\n {\n int err;\n\n err = uv_mutex_init(&thread_handle_mutex);\n if (err) {\n report_uv_error(err);\n }\n };\n\n ~WindowsWorkerPlatform() override\n {\n uv_mutex_destroy(&thread_handle_mutex);\n }\n\n Result<> wake() override\n {\n Lock lock(thread_handle_mutex);\n\n if (!thread_handle) {\n return ok_result();\n }\n\n BOOL success = QueueUserAPC(\n command_perform_helper,\n thread_handle,\n reinterpret_cast(this)\n );\n if (!success) {\n return windows_error_result<>(\"Unable to queue APC\");\n }\n\n return ok_result();\n }\n\n Result<> listen() override\n {\n {\n Lock lock(thread_handle_mutex);\n\n HANDLE pseudo_handle = GetCurrentThread();\n BOOL success = DuplicateHandle(\n GetCurrentProcess(), \/\/ Source process\n pseudo_handle, \/\/ Source handle\n GetCurrentProcess(), \/\/ Destination process\n &thread_handle, \/\/ Destination handle\n 0, \/\/ Desired access\n FALSE, \/\/ Inheritable by new processes\n DUPLICATE_SAME_ACCESS \/\/ options\n );\n if (!success) {\n Result<> r = windows_error_result<>(\"Unable to duplicate thread handle\");\n report_error(\"Unable to acquire thread handle\");\n return r;\n }\n }\n\n while (true) {\n SleepEx(INFINITE, true);\n }\n\n report_error(\"listen loop ended unexpectedly\");\n return health_err_result();\n }\n\n Result<> handle_add_command(const ChannelID channel, const string &root_path)\n {\n \/\/ Convert the path to a wide-character string\n Result convr = to_wchar(root_path);\n if (convr.is_error()) return convr.propagate<>();\n wstring &root_path_w = convr.get_value();\n\n \/\/ Open a directory handle\n HANDLE root = CreateFileW(\n root_path_w.c_str(), \/\/ null-terminated wchar file name\n FILE_LIST_DIRECTORY, \/\/ desired access\n FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, \/\/ share mode\n NULL, \/\/ security attributes\n OPEN_EXISTING, \/\/ creation disposition\n FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, \/\/ flags and attributes\n NULL \/\/ template file\n );\n if (root == INVALID_HANDLE_VALUE) {\n return windows_error_result<>(\"Unable to open directory handle\");\n }\n\n \/\/ Allocate and persist the subscription\n Subscription *sub = new Subscription(channel, root, root_path, this);\n auto insert_result = subscriptions.insert(make_pair(channel, sub));\n if (!insert_result.second) {\n delete sub;\n\n ostringstream msg(\"Channel collision: \");\n msg << channel;\n return error_result(msg.str());\n }\n\n LOGGER << \"Now watching directory \" << root_path << \".\" << endl;\n\n return sub->schedule();\n }\n\n Result<> handle_remove_command(const ChannelID channel)\n {\n return ok_result();\n }\n\n Result<> handle_fs_event(DWORD error_code, DWORD num_bytes, Subscription* sub)\n {\n \/\/ Ensure that the subscription is valid.\n ChannelID channel = sub->get_channel();\n auto it = subscriptions.find(channel);\n if (it == subscriptions.end() || it->second != sub) {\n return ok_result();\n }\n\n \/\/ Handle errors.\n if (error_code == ERROR_OPERATION_ABORTED) {\n LOGGER << \"Operation aborted.\" << endl;\n\n subscriptions.erase(it);\n delete sub;\n\n return ok_result();\n }\n\n if (error_code == ERROR_INVALID_PARAMETER) {\n Result<> resize = sub->use_network_size();\n if (resize.is_error()) return resize;\n\n return sub->schedule();\n }\n\n if (error_code == ERROR_NOTIFY_ENUM_DIR) {\n LOGGER << \"Change buffer overflow. Some events may have been lost.\" << endl;\n return sub->schedule();\n }\n\n if (error_code != ERROR_SUCCESS) {\n return windows_error_result<>(\"Completion callback error\", error_code);\n }\n\n \/\/ Schedule the next completion callback.\n BYTE *base = sub->get_written(num_bytes);\n Result<> next = sub->schedule();\n if (next.is_error()) {\n report_error(string(next.get_error()));\n }\n\n \/\/ Process received events.\n vector messages;\n bool old_path_seen = false;\n string old_path;\n\n while (true) {\n PFILE_NOTIFY_INFORMATION info = reinterpret_cast(base);\n\n wstring wpath{info->FileName, info->FileNameLength};\n Result u8r = to_utf8(wpath);\n if (u8r.is_error()) {\n LOGGER << \"Skipping path: \" << u8r << \".\" << endl;\n } else {\n string path = sub->make_absolute(u8r.get_value());\n\n switch (info->Action) {\n case FILE_ACTION_ADDED:\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_MODIFIED:\n {\n FileSystemPayload payload(channel, ACTION_MODIFIED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_REMOVED:\n {\n FileSystemPayload payload(channel, ACTION_DELETED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n break;\n case FILE_ACTION_RENAMED_OLD_NAME:\n old_path_seen = true;\n old_path = move(path);\n break;\n case FILE_ACTION_RENAMED_NEW_NAME:\n if (old_path_seen) {\n \/\/ Old name received first\n {\n FileSystemPayload payload(channel, ACTION_RENAMED, KIND_UNKNOWN, move(old_path), move(path));\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n\n old_path_seen = false;\n } else {\n \/\/ No old name. Treat it as a creation\n {\n FileSystemPayload payload(channel, ACTION_CREATED, KIND_UNKNOWN, move(path), \"\");\n Message message(move(payload));\n\n LOGGER << \"Emitting filesystem message \" << message << \".\" << endl;\n messages.push_back(move(message));\n }\n }\n break;\n default:\n LOGGER << \"Skipping unexpected action \" << info->Action << \".\" << endl;\n break;\n }\n }\n\n if (info->NextEntryOffset == 0) {\n break;\n }\n base += info->NextEntryOffset;\n }\n\n if (!messages.empty()) {\n Result<> er = emit_all(messages.begin(), messages.end());\n if (er.is_error()) {\n LOGGER << \"Unable to emit messages: \" << er << \".\" << endl;\n }\n }\n\n return next;\n }\n\nprivate:\n uv_mutex_t thread_handle_mutex;\n HANDLE thread_handle;\n\n map subscriptions;\n};\n\nunique_ptr WorkerPlatform::for_worker(WorkerThread *thread)\n{\n return unique_ptr(new WindowsWorkerPlatform(thread));\n}\n\nvoid CALLBACK command_perform_helper(__in ULONG_PTR payload)\n{\n WindowsWorkerPlatform *platform = reinterpret_cast(payload);\n platform->handle_commands();\n}\n\nstatic void CALLBACK event_helper(DWORD error_code, DWORD num_bytes, LPOVERLAPPED overlapped)\n{\n Subscription *sub = static_cast(overlapped->hEvent);\n Result<> r = sub->get_platform()->handle_fs_event(error_code, num_bytes, sub);\n if (r.is_error()) {\n LOGGER << \"Unable to handle filesystem events: \" << r << \".\" << endl;\n }\n}\n\nResult to_utf8(const wstring &in)\n{\n size_t len = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n nullptr, \/\/ destination string, null to measure\n 0, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!len) {\n return windows_error_result(\"Unable to measure string as UTF-8\");\n }\n\n unique_ptr payload(new char[len]);\n size_t copied = WideCharToMultiByte(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.data(), \/\/ source string\n in.size(), \/\/ source string length\n payload.get(), \/\/ destination string\n len, \/\/ destination string length\n nullptr, \/\/ default char\n nullptr \/\/ used default char\n );\n if (!copied) {\n return windows_error_result(\"Unable to convert string to UTF-8\");\n }\n\n return ok_result(string(payload.get(), len));\n}\n\nResult to_wchar(const string &in)\n{\n size_t wlen = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n 0, \/\/ output buffer\n 0 \/\/ output buffer size\n );\n if (wlen == 0) {\n return windows_error_result(\"Unable to measure string as wide string\");\n }\n\n unique_ptr payload(new WCHAR[wlen]);\n size_t conv_success = MultiByteToWideChar(\n CP_UTF8, \/\/ code page\n 0, \/\/ flags,\n in.c_str(), \/\/ source string data\n -1, \/\/ source string length (null-terminated)\n payload.get(), \/\/ output buffer\n wlen \/\/ output buffer size (in bytes)\n );\n if (!conv_success) {\n return windows_error_result(\"Unable to convert string to wide string\");\n }\n\n return ok_result(wstring(payload.get(), wlen - 1));\n}\n\ntemplate < class V >\nResult windows_error_result(const string &prefix)\n{\n return windows_error_result(prefix, GetLastError());\n}\n\ntemplate < class V >\nResult windows_error_result(const string &prefix, DWORD error_code)\n{\n LPVOID msg_buffer;\n\n FormatMessage(\n FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,\n NULL, \/\/ source\n error_code, \/\/ message ID\n MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), \/\/ language ID\n (LPSTR) &msg_buffer, \/\/ output buffer\n 0, \/\/ size\n NULL \/\/ arguments\n );\n\n ostringstream msg;\n msg << prefix << \"\\n (\" << error_code << \") \" << (char*) msg_buffer;\n LocalFree(msg_buffer);\n\n return Result::make_error(msg.str());\n}\n<|endoftext|>"} {"text":"\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(CODEWARRIORDEFS_HPP)\n#define CODEWARRIORDEFS_HPP\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Include some runtime files that will be needed product wide\n\/\/ ---------------------------------------------------------------------------\n#include \/\/ for size_t and ssize_t\n#include \/\/ for MAX of size_t and ssize_t\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ A define in the build for each project is also used to control whether\n\/\/ the export keyword is from the project's viewpoint or the client's.\n\/\/ These defines provide the platform specific keywords that they need\n\/\/ to do this.\n\/\/ ---------------------------------------------------------------------------\n#define PLATFORM_EXPORT\n#define PLATFORM_IMPORT\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Indicate that we do not support native bools\n\/\/ If the compiler can handle boolean itself, do not define it\n\/\/ ---------------------------------------------------------------------------\n\/\/ #define NO_NATIVE_BOOL\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Each compiler might support L\"\" prefixed constants. There are places\n\/\/ where it is advantageous to use the L\"\" where it supported, to avoid\n\/\/ unnecessary transcoding.\n\/\/ If your compiler does not support it, don't define this.\n\/\/ ---------------------------------------------------------------------------\n\/\/ #define XML_LSTRSUPPORT\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define our version of the XMLCh.\n\/\/ ---------------------------------------------------------------------------\ntypedef unsigned short XMLCh;\ntypedef unsigned short UTF16Ch;\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define unsigned 16 and 32 bits integers\n\/\/ ---------------------------------------------------------------------------\ntypedef unsigned short XMLUInt16;\ntypedef unsigned int XMLUInt32;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define signed 32 bits integers\n\/\/ ---------------------------------------------------------------------------\ntypedef int XMLInt32;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLSize_t is the unsigned integral type.\n\/\/ ---------------------------------------------------------------------------\n#if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX)\n typedef size_t XMLSize_t;\n #define XML_SIZE_MAX SIZE_MAX\n typedef ssize_t XMLSSize_t;\n #define XML_SSIZE_MAX SSIZE_MAX\n#else\n typedef unsigned long XMLSize_t;\n #define XML_SIZE_MAX ULONG_MAX\n typedef long XMLSSize_t;\n #define XML_SSIZE_MAX LONG_MAX\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Force on the Xerces debug token if it was on in the build environment\n\/\/ ---------------------------------------------------------------------------\n#ifdef _DEBUG\n#define XERCES_DEBUG\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Provide some common string ops that are different\/notavail for CodeWarrior.\n\/\/ ---------------------------------------------------------------------------\nint stricmp(const char* const str1, const char* const str2);\nint strnicmp(const char* const str1, const char* const str2, const unsigned int count);\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ The name of the DLL that is built by the Codewarrior version of the\n\/\/ system. We append a previously defined token which holds the DLL\n\/\/ versioning string. This is defined in XercesDefs.hpp which is what this\n\/\/ file is included into.\n\/\/ ---------------------------------------------------------------------------\nconst char* const Xerces_DLLName = \"xerces-c\" Xerces_DLLVersionStr;\n\n#endif \/\/CODEWARRIORDEFS_HPP\nTweak to build with Codewarrior 8.\/*\n * The Apache Software License, Version 1.1\n *\n * Copyright (c) 1999-2002 The Apache Software Foundation. All rights\n * reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * 3. The end-user documentation included with the redistribution,\n * if any, must include the following acknowledgment:\n * \"This product includes software developed by the\n * Apache Software Foundation (http:\/\/www.apache.org\/).\"\n * Alternately, this acknowledgment may appear in the software itself,\n * if and wherever such third-party acknowledgments normally appear.\n *\n * 4. The names \"Xerces\" and \"Apache Software Foundation\" must\n * not be used to endorse or promote products derived from this\n * software without prior written permission. For written\n * permission, please contact apache\\@apache.org.\n *\n * 5. Products derived from this software may not be called \"Apache\",\n * nor may \"Apache\" appear in their name, without prior written\n * permission of the Apache Software Foundation.\n *\n * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR\n * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF\n * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n * SUCH DAMAGE.\n * ====================================================================\n *\n * This software consists of voluntary contributions made by many\n * individuals on behalf of the Apache Software Foundation, and was\n * originally based on software copyright (c) 1999, International\n * Business Machines, Inc., http:\/\/www.ibm.com . For more information\n * on the Apache Software Foundation, please see\n * .\n *\/\n\n\/*\n * $Id$\n *\/\n\n#if !defined(CODEWARRIORDEFS_HPP)\n#define CODEWARRIORDEFS_HPP\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Include some runtime files that will be needed product wide\n\/\/ ---------------------------------------------------------------------------\n\/\/#include \/\/ for size_t and ssize_t\n\/\/#include \/\/ for MAX of size_t and ssize_t\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ A define in the build for each project is also used to control whether\n\/\/ the export keyword is from the project's viewpoint or the client's.\n\/\/ These defines provide the platform specific keywords that they need\n\/\/ to do this.\n\/\/ ---------------------------------------------------------------------------\n#define PLATFORM_EXPORT\n#define PLATFORM_IMPORT\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Indicate that we do not support native bools\n\/\/ If the compiler can handle boolean itself, do not define it\n\/\/ ---------------------------------------------------------------------------\n\/\/ #define NO_NATIVE_BOOL\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Each compiler might support L\"\" prefixed constants. There are places\n\/\/ where it is advantageous to use the L\"\" where it supported, to avoid\n\/\/ unnecessary transcoding.\n\/\/ If your compiler does not support it, don't define this.\n\/\/ ---------------------------------------------------------------------------\n\/\/ #define XML_LSTRSUPPORT\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define our version of the XMLCh.\n\/\/ ---------------------------------------------------------------------------\ntypedef unsigned short XMLCh;\ntypedef unsigned short UTF16Ch;\n\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define unsigned 16 and 32 bits integers\n\/\/ ---------------------------------------------------------------------------\ntypedef unsigned short XMLUInt16;\ntypedef unsigned int XMLUInt32;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Define signed 32 bits integers\n\/\/ ---------------------------------------------------------------------------\ntypedef int XMLInt32;\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ XMLSize_t is the unsigned integral type.\n\/\/ ---------------------------------------------------------------------------\n#if defined(_SIZE_T) && defined(SIZE_MAX) && defined(_SSIZE_T) && defined(SSIZE_MAX)\n typedef size_t XMLSize_t;\n #define XML_SIZE_MAX SIZE_MAX\n typedef ssize_t XMLSSize_t;\n #define XML_SSIZE_MAX SSIZE_MAX\n#else\n typedef unsigned long XMLSize_t;\n #define XML_SIZE_MAX ULONG_MAX\n typedef long XMLSSize_t;\n #define XML_SSIZE_MAX LONG_MAX\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Force on the Xerces debug token if it was on in the build environment\n\/\/ ---------------------------------------------------------------------------\n#ifdef _DEBUG\n#define XERCES_DEBUG\n#endif\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ Provide some common string ops that are different\/notavail for CodeWarrior.\n\/\/ ---------------------------------------------------------------------------\nint stricmp(const char* const str1, const char* const str2);\nint strnicmp(const char* const str1, const char* const str2, const unsigned int count);\n\n\/\/ ---------------------------------------------------------------------------\n\/\/ The name of the DLL that is built by the Codewarrior version of the\n\/\/ system. We append a previously defined token which holds the DLL\n\/\/ versioning string. This is defined in XercesDefs.hpp which is what this\n\/\/ file is included into.\n\/\/ ---------------------------------------------------------------------------\nconst char* const Xerces_DLLName = \"xerces-c\" Xerces_DLLVersionStr;\n\n#endif \/\/CODEWARRIORDEFS_HPP\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n\n#include \"vcl\/salbtype.hxx\"\n\n#include \"opengl\/texture.hxx\"\n\n\/\/ texture with allocated size\nImplOpenGLTexture::ImplOpenGLTexture( int nWidth, int nHeight, bool bAllocate ) :\n mnRefCount( 1 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n if( bAllocate )\n glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" allocate\" );\n\n CHECK_GL_ERROR();\n}\n\n\/\/ texture with content retrieved from FBO\nImplOpenGLTexture::ImplOpenGLTexture( int nX, int nY, int nWidth, int nHeight ) :\n mnRefCount( 1 ),\n mnTexture( 0 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n \/\/ FIXME We need the window height here\n \/\/ nY = GetHeight() - nHeight - nY;\n\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nX, nY, nWidth, nHeight, 0 );\n CHECK_GL_ERROR();\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" from x\" << nX << \", y\" << nY );\n\n CHECK_GL_ERROR();\n}\n\n\/\/ texture from buffer data\nImplOpenGLTexture::ImplOpenGLTexture( int nWidth, int nHeight, int nFormat, int nType, sal_uInt8* pData ) :\n mnRefCount( 1 ),\n mnTexture( 0 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n if( !mnTexture )\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, mnWidth, mnHeight, 0, nFormat, nType, pData );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" from data\" );\n\n CHECK_GL_ERROR();\n}\n\nImplOpenGLTexture::~ImplOpenGLTexture()\n{\n SAL_INFO( \"vcl.opengl\", \"~OpenGLTexture \" << mnTexture );\n if( mnTexture != 0 )\n glDeleteTextures( 1, &mnTexture );\n}\n\nOpenGLTexture::OpenGLTexture() :\n maRect( 0, 0, 0, 0 ),\n mpImpl( NULL )\n{\n}\n\nOpenGLTexture::OpenGLTexture( int nWidth, int nHeight, bool bAllocate ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nWidth, nHeight, bAllocate );\n}\n\nOpenGLTexture::OpenGLTexture( int nX, int nY, int nWidth, int nHeight ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nX, nY, nWidth, nHeight );\n}\n\nOpenGLTexture::OpenGLTexture( int nWidth, int nHeight, int nFormat, int nType, sal_uInt8* pData ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nWidth, nHeight, nFormat, nType, pData );\n}\n\nOpenGLTexture::OpenGLTexture( const OpenGLTexture& rTexture )\n{\n maRect = rTexture.maRect;\n mpImpl = rTexture.mpImpl;\n if( mpImpl )\n mpImpl->mnRefCount++;\n}\n\nOpenGLTexture::OpenGLTexture( const OpenGLTexture& rTexture,\n int nX, int nY, int nWidth, int nHeight )\n{\n maRect = Rectangle( Point( rTexture.maRect.Left() + nX, rTexture.maRect.Top() + nY ),\n Size( nWidth, nHeight ) );\n mpImpl = rTexture.mpImpl;\n if( mpImpl )\n mpImpl->mnRefCount++;\n SAL_INFO( \"vcl.opengl\", \"Copying texture \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n}\n\nOpenGLTexture::~OpenGLTexture()\n{\n if( mpImpl )\n {\n if( mpImpl->mnRefCount == 1 )\n delete mpImpl;\n else\n mpImpl->mnRefCount--;\n }\n}\n\nbool OpenGLTexture::IsUnique() const\n{\n return ( mpImpl == NULL || mpImpl->mnRefCount == 1 );\n}\n\nGLuint OpenGLTexture::Id() const\n{\n if( mpImpl )\n return mpImpl->mnTexture;\n return 0;\n}\n\nint OpenGLTexture::GetWidth() const\n{\n return maRect.GetWidth();\n}\n\nint OpenGLTexture::GetHeight() const\n{\n return maRect.GetHeight();\n}\n\nvoid OpenGLTexture::GetCoord( GLfloat* pCoord, const SalTwoRect& rPosAry, bool bInverted ) const\n{\n SAL_INFO( \"vcl.opengl\", \"Getting coord \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n pCoord[0] = pCoord[2] = (maRect.Left() + rPosAry.mnSrcX) \/ (double) mpImpl->mnWidth;\n pCoord[4] = pCoord[6] = (maRect.Left() + rPosAry.mnSrcX + rPosAry.mnSrcWidth) \/ (double) mpImpl->mnWidth;\n\n if( !bInverted )\n {\n pCoord[3] = pCoord[5] = 1.0f - (maRect.Top() + rPosAry.mnSrcY) \/ (double) mpImpl->mnHeight;\n pCoord[1] = pCoord[7] = 1.0f - (maRect.Top() + rPosAry.mnSrcY + rPosAry.mnSrcHeight) \/ (double) mpImpl->mnHeight;\n }\n else\n {\n pCoord[1] = pCoord[7] = 1.0f - (maRect.Top() + rPosAry.mnSrcY) \/ (double) mpImpl->mnHeight;\n pCoord[3] = pCoord[5] = 1.0f - (maRect.Top() + rPosAry.mnSrcY + rPosAry.mnSrcHeight) \/ (double) mpImpl->mnHeight;\n }\n}\n\nvoid OpenGLTexture::GetWholeCoord( GLfloat* pCoord ) const\n{\n if( GetWidth() != mpImpl->mnWidth || GetHeight() != mpImpl->mnHeight )\n {\n pCoord[0] = pCoord[2] = maRect.Left() \/ (double) mpImpl->mnWidth;\n pCoord[4] = pCoord[6] = maRect.Right() \/ (double) mpImpl->mnWidth;\n pCoord[3] = pCoord[5] = 1.0f - maRect.Top() \/ (double) mpImpl->mnHeight;\n pCoord[1] = pCoord[7] = 1.0f - maRect.Bottom() \/ (double) mpImpl->mnHeight;\n }\n else\n {\n pCoord[0] = pCoord[2] = 0;\n pCoord[4] = pCoord[6] = 1;\n pCoord[1] = pCoord[7] = 0;\n pCoord[3] = pCoord[5] = 1;\n }\n}\n\nGLenum OpenGLTexture::GetFilter() const\n{\n if( mpImpl )\n return mpImpl->mnFilter;\n return GL_NEAREST;\n}\n\nvoid OpenGLTexture::SetFilter( GLenum nFilter )\n{\n if( mpImpl )\n {\n mpImpl->mnFilter = nFilter;\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, nFilter );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, nFilter );\n }\n\n CHECK_GL_ERROR();\n}\n\nvoid OpenGLTexture::Bind()\n{\n if( mpImpl )\n glBindTexture( GL_TEXTURE_2D, mpImpl->mnTexture );\n\n CHECK_GL_ERROR();\n}\n\nvoid OpenGLTexture::Unbind()\n{\n if( mpImpl )\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n CHECK_GL_ERROR();\n}\n\nbool OpenGLTexture::Draw()\n{\n GLfloat aPosition[8] = { -1, -1, -1, 1, 1, 1, 1, -1 };\n GLfloat aTexCoord[8];\n\n if( mpImpl == NULL )\n {\n SAL_WARN( \"vcl.opengl\", \"Can't draw invalid texture\" );\n return false;\n }\n\n SAL_INFO( \"vcl.opengl\", \"Drawing texture \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n\n GetWholeCoord( aTexCoord );\n glActiveTexture( GL_TEXTURE0 );\n glBindTexture( GL_TEXTURE_2D, mpImpl->mnTexture );\n glEnableVertexAttribArray( 0 );\n glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 0, aPosition );\n glEnableVertexAttribArray( 1 );\n glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 0, aTexCoord );\n glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );\n glDisableVertexAttribArray( 0 );\n glDisableVertexAttribArray( 1 );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n CHECK_GL_ERROR();\n return true;\n}\n\nvoid OpenGLTexture::Read( GLenum nFormat, GLenum nType, sal_uInt8* pData )\n{\n if( mpImpl == NULL )\n {\n SAL_WARN( \"vcl.opengl\", \"Can't read invalid texture\" );\n return;\n }\n\n Bind();\n glPixelStorei( GL_PACK_ALIGNMENT, 1 );\n\n SAL_INFO( \"vcl.opengl\", \"Reading texture \" << Id() << \" \" << GetWidth() << \"x\" << GetHeight() );\n\n if( GetWidth() == mpImpl->mnWidth && GetHeight() == mpImpl->mnHeight )\n {\n \/\/ XXX: Call not available with GLES 2.0\n glGetTexImage( GL_TEXTURE_2D, 0, nFormat, nType, pData );\n }\n else\n {\n GLuint nFramebufferId;\n glGenFramebuffers( 1, &nFramebufferId );\n glBindFramebuffer( GL_FRAMEBUFFER, nFramebufferId );\n CHECK_GL_ERROR();\n\n glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Id(), 0 );\n CHECK_GL_ERROR();\n glReadPixels( maRect.Left(), mpImpl->mnHeight - maRect.Top(), GetWidth(), GetHeight(), nFormat, nType, pData );\n CHECK_GL_ERROR();\n\n glBindFramebuffer( GL_FRAMEBUFFER, 0 );\n glDeleteFramebuffers( 1, &nFramebufferId );\n\n int bpp = (nFormat == GL_RGB) ? 3 : 4;\n memset( pData, 255, GetWidth() * GetHeight() * bpp );\n }\n\n Unbind();\n CHECK_GL_ERROR();\n}\n\nOpenGLTexture::operator bool() const\n{\n return ( mpImpl != NULL );\n}\n\nOpenGLTexture& OpenGLTexture::operator=( const OpenGLTexture& rTexture )\n{\n if( rTexture.mpImpl )\n rTexture.mpImpl->mnRefCount++;\n if( mpImpl )\n {\n if( mpImpl->mnRefCount == 1 )\n delete mpImpl;\n else\n mpImpl->mnRefCount--;\n }\n\n maRect = rTexture.maRect;\n mpImpl = rTexture.mpImpl;\n\n return *this;\n}\n\nbool OpenGLTexture::operator==( const OpenGLTexture& rTexture ) const\n{\n return (mpImpl == rTexture.mpImpl && maRect == rTexture.maRect );\n}\n\nbool OpenGLTexture::operator!=( const OpenGLTexture& rTexture ) const\n{\n return !( *this == rTexture );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nvcl: Acquire framebuffer from current context when reading back texture\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * This file incorporates work covered by the following license notice:\n *\n * Licensed to the Apache Software Foundation (ASF) under one or more\n * contributor license agreements. See the NOTICE file distributed\n * with this work for additional information regarding copyright\n * ownership. The ASF licenses this file to you under the Apache\n * License, Version 2.0 (the \"License\"); you may not use this file\n * except in compliance with the License. You may obtain a copy of\n * the License at http:\/\/www.apache.org\/licenses\/LICENSE-2.0 .\n *\/\n\n#include \n#include \n#include \n\n#include \"svdata.hxx\"\n\n#include \"vcl\/salbtype.hxx\"\n\n#include \"opengl\/framebuffer.hxx\"\n#include \"opengl\/texture.hxx\"\n\n\/\/ texture with allocated size\nImplOpenGLTexture::ImplOpenGLTexture( int nWidth, int nHeight, bool bAllocate ) :\n mnRefCount( 1 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n if( bAllocate )\n glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nWidth, nHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" allocate\" );\n\n CHECK_GL_ERROR();\n}\n\n\/\/ texture with content retrieved from FBO\nImplOpenGLTexture::ImplOpenGLTexture( int nX, int nY, int nWidth, int nHeight ) :\n mnRefCount( 1 ),\n mnTexture( 0 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n \/\/ FIXME We need the window height here\n \/\/ nY = GetHeight() - nHeight - nY;\n\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n glCopyTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, nX, nY, nWidth, nHeight, 0 );\n CHECK_GL_ERROR();\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" from x\" << nX << \", y\" << nY );\n\n CHECK_GL_ERROR();\n}\n\n\/\/ texture from buffer data\nImplOpenGLTexture::ImplOpenGLTexture( int nWidth, int nHeight, int nFormat, int nType, sal_uInt8* pData ) :\n mnRefCount( 1 ),\n mnTexture( 0 ),\n mnWidth( nWidth ),\n mnHeight( nHeight ),\n mnFilter( GL_NEAREST )\n{\n if( !mnTexture )\n glGenTextures( 1, &mnTexture );\n glBindTexture( GL_TEXTURE_2D, mnTexture );\n glPixelStorei( GL_UNPACK_ALIGNMENT, 1 );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );\n glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, mnWidth, mnHeight, 0, nFormat, nType, pData );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n SAL_INFO( \"vcl.opengl\", \"OpenGLTexture \" << mnTexture << \" \" << nWidth << \"x\" << nHeight << \" from data\" );\n\n CHECK_GL_ERROR();\n}\n\nImplOpenGLTexture::~ImplOpenGLTexture()\n{\n SAL_INFO( \"vcl.opengl\", \"~OpenGLTexture \" << mnTexture );\n if( mnTexture != 0 )\n glDeleteTextures( 1, &mnTexture );\n}\n\nOpenGLTexture::OpenGLTexture() :\n maRect( 0, 0, 0, 0 ),\n mpImpl( NULL )\n{\n}\n\nOpenGLTexture::OpenGLTexture( int nWidth, int nHeight, bool bAllocate ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nWidth, nHeight, bAllocate );\n}\n\nOpenGLTexture::OpenGLTexture( int nX, int nY, int nWidth, int nHeight ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nX, nY, nWidth, nHeight );\n}\n\nOpenGLTexture::OpenGLTexture( int nWidth, int nHeight, int nFormat, int nType, sal_uInt8* pData ) :\n maRect( Point( 0, 0 ), Size( nWidth, nHeight ) )\n{\n mpImpl = new ImplOpenGLTexture( nWidth, nHeight, nFormat, nType, pData );\n}\n\nOpenGLTexture::OpenGLTexture( const OpenGLTexture& rTexture )\n{\n maRect = rTexture.maRect;\n mpImpl = rTexture.mpImpl;\n if( mpImpl )\n mpImpl->mnRefCount++;\n}\n\nOpenGLTexture::OpenGLTexture( const OpenGLTexture& rTexture,\n int nX, int nY, int nWidth, int nHeight )\n{\n maRect = Rectangle( Point( rTexture.maRect.Left() + nX, rTexture.maRect.Top() + nY ),\n Size( nWidth, nHeight ) );\n mpImpl = rTexture.mpImpl;\n if( mpImpl )\n mpImpl->mnRefCount++;\n SAL_INFO( \"vcl.opengl\", \"Copying texture \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n}\n\nOpenGLTexture::~OpenGLTexture()\n{\n if( mpImpl )\n {\n if( mpImpl->mnRefCount == 1 )\n delete mpImpl;\n else\n mpImpl->mnRefCount--;\n }\n}\n\nbool OpenGLTexture::IsUnique() const\n{\n return ( mpImpl == NULL || mpImpl->mnRefCount == 1 );\n}\n\nGLuint OpenGLTexture::Id() const\n{\n if( mpImpl )\n return mpImpl->mnTexture;\n return 0;\n}\n\nint OpenGLTexture::GetWidth() const\n{\n return maRect.GetWidth();\n}\n\nint OpenGLTexture::GetHeight() const\n{\n return maRect.GetHeight();\n}\n\nvoid OpenGLTexture::GetCoord( GLfloat* pCoord, const SalTwoRect& rPosAry, bool bInverted ) const\n{\n SAL_INFO( \"vcl.opengl\", \"Getting coord \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n pCoord[0] = pCoord[2] = (maRect.Left() + rPosAry.mnSrcX) \/ (double) mpImpl->mnWidth;\n pCoord[4] = pCoord[6] = (maRect.Left() + rPosAry.mnSrcX + rPosAry.mnSrcWidth) \/ (double) mpImpl->mnWidth;\n\n if( !bInverted )\n {\n pCoord[3] = pCoord[5] = 1.0f - (maRect.Top() + rPosAry.mnSrcY) \/ (double) mpImpl->mnHeight;\n pCoord[1] = pCoord[7] = 1.0f - (maRect.Top() + rPosAry.mnSrcY + rPosAry.mnSrcHeight) \/ (double) mpImpl->mnHeight;\n }\n else\n {\n pCoord[1] = pCoord[7] = 1.0f - (maRect.Top() + rPosAry.mnSrcY) \/ (double) mpImpl->mnHeight;\n pCoord[3] = pCoord[5] = 1.0f - (maRect.Top() + rPosAry.mnSrcY + rPosAry.mnSrcHeight) \/ (double) mpImpl->mnHeight;\n }\n}\n\nvoid OpenGLTexture::GetWholeCoord( GLfloat* pCoord ) const\n{\n if( GetWidth() != mpImpl->mnWidth || GetHeight() != mpImpl->mnHeight )\n {\n pCoord[0] = pCoord[2] = maRect.Left() \/ (double) mpImpl->mnWidth;\n pCoord[4] = pCoord[6] = maRect.Right() \/ (double) mpImpl->mnWidth;\n pCoord[3] = pCoord[5] = 1.0f - maRect.Top() \/ (double) mpImpl->mnHeight;\n pCoord[1] = pCoord[7] = 1.0f - maRect.Bottom() \/ (double) mpImpl->mnHeight;\n }\n else\n {\n pCoord[0] = pCoord[2] = 0;\n pCoord[4] = pCoord[6] = 1;\n pCoord[1] = pCoord[7] = 0;\n pCoord[3] = pCoord[5] = 1;\n }\n}\n\nGLenum OpenGLTexture::GetFilter() const\n{\n if( mpImpl )\n return mpImpl->mnFilter;\n return GL_NEAREST;\n}\n\nvoid OpenGLTexture::SetFilter( GLenum nFilter )\n{\n if( mpImpl )\n {\n mpImpl->mnFilter = nFilter;\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, nFilter );\n glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, nFilter );\n }\n\n CHECK_GL_ERROR();\n}\n\nvoid OpenGLTexture::Bind()\n{\n if( mpImpl )\n glBindTexture( GL_TEXTURE_2D, mpImpl->mnTexture );\n\n CHECK_GL_ERROR();\n}\n\nvoid OpenGLTexture::Unbind()\n{\n if( mpImpl )\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n CHECK_GL_ERROR();\n}\n\nbool OpenGLTexture::Draw()\n{\n GLfloat aPosition[8] = { -1, -1, -1, 1, 1, 1, 1, -1 };\n GLfloat aTexCoord[8];\n\n if( mpImpl == NULL )\n {\n SAL_WARN( \"vcl.opengl\", \"Can't draw invalid texture\" );\n return false;\n }\n\n SAL_INFO( \"vcl.opengl\", \"Drawing texture \" << Id() << \" [\" << maRect.Left() << \",\" << maRect.Top() << \"] \" << GetWidth() << \"x\" << GetHeight() );\n\n GetWholeCoord( aTexCoord );\n glActiveTexture( GL_TEXTURE0 );\n glBindTexture( GL_TEXTURE_2D, mpImpl->mnTexture );\n glEnableVertexAttribArray( 0 );\n glVertexAttribPointer( 0, 2, GL_FLOAT, GL_FALSE, 0, aPosition );\n glEnableVertexAttribArray( 1 );\n glVertexAttribPointer( 1, 2, GL_FLOAT, GL_FALSE, 0, aTexCoord );\n glDrawArrays( GL_TRIANGLE_FAN, 0, 4 );\n glDisableVertexAttribArray( 0 );\n glDisableVertexAttribArray( 1 );\n glBindTexture( GL_TEXTURE_2D, 0 );\n\n CHECK_GL_ERROR();\n return true;\n}\n\nvoid OpenGLTexture::Read( GLenum nFormat, GLenum nType, sal_uInt8* pData )\n{\n if( mpImpl == NULL )\n {\n SAL_WARN( \"vcl.opengl\", \"Can't read invalid texture\" );\n return;\n }\n\n Bind();\n glPixelStorei( GL_PACK_ALIGNMENT, 1 );\n\n SAL_INFO( \"vcl.opengl\", \"Reading texture \" << Id() << \" \" << GetWidth() << \"x\" << GetHeight() );\n\n if( GetWidth() == mpImpl->mnWidth && GetHeight() == mpImpl->mnHeight )\n {\n \/\/ XXX: Call not available with GLES 2.0\n glGetTexImage( GL_TEXTURE_2D, 0, nFormat, nType, pData );\n }\n else\n {\n \/\/ Retrieve current context\n ImplSVData* pSVData = ImplGetSVData();\n OpenGLContext* pContext = pSVData->maGDIData.mpLastContext;\n OpenGLFramebuffer* pFramebuffer;\n\n pFramebuffer = pContext->AcquireFramebuffer( *this );\n glReadPixels( maRect.Left(), mpImpl->mnHeight - maRect.Top(), GetWidth(), GetHeight(), nFormat, nType, pData );\n pContext->ReleaseFramebuffer( pFramebuffer );\n CHECK_GL_ERROR();\n }\n\n Unbind();\n CHECK_GL_ERROR();\n}\n\nOpenGLTexture::operator bool() const\n{\n return ( mpImpl != NULL );\n}\n\nOpenGLTexture& OpenGLTexture::operator=( const OpenGLTexture& rTexture )\n{\n if( rTexture.mpImpl )\n rTexture.mpImpl->mnRefCount++;\n if( mpImpl )\n {\n if( mpImpl->mnRefCount == 1 )\n delete mpImpl;\n else\n mpImpl->mnRefCount--;\n }\n\n maRect = rTexture.maRect;\n mpImpl = rTexture.mpImpl;\n\n return *this;\n}\n\nbool OpenGLTexture::operator==( const OpenGLTexture& rTexture ) const\n{\n return (mpImpl == rTexture.mpImpl && maRect == rTexture.maRect );\n}\n\nbool OpenGLTexture::operator!=( const OpenGLTexture& rTexture ) const\n{\n return !( *this == rTexture );\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/***************************************************************************\r\n * Copyright (c) 2011 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n\r\n#include \"PartFeatures.h\"\r\n\r\n\r\nusing namespace Part;\r\n\r\nPROPERTY_SOURCE(Part::RuledSurface, Part::Feature)\r\n\r\nRuledSurface::RuledSurface()\r\n{\r\n ADD_PROPERTY_TYPE(Curve1,(0),\"Ruled Surface\",App::Prop_None,\"Curve of ruled surface\");\r\n ADD_PROPERTY_TYPE(Curve2,(0),\"Ruled Surface\",App::Prop_None,\"Curve of ruled surface\");\r\n}\r\n\r\nshort RuledSurface::mustExecute() const\r\n{\r\n if (Curve1.isTouched())\r\n return 1;\r\n if (Curve2.isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nvoid RuledSurface::onChanged(const App::Property* prop)\r\n{\r\n Part::Feature::onChanged(prop);\r\n}\r\n\r\nApp::DocumentObjectExecReturn *RuledSurface::execute(void)\r\n{\r\n try {\r\n App::DocumentObject* c1 = Curve1.getValue();\r\n if (!(c1 && c1->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))\r\n return new App::DocumentObjectExecReturn(\"No shape linked.\");\r\n const std::vector& element1 = Curve1.getSubValues();\r\n if (element1.size() != 1)\r\n return new App::DocumentObjectExecReturn(\"Not exactly one sub-shape linked.\");\r\n App::DocumentObject* c2 = Curve2.getValue();\r\n if (!(c2 && c2->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))\r\n return new App::DocumentObjectExecReturn(\"No shape linked.\");\r\n const std::vector& element2 = Curve2.getSubValues();\r\n if (element2.size() != 1)\r\n return new App::DocumentObjectExecReturn(\"Not exactly one sub-shape linked.\");\r\n\r\n TopoDS_Shape curve1;\r\n const Part::TopoShape& shape1 = static_cast(c1)->Shape.getValue();\r\n if (!shape1._Shape.IsNull()) {\r\n if (shape1._Shape.ShapeType() == TopAbs_EDGE)\r\n curve1 = shape1._Shape;\r\n else\r\n curve1 = shape1.getSubShape(element1[0].c_str());\r\n }\r\n\r\n TopoDS_Shape curve2;\r\n const Part::TopoShape& shape2 = static_cast(c2)->Shape.getValue();\r\n if (!shape2._Shape.IsNull()) {\r\n if (shape2._Shape.ShapeType() == TopAbs_EDGE)\r\n curve2 = shape2._Shape;\r\n else\r\n curve2 = shape2.getSubShape(element2[0].c_str());\r\n }\r\n\r\n if (curve1.IsNull() || curve2.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Linked shapes are empty.\");\r\n if (curve1.ShapeType() == TopAbs_EDGE && curve2.ShapeType() == TopAbs_EDGE) {\r\n TopoDS_Face face = BRepFill::Face(TopoDS::Edge(curve1), TopoDS::Edge(curve2));\r\n this->Shape.setValue(face);\r\n }\r\n else if (curve1.ShapeType() == TopAbs_WIRE && curve2.ShapeType() == TopAbs_WIRE) {\r\n TopoDS_Shell shell = BRepFill::Shell(TopoDS::Wire(curve1), TopoDS::Wire(curve2));\r\n this->Shape.setValue(shell);\r\n }\r\n else {\r\n return new App::DocumentObjectExecReturn(\"Curves must either be edges or wires.\");\r\n }\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n catch (...) {\r\n return new App::DocumentObjectExecReturn(\"General error in RuledSurface::execute()\");\r\n }\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\n\r\nPROPERTY_SOURCE(Part::Loft, Part::Feature)\r\n\r\nLoft::Loft()\r\n{\r\n ADD_PROPERTY_TYPE(Sections,(0),\"Loft\",App::Prop_None,\"List of sections\");\r\n Sections.setSize(0);\r\n ADD_PROPERTY_TYPE(Solid,(false),\"Loft\",App::Prop_None,\"Create solid\");\r\n ADD_PROPERTY_TYPE(Ruled,(false),\"Loft\",App::Prop_None,\"Ruled surface\");\r\n}\r\n\r\nshort Loft::mustExecute() const\r\n{\r\n if (Sections.isTouched())\r\n return 1;\r\n if (Solid.isTouched())\r\n return 1;\r\n if (Ruled.isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nvoid Loft::onChanged(const App::Property* prop)\r\n{\r\n Part::Feature::onChanged(prop);\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Loft::execute(void)\r\n{\r\n if (Sections.getSize() == 0)\r\n return new App::DocumentObjectExecReturn(\"No sections linked.\");\r\n\r\n try {\r\n TopTools_ListOfShape profiles;\r\n const std::vector& shapes = Sections.getValues();\r\n std::vector::const_iterator it;\r\n for (it = shapes.begin(); it != shapes.end(); ++it) {\r\n if (!(*it)->isDerivedFrom(Part::Feature::getClassTypeId()))\r\n return new App::DocumentObjectExecReturn(\"Linked object is not a shape.\");\r\n const TopoDS_Shape& shape = static_cast(*it)->Shape.getValue();\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Linked shape is invalid.\");\r\n if (shape.ShapeType() == TopAbs_WIRE)\r\n profiles.Append(shape);\r\n else if (shape.ShapeType() == TopAbs_VERTEX)\r\n profiles.Append(shape);\r\n else\r\n return new App::DocumentObjectExecReturn(\"Linked shape is neither a vertex nor a wire.\");\r\n }\r\n\r\n Standard_Boolean isSolid = Solid.getValue() ? Standard_True : Standard_False;\r\n Standard_Boolean isRuled = Ruled.getValue() ? Standard_True : Standard_False;\r\n\r\n TopoShape myShape;\r\n this->Shape.setValue(myShape.makeLoft(profiles, isSolid, isRuled));\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n}\r\n0000649: Creating a ruled surface fails\/***************************************************************************\r\n * Copyright (c) 2011 Werner Mayer *\r\n * *\r\n * This file is part of the FreeCAD CAx development system. *\r\n * *\r\n * This library is free software; you can redistribute it and\/or *\r\n * modify it under the terms of the GNU Library General Public *\r\n * License as published by the Free Software Foundation; either *\r\n * version 2 of the License, or (at your option) any later version. *\r\n * *\r\n * This library is distributed in the hope that it will be useful, *\r\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\r\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *\r\n * GNU Library General Public License for more details. *\r\n * *\r\n * You should have received a copy of the GNU Library General Public *\r\n * License along with this library; see the file COPYING.LIB. If not, *\r\n * write to the Free Software Foundation, Inc., 59 Temple Place, *\r\n * Suite 330, Boston, MA 02111-1307, USA *\r\n * *\r\n ***************************************************************************\/\r\n\r\n\r\n#include \"PreCompiled.h\"\r\n#ifndef _PreComp_\r\n# include \r\n# include \r\n# include \r\n# include \r\n#endif\r\n\r\n\r\n#include \"PartFeatures.h\"\r\n\r\n\r\nusing namespace Part;\r\n\r\nPROPERTY_SOURCE(Part::RuledSurface, Part::Feature)\r\n\r\nRuledSurface::RuledSurface()\r\n{\r\n ADD_PROPERTY_TYPE(Curve1,(0),\"Ruled Surface\",App::Prop_None,\"Curve of ruled surface\");\r\n ADD_PROPERTY_TYPE(Curve2,(0),\"Ruled Surface\",App::Prop_None,\"Curve of ruled surface\");\r\n}\r\n\r\nshort RuledSurface::mustExecute() const\r\n{\r\n if (Curve1.isTouched())\r\n return 1;\r\n if (Curve2.isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nvoid RuledSurface::onChanged(const App::Property* prop)\r\n{\r\n Part::Feature::onChanged(prop);\r\n}\r\n\r\nApp::DocumentObjectExecReturn *RuledSurface::execute(void)\r\n{\r\n try {\r\n App::DocumentObject* c1 = Curve1.getValue();\r\n if (!(c1 && c1->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))\r\n return new App::DocumentObjectExecReturn(\"No shape linked.\");\r\n const std::vector& element1 = Curve1.getSubValues();\r\n if (element1.size() != 1)\r\n return new App::DocumentObjectExecReturn(\"Not exactly one sub-shape linked.\");\r\n App::DocumentObject* c2 = Curve2.getValue();\r\n if (!(c2 && c2->getTypeId().isDerivedFrom(Part::Feature::getClassTypeId())))\r\n return new App::DocumentObjectExecReturn(\"No shape linked.\");\r\n const std::vector& element2 = Curve2.getSubValues();\r\n if (element2.size() != 1)\r\n return new App::DocumentObjectExecReturn(\"Not exactly one sub-shape linked.\");\r\n\r\n TopoDS_Shape curve1;\r\n const Part::TopoShape& shape1 = static_cast(c1)->Shape.getValue();\r\n if (!shape1._Shape.IsNull()) {\r\n if (shape1._Shape.ShapeType() == TopAbs_EDGE)\r\n curve1 = shape1._Shape;\r\n else if (shape1._Shape.ShapeType() == TopAbs_WIRE)\r\n curve1 = shape1._Shape;\r\n else\r\n curve1 = shape1.getSubShape(element1[0].c_str());\r\n }\r\n\r\n TopoDS_Shape curve2;\r\n const Part::TopoShape& shape2 = static_cast(c2)->Shape.getValue();\r\n if (!shape2._Shape.IsNull()) {\r\n if (shape2._Shape.ShapeType() == TopAbs_EDGE)\r\n curve2 = shape2._Shape;\r\n else if (shape2._Shape.ShapeType() == TopAbs_WIRE)\r\n curve2 = shape2._Shape;\r\n else\r\n curve2 = shape2.getSubShape(element2[0].c_str());\r\n }\r\n\r\n if (curve1.IsNull() || curve2.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Linked shapes are empty.\");\r\n if (curve1.ShapeType() == TopAbs_EDGE && curve2.ShapeType() == TopAbs_EDGE) {\r\n TopoDS_Face face = BRepFill::Face(TopoDS::Edge(curve1), TopoDS::Edge(curve2));\r\n this->Shape.setValue(face);\r\n }\r\n else if (curve1.ShapeType() == TopAbs_WIRE && curve2.ShapeType() == TopAbs_WIRE) {\r\n TopoDS_Shell shell = BRepFill::Shell(TopoDS::Wire(curve1), TopoDS::Wire(curve2));\r\n this->Shape.setValue(shell);\r\n }\r\n else {\r\n return new App::DocumentObjectExecReturn(\"Curves must either be edges or wires.\");\r\n }\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n catch (...) {\r\n return new App::DocumentObjectExecReturn(\"General error in RuledSurface::execute()\");\r\n }\r\n}\r\n\r\n\/\/ ----------------------------------------------------------------------------\r\n\r\nPROPERTY_SOURCE(Part::Loft, Part::Feature)\r\n\r\nLoft::Loft()\r\n{\r\n ADD_PROPERTY_TYPE(Sections,(0),\"Loft\",App::Prop_None,\"List of sections\");\r\n Sections.setSize(0);\r\n ADD_PROPERTY_TYPE(Solid,(false),\"Loft\",App::Prop_None,\"Create solid\");\r\n ADD_PROPERTY_TYPE(Ruled,(false),\"Loft\",App::Prop_None,\"Ruled surface\");\r\n}\r\n\r\nshort Loft::mustExecute() const\r\n{\r\n if (Sections.isTouched())\r\n return 1;\r\n if (Solid.isTouched())\r\n return 1;\r\n if (Ruled.isTouched())\r\n return 1;\r\n return 0;\r\n}\r\n\r\nvoid Loft::onChanged(const App::Property* prop)\r\n{\r\n Part::Feature::onChanged(prop);\r\n}\r\n\r\nApp::DocumentObjectExecReturn *Loft::execute(void)\r\n{\r\n if (Sections.getSize() == 0)\r\n return new App::DocumentObjectExecReturn(\"No sections linked.\");\r\n\r\n try {\r\n TopTools_ListOfShape profiles;\r\n const std::vector& shapes = Sections.getValues();\r\n std::vector::const_iterator it;\r\n for (it = shapes.begin(); it != shapes.end(); ++it) {\r\n if (!(*it)->isDerivedFrom(Part::Feature::getClassTypeId()))\r\n return new App::DocumentObjectExecReturn(\"Linked object is not a shape.\");\r\n const TopoDS_Shape& shape = static_cast(*it)->Shape.getValue();\r\n if (shape.IsNull())\r\n return new App::DocumentObjectExecReturn(\"Linked shape is invalid.\");\r\n if (shape.ShapeType() == TopAbs_WIRE)\r\n profiles.Append(shape);\r\n else if (shape.ShapeType() == TopAbs_VERTEX)\r\n profiles.Append(shape);\r\n else\r\n return new App::DocumentObjectExecReturn(\"Linked shape is neither a vertex nor a wire.\");\r\n }\r\n\r\n Standard_Boolean isSolid = Solid.getValue() ? Standard_True : Standard_False;\r\n Standard_Boolean isRuled = Ruled.getValue() ? Standard_True : Standard_False;\r\n\r\n TopoShape myShape;\r\n this->Shape.setValue(myShape.makeLoft(profiles, isSolid, isRuled));\r\n return App::DocumentObject::StdReturn;\r\n }\r\n catch (Standard_Failure) {\r\n Handle_Standard_Failure e = Standard_Failure::Caught();\r\n return new App::DocumentObjectExecReturn(e->GetMessageString());\r\n }\r\n}\r\n<|endoftext|>"} {"text":"Vulkan: fix image layout validation error on Android.<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlnmspe.hxx,v $\n * $Revision: 1.20 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#define _XMLOFF_XMLNMSPE_HXX\n\n#include \n\n#define XML_NAMESPACE( prefix, key ) \\\nconst sal_uInt16 XML_NAMESPACE_##prefix = key; \\\nconst sal_uInt16 XML_NAMESPACE_##prefix##_IDX = key;\n\n#define XML_OLD_NAMESPACE( prefix, index ) \\\nconst sal_uInt16 XML_OLD_NAMESPACE_##prefix##_IDX = \\\n (_XML_OLD_NAMESPACE_BASE+index);\n\n\/\/ current namespaces\n\/\/ These namespaces have the same index in the namespace table as prefix used.\n\/\/ If a namespace is added, _XML_OLD_NAMESPACE_BASE has to be adjusted!\nXML_NAMESPACE( OFFICE, 0U )\nXML_NAMESPACE( STYLE, 1U )\nXML_NAMESPACE( TEXT , 2U )\nXML_NAMESPACE( TABLE, 3U )\nXML_NAMESPACE( DRAW , 4U )\nXML_NAMESPACE( FO , 5U )\nXML_NAMESPACE( XLINK, 6U )\nXML_NAMESPACE( DC , 7U )\nXML_NAMESPACE( META , 8U )\nXML_NAMESPACE( NUMBER, 9U )\nXML_NAMESPACE( PRESENTATION, 10U )\nXML_NAMESPACE( SVG, 11U )\nXML_NAMESPACE( CHART, 12U )\nXML_NAMESPACE( DR3D, 13U )\nXML_NAMESPACE( MATH, 14U )\nXML_NAMESPACE( FORM, 15U )\nXML_NAMESPACE( SCRIPT, 16U )\nXML_NAMESPACE( BLOCKLIST, 17U )\nXML_NAMESPACE( FRAMEWORK, 18U )\nXML_NAMESPACE( CONFIG, 19U )\nXML_NAMESPACE( OOO, 20U )\nXML_NAMESPACE( OOOW, 21U )\nXML_NAMESPACE( OOOC, 22U )\nXML_NAMESPACE( DOM, 23U )\nXML_NAMESPACE( TCD, 24U ) \/\/ text conversion dictionary\nXML_NAMESPACE( DB, 25U )\nXML_NAMESPACE( DLG, 26U )\nXML_NAMESPACE( XFORMS, 27U )\nXML_NAMESPACE( XSD, 28U )\nXML_NAMESPACE( XSI, 29U )\nXML_NAMESPACE( SMIL, 30U )\nXML_NAMESPACE( ANIMATION, 31U )\nXML_NAMESPACE( XML, 32U ) \/\/ TODO: This 'implicit' namespace is not yet used\nXML_NAMESPACE( REPORT, 33U )\nXML_NAMESPACE( OF, 34U ) \/\/ OpenFormula aka ODFF\n\n#define _XML_OLD_NAMESPACE_BASE 35U\n\n\/\/ namespaces used in the technical preview (SO 5.2)\nXML_OLD_NAMESPACE( FO, 0U )\nXML_OLD_NAMESPACE( XLINK, 1U )\n\nXML_OLD_NAMESPACE( OFFICE, 2U )\nXML_OLD_NAMESPACE( STYLE, 3U )\nXML_OLD_NAMESPACE( TEXT, 4U )\nXML_OLD_NAMESPACE( TABLE, 5U )\nXML_OLD_NAMESPACE( META, 6U )\n\n#endif \/\/ _XMLOFF_XMLNMSPE_HXX\nINTEGRATION: CWS odfmetadata (1.20.16); FILE MERGED 2008\/06\/19 17:02:38 mst 1.20.16.1: #i90620#: interface change: xmloff - xmloff\/inc\/xmlnmspe.hxx: + add namespace RDFA - xmloff\/source\/core\/nmspmap.cxx: + SvXMLNamespaceMap::GetQNameByKey(): handle the built-in XML namespace - xmloff\/inc\/xmloff\/xmltoken.hxx, xmloff\/source\/core\/xmltoken.cxx: + new namespaces: XML_N_XML, XML_N_RDFA + new token: XML_META_FIELD - xmloff\/inc\/xmloff\/xmlimp.hxx, xmloff\/source\/core\/xmlimp.cxx,: + new methods GetStreamPath(), SetXmlId() + SvXMLImport::_InitCtor(): add implicit namespace declaration for built-in \"xml\" prefix - xmloff\/inc\/xmloff\/xmlexp.hxx, xmloff\/source\/core\/xmlexp.cxx: + new methods GetStreamPath(), AddAttributeXmlId() + SvXMLExport::_InitCtor(): add namespace declaration for RDFA - xmloff\/inc\/xmloff\/txtimp.hxx, xmloff\/source\/text\/txtimp.cxx: + XMLTextPElemTokens: add tokens: XML_TOK_TEXT_META, XML_TOK_TEXT_META_FIELD + XMLTextPAttrTokens: add token XML_TOK_TEXT_P_XMLID + XMLTextListBlockAttrTokens: add token XML_TOK_TEXT_LIST_BLOCK_XMLID + InsertBookmarkStartRange(): add parameter XmlId + FindAndRemoveBookmarkStartRange(): add parameter XmlId\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: xmlnmspe.hxx,v $\n * $Revision: 1.21 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _XMLOFF_XMLNMSPE_HXX\n#define _XMLOFF_XMLNMSPE_HXX\n\n#include \n\n#define XML_NAMESPACE( prefix, key ) \\\nconst sal_uInt16 XML_NAMESPACE_##prefix = key; \\\nconst sal_uInt16 XML_NAMESPACE_##prefix##_IDX = key;\n\n#define XML_OLD_NAMESPACE( prefix, index ) \\\nconst sal_uInt16 XML_OLD_NAMESPACE_##prefix##_IDX = \\\n (_XML_OLD_NAMESPACE_BASE+index);\n\n\/\/ current namespaces\n\/\/ These namespaces have the same index in the namespace table as prefix used.\n\/\/ If a namespace is added, _XML_OLD_NAMESPACE_BASE has to be adjusted!\nXML_NAMESPACE( OFFICE, 0U )\nXML_NAMESPACE( STYLE, 1U )\nXML_NAMESPACE( TEXT , 2U )\nXML_NAMESPACE( TABLE, 3U )\nXML_NAMESPACE( DRAW , 4U )\nXML_NAMESPACE( FO , 5U )\nXML_NAMESPACE( XLINK, 6U )\nXML_NAMESPACE( DC , 7U )\nXML_NAMESPACE( META , 8U )\nXML_NAMESPACE( NUMBER, 9U )\nXML_NAMESPACE( PRESENTATION, 10U )\nXML_NAMESPACE( SVG, 11U )\nXML_NAMESPACE( CHART, 12U )\nXML_NAMESPACE( DR3D, 13U )\nXML_NAMESPACE( MATH, 14U )\nXML_NAMESPACE( FORM, 15U )\nXML_NAMESPACE( SCRIPT, 16U )\nXML_NAMESPACE( BLOCKLIST, 17U )\nXML_NAMESPACE( FRAMEWORK, 18U )\nXML_NAMESPACE( CONFIG, 19U )\nXML_NAMESPACE( OOO, 20U )\nXML_NAMESPACE( OOOW, 21U )\nXML_NAMESPACE( OOOC, 22U )\nXML_NAMESPACE( DOM, 23U )\nXML_NAMESPACE( TCD, 24U ) \/\/ text conversion dictionary\nXML_NAMESPACE( DB, 25U )\nXML_NAMESPACE( DLG, 26U )\nXML_NAMESPACE( XFORMS, 27U )\nXML_NAMESPACE( XSD, 28U )\nXML_NAMESPACE( XSI, 29U )\nXML_NAMESPACE( SMIL, 30U )\nXML_NAMESPACE( ANIMATION, 31U )\nXML_NAMESPACE( XML, 32U )\nXML_NAMESPACE( REPORT, 33U )\nXML_NAMESPACE( OF, 34U ) \/\/ OpenFormula aka ODFF\nXML_NAMESPACE( RDFA, 35U )\n\n#define _XML_OLD_NAMESPACE_BASE 36U\n\n\/\/ namespaces used in the technical preview (SO 5.2)\nXML_OLD_NAMESPACE( FO, 0U )\nXML_OLD_NAMESPACE( XLINK, 1U )\n\nXML_OLD_NAMESPACE( OFFICE, 2U )\nXML_OLD_NAMESPACE( STYLE, 3U )\nXML_OLD_NAMESPACE( TEXT, 4U )\nXML_OLD_NAMESPACE( TABLE, 5U )\nXML_OLD_NAMESPACE( META, 6U )\n\n#endif \/\/ _XMLOFF_XMLNMSPE_HXX\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"component.hxx\"\n\n#include \"bridges\/cpp_uno\/shared\/bridge.hxx\"\n\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"osl\/diagnose.h\"\n#include \"osl\/mutex.hxx\"\n#include \"osl\/time.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/unload.h\"\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"uno\/environment.h\"\n#include \"uno\/lbnames.h\"\n#include \"uno\/mapping.h\"\n#include \"cppu\/EnvDcp.hxx\"\n\nnamespace bridges { namespace cpp_uno { namespace shared {\n\nrtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;\n\n} } }\n\nnamespace {\n\n#if (defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__))\nstatic ::rtl::OUString * s_pStaticOidPart = 0;\n#endif\n\nconst ::rtl::OUString & SAL_CALL cppu_cppenv_getStaticOIdPart() SAL_THROW(())\n{\n#if ! ((defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__)))\n static ::rtl::OUString * s_pStaticOidPart = 0;\n#endif\n if (! s_pStaticOidPart)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (! s_pStaticOidPart)\n {\n ::rtl::OUStringBuffer aRet( 64 );\n aRet.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"];\") );\n \/\/ good guid\n sal_uInt8 ar[16];\n ::rtl_getGlobalProcessId( ar );\n for ( sal_Int32 i = 0; i < 16; ++i )\n {\n aRet.append( (sal_Int32)ar[i], 16 );\n }\n#if (defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__))\n s_pStaticOidPart = new ::rtl::OUString( aRet.makeStringAndClear() );\n#else\n static ::rtl::OUString s_aStaticOidPart(\n aRet.makeStringAndClear() );\n s_pStaticOidPart = &s_aStaticOidPart;\n#endif\n }\n }\n return *s_pStaticOidPart;\n}\n\n}\n\nextern \"C\" {\n\nstatic void s_stub_computeObjectIdentifier(va_list * pParam)\n SAL_THROW(())\n{\n uno_ExtEnvironment * pEnv = va_arg(*pParam, uno_ExtEnvironment *);\n rtl_uString ** ppOId = va_arg(*pParam, rtl_uString **);\n void * pInterface = va_arg(*pParam, void *);\n\n\n OSL_ENSURE( pEnv && ppOId && pInterface, \"### null ptr!\" );\n if (pEnv && ppOId && pInterface)\n {\n if (*ppOId)\n {\n rtl_uString_release( *ppOId );\n *ppOId = 0;\n }\n\n try\n {\n ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface > xHome(\n reinterpret_cast< ::com::sun::star::uno::XInterface * >(\n pInterface ),\n ::com::sun::star::uno::UNO_QUERY );\n OSL_ENSURE( xHome.is(), \"### query to XInterface failed!\" );\n if (xHome.is())\n {\n \/\/ interface\n ::rtl::OUStringBuffer oid( 64 );\n oid.append( reinterpret_cast< sal_Int64 >(xHome.get()), 16 );\n oid.append( (sal_Unicode)';' );\n \/\/ ;environment[context]\n oid.append(\n *reinterpret_cast< ::rtl::OUString const * >(\n &((uno_Environment *) pEnv)->pTypeName ) );\n oid.append( (sal_Unicode)'[' );\n oid.append(\n reinterpret_cast< sal_Int64 >(\n ((uno_Environment *)pEnv)->pContext),\n 16 );\n \/\/ ];good guid\n oid.append( cppu_cppenv_getStaticOIdPart() );\n ::rtl::OUString aRet( oid.makeStringAndClear() );\n ::rtl_uString_acquire( *ppOId = aRet.pData );\n }\n }\n catch (const ::com::sun::star::uno::RuntimeException &)\n {\n OSL_FAIL(\n \"### RuntimeException occurred during queryInterface()!\" );\n }\n }\n}\n\nstatic void SAL_CALL computeObjectIdentifier(\n uno_ExtEnvironment * pExtEnv, rtl_uString ** ppOId, void * pInterface )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_computeObjectIdentifier, pExtEnv, ppOId, pInterface);\n}\n\nstatic void s_stub_acquireInterface(va_list * pParam)\n SAL_THROW(())\n{\n \/*uno_ExtEnvironment * pExtEnv = *\/va_arg(*pParam, uno_ExtEnvironment *);\n void * pCppI = va_arg(*pParam, void *);\n\n reinterpret_cast< ::com::sun::star::uno::XInterface * >( pCppI )->acquire();\n}\n\nstatic void SAL_CALL acquireInterface( uno_ExtEnvironment * pExtEnv, void * pCppI )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_acquireInterface, pExtEnv, pCppI);\n}\n\nstatic void s_stub_releaseInterface(va_list * pParam)\n SAL_THROW(())\n{\n \/*uno_ExtEnvironment * pExtEnv = *\/va_arg(*pParam, uno_ExtEnvironment *);\n void * pCppI = va_arg(*pParam, void *);\n\n reinterpret_cast< ::com::sun::star::uno::XInterface * >( pCppI )->release();\n}\n\nstatic void SAL_CALL releaseInterface( uno_ExtEnvironment * pExtEnv, void * pCppI )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_releaseInterface, pExtEnv, pCppI);\n}\n\nstatic void SAL_CALL environmentDisposing(\n SAL_UNUSED_PARAMETER uno_Environment * ) SAL_THROW(())\n{\n bridges::cpp_uno::shared::g_moduleCount.modCnt.release(\n &bridges::cpp_uno::shared::g_moduleCount.modCnt );\n}\n\n#ifndef DISABLE_DYNLOADING\n\nSAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_canUnload(TimeValue * pTime) SAL_THROW_EXTERN_C() {\n return bridges::cpp_uno::shared::g_moduleCount.canUnload(\n &bridges::cpp_uno::shared::g_moduleCount, pTime);\n}\n\n#endif\n\n#ifdef DISABLE_DYNLOADING\n#define uno_initEnvironment CPPU_ENV_uno_initEnvironment\n#endif\n\nvoid SAL_CALL uno_initEnvironment(uno_Environment * pCppEnv)\n SAL_THROW_EXTERN_C()\n{\n OSL_ENSURE( pCppEnv->pExtEnv, \"### expected extended environment!\" );\n OSL_ENSURE(\n ::rtl_ustr_ascii_compare_WithLength(\n pCppEnv->pTypeName->buffer, rtl_str_getLength(CPPU_CURRENT_LANGUAGE_BINDING_NAME), CPPU_CURRENT_LANGUAGE_BINDING_NAME )\n == 0,\n \"### wrong environment type!\" );\n bridges::cpp_uno::shared::g_moduleCount.modCnt.acquire(\n &bridges::cpp_uno::shared::g_moduleCount.modCnt );\n ((uno_ExtEnvironment *)pCppEnv)->computeObjectIdentifier\n = computeObjectIdentifier;\n ((uno_ExtEnvironment *)pCppEnv)->acquireInterface = acquireInterface;\n ((uno_ExtEnvironment *)pCppEnv)->releaseInterface = releaseInterface;\n pCppEnv->environmentDisposing = environmentDisposing;\n}\n\n#ifdef DISABLE_DYNLOADING\n#define uno_ext_getMapping CPPU_ENV_uno_ext_getMapping\n#endif\n\nvoid SAL_CALL uno_ext_getMapping(\n uno_Mapping ** ppMapping, uno_Environment * pFrom, uno_Environment * pTo)\n SAL_THROW_EXTERN_C()\n{\n OSL_ASSERT( ppMapping && pFrom && pTo );\n if (ppMapping && pFrom && pTo && pFrom->pExtEnv && pTo->pExtEnv)\n {\n uno_Mapping * pMapping = 0;\n\n rtl::OUString from_envTypeName(cppu::EnvDcp::getTypeName(pFrom->pTypeName));\n rtl::OUString to_envTypeName(cppu::EnvDcp::getTypeName(pTo->pTypeName));\n\n if (0 == rtl_ustr_ascii_compare(\n from_envTypeName.pData->buffer,\n CPPU_CURRENT_LANGUAGE_BINDING_NAME ) &&\n 0 == rtl_ustr_ascii_compare(\n to_envTypeName.pData->buffer, UNO_LB_UNO ))\n {\n \/\/ ref count initially 1\n pMapping = bridges::cpp_uno::shared::Bridge::createMapping(\n pFrom->pExtEnv, pTo->pExtEnv, sal_True );\n ::uno_registerMapping(\n &pMapping, bridges::cpp_uno::shared::freeMapping,\n (uno_Environment *)pFrom->pExtEnv,\n (uno_Environment *)pTo->pExtEnv, 0 );\n }\n else if (0 == rtl_ustr_ascii_compare(\n to_envTypeName.pData->buffer,\n CPPU_CURRENT_LANGUAGE_BINDING_NAME ) &&\n 0 == rtl_ustr_ascii_compare(\n from_envTypeName.pData->buffer, UNO_LB_UNO ))\n {\n \/\/ ref count initially 1\n pMapping = bridges::cpp_uno::shared::Bridge::createMapping(\n pTo->pExtEnv, pFrom->pExtEnv, sal_False );\n ::uno_registerMapping(\n &pMapping, bridges::cpp_uno::shared::freeMapping,\n (uno_Environment *)pFrom->pExtEnv,\n (uno_Environment *)pTo->pExtEnv, 0 );\n }\n\n if (*ppMapping)\n {\n (*(*ppMapping)->release)( *ppMapping );\n }\n if (pMapping)\n *ppMapping = pMapping;\n }\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nadd missing exports\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"component.hxx\"\n\n#include \"bridges\/cpp_uno\/shared\/bridge.hxx\"\n\n#include \"com\/sun\/star\/uno\/Reference.hxx\"\n#include \"com\/sun\/star\/uno\/RuntimeException.hpp\"\n#include \"com\/sun\/star\/uno\/XInterface.hpp\"\n#include \"osl\/diagnose.h\"\n#include \"osl\/mutex.hxx\"\n#include \"osl\/time.h\"\n#include \"rtl\/process.h\"\n#include \"rtl\/unload.h\"\n#include \"rtl\/ustrbuf.hxx\"\n#include \"rtl\/ustring.h\"\n#include \"rtl\/ustring.hxx\"\n#include \"sal\/types.h\"\n#include \"uno\/environment.h\"\n#include \"uno\/lbnames.h\"\n#include \"uno\/mapping.h\"\n#include \"cppu\/EnvDcp.hxx\"\n\nnamespace bridges { namespace cpp_uno { namespace shared {\n\nrtl_StandardModuleCount g_moduleCount = MODULE_COUNT_INIT;\n\n} } }\n\nnamespace {\n\n#if (defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__))\nstatic ::rtl::OUString * s_pStaticOidPart = 0;\n#endif\n\nconst ::rtl::OUString & SAL_CALL cppu_cppenv_getStaticOIdPart() SAL_THROW(())\n{\n#if ! ((defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__)))\n static ::rtl::OUString * s_pStaticOidPart = 0;\n#endif\n if (! s_pStaticOidPart)\n {\n ::osl::MutexGuard aGuard( ::osl::Mutex::getGlobalMutex() );\n if (! s_pStaticOidPart)\n {\n ::rtl::OUStringBuffer aRet( 64 );\n aRet.appendAscii( RTL_CONSTASCII_STRINGPARAM(\"];\") );\n \/\/ good guid\n sal_uInt8 ar[16];\n ::rtl_getGlobalProcessId( ar );\n for ( sal_Int32 i = 0; i < 16; ++i )\n {\n aRet.append( (sal_Int32)ar[i], 16 );\n }\n#if (defined(__SUNPRO_CC) && (__SUNPRO_CC == 0x500)) \\\n || (defined(__GNUC__) && defined(__APPLE__))\n s_pStaticOidPart = new ::rtl::OUString( aRet.makeStringAndClear() );\n#else\n static ::rtl::OUString s_aStaticOidPart(\n aRet.makeStringAndClear() );\n s_pStaticOidPart = &s_aStaticOidPart;\n#endif\n }\n }\n return *s_pStaticOidPart;\n}\n\n}\n\nextern \"C\" {\n\nstatic void s_stub_computeObjectIdentifier(va_list * pParam)\n SAL_THROW(())\n{\n uno_ExtEnvironment * pEnv = va_arg(*pParam, uno_ExtEnvironment *);\n rtl_uString ** ppOId = va_arg(*pParam, rtl_uString **);\n void * pInterface = va_arg(*pParam, void *);\n\n\n OSL_ENSURE( pEnv && ppOId && pInterface, \"### null ptr!\" );\n if (pEnv && ppOId && pInterface)\n {\n if (*ppOId)\n {\n rtl_uString_release( *ppOId );\n *ppOId = 0;\n }\n\n try\n {\n ::com::sun::star::uno::Reference<\n ::com::sun::star::uno::XInterface > xHome(\n reinterpret_cast< ::com::sun::star::uno::XInterface * >(\n pInterface ),\n ::com::sun::star::uno::UNO_QUERY );\n OSL_ENSURE( xHome.is(), \"### query to XInterface failed!\" );\n if (xHome.is())\n {\n \/\/ interface\n ::rtl::OUStringBuffer oid( 64 );\n oid.append( reinterpret_cast< sal_Int64 >(xHome.get()), 16 );\n oid.append( (sal_Unicode)';' );\n \/\/ ;environment[context]\n oid.append(\n *reinterpret_cast< ::rtl::OUString const * >(\n &((uno_Environment *) pEnv)->pTypeName ) );\n oid.append( (sal_Unicode)'[' );\n oid.append(\n reinterpret_cast< sal_Int64 >(\n ((uno_Environment *)pEnv)->pContext),\n 16 );\n \/\/ ];good guid\n oid.append( cppu_cppenv_getStaticOIdPart() );\n ::rtl::OUString aRet( oid.makeStringAndClear() );\n ::rtl_uString_acquire( *ppOId = aRet.pData );\n }\n }\n catch (const ::com::sun::star::uno::RuntimeException &)\n {\n OSL_FAIL(\n \"### RuntimeException occurred during queryInterface()!\" );\n }\n }\n}\n\nstatic void SAL_CALL computeObjectIdentifier(\n uno_ExtEnvironment * pExtEnv, rtl_uString ** ppOId, void * pInterface )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_computeObjectIdentifier, pExtEnv, ppOId, pInterface);\n}\n\nstatic void s_stub_acquireInterface(va_list * pParam)\n SAL_THROW(())\n{\n \/*uno_ExtEnvironment * pExtEnv = *\/va_arg(*pParam, uno_ExtEnvironment *);\n void * pCppI = va_arg(*pParam, void *);\n\n reinterpret_cast< ::com::sun::star::uno::XInterface * >( pCppI )->acquire();\n}\n\nstatic void SAL_CALL acquireInterface( uno_ExtEnvironment * pExtEnv, void * pCppI )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_acquireInterface, pExtEnv, pCppI);\n}\n\nstatic void s_stub_releaseInterface(va_list * pParam)\n SAL_THROW(())\n{\n \/*uno_ExtEnvironment * pExtEnv = *\/va_arg(*pParam, uno_ExtEnvironment *);\n void * pCppI = va_arg(*pParam, void *);\n\n reinterpret_cast< ::com::sun::star::uno::XInterface * >( pCppI )->release();\n}\n\nstatic void SAL_CALL releaseInterface( uno_ExtEnvironment * pExtEnv, void * pCppI )\n SAL_THROW(())\n{\n uno_Environment_invoke(&pExtEnv->aBase, s_stub_releaseInterface, pExtEnv, pCppI);\n}\n\nstatic void SAL_CALL environmentDisposing(\n SAL_UNUSED_PARAMETER uno_Environment * ) SAL_THROW(())\n{\n bridges::cpp_uno::shared::g_moduleCount.modCnt.release(\n &bridges::cpp_uno::shared::g_moduleCount.modCnt );\n}\n\n#ifndef DISABLE_DYNLOADING\n\nSAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_canUnload(TimeValue * pTime) SAL_THROW_EXTERN_C() {\n return bridges::cpp_uno::shared::g_moduleCount.canUnload(\n &bridges::cpp_uno::shared::g_moduleCount, pTime);\n}\n\n#endif\n\n#ifdef DISABLE_DYNLOADING\n#define uno_initEnvironment CPPU_ENV_uno_initEnvironment\n#endif\n\nSAL_DLLPUBLIC_EXPORT void SAL_CALL uno_initEnvironment(uno_Environment * pCppEnv)\n SAL_THROW_EXTERN_C()\n{\n OSL_ENSURE( pCppEnv->pExtEnv, \"### expected extended environment!\" );\n OSL_ENSURE(\n ::rtl_ustr_ascii_compare_WithLength(\n pCppEnv->pTypeName->buffer, rtl_str_getLength(CPPU_CURRENT_LANGUAGE_BINDING_NAME), CPPU_CURRENT_LANGUAGE_BINDING_NAME )\n == 0,\n \"### wrong environment type!\" );\n bridges::cpp_uno::shared::g_moduleCount.modCnt.acquire(\n &bridges::cpp_uno::shared::g_moduleCount.modCnt );\n ((uno_ExtEnvironment *)pCppEnv)->computeObjectIdentifier\n = computeObjectIdentifier;\n ((uno_ExtEnvironment *)pCppEnv)->acquireInterface = acquireInterface;\n ((uno_ExtEnvironment *)pCppEnv)->releaseInterface = releaseInterface;\n pCppEnv->environmentDisposing = environmentDisposing;\n}\n\n#ifdef DISABLE_DYNLOADING\n#define uno_ext_getMapping CPPU_ENV_uno_ext_getMapping\n#endif\n\nSAL_DLLPUBLIC_EXPORT void SAL_CALL uno_ext_getMapping(\n uno_Mapping ** ppMapping, uno_Environment * pFrom, uno_Environment * pTo)\n SAL_THROW_EXTERN_C()\n{\n OSL_ASSERT( ppMapping && pFrom && pTo );\n if (ppMapping && pFrom && pTo && pFrom->pExtEnv && pTo->pExtEnv)\n {\n uno_Mapping * pMapping = 0;\n\n rtl::OUString from_envTypeName(cppu::EnvDcp::getTypeName(pFrom->pTypeName));\n rtl::OUString to_envTypeName(cppu::EnvDcp::getTypeName(pTo->pTypeName));\n\n if (0 == rtl_ustr_ascii_compare(\n from_envTypeName.pData->buffer,\n CPPU_CURRENT_LANGUAGE_BINDING_NAME ) &&\n 0 == rtl_ustr_ascii_compare(\n to_envTypeName.pData->buffer, UNO_LB_UNO ))\n {\n \/\/ ref count initially 1\n pMapping = bridges::cpp_uno::shared::Bridge::createMapping(\n pFrom->pExtEnv, pTo->pExtEnv, sal_True );\n ::uno_registerMapping(\n &pMapping, bridges::cpp_uno::shared::freeMapping,\n (uno_Environment *)pFrom->pExtEnv,\n (uno_Environment *)pTo->pExtEnv, 0 );\n }\n else if (0 == rtl_ustr_ascii_compare(\n to_envTypeName.pData->buffer,\n CPPU_CURRENT_LANGUAGE_BINDING_NAME ) &&\n 0 == rtl_ustr_ascii_compare(\n from_envTypeName.pData->buffer, UNO_LB_UNO ))\n {\n \/\/ ref count initially 1\n pMapping = bridges::cpp_uno::shared::Bridge::createMapping(\n pTo->pExtEnv, pFrom->pExtEnv, sal_False );\n ::uno_registerMapping(\n &pMapping, bridges::cpp_uno::shared::freeMapping,\n (uno_Environment *)pFrom->pExtEnv,\n (uno_Environment *)pTo->pExtEnv, 0 );\n }\n\n if (*ppMapping)\n {\n (*(*ppMapping)->release)( *ppMapping );\n }\n if (pMapping)\n *ppMapping = pMapping;\n }\n}\n\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/*\n * This file is part of the Electron Orbital Explorer. The Electron\n * Orbital Explorer is distributed under the Simplified BSD License\n * (also called the \"BSD 2-Clause License\"), in hopes that these\n * rendering techniques might be used by other programmers in\n * applications such as scientific visualization, video gaming, and so\n * on. If you find value in this software and use its technologies for\n * another purpose, I would love to hear back from you at bjthinks (at)\n * gmail (dot) com. If you improve this software and agree to release\n * your modifications under the below license, I encourage you to fork\n * the development tree on github and push your modifications. The\n * Electron Orbital Explorer's development URL is:\n * https:\/\/github.com\/bjthinks\/orbital-explorer\n * (This paragraph is not part of the software license and may be\n * removed.)\n *\n * Copyright (c) 2013, Brian W. Johnson\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * + Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * + Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef ARRAY_HH\n#define ARRAY_HH\n\n#include \n#include \n\n#include \"genericops.hh\"\n\ntemplate \nclass Array : public Equality >\n{\npublic:\n Array() {}\n\n \/\/ Array can be explicitly constructed from a scalar, but no corresponding\n \/\/ assignment operator is defined -- because derived classes have different\n \/\/ behavior when assigned a scalar.\n explicit Array(const T &x)\n {\n for (int i = 0; i < n; ++i)\n data[i] = x;\n }\n\n \/\/ A \"conversion constructor\" for explicitly turning arrays of one type\n \/\/ into another as long as the sizes are the same and the element type\n \/\/ is (explicitly or implicitly) convertible.\n \/\/ This is more type-safe than a conversion operator, which can't be\n \/\/ made explicit.\n template \n explicit Array(const Array &xs)\n {\n for (unsigned i=0; i toVector() const\n {\n std::vector r;\n for (int i = 0; i < n; ++i)\n r.push_back(data[i]);\n return r;\n }\n\n T &operator[](unsigned i)\n {\n check_index(i);\n return data[i];\n }\n const T &operator[](unsigned i) const\n {\n check_index(i);\n return data[i];\n }\n\n bool operator==(const Array &rhs) const\n {\n for (int i = 0; i < n; ++i)\n if (data[i] != rhs.data[i])\n return false;\n return true;\n }\n\nprotected:\n T &unsafe_element(unsigned i)\n {\n return data[i];\n }\n const T &unsafe_element(unsigned i) const\n {\n return data[i];\n }\n\nprivate:\n T data[n];\n\n void check_index(unsigned i) const\n {\n if (i >= n)\n throw_array_range_exception();\n }\n void throw_array_range_exception() const;\n};\n\ntemplate \nvoid Array::throw_array_range_exception() const\n{\n throw std::range_error(\"Array<> index out of range\");\n}\n\n#endif\nAvoid signed vs unsigned comparison warning\/*\n * This file is part of the Electron Orbital Explorer. The Electron\n * Orbital Explorer is distributed under the Simplified BSD License\n * (also called the \"BSD 2-Clause License\"), in hopes that these\n * rendering techniques might be used by other programmers in\n * applications such as scientific visualization, video gaming, and so\n * on. If you find value in this software and use its technologies for\n * another purpose, I would love to hear back from you at bjthinks (at)\n * gmail (dot) com. If you improve this software and agree to release\n * your modifications under the below license, I encourage you to fork\n * the development tree on github and push your modifications. The\n * Electron Orbital Explorer's development URL is:\n * https:\/\/github.com\/bjthinks\/orbital-explorer\n * (This paragraph is not part of the software license and may be\n * removed.)\n *\n * Copyright (c) 2013, Brian W. Johnson\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * + Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * + Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef ARRAY_HH\n#define ARRAY_HH\n\n#include \n#include \n\n#include \"genericops.hh\"\n\ntemplate \nclass Array : public Equality >\n{\npublic:\n Array() {}\n\n \/\/ Array can be explicitly constructed from a scalar, but no corresponding\n \/\/ assignment operator is defined -- because derived classes have different\n \/\/ behavior when assigned a scalar.\n explicit Array(const T &x)\n {\n for (unsigned i = 0; i < n; ++i)\n data[i] = x;\n }\n\n \/\/ A \"conversion constructor\" for explicitly turning arrays of one type\n \/\/ into another as long as the sizes are the same and the element type\n \/\/ is (explicitly or implicitly) convertible.\n \/\/ This is more type-safe than a conversion operator, which can't be\n \/\/ made explicit.\n template \n explicit Array(const Array &xs)\n {\n for (unsigned i=0; i toVector() const\n {\n std::vector r;\n for (int i = 0; i < n; ++i)\n r.push_back(data[i]);\n return r;\n }\n\n T &operator[](unsigned i)\n {\n check_index(i);\n return data[i];\n }\n const T &operator[](unsigned i) const\n {\n check_index(i);\n return data[i];\n }\n\n bool operator==(const Array &rhs) const\n {\n for (int i = 0; i < n; ++i)\n if (data[i] != rhs.data[i])\n return false;\n return true;\n }\n\nprotected:\n T &unsafe_element(unsigned i)\n {\n return data[i];\n }\n const T &unsafe_element(unsigned i) const\n {\n return data[i];\n }\n\nprivate:\n T data[n];\n\n void check_index(unsigned i) const\n {\n if (i >= n)\n throw_array_range_exception();\n }\n void throw_array_range_exception() const;\n};\n\ntemplate \nvoid Array::throw_array_range_exception() const\n{\n throw std::range_error(\"Array<> index out of range\");\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"FiberManagerMap.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace folly { namespace fibers {\n\nnamespace {\n\nclass EventBaseOnDestructionCallback : public EventBase::LoopCallback {\n public:\n explicit EventBaseOnDestructionCallback(EventBase& evb) : evb_(evb) {}\n void runLoopCallback() noexcept override;\n\n private:\n EventBase& evb_;\n};\n\nclass GlobalCache {\n public:\n static FiberManager& get(EventBase& evb, const FiberManager::Options& opts) {\n return instance().getImpl(evb, opts);\n }\n\n static std::unique_ptr erase(EventBase& evb) {\n return instance().eraseImpl(evb);\n }\n\n private:\n GlobalCache() {}\n\n \/\/ Leak this intentionally. During shutdown, we may call getFiberManager,\n \/\/ and want access to the fiber managers during that time.\n static GlobalCache& instance() {\n static auto ret = new GlobalCache();\n return *ret;\n }\n\n FiberManager& getImpl(EventBase& evb, const FiberManager::Options& opts) {\n std::lock_guard lg(mutex_);\n\n auto& fmPtrRef = map_[&evb];\n\n if (!fmPtrRef) {\n auto loopController = make_unique();\n loopController->attachEventBase(evb);\n evb.runOnDestruction(new EventBaseOnDestructionCallback(evb));\n\n fmPtrRef = make_unique(std::move(loopController), opts);\n }\n\n return *fmPtrRef;\n }\n\n std::unique_ptr eraseImpl(EventBase& evb) {\n std::lock_guard lg(mutex_);\n\n DCHECK_EQ(1, map_.count(&evb));\n\n auto ret = std::move(map_[&evb]);\n map_.erase(&evb);\n return ret;\n }\n\n std::mutex mutex_;\n std::unordered_map> map_;\n};\n\nconstexpr size_t kEraseListMaxSize = 64;\n\nclass ThreadLocalCache {\n public:\n static FiberManager& get(EventBase& evb, const FiberManager::Options& opts) {\n return instance()->getImpl(evb, opts);\n }\n\n static void erase(EventBase& evb) {\n for (auto& localInstance : instance().accessAllThreads()) {\n SYNCHRONIZED(info, localInstance.eraseInfo_) {\n if (info.eraseList.size() >= kEraseListMaxSize) {\n info.eraseAll = true;\n } else {\n info.eraseList.push_back(&evb);\n }\n localInstance.eraseRequested_ = true;\n }\n }\n }\n\n private:\n ThreadLocalCache() {}\n\n struct ThreadLocalCacheTag {};\n using ThreadThreadLocalCache = ThreadLocal;\n\n \/\/ Leak this intentionally. During shutdown, we may call getFiberManager,\n \/\/ and want access to the fiber managers during that time.\n static ThreadThreadLocalCache& instance() {\n static auto ret = new ThreadThreadLocalCache([]() { return new ThreadLocalCache(); });\n return *ret;\n }\n\n FiberManager& getImpl(EventBase& evb, const FiberManager::Options& opts) {\n eraseImpl();\n\n auto& fmPtrRef = map_[&evb];\n if (!fmPtrRef) {\n fmPtrRef = &GlobalCache::get(evb, opts);\n }\n\n DCHECK(fmPtrRef != nullptr);\n\n return *fmPtrRef;\n }\n\n void eraseImpl() {\n if (!eraseRequested_.load()) {\n return;\n }\n\n SYNCHRONIZED(info, eraseInfo_) {\n if (info.eraseAll) {\n map_.clear();\n } else {\n for (auto evbPtr : info.eraseList) {\n map_.erase(evbPtr);\n }\n }\n\n info.eraseList.clear();\n info.eraseAll = false;\n eraseRequested_ = false;\n }\n }\n\n std::unordered_map map_;\n std::atomic eraseRequested_{false};\n\n struct EraseInfo {\n bool eraseAll{false};\n std::vector eraseList;\n };\n\n folly::Synchronized eraseInfo_;\n};\n\nvoid EventBaseOnDestructionCallback::runLoopCallback() noexcept {\n auto fm = GlobalCache::erase(evb_);\n DCHECK(fm.get() != nullptr);\n ThreadLocalCache::erase(evb_);\n\n fm->loopUntilNoReady();\n\n delete this;\n}\n\n} \/\/ namespace\n\nFiberManager& getFiberManager(EventBase& evb,\n const FiberManager::Options& opts) {\n return ThreadLocalCache::get(evb, opts);\n}\n\n}}\nConvert Thrift1(2)RequestDispatcher::sendMessage()\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"FiberManagerMap.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace folly { namespace fibers {\n\nnamespace {\n\nclass EventBaseOnDestructionCallback : public EventBase::LoopCallback {\n public:\n explicit EventBaseOnDestructionCallback(EventBase& evb) : evb_(evb) {}\n void runLoopCallback() noexcept override;\n\n private:\n EventBase& evb_;\n};\n\nclass GlobalCache {\n public:\n static FiberManager& get(EventBase& evb, const FiberManager::Options& opts) {\n return instance().getImpl(evb, opts);\n }\n\n static std::unique_ptr erase(EventBase& evb) {\n return instance().eraseImpl(evb);\n }\n\n private:\n GlobalCache() {}\n\n \/\/ Leak this intentionally. During shutdown, we may call getFiberManager,\n \/\/ and want access to the fiber managers during that time.\n static GlobalCache& instance() {\n static auto ret = new GlobalCache();\n return *ret;\n }\n\n FiberManager& getImpl(EventBase& evb, const FiberManager::Options& opts) {\n std::lock_guard lg(mutex_);\n\n auto& fmPtrRef = map_[&evb];\n\n if (!fmPtrRef) {\n auto loopController = make_unique();\n loopController->attachEventBase(evb);\n evb.runOnDestruction(new EventBaseOnDestructionCallback(evb));\n\n fmPtrRef = make_unique(std::move(loopController), opts);\n }\n\n return *fmPtrRef;\n }\n\n std::unique_ptr eraseImpl(EventBase& evb) {\n std::lock_guard lg(mutex_);\n\n DCHECK_EQ(1, map_.count(&evb));\n\n auto ret = std::move(map_[&evb]);\n map_.erase(&evb);\n return ret;\n }\n\n std::mutex mutex_;\n std::unordered_map> map_;\n};\n\nconstexpr size_t kEraseListMaxSize = 64;\n\nclass ThreadLocalCache {\n public:\n static FiberManager& get(EventBase& evb, const FiberManager::Options& opts) {\n return instance()->getImpl(evb, opts);\n }\n\n static void erase(EventBase& evb) {\n for (auto& localInstance : instance().accessAllThreads()) {\n SYNCHRONIZED(info, localInstance.eraseInfo_) {\n if (info.eraseList.size() >= kEraseListMaxSize) {\n info.eraseAll = true;\n } else {\n info.eraseList.push_back(&evb);\n }\n localInstance.eraseRequested_ = true;\n }\n }\n }\n\n private:\n ThreadLocalCache() {}\n\n struct ThreadLocalCacheTag {};\n using ThreadThreadLocalCache = ThreadLocal;\n\n \/\/ Leak this intentionally. During shutdown, we may call getFiberManager,\n \/\/ and want access to the fiber managers during that time.\n static ThreadThreadLocalCache& instance() {\n static auto ret = new ThreadThreadLocalCache([]() { return new ThreadLocalCache(); });\n return *ret;\n }\n\n FiberManager& getImpl(EventBase& evb, const FiberManager::Options& opts) {\n eraseImpl();\n\n auto& fmPtrRef = map_[&evb];\n if (!fmPtrRef) {\n fmPtrRef = &GlobalCache::get(evb, opts);\n }\n\n DCHECK(fmPtrRef != nullptr);\n\n return *fmPtrRef;\n }\n\n void eraseImpl() {\n if (!eraseRequested_.load()) {\n return;\n }\n\n SYNCHRONIZED(info, eraseInfo_) {\n if (info.eraseAll) {\n map_.clear();\n } else {\n for (auto evbPtr : info.eraseList) {\n map_.erase(evbPtr);\n }\n }\n\n info.eraseList.clear();\n info.eraseAll = false;\n eraseRequested_ = false;\n }\n }\n\n std::unordered_map map_;\n std::atomic eraseRequested_{false};\n\n struct EraseInfo {\n bool eraseAll{false};\n std::vector eraseList;\n };\n\n folly::Synchronized eraseInfo_;\n};\n\nvoid EventBaseOnDestructionCallback::runLoopCallback() noexcept {\n auto fm = GlobalCache::erase(evb_);\n DCHECK(fm.get() != nullptr);\n ThreadLocalCache::erase(evb_);\n\n while (fm->hasTasks()) {\n evb_.loopOnce();\n }\n\n delete this;\n}\n\n} \/\/ namespace\n\nFiberManager& getFiberManager(EventBase& evb,\n const FiberManager::Options& opts) {\n return ThreadLocalCache::get(evb, opts);\n}\n\n}}\n<|endoftext|>"} {"text":"#include \"ReplayView.hpp\"\n\n#include \"..\/Game\/Replay.hpp\"\n#include \"..\/Game\/ParseError.hpp\"\n#include \"..\/Game\/GameReader.hpp\"\n#include \"..\/Game\/Players\/Placeholder.hpp\"\n\n#include \"..\/..\/app\/FourInALine.hpp\"\n#include \"..\/Settings\/Sound.hpp\"\n#include \"..\/Settings\/View.hpp\"\n#include \"..\/Settings\/FourInALine.hpp\"\n\n#include \"FileIO.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace GUI\n{\n\n\/**\n * Creates a new replay view.\n *\n * @param manager View manager to use.\n *\/\nReplayView::ReplayView(ViewManager* manager)\n : AbstractView(manager), currentMoveNo(0)\n{\n\tauto settings = ::FourInALine::getInstance()->getSettings();\n\tauto viewSettings = settings->getViewSettings();\n\n\tthis->widget = new Widgets::Board(viewSettings->getTheme(), 0);\n\n\tthis->updateThemeConnection = this->connect(viewSettings, &Settings::View::changed, [=]() {\n\t\tthis->widget->setTheme(viewSettings->getTheme());\n\t});\n\n\tauto application = ::FourInALine::getInstance();\n\tauto soundSettings = application->getSettings()->getSoundSettings();\n\n\tthis->connect(soundSettings, &::Settings::Sound::changed, this, &ReplayView::updateSoundSettings);\n\tthis->updateSoundSettings();\n}\n\n\/**\n * Frees all used resources.\n *\/\nReplayView::~ReplayView()\n{\n\tQObject::disconnect(this->updateThemeConnection);\n}\n\n\/**\n * Returns the central widget of this view.\n *\n * @return Widget for the view.\n *\/\nQWidget* ReplayView::getWidget() const\n{\n\treturn this->widget;\n}\n\n\/**\n * Returns whether there is a replay loaded or not.\n *\n * @return When a replay is loaded true, otherwise false.\n *\/\nbool ReplayView::hasReplay() const\n{\n\treturn !this->replay.isNull();\n}\n\n\/**\n * Returns whether the currently loaded replay has a next move or not.\n *\n * Returns false when no replay is loaded.\n *\n * @return When there is a next move true, otherwise false.\n *\/\nbool ReplayView::hasNextMove() const\n{\n\tif (this->hasReplay())\n\t{\n\t\treturn this->currentMoveNo + 1 < this->replay->getNumberOfMoves();\n\t}\n\n\treturn false;\n}\n\n\/**\n * Returns whether the currently loaded replay has a previous move or not.\n *\n * Returns false when no replay is loaded.\n *\n * @return When there is a previous move true, otherwise false.\n *\/\nbool ReplayView::hasPreviousMove() const\n{\n\tif (this->hasReplay())\n\t{\n\t\treturn this->currentMoveNo > 0;\n\t}\n\n\treturn false;\n}\n\n\/**\n * Does nothing and returns true.\n *\n * This method is called by the view manager before deactivating the view.\n *\n * @return When the view should be deactivated true, otherwise false.\n *\/\nbool ReplayView::confirmDeactivation()\n{\n\treturn true;\n}\n\n\/**\n * Shows a dialog asking the user to open a replay file, then opens the file and loads the replay.\n *\/\nvoid ReplayView::loadReplay()\n{\n\tQByteArray content;\n\tQString fileName;\n\tQString nameFilter = tr(\"Replays (*.replay)\");\n\n\tif (FileIO::GetExistingFileName(this->getWidget(), fileName, nameFilter) &&\n\t FileIO::GetFileContent(this->getWidget(), fileName, content) &&\n\t this->requestActivation())\n\t{\n\t\ttry\n\t\t{\n\t\t\tQBuffer buffer(&content);\n\t\t\tbuffer.open(QIODevice::ReadOnly);\n\t\t\t::Game::GameReader reader;\n\t\t\tauto loadedReplay = reader.readReplay(&buffer);\n\n\t\t\tif (loadedReplay->getNumberOfMoves() == 0)\n\t\t\t{\n\t\t\t\tthrow ::Game::ParseError(\"Empty replays are not supported.\");\n\t\t\t}\n\n\t\t\tthis->closeReplay();\n\t\t\tthis->replay = loadedReplay;\n\t\t\tthis->currentMoveNo = 0;\n\t\t\tthis->jumpToStart();\n\n\t\t\temit this->stateChanged();\n\t\t}\n\t\tcatch (const ::Game::ParseError& error)\n\t\t{\n\t\t\tQMessageBox::critical(this->getWidget(), tr(\"Failed to load replay\"),\n\t\t\t tr(\"Failed to load replay due to parse error: %1\").arg(error.what()));\n\t\t}\n\t}\n}\n\n\/**\n * Closes the currently open replay.\n *\n * Does nothing if no replay is opened.\n *\/\nvoid ReplayView::closeReplay()\n{\n\tif (this->hasReplay())\n\t{\n\t\tthis->replay.reset();\n\t\tthis->currentMoveNo = 0;\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Step to the next move.\n *\/\nvoid ReplayView::nextMove()\n{\n\tif (this->hasNextMove())\n\t{\n\t\tthis->currentMoveNo++;\n\n\t\tauto currentMove = this->replay->getMove(this->currentMoveNo);\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\t\tauto player = this->playerIdToPlayer(currentMove.first);\n\n\t\tthis->widget->startPlayerTurn(player);\n\t\tthis->widget->makeMove(position.first, position.second, player);\n\t\tthis->widget->endPlayerTurn();\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Step to the previous move.\n *\/\nvoid ReplayView::previousMove()\n{\n\tif (this->hasPreviousMove())\n\t{\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\n\t\tthis->widget->makeCellEmpty(position.first, position.second);\n\n\t\tthis->currentMoveNo--;\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Jump to the start of the replay.\n *\/\nvoid ReplayView::jumpToStart()\n{\n\tif (this->hasReplay())\n\t{\n\t\tthis->widget->startNewGame(this->replay->getNumberOfColumns(),\n\t\t this->replay->getNumberOfRows(),\n\t\t this->replay->getFirstPlayer(),\n\t\t this->replay->getSecondPlayer(),\n\t\t false);\n\n\t\tthis->currentMoveNo = 0;\n\n\t\tauto currentMove = this->replay->getMove(this->currentMoveNo);\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\t\tauto player = this->playerIdToPlayer(currentMove.first);\n\n\t\tthis->widget->startPlayerTurn(player);\n\t\tthis->widget->makeMove(position.first, position.second, player);\n\t\tthis->widget->endPlayerTurn();\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Jump to the end of the replay.\n *\/\nvoid ReplayView::jumpToEnd()\n{\n\twhile (this->hasNextMove())\n\t{\n\t\tthis->nextMove();\n\t}\n}\n\n\/**\n * Sets highlighted state for all cells.\n *\n * This method will set the winning cells to highlighted and all other cells\n * to not highlighted.\n *\/\nvoid ReplayView::highlightCells()\n{\n\tauto board = this->replay->computeBoard(this->currentMoveNo);\n\tauto winningCells = board.findWinningCells();\n\n\tfor (unsigned int y = 0; y < board.getNumberOfRows(); ++y)\n\t{\n\t\tfor (unsigned int x = 0; x < board.getNumberOfColumns(); ++x)\n\t\t{\n\t\t\tthis->widget->setCellHighlighted(x, y, false);\n\t\t}\n\t}\n\n\tif (!winningCells.isEmpty())\n\t{\n\t\tfor (auto i = winningCells.begin(); i != winningCells.end(); i++)\n\t\t{\n\t\t\tthis->widget->setCellHighlighted(i.getXPosition(), i.getYPosition(), true);\n\t\t}\n\t}\n}\n\n\/**\n * Returns the placeholder player for the given player id.\n *\n * @param playerId Player id as used in the game engine.\n * @return Placeholder player with the given id.\n *\/\nQSharedPointer< ::Game::Players::Placeholder> ReplayView::playerIdToPlayer(::GameLogic::FourInALine::Game::PlayerType playerId) const\n{\n\tif (playerId == ::GameLogic::FourInALine::Game::PLAYER_ONE)\n\t{\n\t\treturn this->replay->getFirstPlayer();\n\t}\n\telse\n\t{\n\t\treturn this->replay->getSecondPlayer();\n\t}\n}\n\n\/**\n * Reads sound settings from sound settings and updates game board.\n *\/\nvoid ReplayView::updateSoundSettings()\n{\n\tauto application = ::FourInALine::getInstance();\n\tauto soundSettings = application->getSettings()->getSoundSettings();\n\n\tthis->widget->setSoundMuted(!soundSettings->isSoundEnabled());\n\tthis->widget->setSoundVolume(soundSettings->getVolume());\n}\n\n}\nAdded missing delete.#include \"ReplayView.hpp\"\n\n#include \"..\/Game\/Replay.hpp\"\n#include \"..\/Game\/ParseError.hpp\"\n#include \"..\/Game\/GameReader.hpp\"\n#include \"..\/Game\/Players\/Placeholder.hpp\"\n\n#include \"..\/..\/app\/FourInALine.hpp\"\n#include \"..\/Settings\/Sound.hpp\"\n#include \"..\/Settings\/View.hpp\"\n#include \"..\/Settings\/FourInALine.hpp\"\n\n#include \"FileIO.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace GUI\n{\n\n\/**\n * Creates a new replay view.\n *\n * @param manager View manager to use.\n *\/\nReplayView::ReplayView(ViewManager* manager)\n : AbstractView(manager), currentMoveNo(0)\n{\n\tauto settings = ::FourInALine::getInstance()->getSettings();\n\tauto viewSettings = settings->getViewSettings();\n\n\tthis->widget = new Widgets::Board(viewSettings->getTheme(), 0);\n\n\tthis->updateThemeConnection = this->connect(viewSettings, &Settings::View::changed, [=]() {\n\t\tthis->widget->setTheme(viewSettings->getTheme());\n\t});\n\n\tauto application = ::FourInALine::getInstance();\n\tauto soundSettings = application->getSettings()->getSoundSettings();\n\n\tthis->connect(soundSettings, &::Settings::Sound::changed, this, &ReplayView::updateSoundSettings);\n\tthis->updateSoundSettings();\n}\n\n\/**\n * Frees all used resources.\n *\/\nReplayView::~ReplayView()\n{\n\tQObject::disconnect(this->updateThemeConnection);\n\tdelete this->widget;\n}\n\n\/**\n * Returns the central widget of this view.\n *\n * @return Widget for the view.\n *\/\nQWidget* ReplayView::getWidget() const\n{\n\treturn this->widget;\n}\n\n\/**\n * Returns whether there is a replay loaded or not.\n *\n * @return When a replay is loaded true, otherwise false.\n *\/\nbool ReplayView::hasReplay() const\n{\n\treturn !this->replay.isNull();\n}\n\n\/**\n * Returns whether the currently loaded replay has a next move or not.\n *\n * Returns false when no replay is loaded.\n *\n * @return When there is a next move true, otherwise false.\n *\/\nbool ReplayView::hasNextMove() const\n{\n\tif (this->hasReplay())\n\t{\n\t\treturn this->currentMoveNo + 1 < this->replay->getNumberOfMoves();\n\t}\n\n\treturn false;\n}\n\n\/**\n * Returns whether the currently loaded replay has a previous move or not.\n *\n * Returns false when no replay is loaded.\n *\n * @return When there is a previous move true, otherwise false.\n *\/\nbool ReplayView::hasPreviousMove() const\n{\n\tif (this->hasReplay())\n\t{\n\t\treturn this->currentMoveNo > 0;\n\t}\n\n\treturn false;\n}\n\n\/**\n * Does nothing and returns true.\n *\n * This method is called by the view manager before deactivating the view.\n *\n * @return When the view should be deactivated true, otherwise false.\n *\/\nbool ReplayView::confirmDeactivation()\n{\n\treturn true;\n}\n\n\/**\n * Shows a dialog asking the user to open a replay file, then opens the file and loads the replay.\n *\/\nvoid ReplayView::loadReplay()\n{\n\tQByteArray content;\n\tQString fileName;\n\tQString nameFilter = tr(\"Replays (*.replay)\");\n\n\tif (FileIO::GetExistingFileName(this->getWidget(), fileName, nameFilter) &&\n\t FileIO::GetFileContent(this->getWidget(), fileName, content) &&\n\t this->requestActivation())\n\t{\n\t\ttry\n\t\t{\n\t\t\tQBuffer buffer(&content);\n\t\t\tbuffer.open(QIODevice::ReadOnly);\n\t\t\t::Game::GameReader reader;\n\t\t\tauto loadedReplay = reader.readReplay(&buffer);\n\n\t\t\tif (loadedReplay->getNumberOfMoves() == 0)\n\t\t\t{\n\t\t\t\tthrow ::Game::ParseError(\"Empty replays are not supported.\");\n\t\t\t}\n\n\t\t\tthis->closeReplay();\n\t\t\tthis->replay = loadedReplay;\n\t\t\tthis->currentMoveNo = 0;\n\t\t\tthis->jumpToStart();\n\n\t\t\temit this->stateChanged();\n\t\t}\n\t\tcatch (const ::Game::ParseError& error)\n\t\t{\n\t\t\tQMessageBox::critical(this->getWidget(), tr(\"Failed to load replay\"),\n\t\t\t tr(\"Failed to load replay due to parse error: %1\").arg(error.what()));\n\t\t}\n\t}\n}\n\n\/**\n * Closes the currently open replay.\n *\n * Does nothing if no replay is opened.\n *\/\nvoid ReplayView::closeReplay()\n{\n\tif (this->hasReplay())\n\t{\n\t\tthis->replay.reset();\n\t\tthis->currentMoveNo = 0;\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Step to the next move.\n *\/\nvoid ReplayView::nextMove()\n{\n\tif (this->hasNextMove())\n\t{\n\t\tthis->currentMoveNo++;\n\n\t\tauto currentMove = this->replay->getMove(this->currentMoveNo);\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\t\tauto player = this->playerIdToPlayer(currentMove.first);\n\n\t\tthis->widget->startPlayerTurn(player);\n\t\tthis->widget->makeMove(position.first, position.second, player);\n\t\tthis->widget->endPlayerTurn();\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Step to the previous move.\n *\/\nvoid ReplayView::previousMove()\n{\n\tif (this->hasPreviousMove())\n\t{\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\n\t\tthis->widget->makeCellEmpty(position.first, position.second);\n\n\t\tthis->currentMoveNo--;\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Jump to the start of the replay.\n *\/\nvoid ReplayView::jumpToStart()\n{\n\tif (this->hasReplay())\n\t{\n\t\tthis->widget->startNewGame(this->replay->getNumberOfColumns(),\n\t\t this->replay->getNumberOfRows(),\n\t\t this->replay->getFirstPlayer(),\n\t\t this->replay->getSecondPlayer(),\n\t\t false);\n\n\t\tthis->currentMoveNo = 0;\n\n\t\tauto currentMove = this->replay->getMove(this->currentMoveNo);\n\t\tauto position = this->replay->computeMovePosition(this->currentMoveNo);\n\t\tauto player = this->playerIdToPlayer(currentMove.first);\n\n\t\tthis->widget->startPlayerTurn(player);\n\t\tthis->widget->makeMove(position.first, position.second, player);\n\t\tthis->widget->endPlayerTurn();\n\n\t\tthis->highlightCells();\n\n\t\temit this->stateChanged();\n\t}\n}\n\n\/**\n * Jump to the end of the replay.\n *\/\nvoid ReplayView::jumpToEnd()\n{\n\twhile (this->hasNextMove())\n\t{\n\t\tthis->nextMove();\n\t}\n}\n\n\/**\n * Sets highlighted state for all cells.\n *\n * This method will set the winning cells to highlighted and all other cells\n * to not highlighted.\n *\/\nvoid ReplayView::highlightCells()\n{\n\tauto board = this->replay->computeBoard(this->currentMoveNo);\n\tauto winningCells = board.findWinningCells();\n\n\tfor (unsigned int y = 0; y < board.getNumberOfRows(); ++y)\n\t{\n\t\tfor (unsigned int x = 0; x < board.getNumberOfColumns(); ++x)\n\t\t{\n\t\t\tthis->widget->setCellHighlighted(x, y, false);\n\t\t}\n\t}\n\n\tif (!winningCells.isEmpty())\n\t{\n\t\tfor (auto i = winningCells.begin(); i != winningCells.end(); i++)\n\t\t{\n\t\t\tthis->widget->setCellHighlighted(i.getXPosition(), i.getYPosition(), true);\n\t\t}\n\t}\n}\n\n\/**\n * Returns the placeholder player for the given player id.\n *\n * @param playerId Player id as used in the game engine.\n * @return Placeholder player with the given id.\n *\/\nQSharedPointer< ::Game::Players::Placeholder> ReplayView::playerIdToPlayer(::GameLogic::FourInALine::Game::PlayerType playerId) const\n{\n\tif (playerId == ::GameLogic::FourInALine::Game::PLAYER_ONE)\n\t{\n\t\treturn this->replay->getFirstPlayer();\n\t}\n\telse\n\t{\n\t\treturn this->replay->getSecondPlayer();\n\t}\n}\n\n\/**\n * Reads sound settings from sound settings and updates game board.\n *\/\nvoid ReplayView::updateSoundSettings()\n{\n\tauto application = ::FourInALine::getInstance();\n\tauto soundSettings = application->getSettings()->getSoundSettings();\n\n\tthis->widget->setSoundMuted(!soundSettings->isSoundEnabled());\n\tthis->widget->setSoundVolume(soundSettings->getVolume());\n}\n\n}\n<|endoftext|>"} {"text":"\n#include \"Globals.h\"\n#include \"FireworksSerializer.h\"\n#include \"WorldStorage\/FastNBT.h\"\n\n\n\n\n\nvoid cFireworkItem::WriteToNBTCompound(const cFireworkItem & a_FireworkItem, cFastNBTWriter & a_Writer, const ENUM_ITEM_ID a_Type)\n{\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Fireworks\");\n\t\t\ta_Writer.AddByte(\"Flight\", a_FireworkItem.m_FlightTimeInTicks \/ 20);\n\t\t\ta_Writer.BeginList(\"Explosions\", TAG_Compound);\n\t\t\ta_Writer.BeginCompound(\"\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\ta_Writer.AddIntArray(\"Colors\", a_FireworkItem.m_Colours.data(), a_FireworkItem.m_Colours.size());\n\t\t\ta_Writer.AddIntArray(\"FadeColors\", a_FireworkItem.m_FadeColours.data(), a_FireworkItem.m_FadeColours.size());\n\t\t\ta_Writer.EndCompound();\n\t\t\ta_Writer.EndList();\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Explosion\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\tif (!a_FireworkItem.m_Colours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"Colors\", a_FireworkItem.m_Colours.data(), a_FireworkItem.m_Colours.size());\n\t\t\t}\n\t\t\tif (!a_FireworkItem.m_FadeColours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"FadeColors\", a_FireworkItem.m_FadeColours.data(), a_FireworkItem.m_FadeColours.size());\n\t\t\t}\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nvoid cFireworkItem::ParseFromNBT(cFireworkItem & a_FireworkItem, const cParsedNBT & a_NBT, int a_TagIdx, const ENUM_ITEM_ID a_Type)\n{\n\tif (a_TagIdx < 0)\n\t{\n\t\treturn;\n\t}\n\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\tfor (int explosiontag = a_NBT.GetFirstChild(a_TagIdx); explosiontag >= 0; explosiontag = a_NBT.GetNextSibling(explosiontag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(explosiontag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Flicker\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasFlicker = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Trail\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasTrail = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Type\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_Type = a_NBT.GetByte(explosiontag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (TagType == TAG_IntArray)\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Colors\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Divide by four as data length returned in bytes\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst int * ColourData = (const int *)(a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_Colours.push_back(ntohl(ColourData[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"FadeColors\")\n\t\t\t\t\t{\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst int * FadeColourData = (const int *)(a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_FadeColours.push_back(ntohl(FadeColourData[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\tfor (int fireworkstag = a_NBT.GetFirstChild(a_TagIdx); fireworkstag >= 0; fireworkstag = a_NBT.GetNextSibling(fireworkstag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(fireworkstag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tif (a_NBT.GetName(fireworkstag) == \"Flight\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_FlightTimeInTicks = a_NBT.GetByte(fireworkstag) * 20;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ((TagType == TAG_List) && (a_NBT.GetName(fireworkstag) == \"Explosions\"))\n\t\t\t\t{\n\t\t\t\t\tint ExplosionsChild = a_NBT.GetFirstChild(fireworkstag);\n\t\t\t\t\tif ((a_NBT.GetType(ExplosionsChild) == TAG_Compound) && (a_NBT.GetName(ExplosionsChild).empty()))\n\t\t\t\t\t{\n\t\t\t\t\t\tParseFromNBT(a_FireworkItem, a_NBT, ExplosionsChild, E_ITEM_FIREWORK_STAR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::ColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector::const_iterator itr = a_FireworkItem.m_Colours.begin(); itr != a_FireworkItem.m_Colours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::ColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_Colours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::FadeColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector::const_iterator itr = a_FireworkItem.m_FadeColours.begin(); itr != a_FireworkItem.m_FadeColours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::FadeColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_FadeColours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nint cFireworkItem::GetVanillaColourCodeFromDye(short a_DyeMeta)\n{\n\t\/*\n\tColours are supposed to be calculated via: R << 16 + G << 8 + B\n\tHowever, the RGB values fireworks use aren't the same as the ones for dyes (the ones listed in the MC Wiki)\n\tTherefore, here is a list of numbers gotten via the Protocol Proxy\n\t*\/\n\n\tswitch (a_DyeMeta)\n\t{\n\t\tcase E_META_DYE_BLACK: return 0x1E1B1B;\n\t\tcase E_META_DYE_RED: return 0xB3312C;\n\t\tcase E_META_DYE_GREEN: return 0x3B511A;\n\t\tcase E_META_DYE_BROWN: return 0x51301A;\n\t\tcase E_META_DYE_BLUE: return 0x253192;\n\t\tcase E_META_DYE_PURPLE: return 0x7B2FBE;\n\t\tcase E_META_DYE_CYAN: return 0x287697;\n\t\tcase E_META_DYE_LIGHTGRAY: return 0xABABAB;\n\t\tcase E_META_DYE_GRAY: return 0x434343;\n\t\tcase E_META_DYE_PINK: return 0xD88198;\n\t\tcase E_META_DYE_LIGHTGREEN: return 0x41CD34;\n\t\tcase E_META_DYE_YELLOW: return 0xDECF2A;\n\t\tcase E_META_DYE_LIGHTBLUE: return 0x6689D3;\n\t\tcase E_META_DYE_MAGENTA: return 0xC354CD;\n\t\tcase E_META_DYE_ORANGE: return 0xEB8844;\n\t\tcase E_META_DYE_WHITE: return 0xF0F0F0;\n\t\tdefault: ASSERT(!\"Unhandled dye meta whilst trying to get colour code for fireworks!\"); return 0;\n\t}\n}\nFixed MSVC2008 compilation.\n#include \"Globals.h\"\n#include \"FireworksSerializer.h\"\n#include \"WorldStorage\/FastNBT.h\"\n\n\n\n\n\nvoid cFireworkItem::WriteToNBTCompound(const cFireworkItem & a_FireworkItem, cFastNBTWriter & a_Writer, const ENUM_ITEM_ID a_Type)\n{\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Fireworks\");\n\t\t\ta_Writer.AddByte(\"Flight\", a_FireworkItem.m_FlightTimeInTicks \/ 20);\n\t\t\ta_Writer.BeginList(\"Explosions\", TAG_Compound);\n\t\t\ta_Writer.BeginCompound(\"\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\ta_Writer.EndCompound();\n\t\t\ta_Writer.EndList();\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\ta_Writer.BeginCompound(\"Explosion\");\n\t\t\ta_Writer.AddByte(\"Flicker\", a_FireworkItem.m_HasFlicker);\n\t\t\ta_Writer.AddByte(\"Trail\", a_FireworkItem.m_HasTrail);\n\t\t\ta_Writer.AddByte(\"Type\", a_FireworkItem.m_Type);\n\t\t\tif (!a_FireworkItem.m_Colours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"Colors\", &(a_FireworkItem.m_Colours[0]), a_FireworkItem.m_Colours.size());\n\t\t\t}\n\t\t\tif (!a_FireworkItem.m_FadeColours.empty())\n\t\t\t{\n\t\t\t\ta_Writer.AddIntArray(\"FadeColors\", &(a_FireworkItem.m_FadeColours[0]), a_FireworkItem.m_FadeColours.size());\n\t\t\t}\n\t\t\ta_Writer.EndCompound();\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nvoid cFireworkItem::ParseFromNBT(cFireworkItem & a_FireworkItem, const cParsedNBT & a_NBT, int a_TagIdx, const ENUM_ITEM_ID a_Type)\n{\n\tif (a_TagIdx < 0)\n\t{\n\t\treturn;\n\t}\n\n\tswitch (a_Type)\n\t{\n\t\tcase E_ITEM_FIREWORK_STAR:\n\t\t{\n\t\t\tfor (int explosiontag = a_NBT.GetFirstChild(a_TagIdx); explosiontag >= 0; explosiontag = a_NBT.GetNextSibling(explosiontag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(explosiontag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Flicker\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasFlicker = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Trail\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_HasTrail = (a_NBT.GetByte(explosiontag) == 1);\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"Type\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_Type = a_NBT.GetByte(explosiontag);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if (TagType == TAG_IntArray)\n\t\t\t\t{\n\t\t\t\t\tAString ExplosionName = a_NBT.GetName(explosiontag);\n\n\t\t\t\t\tif (ExplosionName == \"Colors\")\n\t\t\t\t\t{\n\t\t\t\t\t\t\/\/ Divide by four as data length returned in bytes\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst int * ColourData = (const int *)(a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_Colours.push_back(ntohl(ColourData[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\telse if (ExplosionName == \"FadeColors\")\n\t\t\t\t\t{\n\t\t\t\t\t\tint DataLength = a_NBT.GetDataLength(explosiontag) \/ 4;\n\t\t\t\t\t\tif (DataLength == 0)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcontinue;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tconst int * FadeColourData = (const int *)(a_NBT.GetData(explosiontag));\n\t\t\t\t\t\tfor (int i = 0; i < DataLength; i++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\ta_FireworkItem.m_FadeColours.push_back(ntohl(FadeColourData[i]));\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tcase E_ITEM_FIREWORK_ROCKET:\n\t\t{\n\t\t\tfor (int fireworkstag = a_NBT.GetFirstChild(a_TagIdx); fireworkstag >= 0; fireworkstag = a_NBT.GetNextSibling(fireworkstag))\n\t\t\t{\n\t\t\t\teTagType TagType = a_NBT.GetType(fireworkstag);\n\t\t\t\tif (TagType == TAG_Byte) \/\/ Custon name tag\n\t\t\t\t{\n\t\t\t\t\tif (a_NBT.GetName(fireworkstag) == \"Flight\")\n\t\t\t\t\t{\n\t\t\t\t\t\ta_FireworkItem.m_FlightTimeInTicks = a_NBT.GetByte(fireworkstag) * 20;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse if ((TagType == TAG_List) && (a_NBT.GetName(fireworkstag) == \"Explosions\"))\n\t\t\t\t{\n\t\t\t\t\tint ExplosionsChild = a_NBT.GetFirstChild(fireworkstag);\n\t\t\t\t\tif ((a_NBT.GetType(ExplosionsChild) == TAG_Compound) && (a_NBT.GetName(ExplosionsChild).empty()))\n\t\t\t\t\t{\n\t\t\t\t\t\tParseFromNBT(a_FireworkItem, a_NBT, ExplosionsChild, E_ITEM_FIREWORK_STAR);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdefault: ASSERT(!\"Unhandled firework item!\"); break;\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::ColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector::const_iterator itr = a_FireworkItem.m_Colours.begin(); itr != a_FireworkItem.m_Colours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::ColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_Colours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nAString cFireworkItem::FadeColoursToString(const cFireworkItem & a_FireworkItem)\n{\n\tAString Result;\n\n\tfor (std::vector::const_iterator itr = a_FireworkItem.m_FadeColours.begin(); itr != a_FireworkItem.m_FadeColours.end(); ++itr)\n\t{\n\t\tAppendPrintf(Result, \"%i;\", *itr);\n\t}\n\n\treturn Result;\n}\n\n\n\n\n\nvoid cFireworkItem::FadeColoursFromString(const AString & a_String, cFireworkItem & a_FireworkItem)\n{\n\tAStringVector Split = StringSplit(a_String, \";\");\n\n\tfor (size_t itr = 0; itr < Split.size(); ++itr)\n\t{\n\t\tif (Split[itr].empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\n\t\ta_FireworkItem.m_FadeColours.push_back(atoi(Split[itr].c_str()));\n\t}\n}\n\n\n\n\n\nint cFireworkItem::GetVanillaColourCodeFromDye(short a_DyeMeta)\n{\n\t\/*\n\tColours are supposed to be calculated via: R << 16 + G << 8 + B\n\tHowever, the RGB values fireworks use aren't the same as the ones for dyes (the ones listed in the MC Wiki)\n\tTherefore, here is a list of numbers gotten via the Protocol Proxy\n\t*\/\n\n\tswitch (a_DyeMeta)\n\t{\n\t\tcase E_META_DYE_BLACK: return 0x1E1B1B;\n\t\tcase E_META_DYE_RED: return 0xB3312C;\n\t\tcase E_META_DYE_GREEN: return 0x3B511A;\n\t\tcase E_META_DYE_BROWN: return 0x51301A;\n\t\tcase E_META_DYE_BLUE: return 0x253192;\n\t\tcase E_META_DYE_PURPLE: return 0x7B2FBE;\n\t\tcase E_META_DYE_CYAN: return 0x287697;\n\t\tcase E_META_DYE_LIGHTGRAY: return 0xABABAB;\n\t\tcase E_META_DYE_GRAY: return 0x434343;\n\t\tcase E_META_DYE_PINK: return 0xD88198;\n\t\tcase E_META_DYE_LIGHTGREEN: return 0x41CD34;\n\t\tcase E_META_DYE_YELLOW: return 0xDECF2A;\n\t\tcase E_META_DYE_LIGHTBLUE: return 0x6689D3;\n\t\tcase E_META_DYE_MAGENTA: return 0xC354CD;\n\t\tcase E_META_DYE_ORANGE: return 0xEB8844;\n\t\tcase E_META_DYE_WHITE: return 0xF0F0F0;\n\t\tdefault: ASSERT(!\"Unhandled dye meta whilst trying to get colour code for fireworks!\"); return 0;\n\t}\n}\n<|endoftext|>"} {"text":"#include \"scenemanager.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"glload\/gl_3_2.h\"\n#include \n\n#include \"scenegroup.hpp\"\n#include \"perspectivecamera.hpp\"\n\n#include \"render\/lightmanager.hpp\"\n\n#include \"collisiondetection\/collidable.hpp\"\n#include \"collisiondetection\/objectorientedboundingbox.hpp\"\n\n#include \"config\/globals.hpp\"\n\nusing namespace scene;\n\nSceneManager::SceneManager()\n: world(3, collisiondetection::AABB(std::make_tuple(glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3(10.0f, 10.0f, -50.0f)))),\nrunning(false){\n}\n\nvoid SceneManager::startSceneLoop() {\n\tscene::PerspectiveCamera& camera = scene::PerspectiveCamera::getInstance();\n\n\trunning = true;\n\n\tstd::thread updateThread([this, &camera]() {\n\t\twhile(running) {\n\t\t\tuniversalGravity.update();\n\n\t\t\tworld.visitScene([](std::shared_ptr child) {\n\t\t\t\tchild->update();\n\n\t\t\t\tchild->buildModelMatrix();\n\t\t\t});\n\n\t\t\tworld.visitGroups([](SceneGroup& group) {\n\t\t\t\tfor (std::shared_ptr& child : group.childItems) {\n\t\t\t\t\tauto collidable = std::dynamic_pointer_cast(child);\n\n\t\t\t\t\tif(collidable.get() != nullptr) {\n\t\t\t\t\t\tfor (std::shared_ptr& other : group.childItems) {\n\t\t\t\t\t\t\tif(other != child) {\n\t\t\t\t\t\t\t\t\/\/TODO Collidables should always have a copy of their bounds\n\n\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& collidableBounds = child->getBounds();\n\t\t\t\t\t\t\t\tcollidableBounds.attachToItem(child.get());\n\n\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& otherBounds = other->getBounds();\n\t\t\t\t\t\t\t\totherBounds.attachToItem(other.get());\n\n\t\t\t\t\t\t\t\tif(collidableBounds.intersects(otherBounds)) {\n\t\t\t\t\t\t\t\t\tcollidable->handleCollision(*other);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif(group.childGroups != nullptr) {\n\t\t\t\t\t\t\t\/\/Check underlying groups for edge cases\n\t\t\t\t\t\t\tfor(SceneGroup& childGroup : *group.childGroups) {\n\t\t\t\t\t\t\t\tfor (std::shared_ptr& other : childGroup.childItems) {\n\t\t\t\t\t\t\t\t\tif(other != child) {\n\t\t\t\t\t\t\t\t\t\t\/\/TODO Collidables should always have a copy of their bounds\n\n\t\t\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& collidableBounds = child->getBounds();\n\t\t\t\t\t\t\t\t\t\tcollidableBounds.attachToItem(child.get());\n\n\t\t\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& otherBounds = other->getBounds();\n\t\t\t\t\t\t\t\t\t\totherBounds.attachToItem(other.get());\n\n\t\t\t\t\t\t\t\t\t\tif(collidableBounds.intersects(otherBounds)) {\n\t\t\t\t\t\t\t\t\t\t\tcollidable->handleCollision(*other);\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tworld.visitGroups([](SceneGroup& group) {\n\t\t\t\tif(group.constraints != nullptr) {\n\t\t\t\t\tauto it = group.childItems.begin();\n\t\t\t\t\twhile(it != group.childItems.end()) {\n\t\t\t\t\t\tconst collisiondetection::BoundingVolume& otherBounds = (*it)->getBounds();\n\t\t\t\t\t\totherBounds.attachToItem((*it).get());\n\n\t\t\t\t\t\tif(!otherBounds.intersects(*(group.constraints))) {\n\t\t\t\t\t\t\tstd::lock_guard guard(group.rootNode->sceneMutex);\n\n\t\t\t\t\t\t\tgroup.rootNode->bubbleItem(*it);\n\t\t\t\t\t\t\tit = group.childItems.erase(it);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t++it;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f\/config::globals::updateRate)*1000));\n\t\t}\n\t});\n\n\twhile(running) {\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n\n\t\trender::LightManager::getInstance().upload();\n\t\tcamera.render(&world);\n\n\t\tglfwSwapBuffers();\n\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f\/config::globals::frameRate)*1000));\n\t}\n\n\tupdateThread.join();\n}\n\nvoid SceneManager::stopSceneLoop() {\n\trunning = false;\n}\n\nvoid SceneManager::addItem(std::shared_ptr item) {\n\tGravitationalObject* gravObject = dynamic_cast(item.get());\n\tif(gravObject != nullptr) {\n\t\tuniversalGravity.addObject(gravObject);\n\t}\n\n\tstd::lock_guard guard(world.rootNode->sceneMutex);\n\tworld.bubbleItem(item);\n}\nBroad phase collisions: Check parents for edge cases#include \"scenemanager.hpp\"\n\n#include \n#include \n#include \n#include \n\n#include \"glload\/gl_3_2.h\"\n#include \n\n#include \"scenegroup.hpp\"\n#include \"perspectivecamera.hpp\"\n\n#include \"render\/lightmanager.hpp\"\n\n#include \"collisiondetection\/collidable.hpp\"\n#include \"collisiondetection\/objectorientedboundingbox.hpp\"\n\n#include \"config\/globals.hpp\"\n\nusing namespace scene;\n\nSceneManager::SceneManager()\n: world(3, collisiondetection::AABB(std::make_tuple(glm::vec3(-10.0f, -10.0f, 10.0f), glm::vec3(10.0f, 10.0f, -50.0f)))),\nrunning(false){\n}\n\nvoid SceneManager::startSceneLoop() {\n\tscene::PerspectiveCamera& camera = scene::PerspectiveCamera::getInstance();\n\n\trunning = true;\n\n\tstd::thread updateThread([this, &camera]() {\n\t\twhile(running) {\n\t\t\tuniversalGravity.update();\n\n\t\t\tworld.visitScene([](std::shared_ptr child) {\n\t\t\t\tchild->update();\n\n\t\t\t\tchild->buildModelMatrix();\n\t\t\t});\n\n\t\t\tworld.visitGroups([](SceneGroup& group) {\n\t\t\t\tfor (std::shared_ptr& child : group.childItems) {\n\t\t\t\t\tauto collidable = std::dynamic_pointer_cast(child);\n\n\t\t\t\t\tif(collidable.get() != nullptr) {\n\t\t\t\t\t\tstd::function collisionCheck = [collidable, child](const SceneGroup& group) {\n\t\t\t\t\t\t\tfor(const std::shared_ptr& other : group.childItems) {\n\t\t\t\t\t\t\t\t\/\/TODO Collidables should always have a copy of their bounds\n\n\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& collidableBounds = child->getBounds();\n\t\t\t\t\t\t\t\tcollidableBounds.attachToItem(child.get());\n\n\t\t\t\t\t\t\t\tconst collisiondetection::BoundingVolume& otherBounds = other->getBounds();\n\t\t\t\t\t\t\t\totherBounds.attachToItem(other.get());\n\n\t\t\t\t\t\t\t\tif(collidableBounds.intersects(otherBounds)) {\n\t\t\t\t\t\t\t\t\tcollidable->handleCollision(*other);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t};\n\n\t\t\t\t\t\tcollisionCheck(group);\n\n\t\t\t\t\t\tif(group.childGroups != nullptr) {\n\t\t\t\t\t\t\t\/\/Check underlying groups for lower edge cases\n\t\t\t\t\t\t\tfor(SceneGroup& childGroup : *group.childGroups) {\n\t\t\t\t\t\t\t\tcollisionCheck(childGroup);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/Check with parents for upper edge cases\n\t\t\t\t\t\tgroup.visitParentGroups(collisionCheck);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tworld.visitGroups([](SceneGroup& group) {\n\t\t\t\tif(group.constraints != nullptr) {\n\t\t\t\t\tauto it = group.childItems.begin();\n\t\t\t\t\twhile(it != group.childItems.end()) {\n\t\t\t\t\t\tconst collisiondetection::BoundingVolume& otherBounds = (*it)->getBounds();\n\t\t\t\t\t\totherBounds.attachToItem((*it).get());\n\n\t\t\t\t\t\tif(!otherBounds.intersects(*(group.constraints))) {\n\t\t\t\t\t\t\tstd::lock_guard guard(group.rootNode->sceneMutex);\n\n\t\t\t\t\t\t\tgroup.rootNode->bubbleItem(*it);\n\t\t\t\t\t\t\tit = group.childItems.erase(it);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t++it;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tstd::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f\/config::globals::updateRate)*1000));\n\t\t}\n\t});\n\n\twhile(running) {\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);\n\n\t\trender::LightManager::getInstance().upload();\n\t\tcamera.render(&world);\n\n\t\tglfwSwapBuffers();\n\n\t\tstd::this_thread::sleep_for(std::chrono::milliseconds((unsigned int)(1.0f\/config::globals::frameRate)*1000));\n\t}\n\n\tupdateThread.join();\n}\n\nvoid SceneManager::stopSceneLoop() {\n\trunning = false;\n}\n\nvoid SceneManager::addItem(std::shared_ptr item) {\n\tGravitationalObject* gravObject = dynamic_cast(item.get());\n\tif(gravObject != nullptr) {\n\t\tuniversalGravity.addObject(gravObject);\n\t}\n\n\tstd::lock_guard guard(world.rootNode->sceneMutex);\n\tworld.bubbleItem(item);\n}\n<|endoftext|>"} {"text":"beginning work on pointers\/************************************************************\nCOSC 501\nElliott Plack\n19 NOV 2013 Due 25 NOV 2013\nProblem: Create a 1-dimensional array with n elements; get\nthe size of the array as user input (validate!), max size\nshould be 10 (declared as class constant). Perform a\nvariety of functions with the array.\nAlgorithm: Get array size from user, validate, get values,\nperform functions.\n************************************************************\/\n\n#include \nusing namespace std;\n\n\n\nint main()\n{\nchar runQuestion = 'Y';\nint arraySize = 0;\nconst int maxArraySize = 10;\n\ncout << \"Do you want to start(Y\/N): \";\ncin >> runQuestion;\n\nwhile (runQuestion == 'Y' || runQuestion == 'y')\n{\n\t\/\/ declare array with pointers\n\tstruct node\n\t{\n\t\tdouble data;\n\t\tnode *next;\n\t};\n\n\tnode *q = new node;\n\tnode *head;\n\thead = q;\n\tq->data = maxArraySize; \/\/ assume the list contains 10 numbers\n\n\t\/\/ fill array\n\tfor (int i = 0; i < maxArraySize; i++)\n\t{\n\t\tnode *p = new node;\n\t\twhile (!(cin >> p->data)) \/\/ error check\n\t\t{\n\t\t\tcin.clear(); \/\/ Clear the error flags\n\t\t\tcin.ignore(100, '\\n'); \/\/ Remove unwanted characters from buffer\n\t\t\tcout << \"\\aInvalid entry. Enter a number: \"; \/\/ Re-issue the prompt\n\t\t}\n\t\tq->next = p;\n\t\tq = p;\n\n\t\t}\n\n\t\/\/ print\n\tcout << \"The array elements are: \";\n\n\tfor (int i = 0; i < arraySize; i++)\n\t{\n\tcout << q->data;\n\tq = q->next;\n\t}\n\n\n\tcout << \"Do you want to continue(Y\/N): \";\n\tcin >> runQuestion;\n\t}\n\n\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Platform-independent Ogg Vorbis\/Theora\/Opus decoder\/player base\n\/\/\n\/\/ Copyright (c) 2013-2015 Brion Vibber \n\/\/ MIT-style license\n\/\/ Please reuse and redistribute with the LICENSE notes intact.\n\/\/\n\n\/\/ C++11\n#include \n#include \n#include \n\n\/\/ good ol' C library\n#include \n#include \n#include \n#include \n\n\/\/ And our own headers.\n#include \n#include \"Bisector.h\"\n\nnamespace OGVCore {\n\n#pragma mark - Declarations\n\n class Player::impl {\n public:\n\n impl(std::shared_ptr aDelegate);\n ~impl();\n\n void load();\n void process();\n\n double getDuration();\n double getVideoWidth();\n double getVideoHeight();\n\n std::string getSourceURL();\n void setSourceURL(std::string aUrl);\n\n double getCurrentTime();\n void setCurrentTime(double aTime);\n\n bool getPaused();\n void setPaused(bool aPaused);\n\n bool getPlaying();\n bool getSeeking();\n\n private:\n std::shared_ptr delegate;\n std::shared_ptr timer;\n std::shared_ptr frameSink;\n std::shared_ptr audioFeeder;\n\n std::shared_ptr stream;\n long byteLength;\n double duration;\n\n\n class StreamDelegate : public StreamFile::Delegate {\n public:\n Player::impl *owner;\n \n StreamDelegate(Player::impl *aOwner) :\n owner(aOwner)\n {}\n\n virtual void onStart()\n {\n \/\/ Fire off the read\/decode\/draw loop...\n owner->byteLength = owner->stream->bytesTotal();\n \n \/\/ If we get X-Content-Duration, that's as good as an explicit hint\n auto durationHeader = owner->stream->getResponseHeader(\"X-Content-Duration\");\n if (durationHeader.length() > 0) {\n owner->duration = std::atof(durationHeader.c_str());\n }\n owner->startProcessingVideo();\n }\n \n virtual void onBuffer()\n {}\n \n virtual void onRead(std::vector data)\n {\n \/\/ Pass chunk into the codec's buffer\n owner->codec->receiveInput(data);\n\n \/\/ Continue the read\/decode\/draw loop...\n owner->pingProcessing();\n }\n \n virtual void onDone()\n {\n if (owner->state == STATE_SEEKING) {\n owner->pingProcessing();\n } else if (owner->state == STATE_SEEKING_END) {\n owner->pingProcessing();\n } else {\n \/\/throw new Error('wtf is this');\n owner->stream.reset();\n \n \/\/ Let the read\/decode\/draw loop know we're out!\n owner->pingProcessing();\n }\n }\n \n virtual void onError(std::string err)\n {\n std::cout << \"reading error: \" << err;\n }\n };\n\n enum {\n STATE_INITIAL,\n STATE_SEEKING_END,\n STATE_LOADED,\n STATE_PLAYING,\n STATE_PAUSED,\n STATE_SEEKING,\n STATE_ENDED\n } state = STATE_INITIAL;\n\n std::unique_ptr codec;\n \n double lastFrameTimestamp = 0.0;\n double frameEndTimestamp = 0.0;\n std::shared_ptr yCbCrBuffer = NULL;\n\n void processFrame();\n void drawFrame();\n void doFrameComplete();\n \n bool started = false;\n\n \/\/ Seeking\n enum {\n SEEKSTATE_NOT_SEEKING,\n SEEKSTATE_BISECT_TO_TARGET,\n SEEKSTATE_BISECT_TO_KEYPOINT,\n SEEKSTATE_LINEAR_TO_TARGET\n } seekState = SEEKSTATE_NOT_SEEKING;\n\n double seekTargetTime = 0.0;\n double seekTargetKeypoint = 0.0;\n double bisectTargetTime = 0.0;\n long lastSeekPosition = 0.0;\n bool lastFrameSkipped;\n std::unique_ptr seekBisector;\n\n void startBisection(double targetTime);\n void seek(double toTime);\n void continueSeekedPlayback();\n void doProcessLinearSeeking();\n void doProcessBisectionSeek();\n\n \/\/ Main stuff!\n void doProcessing();\n void pingProcessing(double delay = -1.0);\n void startProcessingVideo();\n };\n\n#pragma mark - Player pimpl bounce methods\n\n Player::Player(std::shared_ptr aDelegate):\n pimpl(new impl(aDelegate))\n {}\n\n Player::~Player()\n {}\n\n void Player::load()\n {\n pimpl->load();\n }\n\n void Player::process()\n {\n pimpl->process();\n }\n\n double Player::getDuration()\n {\n return pimpl->getDuration();\n }\n\n double Player::getVideoWidth()\n {\n return pimpl->getVideoWidth();\n }\n\n double Player::getVideoHeight()\n {\n return pimpl->getVideoHeight();\n }\n\n std::string Player::getSourceURL()\n {\n return pimpl->getSourceURL();\n }\n\n void Player::setSourceURL(std::string aUrl)\n {\n pimpl->setSourceURL(aUrl);\n }\n\n double Player::getCurrentTime()\n {\n return pimpl->getCurrentTime();\n }\n\n void Player::setCurrentTime(double aTime)\n {\n pimpl->setCurrentTime(aTime);\n }\n\n bool Player::getPaused()\n {\n return pimpl->getPaused();\n }\n\n void Player::setPaused(bool aPaused)\n {\n return pimpl->setPaused(aPaused);\n }\n\n bool Player::getPlaying()\n {\n return pimpl->getPlaying();\n }\n\n bool Player::getSeeking()\n {\n return pimpl->getSeeking();\n }\n\n#pragma mark - impl methods\n\n Player::impl::impl(std::shared_ptr aDelegate):\n delegate(aDelegate),\n timer(delegate->timer())\n {\n }\n\n Player::impl::~impl()\n {\n }\n\n void Player::impl::load()\n {\n if (stream.get() != NULL) {\n\t\t\t\/\/ already loaded.\n\t\t\treturn;\n }\n\n\t\tstarted = false;\n\t\tstream = delegate->streamFile(getSourceURL(), std::shared_ptr(new StreamDelegate(this)));\n\t}\n\n void Player::impl::process()\n {\n \/\/ TODO\n }\n\n double Player::impl::getDuration()\n {\n return NAN; \/\/ TODO\n }\n\n double Player::impl::getVideoWidth()\n {\n return NAN; \/\/ TODO\n }\n\n double Player::impl::getVideoHeight()\n {\n return NAN; \/\/ TODO\n }\n\n std::string Player::impl::getSourceURL()\n {\n return NULL;\n }\n\n void Player::impl::setSourceURL(std::string aUrl)\n {\n \/\/ TODO\n }\n\n double Player::impl::getCurrentTime()\n {\n return NAN; \/\/ TODO\n }\n\n void Player::impl::setCurrentTime(double aTime)\n {\n \/\/ TODO\n }\n\n bool Player::impl::getPaused()\n {\n return false; \/\/ TODO\n }\n\n void Player::impl::setPaused(bool aPaused)\n {\n \/\/ TODO\n }\n\n bool Player::impl::getPlaying()\n {\n return false; \/\/ TODO\n }\n\n bool Player::impl::getSeeking()\n {\n return false; \/\/ TODO\n }\n\n\n void Player::impl::processFrame()\n {\n yCbCrBuffer = codec->dequeueFrame();\n frameEndTimestamp = yCbCrBuffer->timestamp;\n }\n\n void Player::impl::drawFrame()\n {\n frameSink->drawFrame(yCbCrBuffer);\n doFrameComplete();\n }\n\n void Player::impl::doFrameComplete()\n {\n lastFrameTimestamp = timer->getTimestamp();\n }\n\n void Player::impl::startBisection(double targetTime)\n {\n\t\tbisectTargetTime = targetTime;\n\t\tseekBisector.reset(new Bisector(\n\t\t\t\/* start *\/ 0,\n\t\t\t\/* end *\/ byteLength - 1,\n\t\t\t\/* process *\/ [this] (int start, int end, int position) {\n\t\t\t\tif (position == lastSeekPosition) {\n\t\t\t\t\treturn false;\n\t\t\t\t} else {\n\t\t\t\t\tlastSeekPosition = position;\n\t\t\t\t\tlastFrameSkipped = false;\n\t\t\t\t\tcodec->flush();\n\t\t\t\t\tstream->seek(position);\n\t\t\t\t\tstream->readBytes();\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t));\n\t\tseekBisector->start();\n }\n\n void Player::impl::seek(double toTime)\n {\n }\n\n void Player::impl::continueSeekedPlayback()\n {\n }\n\n void Player::impl::doProcessLinearSeeking()\n {\n }\n\n void Player::impl::doProcessBisectionSeek()\n {\n }\n\n void Player::impl::doProcessing()\n {\n }\n\n void Player::impl::pingProcessing(double delay)\n {\n }\n\n void Player::impl::startProcessingVideo()\n {\n }\n\n}\nhey this is nicer\/\/\n\/\/ Platform-independent Ogg Vorbis\/Theora\/Opus decoder\/player base\n\/\/\n\/\/ Copyright (c) 2013-2015 Brion Vibber \n\/\/ MIT-style license\n\/\/ Please reuse and redistribute with the LICENSE notes intact.\n\/\/\n\n\/\/ C++11\n#include \n#include \n#include \n\n\/\/ good ol' C library\n#include \n#include \n#include \n#include \n\n\/\/ And our own headers.\n#include \n#include \"Bisector.h\"\n\nnamespace OGVCore {\n\n#pragma mark - Declarations\n\n class Player::impl {\n public:\n\n impl(std::shared_ptr aDelegate) :\n delegate(aDelegate),\n timer(delegate->timer())\n {}\n\n ~impl()\n {}\n\n void load()\n {\n if (stream.get() != NULL) {\n \/\/ already loaded.\n return;\n }\n\n started = false;\n stream = delegate->streamFile(getSourceURL(), std::shared_ptr(new StreamDelegate(this)));\n }\n\n void process()\n {\n \/\/ TODO\n }\n\n double getDuration()\n {\n return NAN; \/\/ TODO\n }\n\n double getVideoWidth()\n {\n return NAN; \/\/ TODO\n }\n\n double getVideoHeight()\n {\n return NAN; \/\/ TODO\n }\n\n std::string getSourceURL()\n {\n return NULL; \/\/ TODO\n }\n\n void setSourceURL(std::string aUrl)\n {\n }\n\n double getCurrentTime()\n {\n return NAN; \/\/ TODO\n }\n \n void setCurrentTime(double aTime)\n {\n \/\/ TODO\n }\n\n bool getPaused()\n {\n return false; \/\/ TODO\n }\n void setPaused(bool aPaused)\n {\n \/\/ TODO\n }\n\n bool getPlaying()\n {\n return false; \/\/ TODO\n }\n \n bool getSeeking()\n {\n return false; \/\/ TODO\n }\n\n private:\n std::shared_ptr delegate;\n std::shared_ptr timer;\n std::shared_ptr frameSink;\n std::shared_ptr audioFeeder;\n\n std::shared_ptr stream;\n long byteLength;\n double duration;\n\n\n class StreamDelegate : public StreamFile::Delegate {\n public:\n Player::impl *owner;\n \n StreamDelegate(Player::impl *aOwner) :\n owner(aOwner)\n {}\n\n virtual void onStart()\n {\n \/\/ Fire off the read\/decode\/draw loop...\n owner->byteLength = owner->stream->bytesTotal();\n \n \/\/ If we get X-Content-Duration, that's as good as an explicit hint\n auto durationHeader = owner->stream->getResponseHeader(\"X-Content-Duration\");\n if (durationHeader.length() > 0) {\n owner->duration = std::atof(durationHeader.c_str());\n }\n owner->startProcessingVideo();\n }\n \n virtual void onBuffer()\n {}\n \n virtual void onRead(std::vector data)\n {\n \/\/ Pass chunk into the codec's buffer\n owner->codec->receiveInput(data);\n\n \/\/ Continue the read\/decode\/draw loop...\n owner->pingProcessing();\n }\n \n virtual void onDone()\n {\n if (owner->state == STATE_SEEKING) {\n owner->pingProcessing();\n } else if (owner->state == STATE_SEEKING_END) {\n owner->pingProcessing();\n } else {\n \/\/throw new Error('wtf is this');\n owner->stream.reset();\n \n \/\/ Let the read\/decode\/draw loop know we're out!\n owner->pingProcessing();\n }\n }\n \n virtual void onError(std::string err)\n {\n std::cout << \"reading error: \" << err;\n }\n };\n\n enum {\n STATE_INITIAL,\n STATE_SEEKING_END,\n STATE_LOADED,\n STATE_PLAYING,\n STATE_PAUSED,\n STATE_SEEKING,\n STATE_ENDED\n } state = STATE_INITIAL;\n\n std::unique_ptr codec;\n \n bool started = false;\n double lastFrameTimestamp = 0.0;\n double frameEndTimestamp = 0.0;\n std::shared_ptr yCbCrBuffer = NULL;\n\n void processFrame()\n {\n yCbCrBuffer = codec->dequeueFrame();\n frameEndTimestamp = yCbCrBuffer->timestamp;\n }\n\n void drawFrame()\n {\n frameSink->drawFrame(yCbCrBuffer);\n doFrameComplete();\n }\n\n void doFrameComplete()\n {\n lastFrameTimestamp = timer->getTimestamp();\n }\n\n \/\/ Seeking\n enum {\n SEEKSTATE_NOT_SEEKING,\n SEEKSTATE_BISECT_TO_TARGET,\n SEEKSTATE_BISECT_TO_KEYPOINT,\n SEEKSTATE_LINEAR_TO_TARGET\n } seekState = SEEKSTATE_NOT_SEEKING;\n\n double seekTargetTime = 0.0;\n double seekTargetKeypoint = 0.0;\n double bisectTargetTime = 0.0;\n long lastSeekPosition = 0.0;\n bool lastFrameSkipped;\n std::unique_ptr seekBisector;\n\n void startBisection(double targetTime)\n {\n bisectTargetTime = targetTime;\n seekBisector.reset(new Bisector(\n \/* start *\/ 0,\n \/* end *\/ byteLength - 1,\n \/* process *\/ [this] (int start, int end, int position) {\n if (position == lastSeekPosition) {\n return false;\n } else {\n lastSeekPosition = position;\n lastFrameSkipped = false;\n codec->flush();\n stream->seek(position);\n stream->readBytes();\n return true;\n }\n }\n ));\n seekBisector->start();\n }\n \n void seek(double toTime);\n void continueSeekedPlayback();\n void doProcessLinearSeeking();\n void doProcessBisectionSeek();\n\n \/\/ Main stuff!\n void doProcessing()\n {\n \/\/ TODO\n }\n \n void pingProcessing(double delay = -1.0)\n {\n \/\/ TODO\n }\n \n void startProcessingVideo()\n {\n \/\/ TODO\n }\n };\n\n#pragma mark - Player pimpl bounce methods\n\n Player::Player(std::shared_ptr aDelegate):\n pimpl(new impl(aDelegate))\n {}\n\n Player::~Player()\n {}\n\n void Player::load()\n {\n pimpl->load();\n }\n\n void Player::process()\n {\n pimpl->process();\n }\n\n double Player::getDuration()\n {\n return pimpl->getDuration();\n }\n\n double Player::getVideoWidth()\n {\n return pimpl->getVideoWidth();\n }\n\n double Player::getVideoHeight()\n {\n return pimpl->getVideoHeight();\n }\n\n std::string Player::getSourceURL()\n {\n return pimpl->getSourceURL();\n }\n\n void Player::setSourceURL(std::string aUrl)\n {\n pimpl->setSourceURL(aUrl);\n }\n\n double Player::getCurrentTime()\n {\n return pimpl->getCurrentTime();\n }\n\n void Player::setCurrentTime(double aTime)\n {\n pimpl->setCurrentTime(aTime);\n }\n\n bool Player::getPaused()\n {\n return pimpl->getPaused();\n }\n\n void Player::setPaused(bool aPaused)\n {\n return pimpl->setPaused(aPaused);\n }\n\n bool Player::getPlaying()\n {\n return pimpl->getPlaying();\n }\n\n bool Player::getSeeking()\n {\n return pimpl->getSeeking();\n }\n\n}\n<|endoftext|>"} {"text":"#include \".\/JPetScopeModule.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"boost\/regex.hpp\"\n#include \"boost\/filesystem.hpp\"\n\n#include \n#include \n#include \n\n#include \"..\/JPetSigCh\/JPetSigCh.h\"\n#include \"..\/JPetRecoSignal\/JPetRecoSignal.h\"\n#include \"..\/JPetPhysSignal\/JPetPhysSignal.h\"\n#include \"..\/JPetManager\/JPetManager.h\"\n#include \"..\/JPetParamBank\/JPetParamBank.h\"\n#include \"..\/JPetTreeHeader\/JPetTreeHeader.h\"\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nClassImp(JPetScopeModule);\n\nstatic multimap :: iterator fIt;\n\nJPetScopeModule::JPetScopeModule(): JPetAnalysisModule() {\n gSystem->Load(\"libTree\");\n}\n\nJPetScopeModule::JPetScopeModule(const char* name, const char* title): JPetAnalysisModule(name, title) {\n gSystem->Load(\"libTree\");\n}\n\nJPetScopeModule::~JPetScopeModule() {\n if (fWriter != 0) {\n delete fWriter;\n fWriter = 0;\n }\n}\n\nint JPetScopeModule::readFromConfig (const char* fmt, ...) {\n\n va_list args;\n va_start (args, fmt);\n\n string buf;\n\n getline (fConfigFile, buf);\n while (fConfigFile.good() && buf.size() < 2 ) getline(fConfigFile, buf);\n if (!fConfigFile.good()) {va_end(args); return -1;}\n\n \/\/buf.erase(0, to_erase);\n int ret = vsscanf(buf.c_str(), fmt, args);\n\n va_end(args);\n\n return ret;\n}\n\nvoid JPetScopeModule::createInputObjects(const char* inputFilename)\n{\n INFO( Form(\"Starting %s.\", GetName() ) );\n \n fConfigFile.open(fInFilename);\n if (!fConfigFile.is_open()) {\n ERROR(\"Cannot open config file. Exiting\");\n exit(-1);\n }\n \n string buf;\n string cfg_dir = path(fInFilename).parent_path().string();\n string data_dir;\n char cbuf[256];\n int a, b, c;\n \/\/int p1, p2, p3, p4, s1, s2, coll;\n\n \/\/ Read configuration data \n for (int i = 0; i<1; ++i){ \n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm1), cbuf) <= 0) break;\n fConfig.file1 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm2), cbuf) <= 0) break;\n fConfig.file2 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm3), cbuf) <= 0) break;\n fConfig.file3 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm4), cbuf) <= 0) break;\n fConfig.file4 = string(cbuf);\n\n if (readFromConfig(\"%*5c %d\", &(fConfig.scin1)) <= 0) break;\n\n if (readFromConfig(\"%*5c %d\", &(fConfig.scin2)) <= 0) break;\n\n if (readFromConfig(\"%s\", cbuf) <= 0) break;\n data_dir = string(cbuf);\n\n while (true) {\n a = 0;\n b = 0;\n c = 0;\n int d = readFromConfig(\"%d %d %d\", &a, &b, &c);\n if (d <= 0) break;\n else if (d == 1) {\n \/\/ Add single position\n fCollPositions.insert(a);\n }\n else {\n if (d == 2) {c = 1;}\n \/\/ Add multiple positions\n for (int j = a; j <= b; j += c) {\n fCollPositions.insert(j);\n }\n }\n }\n\n }\n\n \/\/Create ParamBank\n JPetPM pm1;\n JPetPM pm2;\n JPetPM pm3;\n JPetPM pm4;\n pm1.setID(fConfig.pm1);\n pm2.setID(fConfig.pm2);\n pm3.setID(fConfig.pm3);\n pm4.setID(fConfig.pm4);\n\n JPetScin scin1;\n JPetScin scin2;\n scin1.setID(fConfig.scin1);\n scin2.setID(fConfig.scin2);\n\n fParamBank = new JPetParamBank();\n fParamBank->addPM(pm1);\n fParamBank->addPM(pm2);\n fParamBank->addPM(pm3);\n fParamBank->addPM(pm4);\n fParamBank->addScintillator(scin1);\n fParamBank->addScintillator(scin2);\n\n fConfig.ppm1 = &(fParamBank->getPM(0));\n fConfig.ppm2 = &(fParamBank->getPM(1));\n fConfig.ppm3 = &(fParamBank->getPM(2));\n fConfig.ppm4 = &(fParamBank->getPM(3));\n fConfig.pscin1 = &(fParamBank->getScintillator(0));\n fConfig.pscin2 = &(fParamBank->getScintillator(1));\n\n fConfig.ppm1->setScin(*(fConfig.pscin1));\n fConfig.ppm2->setScin(*(fConfig.pscin1));\n fConfig.ppm3->setScin(*(fConfig.pscin2));\n fConfig.ppm4->setScin(*(fConfig.pscin2));\n\n\n \/\/ Add oscilloscope files\n for (set::iterator it = fCollPositions.begin(); it != fCollPositions.end(); ++it) {\n string starting_loc = cfg_dir;\n starting_loc += \"\/\";\n starting_loc += data_dir;\n\t starting_loc += \"\/\";\n\t starting_loc += to_string (*it);\n\n path current_dir(starting_loc);\n boost::regex pattern(Form(\"%s_\\\\d*.txt\", fConfig.file1.c_str()));\n \n if (exists(current_dir))\n for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {\n string name = iter->path().leaf().string();\n string dir;\n if (regex_match(name, pattern)) {\n name[1] = (fConfig.file1)[1];\n dir = iter->path().parent_path().string();\n dir += \"\/\";\n dir += name;\n\tint tpos = *it;\n fFiles.insert(pair (tpos, dir));\n }\n }\n else {\n string msg = \"Directory: \\\"\";\n msg += current_dir.string();\n msg += \"\\\" does not exist.\";\n ERROR(msg.c_str());\n }\n }\n fIt = fFiles.begin();\n \/\/printFiles();\n fWriter = 0;\n}\n\nvoid JPetScopeModule::createOutputObjects(const char* outputFilename) {\n \n if (fFiles.empty()) {\n ERROR(\"No files for processing.\");\n }\n else {\n fCurrentPosition = (*fIt).first;\n terminate();\n\n INFO (Form(\"Creating root file for position %d\", fCurrentPosition));\n\n string out_fn(fOutFilename.Data());\n int last_dot = out_fn.find_last_of(\".\");\n\n string out_fn2 = out_fn.substr(0,last_dot+1);\n out_fn2 += to_string(fCurrentPosition);\n out_fn2 += out_fn.substr(last_dot);\n\n fWriter = new JPetWriter(out_fn2.c_str());\n\n fHeader = new JPetTreeHeader(JPetManager::GetManager().getRunNumber());\n fHeader->setBaseFileName(JPetManager::GetManager().getInputFileName().c_str());\n fHeader->addStageInfo(GetName(), GetTitle(), MODULE_VERSION, JPetManager::GetManager().GetTimeString());\n fHeader->setSourcePosition(fCurrentPosition);\n\n fWriter->writeHeader(fHeader);\n fWriter->writeObject(fParamBank, \"ParamBank\");\n }\n}\n\nvoid JPetScopeModule::exec() { \n \n while (fIt != fFiles.end()) {\n \n if ((*fIt).first != fCurrentPosition) createOutputObjects();\n\n JPetPhysSignal psig1, psig2, psig3, psig4;\n JPetHit hit1, hit2;\n \n string osc_file = (*fIt).second;\n string filename;\n\n int tslot_index;\n sscanf(path(osc_file).filename().string().c_str(), \"%*3s %d\", &tslot_index);\n \n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str()));\n JPetRecoSignal& rsig1 = fReader.generateSignal(osc_file.c_str());\n rsig1.setPM(*(fConfig.ppm1));\n rsig1.setTSlotIndex(tslot_index);\n psig1.setRecoSignal(rsig1);\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file2)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file+= \"\/\";\n osc_file+= filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig2 = fReader.generateSignal(osc_file.c_str());\n rsig2.setPM(*(fConfig.ppm2));\n rsig2.setTSlotIndex(tslot_index);\n psig2.setRecoSignal(rsig2);\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file3)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file+= \"\/\";\n osc_file+= filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig3 = fReader.generateSignal(osc_file.c_str());\n rsig3.setPM(*(fConfig.ppm3));\n rsig3.setTSlotIndex(tslot_index);\n psig3.setRecoSignal(rsig3);\n\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file4)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file += \"\/\";\n osc_file += filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig4 = fReader.generateSignal(osc_file.c_str());\n rsig4.setPM(*(fConfig.ppm4));\n rsig4.setTSlotIndex(tslot_index);\n psig4.setRecoSignal(rsig4);\n \n hit1.setSignals(psig1, psig2);\n hit1.setScinID(fConfig.scin1);\n\n hit2.setSignals(psig3, psig4);\n hit2.setScinID(fConfig.scin2);\n\n JPetLOR event;\n\n event.setHits(hit1, hit2);\n\n fWriter->write(event);\n\n break;\n }\n fIt++;\n}\n\nvoid JPetScopeModule::terminate() {\n\/\/ assert(fWriter);\n if(fWriter)\n if(fWriter->isOpen()) {\n \/\/std::cout <<\"in JPetScope terminate()\" <closeFile();\n delete fWriter;\n fWriter = 0;\n }\n}\n\nvoid JPetScopeModule::printCollPositions () {\n INFO (\"Printing all collimator positions:\");\n for (set::iterator iter = fCollPositions.begin(); iter != fCollPositions.end(); ++iter) {\n INFO (Form(\"collimator position: %d\", *iter));\n }\n}\n\nvoid JPetScopeModule::printFiles () {\n INFO (\"Printing all files:\");\n for (map::iterator iter = fFiles.begin(); iter != fFiles.end(); ++iter) {\n INFO (Form(\"%3d %s\", (*iter).first, (*iter).second.c_str()));\n }\n}\n\nvoid JPetScopeModule::setFileName(const char* name)\n{\n fInFilename = TString(name);\n fOutFilename = TString(name);\n fOutFilename.ReplaceAll(\".cfg\", \"\");\n fOutFilename.Append(\".scope.eve.root\");\n}\nsolved problem #632#include \".\/JPetScopeModule.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"boost\/regex.hpp\"\n#include \"boost\/filesystem.hpp\"\n\n#include \n#include \n#include \n\n#include \"..\/JPetSigCh\/JPetSigCh.h\"\n#include \"..\/JPetRecoSignal\/JPetRecoSignal.h\"\n#include \"..\/JPetPhysSignal\/JPetPhysSignal.h\"\n#include \"..\/JPetManager\/JPetManager.h\"\n#include \"..\/JPetParamBank\/JPetParamBank.h\"\n#include \"..\/JPetTreeHeader\/JPetTreeHeader.h\"\n\nusing namespace std;\nusing namespace boost::filesystem;\n\nClassImp(JPetScopeModule);\n\nstatic multimap :: iterator fIt;\n\nJPetScopeModule::JPetScopeModule(): JPetAnalysisModule() {\n gSystem->Load(\"libTree\");\n}\n\nJPetScopeModule::JPetScopeModule(const char* name, const char* title): JPetAnalysisModule(name, title) {\n gSystem->Load(\"libTree\");\n}\n\nJPetScopeModule::~JPetScopeModule() {\n if (fWriter != 0) {\n delete fWriter;\n fWriter = 0;\n }\n}\n\nint JPetScopeModule::readFromConfig (const char* fmt, ...) {\n\n va_list args;\n va_start (args, fmt);\n\n string buf;\n\n getline (fConfigFile, buf);\n while (fConfigFile.good() && buf.size() < 2 ) getline(fConfigFile, buf);\n if (!fConfigFile.good()) {va_end(args); return -1;}\n\n \/\/buf.erase(0, to_erase);\n int ret = vsscanf(buf.c_str(), fmt, args);\n\n va_end(args);\n\n return ret;\n}\n\nvoid JPetScopeModule::createInputObjects(const char* inputFilename)\n{\n INFO( Form(\"Starting %s.\", GetName() ) );\n \n fConfigFile.open(fInFilename);\n if (!fConfigFile.is_open()) {\n ERROR(\"Cannot open config file. Exiting\");\n exit(-1);\n }\n \n string buf;\n string cfg_dir = path(fInFilename).parent_path().string();\n string data_dir;\n char cbuf[256];\n int a, b, c;\n \/\/int p1, p2, p3, p4, s1, s2, coll;\n\n \/\/ Read configuration data \n for (int i = 0; i<1; ++i){ \n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm1), cbuf) <= 0) break;\n fConfig.file1 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm2), cbuf) <= 0) break;\n fConfig.file2 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm3), cbuf) <= 0) break;\n fConfig.file3 = string(cbuf);\n\n if (readFromConfig(\"%*2c %d %s\", &(fConfig.pm4), cbuf) <= 0) break;\n fConfig.file4 = string(cbuf);\n\n if (readFromConfig(\"%*5c %d\", &(fConfig.scin1)) <= 0) break;\n\n if (readFromConfig(\"%*5c %d\", &(fConfig.scin2)) <= 0) break;\n\n if (readFromConfig(\"%s\", cbuf) <= 0) break;\n data_dir = string(cbuf);\n\n while (true) {\n a = 0;\n b = 0;\n c = 0;\n int d = readFromConfig(\"%d %d %d\", &a, &b, &c);\n if (d <= 0) break;\n else if (d == 1) {\n \/\/ Add single position\n fCollPositions.insert(a);\n }\n else {\n if (d == 2) {c = 1;}\n \/\/ Add multiple positions\n for (int j = a; j <= b; j += c) {\n fCollPositions.insert(j);\n }\n }\n }\n\n }\n\n \/\/Create ParamBank\n JPetPM pm1;\n JPetPM pm2;\n JPetPM pm3;\n JPetPM pm4;\n pm1.setID(fConfig.pm1);\n pm2.setID(fConfig.pm2);\n pm3.setID(fConfig.pm3);\n pm4.setID(fConfig.pm4);\n\n JPetScin scin1;\n JPetScin scin2;\n scin1.setID(fConfig.scin1);\n scin2.setID(fConfig.scin2);\n\n fParamBank = new JPetParamBank();\n fParamBank->addPM(pm1);\n fParamBank->addPM(pm2);\n fParamBank->addPM(pm3);\n fParamBank->addPM(pm4);\n fParamBank->addScintillator(scin1);\n fParamBank->addScintillator(scin2);\n\n fConfig.ppm1 = &(fParamBank->getPM(0));\n fConfig.ppm2 = &(fParamBank->getPM(1));\n fConfig.ppm3 = &(fParamBank->getPM(2));\n fConfig.ppm4 = &(fParamBank->getPM(3));\n fConfig.pscin1 = &(fParamBank->getScintillator(0));\n fConfig.pscin2 = &(fParamBank->getScintillator(1));\n\n fConfig.ppm1->setScin(*(fConfig.pscin1));\n fConfig.ppm2->setScin(*(fConfig.pscin1));\n fConfig.ppm3->setScin(*(fConfig.pscin2));\n fConfig.ppm4->setScin(*(fConfig.pscin2));\n\n\n \/\/ Add oscilloscope files\n for (set::iterator it = fCollPositions.begin(); it != fCollPositions.end(); ++it) {\n string starting_loc = cfg_dir;\n starting_loc += \"\/\";\n starting_loc += data_dir;\n\t starting_loc += \"\/\";\n\t starting_loc += to_string (*it);\n\n path current_dir(starting_loc);\n boost::regex pattern(Form(\"%s_\\\\d*.txt\", fConfig.file1.c_str()));\n \n if (exists(current_dir))\n for (recursive_directory_iterator iter(current_dir), end; iter != end; ++iter) {\n string name = iter->path().leaf().string();\n string dir;\n if (regex_match(name, pattern)) {\n name[1] = (fConfig.file1)[1];\n dir = iter->path().parent_path().string();\n dir += \"\/\";\n dir += name;\n\tint tpos = *it;\n fFiles.insert(pair (tpos, dir));\n }\n }\n else {\n string msg = \"Directory: \\\"\";\n msg += current_dir.string();\n msg += \"\\\" does not exist.\";\n ERROR(msg.c_str());\n }\n }\n fIt = fFiles.begin();\n \/\/printFiles();\n fWriter = 0;\n}\n\nvoid JPetScopeModule::createOutputObjects(const char* outputFilename) {\n \n if (fFiles.empty()) {\n ERROR(\"No files for processing.\");\n }\n else {\n fCurrentPosition = (*fIt).first;\n terminate();\n\n INFO (Form(\"Creating root file for position %d\", fCurrentPosition));\n\n string out_fn(fOutFilename.Data());\n int last_dot = out_fn.find_last_of(\".\");\n\n string out_fn2 = out_fn.substr(0,last_dot+1);\n out_fn2 += to_string(fCurrentPosition);\n out_fn2 += out_fn.substr(last_dot);\n\n fWriter = new JPetWriter(out_fn2.c_str());\n\n fHeader = new JPetTreeHeader(JPetManager::GetManager().getRunNumber());\n fHeader->setBaseFileName(JPetManager::GetManager().getInputFileName().c_str());\n fHeader->addStageInfo(GetName(), GetTitle(), MODULE_VERSION, JPetManager::GetManager().GetTimeString());\n fHeader->setSourcePosition(fCurrentPosition);\n\n fWriter->writeHeader(fHeader);\n }\n}\n\nvoid JPetScopeModule::exec() { \n \n while (fIt != fFiles.end()) {\n \n if ((*fIt).first != fCurrentPosition) createOutputObjects();\n fWriter->writeObject(fParamBank, \"ParamBank\");\n\n JPetPhysSignal psig1, psig2, psig3, psig4;\n JPetHit hit1, hit2;\n \n string osc_file = (*fIt).second;\n string filename;\n\n int tslot_index;\n sscanf(path(osc_file).filename().string().c_str(), \"%*3s %d\", &tslot_index);\n \n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str()));\n JPetRecoSignal& rsig1 = fReader.generateSignal(osc_file.c_str());\n rsig1.setPM(*(fConfig.ppm1));\n rsig1.setTSlotIndex(tslot_index);\n psig1.setRecoSignal(rsig1);\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file2)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file+= \"\/\";\n osc_file+= filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig2 = fReader.generateSignal(osc_file.c_str());\n rsig2.setPM(*(fConfig.ppm2));\n rsig2.setTSlotIndex(tslot_index);\n psig2.setRecoSignal(rsig2);\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file3)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file+= \"\/\";\n osc_file+= filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig3 = fReader.generateSignal(osc_file.c_str());\n rsig3.setPM(*(fConfig.ppm3));\n rsig3.setTSlotIndex(tslot_index);\n psig3.setRecoSignal(rsig3);\n\n \n filename = path((*fIt).second).filename().string();\n filename[1] = (fConfig.file4)[1];\n osc_file = path((*fIt).second).parent_path().string();\n osc_file += \"\/\";\n osc_file += filename;\n\n \/\/INFO (Form(\"Processing file: %s\", osc_file.c_str())); \n JPetRecoSignal& rsig4 = fReader.generateSignal(osc_file.c_str());\n rsig4.setPM(*(fConfig.ppm4));\n rsig4.setTSlotIndex(tslot_index);\n psig4.setRecoSignal(rsig4);\n \n hit1.setSignals(psig1, psig2);\n hit1.setScinID(fConfig.scin1);\n\n hit2.setSignals(psig3, psig4);\n hit2.setScinID(fConfig.scin2);\n\n JPetLOR event;\n\n event.setHits(hit1, hit2);\n\n fWriter->write(event);\n\n break;\n }\n fIt++;\n}\n\nvoid JPetScopeModule::terminate() {\n\/\/ assert(fWriter);\n if(fWriter)\n if(fWriter->isOpen()) {\n \/\/std::cout <<\"in JPetScope terminate()\" <closeFile();\n delete fWriter;\n fWriter = 0;\n }\n}\n\nvoid JPetScopeModule::printCollPositions () {\n INFO (\"Printing all collimator positions:\");\n for (set::iterator iter = fCollPositions.begin(); iter != fCollPositions.end(); ++iter) {\n INFO (Form(\"collimator position: %d\", *iter));\n }\n}\n\nvoid JPetScopeModule::printFiles () {\n INFO (\"Printing all files:\");\n for (map::iterator iter = fFiles.begin(); iter != fFiles.end(); ++iter) {\n INFO (Form(\"%3d %s\", (*iter).first, (*iter).second.c_str()));\n }\n}\n\nvoid JPetScopeModule::setFileName(const char* name)\n{\n fInFilename = TString(name);\n fOutFilename = TString(name);\n fOutFilename.ReplaceAll(\".cfg\", \"\");\n fOutFilename.Append(\".scope.eve.root\");\n}\n<|endoftext|>"} {"text":"#include \"Runtime\/World\/CScriptSound.hpp\"\n\n#include \"Runtime\/CStateManager.hpp\"\n#include \"Runtime\/Character\/CModelData.hpp\"\n#include \"Runtime\/Collision\/CMaterialList.hpp\"\n#include \"Runtime\/World\/CActorParameters.hpp\"\n#include \"Runtime\/World\/CWorld.hpp\"\n\n#include \"TCastTo.hpp\" \/\/ Generated file, do not modify include path\n\nnamespace urde {\nbool CScriptSound::sFirstInFrame = false;\n\nCScriptSound::CScriptSound(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,\n u16 soundId, bool active, float maxDist, float distComp, float startDelay, u32 minVol,\n u32 vol, u32 w3, u32 prio, u32 pan, u32 w6, bool looped, bool nonEmitter, bool autoStart,\n bool occlusionTest, bool acoustics, bool worldSfx, bool allowDuplicates, s32 pitch)\n: CActor(uid, active, name, info, xf, CModelData::CModelDataNull(), CMaterialList(EMaterialTypes::NoStepLogic),\n CActorParameters::None(), kInvalidUniqueId)\n, xfc_startDelay(startDelay)\n, x100_soundId(CSfxManager::TranslateSFXID(soundId))\n, x104_maxDist(maxDist)\n, x108_distComp(distComp)\n, x10c_minVol(minVol \/ 127.f)\n, x10e_vol(vol \/ 127.f)\n, x110_(w3)\n, x112_prio(s16(prio))\n, x114_pan(pan \/ 64.f - 1.f)\n, x116_(w6)\n, x118_pitch(pitch \/ 8192.f)\n, x11c_25_looped(looped)\n, x11c_26_nonEmitter(nonEmitter)\n, x11c_27_autoStart(autoStart)\n, x11c_28_occlusionTest(occlusionTest)\n, x11c_29_acoustics(acoustics)\n, x11c_30_worldSfx(worldSfx)\n, x11d_24_allowDuplicates(allowDuplicates) {\n if (x11c_30_worldSfx && (!x11c_26_nonEmitter || !x11c_25_looped))\n x11c_30_worldSfx = false;\n}\n\nvoid CScriptSound::Accept(IVisitor& visitor) { visitor.Visit(this); }\n\nvoid CScriptSound::PreThink(float dt, CStateManager& mgr) {\n CEntity::PreThink(dt, mgr);\n sFirstInFrame = true;\n x11d_25_processedThisFrame = false;\n}\n\nconstexpr CMaterialFilter kSolidFilter =\n CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough});\n\nfloat CScriptSound::GetOccludedVolumeAmount(const zeus::CVector3f& pos, const CStateManager& mgr) {\n zeus::CTransform camXf = mgr.GetCameraManager()->GetCurrentCameraTransform(mgr);\n zeus::CVector3f soundToCam = camXf.origin - pos;\n float soundToCamMag = soundToCam.magnitude();\n zeus::CVector3f soundToCamNorm = soundToCam * (1.f \/ soundToCamMag);\n zeus::CVector3f thirdEdge = zeus::skUp - soundToCamNorm * soundToCamNorm.dot(zeus::skUp);\n zeus::CVector3f cross = soundToCamNorm.cross(thirdEdge);\n static float kInfluenceAmount = 3.f \/ soundToCamMag;\n static float kInfluenceIncrement = kInfluenceAmount;\n\n int totalCount = 0;\n int invalCount = 0;\n float f17 = -kInfluenceAmount;\n while (f17 <= kInfluenceAmount) {\n zeus::CVector3f angledDir = thirdEdge * f17 + soundToCamNorm;\n float f16 = -kInfluenceAmount;\n while (f16 <= kInfluenceAmount) {\n if (mgr.RayStaticIntersection(pos, (cross * f16 + angledDir).normalized(), soundToCamMag, kSolidFilter)\n .IsInvalid())\n ++invalCount;\n ++totalCount;\n f16 += kInfluenceIncrement;\n }\n f17 += kInfluenceIncrement;\n }\n\n return invalCount \/ float(totalCount) * 0.42f + 0.58f;\n}\n\nvoid CScriptSound::Think(float dt, CStateManager& mgr) {\n if (x11c_31_selfFree && (!GetActive() || x11c_25_looped || !x11c_27_autoStart)) {\n mgr.FreeScriptObject(GetUniqueId());\n } else if (GetActive()) {\n if (!x11c_25_looped && x11c_27_autoStart && !x11c_24_playRequested && xec_sfxHandle &&\n !CSfxManager::IsPlaying(xec_sfxHandle))\n mgr.FreeScriptObject(GetUniqueId());\n\n if (!x11c_26_nonEmitter && xec_sfxHandle) {\n if (xf8_updateTimer <= 0.f) {\n xf8_updateTimer = 0.25f;\n CSfxManager::UpdateEmitter(xec_sfxHandle, GetTranslation(), zeus::skZero3f, xf2_maxVolUpd);\n } else {\n xf8_updateTimer -= dt;\n }\n }\n\n if (xec_sfxHandle && !x11c_26_nonEmitter && x11c_28_occlusionTest) {\n if (xe8_occUpdateTimer <= 0.f && sFirstInFrame) {\n sFirstInFrame = false;\n float occVol = GetOccludedVolumeAmount(GetTranslation(), mgr);\n float newMaxVol = std::max(occVol * x10e_vol, x10c_minVol);\n if (newMaxVol != xf0_maxVol) {\n xf0_maxVol = newMaxVol;\n float delta = xf0_maxVol - xf2_maxVolUpd;\n xf4_maxVolUpdDelta = delta \/ 10.5f;\n if (xf4_maxVolUpdDelta == 0.f) {\n if (xf2_maxVolUpd < xf0_maxVol)\n xf4_maxVolUpdDelta = 1.f \/ 127.f;\n else\n xf4_maxVolUpdDelta = -1.f \/ 127.f;\n }\n }\n xe8_occUpdateTimer = 0.5f;\n } else {\n xe8_occUpdateTimer -= dt;\n }\n\n if (xf2_maxVolUpd != xf0_maxVol) {\n xf2_maxVolUpd += xf4_maxVolUpdDelta;\n if (xf4_maxVolUpdDelta > 0.f && xf2_maxVolUpd > xf0_maxVol)\n xf2_maxVolUpd = xf0_maxVol;\n if (xf4_maxVolUpdDelta < 0.f && xf2_maxVolUpd < xf0_maxVol)\n xf2_maxVolUpd = xf0_maxVol;\n CSfxManager::UpdateEmitter(xec_sfxHandle, GetTranslation(), zeus::skZero3f, xf2_maxVolUpd);\n }\n }\n\n if (x11c_24_playRequested) {\n xfc_startDelay -= dt;\n if (xfc_startDelay <= 0.f) {\n x11c_24_playRequested = false;\n PlaySound(mgr);\n }\n }\n\n if (x118_pitch != 0.f && xec_sfxHandle)\n CSfxManager::PitchBend(xec_sfxHandle, x118_pitch);\n }\n}\n\nvoid CScriptSound::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {\n CActor::AcceptScriptMsg(msg, uid, mgr);\n\n switch (msg) {\n case EScriptObjectMessage::Registered: {\n if (GetActive() && x11c_27_autoStart)\n x11c_24_playRequested = true;\n x11c_31_selfFree = mgr.GetIsGeneratingObject();\n } break;\n case EScriptObjectMessage::Play: {\n if (GetActive())\n PlaySound(mgr);\n } break;\n case EScriptObjectMessage::Stop: {\n if (GetActive())\n StopSound(mgr);\n } break;\n case EScriptObjectMessage::Deactivate: {\n StopSound(mgr);\n } break;\n case EScriptObjectMessage::Activate: {\n if (GetActive())\n x11c_24_playRequested = true;\n } break;\n case EScriptObjectMessage::Deleted: {\n if (!x11c_30_worldSfx)\n StopSound(mgr);\n } break;\n default:\n break;\n }\n}\n\nvoid CScriptSound::PlaySound(CStateManager& mgr) {\n if ((x11d_24_allowDuplicates || !xec_sfxHandle || xec_sfxHandle->IsClosed()) && !x11d_25_processedThisFrame) {\n x11d_25_processedThisFrame = true;\n if (x11c_26_nonEmitter) {\n if (!x11c_30_worldSfx || !mgr.GetWorld()->HasGlobalSound(x100_soundId)) {\n xec_sfxHandle = CSfxManager::SfxStart(x100_soundId, x10e_vol, x114_pan, x11c_29_acoustics, x112_prio,\n x11c_25_looped, x11c_30_worldSfx ? kInvalidAreaId : GetAreaIdAlways());\n if (x11c_30_worldSfx)\n mgr.GetWorld()->AddGlobalSound(xec_sfxHandle);\n }\n } else {\n float occVol = x11c_28_occlusionTest ? GetOccludedVolumeAmount(GetTranslation(), mgr) : 1.f;\n xf0_maxVol = xf2_maxVolUpd = x10e_vol * occVol;\n CAudioSys::C3DEmitterParmData data = {};\n data.x0_pos = GetTranslation();\n data.x18_maxDist = x104_maxDist;\n data.x1c_distComp = x108_distComp;\n data.x20_flags = 1; \/\/ Continuous parameter update\n data.x24_sfxId = x100_soundId;\n data.x26_maxVol = xf0_maxVol;\n data.x27_minVol = x10c_minVol;\n data.x29_prio = 0x7f;\n xec_sfxHandle = CSfxManager::AddEmitter(data, x11c_29_acoustics, x112_prio, x11c_25_looped, GetAreaIdAlways());\n }\n }\n}\n\nvoid CScriptSound::StopSound(CStateManager& mgr) {\n x11c_24_playRequested = false;\n if (x11c_30_worldSfx && x11c_26_nonEmitter) {\n mgr.GetWorld()->StopGlobalSound(x100_soundId);\n xec_sfxHandle.reset();\n } else if (xec_sfxHandle) {\n CSfxManager::RemoveEmitter(xec_sfxHandle);\n xec_sfxHandle.reset();\n }\n}\n} \/\/ namespace urde\nCScriptSound: Brace conditionals where applicable#include \"Runtime\/World\/CScriptSound.hpp\"\n\n#include \"Runtime\/CStateManager.hpp\"\n#include \"Runtime\/Character\/CModelData.hpp\"\n#include \"Runtime\/Collision\/CMaterialList.hpp\"\n#include \"Runtime\/World\/CActorParameters.hpp\"\n#include \"Runtime\/World\/CWorld.hpp\"\n\n#include \"TCastTo.hpp\" \/\/ Generated file, do not modify include path\n\nnamespace urde {\nbool CScriptSound::sFirstInFrame = false;\n\nCScriptSound::CScriptSound(TUniqueId uid, std::string_view name, const CEntityInfo& info, const zeus::CTransform& xf,\n u16 soundId, bool active, float maxDist, float distComp, float startDelay, u32 minVol,\n u32 vol, u32 w3, u32 prio, u32 pan, u32 w6, bool looped, bool nonEmitter, bool autoStart,\n bool occlusionTest, bool acoustics, bool worldSfx, bool allowDuplicates, s32 pitch)\n: CActor(uid, active, name, info, xf, CModelData::CModelDataNull(), CMaterialList(EMaterialTypes::NoStepLogic),\n CActorParameters::None(), kInvalidUniqueId)\n, xfc_startDelay(startDelay)\n, x100_soundId(CSfxManager::TranslateSFXID(soundId))\n, x104_maxDist(maxDist)\n, x108_distComp(distComp)\n, x10c_minVol(minVol \/ 127.f)\n, x10e_vol(vol \/ 127.f)\n, x110_(w3)\n, x112_prio(s16(prio))\n, x114_pan(pan \/ 64.f - 1.f)\n, x116_(w6)\n, x118_pitch(pitch \/ 8192.f)\n, x11c_25_looped(looped)\n, x11c_26_nonEmitter(nonEmitter)\n, x11c_27_autoStart(autoStart)\n, x11c_28_occlusionTest(occlusionTest)\n, x11c_29_acoustics(acoustics)\n, x11c_30_worldSfx(worldSfx)\n, x11d_24_allowDuplicates(allowDuplicates) {\n if (x11c_30_worldSfx && (!x11c_26_nonEmitter || !x11c_25_looped)) {\n x11c_30_worldSfx = false;\n }\n}\n\nvoid CScriptSound::Accept(IVisitor& visitor) { visitor.Visit(this); }\n\nvoid CScriptSound::PreThink(float dt, CStateManager& mgr) {\n CEntity::PreThink(dt, mgr);\n sFirstInFrame = true;\n x11d_25_processedThisFrame = false;\n}\n\nconstexpr CMaterialFilter kSolidFilter =\n CMaterialFilter::MakeIncludeExclude({EMaterialTypes::Solid}, {EMaterialTypes::ProjectilePassthrough});\n\nfloat CScriptSound::GetOccludedVolumeAmount(const zeus::CVector3f& pos, const CStateManager& mgr) {\n const zeus::CTransform camXf = mgr.GetCameraManager()->GetCurrentCameraTransform(mgr);\n const zeus::CVector3f soundToCam = camXf.origin - pos;\n const float soundToCamMag = soundToCam.magnitude();\n const zeus::CVector3f soundToCamNorm = soundToCam * (1.f \/ soundToCamMag);\n const zeus::CVector3f thirdEdge = zeus::skUp - soundToCamNorm * soundToCamNorm.dot(zeus::skUp);\n const zeus::CVector3f cross = soundToCamNorm.cross(thirdEdge);\n static float kInfluenceAmount = 3.f \/ soundToCamMag;\n static float kInfluenceIncrement = kInfluenceAmount;\n\n int totalCount = 0;\n int invalCount = 0;\n float f17 = -kInfluenceAmount;\n while (f17 <= kInfluenceAmount) {\n const zeus::CVector3f angledDir = thirdEdge * f17 + soundToCamNorm;\n float f16 = -kInfluenceAmount;\n while (f16 <= kInfluenceAmount) {\n if (mgr.RayStaticIntersection(pos, (cross * f16 + angledDir).normalized(), soundToCamMag, kSolidFilter)\n .IsInvalid()) {\n ++invalCount;\n }\n ++totalCount;\n f16 += kInfluenceIncrement;\n }\n f17 += kInfluenceIncrement;\n }\n\n return invalCount \/ float(totalCount) * 0.42f + 0.58f;\n}\n\nvoid CScriptSound::Think(float dt, CStateManager& mgr) {\n if (x11c_31_selfFree && (!GetActive() || x11c_25_looped || !x11c_27_autoStart)) {\n mgr.FreeScriptObject(GetUniqueId());\n } else if (GetActive()) {\n if (!x11c_25_looped && x11c_27_autoStart && !x11c_24_playRequested && xec_sfxHandle &&\n !CSfxManager::IsPlaying(xec_sfxHandle)) {\n mgr.FreeScriptObject(GetUniqueId());\n }\n\n if (!x11c_26_nonEmitter && xec_sfxHandle) {\n if (xf8_updateTimer <= 0.f) {\n xf8_updateTimer = 0.25f;\n CSfxManager::UpdateEmitter(xec_sfxHandle, GetTranslation(), zeus::skZero3f, xf2_maxVolUpd);\n } else {\n xf8_updateTimer -= dt;\n }\n }\n\n if (xec_sfxHandle && !x11c_26_nonEmitter && x11c_28_occlusionTest) {\n if (xe8_occUpdateTimer <= 0.f && sFirstInFrame) {\n sFirstInFrame = false;\n const float occVol = GetOccludedVolumeAmount(GetTranslation(), mgr);\n const float newMaxVol = std::max(occVol * x10e_vol, x10c_minVol);\n if (newMaxVol != xf0_maxVol) {\n xf0_maxVol = newMaxVol;\n const float delta = xf0_maxVol - xf2_maxVolUpd;\n xf4_maxVolUpdDelta = delta \/ 10.5f;\n if (xf4_maxVolUpdDelta == 0.f) {\n if (xf2_maxVolUpd < xf0_maxVol) {\n xf4_maxVolUpdDelta = 1.f \/ 127.f;\n } else {\n xf4_maxVolUpdDelta = -1.f \/ 127.f;\n }\n }\n }\n xe8_occUpdateTimer = 0.5f;\n } else {\n xe8_occUpdateTimer -= dt;\n }\n\n if (xf2_maxVolUpd != xf0_maxVol) {\n xf2_maxVolUpd += xf4_maxVolUpdDelta;\n if (xf4_maxVolUpdDelta > 0.f && xf2_maxVolUpd > xf0_maxVol) {\n xf2_maxVolUpd = xf0_maxVol;\n }\n if (xf4_maxVolUpdDelta < 0.f && xf2_maxVolUpd < xf0_maxVol) {\n xf2_maxVolUpd = xf0_maxVol;\n }\n CSfxManager::UpdateEmitter(xec_sfxHandle, GetTranslation(), zeus::skZero3f, xf2_maxVolUpd);\n }\n }\n\n if (x11c_24_playRequested) {\n xfc_startDelay -= dt;\n if (xfc_startDelay <= 0.f) {\n x11c_24_playRequested = false;\n PlaySound(mgr);\n }\n }\n\n if (x118_pitch != 0.f && xec_sfxHandle) {\n CSfxManager::PitchBend(xec_sfxHandle, x118_pitch);\n }\n }\n}\n\nvoid CScriptSound::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId uid, CStateManager& mgr) {\n CActor::AcceptScriptMsg(msg, uid, mgr);\n\n switch (msg) {\n case EScriptObjectMessage::Registered: {\n if (GetActive() && x11c_27_autoStart) {\n x11c_24_playRequested = true;\n }\n x11c_31_selfFree = mgr.GetIsGeneratingObject();\n } break;\n case EScriptObjectMessage::Play: {\n if (GetActive()) {\n PlaySound(mgr);\n }\n } break;\n case EScriptObjectMessage::Stop: {\n if (GetActive()) {\n StopSound(mgr);\n }\n } break;\n case EScriptObjectMessage::Deactivate: {\n StopSound(mgr);\n } break;\n case EScriptObjectMessage::Activate: {\n if (GetActive()) {\n x11c_24_playRequested = true;\n }\n } break;\n case EScriptObjectMessage::Deleted: {\n if (!x11c_30_worldSfx) {\n StopSound(mgr);\n }\n } break;\n default:\n break;\n }\n}\n\nvoid CScriptSound::PlaySound(CStateManager& mgr) {\n if (!x11d_24_allowDuplicates && xec_sfxHandle && !xec_sfxHandle->IsClosed() || x11d_25_processedThisFrame) {\n return;\n }\n\n x11d_25_processedThisFrame = true;\n if (x11c_26_nonEmitter) {\n if (!x11c_30_worldSfx || !mgr.GetWorld()->HasGlobalSound(x100_soundId)) {\n xec_sfxHandle = CSfxManager::SfxStart(x100_soundId, x10e_vol, x114_pan, x11c_29_acoustics, x112_prio,\n x11c_25_looped, x11c_30_worldSfx ? kInvalidAreaId : GetAreaIdAlways());\n if (x11c_30_worldSfx) {\n mgr.GetWorld()->AddGlobalSound(xec_sfxHandle);\n }\n }\n } else {\n const float occVol = x11c_28_occlusionTest ? GetOccludedVolumeAmount(GetTranslation(), mgr) : 1.f;\n xf0_maxVol = xf2_maxVolUpd = x10e_vol * occVol;\n CAudioSys::C3DEmitterParmData data = {};\n data.x0_pos = GetTranslation();\n data.x18_maxDist = x104_maxDist;\n data.x1c_distComp = x108_distComp;\n data.x20_flags = 1; \/\/ Continuous parameter update\n data.x24_sfxId = x100_soundId;\n data.x26_maxVol = xf0_maxVol;\n data.x27_minVol = x10c_minVol;\n data.x29_prio = 0x7f;\n xec_sfxHandle = CSfxManager::AddEmitter(data, x11c_29_acoustics, x112_prio, x11c_25_looped, GetAreaIdAlways());\n }\n}\n\nvoid CScriptSound::StopSound(CStateManager& mgr) {\n x11c_24_playRequested = false;\n if (x11c_30_worldSfx && x11c_26_nonEmitter) {\n mgr.GetWorld()->StopGlobalSound(x100_soundId);\n xec_sfxHandle.reset();\n } else if (xec_sfxHandle) {\n CSfxManager::RemoveEmitter(xec_sfxHandle);\n xec_sfxHandle.reset();\n }\n}\n} \/\/ namespace urde\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include \n#include \n\nnamespace Ndk\n{\n\tinline BaseSystem::BaseSystem(SystemIndex systemId) :\n\tm_systemIndex(systemId)\n\t{\n\t\tSetUpdateRate(30);\n\t}\n\n\tinline BaseSystem::BaseSystem(const BaseSystem& system) :\n\tm_excludedComponents(system.m_excludedComponents),\n\tm_requiredComponents(system.m_requiredComponents),\n\tm_systemIndex(system.m_systemIndex),\n\tm_updateCounter(0.f),\n\tm_updateRate(system.m_updateRate)\n\t{\n\t}\n\n\tinline const std::vector& BaseSystem::GetEntities() const\n\t{\n\t\treturn m_entities;\n\t}\n\n\tinline SystemIndex BaseSystem::GetIndex() const\n\t{\n\t\treturn m_systemIndex;\n\t}\n\n\tinline float BaseSystem::GetUpdateRate() const\n\t{\n\t\treturn 1.f \/ m_updateRate;\n\t}\n\n\tinline World& BaseSystem::GetWorld() const\n\t{\n\t\treturn *m_world;\n\t}\n\n\tinline bool BaseSystem::HasEntity(const Entity* entity) const\n\t{\n\t\tif (!entity)\n\t\t\treturn false;\n\n\t\treturn m_entityBits.UnboundedTest(entity->GetId());\n\t}\n\n\tinline void BaseSystem::SetUpdateRate(float updatePerSecond)\n\t{\n\t\tm_updateCounter = 0.f;\n\t\tm_updateRate = (updatePerSecond > 0.f) ? 1.f \/ updatePerSecond : 0.f; \/\/ 0.f means no limit\n\t}\n\n\tinline void BaseSystem::Update(float elapsedTime)\n\t{\n\t\tm_updateCounter -= elapsedTime;\n\t\tif (m_updateCounter < 0.f)\n\t\t{\n\t\t\tm_updateCounter += m_updateRate;\n\t\t\tOnUpdate(elapsedTime);\n\t\t}\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Excludes()\n\t{\n\t\tstatic_assert(std::is_base_of::value , \"ComponentType is not a component\");\n\n\t\tExcludesComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Excludes()\n\t{\n\t\tExcludes();\n\t\tExcludes();\n\t}\n\n\tinline void BaseSystem::ExcludesComponent(ComponentIndex index)\n\t{\n\t\tm_excludedComponents.UnboundedSet(index);\n\t}\n\n\tinline SystemIndex BaseSystem::GetNextIndex()\n\t{\n\t\treturn s_nextIndex++;\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Requires()\n\t{\n\t\tstatic_assert(std::is_base_of::value, \"ComponentType is not a component\");\n\n\t\tRequiresComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Requires()\n\t{\n\t\tRequires();\n\t\tRequires();\n\t}\n\n\tinline void BaseSystem::RequiresComponent(ComponentIndex index)\n\t{\n\t\tm_requiredComponents.UnboundedSet(index);\n\t}\n\n\ttemplate\n\tvoid BaseSystem::RequiresAny()\n\t{\n\t\tstatic_assert(std::is_base_of::value, \"ComponentType is not a component\");\n\n\t\tRequiresAnyComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::RequiresAny()\n\t{\n\t\tRequiresAny();\n\t\tRequiresAny();\n\t}\n\n\tinline void BaseSystem::RequiresAnyComponent(ComponentIndex index)\n\t{\n\t\tm_requiredAnyComponents.UnboundedSet(index);\n\t}\n\n\tinline void BaseSystem::AddEntity(Entity* entity)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\n\t\tm_entities.emplace_back(entity);\n\t\tm_entityBits.UnboundedSet(entity->GetId(), true);\n\n\t\tentity->RegisterSystem(m_systemIndex);\n\n\t\tOnEntityAdded(entity);\n\t}\n\n\tinline void BaseSystem::RemoveEntity(Entity* entity)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\n\t\tauto it = std::find(m_entities.begin(), m_entities.end(), *entity);\n\t\tNazaraAssert(it != m_entities.end(), \"Entity is not part of this system\");\n\n\t\t\/\/ Pour éviter de déplacer beaucoup de handles, on swap le dernier avec celui à supprimer\n\t\tstd::swap(*it, m_entities.back());\n\t\tm_entities.pop_back(); \/\/ On le sort du vector\n\n\t\tm_entityBits.Reset(entity->GetId());\n\t\tentity->UnregisterSystem(m_systemIndex);\n\n\t\tOnEntityRemoved(entity); \/\/ Et on appelle le callback\n\t}\n\n\tinline void BaseSystem::ValidateEntity(Entity* entity, bool justAdded)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\t\tNazaraAssert(HasEntity(entity), \"Entity should be part of system\");\n\n\t\tOnEntityValidation(entity, justAdded);\n\t}\n\n\tinline void BaseSystem::SetWorld(World& world)\n\t{\n\t\tm_world = &world;\n\t}\n\n\tinline bool BaseSystem::Initialize()\n\t{\n\t\ts_nextIndex = 0;\n\n\t\treturn true;\n\t}\n\n\tinline void BaseSystem::Uninitialize()\n\t{\n\t\t\/\/ Rien à faire\n\t}\n}\nSdk\/BaseSystem: Fix update rate of 0\/\/ Copyright (C) 2015 Jérôme Leclercq\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include \n#include \n\nnamespace Ndk\n{\n\tinline BaseSystem::BaseSystem(SystemIndex systemId) :\n\tm_systemIndex(systemId)\n\t{\n\t\tSetUpdateRate(30);\n\t}\n\n\tinline BaseSystem::BaseSystem(const BaseSystem& system) :\n\tm_excludedComponents(system.m_excludedComponents),\n\tm_requiredComponents(system.m_requiredComponents),\n\tm_systemIndex(system.m_systemIndex),\n\tm_updateCounter(0.f),\n\tm_updateRate(system.m_updateRate)\n\t{\n\t}\n\n\tinline const std::vector& BaseSystem::GetEntities() const\n\t{\n\t\treturn m_entities;\n\t}\n\n\tinline SystemIndex BaseSystem::GetIndex() const\n\t{\n\t\treturn m_systemIndex;\n\t}\n\n\tinline float BaseSystem::GetUpdateRate() const\n\t{\n\t\treturn (m_updateRate > 0.f) ? 1.f \/ m_updateRate : 0.f;\n\t}\n\n\tinline World& BaseSystem::GetWorld() const\n\t{\n\t\treturn *m_world;\n\t}\n\n\tinline bool BaseSystem::HasEntity(const Entity* entity) const\n\t{\n\t\tif (!entity)\n\t\t\treturn false;\n\n\t\treturn m_entityBits.UnboundedTest(entity->GetId());\n\t}\n\n\tinline void BaseSystem::SetUpdateRate(float updatePerSecond)\n\t{\n\t\tm_updateCounter = 0.f;\n\t\tm_updateRate = (updatePerSecond > 0.f) ? 1.f \/ updatePerSecond : 0.f; \/\/ 0.f means no limit\n\t}\n\n\tinline void BaseSystem::Update(float elapsedTime)\n\t{\n\t\tif (m_updateRate > 0.f)\n\t\t{\n\t\t\tm_updateCounter -= elapsedTime;\n\t\t\tif (m_updateCounter >= 0.f)\n\t\t\t\treturn;\n\n\t\t\tm_updateCounter += m_updateRate;\n\t\t}\n\n\t\tOnUpdate(elapsedTime);\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Excludes()\n\t{\n\t\tstatic_assert(std::is_base_of::value , \"ComponentType is not a component\");\n\n\t\tExcludesComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Excludes()\n\t{\n\t\tExcludes();\n\t\tExcludes();\n\t}\n\n\tinline void BaseSystem::ExcludesComponent(ComponentIndex index)\n\t{\n\t\tm_excludedComponents.UnboundedSet(index);\n\t}\n\n\tinline SystemIndex BaseSystem::GetNextIndex()\n\t{\n\t\treturn s_nextIndex++;\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Requires()\n\t{\n\t\tstatic_assert(std::is_base_of::value, \"ComponentType is not a component\");\n\n\t\tRequiresComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::Requires()\n\t{\n\t\tRequires();\n\t\tRequires();\n\t}\n\n\tinline void BaseSystem::RequiresComponent(ComponentIndex index)\n\t{\n\t\tm_requiredComponents.UnboundedSet(index);\n\t}\n\n\ttemplate\n\tvoid BaseSystem::RequiresAny()\n\t{\n\t\tstatic_assert(std::is_base_of::value, \"ComponentType is not a component\");\n\n\t\tRequiresAnyComponent(GetComponentIndex());\n\t}\n\n\ttemplate\n\tvoid BaseSystem::RequiresAny()\n\t{\n\t\tRequiresAny();\n\t\tRequiresAny();\n\t}\n\n\tinline void BaseSystem::RequiresAnyComponent(ComponentIndex index)\n\t{\n\t\tm_requiredAnyComponents.UnboundedSet(index);\n\t}\n\n\tinline void BaseSystem::AddEntity(Entity* entity)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\n\t\tm_entities.emplace_back(entity);\n\t\tm_entityBits.UnboundedSet(entity->GetId(), true);\n\n\t\tentity->RegisterSystem(m_systemIndex);\n\n\t\tOnEntityAdded(entity);\n\t}\n\n\tinline void BaseSystem::RemoveEntity(Entity* entity)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\n\t\tauto it = std::find(m_entities.begin(), m_entities.end(), *entity);\n\t\tNazaraAssert(it != m_entities.end(), \"Entity is not part of this system\");\n\n\t\t\/\/ Pour éviter de déplacer beaucoup de handles, on swap le dernier avec celui à supprimer\n\t\tstd::swap(*it, m_entities.back());\n\t\tm_entities.pop_back(); \/\/ On le sort du vector\n\n\t\tm_entityBits.Reset(entity->GetId());\n\t\tentity->UnregisterSystem(m_systemIndex);\n\n\t\tOnEntityRemoved(entity); \/\/ Et on appelle le callback\n\t}\n\n\tinline void BaseSystem::ValidateEntity(Entity* entity, bool justAdded)\n\t{\n\t\tNazaraAssert(entity, \"Invalid entity\");\n\t\tNazaraAssert(HasEntity(entity), \"Entity should be part of system\");\n\n\t\tOnEntityValidation(entity, justAdded);\n\t}\n\n\tinline void BaseSystem::SetWorld(World& world)\n\t{\n\t\tm_world = &world;\n\t}\n\n\tinline bool BaseSystem::Initialize()\n\t{\n\t\ts_nextIndex = 0;\n\n\t\treturn true;\n\t}\n\n\tinline void BaseSystem::Uninitialize()\n\t{\n\t\t\/\/ Rien à faire\n\t}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include \n#include \n\nnamespace Ndk\n{\n\t\/*!\n\t* \\brief Binds SDK module to Lua\n\t*\/\n\n\tvoid LuaBinding::BindSDK()\n\t{\n\t\t\/*********************************** Ndk::Application **********************************\/\n\n\t\t#ifndef NDK_SERVER\n\t\t\/\/application.SetMethod(\"AddWindow\", &Application::AddWindow);\n\t\t#endif\n\t\tapplication.BindMethod(\"AddWorld\", [] (Nz::LuaInstance& instance, Application* application) -> int\n\t\t{\n\t\t\tinstance.Push(application->AddWorld().CreateHandle());\n\t\t\treturn 1;\n\t\t});\n\n\t\tapplication.BindMethod(\"GetUpdateTime\", &Application::GetUpdateTime);\n\t\tapplication.BindMethod(\"Quit\", &Application::Quit);\n\n\t\t\/*********************************** Ndk::Console **********************************\/\n\t\t#ifndef NDK_SERVER\n\t\tconsoleClass.Inherit(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node*\n\t\t{\n\t\t\treturn handle->GetObject();\n\t\t});\n\n\t\tconsoleClass.BindMethod(\"AddLine\", &Console::AddLine, Nz::Color::White);\n\t\tconsoleClass.BindMethod(\"Clear\", &Console::Clear);\n\t\tconsoleClass.BindMethod(\"GetCharacterSize\", &Console::GetCharacterSize);\n\t\tconsoleClass.BindMethod(\"GetHistory\", &Console::GetHistory);\n\t\tconsoleClass.BindMethod(\"GetHistoryBackground\", &Console::GetHistoryBackground);\n\t\tconsoleClass.BindMethod(\"GetInput\", &Console::GetInput);\n\t\tconsoleClass.BindMethod(\"GetInputBackground\", &Console::GetInputBackground);\n\t\tconsoleClass.BindMethod(\"GetSize\", &Console::GetSize);\n\t\tconsoleClass.BindMethod(\"GetTextFont\", &Console::GetTextFont);\n\n\t\tconsoleClass.BindMethod(\"IsVisible\", &Console::IsVisible);\n\n\t\tconsoleClass.BindMethod(\"SendCharacter\", &Console::SendCharacter);\n\t\t\/\/consoleClass.SetMethod(\"SendEvent\", &Console::SendEvent);\n\n\t\tconsoleClass.BindMethod(\"SetCharacterSize\", &Console::SetCharacterSize);\n\t\tconsoleClass.BindMethod(\"SetSize\", &Console::SetSize);\n\t\tconsoleClass.BindMethod(\"SetTextFont\", &Console::SetTextFont);\n\t\t\n\t\tconsoleClass.BindMethod(\"Show\", &Console::Show, true);\n\t\t#endif\n\n\t\t\/*********************************** Ndk::Entity **********************************\/\n\t\tentityClass.BindMethod(\"Enable\", &Entity::Enable);\n\t\tentityClass.BindMethod(\"GetId\", &Entity::GetId);\n\t\tentityClass.BindMethod(\"GetWorld\", &Entity::GetWorld);\n\t\tentityClass.BindMethod(\"Kill\", &Entity::Kill);\n\t\tentityClass.BindMethod(\"IsEnabled\", &Entity::IsEnabled);\n\t\tentityClass.BindMethod(\"IsValid\", &Entity::IsValid);\n\t\tentityClass.BindMethod(\"RemoveAllComponents\", &Entity::RemoveAllComponents);\n\t\tentityClass.BindMethod(\"__tostring\", &EntityHandle::ToString);\n\n\t\tentityClass.BindMethod(\"AddComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\treturn binding->adder(instance, handle);\n\t\t});\n\n\t\tentityClass.BindMethod(\"GetComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\treturn binding->getter(instance, handle->GetComponent(binding->index));\n\t\t});\n\n\t\tentityClass.BindMethod(\"RemoveComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\thandle->RemoveComponent(binding->index);\n\t\t\treturn 0;\n\t\t});\n\n\t\t\/*********************************** Ndk::NodeComponent **********************************\/\n\t\tnodeComponent.Inherit(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node*\n\t\t{\n\t\t\treturn handle->GetObject();\n\t\t});\n\n\t\t\/*********************************** Ndk::VelocityComponent **********************************\/\n\t\tvelocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)\n\t\t{\n\t\t\tstd::size_t length;\n\t\t\tconst char* member = lua.CheckString(1, &length);\n\n\t\t\tif (std::strcmp(member, \"Linear\") == 0)\n\t\t\t{\n\t\t\t\tlua.Push(instance->linearVelocity);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t});\n\n\t\tvelocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)\n\t\t{\n\t\t\tstd::size_t length;\n\t\t\tconst char* member = lua.CheckString(1, &length);\n\n\t\t\tint argIndex = 2;\n\t\t\tif (std::strcmp(member, \"Linear\") == 0)\n\t\t\t{\n\t\t\t\tinstance->linearVelocity = lua.Check(&argIndex);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t});\n\n\t\t\/*********************************** Ndk::World **********************************\/\n\t\tworldClass.BindMethod(\"CreateEntity\", &World::CreateEntity);\n\t\tworldClass.BindMethod(\"CreateEntities\", &World::CreateEntities);\n\t\tworldClass.BindMethod(\"Clear\", &World::Clear);\n\n\n\t\t#ifndef NDK_SERVER\n\t\t\/*********************************** Ndk::GraphicsComponent **********************************\/\n\t\tgraphicsComponent.BindMethod(\"Attach\", &GraphicsComponent::Attach, 0);\n\t\t#endif\n\n\n\t\t\/\/ Components functions\n\t\tm_componentBinding.resize(BaseComponent::GetMaxComponentIndex());\n\n\t\tBindComponent(\"Node\");\n\t\tBindComponent(\"Velocity\");\n\n\t\t#ifndef NDK_SERVER\n\t\tBindComponent(\"Graphics\");\n\t\t#endif\n\t}\n\n\t\/*!\n\t* \\brief Registers the classes that will be used by the Lua instance\n\t*\n\t* \\param instance Lua instance that will interact with the SDK classes\n\t*\/\n\n\tvoid LuaBinding::RegisterSDK(Nz::LuaInstance& instance)\n\t{\n\t\t\/\/ Classes\n\t\tapplication.Register(instance);\n\t\tentityClass.Register(instance);\n\t\tnodeComponent.Register(instance);\n\t\tvelocityComponent.Register(instance);\n\t\tworldClass.Register(instance);\n\n\t\t#ifndef NDK_SERVER\n\t\tconsoleClass.Register(instance);\n\t\tgraphicsComponent.Register(instance);\n\t\t#endif\n\n\t\t\/\/ Enums\n\n\t\t\/\/ ComponentType (fake enumeration to expose component indexes)\n\t\tinstance.PushTable(0, m_componentBinding.size());\n\t\t{\n\t\t\tfor (const ComponentBinding& entry : m_componentBinding)\n\t\t\t{\n\t\t\t\tif (entry.name.IsEmpty())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tinstance.PushField(entry.name, entry.index);\n\t\t\t}\n\t\t}\n\t\tinstance.SetGlobal(\"ComponentType\");\n\t}\n\n\t\/*!\n\t* \\brief Gets the index of the component\n\t* \\return A pointer to the binding linked to a component\n\t*\n\t* \\param instance Lua instance that will interact with the component\n\t* \\param argIndex Index of the component\n\t*\/\n\n\tLuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)\n\t{\n\t\tswitch (instance.GetType(argIndex))\n\t\t{\n\t\t\tcase Nz::LuaType_Number:\n\t\t\t{\n\t\t\t\tComponentIndex componentIndex = instance.Check(&argIndex);\n\t\t\t\tif (componentIndex > m_componentBinding.size())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component index\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tComponentBinding& binding = m_componentBinding[componentIndex];\n\t\t\t\tif (binding.name.IsEmpty())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component index\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\treturn &binding;\n\t\t\t}\n\n\t\t\tcase Nz::LuaType_String:\n\t\t\t{\n\t\t\t\tconst char* key = instance.CheckString(argIndex);\n\t\t\t\tauto it = m_componentBindingByName.find(key);\n\t\t\t\tif (it == m_componentBindingByName.end())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component name\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\treturn &m_componentBinding[it->second];\n\t\t\t}\n\t\t}\n\n\t\tinstance.Error(\"Invalid component index at #\" + Nz::String::Number(argIndex));\n\t\treturn nullptr;\n\t}\n}\nSdk\/Binding: Fix Entity::Enable default argument\/\/ Copyright (C) 2016 Jrme Leclercq, Arnaud Cadot\n\/\/ This file is part of the \"Nazara Development Kit\"\n\/\/ For conditions of distribution and use, see copyright notice in Prerequesites.hpp\n\n#include \n#include \n\nnamespace Ndk\n{\n\t\/*!\n\t* \\brief Binds SDK module to Lua\n\t*\/\n\n\tvoid LuaBinding::BindSDK()\n\t{\n\t\t\/*********************************** Ndk::Application **********************************\/\n\n\t\t#ifndef NDK_SERVER\n\t\t\/\/application.SetMethod(\"AddWindow\", &Application::AddWindow);\n\t\t#endif\n\t\tapplication.BindMethod(\"AddWorld\", [] (Nz::LuaInstance& instance, Application* application) -> int\n\t\t{\n\t\t\tinstance.Push(application->AddWorld().CreateHandle());\n\t\t\treturn 1;\n\t\t});\n\n\t\tapplication.BindMethod(\"GetUpdateTime\", &Application::GetUpdateTime);\n\t\tapplication.BindMethod(\"Quit\", &Application::Quit);\n\n\t\t\/*********************************** Ndk::Console **********************************\/\n\t\t#ifndef NDK_SERVER\n\t\tconsoleClass.Inherit(nodeClass, [] (ConsoleHandle* handle) -> Nz::Node*\n\t\t{\n\t\t\treturn handle->GetObject();\n\t\t});\n\n\t\tconsoleClass.BindMethod(\"AddLine\", &Console::AddLine, Nz::Color::White);\n\t\tconsoleClass.BindMethod(\"Clear\", &Console::Clear);\n\t\tconsoleClass.BindMethod(\"GetCharacterSize\", &Console::GetCharacterSize);\n\t\tconsoleClass.BindMethod(\"GetHistory\", &Console::GetHistory);\n\t\tconsoleClass.BindMethod(\"GetHistoryBackground\", &Console::GetHistoryBackground);\n\t\tconsoleClass.BindMethod(\"GetInput\", &Console::GetInput);\n\t\tconsoleClass.BindMethod(\"GetInputBackground\", &Console::GetInputBackground);\n\t\tconsoleClass.BindMethod(\"GetSize\", &Console::GetSize);\n\t\tconsoleClass.BindMethod(\"GetTextFont\", &Console::GetTextFont);\n\n\t\tconsoleClass.BindMethod(\"IsVisible\", &Console::IsVisible);\n\n\t\tconsoleClass.BindMethod(\"SendCharacter\", &Console::SendCharacter);\n\t\t\/\/consoleClass.SetMethod(\"SendEvent\", &Console::SendEvent);\n\n\t\tconsoleClass.BindMethod(\"SetCharacterSize\", &Console::SetCharacterSize);\n\t\tconsoleClass.BindMethod(\"SetSize\", &Console::SetSize);\n\t\tconsoleClass.BindMethod(\"SetTextFont\", &Console::SetTextFont);\n\t\t\n\t\tconsoleClass.BindMethod(\"Show\", &Console::Show, true);\n\t\t#endif\n\n\t\t\/*********************************** Ndk::Entity **********************************\/\n\t\tentityClass.BindMethod(\"Enable\", &Entity::Enable, true);\n\t\tentityClass.BindMethod(\"GetId\", &Entity::GetId);\n\t\tentityClass.BindMethod(\"GetWorld\", &Entity::GetWorld);\n\t\tentityClass.BindMethod(\"Kill\", &Entity::Kill);\n\t\tentityClass.BindMethod(\"IsEnabled\", &Entity::IsEnabled);\n\t\tentityClass.BindMethod(\"IsValid\", &Entity::IsValid);\n\t\tentityClass.BindMethod(\"RemoveAllComponents\", &Entity::RemoveAllComponents);\n\t\tentityClass.BindMethod(\"__tostring\", &EntityHandle::ToString);\n\n\t\tentityClass.BindMethod(\"AddComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\treturn binding->adder(instance, handle);\n\t\t});\n\n\t\tentityClass.BindMethod(\"GetComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\treturn binding->getter(instance, handle->GetComponent(binding->index));\n\t\t});\n\n\t\tentityClass.BindMethod(\"RemoveComponent\", [this] (Nz::LuaInstance& instance, EntityHandle& handle) -> int\n\t\t{\n\t\t\tComponentBinding* binding = QueryComponentIndex(instance);\n\n\t\t\thandle->RemoveComponent(binding->index);\n\t\t\treturn 0;\n\t\t});\n\n\t\t\/*********************************** Ndk::NodeComponent **********************************\/\n\t\tnodeComponent.Inherit(nodeClass, [] (NodeComponentHandle* handle) -> Nz::Node*\n\t\t{\n\t\t\treturn handle->GetObject();\n\t\t});\n\n\t\t\/*********************************** Ndk::VelocityComponent **********************************\/\n\t\tvelocityComponent.SetGetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)\n\t\t{\n\t\t\tstd::size_t length;\n\t\t\tconst char* member = lua.CheckString(1, &length);\n\n\t\t\tif (std::strcmp(member, \"Linear\") == 0)\n\t\t\t{\n\t\t\t\tlua.Push(instance->linearVelocity);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t});\n\n\t\tvelocityComponent.SetSetter([] (Nz::LuaInstance& lua, VelocityComponentHandle& instance)\n\t\t{\n\t\t\tstd::size_t length;\n\t\t\tconst char* member = lua.CheckString(1, &length);\n\n\t\t\tint argIndex = 2;\n\t\t\tif (std::strcmp(member, \"Linear\") == 0)\n\t\t\t{\n\t\t\t\tinstance->linearVelocity = lua.Check(&argIndex);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn false;\n\t\t});\n\n\t\t\/*********************************** Ndk::World **********************************\/\n\t\tworldClass.BindMethod(\"CreateEntity\", &World::CreateEntity);\n\t\tworldClass.BindMethod(\"CreateEntities\", &World::CreateEntities);\n\t\tworldClass.BindMethod(\"Clear\", &World::Clear);\n\n\n\t\t#ifndef NDK_SERVER\n\t\t\/*********************************** Ndk::GraphicsComponent **********************************\/\n\t\tgraphicsComponent.BindMethod(\"Attach\", &GraphicsComponent::Attach, 0);\n\t\t#endif\n\n\n\t\t\/\/ Components functions\n\t\tm_componentBinding.resize(BaseComponent::GetMaxComponentIndex());\n\n\t\tBindComponent(\"Node\");\n\t\tBindComponent(\"Velocity\");\n\n\t\t#ifndef NDK_SERVER\n\t\tBindComponent(\"Graphics\");\n\t\t#endif\n\t}\n\n\t\/*!\n\t* \\brief Registers the classes that will be used by the Lua instance\n\t*\n\t* \\param instance Lua instance that will interact with the SDK classes\n\t*\/\n\n\tvoid LuaBinding::RegisterSDK(Nz::LuaInstance& instance)\n\t{\n\t\t\/\/ Classes\n\t\tapplication.Register(instance);\n\t\tentityClass.Register(instance);\n\t\tnodeComponent.Register(instance);\n\t\tvelocityComponent.Register(instance);\n\t\tworldClass.Register(instance);\n\n\t\t#ifndef NDK_SERVER\n\t\tconsoleClass.Register(instance);\n\t\tgraphicsComponent.Register(instance);\n\t\t#endif\n\n\t\t\/\/ Enums\n\n\t\t\/\/ ComponentType (fake enumeration to expose component indexes)\n\t\tinstance.PushTable(0, m_componentBinding.size());\n\t\t{\n\t\t\tfor (const ComponentBinding& entry : m_componentBinding)\n\t\t\t{\n\t\t\t\tif (entry.name.IsEmpty())\n\t\t\t\t\tcontinue;\n\n\t\t\t\tinstance.PushField(entry.name, entry.index);\n\t\t\t}\n\t\t}\n\t\tinstance.SetGlobal(\"ComponentType\");\n\t}\n\n\t\/*!\n\t* \\brief Gets the index of the component\n\t* \\return A pointer to the binding linked to a component\n\t*\n\t* \\param instance Lua instance that will interact with the component\n\t* \\param argIndex Index of the component\n\t*\/\n\n\tLuaBinding::ComponentBinding* LuaBinding::QueryComponentIndex(Nz::LuaInstance& instance, int argIndex)\n\t{\n\t\tswitch (instance.GetType(argIndex))\n\t\t{\n\t\t\tcase Nz::LuaType_Number:\n\t\t\t{\n\t\t\t\tComponentIndex componentIndex = instance.Check(&argIndex);\n\t\t\t\tif (componentIndex > m_componentBinding.size())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component index\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\tComponentBinding& binding = m_componentBinding[componentIndex];\n\t\t\t\tif (binding.name.IsEmpty())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component index\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\treturn &binding;\n\t\t\t}\n\n\t\t\tcase Nz::LuaType_String:\n\t\t\t{\n\t\t\t\tconst char* key = instance.CheckString(argIndex);\n\t\t\t\tauto it = m_componentBindingByName.find(key);\n\t\t\t\tif (it == m_componentBindingByName.end())\n\t\t\t\t{\n\t\t\t\t\tinstance.Error(\"Invalid component name\");\n\t\t\t\t\treturn nullptr;\n\t\t\t\t}\n\n\t\t\t\treturn &m_componentBinding[it->second];\n\t\t\t}\n\t\t}\n\n\t\tinstance.Error(\"Invalid component index at #\" + Nz::String::Number(argIndex));\n\t\treturn nullptr;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (c) 2001-2004, Kurt Revis. All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of Kurt Revis, nor Snoize, nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.\n *\/\n\n\n#include \"MessagePortBroadcaster.h\"\n\n#include \"MIDISpyShared.h\"\n#include \n\n\n\/\/ Private function declarations\nCFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info);\nvoid MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info);\nvoid RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context);\n\n\n\/\/ NOTE This static variable is a dumb workaround. See comment in MessagePortWasInvalidated().\nstatic MessagePortBroadcaster *sOneBroadcaster = NULL;\n\n\nMessagePortBroadcaster::MessagePortBroadcaster(CFStringRef broadcasterName, MessagePortBroadcasterDelegate *delegate) :\n mDelegate(delegate),\n mBroadcasterName(NULL),\n mLocalPort(NULL),\n mRunLoopSource(NULL),\n mNextListenerIdentifier(0),\n mListenersByIdentifier(NULL),\n mIdentifiersByListener(NULL),\n mListenerArraysByChannel(NULL)\n{\n CFMessagePortContext messagePortContext = { 0, (void *)this, NULL, NULL, NULL };\n\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: creating\\n\");\n #endif\n \n sOneBroadcaster = this;\n \n if (!broadcasterName)\n broadcasterName = CFSTR(\"Unknown Broadcaster\");\n mBroadcasterName = CFStringCreateCopy(kCFAllocatorDefault, broadcasterName);\n if (!mBroadcasterName)\n goto abort;\n\n \/\/ Create a local port for remote listeners to talk to us with\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: creating local port\\n\");\n #endif\n mLocalPort = CFMessagePortCreateLocal(kCFAllocatorDefault, mBroadcasterName, LocalMessagePortCallBack, &messagePortContext, FALSE);\n if (!mLocalPort) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create local port!\\n\");\n #endif\n goto abort;\n }\n\n \/\/ And add it to the current run loop\n mRunLoopSource = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, mLocalPort, 0);\n if (!mRunLoopSource) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create run loop source for local port!\\n\");\n #endif \n goto abort;\n }\n CFRunLoopAddSource(CFRunLoopGetCurrent(), mRunLoopSource, kCFRunLoopDefaultMode);\n\n \/\/ Create structures to keep track of our listeners\n mListenersByIdentifier = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);\n mIdentifiersByListener = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);\n mListenerArraysByChannel = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);\n if (!mListenersByIdentifier || !mIdentifiersByListener || !mListenerArraysByChannel) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create a listener dictionary!\\n\");\n #endif\n goto abort; \n }\n\n pthread_mutex_init(&mListenerStructuresMutex, NULL);\n\n return;\n\nabort:\n if (mListenerArraysByChannel)\n CFRelease(mListenerArraysByChannel);\n\n if (mIdentifiersByListener)\n CFRelease(mIdentifiersByListener);\n\n if (mListenersByIdentifier)\n CFRelease(mListenersByIdentifier);\n\n if (mRunLoopSource) {\n CFRunLoopSourceInvalidate(mRunLoopSource);\n CFRelease(mRunLoopSource);\n }\n\n if (mLocalPort) {\n CFMessagePortInvalidate(mLocalPort);\n CFRelease(mLocalPort);\n }\n \n if (mBroadcasterName)\n CFRelease(mBroadcasterName);\n\n throw MessagePortBroadcasterException();\n}\n\nMessagePortBroadcaster::~MessagePortBroadcaster()\n{\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: destroying\\n\");\n #endif\n\n \/\/ As we delete our dictionaries, any leftover remote CFMessagePorts will get invalidated.\n \/\/ But we want to bypass the usual invalidation code (since we're just taking everything\n \/\/ down anyway), so we set sOneBroadcaster to NULL. MessagePortWasInvalidated() will\n \/\/ still get called, but it won't be able to call back into this C++ object.\n \/\/ NOTE When restructuring to get rid of sOneBroadcaster, you'll need to rethink this.\n sOneBroadcaster = NULL;\n\n pthread_mutex_destroy(&mListenerStructuresMutex);\n\n if (mListenerArraysByChannel)\n CFRelease(mListenerArraysByChannel);\n\n if (mIdentifiersByListener)\n CFRelease(mIdentifiersByListener);\n\n if (mListenersByIdentifier)\n CFRelease(mListenersByIdentifier);\n\n if (mRunLoopSource) {\n CFRunLoopSourceInvalidate(mRunLoopSource);\n CFRelease(mRunLoopSource);\n }\n\n if (mLocalPort) {\n CFMessagePortInvalidate(mLocalPort);\n CFRelease(mLocalPort);\n }\n\n if (mBroadcasterName)\n CFRelease(mBroadcasterName); \n}\n\nvoid MessagePortBroadcaster::Broadcast(CFDataRef data, SInt32 channel)\n{\n CFArrayRef listeners;\n CFIndex listenerIndex;\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: broadcast(%p, %p)\\n\", data, (void *)channel);\n #endif\n \n pthread_mutex_lock(&mListenerStructuresMutex);\n\n listeners = (CFArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, (void *)channel);\n if (listeners) {\n listenerIndex = CFArrayGetCount(listeners);\n \n while (listenerIndex--) {\n CFMessagePortRef listenerPort = (CFMessagePortRef)CFArrayGetValueAtIndex(listeners, listenerIndex);\n CFMessagePortSendRequest(listenerPort, 0, data, 300, 0, NULL, NULL);\n }\n }\n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n}\n\n\n\/\/\n\/\/ Private functions and methods\n\/\/\n\nCFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info)\n{\n MessagePortBroadcaster *broadcaster = (MessagePortBroadcaster *)info;\n CFDataRef result = NULL;\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: message port callback(msgid=%ld)\\n\", msgid);\n #endif\n \n switch (msgid) {\n case kSpyingMIDIDriverGetNextListenerIdentifierMessageID:\n result = broadcaster->NextListenerIdentifier();\n break;\n\n case kSpyingMIDIDriverAddListenerMessageID:\n broadcaster->AddListener(data);\n break;\n\n case kSpyingMIDIDriverConnectDestinationMessageID:\n broadcaster->ChangeListenerChannelStatus(data, true);\n break;\n\n case kSpyingMIDIDriverDisconnectDestinationMessageID:\n broadcaster->ChangeListenerChannelStatus(data, false);\n break;\n\n default:\n break; \n }\n\n return result;\n}\n\nCFDataRef\tMessagePortBroadcaster::NextListenerIdentifier()\n{\n \/\/ Client is starting up; it wants to know what identifier to use (so it can name its local port).\n \/\/ We give it that data in a reply.\n\n CFDataRef returnedData;\n\n mNextListenerIdentifier++;\n returnedData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&mNextListenerIdentifier, sizeof(UInt32));\n\n return returnedData;\n}\n\nvoid\tMessagePortBroadcaster::AddListener(CFDataRef listenerIdentifierData)\n{\n \/\/ The listener has created a local port on its side, and we need to create a remote port for it.\n \/\/ No reply is necessary.\n\n const UInt8 *dataBytes;\n UInt32 listenerIdentifier;\n CFStringRef listenerPortName;\n CFMessagePortRef remotePort;\n\n if (!listenerIdentifierData || CFDataGetLength(listenerIdentifierData) != sizeof(UInt32))\n return;\n\n dataBytes = CFDataGetBytePtr(listenerIdentifierData);\n if (!dataBytes)\n return;\n\n listenerIdentifier = *(const UInt32 *)dataBytes;\n listenerPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR(\"%@-%lu\"), mBroadcasterName, listenerIdentifier);\n\n remotePort = CFMessagePortCreateRemote(kCFAllocatorDefault, listenerPortName);\n if (remotePort) {\n CFMessagePortSetInvalidationCallBack(remotePort, MessagePortWasInvalidated);\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n CFDictionarySetValue(mListenersByIdentifier, (void *)listenerIdentifier, (void *)remotePort);\n CFDictionarySetValue(mIdentifiersByListener, (void *)remotePort, (void *)listenerIdentifier);\n pthread_mutex_unlock(&mListenerStructuresMutex);\n\n CFRelease(remotePort);\n\n \/\/ TODO we don't really want to do this here -- we want to do it when the client adds a channel\n if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 1)\n mDelegate->BroadcasterListenerCountChanged(this, true);\n }\n\n CFRelease(listenerPortName);\n}\n\nvoid\tMessagePortBroadcaster::ChangeListenerChannelStatus(CFDataRef messageData, Boolean shouldAdd)\n{\n \/\/ From the message data given, take out the identifier of the listener, and the channel it is concerned with.\n \/\/ Then find the remote message port corresponding to that identifier.\n \/\/ Then find the array of listeners for this channel (creating it if necessary), and add\/remove the remote port from the array.\n \/\/ No reply is necessary.\n \n const UInt8 *dataBytes;\n UInt32 identifier;\n SInt32 channel;\n CFMessagePortRef remotePort;\n CFMutableArrayRef channelListeners;\n\n if (!messageData || CFDataGetLength(messageData) != sizeof(UInt32) + sizeof(SInt32))\n return;\n dataBytes = CFDataGetBytePtr(messageData);\n if (!dataBytes)\n return;\n identifier = *(UInt32 *)dataBytes;\n channel = *(SInt32 *)(dataBytes + sizeof(UInt32));\n\n remotePort = (CFMessagePortRef)CFDictionaryGetValue(mListenersByIdentifier, (void *)identifier);\n if (!remotePort)\n return;\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n \n channelListeners = (CFMutableArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, (void *)channel);\n if (!channelListeners && shouldAdd) {\n channelListeners = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);\n CFDictionarySetValue(mListenerArraysByChannel, (void *)channel, channelListeners);\n }\n\n if (shouldAdd) {\n CFArrayAppendValue(channelListeners, remotePort);\n } else if (channelListeners) {\n CFIndex index;\n\n index = CFArrayGetFirstIndexOfValue(channelListeners, CFRangeMake(0, CFArrayGetCount(channelListeners)), remotePort);\n if (index != kCFNotFound)\n CFArrayRemoveValueAtIndex(channelListeners, index);\n }\n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n}\n\nvoid MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info)\n{\n \/\/ NOTE: The info pointer provided to this function is useless. CFMessagePort provides no way to set it for remote ports.\n \/\/ Thus, we have to assume we have one MessagePortBroadcaster, which we look up statically. Lame!\n \/\/ TODO come up with a better solution to this\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: remote port was invalidated\\n\");\n #endif\n\n if (sOneBroadcaster)\n sOneBroadcaster->RemoveListenerWithRemotePort(messagePort);\n}\n\nvoid\tMessagePortBroadcaster::RemoveListenerWithRemotePort(CFMessagePortRef remotePort)\n{\n UInt32 identifier;\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n\n \/\/ Remove this listener from our dictionaries\n const void* ptrId = CFDictionaryGetValue(mIdentifiersByListener, (void *)remotePort);\n#if __LP64__\n identifier = (uintptr_t)ptrId & 0xFFFFFFFFUL;\n#else\n identifier = (UInt32)ptrId;\n#endif\n CFDictionaryRemoveValue(mListenersByIdentifier, (void *)identifier);\n CFDictionaryRemoveValue(mIdentifiersByListener, (void *)remotePort);\n\n \/\/ Also go through the listener array for each channel and remove remotePort from there too\n CFDictionaryApplyFunction(mListenerArraysByChannel, RemoveRemotePortFromChannelArray, remotePort); \n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n\n \/\/ TODO we don't really want to do this here -- we want to do it when a client removes a channel\n if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 0)\n mDelegate->BroadcasterListenerCountChanged(this, false); \n}\n\nvoid RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context)\n{\n \/\/ We don't care about the key (it's a channel number)\n CFMutableArrayRef listenerArray = (CFMutableArrayRef)value;\n CFMessagePortRef remotePort = (CFMessagePortRef)context;\n CFIndex index;\n\n index = CFArrayGetFirstIndexOfValue(listenerArray, CFRangeMake(0, CFArrayGetCount(listenerArray)), remotePort);\n if (index != kCFNotFound)\n CFArrayRemoveValueAtIndex(listenerArray, index);\n}\nFix a potential leak (caught by the analyzer)\/*\n Copyright (c) 2001-2004, Kurt Revis. All rights reserved.\n \n Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n \n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * Neither the name of Kurt Revis, nor Snoize, nor the names of other contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n \n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.\n *\/\n\n\n#include \"MessagePortBroadcaster.h\"\n\n#include \"MIDISpyShared.h\"\n#include \n\n\n\/\/ Private function declarations\nCFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info);\nvoid MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info);\nvoid RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context);\n\n\n\/\/ NOTE This static variable is a dumb workaround. See comment in MessagePortWasInvalidated().\nstatic MessagePortBroadcaster *sOneBroadcaster = NULL;\n\n\nMessagePortBroadcaster::MessagePortBroadcaster(CFStringRef broadcasterName, MessagePortBroadcasterDelegate *delegate) :\n mDelegate(delegate),\n mBroadcasterName(NULL),\n mLocalPort(NULL),\n mRunLoopSource(NULL),\n mNextListenerIdentifier(0),\n mListenersByIdentifier(NULL),\n mIdentifiersByListener(NULL),\n mListenerArraysByChannel(NULL)\n{\n CFMessagePortContext messagePortContext = { 0, (void *)this, NULL, NULL, NULL };\n\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: creating\\n\");\n #endif\n \n sOneBroadcaster = this;\n \n if (!broadcasterName)\n broadcasterName = CFSTR(\"Unknown Broadcaster\");\n mBroadcasterName = CFStringCreateCopy(kCFAllocatorDefault, broadcasterName);\n if (!mBroadcasterName)\n goto abort;\n\n \/\/ Create a local port for remote listeners to talk to us with\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: creating local port\\n\");\n #endif\n mLocalPort = CFMessagePortCreateLocal(kCFAllocatorDefault, mBroadcasterName, LocalMessagePortCallBack, &messagePortContext, FALSE);\n if (!mLocalPort) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create local port!\\n\");\n #endif\n goto abort;\n }\n\n \/\/ And add it to the current run loop\n mRunLoopSource = CFMessagePortCreateRunLoopSource(kCFAllocatorDefault, mLocalPort, 0);\n if (!mRunLoopSource) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create run loop source for local port!\\n\");\n #endif \n goto abort;\n }\n CFRunLoopAddSource(CFRunLoopGetCurrent(), mRunLoopSource, kCFRunLoopDefaultMode);\n\n \/\/ Create structures to keep track of our listeners\n mListenersByIdentifier = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);\n mIdentifiersByListener = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, NULL);\n mListenerArraysByChannel = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, &kCFTypeDictionaryValueCallBacks);\n if (!mListenersByIdentifier || !mIdentifiersByListener || !mListenerArraysByChannel) {\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: couldn't create a listener dictionary!\\n\");\n #endif\n goto abort; \n }\n\n pthread_mutex_init(&mListenerStructuresMutex, NULL);\n\n return;\n\nabort:\n if (mListenerArraysByChannel)\n CFRelease(mListenerArraysByChannel);\n\n if (mIdentifiersByListener)\n CFRelease(mIdentifiersByListener);\n\n if (mListenersByIdentifier)\n CFRelease(mListenersByIdentifier);\n\n if (mRunLoopSource) {\n CFRunLoopSourceInvalidate(mRunLoopSource);\n CFRelease(mRunLoopSource);\n }\n\n if (mLocalPort) {\n CFMessagePortInvalidate(mLocalPort);\n CFRelease(mLocalPort);\n }\n \n if (mBroadcasterName)\n CFRelease(mBroadcasterName);\n\n throw MessagePortBroadcasterException();\n}\n\nMessagePortBroadcaster::~MessagePortBroadcaster()\n{\n #if DEBUG\n fprintf(stderr, \"MessagePortBroadcaster: destroying\\n\");\n #endif\n\n \/\/ As we delete our dictionaries, any leftover remote CFMessagePorts will get invalidated.\n \/\/ But we want to bypass the usual invalidation code (since we're just taking everything\n \/\/ down anyway), so we set sOneBroadcaster to NULL. MessagePortWasInvalidated() will\n \/\/ still get called, but it won't be able to call back into this C++ object.\n \/\/ NOTE When restructuring to get rid of sOneBroadcaster, you'll need to rethink this.\n sOneBroadcaster = NULL;\n\n pthread_mutex_destroy(&mListenerStructuresMutex);\n\n if (mListenerArraysByChannel)\n CFRelease(mListenerArraysByChannel);\n\n if (mIdentifiersByListener)\n CFRelease(mIdentifiersByListener);\n\n if (mListenersByIdentifier)\n CFRelease(mListenersByIdentifier);\n\n if (mRunLoopSource) {\n CFRunLoopSourceInvalidate(mRunLoopSource);\n CFRelease(mRunLoopSource);\n }\n\n if (mLocalPort) {\n CFMessagePortInvalidate(mLocalPort);\n CFRelease(mLocalPort);\n }\n\n if (mBroadcasterName)\n CFRelease(mBroadcasterName); \n}\n\nvoid MessagePortBroadcaster::Broadcast(CFDataRef data, SInt32 channel)\n{\n CFArrayRef listeners;\n CFIndex listenerIndex;\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: broadcast(%p, %p)\\n\", data, (void *)channel);\n #endif\n \n pthread_mutex_lock(&mListenerStructuresMutex);\n\n listeners = (CFArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, (void *)channel);\n if (listeners) {\n listenerIndex = CFArrayGetCount(listeners);\n \n while (listenerIndex--) {\n CFMessagePortRef listenerPort = (CFMessagePortRef)CFArrayGetValueAtIndex(listeners, listenerIndex);\n CFMessagePortSendRequest(listenerPort, 0, data, 300, 0, NULL, NULL);\n }\n }\n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n}\n\n\n\/\/\n\/\/ Private functions and methods\n\/\/\n\nCFDataRef LocalMessagePortCallBack(CFMessagePortRef local, SInt32 msgid, CFDataRef data, void *info)\n{\n MessagePortBroadcaster *broadcaster = (MessagePortBroadcaster *)info;\n CFDataRef result = NULL;\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: message port callback(msgid=%ld)\\n\", msgid);\n #endif\n \n switch (msgid) {\n case kSpyingMIDIDriverGetNextListenerIdentifierMessageID:\n result = broadcaster->NextListenerIdentifier();\n break;\n\n case kSpyingMIDIDriverAddListenerMessageID:\n broadcaster->AddListener(data);\n break;\n\n case kSpyingMIDIDriverConnectDestinationMessageID:\n broadcaster->ChangeListenerChannelStatus(data, true);\n break;\n\n case kSpyingMIDIDriverDisconnectDestinationMessageID:\n broadcaster->ChangeListenerChannelStatus(data, false);\n break;\n\n default:\n break; \n }\n\n return result;\n}\n\nCFDataRef\tMessagePortBroadcaster::NextListenerIdentifier()\n{\n \/\/ Client is starting up; it wants to know what identifier to use (so it can name its local port).\n \/\/ We give it that data in a reply.\n\n CFDataRef returnedData;\n\n mNextListenerIdentifier++;\n returnedData = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&mNextListenerIdentifier, sizeof(UInt32));\n\n return returnedData;\n}\n\nvoid\tMessagePortBroadcaster::AddListener(CFDataRef listenerIdentifierData)\n{\n \/\/ The listener has created a local port on its side, and we need to create a remote port for it.\n \/\/ No reply is necessary.\n\n const UInt8 *dataBytes;\n UInt32 listenerIdentifier;\n CFStringRef listenerPortName;\n CFMessagePortRef remotePort;\n\n if (!listenerIdentifierData || CFDataGetLength(listenerIdentifierData) != sizeof(UInt32))\n return;\n\n dataBytes = CFDataGetBytePtr(listenerIdentifierData);\n if (!dataBytes)\n return;\n\n listenerIdentifier = *(const UInt32 *)dataBytes;\n listenerPortName = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR(\"%@-%lu\"), mBroadcasterName, listenerIdentifier);\n\n remotePort = CFMessagePortCreateRemote(kCFAllocatorDefault, listenerPortName);\n if (remotePort) {\n CFMessagePortSetInvalidationCallBack(remotePort, MessagePortWasInvalidated);\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n CFDictionarySetValue(mListenersByIdentifier, (void *)listenerIdentifier, (void *)remotePort);\n CFDictionarySetValue(mIdentifiersByListener, (void *)remotePort, (void *)listenerIdentifier);\n pthread_mutex_unlock(&mListenerStructuresMutex);\n\n CFRelease(remotePort);\n\n \/\/ TODO we don't really want to do this here -- we want to do it when the client adds a channel\n if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 1)\n mDelegate->BroadcasterListenerCountChanged(this, true);\n }\n\n CFRelease(listenerPortName);\n}\n\nvoid\tMessagePortBroadcaster::ChangeListenerChannelStatus(CFDataRef messageData, Boolean shouldAdd)\n{\n \/\/ From the message data given, take out the identifier of the listener, and the channel it is concerned with.\n \/\/ Then find the remote message port corresponding to that identifier.\n \/\/ Then find the array of listeners for this channel (creating it if necessary), and add\/remove the remote port from the array.\n \/\/ No reply is necessary.\n \n const UInt8 *dataBytes;\n UInt32 identifier;\n SInt32 channel;\n CFMessagePortRef remotePort;\n CFMutableArrayRef channelListeners;\n\n if (!messageData || CFDataGetLength(messageData) != sizeof(UInt32) + sizeof(SInt32))\n return;\n dataBytes = CFDataGetBytePtr(messageData);\n if (!dataBytes)\n return;\n identifier = *(UInt32 *)dataBytes;\n channel = *(SInt32 *)(dataBytes + sizeof(UInt32));\n\n remotePort = (CFMessagePortRef)CFDictionaryGetValue(mListenersByIdentifier, (void *)identifier);\n if (!remotePort)\n return;\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n \n channelListeners = (CFMutableArrayRef)CFDictionaryGetValue(mListenerArraysByChannel, (void *)channel);\n if (!channelListeners && shouldAdd) {\n channelListeners = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);\n if (channelListeners) {\n CFDictionarySetValue(mListenerArraysByChannel, (void *)channel, channelListeners);\n CFRelease(channelListeners);\n }\n }\n\n if (shouldAdd) {\n CFArrayAppendValue(channelListeners, remotePort);\n } else if (channelListeners) {\n CFIndex index;\n\n index = CFArrayGetFirstIndexOfValue(channelListeners, CFRangeMake(0, CFArrayGetCount(channelListeners)), remotePort);\n if (index != kCFNotFound)\n CFArrayRemoveValueAtIndex(channelListeners, index);\n }\n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n}\n\nvoid MessagePortWasInvalidated(CFMessagePortRef messagePort, void *info)\n{\n \/\/ NOTE: The info pointer provided to this function is useless. CFMessagePort provides no way to set it for remote ports.\n \/\/ Thus, we have to assume we have one MessagePortBroadcaster, which we look up statically. Lame!\n \/\/ TODO come up with a better solution to this\n\n #if DEBUG && 0\n fprintf(stderr, \"MessagePortBroadcaster: remote port was invalidated\\n\");\n #endif\n\n if (sOneBroadcaster)\n sOneBroadcaster->RemoveListenerWithRemotePort(messagePort);\n}\n\nvoid\tMessagePortBroadcaster::RemoveListenerWithRemotePort(CFMessagePortRef remotePort)\n{\n UInt32 identifier;\n\n pthread_mutex_lock(&mListenerStructuresMutex);\n\n \/\/ Remove this listener from our dictionaries\n const void* ptrId = CFDictionaryGetValue(mIdentifiersByListener, (void *)remotePort);\n#if __LP64__\n identifier = (uintptr_t)ptrId & 0xFFFFFFFFUL;\n#else\n identifier = (UInt32)ptrId;\n#endif\n CFDictionaryRemoveValue(mListenersByIdentifier, (void *)identifier);\n CFDictionaryRemoveValue(mIdentifiersByListener, (void *)remotePort);\n\n \/\/ Also go through the listener array for each channel and remove remotePort from there too\n CFDictionaryApplyFunction(mListenerArraysByChannel, RemoveRemotePortFromChannelArray, remotePort); \n\n pthread_mutex_unlock(&mListenerStructuresMutex);\n\n \/\/ TODO we don't really want to do this here -- we want to do it when a client removes a channel\n if (mDelegate && CFDictionaryGetCount(mListenersByIdentifier) == 0)\n mDelegate->BroadcasterListenerCountChanged(this, false); \n}\n\nvoid RemoveRemotePortFromChannelArray(const void *key, const void *value, void *context)\n{\n \/\/ We don't care about the key (it's a channel number)\n CFMutableArrayRef listenerArray = (CFMutableArrayRef)value;\n CFMessagePortRef remotePort = (CFMessagePortRef)context;\n CFIndex index;\n\n index = CFArrayGetFirstIndexOfValue(listenerArray, CFRangeMake(0, CFArrayGetCount(listenerArray)), remotePort);\n if (index != kCFNotFound)\n CFArrayRemoveValueAtIndex(listenerArray, index);\n}\n<|endoftext|>"} {"text":"\/*\n * BPLayer.cpp\n *\n * Created on: 02.06.2009\n * Author: Xerces\n *\/\n\n#include \n\/\/own classes\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ANN;\n\n\nBPLayer::BPLayer(int iZLayer) {\n\tm_pBiasNeuron = NULL;\n\tm_iZLayer = iZLayer;\n}\n\nBPLayer::BPLayer(const BPLayer *pLayer, int iZLayer) {\n\tint iNumber \t\t\t= pLayer->GetNeurons().size();\n\tLayerTypeFlag fType \t= pLayer->GetFlag();\n\tm_pBiasNeuron \t\t\t= NULL;\n\n\tm_iZLayer = iZLayer;\n\n\tResize(iNumber);\n\tSetFlag(fType);\n}\n\nBPLayer::BPLayer(const unsigned int &iNumber, LayerTypeFlag fType, int iZLayer) {\n\tResize(iNumber);\n\tm_pBiasNeuron = NULL;\n\tSetFlag(fType);\n\n\tm_iZLayer = iZLayer;\n}\n\nvoid BPLayer::SetZLayer(int iZLayer) {\n\tm_iZLayer = iZLayer;\n}\n\nint BPLayer::GetZLayer() {\n\treturn m_iZLayer;\n}\n\nBPLayer::~BPLayer() {\n\tif(m_pBiasNeuron) {\n\t\tdelete m_pBiasNeuron;\n\t}\n}\n\nvoid BPLayer::Resize(const unsigned int &iSize) {\n\tEraseAll();\n\tAddNeurons(iSize);\n}\n\nvoid BPLayer::AddNeurons(const unsigned int &iSize) {\n\tfor(unsigned int i = 0; i < iSize; i++) {\n\t\tAbsNeuron *pNeuron = new BPNeuron(this);\n\t\tm_lNeurons.push_back(pNeuron);\n\t\tpNeuron->SetID(m_lNeurons.size()-1);\n\t}\n}\n\nvoid BPLayer::ConnectLayer(AbsLayer *pDestLayer, const bool &bAllowAdapt) {\n\tAbsNeuron *pSrcNeuron;\n\n\t\/*\n\t * Vernetze jedes Neuron dieser Schicht mit jedem Neuron in \"destLayer\"\n\t *\/\n\tfor(unsigned int i = 0; i < m_lNeurons.size(); i++) {\n\t\tpSrcNeuron = m_lNeurons[i];\n\t\tConnect(pSrcNeuron, pDestLayer, bAllowAdapt);\n\t}\n\n\tif(m_pBiasNeuron) {\n\t\tConnect(m_pBiasNeuron, pDestLayer, true);\n\t}\n}\n\nvoid BPLayer::ConnectLayer(\n\t\tAbsLayer *pDestLayer,\n\t\tstd::vector > Connections,\n\t\tconst bool bAllowAdapt)\n{\n\tAbsNeuron *pSrcNeuron;\n\n\tassert( Connections.size() != m_lNeurons.size() );\n\tfor(unsigned int i = 0; i < Connections.size(); i++) {\n\t\tstd::vector subArray = Connections.at(i);\n\t\tpSrcNeuron = GetNeuron(i);\n\t\tassert(i != pSrcNeuron->GetID() );\n\n\t\tfor(unsigned int j = 0; j < subArray.size(); j++) {\n\t\t\tassert( j < pDestLayer->GetNeurons().size() );\n\t\t\tAbsNeuron *pDestNeuron = pDestLayer->GetNeuron(j);\n\t\t\tassert( j < pDestNeuron->GetID() );\n\t\t\tConnect(pSrcNeuron, pDestNeuron, bAllowAdapt);\n\t\t}\n\t}\n\n\tif(m_pBiasNeuron) {\n\t\tConnect(m_pBiasNeuron, pDestLayer, true);\n\t}\n}\n\nBPNeuron *BPLayer::GetBiasNeuron() const {\n\treturn m_pBiasNeuron;\n}\n\nvoid BPLayer::SetFlag(const LayerTypeFlag &fType) {\n\tm_fTypeFlag = fType;\n\tif( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {\n\t\tm_pBiasNeuron = new BPNeuron(this);\n\t\tm_pBiasNeuron->SetValue(1.0f);\n\t}\n}\n\nvoid BPLayer::AddFlag(const LayerTypeFlag &fType) {\n\tif( !(m_fTypeFlag & fType) )\n\tm_fTypeFlag |= fType;\n\tif( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {\n\t\tm_pBiasNeuron = new BPNeuron(this);\n\t\tm_pBiasNeuron->SetValue(1.0f);\n\t}\n}\n\nvoid BPLayer::SetLearningRate(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetLearningRate(fVal);\n\t}\n}\n\nvoid BPLayer::SetMomentum(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetMomentum(fVal);\n\t}\n}\n\nvoid BPLayer::SetWeightDecay(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetWeightDecay(fVal);\n\t}\n}\n\nvoid BPLayer::ExpToFS(BZFILE* bz2out, int iBZ2Error) {\n\tstd::cout<<\"Save BPLayer to FS()\"<GetConsO().size();\n\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iNmbOfConnects, sizeof(int) );\n\t\tfor(unsigned int k = 0; k < iNmbOfConnects; k++) {\n\t\t\tEdge *pCurEdge = pCurNeur->GetConO(k);\n\t\t\tiDstLayerID = pCurEdge->GetDestination(pCurNeur)->GetParent()->GetID();\n\t\t\tiDstNeurID = pCurEdge->GetDestinationID(pCurNeur);\n\t\t\tfEdgeValue = pCurEdge->GetValue();\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iDstLayerID, sizeof(int) );\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iDstNeurID, sizeof(int) );\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &fEdgeValue, sizeof(float) );\n\t\t}\n\t}\n}\n\nint BPLayer::ImpFromFS(BZFILE* bz2in, int iBZ2Error, ConTable &Table) {\n\tstd::cout<<\"Load BPLayer from FS()\"<GetConsO().size();\n\n\tassert(iWidth > 0);\n\n\tF2DArray vRes;\n\tvRes.Alloc(iWidth, iHeight);\n\n\tfor(int x = 0; x < static_cast(iWidth); x++) {\n\t\tvRes[0][x] = m_pBiasNeuron->GetConO(x)->GetValue();\n\t}\n\treturn vRes;\n}\n\nvoid BPLayer::ImpBiasEdgesOut(const F2DArray &mat) const {\n\tunsigned int iWidth \t= m_pBiasNeuron->GetConsO().size();\n\n\tassert(iWidth == mat.getW() );\n\n\tfor(int x = 0; x < static_cast(iWidth); x++) {\n\t\t\/\/std::cout<<\"mat: \"<GetConO(x)->SetValue(mat[0][x]);\n\t\t\/\/std::cout<<\"val: \"<GetConO(x)->GetValue()<GetConsI().size();\n\tunsigned int iWidth \t= m_lNeurons.size();\n\n\tassert(iHeight == mat.GetH() );\n\tassert(iWidth == mat.GetW() );\n\n\t#pragma omp parallel for\n\tfor(int y = 0; y < static_cast(iHeight); y++) {\n\t\tfor(unsigned int x = 0; x < iWidth; x++) {\n\t\t\tm_lNeurons.at(x)->GetConI(y)->SetMomentum(mat[y][x]);\n\t\t}\n\t}\n}\n\nvoid BPLayer::ImpMomentumsEdgesOut(const F2DArray &mat) {\n\tunsigned int iHeight \t= m_lNeurons.at(0)->GetConsO().size();\n\tunsigned int iWidth \t= m_lNeurons.size();\n\n\tassert(iHeight == mat.GetH() );\n\tassert(iWidth == mat.GetW() );\n\n\t#pragma omp parallel for\n\tfor(int y = 0; y < static_cast(iHeight); y++) {\n\t\tfor(unsigned int x = 0; x < iWidth; x++) {\n\t\t\tm_lNeurons.at(x)->GetConO(y)->SetMomentum(mat[y][x]);\n\t\t}\n\t}\n}\n\n\/*\n * AUSGABEOPERATOR\n * OSTREAM\n *\/\nstd::ostream& operator << (std::ostream &os, BPLayer &op)\n{\n\tif(op.GetBiasNeuron() != 0)\n\tos << \"Bias neuron: \\t\" << op.GetBiasNeuron()->GetValue() \t<< std::endl;\n os << \"Nr. neurons: \\t\" << op.GetNeurons().size() \t\t\t\t\t<< std::endl;\n return os; \/\/ Ref. auf Stream\n}\n\nstd::ostream& operator << (std::ostream &os, BPLayer *op)\n{\n\tif(op->GetBiasNeuron() != 0)\n\tos << \"Bias neuron: \\t\" << op->GetBiasNeuron()->GetValue()\t<< std::endl;\n os << \"Nr. neurons: \\t\" << op->GetNeurons().size() \t\t\t\t\t<< std::endl;\n return os; \/\/ Ref. auf Stream\n}\n\n\n\n- Typo corrected\/*\n * BPLayer.cpp\n *\n * Created on: 02.06.2009\n * Author: Xerces\n *\/\n\n#include \n\/\/own classes\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nusing namespace ANN;\n\n\nBPLayer::BPLayer(int iZLayer) {\n\tm_pBiasNeuron = NULL;\n\tm_iZLayer = iZLayer;\n}\n\nBPLayer::BPLayer(const BPLayer *pLayer, int iZLayer) {\n\tint iNumber \t\t\t= pLayer->GetNeurons().size();\n\tLayerTypeFlag fType \t= pLayer->GetFlag();\n\tm_pBiasNeuron \t\t\t= NULL;\n\n\tm_iZLayer = iZLayer;\n\n\tResize(iNumber);\n\tSetFlag(fType);\n}\n\nBPLayer::BPLayer(const unsigned int &iNumber, LayerTypeFlag fType, int iZLayer) {\n\tResize(iNumber);\n\tm_pBiasNeuron = NULL;\n\tSetFlag(fType);\n\n\tm_iZLayer = iZLayer;\n}\n\nvoid BPLayer::SetZLayer(int iZLayer) {\n\tm_iZLayer = iZLayer;\n}\n\nint BPLayer::GetZLayer() {\n\treturn m_iZLayer;\n}\n\nBPLayer::~BPLayer() {\n\tif(m_pBiasNeuron) {\n\t\tdelete m_pBiasNeuron;\n\t}\n}\n\nvoid BPLayer::Resize(const unsigned int &iSize) {\n\tEraseAll();\n\tAddNeurons(iSize);\n}\n\nvoid BPLayer::AddNeurons(const unsigned int &iSize) {\n\tfor(unsigned int i = 0; i < iSize; i++) {\n\t\tAbsNeuron *pNeuron = new BPNeuron(this);\n\t\tm_lNeurons.push_back(pNeuron);\n\t\tpNeuron->SetID(m_lNeurons.size()-1);\n\t}\n}\n\nvoid BPLayer::ConnectLayer(AbsLayer *pDestLayer, const bool &bAllowAdapt) {\n\tAbsNeuron *pSrcNeuron;\n\n\t\/*\n\t * Vernetze jedes Neuron dieser Schicht mit jedem Neuron in \"destLayer\"\n\t *\/\n\tfor(unsigned int i = 0; i < m_lNeurons.size(); i++) {\n\t\tpSrcNeuron = m_lNeurons[i];\n\t\tConnect(pSrcNeuron, pDestLayer, bAllowAdapt);\n\t}\n\n\tif(m_pBiasNeuron) {\n\t\tConnect(m_pBiasNeuron, pDestLayer, true);\n\t}\n}\n\nvoid BPLayer::ConnectLayer(\n\t\tAbsLayer *pDestLayer,\n\t\tstd::vector > Connections,\n\t\tconst bool bAllowAdapt)\n{\n\tAbsNeuron *pSrcNeuron;\n\n\tassert( Connections.size() != m_lNeurons.size() );\n\tfor(unsigned int i = 0; i < Connections.size(); i++) {\n\t\tstd::vector subArray = Connections.at(i);\n\t\tpSrcNeuron = GetNeuron(i);\n\t\tassert(i != pSrcNeuron->GetID() );\n\n\t\tfor(unsigned int j = 0; j < subArray.size(); j++) {\n\t\t\tassert( j < pDestLayer->GetNeurons().size() );\n\t\t\tAbsNeuron *pDestNeuron = pDestLayer->GetNeuron(j);\n\t\t\tassert( j < pDestNeuron->GetID() );\n\t\t\tConnect(pSrcNeuron, pDestNeuron, bAllowAdapt);\n\t\t}\n\t}\n\n\tif(m_pBiasNeuron) {\n\t\tConnect(m_pBiasNeuron, pDestLayer, true);\n\t}\n}\n\nBPNeuron *BPLayer::GetBiasNeuron() const {\n\treturn m_pBiasNeuron;\n}\n\nvoid BPLayer::SetFlag(const LayerTypeFlag &fType) {\n\tm_fTypeFlag = fType;\n\tif( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {\n\t\tm_pBiasNeuron = new BPNeuron(this);\n\t\tm_pBiasNeuron->SetValue(1.0f);\n\t}\n}\n\nvoid BPLayer::AddFlag(const LayerTypeFlag &fType) {\n\tif( !(m_fTypeFlag & fType) )\n\tm_fTypeFlag |= fType;\n\tif( (m_fTypeFlag & ANBiasNeuron) && m_pBiasNeuron == NULL ) {\n\t\tm_pBiasNeuron = new BPNeuron(this);\n\t\tm_pBiasNeuron->SetValue(1.0f);\n\t}\n}\n\nvoid BPLayer::SetLearningRate(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetLearningRate(fVal);\n\t}\n}\n\nvoid BPLayer::SetMomentum(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetMomentum(fVal);\n\t}\n}\n\nvoid BPLayer::SetWeightDecay(const float &fVal) {\n\t#pragma omp parallel for\n\tfor(int j = 0; j < static_cast( m_lNeurons.size() ); j++) {\n\t\t((BPNeuron*)m_lNeurons[j])->SetWeightDecay(fVal);\n\t}\n}\n\nvoid BPLayer::ExpToFS(BZFILE* bz2out, int iBZ2Error) {\n\tstd::cout<<\"Save BPLayer to FS()\"<GetConsO().size();\n\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iNmbOfConnects, sizeof(int) );\n\t\tfor(unsigned int k = 0; k < iNmbOfConnects; k++) {\n\t\t\tEdge *pCurEdge = pCurNeur->GetConO(k);\n\t\t\tiDstLayerID = pCurEdge->GetDestination(pCurNeur)->GetParent()->GetID();\n\t\t\tiDstNeurID = pCurEdge->GetDestinationID(pCurNeur);\n\t\t\tfEdgeValue = pCurEdge->GetValue();\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iDstLayerID, sizeof(int) );\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &iDstNeurID, sizeof(int) );\n\t\t\tBZ2_bzWrite( &iBZ2Error, bz2out, &fEdgeValue, sizeof(float) );\n\t\t}\n\t}\n}\n\nint BPLayer::ImpFromFS(BZFILE* bz2in, int iBZ2Error, ConTable &Table) {\n\tstd::cout<<\"Load BPLayer from FS()\"<GetConsO().size();\n\n\tassert(iWidth > 0);\n\n\tF2DArray vRes;\n\tvRes.Alloc(iWidth, iHeight);\n\n\tfor(int x = 0; x < static_cast(iWidth); x++) {\n\t\tvRes[0][x] = m_pBiasNeuron->GetConO(x)->GetValue();\n\t}\n\treturn vRes;\n}\n\nvoid BPLayer::ImpBiasEdgesOut(const F2DArray &mat) const {\n\tunsigned int iWidth \t= m_pBiasNeuron->GetConsO().size();\n\n\tassert(iWidth == mat.GetW() );\n\n\tfor(int x = 0; x < static_cast(iWidth); x++) {\n\t\t\/\/std::cout<<\"mat: \"<GetConO(x)->SetValue(mat[0][x]);\n\t\t\/\/std::cout<<\"val: \"<GetConO(x)->GetValue()<GetConsI().size();\n\tunsigned int iWidth \t= m_lNeurons.size();\n\n\tassert(iHeight == mat.GetH() );\n\tassert(iWidth == mat.GetW() );\n\n\t#pragma omp parallel for\n\tfor(int y = 0; y < static_cast(iHeight); y++) {\n\t\tfor(unsigned int x = 0; x < iWidth; x++) {\n\t\t\tm_lNeurons.at(x)->GetConI(y)->SetMomentum(mat[y][x]);\n\t\t}\n\t}\n}\n\nvoid BPLayer::ImpMomentumsEdgesOut(const F2DArray &mat) {\n\tunsigned int iHeight \t= m_lNeurons.at(0)->GetConsO().size();\n\tunsigned int iWidth \t= m_lNeurons.size();\n\n\tassert(iHeight == mat.GetH() );\n\tassert(iWidth == mat.GetW() );\n\n\t#pragma omp parallel for\n\tfor(int y = 0; y < static_cast(iHeight); y++) {\n\t\tfor(unsigned int x = 0; x < iWidth; x++) {\n\t\t\tm_lNeurons.at(x)->GetConO(y)->SetMomentum(mat[y][x]);\n\t\t}\n\t}\n}\n\n\/*\n * AUSGABEOPERATOR\n * OSTREAM\n *\/\nstd::ostream& operator << (std::ostream &os, BPLayer &op)\n{\n\tif(op.GetBiasNeuron() != 0)\n\tos << \"Bias neuron: \\t\" << op.GetBiasNeuron()->GetValue() \t<< std::endl;\n os << \"Nr. neurons: \\t\" << op.GetNeurons().size() \t\t\t\t\t<< std::endl;\n return os; \/\/ Ref. auf Stream\n}\n\nstd::ostream& operator << (std::ostream &os, BPLayer *op)\n{\n\tif(op->GetBiasNeuron() != 0)\n\tos << \"Bias neuron: \\t\" << op->GetBiasNeuron()->GetValue()\t<< std::endl;\n os << \"Nr. neurons: \\t\" << op->GetNeurons().size() \t\t\t\t\t<< std::endl;\n return os; \/\/ Ref. auf Stream\n}\n\n\n\n<|endoftext|>"} {"text":"#include \r\n\r\n#include \"AttributeModifierName.h\"\r\n#include \"PrimaryAttribute.h\"\r\n#include \"PrimaryAttributeName.h\"\r\n#include \"..\/Math\/Random.h\"\r\n\r\n#include \"components\/debug\/Debug.h\"\r\n\r\nconst std::unordered_map PrimaryAttributeDisplayNames =\r\n{\r\n\t{ PrimaryAttributeName::Strength, \"Strength\" },\r\n\t{ PrimaryAttributeName::Intelligence, \"Intelligence\" },\r\n\t{ PrimaryAttributeName::Willpower, \"Willpower\" },\r\n\t{ PrimaryAttributeName::Agility, \"Agility\" },\r\n\t{ PrimaryAttributeName::Speed, \"Speed\" },\r\n\t{ PrimaryAttributeName::Endurance, \"Endurance\" },\r\n\t{ PrimaryAttributeName::Personality, \"Personality\" },\r\n\t{ PrimaryAttributeName::Luck, \"Luck\" }\r\n};\r\n\r\nconst std::unordered_map> PrimaryAttributeModifierNames =\r\n{\r\n\t{ PrimaryAttributeName::Strength, { AttributeModifierName::MeleeDamage } },\r\n\t{ PrimaryAttributeName::Intelligence, { } },\r\n\t{ PrimaryAttributeName::Willpower, { AttributeModifierName::MagicDefense } },\r\n\t{ PrimaryAttributeName::Agility, { AttributeModifierName::ToHit, AttributeModifierName::ToDefense } },\r\n\t{ PrimaryAttributeName::Speed, { } },\r\n\t{ PrimaryAttributeName::Endurance, { AttributeModifierName::HealthPerLevel, \r\n\tAttributeModifierName::HealModifier } },\r\n\t{ PrimaryAttributeName::Personality, { AttributeModifierName::Charisma } },\r\n\t{ PrimaryAttributeName::Luck, { } }\r\n};\r\n\r\nconst int PrimaryAttribute::MIN_VALUE = 0;\r\nconst int PrimaryAttribute::MAX_VALUE = 100;\r\n\r\nPrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int baseValue)\r\n{\r\n\tDebugAssert(baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\tthis->attributeName = attributeName;\r\n\tthis->baseValue = baseValue;\r\n}\r\n\r\nPrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int raceID, bool male, Random &random)\r\n{\r\n\tDebugAssert(raceID >= 0);\r\n\tDebugAssert(raceID <= 7);\r\n\r\n\tthis->attributeName = attributeName;\r\n\r\n\t\/\/ Lower limit (non-inclusive) of base attribute value, set by race and gender below.\r\n\t\/\/ 20-sided-die roll will be added.\r\n\tint baseValueBase;\r\n\r\n\t\/\/ Source: https:\/\/en.uesp.net\/wiki\/Arena:Character_Creation#Character_Stats\r\n\tif (raceID == 0) \/\/ Breton\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = 40;\r\n\t}\r\n\telse if (raceID == 1) \/\/ Redguard\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 40 : 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 40 : 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = 40;\r\n\t}\r\n\telse if (raceID == 2) \/\/ Nord\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = male ? 30 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 30 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = male ? 40 : 50;\r\n\t}\r\n\telse if (raceID == 3) \/\/ Dark Elf\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = 40;\r\n\t}\r\n\telse if (raceID == 4) \/\/ High Elf\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = male ? 40 : 50;\r\n\t\telse baseValueBase = 40;\r\n\t}\r\n\telse if (raceID == 5) \/\/ Wood Elf\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 30 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = male ? 30 : 40;\r\n\t}\r\n\telse if (raceID == 6) \/\/ Khajiit\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 40 : 50;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = 30;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = 50;\r\n\t}\r\n\telse \/\/ Argonian\r\n\t{\r\n\t\tif (attributeName == PrimaryAttributeName::Strength) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Intelligence) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Willpower) baseValueBase = 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Agility) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Speed) baseValueBase = male ? 50 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Endurance) baseValueBase = male ? 30 : 40;\r\n\t\telse if (attributeName == PrimaryAttributeName::Personality) baseValueBase = 40;\r\n\t\telse baseValueBase = male ? 30 : 40;\r\n\t}\r\n\r\n\tthis->baseValue = baseValueBase + random.next(20) + 1;\r\n}\r\n\r\nint PrimaryAttribute::get() const\r\n{\r\n\tDebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\treturn this->baseValue;\r\n}\r\n\r\nPrimaryAttributeName PrimaryAttribute::getAttributeName() const\r\n{\r\n\treturn this->attributeName;\r\n}\r\n\r\nstd::vector PrimaryAttribute::getModifierNames() const\r\n{\r\n\tauto modifierNames = PrimaryAttributeModifierNames.at(this->getAttributeName());\r\n\treturn modifierNames;\r\n}\r\n\r\nint PrimaryAttribute::getModifier() const\r\n{\r\n\tDebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\t\/\/ This value is exactly right. Try some more experiments.\r\n\tint modifierValue = (this->baseValue - 50) \/ 10;\r\n\treturn modifierValue;\r\n}\r\n\r\nstd::string PrimaryAttribute::toString() const\r\n{\r\n\tauto displayName = PrimaryAttributeDisplayNames.at(this->getAttributeName());\r\n\treturn displayName;\r\n}\r\n\r\nvoid PrimaryAttribute::set(int value)\r\n{\r\n\t\/\/ The caller shouldn't try to set the value to a bad value. If only this was Ada!\r\n\t\/\/ Ada has automatic bounds checking on numeric types, like \"percent is 0.0...100.0\"\r\n\t\/\/ or something, so no assertions would be necessary.\r\n\tDebugAssert(value >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(value <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\tthis->baseValue = value;\r\n}\r\nRemoved hardcoded attribute values.#include \r\n\r\n#include \"AttributeModifierName.h\"\r\n#include \"PrimaryAttribute.h\"\r\n#include \"PrimaryAttributeName.h\"\r\n#include \"..\/Math\/Random.h\"\r\n\r\n#include \"components\/debug\/Debug.h\"\r\n\r\nconst std::unordered_map PrimaryAttributeDisplayNames =\r\n{\r\n\t{ PrimaryAttributeName::Strength, \"Strength\" },\r\n\t{ PrimaryAttributeName::Intelligence, \"Intelligence\" },\r\n\t{ PrimaryAttributeName::Willpower, \"Willpower\" },\r\n\t{ PrimaryAttributeName::Agility, \"Agility\" },\r\n\t{ PrimaryAttributeName::Speed, \"Speed\" },\r\n\t{ PrimaryAttributeName::Endurance, \"Endurance\" },\r\n\t{ PrimaryAttributeName::Personality, \"Personality\" },\r\n\t{ PrimaryAttributeName::Luck, \"Luck\" }\r\n};\r\n\r\nconst std::unordered_map> PrimaryAttributeModifierNames =\r\n{\r\n\t{ PrimaryAttributeName::Strength, { AttributeModifierName::MeleeDamage } },\r\n\t{ PrimaryAttributeName::Intelligence, { } },\r\n\t{ PrimaryAttributeName::Willpower, { AttributeModifierName::MagicDefense } },\r\n\t{ PrimaryAttributeName::Agility, { AttributeModifierName::ToHit, AttributeModifierName::ToDefense } },\r\n\t{ PrimaryAttributeName::Speed, { } },\r\n\t{ PrimaryAttributeName::Endurance, { AttributeModifierName::HealthPerLevel, \r\n\tAttributeModifierName::HealModifier } },\r\n\t{ PrimaryAttributeName::Personality, { AttributeModifierName::Charisma } },\r\n\t{ PrimaryAttributeName::Luck, { } }\r\n};\r\n\r\nconst int PrimaryAttribute::MIN_VALUE = 0;\r\nconst int PrimaryAttribute::MAX_VALUE = 100;\r\n\r\nPrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int baseValue)\r\n{\r\n\tDebugAssert(baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\tthis->attributeName = attributeName;\r\n\tthis->baseValue = baseValue;\r\n}\r\n\r\nPrimaryAttribute::PrimaryAttribute(PrimaryAttributeName attributeName, int raceID, bool male, Random &random)\r\n{\r\n\tDebugAssert(raceID >= 0);\r\n\tDebugAssert(raceID <= 7);\r\n\r\n\tthis->attributeName = attributeName;\r\n\r\n\t\/\/ @todo: read from ExeData::entities::raceAttributes\r\n\tthis->baseValue = 0;\r\n}\r\n\r\nint PrimaryAttribute::get() const\r\n{\r\n\tDebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\treturn this->baseValue;\r\n}\r\n\r\nPrimaryAttributeName PrimaryAttribute::getAttributeName() const\r\n{\r\n\treturn this->attributeName;\r\n}\r\n\r\nstd::vector PrimaryAttribute::getModifierNames() const\r\n{\r\n\tauto modifierNames = PrimaryAttributeModifierNames.at(this->getAttributeName());\r\n\treturn modifierNames;\r\n}\r\n\r\nint PrimaryAttribute::getModifier() const\r\n{\r\n\tDebugAssert(this->baseValue >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(this->baseValue <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\t\/\/ This value is exactly right. Try some more experiments.\r\n\tint modifierValue = (this->baseValue - 50) \/ 10;\r\n\treturn modifierValue;\r\n}\r\n\r\nstd::string PrimaryAttribute::toString() const\r\n{\r\n\tauto displayName = PrimaryAttributeDisplayNames.at(this->getAttributeName());\r\n\treturn displayName;\r\n}\r\n\r\nvoid PrimaryAttribute::set(int value)\r\n{\r\n\t\/\/ The caller shouldn't try to set the value to a bad value. If only this was Ada!\r\n\t\/\/ Ada has automatic bounds checking on numeric types, like \"percent is 0.0...100.0\"\r\n\t\/\/ or something, so no assertions would be necessary.\r\n\tDebugAssert(value >= PrimaryAttribute::MIN_VALUE);\r\n\tDebugAssert(value <= PrimaryAttribute::MAX_VALUE);\r\n\r\n\tthis->baseValue = value;\r\n}\r\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the plugins of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qdirectfbscreen.h\"\n#include \"qdirectfbpaintdevice.h\"\n#include \"qdirectfbpaintengine.h\"\n\n#ifndef QT_NO_QWS_DIRECTFB\n\nQT_BEGIN_NAMESPACE\n\nQDirectFBPaintDevice::QDirectFBPaintDevice(QDirectFBScreen *scr)\n : QCustomRasterPaintDevice(0), dfbSurface(0), screen(scr),\n bpl(-1), lockFlgs(DFBSurfaceLockFlags(0)), mem(0), engine(0), imageFormat(QImage::Format_Invalid)\n{\n#ifdef QT_DIRECTFB_SUBSURFACE\n subSurface = 0;\n syncPending = false;\n#endif\n}\n\nQDirectFBPaintDevice::~QDirectFBPaintDevice()\n{\n unlockSurface();\n if (QDirectFBScreen::instance()) {\n unlockSurface();\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (subSurface) {\n screen->releaseDFBSurface(subSurface);\n }\n#endif\n if (dfbSurface) {\n screen->releaseDFBSurface(dfbSurface);\n }\n }\n delete engine;\n}\n\nIDirectFBSurface *QDirectFBPaintDevice::directFBSurface() const\n{\n return dfbSurface;\n}\n\nbool QDirectFBPaintDevice::lockSurface(DFBSurfaceLockFlags lockFlags)\n{\n if (lockFlgs && (lockFlags & ~lockFlgs))\n unlockSurface();\n if (!mem) {\n Q_ASSERT(dfbSurface);\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (!subSurface) {\n DFBResult result;\n subSurface = screen->getSubSurface(dfbSurface, QRect(), QDirectFBScreen::TrackSurface, &result);\n if (result != DFB_OK || !subSurface) {\n DirectFBError(\"Couldn't create sub surface\", result);\n return false;\n }\n }\n IDirectFBSurface *surface = subSurface;\n#else\n IDirectFBSurface *surface = dfbSurface;\n#endif\n Q_ASSERT(surface);\n mem = QDirectFBScreen::lockSurface(surface, lockFlags, &bpl);\n lockFlgs = lockFlags;\n Q_ASSERT(mem);\n Q_ASSERT(bpl > 0);\n const QSize s = size();\n lockedImage = QImage(mem, s.width(), s.height(), bpl,\n QDirectFBScreen::getImageFormat(dfbSurface));\n return true;\n }\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (syncPending) {\n syncPending = false;\n screen->waitIdle();\n }\n#endif\n return false;\n}\n\nvoid QDirectFBPaintDevice::unlockSurface()\n{\n if (QDirectFBScreen::instance() && lockFlgs) {\n#ifdef QT_DIRECTFB_SUBSURFACE\n IDirectFBSurface *surface = subSurface;\n#else\n IDirectFBSurface *surface = dfbSurface;\n#endif\n if (surface) {\n surface->Unlock(surface);\n lockFlgs = static_cast(0);\n }\n }\n}\n\nvoid *QDirectFBPaintDevice::memory() const\n{\n return mem;\n}\n\nQImage::Format QDirectFBPaintDevice::format() const\n{\n return imageFormat;\n}\n\nint QDirectFBPaintDevice::bytesPerLine() const\n{\n Q_ASSERT(!mem || bpl != -1);\n return bpl;\n}\n\nQSize QDirectFBPaintDevice::size() const\n{\n int w, h;\n dfbSurface->GetSize(dfbSurface, &w, &h);\n return QSize(w, h);\n}\n\nint QDirectFBPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const\n{\n if (!dfbSurface)\n return 0;\n\n switch (metric) {\n case QPaintDevice::PdmWidth:\n case QPaintDevice::PdmHeight:\n return (metric == PdmWidth ? size().width() : size().height());\n case QPaintDevice::PdmWidthMM:\n return (size().width() * 1000) \/ dotsPerMeterX();\n case QPaintDevice::PdmHeightMM:\n return (size().height() * 1000) \/ dotsPerMeterY();\n case QPaintDevice::PdmPhysicalDpiX:\n case QPaintDevice::PdmDpiX:\n return (dotsPerMeterX() * 254) \/ 10000; \/\/ 0.0254 meters-per-inch\n case QPaintDevice::PdmPhysicalDpiY:\n case QPaintDevice::PdmDpiY:\n return (dotsPerMeterY() * 254) \/ 10000; \/\/ 0.0254 meters-per-inch\n case QPaintDevice::PdmDepth:\n return QDirectFBScreen::depth(imageFormat);\n case QPaintDevice::PdmNumColors: {\n if (!lockedImage.isNull())\n return lockedImage.numColors();\n\n DFBResult result;\n IDirectFBPalette *palette = 0;\n unsigned int numColors = 0;\n\n result = dfbSurface->GetPalette(dfbSurface, &palette);\n if ((result != DFB_OK) || !palette)\n return 0;\n\n result = palette->GetSize(palette, &numColors);\n palette->Release(palette);\n if (result != DFB_OK)\n return 0;\n\n return numColors;\n }\n default:\n qCritical(\"QDirectFBPaintDevice::metric(): Unhandled metric!\");\n return 0;\n }\n}\n\nQPaintEngine *QDirectFBPaintDevice::paintEngine() const\n{\n return engine;\n}\n\nQT_END_NAMESPACE\n\n#endif \/\/ QT_NO_QWS_DIRECTFB\nMake sure to set mem to 0 in unlockSurface\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the plugins of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qdirectfbscreen.h\"\n#include \"qdirectfbpaintdevice.h\"\n#include \"qdirectfbpaintengine.h\"\n\n#ifndef QT_NO_QWS_DIRECTFB\n\nQT_BEGIN_NAMESPACE\n\nQDirectFBPaintDevice::QDirectFBPaintDevice(QDirectFBScreen *scr)\n : QCustomRasterPaintDevice(0), dfbSurface(0), screen(scr),\n bpl(-1), lockFlgs(DFBSurfaceLockFlags(0)), mem(0), engine(0), imageFormat(QImage::Format_Invalid)\n{\n#ifdef QT_DIRECTFB_SUBSURFACE\n subSurface = 0;\n syncPending = false;\n#endif\n}\n\nQDirectFBPaintDevice::~QDirectFBPaintDevice()\n{\n unlockSurface();\n if (QDirectFBScreen::instance()) {\n unlockSurface();\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (subSurface) {\n screen->releaseDFBSurface(subSurface);\n }\n#endif\n if (dfbSurface) {\n screen->releaseDFBSurface(dfbSurface);\n }\n }\n delete engine;\n}\n\nIDirectFBSurface *QDirectFBPaintDevice::directFBSurface() const\n{\n return dfbSurface;\n}\n\nbool QDirectFBPaintDevice::lockSurface(DFBSurfaceLockFlags lockFlags)\n{\n if (lockFlgs && (lockFlags & ~lockFlgs))\n unlockSurface();\n if (!mem) {\n Q_ASSERT(dfbSurface);\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (!subSurface) {\n DFBResult result;\n subSurface = screen->getSubSurface(dfbSurface, QRect(), QDirectFBScreen::TrackSurface, &result);\n if (result != DFB_OK || !subSurface) {\n DirectFBError(\"Couldn't create sub surface\", result);\n return false;\n }\n }\n IDirectFBSurface *surface = subSurface;\n#else\n IDirectFBSurface *surface = dfbSurface;\n#endif\n Q_ASSERT(surface);\n mem = QDirectFBScreen::lockSurface(surface, lockFlags, &bpl);\n lockFlgs = lockFlags;\n Q_ASSERT(mem);\n Q_ASSERT(bpl > 0);\n const QSize s = size();\n lockedImage = QImage(mem, s.width(), s.height(), bpl,\n QDirectFBScreen::getImageFormat(dfbSurface));\n return true;\n }\n#ifdef QT_DIRECTFB_SUBSURFACE\n if (syncPending) {\n syncPending = false;\n screen->waitIdle();\n }\n#endif\n return false;\n}\n\nvoid QDirectFBPaintDevice::unlockSurface()\n{\n if (QDirectFBScreen::instance() && lockFlgs) {\n#ifdef QT_DIRECTFB_SUBSURFACE\n IDirectFBSurface *surface = subSurface;\n#else\n IDirectFBSurface *surface = dfbSurface;\n#endif\n if (surface) {\n surface->Unlock(surface);\n lockFlgs = static_cast(0);\n mem = 0;\n }\n }\n}\n\nvoid *QDirectFBPaintDevice::memory() const\n{\n return mem;\n}\n\nQImage::Format QDirectFBPaintDevice::format() const\n{\n return imageFormat;\n}\n\nint QDirectFBPaintDevice::bytesPerLine() const\n{\n Q_ASSERT(!mem || bpl != -1);\n return bpl;\n}\n\nQSize QDirectFBPaintDevice::size() const\n{\n int w, h;\n dfbSurface->GetSize(dfbSurface, &w, &h);\n return QSize(w, h);\n}\n\nint QDirectFBPaintDevice::metric(QPaintDevice::PaintDeviceMetric metric) const\n{\n if (!dfbSurface)\n return 0;\n\n switch (metric) {\n case QPaintDevice::PdmWidth:\n case QPaintDevice::PdmHeight:\n return (metric == PdmWidth ? size().width() : size().height());\n case QPaintDevice::PdmWidthMM:\n return (size().width() * 1000) \/ dotsPerMeterX();\n case QPaintDevice::PdmHeightMM:\n return (size().height() * 1000) \/ dotsPerMeterY();\n case QPaintDevice::PdmPhysicalDpiX:\n case QPaintDevice::PdmDpiX:\n return (dotsPerMeterX() * 254) \/ 10000; \/\/ 0.0254 meters-per-inch\n case QPaintDevice::PdmPhysicalDpiY:\n case QPaintDevice::PdmDpiY:\n return (dotsPerMeterY() * 254) \/ 10000; \/\/ 0.0254 meters-per-inch\n case QPaintDevice::PdmDepth:\n return QDirectFBScreen::depth(imageFormat);\n case QPaintDevice::PdmNumColors: {\n if (!lockedImage.isNull())\n return lockedImage.numColors();\n\n DFBResult result;\n IDirectFBPalette *palette = 0;\n unsigned int numColors = 0;\n\n result = dfbSurface->GetPalette(dfbSurface, &palette);\n if ((result != DFB_OK) || !palette)\n return 0;\n\n result = palette->GetSize(palette, &numColors);\n palette->Release(palette);\n if (result != DFB_OK)\n return 0;\n\n return numColors;\n }\n default:\n qCritical(\"QDirectFBPaintDevice::metric(): Unhandled metric!\");\n return 0;\n }\n}\n\nQPaintEngine *QDirectFBPaintDevice::paintEngine() const\n{\n return engine;\n}\n\nQT_END_NAMESPACE\n\n#endif \/\/ QT_NO_QWS_DIRECTFB\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: layerparser.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: jb $ $Date: 2002-11-22 14:51:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"layerparser.hxx\"\n\n\/\/ -----------------------------------------------------------------------------\n#ifndef CONFIGMGR_WRAPEXCEPTION_HXX\n#include \"wrapexception.hxx\"\n#endif\n\n#define WRAP_PARSE_EXCEPTIONS() \\\n PASS_EXCEPTION(sax::SAXException) \\\n PASS_EXCEPTION(uno::RuntimeException) \\\n WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException ) \\\n WRAP_OTHER_EXCEPTIONS( raiseParseException )\n\n#define WRAP_PARSE_EXCEPTIONS_MSG( msg ) \\\n PASS_EXCEPTION(sax::SAXException) \\\n PASS_EXCEPTION(uno::RuntimeException) \\\n WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \\\n WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg )\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\/\/ -----------------------------------------------------------------------------\n\nLayerParser::LayerParser(ServiceFactory const & _xSvcFactory, uno::Reference< backenduno::XLayerHandler > const & _xHandler)\n: BasicParser(_xSvcFactory)\n, m_xHandler(_xHandler)\n, m_bRemoved(false)\n, m_bNewProp(false)\n{\n if (!m_xHandler.is())\n {\n OUString sMessage(RTL_CONSTASCII_USTRINGPARAM(\"Cannot create LayerParser: Unexpected NULL Handler\"));\n throw uno::RuntimeException(sMessage, NULL);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nLayerParser::~LayerParser()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::startDocument( )\n throw (sax::SAXException, uno::RuntimeException)\n{\n BasicParser::startDocument();\n\n try\n {\n OSL_ENSURE(isEmptyNode(), \"BasicParser does not mark new document as empty\");\n\n m_xHandler->startLayer();\n m_bRemoved = false;\n m_bNewProp = false;\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Starting layer\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::endDocument( ) throw (sax::SAXException, uno::RuntimeException)\n{\n if (isEmptyNode()) OSL_TRACE(\"Configuration Parser: XML layer document ended without any data\");\n\n BasicParser::endDocument();\n\n try\n {\n m_xHandler->endLayer();\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Ending layer\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs )\n throw (sax::SAXException, uno::RuntimeException)\n{\n if ( this->isSkipping() )\n {\n this->startSkipping( aName, xAttribs );\n return;\n }\n\n ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs);\n\n try\n {\n switch (aInfo.type)\n {\n case ElementType::group: case ElementType::set:\n OSL_ENSURE( false, \"Layer XML parser - Unexpected: found group\/set element (should be 'node')\\n\");\n \/\/ fall thru\n case ElementType::layer:\n case ElementType::node:\n this->startNode(aInfo,xAttribs);\n OSL_ASSERT( this->isInNode() && !this->isInProperty() );\n break;\n\n case ElementType::property:\n this->startProperty(aInfo,xAttribs);\n OSL_ASSERT( this->isInUnhandledProperty() );\n break;\n\n case ElementType::value:\n this->startValueData(xAttribs);\n OSL_ASSERT( this->isInValueData() );\n break;\n\n default: \/\/ skip unknown elements\n OSL_ENSURE( aInfo.type >= ElementType::other, \"Layer XML parser - Unexpected: found schema element in layer data\\n\");\n OSL_ENSURE( aInfo.type < ElementType::other, \"Layer XML parser - Warning: ignoring unknown element tag\\n\");\n this->startSkipping( aName, xAttribs );\n return;\n }\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Starting Element\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::endElement( const OUString& aName )\n throw (sax::SAXException, uno::RuntimeException)\n{\n if ( this->wasSkipping(aName) )\n return;\n\n try\n {\n if ( this->isInValueData())\n this->endValueData();\n\n else if (this->isInProperty())\n this->endProperty();\n\n else if (this->isInNode())\n this->endNode();\n\n else {\n this->raiseParseException(\"Layer parser: Invalid XML: endElement without matching startElement\");\n }\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Ending Element\")\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )\n{\n this->checkNotRemoved();\n\n BasicParser::startNode(aInfo,xAttribs);\n\n switch (aInfo.op)\n {\n case Operation::none:\n case Operation::modify:\n m_xHandler->overrideNode(aInfo.name,aInfo.flags);\n break;\n\n case Operation::replace:\n {\n backenduno::TemplateIdentifier aTemplate;\n if (getDataParser().getInstanceType(xAttribs,aTemplate.Name,aTemplate.Component))\n m_xHandler->addOrReplaceNodeFromTemplate(aInfo.name,aTemplate,aInfo.flags);\n else\n m_xHandler->addOrReplaceNode(aInfo.name,aInfo.flags);\n }\n break;\n\n case Operation::remove:\n m_xHandler->dropNode(aInfo.name);\n m_bRemoved = true;\n break;\n\n default: OSL_ASSERT(false);\n case Operation::unknown:\n this->raiseParseException(\"Layer parser: Invalid Data: unknown operation\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endNode()\n{\n if (!this->isInRemoved())\n m_xHandler->endNode();\n else\n m_bRemoved = false;\n\n BasicParser::endNode();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )\n{\n this->checkNotRemoved();\n\n BasicParser::startProperty(aInfo,xAttribs);\n\n switch (aInfo.op)\n {\n case Operation::none:\n case Operation::modify:\n m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType());\n OSL_ASSERT(!m_bNewProp);\n break;\n\n case Operation::replace:\n \/\/ defer to later\n m_bNewProp = true;\n break;\n\n case Operation::remove:\n this->raiseParseException(\"Layer parser: Invalid Data: operation 'remove' is not permitted for properties\");\n\n default: OSL_ASSERT(false);\n case Operation::unknown:\n this->raiseParseException(\"Layer parser: Invalid Data: unknown operation\");\n }\n OSL_POSTCOND(this->isInUnhandledProperty(),\"Error: Property not reckognized as unhandled\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::addOrReplaceCurrentProperty(const uno::Any& aValue)\n{\n const ElementInfo& currentInfo = getActiveNodeInfo() ;\n\n OSL_ASSERT(currentInfo.op == Operation::replace) ;\n\n if (aValue.hasValue())\n {\n m_xHandler->addPropertyWithValue(currentInfo.name,\n currentInfo.flags, aValue) ;\n }\n else\n {\n m_xHandler->addProperty(currentInfo.name, currentInfo.flags,\n getActivePropertyType()) ;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endProperty()\n{\n OSL_ASSERT(!this->isInRemoved());\n\n if (m_bNewProp)\n {\n OSL_ASSERT(getActiveNodeInfo().op == Operation::replace);\n if (this->isInUnhandledProperty())\n {\n \/\/ No value tag is treated as NULL\n addOrReplaceCurrentProperty( uno::Any() ) ;\n }\n m_bNewProp = false;\n }\n else\n {\n OSL_ASSERT(getActiveNodeInfo().op != Operation::replace);\n m_xHandler->endProperty();\n }\n\n BasicParser::endProperty();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs)\n{\n this->checkNotRemoved();\n\n BasicParser::startValueData(xAttribs);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endValueData()\n{\n uno::Any aValue = this->getCurrentValue();\n\n if (m_bNewProp)\n {\n OSL_ENSURE(!isValueDataLocalized(),\"Layer parser: Invalid Data: 'lang' ignored for newly added property.\");\n\n addOrReplaceCurrentProperty(aValue) ;\n }\n else if (this->isValueDataLocalized())\n {\n OUString aLocale = this->getValueDataLocale();\n\n m_xHandler->setPropertyValueForLocale(aValue,aLocale);\n }\n else\n {\n m_xHandler->setPropertyValue(aValue);\n }\n\n BasicParser::endValueData();\n\n OSL_POSTCOND(!this->isInUnhandledProperty(),\"Error: Property not reckognized as unhandled\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::checkNotRemoved()\n{\n if (m_bRemoved)\n raiseParseException(\"Layer parser: Invalid Data: Data inside removed node.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\nINTEGRATION: CWS configapi01 (1.9.26); FILE MERGED 2003\/04\/15 10:25:37 jb 1.9.26.1: #i11893# backend\\updatedata.cxx\/*************************************************************************\n *\n * $RCSfile: layerparser.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2003-04-17 13:34:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"layerparser.hxx\"\n\n\/\/ -----------------------------------------------------------------------------\n#ifndef CONFIGMGR_WRAPEXCEPTION_HXX\n#include \"wrapexception.hxx\"\n#endif\n\n#define WRAP_PARSE_EXCEPTIONS() \\\n PASS_EXCEPTION(sax::SAXException) \\\n PASS_EXCEPTION(uno::RuntimeException) \\\n WRAP_CONFIGDATA_EXCEPTIONS( raiseParseException ) \\\n WRAP_OTHER_EXCEPTIONS( raiseParseException )\n\n#define WRAP_PARSE_EXCEPTIONS_MSG( msg ) \\\n PASS_EXCEPTION(sax::SAXException) \\\n PASS_EXCEPTION(uno::RuntimeException) \\\n WRAP_CONFIGDATA_EXCEPTIONS1( raiseParseException, msg ) \\\n WRAP_OTHER_EXCEPTIONS1( raiseParseException, msg )\n\n\/\/ -----------------------------------------------------------------------------\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\/\/ -----------------------------------------------------------------------------\n\nLayerParser::LayerParser(ServiceFactory const & _xSvcFactory, uno::Reference< backenduno::XLayerHandler > const & _xHandler)\n: BasicParser(_xSvcFactory)\n, m_xHandler(_xHandler)\n, m_bRemoved(false)\n, m_bNewProp(false)\n{\n if (!m_xHandler.is())\n {\n OUString sMessage(RTL_CONSTASCII_USTRINGPARAM(\"Cannot create LayerParser: Unexpected NULL Handler\"));\n throw uno::RuntimeException(sMessage, NULL);\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nLayerParser::~LayerParser()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::startDocument( )\n throw (sax::SAXException, uno::RuntimeException)\n{\n BasicParser::startDocument();\n\n try\n {\n OSL_ENSURE(isEmptyNode(), \"BasicParser does not mark new document as empty\");\n\n m_xHandler->startLayer();\n m_bRemoved = false;\n m_bNewProp = false;\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Starting layer\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::endDocument( ) throw (sax::SAXException, uno::RuntimeException)\n{\n if (isEmptyNode()) OSL_TRACE(\"Configuration Parser: XML layer document ended without any data\");\n\n BasicParser::endDocument();\n\n try\n {\n m_xHandler->endLayer();\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Ending layer\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::startElement( const OUString& aName, const uno::Reference< sax::XAttributeList >& xAttribs )\n throw (sax::SAXException, uno::RuntimeException)\n{\n if ( this->isSkipping() )\n {\n this->startSkipping( aName, xAttribs );\n return;\n }\n\n ElementInfo aInfo = getDataParser().parseElementInfo(aName,xAttribs);\n\n try\n {\n switch (aInfo.type)\n {\n case ElementType::group: case ElementType::set:\n OSL_ENSURE( false, \"Layer XML parser - Unexpected: found group\/set element (should be 'node')\\n\");\n \/\/ fall thru\n case ElementType::layer:\n case ElementType::node:\n this->startNode(aInfo,xAttribs);\n OSL_ASSERT( this->isInNode() && !this->isInProperty() );\n break;\n\n case ElementType::property:\n this->startProperty(aInfo,xAttribs);\n OSL_ASSERT( this->isInUnhandledProperty() );\n break;\n\n case ElementType::value:\n this->startValueData(xAttribs);\n OSL_ASSERT( this->isInValueData() );\n break;\n\n default: \/\/ skip unknown elements\n OSL_ENSURE( aInfo.type >= ElementType::other, \"Layer XML parser - Unexpected: found schema element in layer data\\n\");\n OSL_ENSURE( aInfo.type < ElementType::other, \"Layer XML parser - Warning: ignoring unknown element tag\\n\");\n this->startSkipping( aName, xAttribs );\n return;\n }\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Starting Element\")\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL LayerParser::endElement( const OUString& aName )\n throw (sax::SAXException, uno::RuntimeException)\n{\n if ( this->wasSkipping(aName) )\n return;\n\n try\n {\n if ( this->isInValueData())\n this->endValueData();\n\n else if (this->isInProperty())\n this->endProperty();\n\n else if (this->isInNode())\n this->endNode();\n\n else {\n this->raiseParseException(\"Layer parser: Invalid XML: endElement without matching startElement\");\n }\n }\n WRAP_PARSE_EXCEPTIONS_MSG(\"LayerParser - Ending Element\")\n}\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startNode( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )\n{\n this->checkNotRemoved();\n\n BasicParser::startNode(aInfo,xAttribs);\n\n switch (aInfo.op)\n {\n case Operation::none:\n case Operation::modify:\n m_xHandler->overrideNode(aInfo.name,aInfo.flags,false);\n break;\n\n case Operation::clear:\n m_xHandler->overrideNode(aInfo.name,aInfo.flags,true);\n break;\n\n case Operation::replace:\n {\n backenduno::TemplateIdentifier aTemplate;\n if (getDataParser().getInstanceType(xAttribs,aTemplate.Name,aTemplate.Component))\n m_xHandler->addOrReplaceNodeFromTemplate(aInfo.name,aTemplate,aInfo.flags);\n else\n m_xHandler->addOrReplaceNode(aInfo.name,aInfo.flags);\n }\n break;\n\n case Operation::remove:\n m_xHandler->dropNode(aInfo.name);\n m_bRemoved = true;\n break;\n\n default: OSL_ASSERT(false);\n case Operation::unknown:\n this->raiseParseException(\"Layer parser: Invalid Data: unknown operation\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endNode()\n{\n if (!this->isInRemoved())\n m_xHandler->endNode();\n else\n m_bRemoved = false;\n\n BasicParser::endNode();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startProperty( ElementInfo const & aInfo, const uno::Reference< sax::XAttributeList >& xAttribs )\n{\n this->checkNotRemoved();\n\n BasicParser::startProperty(aInfo,xAttribs);\n\n switch (aInfo.op)\n {\n case Operation::none:\n case Operation::modify:\n m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType(),false);\n OSL_ASSERT(!m_bNewProp);\n break;\n\n case Operation::clear:\n m_xHandler->overrideProperty(aInfo.name,aInfo.flags,getActivePropertyType(),true);\n OSL_ASSERT(!m_bNewProp);\n break;\n\n case Operation::replace:\n \/\/ defer to later\n m_bNewProp = true;\n break;\n\n case Operation::remove:\n this->raiseParseException(\"Layer parser: Invalid Data: operation 'remove' is not permitted for properties\");\n\n default: OSL_ASSERT(false);\n case Operation::unknown:\n this->raiseParseException(\"Layer parser: Invalid Data: unknown operation\");\n }\n OSL_POSTCOND(this->isInUnhandledProperty(),\"Error: Property not reckognized as unhandled\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::addOrReplaceCurrentProperty(const uno::Any& aValue)\n{\n const ElementInfo& currentInfo = getActiveNodeInfo() ;\n\n OSL_ASSERT(currentInfo.op == Operation::replace) ;\n\n if (aValue.hasValue())\n {\n m_xHandler->addPropertyWithValue(currentInfo.name,\n currentInfo.flags, aValue) ;\n }\n else\n {\n m_xHandler->addProperty(currentInfo.name, currentInfo.flags,\n getActivePropertyType()) ;\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endProperty()\n{\n OSL_ASSERT(!this->isInRemoved());\n\n if (m_bNewProp)\n {\n OSL_ASSERT(getActiveNodeInfo().op == Operation::replace);\n if (this->isInUnhandledProperty())\n {\n \/\/ No value tag is treated as NULL\n addOrReplaceCurrentProperty( uno::Any() ) ;\n }\n m_bNewProp = false;\n }\n else\n {\n OSL_ASSERT(getActiveNodeInfo().op != Operation::replace);\n m_xHandler->endProperty();\n }\n\n BasicParser::endProperty();\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::startValueData(const uno::Reference< sax::XAttributeList >& xAttribs)\n{\n this->checkNotRemoved();\n\n BasicParser::startValueData(xAttribs);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::endValueData()\n{\n uno::Any aValue = this->getCurrentValue();\n\n if (m_bNewProp)\n {\n OSL_ENSURE(!isValueDataLocalized(),\"Layer parser: Invalid Data: 'lang' ignored for newly added property.\");\n\n addOrReplaceCurrentProperty(aValue) ;\n }\n else if (this->isValueDataLocalized())\n {\n OUString aLocale = this->getValueDataLocale();\n\n m_xHandler->setPropertyValueForLocale(aValue,aLocale);\n }\n else\n {\n m_xHandler->setPropertyValue(aValue);\n }\n\n BasicParser::endValueData();\n\n OSL_POSTCOND(!this->isInUnhandledProperty(),\"Error: Property not reckognized as unhandled\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerParser::checkNotRemoved()\n{\n if (m_bRemoved)\n raiseParseException(\"Layer parser: Invalid Data: Data inside removed node.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mpositionindicatorview.h\"\n#include \"mpositionindicatorview_p.h\"\n#include \"qapplication.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"mtheme.h\"\n#include \"mviewcreator.h\"\n#include \"mpositionindicator.h\"\n#include \"mscalableimage.h\"\n\nMPositionIndicatorViewPrivate::MPositionIndicatorViewPrivate()\n : controller(0),\n hideTimer(new QTimer()),\n visible(false),\n onDisplay(false)\n{\n}\n\nMPositionIndicatorViewPrivate::~MPositionIndicatorViewPrivate()\n{\n delete this->hideTimer;\n}\n\nvoid MPositionIndicatorViewPrivate::init(MPositionIndicator *controller)\n{\n Q_Q(MPositionIndicatorView);\n\n this->controller = controller;\n hideTimer->setSingleShot(true);\n fadeAnimation = new QPropertyAnimation(controller, \"opacity\", q);\n\n q->connect(hideTimer, SIGNAL(timeout()), SLOT(hide()));\n q->connect(controller, SIGNAL(displayEntered()), SLOT(_q_displayEntered()));\n q->connect(controller, SIGNAL(displayExited()), SLOT(_q_displayExited()));\n}\n\nbool MPositionIndicatorViewPrivate::isInSwitcher() const\n{\n bool isInSwitcher = false;\n if (controller->scene() && !controller->scene()->views().isEmpty()) {\n MWindow* win = qobject_cast(controller->scene()->views().at(0));\n if (win) {\n isInSwitcher = win->isInSwitcher();\n }\n }\n return isInSwitcher;\n}\n\nvoid MPositionIndicatorViewPrivate::_q_displayEntered()\n{\n Q_Q(MPositionIndicatorView);\n\n onDisplay = true;\n if (!isInSwitcher()) {\n hideTimer->start(q->style()->hideTimeout());\n }\n}\n\nvoid MPositionIndicatorViewPrivate::_q_displayExited()\n{\n Q_Q(MPositionIndicatorView);\n\n \/* stop everything and keep indicator visible for next use *\/\n onDisplay = false;\n hideTimer->stop();\n fadeAnimation->stop();\n controller->setProperty(\"opacity\", 1.0f);\n visible = true;\n q->update();\n}\n\nMPositionIndicatorView::MPositionIndicatorView(MPositionIndicator *controller) :\n MWidgetView(* new MPositionIndicatorViewPrivate, controller)\n{\n Q_D(MPositionIndicatorView);\n d->init(controller);\n}\n\nMPositionIndicatorView::~MPositionIndicatorView()\n{\n Q_D(MPositionIndicatorView);\n d->controller = 0;\n}\n\nvoid MPositionIndicatorView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(painter);\n Q_UNUSED(option);\n}\n\nvoid MPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n Q_D(const MPositionIndicatorView);\n\n if (d->isInSwitcher()) {\n return;\n }\n\n QSizeF vpSize = model()->viewportSize();\n QRectF pRange = model()->range().adjusted(0, 0, vpSize.width(), vpSize.height());\n QPointF pPos = model()->position();\n\n const MScalableImage *indicator = style()->indicatorImage();\n const MScalableImage *rail = style()->backgroundImage();\n\n\n if ((int)pRange.height() > (int)vpSize.height()) {\n\n int indicatorPixmapSizeX = indicator->pixmap()->width();\n int railPixmapSizeX = rail->pixmap()->width();\n\n int indicatorHeight = qMax(style()->minIndicatorSize(), int((vpSize.height()\/pRange.height())*size().height()));\n int indicatorPositionY = (pPos.y()\/pRange.height())*size().height();\n\n if (indicatorPositionY + indicatorHeight > size().height()) {\n indicatorHeight = size().height() - indicatorPositionY;\n }\n\n if (indicatorPositionY < 0) {\n indicatorHeight += indicatorPositionY;\n indicatorPositionY = 0;\n }\n\n int railPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - railPixmapSizeX);\n int indicatorPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - indicatorPixmapSizeX);\n\n rail->draw((qreal)railPositionX,\n 0.0,\n (qreal)railPixmapSizeX,\n size().height(),\n painter);\n\n\n\n indicator->draw(indicatorPositionX,\n indicatorPositionY,\n indicatorPixmapSizeX,\n indicatorHeight,\n painter);\n }\n\n if ((int)pRange.width() > (int)vpSize.width()) {\n\n int indicatorPixmapSizeY = indicator->pixmap()->height();\n int railPixmapSizeY = rail->pixmap()->height();\n int indicatorWidth = qMax(style()->minIndicatorSize(), int((vpSize.width()\/pRange.width())*size().width()));\n int indicatorPositionX = (pPos.x()\/pRange.width())*size().width();\n\n if (indicatorPositionX + indicatorWidth > size().width()) {\n indicatorWidth = size().width() - indicatorPositionX;\n }\n\n if (indicatorPositionX < 0) {\n indicatorWidth += indicatorPositionX;\n indicatorPositionX = 0;\n }\n\n rail->draw( 0.0,\n size().height() - railPixmapSizeY,\n size().width(),\n (qreal)railPixmapSizeY,\n painter);\n\n indicator->draw((qreal)indicatorPositionX,\n size().height() - indicatorPixmapSizeY,\n (qreal)indicatorWidth,\n (qreal)indicatorPixmapSizeY,\n painter);\n }\n}\n\nvoid MPositionIndicatorView::updateData(const QList& modifications)\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::updateData(modifications);\n\n if (d->onDisplay) {\n resetHideTimer();\n }\n update();\n}\n\nvoid MPositionIndicatorView::setupModel()\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::setupModel();\n\n if (d->onDisplay) {\n resetHideTimer();\n }\n update();\n}\n\nvoid MPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MPositionIndicatorView::changeEvent(QEvent *event)\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::changeEvent(event);\n\n if (event->type() == QEvent::EnabledChange) {\n if (d->controller->isEnabled()) {\n d->controller->setVisible(true);\n } else {\n d->controller->setVisible(false);\n }\n }\n}\n\nvoid MPositionIndicatorView::hide()\n{\n Q_D(MPositionIndicatorView);\n d->visible = false;\n d->fadeAnimation->stop();\n d->fadeAnimation->setEndValue(0.0f);\n d->fadeAnimation->start();\n update();\n}\n\nvoid MPositionIndicatorView::resetHideTimer()\n{\n Q_D(MPositionIndicatorView);\n if (!d->visible) {\n d->fadeAnimation->stop();\n d->fadeAnimation->setEndValue(1.0f);\n d->fadeAnimation->start();\n d->visible = true;\n }\n d->hideTimer->stop();\n if (!d->isInSwitcher()) {\n d->hideTimer->start(style()->hideTimeout());\n }\n}\n\nM_REGISTER_VIEW_NEW(MPositionIndicatorView, MPositionIndicator)\n\n#include \"moc_mpositionindicatorview.cpp\"\nFixes: NB#218298 - MPositionIndicator does not momentarily appear after it has been enabled\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mpositionindicatorview.h\"\n#include \"mpositionindicatorview_p.h\"\n#include \"qapplication.h\"\n\n#include \n#include \n#include \n#include \n\n#include \"mtheme.h\"\n#include \"mviewcreator.h\"\n#include \"mpositionindicator.h\"\n#include \"mscalableimage.h\"\n\nMPositionIndicatorViewPrivate::MPositionIndicatorViewPrivate()\n : controller(0),\n hideTimer(new QTimer()),\n visible(false),\n onDisplay(false)\n{\n}\n\nMPositionIndicatorViewPrivate::~MPositionIndicatorViewPrivate()\n{\n delete this->hideTimer;\n}\n\nvoid MPositionIndicatorViewPrivate::init(MPositionIndicator *controller)\n{\n Q_Q(MPositionIndicatorView);\n\n this->controller = controller;\n hideTimer->setSingleShot(true);\n fadeAnimation = new QPropertyAnimation(controller, \"opacity\", q);\n\n q->connect(hideTimer, SIGNAL(timeout()), SLOT(hide()));\n q->connect(controller, SIGNAL(displayEntered()), SLOT(_q_displayEntered()));\n q->connect(controller, SIGNAL(displayExited()), SLOT(_q_displayExited()));\n}\n\nbool MPositionIndicatorViewPrivate::isInSwitcher() const\n{\n bool isInSwitcher = false;\n if (controller->scene() && !controller->scene()->views().isEmpty()) {\n MWindow* win = qobject_cast(controller->scene()->views().at(0));\n if (win) {\n isInSwitcher = win->isInSwitcher();\n }\n }\n return isInSwitcher;\n}\n\nvoid MPositionIndicatorViewPrivate::_q_displayEntered()\n{\n Q_Q(MPositionIndicatorView);\n\n onDisplay = true;\n if (!isInSwitcher()) {\n hideTimer->start(q->style()->hideTimeout());\n }\n}\n\nvoid MPositionIndicatorViewPrivate::_q_displayExited()\n{\n Q_Q(MPositionIndicatorView);\n\n \/* stop everything and keep indicator visible for next use *\/\n onDisplay = false;\n hideTimer->stop();\n fadeAnimation->stop();\n controller->setProperty(\"opacity\", 1.0f);\n visible = true;\n q->update();\n}\n\nMPositionIndicatorView::MPositionIndicatorView(MPositionIndicator *controller) :\n MWidgetView(* new MPositionIndicatorViewPrivate, controller)\n{\n Q_D(MPositionIndicatorView);\n d->init(controller);\n}\n\nMPositionIndicatorView::~MPositionIndicatorView()\n{\n Q_D(MPositionIndicatorView);\n d->controller = 0;\n}\n\nvoid MPositionIndicatorView::drawBackground(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(painter);\n Q_UNUSED(option);\n}\n\nvoid MPositionIndicatorView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n Q_D(const MPositionIndicatorView);\n\n if (d->isInSwitcher()) {\n return;\n }\n\n QSizeF vpSize = model()->viewportSize();\n QRectF pRange = model()->range().adjusted(0, 0, vpSize.width(), vpSize.height());\n QPointF pPos = model()->position();\n\n const MScalableImage *indicator = style()->indicatorImage();\n const MScalableImage *rail = style()->backgroundImage();\n\n\n if ((int)pRange.height() > (int)vpSize.height()) {\n\n int indicatorPixmapSizeX = indicator->pixmap()->width();\n int railPixmapSizeX = rail->pixmap()->width();\n\n int indicatorHeight = qMax(style()->minIndicatorSize(), int((vpSize.height()\/pRange.height())*size().height()));\n int indicatorPositionY = (pPos.y()\/pRange.height())*size().height();\n\n if (indicatorPositionY + indicatorHeight > size().height()) {\n indicatorHeight = size().height() - indicatorPositionY;\n }\n\n if (indicatorPositionY < 0) {\n indicatorHeight += indicatorPositionY;\n indicatorPositionY = 0;\n }\n\n int railPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - railPixmapSizeX);\n int indicatorPositionX = (qApp->layoutDirection() == Qt::RightToLeft ? 0 : size().width() - indicatorPixmapSizeX);\n\n rail->draw((qreal)railPositionX,\n 0.0,\n (qreal)railPixmapSizeX,\n size().height(),\n painter);\n\n\n\n indicator->draw(indicatorPositionX,\n indicatorPositionY,\n indicatorPixmapSizeX,\n indicatorHeight,\n painter);\n }\n\n if ((int)pRange.width() > (int)vpSize.width()) {\n\n int indicatorPixmapSizeY = indicator->pixmap()->height();\n int railPixmapSizeY = rail->pixmap()->height();\n int indicatorWidth = qMax(style()->minIndicatorSize(), int((vpSize.width()\/pRange.width())*size().width()));\n int indicatorPositionX = (pPos.x()\/pRange.width())*size().width();\n\n if (indicatorPositionX + indicatorWidth > size().width()) {\n indicatorWidth = size().width() - indicatorPositionX;\n }\n\n if (indicatorPositionX < 0) {\n indicatorWidth += indicatorPositionX;\n indicatorPositionX = 0;\n }\n\n rail->draw( 0.0,\n size().height() - railPixmapSizeY,\n size().width(),\n (qreal)railPixmapSizeY,\n painter);\n\n indicator->draw((qreal)indicatorPositionX,\n size().height() - indicatorPixmapSizeY,\n (qreal)indicatorWidth,\n (qreal)indicatorPixmapSizeY,\n painter);\n }\n}\n\nvoid MPositionIndicatorView::updateData(const QList& modifications)\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::updateData(modifications);\n\n if (d->onDisplay) {\n resetHideTimer();\n }\n update();\n}\n\nvoid MPositionIndicatorView::setupModel()\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::setupModel();\n\n if (d->onDisplay) {\n resetHideTimer();\n }\n update();\n}\n\nvoid MPositionIndicatorView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MPositionIndicatorView::changeEvent(QEvent *event)\n{\n Q_D(MPositionIndicatorView);\n\n MWidgetView::changeEvent(event);\n\n if (event->type() == QEvent::EnabledChange) {\n if (d->controller->isEnabled()) {\n resetHideTimer();\n d->controller->setVisible(true);\n } else {\n d->controller->setVisible(false);\n }\n }\n}\n\nvoid MPositionIndicatorView::hide()\n{\n Q_D(MPositionIndicatorView);\n d->visible = false;\n d->fadeAnimation->stop();\n d->fadeAnimation->setEndValue(0.0f);\n d->fadeAnimation->start();\n update();\n}\n\nvoid MPositionIndicatorView::resetHideTimer()\n{\n Q_D(MPositionIndicatorView);\n if (!d->visible) {\n d->fadeAnimation->stop();\n d->fadeAnimation->setEndValue(1.0f);\n d->fadeAnimation->start();\n d->visible = true;\n }\n d->hideTimer->stop();\n if (!d->isInSwitcher()) {\n d->hideTimer->start(style()->hideTimeout());\n }\n}\n\nM_REGISTER_VIEW_NEW(MPositionIndicatorView, MPositionIndicator)\n\n#include \"moc_mpositionindicatorview.cpp\"\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: spritecanvasbase.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 14:36:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_CANVAS_SPRITECANVASBASE_HXX\n#define INCLUDED_CANVAS_SPRITECANVASBASE_HXX\n\n#ifndef _RTL_REF_HXX_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_RENDERING_XSPRITECANVAS_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_RENDERING_INTERPOLATIONMODE_HPP_\n#include \n#endif\n\n#ifndef INCLUDED_CANVAS_INTEGERBITMAPBASE_HXX\n#include \n#endif\n#ifndef INCLUDED_CANVAS_SPRITEREDRAWMANAGER_HXX\n#include \n#endif\n\n\nnamespace canvas\n{\n \/** Helper template to handle XIntegerBitmap method forwarding to\n BitmapCanvasHelper\n\n Use this helper to handle the XIntegerBitmap part of your\n implementation.\n\n @tpl Base\n Base class to use, most probably one of the\n WeakComponentImplHelperN templates with the appropriate\n interfaces. At least XSpriteCanvas and SpriteSurface should be\n among them (why else would you use this template, then?). Base\n class must have an Base( const Mutex& ) constructor (like the\n WeakComponentImplHelperN templates have).\n\n @tpl CanvasHelper\n Canvas helper implementation for the backend in question\n\n @tpl Mutex\n Lock strategy to use. Defaults to using the\n OBaseMutex-provided lock. Everytime one of the methods is\n entered, an object of type Mutex is created with m_aMutex as\n the sole parameter, and destroyed again when the method scope\n is left.\n\n @tpl UnambiguousBase\n Optional unambiguous base class for XInterface of Base. It's\n sometimes necessary to specify this parameter, e.g. if Base\n derives from multiple UNO interface (were each provides its\n own version of XInterface, making the conversion ambiguous)\n\n @see CanvasBase for further contractual requirements towards\n the CanvasHelper type, and some examples.\n *\/\n template< class Base,\n class CanvasHelper,\n class Mutex=::osl::MutexGuard,\n class UnambiguousBase=::com::sun::star::uno::XInterface > class SpriteCanvasBase :\n public IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase >\n {\n public:\n typedef IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase > BaseType;\n typedef ::rtl::Reference< SpriteCanvasBase > Reference;\n\n SpriteCanvasBase() :\n maRedrawManager()\n {\n }\n\n#if defined __SUNPRO_CC\n using Base::disposing;\n#endif\n virtual void SAL_CALL disposing()\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.disposing();\n\n \/\/ pass on to base class\n BaseType::disposing();\n }\n\n \/\/ XSpriteCanvas\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(animation,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createSpriteFromAnimation(animation);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap > >& animationBitmaps,\n sal_Int8 interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::rendering::VolatileContentDestroyedException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(animationBitmaps,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n tools::verifyRange( interpolationMode,\n ::com::sun::star::rendering::InterpolationMode::NEAREST_NEIGHBOR,\n ::com::sun::star::rendering::InterpolationMode::BEZIERSPLINE4 );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createSpriteFromBitmaps(animationBitmaps, interpolationMode);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifySpriteSize(spriteSize,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createCustomSprite(spriteSize);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(original,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createClonedSprite(original);\n }\n\n \/\/ SpriteSurface\n virtual void showSprite( const Sprite::Reference& rSprite )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.showSprite( rSprite );\n }\n\n virtual void hideSprite( const Sprite::Reference& rSprite )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.hideSprite( rSprite );\n }\n\n virtual void moveSprite( const Sprite::Reference& rSprite,\n const ::basegfx::B2DPoint& rOldPos,\n const ::basegfx::B2DPoint& rNewPos,\n const ::basegfx::B2DVector& rSpriteSize )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.moveSprite( rSprite, rOldPos, rNewPos, rSpriteSize );\n }\n\n virtual void updateSprite( const Sprite::Reference& rSprite,\n const ::basegfx::B2DPoint& rPos,\n const ::basegfx::B2DRange& rUpdateArea )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.updateSprite( rSprite, rPos, rUpdateArea );\n }\n\n protected:\n SpriteRedrawManager maRedrawManager;\n };\n}\n\n#endif \/* INCLUDED_CANVAS_SPRITECANVASBASE_HXX *\/\nINTEGRATION: CWS changefileheader (1.3.80); FILE MERGED 2008\/04\/01 15:03:03 thb 1.3.80.3: #i85898# Stripping all external header guards 2008\/04\/01 10:49:25 thb 1.3.80.2: #i85898# Stripping all external header guards 2008\/03\/28 16:34:53 rt 1.3.80.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: spritecanvasbase.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef INCLUDED_CANVAS_SPRITECANVASBASE_HXX\n#define INCLUDED_CANVAS_SPRITECANVASBASE_HXX\n\n#include \n#include \n#include \n#include \n#include \n\n\nnamespace canvas\n{\n \/** Helper template to handle XIntegerBitmap method forwarding to\n BitmapCanvasHelper\n\n Use this helper to handle the XIntegerBitmap part of your\n implementation.\n\n @tpl Base\n Base class to use, most probably one of the\n WeakComponentImplHelperN templates with the appropriate\n interfaces. At least XSpriteCanvas and SpriteSurface should be\n among them (why else would you use this template, then?). Base\n class must have an Base( const Mutex& ) constructor (like the\n WeakComponentImplHelperN templates have).\n\n @tpl CanvasHelper\n Canvas helper implementation for the backend in question\n\n @tpl Mutex\n Lock strategy to use. Defaults to using the\n OBaseMutex-provided lock. Everytime one of the methods is\n entered, an object of type Mutex is created with m_aMutex as\n the sole parameter, and destroyed again when the method scope\n is left.\n\n @tpl UnambiguousBase\n Optional unambiguous base class for XInterface of Base. It's\n sometimes necessary to specify this parameter, e.g. if Base\n derives from multiple UNO interface (were each provides its\n own version of XInterface, making the conversion ambiguous)\n\n @see CanvasBase for further contractual requirements towards\n the CanvasHelper type, and some examples.\n *\/\n template< class Base,\n class CanvasHelper,\n class Mutex=::osl::MutexGuard,\n class UnambiguousBase=::com::sun::star::uno::XInterface > class SpriteCanvasBase :\n public IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase >\n {\n public:\n typedef IntegerBitmapBase< Base, CanvasHelper, Mutex, UnambiguousBase > BaseType;\n typedef ::rtl::Reference< SpriteCanvasBase > Reference;\n\n SpriteCanvasBase() :\n maRedrawManager()\n {\n }\n\n#if defined __SUNPRO_CC\n using Base::disposing;\n#endif\n virtual void SAL_CALL disposing()\n {\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.disposing();\n\n \/\/ pass on to base class\n BaseType::disposing();\n }\n\n \/\/ XSpriteCanvas\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromAnimation( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimation >& animation ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(animation,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createSpriteFromAnimation(animation);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XAnimatedSprite > SAL_CALL createSpriteFromBitmaps( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XBitmap > >& animationBitmaps,\n sal_Int8 interpolationMode ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::rendering::VolatileContentDestroyedException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(animationBitmaps,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n tools::verifyRange( interpolationMode,\n ::com::sun::star::rendering::InterpolationMode::NEAREST_NEIGHBOR,\n ::com::sun::star::rendering::InterpolationMode::BEZIERSPLINE4 );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createSpriteFromBitmaps(animationBitmaps, interpolationMode);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XCustomSprite > SAL_CALL createCustomSprite( const ::com::sun::star::geometry::RealSize2D& spriteSize ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifySpriteSize(spriteSize,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createCustomSprite(spriteSize);\n }\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite > SAL_CALL createClonedSprite( const ::com::sun::star::uno::Reference< ::com::sun::star::rendering::XSprite >& original ) throw (::com::sun::star::lang::IllegalArgumentException,\n ::com::sun::star::uno::RuntimeException)\n {\n tools::verifyArgs(original,\n BOOST_CURRENT_FUNCTION,\n static_cast< typename BaseType::UnambiguousBaseType* >(this));\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n return BaseType::maCanvasHelper.createClonedSprite(original);\n }\n\n \/\/ SpriteSurface\n virtual void showSprite( const Sprite::Reference& rSprite )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.showSprite( rSprite );\n }\n\n virtual void hideSprite( const Sprite::Reference& rSprite )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.hideSprite( rSprite );\n }\n\n virtual void moveSprite( const Sprite::Reference& rSprite,\n const ::basegfx::B2DPoint& rOldPos,\n const ::basegfx::B2DPoint& rNewPos,\n const ::basegfx::B2DVector& rSpriteSize )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.moveSprite( rSprite, rOldPos, rNewPos, rSpriteSize );\n }\n\n virtual void updateSprite( const Sprite::Reference& rSprite,\n const ::basegfx::B2DPoint& rPos,\n const ::basegfx::B2DRange& rUpdateArea )\n {\n OSL_ASSERT( rSprite.is() );\n\n typename BaseType::MutexType aGuard( BaseType::m_aMutex );\n\n maRedrawManager.updateSprite( rSprite, rPos, rUpdateArea );\n }\n\n protected:\n SpriteRedrawManager maRedrawManager;\n };\n}\n\n#endif \/* INCLUDED_CANVAS_SPRITECANVASBASE_HXX *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: overlaypolypolygon.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n#define _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace overlay\n {\n class SVX_DLLPUBLIC OverlayPolyPolygonStriped : public OverlayObject\n {\n protected:\n \/\/ geometry\n basegfx::B2DPolyPolygon maPolyPolygon;\n\n \/\/ Draw geometry\n virtual void drawGeometry(OutputDevice& rOutputDevice);\n\n \/\/ Create the BaseRange. This method needs to calculate maBaseRange.\n virtual void createBaseRange(OutputDevice& rOutputDevice);\n\n \/\/ eventually remove curves from polygon data (maPolyPolygon)\n virtual void preparePolygonData();\n\n public:\n OverlayPolyPolygonStriped(const basegfx::B2DPolyPolygon& rPolyPolygon);\n virtual ~OverlayPolyPolygonStriped();\n\n \/\/ change geometry\n basegfx::B2DPolyPolygon getPolyPolygon() const { return maPolyPolygon; }\n void setPolyPolygon(const basegfx::B2DPolyPolygon& rNew);\n\n \/\/ Hittest with logical coordinates\n virtual sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol = 0.0) const;\n\n \/\/ transform object coordinates. Needs to transform maSecondPosition\n \/\/ and maThirdPosition.\n virtual void transform(const basegfx::B2DHomMatrix& rMatrix);\n };\n } \/\/ end of namespace overlay\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace overlay\n {\n class OverlayPolyPolygon : public OverlayPolyPolygonStriped\n {\n protected:\n \/\/ Draw geometry\n virtual void drawGeometry(OutputDevice& rOutputDevice);\n\n \/\/ eventually remove curves from polygon data (maPolyPolygon)\n virtual void preparePolygonData();\n\n public:\n OverlayPolyPolygon(\n const basegfx::B2DPolyPolygon& rPolyPolygon,\n Color aPolygonColor = Color(COL_BLACK));\n virtual ~OverlayPolyPolygon();\n };\n } \/\/ end of namespace overlay\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n\n\/\/ eof\nINTEGRATION: CWS aw033 (1.3.100); FILE MERGED 2008\/05\/14 13:58:04 aw 1.3.100.2: RESYNC: (1.3-1.4); FILE MERGED 2007\/11\/19 11:12:02 aw 1.3.100.1: #i39532# Lot of changes to make polygon stuff bezier-able\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: overlaypolypolygon.hxx,v $\n * $Revision: 1.5 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n#define _SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n\n#include \n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace overlay\n {\n class SVX_DLLPUBLIC OverlayPolyPolygonStriped : public OverlayObject\n {\n protected:\n \/\/ geometry\n basegfx::B2DPolyPolygon maPolyPolygon;\n\n \/\/ Draw geometry\n virtual void drawGeometry(OutputDevice& rOutputDevice);\n\n \/\/ Create the BaseRange. This method needs to calculate maBaseRange.\n virtual void createBaseRange(OutputDevice& rOutputDevice);\n\n public:\n OverlayPolyPolygonStriped(const basegfx::B2DPolyPolygon& rPolyPolygon);\n virtual ~OverlayPolyPolygonStriped();\n\n \/\/ change geometry\n basegfx::B2DPolyPolygon getPolyPolygon() const { return maPolyPolygon; }\n void setPolyPolygon(const basegfx::B2DPolyPolygon& rNew);\n\n \/\/ Hittest with logical coordinates\n virtual sal_Bool isHit(const basegfx::B2DPoint& rPos, double fTol = 0.0) const;\n\n \/\/ transform object coordinates. Needs to transform maSecondPosition\n \/\/ and maThirdPosition.\n virtual void transform(const basegfx::B2DHomMatrix& rMatrix);\n };\n } \/\/ end of namespace overlay\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace overlay\n {\n class OverlayPolyPolygon : public OverlayPolyPolygonStriped\n {\n protected:\n \/\/ Draw geometry\n virtual void drawGeometry(OutputDevice& rOutputDevice);\n\n public:\n OverlayPolyPolygon(\n const basegfx::B2DPolyPolygon& rPolyPolygon,\n Color aPolygonColor = Color(COL_BLACK));\n virtual ~OverlayPolyPolygon();\n };\n } \/\/ end of namespace overlay\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif \/\/_SDR_OVERLAY_OVERLAYPOLYPOLYGON_HXX\n\n\/\/ eof\n<|endoftext|>"} {"text":"\/*************************************************************************\n*\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: layerwriter.hxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: hr $ $Date: 2006-06-19 23:36:30 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n************************************************************************\/\n\n#ifndef CONFIGMGR_XML_LAYERWRITER_HXX\n#define CONFIGMGR_XML_LAYERWRITER_HXX\n\n#ifndef CONFIGMGR_XML_WRITERSVC_HXX\n#include \"writersvc.hxx\"\n#endif\n\n#ifndef CONFIGMGR_XML_ELEMENTFORMATTER_HXX\n#include \"elementformatter.hxx\"\n#endif\n\n#ifndef CONFIGMGR_STACK_HXX_\n#include \"stack.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_\n#include \n#endif\n\nnamespace com { namespace sun { namespace star { namespace script {\n class XTypeConverter;\n} } } }\n\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n \/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n\n namespace sax = ::com::sun::star::xml::sax;\n namespace backenduno = ::com::sun::star::configuration::backend;\n\n \/\/ -----------------------------------------------------------------------------\n\n\n class LayerWriter : public LayerWriterService_Base\n {\n public:\n explicit\n LayerWriter(CreationArg _xContext);\n virtual ~LayerWriter();\n\n \/\/ XLayerHandler\n public:\n virtual void SAL_CALL\n startLayer( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endLayer( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endNode( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n dropNode( const OUString& aName )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endProperty( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValue( const uno::Any& aValue )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n private:\n bool isInElement() const;\n void checkInElement(bool bInElement, bool bInProperty = false);\n\n void startNode();\n void startProp(uno::Type const & _aType, bool bNeedType);\n\n void endElement();\n\n void writeValue(uno::Any const & _aValue);\n void writeValue(uno::Any const & _aValue, OUString const & _aLocale);\n\n void outputValue(uno::Any const & _aValue);\n\n void raiseMalformedDataException(sal_Char const * pMsg);\n void raiseIllegalTypeException(sal_Char const * pMsg);\n\n void prepareAddOrReplaceElement(\n rtl::OUString const & name, sal_Int16 attributes);\n\n private:\n typedef Stack< OUString > TagStack;\n uno::Reference< com::sun::star::script::XTypeConverter > m_xTCV;\n TagStack m_aTagStack;\n ElementFormatter m_aFormatter;\n uno::Type m_aPropertyType;\n bool m_bInProperty;\n bool m_bStartedDocument;\n };\n \/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n \/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n#endif\n\n\n\n\nINTEGRATION: CWS changefileheader (1.12.90); FILE MERGED 2008\/04\/01 12:27:40 thb 1.12.90.2: #i85898# Stripping all external header guards 2008\/03\/31 12:23:00 rt 1.12.90.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n*\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: layerwriter.hxx,v $\n * $Revision: 1.13 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n************************************************************************\/\n\n#ifndef CONFIGMGR_XML_LAYERWRITER_HXX\n#define CONFIGMGR_XML_LAYERWRITER_HXX\n\n#include \"writersvc.hxx\"\n#include \"elementformatter.hxx\"\n#include \"stack.hxx\"\n#include \n\nnamespace com { namespace sun { namespace star { namespace script {\n class XTypeConverter;\n} } } }\n\nnamespace configmgr\n{\n \/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n \/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n\n namespace sax = ::com::sun::star::xml::sax;\n namespace backenduno = ::com::sun::star::configuration::backend;\n\n \/\/ -----------------------------------------------------------------------------\n\n\n class LayerWriter : public LayerWriterService_Base\n {\n public:\n explicit\n LayerWriter(CreationArg _xContext);\n virtual ~LayerWriter();\n\n \/\/ XLayerHandler\n public:\n virtual void SAL_CALL\n startLayer( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endLayer( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideNode( const OUString& aName, sal_Int16 aAttributes, sal_Bool bClear )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addOrReplaceNodeFromTemplate( const OUString& aName, const backenduno::TemplateIdentifier& aTemplate, sal_Int16 aAttributes )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endNode( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n dropNode( const OUString& aName )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n overrideProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType, sal_Bool bClear )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n addPropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n endProperty( )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValue( const uno::Any& aValue )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n virtual void SAL_CALL\n setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (backenduno::MalformedDataException, lang::WrappedTargetException,\n uno::RuntimeException);\n\n private:\n bool isInElement() const;\n void checkInElement(bool bInElement, bool bInProperty = false);\n\n void startNode();\n void startProp(uno::Type const & _aType, bool bNeedType);\n\n void endElement();\n\n void writeValue(uno::Any const & _aValue);\n void writeValue(uno::Any const & _aValue, OUString const & _aLocale);\n\n void outputValue(uno::Any const & _aValue);\n\n void raiseMalformedDataException(sal_Char const * pMsg);\n void raiseIllegalTypeException(sal_Char const * pMsg);\n\n void prepareAddOrReplaceElement(\n rtl::OUString const & name, sal_Int16 attributes);\n\n private:\n typedef Stack< OUString > TagStack;\n uno::Reference< com::sun::star::script::XTypeConverter > m_xTCV;\n TagStack m_aTagStack;\n ElementFormatter m_aFormatter;\n uno::Type m_aPropertyType;\n bool m_bInProperty;\n bool m_bStartedDocument;\n };\n \/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n \/\/ -----------------------------------------------------------------------------\n\n} \/\/ namespace configmgr\n#endif\n\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * \\file opencl_module.cc\n *\/\n#include \"opencl_module.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"..\/source_utils.h\"\n#include \"opencl_common.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass OpenCLWrappedFunc {\n public:\n \/\/ initialize the OpenCL function.\n void Init(OpenCLModuleNode* m, ObjectPtr sptr, OpenCLModuleNode::KTRefEntry entry,\n std::string func_name, std::vector arg_size,\n const std::vector& thread_axis_tags) {\n w_ = m->GetGlobalWorkspace();\n m_ = m;\n sptr_ = sptr;\n entry_ = entry;\n func_name_ = func_name;\n arg_size_ = arg_size;\n thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);\n }\n \/\/ invoke the function with void arguments\n void operator()(TVMArgs args, TVMRetValue* rv, void** void_args) const {\n ICHECK(w_->context != nullptr) << \"No OpenCL device\";\n cl::OpenCLThreadEntry* t = w_->GetThreadEntry();\n \/\/ get the kernel from thread local kernel table.\n if (entry_.kernel_id >= t->kernel_table.size()) {\n t->kernel_table.resize(entry_.kernel_id + 1);\n }\n const auto& e = t->kernel_table[entry_.kernel_id];\n cl_kernel kernel = e.kernel;\n if (kernel == nullptr || e.version != entry_.version) {\n kernel = m_->InstallKernel(w_, t, func_name_, entry_);\n }\n \/\/ setup arguments.\n for (cl_uint i = 0; i < arg_size_.size(); ++i) {\n auto* arg = static_cast(void_args[i]);\n OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], arg->buffer));\n }\n cl_command_queue queue = w_->GetQueue(t->device);\n ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);\n cl_uint work_dim = static_cast(thread_axis_cfg_.work_dim());\n for (cl_uint i = 0; i < work_dim; ++i) {\n wl.work_size[i] *= wl.work_size[i + 3];\n }\n \/\/ launch kernel\n OPENCL_CALL(clEnqueueNDRangeKernel(queue, kernel, work_dim, nullptr, wl.work_size,\n wl.work_size + 3, 0, nullptr, nullptr));\n }\n\n private:\n \/\/ global workspace.\n cl::OpenCLWorkspace* w_;\n \/\/ The module\n OpenCLModuleNode* m_;\n \/\/ resource handle\n ObjectPtr sptr_;\n \/\/ global kernel id in the kernel table.\n OpenCLModuleNode::KTRefEntry entry_;\n \/\/ The name of the function.\n std::string func_name_;\n \/\/ convert code for void argument\n std::vector arg_size_;\n \/\/ thread axis config\n ThreadAxisConfig thread_axis_cfg_;\n};\n\nOpenCLModuleNode::~OpenCLModuleNode() {\n {\n \/\/ free the kernel ids in global table.\n std::lock_guard lock(workspace_->mu);\n for (auto& kv : kid_map_) {\n workspace_->free_kernel_ids.push_back(kv.second.kernel_id);\n }\n }\n \/\/ free the kernels\n for (cl_kernel k : kernels_) {\n OPENCL_CALL(clReleaseKernel(k));\n }\n \/\/ free the programs\n for (auto& kv : programs_) {\n for (auto& program : kv.second) {\n if (program) {\n OPENCL_CALL(clReleaseProgram(program));\n }\n }\n }\n}\n\ncl::OpenCLWorkspace* OpenCLModuleNode::GetGlobalWorkspace() {\n return cl::OpenCLWorkspace::Global();\n}\n\nPackedFunc OpenCLModuleNode::GetFunction(const std::string& name,\n const ObjectPtr& sptr_to_self) {\n ICHECK_EQ(sptr_to_self.get(), this);\n ICHECK_NE(name, symbol::tvm_module_main) << \"Device function do not have main\";\n auto it = fmap_.find(name);\n if (it == fmap_.end()) return PackedFunc();\n const FunctionInfo& info = it->second;\n OpenCLWrappedFunc f;\n std::vector arg_size(info.arg_types.size());\n for (size_t i = 0; i < info.arg_types.size(); ++i) {\n DLDataType t = info.arg_types[i];\n ICHECK_EQ(t.lanes, 1U);\n if (t.code == kTVMOpaqueHandle) {\n \/\/ specially store pointer type size in OpenCL driver\n arg_size[i] = sizeof(void*);\n } else {\n uint32_t bits = t.bits;\n ICHECK_EQ(bits % 8, 0U);\n arg_size[i] = bits \/ 8;\n }\n }\n \/\/ initialize the wrapped func.\n f.Init(this, sptr_to_self, kid_map_.at(name), name, arg_size, info.thread_axis_tags);\n return PackFuncVoidAddr(f, info.arg_types);\n}\n\nvoid OpenCLModuleNode::SaveToFile(const std::string& file_name, const std::string& format) {\n std::string fmt = GetFileFormat(file_name, format);\n ICHECK_EQ(fmt, fmt_) << \"Can only save to format=\" << fmt_;\n std::string meta_file = GetMetaFilePath(file_name);\n SaveMetaDataToFile(meta_file, fmap_);\n SaveBinaryToFile(file_name, data_);\n}\n\nvoid OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {\n stream->Write(fmt_);\n stream->Write(fmap_);\n stream->Write(data_);\n}\n\nstd::string OpenCLModuleNode::GetSource(const std::string& format) {\n if (format == fmt_) return data_;\n if (fmt_ == \"cl\") {\n return data_;\n } else {\n return source_;\n }\n}\n\nvoid OpenCLModuleNode::Init() {\n workspace_ = GetGlobalWorkspace();\n workspace_->Init();\n \/\/ initialize the kernel id, need to lock global table.\n std::lock_guard lock(workspace_->mu);\n for (const auto& kv : fmap_) {\n const std::string& key = kv.first;\n KTRefEntry e;\n if (workspace_->free_kernel_ids.size() != 0) {\n e.kernel_id = workspace_->free_kernel_ids.back();\n workspace_->free_kernel_ids.pop_back();\n } else {\n e.kernel_id = workspace_->num_registered_kernels++;\n }\n e.version = workspace_->timestamp++;\n kid_map_[key] = e;\n }\n\n \/\/ split into source artifacts for each kernel\n parsed_kernels_ = SplitKernels(GetSource(\"cl\"));\n ICHECK(!parsed_kernels_.empty()) << \"The OpenCL module expects a kernel delimited \"\n << \"source from code generation, but no kernel \"\n << \"delimiter was found.\";\n ICHECK_EQ(workspace_->num_registered_kernels, parsed_kernels_.size())\n << \"The number of registered kernels does not match number of parsed kernel sources\";\n \/\/ zero initialize cl_program pointers for each device kernel\n for (auto& kv : parsed_kernels_) {\n programs_.insert({kv.first, std::vector(workspace_->devices.size(), nullptr)});\n }\n}\n\ncl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w, cl::OpenCLThreadEntry* t,\n const std::string& func_name, const KTRefEntry& e) {\n std::lock_guard lock(build_lock_);\n int device_id = t->device.device_id;\n if (programs_[func_name][device_id] == nullptr) {\n \/\/ create program\n if (fmt_ == \"cl\") {\n const char* s = parsed_kernels_[func_name].c_str();\n size_t len = parsed_kernels_[func_name].length();\n cl_int err;\n programs_[func_name][device_id] = clCreateProgramWithSource(w->context, 1, &s, &len, &err);\n OPENCL_CHECK_ERROR(err);\n } else if (fmt_ == \"xclbin\" || fmt_ == \"awsxclbin\" || fmt_ == \"aocx\") {\n const unsigned char* s = (const unsigned char*)data_.c_str();\n size_t len = data_.length();\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n programs_[func_name][device_id] =\n clCreateProgramWithBinary(w->context, 1, &dev, &len, &s, NULL, &err);\n OPENCL_CHECK_ERROR(err);\n } else {\n LOG(FATAL) << \"Unknown OpenCL format \" << fmt_;\n }\n \/\/ build program\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n err = clBuildProgram(programs_[func_name][device_id], 1, &dev, nullptr, nullptr, nullptr);\n if (err != CL_SUCCESS) {\n size_t len;\n std::string log;\n clGetProgramBuildInfo(programs_[func_name][device_id], dev, CL_PROGRAM_BUILD_LOG, 0, nullptr,\n &len);\n log.resize(len);\n clGetProgramBuildInfo(programs_[func_name][device_id], dev, CL_PROGRAM_BUILD_LOG, len,\n &log[0], nullptr);\n LOG(FATAL) << \"OpenCL build error for device=\" << dev << \"\\n\" << log;\n }\n }\n \/\/ build kernel\n cl_int err;\n cl_kernel kernel = clCreateKernel(programs_[func_name][device_id], func_name.c_str(), &err);\n OPENCL_CHECK_ERROR(err);\n t->kernel_table[e.kernel_id].kernel = kernel;\n t->kernel_table[e.kernel_id].version = e.version;\n kernels_.push_back(kernel);\n return kernel;\n}\n\nModule OpenCLModuleCreate(std::string data, std::string fmt,\n std::unordered_map fmap, std::string source) {\n auto n = make_object(data, fmt, fmap, source);\n n->Init();\n return Module(n);\n}\n\n\/\/ Load module from module.\nModule OpenCLModuleLoadFile(const std::string& file_name, const std::string& format) {\n std::string data;\n std::unordered_map fmap;\n std::string fmt = GetFileFormat(file_name, format);\n std::string meta_file = GetMetaFilePath(file_name);\n LoadBinaryFromFile(file_name, &data);\n LoadMetaDataFromFile(meta_file, &fmap);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nModule OpenCLModuleLoadBinary(void* strm) {\n dmlc::Stream* stream = static_cast(strm);\n std::string data;\n std::unordered_map fmap;\n std::string fmt;\n stream->Read(&fmt);\n stream->Read(&fmap);\n stream->Read(&data);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadfile_cl\").set_body_typed(OpenCLModuleLoadFile);\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadfile_clbin\").set_body_typed(OpenCLModuleLoadFile);\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadbinary_opencl\").set_body_typed(OpenCLModuleLoadBinary);\n} \/\/ namespace runtime\n} \/\/ namespace tvm\nUpdate parsed kernel sources check. (#8257)\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing,\n * software distributed under the License is distributed on an\n * \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n * specific language governing permissions and limitations\n * under the License.\n *\/\n\n\/*!\n * \\file opencl_module.cc\n *\/\n#include \"opencl_module.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \"..\/source_utils.h\"\n#include \"opencl_common.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass OpenCLWrappedFunc {\n public:\n \/\/ initialize the OpenCL function.\n void Init(OpenCLModuleNode* m, ObjectPtr sptr, OpenCLModuleNode::KTRefEntry entry,\n std::string func_name, std::vector arg_size,\n const std::vector& thread_axis_tags) {\n w_ = m->GetGlobalWorkspace();\n m_ = m;\n sptr_ = sptr;\n entry_ = entry;\n func_name_ = func_name;\n arg_size_ = arg_size;\n thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);\n }\n \/\/ invoke the function with void arguments\n void operator()(TVMArgs args, TVMRetValue* rv, void** void_args) const {\n ICHECK(w_->context != nullptr) << \"No OpenCL device\";\n cl::OpenCLThreadEntry* t = w_->GetThreadEntry();\n \/\/ get the kernel from thread local kernel table.\n if (entry_.kernel_id >= t->kernel_table.size()) {\n t->kernel_table.resize(entry_.kernel_id + 1);\n }\n const auto& e = t->kernel_table[entry_.kernel_id];\n cl_kernel kernel = e.kernel;\n if (kernel == nullptr || e.version != entry_.version) {\n kernel = m_->InstallKernel(w_, t, func_name_, entry_);\n }\n \/\/ setup arguments.\n for (cl_uint i = 0; i < arg_size_.size(); ++i) {\n auto* arg = static_cast(void_args[i]);\n OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], arg->buffer));\n }\n cl_command_queue queue = w_->GetQueue(t->device);\n ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);\n cl_uint work_dim = static_cast(thread_axis_cfg_.work_dim());\n for (cl_uint i = 0; i < work_dim; ++i) {\n wl.work_size[i] *= wl.work_size[i + 3];\n }\n \/\/ launch kernel\n OPENCL_CALL(clEnqueueNDRangeKernel(queue, kernel, work_dim, nullptr, wl.work_size,\n wl.work_size + 3, 0, nullptr, nullptr));\n }\n\n private:\n \/\/ global workspace.\n cl::OpenCLWorkspace* w_;\n \/\/ The module\n OpenCLModuleNode* m_;\n \/\/ resource handle\n ObjectPtr sptr_;\n \/\/ global kernel id in the kernel table.\n OpenCLModuleNode::KTRefEntry entry_;\n \/\/ The name of the function.\n std::string func_name_;\n \/\/ convert code for void argument\n std::vector arg_size_;\n \/\/ thread axis config\n ThreadAxisConfig thread_axis_cfg_;\n};\n\nOpenCLModuleNode::~OpenCLModuleNode() {\n {\n \/\/ free the kernel ids in global table.\n std::lock_guard lock(workspace_->mu);\n for (auto& kv : kid_map_) {\n workspace_->free_kernel_ids.push_back(kv.second.kernel_id);\n }\n }\n \/\/ free the kernels\n for (cl_kernel k : kernels_) {\n OPENCL_CALL(clReleaseKernel(k));\n }\n \/\/ free the programs\n for (auto& kv : programs_) {\n for (auto& program : kv.second) {\n if (program) {\n OPENCL_CALL(clReleaseProgram(program));\n }\n }\n }\n}\n\ncl::OpenCLWorkspace* OpenCLModuleNode::GetGlobalWorkspace() {\n return cl::OpenCLWorkspace::Global();\n}\n\nPackedFunc OpenCLModuleNode::GetFunction(const std::string& name,\n const ObjectPtr& sptr_to_self) {\n ICHECK_EQ(sptr_to_self.get(), this);\n ICHECK_NE(name, symbol::tvm_module_main) << \"Device function do not have main\";\n auto it = fmap_.find(name);\n if (it == fmap_.end()) return PackedFunc();\n const FunctionInfo& info = it->second;\n OpenCLWrappedFunc f;\n std::vector arg_size(info.arg_types.size());\n for (size_t i = 0; i < info.arg_types.size(); ++i) {\n DLDataType t = info.arg_types[i];\n ICHECK_EQ(t.lanes, 1U);\n if (t.code == kTVMOpaqueHandle) {\n \/\/ specially store pointer type size in OpenCL driver\n arg_size[i] = sizeof(void*);\n } else {\n uint32_t bits = t.bits;\n ICHECK_EQ(bits % 8, 0U);\n arg_size[i] = bits \/ 8;\n }\n }\n \/\/ initialize the wrapped func.\n f.Init(this, sptr_to_self, kid_map_.at(name), name, arg_size, info.thread_axis_tags);\n return PackFuncVoidAddr(f, info.arg_types);\n}\n\nvoid OpenCLModuleNode::SaveToFile(const std::string& file_name, const std::string& format) {\n std::string fmt = GetFileFormat(file_name, format);\n ICHECK_EQ(fmt, fmt_) << \"Can only save to format=\" << fmt_;\n std::string meta_file = GetMetaFilePath(file_name);\n SaveMetaDataToFile(meta_file, fmap_);\n SaveBinaryToFile(file_name, data_);\n}\n\nvoid OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {\n stream->Write(fmt_);\n stream->Write(fmap_);\n stream->Write(data_);\n}\n\nstd::string OpenCLModuleNode::GetSource(const std::string& format) {\n if (format == fmt_) return data_;\n if (fmt_ == \"cl\") {\n return data_;\n } else {\n return source_;\n }\n}\n\nvoid OpenCLModuleNode::Init() {\n workspace_ = GetGlobalWorkspace();\n workspace_->Init();\n \/\/ initialize the kernel id, need to lock global table.\n std::lock_guard lock(workspace_->mu);\n for (const auto& kv : fmap_) {\n const std::string& key = kv.first;\n KTRefEntry e;\n if (workspace_->free_kernel_ids.size() != 0) {\n e.kernel_id = workspace_->free_kernel_ids.back();\n workspace_->free_kernel_ids.pop_back();\n } else {\n e.kernel_id = workspace_->num_registered_kernels++;\n }\n e.version = workspace_->timestamp++;\n kid_map_[key] = e;\n }\n\n \/\/ split into source artifacts for each kernel\n parsed_kernels_ = SplitKernels(GetSource(\"cl\"));\n ICHECK(!parsed_kernels_.empty()) << \"The OpenCL module expects a kernel delimited \"\n << \"source from code generation, but no kernel \"\n << \"delimiter was found.\";\n ICHECK_EQ(fmap_.size(), parsed_kernels_.size())\n << \"The number of parsed kernel sources does not match the number of kernel functions\";\n \/\/ zero initialize cl_program pointers for each device kernel\n for (auto& kv : parsed_kernels_) {\n programs_.insert({kv.first, std::vector(workspace_->devices.size(), nullptr)});\n }\n}\n\ncl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w, cl::OpenCLThreadEntry* t,\n const std::string& func_name, const KTRefEntry& e) {\n std::lock_guard lock(build_lock_);\n int device_id = t->device.device_id;\n if (programs_[func_name][device_id] == nullptr) {\n \/\/ create program\n if (fmt_ == \"cl\") {\n const char* s = parsed_kernels_[func_name].c_str();\n size_t len = parsed_kernels_[func_name].length();\n cl_int err;\n programs_[func_name][device_id] = clCreateProgramWithSource(w->context, 1, &s, &len, &err);\n OPENCL_CHECK_ERROR(err);\n } else if (fmt_ == \"xclbin\" || fmt_ == \"awsxclbin\" || fmt_ == \"aocx\") {\n const unsigned char* s = (const unsigned char*)data_.c_str();\n size_t len = data_.length();\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n programs_[func_name][device_id] =\n clCreateProgramWithBinary(w->context, 1, &dev, &len, &s, NULL, &err);\n OPENCL_CHECK_ERROR(err);\n } else {\n LOG(FATAL) << \"Unknown OpenCL format \" << fmt_;\n }\n \/\/ build program\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n err = clBuildProgram(programs_[func_name][device_id], 1, &dev, nullptr, nullptr, nullptr);\n if (err != CL_SUCCESS) {\n size_t len;\n std::string log;\n clGetProgramBuildInfo(programs_[func_name][device_id], dev, CL_PROGRAM_BUILD_LOG, 0, nullptr,\n &len);\n log.resize(len);\n clGetProgramBuildInfo(programs_[func_name][device_id], dev, CL_PROGRAM_BUILD_LOG, len,\n &log[0], nullptr);\n LOG(FATAL) << \"OpenCL build error for device=\" << dev << \"\\n\" << log;\n }\n }\n \/\/ build kernel\n cl_int err;\n cl_kernel kernel = clCreateKernel(programs_[func_name][device_id], func_name.c_str(), &err);\n OPENCL_CHECK_ERROR(err);\n t->kernel_table[e.kernel_id].kernel = kernel;\n t->kernel_table[e.kernel_id].version = e.version;\n kernels_.push_back(kernel);\n return kernel;\n}\n\nModule OpenCLModuleCreate(std::string data, std::string fmt,\n std::unordered_map fmap, std::string source) {\n auto n = make_object(data, fmt, fmap, source);\n n->Init();\n return Module(n);\n}\n\n\/\/ Load module from module.\nModule OpenCLModuleLoadFile(const std::string& file_name, const std::string& format) {\n std::string data;\n std::unordered_map fmap;\n std::string fmt = GetFileFormat(file_name, format);\n std::string meta_file = GetMetaFilePath(file_name);\n LoadBinaryFromFile(file_name, &data);\n LoadMetaDataFromFile(meta_file, &fmap);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nModule OpenCLModuleLoadBinary(void* strm) {\n dmlc::Stream* stream = static_cast(strm);\n std::string data;\n std::unordered_map fmap;\n std::string fmt;\n stream->Read(&fmt);\n stream->Read(&fmap);\n stream->Read(&data);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadfile_cl\").set_body_typed(OpenCLModuleLoadFile);\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadfile_clbin\").set_body_typed(OpenCLModuleLoadFile);\n\nTVM_REGISTER_GLOBAL(\"runtime.module.loadbinary_opencl\").set_body_typed(OpenCLModuleLoadBinary);\n} \/\/ namespace runtime\n} \/\/ namespace tvm\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"qmakeprojectimporter.h\"\n\n#include \"qmakebuildinfo.h\"\n#include \"qmakekitinformation.h\"\n#include \"qmakebuildconfiguration.h\"\n#include \"qmakeproject.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nstatic const Core::Id QT_IS_TEMPORARY(\"Qmake.TempQt\");\n\nnamespace QmakeProjectManager {\nnamespace Internal {\n\nQmakeProjectImporter::QmakeProjectImporter(const QString &path) :\n ProjectExplorer::ProjectImporter(path)\n{ }\n\nQList QmakeProjectImporter::import(const Utils::FileName &importPath,\n bool silent)\n{\n QList result;\n QFileInfo fi = importPath.toFileInfo();\n if (!fi.exists() && !fi.isDir())\n return result;\n\n QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String(\"Makefile*\")));\n\n QtSupport::BaseQtVersion *version = 0;\n bool temporaryVersion = false;\n\n foreach (const QString &file, makefiles) {\n \/\/ find interesting makefiles\n QString makefile = importPath.toString() + QLatin1Char('\/') + file;\n Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);\n QFileInfo qmakeFi = qmakeBinary.toFileInfo();\n Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath());\n if (canonicalQmakeBinary.isEmpty())\n continue;\n if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject)\n continue;\n\n \/\/ Find version:\n foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) {\n QFileInfo vfi = v->qmakeCommand().toFileInfo();\n Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());\n if (current == canonicalQmakeBinary) {\n version = v;\n break;\n }\n }\n\n \/\/ Create a new version if not found:\n if (!version) {\n \/\/ Do not use the canonical path here...\n version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);\n if (!version)\n continue;\n\n setIsUpdating(true);\n QtSupport::QtVersionManager::addVersion(version);\n setIsUpdating(false);\n temporaryVersion = true;\n }\n\n \/\/ find qmake arguments and mkspec\n QPair makefileBuildConfig =\n QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());\n\n QString additionalArguments = makefileBuildConfig.second;\n Utils::FileName parsedSpec =\n QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version);\n Utils::FileName versionSpec = version->mkspec();\n if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1(\"default\"))\n parsedSpec = versionSpec;\n\n QString specArgument;\n \/\/ Compare mkspecs and add to additional arguments\n if (parsedSpec != versionSpec)\n specArgument = QLatin1String(\"-spec \") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());\n Utils::QtcProcess::addArgs(&specArgument, additionalArguments);\n\n \/\/ Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux):\n QList kitList;\n foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {\n QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k);\n Utils::FileName kitSpec = QmakeKitInformation::mkspec(k);\n ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);\n if (kitSpec.isEmpty() && kitVersion)\n kitSpec = kitVersion->mkspecFor(tc);\n\n if (kitVersion == version\n && kitSpec == parsedSpec)\n kitList.append(k);\n }\n if (kitList.isEmpty())\n kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));\n\n foreach (ProjectExplorer::Kit *k, kitList) {\n addProject(k);\n\n QmakeBuildConfigurationFactory *factory\n = qobject_cast(\n ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath()));\n\n if (!factory)\n continue;\n\n \/\/ create info:\n QmakeBuildInfo *info = new QmakeBuildInfo(factory);\n if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) {\n info->type = ProjectExplorer::BuildConfiguration::Debug;\n info->displayName = QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"Debug\");\n } else {\n info->type = ProjectExplorer::BuildConfiguration::Release;\n info->displayName = QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"Release\");\n }\n info->kitId = k->id();\n info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath());\n info->additionalArguments = additionalArguments;\n info->makefile = makefile;\n\n bool found = false;\n foreach (ProjectExplorer::BuildInfo *bInfo, result) {\n if (*static_cast(bInfo) == *info) {\n found = true;\n break;\n }\n }\n if (found)\n delete info;\n else\n result << info;\n }\n }\n\n if (result.isEmpty() && !silent)\n QMessageBox::critical(Core::ICore::mainWindow(),\n QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"No Build Found\"),\n QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"No build found in %1 matching project %2.\")\n .arg(importPath.toUserOutput()).arg(QDir::toNativeSeparators(projectFilePath())));\n\n return result;\n}\n\nQStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath)\n{\n QStringList candidates;\n\n QFileInfo pfi = projectPath.toFileInfo();\n const QString prefix = pfi.baseName();\n candidates << pfi.absolutePath();\n\n QList kitList = ProjectExplorer::KitManager::kits();\n foreach (ProjectExplorer::Kit *k, kitList) {\n QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString()));\n const QString baseDir = fi.absolutePath();\n\n foreach (const QString &dir, QDir(baseDir).entryList()) {\n const QString path = baseDir + QLatin1Char('\/') + dir;\n if (dir.startsWith(prefix) && !candidates.contains(path))\n candidates << path;\n }\n }\n return candidates;\n}\n\nProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList &possibleTargets)\n{\n \/\/ Select active target\n \/\/ a) The default target\n \/\/ b) Simulator target\n \/\/ c) Desktop target\n \/\/ d) the first target\n ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0);\n int activeTargetPriority = 0;\n foreach (ProjectExplorer::Target *t, possibleTargets) {\n QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());\n if (t->kit() == ProjectExplorer::KitManager::defaultKit()) {\n activeTarget = t;\n activeTargetPriority = 3;\n } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) {\n activeTarget = t;\n activeTargetPriority = 2;\n } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) {\n activeTarget = t;\n activeTargetPriority = 1;\n }\n }\n return activeTarget;\n}\n\nvoid QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k)\n{\n QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt());\n if (version)\n QtSupport::QtVersionManager::removeVersion(version);\n}\n\nProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version,\n bool temporaryVersion,\n const Utils::FileName &parsedSpec)\n{\n ProjectExplorer::Kit *k = new ProjectExplorer::Kit;\n QtSupport::QtKitInformation::setQtVersion(k, version);\n ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));\n QmakeKitInformation::setMkspec(k, parsedSpec);\n\n markTemporary(k);\n if (temporaryVersion)\n k->setValue(QT_IS_TEMPORARY, version->uniqueId());\n\n k->setDisplayName(version->displayName());\n setIsUpdating(true);\n ProjectExplorer::KitManager::registerKit(k);\n setIsUpdating(false);\n return k;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmakeProjectManager\nProject Import: Make sure all values are fully set up\/****************************************************************************\n**\n** Copyright (C) 2014 Digia Plc and\/or its subsidiary(-ies).\n** Contact: http:\/\/www.qt-project.org\/legal\n**\n** This file is part of Qt Creator.\n**\n** Commercial License Usage\n** Licensees holding valid commercial Qt licenses may use this file in\n** accordance with the commercial license agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Digia. For licensing terms and\n** conditions see http:\/\/qt.digia.com\/licensing. For further information\n** use the contact form at http:\/\/qt.digia.com\/contact-us.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Digia gives you certain additional\n** rights. These rights are described in the Digia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n****************************************************************************\/\n\n#include \"qmakeprojectimporter.h\"\n\n#include \"qmakebuildinfo.h\"\n#include \"qmakekitinformation.h\"\n#include \"qmakebuildconfiguration.h\"\n#include \"qmakeproject.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\nstatic const Core::Id QT_IS_TEMPORARY(\"Qmake.TempQt\");\n\nnamespace QmakeProjectManager {\nnamespace Internal {\n\nQmakeProjectImporter::QmakeProjectImporter(const QString &path) :\n ProjectExplorer::ProjectImporter(path)\n{ }\n\nQList QmakeProjectImporter::import(const Utils::FileName &importPath,\n bool silent)\n{\n QList result;\n QFileInfo fi = importPath.toFileInfo();\n if (!fi.exists() && !fi.isDir())\n return result;\n\n QStringList makefiles = QDir(importPath.toString()).entryList(QStringList(QLatin1String(\"Makefile*\")));\n\n QtSupport::BaseQtVersion *version = 0;\n bool temporaryVersion = false;\n\n foreach (const QString &file, makefiles) {\n \/\/ find interesting makefiles\n QString makefile = importPath.toString() + QLatin1Char('\/') + file;\n Utils::FileName qmakeBinary = QtSupport::QtVersionManager::findQMakeBinaryFromMakefile(makefile);\n QFileInfo qmakeFi = qmakeBinary.toFileInfo();\n Utils::FileName canonicalQmakeBinary = Utils::FileName::fromString(qmakeFi.canonicalFilePath());\n if (canonicalQmakeBinary.isEmpty())\n continue;\n if (QtSupport::QtVersionManager::makefileIsFor(makefile, projectFilePath()) != QtSupport::QtVersionManager::SameProject)\n continue;\n\n \/\/ Find version:\n foreach (QtSupport::BaseQtVersion *v, QtSupport::QtVersionManager::versions()) {\n QFileInfo vfi = v->qmakeCommand().toFileInfo();\n Utils::FileName current = Utils::FileName::fromString(vfi.canonicalFilePath());\n if (current == canonicalQmakeBinary) {\n version = v;\n break;\n }\n }\n\n \/\/ Create a new version if not found:\n if (!version) {\n \/\/ Do not use the canonical path here...\n version = QtSupport::QtVersionFactory::createQtVersionFromQMakePath(qmakeBinary);\n if (!version)\n continue;\n\n setIsUpdating(true);\n QtSupport::QtVersionManager::addVersion(version);\n setIsUpdating(false);\n temporaryVersion = true;\n }\n\n \/\/ find qmake arguments and mkspec\n QPair makefileBuildConfig =\n QtSupport::QtVersionManager::scanMakeFile(makefile, version->defaultBuildConfig());\n\n QString additionalArguments = makefileBuildConfig.second;\n Utils::FileName parsedSpec =\n QmakeBuildConfiguration::extractSpecFromArguments(&additionalArguments, importPath.toString(), version);\n Utils::FileName versionSpec = version->mkspec();\n if (parsedSpec.isEmpty() || parsedSpec == Utils::FileName::fromLatin1(\"default\"))\n parsedSpec = versionSpec;\n\n QString specArgument;\n \/\/ Compare mkspecs and add to additional arguments\n if (parsedSpec != versionSpec)\n specArgument = QLatin1String(\"-spec \") + Utils::QtcProcess::quoteArg(parsedSpec.toUserOutput());\n Utils::QtcProcess::addArgs(&specArgument, additionalArguments);\n\n \/\/ Find kits (can be more than one, e.g. (Linux-)Desktop and embedded linux):\n QList kitList;\n foreach (ProjectExplorer::Kit *k, ProjectExplorer::KitManager::kits()) {\n QtSupport::BaseQtVersion *kitVersion = QtSupport::QtKitInformation::qtVersion(k);\n Utils::FileName kitSpec = QmakeKitInformation::mkspec(k);\n ProjectExplorer::ToolChain *tc = ProjectExplorer::ToolChainKitInformation::toolChain(k);\n if (kitSpec.isEmpty() && kitVersion)\n kitSpec = kitVersion->mkspecFor(tc);\n\n if (kitVersion == version\n && kitSpec == parsedSpec)\n kitList.append(k);\n }\n if (kitList.isEmpty())\n kitList.append(createTemporaryKit(version, temporaryVersion, parsedSpec));\n\n foreach (ProjectExplorer::Kit *k, kitList) {\n addProject(k);\n\n QmakeBuildConfigurationFactory *factory\n = qobject_cast(\n ProjectExplorer::IBuildConfigurationFactory::find(k, projectFilePath()));\n\n if (!factory)\n continue;\n\n \/\/ create info:\n QmakeBuildInfo *info = new QmakeBuildInfo(factory);\n if (makefileBuildConfig.first & QtSupport::BaseQtVersion::DebugBuild) {\n info->type = ProjectExplorer::BuildConfiguration::Debug;\n info->displayName = QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"Debug\");\n } else {\n info->type = ProjectExplorer::BuildConfiguration::Release;\n info->displayName = QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"Release\");\n }\n info->kitId = k->id();\n info->buildDirectory = Utils::FileName::fromString(fi.absoluteFilePath());\n info->additionalArguments = additionalArguments;\n info->makefile = makefile;\n\n bool found = false;\n foreach (ProjectExplorer::BuildInfo *bInfo, result) {\n if (*static_cast(bInfo) == *info) {\n found = true;\n break;\n }\n }\n if (found)\n delete info;\n else\n result << info;\n }\n }\n\n if (result.isEmpty() && !silent)\n QMessageBox::critical(Core::ICore::mainWindow(),\n QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"No Build Found\"),\n QCoreApplication::translate(\"QmakeProjectManager::Internal::QmakeProjectImporter\", \"No build found in %1 matching project %2.\")\n .arg(importPath.toUserOutput()).arg(QDir::toNativeSeparators(projectFilePath())));\n\n return result;\n}\n\nQStringList QmakeProjectImporter::importCandidates(const Utils::FileName &projectPath)\n{\n QStringList candidates;\n\n QFileInfo pfi = projectPath.toFileInfo();\n const QString prefix = pfi.baseName();\n candidates << pfi.absolutePath();\n\n QList kitList = ProjectExplorer::KitManager::kits();\n foreach (ProjectExplorer::Kit *k, kitList) {\n QFileInfo fi(QmakeProject::shadowBuildDirectory(projectPath.toString(), k, QString()));\n const QString baseDir = fi.absolutePath();\n\n foreach (const QString &dir, QDir(baseDir).entryList()) {\n const QString path = baseDir + QLatin1Char('\/') + dir;\n if (dir.startsWith(prefix) && !candidates.contains(path))\n candidates << path;\n }\n }\n return candidates;\n}\n\nProjectExplorer::Target *QmakeProjectImporter::preferredTarget(const QList &possibleTargets)\n{\n \/\/ Select active target\n \/\/ a) The default target\n \/\/ b) Simulator target\n \/\/ c) Desktop target\n \/\/ d) the first target\n ProjectExplorer::Target *activeTarget = possibleTargets.isEmpty() ? 0 : possibleTargets.at(0);\n int activeTargetPriority = 0;\n foreach (ProjectExplorer::Target *t, possibleTargets) {\n QtSupport::BaseQtVersion *version = QtSupport::QtKitInformation::qtVersion(t->kit());\n if (t->kit() == ProjectExplorer::KitManager::defaultKit()) {\n activeTarget = t;\n activeTargetPriority = 3;\n } else if (activeTargetPriority < 2 && version && version->type() == QLatin1String(QtSupport::Constants::SIMULATORQT)) {\n activeTarget = t;\n activeTargetPriority = 2;\n } else if (activeTargetPriority < 1 && version && version->type() == QLatin1String(QtSupport::Constants::DESKTOPQT)) {\n activeTarget = t;\n activeTargetPriority = 1;\n }\n }\n return activeTarget;\n}\n\nvoid QmakeProjectImporter::cleanupKit(ProjectExplorer::Kit *k)\n{\n QtSupport::BaseQtVersion *version = QtSupport::QtVersionManager::version(k->value(QT_IS_TEMPORARY, -1).toInt());\n if (version)\n QtSupport::QtVersionManager::removeVersion(version);\n}\n\nProjectExplorer::Kit *QmakeProjectImporter::createTemporaryKit(QtSupport::BaseQtVersion *version,\n bool temporaryVersion,\n const Utils::FileName &parsedSpec)\n{\n ProjectExplorer::Kit *k = new ProjectExplorer::Kit;\n\n ProjectExplorer::KitGuard guard(k);\n\n QtSupport::QtKitInformation::setQtVersion(k, version);\n ProjectExplorer::ToolChainKitInformation::setToolChain(k, version->preferredToolChain(parsedSpec));\n QmakeKitInformation::setMkspec(k, parsedSpec);\n\n markTemporary(k);\n if (temporaryVersion)\n k->setValue(QT_IS_TEMPORARY, version->uniqueId());\n\n \/\/ Set up other values:\n foreach (ProjectExplorer::KitInformation *ki, ProjectExplorer::KitManager::kitInformation()) {\n if (ki->id() == ProjectExplorer::ToolChainKitInformation::id()\n || ki->id() == QtSupport::QtKitInformation::id())\n continue;\n ki->setup(k);\n }\n\n k->setDisplayName(version->displayName());\n\n setIsUpdating(true);\n ProjectExplorer::KitManager::registerKit(k);\n setIsUpdating(false);\n return k;\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace QmakeProjectManager\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \"serverconfig.hpp\"\r\n#include \"util\/util.hpp\"\r\n#include \"filesystem.hpp\"\r\n#include \"logger.hpp\"\r\n\r\nnamespace po = boost::program_options;\r\n\r\nnamespace redi {\r\n\r\nconst char* ServerConfig::ConfigFilePath = \"configuration.txt\";\r\nconst char* ServerConfig::DefaultConfigFileContent =\r\n \"# Hello !\\n\"\r\n \"online=false\\n\"\r\n \"maxplayers=1472\\n\"\r\n \"motd=Redi - Highly flammable\\n\"\r\n \"gamemode=1\\n\"\r\n \"difficulty=0\\n\"\r\n \"leveltype=DEFAULT\\n\"\r\n \"port=25565\\n\"\r\n \"icon=icon.png\\n\"\r\n \"rangeview=5\";\r\n\r\nServerConfig::ServerConfig() {\r\n onlineMode = false;\r\n maxPlayers = 1472;\r\n motd = \"Redi - Highly flammable\";\r\n gamemode = Gamemode::Creative;\r\n difficulty = Difficulty::Peaceful;\r\n levelType = \"DEFAULT\";\r\n reducedDebugInfo = false;\r\n port = 25565;\r\n iconpath = \"icon.png\";\r\n rangeView = 5;\r\n \r\n if (fs::exists(ConfigFilePath)) {\r\n try {\r\n readConfig();\r\n }\r\n catch (std::exception&) {\r\n Logger::error(\"Error while parsing the configuration file\");\r\n throw;\r\n }\r\n }\r\n else {\r\n writeConfig();\r\n }\r\n}\r\n\r\nvoid ServerConfig::readConfig() {\r\n static const char* OnlineText = \"online\";\r\n static const char* MaxPlayerText = \"maxplayers\";\r\n static const char* MotdText = \"motd\";\r\n static const char* GamemodeText = \"gamemode\";\r\n static const char* DifficultyText = \"difficulty\";\r\n static const char* LevelTypeText = \"leveltype\";\r\n static const char* PortText = \"port\";\r\n static const char* IconText = \"icon\";\r\n static const char* RangeViewText = \"rangeview\";\r\n \r\n boost::property_tree::ptree tree;\r\n \r\n \/*\r\n * Just a tree, keep scrolling.\r\n _{\\ _{\\{\\\/}\/}\/}__\r\n {\/{\/\\}{\/{\/\\}(\\}{\/\\} _\r\n {\/{\/\\}{\/{\/\\}(_)\\}{\/{\/\\} _\r\n {\\{\/(\\}\\}{\/{\/\\}\\}{\/){\/\\}\\} \/\\}\r\n {\/{\/(_)\/}{\\{\/)\\}{\\(_){\/}\/}\/}\/}\r\n _{\\{\/{\/{\\{\/{\/(_)\/}\/}\/}{\\(\/}\/}\/}\r\n {\/{\/{\\{\\{\\(\/}{\\{\\\/}\/}{\\}(_){\\\/}\\}\r\n _{\\{\/{\\{\/(_)\\}\/}{\/{\/{\/\\}\\})\\}{\/\\}\r\n {\/{\/{\\{\\(\/}{\/{\\{\\{\\\/})\/}{\\(_)\/}\/}\\}\r\n {\\{\\\/}(_){\\{\\{\\\/}\/}(_){\\\/}{\\\/}\/})\/}\r\n {\/{\\{\\\/}{\/{\\{\\{\\\/}\/}{\\{\\\/}\/}\\}(_)\r\n {\/{\\{\\\/}{\/){\\{\\{\\\/}\/}{\\{\\(\/}\/}\\}\/}\r\n {\/{\\{\\\/}(_){\\{\\{\\(\/}\/}{\\(_)\/}\/}\\}\r\n {\/({\/{\\{\/{\\{\\\/}(_){\\\/}\/}\\}\/}(\\}\r\n (_){\/{\\\/}{\\{\\\/}\/}{\\{\\)\/}\/}(_)\r\n {\/{\/{\\{\\\/}{\/{\\{\\{\\(_)\/}\r\n {\/{\\{\\{\\\/}\/}{\\{\\\\}\/}\r\n {){\/ {\\\/}{\\\/} \\}\\}\r\n (_) \\.-'.-\/\r\n __...--- |'-.-'| --...__\r\n _...--\" .-' |'-.-'| ' -. \"\"--..__\r\n -\" ' . . ' |.'-._| ' . . ' jro\r\n . '- ' .--' | '-.'| . ' . '\r\n ' .. |'-_.-|\r\n . ' . _.-|-._ -|-._ . ' .\r\n .' |'- .-| '.\r\n ..-' ' . '. `-._.-´ .' ' - .\r\n .-' ' '-._______.-' ' .\r\n . ~,\r\n . . |\\ . ' '-.\r\n *\/\r\n \r\n boost::property_tree::ini_parser::read_ini(ConfigFilePath, tree);\r\n \r\n if (tree.count(OnlineText)) {\r\n onlineMode = tree.get(OnlineText);\r\n }\r\n if (tree.count(MaxPlayerText)) {\r\n maxPlayers = tree.get(MaxPlayerText);\r\n }\r\n if (tree.count(MotdText)) {\r\n motd = tree.get(MotdText);\r\n }\r\n if (tree.count(GamemodeText)) {\r\n gamemode = static_cast(tree.get(GamemodeText));\r\n }\r\n if (tree.count(DifficultyText)) {\r\n difficulty = static_cast(tree.get(DifficultyText));\r\n }\r\n if (tree.count(LevelTypeText)) {\r\n levelType = tree.get(LevelTypeText);\r\n }\r\n if (tree.count(PortText)) {\r\n port = tree.get(PortText);\r\n }\r\n if (tree.count(IconText)) {\r\n iconpath = tree.get(IconText);\r\n readIcon();\r\n }\r\n if (tree.count(RangeViewText)) {\r\n rangeView = tree.get(RangeViewText);\r\n }\r\n}\r\n\r\n\/*\r\n * Reads the server icon from disk.\r\n *\/\r\nvoid ServerConfig::readIcon() {\r\n if (fs::exists(iconpath)) {\r\n ByteBuffer buffer = util::readFile(iconpath);\r\n \r\n iconb64 = std::string(\"data:image\/png;base64,\") +\r\n util::Base64Encoder::encodeToString(buffer);\r\n \/*\r\n * Icon has to be sent encoded as base64.\r\n *\/\r\n }\r\n}\r\n\r\n\/*\r\n * Writes the default configuration file.\r\n *\/\r\nvoid ServerConfig::writeConfig() {\r\n std::ofstream(ConfigFilePath) << DefaultConfigFileContent;\r\n}\r\n\r\nconst char* GamemodeEnumToString(Gamemode g) {\r\n const char* names[] = {\"survival\", \"creative\", \"adventure\", \"spectator\"};\r\n return names[static_cast(g)];\r\n}\r\n\r\nconst char* DifficultyEnumToString(Difficulty d) {\r\n const char* names[] = {\"peaceful\", \"easy\", \"normal\", \"hard\"};\r\n return names[static_cast(d)];\r\n}\r\n\r\n} \/\/ namespace redi\r\nFixed#include \r\n#include \r\n#include \"serverconfig.hpp\"\r\n#include \"util\/util.hpp\"\r\n#include \"filesystem.hpp\"\r\n#include \"logger.hpp\"\r\n\r\nnamespace redi {\r\n\r\nconst char* ServerConfig::ConfigFilePath = \"configuration.txt\";\r\nconst char* ServerConfig::DefaultConfigFileContent =\r\n \"# Hello !\\n\"\r\n \"online=false\\n\"\r\n \"maxplayers=1472\\n\"\r\n \"motd=Redi - Highly flammable\\n\"\r\n \"gamemode=1\\n\"\r\n \"difficulty=0\\n\"\r\n \"leveltype=DEFAULT\\n\"\r\n \"port=25565\\n\"\r\n \"icon=icon.png\\n\"\r\n \"rangeview=5\";\r\n\r\nServerConfig::ServerConfig() {\r\n onlineMode = false;\r\n maxPlayers = 1472;\r\n motd = \"Redi - Highly flammable\";\r\n gamemode = Gamemode::Creative;\r\n difficulty = Difficulty::Peaceful;\r\n levelType = \"DEFAULT\";\r\n reducedDebugInfo = false;\r\n port = 25565;\r\n iconpath = \"icon.png\";\r\n rangeView = 5;\r\n \r\n if (fs::exists(ConfigFilePath)) {\r\n try {\r\n readConfig();\r\n }\r\n catch (std::exception&) {\r\n Logger::error(\"Error while parsing the configuration file\");\r\n throw;\r\n }\r\n }\r\n else {\r\n writeConfig();\r\n }\r\n}\r\n\r\nvoid ServerConfig::readConfig() {\r\n static const char* OnlineText = \"online\";\r\n static const char* MaxPlayerText = \"maxplayers\";\r\n static const char* MotdText = \"motd\";\r\n static const char* GamemodeText = \"gamemode\";\r\n static const char* DifficultyText = \"difficulty\";\r\n static const char* LevelTypeText = \"leveltype\";\r\n static const char* PortText = \"port\";\r\n static const char* IconText = \"icon\";\r\n static const char* RangeViewText = \"rangeview\";\r\n \r\n boost::property_tree::ptree tree;\r\n \r\n \/*\r\n * Just a tree, keep scrolling.\r\n _{\\ _{\\{\\\/}\/}\/}__\r\n {\/{\/\\}{\/{\/\\}(\\}{\/\\} _\r\n {\/{\/\\}{\/{\/\\}(_)\\}{\/{\/\\} _\r\n {\\{\/(\\}\\}{\/{\/\\}\\}{\/){\/\\}\\} \/\\}\r\n {\/{\/(_)\/}{\\{\/)\\}{\\(_){\/}\/}\/}\/}\r\n _{\\{\/{\/{\\{\/{\/(_)\/}\/}\/}{\\(\/}\/}\/}\r\n {\/{\/{\\{\\{\\(\/}{\\{\\\/}\/}{\\}(_){\\\/}\\}\r\n _{\\{\/{\\{\/(_)\\}\/}{\/{\/{\/\\}\\})\\}{\/\\}\r\n {\/{\/{\\{\\(\/}{\/{\\{\\{\\\/})\/}{\\(_)\/}\/}\\}\r\n {\\{\\\/}(_){\\{\\{\\\/}\/}(_){\\\/}{\\\/}\/})\/}\r\n {\/{\\{\\\/}{\/{\\{\\{\\\/}\/}{\\{\\\/}\/}\\}(_)\r\n {\/{\\{\\\/}{\/){\\{\\{\\\/}\/}{\\{\\(\/}\/}\\}\/}\r\n {\/{\\{\\\/}(_){\\{\\{\\(\/}\/}{\\(_)\/}\/}\\}\r\n {\/({\/{\\{\/{\\{\\\/}(_){\\\/}\/}\\}\/}(\\}\r\n (_){\/{\\\/}{\\{\\\/}\/}{\\{\\)\/}\/}(_)\r\n {\/{\/{\\{\\\/}{\/{\\{\\{\\(_)\/}\r\n {\/{\\{\\{\\\/}\/}{\\{\\\\}\/}\r\n {){\/ {\\\/}{\\\/} \\}\\}\r\n (_) \\.-'.-\/\r\n __...--- |'-.-'| --...__\r\n _...--\" .-' |'-.-'| ' -. \"\"--..__\r\n -\" ' . . ' |.'-._| ' . . ' jro\r\n . '- ' .--' | '-.'| . ' . '\r\n ' .. |'-_.-|\r\n . ' . _.-|-._ -|-._ . ' .\r\n .' |'- .-| '.\r\n ..-' ' . '. `-._.-´ .' ' - .\r\n .-' ' '-._______.-' ' .\r\n . ~,\r\n . . |\\ . ' '-.\r\n *\/\r\n \r\n boost::property_tree::ini_parser::read_ini(ConfigFilePath, tree);\r\n \r\n if (tree.count(OnlineText)) {\r\n onlineMode = tree.get(OnlineText);\r\n }\r\n if (tree.count(MaxPlayerText)) {\r\n maxPlayers = tree.get(MaxPlayerText);\r\n }\r\n if (tree.count(MotdText)) {\r\n motd = tree.get(MotdText);\r\n }\r\n if (tree.count(GamemodeText)) {\r\n gamemode = static_cast(tree.get(GamemodeText));\r\n }\r\n if (tree.count(DifficultyText)) {\r\n difficulty = static_cast(tree.get(DifficultyText));\r\n }\r\n if (tree.count(LevelTypeText)) {\r\n levelType = tree.get(LevelTypeText);\r\n }\r\n if (tree.count(PortText)) {\r\n port = tree.get(PortText);\r\n }\r\n if (tree.count(IconText)) {\r\n iconpath = tree.get(IconText);\r\n readIcon();\r\n }\r\n if (tree.count(RangeViewText)) {\r\n rangeView = tree.get(RangeViewText);\r\n }\r\n}\r\n\r\n\/*\r\n * Reads the server icon from disk.\r\n *\/\r\nvoid ServerConfig::readIcon() {\r\n if (fs::exists(iconpath)) {\r\n ByteBuffer buffer = util::readFile(iconpath);\r\n \r\n iconb64 = std::string(\"data:image\/png;base64,\") +\r\n util::Base64Encoder::encodeToString(buffer);\r\n \/*\r\n * Icon has to be sent encoded as base64.\r\n *\/\r\n }\r\n}\r\n\r\n\/*\r\n * Writes the default configuration file.\r\n *\/\r\nvoid ServerConfig::writeConfig() {\r\n std::ofstream(ConfigFilePath) << DefaultConfigFileContent;\r\n}\r\n\r\nconst char* GamemodeEnumToString(Gamemode g) {\r\n const char* names[] = {\"survival\", \"creative\", \"adventure\", \"spectator\"};\r\n return names[static_cast(g)];\r\n}\r\n\r\nconst char* DifficultyEnumToString(Difficulty d) {\r\n const char* names[] = {\"peaceful\", \"easy\", \"normal\", \"hard\"};\r\n return names[static_cast(d)];\r\n}\r\n\r\n} \/\/ namespace redi\r\n<|endoftext|>"} {"text":"#include \"window.h\"\n\nnamespace elsa {\n\tnamespace vm {\n\n\t\t\/\/ Refactor this if support for multiple windows is added\n\t\tHDC mem_hdc;\n\t\tHBITMAP bitmap;\n\n\t\tWindow::Window(const std::wstring& title, int width, int height)\n\t\t{\n\t\t\thinstance_ = GetModuleHandle(NULL);\n\n\t\t\twcex_.cbSize = sizeof(WNDCLASSEX);\n\t\t\twcex_.style = CS_HREDRAW | CS_VREDRAW;\n\t\t\twcex_.lpfnWndProc = WndProc;\n\t\t\twcex_.cbClsExtra = 0;\n\t\t\twcex_.cbWndExtra = 0;\n\t\t\twcex_.hInstance = hinstance_;\n\t\t\twcex_.hIcon = LoadIcon(hinstance_, MAKEINTRESOURCE(IDI_APPLICATION));\n\t\t\twcex_.hCursor = LoadCursor(NULL, IDC_ARROW);\n\t\t\twcex_.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n\t\t\twcex_.lpszMenuName = NULL;\n\t\t\twcex_.lpszClassName = L\"ElsaWindow\";\n\t\t\twcex_.hIconSm = LoadIcon(wcex_.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));\n\n\t\t\tif (!RegisterClassEx(&wcex_))\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Call to RegisterClassEx failed!\", L\"ElsaWindow\", NULL);\n\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to RegisterClassEx failed\");\n\t\t\t}\n\n\t\t\tDWORD window_style = WS_OVERLAPPEDWINDOW;\n\t\t\tRECT client_rect = { 0, 0, width, height };\n\t\t\tif (!AdjustWindowRectEx(&client_rect, window_style, false, NULL))\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to AdjustWindowRectEx failed\");\n\t\t\t}\n\n\t\t\thwnd_ = CreateWindow(\n\t\t\t\tL\"ElsaWindow\",\n\t\t\t\ttitle.c_str(),\n\t\t\t\twindow_style,\n\t\t\t\tCW_USEDEFAULT, \n\t\t\t\tCW_USEDEFAULT,\n\t\t\t\t\/\/ width\n\t\t\t\tclient_rect.right - client_rect.left, \n\t\t\t\t\/\/ height\n\t\t\t\tclient_rect.bottom - client_rect.top,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\thinstance_,\n\t\t\t\tNULL\n\t\t\t\t);\n\n#ifdef _DEBUG\n\t\t\tGetClientRect(hwnd_, &client_rect);\n\t\t\tif (client_rect.right != width || client_rect.bottom != height)\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Invalid client area size\");\n\t\t\t}\n#endif\n\n\t\t\tif (!hwnd_)\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to CreateWindow failed\");\n\t\t\t}\n\n\t\t\tHDC hdc = GetDC(hwnd_);\n\t\t\tmem_hdc = CreateCompatibleDC(hdc);\n\t\t\tbitmap = CreateCompatibleBitmap(hdc, width, height);\n\n\t\t\tSelectObject(mem_hdc, bitmap);\n\t\t}\n\n\t\tWindow::~Window() \n\t\t{\n\n\t\t}\n\n\t\tLRESULT Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n\t\t{\n\t\t\tswitch (message)\n\t\t\t{\n\t\t\tcase WM_PAINT: {\n\t\t\t\tPAINTSTRUCT ps;\n\t\t\t\tHDC hdc = BeginPaint(hWnd, &ps);\n\t\t\t\tauto width = ps.rcPaint.right;\n\t\t\t\tauto height = ps.rcPaint.bottom;\n\t\t\t\tBitBlt(hdc, 0, 0, width, height, mem_hdc, 0, 0, SRCCOPY);\n\t\t\t\tEndPaint(hWnd, &ps);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase WM_DESTROY:\n\t\t\t\tPostQuitMessage(0);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn DefWindowProc(hWnd, message, wParam, lParam);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tResourceHandleType Window::get_type()\n\t\t{\n\t\t\treturn ResourceHandleType::Window;\n\t\t}\n\n\t\tvoid Window::open()\n\t\t{\n\t\t\tShowWindow(hwnd_, SW_SHOW);\n\t\t\tUpdateWindow(hwnd_);\n\t\t}\n\n\t\tvoid Window::update()\n\t\t{\n\t\t\tRedrawWindow(hwnd_, NULL, NULL, RDW_INVALIDATE);\n\t\t}\n\n\t\tvoid Window::fill_rect(int x, int y, int width, int height, int r, int g, int b)\n\t\t{\n\t\t\tauto brush = CreateSolidBrush(RGB(r, b, b));\n\t\t\tRECT rect;\n\t\t\trect.left = x;\n\t\t\trect.right = x + width;\n\t\t\trect.top = y;\n\t\t\trect.bottom = y + height;\n\t\t\tFillRect(mem_hdc, &rect, brush);\n\t\t\tDeleteObject(brush);\n\t\t}\n\t}\n}\nadded some cleanup code in the window class#include \"window.h\"\n\nnamespace elsa {\n\tnamespace vm {\n\n\t\t\/\/ Refactor this if support for multiple windows is added\n\t\tHDC mem_hdc;\n\t\tHBITMAP bitmap;\n\n\t\tWindow::Window(const std::wstring& title, int width, int height)\n\t\t{\n\t\t\thinstance_ = GetModuleHandle(NULL);\n\n\t\t\twcex_.cbSize = sizeof(WNDCLASSEX);\n\t\t\twcex_.style = CS_HREDRAW | CS_VREDRAW;\n\t\t\twcex_.lpfnWndProc = WndProc;\n\t\t\twcex_.cbClsExtra = 0;\n\t\t\twcex_.cbWndExtra = 0;\n\t\t\twcex_.hInstance = hinstance_;\n\t\t\twcex_.hIcon = LoadIcon(hinstance_, MAKEINTRESOURCE(IDI_APPLICATION));\n\t\t\twcex_.hCursor = LoadCursor(NULL, IDC_ARROW);\n\t\t\twcex_.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);\n\t\t\twcex_.lpszMenuName = NULL;\n\t\t\twcex_.lpszClassName = L\"ElsaWindow\";\n\t\t\twcex_.hIconSm = LoadIcon(wcex_.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));\n\n\t\t\tif (!RegisterClassEx(&wcex_))\n\t\t\t{\n\t\t\t\tMessageBox(NULL, L\"Call to RegisterClassEx failed!\", L\"ElsaWindow\", NULL);\n\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to RegisterClassEx failed\");\n\t\t\t}\n\n\t\t\tDWORD window_style = WS_OVERLAPPEDWINDOW;\n\t\t\tRECT client_rect = { 0, 0, width, height };\n\t\t\tif (!AdjustWindowRectEx(&client_rect, window_style, false, NULL))\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to AdjustWindowRectEx failed\");\n\t\t\t}\n\n\t\t\thwnd_ = CreateWindow(\n\t\t\t\tL\"ElsaWindow\",\n\t\t\t\ttitle.c_str(),\n\t\t\t\twindow_style,\n\t\t\t\tCW_USEDEFAULT, \n\t\t\t\tCW_USEDEFAULT,\n\t\t\t\t\/\/ width\n\t\t\t\tclient_rect.right - client_rect.left, \n\t\t\t\t\/\/ height\n\t\t\t\tclient_rect.bottom - client_rect.top,\n\t\t\t\tNULL,\n\t\t\t\tNULL,\n\t\t\t\thinstance_,\n\t\t\t\tNULL\n\t\t\t\t);\n\n#ifdef _DEBUG\n\t\t\tGetClientRect(hwnd_, &client_rect);\n\t\t\tif (client_rect.right != width || client_rect.bottom != height)\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Invalid client area size\");\n\t\t\t}\n#endif\n\n\t\t\tif (!hwnd_)\n\t\t\t{\n\t\t\t\tthrow RuntimeException(\"Could not create window, call to CreateWindow failed\");\n\t\t\t}\n\n\t\t\tHDC hdc = GetDC(hwnd_);\n\t\t\tmem_hdc = CreateCompatibleDC(hdc);\n\t\t\tbitmap = CreateCompatibleBitmap(hdc, width, height);\n\n\t\t\tSelectObject(mem_hdc, bitmap);\n\n\t\t\tDeleteObject(hdc);\n\t\t}\n\n\t\tWindow::~Window() \n\t\t{\n\n\t\t}\n\n\t\tLRESULT Window::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)\n\t\t{\n\t\t\tswitch (message)\n\t\t\t{\n\t\t\tcase WM_PAINT: {\n\t\t\t\tPAINTSTRUCT ps;\n\t\t\t\tHDC hdc = BeginPaint(hWnd, &ps);\n\t\t\t\tauto width = ps.rcPaint.right;\n\t\t\t\tauto height = ps.rcPaint.bottom;\n\t\t\t\tBitBlt(hdc, 0, 0, width, height, mem_hdc, 0, 0, SRCCOPY);\n\t\t\t\tEndPaint(hWnd, &ps);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase WM_DESTROY:\n\t\t\t\tDeleteObject(mem_hdc);\n\t\t\t\tDeleteObject(bitmap);\n\t\t\t\tPostQuitMessage(0);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn DefWindowProc(hWnd, message, wParam, lParam);\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\treturn 0;\n\t\t}\n\n\t\tResourceHandleType Window::get_type()\n\t\t{\n\t\t\treturn ResourceHandleType::Window;\n\t\t}\n\n\t\tvoid Window::open()\n\t\t{\n\t\t\tShowWindow(hwnd_, SW_SHOW);\n\t\t\tUpdateWindow(hwnd_);\n\t\t}\n\n\t\tvoid Window::update()\n\t\t{\n\t\t\tRedrawWindow(hwnd_, NULL, NULL, RDW_INVALIDATE);\n\t\t}\n\n\t\tvoid Window::fill_rect(int x, int y, int width, int height, int r, int g, int b)\n\t\t{\n\t\t\tauto brush = CreateSolidBrush(RGB(r, b, b));\n\t\t\tRECT rect;\n\t\t\trect.left = x;\n\t\t\trect.right = x + width;\n\t\t\trect.top = y;\n\t\t\trect.bottom = y + height;\n\t\t\tFillRect(mem_hdc, &rect, brush);\n\t\t\tDeleteObject(brush);\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"Bump the limit for test-heap\/TestSizeOfRegExpCode<|endoftext|>"} {"text":"fix storage order request<|endoftext|>"} {"text":"update 1D test with labels due to changes in TH1::Merge done withthe previous commit (37655)<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical Image Computing.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n\n\/\/ qt widgets module\n#include \"QmitkCustomVariants.h\"\n#include \"QmitkEnums.h\"\n\nQmitkDataStorageDefaultListModel::QmitkDataStorageDefaultListModel(QObject *parent)\n{\n \/\/ nothing here\n}\n\nvoid QmitkDataStorageDefaultListModel::DataStorageChanged()\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodePredicateChanged()\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeAdded(const mitk::DataNode* node)\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeChanged(const mitk::DataNode* node)\n{\n \/\/ nothing here, since the \"'NodeChanged'-event is currently sent far too often\n \/\/UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeRemoved(const mitk::DataNode* node)\n{\n UpdateModelData();\n}\n\nQModelIndex QmitkDataStorageDefaultListModel::index(int row, int column, const QModelIndex &parent) const\n{\n bool hastIndex = hasIndex(row, column, parent);\n if (hastIndex)\n {\n return createIndex(row, column);\n }\n\n return QModelIndex();\n}\n\nQModelIndex QmitkDataStorageDefaultListModel::parent(const QModelIndex &child) const\n{\n return QModelIndex();\n}\n\nint QmitkDataStorageDefaultListModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return m_DataNodes.size();\n}\n\nint QmitkDataStorageDefaultListModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return 1;\n}\n\nQVariant QmitkDataStorageDefaultListModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid())\n {\n return QVariant();\n }\n\n if(index.row() < 0 || index.row() >= m_DataNodes.size())\n {\n return QVariant();\n }\n\n mitk::DataNode::Pointer dataNode = m_DataNodes.at(index.row());\n if (Qt::DisplayRole == role)\n {\n return QVariant(QString::fromStdString(dataNode->GetName()));\n }\n else if (QmitkDataNodeRole == role)\n {\n return QVariant::fromValue(dataNode);\n }\n\n return QVariant();\n}\n\nQVariant QmitkDataStorageDefaultListModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n return QVariant(tr(\"Nodes\"));\n}\n\nQt::ItemFlags QmitkDataStorageDefaultListModel::flags(const QModelIndex &index) const\n{\n if (index.isValid())\n {\n return Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n }\n\n return Qt::NoItemFlags;\n}\n\nvoid QmitkDataStorageDefaultListModel::UpdateModelData()\n{\n mitk::DataStorage::SetOfObjects::ConstPointer dataNodes;\n if (m_DataStorage != nullptr)\n {\n if (m_NodePredicate != nullptr)\n {\n dataNodes = m_DataStorage->GetSubset(m_NodePredicate);\n }\n else\n {\n dataNodes = m_DataStorage->GetAll();\n }\n }\n\n \/\/ update the model, so that it will be filled with the nodes of the new data storage\n beginResetModel();\n m_DataNodes.clear();\n\n \/\/ add all (filtered) nodes to the vector of nodes\n if (dataNodes != nullptr)\n {\n for (auto& node : *dataNodes)\n {\n m_DataNodes.push_back(node);\n }\n }\n endResetModel();\n}\nfixed little typo\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical Image Computing.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#include \n\n\/\/ qt widgets module\n#include \"QmitkCustomVariants.h\"\n#include \"QmitkEnums.h\"\n\nQmitkDataStorageDefaultListModel::QmitkDataStorageDefaultListModel(QObject *parent)\n{\n \/\/ nothing here\n}\n\nvoid QmitkDataStorageDefaultListModel::DataStorageChanged()\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodePredicateChanged()\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeAdded(const mitk::DataNode* node)\n{\n UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeChanged(const mitk::DataNode* node)\n{\n \/\/ nothing here, since the \"'NodeChanged'-event is currently sent far too often\n \/\/UpdateModelData();\n}\n\nvoid QmitkDataStorageDefaultListModel::NodeRemoved(const mitk::DataNode* node)\n{\n UpdateModelData();\n}\n\nQModelIndex QmitkDataStorageDefaultListModel::index(int row, int column, const QModelIndex &parent) const\n{\n bool hasIndex = this->hasIndex(row, column, parent);\n if (hasIndex)\n {\n return this->createIndex(row, column);\n }\n\n return QModelIndex();\n}\n\nQModelIndex QmitkDataStorageDefaultListModel::parent(const QModelIndex &child) const\n{\n return QModelIndex();\n}\n\nint QmitkDataStorageDefaultListModel::rowCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return m_DataNodes.size();\n}\n\nint QmitkDataStorageDefaultListModel::columnCount(const QModelIndex &parent) const\n{\n if (parent.isValid())\n {\n return 0;\n }\n\n return 1;\n}\n\nQVariant QmitkDataStorageDefaultListModel::data(const QModelIndex &index, int role) const\n{\n if (!index.isValid())\n {\n return QVariant();\n }\n\n if(index.row() < 0 || index.row() >= m_DataNodes.size())\n {\n return QVariant();\n }\n\n mitk::DataNode::Pointer dataNode = m_DataNodes.at(index.row());\n if (Qt::DisplayRole == role)\n {\n return QVariant(QString::fromStdString(dataNode->GetName()));\n }\n else if (QmitkDataNodeRole == role)\n {\n return QVariant::fromValue(dataNode);\n }\n\n return QVariant();\n}\n\nQVariant QmitkDataStorageDefaultListModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n return QVariant(tr(\"Nodes\"));\n}\n\nQt::ItemFlags QmitkDataStorageDefaultListModel::flags(const QModelIndex &index) const\n{\n if (index.isValid())\n {\n return Qt::ItemIsEnabled | Qt::ItemIsSelectable;\n }\n\n return Qt::NoItemFlags;\n}\n\nvoid QmitkDataStorageDefaultListModel::UpdateModelData()\n{\n mitk::DataStorage::SetOfObjects::ConstPointer dataNodes;\n if (m_DataStorage != nullptr)\n {\n if (m_NodePredicate != nullptr)\n {\n dataNodes = m_DataStorage->GetSubset(m_NodePredicate);\n }\n else\n {\n dataNodes = m_DataStorage->GetAll();\n }\n }\n\n \/\/ update the model, so that it will be filled with the nodes of the new data storage\n beginResetModel();\n m_DataNodes.clear();\n\n \/\/ add all (filtered) nodes to the vector of nodes\n if (dataNodes != nullptr)\n {\n for (auto& node : *dataNodes)\n {\n m_DataNodes.push_back(node);\n }\n }\n endResetModel();\n}\n<|endoftext|>"} {"text":"#include \"amalgamated_budget.hpp\"\n#include \"account.hpp\"\n#include \"account_impl.hpp\"\n#include \"account_type.hpp\"\n#include \"budget_item_reader.hpp\"\n#include \"draft_journal.hpp\"\n#include \"entry.hpp\"\n#include \"frequency.hpp\"\n#include \"interval_type.hpp\"\n#include \"phatbooks_exceptions.hpp\"\n#include \"repeater.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::scoped_ptr;\nusing jewel::Decimal;\nusing sqloxx::SQLStatement;\nusing std::accumulate;\nusing std::ostream;\nusing std::pair;\nusing std::vector;\n\nnamespace gregorian = boost::gregorian;\n\n\/\/ For debugging only\n#include \n#include \nusing std::endl;\n\/\/ End debugging stuff\n\n\n\n\nnamespace phatbooks\n{\n\n\nBOOST_STATIC_ASSERT((boost::is_same::value));\n\n\nvoid\nAmalgamatedBudget::setup_tables(PhatbooksDatabaseConnection& dbc)\n{\n\tdbc.execute_sql\n\t(\t\"create index budget_item_account_index on budget_items(account_id)\"\n\t);\n\tdbc.execute_sql\n\t(\t\"create table amalgamated_budget_data\"\n\t\t\"(\"\n\t\t\t\"journal_id integer unique not null \"\n\t\t\t\"references draft_journal_detail, \"\n\t\t\t\"balancing_account_id integer unique not null \"\n\t\t\t\"references accounts\"\n\t\t\")\"\n\t);\n\tDraftJournal instrument(dbc);\n\tinstrument.set_name(\"AMALGAMATED BUDGET INSTRUMENT\");\n\tinstrument.set_whether_actual(false);\n\tinstrument.set_comment(\"\");\n\tinstrument.save();\n\n\tAccount balancing_account(dbc);\n\tbalancing_account.set_account_type(account_type::pure_envelope);\n\tbalancing_account.set_name(\"BUDGET IMBALANCE\");\n\tbalancing_account.set_description(\"\");\n\tbalancing_account.set_commodity\n\t(\tCommodity::default_commodity(dbc)\n\t);\n\tbalancing_account.save();\n\n\tSQLStatement statement\n\t(\tdbc,\n\t\t\"insert into amalgamated_budget_data\"\n\t\t\"(journal_id, balancing_account_id) \"\n\t\t\"values(:journal_id, :balancing_account_id)\"\n\t);\n\tstatement.bind(\":journal_id\", instrument.id());\n\tstatement.bind(\":balancing_account_id\", balancing_account.id());\n\tstatement.step_final();\n\n\treturn;\n}\n\nAmalgamatedBudget::AmalgamatedBudget\n(\tPhatbooksDatabaseConnection& p_database_connection\n):\n\tm_is_loaded(false),\n\tm_database_connection(p_database_connection),\n\tm_frequency(1, interval_type::days),\n\tm_map(new Map),\n\tm_instrument(0),\n\tm_balancing_account(0)\n{\n}\n\n\nAmalgamatedBudget::~AmalgamatedBudget()\n{\n\tdelete m_instrument;\n\tm_instrument = 0;\n\n\tdelete m_balancing_account;\n\tm_balancing_account = 0;\n}\n\n\nvoid\nAmalgamatedBudget::load() const\n{\n\tif (m_is_loaded)\n\t{\n\t\treturn;\n\t}\n\tassert (!m_is_loaded);\n\tload_balancing_account();\n\tload_instrument();\n\tload_map();\n\tm_is_loaded = true;\n\treturn;\n}\n\n\nFrequency\nAmalgamatedBudget::frequency() const\n{\n\tload();\n\tassert (m_frequency.num_steps() == 1);\n\treturn m_frequency;\n}\n\n\nvoid\nAmalgamatedBudget::set_frequency(Frequency const& p_frequency)\n{\n\tload();\n\tm_frequency = p_frequency;\n\tregenerate();\n\treturn;\n}\n\n\n\nDecimal\nAmalgamatedBudget::budget(AccountImpl::Id p_account_id) const\n{\n\tload();\n\tMap::const_iterator it = m_map->find(p_account_id);\n\tassert (it != m_map->end());\n\treturn it->second;\n}\n\n\nnamespace\n{\n\tDecimal map_entry_accumulation_aux\n\t(\tDecimal const& dec,\n\t\tpair const& rhs\n\t)\n\t{\n\t\treturn dec + rhs.second;\n\t}\n\n} \/\/ end anonymous namespace\t\n\n\nDecimal\nAmalgamatedBudget::balance() const\n{\n\tload();\n\treturn accumulate\n\t(\tm_map->begin(),\n\t\tm_map->end(),\n\t\tDecimal(0, 0),\n\t\tmap_entry_accumulation_aux\n\t);\n}\t\n\n\nvoid\nAmalgamatedBudget::generate_supported_frequencies(vector& vec)\n{\n\t\/\/ NOTE This is co-dependent with the function\n\t\/\/ AmalgamatedBudget::supports_frequency. If this\n\t\/\/ changes, that must change too.\n\tvec.reserve(10);\n\tvec.push_back(Frequency(1, interval_type::days));\n\tvec.push_back(Frequency(1, interval_type::weeks));\n\tvec.push_back(Frequency(2, interval_type::weeks));\n\tvec.push_back(Frequency(4, interval_type::weeks));\n\tvec.push_back(Frequency(1, interval_type::months));\n\tvec.push_back(Frequency(2, interval_type::months));\n\tvec.push_back(Frequency(3, interval_type::months));\n\tvec.push_back(Frequency(4, interval_type::months));\n\tvec.push_back(Frequency(6, interval_type::months));\n\tvec.push_back(Frequency(12, interval_type::months));\n\treturn;\n}\n\n\nbool\nAmalgamatedBudget::supports_frequency(Frequency const& p_frequency)\n{\n\t\/\/ NOTE This is co-dependent with the function\n\t\/\/ AmalgamatedBudget::supported_frequencies. If this changes,\n\t\/\/ that must change too.\n\tswitch (p_frequency.step_type())\n\t{\n\tcase interval_type::days:\n\t\treturn p_frequency.num_steps() == 1;\n\tcase interval_type::weeks:\n\t\tswitch (p_frequency.num_steps())\n\t\t{\n\t\tcase 1: case 2:\treturn true;\n\t\tcase 3:\t\t\treturn false;\n\t\tcase 4:\t\t\treturn true;\n\t\tdefault: \t\treturn false;\n\t\t}\n\tcase interval_type::months:\n\t\tswitch (p_frequency.num_steps())\n\t\t{\n\t\tcase 1: case 2: case 3: case 4:\t\t\t\treturn true;\n\t\tcase 5:\t\t\t\t\t\t\t\t\t\treturn false;\n\t\tcase 6:\t\t\t\t\t\t\t\t\t\treturn true;\n\t\tcase 7: case 8: case 9: case 10: case 11:\treturn false;\n\t\tcase 12:\t\t\t\t\t\t\t\t\treturn true;\t\n\t\tdefault:\t\t\t\t\t\t\t\t\treturn false;\n\t\t}\n\tcase interval_type::month_ends:\n\t\treturn false;\n\tdefault:\n\t\tassert (false);\n\t}\n}\n\t\n\nAccount\nAmalgamatedBudget::balancing_account() const\n{\n\tload();\n\tassert (m_balancing_account != 0);\n\treturn *m_balancing_account;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate()\n{\n\tload();\n\tregenerate_map();\n\tregenerate_instrument();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::load_map() const\n{\n\tassert (!m_is_loaded);\n\tassert (m_map->empty());\n\tgenerate_map();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::generate_map() const\n{\n\tscoped_ptr map_elect(new Map);\n\tassert (map_elect->empty());\n\n\tSQLStatement account_selector\n\t(\tm_database_connection,\n\t\t\"select account_id from accounts\"\n\t);\n\twhile (account_selector.step())\n\t{\n\t\tAccountImpl::Id const account_id =\n\t\t\taccount_selector.extract(0);\n\t\tAccount const account(m_database_connection, account_id);\n\t\t(*map_elect)[account_id] =\n\t\t\tDecimal(0, account.commodity().precision());\n\t}\n\tBudgetItemReader budget_item_reader(m_database_connection);\n\tBudgetItemReader::const_iterator const beg = budget_item_reader.begin();\n\tBudgetItemReader::const_iterator const end = budget_item_reader.end();\n\t\n\t\/\/ First we calculate budgets amalgamated on the basis of\n\t\/\/ the canonical frequency\n\tBudgetItemReader::const_iterator it = beg;\n\tfor ( ; it != end; ++it)\n\t{\n\t\tFrequency const raw_frequency = it->frequency();\n\t\tif (!AmalgamatedBudget::supports_frequency(raw_frequency))\n\t\t{\n\t\t\tthrow InvalidFrequencyException\n\t\t\t(\t\"Frequency not supported by AmalgamatedBudget.\"\n\t\t\t);\n\t\t}\n\t\tAccountImpl::Id const account_id = it->account().id();\n\t\tjewel::Decimal const raw_amount = it->amount();\n\t\tjewel::Decimal const canonical_amount = convert_to_canonical\n\t\t(\traw_frequency,\n\t\t\traw_amount\n\t\t);\n\t\tMap::iterator tmit = map_elect->find(account_id);\n\t\tassert (tmit != map_elect->end());\t\n\t\ttmit->second += canonical_amount;\n\t}\n\t\/\/ Now convert to desired frequency\n\tfor \n\t(\tMap::iterator mit = map_elect->begin(), mend = map_elect->end();\n\t\tmit != mend;\n\t\t++mit\n\t)\n\t{\n\t\tmit->second = round\n\t\t(\tconvert_from_canonical(m_frequency, mit->second),\n\t\t\tAccount(m_database_connection, mit->first).commodity().precision()\n\t\t);\n\t}\n\tusing std::swap;\n\tswap(m_map, map_elect);\n\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate_map()\n{\n\tload();\n\tgenerate_map();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate_instrument()\n{\n\tload();\n\n\tDraftJournal fresh_journal(m_database_connection);\n\tfresh_journal.mimic(*m_instrument);\n\treflect_entries(fresh_journal);\n\treflect_repeater(fresh_journal);\n\n\t\/\/ Deal with imbalance\n\tAccount const ba = balancing_account();\n\tEntry balancing_entry(m_database_connection);\n\tbalancing_entry.set_account(ba);\n\tbalancing_entry.set_comment(\"\");\n\tbalancing_entry.set_whether_reconciled(false);\n\tbalancing_entry.set_amount\n\t(\t-round(fresh_journal.balance(), ba.commodity().precision())\n\t);\n\tfresh_journal.push_entry(balancing_entry);\n\tassert (fresh_journal.is_balanced());\n\n\tm_instrument->mimic(fresh_journal);\n\tm_instrument->save();\n\n\treturn;\n}\n\nvoid\nAmalgamatedBudget::load_balancing_account() const\n{\n\tSQLStatement statement\n\t(\tm_database_connection,\n\t\t\"select balancing_account_id from amalgamated_budget_data\"\n\t);\n\tstatement.step();\n\tif (m_balancing_account)\n\t{\n\t\tdelete m_balancing_account;\n\t\tm_balancing_account = 0;\n\t}\n\tm_balancing_account = new Account\n\t(\tm_database_connection,\n\t\tstatement.extract(0)\n\t);\n\tstatement.step_final();\n\treturn;\n}\n\nvoid\nAmalgamatedBudget::load_instrument() const\n{\n\t\/\/ Set the instrument (the DraftJournal that carries out\n\t\/\/ the AmalgamatedBudget)\n\tSQLStatement statement\n\t(\tm_database_connection,\n\t\t\"select journal_id from amalgamated_budget_data\"\n\t);\n\tstatement.step();\n\tif (m_instrument)\n\t{\n\t\tdelete m_instrument;\n\t\tm_instrument = 0;\n\t}\n\tm_instrument = new DraftJournal\n\t(\tm_database_connection,\n\t\tstatement.extract(0)\n\t);\n\tstatement.step_final();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::reflect_entries(DraftJournal& p_journal)\n{\n\tload();\n\tp_journal.clear_entries();\n\tMap const& map = *m_map;\n\tfor\n\t(\tMap::const_iterator it = map.begin(), end = map.end();\n\t\tit != end;\n\t\t++it\n\t)\n\t{\n\t\tEntry entry(m_database_connection);\n\t\tAccount const account(m_database_connection, it->first);\n\t\tentry.set_account(account);\n\t\tentry.set_comment(\"\");\n\t\tentry.set_amount(-(it->second));\n\t\tentry.set_whether_reconciled(false);\n\t\tp_journal.push_entry(entry);\n\t}\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::reflect_repeater(DraftJournal& p_journal)\n{\n\tload();\n\tvector const& old_repeaters = p_journal.repeaters();\n\tif (old_repeaters.size() == 1)\n\t{\n\t\tFrequency const old_frequency = old_repeaters[0].frequency();\n\t\tif \n\t\t(\told_frequency.step_type() == m_frequency.step_type() &&\n\t\t\told_frequency.num_steps() == m_frequency.num_steps()\n\t\t)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\tp_journal.clear_repeaters();\n\tRepeater new_repeater(m_database_connection);\n\tnew_repeater.set_frequency(m_frequency);\n\tnew_repeater.set_next_date(gregorian::day_clock::local_day());\n\tassert (p_journal.repeaters().empty());\n\tp_journal.push_repeater(new_repeater);\n\treturn;\n}\n\n\n\n\n\n} \/\/ namespace phatbooks\n\n\nStopped AmalgamatedBudget::m_instrument from being populated with Entries for Accounts for which the budget is NIL.#include \"amalgamated_budget.hpp\"\n#include \"account.hpp\"\n#include \"account_impl.hpp\"\n#include \"account_type.hpp\"\n#include \"budget_item_reader.hpp\"\n#include \"draft_journal.hpp\"\n#include \"entry.hpp\"\n#include \"frequency.hpp\"\n#include \"interval_type.hpp\"\n#include \"phatbooks_exceptions.hpp\"\n#include \"repeater.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing boost::scoped_ptr;\nusing jewel::Decimal;\nusing sqloxx::SQLStatement;\nusing std::accumulate;\nusing std::ostream;\nusing std::pair;\nusing std::vector;\n\nnamespace gregorian = boost::gregorian;\n\n\/\/ For debugging only\n#include \n#include \nusing std::endl;\n\/\/ End debugging stuff\n\n\n\n\nnamespace phatbooks\n{\n\n\nBOOST_STATIC_ASSERT((boost::is_same::value));\n\n\nvoid\nAmalgamatedBudget::setup_tables(PhatbooksDatabaseConnection& dbc)\n{\n\tdbc.execute_sql\n\t(\t\"create index budget_item_account_index on budget_items(account_id)\"\n\t);\n\tdbc.execute_sql\n\t(\t\"create table amalgamated_budget_data\"\n\t\t\"(\"\n\t\t\t\"journal_id integer unique not null \"\n\t\t\t\"references draft_journal_detail, \"\n\t\t\t\"balancing_account_id integer unique not null \"\n\t\t\t\"references accounts\"\n\t\t\")\"\n\t);\n\tDraftJournal instrument(dbc);\n\tinstrument.set_name(\"AMALGAMATED BUDGET INSTRUMENT\");\n\tinstrument.set_whether_actual(false);\n\tinstrument.set_comment(\"\");\n\tinstrument.save();\n\n\tAccount balancing_account(dbc);\n\tbalancing_account.set_account_type(account_type::pure_envelope);\n\tbalancing_account.set_name(\"BUDGET IMBALANCE\");\n\tbalancing_account.set_description(\"\");\n\tbalancing_account.set_commodity\n\t(\tCommodity::default_commodity(dbc)\n\t);\n\tbalancing_account.save();\n\n\tSQLStatement statement\n\t(\tdbc,\n\t\t\"insert into amalgamated_budget_data\"\n\t\t\"(journal_id, balancing_account_id) \"\n\t\t\"values(:journal_id, :balancing_account_id)\"\n\t);\n\tstatement.bind(\":journal_id\", instrument.id());\n\tstatement.bind(\":balancing_account_id\", balancing_account.id());\n\tstatement.step_final();\n\n\treturn;\n}\n\nAmalgamatedBudget::AmalgamatedBudget\n(\tPhatbooksDatabaseConnection& p_database_connection\n):\n\tm_is_loaded(false),\n\tm_database_connection(p_database_connection),\n\tm_frequency(1, interval_type::days),\n\tm_map(new Map),\n\tm_instrument(0),\n\tm_balancing_account(0)\n{\n}\n\n\nAmalgamatedBudget::~AmalgamatedBudget()\n{\n\tdelete m_instrument;\n\tm_instrument = 0;\n\n\tdelete m_balancing_account;\n\tm_balancing_account = 0;\n}\n\n\nvoid\nAmalgamatedBudget::load() const\n{\n\tif (m_is_loaded)\n\t{\n\t\treturn;\n\t}\n\tassert (!m_is_loaded);\n\tload_balancing_account();\n\tload_instrument();\n\tload_map();\n\tm_is_loaded = true;\n\treturn;\n}\n\n\nFrequency\nAmalgamatedBudget::frequency() const\n{\n\tload();\n\tassert (m_frequency.num_steps() == 1);\n\treturn m_frequency;\n}\n\n\nvoid\nAmalgamatedBudget::set_frequency(Frequency const& p_frequency)\n{\n\tload();\n\tm_frequency = p_frequency;\n\tregenerate();\n\treturn;\n}\n\n\n\nDecimal\nAmalgamatedBudget::budget(AccountImpl::Id p_account_id) const\n{\n\tload();\n\tMap::const_iterator it = m_map->find(p_account_id);\n\tassert (it != m_map->end());\n\treturn it->second;\n}\n\n\nnamespace\n{\n\tDecimal map_entry_accumulation_aux\n\t(\tDecimal const& dec,\n\t\tpair const& rhs\n\t)\n\t{\n\t\treturn dec + rhs.second;\n\t}\n\n} \/\/ end anonymous namespace\t\n\n\nDecimal\nAmalgamatedBudget::balance() const\n{\n\tload();\n\treturn accumulate\n\t(\tm_map->begin(),\n\t\tm_map->end(),\n\t\tDecimal(0, 0),\n\t\tmap_entry_accumulation_aux\n\t);\n}\t\n\n\nvoid\nAmalgamatedBudget::generate_supported_frequencies(vector& vec)\n{\n\t\/\/ NOTE This is co-dependent with the function\n\t\/\/ AmalgamatedBudget::supports_frequency. If this\n\t\/\/ changes, that must change too.\n\tvec.reserve(10);\n\tvec.push_back(Frequency(1, interval_type::days));\n\tvec.push_back(Frequency(1, interval_type::weeks));\n\tvec.push_back(Frequency(2, interval_type::weeks));\n\tvec.push_back(Frequency(4, interval_type::weeks));\n\tvec.push_back(Frequency(1, interval_type::months));\n\tvec.push_back(Frequency(2, interval_type::months));\n\tvec.push_back(Frequency(3, interval_type::months));\n\tvec.push_back(Frequency(4, interval_type::months));\n\tvec.push_back(Frequency(6, interval_type::months));\n\tvec.push_back(Frequency(12, interval_type::months));\n\treturn;\n}\n\n\nbool\nAmalgamatedBudget::supports_frequency(Frequency const& p_frequency)\n{\n\t\/\/ NOTE This is co-dependent with the function\n\t\/\/ AmalgamatedBudget::supported_frequencies. If this changes,\n\t\/\/ that must change too.\n\tswitch (p_frequency.step_type())\n\t{\n\tcase interval_type::days:\n\t\treturn p_frequency.num_steps() == 1;\n\tcase interval_type::weeks:\n\t\tswitch (p_frequency.num_steps())\n\t\t{\n\t\tcase 1: case 2:\treturn true;\n\t\tcase 3:\t\t\treturn false;\n\t\tcase 4:\t\t\treturn true;\n\t\tdefault: \t\treturn false;\n\t\t}\n\tcase interval_type::months:\n\t\tswitch (p_frequency.num_steps())\n\t\t{\n\t\tcase 1: case 2: case 3: case 4:\t\t\t\treturn true;\n\t\tcase 5:\t\t\t\t\t\t\t\t\t\treturn false;\n\t\tcase 6:\t\t\t\t\t\t\t\t\t\treturn true;\n\t\tcase 7: case 8: case 9: case 10: case 11:\treturn false;\n\t\tcase 12:\t\t\t\t\t\t\t\t\treturn true;\t\n\t\tdefault:\t\t\t\t\t\t\t\t\treturn false;\n\t\t}\n\tcase interval_type::month_ends:\n\t\treturn false;\n\tdefault:\n\t\tassert (false);\n\t}\n}\n\t\n\nAccount\nAmalgamatedBudget::balancing_account() const\n{\n\tload();\n\tassert (m_balancing_account != 0);\n\treturn *m_balancing_account;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate()\n{\n\tload();\n\tregenerate_map();\n\tregenerate_instrument();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::load_map() const\n{\n\tassert (!m_is_loaded);\n\tassert (m_map->empty());\n\tgenerate_map();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::generate_map() const\n{\n\tscoped_ptr map_elect(new Map);\n\tassert (map_elect->empty());\n\n\tSQLStatement account_selector\n\t(\tm_database_connection,\n\t\t\"select account_id from accounts\"\n\t);\n\twhile (account_selector.step())\n\t{\n\t\tAccountImpl::Id const account_id =\n\t\t\taccount_selector.extract(0);\n\t\tAccount const account(m_database_connection, account_id);\n\t\t(*map_elect)[account_id] =\n\t\t\tDecimal(0, account.commodity().precision());\n\t}\n\tBudgetItemReader budget_item_reader(m_database_connection);\n\tBudgetItemReader::const_iterator const beg = budget_item_reader.begin();\n\tBudgetItemReader::const_iterator const end = budget_item_reader.end();\n\t\n\t\/\/ First we calculate budgets amalgamated on the basis of\n\t\/\/ the canonical frequency\n\tBudgetItemReader::const_iterator it = beg;\n\tfor ( ; it != end; ++it)\n\t{\n\t\tFrequency const raw_frequency = it->frequency();\n\t\tif (!AmalgamatedBudget::supports_frequency(raw_frequency))\n\t\t{\n\t\t\tthrow InvalidFrequencyException\n\t\t\t(\t\"Frequency not supported by AmalgamatedBudget.\"\n\t\t\t);\n\t\t}\n\t\tAccountImpl::Id const account_id = it->account().id();\n\t\tjewel::Decimal const raw_amount = it->amount();\n\t\tjewel::Decimal const canonical_amount = convert_to_canonical\n\t\t(\traw_frequency,\n\t\t\traw_amount\n\t\t);\n\t\tMap::iterator tmit = map_elect->find(account_id);\n\t\tassert (tmit != map_elect->end());\t\n\t\ttmit->second += canonical_amount;\n\t}\n\t\/\/ Now convert to desired frequency\n\tfor \n\t(\tMap::iterator mit = map_elect->begin(), mend = map_elect->end();\n\t\tmit != mend;\n\t\t++mit\n\t)\n\t{\n\t\tmit->second = round\n\t\t(\tconvert_from_canonical(m_frequency, mit->second),\n\t\t\tAccount(m_database_connection, mit->first).commodity().precision()\n\t\t);\n\t}\n\tusing std::swap;\n\tswap(m_map, map_elect);\n\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate_map()\n{\n\tload();\n\tgenerate_map();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::regenerate_instrument()\n{\n\tload();\n\n\tDraftJournal fresh_journal(m_database_connection);\n\tfresh_journal.mimic(*m_instrument);\n\treflect_entries(fresh_journal);\n\treflect_repeater(fresh_journal);\n\n\t\/\/ Deal with imbalance\n\tAccount const ba = balancing_account();\n\tEntry balancing_entry(m_database_connection);\n\tbalancing_entry.set_account(ba);\n\tbalancing_entry.set_comment(\"\");\n\tbalancing_entry.set_whether_reconciled(false);\n\tbalancing_entry.set_amount\n\t(\t-round(fresh_journal.balance(), ba.commodity().precision())\n\t);\n\tfresh_journal.push_entry(balancing_entry);\n\tassert (fresh_journal.is_balanced());\n\n\tm_instrument->mimic(fresh_journal);\n\tm_instrument->save();\n\n\treturn;\n}\n\nvoid\nAmalgamatedBudget::load_balancing_account() const\n{\n\tSQLStatement statement\n\t(\tm_database_connection,\n\t\t\"select balancing_account_id from amalgamated_budget_data\"\n\t);\n\tstatement.step();\n\tif (m_balancing_account)\n\t{\n\t\tdelete m_balancing_account;\n\t\tm_balancing_account = 0;\n\t}\n\tm_balancing_account = new Account\n\t(\tm_database_connection,\n\t\tstatement.extract(0)\n\t);\n\tstatement.step_final();\n\treturn;\n}\n\nvoid\nAmalgamatedBudget::load_instrument() const\n{\n\t\/\/ Set the instrument (the DraftJournal that carries out\n\t\/\/ the AmalgamatedBudget)\n\tSQLStatement statement\n\t(\tm_database_connection,\n\t\t\"select journal_id from amalgamated_budget_data\"\n\t);\n\tstatement.step();\n\tif (m_instrument)\n\t{\n\t\tdelete m_instrument;\n\t\tm_instrument = 0;\n\t}\n\tm_instrument = new DraftJournal\n\t(\tm_database_connection,\n\t\tstatement.extract(0)\n\t);\n\tstatement.step_final();\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::reflect_entries(DraftJournal& p_journal)\n{\n\tload();\n\tp_journal.clear_entries();\n\tMap const& map = *m_map;\n\tfor\n\t(\tMap::const_iterator it = map.begin(), end = map.end();\n\t\tit != end;\n\t\t++it\n\t)\n\t{\n\t\tif (it->second != Decimal(0, 0))\n\t\t{\n\t\t\tEntry entry(m_database_connection);\n\t\t\tentry.set_account\n\t\t\t(\tAccount(m_database_connection, it->first)\n\t\t\t);\n\t\t\tentry.set_comment(\"\");\n\t\t\tentry.set_amount(-(it->second));\n\t\t\tentry.set_whether_reconciled(false);\n\t\t\tp_journal.push_entry(entry);\n\t\t}\n\t}\n\treturn;\n}\n\n\nvoid\nAmalgamatedBudget::reflect_repeater(DraftJournal& p_journal)\n{\n\tload();\n\tvector const& old_repeaters = p_journal.repeaters();\n\tif (old_repeaters.size() == 1)\n\t{\n\t\tFrequency const old_frequency = old_repeaters[0].frequency();\n\t\tif \n\t\t(\told_frequency.step_type() == m_frequency.step_type() &&\n\t\t\told_frequency.num_steps() == m_frequency.num_steps()\n\t\t)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t}\n\tp_journal.clear_repeaters();\n\tRepeater new_repeater(m_database_connection);\n\tnew_repeater.set_frequency(m_frequency);\n\tnew_repeater.set_next_date(gregorian::day_clock::local_day());\n\tassert (p_journal.repeaters().empty());\n\tp_journal.push_repeater(new_repeater);\n\treturn;\n}\n\n\n\n\n\n} \/\/ namespace phatbooks\n\n\n<|endoftext|>"} {"text":"\/\/! \\file **************************************************************\n\/\/! \\brief Source Action de sauvegarde de traduction.\n\/\/! \n\/\/! - Compilateur : GCC,MinGW\n\/\/!\n\/\/! \\author Antoine Maleyrie\n\/\/! \\version 0.9\n\/\/! \\date 31.03.2013\n\/\/!\n\/\/! ********************************************************************\n\n\/*\n*\tCopyright © 2013 - Antoine Maleyrie.\n*\/\n\n#include \"action\/actSaveTranslation.hpp\"\n#include \"resource.hpp\"\n\n#include \n#include \n#include \n#include \n\n\n\/\/TEST\n#include \n\n\n\/\/ *********************************************************************\n\/\/ Class PanelActSaveTranslation\n\/\/ *********************************************************************\n\nPanelActSaveTranslation::PanelActSaveTranslation(wxWindow* parent, wxButton* buttonOK, ActSaveTranslation * act)\n: GuiPanelActSaveTranslation(parent), _act(act), _buttonOK(buttonOK)\n{\n\tstd::map const& languages = Resource::getInstance()->getLanguages();\t\n\t\n\t\/\/Ajout des langues.\n\tfor(auto &it: languages)\n\t{\n\t\t_choiceLanguageSource->Append(it.second);\n\t\t_choiceLanguageOfTranslation->Append(it.second);\n\t}\n\t\n\t\/\/Sélectionne les bonnes langues.\n\tint n = _choiceLanguageSource->FindString(languages.at(_act->_lgsrc));\n\t_choiceLanguageSource->SetSelection(n);\n\tn = _choiceLanguageOfTranslation->FindString(languages.at(_act->_lgto));\n\t_choiceLanguageOfTranslation->SetSelection(n);\n\t\n\t\/\/Sélectionne le bon fichier.\n\t_filePickerFile->SetFileName(_act->_fileName);\n\t\n\t\/\/Tout sauvegarder ?\n\tif(_act->_saveAll)\n\t\t_radioBtnSaveAllTranslations->SetValue(true);\n\telse\n\t\t_radioBtnSaveATranslation->SetValue(true);\n\t\t\n\t\/\/Pas de doublon\n\tif(_act->_noDoublon)\n\t\t_checkBoxNoDoublon->SetValue(true);\n\telse\n\t\t_checkBoxNoDoublon->SetValue(false);\n\t\t\n\t\/\/Dessiner un dialogue\n\tif(_act->_showDialog)\n\t\t_checkBoxShowDialog->SetValue(true);\n\telse\n\t\t_checkBoxShowDialog->SetValue(false);\n\t\t\n\t\t\n\t\/\/Lier l'événement du bouton OK du wxWindow parent.\n\t_buttonOK->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &PanelActSaveTranslation::OnOKButtonClick, this, _buttonOK->GetId());\n}\n\nPanelActSaveTranslation::~PanelActSaveTranslation()\n{\n\t_buttonOK->Unbind(wxEVT_COMMAND_BUTTON_CLICKED, &PanelActSaveTranslation::OnOKButtonClick, this, _buttonOK->GetId());\n}\n\nvoid PanelActSaveTranslation::OnOKButtonClick(wxCommandEvent& event)\n{\n\t\/\/Vérifie si il y a un fichier de sélectionner.\n\tif(_filePickerFile->GetFileName().GetFullName().IsEmpty())\n\t{\n\t\twxMessageBox(_(\"The name of file is empty.\"), _(\"Name file invalid\"), wxOK|wxICON_EXCLAMATION|wxCENTRE, this);\n\t\treturn;\n\t}\n\t\n\t\/\/Récupérer le nom du fichier.\n\twxFileName tmpFileName = _filePickerFile->GetFileName();\n\t\t\n\t\/\/Si fichier a été modifier ?\n\tif(_act->_fileName != tmpFileName)\n\t{\n\t\t\/\/Le fichier est déjà existent ?\n\t\tif(tmpFileName.Exists() && tmpFileName != _act->_fileName)\n\t\t{\n\t\t\t\/\/Si il existe, on demande si il faut remplacer le fichier.\n\t\t\twxString message = _(\"The file \\\"\") + tmpFileName.GetFullPath() + _(\"\\\" already exists.\\n\") + _(\"Do you want delete this file?\");\n\t\t\twxMessageDialog *dlg = new wxMessageDialog(this, message, _(\"Delete a file\"), wxYES_NO|wxICON_QUESTION|wxICON_EXCLAMATION|wxCENTRE);\n\t\t\tif(dlg->ShowModal() != wxID_YES)\n\t\t\t{\n\t\t\t\tdlg->Destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Suppression du fichier.\n\t\t\t\tif(!wxRemoveFile(_filePickerFile->GetPath()))\n\t\t\t\t{\n\t\t\t\t\twxLogError(_(\"Could not remove the file : \")+tmpFileName.GetFullPath());\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tdlg->Destroy();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/Affect le langage source.\n\tint n = _choiceLanguageSource->GetSelection();\n\twxString s = _choiceLanguageSource->GetString(n);\n\t_act->_lgsrc = Resource::getInstance()->languageToAbbreviation(s);\n\t\n\t\/\/Affect le langage de destination.\n\tn = _choiceLanguageOfTranslation->GetSelection();\n\ts = _choiceLanguageOfTranslation->GetString(n);\n\t_act->_lgto = Resource::getInstance()->languageToAbbreviation(s);\n\t\n\t\/\/Affect les autres arguments.\n\t_act->_fileName = tmpFileName;\n\t_act->_saveAll = _radioBtnSaveAllTranslations->GetValue();\n\t_act->_noDoublon = _checkBoxNoDoublon->IsChecked();\n\t_act->_showDialog = _checkBoxShowDialog->IsChecked();\n\t\t\n\t\/\/Propage l'événement.\n\tevent.Skip();\n}\n\n\/\/ *********************************************************************\n\/\/ Class ActSaveTranslationFile\n\/\/ *********************************************************************\nActSaveTranslationFile::ActSaveTranslationFile(wxFileName const& fileName)\n: _fileName(fileName), _isOk(true)\n{\n\t\/\/Si le fichier existe on le charge\n\tif(wxFile::Exists(fileName.GetFullPath()))\n\t{\n\t\t\/\/Ouverture du fichier\n\t\twxFileInputStream file(_fileName.GetFullPath());\n\t\t_isOk = file.IsOk();\n\t\t\n\t\t\/\/OK ?\n\t\tif(_isOk)\n\t\t{\t\n\t\t\t\/\/Le buffer pour stoker le tout contenue fichier\n\t\t\twxMemoryBuffer buffer;\n\t\t\t\/\/data temporaire.\n\t\t\tuint8_t tmpData[1024];\n\t\t\t\n\t\t\t\/\/Lie des données temps qu'il y en a.\n\t\t\twhile(file.CanRead() && !file.Eof())\n\t\t\t{\n\t\t\t\tfile.Read(tmpData, 1024);\n\t\t\t\tbuffer.AppendData(tmpData, file.LastRead());\n\t\t\t}\n\t\t\t\n\t\t\t\/\/Ajouter les données dans un wxString.\n\t\t\twxString stringFile;\n\t\t\tstringFile.Append((const char *)buffer.GetData(), buffer.GetDataLen());\n\t\t\t\n\t\t\t\/\/On récupère la première ligne et on sauvegarde le reste\n\t\t\twxString firstLine = stringFile.BeforeFirst('\\n', &_texts);\n\t\t\t\n\t\t\t\/\/On analyse la première ligne\n\t\t\twxString beforeComma;\n\t\t\tfor(size_t i = 0; i const& translations)\n{\n\t\/\/Caractère en minuscule.\n\ttext.MakeLower();\n\tmainTranslate.MakeLower();\n}\n\n\/\/ *********************************************************************\n\/\/ Class ActSaveTranslation\n\/\/ *********************************************************************\n\n\/\/! \\todo a compléter avec les local\nActSaveTranslation::ActSaveTranslation()\n: ActSaveTranslation(\t\"en\", \"fr\", wxFileName(wxGetUserHome(), \"\"),\n\t\t\t\t\t\ttrue, true, true)\n{\n}\n\nActSaveTranslation::ActSaveTranslation(wxString const& lgsrc,\n\t\t\t\t\t\t\twxString const& lgto,\n\t\t\t\t\t\t\twxFileName const& fileName,\n\t\t\t\t\t\t\tbool soveAll,\n\t\t\t\t\t\t\tbool noDoublon,\n\t\t\t\t\t\t\tbool showDialog)\n: Action(_(\"Save a translation\"), \"ActSaveTranslation\",\n_(\"Translation a word or a group words from google and save in a file.\")),\n_lgsrc(lgsrc), _lgto(lgto), _fileName(fileName),\n_saveAll(soveAll), _noDoublon(noDoublon), _showDialog(showDialog)\n{\n}\n\nActSaveTranslation::~ActSaveTranslation()\n{\n}\n\nvoid ActSaveTranslation::execute()\n{\n\t\/\/On récupère le contenue de la presse papier.\n\twxString clipboard = Resource::getClipboard();\n\t\n\t\/\/La presse papier est t'elle vide ?\n\tif(clipboard.IsEmpty())\n\t{\n\t\t\/\/Pas de texte à traduire\n\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"Sorry, nothing at save.\"));\n\t\treturn;\n\t}\n\n\t\/\/On récupère le texte traduit\n\tstd::map translations;\n\twxString mainTranslate = Resource::getTranslations(&translations, clipboard, _lgsrc, _lgto);\n\t\/\/On vérifie si une traduction existe.\n\tif(mainTranslate.IsEmpty())\n\t{\n\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"Sorry, nothing at save.\"));\n\t\treturn;\n\t}\n\t\n\t\/\/On vérifie la validités du fichier.\n\tif(_fileName.GetFullName().IsEmpty())\n\t{\n\t\twxMessageBox(_(\"The name of file is wrong.\"), _(\"Name file invalid.\"), wxOK|wxICON_EXCLAMATION|wxCENTRE);\n\t\treturn;\n\t}\n\t\n\t\/\/Fichier de sauvegarde\n\tActSaveTranslationFile file(_fileName);\n\t\n\t\/\/Vérifie si ok\n\tif(!file.isOk())\n\t\treturn;\n\t\n\t\/\/Si on dois vérifier l'existence du texte dans le fichier\n\tif(_noDoublon)\n\t{\n\t\tif(file.exist(clipboard))\n\t\t{\n\t\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"The text is already existing in \")+_fileName.GetFullPath());\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\t\/\/Sinon on le sauvegarde.\n\tif(_saveAll)\/\/Doit ton tout sauvegarder ?\n\t{\n\t\tfile.save(clipboard, mainTranslate, translations);\n\t}\n\telse\n\t{\n\t\tfile.save(clipboard, mainTranslate);\n\t}\n\t\n\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"The text has be saved.\"));\n}\n\nwxPanel* ActSaveTranslation::getPanelPreferences(wxWindow* parent, wxButton* buttonOK)\n{\n\treturn new PanelActSaveTranslation(parent, buttonOK, this);\n}\n\nvoid ActSaveTranslation::actLoad(wxFileConfig & fileConfig)\n{\t\n\t\/\/On récupère les langages.\n\tfileConfig.Read(\"lgsrc\", &_lgsrc);\n\tfileConfig.Read(\"lgto\", &_lgto);\n\t\n\t\/\/On récupère le fichier.\n\twxString file;\n\tfileConfig.Read(\"fileName\", &file);\n\t_fileName.Assign(file);\n\t\n\t\/\/On récupère le reste\n\tfileConfig.Read(\"saveAll\", &_saveAll);\t\t\n\tfileConfig.Read(\"noDoublon\", &_noDoublon);\n\tfileConfig.Read(\"showDialog\", &_showDialog);\n}\n\t\t\nvoid ActSaveTranslation::actSave(wxFileConfig & fileConfig)const\n{\t\n\t\/\/On sauvegarde les langages.\n\tfileConfig.Write(\"lgsrc\", _lgsrc);\n\tfileConfig.Write(\"lgto\", _lgto);\n\t\n\t\/\/On sauvegarde le fichier.\n\tfileConfig.Write(\"fileName\", _fileName.GetFullPath());\n\t\n\t\/\/On sauvegarde le reste\n\tfileConfig.Write(\"saveAll\", _saveAll);\t\t\n\tfileConfig.Write(\"noDoublon\", _noDoublon);\n\tfileConfig.Write(\"showDialog\", _showDialog);\n}\n\nwxString ActSaveTranslation::getStringPreferences()const\n{\n\treturn \tResource::getInstance()->abbreviationToLanguage(_lgsrc) +\n\t\t\t_(\" to \") +\n\t\t\tResource::getInstance()->abbreviationToLanguage(_lgto) +\n\t\t\t_(\" in \") + _fileName.GetFullPath();\n}\nfix bug in ActSaveTranslationFile::exist\/\/! \\file **************************************************************\n\/\/! \\brief Source Action de sauvegarde de traduction.\n\/\/! \n\/\/! - Compilateur : GCC,MinGW\n\/\/!\n\/\/! \\author Antoine Maleyrie\n\/\/! \\version 0.9\n\/\/! \\date 31.03.2013\n\/\/!\n\/\/! ********************************************************************\n\n\/*\n*\tCopyright © 2013 - Antoine Maleyrie.\n*\/\n\n#include \"action\/actSaveTranslation.hpp\"\n#include \"resource.hpp\"\n\n#include \n#include \n#include \n#include \n\n\n\/\/TEST\n#include \n\n\n\/\/ *********************************************************************\n\/\/ Class PanelActSaveTranslation\n\/\/ *********************************************************************\n\nPanelActSaveTranslation::PanelActSaveTranslation(wxWindow* parent, wxButton* buttonOK, ActSaveTranslation * act)\n: GuiPanelActSaveTranslation(parent), _act(act), _buttonOK(buttonOK)\n{\n\tstd::map const& languages = Resource::getInstance()->getLanguages();\t\n\t\n\t\/\/Ajout des langues.\n\tfor(auto &it: languages)\n\t{\n\t\t_choiceLanguageSource->Append(it.second);\n\t\t_choiceLanguageOfTranslation->Append(it.second);\n\t}\n\t\n\t\/\/Sélectionne les bonnes langues.\n\tint n = _choiceLanguageSource->FindString(languages.at(_act->_lgsrc));\n\t_choiceLanguageSource->SetSelection(n);\n\tn = _choiceLanguageOfTranslation->FindString(languages.at(_act->_lgto));\n\t_choiceLanguageOfTranslation->SetSelection(n);\n\t\n\t\/\/Sélectionne le bon fichier.\n\t_filePickerFile->SetFileName(_act->_fileName);\n\t\n\t\/\/Tout sauvegarder ?\n\tif(_act->_saveAll)\n\t\t_radioBtnSaveAllTranslations->SetValue(true);\n\telse\n\t\t_radioBtnSaveATranslation->SetValue(true);\n\t\t\n\t\/\/Pas de doublon\n\tif(_act->_noDoublon)\n\t\t_checkBoxNoDoublon->SetValue(true);\n\telse\n\t\t_checkBoxNoDoublon->SetValue(false);\n\t\t\n\t\/\/Dessiner un dialogue\n\tif(_act->_showDialog)\n\t\t_checkBoxShowDialog->SetValue(true);\n\telse\n\t\t_checkBoxShowDialog->SetValue(false);\n\t\t\n\t\t\n\t\/\/Lier l'événement du bouton OK du wxWindow parent.\n\t_buttonOK->Bind(wxEVT_COMMAND_BUTTON_CLICKED, &PanelActSaveTranslation::OnOKButtonClick, this, _buttonOK->GetId());\n}\n\nPanelActSaveTranslation::~PanelActSaveTranslation()\n{\n\t_buttonOK->Unbind(wxEVT_COMMAND_BUTTON_CLICKED, &PanelActSaveTranslation::OnOKButtonClick, this, _buttonOK->GetId());\n}\n\nvoid PanelActSaveTranslation::OnOKButtonClick(wxCommandEvent& event)\n{\n\t\/\/Vérifie si il y a un fichier de sélectionner.\n\tif(_filePickerFile->GetFileName().GetFullName().IsEmpty())\n\t{\n\t\twxMessageBox(_(\"The name of file is empty.\"), _(\"Name file invalid\"), wxOK|wxICON_EXCLAMATION|wxCENTRE, this);\n\t\treturn;\n\t}\n\t\n\t\/\/Récupérer le nom du fichier.\n\twxFileName tmpFileName = _filePickerFile->GetFileName();\n\t\t\n\t\/\/Si fichier a été modifier ?\n\tif(_act->_fileName != tmpFileName)\n\t{\n\t\t\/\/Le fichier est déjà existent ?\n\t\tif(tmpFileName.Exists() && tmpFileName != _act->_fileName)\n\t\t{\n\t\t\t\/\/Si il existe, on demande si il faut remplacer le fichier.\n\t\t\twxString message = _(\"The file \\\"\") + tmpFileName.GetFullPath() + _(\"\\\" already exists.\\n\") + _(\"Do you want delete this file?\");\n\t\t\twxMessageDialog *dlg = new wxMessageDialog(this, message, _(\"Delete a file\"), wxYES_NO|wxICON_QUESTION|wxICON_EXCLAMATION|wxCENTRE);\n\t\t\tif(dlg->ShowModal() != wxID_YES)\n\t\t\t{\n\t\t\t\tdlg->Destroy();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/Suppression du fichier.\n\t\t\t\tif(!wxRemoveFile(_filePickerFile->GetPath()))\n\t\t\t\t{\n\t\t\t\t\twxLogError(_(\"Could not remove the file : \")+tmpFileName.GetFullPath());\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tdlg->Destroy();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\/\/Affect le langage source.\n\tint n = _choiceLanguageSource->GetSelection();\n\twxString s = _choiceLanguageSource->GetString(n);\n\t_act->_lgsrc = Resource::getInstance()->languageToAbbreviation(s);\n\t\n\t\/\/Affect le langage de destination.\n\tn = _choiceLanguageOfTranslation->GetSelection();\n\ts = _choiceLanguageOfTranslation->GetString(n);\n\t_act->_lgto = Resource::getInstance()->languageToAbbreviation(s);\n\t\n\t\/\/Affect les autres arguments.\n\t_act->_fileName = tmpFileName;\n\t_act->_saveAll = _radioBtnSaveAllTranslations->GetValue();\n\t_act->_noDoublon = _checkBoxNoDoublon->IsChecked();\n\t_act->_showDialog = _checkBoxShowDialog->IsChecked();\n\t\t\n\t\/\/Propage l'événement.\n\tevent.Skip();\n}\n\n\/\/ *********************************************************************\n\/\/ Class ActSaveTranslationFile\n\/\/ *********************************************************************\nActSaveTranslationFile::ActSaveTranslationFile(wxFileName const& fileName)\n: _fileName(fileName), _isOk(true)\n{\n\t\/\/Si le fichier existe on le charge\n\tif(wxFile::Exists(fileName.GetFullPath()))\n\t{\n\t\t\/\/Ouverture du fichier\n\t\twxFileInputStream file(_fileName.GetFullPath());\n\t\t_isOk = file.IsOk();\n\t\t\n\t\t\/\/OK ?\n\t\tif(_isOk)\n\t\t{\t\n\t\t\t\/\/Le buffer pour stoker le tout contenue fichier\n\t\t\twxMemoryBuffer buffer;\n\t\t\t\/\/data temporaire.\n\t\t\tuint8_t tmpData[1024];\n\t\t\t\n\t\t\t\/\/Lie des données temps qu'il y en a.\n\t\t\twhile(file.CanRead() && !file.Eof())\n\t\t\t{\n\t\t\t\tfile.Read(tmpData, 1024);\n\t\t\t\tbuffer.AppendData(tmpData, file.LastRead());\n\t\t\t}\n\t\t\t\n\t\t\t\/\/Ajouter les données dans un wxString.\n\t\t\twxString stringFile;\n\t\t\tstringFile.Append((const char *)buffer.GetData(), buffer.GetDataLen());\n\t\t\t\n\t\t\t\/\/On récupère la première ligne et on sauvegarde le reste\n\t\t\twxString firstLine = stringFile.BeforeFirst('\\n', &_texts);\n\t\t\t\n\t\t\t\/\/On analyse la première ligne\n\t\t\twxString beforeComma;\n\t\t\tfor(size_t i = 0; i const& translations)\n{\n\t\/\/Caractère en minuscule.\n\ttext.MakeLower();\n\tmainTranslate.MakeLower();\n}\n\n\/\/ *********************************************************************\n\/\/ Class ActSaveTranslation\n\/\/ *********************************************************************\n\n\/\/! \\todo a compléter avec les local\nActSaveTranslation::ActSaveTranslation()\n: ActSaveTranslation(\t\"en\", \"fr\", wxFileName(wxGetUserHome(), \"\"),\n\t\t\t\t\t\ttrue, true, true)\n{\n}\n\nActSaveTranslation::ActSaveTranslation(wxString const& lgsrc,\n\t\t\t\t\t\t\twxString const& lgto,\n\t\t\t\t\t\t\twxFileName const& fileName,\n\t\t\t\t\t\t\tbool soveAll,\n\t\t\t\t\t\t\tbool noDoublon,\n\t\t\t\t\t\t\tbool showDialog)\n: Action(_(\"Save a translation\"), \"ActSaveTranslation\",\n_(\"Translation a word or a group words from google and save in a file.\")),\n_lgsrc(lgsrc), _lgto(lgto), _fileName(fileName),\n_saveAll(soveAll), _noDoublon(noDoublon), _showDialog(showDialog)\n{\n}\n\nActSaveTranslation::~ActSaveTranslation()\n{\n}\n\nvoid ActSaveTranslation::execute()\n{\n\t\/\/On récupère le contenue de la presse papier.\n\twxString clipboard = Resource::getClipboard();\n\t\n\t\/\/La presse papier est t'elle vide ?\n\tif(clipboard.IsEmpty())\n\t{\n\t\t\/\/Pas de texte à traduire\n\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"Sorry, nothing at save.\"));\n\t\treturn;\n\t}\n\n\t\/\/On récupère le texte traduit\n\tstd::map translations;\n\twxString mainTranslate = Resource::getTranslations(&translations, clipboard, _lgsrc, _lgto);\n\t\/\/On vérifie si une traduction existe.\n\tif(mainTranslate.IsEmpty())\n\t{\n\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"Sorry, nothing at save.\"));\n\t\treturn;\n\t}\n\t\n\t\/\/On vérifie la validités du fichier.\n\tif(_fileName.GetFullName().IsEmpty())\n\t{\n\t\twxMessageBox(_(\"The name of file is wrong.\"), _(\"Name file invalid.\"), wxOK|wxICON_EXCLAMATION|wxCENTRE);\n\t\treturn;\n\t}\n\t\n\t\/\/Fichier de sauvegarde\n\tActSaveTranslationFile file(_fileName);\n\t\n\t\/\/Vérifie si ok\n\tif(!file.isOk())\n\t\treturn;\n\t\n\t\/\/Si on dois vérifier l'existence du texte dans le fichier\n\tif(_noDoublon)\n\t{\n\t\tif(file.exist(clipboard))\n\t\t{\n\t\t\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"The text is already existing in \")+_fileName.GetFullPath());\n\t\t\treturn;\n\t\t}\n\t}\n\t\n\t\/\/Sinon on le sauvegarde.\n\tif(_saveAll)\/\/Doit ton tout sauvegarder ?\n\t{\n\t\tfile.save(clipboard, mainTranslate, translations);\n\t}\n\telse\n\t{\n\t\tfile.save(clipboard, mainTranslate);\n\t}\n\t\n\tNotification::getInstance()->notify(_(\"Save clipboard translation\"), _(\"The text has be saved.\"));\n}\n\nwxPanel* ActSaveTranslation::getPanelPreferences(wxWindow* parent, wxButton* buttonOK)\n{\n\treturn new PanelActSaveTranslation(parent, buttonOK, this);\n}\n\nvoid ActSaveTranslation::actLoad(wxFileConfig & fileConfig)\n{\t\n\t\/\/On récupère les langages.\n\tfileConfig.Read(\"lgsrc\", &_lgsrc);\n\tfileConfig.Read(\"lgto\", &_lgto);\n\t\n\t\/\/On récupère le fichier.\n\twxString file;\n\tfileConfig.Read(\"fileName\", &file);\n\t_fileName.Assign(file);\n\t\n\t\/\/On récupère le reste\n\tfileConfig.Read(\"saveAll\", &_saveAll);\t\t\n\tfileConfig.Read(\"noDoublon\", &_noDoublon);\n\tfileConfig.Read(\"showDialog\", &_showDialog);\n}\n\t\t\nvoid ActSaveTranslation::actSave(wxFileConfig & fileConfig)const\n{\t\n\t\/\/On sauvegarde les langages.\n\tfileConfig.Write(\"lgsrc\", _lgsrc);\n\tfileConfig.Write(\"lgto\", _lgto);\n\t\n\t\/\/On sauvegarde le fichier.\n\tfileConfig.Write(\"fileName\", _fileName.GetFullPath());\n\t\n\t\/\/On sauvegarde le reste\n\tfileConfig.Write(\"saveAll\", _saveAll);\t\t\n\tfileConfig.Write(\"noDoublon\", _noDoublon);\n\tfileConfig.Write(\"showDialog\", _showDialog);\n}\n\nwxString ActSaveTranslation::getStringPreferences()const\n{\n\treturn \tResource::getInstance()->abbreviationToLanguage(_lgsrc) +\n\t\t\t_(\" to \") +\n\t\t\tResource::getInstance()->abbreviationToLanguage(_lgto) +\n\t\t\t_(\" in \") + _fileName.GetFullPath();\n}\n<|endoftext|>"} {"text":"\/*\n * AudioSubsystem.cpp\n *\n * Created on: 5 maj 2014\n * Author: Lech Kulina\n * E-Mail: kulinalech@gmail.com\n *\/\n\n#include \n#include \n#include \n\nCosmic::Core::AudioSubsystem::AudioSubsystem() :\n logger(\n boost::log::keywords::severity = Common::Severity::Trace,\n boost::log::keywords::channel = Common::Channel::Subsystem),\n initialized(false) {\n BOOST_LOG_FUNCTION();\n\n \/\/initialize SDL mixer library with OGG\/Vorbis support\n BOOST_LOG(logger) << \"Initializing SDL_mixer library with OGG\/Vorbis support.\";\n const int requestedFlags = MIX_INIT_OGG;\n const int acquiredFlags = Mix_Init(requestedFlags);\n if ((acquiredFlags & requestedFlags) != requestedFlags) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to initialize SDL_mixer with OGG\/Vorbis support. \" << Mix_GetError();\n Mix_Quit();\n return;\n }\n\n \/\/retrieve version of SDL mixer library that we are currently linked against\n memcpy(&version, Mix_Linked_Version(), sizeof(SDL_version));\n BOOST_LOG_SEV(logger, Common::Severity::Debug)\n << \"SDL_mixer \" << int(version.major) << \".\" << int(version.minor) << \".\" << int(version.patch) << \" initialized with OGG\/Vorbis support.\";\n\n \/\/open audio device with default settings (for now at least...)\n BOOST_LOG(logger) << \"Opening audio device.\";\n if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096) != 0) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to open audio device. \" << Mix_GetError();\n Mix_Quit();\n return;\n }\n\n \/\/query the actual format that is in use by the opened audio device\n if (Mix_QuerySpec(&frequency, &format, &channels) == 0) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to query audio format that is in use by the current audio device. \" << Mix_GetError();\n Mix_CloseAudio();\n Mix_Quit();\n return;\n }\n BOOST_LOG_SEV(logger, Common::Severity::Debug)\n << \"Audio device with frequency \" << frequency << \", format \" << format << \" and number of channels \" << channels << \" opened.\";\n\n initialized = true;\n}\n\nCosmic::Core::AudioSubsystem::~AudioSubsystem() {\n BOOST_LOG_FUNCTION();\n\n \/\/check if we are initialized\n if (!isInitialized()) {\n BOOST_LOG_SEV(logger, Common::Severity::Debug) << \"SDL_mixer library was not initialized.\";\n return;\n }\n\n \/\/close audio device\n BOOST_LOG(logger) << \"Closing audio device.\";\n Mix_CloseAudio();\n\n \/\/clean up SDL_mixer library stuff\n BOOST_LOG(logger) << \"Cleaning up SDL_mixer library.\";\n Mix_Quit();\n}\n\nbool Cosmic::Core::AudioSubsystem::isInitialized() const {\n return initialized;\n}\nGet chunk decoders info\/*\n * AudioSubsystem.cpp\n *\n * Created on: 5 maj 2014\n * Author: Lech Kulina\n * E-Mail: kulinalech@gmail.com\n *\/\n\n#include \n#include \n#include \n\nCosmic::Core::AudioSubsystem::AudioSubsystem() :\n logger(\n boost::log::keywords::severity = Common::Severity::Trace,\n boost::log::keywords::channel = Common::Channel::Subsystem),\n initialized(false) {\n BOOST_LOG_FUNCTION();\n\n \/\/initialize SDL mixer library with OGG\/Vorbis support\n BOOST_LOG(logger) << \"Initializing SDL_mixer library with OGG\/Vorbis support.\";\n const int requestedFlags = MIX_INIT_OGG;\n const int acquiredFlags = Mix_Init(requestedFlags);\n if ((acquiredFlags & requestedFlags) != requestedFlags) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to initialize SDL_mixer with OGG\/Vorbis support. \" << Mix_GetError();\n Mix_Quit();\n return;\n }\n\n \/\/retrieve version of SDL mixer library that we are currently linked against\n memcpy(&version, Mix_Linked_Version(), sizeof(SDL_version));\n BOOST_LOG_SEV(logger, Common::Severity::Debug)\n << \"SDL_mixer \" << int(version.major) << \".\" << int(version.minor) << \".\" << int(version.patch) << \" initialized with OGG\/Vorbis support.\";\n\n \/\/open audio device with default settings (for now at least...)\n BOOST_LOG(logger) << \"Opening audio device.\";\n if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, 2, 4096) != 0) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to open audio device. \" << Mix_GetError();\n Mix_Quit();\n return;\n }\n\n \/\/get the chunk decoders info\n const int chunkDecoders = Mix_GetNumChunkDecoders();\n BOOST_LOG(logger) << \"There are \" << chunkDecoders << \" chunk decoders available.\";\n for (int i=0; i < chunkDecoders; ++i) {\n BOOST_LOG_SEV(logger, Common::Severity::Debug)\n << \"Found \" << Mix_GetChunkDecoder(i) << \" chunk decoder.\";\n }\n\n \/\/query the actual format that is in use by the opened audio device\n if (Mix_QuerySpec(&frequency, &format, &channels) == 0) {\n BOOST_LOG_SEV(logger, Common::Severity::Critical)\n << \"Failed to query audio format that is in use by the current audio device. \" << Mix_GetError();\n Mix_CloseAudio();\n Mix_Quit();\n return;\n }\n BOOST_LOG_SEV(logger, Common::Severity::Debug)\n << \"Audio device with frequency \" << frequency << \", format \" << format << \" and number of channels \" << channels << \" opened.\";\n\n initialized = true;\n}\n\nCosmic::Core::AudioSubsystem::~AudioSubsystem() {\n BOOST_LOG_FUNCTION();\n\n \/\/check if we are initialized\n if (!isInitialized()) {\n BOOST_LOG_SEV(logger, Common::Severity::Debug) << \"SDL_mixer library was not initialized.\";\n return;\n }\n\n \/\/close audio device\n BOOST_LOG(logger) << \"Closing audio device.\";\n Mix_CloseAudio();\n\n \/\/clean up SDL_mixer library stuff\n BOOST_LOG(logger) << \"Cleaning up SDL_mixer library.\";\n Mix_Quit();\n}\n\nbool Cosmic::Core::AudioSubsystem::isInitialized() const {\n return initialized;\n}\n<|endoftext|>"} {"text":"Additional tests<|endoftext|>"} {"text":"#ifndef STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP\n#ifdef STAN_OPENCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\ninline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block);\nnamespace internal {\ninline matrix_gpu cholesky_decompose_recursion(matrix_gpu& A,\n const int min_block) {\n matrix_gpu L(A.rows(), A.cols());\n if (A.rows() <= min_block || A.rows() < 100) {\n try {\n opencl_kernels::cholesky_decompose(cl::NDRange(A.rows()),\n cl::NDRange(A.rows()), A.buffer(),\n L.buffer(), A.rows());\n } catch (const cl::Error& e) {\n check_opencl_error(\"cholesky_decompose\", e);\n }\n } else {\n L = stan::math::cholesky_decompose(A, min_block);\n }\n return L;\n}\n} \/\/ namespace internal\n\/**\n * Return the lower-triangular Cholesky factor (i.e., matrix\n * square root) of the specified square, symmetric matrix.\n * The return value \\f$L\\f$ will be a lower-traingular matrix such that the\n * original matrix \\f$A\\f$ is given by\n *

\\f$A = L \\times L^T\\f$.\n * The Cholesky decomposition is computed on the GPU. This algorithm is\n * recursive. The matrix is subset into a matrix of size\n * A.rows() \/ 2<\/code>, and if the block<\/code> size is less than\n * 100 then the cholesky decomposition on the GPU is computed\n * using that submatrix. If block<\/code> is greater than\n * 100 or min_block<\/code> then cholesky_decompose<\/code> is run again\n * with block<\/code> equal to A.rows() \/ 2<\/code>. Once the\n * Cholesky Decomposition is computed, the full matrix cholesky is created\n * by propogating the cholesky forward as given in the reference report below.\n *\n * For a full guide to how this works\n * see the Cholesy decompostion chapter in the reference report\n * here<\/a>.\n * @param A Symmetric matrix on the GPU.\n * @param min_block The minimum block size to execute the cholesky on.\n * @return Square root of matrix on the GPU.\n * @throw std::domain_error if m is not\n * positive definite (if m has more than 0 elements)\n *\/\ninline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block) {\n auto offset = 0;\n auto block = floor(A.rows() \/ 2);\n \/\/ NOTE: The code in this section follows the naming conventions\n \/\/ in the report linked in the docs.\n matrix_gpu A_11(block, block);\n \/\/ Repeats the blocked cholesky decomposition until the size of the remaining\n \/\/ submatrix is smaller or equal to the block size\n if ((offset + block) < (A.rows())) {\n auto block_subset = A.rows() - offset - block;\n matrix_gpu A_21(block_subset, block);\n matrix_gpu A_22(block_subset, block_subset);\n \/\/ Copies a block of the input A into A_11\n A_11.sub_block(A, offset, offset, 0, 0, block, block);\n \/\/ The following function either calls the\n \/\/ blocked cholesky recursively for the submatrix A_11\n \/\/ or calls the kernel directly if the size of the block is small enough\n matrix_gpu L_11\n = stan::math::internal::cholesky_decompose_recursion(A_11, min_block);\n \/\/ Copies L_11 back to the input matrix\n A.sub_block(L_11, 0, 0, offset, offset, block, block);\n \/\/ Copies a block of the input A into A_21\n auto block_offset = offset + block;\n A_21.sub_block(A, block_offset, offset, 0, 0, block_subset, block);\n \/\/ computes A_21*((L_11^-1)^T)\n \/\/ and copies the resulting submatrix to the input matrix\n matrix_gpu L_21 = A_21 * transpose(lower_triangular_inverse(L_11));\n A.sub_block(L_21, 0, 0, block_offset, offset, block_subset, block);\n A_22.sub_block(A, block_offset, block_offset, 0, 0, block_subset,\n block_subset);\n \/\/ computes A_22 - L_21*(L_21^T)\n matrix_gpu L_22 = A_22 - multiply_transpose(L_21);\n A.sub_block(L_22, 0, 0, block_offset, block_offset, block_subset,\n block_subset);\n offset += block;\n }\n \/\/ Computes the Cholesky factor for the remaining submatrix\n const auto remaining_rows = A.rows() - offset;\n if (remaining_rows > 0) {\n matrix_gpu A_11(remaining_rows, remaining_rows);\n A_11.sub_block(A, offset, offset, 0, 0, remaining_rows, remaining_rows);\n \/\/ calculate the cholesky factor for the remaining part of the matrix\n matrix_gpu L_11\n = stan::math::internal::cholesky_decompose_recursion(A_11, min_block);\n A.sub_block(L_11, 0, 0, offset, offset, remaining_rows, remaining_rows);\n }\n check_nan(\"cholesky_decompose_gpu\", \"Matrix m\", A);\n check_diagonal_zeros(\"cholesky_decompose_gpu\", \"Matrix m\", A);\n A.zeros();\n return A;\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags\/RELEASE_500\/final)#ifndef STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP\n#define STAN_MATH_GPU_CHOLESKY_DECOMPOSE_HPP\n#ifdef STAN_OPENCL\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\ninline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block);\nnamespace internal {\ninline matrix_gpu cholesky_decompose_recursion(matrix_gpu& A,\n const int min_block) {\n matrix_gpu L(A.rows(), A.cols());\n if (A.rows() <= min_block || A.rows() < 100) {\n try {\n opencl_kernels::cholesky_decompose(cl::NDRange(A.rows()),\n cl::NDRange(A.rows()), A.buffer(),\n L.buffer(), A.rows());\n } catch (const cl::Error& e) {\n check_opencl_error(\"cholesky_decompose\", e);\n }\n } else {\n L = stan::math::cholesky_decompose(A, min_block);\n }\n return L;\n}\n} \/\/ namespace internal\n\/**\n * Return the lower-triangular Cholesky factor (i.e., matrix\n * square root) of the specified square, symmetric matrix.\n * The return value \\f$L\\f$ will be a lower-traingular matrix such that the\n * original matrix \\f$A\\f$ is given by\n *

\\f$A = L \\times L^T\\f$.\n * The Cholesky decomposition is computed on the GPU. This algorithm is\n * recursive. The matrix is subset into a matrix of size\n * A.rows() \/ 2<\/code>, and if the block<\/code> size is less than\n * 100 then the cholesky decomposition on the GPU is computed\n * using that submatrix. If block<\/code> is greater than\n * 100 or min_block<\/code> then cholesky_decompose<\/code> is run\n * again with block<\/code> equal to A.rows() \/ 2<\/code>. Once the\n * Cholesky Decomposition is computed, the full matrix cholesky is created\n * by propogating the cholesky forward as given in the reference report below.\n *\n * For a full guide to how this works\n * see the Cholesy decompostion chapter in the reference report\n * here<\/a>.\n * @param A Symmetric matrix on the GPU.\n * @param min_block The minimum block size to execute the cholesky on.\n * @return Square root of matrix on the GPU.\n * @throw std::domain_error if m is not\n * positive definite (if m has more than 0 elements)\n *\/\ninline matrix_gpu cholesky_decompose(matrix_gpu& A, const int min_block) {\n auto offset = 0;\n auto block = floor(A.rows() \/ 2);\n \/\/ NOTE: The code in this section follows the naming conventions\n \/\/ in the report linked in the docs.\n matrix_gpu A_11(block, block);\n \/\/ Repeats the blocked cholesky decomposition until the size of the remaining\n \/\/ submatrix is smaller or equal to the block size\n if ((offset + block) < (A.rows())) {\n auto block_subset = A.rows() - offset - block;\n matrix_gpu A_21(block_subset, block);\n matrix_gpu A_22(block_subset, block_subset);\n \/\/ Copies a block of the input A into A_11\n A_11.sub_block(A, offset, offset, 0, 0, block, block);\n \/\/ The following function either calls the\n \/\/ blocked cholesky recursively for the submatrix A_11\n \/\/ or calls the kernel directly if the size of the block is small enough\n matrix_gpu L_11\n = stan::math::internal::cholesky_decompose_recursion(A_11, min_block);\n \/\/ Copies L_11 back to the input matrix\n A.sub_block(L_11, 0, 0, offset, offset, block, block);\n \/\/ Copies a block of the input A into A_21\n auto block_offset = offset + block;\n A_21.sub_block(A, block_offset, offset, 0, 0, block_subset, block);\n \/\/ computes A_21*((L_11^-1)^T)\n \/\/ and copies the resulting submatrix to the input matrix\n matrix_gpu L_21 = A_21 * transpose(lower_triangular_inverse(L_11));\n A.sub_block(L_21, 0, 0, block_offset, offset, block_subset, block);\n A_22.sub_block(A, block_offset, block_offset, 0, 0, block_subset,\n block_subset);\n \/\/ computes A_22 - L_21*(L_21^T)\n matrix_gpu L_22 = A_22 - multiply_transpose(L_21);\n A.sub_block(L_22, 0, 0, block_offset, block_offset, block_subset,\n block_subset);\n offset += block;\n }\n \/\/ Computes the Cholesky factor for the remaining submatrix\n const auto remaining_rows = A.rows() - offset;\n if (remaining_rows > 0) {\n matrix_gpu A_11(remaining_rows, remaining_rows);\n A_11.sub_block(A, offset, offset, 0, 0, remaining_rows, remaining_rows);\n \/\/ calculate the cholesky factor for the remaining part of the matrix\n matrix_gpu L_11\n = stan::math::internal::cholesky_decompose_recursion(A_11, min_block);\n A.sub_block(L_11, 0, 0, offset, offset, remaining_rows, remaining_rows);\n }\n check_nan(\"cholesky_decompose_gpu\", \"Matrix m\", A);\n check_diagonal_zeros(\"cholesky_decompose_gpu\", \"Matrix m\", A);\n A.zeros();\n return A;\n}\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#include \"platform\/context.hpp\"\n#include \"amdocl\/cl_gl_amd.hpp\"\n#include \"amdocl\/cl_common.hpp\"\n#include \"platform\/commandqueue.hpp\"\n\n#include \n#include \n\n#ifdef _WIN32\n#include \n#include \n#include \"CL\/cl_d3d10.h\"\n#include \"CL\/cl_d3d11.h\"\n#include \"CL\/cl_dx9_media_sharing.h\"\n#endif \/\/_WIN32\n\nnamespace amd {\n\nContext::Context(const std::vector& devices, const Info& info)\n : devices_(devices),\n info_(info),\n properties_(NULL),\n glenv_(NULL),\n customHostAllocDevice_(NULL) {\n for (const auto& device : devices) {\n device->retain();\n if (customHostAllocDevice_ == NULL && device->customHostAllocator()) {\n customHostAllocDevice_ = device;\n }\n if (device->svmSupport()) {\n svmAllocDevice_.push_back(device);\n }\n }\n if (svmAllocDevice_.size() > 1) {\n \/\/ make sure the CPU is the last device to do allocation.\n if ((svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU)) {\n std::swap(svmAllocDevice_.front(), svmAllocDevice_.back());\n }\n\n uint isFirstDeviceFGSEnabled = svmAllocDevice_.front()->isFineGrainedSystem(true);\n for (auto& dev : svmAllocDevice_) {\n \/\/ allocation on fine - grained system incapable device first\n if (isFirstDeviceFGSEnabled && (dev->type() == CL_DEVICE_TYPE_GPU) &&\n (!(dev->isFineGrainedSystem(true)))) {\n std::swap(svmAllocDevice_.front(), dev);\n break;\n }\n }\n }\n}\n\nContext::~Context() {\n static const bool VALIDATE_ONLY = false;\n\n \/\/ Dissociate OCL context with any external device\n if (info_.flags_ & (GLDeviceKhr | D3D10DeviceKhr | D3D11DeviceKhr)) {\n std::vector::const_iterator it;\n \/\/ Loop through all devices\n for (it = devices_.begin(); it != devices_.end(); it++) {\n (*it)->unbindExternalDevice(info_.flags_, info_.hDev_, info_.hCtx_, VALIDATE_ONLY);\n }\n }\n\n if (properties_ != NULL) {\n delete[] properties_;\n }\n if (glenv_ != NULL) {\n delete glenv_;\n glenv_ = NULL;\n }\n\n std::for_each(devices_.begin(), devices_.end(), std::mem_fun(&Device::release));\n}\n\nint Context::checkProperties(const cl_context_properties* properties, Context::Info* info) {\n cl_platform_id pfmId = 0;\n uint count = 0;\n\n const struct Element {\n intptr_t name;\n void* ptr;\n }* p = reinterpret_cast(properties);\n\n \/\/ Clear the context infor structure\n ::memset(info, 0, sizeof(Context::Info));\n\n if (properties == NULL) {\n return CL_SUCCESS;\n }\n\n \/\/ Process all properties\n while (p->name != 0) {\n switch (p->name) {\n case CL_CONTEXT_INTEROP_USER_SYNC:\n if (p->ptr == reinterpret_cast(CL_TRUE)) {\n info->flags_ |= InteropUserSync;\n }\n break;\n#ifdef _WIN32\n case CL_CONTEXT_D3D10_DEVICE_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D10DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D10DeviceKhr;\n break;\n case CL_CONTEXT_D3D11_DEVICE_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D11DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D11DeviceKhr;\n break;\n case CL_CONTEXT_ADAPTER_D3D9_KHR:\n if (p->ptr == NULL) { \/\/ not supported for xp\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceKhr;\n break;\n case CL_CONTEXT_ADAPTER_D3D9EX_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceEXKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceEXKhr;\n break;\n case CL_CONTEXT_ADAPTER_DXVA_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceVAKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceVAKhr;\n break;\n#endif \/\/_WIN32\n\n case CL_EGL_DISPLAY_KHR:\n info->flags_ |= EGLDeviceKhr;\n\n#ifdef _WIN32\n case CL_WGL_HDC_KHR:\n#endif \/\/_WIN32\n\n#if defined(__linux__)\n case CL_GLX_DISPLAY_KHR:\n#endif \/\/ linux\n info->hDev_[GLDeviceKhrIdx] = p->ptr;\n\n#if defined(__APPLE__) || defined(__MACOSX)\n case CL_CGL_SHAREGROUP_KHR:\n Unimplemented();\n break;\n#endif \/\/__APPLE__ || MACOS\n\n case CL_GL_CONTEXT_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n }\n if (p->name == CL_GL_CONTEXT_KHR) {\n info->hCtx_ = p->ptr;\n }\n info->flags_ |= GLDeviceKhr;\n break;\n case CL_CONTEXT_PLATFORM:\n pfmId = reinterpret_cast(p->ptr);\n if ((NULL != pfmId) && (AMD_PLATFORM != pfmId)) {\n return CL_INVALID_VALUE;\n }\n break;\n case CL_CONTEXT_OFFLINE_DEVICES_AMD:\n if (p->ptr != reinterpret_cast(1)) {\n return CL_INVALID_VALUE;\n }\n \/\/ Set the offline device flag\n info->flags_ |= OfflineDevices;\n break;\n case CL_CONTEXT_COMMAND_INTERCEPT_CALLBACK_AMD:\n \/\/ Set the command intercept flag\n info->commandIntercept_ = (cl_int(CL_CALLBACK*)(cl_event, cl_int*))p->ptr;\n info->flags_ |= CommandIntercept;\n break;\n default:\n return CL_INVALID_VALUE;\n }\n p++;\n count++;\n }\n\n info->propertiesSize_ = count * sizeof(Element) + sizeof(intptr_t);\n return CL_SUCCESS;\n}\n\nint Context::create(const intptr_t* properties) {\n static const bool VALIDATE_ONLY = false;\n int result = CL_SUCCESS;\n\n if (properties != NULL) {\n properties_ = new cl_context_properties[info().propertiesSize_ \/ sizeof(cl_context_properties)];\n if (properties_ == NULL) {\n return CL_OUT_OF_HOST_MEMORY;\n }\n\n ::memcpy(properties_, properties, info().propertiesSize_);\n }\n\n \/\/ Check if OCL context can be associated with any external device\n if (info_.flags_ & (D3D10DeviceKhr | D3D11DeviceKhr | GLDeviceKhr | D3D9DeviceKhr |\n D3D9DeviceEXKhr | D3D9DeviceVAKhr)) {\n std::vector::const_iterator it;\n \/\/ Loop through all devices\n for (it = devices_.begin(); it != devices_.end(); it++) {\n if (!(*it)->bindExternalDevice(info_.flags_, info_.hDev_, info_.hCtx_, VALIDATE_ONLY)) {\n result = CL_INVALID_VALUE;\n }\n }\n }\n\n \/\/ Check if the device binding wasn't successful\n if (result != CL_SUCCESS) {\n if (info_.flags_ & GLDeviceKhr) {\n result = CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n } else if (info_.flags_ & D3D10DeviceKhr) {\n \/\/ return CL_INVALID_VALUE; \/\/ FIXME_odintsov: CL_INVALID_D3D_INTEROP;\n } else if (info_.flags_ & D3D11DeviceKhr) {\n \/\/ return CL_INVALID_VALUE; \/\/ FIXME_odintsov: CL_INVALID_D3D_INTEROP;\n } else if (info_.flags_ & (D3D9DeviceKhr | D3D9DeviceEXKhr | D3D9DeviceVAKhr)) {\n \/\/ return CL_INVALID_DX9_MEDIA_ADAPTER_KHR;\n }\n } else {\n if (info_.flags_ & GLDeviceKhr) {\n \/\/ Init context for GL interop\n if (glenv_ == NULL) {\n HMODULE h = (HMODULE)Os::loadLibrary(\n#ifdef _WIN32\n \"OpenGL32.dll\"\n#else \/\/!_WIN32\n \"libGL.so.1\"\n#endif \/\/!_WIN32\n );\n\n if (h && (glenv_ = new GLFunctions(h, (info_.flags_ & Flags::EGLDeviceKhr) != 0))) {\n if (!glenv_->init(reinterpret_cast(info_.hDev_[GLDeviceKhrIdx]),\n reinterpret_cast(info_.hCtx_))) {\n delete glenv_;\n glenv_ = NULL;\n result = CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n }\n }\n }\n }\n }\n\n return result;\n}\n\nvoid* Context::hostAlloc(size_t size, size_t alignment, bool atomics) const {\n if (customHostAllocDevice_ != NULL) {\n return customHostAllocDevice_->hostAlloc(size, alignment, atomics);\n }\n return AlignedMemory::allocate(size, alignment);\n}\n\nvoid Context::hostFree(void* ptr) const {\n if (customHostAllocDevice_ != NULL) {\n customHostAllocDevice_->hostFree(ptr);\n return;\n }\n AlignedMemory::deallocate(ptr);\n}\n\nvoid* Context::svmAlloc(size_t size, size_t alignment, cl_svm_mem_flags flags) {\n unsigned int numSVMDev = svmAllocDevice_.size();\n if (numSVMDev < 1) {\n return NULL;\n }\n\n if (svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU) {\n return AlignedMemory::allocate(size, alignment);\n } else {\n void* svmPtrAlloced = NULL;\n void* tempPtr = NULL;\n\n for (const auto& dev : svmAllocDevice_) {\n if (dev->type() == CL_DEVICE_TYPE_GPU) {\n \/\/ check if the device support svm platform atomics,\n \/\/ skipped allocation for platform atomics if not supported by this device\n if ((flags & CL_MEM_SVM_ATOMICS) &&\n !(dev->info().svmCapabilities_ & CL_DEVICE_SVM_ATOMICS)) {\n continue;\n }\n svmPtrAlloced = dev->svmAlloc(*this, size, alignment, flags, svmPtrAlloced);\n if (svmPtrAlloced == NULL) {\n return NULL;\n }\n }\n }\n return svmPtrAlloced;\n }\n}\n\nvoid Context::svmFree(void* ptr) const {\n if (svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU) {\n AlignedMemory::deallocate(ptr);\n return;\n }\n\n for (const auto& dev : svmAllocDevice_) {\n if (dev->type() == CL_DEVICE_TYPE_GPU) {\n dev->svmFree(ptr);\n }\n }\n return;\n}\n\nbool Context::containsDevice(const Device* device) const {\n std::vector::const_iterator it;\n\n for (it = devices_.begin(); it != devices_.end(); ++it) {\n if (device == *it || (*it)->isAncestor(device)) {\n return true;\n }\n }\n return false;\n}\n\nDeviceQueue* Context::defDeviceQueue(const Device& dev) const {\n std::map::const_iterator it = deviceQueues_.find(&dev);\n if (it != deviceQueues_.end()) {\n return it->second.defDeviceQueue_;\n } else {\n return NULL;\n }\n}\n\nbool Context::isDevQueuePossible(const Device& dev) {\n return (deviceQueues_[&dev].deviceQueueCnt_ < dev.info().maxOnDeviceQueues_) ? true : false;\n}\n\nvoid Context::addDeviceQueue(const Device& dev, DeviceQueue* queue, bool defDevQueue) {\n DeviceQueueInfo& info = deviceQueues_[&dev];\n info.deviceQueueCnt_++;\n if (defDevQueue) {\n info.defDeviceQueue_ = queue;\n }\n}\n\nvoid Context::removeDeviceQueue(const Device& dev, DeviceQueue* queue) {\n DeviceQueueInfo& info = deviceQueues_[&dev];\n assert((info.deviceQueueCnt_ != 0) && \"The device queue map is empty!\");\n info.deviceQueueCnt_--;\n if (info.defDeviceQueue_ == queue) {\n info.defDeviceQueue_ = NULL;\n }\n}\n\n} \/\/ namespace amd\nP4 to Git Change 1419977 by gandryey@gera-w8 on 2017\/06\/08 11:16:05\/\/\n\/\/ Copyright (c) 2008 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#include \"platform\/context.hpp\"\n#include \"amdocl\/cl_gl_amd.hpp\"\n#include \"amdocl\/cl_common.hpp\"\n#include \"platform\/commandqueue.hpp\"\n\n#include \n#include \n\n#ifdef _WIN32\n#include \n#include \n#include \"CL\/cl_d3d10.h\"\n#include \"CL\/cl_d3d11.h\"\n#include \"CL\/cl_dx9_media_sharing.h\"\n#endif \/\/_WIN32\n\nnamespace amd {\n\nContext::Context(const std::vector& devices, const Info& info)\n : devices_(devices),\n info_(info),\n properties_(NULL),\n glenv_(NULL),\n customHostAllocDevice_(NULL) {\n for (const auto& device : devices) {\n device->retain();\n if (customHostAllocDevice_ == NULL && device->customHostAllocator()) {\n customHostAllocDevice_ = device;\n }\n if (device->svmSupport()) {\n svmAllocDevice_.push_back(device);\n }\n }\n if (svmAllocDevice_.size() > 1) {\n \/\/ make sure the CPU is the last device to do allocation.\n if ((svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU)) {\n std::swap(svmAllocDevice_.front(), svmAllocDevice_.back());\n }\n\n uint isFirstDeviceFGSEnabled = svmAllocDevice_.front()->isFineGrainedSystem(true);\n for (auto& dev : svmAllocDevice_) {\n \/\/ allocation on fine - grained system incapable device first\n if (isFirstDeviceFGSEnabled && (dev->type() == CL_DEVICE_TYPE_GPU) &&\n (!(dev->isFineGrainedSystem(true)))) {\n std::swap(svmAllocDevice_.front(), dev);\n break;\n }\n }\n }\n}\n\nContext::~Context() {\n static const bool VALIDATE_ONLY = false;\n\n \/\/ Dissociate OCL context with any external device\n if (info_.flags_ & (GLDeviceKhr | D3D10DeviceKhr | D3D11DeviceKhr)) {\n std::vector::const_iterator it;\n \/\/ Loop through all devices\n for (it = devices_.begin(); it != devices_.end(); it++) {\n (*it)->unbindExternalDevice(info_.flags_, info_.hDev_, info_.hCtx_, VALIDATE_ONLY);\n }\n }\n\n if (properties_ != NULL) {\n delete[] properties_;\n }\n if (glenv_ != NULL) {\n delete glenv_;\n glenv_ = NULL;\n }\n\n std::for_each(devices_.begin(), devices_.end(), std::mem_fun(&Device::release));\n\n#if defined WITH_LIQUID_FLASH\n lfTerminate();\n#endif \/\/ WITH_LIQUID_FLASH\n}\n\nint Context::checkProperties(const cl_context_properties* properties, Context::Info* info) {\n cl_platform_id pfmId = 0;\n uint count = 0;\n\n const struct Element {\n intptr_t name;\n void* ptr;\n }* p = reinterpret_cast(properties);\n\n \/\/ Clear the context infor structure\n ::memset(info, 0, sizeof(Context::Info));\n\n if (properties == NULL) {\n return CL_SUCCESS;\n }\n\n \/\/ Process all properties\n while (p->name != 0) {\n switch (p->name) {\n case CL_CONTEXT_INTEROP_USER_SYNC:\n if (p->ptr == reinterpret_cast(CL_TRUE)) {\n info->flags_ |= InteropUserSync;\n }\n break;\n#ifdef _WIN32\n case CL_CONTEXT_D3D10_DEVICE_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D10DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D10DeviceKhr;\n break;\n case CL_CONTEXT_D3D11_DEVICE_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D11DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D11DeviceKhr;\n break;\n case CL_CONTEXT_ADAPTER_D3D9_KHR:\n if (p->ptr == NULL) { \/\/ not supported for xp\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceKhr;\n break;\n case CL_CONTEXT_ADAPTER_D3D9EX_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceEXKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceEXKhr;\n break;\n case CL_CONTEXT_ADAPTER_DXVA_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_VALUE;\n }\n info->hDev_[D3D9DeviceVAKhrIdx] = p->ptr;\n info->flags_ |= D3D9DeviceVAKhr;\n break;\n#endif \/\/_WIN32\n\n case CL_EGL_DISPLAY_KHR:\n info->flags_ |= EGLDeviceKhr;\n\n#ifdef _WIN32\n case CL_WGL_HDC_KHR:\n#endif \/\/_WIN32\n\n#if defined(__linux__)\n case CL_GLX_DISPLAY_KHR:\n#endif \/\/ linux\n info->hDev_[GLDeviceKhrIdx] = p->ptr;\n\n#if defined(__APPLE__) || defined(__MACOSX)\n case CL_CGL_SHAREGROUP_KHR:\n Unimplemented();\n break;\n#endif \/\/__APPLE__ || MACOS\n\n case CL_GL_CONTEXT_KHR:\n if (p->ptr == NULL) {\n return CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n }\n if (p->name == CL_GL_CONTEXT_KHR) {\n info->hCtx_ = p->ptr;\n }\n info->flags_ |= GLDeviceKhr;\n break;\n case CL_CONTEXT_PLATFORM:\n pfmId = reinterpret_cast(p->ptr);\n if ((NULL != pfmId) && (AMD_PLATFORM != pfmId)) {\n return CL_INVALID_VALUE;\n }\n break;\n case CL_CONTEXT_OFFLINE_DEVICES_AMD:\n if (p->ptr != reinterpret_cast(1)) {\n return CL_INVALID_VALUE;\n }\n \/\/ Set the offline device flag\n info->flags_ |= OfflineDevices;\n break;\n case CL_CONTEXT_COMMAND_INTERCEPT_CALLBACK_AMD:\n \/\/ Set the command intercept flag\n info->commandIntercept_ = (cl_int(CL_CALLBACK*)(cl_event, cl_int*))p->ptr;\n info->flags_ |= CommandIntercept;\n break;\n default:\n return CL_INVALID_VALUE;\n }\n p++;\n count++;\n }\n\n info->propertiesSize_ = count * sizeof(Element) + sizeof(intptr_t);\n return CL_SUCCESS;\n}\n\nint Context::create(const intptr_t* properties) {\n static const bool VALIDATE_ONLY = false;\n int result = CL_SUCCESS;\n\n if (properties != NULL) {\n properties_ = new cl_context_properties[info().propertiesSize_ \/ sizeof(cl_context_properties)];\n if (properties_ == NULL) {\n return CL_OUT_OF_HOST_MEMORY;\n }\n\n ::memcpy(properties_, properties, info().propertiesSize_);\n }\n\n \/\/ Check if OCL context can be associated with any external device\n if (info_.flags_ & (D3D10DeviceKhr | D3D11DeviceKhr | GLDeviceKhr | D3D9DeviceKhr |\n D3D9DeviceEXKhr | D3D9DeviceVAKhr)) {\n std::vector::const_iterator it;\n \/\/ Loop through all devices\n for (it = devices_.begin(); it != devices_.end(); it++) {\n if (!(*it)->bindExternalDevice(info_.flags_, info_.hDev_, info_.hCtx_, VALIDATE_ONLY)) {\n result = CL_INVALID_VALUE;\n }\n }\n }\n\n \/\/ Check if the device binding wasn't successful\n if (result != CL_SUCCESS) {\n if (info_.flags_ & GLDeviceKhr) {\n result = CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n } else if (info_.flags_ & D3D10DeviceKhr) {\n \/\/ return CL_INVALID_VALUE; \/\/ FIXME_odintsov: CL_INVALID_D3D_INTEROP;\n } else if (info_.flags_ & D3D11DeviceKhr) {\n \/\/ return CL_INVALID_VALUE; \/\/ FIXME_odintsov: CL_INVALID_D3D_INTEROP;\n } else if (info_.flags_ & (D3D9DeviceKhr | D3D9DeviceEXKhr | D3D9DeviceVAKhr)) {\n \/\/ return CL_INVALID_DX9_MEDIA_ADAPTER_KHR;\n }\n } else {\n if (info_.flags_ & GLDeviceKhr) {\n \/\/ Init context for GL interop\n if (glenv_ == NULL) {\n HMODULE h = (HMODULE)Os::loadLibrary(\n#ifdef _WIN32\n \"OpenGL32.dll\"\n#else \/\/!_WIN32\n \"libGL.so.1\"\n#endif \/\/!_WIN32\n );\n\n if (h && (glenv_ = new GLFunctions(h, (info_.flags_ & Flags::EGLDeviceKhr) != 0))) {\n if (!glenv_->init(reinterpret_cast(info_.hDev_[GLDeviceKhrIdx]),\n reinterpret_cast(info_.hCtx_))) {\n delete glenv_;\n glenv_ = NULL;\n result = CL_INVALID_GL_SHAREGROUP_REFERENCE_KHR;\n }\n }\n }\n }\n }\n#if defined WITH_LIQUID_FLASH\n lfInit();\n#endif \/\/ WITH_LIQUID_FLASH\n return result;\n}\n\nvoid* Context::hostAlloc(size_t size, size_t alignment, bool atomics) const {\n if (customHostAllocDevice_ != NULL) {\n return customHostAllocDevice_->hostAlloc(size, alignment, atomics);\n }\n return AlignedMemory::allocate(size, alignment);\n}\n\nvoid Context::hostFree(void* ptr) const {\n if (customHostAllocDevice_ != NULL) {\n customHostAllocDevice_->hostFree(ptr);\n return;\n }\n AlignedMemory::deallocate(ptr);\n}\n\nvoid* Context::svmAlloc(size_t size, size_t alignment, cl_svm_mem_flags flags) {\n unsigned int numSVMDev = svmAllocDevice_.size();\n if (numSVMDev < 1) {\n return NULL;\n }\n\n if (svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU) {\n return AlignedMemory::allocate(size, alignment);\n } else {\n void* svmPtrAlloced = NULL;\n void* tempPtr = NULL;\n\n for (const auto& dev : svmAllocDevice_) {\n if (dev->type() == CL_DEVICE_TYPE_GPU) {\n \/\/ check if the device support svm platform atomics,\n \/\/ skipped allocation for platform atomics if not supported by this device\n if ((flags & CL_MEM_SVM_ATOMICS) &&\n !(dev->info().svmCapabilities_ & CL_DEVICE_SVM_ATOMICS)) {\n continue;\n }\n svmPtrAlloced = dev->svmAlloc(*this, size, alignment, flags, svmPtrAlloced);\n if (svmPtrAlloced == NULL) {\n return NULL;\n }\n }\n }\n return svmPtrAlloced;\n }\n}\n\nvoid Context::svmFree(void* ptr) const {\n if (svmAllocDevice_.front()->type() == CL_DEVICE_TYPE_CPU) {\n AlignedMemory::deallocate(ptr);\n return;\n }\n\n for (const auto& dev : svmAllocDevice_) {\n if (dev->type() == CL_DEVICE_TYPE_GPU) {\n dev->svmFree(ptr);\n }\n }\n return;\n}\n\nbool Context::containsDevice(const Device* device) const {\n std::vector::const_iterator it;\n\n for (it = devices_.begin(); it != devices_.end(); ++it) {\n if (device == *it || (*it)->isAncestor(device)) {\n return true;\n }\n }\n return false;\n}\n\nDeviceQueue* Context::defDeviceQueue(const Device& dev) const {\n std::map::const_iterator it = deviceQueues_.find(&dev);\n if (it != deviceQueues_.end()) {\n return it->second.defDeviceQueue_;\n } else {\n return NULL;\n }\n}\n\nbool Context::isDevQueuePossible(const Device& dev) {\n return (deviceQueues_[&dev].deviceQueueCnt_ < dev.info().maxOnDeviceQueues_) ? true : false;\n}\n\nvoid Context::addDeviceQueue(const Device& dev, DeviceQueue* queue, bool defDevQueue) {\n DeviceQueueInfo& info = deviceQueues_[&dev];\n info.deviceQueueCnt_++;\n if (defDevQueue) {\n info.defDeviceQueue_ = queue;\n }\n}\n\nvoid Context::removeDeviceQueue(const Device& dev, DeviceQueue* queue) {\n DeviceQueueInfo& info = deviceQueues_[&dev];\n assert((info.deviceQueueCnt_ != 0) && \"The device queue map is empty!\");\n info.deviceQueueCnt_--;\n if (info.defDeviceQueue_ == queue) {\n info.defDeviceQueue_ = NULL;\n }\n}\n\n} \/\/ namespace amd\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/\n\/\/ --------------------\n\/\/ Class AliMpLocalBoard\n\/\/ --------------------\n\/\/ The class defines the properties of local board\n\/\/ Author: Ch. Finck, Subatech Nantes\n\n#include \"AliMpLocalBoard.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpIntPair.h\"\n\n#include \"AliLog.h\"\n\n#include \n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMpLocalBoard)\n\/\/\/ \\endcond\n\n\n\/\/_____________________________________________________________________________\nAliMpLocalBoard::AliMpLocalBoard(Int_t id, const Char_t* name, Int_t slot)\n : TNamed(name, \"mapping trigger local board\"),\n fId(id),\n fSlot(slot),\n fTC(true),\n fCrate(),\n fSwitches(false),\n fNotified(true),\n fDEId(false)\n\n{\n\/\/\/ Default constructor\n}\n\n\/\/______________________________________________________________________________\nAliMpLocalBoard::AliMpLocalBoard(TRootIOCtor* \/*ioCtor*\/)\n : TNamed(),\n fId(),\n fSlot(),\n fTC(),\n fCrate(),\n fSwitches(),\n fNotified(),\n fDEId()\n{\n\/\/\/ Root IO constructor\n}\n\n\n\/\/_____________________________________________________________________________\nAliMpLocalBoard::~AliMpLocalBoard() \n{\n\/\/\/ Destructor\n\n}\n\n\/\/_____________________________________________________________________________\nInt_t AliMpLocalBoard::GetIndex(Int_t chamberId) const\n{\n\/\/\/ Return the index from chamver Id.\n\/\/\/ chamberId could range from 10-13 in absolute value\n\/\/\/ chamberId could also range from 0-3 in relative value\n\n Int_t index = chamberId;\n \n if ( chamberId >= AliMpConstants::NofTrackingChambers() && \n chamberId < AliMpConstants::NofChambers() )\n {\n index -= AliMpConstants::NofTrackingChambers();\n } \n\n if (index < 0 || index >= AliMpConstants::NofTriggerChambers() ) \n {\n AliError(Form(\"chamber# %d not a valid trigger chamber Id, [0-3] or [10-13]\", chamberId));\n return -1;\n }\n\n return index;\n}\n\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::AddDE(Int_t detElemId)\n{\n\/\/\/ Add detection element with given detElemId.\n\/\/\/ Return true if the detection element was added\n\n if ( HasDEId(detElemId) ) {\n AliWarningStream() \n << \"Detection element Id = \" << detElemId << \" already present.\"\n << endl;\n return false;\n }\n\n fDEId.Add(detElemId);\n return true;\n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetNofDEs() const\n{ \n\/\/\/ Return the number of detection elements connected to this crate\n\n return fDEId.GetSize(); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetDEId(Int_t index) const\n{ \n\/\/\/ Return the detection element by index (in loop)\n\n return fDEId.GetValue(index); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetDEIdByChamber(Int_t chamberId) const\n{ \n\/\/\/ Return the detection element by index (in loop)\n\n return fDEId.GetValue(GetIndex(chamberId)); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::HasDEId(Int_t detElemId) const\n{ \n\/\/\/ Return true if the detection element Id is present\n\n return fDEId.HasValue(detElemId); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::AddSwitch(Int_t swit)\n{\n\/\/\/ Add a swicth for the given local board\n\/\/\/ Return true if switch was added\n\n if ( swit > 1 ) {\n AliWarningStream() \n\t << \"Invalid value for switch = \" << swit \n\t << endl;\n return false;\n }\n\n fSwitches.Add(swit);\n return true;\n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetNofSwitches() const\n{ \n\/\/\/ Return the number switches in this local board\n\n return fSwitches.GetSize(); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetSwitch(Int_t index) const\n{\n\/\/\/ Return switch by index (in loop)\n\n if (index < fSwitches.GetSize())\n\treturn fSwitches.GetValue(index);\n else \n\tAliWarning(\"Switch index too large\");\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nAliMpIntPair AliMpLocalBoard::GetPosition() const\n{\n\/\/\/ gives position of the local board in (line, col)\n\n const Char_t* boardName = GetName();\n Int_t iLine = boardName[4] - '0';\n Int_t iCol = boardName[2] - '0';\n if ( iLine == 5 ) --iCol;\n\n return (AliMpIntPair(iLine, iCol));\n\n}\n\nGetPosition corrected (Philippe C.)\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/\/\n\/\/ --------------------\n\/\/ Class AliMpLocalBoard\n\/\/ --------------------\n\/\/ The class defines the properties of local board\n\/\/ Author: Ch. Finck, Subatech Nantes\n\n#include \"AliMpLocalBoard.h\"\n#include \"AliMpConstants.h\"\n#include \"AliMpIntPair.h\"\n\n#include \"AliLog.h\"\n\n#include \n#include \n\n\/\/\/ \\cond CLASSIMP\nClassImp(AliMpLocalBoard)\n\/\/\/ \\endcond\n\n\n\/\/_____________________________________________________________________________\nAliMpLocalBoard::AliMpLocalBoard(Int_t id, const Char_t* name, Int_t slot)\n : TNamed(name, \"mapping trigger local board\"),\n fId(id),\n fSlot(slot),\n fTC(true),\n fCrate(),\n fSwitches(false),\n fNotified(true),\n fDEId(false)\n\n{\n\/\/\/ Default constructor\n}\n\n\/\/______________________________________________________________________________\nAliMpLocalBoard::AliMpLocalBoard(TRootIOCtor* \/*ioCtor*\/)\n : TNamed(),\n fId(),\n fSlot(),\n fTC(),\n fCrate(),\n fSwitches(),\n fNotified(),\n fDEId()\n{\n\/\/\/ Root IO constructor\n}\n\n\n\/\/_____________________________________________________________________________\nAliMpLocalBoard::~AliMpLocalBoard() \n{\n\/\/\/ Destructor\n\n}\n\n\/\/_____________________________________________________________________________\nInt_t AliMpLocalBoard::GetIndex(Int_t chamberId) const\n{\n\/\/\/ Return the index from chamver Id.\n\/\/\/ chamberId could range from 10-13 in absolute value\n\/\/\/ chamberId could also range from 0-3 in relative value\n\n Int_t index = chamberId;\n \n if ( chamberId >= AliMpConstants::NofTrackingChambers() && \n chamberId < AliMpConstants::NofChambers() )\n {\n index -= AliMpConstants::NofTrackingChambers();\n } \n\n if (index < 0 || index >= AliMpConstants::NofTriggerChambers() ) \n {\n AliError(Form(\"chamber# %d not a valid trigger chamber Id, [0-3] or [10-13]\", chamberId));\n return -1;\n }\n\n return index;\n}\n\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::AddDE(Int_t detElemId)\n{\n\/\/\/ Add detection element with given detElemId.\n\/\/\/ Return true if the detection element was added\n\n if ( HasDEId(detElemId) ) {\n AliWarningStream() \n << \"Detection element Id = \" << detElemId << \" already present.\"\n << endl;\n return false;\n }\n\n fDEId.Add(detElemId);\n return true;\n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetNofDEs() const\n{ \n\/\/\/ Return the number of detection elements connected to this crate\n\n return fDEId.GetSize(); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetDEId(Int_t index) const\n{ \n\/\/\/ Return the detection element by index (in loop)\n\n return fDEId.GetValue(index); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetDEIdByChamber(Int_t chamberId) const\n{ \n\/\/\/ Return the detection element by index (in loop)\n\n return fDEId.GetValue(GetIndex(chamberId)); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::HasDEId(Int_t detElemId) const\n{ \n\/\/\/ Return true if the detection element Id is present\n\n return fDEId.HasValue(detElemId); \n}\n\n\/\/______________________________________________________________________________\nBool_t AliMpLocalBoard::AddSwitch(Int_t swit)\n{\n\/\/\/ Add a swicth for the given local board\n\/\/\/ Return true if switch was added\n\n if ( swit > 1 ) {\n AliWarningStream() \n\t << \"Invalid value for switch = \" << swit \n\t << endl;\n return false;\n }\n\n fSwitches.Add(swit);\n return true;\n} \n\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetNofSwitches() const\n{ \n\/\/\/ Return the number switches in this local board\n\n return fSwitches.GetSize(); \n}\n\n\/\/______________________________________________________________________________\nInt_t AliMpLocalBoard::GetSwitch(Int_t index) const\n{\n\/\/\/ Return switch by index (in loop)\n\n if (index < fSwitches.GetSize())\n\treturn fSwitches.GetValue(index);\n else \n\tAliWarning(\"Switch index too large\");\n\n return -1;\n}\n\n\/\/______________________________________________________________________________\nAliMpIntPair AliMpLocalBoard::GetPosition() const\n{\n\/\/\/ gives position of the local board in (line, col)\n\n const Char_t* boardName = GetName();\n Int_t iLine = boardName[4] - '0';\n Int_t iCol = boardName[2] - '0';\n\n return (AliMpIntPair(iLine, iCol));\n}\n\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev \n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#include \n#else\n#include \/* PATH_MAX *\/\n#include \n#endif\n\nnamespace {\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n#if defined(__APPLE__) || defined(__CYGWIN__)\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n\n Paths.push_back(\"\/lib\/x86_64-linux-gnu\/\");\n Paths.push_back(\"\/usr\/local\/lib64\/\");\n Paths.push_back(\"\/usr\/lib64\/\");\n Paths.push_back(\"\/lib64\/\");\n#else\n static bool initialized = false;\n static std::vector SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from\n = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),\n sys_path.end());\n sys_path += ':';\n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n\n for (std::vector::const_iterator I = SysPaths.begin(),\n E = SysPaths.end(); I != E; ++I)\n Paths.push_back((*I).c_str());\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n}\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)\n : m_Opts(Opts) {\n GetSystemLibraryPaths(m_SystemSearchPaths);\n m_SystemSearchPaths.push_back(\".\");\n }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n bool onDisk = (Error == llvm::errc::success);\n if (exists)\n *exists = onDisk;\n\n return onDisk &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n (Magic == file_magic::pecoff_executable)\n#else\n (Magic == file_magic::elf_shared_object)\n#endif\n#elif defined(LLVM_ON_WIN32)\n (Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n std::string\n DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {\n llvm::SmallVector\n Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());\n\n for (llvm::SmallVectorImpl::const_iterator\n IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath); \/\/ FIXME: move alloc outside loop\n llvm::sys::path::append(ThisPath, libStem);\n bool exists;\n if (isSharedLib(ThisPath.str(), &exists))\n return ThisPath.str();\n if (exists)\n return \"\";\n }\n return \"\";\n }\n\n std::string\n DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {\n using namespace llvm::sys;\n\n std::string foundDyLib = lookupLibInPaths(libStem);\n\n if (foundDyLib.empty()) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(libStem);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n foundDyLib = lookupLibInPaths(filenameWithExt);\n#ifdef __APPLE__\n if (foundDyLib.empty()) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n foundDyLib = lookupLibInPaths(filenameWithExt);\n }\n#endif\n }\n\n if (foundDyLib.empty())\n return \"\";\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString FullPath(\"\");\n char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::DyLibMan::lookupLibMaybeAddExt(): error getting \"\n \"real (canonical) path of library \" << foundDyLib << '\\n';\n return foundDyLib;\n }\n FullPath.set_size(strlen(res));\n return FullPath.str();\n }\n\n static std::string normalizePath(llvm::StringRef path) {\n \/\/ Make the path canonical if the file exists.\n struct stat buffer;\n if (stat(path.data(), &buffer) != 0)\n return \"\";\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, path.data(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(path.data(), buf);\n#endif\n if (res == 0) {\n assert(0 && \"Cannot normalize!?\");\n return \"\";\n }\n return res;\n }\n\n std::string\n DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {\n llvm::SmallString<128> Absolute(libStem);\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = libStem == Absolute;\n\n \/\/ If it is an absolute path, don't try iterate over the paths.\n if (isAbsolute) {\n if (isSharedLib(libStem))\n return normalizePath(libStem);\n else\n return \"\";\n }\n\n std::string foundName = lookupLibMaybeAddExt(libStem);\n if (foundName.empty() && !libStem.startswith(\"lib\")) {\n \/\/ try with \"lib\" prefix:\n foundName = lookupLibMaybeAddExt(\"lib\" + libStem.str());\n }\n\n if (isSharedLib(foundName))\n return normalizePath(foundName);\n return \"\";\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& libStem,\n bool permanent) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (canonicalLoadedLib.empty())\n return kLoadLibNotFound;\n\n if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())\n return kLoadLibAlreadyLoaded;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,\n DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),\n RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::DyLibMan::loadLibrary(): \" << errMsg << '\\n';\n return kLoadLibLoadError;\n }\n std::pair insRes\n = m_DyLibs.insert(std::pair(dyLibHandle,\n canonicalLoadedLib));\n if (!insRes.second)\n return kLoadLibAlreadyLoaded;\n m_LoadedLibraries.insert(canonicalLoadedLib);\n return kLoadLibSuccess;\n }\n\n void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (!isLibraryLoaded(canonicalLoadedLib))\n return;\n\n DyLibHandle dyLibHandle = 0;\n for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();\n I != E; ++I) {\n if (I->second == canonicalLoadedLib)\n dyLibHandle = I->first;\n }\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n FreeLibrary(dyLibHandle);\n errMsg = \"UnoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n dlclose(const_cast(dyLibHandle));\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (InterpreterCallbacks* C = m_Interpreter.getCallbacks())\n C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib);\n\n m_DyLibs.erase(dyLibHandle);\n m_LoadedLibraries.erase(canonicalLoadedLib);\n }\n\n bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {\n std::string canonPath = normalizePath(fullPath);\n if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())\n return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast(handle));\n }\n} \/\/ end namespace cling\nRevert unintentionally checked in code.\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ author: Vassil Vassilev \n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#include \n#else\n#include \/* PATH_MAX *\/\n#include \n#endif\n\nnamespace {\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n#if defined(__APPLE__) || defined(__CYGWIN__)\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n\n Paths.push_back(\"\/lib\/x86_64-linux-gnu\/\");\n Paths.push_back(\"\/usr\/local\/lib64\/\");\n Paths.push_back(\"\/usr\/lib64\/\");\n Paths.push_back(\"\/lib64\/\");\n#else\n static bool initialized = false;\n static std::vector SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from\n = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace),\n sys_path.end());\n sys_path += ':';\n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n\n for (std::vector::const_iterator I = SysPaths.begin(),\n E = SysPaths.end(); I != E; ++I)\n Paths.push_back((*I).c_str());\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n}\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts)\n : m_Opts(Opts) {\n GetSystemLibraryPaths(m_SystemSearchPaths);\n m_SystemSearchPaths.push_back(\".\");\n }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n bool onDisk = (Error == llvm::errc::success);\n if (exists)\n *exists = onDisk;\n\n return onDisk &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n (Magic == file_magic::pecoff_executable)\n#else\n (Magic == file_magic::elf_shared_object)\n#endif\n#elif defined(LLVM_ON_WIN32)\n (Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n std::string\n DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const {\n llvm::SmallVector\n Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end());\n\n for (llvm::SmallVectorImpl::const_iterator\n IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath); \/\/ FIXME: move alloc outside loop\n llvm::sys::path::append(ThisPath, libStem);\n bool exists;\n if (isSharedLib(ThisPath.str(), &exists))\n return ThisPath.str();\n if (exists)\n return \"\";\n }\n return \"\";\n }\n\n std::string\n DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const {\n using namespace llvm::sys;\n\n std::string foundDyLib = lookupLibInPaths(libStem);\n\n if (foundDyLib.empty()) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(libStem);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n foundDyLib = lookupLibInPaths(filenameWithExt);\n#ifdef __APPLE__\n if (foundDyLib.empty()) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n foundDyLib = lookupLibInPaths(filenameWithExt);\n }\n#endif\n }\n\n if (foundDyLib.empty())\n return \"\";\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString FullPath(\"\");\n char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::DyLibMan::lookupLibMaybeAddExt(): error getting \"\n \"real (canonical) path of library \" << foundDyLib << '\\n';\n return foundDyLib;\n }\n FullPath.set_size(strlen(res));\n return FullPath.str();\n }\n\n static std::string normalizePath(llvm::StringRef path) {\n \/\/ Make the path canonical if the file exists.\n struct stat buffer;\n if (stat(path.data(), &buffer) != 0)\n return \"\";\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, path.data(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(path.data(), buf);\n#endif\n if (res == 0) {\n assert(0 && \"Cannot normalize!?\");\n return \"\";\n }\n return res;\n }\n\n std::string\n DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const {\n llvm::SmallString<128> Absolute(libStem);\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = libStem == Absolute;\n\n \/\/ If it is an absolute path, don't try iterate over the paths.\n if (isAbsolute) {\n if (isSharedLib(libStem))\n return normalizePath(libStem);\n else\n return \"\";\n }\n\n std::string foundName = lookupLibMaybeAddExt(libStem);\n if (foundName.empty() && !libStem.startswith(\"lib\")) {\n \/\/ try with \"lib\" prefix:\n foundName = lookupLibMaybeAddExt(\"lib\" + libStem.str());\n }\n\n if (isSharedLib(foundName))\n return normalizePath(foundName);\n return \"\";\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& libStem,\n bool permanent) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (canonicalLoadedLib.empty())\n return kLoadLibNotFound;\n\n if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end())\n return kLoadLibAlreadyLoaded;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL,\n DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(),\n RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::DyLibMan::loadLibrary(): \" << errMsg << '\\n';\n return kLoadLibLoadError;\n }\n std::pair insRes\n = m_DyLibs.insert(std::pair(dyLibHandle,\n canonicalLoadedLib));\n if (!insRes.second)\n return kLoadLibAlreadyLoaded;\n m_LoadedLibraries.insert(canonicalLoadedLib);\n return kLoadLibSuccess;\n }\n\n void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) {\n std::string canonicalLoadedLib = lookupLibrary(libStem);\n if (!isLibraryLoaded(canonicalLoadedLib))\n return;\n\n DyLibHandle dyLibHandle = 0;\n for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end();\n I != E; ++I) {\n if (I->second == canonicalLoadedLib)\n dyLibHandle = I->first;\n }\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n FreeLibrary(dyLibHandle);\n errMsg = \"UnoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n dlclose(const_cast(dyLibHandle));\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n m_DyLibs.erase(dyLibHandle);\n m_LoadedLibraries.erase(canonicalLoadedLib);\n }\n\n bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const {\n std::string canonPath = normalizePath(fullPath);\n if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end())\n return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast(handle));\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \"co\/co_unittest.h\"\n#include \"tpp_types.h\"\n#include \"tpp_thread.h\"\n#include \"tpp_backtrace.h\"\n#include \"tpp_corotine.h\"\n#include \"tpp_intrusive_ptr.h\"\n\n#define __TPP_LITTLE_ENDIAN (0x41424344UL)\n#define __TPP_BIG_ENDIAN (0x44434241UL)\n#define __TPP_PDP_ENDIAN (0x42414443UL)\n#define __TPP_BYTE_ORDER ('ABCD')\n\nenum {\n TPP_LITTLE_ENDIAN = 0x03020100ul,\n TPP_BIG_ENDIAN = 0x00010203ul,\n TPP_PDP_ENDIAN = 0x01000302ul,\n};\nstatic const union { unsigned char bytes[4]; uint32_t value; } tpp_byte_order = {{0, 1, 2, 3}};\n#define TPP_BYTE_ORDER (tpp_byte_order.value)\n\nvoid thread_closure(void* arg) {\n std::cout << \"**************** thread_closure ************* \" << arg << std::endl;\n}\n\nvoid corotine_closure(void* arg) {\n tpp::Corotine* co = (tpp::Corotine*)arg;\n auto c = co->running();\n for (auto i = 0; i < 5; ++i) {\n std::cout << \"**************** corotine_closure ************* \" << c << std::endl;\n co->yield();\n }\n}\n\nclass Integer : public tpp::IntrusiveRefCounter {\npublic:\n Integer(void) {\n std::cout << \"********** Integer::Integer **********\" << std::endl;\n }\n\n ~Integer(void) {\n std::cout << \"********** Integer::~Integer **********\" << std::endl;\n }\n};\n\nint main(int argc, char* argv[]) {\n TPP_UNUSED(argc);\n TPP_UNUSED(argv);\n\n std::cout << \"Hello, `tpp` !\" << std::endl;\n\n {\n \/\/ byte order checking\n \/\/ if (__TPP_BYTE_ORDER == __TPP_LITTLE_ENDIAN)\n if (TPP_BYTE_ORDER == TPP_LITTLE_ENDIAN)\n std::cout << \"little endian\" << std::endl;\n else if (BYTE_ORDER == BIG_ENDIAN)\n std::cout << \"big endian\" << std::endl;\n else if (BYTE_ORDER == PDP_ENDIAN)\n std::cout << \"pdp endian\" << std::endl;\n else\n std::cout << \"error endian\" << std::endl;\n }\n\n {\n \/\/ thread sample\n tpp::Thread t(thread_closure, nullptr);\n t.join();\n }\n {\n \/\/ backtrace sample\n std::string bt;\n tpp::__libtpp_backtrace(bt);\n std::cout << bt << std::endl;\n }\n {\n \/\/ intrusive pointer sample\n tpp::IntrusivePtr p(new Integer());\n }\n co::test::run_all_unittests();\n\n {\n \/\/ corotine sample\n tpp::Corotine co;\n auto c1 = co.create(corotine_closure, &co);\n auto c2 = co.create(corotine_closure, &co);\n\n while (tpp::CoStatus::DEAD != co.status(c1)\n && tpp::CoStatus::DEAD != co.status(c2)) {\n std::cout << \"================ main corotine - corotines status >> \" << (int)co.status(c1) << \" : \" << (int)co.status(c2) << std::endl;\n co.resume(c1);\n co.resume(c2);\n }\n std::cout << \"================ return main thread ================\" << std::endl;\n }\n\n return 0;\n}\nfix(tpp): fixed bug of get byte order\/\/ Copyright (c) 2016 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n#include \n#include \"co\/co_unittest.h\"\n#include \"tpp_types.h\"\n#include \"tpp_thread.h\"\n#include \"tpp_backtrace.h\"\n#include \"tpp_corotine.h\"\n#include \"tpp_intrusive_ptr.h\"\n\n#define __TPP_LITTLE_ENDIAN (0x41424344UL)\n#define __TPP_BIG_ENDIAN (0x44434241UL)\n#define __TPP_PDP_ENDIAN (0x42414443UL)\n#define __TPP_BYTE_ORDER ('ABCD')\n\nenum {\n TPP_LITTLE_ENDIAN = 0x03020100ul,\n TPP_BIG_ENDIAN = 0x00010203ul,\n TPP_PDP_ENDIAN = 0x01000302ul,\n};\nstatic const union { unsigned char bytes[4]; uint32_t value; } tpp_byte_order = {{0, 1, 2, 3}};\n#define TPP_BYTE_ORDER (tpp_byte_order.value)\n\nvoid thread_closure(void* arg) {\n std::cout << \"**************** thread_closure ************* \" << arg << std::endl;\n}\n\nvoid corotine_closure(void* arg) {\n tpp::Corotine* co = (tpp::Corotine*)arg;\n auto c = co->running();\n for (auto i = 0; i < 5; ++i) {\n std::cout << \"**************** corotine_closure ************* \" << c << std::endl;\n co->yield();\n }\n}\n\nclass Integer : public tpp::IntrusiveRefCounter {\npublic:\n Integer(void) {\n std::cout << \"********** Integer::Integer **********\" << std::endl;\n }\n\n ~Integer(void) {\n std::cout << \"********** Integer::~Integer **********\" << std::endl;\n }\n};\n\nint main(int argc, char* argv[]) {\n TPP_UNUSED(argc);\n TPP_UNUSED(argv);\n\n std::cout << \"Hello, `tpp` !\" << std::endl;\n\n {\n \/\/ byte order checking\n \/\/ if (__TPP_BYTE_ORDER == __TPP_LITTLE_ENDIAN)\n if (TPP_BYTE_ORDER == TPP_LITTLE_ENDIAN)\n std::cout << \"little endian\" << std::endl;\n else if (TPP_BYTE_ORDER == TPP_BIG_ENDIAN)\n std::cout << \"big endian\" << std::endl;\n else if (TPP_BYTE_ORDER == TPP_PDP_ENDIAN)\n std::cout << \"pdp endian\" << std::endl;\n else\n std::cout << \"error endian\" << std::endl;\n }\n\n {\n \/\/ thread sample\n tpp::Thread t(thread_closure, nullptr);\n t.join();\n }\n {\n \/\/ backtrace sample\n std::string bt;\n tpp::__libtpp_backtrace(bt);\n std::cout << bt << std::endl;\n }\n {\n \/\/ intrusive pointer sample\n tpp::IntrusivePtr p(new Integer());\n }\n co::test::run_all_unittests();\n\n {\n \/\/ corotine sample\n tpp::Corotine co;\n auto c1 = co.create(corotine_closure, &co);\n auto c2 = co.create(corotine_closure, &co);\n\n while (tpp::CoStatus::DEAD != co.status(c1)\n && tpp::CoStatus::DEAD != co.status(c2)) {\n std::cout << \"================ main corotine - corotines status >> \" << (int)co.status(c1) << \" : \" << (int)co.status(c2) << std::endl;\n co.resume(c1);\n co.resume(c2);\n }\n std::cout << \"================ return main thread ================\" << std::endl;\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/*********************************************************\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF\n\/\/ ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY\n\/\/ IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR\n\/\/ PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.\n\/\/\n\/\/*********************************************************\n#include \"pch.h\"\n#if !TV_API && defined(_WIN32)\n#include \n#endif\n#include \"xsapi\/system.h\"\n#include \"local_config.h\"\n#include \"xbox_system_factory.h\"\n#include \"Utils.h\"\n#if XSAPI_A\n#include \"a\/user_impl_a.h\"\n#include \"a\/java_interop.h\"\n#endif\n\nusing namespace std;\nNAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN\n\nstd::shared_ptr local_config::get_local_config_singleton()\n{\n auto xsapiSingleton = get_xsapi_singleton();\n std::lock_guard guard(xsapiSingleton->s_singletonLock);\n if (xsapiSingleton->s_localConfigSingleton == nullptr)\n {\n xsapiSingleton->s_localConfigSingleton = std::make_shared();\n\n#if !TV_API\n xbox_live_result configResult = xsapiSingleton->s_localConfigSingleton->read();\n if (configResult.err())\n {\n LOGS_ERROR << \"Loading local config file error: \" << configResult.err() << \", msg:\" << configResult.err_message();\n XSAPI_ASSERT(!configResult.err());\n }\n#endif\n }\n return xsapiSingleton->s_localConfigSingleton;\n}\n\nlocal_config::local_config()\n{\n}\n\n#if !TV_API\nuint64_t local_config::get_uint64_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ uint64_t defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n return utils::extract_json_uint52(m_jsonConfig, name.c_str(), required, defaultValue);\n}\n\nstring_t local_config::get_value_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ const string_t& defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n return utils::extract_json_string(m_jsonConfig, name.c_str(), required, defaultValue);\n}\n\nbool local_config::get_bool_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ bool defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n\n std::error_code err;\n auto value = utils::extract_json_field(m_jsonConfig, name.c_str(), err, required);\n\n \/\/ the value could be \"0\", \"1\", or true false\n if (value.is_boolean())\n {\n return value.as_bool();\n }\n else if (value.is_string())\n {\n return value.as_string() == _T(\"1\");\n }\n else\n {\n return defaultValue;\n }\n}\n\nuint32_t local_config::title_id()\n{\n uint64_t titleId = get_uint64_from_config(_T(\"TitleId\"), false, 0);\n\n \/\/ Also support title id in string from\n if (titleId == 0)\n {\n string_t titleIdString = get_value_from_config(_T(\"TitleId\"), false, _T(\"\"));\n if (!titleIdString.empty())\n {\n titleId = utils::string_t_to_uint64(titleIdString);\n }\n }\n\n return static_cast(titleId);\n}\n\nstring_t local_config::scid()\n{\n return get_value_from_config(_T(\"PrimaryServiceConfigId\"), false, _T(\"\"));\n}\n\nuint32_t local_config::override_title_id()\n{\n uint64_t titleId = get_uint64_from_config(_T(\"OverrideTitleId\"), false, 0);\n return static_cast(titleId);\n}\n\nstring_t local_config::override_scid()\n{\n return get_value_from_config(_T(\"OverrideServiceConfigId\"), false, _T(\"\"));\n}\n\nstring_t local_config::environment_prefix()\n{\n return get_value_from_config(_T(\"EnvironmentPrefix\"), false, _T(\"\"));\n}\n\nstring_t local_config::environment()\n{\n string_t environment = get_value_from_config(_T(\"Environment\"), false, _T(\"\"));\n if (!environment.empty())\n {\n if (environment[0] != _T('.'))\n {\n environment = _T(\".\") + environment;\n }\n }\n\n return environment;\n}\n\nstring_t local_config::sandbox()\n{\n return get_value_from_config(_T(\"Sandbox\"), false, _T(\"RETAIL\"));\n}\n\nstring_t local_config::client_secret()\n{\n return get_value_from_config(_T(\"ClientSecret\"), false, _T(\"\"));\n}\n\nbool local_config::use_first_party_token()\n{\n return get_bool_from_config(_T(\"FirstParty\"), false, false);\n}\n\n#if XSAPI_I\nstring_t local_config::apns_environment()\n{\n return get_value_from_config(_T(\"ApnsEnvironment\"), false, _T(\"apnsProduction\"));\n}\n#endif\n\n#endif\nNAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END\n\nAdding support for titleId in hex (#59)\/\/*********************************************************\n\/\/\n\/\/ Copyright (c) Microsoft. All rights reserved.\n\/\/ THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF\n\/\/ ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY\n\/\/ IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR\n\/\/ PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.\n\/\/\n\/\/*********************************************************\n#include \"pch.h\"\n#if !TV_API && defined(_WIN32)\n#include \n#endif\n#include \"xsapi\/system.h\"\n#include \"local_config.h\"\n#include \"xbox_system_factory.h\"\n#include \"Utils.h\"\n#if XSAPI_A\n#include \"a\/user_impl_a.h\"\n#include \"a\/java_interop.h\"\n#endif\n\nusing namespace std;\nNAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_BEGIN\n\nstd::shared_ptr local_config::get_local_config_singleton()\n{\n auto xsapiSingleton = get_xsapi_singleton();\n std::lock_guard guard(xsapiSingleton->s_singletonLock);\n if (xsapiSingleton->s_localConfigSingleton == nullptr)\n {\n xsapiSingleton->s_localConfigSingleton = std::make_shared();\n\n#if !TV_API\n xbox_live_result configResult = xsapiSingleton->s_localConfigSingleton->read();\n if (configResult.err())\n {\n LOGS_ERROR << \"Loading local config file error: \" << configResult.err() << \", msg:\" << configResult.err_message();\n XSAPI_ASSERT(!configResult.err());\n }\n#endif\n }\n return xsapiSingleton->s_localConfigSingleton;\n}\n\nlocal_config::local_config()\n{\n}\n\n#if !TV_API\nuint64_t local_config::get_uint64_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ uint64_t defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n return utils::extract_json_uint52(m_jsonConfig, name.c_str(), required, defaultValue);\n}\n\nstring_t local_config::get_value_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ const string_t& defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n return utils::extract_json_string(m_jsonConfig, name.c_str(), required, defaultValue);\n}\n\nbool local_config::get_bool_from_config(\n _In_ const string_t& name,\n _In_ bool required,\n _In_ bool defaultValue\n )\n{\n std::lock_guard guard(m_jsonConfigLock);\n\n std::error_code err;\n auto value = utils::extract_json_field(m_jsonConfig, name.c_str(), err, required);\n\n \/\/ the value could be \"0\", \"1\", or true false\n if (value.is_boolean())\n {\n return value.as_bool();\n }\n else if (value.is_string())\n {\n return value.as_string() == _T(\"1\");\n }\n else\n {\n return defaultValue;\n }\n}\n\nuint32_t local_config::title_id()\n{\n uint64_t titleId = get_uint64_from_config(_T(\"TitleId\"), false, 0);\n\n \/\/ Also support title id in string dec form or string hex form \n if (titleId == 0)\n {\n string_t titleIdString = get_value_from_config(_T(\"TitleId\"), false, _T(\"\"));\n if (!titleIdString.empty())\n {\n titleId = utils::string_t_to_uint64(titleIdString);\n if (titleId == 0)\n {\n stringstream_t ss;\n ss << std::hex << titleIdString;\n ss >> titleId;\n }\n }\n }\n\n return static_cast(titleId);\n}\n\nstring_t local_config::scid()\n{\n return get_value_from_config(_T(\"PrimaryServiceConfigId\"), false, _T(\"\"));\n}\n\nuint32_t local_config::override_title_id()\n{\n uint64_t titleId = get_uint64_from_config(_T(\"OverrideTitleId\"), false, 0);\n return static_cast(titleId);\n}\n\nstring_t local_config::override_scid()\n{\n return get_value_from_config(_T(\"OverrideServiceConfigId\"), false, _T(\"\"));\n}\n\nstring_t local_config::environment_prefix()\n{\n return get_value_from_config(_T(\"EnvironmentPrefix\"), false, _T(\"\"));\n}\n\nstring_t local_config::environment()\n{\n string_t environment = get_value_from_config(_T(\"Environment\"), false, _T(\"\"));\n if (!environment.empty())\n {\n if (environment[0] != _T('.'))\n {\n environment = _T(\".\") + environment;\n }\n }\n\n return environment;\n}\n\nstring_t local_config::sandbox()\n{\n return get_value_from_config(_T(\"Sandbox\"), false, _T(\"RETAIL\"));\n}\n\nstring_t local_config::client_secret()\n{\n return get_value_from_config(_T(\"ClientSecret\"), false, _T(\"\"));\n}\n\nbool local_config::use_first_party_token()\n{\n return get_bool_from_config(_T(\"FirstParty\"), false, false);\n}\n\n#if XSAPI_I\nstring_t local_config::apns_environment()\n{\n return get_value_from_config(_T(\"ApnsEnvironment\"), false, _T(\"apnsProduction\"));\n}\n#endif\n\n#endif\nNAMESPACE_MICROSOFT_XBOX_SERVICES_CPP_END\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector &points, const std::vector &normals, const std::vector &colors)\n : points_(&points),\n normals_((normals.size() == points.size()) ? &normals : NULL),\n colors_((colors.size() == points.size()) ? &colors : NULL),\n kd_tree_(new KDTree(points)),\n kd_tree_owned_(true)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector &points, const std::vector &normals, const std::vector &colors, const KDTree &kd_tree)\n : points_(&points),\n normals_((normals.size() == points.size()) ? &normals : NULL),\n colors_((colors.size() == points.size()) ? &colors : NULL),\n kd_tree_((KDTree*)&kd_tree),\n kd_tree_owned_(false)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud)\n : points_(&cloud.points),\n normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL),\n colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL),\n kd_tree_(new KDTree(cloud.points)),\n kd_tree_owned_(true)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud, const KDTree &kd_tree)\n : points_(&cloud.points),\n normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL),\n colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL),\n kd_tree_((KDTree*)&kd_tree),\n kd_tree_owned_(false)\n{}\n\nConnectedComponentSegmentation::~ConnectedComponentSegmentation() {\n if (kd_tree_owned_) delete kd_tree_;\n}\n\nConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(std::vector seeds_ind,\n float dist_thresh,\n float normal_angle_thresh,\n float color_diff_thresh,\n size_t min_segment_size,\n size_t max_segment_size)\n{\n dist_thresh_ = dist_thresh;\n normal_angle_thresh_ = normal_angle_thresh;\n color_diff_thresh_ = color_diff_thresh;\n min_segment_size_ = min_segment_size;\n max_segment_size_ = max_segment_size;\n\n std::vector has_been_assigned(points_->size(), false);\n\n std::vector neighbors;\n std::vector distances;\n\n component_indices_.clear();\n for (size_t i = 0; i < seeds_ind.size(); i++) {\n if (has_been_assigned[seeds_ind[i]]) continue;\n\n std::vector curr_cc_ind;\n std::vector is_in_stack(points_->size(), 0);\n\n std::stack seeds_stack;\n seeds_stack.push(seeds_ind[i]);\n is_in_stack[seeds_ind[i]] = 1;\n while (!seeds_stack.empty()) {\n size_t curr_seed = seeds_stack.top();\n seeds_stack.pop();\n\n has_been_assigned[curr_seed] = 1;\n curr_cc_ind.emplace_back(curr_seed);\n\n kd_tree_->radiusSearch((*points_)[curr_seed], dist_thresh_, neighbors, distances);\n\n for (size_t j = 0; j < neighbors.size(); j++) {\n if (is_similar_(curr_seed,neighbors[j]) && !is_in_stack[neighbors[j]]) {\n seeds_stack.push(neighbors[j]);\n is_in_stack[neighbors[j]] = 1;\n }\n }\n\n }\n\n if (curr_cc_ind.size() >= min_segment_size_ && curr_cc_ind.size() <= max_segment_size_) {\n component_indices_.emplace_back(curr_cc_ind);\n }\n }\n\n std::sort(component_indices_.begin(), component_indices_.end(), vector_size_comparator_);\n\n label_map_ = std::vector(points_->size(), component_indices_.size());\n for (size_t i = 0; i < component_indices_.size(); i++) {\n for (size_t j = 0; j < component_indices_[i].size(); j++) {\n label_map_[component_indices_[i][j]] = i;\n }\n }\n\n return *this;\n}\n\nConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(float dist_thresh,\n float normal_angle_thresh,\n float color_diff_thresh,\n size_t min_segment_size,\n size_t max_segment_size)\n{\n std::vector seeds_ind(points_->size());\n for (size_t i = 0; i < seeds_ind.size(); i++) {\n seeds_ind[i] = i;\n }\n return segment(seeds_ind, dist_thresh, normal_angle_thresh, color_diff_thresh, min_segment_size, max_segment_size);\n}\nConnected component segmentation improvements#include \n#include \n\n#include \n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector &points, const std::vector &normals, const std::vector &colors)\n : points_(&points),\n normals_((normals.size() == points.size()) ? &normals : NULL),\n colors_((colors.size() == points.size()) ? &colors : NULL),\n kd_tree_(new KDTree(points)),\n kd_tree_owned_(true)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const std::vector &points, const std::vector &normals, const std::vector &colors, const KDTree &kd_tree)\n : points_(&points),\n normals_((normals.size() == points.size()) ? &normals : NULL),\n colors_((colors.size() == points.size()) ? &colors : NULL),\n kd_tree_((KDTree*)&kd_tree),\n kd_tree_owned_(false)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud)\n : points_(&cloud.points),\n normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL),\n colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL),\n kd_tree_(new KDTree(cloud.points)),\n kd_tree_owned_(true)\n{}\n\nConnectedComponentSegmentation::ConnectedComponentSegmentation(const PointCloud &cloud, const KDTree &kd_tree)\n : points_(&cloud.points),\n normals_((cloud.normals.size() == cloud.points.size()) ? &cloud.normals : NULL),\n colors_((cloud.colors.size() == cloud.points.size()) ? &cloud.colors : NULL),\n kd_tree_((KDTree*)&kd_tree),\n kd_tree_owned_(false)\n{}\n\nConnectedComponentSegmentation::~ConnectedComponentSegmentation() {\n if (kd_tree_owned_) delete kd_tree_;\n}\n\nConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(std::vector seeds_ind,\n float dist_thresh,\n float normal_angle_thresh,\n float color_diff_thresh,\n size_t min_segment_size,\n size_t max_segment_size)\n{\n dist_thresh_ = dist_thresh;\n normal_angle_thresh_ = normal_angle_thresh;\n color_diff_thresh_ = color_diff_thresh;\n min_segment_size_ = min_segment_size;\n max_segment_size_ = max_segment_size;\n\n std::vector has_been_assigned(points_->size(), false);\n\n std::vector neighbors;\n std::vector distances;\n\n component_indices_.clear();\n for (size_t i = 0; i < seeds_ind.size(); i++) {\n if (has_been_assigned[seeds_ind[i]]) continue;\n\n std::stack seeds_stack;\n seeds_stack.push(seeds_ind[i]);\n has_been_assigned[seeds_ind[i]] = true;\n\n std::vector curr_cc_ind;\n while (!seeds_stack.empty()) {\n size_t curr_seed = seeds_stack.top();\n seeds_stack.pop();\n curr_cc_ind.emplace_back(curr_seed);\n\n kd_tree_->radiusSearch((*points_)[curr_seed], dist_thresh_, neighbors, distances);\n for (size_t j = 1; j < neighbors.size(); j++) {\n if (!has_been_assigned[neighbors[j]] && is_similar_(curr_seed,neighbors[j])) {\n seeds_stack.push(neighbors[j]);\n has_been_assigned[neighbors[j]] = true;\n }\n }\n\n }\n\n if (curr_cc_ind.size() >= min_segment_size_ && curr_cc_ind.size() <= max_segment_size_) {\n component_indices_.emplace_back(curr_cc_ind);\n }\n }\n\n std::sort(component_indices_.begin(), component_indices_.end(), vector_size_comparator_);\n\n label_map_ = std::vector(points_->size(), component_indices_.size());\n for (size_t i = 0; i < component_indices_.size(); i++) {\n for (size_t j = 0; j < component_indices_[i].size(); j++) {\n label_map_[component_indices_[i][j]] = i;\n }\n }\n\n return *this;\n}\n\nConnectedComponentSegmentation& ConnectedComponentSegmentation::segment(float dist_thresh,\n float normal_angle_thresh,\n float color_diff_thresh,\n size_t min_segment_size,\n size_t max_segment_size)\n{\n std::vector seeds_ind(points_->size());\n for (size_t i = 0; i < seeds_ind.size(); i++) {\n seeds_ind[i] = i;\n }\n return segment(seeds_ind, dist_thresh, normal_angle_thresh, color_diff_thresh, min_segment_size, max_segment_size);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: ScaleAutomatism.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2004-05-11 14:11:16 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2003 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#include \"ScaleAutomatism.hxx\"\n#include \"macros.hxx\"\n#include \"TickmarkHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_\n#include \n#endif\n\n#ifndef INCLUDED_RTL_MATH_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::chart2;\n\nScaleAutomatism::ScaleAutomatism( const ScaleData& rSourceScale )\n : m_fValueMinimum( 0.0 )\n , m_fValueMaximum( 0.0 )\n , m_nMaximumAutomaticMainIncrementCount(10)\n , m_aSourceScale( rSourceScale )\n , m_aSourceIncrement()\n , m_aSourceSubIncrementList()\n{\n ::rtl::math::setNan( &m_fValueMinimum );\n ::rtl::math::setNan( &m_fValueMaximum );\n}\n\nScaleAutomatism::ScaleAutomatism( const ScaleData& rSourceScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n : m_fValueMinimum( 0.0 )\n , m_fValueMaximum( 0.0 )\n , m_nMaximumAutomaticMainIncrementCount(9)\n , m_aSourceScale( rSourceScale )\n , m_aSourceIncrement( rSourceIncrement )\n , m_aSourceSubIncrementList( rSourceSubIncrementList )\n{\n ::rtl::math::setNan( &m_fValueMinimum );\n ::rtl::math::setNan( &m_fValueMaximum );\n}\n\nScaleAutomatism::~ScaleAutomatism()\n{\n}\n\n\/\/@todo these method should become part of the scaling interface and implementation somehow\n\/\/@todo problem with outparamters at api\nExplicitIncrementData getExplicitIncrementAndScaleForLogarithm(\n bool bChangeMinimumToIncrementRythm, bool bChangeMaximumToIncrementRythm\n , sal_Int32 nMaximumAutomaticMainIncrementCount\n , ExplicitScaleData& rExplicitScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n{\n \/\/minimum and maximum of the ExplicitScaleData may be changed\n \/\/to suiteable values if allowed\n \/\/but they will definitly be changed if they are out of allowed borders\n\n if( nMaximumAutomaticMainIncrementCount <= 0 )\n nMaximumAutomaticMainIncrementCount = 5;\n\n \/\/make sure that minimum and maximum are not out of allowed range\n {\n if( rExplicitScale.Maximum<=0.0 )\n rExplicitScale.Maximum = 100.0;\n if( rExplicitScale.Minimum<=0.0 )\n {\n rExplicitScale.Minimum = 0.1;\n if( rExplicitScale.Minimum >= rExplicitScale.Maximum )\n rExplicitScale.Minimum = log(rExplicitScale.Maximum)\/10.0;\n }\n if( rExplicitScale.Maximum<= rExplicitScale.Minimum )\n rExplicitScale.Maximum = rExplicitScale.Minimum + 10;\n }\n\n ExplicitIncrementData aRet;\n if(!(rSourceIncrement.PostEquidistant>>=aRet.PostEquidistant))\n {\n \/\/maybe scaling dependent\n aRet.PostEquidistant = sal_True;\n }\n if(!(rSourceIncrement.Distance>>=aRet.Distance))\n {\n \/\/autocalculate the distance\n if(aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n {\n double fRange = rExplicitScale.Scaling->doScaling( rExplicitScale.Maximum )\n - rExplicitScale.Scaling->doScaling( rExplicitScale.Minimum );\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n \/\/make a fine value out of fSlice now:\n \/\/only integers are reasonable as distance values\n sal_Int32 nDistance = static_cast(fSlice);\n if(nDistance<=0)\n nDistance=1;\n aRet.Distance = nDistance;\n }\n else\n {\n \/\/@todo this was not tested\n double fRange = rExplicitScale.Maximum - rExplicitScale.Minimum;\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n \/\/make a fine value out of fSlice now:\n double fSliceMagnitude = pow ( (double)10, floor (log10 (fSlice)));\n aRet.Distance = static_cast(fSlice\/fSliceMagnitude)*fSliceMagnitude;\n }\n }\n\n if(!(rSourceIncrement.BaseValue>>=aRet.BaseValue))\n {\n \/\/scaling dependent\n \/\/@maybe todo is this default also plotter dependent ??\n aRet.BaseValue = 1.0;\n }\n else if( aRet.BaseValue<=0.0 ) \/\/make sure that BaseValue is not out of allowed ranges\n aRet.BaseValue = 1.0;\n\n if(bChangeMinimumToIncrementRythm)\n {\n double fMin = rExplicitScale.Minimum;\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMin = rExplicitScale.Scaling->doScaling(fMin);\n\n fMin = TickmarkHelper::getMinimumAtIncrement( fMin, aRet );\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMin = rExplicitScale.Scaling->getInverseScaling()->doScaling(fMin);\n rExplicitScale.Minimum = fMin;\n\n if( rExplicitScale.Minimum<=0.0 )\n {\n rExplicitScale.Minimum = 0.1;\n if( rExplicitScale.Minimum >= rExplicitScale.Maximum )\n rExplicitScale.Minimum = log(rExplicitScale.Maximum)\/10.0;\n }\n }\n if(bChangeMaximumToIncrementRythm)\n {\n double fMax = rExplicitScale.Maximum;\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMax = rExplicitScale.Scaling->doScaling(fMax);\n fMax = TickmarkHelper::getMaximumAtIncrement( fMax, aRet );\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMax = rExplicitScale.Scaling->getInverseScaling()->doScaling(fMax);\n rExplicitScale.Maximum = fMax;\n }\n \/\/---------------------------------------------------------------\n \/\/fill explicit sub increment\n sal_Int32 nSubCount = rSourceSubIncrementList.getLength();\n aRet.SubIncrements.realloc(nSubCount);\n for( sal_Int32 nN=0; nN>=rExplicitSubIncrement.IntervalCount))\n {\n \/\/scaling dependent\n \/\/@todo autocalculate IntervalCount dependent on MainIncrement and scaling\n rExplicitSubIncrement.IntervalCount = 5;\n }\n if(!(rSubIncrement.PostEquidistant>>=rExplicitSubIncrement.PostEquidistant))\n {\n \/\/scaling dependent\n rExplicitSubIncrement.PostEquidistant = sal_False;\n }\n }\n return aRet;\n}\n\nExplicitIncrementData getExplicitIncrementAndScaleForLinear(\n bool bChangeMinimumToIncrementRythm, bool bChangeMaximumToIncrementRythm\n , sal_Int32 nMaximumAutomaticMainIncrementCount\n , ExplicitScaleData& rExplicitScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n{\n \/\/minimum and maximum of the ExplicitScaleData may be changed\n \/\/to suiteable values if allowed\n \/\/but they will definitly be changed if they are out of allowed borders\n\n if( nMaximumAutomaticMainIncrementCount <= 0 )\n nMaximumAutomaticMainIncrementCount = 5;\n\n \/\/make sure that minimum and maximum have allowed values\n {\n if( rExplicitScale.Maximum<= rExplicitScale.Minimum )\n rExplicitScale.Maximum = rExplicitScale.Minimum + 10;\n }\n\n ExplicitIncrementData aRet;\n if(!(rSourceIncrement.PostEquidistant>>=aRet.PostEquidistant))\n {\n \/\/maybe scaling dependent\n aRet.PostEquidistant = sal_True;\n }\n if(!(rSourceIncrement.Distance>>=aRet.Distance))\n {\n \/\/autocalculate the distance\n double fRange = rExplicitScale.Maximum - rExplicitScale.Minimum;\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n\n \/\/make a fine value out of fSlice now:\n double fSliceMagnitude = pow ( (double)10, floor (log10 (fSlice)));\n fSlice \/= fSliceMagnitude;\n if(fSlice<=1.0)\n fSlice=1.0;\n else if( fSlice<= 2.0 )\n fSlice=2.0;\n else if( fSlice<= 2.5 )\n fSlice=2.5;\n else if( fSlice<= 5.0)\n fSlice=5.0;\n else\n fSlice=10.0;\n\n aRet.Distance = fSlice*fSliceMagnitude;\n }\n if(!(rSourceIncrement.BaseValue>>=aRet.BaseValue))\n {\n \/\/@maybe todo is this default also plotter dependent ??\n aRet.BaseValue = 0.0;\n }\n if(bChangeMinimumToIncrementRythm)\n {\n rExplicitScale.Minimum = TickmarkHelper::getMinimumAtIncrement( rExplicitScale.Minimum, aRet );\n }\n if(bChangeMaximumToIncrementRythm)\n {\n rExplicitScale.Maximum = TickmarkHelper::getMaximumAtIncrement( rExplicitScale.Maximum, aRet );\n }\n \/\/---------------------------------------------------------------\n \/\/fill explicit sub increment\n sal_Int32 nSubCount = rSourceSubIncrementList.getLength();\n aRet.SubIncrements.realloc(nSubCount);\n for( sal_Int32 nN=0; nN>=rExplicitSubIncrement.IntervalCount))\n {\n \/\/scaling dependent\n \/\/@todo autocalculate IntervalCount dependent on MainIncrement and scaling\n rExplicitSubIncrement.IntervalCount = 2;\n }\n if(!(rSubIncrement.PostEquidistant>>=rExplicitSubIncrement.PostEquidistant))\n {\n \/\/scaling dependent\n rExplicitSubIncrement.PostEquidistant = sal_False;\n }\n }\n return aRet;\n}\n\nvoid ScaleAutomatism::calculateExplicitScaleAndIncrement(\n ExplicitScaleData& rExplicitScale\n , ExplicitIncrementData& rExplicitIncrement )\n{\n \/\/---------------------------------------------------------------\n \/\/fill explicit scale\n bool bChangeMinimumToIncrementRythm=false, bChangeMaximumToIncrementRythm=false;\n if(!(m_aSourceScale.Minimum>>=rExplicitScale.Minimum))\n {\n \/\/autocalculate the minimum in first iteration\n \/\/the increment is considered below\n if( !::rtl::math::isNan(m_fValueMinimum) )\n rExplicitScale.Minimum = m_fValueMinimum;\n else\n rExplicitScale.Minimum = 0.0;\/\/@todo get Minimum from scsaling or from plotter????\n bChangeMinimumToIncrementRythm = true;\n }\n if(!(m_aSourceScale.Maximum>>=rExplicitScale.Maximum))\n {\n \/\/autocalculate the maximum in first iteration\n \/\/the increment is considered below\n if( !::rtl::math::isNan(m_fValueMaximum) )\n rExplicitScale.Maximum = m_fValueMaximum;\n else\n rExplicitScale.Maximum = 10.0;\/\/@todo get Maximum from scaling or from plotter????\n bChangeMaximumToIncrementRythm=true;\n }\n rExplicitScale.Orientation = m_aSourceScale.Orientation;\/\/AxisOrientation_MATHEMATICAL;\n rExplicitScale.Scaling = m_aSourceScale.Scaling;\n rExplicitScale.Breaks = m_aSourceScale.Breaks;\n \/\/---------------------------------------------------------------\n \/\/fill explicit increment\n \/\/minimum and maximum of the ExplicitScaleData may be changed if allowed\n uno::Reference< lang::XServiceName > xServiceName( rExplicitScale.Scaling, uno::UNO_QUERY );\n bool bIsLogarithm = ( xServiceName.is() && (xServiceName->getServiceName()).equals(\n C2U( \"com.sun.star.chart2.LogarithmicScaling\" )));\n if(bIsLogarithm)\n rExplicitIncrement = getExplicitIncrementAndScaleForLogarithm( bChangeMinimumToIncrementRythm, bChangeMaximumToIncrementRythm, m_nMaximumAutomaticMainIncrementCount\n , rExplicitScale, m_aSourceIncrement, m_aSourceSubIncrementList );\n else\n rExplicitIncrement = getExplicitIncrementAndScaleForLinear( bChangeMinimumToIncrementRythm, bChangeMaximumToIncrementRythm, m_nMaximumAutomaticMainIncrementCount\n , rExplicitScale, m_aSourceIncrement, m_aSourceSubIncrementList );\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\nINTEGRATION: CWS ooo19126 (1.4.88); FILE MERGED 2005\/09\/05 18:43:37 rt 1.4.88.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: ScaleAutomatism.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 01:36:11 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#include \"ScaleAutomatism.hxx\"\n#include \"macros.hxx\"\n#include \"TickmarkHelper.hxx\"\n\n#ifndef _COM_SUN_STAR_LANG_XSERVICENAME_HPP_\n#include \n#endif\n\n#ifndef INCLUDED_RTL_MATH_HXX\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n\/\/.............................................................................\nnamespace chart\n{\n\/\/.............................................................................\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::chart2;\n\nScaleAutomatism::ScaleAutomatism( const ScaleData& rSourceScale )\n : m_fValueMinimum( 0.0 )\n , m_fValueMaximum( 0.0 )\n , m_nMaximumAutomaticMainIncrementCount(10)\n , m_aSourceScale( rSourceScale )\n , m_aSourceIncrement()\n , m_aSourceSubIncrementList()\n{\n ::rtl::math::setNan( &m_fValueMinimum );\n ::rtl::math::setNan( &m_fValueMaximum );\n}\n\nScaleAutomatism::ScaleAutomatism( const ScaleData& rSourceScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n : m_fValueMinimum( 0.0 )\n , m_fValueMaximum( 0.0 )\n , m_nMaximumAutomaticMainIncrementCount(9)\n , m_aSourceScale( rSourceScale )\n , m_aSourceIncrement( rSourceIncrement )\n , m_aSourceSubIncrementList( rSourceSubIncrementList )\n{\n ::rtl::math::setNan( &m_fValueMinimum );\n ::rtl::math::setNan( &m_fValueMaximum );\n}\n\nScaleAutomatism::~ScaleAutomatism()\n{\n}\n\n\/\/@todo these method should become part of the scaling interface and implementation somehow\n\/\/@todo problem with outparamters at api\nExplicitIncrementData getExplicitIncrementAndScaleForLogarithm(\n bool bChangeMinimumToIncrementRythm, bool bChangeMaximumToIncrementRythm\n , sal_Int32 nMaximumAutomaticMainIncrementCount\n , ExplicitScaleData& rExplicitScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n{\n \/\/minimum and maximum of the ExplicitScaleData may be changed\n \/\/to suiteable values if allowed\n \/\/but they will definitly be changed if they are out of allowed borders\n\n if( nMaximumAutomaticMainIncrementCount <= 0 )\n nMaximumAutomaticMainIncrementCount = 5;\n\n \/\/make sure that minimum and maximum are not out of allowed range\n {\n if( rExplicitScale.Maximum<=0.0 )\n rExplicitScale.Maximum = 100.0;\n if( rExplicitScale.Minimum<=0.0 )\n {\n rExplicitScale.Minimum = 0.1;\n if( rExplicitScale.Minimum >= rExplicitScale.Maximum )\n rExplicitScale.Minimum = log(rExplicitScale.Maximum)\/10.0;\n }\n if( rExplicitScale.Maximum<= rExplicitScale.Minimum )\n rExplicitScale.Maximum = rExplicitScale.Minimum + 10;\n }\n\n ExplicitIncrementData aRet;\n if(!(rSourceIncrement.PostEquidistant>>=aRet.PostEquidistant))\n {\n \/\/maybe scaling dependent\n aRet.PostEquidistant = sal_True;\n }\n if(!(rSourceIncrement.Distance>>=aRet.Distance))\n {\n \/\/autocalculate the distance\n if(aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n {\n double fRange = rExplicitScale.Scaling->doScaling( rExplicitScale.Maximum )\n - rExplicitScale.Scaling->doScaling( rExplicitScale.Minimum );\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n \/\/make a fine value out of fSlice now:\n \/\/only integers are reasonable as distance values\n sal_Int32 nDistance = static_cast(fSlice);\n if(nDistance<=0)\n nDistance=1;\n aRet.Distance = nDistance;\n }\n else\n {\n \/\/@todo this was not tested\n double fRange = rExplicitScale.Maximum - rExplicitScale.Minimum;\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n \/\/make a fine value out of fSlice now:\n double fSliceMagnitude = pow ( (double)10, floor (log10 (fSlice)));\n aRet.Distance = static_cast(fSlice\/fSliceMagnitude)*fSliceMagnitude;\n }\n }\n\n if(!(rSourceIncrement.BaseValue>>=aRet.BaseValue))\n {\n \/\/scaling dependent\n \/\/@maybe todo is this default also plotter dependent ??\n aRet.BaseValue = 1.0;\n }\n else if( aRet.BaseValue<=0.0 ) \/\/make sure that BaseValue is not out of allowed ranges\n aRet.BaseValue = 1.0;\n\n if(bChangeMinimumToIncrementRythm)\n {\n double fMin = rExplicitScale.Minimum;\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMin = rExplicitScale.Scaling->doScaling(fMin);\n\n fMin = TickmarkHelper::getMinimumAtIncrement( fMin, aRet );\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMin = rExplicitScale.Scaling->getInverseScaling()->doScaling(fMin);\n rExplicitScale.Minimum = fMin;\n\n if( rExplicitScale.Minimum<=0.0 )\n {\n rExplicitScale.Minimum = 0.1;\n if( rExplicitScale.Minimum >= rExplicitScale.Maximum )\n rExplicitScale.Minimum = log(rExplicitScale.Maximum)\/10.0;\n }\n }\n if(bChangeMaximumToIncrementRythm)\n {\n double fMax = rExplicitScale.Maximum;\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMax = rExplicitScale.Scaling->doScaling(fMax);\n fMax = TickmarkHelper::getMaximumAtIncrement( fMax, aRet );\n if( aRet.PostEquidistant && rExplicitScale.Scaling.is() )\n fMax = rExplicitScale.Scaling->getInverseScaling()->doScaling(fMax);\n rExplicitScale.Maximum = fMax;\n }\n \/\/---------------------------------------------------------------\n \/\/fill explicit sub increment\n sal_Int32 nSubCount = rSourceSubIncrementList.getLength();\n aRet.SubIncrements.realloc(nSubCount);\n for( sal_Int32 nN=0; nN>=rExplicitSubIncrement.IntervalCount))\n {\n \/\/scaling dependent\n \/\/@todo autocalculate IntervalCount dependent on MainIncrement and scaling\n rExplicitSubIncrement.IntervalCount = 5;\n }\n if(!(rSubIncrement.PostEquidistant>>=rExplicitSubIncrement.PostEquidistant))\n {\n \/\/scaling dependent\n rExplicitSubIncrement.PostEquidistant = sal_False;\n }\n }\n return aRet;\n}\n\nExplicitIncrementData getExplicitIncrementAndScaleForLinear(\n bool bChangeMinimumToIncrementRythm, bool bChangeMaximumToIncrementRythm\n , sal_Int32 nMaximumAutomaticMainIncrementCount\n , ExplicitScaleData& rExplicitScale\n , const IncrementData& rSourceIncrement\n , const uno::Sequence< SubIncrement >& rSourceSubIncrementList )\n{\n \/\/minimum and maximum of the ExplicitScaleData may be changed\n \/\/to suiteable values if allowed\n \/\/but they will definitly be changed if they are out of allowed borders\n\n if( nMaximumAutomaticMainIncrementCount <= 0 )\n nMaximumAutomaticMainIncrementCount = 5;\n\n \/\/make sure that minimum and maximum have allowed values\n {\n if( rExplicitScale.Maximum<= rExplicitScale.Minimum )\n rExplicitScale.Maximum = rExplicitScale.Minimum + 10;\n }\n\n ExplicitIncrementData aRet;\n if(!(rSourceIncrement.PostEquidistant>>=aRet.PostEquidistant))\n {\n \/\/maybe scaling dependent\n aRet.PostEquidistant = sal_True;\n }\n if(!(rSourceIncrement.Distance>>=aRet.Distance))\n {\n \/\/autocalculate the distance\n double fRange = rExplicitScale.Maximum - rExplicitScale.Minimum;\n double fSlice = fRange\/nMaximumAutomaticMainIncrementCount;\n\n \/\/make a fine value out of fSlice now:\n double fSliceMagnitude = pow ( (double)10, floor (log10 (fSlice)));\n fSlice \/= fSliceMagnitude;\n if(fSlice<=1.0)\n fSlice=1.0;\n else if( fSlice<= 2.0 )\n fSlice=2.0;\n else if( fSlice<= 2.5 )\n fSlice=2.5;\n else if( fSlice<= 5.0)\n fSlice=5.0;\n else\n fSlice=10.0;\n\n aRet.Distance = fSlice*fSliceMagnitude;\n }\n if(!(rSourceIncrement.BaseValue>>=aRet.BaseValue))\n {\n \/\/@maybe todo is this default also plotter dependent ??\n aRet.BaseValue = 0.0;\n }\n if(bChangeMinimumToIncrementRythm)\n {\n rExplicitScale.Minimum = TickmarkHelper::getMinimumAtIncrement( rExplicitScale.Minimum, aRet );\n }\n if(bChangeMaximumToIncrementRythm)\n {\n rExplicitScale.Maximum = TickmarkHelper::getMaximumAtIncrement( rExplicitScale.Maximum, aRet );\n }\n \/\/---------------------------------------------------------------\n \/\/fill explicit sub increment\n sal_Int32 nSubCount = rSourceSubIncrementList.getLength();\n aRet.SubIncrements.realloc(nSubCount);\n for( sal_Int32 nN=0; nN>=rExplicitSubIncrement.IntervalCount))\n {\n \/\/scaling dependent\n \/\/@todo autocalculate IntervalCount dependent on MainIncrement and scaling\n rExplicitSubIncrement.IntervalCount = 2;\n }\n if(!(rSubIncrement.PostEquidistant>>=rExplicitSubIncrement.PostEquidistant))\n {\n \/\/scaling dependent\n rExplicitSubIncrement.PostEquidistant = sal_False;\n }\n }\n return aRet;\n}\n\nvoid ScaleAutomatism::calculateExplicitScaleAndIncrement(\n ExplicitScaleData& rExplicitScale\n , ExplicitIncrementData& rExplicitIncrement )\n{\n \/\/---------------------------------------------------------------\n \/\/fill explicit scale\n bool bChangeMinimumToIncrementRythm=false, bChangeMaximumToIncrementRythm=false;\n if(!(m_aSourceScale.Minimum>>=rExplicitScale.Minimum))\n {\n \/\/autocalculate the minimum in first iteration\n \/\/the increment is considered below\n if( !::rtl::math::isNan(m_fValueMinimum) )\n rExplicitScale.Minimum = m_fValueMinimum;\n else\n rExplicitScale.Minimum = 0.0;\/\/@todo get Minimum from scsaling or from plotter????\n bChangeMinimumToIncrementRythm = true;\n }\n if(!(m_aSourceScale.Maximum>>=rExplicitScale.Maximum))\n {\n \/\/autocalculate the maximum in first iteration\n \/\/the increment is considered below\n if( !::rtl::math::isNan(m_fValueMaximum) )\n rExplicitScale.Maximum = m_fValueMaximum;\n else\n rExplicitScale.Maximum = 10.0;\/\/@todo get Maximum from scaling or from plotter????\n bChangeMaximumToIncrementRythm=true;\n }\n rExplicitScale.Orientation = m_aSourceScale.Orientation;\/\/AxisOrientation_MATHEMATICAL;\n rExplicitScale.Scaling = m_aSourceScale.Scaling;\n rExplicitScale.Breaks = m_aSourceScale.Breaks;\n \/\/---------------------------------------------------------------\n \/\/fill explicit increment\n \/\/minimum and maximum of the ExplicitScaleData may be changed if allowed\n uno::Reference< lang::XServiceName > xServiceName( rExplicitScale.Scaling, uno::UNO_QUERY );\n bool bIsLogarithm = ( xServiceName.is() && (xServiceName->getServiceName()).equals(\n C2U( \"com.sun.star.chart2.LogarithmicScaling\" )));\n if(bIsLogarithm)\n rExplicitIncrement = getExplicitIncrementAndScaleForLogarithm( bChangeMinimumToIncrementRythm, bChangeMaximumToIncrementRythm, m_nMaximumAutomaticMainIncrementCount\n , rExplicitScale, m_aSourceIncrement, m_aSourceSubIncrementList );\n else\n rExplicitIncrement = getExplicitIncrementAndScaleForLinear( bChangeMinimumToIncrementRythm, bChangeMaximumToIncrementRythm, m_nMaximumAutomaticMainIncrementCount\n , rExplicitScale, m_aSourceIncrement, m_aSourceSubIncrementList );\n}\n\n\/\/.............................................................................\n} \/\/namespace chart\n\/\/.............................................................................\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev \n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#include \n#else\n#include \/* PATH_MAX *\/\n#include \n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n Magic == file_magic::pecoff_executable\n#else\n Magic == file_magic::elf_shared_object\n#endif\n#elif defined(LLVM_ON_WIN32)\n\t\t(Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n static bool initialized = false;\n static std::vector SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());\n sys_path += ':'; \n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n std::vector::const_iterator it = SysPaths.begin();\n while ((++it) != SysPaths.end()) {\n Paths.push_back((*it).c_str());\n }\n#ifdef __APPLE__\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n SearchPaths.push_back(\".\"); \/\/ search also in the current directory\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString FullPath(\"\");\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(FullPath.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair insRes\n = m_DyLibs.insert(std::pair(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast(handle));\n }\n} \/\/ end namespace cling\nUse hard-coded system library path on cygwin\/gcc\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/ version: $Id$\n\/\/ author: Vassil Vassilev \n\/\/------------------------------------------------------------------------------\n\n#include \"cling\/Interpreter\/DynamicLibraryManager.h\"\n#include \"cling\/Interpreter\/InvocationOptions.h\"\n\n#include \"llvm\/Support\/DynamicLibrary.h\"\n#include \"llvm\/Support\/FileSystem.h\"\n#include \"llvm\/Support\/Path.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \n#include \n#include \n#include \n\n#ifdef WIN32\n#include \n#include \n#else\n#include \/* PATH_MAX *\/\n#include \n#endif\n\nnamespace cling {\n DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) \n : m_Opts(Opts) { }\n\n DynamicLibraryManager::~DynamicLibraryManager() {}\n\n static bool isSharedLib(llvm::StringRef LibName, bool& exists) {\n using namespace llvm::sys::fs;\n file_magic Magic;\n llvm::error_code Error = identify_magic(LibName, Magic);\n exists = (Error == llvm::errc::success);\n return exists &&\n#ifdef __APPLE__\n (Magic == file_magic::macho_fixed_virtual_memory_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib\n || Magic == file_magic::macho_dynamically_linked_shared_lib_stub)\n#elif defined(LLVM_ON_UNIX)\n#ifdef __CYGWIN__\n Magic == file_magic::pecoff_executable\n#else\n Magic == file_magic::elf_shared_object\n#endif\n#elif defined(LLVM_ON_WIN32)\n\t\t(Magic == file_magic::pecoff_executable)\n#else\n# error \"Unsupported platform.\"\n#endif\n ;\n }\n\n static void\n findSharedLibrary(llvm::StringRef fileStem,\n const llvm::SmallVectorImpl& Paths,\n llvm::SmallString<512>& FoundDyLib,\n bool& exists, bool& isDyLib) {\n for (llvm::SmallVectorImpl::const_iterator\n IPath = Paths.begin(), EPath = Paths.end(); IPath != EPath; ++IPath) {\n llvm::SmallString<512> ThisPath(*IPath);\n llvm::sys::path::append(ThisPath, fileStem);\n isDyLib = isSharedLib(ThisPath.str(), exists);\n if (isDyLib)\n ThisPath.swap(FoundDyLib);\n if (exists)\n return;\n }\n }\n\n#if defined(LLVM_ON_UNIX)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char* env_var = getenv(\"LD_LIBRARY_PATH\");\n#if __APPLE__\n if (!env_var)\n env_var = getenv(\"DYLD_LIBRARY_PATH\");\n if (!env_var)\n env_var = getenv(\"DYLD_FALLBACK_LIBRARY_PATH\");\n#endif\n if (env_var != 0) {\n static const char PathSeparator = ':';\n const char* at = env_var;\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n Paths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n\n if (*at != 0)\n if (llvm::sys::fs::is_directory(llvm::StringRef(at)))\n Paths.push_back(at);\n }\n#ifndef __CYGWIN__\n static bool initialized = false;\n static std::vector SysPaths;\n if (!initialized) {\n \/\/ trick to get the system search path\n std::string cmd(\"LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1\");\n FILE *pf = popen(cmd.c_str (), \"r\");\n std::string result = \"\";\n std::string sys_path = \"\";\n char buffer[128];\n while (!feof(pf)) {\n if (fgets(buffer, 128, pf) != NULL)\n result += buffer;\n }\n pclose(pf);\n std::size_t from = result.find(\"search path=\", result.find(\"(LD_LIBRARY_PATH)\"));\n std::size_t to = result.find(\"(system search path)\");\n if (from != std::string::npos && to != std::string::npos) {\n from += 12;\n sys_path = result.substr(from, to-from);\n sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end());\n sys_path += ':'; \n }\n static const char PathSeparator = ':';\n const char* at = sys_path.c_str();\n const char* delim = strchr(at, PathSeparator);\n while (delim != 0) {\n std::string tmp(at, size_t(delim-at));\n if (llvm::sys::fs::is_directory(tmp.c_str()))\n SysPaths.push_back(tmp);\n at = delim + 1;\n delim = strchr(at, PathSeparator);\n }\n initialized = true;\n }\n std::vector::const_iterator it = SysPaths.begin();\n while ((++it) != SysPaths.end()) {\n Paths.push_back((*it).c_str());\n }\n#endif\n#if defined(__APPLE__) || defined(__CYGWIN__)\n Paths.push_back(\"\/usr\/local\/lib\/\");\n Paths.push_back(\"\/usr\/X11R6\/lib\/\");\n Paths.push_back(\"\/usr\/lib\/\");\n Paths.push_back(\"\/lib\/\");\n\n Paths.push_back(\"\/lib\/x86_64-linux-gnu\/\");\n Paths.push_back(\"\/usr\/local\/lib64\/\");\n Paths.push_back(\"\/usr\/lib64\/\");\n Paths.push_back(\"\/lib64\/\");\n#endif\n }\n#elif defined(LLVM_ON_WIN32)\n static void GetSystemLibraryPaths(llvm::SmallVectorImpl& Paths) {\n char buff[MAX_PATH];\n \/\/ Generic form of C:\\Windows\\System32\n HRESULT res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_SYSTEM,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get system directory\");\n return;\n }\n Paths.push_back(buff);\n\n \/\/ Reset buff.\n buff[0] = 0;\n \/\/ Generic form of C:\\Windows\n res = SHGetFolderPathA(NULL,\n CSIDL_FLAG_CREATE | CSIDL_WINDOWS,\n NULL,\n SHGFP_TYPE_CURRENT,\n buff);\n if (res != S_OK) {\n assert(0 && \"Failed to get windows directory\");\n return;\n }\n Paths.push_back(buff);\n }\n#else\n# error \"Unsupported platform.\"\n#endif\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::tryLinker(const std::string& filename, bool permanent,\n bool isAbsolute, bool& exists,\n bool& isDyLib) {\n using namespace llvm::sys;\n exists = false;\n isDyLib = false;\n\n llvm::SmallString<512> FoundDyLib;\n\n if (isAbsolute) {\n isDyLib = isSharedLib(filename, exists);\n if (isDyLib)\n FoundDyLib = filename;\n } else {\n llvm::SmallVector\n SearchPaths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end());\n GetSystemLibraryPaths(SearchPaths);\n SearchPaths.push_back(\".\"); \/\/ search also in the current directory\n\n findSharedLibrary(filename, SearchPaths, FoundDyLib, exists, isDyLib);\n\n if (!exists) {\n \/\/ Add DyLib extension:\n llvm::SmallString<512> filenameWithExt(filename);\n#if defined(LLVM_ON_UNIX)\n#ifdef __APPLE__\n llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1;\n#endif\n static const char* DyLibExt = \".so\";\n#elif defined(LLVM_ON_WIN32)\n static const char* DyLibExt = \".dll\";\n#else\n# error \"Unsupported platform.\"\n#endif\n filenameWithExt += DyLibExt;\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n#ifdef __APPLE__\n if (!exists) {\n filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end());\n filenameWithExt += \".dylib\";\n findSharedLibrary(filenameWithExt, SearchPaths, FoundDyLib, exists,\n isDyLib);\n }\n#endif\n }\n }\n\n if (!isDyLib)\n return kLoadLibError;\n \n assert(!FoundDyLib.empty() && \"The shared lib exists but can't find it!\");\n\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n llvm::SmallString<_MAX_PATH> FullPath(\"\");\n char *res = _fullpath((char *)FullPath.data(), FoundDyLib.c_str(), _MAX_PATH);\n#else\n llvm::SmallString FullPath(\"\");\n char *res = realpath(FoundDyLib.c_str(), (char *)FullPath.data());\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): error getting real (canonical) path\\n\";\n return kLoadLibError;\n }\n FullPath.set_size(strlen(res));\n if (m_loadedLibraries.find(FullPath) != m_loadedLibraries.end())\n return kLoadLibExists;\n\n std::string errMsg;\n \/\/ TODO: !permanent case\n#if defined(LLVM_ON_WIN32)\n HMODULE dyLibHandle = LoadLibraryEx(FullPath.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES);\n errMsg = \"LoadLibraryEx: GetLastError() returned \";\n errMsg += GetLastError();\n#else\n const void* dyLibHandle = dlopen(FullPath.c_str(), RTLD_LAZY|RTLD_GLOBAL);\n if (const char* DyLibError = dlerror()) {\n errMsg = DyLibError;\n }\n#endif\n if (!dyLibHandle) {\n llvm::errs() << \"cling::Interpreter::tryLinker(): \" << errMsg << '\\n';\n return kLoadLibError;\n }\n std::pair insRes\n = m_DyLibs.insert(std::pair(dyLibHandle,\n FullPath.str()));\n if (!insRes.second)\n return kLoadLibExists;\n m_loadedLibraries.insert(FullPath);\n return kLoadLibSuccess;\n }\n\n DynamicLibraryManager::LoadLibResult\n DynamicLibraryManager::loadLibrary(const std::string& filename,\n bool permanent, bool* tryCode) {\n llvm::SmallString<128> Absolute((llvm::StringRef(filename)));\n llvm::sys::fs::make_absolute(Absolute);\n bool isAbsolute = filename == Absolute.c_str();\n bool exists = false;\n bool isDyLib = false;\n LoadLibResult res = tryLinker(filename, permanent, isAbsolute, exists,\n isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (exists)\n return res;\n\n if (!isAbsolute && filename.compare(0, 3, \"lib\")) {\n \/\/ try with \"lib\" prefix:\n res = tryLinker(\"lib\" + filename, permanent, false, exists, isDyLib);\n if (tryCode) {\n *tryCode = !isDyLib;\n if (isAbsolute)\n *tryCode &= exists;\n }\n if (res != kLoadLibError)\n return res;\n }\n return kLoadLibError;\n }\n\n bool\n DynamicLibraryManager::isDynamicLibraryLoaded(llvm::StringRef fullPath) const {\n \/\/ get canonical path name and check if already loaded\n#if defined(LLVM_ON_WIN32)\n char buf[_MAX_PATH];\n char *res = _fullpath(buf, fullPath.str().c_str(), _MAX_PATH);\n#else\n char buf[PATH_MAX+1];\n char *res = realpath(fullPath.str().c_str(), buf);\n#endif\n if (res == 0) {\n llvm::errs() << \"cling::Interpreter::isDynamicLibraryLoaded(): error getting real (canonical) path\\n\";\n return false;\n }\n if (m_loadedLibraries.find(buf) != m_loadedLibraries.end()) return true;\n return false;\n }\n\n void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) {\n llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast(handle));\n }\n} \/\/ end namespace cling\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nvoid getQuaternion(const iDynTree::Rotation & rot,\n iDynTree::Vector4 & quat_idyntree,\n iDynTree::Vector4 & quat_kdl,\n iDynTree::Vector4 & quat_yarp)\n{\n rot.getQuaternion(quat_idyntree);\n\n \/\/ Notice that KDL uses a imaginary\/real serialization, while we use real\/imaginary\n iDynTree::ToKDL(rot).GetQuaternion(quat_kdl(1),quat_kdl(2),quat_kdl(3),quat_kdl(0));\n\n yarp::sig::Matrix rotYarp(3,3);\n iDynTree::toYarp(rot,rotYarp);\n\n yarp::sig::Vector quat_yarp_yarp(4);\n\n quat_yarp_yarp = yarp::math::dcm2quat(rotYarp);\n\n iDynTree::toiDynTree(quat_yarp_yarp,quat_yarp);\n}\n\nvoid checkRotationToQuaternion(const iDynTree::Rotation randRot)\n{\n iDynTree::Vector4 quat_idyntree, quat_kdl, quat_yarp;\n getQuaternion(randRot,quat_idyntree,quat_kdl,quat_yarp);\n\n std::cerr << \"Quaternion converted by KDL: \" << quat_kdl.toString() << \" ( norm \" << toEigen(quat_kdl).norm() << \" ) \" << std::endl;\n std::cerr << \"Quaternion converted by YARP: \" << quat_yarp.toString() << \" ( norm \" << toEigen(quat_yarp).norm() << \" ) \" << std::endl;\n std::cerr << \"Quaternion converted by iDynTree: \" << quat_idyntree.toString() << \" ( norm \" << toEigen(quat_idyntree).norm() << \" ) \" << std::endl;\n\n \/*\n ASSERT_EQUAL_VECTOR(quat_kdl,quat_yarp);\n ASSERT_EQUAL_VECTOR(quat_idyntree,quat_kdl);\n ASSERT_EQUAL_VECTOR(quat_idyntree,quat_yarp);\n *\/\n\n \/\/ Check going back to a rotation\n iDynTree::Rotation randRotCheck = iDynTree::Rotation::RotationFromQuaternion(quat_idyntree);\n\n std::cerr << \"Original rotation:\\n\" << randRot.toString() << std::endl;\n std::cerr << \"Rotation converted back and forth from quaternion:\\n\" << randRotCheck.toString() << std::endl;\n\n\n \/\/ASSERT_EQUAL_MATRIX(randRot,randRotCheck);\n}\n\nint main()\n{\n std::cerr << \"Quaternion Consistency check \" << std::endl;\n\n\n \/\/ First we check an easy one for debugging\n checkRotationToQuaternion(iDynTree::Rotation::RPY(M_PI,0.0,0.0));\n\n \/\/ Then some random ones\n int nrOfTrials = 0;\n\n for(int i=0; i < nrOfTrials;i++)\n {\n \/\/ Create random rotation\n iDynTree::Rotation randRot = iDynTree::getRandomRotation();\n\n checkRotationToQuaternion(randRot);\n }\n\n return EXIT_SUCCESS;\n}\nAdded infrastructure for test of output ranges of component returned by getQuaternion\/*\n * Copyright (C) 2016 Fondazione Istituto Italiano di Tecnologia\n * Authors: Silvio Traversaro\n * CopyPolicy: Released under the terms of the LGPLv2.1 or later, see LGPL.TXT\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\nclass MaxMin\n{\npublic:\n double min;\n double max;\n\n MaxMin()\n {\n min = std::numeric_limits::max();\n max = -std::numeric_limits::max();\n }\n\n void update(const double newValue)\n {\n if( newValue > max )\n {\n max = newValue;\n }\n\n if( newValue < min )\n {\n min = newValue;\n }\n }\n};\n\nclass QuaternionMaxMin\n{\npublic:\n MaxMin help[4];\n\n void update(const iDynTree::Vector4 & quat)\n {\n help[0].update(quat(0));\n help[1].update(quat(1));\n help[2].update(quat(2));\n help[3].update(quat(3));\n }\n\n std::string toString()\n {\n std::stringstream ss;\n ss << \"Real part is in (\" << (help[0].min) << \" , \" << (help[0].max) << \")\" << std::endl;\n ss << \"Imag x is in (\" << (help[1].min) << \" , \" << (help[1].max) << \")\" << std::endl;\n ss << \"Imag y is in (\" << (help[2].min) << \" , \" << (help[2].max) << \")\" << std::endl;\n ss << \"Imag z is in (\" << (help[3].min) << \" , \" << (help[3].max) << \")\" << std::endl;\n\n return ss.str();\n }\n};\n\nstruct QuaternionMaxMinHelper\n{\n QuaternionMaxMin idyntree;\n QuaternionMaxMin yarp;\n QuaternionMaxMin kdl;\n};\n\nvoid getQuaternion(const iDynTree::Rotation & rot,\n iDynTree::Vector4 & quat_idyntree,\n iDynTree::Vector4 & quat_kdl,\n iDynTree::Vector4 & quat_yarp)\n{\n rot.getQuaternion(quat_idyntree);\n\n \/\/ Notice that KDL uses a imaginary\/real serialization, while we use real\/imaginary\n iDynTree::ToKDL(rot).GetQuaternion(quat_kdl(1),quat_kdl(2),quat_kdl(3),quat_kdl(0));\n\n yarp::sig::Matrix rotYarp(3,3);\n iDynTree::toYarp(rot,rotYarp);\n\n yarp::sig::Vector quat_yarp_yarp(4);\n\n quat_yarp_yarp = yarp::math::dcm2quat(rotYarp);\n\n iDynTree::toiDynTree(quat_yarp_yarp,quat_yarp);\n}\n\nvoid checkRotationToQuaternion(const iDynTree::Rotation randRot, QuaternionMaxMinHelper & helper, bool verbose)\n{\n iDynTree::Vector4 quat_idyntree, quat_kdl, quat_yarp;\n getQuaternion(randRot,quat_idyntree,quat_kdl,quat_yarp);\n\n if( verbose )\n {\n std::cerr << \"Quaternion converted by KDL: \" << quat_kdl.toString() << \" ( norm \" << toEigen(quat_kdl).norm() << \" ) \" << std::endl;\n std::cerr << \"Quaternion converted by YARP: \" << quat_yarp.toString() << \" ( norm \" << toEigen(quat_yarp).norm() << \" ) \" << std::endl;\n std::cerr << \"Quaternion converted by iDynTree: \" << quat_idyntree.toString() << \" ( norm \" << toEigen(quat_idyntree).norm() << \" ) \" << std::endl;\n }\n\n \/*\n ASSERT_EQUAL_VECTOR(quat_kdl,quat_yarp);\n ASSERT_EQUAL_VECTOR(quat_idyntree,quat_kdl);\n ASSERT_EQUAL_VECTOR(quat_idyntree,quat_yarp);\n *\/\n\n \/\/ Check going back to a rotation\n iDynTree::Rotation randRotCheck = iDynTree::Rotation::RotationFromQuaternion(quat_idyntree);\n\n if( verbose )\n {\n std::cerr << \"Original rotation:\\n\" << randRot.toString() << std::endl;\n std::cerr << \"Rotation converted back and forth from quaternion:\\n\" << randRotCheck.toString() << std::endl;\n }\n\n\n \/\/ASSERT_EQUAL_MATRIX(randRot,randRotCheck);\n\n \/\/ Check range\n helper.idyntree.update(quat_idyntree);\n helper.kdl.update(quat_kdl);\n helper.yarp.update(quat_yarp);\n}\n\nint main()\n{\n std::cerr << \"Quaternion Consistency check \" << std::endl;\n\n \/\/ Check ranges of the output quaternions\n QuaternionMaxMinHelper rangeHelper;\n\n \/\/ First we check an easy one for debugging\n checkRotationToQuaternion(iDynTree::Rotation::RPY(M_PI,0.0,0.0),rangeHelper,false);\n\n \/\/ Then we check two rotation, to see if any implementation suffer of the\n \/\/ discontinuities reported in http:\/\/it.mathworks.com\/matlabcentral\/answers\/164746-bug-in-dcm2quat-function\n iDynTree::Rotation T_1059 = iDynTree::Rotation(0.4218,-0.3220,0.8475,\n 0.7299,-0.4339,-0.5282,\n 0.5378,0.8414,0.0520);\n\n iDynTree::Rotation T_1060 = iDynTree::Rotation(0.4312,-0.2603,0.8639,\n 0.7289,-0.4637,-0.5036,\n 0.5317,0.8469,-0.0102);\n\n checkRotationToQuaternion(T_1059,rangeHelper,true);\n checkRotationToQuaternion(T_1060,rangeHelper,true);\n\n \/\/ Then some random ones\n int nrOfTrials = 100000;\n\n\n for(int i=0; i < nrOfTrials;i++)\n {\n \/\/ Create random rotation\n iDynTree::Rotation randRot = iDynTree::getRandomRotation();\n\n checkRotationToQuaternion(randRot,rangeHelper,false);\n }\n\n std::cerr << \"KDL quaternion ranges: \" << std::endl;\n std::cerr << rangeHelper.kdl.toString();\n\n std::cerr << \"YARP quaternion ranges: \" << std::endl;\n std::cerr << rangeHelper.yarp.toString();\n\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\nextern \"C\" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {\n (void)self;\n const char *hash = getenv(\"OSTREE_HASH\");\n return ostree_deployment_new(0, \"dummy-os\", hash, 1, hash, 1);\n}\n\nextern \"C\" const char *ostree_deployment_get_csum(OstreeDeployment *self) {\n (void)self;\n return getenv(\"OSTREE_HASH\");\n}\naktualizr-lite: Fix mem leak in test code#include \n#include \n\nextern \"C\" OstreeDeployment *ostree_sysroot_get_booted_deployment(OstreeSysroot *self) {\n (void)self;\n static OstreeDeployment *deployment;\n\n if (deployment != nullptr) {\n return deployment;\n }\n\n const char *hash = getenv(\"OSTREE_HASH\");\n deployment = ostree_deployment_new(0, \"dummy-os\", hash, 1, hash, 1);\n return deployment;\n}\n\nextern \"C\" const char *ostree_deployment_get_csum(OstreeDeployment *self) {\n (void)self;\n return getenv(\"OSTREE_HASH\");\n}\n<|endoftext|>"} {"text":"\/** \\file generate_subscription_packets.cc\n * \\brief Imports data from Zeder and writes a subscription packets defintion file.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n * \\copyright 2020-2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zeder.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"packet_definition_config_file packet_subscriptions_output\\n\"\n \"\\tFor the documentation of the input config file, please see data\/generate_subscription_packets.README.\");\n}\n\n\n\/\/ Return true if an entry of \"class_list\" equals one of the vertical-bar-separated values of \"expected_values_str.\"\nbool FoundExpectedClassValue(const std::string &expected_values_str, const std::string &class_list_str) {\n std::vector expected_values;\n StringUtil::Split(expected_values_str, '|', &expected_values);\n\n std::vector class_list;\n StringUtil::SplitThenTrimWhite(class_list_str, ',', &class_list);\n\n for (const auto &class_str : class_list) {\n if (std::find_if(expected_values.cbegin(), expected_values.cend(),\n [&class_str](auto &expected_value) { return ::strcasecmp(class_str.c_str(), expected_value.c_str()) == 0; }) != expected_values.cend())\n return true;\n }\n return false;\n}\n\n\nbool IncludeJournal(const Zeder::Entry &journal, const IniFile::Section &filter_section) {\n for (const auto &entry : filter_section) {\n if (entry.name_.empty() or entry.name_ == \"description\")\n continue;\n\n const std::string &zeder_column_name(entry.name_);\n const auto column_value(StringUtil::TrimWhite(journal.lookup(zeder_column_name == \"except_class\" ? \"class\" : zeder_column_name)));\n if (column_value.empty())\n {\n LOG_INFO(\"\\tcolumn \" + zeder_column_name + \" was empty!\");\n return false;\n\n }\n\n const bool found_it(FoundExpectedClassValue(entry.value_, column_value));\n if (zeder_column_name == \"except_class\") {\n if (found_it)\n return false;\n } else if (not found_it)\n return false;\n }\n\n return true;\n}\n\n\n\/\/ Please note that Zeder PPN entries are separated by spaces and, unlike what the column names \"print_ppn\" and\n\/\/ \"online_ppn\" imply may in rare cases contain space-separated lists of PPN's.\nvoid ProcessPPNs(const std::string &ppns, std::set * const bundle_ppns) {\n std::vector individual_ppns;\n StringUtil::Split(ppns, ' ', &individual_ppns);\n bundle_ppns->insert(individual_ppns.cbegin(), individual_ppns.cend());\n}\n\n\nstd::string EscapeDoubleQuotes(const std::string &s) {\n std::string escaped_s;\n escaped_s.reserve(s.size());\n\n for (const char ch : s) {\n if (ch == '\"' or ch == '\\\\')\n escaped_s += '\\\\';\n escaped_s += ch;\n }\n\n return escaped_s;\n}\n\n\nvoid GenerateBundleDefinition(const Zeder::SimpleZeder &zeder, const std::string &bundle_instances,\n const IniFile::Section §ion, File * const output_file)\n{\n unsigned included_journal_count(0);\n std::set bundle_ppns; \/\/ We use a std::set because it is automatically being sorted for us.\n bool contains_print(false);\n bool contains_online(false);\n for (const auto &journal : zeder) {\n if (journal.empty() or not IncludeJournal(journal, section))\n continue;\n\n ++included_journal_count;\n const auto print_ppns(journal.lookup(\"pppn\"));\n const auto online_ppns(journal.lookup(\"eppn\"));\n\n if (print_ppns.empty() and online_ppns.empty()) {\n --included_journal_count;\n LOG_WARNING(\"Zeder entry #\" + std::to_string(journal.getId()) + \" is missing print and online PPN's!\");\n continue;\n }\n\n \/\/ Prefer online journals to print journals:\n \/\/ At the moment the logic is electronic over print\n \/\/ in discussion if this should be changed (if so, publication year range has to be considered)\n if (not online_ppns.empty()) {\n ProcessPPNs(online_ppns, &bundle_ppns);\n contains_online = true;\n } else {\n ProcessPPNs(print_ppns, &bundle_ppns);\n contains_print = true;\n }\n }\n\n if (bundle_ppns.empty())\n LOG_WARNING(\"No bundle generated for \\\"\" + section.getSectionName() + \"\\\" because there were no matching entries in Zeder!\");\n else {\n (*output_file) << '[' << section.getSectionName() << \"]\\n\";\n (*output_file) << \"display_name = \\\"\" << EscapeDoubleQuotes(section.getSectionName()) << \"\\\"\\n\";\n const auto description(section.find(\"description\"));\n if (description != section.end())\n (*output_file) << \"description = \\\"\" << EscapeDoubleQuotes(description->value_) << \"\\\"\\n\";\n (*output_file) << \"instances = \\\"\" << bundle_instances << \"\\\"\\n\";\n std::string media_type;\n if (contains_online) \n if (contains_print)\n media_type = \"online_and_print\";\n else\n media_type = \"online\";\n else\n media_type = \"print\";\n (*output_file) << \"media_type = \\\"\" << media_type << \"\\\"\\n\";\n (*output_file) << \"ppns = \" << StringUtil::Join(bundle_ppns, ',') << '\\n';\n (*output_file) << '\\n';\n }\n\n LOG_INFO(\"included \" + std::to_string(included_journal_count) + \" journal(s) with \" + std::to_string(bundle_ppns.size())\n + \" PPN's in the bundle for \\\"\" + section.getSectionName() + \"\\\".\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n Usage();\n\n const IniFile packet_definitions_ini_file(argv[1]);\n const auto zeder_instance(packet_definitions_ini_file.getString(\"\", \"zeder_instance\"));\n if (zeder_instance != \"ixtheo\" and zeder_instance != \"relbib\")\n LOG_ERROR(\"zeder_instance in \\\"\" + packet_definitions_ini_file.getFilename()\n + \"\\\" must be either \\\"ixtheo\\\" or \\\"relbib\\\"!\");\n\n const Zeder::SimpleZeder zeder(zeder_instance == \"ixtheo\" ? Zeder::IXTHEO : Zeder::KRIMDOK);\n if (not zeder)\n LOG_ERROR(\"can't connect to the Zeder MySQL server!\");\n if (unlikely(zeder.empty()))\n LOG_ERROR(\"found no Zeder entries matching any of our requested columns!\"\n \" (This *should* not happen as we included the column ID!)\");\n\n const auto bundle_instances(packet_definitions_ini_file.getString(\"\", \"bundle_instances\"));\n\n const auto bundle_definitions_output_file(FileUtil::OpenOutputFileOrDie(argv[2]));\n for (const auto §ion : packet_definitions_ini_file) {\n if (section.getSectionName().empty())\n continue; \/\/ Skip the global section.\n GenerateBundleDefinition(zeder, bundle_instances, section, bundle_definitions_output_file.get());\n }\n\n return EXIT_SUCCESS;\n}\ngenerate_subscription_packets.cc: Change error message related to Zeder connection\/** \\file generate_subscription_packets.cc\n * \\brief Imports data from Zeder and writes a subscription packets defintion file.\n * \\author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de)\n * \\copyright 2020-2021 Universitätsbibliothek Tübingen. All rights reserved.\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n#include \n#include \"Compiler.h\"\n#include \"FileUtil.h\"\n#include \"IniFile.h\"\n#include \"StringUtil.h\"\n#include \"util.h\"\n#include \"Zeder.h\"\n\n\nnamespace {\n\n\n[[noreturn]] void Usage() {\n ::Usage(\"packet_definition_config_file packet_subscriptions_output\\n\"\n \"\\tFor the documentation of the input config file, please see data\/generate_subscription_packets.README.\");\n}\n\n\n\/\/ Return true if an entry of \"class_list\" equals one of the vertical-bar-separated values of \"expected_values_str.\"\nbool FoundExpectedClassValue(const std::string &expected_values_str, const std::string &class_list_str) {\n std::vector expected_values;\n StringUtil::Split(expected_values_str, '|', &expected_values);\n\n std::vector class_list;\n StringUtil::SplitThenTrimWhite(class_list_str, ',', &class_list);\n\n for (const auto &class_str : class_list) {\n if (std::find_if(expected_values.cbegin(), expected_values.cend(),\n [&class_str](auto &expected_value) { return ::strcasecmp(class_str.c_str(), expected_value.c_str()) == 0; }) != expected_values.cend())\n return true;\n }\n return false;\n}\n\n\nbool IncludeJournal(const Zeder::Entry &journal, const IniFile::Section &filter_section) {\n for (const auto &entry : filter_section) {\n if (entry.name_.empty() or entry.name_ == \"description\")\n continue;\n\n const std::string &zeder_column_name(entry.name_);\n const auto column_value(StringUtil::TrimWhite(journal.lookup(zeder_column_name == \"except_class\" ? \"class\" : zeder_column_name)));\n if (column_value.empty())\n {\n LOG_INFO(\"\\tcolumn \" + zeder_column_name + \" was empty!\");\n return false;\n\n }\n\n const bool found_it(FoundExpectedClassValue(entry.value_, column_value));\n if (zeder_column_name == \"except_class\") {\n if (found_it)\n return false;\n } else if (not found_it)\n return false;\n }\n\n return true;\n}\n\n\n\/\/ Please note that Zeder PPN entries are separated by spaces and, unlike what the column names \"print_ppn\" and\n\/\/ \"online_ppn\" imply may in rare cases contain space-separated lists of PPN's.\nvoid ProcessPPNs(const std::string &ppns, std::set * const bundle_ppns) {\n std::vector individual_ppns;\n StringUtil::Split(ppns, ' ', &individual_ppns);\n bundle_ppns->insert(individual_ppns.cbegin(), individual_ppns.cend());\n}\n\n\nstd::string EscapeDoubleQuotes(const std::string &s) {\n std::string escaped_s;\n escaped_s.reserve(s.size());\n\n for (const char ch : s) {\n if (ch == '\"' or ch == '\\\\')\n escaped_s += '\\\\';\n escaped_s += ch;\n }\n\n return escaped_s;\n}\n\n\nvoid GenerateBundleDefinition(const Zeder::SimpleZeder &zeder, const std::string &bundle_instances,\n const IniFile::Section §ion, File * const output_file)\n{\n unsigned included_journal_count(0);\n std::set bundle_ppns; \/\/ We use a std::set because it is automatically being sorted for us.\n bool contains_print(false);\n bool contains_online(false);\n for (const auto &journal : zeder) {\n if (journal.empty() or not IncludeJournal(journal, section))\n continue;\n\n ++included_journal_count;\n const auto print_ppns(journal.lookup(\"pppn\"));\n const auto online_ppns(journal.lookup(\"eppn\"));\n\n if (print_ppns.empty() and online_ppns.empty()) {\n --included_journal_count;\n LOG_WARNING(\"Zeder entry #\" + std::to_string(journal.getId()) + \" is missing print and online PPN's!\");\n continue;\n }\n\n \/\/ Prefer online journals to print journals:\n \/\/ At the moment the logic is electronic over print\n \/\/ in discussion if this should be changed (if so, publication year range has to be considered)\n if (not online_ppns.empty()) {\n ProcessPPNs(online_ppns, &bundle_ppns);\n contains_online = true;\n } else {\n ProcessPPNs(print_ppns, &bundle_ppns);\n contains_print = true;\n }\n }\n\n if (bundle_ppns.empty())\n LOG_WARNING(\"No bundle generated for \\\"\" + section.getSectionName() + \"\\\" because there were no matching entries in Zeder!\");\n else {\n (*output_file) << '[' << section.getSectionName() << \"]\\n\";\n (*output_file) << \"display_name = \\\"\" << EscapeDoubleQuotes(section.getSectionName()) << \"\\\"\\n\";\n const auto description(section.find(\"description\"));\n if (description != section.end())\n (*output_file) << \"description = \\\"\" << EscapeDoubleQuotes(description->value_) << \"\\\"\\n\";\n (*output_file) << \"instances = \\\"\" << bundle_instances << \"\\\"\\n\";\n std::string media_type;\n if (contains_online)\n if (contains_print)\n media_type = \"online_and_print\";\n else\n media_type = \"online\";\n else\n media_type = \"print\";\n (*output_file) << \"media_type = \\\"\" << media_type << \"\\\"\\n\";\n (*output_file) << \"ppns = \" << StringUtil::Join(bundle_ppns, ',') << '\\n';\n (*output_file) << '\\n';\n }\n\n LOG_INFO(\"included \" + std::to_string(included_journal_count) + \" journal(s) with \" + std::to_string(bundle_ppns.size())\n + \" PPN's in the bundle for \\\"\" + section.getSectionName() + \"\\\".\");\n}\n\n\n} \/\/ unnamed namespace\n\n\nint Main(int argc, char *argv[]) {\n if (argc != 3)\n Usage();\n\n const IniFile packet_definitions_ini_file(argv[1]);\n const auto zeder_instance(packet_definitions_ini_file.getString(\"\", \"zeder_instance\"));\n if (zeder_instance != \"ixtheo\" and zeder_instance != \"relbib\")\n LOG_ERROR(\"zeder_instance in \\\"\" + packet_definitions_ini_file.getFilename()\n + \"\\\" must be either \\\"ixtheo\\\" or \\\"relbib\\\"!\");\n\n const Zeder::SimpleZeder zeder(zeder_instance == \"ixtheo\" ? Zeder::IXTHEO : Zeder::KRIMDOK);\n if (not zeder)\n LOG_ERROR(\"can't connect to Zeder!\");\n if (unlikely(zeder.empty()))\n LOG_ERROR(\"found no Zeder entries matching any of our requested columns!\"\n \" (This *should* not happen as we included the column ID!)\");\n\n const auto bundle_instances(packet_definitions_ini_file.getString(\"\", \"bundle_instances\"));\n\n const auto bundle_definitions_output_file(FileUtil::OpenOutputFileOrDie(argv[2]));\n for (const auto §ion : packet_definitions_ini_file) {\n if (section.getSectionName().empty())\n continue; \/\/ Skip the global section.\n GenerateBundleDefinition(zeder, bundle_instances, section, bundle_definitions_output_file.get());\n }\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \"setupwizard_cli.h\"\n\nWARNINGS_DISABLE\n#include \n#include \n#include \n#include \n\n#include \"ui_setupwizard_cli.h\"\nWARNINGS_ENABLE\n\n#include \n#include \n\n#include \"tasks-defs.h\"\n#include \"taskstatus.h\"\n#include \"utils.h\"\n\nCliPage::CliPage(QWidget *parent)\n : TWizardPage(parent), _ui(new Ui::CliPage), _problemOccurred(false)\n{\n _ui->setupUi(this);\n\n \/\/ We only want to expand the widget if there's a problem.\n _ui->cliAdvancedWidget->hide();\n _ui->cliAdvancedButton->setChecked(false);\n\n \/\/ Basic operation on this page.\n connect(_ui->cliAdvancedButton, &QPushButton::toggled,\n _ui->cliAdvancedWidget, &QWidget::setVisible);\n\n \/\/ A config field changed.\n connect(_ui->cliPathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::tarsnapPathChanged);\n connect(_ui->cachePathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::tarsnapCacheChanged);\n connect(_ui->appdataPathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::appDataDirChanged);\n}\n\nCliPage::~CliPage()\n{\n delete _ui;\n}\n\nvoid CliPage::initializePage()\n{\n TWizardPage::initializePage();\n\n \/\/ CLI path.\n QString tarsnapPath = Utils::findTarsnapClientInPath(\"\", true);\n _ui->cliPathLineBrowse->setText(tarsnapPath);\n if(tarsnapPath.isEmpty())\n {\n \/\/ Trigger this manually, because the automatic connection\n \/\/ won't trigger it's blank.\n tarsnapPathChanged(tarsnapPath);\n }\n\n \/\/\/ Cache dir.\n QString tarsnapCacheDir =\n QStandardPaths::writableLocation(QStandardPaths::CacheLocation);\n if(ensureDirExists(tarsnapCacheDir))\n _ui->cachePathLineBrowse->setText(tarsnapCacheDir);\n\n \/\/ App Data dir.\n QString appDataDir = QStandardPaths::writableLocation(APPDATA);\n if(ensureDirExists(appDataDir))\n _ui->appdataPathLineBrowse->setText(appDataDir);\n}\n\nbool CliPage::checkComplete()\n{\n \/\/ Check the remaining items.\n TSettings settings;\n\n \/\/ Do we have a valid version number? (This is the last piece of config.)\n if(!settings.contains(\"tarsnap\/version\"))\n return setProceedButton(false);\n\n \/\/ Do we have everything else? (Double-check; almost certainly not needed.)\n if((!settings.contains(\"tarsnap\/path\"))\n || (!settings.contains(\"tarsnap\/cache\"))\n || (!settings.contains(\"app\/app_data\")))\n return setProceedButton(false);\n\n _problemOccurred = false;\n _ui->cliValidationLabel->clear();\n return setProceedButton(true);\n}\n\nvoid CliPage::reportError(const QString &text)\n{\n _ui->cliValidationLabel->messageError(text);\n _ui->cliAdvancedButton->setChecked(true);\n setProceedButton(false);\n _problemOccurred = true;\n}\n\nvoid CliPage::tarsnapCacheChanged(const QString &text)\n{\n \/\/ Clear previous setting.\n TSettings settings;\n settings.remove(\"tarsnap\/cache\");\n\n if(text.isEmpty())\n {\n reportError(tr(\"Empty Tarsnap cache directory set.\"));\n return;\n }\n\n QString tarsnapCacheDir = Utils::validateTarsnapCache(text);\n if(tarsnapCacheDir.isEmpty())\n {\n reportError(tr(\"Invalid Tarsnap cache directory set.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"tarsnap\/cache\", tarsnapCacheDir);\n checkComplete();\n}\n\nvoid CliPage::appDataDirChanged(const QString &text)\n{\n \/\/ Clear previous setting.\n TSettings settings;\n settings.remove(\"app\/app_data\");\n\n if(text.isEmpty())\n {\n reportError(tr(\"Empty App data directory set.\"));\n return;\n }\n\n QString appDataDir = Utils::validateAppDataDir(text);\n if(appDataDir.isEmpty())\n {\n reportError(tr(\"Invalid App data directory set.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"app\/app_data\", appDataDir);\n checkComplete();\n}\n\nvoid CliPage::tarsnapPathChanged(const QString &text)\n{\n \/\/ Clear previous settings.\n TSettings settings;\n settings.remove(\"tarsnap\/path\");\n settings.remove(\"tarsnap\/version\");\n\n if(text.isEmpty())\n {\n reportError(tr(\"Empty Tarsnap directory set.\"));\n return;\n }\n\n QString tarsnapDir = Utils::findTarsnapClientInPath(text, true);\n if(tarsnapDir.isEmpty())\n {\n reportError(tr(\"Tarsnap utilities not found. Visit \"\n \"tarsnap.com<\/a>\"\n \" for help with acquiring them.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"tarsnap\/path\", tarsnapDir);\n emit tarsnapVersionRequested();\n checkComplete();\n}\n\nvoid CliPage::tarsnapVersionResponse(TaskStatus status, QString versionString)\n{\n TSettings settings;\n\n \/\/ Sanity check.\n if(versionString.isEmpty())\n status = TaskStatus::Failed;\n\n \/\/ Handle response.\n switch(status)\n {\n case TaskStatus::Completed:\n \/\/ Record value\n settings.setValue(\"tarsnap\/version\", versionString);\n \/\/ Auto-focus on \"Next\" if the user isn't manually changing things.\n if(checkComplete() && !_problemOccurred)\n _ui->nextButton->setFocus();\n \/\/ Display message (after checkComplete, which can clear the label).\n _ui->cliValidationLabel->messageNormal(\n tr(\"Tarsnap CLI version \") + versionString + tr(\" detected. ✔\"));\n break;\n case TaskStatus::VersionTooLow:\n \/\/ Don't record the too-low version number.\n reportError(\n tr(\"Tarsnap CLI version \") + versionString\n + tr(\" too low; must be at least %1\").arg(TARSNAP_MIN_VERSION));\n break;\n case TaskStatus::Failed:\n reportError(tr(\"Error retrieving Tarsnap CLI verison\"));\n break;\n default:\n break;\n }\n}\n\nbool CliPage::ensureDirExists(const QString &dirname)\n{\n \/\/ Create directory (if needed).\n if(QDir().mkpath(dirname))\n return true;\n else\n {\n QMessageBox::critical(this, tr(\"Could not create directory\"),\n tr(\"Could not create directory\") + \": \"\n + dirname);\n return false;\n }\n}\nSetupWizard CLI: better message for missing binaries#include \"setupwizard_cli.h\"\n\nWARNINGS_DISABLE\n#include \n#include \n#include \n#include \n\n#include \"ui_setupwizard_cli.h\"\nWARNINGS_ENABLE\n\n#include \n#include \n\n#include \"tasks-defs.h\"\n#include \"taskstatus.h\"\n#include \"utils.h\"\n\nCliPage::CliPage(QWidget *parent)\n : TWizardPage(parent), _ui(new Ui::CliPage), _problemOccurred(false)\n{\n _ui->setupUi(this);\n\n \/\/ We only want to expand the widget if there's a problem.\n _ui->cliAdvancedWidget->hide();\n _ui->cliAdvancedButton->setChecked(false);\n\n \/\/ Basic operation on this page.\n connect(_ui->cliAdvancedButton, &QPushButton::toggled,\n _ui->cliAdvancedWidget, &QWidget::setVisible);\n\n \/\/ A config field changed.\n connect(_ui->cliPathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::tarsnapPathChanged);\n connect(_ui->cachePathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::tarsnapCacheChanged);\n connect(_ui->appdataPathLineBrowse, &PathLineBrowse::textChanged, this,\n &CliPage::appDataDirChanged);\n}\n\nCliPage::~CliPage()\n{\n delete _ui;\n}\n\nvoid CliPage::initializePage()\n{\n TWizardPage::initializePage();\n\n \/\/ CLI path.\n QString tarsnapPath = Utils::findTarsnapClientInPath(\"\", true);\n _ui->cliPathLineBrowse->setText(tarsnapPath);\n if(tarsnapPath.isEmpty())\n {\n \/\/ Trigger this manually, because the automatic connection\n \/\/ won't trigger it's blank.\n tarsnapPathChanged(tarsnapPath);\n }\n\n \/\/\/ Cache dir.\n QString tarsnapCacheDir =\n QStandardPaths::writableLocation(QStandardPaths::CacheLocation);\n if(ensureDirExists(tarsnapCacheDir))\n _ui->cachePathLineBrowse->setText(tarsnapCacheDir);\n\n \/\/ App Data dir.\n QString appDataDir = QStandardPaths::writableLocation(APPDATA);\n if(ensureDirExists(appDataDir))\n _ui->appdataPathLineBrowse->setText(appDataDir);\n}\n\nbool CliPage::checkComplete()\n{\n \/\/ Check the remaining items.\n TSettings settings;\n\n \/\/ Do we have a valid version number? (This is the last piece of config.)\n if(!settings.contains(\"tarsnap\/version\"))\n return setProceedButton(false);\n\n \/\/ Do we have everything else? (Double-check; almost certainly not needed.)\n if((!settings.contains(\"tarsnap\/path\"))\n || (!settings.contains(\"tarsnap\/cache\"))\n || (!settings.contains(\"app\/app_data\")))\n return setProceedButton(false);\n\n _problemOccurred = false;\n _ui->cliValidationLabel->clear();\n return setProceedButton(true);\n}\n\nvoid CliPage::reportError(const QString &text)\n{\n _ui->cliValidationLabel->messageError(text);\n _ui->cliAdvancedButton->setChecked(true);\n setProceedButton(false);\n _problemOccurred = true;\n}\n\nvoid CliPage::tarsnapCacheChanged(const QString &text)\n{\n \/\/ Clear previous setting.\n TSettings settings;\n settings.remove(\"tarsnap\/cache\");\n\n if(text.isEmpty())\n {\n reportError(tr(\"Empty Tarsnap cache directory set.\"));\n return;\n }\n\n QString tarsnapCacheDir = Utils::validateTarsnapCache(text);\n if(tarsnapCacheDir.isEmpty())\n {\n reportError(tr(\"Invalid Tarsnap cache directory set.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"tarsnap\/cache\", tarsnapCacheDir);\n checkComplete();\n}\n\nvoid CliPage::appDataDirChanged(const QString &text)\n{\n \/\/ Clear previous setting.\n TSettings settings;\n settings.remove(\"app\/app_data\");\n\n if(text.isEmpty())\n {\n reportError(tr(\"Empty App data directory set.\"));\n return;\n }\n\n QString appDataDir = Utils::validateAppDataDir(text);\n if(appDataDir.isEmpty())\n {\n reportError(tr(\"Invalid App data directory set.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"app\/app_data\", appDataDir);\n checkComplete();\n}\n\nvoid CliPage::tarsnapPathChanged(const QString &text)\n{\n \/\/ Clear previous settings.\n TSettings settings;\n settings.remove(\"tarsnap\/path\");\n settings.remove(\"tarsnap\/version\");\n\n \/\/ Don't check for an empty dir here, because we want users to see the\n \/\/ \"visit tarsnap.com\" message if they don't have the binaries.\n\n QString tarsnapDir = Utils::findTarsnapClientInPath(text, true);\n if(tarsnapDir.isEmpty())\n {\n reportError(tr(\"Tarsnap utilities not found. Visit \"\n \"tarsnap.com<\/a>\"\n \" for help with acquiring them.\"));\n return;\n }\n\n \/\/ We're ok\n settings.setValue(\"tarsnap\/path\", tarsnapDir);\n emit tarsnapVersionRequested();\n checkComplete();\n}\n\nvoid CliPage::tarsnapVersionResponse(TaskStatus status, QString versionString)\n{\n TSettings settings;\n\n \/\/ Sanity check.\n if(versionString.isEmpty())\n status = TaskStatus::Failed;\n\n \/\/ Handle response.\n switch(status)\n {\n case TaskStatus::Completed:\n \/\/ Record value\n settings.setValue(\"tarsnap\/version\", versionString);\n \/\/ Auto-focus on \"Next\" if the user isn't manually changing things.\n if(checkComplete() && !_problemOccurred)\n _ui->nextButton->setFocus();\n \/\/ Display message (after checkComplete, which can clear the label).\n _ui->cliValidationLabel->messageNormal(\n tr(\"Tarsnap CLI version \") + versionString + tr(\" detected. ✔\"));\n break;\n case TaskStatus::VersionTooLow:\n \/\/ Don't record the too-low version number.\n reportError(\n tr(\"Tarsnap CLI version \") + versionString\n + tr(\" too low; must be at least %1\").arg(TARSNAP_MIN_VERSION));\n break;\n case TaskStatus::Failed:\n reportError(tr(\"Error retrieving Tarsnap CLI verison\"));\n break;\n default:\n break;\n }\n}\n\nbool CliPage::ensureDirExists(const QString &dirname)\n{\n \/\/ Create directory (if needed).\n if(QDir().mkpath(dirname))\n return true;\n else\n {\n QMessageBox::critical(this, tr(\"Could not create directory\"),\n tr(\"Could not create directory\") + \": \"\n + dirname);\n return false;\n }\n}\n<|endoftext|>"} {"text":"\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner \n\n#include \n#include \n#include \n#include \n\n#ifdef HAVE_PATHS_H\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include \n#include \n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner ,\\n\"\n \"Markus Wbben \\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx ,\\n\"\n \"Stephan Meyer ,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\nconst char *aboutText = \n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner ,\\n\"\n \"Don Sanders ,\\n\"\n \"Waldo Bastian ,\\n\"\n \"Andreas Gungl ,\\n\"\n \"Lars Knoll ,\\n\"\n \"J. Nick Koston ,\\n\"\n \"Daniel Naber ,\\n\"\n \"Sven Radej ,\\n\"\n \"Espen Sand ,\\n\"\n \"George Staikos ,\\n\"\n \"Mario Weilguni ,\\n\"\n \"Robert D. Williams \\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx ,\\n\"\n \"Stephan Meyer \\n\"\n \"and the above authors.\\n\\n\"\n \"Please send bugreports to kmail@kde.org\";\n\n\/\/static const char *description = I18N_NOOP(\"A KDE E-Mail client.\"); \nstatic const char *description = aboutText;\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject \",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc

\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc
\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header
\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg \",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\nstatic void signalHandler(int sigId);\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/-----------------------------------------------------------------------------\n\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters(); \n ::exit(-1); \/\/ \n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj;\n KURL messageFile = QString::null;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = args->getOption(\"subject\");\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = args->getOption(\"cc\");\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = args->getOption(\"bcc\");\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, messageFile);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"), \n KMAIL_VERSION, \n description,\n\t\t KAboutData::License_GPL,\n \"(c) 1997-2000, The KMail developers\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n exit(0);\n \n KMailApplication app;\n \n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n \n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n \n \/\/ Go!\n kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n}\n\nWABA: Fix BR6454, you need to update kdelibs\/dcop for this!!\/\/ KMail startup and initialize code\n\/\/ Author: Stefan Taferner \n\n#include \n#include \n#include \n#include \n\n#ifdef HAVE_PATHS_H\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"kmkernel.h\" \/\/control center\n\n#undef Status \/\/ stupid X headers\n#include \"kmailIface_stub.h\" \/\/ to call control center of master kmail\n\n#include \n#include \n\n#include \"kmversion.h\"\n\n\n\/\/ OLD about text. This is horrbly outdated.\n\/*const char* aboutText =\n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner ,\\n\"\n \"Markus Wbben \\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx ,\\n\"\n \"Stephan Meyer ,\\n\"\n \"and the above authors.\\n\\n\"\n \"This program is covered by the GPL.\\n\\n\"\n \"Please send bugreports to taferner@kde.org\";\n*\/\nconst char *aboutText = \n \"KMail [\" KMAIL_VERSION \"] by\\n\\n\"\n \"Stefan Taferner ,\\n\"\n \"Don Sanders ,\\n\"\n \"Waldo Bastian ,\\n\"\n \"Andreas Gungl ,\\n\"\n \"Lars Knoll ,\\n\"\n \"J. Nick Koston ,\\n\"\n \"Daniel Naber ,\\n\"\n \"Sven Radej ,\\n\"\n \"Espen Sand ,\\n\"\n \"George Staikos ,\\n\"\n \"Mario Weilguni ,\\n\"\n \"Robert D. Williams \\n\\n\"\n \"based on the work of:\\n\"\n \"Lynx ,\\n\"\n \"Stephan Meyer \\n\"\n \"and the above authors.\\n\\n\"\n \"Please send bugreports to kmail@kde.org\";\n\n\/\/static const char *description = I18N_NOOP(\"A KDE E-Mail client.\"); \nstatic const char *description = aboutText;\n\nstatic KCmdLineOptions kmoptions[] =\n{\n { \"s\", 0 , 0 },\n { \"subject \",\tI18N_NOOP(\"Set subject of msg.\"), 0 },\n { \"c\", 0 , 0 },\n { \"cc
\",\t\tI18N_NOOP(\"Send CC: to 'address'.\"), 0 },\n { \"b\", 0 , 0 },\n { \"bcc
\",\t\tI18N_NOOP(\"Send BCC: to 'addres'.\"), 0 },\n { \"h\", 0 , 0 },\n { \"header
\",\t\tI18N_NOOP(\"Add 'header' to msg.\"), 0 },\n { \"msg \",\t\tI18N_NOOP(\"Read msg-body from 'file'.\"), 0 },\n { \"check\",\t\t\tI18N_NOOP(\"Check for new mail only.\"), 0 },\n { \"composer\",\t\t\tI18N_NOOP(\"Open only composer window.\"), 0 },\n { \"+[address]\",\t\tI18N_NOOP(\"Send msg to 'address'.\"), 0 },\n\/\/ { \"+[file]\", I18N_NOOP(\"Show message from file 'file'.\"), 0 },\n { 0, 0, 0}\n};\n\n\nstatic void signalHandler(int sigId);\nstatic void setSignalHandler(void (*handler)(int));\n\n\/\/-----------------------------------------------------------------------------\n\n\n\/\/ Crash recovery signal handler\nstatic void signalHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Exiting)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters(); \n ::exit(-1); \/\/ \n}\n\n\/\/ Crash recovery signal handler\nstatic void crashHandler(int sigId)\n{\n setSignalHandler(SIG_DFL);\n fprintf(stderr, \"*** KMail got signal %d (Crashing)\\n\", sigId);\n \/\/ try to cleanup all windows\n kernel->dumpDeadLetters();\n \/\/ Return to DrKonqi.\n}\n\/\/-----------------------------------------------------------------------------\n\n\nstatic void setSignalHandler(void (*handler)(int))\n{\n signal(SIGKILL, handler);\n signal(SIGTERM, handler);\n signal(SIGHUP, handler);\n KCrash::setEmergencySaveFunction(crashHandler);\n}\n\/\/-----------------------------------------------------------------------------\n\nclass KMailApplication : public KUniqueApplication\n{\npublic:\n KMailApplication() : KUniqueApplication() { };\n\n virtual int newInstance();\n};\n\nint KMailApplication::newInstance()\n{\n QString to, cc, bcc, subj;\n KURL messageFile = QString::null;\n bool mailto = false;\n bool checkMail = false;\n \/\/bool viewOnly = false;\n\n \/\/ process args:\n KCmdLineArgs *args = KCmdLineArgs::parsedArgs();\n if (args->getOption(\"subject\"))\n {\n mailto = true;\n subj = args->getOption(\"subject\");\n }\n\n if (args->getOption(\"cc\"))\n {\n mailto = true;\n cc = args->getOption(\"cc\");\n }\n\n if (args->getOption(\"bcc\"))\n {\n mailto = true;\n bcc = args->getOption(\"bcc\");\n }\n\n if (args->isSet(\"composer\"))\n mailto = true;\n\n if (args->isSet(\"check\"))\n checkMail = true;\n\n for(int i= 0; i < args->count(); i++)\n {\n if (!to.isEmpty())\n to += \", \";\n if (strncasecmp(args->arg(i),\"mailto:\",7)==0)\n to += args->arg(i);\n else\n to += args->arg(i);\n mailto = true;\n }\n\n args->clear();\n\n kernel->action (mailto, checkMail, to, cc, bcc, subj, messageFile);\n return 0;\n}\n\nint main(int argc, char *argv[])\n{\n \/\/ WABA: KMail is a KUniqueApplication. Unfortunately this makes debugging\n \/\/ a bit harder: You should pass --nofork as commandline argument when using\n \/\/ a debugger. In gdb you can do this by typing \"set args --nofork\" before\n \/\/ typing \"run\".\n\n KAboutData about(\"kmail\", I18N_NOOP(\"KMail\"), \n KMAIL_VERSION, \n description,\n\t\t KAboutData::License_GPL,\n \"(c) 1997-2000, The KMail developers\" );\n\n KCmdLineArgs::init(argc, argv, &about);\n KCmdLineArgs::addCmdLineOptions( kmoptions ); \/\/ Add kmail options\n\n if (!KMailApplication::start())\n exit(0);\n \n KMailApplication app;\n kapp->dcopClient()->suspend(); \/\/ Don't handle DCOP requests yet\n \n \/\/local, do the init\n KMKernel kmailKernel;\n kmailKernel.init();\n\n \/\/ and session management\n kmailKernel.doSessionManagement();\n \n \/\/ any dead letters?\n kmailKernel.recoverDeadLetters();\n\n setSignalHandler(signalHandler);\n\n kapp->dcopClient()->resume(); \/\/ Ok. We are ready for DCOP requests.\n \/\/ Go!\n kapp->exec();\n\n \/\/ clean up\n kmailKernel.cleanup();\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_view.h\"\n\n#include \"chrome\/browser\/extensions\/extension.h\"\n#include \"chrome\/browser\/extensions\/extension_message_service.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n\nExtensionView::ExtensionView(\n Extension* extension, const GURL& url, Profile* profile) :\n HWNDHtmlView(url, this, false), extension_(extension), profile_(profile) {\n \/\/ TODO(mpcomplete): query this from the renderer somehow?\n set_preferred_size(gfx::Size(100, 100));\n}\n\nvoid ExtensionView::CreatingRenderer() {\n render_view_host()->AllowExtensionBindings();\n}\n\nvoid ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) {\n ExtensionMessageService::GetInstance()->RegisterExtensionView(this);\n}\n\nWebPreferences ExtensionView::GetWebkitPrefs() {\n \/\/ TODO(mpcomplete): return some reasonable prefs.\n return WebPreferences();\n}\n\nvoid ExtensionView::RunJavaScriptMessage(\n const std::wstring& message,\n const std::wstring& default_prompt,\n const GURL& frame_url,\n const int flags,\n IPC::Message* reply_msg,\n bool* did_suppress_message) {\n \/\/ Automatically cancel the javascript alert (otherwise the renderer hangs\n \/\/ indefinitely).\n *did_suppress_message = true;\n render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L\"\");\n}\n\nvoid ExtensionView::DidStartLoading(RenderViewHost* render_view_host,\n int32 page_id) {\n static const StringPiece toolstrip_css(\n ResourceBundle::GetSharedInstance().GetRawDataResource(\n IDR_EXTENSIONS_TOOLSTRIP_CSS));\n render_view_host->InsertCSSInWebFrame(L\"\", toolstrip_css.as_string());\n}\nOCD fixing of style for the initializer list of ExtensionView. Review URL: http:\/\/codereview.chromium.org\/56113\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extension_view.h\"\n\n#include \"chrome\/browser\/extensions\/extension.h\"\n#include \"chrome\/browser\/extensions\/extension_message_service.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n\n#include \"grit\/browser_resources.h\"\n#include \"grit\/generated_resources.h\"\n\nExtensionView::ExtensionView(Extension* extension,\n const GURL& url,\n Profile* profile)\n : HWNDHtmlView(url, this, false),\n extension_(extension),\n profile_(profile) {\n \/\/ TODO(mpcomplete): query this from the renderer somehow?\n set_preferred_size(gfx::Size(100, 100));\n}\n\nvoid ExtensionView::CreatingRenderer() {\n render_view_host()->AllowExtensionBindings();\n}\n\nvoid ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) {\n ExtensionMessageService::GetInstance()->RegisterExtensionView(this);\n}\n\nWebPreferences ExtensionView::GetWebkitPrefs() {\n \/\/ TODO(mpcomplete): return some reasonable prefs.\n return WebPreferences();\n}\n\nvoid ExtensionView::RunJavaScriptMessage(\n const std::wstring& message,\n const std::wstring& default_prompt,\n const GURL& frame_url,\n const int flags,\n IPC::Message* reply_msg,\n bool* did_suppress_message) {\n \/\/ Automatically cancel the javascript alert (otherwise the renderer hangs\n \/\/ indefinitely).\n *did_suppress_message = true;\n render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L\"\");\n}\n\nvoid ExtensionView::DidStartLoading(RenderViewHost* render_view_host,\n int32 page_id) {\n static const StringPiece toolstrip_css(\n ResourceBundle::GetSharedInstance().GetRawDataResource(\n IDR_EXTENSIONS_TOOLSTRIP_CSS));\n render_view_host->InsertCSSInWebFrame(L\"\", toolstrip_css.as_string());\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nvoid print_graph(const char *filename, const Graph& graph) {\n if (filename == NULL || strlen(filename) == 0) {\n return;\n }\n\n std::ostream *stream;\n std::ofstream *file_stream;\n\n std::string mpi_filename = std::string(\"mpi-output-\") + std::to_string(GraphPad::global_myrank);\n file_stream = new std::ofstream(mpi_filename.c_str());\n stream = file_stream;\n\n for (size_t i = 0; i < graph.nvertices; i++) {\n if (graph.vertexproperty.node_owner(i+1)) {\n (*stream) << i + 1 << \" \" << graph.getVertexproperty(i+1) << std::endl;\n }\n }\n\n if (file_stream != NULL) {\n if (!file_stream->good()) {\n std::cerr << \"failed to write output to file\" << endl;\n }\n\n file_stream->flush();\n file_stream->close();\n delete file_stream;\n }\n\n MPI_Barrier(MPI_COMM_WORLD);\n if (GraphPad::global_myrank == 0) {\n std::ostream *stream_all;\n std::ofstream *file_stream_all;\n std::ifstream *mpi_stream;\n int mpi_comm_size;\n MPI_Comm_size(MPI_COMM_WORLD, &mpi_comm_size);\n if (strcmp(filename, \"-\") != 0) {\n file_stream_all = new std::ofstream(filename);\n stream_all = file_stream_all;\n } else {\n file_stream_all = NULL;\n stream_all = &std::cout;\n }\n for (int i = 0; i < mpi_comm_size; i++) {\n char buffer[1024];\n mpi_filename = std::string(\"mpi-output-\") + std::to_string(i);\n mpi_stream = new std::ifstream(mpi_filename.c_str());\n while (!(*mpi_stream).eof()) {\n (*mpi_stream).getline(buffer, 1024);\n (*stream_all) << buffer << std::endl;\n }\n mpi_stream->close();\n delete mpi_stream;\n std::remove(mpi_filename.c_str());\n }\n if (file_stream_all != NULL) {\n if (!file_stream_all->good()) {\n std::cerr << \"failed to write output to file\" << endl;\n }\n file_stream_all->flush();\n file_stream_all->close();\n delete file_stream_all;\n }\n }\n}\n\nbool get_bit(size_t idx, char* vec) {\n size_t offset = idx >> 3;\n size_t bit = idx & 0x7;\n char mask = 1 << bit;\n return (vec[offset] & mask) != 0;\n}\n\nbool set_bit(size_t idx, char* vec) {\n size_t offset = idx >> 3;\n size_t bit = idx & 0x7;\n char mask = 1 << bit;\n char val = vec[offset];\n\n if (!(val & mask)) {\n vec[offset] = val | mask;\n return true;\n }\n\n return false;\n}\n\ndouble timer() {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return tv.tv_sec + tv.tv_usec \/ 1000000.0;\n}\n\nstatic std::vector> timers;\n\nvoid timer_start() {\n timers.clear();\n}\n\nvoid timer_next(std::string name) {\n timers.push_back(std::make_pair(name, timer()));\n}\n\nvoid timer_end() {\n timer_next(\"end\");\n\n std::cerr << \"Timing results:\" << std::endl;\n\n for (size_t i = 0; i < timers.size() - 1; i++) {\n std::string &name = timers[i].first;\n double time = timers[i + 1].second - timers[i].second;\n\n std::cerr << \" - \" << name << \": \" << time << \" sec\" << std::endl;\n }\n\n timers.clear();\n}\nFix emply line in output#include \n#include \n#include \n#include \n#include \n#include \n\ntemplate \nvoid print_graph(const char *filename, const Graph& graph) {\n if (filename == NULL || strlen(filename) == 0) {\n return;\n }\n\n std::ostream *stream;\n std::ofstream *file_stream;\n\n std::string mpi_filename = std::string(\"mpi-output-\") + std::to_string(GraphPad::global_myrank);\n file_stream = new std::ofstream(mpi_filename.c_str());\n stream = file_stream;\n\n for (size_t i = 0; i < graph.nvertices; i++) {\n if (graph.vertexproperty.node_owner(i+1)) {\n (*stream) << i + 1 << \" \" << graph.getVertexproperty(i+1) << std::endl;\n }\n }\n\n if (file_stream != NULL) {\n if (!file_stream->good()) {\n std::cerr << \"failed to write output to file\" << endl;\n }\n\n file_stream->flush();\n file_stream->close();\n delete file_stream;\n }\n\n MPI_Barrier(MPI_COMM_WORLD);\n if (GraphPad::global_myrank == 0) {\n std::ostream *stream_all;\n std::ofstream *file_stream_all;\n std::ifstream *mpi_stream;\n int mpi_comm_size;\n MPI_Comm_size(MPI_COMM_WORLD, &mpi_comm_size);\n if (strcmp(filename, \"-\") != 0) {\n file_stream_all = new std::ofstream(filename);\n stream_all = file_stream_all;\n } else {\n file_stream_all = NULL;\n stream_all = &std::cout;\n }\n for (int i = 0; i < mpi_comm_size; i++) {\n char buffer[1024];\n mpi_filename = std::string(\"mpi-output-\") + std::to_string(i);\n mpi_stream = new std::ifstream(mpi_filename.c_str());\n (*mpi_stream).getline(buffer, 1024);\n while (!(*mpi_stream).eof()) {\n (*stream_all) << buffer << std::endl;\n (*mpi_stream).getline(buffer, 1024);\n }\n mpi_stream->close();\n delete mpi_stream;\n std::remove(mpi_filename.c_str());\n }\n if (file_stream_all != NULL) {\n if (!file_stream_all->good()) {\n std::cerr << \"failed to write output to file\" << endl;\n }\n file_stream_all->flush();\n file_stream_all->close();\n delete file_stream_all;\n }\n }\n}\n\nbool get_bit(size_t idx, char* vec) {\n size_t offset = idx >> 3;\n size_t bit = idx & 0x7;\n char mask = 1 << bit;\n return (vec[offset] & mask) != 0;\n}\n\nbool set_bit(size_t idx, char* vec) {\n size_t offset = idx >> 3;\n size_t bit = idx & 0x7;\n char mask = 1 << bit;\n char val = vec[offset];\n\n if (!(val & mask)) {\n vec[offset] = val | mask;\n return true;\n }\n\n return false;\n}\n\ndouble timer() {\n struct timeval tv;\n gettimeofday(&tv, NULL);\n return tv.tv_sec + tv.tv_usec \/ 1000000.0;\n}\n\nstatic std::vector> timers;\n\nvoid timer_start() {\n timers.clear();\n}\n\nvoid timer_next(std::string name) {\n timers.push_back(std::make_pair(name, timer()));\n}\n\nvoid timer_end() {\n timer_next(\"end\");\n\n std::cerr << \"Timing results:\" << std::endl;\n\n for (size_t i = 0; i < timers.size() - 1; i++) {\n std::string &name = timers[i].first;\n double time = timers[i + 1].second - timers[i].second;\n\n std::cerr << \" - \" << name << \": \" << time << \" sec\" << std::endl;\n }\n\n timers.clear();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2011-2014 Red Hat, Inc.\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; If not, see .\n *\n * Author: tasleson\n *\/\n\n#ifndef LSM_IPC_H\n#define LSM_IPC_H\n\n#include \"libstoragemgmt\/libstoragemgmt_common.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/\/ Common serialization\n\n\/**\n * Sends and receives payloads, unaware of the contents.\n * Notes: Not thread safe. i.e. you cannot share the same object with two or\n * more threads.\n *\/\nclass LSM_DLL_LOCAL Transport {\n public:\n \/**\n * Size of the header which immediately proceeds the payload.\n *\/\n const static int HDR_LEN = 10;\n\n \/**\n * Empty ctor.\n * @return\n *\/\n Transport();\n\n \/**\n * Class ctor\n * @param socket_desc Connected socket descriptor.\n *\/\n Transport(int socket_desc);\n\n \/**\n * Class dtor\n *\/\n ~Transport();\n\n \/**\n * Sends a message over the transport.\n * @param[in] msg The message to be sent.\n * @param[out] error_code Errno (only valid if we return -1)\n * @return 0 on success, else -1\n *\/\n int msg_send(const std::string &msg, int &error_code);\n\n \/**\n * Received a message over the transport.\n * Note: A zero read indicates that the transport was closed by other side,\n * no error code will be set in that case.\n * @param error_code (0 on success, else errno)\n * @return Message on success else 0 size with error_code set (not if EOF)\n *\/\n std::string msg_recv(int &error_code);\n\n \/**\n * Creates a connected socket (AF_UNIX) to the specified path\n * @param path of the AF_UNIX file to be used for IPC\n * @param error_code Error reason for the failure (errno)\n * @return -1 on error, else connected socket.\n *\/\n static int socket_get(const std::string &path, int &error_code);\n\n \/**\n * Closes the transport, called in the destructor if not done in advance.\n * @return 0 on success, else EBADF, EINTR, EIO.\n *\/\n void close();\n\n private:\n int s; \/\/ Socket descriptor\n};\n\n\/**\n * Generic function to convert Type v into a string.\n * @param v Template type T\n * @return string representation\n *\/\ntemplate static std::string to_string(Type v) {\n std::stringstream out;\n out << v;\n return out.str();\n}\n\n\/**\n * Class that represents an EOF condition\n * @param m Message\n *\/\nclass LSM_DLL_LOCAL EOFException : public std::runtime_error {\n public:\n EOFException(std::string m);\n};\n\n\/**\n * User defined class for Value errors during serialize \/ de-serialize.\n *\/\nclass LSM_DLL_LOCAL ValueException : public std::runtime_error {\n public:\n \/**\n * Constructor\n * @param m Exception message\n *\/\n ValueException(std::string m);\n};\n\n\/**\n * User defined class for errors\n *\/\nclass LSM_DLL_LOCAL LsmException : public std::runtime_error {\n public:\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n *\/\n LsmException(int code, std::string &msg);\n\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n * @param debug_addl Additional debug data\n *\/\n LsmException(int code, std::string &msg, const std::string &debug_addl);\n\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n * @param debug_addl Additional debug\n * @param debug_data_addl Additional debug data\n *\/\n LsmException(int code, std::string &msg, const std::string &debug_addl,\n const std::string &debug_data_addl);\n\n \/**\n * Destructor\n *\/\n ~LsmException() throw();\n\n int error_code;\n std::string debug;\n std::string debug_data;\n};\n\n\/**\n * Represents a value in the serialization.\n *\/\nclass LSM_DLL_LOCAL Value {\n public:\n \/**\n * Different types this class can hold.\n *\/\n enum value_type {\n null_t,\n boolean_t,\n string_t,\n numeric_t,\n object_t,\n array_t\n };\n\n \/**\n * Default constructor creates a \"null\" type\n *\/\n Value(void);\n\n \/**\n * Boolean constructor\n * @param v value\n *\/\n Value(bool v);\n\n \/**\n * Numeric unsigned 32 constructor\n * @param v value\n *\/\n Value(uint32_t v);\n\n \/**\n * Numeric signed 32 constructor\n * @param v value\n *\/\n Value(int32_t v);\n\n \/**\n * Numeric unsigned 64 constructor.\n * @param v value\n *\/\n Value(uint64_t v);\n\n \/**\n * Numeric signed 64 constructor.\n * @param v value\n *\/\n Value(int64_t v);\n\n \/**\n * Constructor in which you specify type and initial value as string.\n * @param type Type this object will hold.\n * @param v value\n *\/\n Value(value_type type, const std::string &v);\n\n \/**\n * Constructor for char * i.e. string.\n * @param v value\n *\/\n Value(const char *v);\n\n \/**\n * Constructor for std::string\n * @param v value\n *\/\n Value(const std::string &v);\n\n \/**\n * Constructor for object type\n * @param v values\n *\/\n Value(const std::map &v);\n\n \/**\n * Constructor for array type\n * @param v array values\n *\/\n Value(const std::vector &v);\n\n \/**\n * Serialize Value to json\n * @return\n *\/\n std::string serialize(void);\n\n \/**\n * Returns the enumerated type represented by object\n * @return enumerated type\n *\/\n value_type valueType() const;\n\n \/**\n * Overloaded operator for map access\n * @param key\n * @return Value\n *\/\n Value &operator[](const std::string &key);\n\n \/**\n * Overloaded operator for vector(array) access\n * @param i\n * @return Value\n *\/\n Value &operator[](uint32_t i);\n\n \/**\n * Returns true if value has a key in key\/value pair\n * @return true if key exists, else false.\n *\/\n bool hasKey(const std::string &k);\n\n \/**\n * Checks to see if a Value contains a valid request\n * @return True if it is a request, else false\n *\/\n bool isValidRequest(void);\n\n \/**\n * Given a key returns the value.\n * @param key\n * @return Value\n *\/\n Value getValue(const char *key);\n\n \/**\n * Boolean value represented by object.\n * @return true, false ValueException on error\n *\/\n bool asBool();\n\n \/**\n * Signed 32 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n int32_t asInt32_t();\n\n \/**\n * Signed 64 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n int64_t asInt64_t();\n\n \/**\n * Unsigned 32 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n uint32_t asUint32_t();\n\n \/**\n * Unsigned 64 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n uint64_t asUint64_t();\n\n \/**\n * String value represented by object.\n * @return string value else ValueException on error\n *\/\n std::string asString();\n\n \/**\n * Return string as a pointer to a character array\n * @return\n *\/\n const char *asC_str();\n\n \/**\n * key\/value represented by object.\n * @return map of key and values else ValueException on error\n *\/\n std::map asObject();\n\n \/**\n * vector of values represented by object.\n * @return vector of array values else ValueException on error\n *\/\n std::vector asArray();\n\n private:\n value_type t;\n std::vector array;\n std::map obj;\n std::string s;\n};\n\n\/**\n * Serialize, de-serialize methods.\n *\/\nclass LSM_DLL_LOCAL Payload {\n public:\n \/**\n * Given a Value returns json representation.\n * @param v Value to serialize\n * @return String representation\n *\/\n static std::string serialize(Value &v);\n\n \/**\n * Given a json string return a Value\n * @param json String to de-serialize\n * @return Value\n *\/\n static Value deserialize(const std::string &json);\n};\n\nclass LSM_DLL_LOCAL Ipc {\n public:\n \/**\n * Constructor\n *\/\n Ipc();\n\n \/**\n * Constructor that takes a file descriptor\n * @param fd File descriptor to use\n *\/\n Ipc(int fd);\n\n \/**\n * Constructor that takes a socket path\n * @param socket_path Unix domain socket\n *\/\n Ipc(std::string socket_path);\n\n \/**\n * Destructor\n *\/\n ~Ipc();\n\n \/**\n * Send a request over IPC\n * @param request IPC function name\n * @param params Parameters\n * @param id Request ID\n *\/\n void requestSend(const std::string request, const Value ¶ms,\n int32_t id = 100);\n \/**\n * Reads a request\n * @returns Value\n *\/\n Value readRequest(void);\n\n \/**\n * Send a response to a request\n * @param response Response value\n * @param id Id that matches request\n *\/\n void responseSend(const Value &response, uint32_t id = 100);\n\n \/**\n * Read a response\n * @return Value of response\n *\/\n Value responseRead();\n\n \/**\n * Send an error\n * @param error_code Error code\n * @param msg Error message\n * @param debug Debug data\n * @param id Id that matches request\n *\/\n void errorSend(int error_code, std::string msg, std::string debug,\n uint32_t id = 100);\n\n \/**\n * Do a remote procedure call (Request with a returned response\n * @param request Function method\n * @param params Function parameters\n * @param id Id of request\n * @return Result of the operation.\n *\/\n Value rpc(const std::string &request, const Value ¶ms,\n int32_t id = 100);\n\n private:\n Transport t;\n};\n\n#endif\nCorrect Transport header comment\/*\n * Copyright (C) 2011-2014 Red Hat, Inc.\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; If not, see .\n *\n * Author: tasleson\n *\/\n\n#ifndef LSM_IPC_H\n#define LSM_IPC_H\n\n#include \"libstoragemgmt\/libstoragemgmt_common.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef HAVE_CONFIG_H\n#include \"config.h\"\n#endif\n\n\/\/ Common serialization\n\n\/**\n * Sends and receives payloads, unaware of the contents.\n * Notes: Not thread safe. i.e. you cannot share the same object with two or\n * more threads.\n *\/\nclass LSM_DLL_LOCAL Transport {\n public:\n \/**\n * Size of the header which immediately precedes the payload.\n *\/\n const static int HDR_LEN = 10;\n\n \/**\n * Empty ctor.\n * @return\n *\/\n Transport();\n\n \/**\n * Class ctor\n * @param socket_desc Connected socket descriptor.\n *\/\n Transport(int socket_desc);\n\n \/**\n * Class dtor\n *\/\n ~Transport();\n\n \/**\n * Sends a message over the transport.\n * @param[in] msg The message to be sent.\n * @param[out] error_code Errno (only valid if we return -1)\n * @return 0 on success, else -1\n *\/\n int msg_send(const std::string &msg, int &error_code);\n\n \/**\n * Received a message over the transport.\n * Note: A zero read indicates that the transport was closed by other side,\n * no error code will be set in that case.\n * @param error_code (0 on success, else errno)\n * @return Message on success else 0 size with error_code set (not if EOF)\n *\/\n std::string msg_recv(int &error_code);\n\n \/**\n * Creates a connected socket (AF_UNIX) to the specified path\n * @param path of the AF_UNIX file to be used for IPC\n * @param error_code Error reason for the failure (errno)\n * @return -1 on error, else connected socket.\n *\/\n static int socket_get(const std::string &path, int &error_code);\n\n \/**\n * Closes the transport, called in the destructor if not done in advance.\n * @return 0 on success, else EBADF, EINTR, EIO.\n *\/\n void close();\n\n private:\n int s; \/\/ Socket descriptor\n};\n\n\/**\n * Generic function to convert Type v into a string.\n * @param v Template type T\n * @return string representation\n *\/\ntemplate static std::string to_string(Type v) {\n std::stringstream out;\n out << v;\n return out.str();\n}\n\n\/**\n * Class that represents an EOF condition\n * @param m Message\n *\/\nclass LSM_DLL_LOCAL EOFException : public std::runtime_error {\n public:\n EOFException(std::string m);\n};\n\n\/**\n * User defined class for Value errors during serialize \/ de-serialize.\n *\/\nclass LSM_DLL_LOCAL ValueException : public std::runtime_error {\n public:\n \/**\n * Constructor\n * @param m Exception message\n *\/\n ValueException(std::string m);\n};\n\n\/**\n * User defined class for errors\n *\/\nclass LSM_DLL_LOCAL LsmException : public std::runtime_error {\n public:\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n *\/\n LsmException(int code, std::string &msg);\n\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n * @param debug_addl Additional debug data\n *\/\n LsmException(int code, std::string &msg, const std::string &debug_addl);\n\n \/**\n * Constructor\n * @param code Error code\n * @param msg Error message\n * @param debug_addl Additional debug\n * @param debug_data_addl Additional debug data\n *\/\n LsmException(int code, std::string &msg, const std::string &debug_addl,\n const std::string &debug_data_addl);\n\n \/**\n * Destructor\n *\/\n ~LsmException() throw();\n\n int error_code;\n std::string debug;\n std::string debug_data;\n};\n\n\/**\n * Represents a value in the serialization.\n *\/\nclass LSM_DLL_LOCAL Value {\n public:\n \/**\n * Different types this class can hold.\n *\/\n enum value_type {\n null_t,\n boolean_t,\n string_t,\n numeric_t,\n object_t,\n array_t\n };\n\n \/**\n * Default constructor creates a \"null\" type\n *\/\n Value(void);\n\n \/**\n * Boolean constructor\n * @param v value\n *\/\n Value(bool v);\n\n \/**\n * Numeric unsigned 32 constructor\n * @param v value\n *\/\n Value(uint32_t v);\n\n \/**\n * Numeric signed 32 constructor\n * @param v value\n *\/\n Value(int32_t v);\n\n \/**\n * Numeric unsigned 64 constructor.\n * @param v value\n *\/\n Value(uint64_t v);\n\n \/**\n * Numeric signed 64 constructor.\n * @param v value\n *\/\n Value(int64_t v);\n\n \/**\n * Constructor in which you specify type and initial value as string.\n * @param type Type this object will hold.\n * @param v value\n *\/\n Value(value_type type, const std::string &v);\n\n \/**\n * Constructor for char * i.e. string.\n * @param v value\n *\/\n Value(const char *v);\n\n \/**\n * Constructor for std::string\n * @param v value\n *\/\n Value(const std::string &v);\n\n \/**\n * Constructor for object type\n * @param v values\n *\/\n Value(const std::map &v);\n\n \/**\n * Constructor for array type\n * @param v array values\n *\/\n Value(const std::vector &v);\n\n \/**\n * Serialize Value to json\n * @return\n *\/\n std::string serialize(void);\n\n \/**\n * Returns the enumerated type represented by object\n * @return enumerated type\n *\/\n value_type valueType() const;\n\n \/**\n * Overloaded operator for map access\n * @param key\n * @return Value\n *\/\n Value &operator[](const std::string &key);\n\n \/**\n * Overloaded operator for vector(array) access\n * @param i\n * @return Value\n *\/\n Value &operator[](uint32_t i);\n\n \/**\n * Returns true if value has a key in key\/value pair\n * @return true if key exists, else false.\n *\/\n bool hasKey(const std::string &k);\n\n \/**\n * Checks to see if a Value contains a valid request\n * @return True if it is a request, else false\n *\/\n bool isValidRequest(void);\n\n \/**\n * Given a key returns the value.\n * @param key\n * @return Value\n *\/\n Value getValue(const char *key);\n\n \/**\n * Boolean value represented by object.\n * @return true, false ValueException on error\n *\/\n bool asBool();\n\n \/**\n * Signed 32 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n int32_t asInt32_t();\n\n \/**\n * Signed 64 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n int64_t asInt64_t();\n\n \/**\n * Unsigned 32 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n uint32_t asUint32_t();\n\n \/**\n * Unsigned 64 integer value represented by object.\n * @return integer value else ValueException on error\n *\/\n uint64_t asUint64_t();\n\n \/**\n * String value represented by object.\n * @return string value else ValueException on error\n *\/\n std::string asString();\n\n \/**\n * Return string as a pointer to a character array\n * @return\n *\/\n const char *asC_str();\n\n \/**\n * key\/value represented by object.\n * @return map of key and values else ValueException on error\n *\/\n std::map asObject();\n\n \/**\n * vector of values represented by object.\n * @return vector of array values else ValueException on error\n *\/\n std::vector asArray();\n\n private:\n value_type t;\n std::vector array;\n std::map obj;\n std::string s;\n};\n\n\/**\n * Serialize, de-serialize methods.\n *\/\nclass LSM_DLL_LOCAL Payload {\n public:\n \/**\n * Given a Value returns json representation.\n * @param v Value to serialize\n * @return String representation\n *\/\n static std::string serialize(Value &v);\n\n \/**\n * Given a json string return a Value\n * @param json String to de-serialize\n * @return Value\n *\/\n static Value deserialize(const std::string &json);\n};\n\nclass LSM_DLL_LOCAL Ipc {\n public:\n \/**\n * Constructor\n *\/\n Ipc();\n\n \/**\n * Constructor that takes a file descriptor\n * @param fd File descriptor to use\n *\/\n Ipc(int fd);\n\n \/**\n * Constructor that takes a socket path\n * @param socket_path Unix domain socket\n *\/\n Ipc(std::string socket_path);\n\n \/**\n * Destructor\n *\/\n ~Ipc();\n\n \/**\n * Send a request over IPC\n * @param request IPC function name\n * @param params Parameters\n * @param id Request ID\n *\/\n void requestSend(const std::string request, const Value ¶ms,\n int32_t id = 100);\n \/**\n * Reads a request\n * @returns Value\n *\/\n Value readRequest(void);\n\n \/**\n * Send a response to a request\n * @param response Response value\n * @param id Id that matches request\n *\/\n void responseSend(const Value &response, uint32_t id = 100);\n\n \/**\n * Read a response\n * @return Value of response\n *\/\n Value responseRead();\n\n \/**\n * Send an error\n * @param error_code Error code\n * @param msg Error message\n * @param debug Debug data\n * @param id Id that matches request\n *\/\n void errorSend(int error_code, std::string msg, std::string debug,\n uint32_t id = 100);\n\n \/**\n * Do a remote procedure call (Request with a returned response\n * @param request Function method\n * @param params Function parameters\n * @param id Id of request\n * @return Result of the operation.\n *\/\n Value rpc(const std::string &request, const Value ¶ms,\n int32_t id = 100);\n\n private:\n Transport t;\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/iomgr\/executor\/mpmcqueue.h\"\n\nnamespace grpc_core {\n\nDebugOnlyTraceFlag grpc_thread_pool_trace(false, \"thread_pool\");\n\ninline void* InfLenFIFOQueue::PopFront() {\n \/\/ Caller should already check queue is not empty and has already held the\n \/\/ mutex. This function will only do the job of removal.\n void* result = queue_head_->content;\n Node* head_to_remove = queue_head_;\n queue_head_ = queue_head_->next;\n\n count_.FetchSub(1, MemoryOrder::RELAXED);\n\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n gpr_timespec wait_time =\n gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), head_to_remove->insert_time);\n\n \/\/ Updates Stats info\n stats_.num_completed++;\n stats_.total_queue_time = gpr_time_add(stats_.total_queue_time, wait_time);\n stats_.max_queue_time = gpr_time_max(\n gpr_convert_clock_type(stats_.max_queue_time, GPR_TIMESPAN), wait_time);\n\n if (count_.Load(MemoryOrder::RELAXED) == 0) {\n stats_.busy_queue_time =\n gpr_time_add(stats_.busy_queue_time,\n gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), busy_time));\n }\n\n gpr_log(GPR_INFO,\n \"[InfLenFIFOQueue PopFront] num_completed: %\" PRIu64\n \" total_queue_time: %f max_queue_time: %f busy_queue_time: %f\",\n stats_.num_completed,\n gpr_timespec_to_micros(stats_.total_queue_time),\n gpr_timespec_to_micros(stats_.max_queue_time),\n gpr_timespec_to_micros(stats_.busy_queue_time));\n }\n\n Delete(head_to_remove);\n \/\/ Singal waiting thread\n if (count_.Load(MemoryOrder::RELAXED) > 0 && num_waiters_ > 0) {\n wait_nonempty_.Signal();\n }\n\n return result;\n}\n\nInfLenFIFOQueue::~InfLenFIFOQueue() {\n GPR_ASSERT(count_.Load(MemoryOrder::RELAXED) == 0);\n GPR_ASSERT(num_waiters_ == 0);\n}\n\nvoid InfLenFIFOQueue::Put(void* elem) {\n MutexLock l(&mu_);\n\n Node* new_node = New(elem);\n if (count_.FetchAdd(1, MemoryOrder::RELAXED) == 0) {\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n busy_time = gpr_now(GPR_CLOCK_MONOTONIC);\n }\n queue_head_ = queue_tail_ = new_node;\n } else {\n queue_tail_->next = new_node;\n queue_tail_ = queue_tail_->next;\n }\n\n \/\/ Updates Stats info\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n stats_.num_started++;\n gpr_log(GPR_INFO, \"[InfLenFIFOQueue Put] num_started: %\" PRIu64,\n stats_.num_started);\n }\n\n if (num_waiters_ > 0) {\n wait_nonempty_.Signal();\n }\n}\n\nvoid* InfLenFIFOQueue::Get() {\n MutexLock l(&mu_);\n if (count_.Load(MemoryOrder::RELAXED) == 0) {\n num_waiters_++;\n do {\n wait_nonempty_.Wait(&mu_);\n } while (count_.Load(MemoryOrder::RELAXED) == 0);\n num_waiters_--;\n }\n GPR_DEBUG_ASSERT(count_.Load(MemoryOrder::RELAXED) > 0);\n return PopFront();\n}\n\n} \/\/ namespace grpc_core\nChange FetchAdd\/Sub to Load-Add\/Sub-Store\/*\n *\n * Copyright 2019 gRPC authors.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n#include \n\n#include \"src\/core\/lib\/iomgr\/executor\/mpmcqueue.h\"\n\nnamespace grpc_core {\n\nDebugOnlyTraceFlag grpc_thread_pool_trace(false, \"thread_pool\");\n\ninline void* InfLenFIFOQueue::PopFront() {\n \/\/ Caller should already check queue is not empty and has already held the\n \/\/ mutex. This function will only do the job of removal.\n void* result = queue_head_->content;\n Node* head_to_remove = queue_head_;\n queue_head_ = queue_head_->next;\n\n count_.Store(count_.Load(MemoryOrder::RELAXED) - 1, MemoryOrder::RELAXED);\n\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n gpr_timespec wait_time =\n gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), head_to_remove->insert_time);\n\n \/\/ Updates Stats info\n stats_.num_completed++;\n stats_.total_queue_time = gpr_time_add(stats_.total_queue_time, wait_time);\n stats_.max_queue_time = gpr_time_max(\n gpr_convert_clock_type(stats_.max_queue_time, GPR_TIMESPAN), wait_time);\n\n if (count_.Load(MemoryOrder::RELAXED) == 0) {\n stats_.busy_queue_time =\n gpr_time_add(stats_.busy_queue_time,\n gpr_time_sub(gpr_now(GPR_CLOCK_MONOTONIC), busy_time));\n }\n\n gpr_log(GPR_INFO,\n \"[InfLenFIFOQueue PopFront] num_completed: %\" PRIu64\n \" total_queue_time: %f max_queue_time: %f busy_queue_time: %f\",\n stats_.num_completed,\n gpr_timespec_to_micros(stats_.total_queue_time),\n gpr_timespec_to_micros(stats_.max_queue_time),\n gpr_timespec_to_micros(stats_.busy_queue_time));\n }\n\n Delete(head_to_remove);\n \/\/ Singal waiting thread\n if (count_.Load(MemoryOrder::RELAXED) > 0 && num_waiters_ > 0) {\n wait_nonempty_.Signal();\n }\n\n return result;\n}\n\nInfLenFIFOQueue::~InfLenFIFOQueue() {\n GPR_ASSERT(count_.Load(MemoryOrder::RELAXED) == 0);\n GPR_ASSERT(num_waiters_ == 0);\n}\n\nvoid InfLenFIFOQueue::Put(void* elem) {\n MutexLock l(&mu_);\n\n Node* new_node = New(elem);\n if (count_.Load(MemoryOrder::RELAXED) == 0) {\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n busy_time = gpr_now(GPR_CLOCK_MONOTONIC);\n }\n queue_head_ = queue_tail_ = new_node;\n } else {\n queue_tail_->next = new_node;\n queue_tail_ = queue_tail_->next;\n }\n count_.Store(count_.Load(MemoryOrder::RELAXED) + 1, MemoryOrder::RELAXED);\n \/\/ Updates Stats info\n if (GRPC_TRACE_FLAG_ENABLED(grpc_thread_pool_trace)) {\n stats_.num_started++;\n gpr_log(GPR_INFO, \"[InfLenFIFOQueue Put] num_started: %\" PRIu64,\n stats_.num_started);\n }\n\n if (num_waiters_ > 0) {\n wait_nonempty_.Signal();\n }\n}\n\nvoid* InfLenFIFOQueue::Get() {\n MutexLock l(&mu_);\n if (count_.Load(MemoryOrder::RELAXED) == 0) {\n num_waiters_++;\n do {\n wait_nonempty_.Wait(&mu_);\n } while (count_.Load(MemoryOrder::RELAXED) == 0);\n num_waiters_--;\n }\n GPR_DEBUG_ASSERT(count_.Load(MemoryOrder::RELAXED) > 0);\n return PopFront();\n}\n\n} \/\/ namespace grpc_core\n<|endoftext|>"} {"text":"\/\/=====================================================================\/\/\n\/*! @file\n @brief RX24T EEPROM サンプル @n\n\t\t\t・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/cmt_io.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n\nnamespace {\n\n\tclass cmt_task {\n\tpublic:\n\t\tvoid operator() () {\n\t\t}\n\t};\n\n\tdevice::cmt_io cmt_;\n\n\ttypedef utils::fixed_fifo fifo128;\n\tdevice::sci_io sci_;\n\n\tutils::command<256> command_;\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 80MHz 動作 wait 設定\n\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\tdevice::SYSTEM::OPCCR = 0; \/\/ 高速モード選択\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\n\t\/\/ clock osc 10MHz\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\n\t\/\/ メインクロック・ドライブ能力設定、内部発信\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0; \/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::PLLCR.STC = 0b001111;\t\t\/\/ PLL input: 1, PLL 8 倍(80MHz)\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/4 (80\/4=20)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1)\t\t\/\/ 1\/2 (80\/2=40)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1);\t\/\/ 1\/2 (80\/2=40)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\t\/\/ タイマー設定(60Hz)\n\tuint8_t cmt_irq_level = 4;\n\tcmt_.start(60, cmt_irq_level);\n\n\t\/\/ SCI 設定\n\tstatic const uint8_t sci_level = 2;\n\tsci_.start(115200, sci_level);\n\n\tutils::format(\"RX24T EEPROM sample\\n\");\n\n\tcommand_.set_prompt(\"# \");\n\n\tdevice::PORT0::PDR.B0 = 1; \/\/ output\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt_.sync();\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\n\t\t}\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tdevice::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1;\n\t}\n}\nRename: cmt_io to cmt_mgr\/\/=====================================================================\/\/\n\/*! @file\n @brief RX24T EEPROM サンプル @n\n\t\t\t・P00(4) ピンに赤色LED(VF:1.9V)を吸い込みで接続する\n @author 平松邦仁 (hira@rvf-rc45.net)\n\t@copyright\tCopyright (C) 2017 Kunihito Hiramatsu @n\n\t\t\t\tReleased under the MIT license @n\n\t\t\t\thttps:\/\/github.com\/hirakuni45\/RX\/blob\/master\/LICENSE\n*\/\n\/\/=====================================================================\/\/\n#include \"common\/renesas.hpp\"\n#include \"common\/cmt_mgr.hpp\"\n#include \"common\/fixed_fifo.hpp\"\n#include \"common\/sci_io.hpp\"\n#include \"common\/format.hpp\"\n#include \"common\/command.hpp\"\n\nnamespace {\n\n\tclass cmt_task {\n\tpublic:\n\t\tvoid operator() () {\n\t\t}\n\t};\n\n\tdevice::cmt_mgr cmt_;\n\n\ttypedef utils::fixed_fifo fifo128;\n\tdevice::sci_io sci_;\n\n\tutils::command<256> command_;\n}\n\nextern \"C\" {\n\n\tvoid sci_putch(char ch)\n\t{\n\t\tsci_.putch(ch);\n\t}\n\n\tvoid sci_puts(const char* str)\n\t{\n\t\tsci_.puts(str);\n\t}\n\n\tchar sci_getch(void)\n\t{\n\t\treturn sci_.getch();\n\t}\n\n\tuint16_t sci_length()\n\t{\n\t\treturn sci_.recv_length();\n\t}\n\n}\n\nint main(int argc, char** argv);\n\nint main(int argc, char** argv)\n{\n\tdevice::SYSTEM::PRCR = 0xA50B;\t\/\/ クロック、低消費電力、関係書き込み許可\n\n\tdevice::SYSTEM::MEMWAIT = 0b10; \/\/ 80MHz 動作 wait 設定\n\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\tdevice::SYSTEM::OPCCR = 0; \/\/ 高速モード選択\n\twhile(device::SYSTEM::OPCCR.OPCMTSF() != 0) asm(\"nop\");\n\n\t\/\/ clock osc 10MHz\n\tdevice::SYSTEM::MOSCWTCR = 9;\t\/\/ 4ms wait\n\t\/\/ メインクロック・ドライブ能力設定、内部発信\n\tdevice::SYSTEM::MOFCR = device::SYSTEM::MOFCR.MODRV21.b(1);\n\tdevice::SYSTEM::MOSCCR.MOSTP = 0; \/\/ メインクロック発振器動作\n\twhile(device::SYSTEM::OSCOVFSR.MOOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::PLLCR.STC = 0b001111;\t\t\/\/ PLL input: 1, PLL 8 倍(80MHz)\n\tdevice::SYSTEM::PLLCR2.PLLEN = 0;\t\t\t\/\/ PLL 動作\n\twhile(device::SYSTEM::OSCOVFSR.PLOVF() == 0) asm(\"nop\");\n\n\tdevice::SYSTEM::SCKCR = device::SYSTEM::SCKCR.FCK.b(2)\t\t\/\/ 1\/4 (80\/4=20)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.ICK.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKA.b(0)\t\t\/\/ 1\/1 (80\/1=80)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKB.b(1)\t\t\/\/ 1\/2 (80\/2=40)\n\t\t\t\t\t\t | device::SYSTEM::SCKCR.PCKD.b(1);\t\/\/ 1\/2 (80\/2=40)\n\tdevice::SYSTEM::SCKCR3.CKSEL = 0b100;\t\/\/\/< PLL 選択\n\n\t\/\/ タイマー設定(60Hz)\n\tuint8_t cmt_irq_level = 4;\n\tcmt_.start(60, cmt_irq_level);\n\n\t\/\/ SCI 設定\n\tstatic const uint8_t sci_level = 2;\n\tsci_.start(115200, sci_level);\n\n\tutils::format(\"RX24T EEPROM sample\\n\");\n\n\tcommand_.set_prompt(\"# \");\n\n\tdevice::PORT0::PDR.B0 = 1; \/\/ output\n\n\tuint32_t cnt = 0;\n\twhile(1) {\n\t\tcmt_.sync();\n\n\t\t\/\/ コマンド入力と、コマンド解析\n\t\tif(command_.service()) {\n\n\t\t}\n\n\t\t++cnt;\n\t\tif(cnt >= 30) {\n\t\t\tcnt = 0;\n\t\t}\n\t\tdevice::PORT0::PODR.B0 = (cnt < 10) ? 0 : 1;\n\t}\n}\n<|endoftext|>"} {"text":"\/************************************\n** No Bullsh*t Command Line Parser **\n** nbcl.cpp **\n** Copyright 2011-2012 OmegaSDG **\n************************************\/\n\n#include \n#include \n\n#include \"nbcl.h\"\n\nNBCL::NBCL(int argc, char** argv) :\n\targc(argc), argv(argv), strayArgsDesc(\"\")\n{\n}\n\nNBCL::~NBCL()\n{\n\tunsigned int opt;\n\n\tfor (opt = 0; opt < OptList.size(); opt++)\n\t\tdelete OptList[opt];\n}\n\nvoid NBCL::insert(std::string shortopt, std::string longopt,\n\tstd::string arg, std::string desc)\n{\n\tOption* opt = new Option;\n\topt->shortopt = shortopt;\n\topt->longopt = longopt;\n\topt->arg = arg;\n\topt->desc = desc;\n\topt->present = false;\n\topt->value = \"\";\n\tOptList.push_back(opt);\n}\n\nvoid NBCL::setStrayArgsDesc(std::string desc)\n{\n\tstrayArgsDesc = desc;\n}\n\nbool NBCL::parse()\n{\n\tint argn;\n\tint opt;\n\n\tfor (argn = 1; argn < argc; argn++) { \/* Read command line. *\/\n\t\topt = findOpt(argv[argn]);\n\t\tif (opt!=-1) { \/* This argument is an option switch. *\/\n\t\t\tif (!OptList[opt]->arg.empty()) { \/* It takes an argument. *\/\n\t\t\t\tif (argn + 1 < argc) {\n\t\t\t\t\tOptList[opt]->value = argv[argn+1]; \/* Add next argument as the option value. *\/\n\t\t\t\t\targn++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOptList[opt]->present = true; \/* Tell the option it exists. *\/\n\t\t}\n\t\telse \/* This argument is a stray. *\/\n\t\t\tstrayArgsList.push_back(argv[argn]);\n\t}\n\treturn true;\n}\n\nbool NBCL::check(std::string longopt)\n{\n\tint opt = findOpt(longopt);\n\tif (opt!=-1)\n\t\treturn OptList[opt]->present;\n\telse\n\t\treturn false;\n}\n\nstd::string NBCL::get(std::string longopt)\n{\n\tint opt = findOpt(longopt);\n\tif (opt!=-1)\n\t\treturn OptList[opt]->value;\n\telse\n\t\treturn \"\";\n}\n\nvoid NBCL::usage()\n{\n\tint optmax = 0;\n\tint argmax = 0;\n\n\tusageSize(&optmax, &argmax);\n\tusagePrintShort();\n\tusagePrintLong(optmax, argmax);\n}\n\nstd::vector NBCL::getStrayArgsList()\n{\n\treturn strayArgsList;\n}\n\n\/* Makes width calculations needed for formatting usage output. *\/\nvoid NBCL::usageSize(int* optmax, int* argmax)\n{\n\tunsigned int opt;\n\n\tfor (opt = 0; opt < OptList.size(); opt++) {\n\t\tif (OptList[opt]->shortopt.size() + OptList[opt]->longopt.size() > (unsigned)*optmax)\n\t\t\t*optmax = (int)OptList[opt]->shortopt.size() + (int)OptList[opt]->longopt.size() + 1;\n\n\t\tif ((int)OptList[opt]->arg.size() > *argmax)\n\t\t\t*argmax = (int)OptList[opt]->arg.size();\n\t}\n}\n\nvoid NBCL::usagePrintShort()\n{\n\t#ifdef _WIN32\n\t\tchar fname[_MAX_FNAME];\n\t\tchar ext[_MAX_EXT];\n\t\t_splitpath(argv[0], NULL, NULL, fname, ext);\n\t\tif (ext[strlen(ext)-1] == ' ') \/* Windows thinks I want a space at the end. It's wrong. *\/\n\t\t\text[strlen(ext)-1] = 0;\n\t\tfprintf(stderr, \"Usage: %s%s [OPTIONS] \", fname, ext);\n\t#else\n\t\tfprintf(stderr, \"Usage: %s [OPTIONS] \", argv[0]);\n\t#endif\n\tfprintf(stderr, strayArgsDesc.c_str());\n}\n\n\/* Lots of ugly formatting code. *\/\nvoid NBCL::usagePrintLong(int optmax, int argmax)\n{\n\tunsigned int opt;\n\n\tfprintf(stderr, \"\\n\\nAvailable options:\\n\");\n\n\tfor (opt = 0; opt < OptList.size(); opt++) {\n\t\tif (!OptList[opt]->shortopt.empty())\n\t\t\tfprintf(stderr, \" %s,\", OptList[opt]->shortopt.c_str());\n\t\telse\n\t\t\tfprintf(stderr, \" \");\n\n\t\tfprintf(stderr, (std::string(\"%-\")+itostr(optmax+1)+\"s\").c_str(), OptList[opt]->longopt.c_str());\n\n\t\tif (!OptList[opt]->arg.empty())\n\t\t\tfprintf(stderr, (std::string(\"%-\")+itostr(argmax+3)+\"s\").c_str(), OptList[opt]->arg.c_str());\n\t\telse\n\t\t\tfprintf(stderr, (std::string(\"%-\")+itostr(argmax+3)+\"c\").c_str(), ' ');\n\n\t\tfprintf(stderr, \"%s\\n\", OptList[opt]->desc.c_str());\n\t}\n}\n\nstd::string NBCL::itostr(int in)\n{\n\tstd::stringstream out;\n\tout << in;\n\treturn out.str();\n}\n\nint NBCL::findOpt(std::string name)\n{\n\tfor (unsigned int opt = 0; opt < OptList.size(); opt++) {\n\t\tif (!OptList[opt]->shortopt.compare(name) ||\n\t\t\t!OptList[opt]->longopt.compare(name))\n\t\t\t\treturn opt;\n\t}\n\treturn -1;\n}\n\n\/* Thanks to:\n * http:\/\/stackoverflow.com\/questions\/1022957\n * http:\/\/stackoverflow.com\/questions\/6812224\n*\/\n\/* TODO: Use for breaking lines on small consoles. *\/\nunsigned int NBCL::getConsoleWidth()\n{\n\t#if defined __unix__ || defined __APPLE__\n\t\tstruct winsize w;\n\t\tioctl(STDOUT_FILENO, TIOCGWINSZ, &w);\n\t\treturn (unsigned int)w.ws_col;\n\t#elif _WIN32\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint ret = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);\n\t\tif (ret)\n\t\t\treturn (unsigned int)csbi.dwSize.X;\n\t\telse\n\t\t\treturn 0; \/* Failure *\/\n\t#else\n\t\treturn 0; \/* Failure *\/\n\t#endif\n}\n\nAnything starting with a dash is traditionally assumed to be an option switch.\/************************************\n** No Bullsh*t Command Line Parser **\n** nbcl.cpp **\n** Copyright 2011-2012 OmegaSDG **\n************************************\/\n\n#include \n#include \n\n#include \"nbcl.h\"\n\nNBCL::NBCL(int argc, char** argv) :\n\targc(argc), argv(argv), strayArgsDesc(\"\")\n{\n}\n\nNBCL::~NBCL()\n{\n\tunsigned int opt;\n\n\tfor (opt = 0; opt < OptList.size(); opt++)\n\t\tdelete OptList[opt];\n}\n\nvoid NBCL::insert(std::string shortopt, std::string longopt,\n\tstd::string arg, std::string desc)\n{\n\tOption* opt = new Option;\n\topt->shortopt = shortopt;\n\topt->longopt = longopt;\n\topt->arg = arg;\n\topt->desc = desc;\n\topt->present = false;\n\topt->value = \"\";\n\tOptList.push_back(opt);\n}\n\nvoid NBCL::setStrayArgsDesc(std::string desc)\n{\n\tstrayArgsDesc = desc;\n}\n\nbool NBCL::parse()\n{\n\tint argn;\n\tint opt;\n\n\tfor (argn = 1; argn < argc; argn++) { \/* Read command line. *\/\n\t\topt = findOpt(argv[argn]);\n\t\tif (opt!=-1) { \/* This argument is an option switch. *\/\n\t\t\tif (!OptList[opt]->arg.empty()) { \/* It takes an argument. *\/\n\t\t\t\tif (argn + 1 < argc) {\n\t\t\t\t\tOptList[opt]->value = argv[argn+1]; \/* Add next argument as the option value. *\/\n\t\t\t\t\targn++;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\tOptList[opt]->present = true; \/* Tell the option it exists. *\/\n\t\t}\n\t\telse if (argv[argn][0] == '-') \/* Nonexistent option. *\/\n\t\t\treturn false;\n\t\telse \/* This argument is a stray. *\/\n\t\t\tstrayArgsList.push_back(argv[argn]);\n\t}\n\treturn true;\n}\n\nbool NBCL::check(std::string longopt)\n{\n\tint opt = findOpt(longopt);\n\tif (opt!=-1)\n\t\treturn OptList[opt]->present;\n\telse\n\t\treturn false;\n}\n\nstd::string NBCL::get(std::string longopt)\n{\n\tint opt = findOpt(longopt);\n\tif (opt!=-1)\n\t\treturn OptList[opt]->value;\n\telse\n\t\treturn \"\";\n}\n\nvoid NBCL::usage()\n{\n\tint optmax = 0;\n\tint argmax = 0;\n\n\tusageSize(&optmax, &argmax);\n\tusagePrintShort();\n\tusagePrintLong(optmax, argmax);\n}\n\nstd::vector NBCL::getStrayArgsList()\n{\n\treturn strayArgsList;\n}\n\n\/* Makes width calculations needed for formatting usage output. *\/\nvoid NBCL::usageSize(int* optmax, int* argmax)\n{\n\tunsigned int opt;\n\n\tfor (opt = 0; opt < OptList.size(); opt++) {\n\t\tif (OptList[opt]->shortopt.size() + OptList[opt]->longopt.size() > (unsigned)*optmax)\n\t\t\t*optmax = (int)OptList[opt]->shortopt.size() + (int)OptList[opt]->longopt.size() + 1;\n\n\t\tif ((int)OptList[opt]->arg.size() > *argmax)\n\t\t\t*argmax = (int)OptList[opt]->arg.size();\n\t}\n}\n\nvoid NBCL::usagePrintShort()\n{\n\t#ifdef _WIN32\n\t\tchar fname[_MAX_FNAME];\n\t\tchar ext[_MAX_EXT];\n\t\t_splitpath(argv[0], NULL, NULL, fname, ext);\n\t\tif (ext[strlen(ext)-1] == ' ') \/* Windows thinks I want a space at the end. It's wrong. *\/\n\t\t\text[strlen(ext)-1] = 0;\n\t\tfprintf(stderr, \"Usage: %s%s [OPTIONS] \", fname, ext);\n\t#else\n\t\tfprintf(stderr, \"Usage: %s [OPTIONS] \", argv[0]);\n\t#endif\n\tfprintf(stderr, strayArgsDesc.c_str());\n}\n\n\/* Lots of ugly formatting code. *\/\nvoid NBCL::usagePrintLong(int optmax, int argmax)\n{\n\tunsigned int opt;\n\n\tfprintf(stderr, \"\\n\\nAvailable options:\\n\");\n\n\tfor (opt = 0; opt < OptList.size(); opt++) {\n\t\tif (!OptList[opt]->shortopt.empty())\n\t\t\tfprintf(stderr, \" %s,\", OptList[opt]->shortopt.c_str());\n\t\telse\n\t\t\tfprintf(stderr, \" \");\n\n\t\tfprintf(stderr, (std::string(\"%-\")+itostr(optmax+1)+\"s\").c_str(), OptList[opt]->longopt.c_str());\n\n\t\tif (!OptList[opt]->arg.empty())\n\t\t\tfprintf(stderr, (std::string(\"%-\")+itostr(argmax+3)+\"s\").c_str(), OptList[opt]->arg.c_str());\n\t\telse\n\t\t\tfprintf(stderr, (std::string(\"%-\")+itostr(argmax+3)+\"c\").c_str(), ' ');\n\n\t\tfprintf(stderr, \"%s\\n\", OptList[opt]->desc.c_str());\n\t}\n}\n\nstd::string NBCL::itostr(int in)\n{\n\tstd::stringstream out;\n\tout << in;\n\treturn out.str();\n}\n\nint NBCL::findOpt(std::string name)\n{\n\tfor (unsigned int opt = 0; opt < OptList.size(); opt++) {\n\t\tif (!OptList[opt]->shortopt.compare(name) ||\n\t\t\t!OptList[opt]->longopt.compare(name))\n\t\t\t\treturn opt;\n\t}\n\treturn -1;\n}\n\n\/* Thanks to:\n * http:\/\/stackoverflow.com\/questions\/1022957\n * http:\/\/stackoverflow.com\/questions\/6812224\n*\/\n\/* TODO: Use for breaking lines on small consoles. *\/\nunsigned int NBCL::getConsoleWidth()\n{\n\t#if defined __unix__ || defined __APPLE__\n\t\tstruct winsize w;\n\t\tioctl(STDOUT_FILENO, TIOCGWINSZ, &w);\n\t\treturn (unsigned int)w.ws_col;\n\t#elif _WIN32\n\t\tCONSOLE_SCREEN_BUFFER_INFO csbi;\n\t\tint ret = GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);\n\t\tif (ret)\n\t\t\treturn (unsigned int)csbi.dwSize.X;\n\t\telse\n\t\t\treturn 0; \/* Failure *\/\n\t#else\n\t\treturn 0; \/* Failure *\/\n\t#endif\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/autofill\/autofill_dialog.h\"\n#include \"chrome\/browser\/autofill\/autofill_infobar_delegate.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"webkit\/glue\/form_data.h\"\n#include \"webkit\/glue\/form_field.h\"\n#include \"webkit\/glue\/form_field_values.h\"\n\nAutoFillManager::AutoFillManager(TabContents* tab_contents)\n : tab_contents_(tab_contents),\n personal_data_(NULL),\n infobar_(NULL) {\n DCHECK(tab_contents);\n personal_data_ = tab_contents_->profile()->GetPersonalDataManager();\n}\n\nAutoFillManager::~AutoFillManager() {\n if (personal_data_)\n personal_data_->RemoveObserver(this);\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement);\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);\n prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false);\n}\n\nvoid AutoFillManager::FormFieldValuesSubmitted(\n const webkit_glue::FormFieldValues& form) {\n if (!personal_data_)\n return;\n\n \/\/ Grab a copy of the form data.\n upload_form_structure_.reset(new FormStructure(form));\n\n if (!upload_form_structure_->IsAutoFillable())\n return;\n\n \/\/ Determine the possible field types.\n DeterminePossibleFieldTypes(upload_form_structure_.get());\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);\n if (!infobar_shown) {\n \/\/ Ask the user for permission to save form information.\n infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));\n } else if (IsAutoFillEnabled()) {\n HandleSubmit();\n }\n}\n\nvoid AutoFillManager::FormsSeen(\n const std::vector& forms) {\n if (!IsAutoFillEnabled())\n return;\n\n form_structures_.reset();\n for (std::vector::const_iterator iter =\n forms.begin();\n iter != forms.end(); ++iter) {\n FormStructure* form_structure = new FormStructure(*iter);\n DeterminePossibleFieldTypes(form_structure);\n form_structures_.push_back(form_structure);\n }\n}\n\nbool AutoFillManager::GetAutoFillSuggestions(\n int query_id, const webkit_glue::FormField& field) {\n if (!IsAutoFillEnabled())\n return false;\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (!host)\n return false;\n\n const std::vector& profiles = personal_data_->profiles();\n if (profiles.empty())\n return false;\n\n AutoFillFieldType type = UNKNOWN_TYPE;\n for (std::vector::iterator form = form_structures_.begin();\n form != form_structures_.end(); ++form) {\n for (std::vector::const_iterator iter = (*form)->begin();\n iter != (*form)->end(); ++iter) {\n \/\/ The field list is terminated with a NULL AutoFillField, so don't try to\n \/\/ dereference it.\n if (!*iter)\n break;\n\n AutoFillField* form_field = *iter;\n if (*form_field != field)\n continue;\n\n if (form_field->possible_types().find(NAME_FIRST) !=\n form_field->possible_types().end() ||\n form_field->heuristic_type() == NAME_FIRST) {\n type = NAME_FIRST;\n break;\n }\n\n if (form_field->possible_types().find(NAME_FULL) !=\n form_field->possible_types().end() ||\n form_field->heuristic_type() == NAME_FULL) {\n type = NAME_FULL;\n break;\n }\n }\n }\n\n if (type == UNKNOWN_TYPE)\n return false;\n\n std::vector names;\n std::vector labels;\n for (std::vector::const_iterator iter = profiles.begin();\n iter != profiles.end(); ++iter) {\n string16 name = (*iter)->GetFieldText(AutoFillType(type));\n string16 label = (*iter)->Label();\n\n \/\/ TODO(jhawkins): What if name.length() == 0?\n if (StartsWith(name, field.value(), false)) {\n names.push_back(name);\n labels.push_back(label);\n }\n }\n\n \/\/ No suggestions.\n if (names.empty())\n return false;\n\n \/\/ TODO(jhawkins): If the default profile is in this list, set it as the\n \/\/ default suggestion index.\n host->AutoFillSuggestionsReturned(query_id, names, labels, -1);\n return true;\n}\n\nbool AutoFillManager::FillAutoFillFormData(int query_id,\n const FormData& form,\n const string16& name,\n const string16& label) {\n if (!IsAutoFillEnabled())\n return false;\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (!host)\n return false;\n\n const std::vector& profiles = personal_data_->profiles();\n if (profiles.empty())\n return false;\n\n const AutoFillProfile* profile = NULL;\n for (std::vector::const_iterator iter = profiles.begin();\n iter != profiles.end(); ++iter) {\n if ((*iter)->Label() != label)\n continue;\n\n if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name &&\n (*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name)\n continue;\n\n profile = *iter;\n break;\n }\n\n if (!profile)\n return false;\n\n FormData result = form;\n for (std::vector::const_iterator iter =\n form_structures_.begin();\n iter != form_structures_.end(); ++iter) {\n const FormStructure* form_structure = *iter;\n if (*form_structure != form)\n continue;\n\n for (size_t i = 0; i < form_structure->field_count(); ++i) {\n const AutoFillField* field = form_structure->field(i);\n\n for (size_t j = 0; j < result.values.size(); ++j) {\n if (field->name() == result.elements[j]) {\n result.values[j] =\n profile->GetFieldText(AutoFillType(field->heuristic_type()));\n break;\n }\n }\n }\n }\n\n host->AutoFillFormDataFilled(query_id, result);\n return true;\n}\n\nvoid AutoFillManager::OnAutoFillDialogApply(\n std::vector* profiles,\n std::vector* credit_cards) {\n DCHECK(personal_data_);\n\n \/\/ Save the personal data.\n personal_data_->SetProfiles(profiles);\n personal_data_->SetCreditCards(credit_cards);\n\n HandleSubmit();\n}\n\nvoid AutoFillManager::OnPersonalDataLoaded() {\n DCHECK(personal_data_);\n\n \/\/ We might have been alerted that the PersonalDataManager has loaded, so\n \/\/ remove ourselves as observer.\n personal_data_->RemoveObserver(this);\n\n ShowAutoFillDialog(\n this, personal_data_->profiles(), personal_data_->credit_cards());\n}\n\nvoid AutoFillManager::OnInfoBarAccepted() {\n DCHECK(personal_data_);\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n prefs->SetBoolean(prefs::kAutoFillEnabled, true);\n\n \/\/ If the personal data manager has not loaded the data yet, set ourselves as\n \/\/ its observer so that we can listen for the OnPersonalDataLoaded signal.\n if (!personal_data_->IsDataLoaded())\n personal_data_->SetObserver(this);\n else\n OnPersonalDataLoaded();\n}\n\nvoid AutoFillManager::Reset() {\n upload_form_structure_.reset();\n}\n\nvoid AutoFillManager::DeterminePossibleFieldTypes(\n FormStructure* form_structure) {\n DCHECK(personal_data_);\n\n \/\/ TODO(jhawkins): Update field text.\n\n form_structure->GetHeuristicAutoFillTypes();\n\n for (size_t i = 0; i < form_structure->field_count(); i++) {\n const AutoFillField* field = form_structure->field(i);\n FieldTypeSet field_types;\n personal_data_->GetPossibleFieldTypes(field->value(), &field_types);\n form_structure->set_possible_types(i, field_types);\n }\n}\n\nvoid AutoFillManager::HandleSubmit() {\n DCHECK(personal_data_);\n\n \/\/ If there wasn't enough data to import then we don't want to send an upload\n \/\/ to the server.\n if (!personal_data_->ImportFormData(form_structures_.get(), this))\n return;\n\n UploadFormData();\n}\n\nvoid AutoFillManager::UploadFormData() {\n std::string xml;\n bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);\n DCHECK(ok);\n\n \/\/ TODO(jhawkins): Initiate the upload request thread.\n}\n\nbool AutoFillManager::IsAutoFillEnabled() {\n \/\/ The PersonalDataManager is NULL in OTR.\n if (!personal_data_)\n return false;\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n\n \/\/ Migrate obsolete autofill pref.\n if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) {\n bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled);\n prefs->ClearPref(prefs::kFormAutofillEnabled);\n prefs->SetBoolean(prefs::kAutoFillEnabled, enabled);\n return enabled;\n }\n\n return prefs->GetBoolean(prefs::kAutoFillEnabled);\n}\nEnable AutoFill++ by default for new profiles.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/autofill\/autofill_manager.h\"\n\n#include \n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/autofill\/autofill_dialog.h\"\n#include \"chrome\/browser\/autofill\/autofill_infobar_delegate.h\"\n#include \"chrome\/browser\/autofill\/form_structure.h\"\n#include \"chrome\/browser\/pref_service.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/browser\/renderer_host\/render_view_host.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"webkit\/glue\/form_data.h\"\n#include \"webkit\/glue\/form_field.h\"\n#include \"webkit\/glue\/form_field_values.h\"\n\nAutoFillManager::AutoFillManager(TabContents* tab_contents)\n : tab_contents_(tab_contents),\n personal_data_(NULL),\n infobar_(NULL) {\n DCHECK(tab_contents);\n personal_data_ = tab_contents_->profile()->GetPersonalDataManager();\n}\n\nAutoFillManager::~AutoFillManager() {\n if (personal_data_)\n personal_data_->RemoveObserver(this);\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement);\n}\n\n\/\/ static\nvoid AutoFillManager::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false);\n prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, true);\n}\n\nvoid AutoFillManager::FormFieldValuesSubmitted(\n const webkit_glue::FormFieldValues& form) {\n if (!personal_data_)\n return;\n\n \/\/ Grab a copy of the form data.\n upload_form_structure_.reset(new FormStructure(form));\n\n if (!upload_form_structure_->IsAutoFillable())\n return;\n\n \/\/ Determine the possible field types.\n DeterminePossibleFieldTypes(upload_form_structure_.get());\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown);\n if (!infobar_shown) {\n \/\/ Ask the user for permission to save form information.\n infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this));\n } else if (IsAutoFillEnabled()) {\n HandleSubmit();\n }\n}\n\nvoid AutoFillManager::FormsSeen(\n const std::vector& forms) {\n if (!IsAutoFillEnabled())\n return;\n\n form_structures_.reset();\n for (std::vector::const_iterator iter =\n forms.begin();\n iter != forms.end(); ++iter) {\n FormStructure* form_structure = new FormStructure(*iter);\n DeterminePossibleFieldTypes(form_structure);\n form_structures_.push_back(form_structure);\n }\n}\n\nbool AutoFillManager::GetAutoFillSuggestions(\n int query_id, const webkit_glue::FormField& field) {\n if (!IsAutoFillEnabled())\n return false;\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (!host)\n return false;\n\n const std::vector& profiles = personal_data_->profiles();\n if (profiles.empty())\n return false;\n\n AutoFillFieldType type = UNKNOWN_TYPE;\n for (std::vector::iterator form = form_structures_.begin();\n form != form_structures_.end(); ++form) {\n for (std::vector::const_iterator iter = (*form)->begin();\n iter != (*form)->end(); ++iter) {\n \/\/ The field list is terminated with a NULL AutoFillField, so don't try to\n \/\/ dereference it.\n if (!*iter)\n break;\n\n AutoFillField* form_field = *iter;\n if (*form_field != field)\n continue;\n\n if (form_field->possible_types().find(NAME_FIRST) !=\n form_field->possible_types().end() ||\n form_field->heuristic_type() == NAME_FIRST) {\n type = NAME_FIRST;\n break;\n }\n\n if (form_field->possible_types().find(NAME_FULL) !=\n form_field->possible_types().end() ||\n form_field->heuristic_type() == NAME_FULL) {\n type = NAME_FULL;\n break;\n }\n }\n }\n\n if (type == UNKNOWN_TYPE)\n return false;\n\n std::vector names;\n std::vector labels;\n for (std::vector::const_iterator iter = profiles.begin();\n iter != profiles.end(); ++iter) {\n string16 name = (*iter)->GetFieldText(AutoFillType(type));\n string16 label = (*iter)->Label();\n\n \/\/ TODO(jhawkins): What if name.length() == 0?\n if (StartsWith(name, field.value(), false)) {\n names.push_back(name);\n labels.push_back(label);\n }\n }\n\n \/\/ No suggestions.\n if (names.empty())\n return false;\n\n \/\/ TODO(jhawkins): If the default profile is in this list, set it as the\n \/\/ default suggestion index.\n host->AutoFillSuggestionsReturned(query_id, names, labels, -1);\n return true;\n}\n\nbool AutoFillManager::FillAutoFillFormData(int query_id,\n const FormData& form,\n const string16& name,\n const string16& label) {\n if (!IsAutoFillEnabled())\n return false;\n\n RenderViewHost* host = tab_contents_->render_view_host();\n if (!host)\n return false;\n\n const std::vector& profiles = personal_data_->profiles();\n if (profiles.empty())\n return false;\n\n const AutoFillProfile* profile = NULL;\n for (std::vector::const_iterator iter = profiles.begin();\n iter != profiles.end(); ++iter) {\n if ((*iter)->Label() != label)\n continue;\n\n if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name &&\n (*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name)\n continue;\n\n profile = *iter;\n break;\n }\n\n if (!profile)\n return false;\n\n FormData result = form;\n for (std::vector::const_iterator iter =\n form_structures_.begin();\n iter != form_structures_.end(); ++iter) {\n const FormStructure* form_structure = *iter;\n if (*form_structure != form)\n continue;\n\n for (size_t i = 0; i < form_structure->field_count(); ++i) {\n const AutoFillField* field = form_structure->field(i);\n\n for (size_t j = 0; j < result.values.size(); ++j) {\n if (field->name() == result.elements[j]) {\n result.values[j] =\n profile->GetFieldText(AutoFillType(field->heuristic_type()));\n break;\n }\n }\n }\n }\n\n host->AutoFillFormDataFilled(query_id, result);\n return true;\n}\n\nvoid AutoFillManager::OnAutoFillDialogApply(\n std::vector* profiles,\n std::vector* credit_cards) {\n DCHECK(personal_data_);\n\n \/\/ Save the personal data.\n personal_data_->SetProfiles(profiles);\n personal_data_->SetCreditCards(credit_cards);\n\n HandleSubmit();\n}\n\nvoid AutoFillManager::OnPersonalDataLoaded() {\n DCHECK(personal_data_);\n\n \/\/ We might have been alerted that the PersonalDataManager has loaded, so\n \/\/ remove ourselves as observer.\n personal_data_->RemoveObserver(this);\n\n ShowAutoFillDialog(\n this, personal_data_->profiles(), personal_data_->credit_cards());\n}\n\nvoid AutoFillManager::OnInfoBarAccepted() {\n DCHECK(personal_data_);\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n prefs->SetBoolean(prefs::kAutoFillEnabled, true);\n\n \/\/ If the personal data manager has not loaded the data yet, set ourselves as\n \/\/ its observer so that we can listen for the OnPersonalDataLoaded signal.\n if (!personal_data_->IsDataLoaded())\n personal_data_->SetObserver(this);\n else\n OnPersonalDataLoaded();\n}\n\nvoid AutoFillManager::Reset() {\n upload_form_structure_.reset();\n}\n\nvoid AutoFillManager::DeterminePossibleFieldTypes(\n FormStructure* form_structure) {\n DCHECK(personal_data_);\n\n \/\/ TODO(jhawkins): Update field text.\n\n form_structure->GetHeuristicAutoFillTypes();\n\n for (size_t i = 0; i < form_structure->field_count(); i++) {\n const AutoFillField* field = form_structure->field(i);\n FieldTypeSet field_types;\n personal_data_->GetPossibleFieldTypes(field->value(), &field_types);\n form_structure->set_possible_types(i, field_types);\n }\n}\n\nvoid AutoFillManager::HandleSubmit() {\n DCHECK(personal_data_);\n\n \/\/ If there wasn't enough data to import then we don't want to send an upload\n \/\/ to the server.\n if (!personal_data_->ImportFormData(form_structures_.get(), this))\n return;\n\n UploadFormData();\n}\n\nvoid AutoFillManager::UploadFormData() {\n std::string xml;\n bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml);\n DCHECK(ok);\n\n \/\/ TODO(jhawkins): Initiate the upload request thread.\n}\n\nbool AutoFillManager::IsAutoFillEnabled() {\n \/\/ The PersonalDataManager is NULL in OTR.\n if (!personal_data_)\n return false;\n\n PrefService* prefs = tab_contents_->profile()->GetPrefs();\n\n \/\/ Migrate obsolete autofill pref.\n if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) {\n bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled);\n prefs->ClearPref(prefs::kFormAutofillEnabled);\n prefs->SetBoolean(prefs::kAutoFillEnabled, enabled);\n return enabled;\n }\n\n return prefs->GetBoolean(prefs::kAutoFillEnabled);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/startup_helper.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/webstore_standalone_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/api\/i18n\/default_locale_handler.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"ipc\/ipc_message.h\"\n\nnamespace {\n\nvoid PrintPackExtensionMessage(const std::string& message) {\n printf(\"%s\\n\", message.c_str());\n}\n\n} \/\/ namespace\n\nnamespace extensions {\n\nStartupHelper::StartupHelper() : pack_job_succeeded_(false) {\n (new DefaultLocaleHandler)->Register();\n}\n\nvoid StartupHelper::OnPackSuccess(\n const base::FilePath& crx_path,\n const base::FilePath& output_private_key_path) {\n pack_job_succeeded_ = true;\n PrintPackExtensionMessage(\n UTF16ToUTF8(\n PackExtensionJob::StandardSuccessMessage(crx_path,\n output_private_key_path)));\n}\n\nvoid StartupHelper::OnPackFailure(const std::string& error_message,\n ExtensionCreator::ErrorType type) {\n PrintPackExtensionMessage(error_message);\n}\n\nbool StartupHelper::PackExtension(const CommandLine& cmd_line) {\n if (!cmd_line.HasSwitch(switches::kPackExtension))\n return false;\n\n \/\/ Input Paths.\n base::FilePath src_dir =\n cmd_line.GetSwitchValuePath(switches::kPackExtension);\n base::FilePath private_key_path;\n if (cmd_line.HasSwitch(switches::kPackExtensionKey)) {\n private_key_path = cmd_line.GetSwitchValuePath(switches::kPackExtensionKey);\n }\n\n \/\/ Launch a job to perform the packing on the file thread. Ignore warnings\n \/\/ from the packing process. (e.g. Overwrite any existing crx file.)\n pack_job_ = new PackExtensionJob(this, src_dir, private_key_path,\n ExtensionCreator::kOverwriteCRX);\n pack_job_->set_asynchronous(false);\n pack_job_->Start();\n\n return pack_job_succeeded_;\n}\n\nbool StartupHelper::UninstallExtension(const CommandLine& cmd_line,\n Profile* profile) {\n DCHECK(profile);\n\n if (!cmd_line.HasSwitch(switches::kUninstallExtension))\n return false;\n\n ExtensionService* extension_service = profile->GetExtensionService();\n if (!extension_service)\n return false;\n\n std::string extension_id = cmd_line.GetSwitchValueASCII(\n switches::kUninstallExtension);\n return ExtensionService::UninstallExtensionHelper(extension_service,\n extension_id);\n}\n\nnamespace {\n\nclass AppInstallHelper {\n public:\n \/\/ A callback for when the install process is done.\n typedef base::Callback DoneCallback;\n\n AppInstallHelper();\n virtual ~AppInstallHelper();\n bool success() { return success_; }\n const std::string& error() { return error_; }\n void BeginInstall(Profile* profile,\n const std::string& id,\n WebstoreStandaloneInstaller::PromptType prompt_type,\n DoneCallback callback);\n\n private:\n WebstoreStandaloneInstaller::Callback Callback();\n void OnAppInstallComplete(bool success, const std::string& error);\n\n DoneCallback done_callback_;\n\n \/\/ These hold on to the result of the app install when it is complete.\n bool success_;\n std::string error_;\n\n scoped_ptr web_contents_;\n scoped_refptr installer_;\n};\n\nAppInstallHelper::AppInstallHelper() : success_(false) {}\n\nAppInstallHelper::~AppInstallHelper() {}\n\nWebstoreStandaloneInstaller::Callback AppInstallHelper::Callback() {\n return base::Bind(&AppInstallHelper::OnAppInstallComplete,\n base::Unretained(this));\n}\n\nvoid AppInstallHelper::BeginInstall(\n Profile* profile,\n const std::string& id,\n WebstoreStandaloneInstaller::PromptType prompt_type,\n DoneCallback done_callback) {\n done_callback_ = done_callback;\n\n WebstoreStandaloneInstaller::Callback callback =\n base::Bind(&AppInstallHelper::OnAppInstallComplete,\n base::Unretained(this));\n installer_ = new WebstoreStandaloneInstaller(\n id,\n WebstoreStandaloneInstaller::DO_NOT_REQUIRE_VERIFIED_SITE,\n prompt_type,\n GURL(),\n profile,\n NULL,\n callback);\n installer_->BeginInstall();\n}\n\nvoid AppInstallHelper::OnAppInstallComplete(bool success,\n const std::string& error) {\n success_ = success;\n error_= error;\n done_callback_.Run();\n}\n\nvoid DeleteHelperAndRunCallback(AppInstallHelper* helper,\n base::Callback callback) {\n delete helper;\n callback.Run();\n}\n\n} \/\/ namespace\n\nbool StartupHelper::InstallFromWebstore(const CommandLine& cmd_line,\n Profile* profile) {\n std::string id = cmd_line.GetSwitchValueASCII(switches::kInstallFromWebstore);\n if (!Extension::IdIsValid(id)) {\n LOG(ERROR) << \"Invalid id for \" << switches::kInstallFromWebstore\n << \" : '\" << id << \"'\";\n return false;\n }\n\n AppInstallHelper helper;\n helper.BeginInstall(profile, id,\n WebstoreStandaloneInstaller::STANDARD_PROMPT,\n MessageLoop::QuitWhenIdleClosure());\n\n MessageLoop::current()->Run();\n if (!helper.success())\n LOG(ERROR) << \"InstallFromWebstore failed with error: \" << helper.error();\n return helper.success();\n}\n\nvoid StartupHelper::LimitedInstallFromWebstore(\n const CommandLine& cmd_line,\n Profile* profile,\n base::Callback done_callback) {\n std::string id = WebStoreIdFromLimitedInstallCmdLine(cmd_line);\n if (!Extension::IdIsValid(id)) {\n LOG(ERROR) << \"Invalid index for \" << switches::kLimitedInstallFromWebstore;\n done_callback.Run();\n return;\n }\n\n AppInstallHelper* helper = new AppInstallHelper();\n helper->BeginInstall(profile, id,\n WebstoreStandaloneInstaller::STANDARD_PROMPT,\n base::Bind(&DeleteHelperAndRunCallback, helper, done_callback));\n}\n\nstd::string StartupHelper::WebStoreIdFromLimitedInstallCmdLine(\n const CommandLine& cmd_line) {\n std::string index = cmd_line.GetSwitchValueASCII(\n switches::kLimitedInstallFromWebstore);\n std::string id;\n if (index == \"1\") {\n id = \"nckgahadagoaajjgafhacjanaoiihapd\";\n } else if (index == \"2\") {\n id = \"ecglahbcnmdpdciemllbhojghbkagdje\";\n }\n return id;\n}\n\nStartupHelper::~StartupHelper() {\n if (pack_job_.get())\n pack_job_->ClearClient();\n}\n\n} \/\/ namespace extensions\nFix --pack-extension for platform apps\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/startup_helper.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/bind_helpers.h\"\n#include \"base\/command_line.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/string_util.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/webstore_standalone_installer.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/api\/i18n\/default_locale_handler.h\"\n#include \"chrome\/common\/extensions\/background_info.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"content\/public\/browser\/web_contents.h\"\n#include \"ipc\/ipc_message.h\"\n\nnamespace {\n\nvoid PrintPackExtensionMessage(const std::string& message) {\n printf(\"%s\\n\", message.c_str());\n}\n\n} \/\/ namespace\n\nnamespace extensions {\n\nStartupHelper::StartupHelper() : pack_job_succeeded_(false) {\n (new DefaultLocaleHandler)->Register();\n (new BackgroundManifestHandler)->Register();\n}\n\nvoid StartupHelper::OnPackSuccess(\n const base::FilePath& crx_path,\n const base::FilePath& output_private_key_path) {\n pack_job_succeeded_ = true;\n PrintPackExtensionMessage(\n UTF16ToUTF8(\n PackExtensionJob::StandardSuccessMessage(crx_path,\n output_private_key_path)));\n}\n\nvoid StartupHelper::OnPackFailure(const std::string& error_message,\n ExtensionCreator::ErrorType type) {\n PrintPackExtensionMessage(error_message);\n}\n\nbool StartupHelper::PackExtension(const CommandLine& cmd_line) {\n if (!cmd_line.HasSwitch(switches::kPackExtension))\n return false;\n\n \/\/ Input Paths.\n base::FilePath src_dir =\n cmd_line.GetSwitchValuePath(switches::kPackExtension);\n base::FilePath private_key_path;\n if (cmd_line.HasSwitch(switches::kPackExtensionKey)) {\n private_key_path = cmd_line.GetSwitchValuePath(switches::kPackExtensionKey);\n }\n\n \/\/ Launch a job to perform the packing on the file thread. Ignore warnings\n \/\/ from the packing process. (e.g. Overwrite any existing crx file.)\n pack_job_ = new PackExtensionJob(this, src_dir, private_key_path,\n ExtensionCreator::kOverwriteCRX);\n pack_job_->set_asynchronous(false);\n pack_job_->Start();\n\n return pack_job_succeeded_;\n}\n\nbool StartupHelper::UninstallExtension(const CommandLine& cmd_line,\n Profile* profile) {\n DCHECK(profile);\n\n if (!cmd_line.HasSwitch(switches::kUninstallExtension))\n return false;\n\n ExtensionService* extension_service = profile->GetExtensionService();\n if (!extension_service)\n return false;\n\n std::string extension_id = cmd_line.GetSwitchValueASCII(\n switches::kUninstallExtension);\n return ExtensionService::UninstallExtensionHelper(extension_service,\n extension_id);\n}\n\nnamespace {\n\nclass AppInstallHelper {\n public:\n \/\/ A callback for when the install process is done.\n typedef base::Callback DoneCallback;\n\n AppInstallHelper();\n virtual ~AppInstallHelper();\n bool success() { return success_; }\n const std::string& error() { return error_; }\n void BeginInstall(Profile* profile,\n const std::string& id,\n WebstoreStandaloneInstaller::PromptType prompt_type,\n DoneCallback callback);\n\n private:\n WebstoreStandaloneInstaller::Callback Callback();\n void OnAppInstallComplete(bool success, const std::string& error);\n\n DoneCallback done_callback_;\n\n \/\/ These hold on to the result of the app install when it is complete.\n bool success_;\n std::string error_;\n\n scoped_ptr web_contents_;\n scoped_refptr installer_;\n};\n\nAppInstallHelper::AppInstallHelper() : success_(false) {}\n\nAppInstallHelper::~AppInstallHelper() {}\n\nWebstoreStandaloneInstaller::Callback AppInstallHelper::Callback() {\n return base::Bind(&AppInstallHelper::OnAppInstallComplete,\n base::Unretained(this));\n}\n\nvoid AppInstallHelper::BeginInstall(\n Profile* profile,\n const std::string& id,\n WebstoreStandaloneInstaller::PromptType prompt_type,\n DoneCallback done_callback) {\n done_callback_ = done_callback;\n\n WebstoreStandaloneInstaller::Callback callback =\n base::Bind(&AppInstallHelper::OnAppInstallComplete,\n base::Unretained(this));\n installer_ = new WebstoreStandaloneInstaller(\n id,\n WebstoreStandaloneInstaller::DO_NOT_REQUIRE_VERIFIED_SITE,\n prompt_type,\n GURL(),\n profile,\n NULL,\n callback);\n installer_->BeginInstall();\n}\n\nvoid AppInstallHelper::OnAppInstallComplete(bool success,\n const std::string& error) {\n success_ = success;\n error_= error;\n done_callback_.Run();\n}\n\nvoid DeleteHelperAndRunCallback(AppInstallHelper* helper,\n base::Callback callback) {\n delete helper;\n callback.Run();\n}\n\n} \/\/ namespace\n\nbool StartupHelper::InstallFromWebstore(const CommandLine& cmd_line,\n Profile* profile) {\n std::string id = cmd_line.GetSwitchValueASCII(switches::kInstallFromWebstore);\n if (!Extension::IdIsValid(id)) {\n LOG(ERROR) << \"Invalid id for \" << switches::kInstallFromWebstore\n << \" : '\" << id << \"'\";\n return false;\n }\n\n AppInstallHelper helper;\n helper.BeginInstall(profile, id,\n WebstoreStandaloneInstaller::STANDARD_PROMPT,\n MessageLoop::QuitWhenIdleClosure());\n\n MessageLoop::current()->Run();\n if (!helper.success())\n LOG(ERROR) << \"InstallFromWebstore failed with error: \" << helper.error();\n return helper.success();\n}\n\nvoid StartupHelper::LimitedInstallFromWebstore(\n const CommandLine& cmd_line,\n Profile* profile,\n base::Callback done_callback) {\n std::string id = WebStoreIdFromLimitedInstallCmdLine(cmd_line);\n if (!Extension::IdIsValid(id)) {\n LOG(ERROR) << \"Invalid index for \" << switches::kLimitedInstallFromWebstore;\n done_callback.Run();\n return;\n }\n\n AppInstallHelper* helper = new AppInstallHelper();\n helper->BeginInstall(profile, id,\n WebstoreStandaloneInstaller::STANDARD_PROMPT,\n base::Bind(&DeleteHelperAndRunCallback, helper, done_callback));\n}\n\nstd::string StartupHelper::WebStoreIdFromLimitedInstallCmdLine(\n const CommandLine& cmd_line) {\n std::string index = cmd_line.GetSwitchValueASCII(\n switches::kLimitedInstallFromWebstore);\n std::string id;\n if (index == \"1\") {\n id = \"nckgahadagoaajjgafhacjanaoiihapd\";\n } else if (index == \"2\") {\n id = \"ecglahbcnmdpdciemllbhojghbkagdje\";\n }\n return id;\n}\n\nStartupHelper::~StartupHelper() {\n if (pack_job_.get())\n pack_job_->ClearClient();\n}\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_dds\/dds\/dds_types.hpp\"\n#include \"iceoryx_dds\/gateway\/channel.hpp\"\n#include \"iceoryx_posh\/capro\/service_description.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace ::testing;\nusing ::testing::_;\n\n\/\/ ======================================== Helpers ======================================== \/\/\n\/\/ We do not need real channel terminals to test the base class.\nstruct StubbedIceoryxTerminal\n{\n StubbedIceoryxTerminal(iox::capro::ServiceDescription sd){};\n};\n\nstruct StubbedDDSTerminal\n{\n StubbedDDSTerminal(iox::dds::IdString sid, iox::dds::IdString iid, iox::dds::IdString eid){};\n};\n\nusing TestChannel = iox::dds::Channel;\n\n\/\/ ======================================== Fixture ======================================== \/\/\nclass ChannelTest : public Test\n{\n public:\n void SetUp(){};\n void TearDown(){};\n};\n\n\/\/ ======================================== Tests ======================================== \/\/\nTEST_F(ChannelTest, ReturnsEmptyOptionalIfObjectPoolExhausted)\n{\n auto channel = iox::dds::Channel::create({\"\", \"\", \"\"});\n}\niox-#273 fix warning in dds test\/\/ Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"iceoryx_dds\/dds\/dds_types.hpp\"\n#include \"iceoryx_dds\/gateway\/channel.hpp\"\n#include \"iceoryx_posh\/capro\/service_description.hpp\"\n\n#include \"test.hpp\"\n\nusing namespace ::testing;\nusing ::testing::_;\n\n\/\/ ======================================== Helpers ======================================== \/\/\n\/\/ We do not need real channel terminals to test the base class.\nstruct StubbedIceoryxTerminal\n{\n StubbedIceoryxTerminal(iox::capro::ServiceDescription){};\n};\n\nstruct StubbedDDSTerminal\n{\n StubbedDDSTerminal(iox::dds::IdString, iox::dds::IdString, iox::dds::IdString){};\n};\n\nusing TestChannel = iox::dds::Channel;\n\n\/\/ ======================================== Fixture ======================================== \/\/\nclass ChannelTest : public Test\n{\n public:\n void SetUp(){};\n void TearDown(){};\n};\n\n\/\/ ======================================== Tests ======================================== \/\/\nTEST_F(ChannelTest, ReturnsEmptyOptionalIfObjectPoolExhausted)\n{\n auto channel = iox::dds::Channel::create({\"\", \"\", \"\"});\n}\n<|endoftext|>"} {"text":"#include \"fof_brute.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\n\ntypedef std::pair Point;\n\ndouble dist(double *p1, double *p2, size_t ndim) {\n double d2 = 0.;\n for(size_t i = 0 ; i < ndim ; ++i) {\n d2 += pow(p1[i] - p2[i], 2);\n }\n return sqrt(d2);\n}\n\n} \/\/ anonymous namespace\n\n\/\/ A brute force friends of friends finder without the Rtree accelerator.\nstd::vector< std::vector > friends_of_friends_brute(\n\tdouble *data,\n\tsize_t npts,\n\tsize_t ndim,\n\tdouble linking_length\n) {\n \/\/Create list of unused points with indices\n std::vector unused;\n std::vector< std::vector< size_t > > groups;\n for(size_t i=0 ; i();\n \tauto toadd = std::vector();\n toadd.push_back(unused.back());\n unused.pop_back();\n\n while (!toadd.empty()) {\n \tauto point = toadd.back();\n \ttoadd.pop_back();\n \tgroup.push_back(point.first);\n\n \tfor (auto i = 0; i < unused.size(); ++i) {\n \t\tif(dist(unused[i].second, point.second, ndim) < linking_length) {\n toadd.push_back(unused[i]);\n unused[i].second = nullptr; \/\/ Mark the unused point to be deleted\n }\n \t}\n\n \/\/ Remove any deleted points\n \tunused.erase(\n std::remove_if(unused.begin(), unused.end(), [](Point p){return p.second == nullptr;}),\n unused.end()\n );\n }\n groups.push_back(group);\n }\n return groups;\n}\nRange based for loop#include \"fof_brute.hpp\"\n\n#include \n#include \n#include \n\nnamespace {\n\ntypedef std::pair Point;\n\ndouble dist(double *p1, double *p2, size_t ndim) {\n double d2 = 0.;\n for(size_t i = 0 ; i < ndim ; ++i) {\n d2 += pow(p1[i] - p2[i], 2);\n }\n return sqrt(d2);\n}\n\n} \/\/ anonymous namespace\n\n\/\/ A brute force friends of friends finder without the Rtree accelerator.\nstd::vector< std::vector > friends_of_friends_brute(\n\tdouble *data,\n\tsize_t npts,\n\tsize_t ndim,\n\tdouble linking_length\n) {\n \/\/Create list of unused points with indices\n std::vector unused;\n std::vector< std::vector< size_t > > groups;\n for(size_t i=0 ; i();\n \tauto toadd = std::vector();\n toadd.push_back(unused.back());\n unused.pop_back();\n\n while (!toadd.empty()) {\n \tauto point = toadd.back();\n \ttoadd.pop_back();\n \tgroup.push_back(point.first);\n\n for (auto& unused_point: unused) {\n if(dist(unused_point.second, point.second, ndim) < linking_length) {\n toadd.push_back(unused_point);\n unused_point.second = nullptr; \/\/ Mark the unused point to be deleted\n } \n }\n\n \/\/ Remove any deleted points\n \tunused.erase(\n std::remove_if(unused.begin(), unused.end(), [](Point p){return p.second == nullptr;}),\n unused.end()\n );\n }\n groups.push_back(group);\n }\n return groups;\n}\n<|endoftext|>"} {"text":"Add test for derived usage of reflector_init<|endoftext|>"} {"text":"\/\/===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the PassManagerBuilder class, which is used to set up a\n\/\/ \"standard\" optimization sequence suitable for languages like C and C++.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\n#include \"llvm-c\/Transforms\/PassManagerBuilder.h\"\n\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/DefaultPasses.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Passes.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetLibraryInfo.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Vectorize.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\nusing namespace llvm;\n\nstatic cl::opt\nRunVectorization(\"vectorize\", cl::desc(\"Run vectorization passes\"));\n\nPassManagerBuilder::PassManagerBuilder() {\n OptLevel = 2;\n SizeLevel = 0;\n LibraryInfo = 0;\n Inliner = 0;\n DisableSimplifyLibCalls = false;\n DisableUnitAtATime = false;\n DisableUnrollLoops = false;\n Vectorize = RunVectorization;\n}\n\nPassManagerBuilder::~PassManagerBuilder() {\n delete LibraryInfo;\n delete Inliner;\n}\n\n\/\/\/ Set of global extensions, automatically added as part of the standard set.\nstatic ManagedStatic, 8> > GlobalExtensions;\n\nvoid PassManagerBuilder::addGlobalExtension(\n PassManagerBuilder::ExtensionPointTy Ty,\n PassManagerBuilder::ExtensionFn Fn) {\n GlobalExtensions->push_back(std::make_pair(Ty, Fn));\n}\n\nvoid PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {\n Extensions.push_back(std::make_pair(Ty, Fn));\n}\n\nvoid PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,\n PassManagerBase &PM) const {\n for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)\n if ((*GlobalExtensions)[i].first == ETy)\n (*GlobalExtensions)[i].second(*this, PM);\n for (unsigned i = 0, e = Extensions.size(); i != e; ++i)\n if (Extensions[i].first == ETy)\n Extensions[i].second(*this, PM);\n}\n\nvoid\nPassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {\n \/\/ Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that\n \/\/ BasicAliasAnalysis wins if they disagree. This is intended to help\n \/\/ support \"obvious\" type-punning idioms.\n PM.add(createTypeBasedAliasAnalysisPass());\n PM.add(createBasicAliasAnalysisPass());\n}\n\nvoid PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {\n addExtensionsToPM(EP_EarlyAsPossible, FPM);\n\n \/\/ Add LibraryInfo if we have some.\n if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));\n\n if (OptLevel == 0) return;\n\n addInitialAliasAnalysisPasses(FPM);\n\n FPM.add(createCFGSimplificationPass());\n FPM.add(createScalarReplAggregatesPass());\n FPM.add(createEarlyCSEPass());\n FPM.add(createLowerExpectIntrinsicPass());\n}\n\nvoid PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {\n \/\/ If all optimizations are disabled, just run the always-inline pass.\n if (OptLevel == 0) {\n if (Inliner) {\n MPM.add(Inliner);\n Inliner = 0;\n }\n addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);\n return;\n }\n\n \/\/ Add LibraryInfo if we have some.\n if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));\n\n addInitialAliasAnalysisPasses(MPM);\n\n if (!DisableUnitAtATime) {\n addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);\n\n MPM.add(createGlobalOptimizerPass()); \/\/ Optimize out global vars\n\n MPM.add(createIPSCCPPass()); \/\/ IP SCCP\n MPM.add(createDeadArgEliminationPass()); \/\/ Dead argument elimination\n\n MPM.add(createInstructionCombiningPass());\/\/ Clean up after IPCP & DAE\n MPM.add(createCFGSimplificationPass()); \/\/ Clean up after IPCP & DAE\n }\n\n \/\/ Start of CallGraph SCC passes.\n if (!DisableUnitAtATime)\n MPM.add(createPruneEHPass()); \/\/ Remove dead EH info\n if (Inliner) {\n MPM.add(Inliner);\n Inliner = 0;\n }\n if (!DisableUnitAtATime)\n MPM.add(createFunctionAttrsPass()); \/\/ Set readonly\/readnone attrs\n if (OptLevel > 2)\n MPM.add(createArgumentPromotionPass()); \/\/ Scalarize uninlined fn args\n\n \/\/ Start of function pass.\n \/\/ Break up aggregate allocas, using SSAUpdater.\n MPM.add(createScalarReplAggregatesPass(-1, false));\n MPM.add(createEarlyCSEPass()); \/\/ Catch trivial redundancies\n if (!DisableSimplifyLibCalls)\n MPM.add(createSimplifyLibCallsPass()); \/\/ Library Call Optimizations\n MPM.add(createJumpThreadingPass()); \/\/ Thread jumps.\n MPM.add(createCorrelatedValuePropagationPass()); \/\/ Propagate conditionals\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createInstructionCombiningPass()); \/\/ Combine silly seq's\n\n MPM.add(createTailCallEliminationPass()); \/\/ Eliminate tail calls\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createReassociatePass()); \/\/ Reassociate expressions\n MPM.add(createLoopRotatePass()); \/\/ Rotate Loop\n MPM.add(createLICMPass()); \/\/ Hoist loop invariants\n MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));\n MPM.add(createInstructionCombiningPass());\n MPM.add(createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n MPM.add(createLoopIdiomPass()); \/\/ Recognize idioms like memset.\n MPM.add(createLoopDeletionPass()); \/\/ Delete dead loops\n if (!DisableUnrollLoops)\n MPM.add(createLoopUnrollPass()); \/\/ Unroll small loops\n addExtensionsToPM(EP_LoopOptimizerEnd, MPM);\n\n if (OptLevel > 1)\n MPM.add(createGVNPass()); \/\/ Remove redundancies\n MPM.add(createMemCpyOptPass()); \/\/ Remove memcpy \/ form memset\n MPM.add(createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n MPM.add(createInstructionCombiningPass());\n MPM.add(createJumpThreadingPass()); \/\/ Thread jumps\n MPM.add(createCorrelatedValuePropagationPass());\n MPM.add(createDeadStoreEliminationPass()); \/\/ Delete dead stores\n\n addExtensionsToPM(EP_ScalarOptimizerLate, MPM);\n\n if (Vectorize) {\n MPM.add(createBBVectorizePass());\n MPM.add(createInstructionCombiningPass());\n if (OptLevel > 1)\n MPM.add(createGVNPass()); \/\/ Remove redundancies\n }\n\n MPM.add(createAggressiveDCEPass()); \/\/ Delete dead instructions\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createInstructionCombiningPass()); \/\/ Clean up after everything.\n\n if (!DisableUnitAtATime) {\n \/\/ FIXME: We shouldn't bother with this anymore.\n MPM.add(createStripDeadPrototypesPass()); \/\/ Get rid of dead prototypes\n\n \/\/ GlobalOpt already deletes dead functions and globals, at -O3 try a\n \/\/ late pass of GlobalDCE. It is capable of deleting dead cycles.\n if (OptLevel > 2)\n MPM.add(createGlobalDCEPass()); \/\/ Remove dead fns and globals.\n\n if (OptLevel > 1)\n MPM.add(createConstantMergePass()); \/\/ Merge dup global constants\n }\n addExtensionsToPM(EP_OptimizerLast, MPM);\n}\n\nvoid PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,\n bool Internalize,\n bool RunInliner,\n bool DisableGVNLoadPRE) {\n \/\/ Provide AliasAnalysis services for optimizations.\n addInitialAliasAnalysisPasses(PM);\n\n \/\/ Now that composite has been compiled, scan through the module, looking\n \/\/ for a main function. If main is defined, mark all other functions\n \/\/ internal.\n if (Internalize)\n PM.add(createInternalizePass(true));\n\n \/\/ Propagate constants at call sites into the functions they call. This\n \/\/ opens opportunities for globalopt (and inlining) by substituting function\n \/\/ pointers passed as arguments to direct uses of functions.\n PM.add(createIPSCCPPass());\n\n \/\/ Now that we internalized some globals, see if we can hack on them!\n PM.add(createGlobalOptimizerPass());\n\n \/\/ Linking modules together can lead to duplicated global constants, only\n \/\/ keep one copy of each constant.\n PM.add(createConstantMergePass());\n\n \/\/ Remove unused arguments from functions.\n PM.add(createDeadArgEliminationPass());\n\n \/\/ Reduce the code after globalopt and ipsccp. Both can open up significant\n \/\/ simplification opportunities, and both can propagate functions through\n \/\/ function pointers. When this happens, we often have to resolve varargs\n \/\/ calls, etc, so let instcombine do this.\n PM.add(createInstructionCombiningPass());\n\n \/\/ Inline small functions\n if (RunInliner)\n PM.add(createFunctionInliningPass());\n\n PM.add(createPruneEHPass()); \/\/ Remove dead EH info.\n\n \/\/ Optimize globals again if we ran the inliner.\n if (RunInliner)\n PM.add(createGlobalOptimizerPass());\n PM.add(createGlobalDCEPass()); \/\/ Remove dead functions.\n\n \/\/ If we didn't decide to inline a function, check to see if we can\n \/\/ transform it to pass arguments by value instead of by reference.\n PM.add(createArgumentPromotionPass());\n\n \/\/ The IPO passes may leave cruft around. Clean up after them.\n PM.add(createInstructionCombiningPass());\n PM.add(createJumpThreadingPass());\n \/\/ Break up allocas\n PM.add(createScalarReplAggregatesPass());\n\n \/\/ Run a few AA driven optimizations here and now, to cleanup the code.\n PM.add(createFunctionAttrsPass()); \/\/ Add nocapture.\n PM.add(createGlobalsModRefPass()); \/\/ IP alias analysis.\n\n PM.add(createLICMPass()); \/\/ Hoist loop invariants.\n PM.add(createGVNPass(DisableGVNLoadPRE)); \/\/ Remove redundancies.\n PM.add(createMemCpyOptPass()); \/\/ Remove dead memcpys.\n \/\/ Nuke dead stores.\n PM.add(createDeadStoreEliminationPass());\n\n \/\/ Cleanup and simplify the code after the scalar optimizations.\n PM.add(createInstructionCombiningPass());\n\n PM.add(createJumpThreadingPass());\n\n \/\/ Delete basic blocks, which optimization passes may have killed.\n PM.add(createCFGSimplificationPass());\n\n \/\/ Now that we have optimized the program, discard unreachable functions.\n PM.add(createGlobalDCEPass());\n}\n\nLLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void) {\n PassManagerBuilder *PMB = new PassManagerBuilder();\n return wrap(PMB);\n}\n\nvoid LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {\n PassManagerBuilder *Builder = unwrap(PMB);\n delete Builder;\n}\n\nvoid\nLLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,\n unsigned OptLevel) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->OptLevel = OptLevel;\n}\n\nvoid\nLLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,\n unsigned SizeLevel) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->SizeLevel = SizeLevel;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableUnitAtATime = Value;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableUnrollLoops = Value;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableSimplifyLibCalls = Value;\n}\n\nvoid\nLLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,\n unsigned Threshold) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->Inliner = createFunctionInliningPass(Threshold);\n}\n\nvoid\nLLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM) {\n PassManagerBuilder *Builder = unwrap(PMB);\n FunctionPassManager *FPM = unwrap(PM);\n Builder->populateFunctionPassManager(*FPM);\n}\n\nvoid\nLLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM) {\n PassManagerBuilder *Builder = unwrap(PMB);\n PassManagerBase *MPM = unwrap(PM);\n Builder->populateModulePassManager(*MPM);\n}\n\nvoid LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM,\n bool Internalize,\n bool RunInliner) {\n PassManagerBuilder *Builder = unwrap(PMB);\n PassManagerBase *LPM = unwrap(PM);\n Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);\n}\nBy default, use Early-CSE instead of GVN for vectorization cleanup.\/\/===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines the PassManagerBuilder class, which is used to set up a\n\/\/ \"standard\" optimization sequence suitable for languages like C and C++.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\n#include \"llvm\/Transforms\/IPO\/PassManagerBuilder.h\"\n\n#include \"llvm-c\/Transforms\/PassManagerBuilder.h\"\n\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/DefaultPasses.h\"\n#include \"llvm\/PassManager.h\"\n#include \"llvm\/Analysis\/Passes.h\"\n#include \"llvm\/Analysis\/Verifier.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Target\/TargetLibraryInfo.h\"\n#include \"llvm\/Transforms\/Scalar.h\"\n#include \"llvm\/Transforms\/Vectorize.h\"\n#include \"llvm\/Transforms\/IPO.h\"\n#include \"llvm\/ADT\/SmallVector.h\"\n#include \"llvm\/Support\/ManagedStatic.h\"\n\nusing namespace llvm;\n\nstatic cl::opt\nRunVectorization(\"vectorize\", cl::desc(\"Run vectorization passes\"));\n\nstatic cl::opt\nUseGVNAfterVectorization(\"use-gvn-after-vectorization\",\n cl::init(false), cl::Hidden,\n cl::desc(\"Run GVN instead of Early CSE after vectorization passes\"));\n\nPassManagerBuilder::PassManagerBuilder() {\n OptLevel = 2;\n SizeLevel = 0;\n LibraryInfo = 0;\n Inliner = 0;\n DisableSimplifyLibCalls = false;\n DisableUnitAtATime = false;\n DisableUnrollLoops = false;\n Vectorize = RunVectorization;\n}\n\nPassManagerBuilder::~PassManagerBuilder() {\n delete LibraryInfo;\n delete Inliner;\n}\n\n\/\/\/ Set of global extensions, automatically added as part of the standard set.\nstatic ManagedStatic, 8> > GlobalExtensions;\n\nvoid PassManagerBuilder::addGlobalExtension(\n PassManagerBuilder::ExtensionPointTy Ty,\n PassManagerBuilder::ExtensionFn Fn) {\n GlobalExtensions->push_back(std::make_pair(Ty, Fn));\n}\n\nvoid PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) {\n Extensions.push_back(std::make_pair(Ty, Fn));\n}\n\nvoid PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy,\n PassManagerBase &PM) const {\n for (unsigned i = 0, e = GlobalExtensions->size(); i != e; ++i)\n if ((*GlobalExtensions)[i].first == ETy)\n (*GlobalExtensions)[i].second(*this, PM);\n for (unsigned i = 0, e = Extensions.size(); i != e; ++i)\n if (Extensions[i].first == ETy)\n Extensions[i].second(*this, PM);\n}\n\nvoid\nPassManagerBuilder::addInitialAliasAnalysisPasses(PassManagerBase &PM) const {\n \/\/ Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that\n \/\/ BasicAliasAnalysis wins if they disagree. This is intended to help\n \/\/ support \"obvious\" type-punning idioms.\n PM.add(createTypeBasedAliasAnalysisPass());\n PM.add(createBasicAliasAnalysisPass());\n}\n\nvoid PassManagerBuilder::populateFunctionPassManager(FunctionPassManager &FPM) {\n addExtensionsToPM(EP_EarlyAsPossible, FPM);\n\n \/\/ Add LibraryInfo if we have some.\n if (LibraryInfo) FPM.add(new TargetLibraryInfo(*LibraryInfo));\n\n if (OptLevel == 0) return;\n\n addInitialAliasAnalysisPasses(FPM);\n\n FPM.add(createCFGSimplificationPass());\n FPM.add(createScalarReplAggregatesPass());\n FPM.add(createEarlyCSEPass());\n FPM.add(createLowerExpectIntrinsicPass());\n}\n\nvoid PassManagerBuilder::populateModulePassManager(PassManagerBase &MPM) {\n \/\/ If all optimizations are disabled, just run the always-inline pass.\n if (OptLevel == 0) {\n if (Inliner) {\n MPM.add(Inliner);\n Inliner = 0;\n }\n addExtensionsToPM(EP_EnabledOnOptLevel0, MPM);\n return;\n }\n\n \/\/ Add LibraryInfo if we have some.\n if (LibraryInfo) MPM.add(new TargetLibraryInfo(*LibraryInfo));\n\n addInitialAliasAnalysisPasses(MPM);\n\n if (!DisableUnitAtATime) {\n addExtensionsToPM(EP_ModuleOptimizerEarly, MPM);\n\n MPM.add(createGlobalOptimizerPass()); \/\/ Optimize out global vars\n\n MPM.add(createIPSCCPPass()); \/\/ IP SCCP\n MPM.add(createDeadArgEliminationPass()); \/\/ Dead argument elimination\n\n MPM.add(createInstructionCombiningPass());\/\/ Clean up after IPCP & DAE\n MPM.add(createCFGSimplificationPass()); \/\/ Clean up after IPCP & DAE\n }\n\n \/\/ Start of CallGraph SCC passes.\n if (!DisableUnitAtATime)\n MPM.add(createPruneEHPass()); \/\/ Remove dead EH info\n if (Inliner) {\n MPM.add(Inliner);\n Inliner = 0;\n }\n if (!DisableUnitAtATime)\n MPM.add(createFunctionAttrsPass()); \/\/ Set readonly\/readnone attrs\n if (OptLevel > 2)\n MPM.add(createArgumentPromotionPass()); \/\/ Scalarize uninlined fn args\n\n \/\/ Start of function pass.\n \/\/ Break up aggregate allocas, using SSAUpdater.\n MPM.add(createScalarReplAggregatesPass(-1, false));\n MPM.add(createEarlyCSEPass()); \/\/ Catch trivial redundancies\n if (!DisableSimplifyLibCalls)\n MPM.add(createSimplifyLibCallsPass()); \/\/ Library Call Optimizations\n MPM.add(createJumpThreadingPass()); \/\/ Thread jumps.\n MPM.add(createCorrelatedValuePropagationPass()); \/\/ Propagate conditionals\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createInstructionCombiningPass()); \/\/ Combine silly seq's\n\n MPM.add(createTailCallEliminationPass()); \/\/ Eliminate tail calls\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createReassociatePass()); \/\/ Reassociate expressions\n MPM.add(createLoopRotatePass()); \/\/ Rotate Loop\n MPM.add(createLICMPass()); \/\/ Hoist loop invariants\n MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3));\n MPM.add(createInstructionCombiningPass());\n MPM.add(createIndVarSimplifyPass()); \/\/ Canonicalize indvars\n MPM.add(createLoopIdiomPass()); \/\/ Recognize idioms like memset.\n MPM.add(createLoopDeletionPass()); \/\/ Delete dead loops\n if (!DisableUnrollLoops)\n MPM.add(createLoopUnrollPass()); \/\/ Unroll small loops\n addExtensionsToPM(EP_LoopOptimizerEnd, MPM);\n\n if (OptLevel > 1)\n MPM.add(createGVNPass()); \/\/ Remove redundancies\n MPM.add(createMemCpyOptPass()); \/\/ Remove memcpy \/ form memset\n MPM.add(createSCCPPass()); \/\/ Constant prop with SCCP\n\n \/\/ Run instcombine after redundancy elimination to exploit opportunities\n \/\/ opened up by them.\n MPM.add(createInstructionCombiningPass());\n MPM.add(createJumpThreadingPass()); \/\/ Thread jumps\n MPM.add(createCorrelatedValuePropagationPass());\n MPM.add(createDeadStoreEliminationPass()); \/\/ Delete dead stores\n\n addExtensionsToPM(EP_ScalarOptimizerLate, MPM);\n\n if (Vectorize) {\n MPM.add(createBBVectorizePass());\n MPM.add(createInstructionCombiningPass());\n if (OptLevel > 1 && UseGVNAfterVectorization)\n MPM.add(createGVNPass()); \/\/ Remove redundancies\n else\n MPM.add(createEarlyCSEPass()); \/\/ Catch trivial redundancies\n }\n\n MPM.add(createAggressiveDCEPass()); \/\/ Delete dead instructions\n MPM.add(createCFGSimplificationPass()); \/\/ Merge & remove BBs\n MPM.add(createInstructionCombiningPass()); \/\/ Clean up after everything.\n\n if (!DisableUnitAtATime) {\n \/\/ FIXME: We shouldn't bother with this anymore.\n MPM.add(createStripDeadPrototypesPass()); \/\/ Get rid of dead prototypes\n\n \/\/ GlobalOpt already deletes dead functions and globals, at -O3 try a\n \/\/ late pass of GlobalDCE. It is capable of deleting dead cycles.\n if (OptLevel > 2)\n MPM.add(createGlobalDCEPass()); \/\/ Remove dead fns and globals.\n\n if (OptLevel > 1)\n MPM.add(createConstantMergePass()); \/\/ Merge dup global constants\n }\n addExtensionsToPM(EP_OptimizerLast, MPM);\n}\n\nvoid PassManagerBuilder::populateLTOPassManager(PassManagerBase &PM,\n bool Internalize,\n bool RunInliner,\n bool DisableGVNLoadPRE) {\n \/\/ Provide AliasAnalysis services for optimizations.\n addInitialAliasAnalysisPasses(PM);\n\n \/\/ Now that composite has been compiled, scan through the module, looking\n \/\/ for a main function. If main is defined, mark all other functions\n \/\/ internal.\n if (Internalize)\n PM.add(createInternalizePass(true));\n\n \/\/ Propagate constants at call sites into the functions they call. This\n \/\/ opens opportunities for globalopt (and inlining) by substituting function\n \/\/ pointers passed as arguments to direct uses of functions.\n PM.add(createIPSCCPPass());\n\n \/\/ Now that we internalized some globals, see if we can hack on them!\n PM.add(createGlobalOptimizerPass());\n\n \/\/ Linking modules together can lead to duplicated global constants, only\n \/\/ keep one copy of each constant.\n PM.add(createConstantMergePass());\n\n \/\/ Remove unused arguments from functions.\n PM.add(createDeadArgEliminationPass());\n\n \/\/ Reduce the code after globalopt and ipsccp. Both can open up significant\n \/\/ simplification opportunities, and both can propagate functions through\n \/\/ function pointers. When this happens, we often have to resolve varargs\n \/\/ calls, etc, so let instcombine do this.\n PM.add(createInstructionCombiningPass());\n\n \/\/ Inline small functions\n if (RunInliner)\n PM.add(createFunctionInliningPass());\n\n PM.add(createPruneEHPass()); \/\/ Remove dead EH info.\n\n \/\/ Optimize globals again if we ran the inliner.\n if (RunInliner)\n PM.add(createGlobalOptimizerPass());\n PM.add(createGlobalDCEPass()); \/\/ Remove dead functions.\n\n \/\/ If we didn't decide to inline a function, check to see if we can\n \/\/ transform it to pass arguments by value instead of by reference.\n PM.add(createArgumentPromotionPass());\n\n \/\/ The IPO passes may leave cruft around. Clean up after them.\n PM.add(createInstructionCombiningPass());\n PM.add(createJumpThreadingPass());\n \/\/ Break up allocas\n PM.add(createScalarReplAggregatesPass());\n\n \/\/ Run a few AA driven optimizations here and now, to cleanup the code.\n PM.add(createFunctionAttrsPass()); \/\/ Add nocapture.\n PM.add(createGlobalsModRefPass()); \/\/ IP alias analysis.\n\n PM.add(createLICMPass()); \/\/ Hoist loop invariants.\n PM.add(createGVNPass(DisableGVNLoadPRE)); \/\/ Remove redundancies.\n PM.add(createMemCpyOptPass()); \/\/ Remove dead memcpys.\n \/\/ Nuke dead stores.\n PM.add(createDeadStoreEliminationPass());\n\n \/\/ Cleanup and simplify the code after the scalar optimizations.\n PM.add(createInstructionCombiningPass());\n\n PM.add(createJumpThreadingPass());\n\n \/\/ Delete basic blocks, which optimization passes may have killed.\n PM.add(createCFGSimplificationPass());\n\n \/\/ Now that we have optimized the program, discard unreachable functions.\n PM.add(createGlobalDCEPass());\n}\n\nLLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate(void) {\n PassManagerBuilder *PMB = new PassManagerBuilder();\n return wrap(PMB);\n}\n\nvoid LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) {\n PassManagerBuilder *Builder = unwrap(PMB);\n delete Builder;\n}\n\nvoid\nLLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB,\n unsigned OptLevel) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->OptLevel = OptLevel;\n}\n\nvoid\nLLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB,\n unsigned SizeLevel) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->SizeLevel = SizeLevel;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableUnitAtATime = Value;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableUnrollLoops = Value;\n}\n\nvoid\nLLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB,\n LLVMBool Value) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->DisableSimplifyLibCalls = Value;\n}\n\nvoid\nLLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB,\n unsigned Threshold) {\n PassManagerBuilder *Builder = unwrap(PMB);\n Builder->Inliner = createFunctionInliningPass(Threshold);\n}\n\nvoid\nLLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM) {\n PassManagerBuilder *Builder = unwrap(PMB);\n FunctionPassManager *FPM = unwrap(PM);\n Builder->populateFunctionPassManager(*FPM);\n}\n\nvoid\nLLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM) {\n PassManagerBuilder *Builder = unwrap(PMB);\n PassManagerBase *MPM = unwrap(PM);\n Builder->populateModulePassManager(*MPM);\n}\n\nvoid LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB,\n LLVMPassManagerRef PM,\n bool Internalize,\n bool RunInliner) {\n PassManagerBuilder *Builder = unwrap(PMB);\n PassManagerBase *LPM = unwrap(PM);\n Builder->populateLTOPassManager(*LPM, Internalize, RunInliner);\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"opencv2\/ocl\/ocl.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace ocl;\n\n\nstruct App\n{\n App(CommandLineParser& cmd);\n void run();\n void handleKey(char key);\n void printParams() const;\n\n void workBegin()\n {\n work_begin = getTickCount();\n }\n void workEnd()\n {\n int64 d = getTickCount() - work_begin;\n double f = getTickFrequency();\n work_fps = f \/ d;\n }\n string method_str() const\n {\n switch (method)\n {\n case BM:\n return \"BM\";\n case BP:\n return \"BP\";\n case CSBP:\n return \"CSBP\";\n }\n return \"\";\n }\n string text() const\n {\n stringstream ss;\n ss << \"(\" << method_str() << \") FPS: \" << setiosflags(ios::left)\n << setprecision(4) << work_fps;\n return ss.str();\n }\nprivate:\n bool running;\n\n Mat left_src, right_src;\n Mat left, right;\n oclMat d_left, d_right;\n\n StereoBM_OCL bm;\n StereoBeliefPropagation bp;\n StereoConstantSpaceBP csbp;\n\n int64 work_begin;\n double work_fps;\n\n string l_img, r_img;\n string out_img;\n enum {BM, BP, CSBP} method;\n int ndisp; \/\/ Max disparity + 1\n enum {GPU, CPU} type;\n};\n\nint main(int argc, char** argv)\n{\n const char* keys =\n \"{ h | help | false | print help message }\"\n \"{ l | left | | specify left image }\"\n \"{ r | right | | specify right image }\"\n \"{ m | method | BM | specify match method(BM\/BP\/CSBP) }\"\n \"{ n | ndisp | 64 | specify number of disparity levels }\"\n \"{ s | cpu_ocl | false | use cpu or gpu as ocl device to process the image }\"\n \"{ o | output | stereo_match_output.jpg | specify output path when input is images}\";\n CommandLineParser cmd(argc, argv, keys);\n if (cmd.get(\"help\"))\n {\n cout << \"Avaible options:\" << endl;\n cmd.printParams();\n return 0;\n }\n try\n {\n App app(cmd);\n int flag = CVCL_DEVICE_TYPE_GPU;\n if(cmd.get(\"s\") == true)\n flag = CVCL_DEVICE_TYPE_CPU;\n\n vector info;\n if(getDevice(info, flag) == 0)\n {\n throw runtime_error(\"Error: Did not find a valid OpenCL device!\");\n }\n cout << \"Device name:\" << info[0].DeviceName[0] << endl;\n\n app.run();\n }\n catch (const exception& e)\n {\n cout << \"error: \" << e.what() << endl;\n }\n return 0;\n}\n\nApp::App(CommandLineParser& cmd)\n : running(false),method(BM)\n{\n cout << \"stereo_match_ocl sample\\n\";\n cout << \"\\nControls:\\n\"\n << \"\\tesc - exit\\n\"\n << \"\\tp - print current parameters\\n\"\n << \"\\tg - convert source images into gray\\n\"\n << \"\\tm - change stereo match method\\n\"\n << \"\\ts - change Sobel prefiltering flag (for BM only)\\n\"\n << \"\\t1\/q - increase\/decrease maximum disparity\\n\"\n << \"\\t2\/w - increase\/decrease window size (for BM only)\\n\"\n << \"\\t3\/e - increase\/decrease iteration count (for BP and CSBP only)\\n\"\n << \"\\t4\/r - increase\/decrease level count (for BP and CSBP only)\\n\";\n l_img = cmd.get(\"l\");\n r_img = cmd.get(\"r\");\n string mstr = cmd.get(\"m\");\n if(mstr == \"BM\") method = BM;\n else if(mstr == \"BP\") method = BP;\n else if(mstr == \"CSBP\") method = CSBP;\n else cout << \"unknown method!\\n\";\n ndisp = cmd.get(\"n\");\n out_img = cmd.get(\"o\");\n}\n\n\nvoid App::run()\n{\n \/\/ Load images\n left_src = imread(l_img);\n right_src = imread(r_img);\n if (left_src.empty()) throw runtime_error(\"can't open file \\\"\" + l_img + \"\\\"\");\n if (right_src.empty()) throw runtime_error(\"can't open file \\\"\" + r_img + \"\\\"\");\n\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n\n d_left.upload(left);\n d_right.upload(right);\n\n imshow(\"left\", left);\n imshow(\"right\", right);\n\n \/\/ Set common parameters\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n\n cout << endl;\n printParams();\n\n running = true;\n bool written = false;\n while (running)\n {\n\n \/\/ Prepare disparity map of specified type\n Mat disp;\n oclMat d_disp;\n workBegin();\n switch (method)\n {\n case BM:\n if (d_left.channels() > 1 || d_right.channels() > 1)\n {\n cout << \"BM doesn't support color images\\n\";\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n cout << \"image_channels: \" << left.channels() << endl;\n d_left.upload(left);\n d_right.upload(right);\n imshow(\"left\", left);\n imshow(\"right\", right);\n }\n bm(d_left, d_right, d_disp);\n break;\n case BP:\n bp(d_left, d_right, d_disp);\n break;\n case CSBP:\n csbp(d_left, d_right, d_disp);\n break;\n }\n workEnd();\n\n \/\/ Show results\n d_disp.download(disp);\n if (method != BM)\n {\n disp.convertTo(disp, 0);\n }\n putText(disp, text(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar::all(255));\n imshow(\"disparity\", disp);\n if(!written)\n {\n imwrite(out_img, disp);\n written = true;\n }\n handleKey((char)waitKey(3));\n }\n}\n\n\nvoid App::printParams() const\n{\n cout << \"--- Parameters ---\\n\";\n cout << \"image_size: (\" << left.cols << \", \" << left.rows << \")\\n\";\n cout << \"image_channels: \" << left.channels() << endl;\n cout << \"method: \" << method_str() << endl\n << \"ndisp: \" << ndisp << endl;\n switch (method)\n {\n case BM:\n cout << \"win_size: \" << bm.winSize << endl;\n cout << \"prefilter_sobel: \" << bm.preset << endl;\n break;\n case BP:\n cout << \"iter_count: \" << bp.iters << endl;\n cout << \"level_count: \" << bp.levels << endl;\n break;\n case CSBP:\n cout << \"iter_count: \" << csbp.iters << endl;\n cout << \"level_count: \" << csbp.levels << endl;\n break;\n }\n cout << endl;\n}\n\n\nvoid App::handleKey(char key)\n{\n switch (key)\n {\n case 27:\n running = false;\n break;\n case 'p':\n case 'P':\n printParams();\n break;\n case 'g':\n case 'G':\n if (left.channels() == 1 && method != BM)\n {\n left = left_src;\n right = right_src;\n }\n else\n {\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n }\n d_left.upload(left);\n d_right.upload(right);\n cout << \"image_channels: \" << left.channels() << endl;\n imshow(\"left\", left);\n imshow(\"right\", right);\n break;\n case 'm':\n case 'M':\n switch (method)\n {\n case BM:\n method = BP;\n break;\n case BP:\n method = CSBP;\n break;\n case CSBP:\n method = BM;\n break;\n }\n cout << \"method: \" << method_str() << endl;\n break;\n case 's':\n case 'S':\n if (method == BM)\n {\n switch (bm.preset)\n {\n case StereoBM_OCL::BASIC_PRESET:\n bm.preset = StereoBM_OCL::PREFILTER_XSOBEL;\n break;\n case StereoBM_OCL::PREFILTER_XSOBEL:\n bm.preset = StereoBM_OCL::BASIC_PRESET;\n break;\n }\n cout << \"prefilter_sobel: \" << bm.preset << endl;\n }\n break;\n case '1':\n ndisp == 1 ? ndisp = 8 : ndisp += 8;\n cout << \"ndisp: \" << ndisp << endl;\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n break;\n case 'q':\n case 'Q':\n ndisp = max(ndisp - 8, 1);\n cout << \"ndisp: \" << ndisp << endl;\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n break;\n case '2':\n if (method == BM)\n {\n bm.winSize = min(bm.winSize + 1, 51);\n cout << \"win_size: \" << bm.winSize << endl;\n }\n break;\n case 'w':\n case 'W':\n if (method == BM)\n {\n bm.winSize = max(bm.winSize - 1, 2);\n cout << \"win_size: \" << bm.winSize << endl;\n }\n break;\n case '3':\n if (method == BP)\n {\n bp.iters += 1;\n cout << \"iter_count: \" << bp.iters << endl;\n }\n else if (method == CSBP)\n {\n csbp.iters += 1;\n cout << \"iter_count: \" << csbp.iters << endl;\n }\n break;\n case 'e':\n case 'E':\n if (method == BP)\n {\n bp.iters = max(bp.iters - 1, 1);\n cout << \"iter_count: \" << bp.iters << endl;\n }\n else if (method == CSBP)\n {\n csbp.iters = max(csbp.iters - 1, 1);\n cout << \"iter_count: \" << csbp.iters << endl;\n }\n break;\n case '4':\n if (method == BP)\n {\n bp.levels += 1;\n cout << \"level_count: \" << bp.levels << endl;\n }\n else if (method == CSBP)\n {\n csbp.levels += 1;\n cout << \"level_count: \" << csbp.levels << endl;\n }\n break;\n case 'r':\n case 'R':\n if (method == BP)\n {\n bp.levels = max(bp.levels - 1, 1);\n cout << \"level_count: \" << bp.levels << endl;\n }\n else if (method == CSBP)\n {\n csbp.levels = max(csbp.levels - 1, 1);\n cout << \"level_count: \" << csbp.levels << endl;\n }\n break;\n }\n}\n\n\na bug fix in stereo_match sample#include \n#include \n#include \n#include \n#include \n#include \"opencv2\/ocl\/ocl.hpp\"\n#include \"opencv2\/highgui\/highgui.hpp\"\n\nusing namespace cv;\nusing namespace std;\nusing namespace ocl;\n\n\nstruct App\n{\n App(CommandLineParser& cmd);\n void run();\n void handleKey(char key);\n void printParams() const;\n\n void workBegin()\n {\n work_begin = getTickCount();\n }\n void workEnd()\n {\n int64 d = getTickCount() - work_begin;\n double f = getTickFrequency();\n work_fps = f \/ d;\n }\n string method_str() const\n {\n switch (method)\n {\n case BM:\n return \"BM\";\n case BP:\n return \"BP\";\n case CSBP:\n return \"CSBP\";\n }\n return \"\";\n }\n string text() const\n {\n stringstream ss;\n ss << \"(\" << method_str() << \") FPS: \" << setiosflags(ios::left)\n << setprecision(4) << work_fps;\n return ss.str();\n }\nprivate:\n bool running;\n\n Mat left_src, right_src;\n Mat left, right;\n oclMat d_left, d_right;\n\n StereoBM_OCL bm;\n StereoBeliefPropagation bp;\n StereoConstantSpaceBP csbp;\n\n int64 work_begin;\n double work_fps;\n\n string l_img, r_img;\n string out_img;\n enum {BM, BP, CSBP} method;\n int ndisp; \/\/ Max disparity + 1\n enum {GPU, CPU} type;\n};\n\nint main(int argc, char** argv)\n{\n const char* keys =\n \"{ h | help | false | print help message }\"\n \"{ l | left | | specify left image }\"\n \"{ r | right | | specify right image }\"\n \"{ m | method | BM | specify match method(BM\/BP\/CSBP) }\"\n \"{ n | ndisp | 64 | specify number of disparity levels }\"\n \"{ s | cpu_ocl | false | use cpu or gpu as ocl device to process the image }\"\n \"{ o | output | stereo_match_output.jpg | specify output path when input is images}\";\n CommandLineParser cmd(argc, argv, keys);\n if (cmd.get(\"help\"))\n {\n cout << \"Avaible options:\" << endl;\n cmd.printParams();\n return 0;\n }\n try\n {\n App app(cmd);\n int flag = CVCL_DEVICE_TYPE_GPU;\n if(cmd.get(\"s\") == true)\n flag = CVCL_DEVICE_TYPE_CPU;\n\n vector info;\n if(getDevice(info, flag) == 0)\n {\n throw runtime_error(\"Error: Did not find a valid OpenCL device!\");\n }\n cout << \"Device name:\" << info[0].DeviceName[0] << endl;\n\n app.run();\n }\n catch (const exception& e)\n {\n cout << \"error: \" << e.what() << endl;\n }\n return 0;\n}\n\nApp::App(CommandLineParser& cmd)\n : running(false),method(BM)\n{\n cout << \"stereo_match_ocl sample\\n\";\n cout << \"\\nControls:\\n\"\n << \"\\tesc - exit\\n\"\n << \"\\tp - print current parameters\\n\"\n << \"\\tg - convert source images into gray\\n\"\n << \"\\tm - change stereo match method\\n\"\n << \"\\ts - change Sobel prefiltering flag (for BM only)\\n\"\n << \"\\t1\/q - increase\/decrease maximum disparity\\n\"\n << \"\\t2\/w - increase\/decrease window size (for BM only)\\n\"\n << \"\\t3\/e - increase\/decrease iteration count (for BP and CSBP only)\\n\"\n << \"\\t4\/r - increase\/decrease level count (for BP and CSBP only)\\n\";\n l_img = cmd.get(\"l\");\n r_img = cmd.get(\"r\");\n string mstr = cmd.get(\"m\");\n if(mstr == \"BM\") method = BM;\n else if(mstr == \"BP\") method = BP;\n else if(mstr == \"CSBP\") method = CSBP;\n else cout << \"unknown method!\\n\";\n ndisp = cmd.get(\"n\");\n out_img = cmd.get(\"o\");\n}\n\n\nvoid App::run()\n{\n \/\/ Load images\n left_src = imread(l_img);\n right_src = imread(r_img);\n if (left_src.empty()) throw runtime_error(\"can't open file \\\"\" + l_img + \"\\\"\");\n if (right_src.empty()) throw runtime_error(\"can't open file \\\"\" + r_img + \"\\\"\");\n\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n\n d_left.upload(left);\n d_right.upload(right);\n\n imshow(\"left\", left);\n imshow(\"right\", right);\n\n \/\/ Set common parameters\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n\n cout << endl;\n printParams();\n\n running = true;\n bool written = false;\n while (running)\n {\n\n \/\/ Prepare disparity map of specified type\n Mat disp;\n oclMat d_disp;\n workBegin();\n switch (method)\n {\n case BM:\n if (d_left.channels() > 1 || d_right.channels() > 1)\n {\n cout << \"BM doesn't support color images\\n\";\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n cout << \"image_channels: \" << left.channels() << endl;\n d_left.upload(left);\n d_right.upload(right);\n imshow(\"left\", left);\n imshow(\"right\", right);\n }\n bm(d_left, d_right, d_disp);\n break;\n case BP:\n bp(d_left, d_right, d_disp);\n break;\n case CSBP:\n csbp(d_left, d_right, d_disp);\n break;\n }\n \/\/ Show results\n d_disp.download(disp);\n workEnd();\n if (method != BM)\n {\n disp.convertTo(disp, 0);\n }\n putText(disp, text(), Point(5, 25), FONT_HERSHEY_SIMPLEX, 1.0, Scalar::all(255));\n imshow(\"disparity\", disp);\n if(!written)\n {\n imwrite(out_img, disp);\n written = true;\n }\n handleKey((char)waitKey(3));\n }\n}\n\n\nvoid App::printParams() const\n{\n cout << \"--- Parameters ---\\n\";\n cout << \"image_size: (\" << left.cols << \", \" << left.rows << \")\\n\";\n cout << \"image_channels: \" << left.channels() << endl;\n cout << \"method: \" << method_str() << endl\n << \"ndisp: \" << ndisp << endl;\n switch (method)\n {\n case BM:\n cout << \"win_size: \" << bm.winSize << endl;\n cout << \"prefilter_sobel: \" << bm.preset << endl;\n break;\n case BP:\n cout << \"iter_count: \" << bp.iters << endl;\n cout << \"level_count: \" << bp.levels << endl;\n break;\n case CSBP:\n cout << \"iter_count: \" << csbp.iters << endl;\n cout << \"level_count: \" << csbp.levels << endl;\n break;\n }\n cout << endl;\n}\n\n\nvoid App::handleKey(char key)\n{\n switch (key)\n {\n case 27:\n running = false;\n break;\n case 'p':\n case 'P':\n printParams();\n break;\n case 'g':\n case 'G':\n if (left.channels() == 1 && method != BM)\n {\n left = left_src;\n right = right_src;\n }\n else\n {\n cvtColor(left_src, left, CV_BGR2GRAY);\n cvtColor(right_src, right, CV_BGR2GRAY);\n }\n d_left.upload(left);\n d_right.upload(right);\n cout << \"image_channels: \" << left.channels() << endl;\n imshow(\"left\", left);\n imshow(\"right\", right);\n break;\n case 'm':\n case 'M':\n switch (method)\n {\n case BM:\n method = BP;\n break;\n case BP:\n method = CSBP;\n break;\n case CSBP:\n method = BM;\n break;\n }\n cout << \"method: \" << method_str() << endl;\n break;\n case 's':\n case 'S':\n if (method == BM)\n {\n switch (bm.preset)\n {\n case StereoBM_OCL::BASIC_PRESET:\n bm.preset = StereoBM_OCL::PREFILTER_XSOBEL;\n break;\n case StereoBM_OCL::PREFILTER_XSOBEL:\n bm.preset = StereoBM_OCL::BASIC_PRESET;\n break;\n }\n cout << \"prefilter_sobel: \" << bm.preset << endl;\n }\n break;\n case '1':\n ndisp == 1 ? ndisp = 8 : ndisp += 8;\n cout << \"ndisp: \" << ndisp << endl;\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n break;\n case 'q':\n case 'Q':\n ndisp = max(ndisp - 8, 1);\n cout << \"ndisp: \" << ndisp << endl;\n bm.ndisp = ndisp;\n bp.ndisp = ndisp;\n csbp.ndisp = ndisp;\n break;\n case '2':\n if (method == BM)\n {\n bm.winSize = min(bm.winSize + 1, 51);\n cout << \"win_size: \" << bm.winSize << endl;\n }\n break;\n case 'w':\n case 'W':\n if (method == BM)\n {\n bm.winSize = max(bm.winSize - 1, 2);\n cout << \"win_size: \" << bm.winSize << endl;\n }\n break;\n case '3':\n if (method == BP)\n {\n bp.iters += 1;\n cout << \"iter_count: \" << bp.iters << endl;\n }\n else if (method == CSBP)\n {\n csbp.iters += 1;\n cout << \"iter_count: \" << csbp.iters << endl;\n }\n break;\n case 'e':\n case 'E':\n if (method == BP)\n {\n bp.iters = max(bp.iters - 1, 1);\n cout << \"iter_count: \" << bp.iters << endl;\n }\n else if (method == CSBP)\n {\n csbp.iters = max(csbp.iters - 1, 1);\n cout << \"iter_count: \" << csbp.iters << endl;\n }\n break;\n case '4':\n if (method == BP)\n {\n bp.levels += 1;\n cout << \"level_count: \" << bp.levels << endl;\n }\n else if (method == CSBP)\n {\n csbp.levels += 1;\n cout << \"level_count: \" << csbp.levels << endl;\n }\n break;\n case 'r':\n case 'R':\n if (method == BP)\n {\n bp.levels = max(bp.levels - 1, 1);\n cout << \"level_count: \" << bp.levels << endl;\n }\n else if (method == CSBP)\n {\n csbp.levels = max(csbp.levels - 1, 1);\n cout << \"level_count: \" << csbp.levels << endl;\n }\n break;\n }\n}\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/host_content_settings_map.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n\n\/\/ static\nconst wchar_t* HostContentSettingsMap::kTypeNames[] = {\n L\"cookies\",\n L\"images\",\n L\"javascript\",\n L\"plugins\",\n L\"popups\",\n};\n\nHostContentSettingsMap::HostContentSettingsMap(Profile* profile)\n : profile_(profile),\n block_third_party_cookies_(false) {\n DCHECK_EQ(arraysize(kTypeNames),\n static_cast(CONTENT_SETTINGS_NUM_TYPES));\n\n const DictionaryValue* default_settings_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kDefaultContentSettings);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (default_settings_dictionary != NULL) {\n GetSettingsFromDictionary(default_settings_dictionary,\n &default_content_settings_);\n }\n\n const DictionaryValue* all_settings_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kPerHostContentSettings);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (all_settings_dictionary != NULL) {\n for (DictionaryValue::key_iterator i(all_settings_dictionary->begin_keys());\n i != all_settings_dictionary->end_keys(); ++i) {\n std::wstring wide_host(*i);\n DictionaryValue* host_settings_dictionary = NULL;\n bool found = all_settings_dictionary->GetDictionaryWithoutPathExpansion(\n wide_host, &host_settings_dictionary);\n DCHECK(found);\n ContentSettings settings;\n GetSettingsFromDictionary(host_settings_dictionary, &settings);\n host_content_settings_[WideToUTF8(wide_host)] = settings;\n }\n }\n\n \/\/ TODO(darin): init third-party cookie pref\n}\n\n\/\/ static\nvoid HostContentSettingsMap::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kDefaultContentSettings);\n prefs->RegisterDictionaryPref(prefs::kPerHostContentSettings);\n\n \/\/ TODO(darin): register third-party cookie pref\n}\n\nContentSetting HostContentSettingsMap::GetDefaultContentSetting(\n ContentSettingsType content_type) const {\n AutoLock auto_lock(lock_);\n return default_content_settings_.settings[content_type];\n}\n\nContentSetting HostContentSettingsMap::GetContentSetting(\n const std::string& host,\n ContentSettingsType content_type) const {\n AutoLock auto_lock(lock_);\n HostContentSettings::const_iterator i(host_content_settings_.find(host));\n return (i == host_content_settings_.end()) ?\n default_content_settings_.settings[content_type] :\n i->second.settings[content_type];\n}\n\nContentSettings HostContentSettingsMap::GetContentSettings(\n const std::string& host) const {\n AutoLock auto_lock(lock_);\n HostContentSettings::const_iterator i(host_content_settings_.find(host));\n if (i == host_content_settings_.end())\n return default_content_settings_;\n\n ContentSettings output;\n for (int i = 0; i < CONTENT_SETTINGS_NUM_TYPES; ++i) {\n if (i->second.settings[i] == CONTENT_SETTING_DEFAULT) {\n output.settings[i] = default_content_settings_.settings[i];\n } else {\n output.settings[i] = i->second.settings[i];\n }\n }\n return output;\n}\n\nvoid HostContentSettingsMap::GetHostContentSettingsForOneType(\n ContentSettingsType content_type,\n HostContentSettingsForOneType* settings) const {\n DCHECK(settings);\n settings->clear();\n\n AutoLock auto_lock(lock_);\n for (HostContentSettings::const_iterator i(host_content_settings_.begin());\n i != host_content_settings_.end(); ++i) {\n ContentSetting setting = i->second.settings[content_type];\n if (setting != CONTENT_SETTING_DEFAULT)\n (*settings)[i->first] = setting;\n }\n}\n\nvoid HostContentSettingsMap::SetDefaultContentSetting(\n ContentSettingsType content_type,\n ContentSetting setting) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n {\n AutoLock auto_lock(lock_);\n default_content_settings_.settings[content_type] = setting;\n }\n\n profile_->GetPrefs()->GetMutableDictionary(prefs::kDefaultContentSettings)->\n SetWithoutPathExpansion(std::wstring(kTypeNames[content_type]),\n Value::CreateIntegerValue(setting));\n}\n\nvoid HostContentSettingsMap::SetContentSetting(const std::string& host,\n ContentSettingsType content_type,\n ContentSetting setting) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n bool all_default = true;\n {\n AutoLock auto_lock(lock_);\n if (!host_content_settings_.count(host))\n host_content_settings_[host] = ContentSettings();\n HostContentSettings::iterator i(host_content_settings_.find(host));\n ContentSettings& settings = i->second;\n settings.settings[content_type] = setting;\n for (size_t i = 0; i < arraysize(settings.settings); ++i) {\n if (settings.settings[i] != CONTENT_SETTING_DEFAULT) {\n all_default = false;\n break;\n }\n }\n if (all_default)\n host_content_settings_.erase(i);\n }\n\n std::wstring wide_host(UTF8ToWide(host));\n DictionaryValue* all_settings_dictionary =\n profile_->GetPrefs()->GetMutableDictionary(\n prefs::kPerHostContentSettings);\n if (all_default) {\n all_settings_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);\n return;\n }\n DictionaryValue* host_settings_dictionary;\n bool found = all_settings_dictionary->GetDictionaryWithoutPathExpansion(\n wide_host, &host_settings_dictionary);\n if (!found) {\n host_settings_dictionary = new DictionaryValue;\n all_settings_dictionary->SetWithoutPathExpansion(\n wide_host, host_settings_dictionary);\n }\n host_settings_dictionary->SetWithoutPathExpansion(\n std::wstring(kTypeNames[content_type]),\n Value::CreateIntegerValue(setting));\n}\n\nvoid HostContentSettingsMap::ResetToDefaults() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n {\n AutoLock auto_lock(lock_);\n default_content_settings_ = ContentSettings();\n host_content_settings_.clear();\n }\n\n profile_->GetPrefs()->ClearPref(prefs::kDefaultContentSettings);\n profile_->GetPrefs()->ClearPref(prefs::kPerHostContentSettings);\n\n \/\/ TODO(darin): clear third-party cookie pref\n}\n\nHostContentSettingsMap::~HostContentSettingsMap() {\n}\n\nvoid HostContentSettingsMap::GetSettingsFromDictionary(\n const DictionaryValue* dictionary,\n ContentSettings* settings) {\n for (DictionaryValue::key_iterator i(dictionary->begin_keys());\n i != dictionary->end_keys(); ++i) {\n std::wstring content_type(*i);\n int setting = CONTENT_SETTING_DEFAULT;\n bool found = dictionary->GetIntegerWithoutPathExpansion(content_type,\n &setting);\n DCHECK(found);\n for (size_t type = 0; type < arraysize(kTypeNames); ++type) {\n if (std::wstring(kTypeNames[type]) == content_type) {\n settings->settings[type] = static_cast(setting);\n break;\n }\n }\n }\n}\nFix compilation error. Oops!\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/host_content_settings_map.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/chrome_thread.h\"\n#include \"chrome\/browser\/profile.h\"\n#include \"chrome\/common\/pref_names.h\"\n#include \"chrome\/common\/pref_service.h\"\n\n\/\/ static\nconst wchar_t* HostContentSettingsMap::kTypeNames[] = {\n L\"cookies\",\n L\"images\",\n L\"javascript\",\n L\"plugins\",\n L\"popups\",\n};\n\nHostContentSettingsMap::HostContentSettingsMap(Profile* profile)\n : profile_(profile),\n block_third_party_cookies_(false) {\n DCHECK_EQ(arraysize(kTypeNames),\n static_cast(CONTENT_SETTINGS_NUM_TYPES));\n\n const DictionaryValue* default_settings_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kDefaultContentSettings);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (default_settings_dictionary != NULL) {\n GetSettingsFromDictionary(default_settings_dictionary,\n &default_content_settings_);\n }\n\n const DictionaryValue* all_settings_dictionary =\n profile_->GetPrefs()->GetDictionary(prefs::kPerHostContentSettings);\n \/\/ Careful: The returned value could be NULL if the pref has never been set.\n if (all_settings_dictionary != NULL) {\n for (DictionaryValue::key_iterator i(all_settings_dictionary->begin_keys());\n i != all_settings_dictionary->end_keys(); ++i) {\n std::wstring wide_host(*i);\n DictionaryValue* host_settings_dictionary = NULL;\n bool found = all_settings_dictionary->GetDictionaryWithoutPathExpansion(\n wide_host, &host_settings_dictionary);\n DCHECK(found);\n ContentSettings settings;\n GetSettingsFromDictionary(host_settings_dictionary, &settings);\n host_content_settings_[WideToUTF8(wide_host)] = settings;\n }\n }\n\n \/\/ TODO(darin): init third-party cookie pref\n}\n\n\/\/ static\nvoid HostContentSettingsMap::RegisterUserPrefs(PrefService* prefs) {\n prefs->RegisterDictionaryPref(prefs::kDefaultContentSettings);\n prefs->RegisterDictionaryPref(prefs::kPerHostContentSettings);\n\n \/\/ TODO(darin): register third-party cookie pref\n}\n\nContentSetting HostContentSettingsMap::GetDefaultContentSetting(\n ContentSettingsType content_type) const {\n AutoLock auto_lock(lock_);\n return default_content_settings_.settings[content_type];\n}\n\nContentSetting HostContentSettingsMap::GetContentSetting(\n const std::string& host,\n ContentSettingsType content_type) const {\n AutoLock auto_lock(lock_);\n HostContentSettings::const_iterator i(host_content_settings_.find(host));\n return (i == host_content_settings_.end()) ?\n default_content_settings_.settings[content_type] :\n i->second.settings[content_type];\n}\n\nContentSettings HostContentSettingsMap::GetContentSettings(\n const std::string& host) const {\n AutoLock auto_lock(lock_);\n HostContentSettings::const_iterator i(host_content_settings_.find(host));\n if (i == host_content_settings_.end())\n return default_content_settings_;\n\n ContentSettings output;\n for (int j = 0; j < CONTENT_SETTINGS_NUM_TYPES; ++j) {\n if (i->second.settings[j] == CONTENT_SETTING_DEFAULT) {\n output.settings[j] = default_content_settings_.settings[j];\n } else {\n output.settings[j] = i->second.settings[j];\n }\n }\n return output;\n}\n\nvoid HostContentSettingsMap::GetHostContentSettingsForOneType(\n ContentSettingsType content_type,\n HostContentSettingsForOneType* settings) const {\n DCHECK(settings);\n settings->clear();\n\n AutoLock auto_lock(lock_);\n for (HostContentSettings::const_iterator i(host_content_settings_.begin());\n i != host_content_settings_.end(); ++i) {\n ContentSetting setting = i->second.settings[content_type];\n if (setting != CONTENT_SETTING_DEFAULT)\n (*settings)[i->first] = setting;\n }\n}\n\nvoid HostContentSettingsMap::SetDefaultContentSetting(\n ContentSettingsType content_type,\n ContentSetting setting) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n {\n AutoLock auto_lock(lock_);\n default_content_settings_.settings[content_type] = setting;\n }\n\n profile_->GetPrefs()->GetMutableDictionary(prefs::kDefaultContentSettings)->\n SetWithoutPathExpansion(std::wstring(kTypeNames[content_type]),\n Value::CreateIntegerValue(setting));\n}\n\nvoid HostContentSettingsMap::SetContentSetting(const std::string& host,\n ContentSettingsType content_type,\n ContentSetting setting) {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n bool all_default = true;\n {\n AutoLock auto_lock(lock_);\n if (!host_content_settings_.count(host))\n host_content_settings_[host] = ContentSettings();\n HostContentSettings::iterator i(host_content_settings_.find(host));\n ContentSettings& settings = i->second;\n settings.settings[content_type] = setting;\n for (size_t i = 0; i < arraysize(settings.settings); ++i) {\n if (settings.settings[i] != CONTENT_SETTING_DEFAULT) {\n all_default = false;\n break;\n }\n }\n if (all_default)\n host_content_settings_.erase(i);\n }\n\n std::wstring wide_host(UTF8ToWide(host));\n DictionaryValue* all_settings_dictionary =\n profile_->GetPrefs()->GetMutableDictionary(\n prefs::kPerHostContentSettings);\n if (all_default) {\n all_settings_dictionary->RemoveWithoutPathExpansion(wide_host, NULL);\n return;\n }\n DictionaryValue* host_settings_dictionary;\n bool found = all_settings_dictionary->GetDictionaryWithoutPathExpansion(\n wide_host, &host_settings_dictionary);\n if (!found) {\n host_settings_dictionary = new DictionaryValue;\n all_settings_dictionary->SetWithoutPathExpansion(\n wide_host, host_settings_dictionary);\n }\n host_settings_dictionary->SetWithoutPathExpansion(\n std::wstring(kTypeNames[content_type]),\n Value::CreateIntegerValue(setting));\n}\n\nvoid HostContentSettingsMap::ResetToDefaults() {\n DCHECK(ChromeThread::CurrentlyOn(ChromeThread::UI));\n\n {\n AutoLock auto_lock(lock_);\n default_content_settings_ = ContentSettings();\n host_content_settings_.clear();\n }\n\n profile_->GetPrefs()->ClearPref(prefs::kDefaultContentSettings);\n profile_->GetPrefs()->ClearPref(prefs::kPerHostContentSettings);\n\n \/\/ TODO(darin): clear third-party cookie pref\n}\n\nHostContentSettingsMap::~HostContentSettingsMap() {\n}\n\nvoid HostContentSettingsMap::GetSettingsFromDictionary(\n const DictionaryValue* dictionary,\n ContentSettings* settings) {\n for (DictionaryValue::key_iterator i(dictionary->begin_keys());\n i != dictionary->end_keys(); ++i) {\n std::wstring content_type(*i);\n int setting = CONTENT_SETTING_DEFAULT;\n bool found = dictionary->GetIntegerWithoutPathExpansion(content_type,\n &setting);\n DCHECK(found);\n for (size_t type = 0; type < arraysize(kTypeNames); ++type) {\n if (std::wstring(kTypeNames[type]) == content_type) {\n settings->settings[type] = static_cast(setting);\n break;\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Time: O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n bool isPalindrome(string s) {\n int i = 0, j = s.length() - 1;\n while (i < j) {\n if (!isalnum(s[i])) {\n ++i;\n } else if (!isalnum(s[j])) {\n --j;\n } else if (::tolower(s[i]) != ::tolower(s[j])) {\n return false;\n } else {\n ++i, --j;\n }\n }\n return true;\n }\n};\n\n\/\/ Time: O(n)\n\/\/ Space: O(1)\n\/\/ Iterator solution.\nclass Solution2 {\npublic: \n bool isPalindrome(string s) {\n auto left = s.begin();\n auto right = prev(s.end());\n for(; left < right;) { \n if(!isalnum(*left)) {\n ++left;\n } else if(!isalnum(*right)) {\n --right; \n } else if(::tolower(*left) != ::tolower(*right)) {\n return false;\n } else {\n ++left, --right;\n }\n }\n return true;\n }\n};\nUpdate valid-palindrome.cpp\/\/ Time: O(n)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n bool isPalindrome(string s) {\n int i = 0, j = s.length() - 1;\n while (i < j) {\n if (!isalnum(s[i])) {\n ++i;\n } else if (!isalnum(s[j])) {\n --j;\n } else if (tolower(s[i]) != tolower(s[j])) {\n return false;\n } else {\n ++i, --j;\n }\n }\n return true;\n }\n};\n\n\/\/ Time: O(n)\n\/\/ Space: O(1)\n\/\/ Iterator solution.\nclass Solution2 {\npublic: \n bool isPalindrome(string s) {\n auto left = s.begin();\n auto right = prev(s.end());\n for(; left < right;) { \n if(!isalnum(*left)) {\n ++left;\n } else if(!isalnum(*right)) {\n --right; \n } else if(tolower(*left) != tolower(*right)) {\n return false;\n } else {\n ++left, --right;\n }\n }\n return true;\n }\n};\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InjectedScriptManager.h\"\n\n#include \"bindings\/core\/v8\/BindingSecurity.h\"\n#include \"bindings\/core\/v8\/ScopedPersistent.h\"\n#include \"bindings\/core\/v8\/ScriptDebugServer.h\"\n#include \"bindings\/core\/v8\/ScriptValue.h\"\n#include \"bindings\/core\/v8\/V8Binding.h\"\n#include \"bindings\/core\/v8\/V8InjectedScriptHost.h\"\n#include \"bindings\/core\/v8\/V8ObjectConstructor.h\"\n#include \"bindings\/core\/v8\/V8ScriptRunner.h\"\n#include \"bindings\/core\/v8\/V8Window.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/inspector\/InjectedScriptHost.h\"\n#include \"wtf\/RefPtr.h\"\n\nnamespace blink {\n\nInjectedScriptManager::CallbackData* InjectedScriptManager::createCallbackData(InjectedScriptManager* injectedScriptManager)\n{\n OwnPtr callbackData = adoptPtr(new InjectedScriptManager::CallbackData());\n InjectedScriptManager::CallbackData* callbackDataPtr = callbackData.get();\n callbackData->injectedScriptManager = injectedScriptManager;\n m_callbackDataSet.add(callbackData.release());\n return callbackDataPtr;\n}\n\nvoid InjectedScriptManager::removeCallbackData(InjectedScriptManager::CallbackData* callbackData)\n{\n fprintf(stderr, \"b %p\\n\", callbackData);\n ASSERT(m_callbackDataSet.contains(callbackData));\n fprintf(stderr, \"c %p\\n\", callbackData);\n m_callbackDataSet.remove(callbackData);\n fprintf(stderr, \"d %p\\n\", callbackData);\n}\n\nstatic v8::Local createInjectedScriptHostV8Wrapper(PassRefPtrWillBeRawPtr host, InjectedScriptManager* injectedScriptManager, v8::Handle creationContext, v8::Isolate* isolate)\n{\n ASSERT(host);\n\n v8::Handle wrapper = V8DOMWrapper::createWrapper(creationContext, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host.get()), isolate);\n if (UNLIKELY(wrapper.IsEmpty()))\n return wrapper;\n\n \/\/ Create a weak reference to the v8 wrapper of InspectorBackend to deref\n \/\/ InspectorBackend when the wrapper is garbage collected.\n InjectedScriptManager::CallbackData* callbackData = injectedScriptManager->createCallbackData(injectedScriptManager);\n callbackData->host = host.get();\n callbackData->handle.set(isolate, wrapper);\n callbackData->handle.setWeak(callbackData, &InjectedScriptManager::setWeakCallback);\n\n#if ENABLE(OILPAN)\n V8DOMWrapper::setNativeInfoWithPersistentHandle(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host), &callbackData->host);\n#else\n V8DOMWrapper::setNativeInfo(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host.get()));\n#endif\n ASSERT(V8DOMWrapper::isDOMWrapper(wrapper));\n return wrapper;\n}\n\nScriptValue InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id)\n{\n v8::Isolate* isolate = inspectedScriptState->isolate();\n ScriptState::Scope scope(inspectedScriptState);\n\n \/\/ Call custom code to create InjectedScripHost wrapper specific for the context\n \/\/ instead of calling toV8() that would create the\n \/\/ wrapper in the current context.\n \/\/ FIXME: make it possible to use generic bindings factory for InjectedScriptHost.\n v8::Local scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost, this, inspectedScriptState->context()->Global(), inspectedScriptState->isolate());\n if (scriptHostWrapper.IsEmpty())\n return ScriptValue();\n\n \/\/ Inject javascript into the context. The compiled script is supposed to evaluate into\n \/\/ a single anonymous function(it's anonymous to avoid cluttering the global object with\n \/\/ inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper,\n \/\/ injected script id and explicit reference to the inspected global object. The function is expected\n \/\/ to create and configure InjectedScript instance that is going to be used by the inspector.\n v8::Local value = V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, scriptSource), isolate);\n ASSERT(!value.IsEmpty());\n ASSERT(value->IsFunction());\n\n v8::Local windowGlobal = inspectedScriptState->context()->Global();\n v8::Handle info[] = { scriptHostWrapper, windowGlobal, v8::Number::New(inspectedScriptState->isolate(), id) };\n v8::Local injectedScriptValue = V8ScriptRunner::callInternalFunction(v8::Local::Cast(value), windowGlobal, WTF_ARRAY_LENGTH(info), info, inspectedScriptState->isolate());\n return ScriptValue(inspectedScriptState, injectedScriptValue);\n}\n\nbool InjectedScriptManager::canAccessInspectedWindow(ScriptState* scriptState)\n{\n ScriptState::Scope scope(scriptState);\n v8::Local global = scriptState->context()->Global();\n if (global.IsEmpty())\n return false;\n v8::Handle holder = V8Window::findInstanceInPrototypeChain(global, scriptState->isolate());\n if (holder.IsEmpty())\n return false;\n LocalFrame* frame = V8Window::toNative(holder)->frame();\n\n return BindingSecurity::shouldAllowAccessToFrame(scriptState->isolate(), frame, DoNotReportSecurityError);\n}\n\nvoid InjectedScriptManager::setWeakCallback(const v8::WeakCallbackData& data)\n{\n InjectedScriptManager::CallbackData* callbackData = data.GetParameter();\n fprintf(stderr, \"a %p\\n\", callbackData);\n callbackData->injectedScriptManager->removeCallbackData(callbackData);\n}\n\n} \/\/ namespace blink\nRemove fprintf()s I mis-committed in r179905\/*\n * Copyright (C) 2012 Google Inc. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n *\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above\n * copyright notice, this list of conditions and the following disclaimer\n * in the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Google Inc. nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"config.h\"\n#include \"core\/inspector\/InjectedScriptManager.h\"\n\n#include \"bindings\/core\/v8\/BindingSecurity.h\"\n#include \"bindings\/core\/v8\/ScopedPersistent.h\"\n#include \"bindings\/core\/v8\/ScriptDebugServer.h\"\n#include \"bindings\/core\/v8\/ScriptValue.h\"\n#include \"bindings\/core\/v8\/V8Binding.h\"\n#include \"bindings\/core\/v8\/V8InjectedScriptHost.h\"\n#include \"bindings\/core\/v8\/V8ObjectConstructor.h\"\n#include \"bindings\/core\/v8\/V8ScriptRunner.h\"\n#include \"bindings\/core\/v8\/V8Window.h\"\n#include \"core\/frame\/LocalDOMWindow.h\"\n#include \"core\/inspector\/InjectedScriptHost.h\"\n#include \"wtf\/RefPtr.h\"\n\nnamespace blink {\n\nInjectedScriptManager::CallbackData* InjectedScriptManager::createCallbackData(InjectedScriptManager* injectedScriptManager)\n{\n OwnPtr callbackData = adoptPtr(new InjectedScriptManager::CallbackData());\n InjectedScriptManager::CallbackData* callbackDataPtr = callbackData.get();\n callbackData->injectedScriptManager = injectedScriptManager;\n m_callbackDataSet.add(callbackData.release());\n return callbackDataPtr;\n}\n\nvoid InjectedScriptManager::removeCallbackData(InjectedScriptManager::CallbackData* callbackData)\n{\n ASSERT(m_callbackDataSet.contains(callbackData));\n m_callbackDataSet.remove(callbackData);\n}\n\nstatic v8::Local createInjectedScriptHostV8Wrapper(PassRefPtrWillBeRawPtr host, InjectedScriptManager* injectedScriptManager, v8::Handle creationContext, v8::Isolate* isolate)\n{\n ASSERT(host);\n\n v8::Handle wrapper = V8DOMWrapper::createWrapper(creationContext, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host.get()), isolate);\n if (UNLIKELY(wrapper.IsEmpty()))\n return wrapper;\n\n \/\/ Create a weak reference to the v8 wrapper of InspectorBackend to deref\n \/\/ InspectorBackend when the wrapper is garbage collected.\n InjectedScriptManager::CallbackData* callbackData = injectedScriptManager->createCallbackData(injectedScriptManager);\n callbackData->host = host.get();\n callbackData->handle.set(isolate, wrapper);\n callbackData->handle.setWeak(callbackData, &InjectedScriptManager::setWeakCallback);\n\n#if ENABLE(OILPAN)\n V8DOMWrapper::setNativeInfoWithPersistentHandle(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host), &callbackData->host);\n#else\n V8DOMWrapper::setNativeInfo(wrapper, &V8InjectedScriptHost::wrapperTypeInfo, V8InjectedScriptHost::toInternalPointer(host.get()));\n#endif\n ASSERT(V8DOMWrapper::isDOMWrapper(wrapper));\n return wrapper;\n}\n\nScriptValue InjectedScriptManager::createInjectedScript(const String& scriptSource, ScriptState* inspectedScriptState, int id)\n{\n v8::Isolate* isolate = inspectedScriptState->isolate();\n ScriptState::Scope scope(inspectedScriptState);\n\n \/\/ Call custom code to create InjectedScripHost wrapper specific for the context\n \/\/ instead of calling toV8() that would create the\n \/\/ wrapper in the current context.\n \/\/ FIXME: make it possible to use generic bindings factory for InjectedScriptHost.\n v8::Local scriptHostWrapper = createInjectedScriptHostV8Wrapper(m_injectedScriptHost, this, inspectedScriptState->context()->Global(), inspectedScriptState->isolate());\n if (scriptHostWrapper.IsEmpty())\n return ScriptValue();\n\n \/\/ Inject javascript into the context. The compiled script is supposed to evaluate into\n \/\/ a single anonymous function(it's anonymous to avoid cluttering the global object with\n \/\/ inspector's stuff) the function is called a few lines below with InjectedScriptHost wrapper,\n \/\/ injected script id and explicit reference to the inspected global object. The function is expected\n \/\/ to create and configure InjectedScript instance that is going to be used by the inspector.\n v8::Local value = V8ScriptRunner::compileAndRunInternalScript(v8String(isolate, scriptSource), isolate);\n ASSERT(!value.IsEmpty());\n ASSERT(value->IsFunction());\n\n v8::Local windowGlobal = inspectedScriptState->context()->Global();\n v8::Handle info[] = { scriptHostWrapper, windowGlobal, v8::Number::New(inspectedScriptState->isolate(), id) };\n v8::Local injectedScriptValue = V8ScriptRunner::callInternalFunction(v8::Local::Cast(value), windowGlobal, WTF_ARRAY_LENGTH(info), info, inspectedScriptState->isolate());\n return ScriptValue(inspectedScriptState, injectedScriptValue);\n}\n\nbool InjectedScriptManager::canAccessInspectedWindow(ScriptState* scriptState)\n{\n ScriptState::Scope scope(scriptState);\n v8::Local global = scriptState->context()->Global();\n if (global.IsEmpty())\n return false;\n v8::Handle holder = V8Window::findInstanceInPrototypeChain(global, scriptState->isolate());\n if (holder.IsEmpty())\n return false;\n LocalFrame* frame = V8Window::toNative(holder)->frame();\n\n return BindingSecurity::shouldAllowAccessToFrame(scriptState->isolate(), frame, DoNotReportSecurityError);\n}\n\nvoid InjectedScriptManager::setWeakCallback(const v8::WeakCallbackData& data)\n{\n InjectedScriptManager::CallbackData* callbackData = data.GetParameter();\n callbackData->injectedScriptManager->removeCallbackData(callbackData);\n}\n\n} \/\/ namespace blink\n<|endoftext|>"} {"text":"\/**\n * \\file\n * \\brief FifoQueueBase class header\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-12-17\n *\/\n\n#ifndef INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\n#define INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"distortos\/scheduler\/SemaphoreWaitFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitForFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitUntilFunctor.hpp\"\n\nnamespace distortos\n{\n\nnamespace scheduler\n{\n\n\/\/\/ FifoQueueBase class implements whole functionality of FifoQueue template class\nclass FifoQueueBase\n{\npublic:\n\n\t\/\/\/ required by templated constructor to deduce type\n\ttemplate\n\tclass TypeTag\n\t{\n\n\t};\n\n\t\/\/\/ type of uninitialized storage for data\n\ttemplate\n\tusing Storage = typename std::aligned_storage::type;\n\n\t\/**\n\t * \\brief Functor is a type-erased interface for functors which execute some action on queue's storage (like\n\t * copy-constructing, swapping, destroying, emplacing, ...).\n\t *\n\t * The functor will be called by FifoQueueBase internals with one argument - \\a storage - which is a reference to\n\t * pointer to queue's storage - after executing functor's action, the pointer should be incremented to next position\n\t * (using the actual size of element)\n\t *\/\n\n\tusing Functor = estd::TypeErasedFunctor;\n\n\t\/**\n\t * \\brief BoundedFunctor is a type-erased Functor which calls its bounded functor to execute actions on queue's\n\t * storage and deals with the pointer increments\n\t *\n\t * \\param T is the type of element\n\t * \\param F is the type of bounded functor, it will be called with Storage*<\/em> as only argument\n\t *\/\n\n\ttemplate\n\tclass BoundedFunctor : public Functor\n\t{\n\tpublic:\n\n\t\t\/**\n\t\t * \\brief BoundedFunctor's constructor\n\t\t *\n\t\t * \\param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct\n\t\t * internal bounded functor\n\t\t *\/\n\n\t\tconstexpr explicit BoundedFunctor(F&& boundedFunctor) :\n\t\t\t\tboundedFunctor_{std::move(boundedFunctor)}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Calls the bounded functor which will execute some action on queue's storage (like copy-constructing,\n\t\t * swapping, destroying, emplacing, ...) and increments the storage pointer to next position (using the actual\n\t\t * size of element)\n\t\t *\n\t\t * \\param [in,out] storage is a reference to pointer to queue's storage - after executing bounded functor, the\n\t\t * pointer will be incremented to next position (using the actual size of element)\n\t\t *\/\n\n\t\tvirtual void operator()(void*& storage) const override\n\t\t{\n\t\t\tauto typedStorage = static_cast*>(storage);\n\t\t\tboundedFunctor_(typedStorage);\n\t\t\tstorage = typedStorage + 1;\n\t\t}\n\n\tprivate:\n\n\t\t\/\/\/ bounded functor\n\t\tF boundedFunctor_;\n\t};\n\n\t\/**\n\t * \\brief Helper factory function to make BoundedFunctor object with partially deduced template arguments\n\t *\n\t * \\param T is the type of element\n\t * \\param F is the type of bounded functor, it will be called with Storage*<\/em> as only argument\n\t *\n\t * \\param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct internal\n\t * bounded functor\n\t *\n\t * \\return BoundedFunctor object with partially deduced template arguments\n\t *\/\n\n\ttemplate\n\tconstexpr static BoundedFunctor makeBoundedFunctor(F&& boundedFunctor)\n\t{\n\t\treturn BoundedFunctor{std::move(boundedFunctor)};\n\t}\n\n\t\/**\n\t * \\brief FifoQueueBase's constructor\n\t *\n\t * \\param T is the type of data in queue\n\t *\n\t * \\param [in] storage is an array of Storage elements\n\t * \\param [in] maxElements is the number of elements in storage array\n\t * \\param [in] typeTag is used to deduce T, as deduction from storage is not possible (nested-name-specifier, so a\n\t * non-deduced context)\n\t *\/\n\n\ttemplate\n\tFifoQueueBase(Storage* const storage, size_t maxElements, TypeTag);\n\n\t\/**\n\t * \\brief Implementation of pop() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a popSemaphore_\n\t * \\param [in] functor is a reference to Functor which will execute actions related to popping - it will get a\n\t * reference to readPosition_ as argument\n\t *\n\t * \\return zero if element was popped successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint popImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)\n\t{\n\t\treturn popPushImplementation(waitSemaphoreFunctor, functor, popSemaphore_, pushSemaphore_, readPosition_);\n\t}\n\n\t\/**\n\t * \\brief Pushes the element to the queue.\n\t *\n\t * Internal version - builds the Functor object.\n\t *\n\t * \\param T is the type of data pushed to queue\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\ttemplate\n\tint pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, const T& value);\n\n\t\/**\n\t * \\brief Pushes the element to the queue.\n\t *\n\t * Internal version - builds the Functor object.\n\t *\n\t * \\param T is the type of data pushed to queue\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is\n\t * move-constructed\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\ttemplate\n\tint pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, T&& value);\n\nprivate:\n\n\t\/**\n\t * \\brief Implementation of pop() and push() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a waitSemaphore\n\t * \\param [in] functor is a reference to Functor which will execute actions related to popping\/pushing - it will get\n\t * a reference to \\a storage as argument\n\t * \\param [in] waitSemaphore is a reference to semaphore that will be waited for, \\a popSemaphore_ for pop(), \\a\n\t * pushSemaphore_ for push()\n\t * \\param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \\a pushSemaphore_\n\t * for pop(), \\a popSemaphore_ for push()\n\t * \\param [in] storage is a reference to appropriate pointer to storage, which will be passed to \\a functor, \\a\n\t * readPosition_ for pop(), \\a writePosition_ for push()\n\t *\n\t * \\return zero if operation was successful, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint popPushImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor,\n\t\t\tSemaphore& waitSemaphore, Semaphore& postSemaphore, void*& storage);\n\n\t\/**\n\t * \\brief Implementation of push() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a\n\t * reference to writePosition_ as argument\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint pushImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)\n\t{\n\t\treturn popPushImplementation(waitSemaphoreFunctor, functor, pushSemaphore_, popSemaphore_, writePosition_);\n\t}\n\n\t\/\/\/ semaphore guarding access to \"pop\" functions - its value is equal to the number of available elements\n\tSemaphore popSemaphore_;\n\n\t\/\/\/ semaphore guarding access to \"push\" functions - its value is equal to the number of free slots\n\tSemaphore pushSemaphore_;\n\n\t\/\/\/ beginning of array with Storage elements\n\tvoid* const storageBegin_;\n\n\t\/\/\/ pointer to past-the-last element of array with Storage elements\n\tvoid* const storageEnd_;\n\n\t\/\/\/ pointer to first element available for reading\n\tvoid* readPosition_;\n\n\t\/\/\/ pointer to first free slot available for writing\n\tvoid* writePosition_;\n};\n\ntemplate\nFifoQueueBase::FifoQueueBase(Storage* const storage, const size_t maxElements, TypeTag) :\n\t\tpopSemaphore_{0, maxElements},\n\t\tpushSemaphore_{maxElements, maxElements},\n\t\tstorageBegin_{storage},\n\t\tstorageEnd_{storage + maxElements},\n\t\treadPosition_{storage},\n\t\twritePosition_{storage}\n{\n\n}\n\ntemplate\nint FifoQueueBase::pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, const T& value)\n{\n\tconst auto copyFunctor = makeBoundedFunctor(\n\t\t\t[&value](Storage* const storage)\n\t\t\t{\n\t\t\t\tnew (storage) T{value};\n\t\t\t});\n\treturn pushImplementation(waitSemaphoreFunctor, copyFunctor);\n}\n\ntemplate\nint FifoQueueBase::pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, T&& value)\n{\n\tconst auto moveFunctor = makeBoundedFunctor(\n\t\t\t[&value](Storage* const storage)\n\t\t\t{\n\t\t\t\tnew (storage) T{std::move(value)};\n\t\t\t});\n\treturn pushImplementation(waitSemaphoreFunctor, moveFunctor);\n}\n\n}\t\/\/ namespace scheduler\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\nFifoQueueBase: make FifoQueueBase::pushImplementation() public\/**\n * \\file\n * \\brief FifoQueueBase class header\n *\n * \\author Copyright (C) 2014 Kamil Szczygiel http:\/\/www.distortec.com http:\/\/www.freddiechopin.info\n *\n * \\par License\n * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not\n * distributed with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\date 2014-12-17\n *\/\n\n#ifndef INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\n#define INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\n\n#include \"distortos\/Semaphore.hpp\"\n\n#include \"distortos\/scheduler\/SemaphoreWaitFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitForFunctor.hpp\"\n#include \"distortos\/scheduler\/SemaphoreTryWaitUntilFunctor.hpp\"\n\nnamespace distortos\n{\n\nnamespace scheduler\n{\n\n\/\/\/ FifoQueueBase class implements whole functionality of FifoQueue template class\nclass FifoQueueBase\n{\npublic:\n\n\t\/\/\/ required by templated constructor to deduce type\n\ttemplate\n\tclass TypeTag\n\t{\n\n\t};\n\n\t\/\/\/ type of uninitialized storage for data\n\ttemplate\n\tusing Storage = typename std::aligned_storage::type;\n\n\t\/**\n\t * \\brief Functor is a type-erased interface for functors which execute some action on queue's storage (like\n\t * copy-constructing, swapping, destroying, emplacing, ...).\n\t *\n\t * The functor will be called by FifoQueueBase internals with one argument - \\a storage - which is a reference to\n\t * pointer to queue's storage - after executing functor's action, the pointer should be incremented to next position\n\t * (using the actual size of element)\n\t *\/\n\n\tusing Functor = estd::TypeErasedFunctor;\n\n\t\/**\n\t * \\brief BoundedFunctor is a type-erased Functor which calls its bounded functor to execute actions on queue's\n\t * storage and deals with the pointer increments\n\t *\n\t * \\param T is the type of element\n\t * \\param F is the type of bounded functor, it will be called with Storage*<\/em> as only argument\n\t *\/\n\n\ttemplate\n\tclass BoundedFunctor : public Functor\n\t{\n\tpublic:\n\n\t\t\/**\n\t\t * \\brief BoundedFunctor's constructor\n\t\t *\n\t\t * \\param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct\n\t\t * internal bounded functor\n\t\t *\/\n\n\t\tconstexpr explicit BoundedFunctor(F&& boundedFunctor) :\n\t\t\t\tboundedFunctor_{std::move(boundedFunctor)}\n\t\t{\n\n\t\t}\n\n\t\t\/**\n\t\t * \\brief Calls the bounded functor which will execute some action on queue's storage (like copy-constructing,\n\t\t * swapping, destroying, emplacing, ...) and increments the storage pointer to next position (using the actual\n\t\t * size of element)\n\t\t *\n\t\t * \\param [in,out] storage is a reference to pointer to queue's storage - after executing bounded functor, the\n\t\t * pointer will be incremented to next position (using the actual size of element)\n\t\t *\/\n\n\t\tvirtual void operator()(void*& storage) const override\n\t\t{\n\t\t\tauto typedStorage = static_cast*>(storage);\n\t\t\tboundedFunctor_(typedStorage);\n\t\t\tstorage = typedStorage + 1;\n\t\t}\n\n\tprivate:\n\n\t\t\/\/\/ bounded functor\n\t\tF boundedFunctor_;\n\t};\n\n\t\/**\n\t * \\brief Helper factory function to make BoundedFunctor object with partially deduced template arguments\n\t *\n\t * \\param T is the type of element\n\t * \\param F is the type of bounded functor, it will be called with Storage*<\/em> as only argument\n\t *\n\t * \\param [in] boundedFunctor is a rvalue reference to bounded functor which will be used to move-construct internal\n\t * bounded functor\n\t *\n\t * \\return BoundedFunctor object with partially deduced template arguments\n\t *\/\n\n\ttemplate\n\tconstexpr static BoundedFunctor makeBoundedFunctor(F&& boundedFunctor)\n\t{\n\t\treturn BoundedFunctor{std::move(boundedFunctor)};\n\t}\n\n\t\/**\n\t * \\brief FifoQueueBase's constructor\n\t *\n\t * \\param T is the type of data in queue\n\t *\n\t * \\param [in] storage is an array of Storage elements\n\t * \\param [in] maxElements is the number of elements in storage array\n\t * \\param [in] typeTag is used to deduce T, as deduction from storage is not possible (nested-name-specifier, so a\n\t * non-deduced context)\n\t *\/\n\n\ttemplate\n\tFifoQueueBase(Storage* const storage, size_t maxElements, TypeTag);\n\n\t\/**\n\t * \\brief Implementation of pop() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a popSemaphore_\n\t * \\param [in] functor is a reference to Functor which will execute actions related to popping - it will get a\n\t * reference to readPosition_ as argument\n\t *\n\t * \\return zero if element was popped successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint popImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)\n\t{\n\t\treturn popPushImplementation(waitSemaphoreFunctor, functor, popSemaphore_, pushSemaphore_, readPosition_);\n\t}\n\n\t\/**\n\t * \\brief Implementation of push() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] functor is a reference to Functor which will execute actions related to pushing - it will get a\n\t * reference to writePosition_ as argument\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint pushImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor)\n\t{\n\t\treturn popPushImplementation(waitSemaphoreFunctor, functor, pushSemaphore_, popSemaphore_, writePosition_);\n\t}\n\n\t\/**\n\t * \\brief Pushes the element to the queue.\n\t *\n\t * Internal version - builds the Functor object.\n\t *\n\t * \\param T is the type of data pushed to queue\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] value is a reference to object that will be pushed, value in queue's storage is copy-constructed\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\ttemplate\n\tint pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, const T& value);\n\n\t\/**\n\t * \\brief Pushes the element to the queue.\n\t *\n\t * Internal version - builds the Functor object.\n\t *\n\t * \\param T is the type of data pushed to queue\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a pushSemaphore_\n\t * \\param [in] value is a rvalue reference to object that will be pushed, value in queue's storage is\n\t * move-constructed\n\t *\n\t * \\return zero if element was pushed successfully, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\ttemplate\n\tint pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, T&& value);\n\nprivate:\n\n\t\/**\n\t * \\brief Implementation of pop() and push() using type-erased functor\n\t *\n\t * \\param [in] waitSemaphoreFunctor is a reference to SemaphoreFunctor which will be executed with \\a waitSemaphore\n\t * \\param [in] functor is a reference to Functor which will execute actions related to popping\/pushing - it will get\n\t * a reference to \\a storage as argument\n\t * \\param [in] waitSemaphore is a reference to semaphore that will be waited for, \\a popSemaphore_ for pop(), \\a\n\t * pushSemaphore_ for push()\n\t * \\param [in] postSemaphore is a reference to semaphore that will be posted after the operation, \\a pushSemaphore_\n\t * for pop(), \\a popSemaphore_ for push()\n\t * \\param [in] storage is a reference to appropriate pointer to storage, which will be passed to \\a functor, \\a\n\t * readPosition_ for pop(), \\a writePosition_ for push()\n\t *\n\t * \\return zero if operation was successful, error code otherwise:\n\t * - error codes returned by \\a waitSemaphoreFunctor's operator() call;\n\t * - error codes returned by Semaphore::post();\n\t *\/\n\n\tint popPushImplementation(const SemaphoreFunctor& waitSemaphoreFunctor, const Functor& functor,\n\t\t\tSemaphore& waitSemaphore, Semaphore& postSemaphore, void*& storage);\n\n\t\/\/\/ semaphore guarding access to \"pop\" functions - its value is equal to the number of available elements\n\tSemaphore popSemaphore_;\n\n\t\/\/\/ semaphore guarding access to \"push\" functions - its value is equal to the number of free slots\n\tSemaphore pushSemaphore_;\n\n\t\/\/\/ beginning of array with Storage elements\n\tvoid* const storageBegin_;\n\n\t\/\/\/ pointer to past-the-last element of array with Storage elements\n\tvoid* const storageEnd_;\n\n\t\/\/\/ pointer to first element available for reading\n\tvoid* readPosition_;\n\n\t\/\/\/ pointer to first free slot available for writing\n\tvoid* writePosition_;\n};\n\ntemplate\nFifoQueueBase::FifoQueueBase(Storage* const storage, const size_t maxElements, TypeTag) :\n\t\tpopSemaphore_{0, maxElements},\n\t\tpushSemaphore_{maxElements, maxElements},\n\t\tstorageBegin_{storage},\n\t\tstorageEnd_{storage + maxElements},\n\t\treadPosition_{storage},\n\t\twritePosition_{storage}\n{\n\n}\n\ntemplate\nint FifoQueueBase::pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, const T& value)\n{\n\tconst auto copyFunctor = makeBoundedFunctor(\n\t\t\t[&value](Storage* const storage)\n\t\t\t{\n\t\t\t\tnew (storage) T{value};\n\t\t\t});\n\treturn pushImplementation(waitSemaphoreFunctor, copyFunctor);\n}\n\ntemplate\nint FifoQueueBase::pushInternal(const SemaphoreFunctor& waitSemaphoreFunctor, T&& value)\n{\n\tconst auto moveFunctor = makeBoundedFunctor(\n\t\t\t[&value](Storage* const storage)\n\t\t\t{\n\t\t\t\tnew (storage) T{std::move(value)};\n\t\t\t});\n\treturn pushImplementation(waitSemaphoreFunctor, moveFunctor);\n}\n\n}\t\/\/ namespace scheduler\n\n}\t\/\/ namespace distortos\n\n#endif\t\/\/ INCLUDE_DISTORTOS_SCHEDULER_FIFOQUEUEBASE_HPP_\n<|endoftext|>"} {"text":"#include \"cssysdef.h\"\n#include \"aws\/awslabel.h\"\n#include \"ivideo\/graph2d.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"ivideo\/fontserv.h\"\n#include \"csutil\/scfstr.h\"\n\n#include \n\nSCF_IMPLEMENT_IBASE(awsLabel)\n SCF_IMPLEMENTS_INTERFACE(awsComponent)\nSCF_IMPLEMENT_IBASE_END\n\nconst int awsLabel::signalClicked=0x1;\n\nawsLabel::awsLabel():is_down(false), mouse_is_over(false), \n caption(NULL)\n{ }\n\nawsLabel::~awsLabel()\n{ }\n\nchar *\nawsLabel::Type() \n{ return \"Label\"; }\n\nbool\nawsLabel::Setup(iAws *_wmgr, awsComponentNode *settings)\n{\n if (!awsComponent::Setup(_wmgr, settings)) return false;\n\n iAwsPrefManager *pm=WindowManager()->GetPrefMgr();\n\n pm->GetString(settings, \"Caption\", caption);\n\n return true;\n}\n\nbool \nawsLabel::GetProperty(char *name, void **parm)\n{\n if (awsComponent::GetProperty(name, parm)) return true;\n\n if (strcmp(\"Caption\", name)==0)\n {\n char *st = NULL;\n\n if (caption) st=caption->GetData();\n\n iString *s = new scfString(st);\n *parm = (void *)s;\n return true;\n }\n\n return false;\n}\n\nbool \nawsLabel::SetProperty(char *name, void *parm)\n{\n if (awsComponent::SetProperty(name, parm)) return true;\n\n if (strcmp(\"Caption\", name)==0)\n {\n iString *s = (iString *)(parm);\n \n if (s)\n {\n if (caption) caption->DecRef();\n caption=s;\n caption->IncRef();\n Invalidate();\n }\n \n return true;\n }\n \n return false;\n}\n\n\nvoid \nawsLabel::OnDraw(csRect clip)\n{\n iGraphics2D *g2d = WindowManager()->G2D();\n \n \/\/ Draw the caption, if there is one \n if (caption)\n { \n int tw, th, tx, ty;\n \n \/\/ Get the size of the text\n WindowManager()->GetPrefMgr()->GetDefaultFont()->GetDimensions(caption->GetData(), tw, th);\n\n \/\/ Calculate the center\n tx = (Frame().Width()>>1) - (tw>>1);\n ty = (Frame().Height()>>1) - (th>>1);\n\n \/\/ Draw the text\n g2d->Write(WindowManager()->GetPrefMgr()->GetDefaultFont(),\n Frame().xmin+tx+is_down,\n Frame().ymin+ty+is_down,\n WindowManager()->GetPrefMgr()->GetColor(AC_TEXTFORE),\n -1,\n caption->GetData());\n\n }\n}\n\nbool \nawsLabel::OnMouseDown(int button, int x, int y)\n{\n is_down=true;\n \/\/Invalidate();\n return false;\n}\n \nbool \nawsLabel::OnMouseUp(int button, int x, int y)\n{\n if (is_down)\n Broadcast(signalClicked);\n\n is_down=false;\n \/\/Invalidate();\n return false;\n}\n \nbool\nawsLabel::OnMouseMove(int button, int x, int y)\n{\n return false;\n}\n\nbool\nawsLabel::OnMouseClick(int button, int x, int y)\n{\n return false;\n}\n\nbool\nawsLabel::OnMouseDoubleClick(int button, int x, int y)\n{\n return false;\n}\n\nbool \nawsLabel::OnMouseExit()\n{\n mouse_is_over=false;\n \/\/Invalidate();\n\n if (is_down)\n is_down=false;\n \n return true;\n}\n\nbool\nawsLabel::OnMouseEnter()\n{\n mouse_is_over=true;\n \/\/Invalidate();\n return true;\n}\n\nbool\nawsLabel::OnKeypress(int key, int modifiers)\n{\n return false;\n}\n \nbool\nawsLabel::OnLostFocus()\n{\n return false;\n}\n\nbool \nawsLabel::OnGainFocus()\n{\n return false;\n}\n\n\/************************************* Command Button Factory ****************\/\nSCF_IMPLEMENT_IBASE(awsLabelFactory)\n SCF_IMPLEMENTS_INTERFACE(iAwsComponentFactory)\nSCF_IMPLEMENT_IBASE_END\n\nawsLabelFactory::awsLabelFactory(iAws *wmgr):awsComponentFactory(wmgr)\n{\n Register(\"Label\");\n RegisterConstant(\"signalLabelClicked\", awsLabel::signalClicked);\n}\n\nawsLabelFactory::~awsLabelFactory()\n{\n \/\/ empty\n}\n\niAwsComponent *\nawsLabelFactory::Create()\n{\n return new awsLabel; \n}\n\nChristopher:#include \"cssysdef.h\"\n#include \"aws\/awslabel.h\"\n#include \"ivideo\/graph2d.h\"\n#include \"ivideo\/graph3d.h\"\n#include \"ivideo\/fontserv.h\"\n#include \"csutil\/scfstr.h\"\n\n#include \n\nSCF_IMPLEMENT_IBASE(awsLabel)\n SCF_IMPLEMENTS_INTERFACE(awsComponent)\nSCF_IMPLEMENT_IBASE_END\n\nconst int awsLabel::signalClicked=0x1;\n\nconst int awsLabel::alignLeft=0x0;\nconst int awsLabel::alignRight=0x1;\nconst int awsLabel::alignCenter=0x2;\n\nawsLabel::awsLabel():is_down(false), mouse_is_over(false), alignment(0), \n caption(NULL)\n{ }\n\nawsLabel::~awsLabel()\n{ }\n\nchar *\nawsLabel::Type() \n{ return \"Label\"; }\n\nbool\nawsLabel::Setup(iAws *_wmgr, awsComponentNode *settings)\n{\n if (!awsComponent::Setup(_wmgr, settings)) return false;\n\n iAwsPrefManager *pm=WindowManager()->GetPrefMgr();\n\n pm->GetString(settings, \"Caption\", caption);\n pm->GetInt(settings, \"Align\", alignment);\n\n return true;\n}\n\nbool \nawsLabel::GetProperty(char *name, void **parm)\n{\n if (awsComponent::GetProperty(name, parm)) return true;\n\n if (strcmp(\"Caption\", name)==0)\n {\n char *st = NULL;\n\n if (caption) st=caption->GetData();\n\n iString *s = new scfString(st);\n *parm = (void *)s;\n return true;\n }\n\n return false;\n}\n\nbool \nawsLabel::SetProperty(char *name, void *parm)\n{\n if (awsComponent::SetProperty(name, parm)) return true;\n\n if (strcmp(\"Caption\", name)==0)\n {\n iString *s = (iString *)(parm);\n \n if (s)\n {\n if (caption) caption->DecRef();\n caption=s;\n caption->IncRef();\n Invalidate();\n }\n \n return true;\n }\n \n return false;\n}\n\n\nvoid \nawsLabel::OnDraw(csRect clip)\n{\n iGraphics2D *g2d = WindowManager()->G2D();\n \n \/\/ Draw the caption, if there is one \n if (caption)\n { \n int tw, th, tx, ty, mcc;\n \n mcc = WindowManager()->GetPrefMgr()->GetDefaultFont()->GetLength(caption->GetData(), Frame().Width());\n\n scfString tmp(caption->GetData());\n tmp.Truncate(mcc);\n\n \/\/ Get the size of the text\n WindowManager()->GetPrefMgr()->GetDefaultFont()->GetDimensions(tmp.GetData(), tw, th);\n\n \/\/ Calculate the center\n ty = (Frame().Height()>>1) - (th>>1);\n\n switch(alignment)\n {\n case alignRight:\n tx = Frame().Width()-tw;\n break;\n\n case alignCenter:\n tx = (Frame().Width()>>1) - (tw>>1);\n break;\n\n default:\n tx = 0;\n break;\n }\n\n\n\n \/\/ Draw the text\n g2d->Write(WindowManager()->GetPrefMgr()->GetDefaultFont(),\n Frame().xmin+tx+is_down,\n Frame().ymin+ty+is_down,\n WindowManager()->GetPrefMgr()->GetColor(AC_TEXTFORE),\n -1,\n tmp.GetData());\n\n }\n}\n\nbool \nawsLabel::OnMouseDown(int button, int x, int y)\n{\n is_down=true;\n \/\/Invalidate();\n return false;\n}\n \nbool \nawsLabel::OnMouseUp(int button, int x, int y)\n{\n if (is_down)\n Broadcast(signalClicked);\n\n is_down=false;\n \/\/Invalidate();\n return false;\n}\n \nbool\nawsLabel::OnMouseMove(int button, int x, int y)\n{\n return false;\n}\n\nbool\nawsLabel::OnMouseClick(int button, int x, int y)\n{\n return false;\n}\n\nbool\nawsLabel::OnMouseDoubleClick(int button, int x, int y)\n{\n return false;\n}\n\nbool \nawsLabel::OnMouseExit()\n{\n mouse_is_over=false;\n \/\/Invalidate();\n\n if (is_down)\n is_down=false;\n \n return true;\n}\n\nbool\nawsLabel::OnMouseEnter()\n{\n mouse_is_over=true;\n \/\/Invalidate();\n return true;\n}\n\nbool\nawsLabel::OnKeypress(int key, int modifiers)\n{\n return false;\n}\n \nbool\nawsLabel::OnLostFocus()\n{\n return false;\n}\n\nbool \nawsLabel::OnGainFocus()\n{\n return false;\n}\n\n\/************************************* Command Button Factory ****************\/\nSCF_IMPLEMENT_IBASE(awsLabelFactory)\n SCF_IMPLEMENTS_INTERFACE(iAwsComponentFactory)\nSCF_IMPLEMENT_IBASE_END\n\nawsLabelFactory::awsLabelFactory(iAws *wmgr):awsComponentFactory(wmgr)\n{\n Register(\"Label\");\n RegisterConstant(\"signalLabelClicked\", awsLabel::signalClicked);\n\n RegisterConstant(\"lblAlignLeft\", awsLabel::alignLeft);\n RegisterConstant(\"lblAlignRight\", awsLabel::alignRight);\n RegisterConstant(\"lblAlignCenter\", awsLabel::alignCenter);\n}\n\nawsLabelFactory::~awsLabelFactory()\n{\n \/\/ empty\n}\n\niAwsComponent *\nawsLabelFactory::Create()\n{\n return new awsLabel; \n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Need to include this before any other file because it defines\n\/\/ IPC_MESSAGE_LOG_ENABLED. We need to use it to define\n\/\/ IPC_MESSAGE_MACROS_LOG_ENABLED so that all_messages.h will generate the\n\/\/ ViewMsgLog et al. functions.\n#include \"ipc\/ipc_message.h\"\n\n#ifdef IPC_MESSAGE_LOG_ENABLED\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n\n\/\/ We need to do this real early to be sure IPC_MESSAGE_MACROS_LOG_ENABLED\n\/\/ doesn't get undefined.\n#include \"chrome\/common\/all_messages.h\"\n\n#include \"chrome\/browser\/ui\/views\/about_ipc_dialog.h\"\n\n#include \n\n#include \"base\/string_util.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/ui\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"content\/public\/browser\/content_ipc_logging.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_job.h\"\n#include \"ui\/views\/controls\/button\/text_button.h\"\n#include \"ui\/views\/controls\/native\/native_view_host.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ We don't localize this UI since this is a developer-only feature.\nconst wchar_t kStartTrackingLabel[] = L\"Start tracking\";\nconst wchar_t kStopTrackingLabel[] = L\"Stop tracking\";\nconst wchar_t kClearLabel[] = L\"Clear\";\nconst wchar_t kFilterLabel[] = L\"Filter...\";\n\nenum {\n kTimeColumn = 0,\n kChannelColumn,\n kMessageColumn,\n kFlagsColumn,\n kDispatchColumn,\n kProcessColumn,\n kParamsColumn,\n};\n\n\/\/ This class registers the browser IPC logger functions with IPC::Logging.\nclass RegisterLoggerFuncs {\n public:\n RegisterLoggerFuncs() {\n IPC::Logging::set_log_function_map(&g_log_function_mapping);\n }\n};\n\nRegisterLoggerFuncs g_register_logger_funcs;\n\n\/\/ The singleton dialog box. This is non-NULL when a dialog is active so we\n\/\/ know not to create a new one.\nAboutIPCDialog* g_active_dialog = NULL;\n\nstd::set disabled_messages;\n\n\/\/ Settings dialog -------------------------------------------------------------\n\nbool init_done = false;\nHWND settings_dialog = NULL;\n\/\/ Settings.\nCListViewCtrl* messages = NULL;\n\nvoid OnCheck(int id, bool checked) {\n if (!init_done)\n return;\n\n if (checked)\n disabled_messages.erase(id);\n else\n disabled_messages.insert(id);\n}\n\nvoid InitDialog(HWND hwnd) {\n messages = new CListViewCtrl(::GetDlgItem(hwnd, IDC_Messages));\n\n messages->SetViewType(LVS_REPORT);\n messages->SetExtendedListViewStyle(LVS_EX_CHECKBOXES);\n messages->ModifyStyle(0, LVS_SORTASCENDING | LVS_NOCOLUMNHEADER);\n messages->InsertColumn(0, L\"id\", LVCFMT_LEFT, 230);\n\n LogFunctionMap* log_functions = IPC::Logging::log_function_map();\n for (LogFunctionMap::iterator i = log_functions->begin();\n i != log_functions->end(); ++i) {\n std::string name;\n (*i->second)(&name, NULL, NULL);\n if (name.empty())\n continue; \/\/ Will happen if the message file isn't included above.\n std::wstring wname = UTF8ToWide(name);\n\n int index = messages->InsertItem(\n LVIF_TEXT | LVIF_PARAM, 0, wname.c_str(), 0, 0, 0, i->first);\n\n messages->SetItemText(index, 0, wname.c_str());\n\n if (disabled_messages.find(i->first) == disabled_messages.end())\n messages->SetCheckState(index, TRUE);\n }\n\n init_done = true;\n}\n\nvoid CloseDialog() {\n delete messages;\n messages = NULL;\n\n init_done = false;\n\n ::DestroyWindow(settings_dialog);\n settings_dialog = NULL;\n\n \/* The old version of this code stored the last settings in the preferences.\n But with this dialog, there currently isn't an easy way to get the profile\n to save in the preferences.\n Profile* current_profile = profile();\n if (!current_profile)\n return;\n PrefService* prefs = current_profile->GetPrefs();\n if (!prefs->FindPreference(prefs::kIpcDisabledMessages))\n return;\n ListValue* list = prefs->GetMutableList(prefs::kIpcDisabledMessages);\n list->Clear();\n for (std::set::const_iterator itr = disabled_messages_.begin();\n itr != disabled_messages_.end();\n ++itr) {\n list->Append(Value::CreateIntegerValue(*itr));\n }\n *\/\n}\n\nvoid OnButtonClick(int id) {\n int count = messages->GetItemCount();\n for (int i = 0; i < count; ++i)\n messages->SetCheckState(i, id == IDC_MessagesAll);\n}\n\nINT_PTR CALLBACK DialogProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {\n switch (msg) {\n case WM_INITDIALOG:\n InitDialog(hwnd);\n return FALSE; \/\/ Don't set keyboard focus.\n case WM_SYSCOMMAND:\n if (wparam == SC_CLOSE) {\n CloseDialog();\n return FALSE;\n }\n break;\n case WM_NOTIFY: {\n NMLISTVIEW* info = reinterpret_cast(lparam);\n if (wparam == IDC_Messages && info->hdr.code == LVN_ITEMCHANGED) {\n if (info->uChanged & LVIF_STATE) {\n bool checked = (info->uNewState >> 12) == 2;\n OnCheck(static_cast(info->lParam), checked);\n }\n return FALSE;\n }\n break;\n }\n case WM_COMMAND:\n if (HIWORD(wparam) == BN_CLICKED)\n OnButtonClick(LOWORD(wparam));\n break;\n }\n return FALSE;\n}\n\nvoid RunSettingsDialog(HWND parent) {\n if (settings_dialog)\n return;\n HINSTANCE module_handle = GetModuleHandle(chrome::kBrowserResourcesDll);\n settings_dialog = CreateDialog(module_handle,\n MAKEINTRESOURCE(IDD_IPC_SETTINGS),\n NULL,\n &DialogProc);\n ::ShowWindow(settings_dialog, SW_SHOW);\n}\n\n} \/\/ namespace\n\n\/\/ AboutIPCDialog --------------------------------------------------------------\n\nAboutIPCDialog::AboutIPCDialog()\n : track_toggle_(NULL),\n clear_button_(NULL),\n filter_button_(NULL),\n table_(NULL),\n tracking_(false) {\n SetupControls();\n IPC::Logging::GetInstance()->SetConsumer(this);\n}\n\nAboutIPCDialog::~AboutIPCDialog() {\n g_active_dialog = NULL;\n IPC::Logging::GetInstance()->SetConsumer(NULL);\n}\n\n\/\/ static\nvoid AboutIPCDialog::RunDialog() {\n if (!g_active_dialog) {\n g_active_dialog = new AboutIPCDialog;\n views::Widget::CreateWindow(g_active_dialog)->Show();\n } else {\n \/\/ TODO(brettw) it would be nice to focus the existing window.\n }\n}\n\nvoid AboutIPCDialog::SetupControls() {\n views::GridLayout* layout = views::GridLayout::CreatePanel(this);\n SetLayoutManager(layout);\n\n track_toggle_ = new views::TextButton(this, kStartTrackingLabel);\n clear_button_ = new views::TextButton(this, kClearLabel);\n filter_button_ = new views::TextButton(this, kFilterLabel);\n\n table_ = new views::NativeViewHost;\n\n static const int first_column_set = 1;\n views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n\n static const int table_column_set = 2;\n column_set = layout->AddColumnSet(table_column_set);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,\n 100.0f, views::GridLayout::FIXED, 0, 0);\n\n layout->StartRow(0, first_column_set);\n layout->AddView(track_toggle_);\n layout->AddView(clear_button_);\n layout->AddView(filter_button_);\n layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);\n layout->StartRow(1.0f, table_column_set);\n layout->AddView(table_);\n}\n\ngfx::Size AboutIPCDialog::GetPreferredSize() {\n return gfx::Size(800, 400);\n}\n\nviews::View* AboutIPCDialog::GetContentsView() {\n return this;\n}\n\nint AboutIPCDialog::GetDialogButtons() const {\n \/\/ Don't want OK or Cancel.\n return 0;\n}\n\nstring16 AboutIPCDialog::GetWindowTitle() const {\n return ASCIIToUTF16(\"about:ipc\");\n}\n\nvoid AboutIPCDialog::Layout() {\n if (!message_list_.m_hWnd) {\n HWND parent_window = GetWidget()->GetNativeView();\n\n RECT rect = {0, 0, 10, 10};\n HWND list_hwnd = message_list_.Create(parent_window,\n rect, NULL, WS_CHILD | WS_VISIBLE | LVS_SORTASCENDING);\n message_list_.SetViewType(LVS_REPORT);\n message_list_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);\n\n int column_index = 0;\n message_list_.InsertColumn(kTimeColumn, L\"time\", LVCFMT_LEFT, 80);\n message_list_.InsertColumn(kChannelColumn, L\"channel\", LVCFMT_LEFT, 110);\n message_list_.InsertColumn(kMessageColumn, L\"message\", LVCFMT_LEFT, 240);\n message_list_.InsertColumn(kFlagsColumn, L\"flags\", LVCFMT_LEFT, 50);\n message_list_.InsertColumn(kDispatchColumn, L\"dispatch (ms)\", LVCFMT_RIGHT,\n 80);\n message_list_.InsertColumn(kProcessColumn, L\"process (ms)\", LVCFMT_RIGHT,\n 80);\n message_list_.InsertColumn(kParamsColumn, L\"parameters\", LVCFMT_LEFT, 500);\n\n table_->Attach(list_hwnd);\n }\n\n View::Layout();\n}\n\nvoid AboutIPCDialog::Log(const IPC::LogData& data) {\n if (disabled_messages.find(data.type) != disabled_messages.end())\n return; \/\/ Message type is filtered out.\n\n base::Time sent = base::Time::FromInternalValue(data.sent);\n base::Time::Exploded exploded;\n sent.LocalExplode(&exploded);\n if (exploded.hour > 12)\n exploded.hour -= 12;\n\n std::wstring sent_str = StringPrintf(L\"%02d:%02d:%02d.%03d\",\n exploded.hour, exploded.minute, exploded.second, exploded.millisecond);\n\n int count = message_list_.GetItemCount();\n int index = message_list_.InsertItem(count, sent_str.c_str());\n\n message_list_.SetItemText(index, kTimeColumn, sent_str.c_str());\n message_list_.SetItemText(index, kChannelColumn,\n ASCIIToWide(data.channel).c_str());\n\n std::string message_name;\n IPC::Logging::GetMessageText(data.type, &message_name, NULL, NULL);\n message_list_.SetItemText(index, kMessageColumn,\n UTF8ToWide(message_name).c_str());\n message_list_.SetItemText(index, kFlagsColumn,\n UTF8ToWide(data.flags).c_str());\n\n int64 time_to_send = (base::Time::FromInternalValue(data.receive) -\n sent).InMilliseconds();\n \/\/ time can go backwards by a few ms (see Time), don't show that.\n time_to_send = std::max(static_cast(time_to_send), 0);\n std::wstring temp = StringPrintf(L\"%d\", time_to_send);\n message_list_.SetItemText(index, kDispatchColumn, temp.c_str());\n\n int64 time_to_process = (base::Time::FromInternalValue(data.dispatch) -\n base::Time::FromInternalValue(data.receive)).InMilliseconds();\n time_to_process = std::max(static_cast(time_to_process), 0);\n temp = StringPrintf(L\"%d\", time_to_process);\n message_list_.SetItemText(index, kProcessColumn, temp.c_str());\n\n message_list_.SetItemText(index, kParamsColumn,\n UTF8ToWide(data.params).c_str());\n message_list_.EnsureVisible(index, FALSE);\n}\n\nbool AboutIPCDialog::CanResize() const {\n return true;\n}\n\nvoid AboutIPCDialog::ButtonPressed(\n views::Button* button, const views::Event& event) {\n if (button == track_toggle_) {\n if (tracking_) {\n track_toggle_->SetText(kStartTrackingLabel);\n tracking_ = false;\n content::EnableIPCLogging(false);\n } else {\n track_toggle_->SetText(kStopTrackingLabel);\n tracking_ = true;\n content::EnableIPCLogging(true);\n }\n track_toggle_->SchedulePaint();\n } else if (button == clear_button_) {\n message_list_.DeleteAllItems();\n } else if (button == filter_button_) {\n RunSettingsDialog(GetWidget()->GetNativeView());\n }\n}\n\nnamespace browser {\n\nvoid ShowAboutIPCDialog() {\n AboutIPCDialog::RunDialog();\n}\n\n} \/\/ namespace browser\n\n#endif \/\/ IPC_MESSAGE_LOG_ENABLED\nviews: Return the appropriate value for GetDialogButtons() in AboutIPCDialog.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Need to include this before any other file because it defines\n\/\/ IPC_MESSAGE_LOG_ENABLED. We need to use it to define\n\/\/ IPC_MESSAGE_MACROS_LOG_ENABLED so that all_messages.h will generate the\n\/\/ ViewMsgLog et al. functions.\n#include \"ipc\/ipc_message.h\"\n\n#ifdef IPC_MESSAGE_LOG_ENABLED\n#define IPC_MESSAGE_MACROS_LOG_ENABLED\n\n\/\/ We need to do this real early to be sure IPC_MESSAGE_MACROS_LOG_ENABLED\n\/\/ doesn't get undefined.\n#include \"chrome\/common\/all_messages.h\"\n\n#include \"chrome\/browser\/ui\/views\/about_ipc_dialog.h\"\n\n#include \n\n#include \"base\/string_util.h\"\n#include \"base\/threading\/thread.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/app\/chrome_command_ids.h\"\n#include \"chrome\/app\/chrome_dll_resource.h\"\n#include \"chrome\/browser\/ui\/browser_dialogs.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"content\/public\/browser\/content_ipc_logging.h\"\n#include \"net\/url_request\/url_request.h\"\n#include \"net\/url_request\/url_request_job.h\"\n#include \"ui\/views\/controls\/button\/text_button.h\"\n#include \"ui\/views\/controls\/native\/native_view_host.h\"\n#include \"ui\/views\/layout\/grid_layout.h\"\n#include \"ui\/views\/layout\/layout_constants.h\"\n#include \"ui\/views\/widget\/widget.h\"\n\nnamespace {\n\n\/\/ We don't localize this UI since this is a developer-only feature.\nconst wchar_t kStartTrackingLabel[] = L\"Start tracking\";\nconst wchar_t kStopTrackingLabel[] = L\"Stop tracking\";\nconst wchar_t kClearLabel[] = L\"Clear\";\nconst wchar_t kFilterLabel[] = L\"Filter...\";\n\nenum {\n kTimeColumn = 0,\n kChannelColumn,\n kMessageColumn,\n kFlagsColumn,\n kDispatchColumn,\n kProcessColumn,\n kParamsColumn,\n};\n\n\/\/ This class registers the browser IPC logger functions with IPC::Logging.\nclass RegisterLoggerFuncs {\n public:\n RegisterLoggerFuncs() {\n IPC::Logging::set_log_function_map(&g_log_function_mapping);\n }\n};\n\nRegisterLoggerFuncs g_register_logger_funcs;\n\n\/\/ The singleton dialog box. This is non-NULL when a dialog is active so we\n\/\/ know not to create a new one.\nAboutIPCDialog* g_active_dialog = NULL;\n\nstd::set disabled_messages;\n\n\/\/ Settings dialog -------------------------------------------------------------\n\nbool init_done = false;\nHWND settings_dialog = NULL;\n\/\/ Settings.\nCListViewCtrl* messages = NULL;\n\nvoid OnCheck(int id, bool checked) {\n if (!init_done)\n return;\n\n if (checked)\n disabled_messages.erase(id);\n else\n disabled_messages.insert(id);\n}\n\nvoid InitDialog(HWND hwnd) {\n messages = new CListViewCtrl(::GetDlgItem(hwnd, IDC_Messages));\n\n messages->SetViewType(LVS_REPORT);\n messages->SetExtendedListViewStyle(LVS_EX_CHECKBOXES);\n messages->ModifyStyle(0, LVS_SORTASCENDING | LVS_NOCOLUMNHEADER);\n messages->InsertColumn(0, L\"id\", LVCFMT_LEFT, 230);\n\n LogFunctionMap* log_functions = IPC::Logging::log_function_map();\n for (LogFunctionMap::iterator i = log_functions->begin();\n i != log_functions->end(); ++i) {\n std::string name;\n (*i->second)(&name, NULL, NULL);\n if (name.empty())\n continue; \/\/ Will happen if the message file isn't included above.\n std::wstring wname = UTF8ToWide(name);\n\n int index = messages->InsertItem(\n LVIF_TEXT | LVIF_PARAM, 0, wname.c_str(), 0, 0, 0, i->first);\n\n messages->SetItemText(index, 0, wname.c_str());\n\n if (disabled_messages.find(i->first) == disabled_messages.end())\n messages->SetCheckState(index, TRUE);\n }\n\n init_done = true;\n}\n\nvoid CloseDialog() {\n delete messages;\n messages = NULL;\n\n init_done = false;\n\n ::DestroyWindow(settings_dialog);\n settings_dialog = NULL;\n\n \/* The old version of this code stored the last settings in the preferences.\n But with this dialog, there currently isn't an easy way to get the profile\n to save in the preferences.\n Profile* current_profile = profile();\n if (!current_profile)\n return;\n PrefService* prefs = current_profile->GetPrefs();\n if (!prefs->FindPreference(prefs::kIpcDisabledMessages))\n return;\n ListValue* list = prefs->GetMutableList(prefs::kIpcDisabledMessages);\n list->Clear();\n for (std::set::const_iterator itr = disabled_messages_.begin();\n itr != disabled_messages_.end();\n ++itr) {\n list->Append(Value::CreateIntegerValue(*itr));\n }\n *\/\n}\n\nvoid OnButtonClick(int id) {\n int count = messages->GetItemCount();\n for (int i = 0; i < count; ++i)\n messages->SetCheckState(i, id == IDC_MessagesAll);\n}\n\nINT_PTR CALLBACK DialogProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {\n switch (msg) {\n case WM_INITDIALOG:\n InitDialog(hwnd);\n return FALSE; \/\/ Don't set keyboard focus.\n case WM_SYSCOMMAND:\n if (wparam == SC_CLOSE) {\n CloseDialog();\n return FALSE;\n }\n break;\n case WM_NOTIFY: {\n NMLISTVIEW* info = reinterpret_cast(lparam);\n if (wparam == IDC_Messages && info->hdr.code == LVN_ITEMCHANGED) {\n if (info->uChanged & LVIF_STATE) {\n bool checked = (info->uNewState >> 12) == 2;\n OnCheck(static_cast(info->lParam), checked);\n }\n return FALSE;\n }\n break;\n }\n case WM_COMMAND:\n if (HIWORD(wparam) == BN_CLICKED)\n OnButtonClick(LOWORD(wparam));\n break;\n }\n return FALSE;\n}\n\nvoid RunSettingsDialog(HWND parent) {\n if (settings_dialog)\n return;\n HINSTANCE module_handle = GetModuleHandle(chrome::kBrowserResourcesDll);\n settings_dialog = CreateDialog(module_handle,\n MAKEINTRESOURCE(IDD_IPC_SETTINGS),\n NULL,\n &DialogProc);\n ::ShowWindow(settings_dialog, SW_SHOW);\n}\n\n} \/\/ namespace\n\n\/\/ AboutIPCDialog --------------------------------------------------------------\n\nAboutIPCDialog::AboutIPCDialog()\n : track_toggle_(NULL),\n clear_button_(NULL),\n filter_button_(NULL),\n table_(NULL),\n tracking_(false) {\n SetupControls();\n IPC::Logging::GetInstance()->SetConsumer(this);\n}\n\nAboutIPCDialog::~AboutIPCDialog() {\n g_active_dialog = NULL;\n IPC::Logging::GetInstance()->SetConsumer(NULL);\n}\n\n\/\/ static\nvoid AboutIPCDialog::RunDialog() {\n if (!g_active_dialog) {\n g_active_dialog = new AboutIPCDialog;\n views::Widget::CreateWindow(g_active_dialog)->Show();\n } else {\n \/\/ TODO(brettw) it would be nice to focus the existing window.\n }\n}\n\nvoid AboutIPCDialog::SetupControls() {\n views::GridLayout* layout = views::GridLayout::CreatePanel(this);\n SetLayoutManager(layout);\n\n track_toggle_ = new views::TextButton(this, kStartTrackingLabel);\n clear_button_ = new views::TextButton(this, kClearLabel);\n filter_button_ = new views::TextButton(this, kFilterLabel);\n\n table_ = new views::NativeViewHost;\n\n static const int first_column_set = 1;\n views::ColumnSet* column_set = layout->AddColumnSet(first_column_set);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n column_set->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER,\n 33.33f, views::GridLayout::FIXED, 0, 0);\n\n static const int table_column_set = 2;\n column_set = layout->AddColumnSet(table_column_set);\n column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL,\n 100.0f, views::GridLayout::FIXED, 0, 0);\n\n layout->StartRow(0, first_column_set);\n layout->AddView(track_toggle_);\n layout->AddView(clear_button_);\n layout->AddView(filter_button_);\n layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing);\n layout->StartRow(1.0f, table_column_set);\n layout->AddView(table_);\n}\n\ngfx::Size AboutIPCDialog::GetPreferredSize() {\n return gfx::Size(800, 400);\n}\n\nviews::View* AboutIPCDialog::GetContentsView() {\n return this;\n}\n\nint AboutIPCDialog::GetDialogButtons() const {\n return ui::DIALOG_BUTTON_NONE;\n}\n\nstring16 AboutIPCDialog::GetWindowTitle() const {\n return ASCIIToUTF16(\"about:ipc\");\n}\n\nvoid AboutIPCDialog::Layout() {\n if (!message_list_.m_hWnd) {\n HWND parent_window = GetWidget()->GetNativeView();\n\n RECT rect = {0, 0, 10, 10};\n HWND list_hwnd = message_list_.Create(parent_window,\n rect, NULL, WS_CHILD | WS_VISIBLE | LVS_SORTASCENDING);\n message_list_.SetViewType(LVS_REPORT);\n message_list_.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT);\n\n int column_index = 0;\n message_list_.InsertColumn(kTimeColumn, L\"time\", LVCFMT_LEFT, 80);\n message_list_.InsertColumn(kChannelColumn, L\"channel\", LVCFMT_LEFT, 110);\n message_list_.InsertColumn(kMessageColumn, L\"message\", LVCFMT_LEFT, 240);\n message_list_.InsertColumn(kFlagsColumn, L\"flags\", LVCFMT_LEFT, 50);\n message_list_.InsertColumn(kDispatchColumn, L\"dispatch (ms)\", LVCFMT_RIGHT,\n 80);\n message_list_.InsertColumn(kProcessColumn, L\"process (ms)\", LVCFMT_RIGHT,\n 80);\n message_list_.InsertColumn(kParamsColumn, L\"parameters\", LVCFMT_LEFT, 500);\n\n table_->Attach(list_hwnd);\n }\n\n View::Layout();\n}\n\nvoid AboutIPCDialog::Log(const IPC::LogData& data) {\n if (disabled_messages.find(data.type) != disabled_messages.end())\n return; \/\/ Message type is filtered out.\n\n base::Time sent = base::Time::FromInternalValue(data.sent);\n base::Time::Exploded exploded;\n sent.LocalExplode(&exploded);\n if (exploded.hour > 12)\n exploded.hour -= 12;\n\n std::wstring sent_str = StringPrintf(L\"%02d:%02d:%02d.%03d\",\n exploded.hour, exploded.minute, exploded.second, exploded.millisecond);\n\n int count = message_list_.GetItemCount();\n int index = message_list_.InsertItem(count, sent_str.c_str());\n\n message_list_.SetItemText(index, kTimeColumn, sent_str.c_str());\n message_list_.SetItemText(index, kChannelColumn,\n ASCIIToWide(data.channel).c_str());\n\n std::string message_name;\n IPC::Logging::GetMessageText(data.type, &message_name, NULL, NULL);\n message_list_.SetItemText(index, kMessageColumn,\n UTF8ToWide(message_name).c_str());\n message_list_.SetItemText(index, kFlagsColumn,\n UTF8ToWide(data.flags).c_str());\n\n int64 time_to_send = (base::Time::FromInternalValue(data.receive) -\n sent).InMilliseconds();\n \/\/ time can go backwards by a few ms (see Time), don't show that.\n time_to_send = std::max(static_cast(time_to_send), 0);\n std::wstring temp = StringPrintf(L\"%d\", time_to_send);\n message_list_.SetItemText(index, kDispatchColumn, temp.c_str());\n\n int64 time_to_process = (base::Time::FromInternalValue(data.dispatch) -\n base::Time::FromInternalValue(data.receive)).InMilliseconds();\n time_to_process = std::max(static_cast(time_to_process), 0);\n temp = StringPrintf(L\"%d\", time_to_process);\n message_list_.SetItemText(index, kProcessColumn, temp.c_str());\n\n message_list_.SetItemText(index, kParamsColumn,\n UTF8ToWide(data.params).c_str());\n message_list_.EnsureVisible(index, FALSE);\n}\n\nbool AboutIPCDialog::CanResize() const {\n return true;\n}\n\nvoid AboutIPCDialog::ButtonPressed(\n views::Button* button, const views::Event& event) {\n if (button == track_toggle_) {\n if (tracking_) {\n track_toggle_->SetText(kStartTrackingLabel);\n tracking_ = false;\n content::EnableIPCLogging(false);\n } else {\n track_toggle_->SetText(kStopTrackingLabel);\n tracking_ = true;\n content::EnableIPCLogging(true);\n }\n track_toggle_->SchedulePaint();\n } else if (button == clear_button_) {\n message_list_.DeleteAllItems();\n } else if (button == filter_button_) {\n RunSettingsDialog(GetWidget()->GetNativeView());\n }\n}\n\nnamespace browser {\n\nvoid ShowAboutIPCDialog() {\n AboutIPCDialog::RunDialog();\n}\n\n} \/\/ namespace browser\n\n#endif \/\/ IPC_MESSAGE_LOG_ENABLED\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/installer\/util\/self_reg_work_item.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/installer\/util\/logging_installer.h\"\n\n\/\/ Default registration export names.\nconst char kDefaultRegistrationEntryPoint[] = \"DllRegisterServer\";\nconst char kDefaultUnregistrationEntryPoint[] = \"DllUnregisterServer\";\n\n\/\/ User-level registration export names.\nconst char kUserRegistrationEntryPoint[] = \"DllRegisterUserServer\";\nconst char kUserUnregistrationEntryPoint[] = \"DllUnregisterUserServer\";\n\nSelfRegWorkItem::SelfRegWorkItem(const std::wstring& dll_path,\n bool do_register,\n bool user_level_registration)\n : do_register_(do_register), dll_path_(dll_path),\n user_level_registration_(user_level_registration) {\n}\n\nSelfRegWorkItem::~SelfRegWorkItem() {\n}\n\nbool SelfRegWorkItem::RegisterDll(bool do_register) {\n HMODULE dll_module = ::LoadLibraryEx(dll_path_.c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n bool success = false;\n if (NULL != dll_module) {\n PROC register_server_func = NULL;\n if (do_register) {\n register_server_func = ::GetProcAddress(dll_module,\n user_level_registration_ ? kUserRegistrationEntryPoint :\n kDefaultRegistrationEntryPoint);\n } else {\n register_server_func = ::GetProcAddress(dll_module,\n user_level_registration_ ? kUserUnregistrationEntryPoint :\n kDefaultUnregistrationEntryPoint);\n }\n\n if (NULL != register_server_func) {\n success = SUCCEEDED(register_server_func());\n if (!success) {\n LOG(ERROR) << \"Failed to \" << (do_register ? \"register\" : \"unregister\")\n << \" DLL at \" << dll_path_.c_str();\n }\n }\n ::FreeLibrary(dll_module);\n }\n return success;\n}\n\nbool SelfRegWorkItem::Do() {\n return RegisterDll(do_register_);\n}\n\nvoid SelfRegWorkItem::Rollback() {\n RegisterDll(!do_register_);\n}\nAdd some verbose logging when registering COM components.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/installer\/util\/self_reg_work_item.h\"\n\n#include \"base\/logging.h\"\n#include \"chrome\/installer\/util\/logging_installer.h\"\n\n\/\/ Default registration export names.\nconst char kDefaultRegistrationEntryPoint[] = \"DllRegisterServer\";\nconst char kDefaultUnregistrationEntryPoint[] = \"DllUnregisterServer\";\n\n\/\/ User-level registration export names.\nconst char kUserRegistrationEntryPoint[] = \"DllRegisterUserServer\";\nconst char kUserUnregistrationEntryPoint[] = \"DllUnregisterUserServer\";\n\nSelfRegWorkItem::SelfRegWorkItem(const std::wstring& dll_path,\n bool do_register,\n bool user_level_registration)\n : do_register_(do_register), dll_path_(dll_path),\n user_level_registration_(user_level_registration) {\n}\n\nSelfRegWorkItem::~SelfRegWorkItem() {\n}\n\nbool SelfRegWorkItem::RegisterDll(bool do_register) {\n VLOG(1) << \"COM \" << (do_register ? \"registration of \" : \"unregistration of \")\n << dll_path_;\n\n HMODULE dll_module = ::LoadLibraryEx(dll_path_.c_str(), NULL,\n LOAD_WITH_ALTERED_SEARCH_PATH);\n bool success = false;\n if (NULL != dll_module) {\n PROC register_server_func = NULL;\n if (do_register) {\n register_server_func = ::GetProcAddress(dll_module,\n user_level_registration_ ? kUserRegistrationEntryPoint :\n kDefaultRegistrationEntryPoint);\n } else {\n register_server_func = ::GetProcAddress(dll_module,\n user_level_registration_ ? kUserUnregistrationEntryPoint :\n kDefaultUnregistrationEntryPoint);\n }\n\n if (NULL != register_server_func) {\n success = SUCCEEDED(register_server_func());\n if (!success) {\n LOG(ERROR) << \"Failed to \" << (do_register ? \"register\" : \"unregister\")\n << \" DLL at \" << dll_path_.c_str();\n }\n }\n ::FreeLibrary(dll_module);\n } else {\n LOG(WARNING) << \"Failed to load: \" << dll_path_;\n }\n return success;\n}\n\nbool SelfRegWorkItem::Do() {\n return RegisterDll(do_register_);\n}\n\nvoid SelfRegWorkItem::Rollback() {\n RegisterDll(!do_register_);\n}\n<|endoftext|>"} {"text":"Better message to the log when migrating across versions.<|endoftext|>"} {"text":"\/*\n * DesktopUpdateChecker.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"DesktopUpdateChecker.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"DesktopOptions.hpp\"\n#include \"DesktopURLDownloader.hpp\"\n#include \"DesktopUpdateAvailableDialog.hpp\"\n\n#include \"DesktopUtils.hpp\"\n\n#include \"config.h\"\n\nusing namespace core;\n\nnamespace desktop {\n\nQUrl UpdateChecker::checkForUpdatesURL()\n{\n QUrl url(QString::fromAscii(\"http:\/\/www.rstudio.org\/links\/check_for_update\"));\n url.addQueryItem(QString::fromAscii(\"version\"), QString::fromAscii(RSTUDIO_VERSION));\n QString platform;\n#if defined(_WIN32)\n platform = QString::fromAscii(\"windows\");\n#elif defined(__APPLE__)\n platform = QString::fromAscii(\"mac\");\n#else\n platform = QString::fromAscii(\"linux\");\n#endif\n url.addQueryItem(QString::fromAscii(\"os\"), platform);\n return url;\n}\n\nvoid UpdateChecker::performCheck(bool manuallyInvoked)\n{\n \/\/ build URL (specify key-value pair return)\n QUrl url = checkForUpdatesURL();\n url.addQueryItem(QString::fromAscii(\"format\"), QString::fromAscii(\"kvp\"));\n\n \/\/ download manifest (URL downlader frees itself)\n URLDownloader* pURLDownloader = new URLDownloader(url,\n 10000,\n manuallyInvoked,\n pOwnerWindow_);\n connect(pURLDownloader, SIGNAL(downloadError(const QString&)),\n this, SLOT(manifestDownloadError(const QString&)));\n connect(pURLDownloader, SIGNAL(downloadComplete(const QByteArray&)),\n this, SLOT(manifestDownloadComplete(const QByteArray&)));\n}\n\nvoid UpdateChecker::manifestDownloadError(const QString &message)\n{\n LOG_ERROR_MESSAGE(\"Error downloading manifest: \" + std::string(message.toUtf8().constData()));\n\n URLDownloader* pURLDownloader = qobject_cast(sender());\n if (pURLDownloader && pURLDownloader->manuallyInvoked())\n {\n \/\/ WA_DeleteOnClose\n QMessageBox* pMsg = new QMessageBox(\n safeMessageBoxIcon(QMessageBox::Warning),\n QString::fromUtf8(\"Error Checking for Updates\"),\n QString::fromUtf8(\"An error occurred while checking for updates:\\n\\n\")\n + message,\n QMessageBox::NoButton,\n pOwnerWindow_,\n Qt::Sheet | Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);\n pMsg->setWindowModality(Qt::WindowModal);\n pMsg->setAttribute(Qt::WA_DeleteOnClose);\n pMsg->addButton(new QPushButton(QString::fromUtf8(\"OK\")), QMessageBox::AcceptRole);\n pMsg->show();\n }\n}\n\nvoid UpdateChecker::manifestDownloadComplete(const QByteArray& data)\n{\n \/\/ parse manifest\n std::string manifest(data.constData(), data.size());\n http::Fields fields;\n http::util::parseForm(manifest, &fields);\n\n \/\/ get the list of ignored updates\n QStringList ignoredVersions = options().ignoredUpdateVersions();\n\n URLDownloader* pURLDownloader = qobject_cast(sender());\n\n \/\/ is there an update which we haven't already chosen to ignore?\n std::string stdUpdateVersion = http::util::fieldValue(fields, \"update-version\");\n QString updateVersion = QString::fromUtf8(stdUpdateVersion.c_str());\n if ( (updateVersion.size() > 0) &&\n (!ignoredVersions.contains(updateVersion) || pURLDownloader->manuallyInvoked()) )\n {\n \/\/ get update info\n std::string updateURL = http::util::fieldValue(fields, \"update-url\");\n std::string updateMessage = http::util::fieldValue(fields, \"update-message\");\n int isUrgent = http::util::fieldValue(fields, \"update-urgent\", 0);\n DesktopUpdateInfo updateInfo;\n updateInfo.currentVersion = QString::fromUtf8(RSTUDIO_VERSION);\n updateInfo.updatedVersion = updateVersion;\n updateInfo.updateURL = QString::fromUtf8(updateURL.c_str());\n updateInfo.updateMessage = QString::fromUtf8(updateMessage.c_str());\n updateInfo.isUrgent = isUrgent != 0;\n\n \/\/ invoke dialog\n DesktopUpdateAvailableDialog dialog(updateInfo, pOwnerWindow_);\n int result = dialog.exec();\n\n \/\/ record if we are permanently ignoring\n switch (result)\n {\n case DesktopUpdateAvailableDialog::Accepted:\n QDesktopServices::openUrl(QUrl(updateInfo.updateURL));\n break;\n case DesktopUpdateAvailableDialog::Rejected:\n break;\n case DesktopUpdateAvailableDialog::Ignored:\n ignoredVersions.append(updateVersion);\n options().setIgnoredUpdateVersions(ignoredVersions);\n break;\n }\n }\n else\n {\n if (pURLDownloader && pURLDownloader->manuallyInvoked())\n {\n \/\/ WA_DeleteOnClose\n QMessageBox* pMsg = new QMessageBox(\n safeMessageBoxIcon(QMessageBox::Information),\n QString::fromUtf8(\"No Update Available\"),\n QString::fromUtf8(\"You're using the newest version of RStudio.\"),\n QMessageBox::NoButton,\n pOwnerWindow_,\n Qt::Sheet | Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);\n pMsg->setWindowModality(Qt::WindowModal);\n pMsg->setAttribute(Qt::WA_DeleteOnClose);\n pMsg->addButton(new QPushButton(QString::fromUtf8(\"OK\")), QMessageBox::AcceptRole);\n pMsg->show();\n }\n }\n}\n\n\n} \/\/ namespace desktop\nCheck for updates passes a query param indicating whether this is a manual check\/*\n * DesktopUpdateChecker.cpp\n *\n * Copyright (C) 2009-11 by RStudio, Inc.\n *\n * This program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \"DesktopUpdateChecker.hpp\"\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"DesktopOptions.hpp\"\n#include \"DesktopURLDownloader.hpp\"\n#include \"DesktopUpdateAvailableDialog.hpp\"\n\n#include \"DesktopUtils.hpp\"\n\n#include \"config.h\"\n\nusing namespace core;\n\nnamespace desktop {\n\nQUrl UpdateChecker::checkForUpdatesURL()\n{\n QUrl url(QString::fromAscii(\"http:\/\/www.rstudio.org\/links\/check_for_update\"));\n url.addQueryItem(QString::fromAscii(\"version\"), QString::fromAscii(RSTUDIO_VERSION));\n QString platform;\n#if defined(_WIN32)\n platform = QString::fromAscii(\"windows\");\n#elif defined(__APPLE__)\n platform = QString::fromAscii(\"mac\");\n#else\n platform = QString::fromAscii(\"linux\");\n#endif\n url.addQueryItem(QString::fromAscii(\"os\"), platform);\n return url;\n}\n\nvoid UpdateChecker::performCheck(bool manuallyInvoked)\n{\n \/\/ build URL (specify key-value pair return)\n QUrl url = checkForUpdatesURL();\n url.addQueryItem(QString::fromAscii(\"format\"), QString::fromAscii(\"kvp\"));\n if (manuallyInvoked)\n url.addQueryItem(QString::fromAscii(\"manual\"), QString::fromAscii(\"true\"));\n\n \/\/ download manifest (URL downlader frees itself)\n URLDownloader* pURLDownloader = new URLDownloader(url,\n 10000,\n manuallyInvoked,\n pOwnerWindow_);\n connect(pURLDownloader, SIGNAL(downloadError(const QString&)),\n this, SLOT(manifestDownloadError(const QString&)));\n connect(pURLDownloader, SIGNAL(downloadComplete(const QByteArray&)),\n this, SLOT(manifestDownloadComplete(const QByteArray&)));\n}\n\nvoid UpdateChecker::manifestDownloadError(const QString &message)\n{\n LOG_ERROR_MESSAGE(\"Error downloading manifest: \" + std::string(message.toUtf8().constData()));\n\n URLDownloader* pURLDownloader = qobject_cast(sender());\n if (pURLDownloader && pURLDownloader->manuallyInvoked())\n {\n \/\/ WA_DeleteOnClose\n QMessageBox* pMsg = new QMessageBox(\n safeMessageBoxIcon(QMessageBox::Warning),\n QString::fromUtf8(\"Error Checking for Updates\"),\n QString::fromUtf8(\"An error occurred while checking for updates:\\n\\n\")\n + message,\n QMessageBox::NoButton,\n pOwnerWindow_,\n Qt::Sheet | Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);\n pMsg->setWindowModality(Qt::WindowModal);\n pMsg->setAttribute(Qt::WA_DeleteOnClose);\n pMsg->addButton(new QPushButton(QString::fromUtf8(\"OK\")), QMessageBox::AcceptRole);\n pMsg->show();\n }\n}\n\nvoid UpdateChecker::manifestDownloadComplete(const QByteArray& data)\n{\n \/\/ parse manifest\n std::string manifest(data.constData(), data.size());\n http::Fields fields;\n http::util::parseForm(manifest, &fields);\n\n \/\/ get the list of ignored updates\n QStringList ignoredVersions = options().ignoredUpdateVersions();\n\n URLDownloader* pURLDownloader = qobject_cast(sender());\n\n \/\/ is there an update which we haven't already chosen to ignore?\n std::string stdUpdateVersion = http::util::fieldValue(fields, \"update-version\");\n QString updateVersion = QString::fromUtf8(stdUpdateVersion.c_str());\n if ( (updateVersion.size() > 0) &&\n (!ignoredVersions.contains(updateVersion) || pURLDownloader->manuallyInvoked()) )\n {\n \/\/ get update info\n std::string updateURL = http::util::fieldValue(fields, \"update-url\");\n std::string updateMessage = http::util::fieldValue(fields, \"update-message\");\n int isUrgent = http::util::fieldValue(fields, \"update-urgent\", 0);\n DesktopUpdateInfo updateInfo;\n updateInfo.currentVersion = QString::fromUtf8(RSTUDIO_VERSION);\n updateInfo.updatedVersion = updateVersion;\n updateInfo.updateURL = QString::fromUtf8(updateURL.c_str());\n updateInfo.updateMessage = QString::fromUtf8(updateMessage.c_str());\n updateInfo.isUrgent = isUrgent != 0;\n\n \/\/ invoke dialog\n DesktopUpdateAvailableDialog dialog(updateInfo, pOwnerWindow_);\n int result = dialog.exec();\n\n \/\/ record if we are permanently ignoring\n switch (result)\n {\n case DesktopUpdateAvailableDialog::Accepted:\n QDesktopServices::openUrl(QUrl(updateInfo.updateURL));\n break;\n case DesktopUpdateAvailableDialog::Rejected:\n break;\n case DesktopUpdateAvailableDialog::Ignored:\n ignoredVersions.append(updateVersion);\n options().setIgnoredUpdateVersions(ignoredVersions);\n break;\n }\n }\n else\n {\n if (pURLDownloader && pURLDownloader->manuallyInvoked())\n {\n \/\/ WA_DeleteOnClose\n QMessageBox* pMsg = new QMessageBox(\n safeMessageBoxIcon(QMessageBox::Information),\n QString::fromUtf8(\"No Update Available\"),\n QString::fromUtf8(\"You're using the newest version of RStudio.\"),\n QMessageBox::NoButton,\n pOwnerWindow_,\n Qt::Sheet | Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);\n pMsg->setWindowModality(Qt::WindowModal);\n pMsg->setAttribute(Qt::WA_DeleteOnClose);\n pMsg->addButton(new QPushButton(QString::fromUtf8(\"OK\")), QMessageBox::AcceptRole);\n pMsg->show();\n }\n }\n}\n\n\n} \/\/ namespace desktop\n<|endoftext|>"} {"text":"\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n\n#include \"base\/fscapi.h\"\n\n#if FUN_TRANSPORT_AGENT == FUN_MAC_TRANSPORT_AGENT\n\n#include \n#include \n#if defined(FUN_IPHONE)\n#include \n#include \n#if TARGET_IPHONE_SIMULATOR\n#include \n#else\n#include \n#endif\n#else\n#include \n#endif\n\n#include \"http\/MacTransportAgent.h\"\n#include \"http\/constants.h\"\n\n#include \"base\/util\/utils.h\"\n#include \"base\/util\/StringBuffer.h\"\n\n\nUSE_NAMESPACE\n\nMacTransportAgent::MacTransportAgent() : TransportAgent() {}\n\nMacTransportAgent::~MacTransportAgent() {}\n\n\/*\n * Constructor.\n * In this implementation newProxy is ignored, since proxy configuration\n * is taken from the WinInet subsystem.\n *\n * @param url the url where messages will be sent with sendMessage()\n * @param proxy proxy information or NULL if no proxy should be used\n *\/\nMacTransportAgent::MacTransportAgent(URL& newURL, Proxy& newProxy, unsigned int maxResponseTimeout)\n: TransportAgent(newURL, newProxy, maxResponseTimeout)\n{}\n \n\n\/*\n * Sends the given SyncML message to the server specified\n * by the instal property 'url'. Returns the response status code or -1\n * if it was not possible initialize the connection.\n *\n * Use getResponse() to get the server response.\n *\/\nchar* MacTransportAgent::sendMessage(const char* msg){\n LOG.debug(\"MacTransportAgent::sendMessage begin\");\n if(!msg) {\n LOG.error(\"MacTransportAgent::sendMessage error: NULL message.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: NULL message.\");\n return NULL;\n }\n \n bool gotflags = true;\n bool isReachable = true;\n bool noConnectionRequired = true; \n \n StringBuffer result;\n CFIndex bytesRead = 1;\n int statusCode = -1;\n\n#if defined(FUN_IPHONE) \n SCNetworkReachabilityFlags flags;\n SCNetworkReachabilityRef scnReachRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, url.host);\n \n gotflags = SCNetworkReachabilityGetFlags(scnReachRef, &flags);\n isReachable = flags & kSCNetworkReachabilityFlagsReachable;\n noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);\n if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {\n noConnectionRequired = true;\n }\n CFRelease(scnReachRef);\n#endif\n \n\n if ( gotflags && isReachable && noConnectionRequired ){\n char* ret=0;\n \/\/ size_t size = strlen(msg);\n LOG.debug(\"Requesting resource %s at %s:%d\", url.resource, url.host, url.port);\n \n LOG.debug(\"Sending HTTP Request: %s\", msg);\n \n \/\/ Construct some headers\n CFStringRef headerFieldName = CFSTR(\"Content-Type\");\n CFStringRef headerFieldValue = CFSTR(\"application\/vnd.syncml+xml\");\n \n \/\/ Construct URL\n CFStringRef CFurl = CFStringCreateWithCString(NULL, url.fullURL, kCFStringEncodingUTF8);\n CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFurl, NULL);\n \n CFStringRef requestMethod = CFSTR(\"POST\");\n \n CFHTTPMessageRef httpRequest =\n CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);\n CFStringRef useragent = CFStringCreateWithCString(NULL, getUserAgent(), kCFStringEncodingUTF8);\n CFHTTPMessageSetHeaderFieldValue(httpRequest, CFSTR(\"user-agent\"), useragent);\n if(!httpRequest){\n LOG.error(\"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n \n goto finally;\n }\n \n \n CFDataRef bodyData = CFDataCreate(kCFAllocatorDefault, (const UInt8*)msg, strlen(msg));\t\n if (!bodyData){\n LOG.error(\"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n goto finally;\n } \n CFHTTPMessageSetBody(httpRequest, bodyData);\n CFHTTPMessageSetHeaderFieldValue(httpRequest, headerFieldName, headerFieldValue);\n \n CFReadStreamRef responseStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, httpRequest);\n \n bool setProperty;\n \/\/if we are trying to sync on a https server we have to have a trusted certificate.\n \/\/no self signed certificates are accepted\n if(strcmp(url.protocol, \"https\")==0){\n NSDictionary *sslProperties;\n sslProperties = [NSDictionary dictionaryWithObjectsAndKeys:\n (NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,\n kCFBooleanFalse, kCFStreamSSLAllowsAnyRoot,\n kCFBooleanTrue, kCFStreamSSLValidatesCertificateChain,\n kCFNull, kCFStreamSSLPeerName,\n nil];\n\n setProperty = CFReadStreamSetProperty( responseStream, \n kCFStreamPropertySSLSettings, \n sslProperties );\n [sslProperties release];\n }\n \n if (!CFReadStreamOpen(responseStream)) {\/\/Sends request\n LOG.error(\"Failed to send HTTP request...\");\n }\n \n\n \n#define READ_SIZE 1000\n \n UInt8 buffer[READ_SIZE];\n while ( (bytesRead = CFReadStreamRead(responseStream, buffer, READ_SIZE-1)) > 0)\n {\n \/\/ Convert what was read to a C-string\n buffer[bytesRead] = 0;\n \/\/ Append it to the reply string\n result.append((const char*)buffer);\n }\n \n \n CFHTTPMessageRef reply = (CFHTTPMessageRef) CFReadStreamCopyProperty( responseStream, kCFStreamPropertyHTTPResponseHeader);\n \n \n \/\/ Pull the status code from the headers\n if (reply) {\n statusCode = CFHTTPMessageGetResponseStatusCode(reply);\n CFRelease(reply);\n }\n \n \n LOG.debug(\"Status Code: %d\", statusCode);\n LOG.debug(\"Result: %s\", result.c_str());\n \n\n \n switch (statusCode) {\n case 0: {\n LOG.debug(\"Http request successful.\");\n \n \/\/ No errors, copy the response\n \/\/ TODO: avoid byte copy\n ret = stringdup(result.c_str());\n \n break;\n }\n case 200: {\n LOG.debug(\"Http request successful.\");\n \n \/\/ No errors, copy the response\n \/\/ TODO: avoid byte copy\n ret = stringdup(result.c_str());\n \n break;\n }\n case -1: { \/\/ no connection (TODO: implement retry)\n setErrorF(ERR_SERVER_ERROR, \"Network error in server receiving data. \");\n LOG.error(\"%s\", getLastErrorMsg());\n \n break;\n }\n case 400: { \/\/ 400 bad request error. TODO: retry to send the message\n setErrorF(ERR_SERVER_ERROR, \"HTTP server error: %d. Server failure.\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n \n break;\n }\n case 500: { \/\/ 500 -> out code 2052\n setErrorF(ERR_SERVER_ERROR, \"HTTP server error: %d. Server failure.\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n case 404: { \/\/ 404 -> out code 2060\n setErrorF(ERR_HTTP_NOT_FOUND, \"HTTP request error: resource not found (status %d)\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n case 408: { \/\/ 408 -> out code 2061\n setErrorF(ERR_HTTP_REQUEST_TIMEOUT, \"HTTP request error: server timed out waiting for request (status %d)\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n \n default: {\n setErrorF(statusCode, \"HTTP request error: status received = %d\", statusCode);\n LOG.error(\"%s\", getLastErrorMsg());\n }\n }\n \n finally:\n CFRelease(headerFieldName);\n CFRelease(headerFieldValue);\n CFRelease(CFurl);\n CFRelease(myURL);\n CFRelease(httpRequest);\n CFRelease(bodyData);\n CFRelease(responseStream);\n CFRelease(requestMethod);\n CFRelease(useragent);\n\n LOG.debug(\"MacTransportAgent::sendMessage end\"); \n return ret;\n }else{\n setErrorF(ERR_CONNECT, \"Network error: the attempt to connect to the server failed -> exit\");\n LOG.debug(\"%s\", getLastErrorMsg());\n LOG.debug(\"MacTransportAgent::sendMessage end\");\n return NULL;\n }\n}\n\n#endif\n\ncorrected ssl support\/*\n * Funambol is a mobile platform developed by Funambol, Inc. \n * Copyright (C) 2003 - 2007 Funambol, Inc.\n * \n * This program is free software; you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License version 3 as published by\n * the Free Software Foundation with the addition of the following permission \n * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED\n * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE \n * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.\n * \n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n * details.\n * \n * You should have received a copy of the GNU Affero General Public License \n * along with this program; if not, see http:\/\/www.gnu.org\/licenses or write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n * MA 02110-1301 USA.\n * \n * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite \n * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.\n * \n * The interactive user interfaces in modified source and object code versions\n * of this program must display Appropriate Legal Notices, as required under\n * Section 5 of the GNU Affero General Public License version 3.\n * \n * In accordance with Section 7(b) of the GNU Affero General Public License\n * version 3, these Appropriate Legal Notices must retain the display of the\n * \"Powered by Funambol\" logo. If the display of the logo is not reasonably \n * feasible for technical reasons, the Appropriate Legal Notices must display\n * the words \"Powered by Funambol\".\n *\/\n\n\n#include \"base\/fscapi.h\"\n\n#if FUN_TRANSPORT_AGENT == FUN_MAC_TRANSPORT_AGENT\n\n#include \n#include \n#if defined(FUN_IPHONE)\n#include \n#include \n#if TARGET_IPHONE_SIMULATOR\n#include \n#else\n#include \n#endif\n#else\n#include \n#endif\n\n#include \"http\/MacTransportAgent.h\"\n#include \"http\/constants.h\"\n\n#include \"base\/util\/utils.h\"\n#include \"base\/util\/StringBuffer.h\"\n\n\nUSE_NAMESPACE\n\nMacTransportAgent::MacTransportAgent() : TransportAgent() {}\n\nMacTransportAgent::~MacTransportAgent() {}\n\n\/*\n * Constructor.\n * In this implementation newProxy is ignored, since proxy configuration\n * is taken from the WinInet subsystem.\n *\n * @param url the url where messages will be sent with sendMessage()\n * @param proxy proxy information or NULL if no proxy should be used\n *\/\nMacTransportAgent::MacTransportAgent(URL& newURL, Proxy& newProxy, unsigned int maxResponseTimeout)\n: TransportAgent(newURL, newProxy, maxResponseTimeout)\n{}\n \n\n\/*\n * Sends the given SyncML message to the server specified\n * by the instal property 'url'. Returns the response status code or -1\n * if it was not possible initialize the connection.\n *\n * Use getResponse() to get the server response.\n *\/\nchar* MacTransportAgent::sendMessage(const char* msg){\n LOG.debug(\"MacTransportAgent::sendMessage begin\");\n if(!msg) {\n LOG.error(\"MacTransportAgent::sendMessage error: NULL message.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: NULL message.\");\n return NULL;\n }\n \n bool gotflags = true;\n bool isReachable = true;\n bool noConnectionRequired = true; \n \n StringBuffer result;\n CFIndex bytesRead = 1;\n int statusCode = -1;\n\n#if defined(FUN_IPHONE) \n SCNetworkReachabilityFlags flags;\n SCNetworkReachabilityRef scnReachRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, url.host);\n \n gotflags = SCNetworkReachabilityGetFlags(scnReachRef, &flags);\n isReachable = flags & kSCNetworkReachabilityFlagsReachable;\n noConnectionRequired = !(flags & kSCNetworkReachabilityFlagsConnectionRequired);\n if ((flags & kSCNetworkReachabilityFlagsIsWWAN)) {\n noConnectionRequired = true;\n }\n CFRelease(scnReachRef);\n#endif\n \n\n if ( gotflags && isReachable && noConnectionRequired ){\n char* ret=0;\n \/\/ size_t size = strlen(msg);\n LOG.debug(\"Requesting resource %s at %s:%d\", url.resource, url.host, url.port);\n \n LOG.debug(\"Sending HTTP Request: %s\", msg);\n \n \/\/ Construct some headers\n CFStringRef headerFieldName = CFSTR(\"Content-Type\");\n CFStringRef headerFieldValue = CFSTR(\"application\/vnd.syncml+xml\");\n \n \/\/ Construct URL\n CFStringRef CFurl = CFStringCreateWithCString(NULL, url.fullURL, kCFStringEncodingUTF8);\n CFURLRef myURL = CFURLCreateWithString(kCFAllocatorDefault, CFurl, NULL);\n \n CFStringRef requestMethod = CFSTR(\"POST\");\n \n CFHTTPMessageRef httpRequest =\n CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, myURL, kCFHTTPVersion1_1);\n CFStringRef useragent = CFStringCreateWithCString(NULL, getUserAgent(), kCFStringEncodingUTF8);\n CFHTTPMessageSetHeaderFieldValue(httpRequest, CFSTR(\"user-agent\"), useragent);\n if(!httpRequest){\n LOG.error(\"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n \n goto finally;\n }\n \n \n CFDataRef bodyData = CFDataCreate(kCFAllocatorDefault, (const UInt8*)msg, strlen(msg));\t\n if (!bodyData){\n LOG.error(\"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n setError(ERR_NETWORK_INIT, \"MacTransportAgent::sendMessage error: CFHTTPMessageCreateRequest Error.\");\n goto finally;\n } \n CFHTTPMessageSetBody(httpRequest, bodyData);\n CFHTTPMessageSetHeaderFieldValue(httpRequest, headerFieldName, headerFieldValue);\n \n CFReadStreamRef responseStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, httpRequest);\n \n \/\/bool setProperty;\n \/\/if we are trying to sync on a https server we have to have a trusted certificate.\n \/\/no self signed certificates are accepted\n \/*if(strcmp(url.protocol, \"https\")==0){\n NSDictionary *sslProperties;\n sslProperties = [NSDictionary dictionaryWithObjectsAndKeys:\n (NSString *)kCFStreamSocketSecurityLevelNegotiatedSSL, kCFStreamSSLLevel,\n kCFBooleanFalse, kCFStreamSSLAllowsAnyRoot,\n kCFBooleanTrue, kCFStreamSSLValidatesCertificateChain,\n kCFNull, kCFStreamSSLPeerName,\n nil];\n\n setProperty = CFReadStreamSetProperty( responseStream, \n kCFStreamPropertySSLSettings, \n sslProperties );\n [sslProperties release];\n }*\/\n \n if (!CFReadStreamOpen(responseStream)) {\/\/Sends request\n LOG.error(\"Failed to send HTTP request...\");\n }\n \n\n \n#define READ_SIZE 1000\n \n UInt8 buffer[READ_SIZE];\n while ( (bytesRead = CFReadStreamRead(responseStream, buffer, READ_SIZE-1)) > 0)\n {\n \/\/ Convert what was read to a C-string\n buffer[bytesRead] = 0;\n \/\/ Append it to the reply string\n result.append((const char*)buffer);\n }\n \n \n CFHTTPMessageRef reply = (CFHTTPMessageRef) CFReadStreamCopyProperty( responseStream, kCFStreamPropertyHTTPResponseHeader);\n \n \n \/\/ Pull the status code from the headers\n if (reply) {\n statusCode = CFHTTPMessageGetResponseStatusCode(reply);\n CFRelease(reply);\n }\n \n \n LOG.debug(\"Status Code: %d\", statusCode);\n LOG.debug(\"Result: %s\", result.c_str());\n \n\n \n switch (statusCode) {\n case 0: {\n LOG.debug(\"Http request successful.\");\n \n \/\/ No errors, copy the response\n \/\/ TODO: avoid byte copy\n ret = stringdup(result.c_str());\n \n break;\n }\n case 200: {\n LOG.debug(\"Http request successful.\");\n \n \/\/ No errors, copy the response\n \/\/ TODO: avoid byte copy\n ret = stringdup(result.c_str());\n \n break;\n }\n case -1: { \/\/ no connection (TODO: implement retry)\n setErrorF(ERR_SERVER_ERROR, \"Network error in server receiving data. \");\n LOG.error(\"%s\", getLastErrorMsg());\n \n break;\n }\n case 400: { \/\/ 400 bad request error. TODO: retry to send the message\n setErrorF(ERR_SERVER_ERROR, \"HTTP server error: %d. Server failure.\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n \n break;\n }\n case 500: { \/\/ 500 -> out code 2052\n setErrorF(ERR_SERVER_ERROR, \"HTTP server error: %d. Server failure.\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n case 404: { \/\/ 404 -> out code 2060\n setErrorF(ERR_HTTP_NOT_FOUND, \"HTTP request error: resource not found (status %d)\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n case 408: { \/\/ 408 -> out code 2061\n setErrorF(ERR_HTTP_REQUEST_TIMEOUT, \"HTTP request error: server timed out waiting for request (status %d)\", statusCode);\n LOG.debug(\"%s\", getLastErrorMsg());\n break;\n }\n \n default: {\n setErrorF(statusCode, \"HTTP request error: status received = %d\", statusCode);\n LOG.error(\"%s\", getLastErrorMsg());\n }\n }\n \n finally:\n CFRelease(headerFieldName);\n CFRelease(headerFieldValue);\n CFRelease(CFurl);\n CFRelease(myURL);\n CFRelease(httpRequest);\n CFRelease(bodyData);\n CFRelease(responseStream);\n CFRelease(requestMethod);\n CFRelease(useragent);\n\n LOG.debug(\"MacTransportAgent::sendMessage end\"); \n return ret;\n }else{\n setErrorF(ERR_CONNECT, \"Network error: the attempt to connect to the server failed -> exit\");\n LOG.debug(\"%s\", getLastErrorMsg());\n LOG.debug(\"MacTransportAgent::sendMessage end\");\n return NULL;\n }\n}\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/#define TWO_CAM\n\/\/#define DISPLAY\n#define DEBUG_NO_SENSORS\n\n#include \n#include \"CameraLogger.h\"\n#include \"GPSLogger.h\"\n\n#define ZMQ_CAMERALOGGER_BIND_PORT 5001 \/\/ this app will listen on this port\n#define ZMQ_DIAGNOSTICS_SEND_PORT 5000 \/\/ this app will send to master on this port\n\n#define CAMERA_DISPLAY_SKIP 3\n#define NUMTHREAD_PER_BUFFER 10\n\nSyncBuffer cam1_buff[NUMTHREAD_PER_BUFFER];\nSyncBuffer cam2_buff[NUMTHREAD_PER_BUFFER];\n\nzmq::context_t context(1);\nzmq::socket_t my_commands(context, ZMQ_SUB);\nzmq::socket_t send_diagnostics(context, ZMQ_PUB);\n\nbool is_done_working = false; \nbool quit_via_user_input = false;\n\nTime currentTime(boost::posix_time::microsec_clock::local_time());\nTime lastTime(currentTime);\n\ninline void ImageCallback(Image* pImage, const void* pCallbackData, \n SyncBuffer* w_buff) { \n if (!is_done_working) {\n Image* im = new Image();\n pImage->Convert(PIXEL_FORMAT_BGR, im);\n if (!w_buff->getBuffer()->pushBack(im)) {\n boost::mutex::scoped_lock io_lock ( *(w_buff->getMutex()) );\n cerr << \"Warning! Buffer full, overwriting data!\" << endl; \n }\n }\n}\n\ninline void sendDiagnosticsMessage(string message) { \n zmq::message_t diag_msg_t((void *) message.c_str(), message.length(), NULL);\n send_diagnostics.send(diag_msg_t, ZMQ_NOBLOCK);\n}\n\nvoid ctrlC (int)\n{\n#ifndef DISPLAY\n \/\/printf(\"\\nCtrl-C detected, exit condition set to true.\\n\");\n \/\/is_done_working = true;\n#endif\n#ifdef DISPLAY\n printf(\"\\nCtrl-C Disabled! Use 'q' to quit instead\\n\");\n#endif\n}\n\nint main(int argc, char** argv)\n{\n using namespace boost::program_options;\n options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"serial,s\", value(), \"the serial location for the gps unit\")\n (\"maxframes,m\", value(), \"maximum number of frames to capture\")\n (\"output,o\", value(), \"the filename for data logging\");\n\n signal (SIGINT, ctrlC);\n\n string diagnostics_address = \"tcp:\/\/localhost:\"+boost::to_string(ZMQ_DIAGNOSTICS_SEND_PORT);\n send_diagnostics.connect(diagnostics_address.c_str());\n sleep(1);\n sendDiagnosticsMessage(\"WARN:Connecting to Cameras...\");\n\n\n variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n notify(vm);\n if (vm.count(\"help\")) { \n cout << desc << endl;\n return 1;\n }\n string fname1 = \"\";\n string fname2 = \"\";\n string fnamegps = \"\";\n if (vm.count(\"output\")) { \n fname1 = vm[\"output\"].as() + \"1.avi\";\n fname2 = vm[\"output\"].as() + \"2.avi\";\n fnamegps = vm[\"output\"].as() + \"_gps.out\";\n }\n else {\n cout << desc << endl;\n return 1;\n };\n\n uint64_t maxframes = -1; \n if (vm.count(\"maxframes\")) {\n maxframes = vm[\"maxframes\"].as(); \n }\n\n#ifdef DEBUG_NO_SENSORS\n bool useGPS = false;\n#else\n bool useGPS = true; \n#endif\n GPSLogger gpsLogger;\n ofstream gps_output;\n if (useGPS) {\n gps_output.open(fnamegps.c_str());\n gpsLogger.Connect(vm[\"serial\"].as());\n }\n int imageWidth = 1280;\n int imageHeight = 960;\n\n cout << \"Capturing for maximum of \" << maxframes << \" frames\" << endl; \n cout << \"Filenames: \" << fname1 << \" \" << fname2 << endl; \n\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++)\n {\n cam1_buff[thread_num].getBuffer()->setCapacity(1000);\n cam2_buff[thread_num].getBuffer()->setCapacity(1000);\n }\n\n#ifndef DEBUG_NO_SENSORS\n Camera* cam1 = ConnectCamera(0); \/\/ 0 indexing\n assert(cam1 != NULL);\n RunCamera(cam1);\n\n Consumer* cam1_consumer[NUMTHREAD_PER_BUFFER];\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n stringstream sstm;\n sstm << \"split_\" << thread_num << \"_\" << fname1; \n string thread_fname = sstm.str();\n cam1_consumer[thread_num] = new Consumer(\n cam1_buff[thread_num].getBuffer(),\n thread_fname, cam1_buff[thread_num].getMutex(), 50.0f,\n imageWidth, imageHeight);\n }\n#endif\n\n#ifdef DISPLAY\n cvNamedWindow(\"cam1\", CV_WINDOW_AUTOSIZE);\n#endif\n\n#ifdef TWO_CAM\n Camera* cam2 = ConnectCamera(1); \/\/ 0 indexing \n assert(cam2 != NULL);\n RunCamera(cam2); \n Consumer* cam2_consumer[NUMTHREAD_PER_BUFFER];\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n stringstream sstm;\n sstm << \"split_\" << thread_num << \"_\" << fname2; \n string thread_fname = sstm.str();\n cam2_consumer[thread_num] = new Consumer(\n cam2_buff[thread_num].getBuffer(),\n thread_fname, cam2_buff[thread_num].getMutex(), 50.0f,\n imageWidth, imageHeight);\n }\n#ifdef DISPLAY\n cvNamedWindow(\"cam2\", CV_WINDOW_AUTOSIZE);\n#endif \/\/DISPLAY\n#endif \/\/TWO_CAM\n\n IplImage* img = cvCreateImage(cvSize(imageWidth, imageHeight), IPL_DEPTH_8U, 3);\n string lastValidGPSPacket;\n\n \/\/\/\/ setup ZMQ communication\n string bind_address = \"tcp:\/\/*:\"+boost::to_string(ZMQ_CAMERALOGGER_BIND_PORT);\n cout << \"binding to \" << bind_address << endl; \n my_commands.bind(\"tcp:\/\/*:5001\");\n my_commands.setsockopt(ZMQ_SUBSCRIBE, NULL, 0);\n cout << \"binding successful\" << endl; \n \n#ifdef DEBUG_NO_SENSORS\n img = cvLoadImage(\"\/home\/smart\/sail-car-log\/cameralogger\/xkcd.png\");\n lastValidGPSPacket=\"#MARK1PVAA,USB1,0,92.0,EXACT,1753,238273.050,00000000,0000,470;1753,238273.050000025,37.856359728,-122.494864165,110.390118713,16.041177523,-24.789919285,-1.752024973,-3.954175540,4.393638450,32.292000751,INS_SOLUTION_GOOD*016857cc\";\n#endif\n \n \/\/ start GPS Trigger\n if (useGPS) gpsLogger.Run();\n \n uint64_t numframes = 0;\n uint64_t lastframes = 0; \n \/\/\/\/\/\/\/\/\/ main loop\n while (!is_done_working) {\n numframes++;\n if (numframes > maxframes) { \n is_done_working = true;\n }\n try {\n zmq::message_t command_msg; \n if (my_commands.recv(&command_msg, ZMQ_NOBLOCK) == true) { \n string command((const char*)command_msg.data(), command_msg.size());\n if (command.compare(\"TERMINATE\") == 0) {\n \/\/ properly close the application \n is_done_working = true; \n quit_via_user_input = true;\n } \n else if (command.compare(\"LASTCAMERADATA\") == 0) { \n \/\/ transmit the camera data over\n }\n else if (command.compare(\"LASTGPSDATA\") == 0) { \n \/\/ transmit the last known GPS log over\n }\n }\n } catch (const zmq::error_t&e) {}\n\n#ifndef DEBUG_NO_SENSORS\n Image image; \n cam1->RetrieveBuffer(&image);\n ImageCallback(&image, NULL, &cam1_buff[numframes % NUMTHREAD_PER_BUFFER]);\n\n Image cimage; \n if (numframes % CAMERA_DISPLAY_SKIP == 0) {\n image.Convert(PIXEL_FORMAT_BGR, &cimage);\n convertToCV(&cimage, img); \n #ifdef DISPLAY\n show(img, \"cam1\");\n #endif \/\/DISPLAY\n }\n#endif \/\/DEBUG_NO_SENSORS\n\n#ifdef TWO_CAM\n cam2->RetrieveBuffer(&image);\n ImageCallback(&image, NULL, &cam2_buff[numframes % NUMTHREAD_PER_BUFFER]);\n if (numframes % CAMERA_DISPLAY_SKIP == 0) {\n image.Convert(PIXEL_FORMAT_BGR, &cimage);\n convertToCV(&cimage, img); \n #ifdef DISPLAY\n show(img, \"cam2\");\n #endif \/\/DISPLAY\n }\n#endif \/\/ TWO_CAM\n\n#ifdef DISPLAY\n char r = cvWaitKey(1);\n if (r == 'q') {\n is_done_working = true;\n quit_via_user_input = true;\n }\n#endif \/\/DISPLAY\n\n if (useGPS) {\n GPSLogger::GPSPacketType packet = gpsLogger.getPacket();\n int GPSPacketSuccess = boost::get<0>(packet); \n if (GPSPacketSuccess > 0) { \n lastValidGPSPacket = boost::get<1>(packet);\n gps_output << lastValidGPSPacket << endl;\n } else {\n sendDiagnosticsMessage(\"WARN:Bad GPS Packet\"); \n }\n\n }\n\n currentTime = Time(boost::posix_time::microsec_clock::local_time()); \n if ((currentTime - lastTime).total_milliseconds() > 1000) {\n string captureRateMsg = \"INFOCAPTURERATE:\" + boost::to_string(numframes-lastframes); \n sendDiagnosticsMessage(captureRateMsg);\n\n int queue_size = 0; \n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++)\n {\n queue_size += cam1_buff[thread_num].getBuffer()->getSize();\n queue_size += cam2_buff[thread_num].getBuffer()->getSize(); \n }\n\n string bufferSizeMsg = \"INFOBUFFERSIZE:\" + boost::to_string(queue_size);\n sendDiagnosticsMessage(bufferSizeMsg);\n\n \/\/ encode last image for transmission\n Mat lastCameraImage(img);\n vector lastCameraImageBuf; string lastCameraImageMsg; \n resize(lastCameraImage, lastCameraImage, Size(320,240));\n imencode(\".png\", lastCameraImage, lastCameraImageBuf);\n lastCameraImageMsg = string(lastCameraImageBuf.begin(), lastCameraImageBuf.end());\n lastCameraImageMsg = \"CAM:\" + lastCameraImageMsg; \n sendDiagnosticsMessage(lastCameraImageMsg);\n\n GPSRecord record(lastValidGPSPacket);\n if (record.isValid()) {\n std::ostringstream lat;\n lat << std::fixed << std::setprecision(8);\n lat << record.latitude; \n std::ostringstream lon;\n lon << std::fixed << std::setprecision(8);\n lon << record.longitude;\n string gpsMsg = \"GPS:\" + lat.str() + \",\" + lon.str();\n sendDiagnosticsMessage(gpsMsg);\n }\n\n\n lastTime = currentTime;\n lastframes = numframes; \n }\n#ifdef DEBUG_NO_SENSORS\n usleep(200); \n#endif\n } \n cout << \"numframes = \" << numframes << endl;\n\n\n \/\/\/\/\/\/\/ cleanup\n if (useGPS) gpsLogger.Close();\n#ifdef DISPLAY\n cvDestroyWindow(\"cam1\");\n cvDestroyWindow(\"cam2\");\n#endif\n#ifndef DEBUG_NO_SENSORS\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n cam1_consumer[thread_num]->stop();\n delete cam1_consumer[thread_num];\n }\n CloseCamera(cam1);\n delete cam1; \n#endif \n#ifdef TWO_CAM\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n cam2_consumer[thread_num]->stop();\n delete cam2_consumer[thread_num];\n }\n CloseCamera(cam2);\n delete cam2;\n#endif\n if (quit_via_user_input) return 1;\n return 0;\n}\nmore warnings\/\/#define TWO_CAM\n\/\/#define DISPLAY\n#define DEBUG_NO_SENSORS\n\n#include \n#include \"CameraLogger.h\"\n#include \"GPSLogger.h\"\n\n#define ZMQ_CAMERALOGGER_BIND_PORT 5001 \/\/ this app will listen on this port\n#define ZMQ_DIAGNOSTICS_SEND_PORT 5000 \/\/ this app will send to master on this port\n\n#define CAMERA_DISPLAY_SKIP 3\n#define NUMTHREAD_PER_BUFFER 10\n\nSyncBuffer cam1_buff[NUMTHREAD_PER_BUFFER];\nSyncBuffer cam2_buff[NUMTHREAD_PER_BUFFER];\n\nzmq::context_t context(1);\nzmq::socket_t my_commands(context, ZMQ_SUB);\nzmq::socket_t send_diagnostics(context, ZMQ_PUB);\n\nbool is_done_working = false; \nbool quit_via_user_input = false;\n\nTime currentTime(boost::posix_time::microsec_clock::local_time());\nTime lastTime(currentTime);\n\ninline void ImageCallback(Image* pImage, const void* pCallbackData, \n SyncBuffer* w_buff) { \n if (!is_done_working) {\n Image* im = new Image();\n pImage->Convert(PIXEL_FORMAT_BGR, im);\n if (!w_buff->getBuffer()->pushBack(im)) {\n boost::mutex::scoped_lock io_lock ( *(w_buff->getMutex()) );\n cerr << \"Warning! Buffer full, overwriting data!\" << endl; \n }\n }\n}\n\ninline void sendDiagnosticsMessage(string message) { \n zmq::message_t diag_msg_t((void *) message.c_str(), message.length(), NULL);\n send_diagnostics.send(diag_msg_t, ZMQ_NOBLOCK);\n}\n\nvoid ctrlC (int)\n{\n#ifndef DISPLAY\n \/\/printf(\"\\nCtrl-C detected, exit condition set to true.\\n\");\n \/\/is_done_working = true;\n#endif\n#ifdef DISPLAY\n printf(\"\\nCtrl-C Disabled! Use 'q' to quit instead\\n\");\n#endif\n}\n\nint main(int argc, char** argv)\n{\n using namespace boost::program_options;\n options_description desc(\"Allowed options\");\n desc.add_options()\n (\"help\", \"produce help message\")\n (\"serial,s\", value(), \"the serial location for the gps unit\")\n (\"maxframes,m\", value(), \"maximum number of frames to capture\")\n (\"output,o\", value(), \"the filename for data logging\");\n\n signal (SIGINT, ctrlC);\n\n string diagnostics_address = \"tcp:\/\/localhost:\"+boost::to_string(ZMQ_DIAGNOSTICS_SEND_PORT);\n send_diagnostics.connect(diagnostics_address.c_str());\n sleep(1);\n sendDiagnosticsMessage(\"WARN:Connecting to Cameras...\");\n\n\n variables_map vm;\n store(parse_command_line(argc, argv, desc), vm);\n notify(vm);\n if (vm.count(\"help\")) { \n cout << desc << endl;\n return 1;\n }\n string fname1 = \"\";\n string fname2 = \"\";\n string fnamegps = \"\";\n if (vm.count(\"output\")) { \n fname1 = vm[\"output\"].as() + \"1.avi\";\n fname2 = vm[\"output\"].as() + \"2.avi\";\n fnamegps = vm[\"output\"].as() + \"_gps.out\";\n }\n else {\n cout << desc << endl;\n return 1;\n };\n\n uint64_t maxframes = -1; \n if (vm.count(\"maxframes\")) {\n maxframes = vm[\"maxframes\"].as(); \n }\n\n#ifdef DEBUG_NO_SENSORS\n bool useGPS = false;\n#else\n bool useGPS = true; \n#endif\n GPSLogger gpsLogger;\n ofstream gps_output;\n if (useGPS) {\n gps_output.open(fnamegps.c_str());\n gpsLogger.Connect(vm[\"serial\"].as());\n }\n int imageWidth = 1280;\n int imageHeight = 960;\n\n cout << \"Capturing for maximum of \" << maxframes << \" frames\" << endl; \n cout << \"Filenames: \" << fname1 << \" \" << fname2 << endl; \n\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++)\n {\n cam1_buff[thread_num].getBuffer()->setCapacity(1000);\n cam2_buff[thread_num].getBuffer()->setCapacity(1000);\n }\n\n#ifndef DEBUG_NO_SENSORS\n Camera* cam1 = ConnectCamera(0); \/\/ 0 indexing\n assert(cam1 != NULL);\n RunCamera(cam1);\n\n Consumer* cam1_consumer[NUMTHREAD_PER_BUFFER];\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n stringstream sstm;\n sstm << \"split_\" << thread_num << \"_\" << fname1; \n string thread_fname = sstm.str();\n cam1_consumer[thread_num] = new Consumer(\n cam1_buff[thread_num].getBuffer(),\n thread_fname, cam1_buff[thread_num].getMutex(), 50.0f,\n imageWidth, imageHeight);\n }\n#endif\n\n#ifdef DISPLAY\n cvNamedWindow(\"cam1\", CV_WINDOW_AUTOSIZE);\n#endif\n\n#ifdef TWO_CAM\n Camera* cam2 = ConnectCamera(1); \/\/ 0 indexing \n assert(cam2 != NULL);\n RunCamera(cam2); \n Consumer* cam2_consumer[NUMTHREAD_PER_BUFFER];\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n stringstream sstm;\n sstm << \"split_\" << thread_num << \"_\" << fname2; \n string thread_fname = sstm.str();\n cam2_consumer[thread_num] = new Consumer(\n cam2_buff[thread_num].getBuffer(),\n thread_fname, cam2_buff[thread_num].getMutex(), 50.0f,\n imageWidth, imageHeight);\n }\n#ifdef DISPLAY\n cvNamedWindow(\"cam2\", CV_WINDOW_AUTOSIZE);\n#endif \/\/DISPLAY\n#endif \/\/TWO_CAM\n\n IplImage* img = cvCreateImage(cvSize(imageWidth, imageHeight), IPL_DEPTH_8U, 3);\n string lastValidGPSPacket;\n\n \/\/\/\/ setup ZMQ communication\n string bind_address = \"tcp:\/\/*:\"+boost::to_string(ZMQ_CAMERALOGGER_BIND_PORT);\n cout << \"binding to \" << bind_address << endl; \n my_commands.bind(\"tcp:\/\/*:5001\");\n my_commands.setsockopt(ZMQ_SUBSCRIBE, NULL, 0);\n cout << \"binding successful\" << endl; \n \n#ifdef DEBUG_NO_SENSORS\n img = cvLoadImage(\"\/home\/smart\/sail-car-log\/cameralogger\/xkcd.png\");\n lastValidGPSPacket=\"#MARK1PVAA,USB1,0,92.0,EXACT,1753,238273.050,00000000,0000,470;1753,238273.050000025,37.856359728,-122.494864165,110.390118713,16.041177523,-24.789919285,-1.752024973,-3.954175540,4.393638450,32.292000751,INS_SOLUTION_GOOD*016857cc\";\n#endif\n \n \/\/ start GPS Trigger\n sendDiagnosticsMessage(\"WARN:Connecting to GPS...\");\n if (useGPS) gpsLogger.Run();\n \n uint64_t numframes = 0;\n uint64_t lastframes = 0; \n \/\/\/\/\/\/\/\/\/ main loop\n while (!is_done_working) {\n numframes++;\n if (numframes > maxframes) { \n is_done_working = true;\n }\n try {\n zmq::message_t command_msg; \n if (my_commands.recv(&command_msg, ZMQ_NOBLOCK) == true) { \n string command((const char*)command_msg.data(), command_msg.size());\n if (command.compare(\"TERMINATE\") == 0) {\n \/\/ properly close the application \n is_done_working = true; \n quit_via_user_input = true;\n } \n else if (command.compare(\"LASTCAMERADATA\") == 0) { \n \/\/ transmit the camera data over\n }\n else if (command.compare(\"LASTGPSDATA\") == 0) { \n \/\/ transmit the last known GPS log over\n }\n }\n } catch (const zmq::error_t&e) {}\n\n#ifndef DEBUG_NO_SENSORS\n Image image; \n cam1->RetrieveBuffer(&image);\n ImageCallback(&image, NULL, &cam1_buff[numframes % NUMTHREAD_PER_BUFFER]);\n\n Image cimage; \n if (numframes % CAMERA_DISPLAY_SKIP == 0) {\n image.Convert(PIXEL_FORMAT_BGR, &cimage);\n convertToCV(&cimage, img); \n #ifdef DISPLAY\n show(img, \"cam1\");\n #endif \/\/DISPLAY\n }\n#endif \/\/DEBUG_NO_SENSORS\n\n#ifdef TWO_CAM\n cam2->RetrieveBuffer(&image);\n ImageCallback(&image, NULL, &cam2_buff[numframes % NUMTHREAD_PER_BUFFER]);\n if (numframes % CAMERA_DISPLAY_SKIP == 0) {\n image.Convert(PIXEL_FORMAT_BGR, &cimage);\n convertToCV(&cimage, img); \n #ifdef DISPLAY\n show(img, \"cam2\");\n #endif \/\/DISPLAY\n }\n#endif \/\/ TWO_CAM\n\n#ifdef DISPLAY\n char r = cvWaitKey(1);\n if (r == 'q') {\n is_done_working = true;\n quit_via_user_input = true;\n }\n#endif \/\/DISPLAY\n\n if (useGPS) {\n GPSLogger::GPSPacketType packet = gpsLogger.getPacket();\n int GPSPacketSuccess = boost::get<0>(packet); \n if (GPSPacketSuccess > 0) { \n lastValidGPSPacket = boost::get<1>(packet);\n gps_output << lastValidGPSPacket << endl;\n } else {\n sendDiagnosticsMessage(\"WARN:Bad GPS Packet\"); \n }\n\n }\n\n currentTime = Time(boost::posix_time::microsec_clock::local_time()); \n if ((currentTime - lastTime).total_milliseconds() > 1000) {\n string captureRateMsg = \"INFOCAPTURERATE:\" + boost::to_string(numframes-lastframes); \n sendDiagnosticsMessage(captureRateMsg);\n\n int queue_size = 0; \n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++)\n {\n queue_size += cam1_buff[thread_num].getBuffer()->getSize();\n queue_size += cam2_buff[thread_num].getBuffer()->getSize(); \n }\n\n string bufferSizeMsg = \"INFOBUFFERSIZE:\" + boost::to_string(queue_size);\n sendDiagnosticsMessage(bufferSizeMsg);\n\n \/\/ encode last image for transmission\n Mat lastCameraImage(img);\n vector lastCameraImageBuf; string lastCameraImageMsg; \n resize(lastCameraImage, lastCameraImage, Size(320,240));\n imencode(\".png\", lastCameraImage, lastCameraImageBuf);\n lastCameraImageMsg = string(lastCameraImageBuf.begin(), lastCameraImageBuf.end());\n lastCameraImageMsg = \"CAM:\" + lastCameraImageMsg; \n sendDiagnosticsMessage(lastCameraImageMsg);\n\n GPSRecord record(lastValidGPSPacket);\n if (record.isValid()) {\n std::ostringstream lat;\n lat << std::fixed << std::setprecision(8);\n lat << record.latitude; \n std::ostringstream lon;\n lon << std::fixed << std::setprecision(8);\n lon << record.longitude;\n string gpsMsg = \"GPS:\" + lat.str() + \",\" + lon.str();\n sendDiagnosticsMessage(gpsMsg);\n }\n\n\n lastTime = currentTime;\n lastframes = numframes; \n }\n#ifdef DEBUG_NO_SENSORS\n usleep(200); \n#endif\n } \n cout << \"numframes = \" << numframes << endl;\n\n\n \/\/\/\/\/\/\/ cleanup\n sendDiagnosticsMessage(\"WARN:Shutting Down GPS...\");\n if (useGPS) gpsLogger.Close();\n#ifdef DISPLAY\n cvDestroyWindow(\"cam1\");\n cvDestroyWindow(\"cam2\");\n sendDiagnosticsMessage(\"WARN:Shutting Down Cameras...\");\n#endif\n#ifndef DEBUG_NO_SENSORS\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n cam1_consumer[thread_num]->stop();\n delete cam1_consumer[thread_num];\n }\n CloseCamera(cam1);\n delete cam1; \n#endif \n#ifdef TWO_CAM\n for (int thread_num = 0; thread_num < NUMTHREAD_PER_BUFFER; thread_num++) {\n cam2_consumer[thread_num]->stop();\n delete cam2_consumer[thread_num];\n }\n CloseCamera(cam2);\n delete cam2;\n#endif\n if (quit_via_user_input) return 1;\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/tools\/crash_service\/crash_service.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"breakpad\/src\/client\/windows\/crash_generation\/crash_generation_server.h\"\n#include \"breakpad\/src\/client\/windows\/sender\/crash_report_sender.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/win_util.h\"\n\n\/\/ TODO(cpu): Bug 1169078. There is a laundry list of things to do for this\n\/\/ application. They will be addressed as they are required.\n\nnamespace {\n\nconst wchar_t kTestPipeName[] = L\"\\\\\\\\.\\\\pipe\\\\ChromeCrashServices\";\n\nconst wchar_t kCrashReportURL[] = L\"https:\/\/www.google.com\/cr\/report\";\nconst wchar_t kCheckPointFile[] = L\"crash_checkpoint.txt\";\n\ntypedef std::map CrashMap;\n\nbool CustomInfoToMap(const google_breakpad::ClientInfo* client_info,\n const std::wstring& reporter_tag, CrashMap* map) {\n google_breakpad::CustomClientInfo info = client_info->GetCustomInfo();\n\n for (int i = 0; i < info.count; ++i) {\n (*map)[info.entries[i].name] = info.entries[i].value;\n }\n\n (*map)[L\"rept\"] = reporter_tag;\n\n return (map->size() > 0);\n}\n\nbool WriteCustomInfoToFile(const std::wstring& dump_path, const CrashMap& map) {\n std::wstring file_path(dump_path);\n size_t last_dot = file_path.rfind(L'.');\n if (last_dot == std::wstring::npos)\n return false;\n file_path.resize(last_dot);\n file_path += L\".txt\";\n\n std::wofstream file(file_path.c_str(),\n std::ios_base::out | std::ios_base::app | std::ios::binary);\n if (!file.is_open())\n return false;\n\n CrashMap::const_iterator pos;\n for (pos = map.begin(); pos != map.end(); ++pos) {\n std::wstring line = pos->first;\n line += L':';\n line += pos->second;\n line += L'\\n';\n file.write(line.c_str(), static_cast(line.length()));\n }\n return true;\n}\n\n\/\/ The window procedure task is to handle when a) the user logs off.\n\/\/ b) the system shuts down or c) when the user closes the window.\nLRESULT __stdcall CrashSvcWndProc(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam) {\n switch (message) {\n case WM_CLOSE:\n case WM_ENDSESSION:\n case WM_DESTROY:\n PostQuitMessage(0);\n break;\n default:\n return DefWindowProc(hwnd, message, wparam, lparam);\n }\n return 0;\n}\n\n\/\/ This is the main and only application window.\nHWND g_top_window = NULL;\n\nbool CreateTopWindow(HINSTANCE instance, bool visible) {\n WNDCLASSEXW wcx = {0};\n wcx.cbSize = sizeof(wcx);\n wcx.style = CS_HREDRAW | CS_VREDRAW;\n wcx.lpfnWndProc = CrashSvcWndProc;\n wcx.hInstance = instance;\n wcx.lpszClassName = L\"crash_svc_class\";\n ATOM atom = ::RegisterClassExW(&wcx);\n DWORD style = visible ? WS_POPUPWINDOW | WS_VISIBLE : WS_OVERLAPPED;\n\n \/\/ The window size is zero but being a popup window still shows in the\n \/\/ task bar and can be closed using the system menu or using task manager.\n HWND window = CreateWindowExW(0, wcx.lpszClassName, L\"crash service\", style,\n CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,\n NULL, NULL, instance, NULL);\n if (!window)\n return false;\n\n ::UpdateWindow(window);\n LOG(INFO) << \"window handle is \" << window;\n g_top_window = window;\n return true;\n}\n\n\/\/ Simple helper class to keep the process alive until the current request\n\/\/ finishes.\nclass ProcessingLock {\n public:\n ProcessingLock() {\n ::InterlockedIncrement(&op_count_);\n }\n ~ProcessingLock() {\n ::InterlockedDecrement(&op_count_);\n }\n static bool IsWorking() {\n return (op_count_ != 0);\n }\n private:\n static volatile LONG op_count_;\n};\n\nvolatile LONG ProcessingLock::op_count_ = 0;\n\n\/\/ This structure contains the information that the worker thread needs to\n\/\/ send a crash dump to the server.\nstruct DumpJobInfo {\n DWORD pid;\n CrashService* self;\n CrashMap map;\n std::wstring dump_path;\n\n DumpJobInfo(DWORD process_id, CrashService* service,\n const CrashMap& crash_map, const std::wstring& path)\n : pid(process_id), self(service), map(crash_map), dump_path(path) {\n }\n};\n\n} \/\/ namespace\n\n\/\/ Command line switches:\nconst wchar_t CrashService::kMaxReports[] = L\"max-reports\";\nconst wchar_t CrashService::kNoWindow[] = L\"no-window\";\nconst wchar_t CrashService::kReporterTag[]= L\"reporter\";\n\nCrashService::CrashService(const std::wstring& report_dir)\n : report_path_(report_dir),\n sender_(NULL),\n dumper_(NULL),\n requests_handled_(0),\n requests_sent_(0),\n clients_connected_(0),\n clients_terminated_(0) {\n chrome::RegisterPathProvider();\n}\n\nCrashService::~CrashService() {\n AutoLock lock(sending_);\n delete dumper_;\n delete sender_;\n}\n\nbool CrashService::Initialize(const std::wstring& command_line) {\n using google_breakpad::CrashReportSender;\n using google_breakpad::CrashGenerationServer;\n\n const wchar_t* pipe_name = kTestPipeName;\n std::wstring dumps_path;\n int max_reports = -1;\n\n \/\/ The checkpoint file allows CrashReportSender to enforce the the maximum\n \/\/ reports per day quota. Does not seem to serve any other purpose.\n std::wstring checkpoint_path = report_path_;\n file_util::AppendToPath(&checkpoint_path, kCheckPointFile);\n\n \/\/ The dumps path is typically : '\\Local settings\\\n \/\/ Application data\\Goggle\\Chrome\\Crash Reports' and the report path is\n \/\/ Application data\\Google\\Chrome\\Reported Crashes.txt\n if (!PathService::Get(chrome::DIR_USER_DATA, &report_path_)) {\n LOG(ERROR) << \"could not get DIR_USER_DATA\";\n return false;\n }\n file_util::AppendToPath(&report_path_, chrome::kCrashReportLog);\n if (!PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path)) {\n LOG(ERROR) << \"could not get DIR_CRASH_DUMPS\";\n return false;\n }\n\n CommandLine cmd_line(command_line);\n\n \/\/ We can override the send reports quota with a command line switch.\n if (cmd_line.HasSwitch(kMaxReports))\n max_reports = _wtoi(cmd_line.GetSwitchValue(kMaxReports).c_str());\n\n if (max_reports > 0) {\n \/\/ Create the http sender object.\n sender_ = new CrashReportSender(checkpoint_path);\n if (!sender_) {\n LOG(ERROR) << \"could not create sender\";\n return false;\n }\n sender_->set_max_reports_per_day(max_reports);\n }\n \/\/ Create the OOP crash generator object.\n dumper_ = new CrashGenerationServer(pipe_name, NULL,\n &CrashService::OnClientConnected, this,\n &CrashService::OnClientDumpRequest, this,\n &CrashService::OnClientExited, this,\n true, &dumps_path);\n if (!dumper_) {\n LOG(ERROR) << \"could not create dumper\";\n return false;\n }\n\n if (!CreateTopWindow(::GetModuleHandleW(NULL),\n !cmd_line.HasSwitch(kNoWindow))) {\n LOG(ERROR) << \"could not create window\";\n return false;\n }\n\n reporter_tag_ = L\"crash svc\";\n if (cmd_line.HasSwitch(kReporterTag))\n reporter_tag_ = cmd_line.GetSwitchValue(kReporterTag);\n\n \/\/ Log basic information.\n LOG(INFO) << \"pipe name is \" << pipe_name;\n LOG(INFO) << \"dumps at \" << dumps_path;\n LOG(INFO) << \"reports at \" << report_path_;\n\n if (sender_) {\n LOG(INFO) << \"checkpoint is \" << checkpoint_path;\n LOG(INFO) << \"server is \" << kCrashReportURL;\n LOG(INFO) << \"maximum \" << sender_->max_reports_per_day() << \" reports\/day\";\n LOG(INFO) << \"reporter is \" << reporter_tag_;\n }\n \/\/ Start servicing clients.\n if (!dumper_->Start()) {\n LOG(ERROR) << \"could not start dumper\";\n return false;\n }\n\n \/\/ This is throwaway code. We don't need to sync with the browser process\n \/\/ once Google Update is updated to a version supporting OOP crash handling.\n \/\/ Create or open an event to signal the browser process that the crash\n \/\/ service is initialized.\n HANDLE running_event =\n ::CreateEventW(NULL, TRUE, TRUE, L\"g_chrome_crash_svc\");\n \/\/ If the browser already had the event open, the CreateEvent call did not\n \/\/ signal it. We need to do it manually.\n ::SetEvent(running_event);\n\n return true;\n}\n\nvoid CrashService::OnClientConnected(void* context,\n const google_breakpad::ClientInfo* client_info) {\n ProcessingLock lock;\n LOG(INFO) << \"client start. pid = \" << client_info->pid();\n CrashService* self = static_cast(context);\n ::InterlockedIncrement(&self->clients_connected_);\n}\n\nvoid CrashService::OnClientExited(void* context,\n const google_breakpad::ClientInfo* client_info) {\n ProcessingLock lock;\n LOG(INFO) << \"client end. pid = \" << client_info->pid();\n CrashService* self = static_cast(context);\n ::InterlockedIncrement(&self->clients_terminated_);\n\n if (!self->sender_)\n return;\n\n \/\/ When we are instructed to send reports we need to exit if there are\n \/\/ no more clients to service. The next client that runs will start us.\n \/\/ Only chrome.exe starts crash_service with a non-zero max_reports.\n if (self->clients_connected_ > self->clients_terminated_)\n return;\n if (self->sender_->max_reports_per_day() > 0) {\n \/\/ Wait for the other thread to send crashes, if applicable. The sender\n \/\/ thread takes the sending_ lock, so the sleep is just to give it a\n \/\/ chance to start.\n ::Sleep(1000);\n AutoLock lock(self->sending_);\n \/\/ Some people can restart chrome very fast, check again if we have\n \/\/ a new client before exiting for real.\n if (self->clients_connected_ == self->clients_terminated_) {\n LOG(INFO) << \"zero clients. exiting\";\n ::PostMessage(g_top_window, WM_CLOSE, 0, 0);\n }\n }\n}\n\nvoid CrashService::OnClientDumpRequest(void* context,\n const google_breakpad::ClientInfo* client_info,\n const std::wstring* file_path) {\n ProcessingLock lock;\n\n if (!file_path) {\n LOG(ERROR) << \"dump with no file path\";\n return;\n }\n if (!client_info) {\n LOG(ERROR) << \"dump with no client info\";\n return;\n }\n\n DWORD pid = client_info->pid();\n LOG(INFO) << \"dump for pid = \" << pid << \" is \" << *file_path;\n\n CrashService* self = static_cast(context);\n if (!self) {\n LOG(ERROR) << \"dump with no context\";\n return;\n }\n\n CrashMap map;\n CustomInfoToMap(client_info, self->reporter_tag_, &map);\n\n if (!WriteCustomInfoToFile(*file_path, map)) {\n LOG(ERROR) << \"could not write custom info file\";\n }\n\n if (!self->sender_)\n return;\n\n \/\/ Send the crash dump using a worker thread. This operation has retry\n \/\/ logic in case there is no internet connection at the time.\n DumpJobInfo* dump_job = new DumpJobInfo(pid, self, map, *file_path);\n if (!::QueueUserWorkItem(&CrashService::AsyncSendDump,\n dump_job, WT_EXECUTELONGFUNCTION)) {\n LOG(ERROR) << \"could not queue job\";\n }\n}\n\n\/\/ We are going to try sending the report several times. If we can't send,\n\/\/ we sleep from one minute to several hours depending on the retry round.\nunsigned long CrashService::AsyncSendDump(void* context) {\n if (!context)\n return 0;\n\n DumpJobInfo* info = static_cast(context);\n\n std::wstring report_id = L\"\";\n\n const DWORD kOneMinute = 60*1000;\n const DWORD kOneHour = 60*kOneMinute;\n\n const DWORD kSleepSchedule[] = {\n 24*kOneHour,\n 8*kOneHour,\n 4*kOneHour,\n kOneHour,\n 15*kOneMinute,\n 0};\n\n int retry_round = arraysize(kSleepSchedule) - 1;\n\n do {\n ::Sleep(kSleepSchedule[retry_round]);\n {\n \/\/ Take the server lock while sending. This also prevent early\n \/\/ termination of the service object.\n AutoLock lock(info->self->sending_);\n LOG(INFO) << \"trying to send report for pid = \" << info->pid;\n google_breakpad::ReportResult send_result\n = info->self->sender_->SendCrashReport(kCrashReportURL, info->map,\n info->dump_path, &report_id);\n switch (send_result) {\n case google_breakpad::RESULT_FAILED:\n report_id = L\"\";\n break;\n case google_breakpad::RESULT_REJECTED:\n report_id = L\"\";\n ++info->self->requests_handled_;\n retry_round = 0;\n break;\n case google_breakpad::RESULT_SUCCEEDED:\n ++info->self->requests_sent_;\n ++info->self->requests_handled_;\n retry_round = 0;\n break;\n case google_breakpad::RESULT_THROTTLED:\n report_id = L\"\";\n break;\n default:\n report_id = L\"\";\n break;\n };\n }\n\n LOG(INFO) << \"dump for pid =\" << info->pid << \" crash2 id =\" << report_id;\n --retry_round;\n } while(retry_round >= 0);\n\n if (!::DeleteFileW(info->dump_path.c_str()))\n LOG(WARNING) << \"could not delete \" << info->dump_path;\n\n delete info;\n return 0;\n}\n\nint CrashService::ProcessingLoop() {\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n LOG(INFO) << \"session ending..\";\n while (ProcessingLock::IsWorking()) {\n ::Sleep(50);\n }\n\n LOG(INFO) << \"clients connected :\" << clients_connected_;\n LOG(INFO) << \"clients terminated :\" << clients_terminated_;\n LOG(INFO) << \"dumps serviced :\" << requests_handled_;\n LOG(INFO) << \"dumps reported :\" << requests_sent_;\n\n return static_cast(msg.wParam);\n}\n\nSwitch to the new crash service URL.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/tools\/crash_service\/crash_service.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"breakpad\/src\/client\/windows\/crash_generation\/crash_generation_server.h\"\n#include \"breakpad\/src\/client\/windows\/sender\/crash_report_sender.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/win_util.h\"\n\n\/\/ TODO(cpu): Bug 1169078. There is a laundry list of things to do for this\n\/\/ application. They will be addressed as they are required.\n\nnamespace {\n\nconst wchar_t kTestPipeName[] = L\"\\\\\\\\.\\\\pipe\\\\ChromeCrashServices\";\n\nconst wchar_t kCrashReportURL[] = L\"https:\/\/clients2.google.com\/cr\/report\";\nconst wchar_t kCheckPointFile[] = L\"crash_checkpoint.txt\";\n\ntypedef std::map CrashMap;\n\nbool CustomInfoToMap(const google_breakpad::ClientInfo* client_info,\n const std::wstring& reporter_tag, CrashMap* map) {\n google_breakpad::CustomClientInfo info = client_info->GetCustomInfo();\n\n for (int i = 0; i < info.count; ++i) {\n (*map)[info.entries[i].name] = info.entries[i].value;\n }\n\n (*map)[L\"rept\"] = reporter_tag;\n\n return (map->size() > 0);\n}\n\nbool WriteCustomInfoToFile(const std::wstring& dump_path, const CrashMap& map) {\n std::wstring file_path(dump_path);\n size_t last_dot = file_path.rfind(L'.');\n if (last_dot == std::wstring::npos)\n return false;\n file_path.resize(last_dot);\n file_path += L\".txt\";\n\n std::wofstream file(file_path.c_str(),\n std::ios_base::out | std::ios_base::app | std::ios::binary);\n if (!file.is_open())\n return false;\n\n CrashMap::const_iterator pos;\n for (pos = map.begin(); pos != map.end(); ++pos) {\n std::wstring line = pos->first;\n line += L':';\n line += pos->second;\n line += L'\\n';\n file.write(line.c_str(), static_cast(line.length()));\n }\n return true;\n}\n\n\/\/ The window procedure task is to handle when a) the user logs off.\n\/\/ b) the system shuts down or c) when the user closes the window.\nLRESULT __stdcall CrashSvcWndProc(HWND hwnd, UINT message,\n WPARAM wparam, LPARAM lparam) {\n switch (message) {\n case WM_CLOSE:\n case WM_ENDSESSION:\n case WM_DESTROY:\n PostQuitMessage(0);\n break;\n default:\n return DefWindowProc(hwnd, message, wparam, lparam);\n }\n return 0;\n}\n\n\/\/ This is the main and only application window.\nHWND g_top_window = NULL;\n\nbool CreateTopWindow(HINSTANCE instance, bool visible) {\n WNDCLASSEXW wcx = {0};\n wcx.cbSize = sizeof(wcx);\n wcx.style = CS_HREDRAW | CS_VREDRAW;\n wcx.lpfnWndProc = CrashSvcWndProc;\n wcx.hInstance = instance;\n wcx.lpszClassName = L\"crash_svc_class\";\n ATOM atom = ::RegisterClassExW(&wcx);\n DWORD style = visible ? WS_POPUPWINDOW | WS_VISIBLE : WS_OVERLAPPED;\n\n \/\/ The window size is zero but being a popup window still shows in the\n \/\/ task bar and can be closed using the system menu or using task manager.\n HWND window = CreateWindowExW(0, wcx.lpszClassName, L\"crash service\", style,\n CW_USEDEFAULT, CW_USEDEFAULT, 0, 0,\n NULL, NULL, instance, NULL);\n if (!window)\n return false;\n\n ::UpdateWindow(window);\n LOG(INFO) << \"window handle is \" << window;\n g_top_window = window;\n return true;\n}\n\n\/\/ Simple helper class to keep the process alive until the current request\n\/\/ finishes.\nclass ProcessingLock {\n public:\n ProcessingLock() {\n ::InterlockedIncrement(&op_count_);\n }\n ~ProcessingLock() {\n ::InterlockedDecrement(&op_count_);\n }\n static bool IsWorking() {\n return (op_count_ != 0);\n }\n private:\n static volatile LONG op_count_;\n};\n\nvolatile LONG ProcessingLock::op_count_ = 0;\n\n\/\/ This structure contains the information that the worker thread needs to\n\/\/ send a crash dump to the server.\nstruct DumpJobInfo {\n DWORD pid;\n CrashService* self;\n CrashMap map;\n std::wstring dump_path;\n\n DumpJobInfo(DWORD process_id, CrashService* service,\n const CrashMap& crash_map, const std::wstring& path)\n : pid(process_id), self(service), map(crash_map), dump_path(path) {\n }\n};\n\n} \/\/ namespace\n\n\/\/ Command line switches:\nconst wchar_t CrashService::kMaxReports[] = L\"max-reports\";\nconst wchar_t CrashService::kNoWindow[] = L\"no-window\";\nconst wchar_t CrashService::kReporterTag[]= L\"reporter\";\n\nCrashService::CrashService(const std::wstring& report_dir)\n : report_path_(report_dir),\n sender_(NULL),\n dumper_(NULL),\n requests_handled_(0),\n requests_sent_(0),\n clients_connected_(0),\n clients_terminated_(0) {\n chrome::RegisterPathProvider();\n}\n\nCrashService::~CrashService() {\n AutoLock lock(sending_);\n delete dumper_;\n delete sender_;\n}\n\nbool CrashService::Initialize(const std::wstring& command_line) {\n using google_breakpad::CrashReportSender;\n using google_breakpad::CrashGenerationServer;\n\n const wchar_t* pipe_name = kTestPipeName;\n std::wstring dumps_path;\n int max_reports = -1;\n\n \/\/ The checkpoint file allows CrashReportSender to enforce the the maximum\n \/\/ reports per day quota. Does not seem to serve any other purpose.\n std::wstring checkpoint_path = report_path_;\n file_util::AppendToPath(&checkpoint_path, kCheckPointFile);\n\n \/\/ The dumps path is typically : '\\Local settings\\\n \/\/ Application data\\Goggle\\Chrome\\Crash Reports' and the report path is\n \/\/ Application data\\Google\\Chrome\\Reported Crashes.txt\n if (!PathService::Get(chrome::DIR_USER_DATA, &report_path_)) {\n LOG(ERROR) << \"could not get DIR_USER_DATA\";\n return false;\n }\n file_util::AppendToPath(&report_path_, chrome::kCrashReportLog);\n if (!PathService::Get(chrome::DIR_CRASH_DUMPS, &dumps_path)) {\n LOG(ERROR) << \"could not get DIR_CRASH_DUMPS\";\n return false;\n }\n\n CommandLine cmd_line(command_line);\n\n \/\/ We can override the send reports quota with a command line switch.\n if (cmd_line.HasSwitch(kMaxReports))\n max_reports = _wtoi(cmd_line.GetSwitchValue(kMaxReports).c_str());\n\n if (max_reports > 0) {\n \/\/ Create the http sender object.\n sender_ = new CrashReportSender(checkpoint_path);\n if (!sender_) {\n LOG(ERROR) << \"could not create sender\";\n return false;\n }\n sender_->set_max_reports_per_day(max_reports);\n }\n \/\/ Create the OOP crash generator object.\n dumper_ = new CrashGenerationServer(pipe_name, NULL,\n &CrashService::OnClientConnected, this,\n &CrashService::OnClientDumpRequest, this,\n &CrashService::OnClientExited, this,\n true, &dumps_path);\n if (!dumper_) {\n LOG(ERROR) << \"could not create dumper\";\n return false;\n }\n\n if (!CreateTopWindow(::GetModuleHandleW(NULL),\n !cmd_line.HasSwitch(kNoWindow))) {\n LOG(ERROR) << \"could not create window\";\n return false;\n }\n\n reporter_tag_ = L\"crash svc\";\n if (cmd_line.HasSwitch(kReporterTag))\n reporter_tag_ = cmd_line.GetSwitchValue(kReporterTag);\n\n \/\/ Log basic information.\n LOG(INFO) << \"pipe name is \" << pipe_name;\n LOG(INFO) << \"dumps at \" << dumps_path;\n LOG(INFO) << \"reports at \" << report_path_;\n\n if (sender_) {\n LOG(INFO) << \"checkpoint is \" << checkpoint_path;\n LOG(INFO) << \"server is \" << kCrashReportURL;\n LOG(INFO) << \"maximum \" << sender_->max_reports_per_day() << \" reports\/day\";\n LOG(INFO) << \"reporter is \" << reporter_tag_;\n }\n \/\/ Start servicing clients.\n if (!dumper_->Start()) {\n LOG(ERROR) << \"could not start dumper\";\n return false;\n }\n\n \/\/ This is throwaway code. We don't need to sync with the browser process\n \/\/ once Google Update is updated to a version supporting OOP crash handling.\n \/\/ Create or open an event to signal the browser process that the crash\n \/\/ service is initialized.\n HANDLE running_event =\n ::CreateEventW(NULL, TRUE, TRUE, L\"g_chrome_crash_svc\");\n \/\/ If the browser already had the event open, the CreateEvent call did not\n \/\/ signal it. We need to do it manually.\n ::SetEvent(running_event);\n\n return true;\n}\n\nvoid CrashService::OnClientConnected(void* context,\n const google_breakpad::ClientInfo* client_info) {\n ProcessingLock lock;\n LOG(INFO) << \"client start. pid = \" << client_info->pid();\n CrashService* self = static_cast(context);\n ::InterlockedIncrement(&self->clients_connected_);\n}\n\nvoid CrashService::OnClientExited(void* context,\n const google_breakpad::ClientInfo* client_info) {\n ProcessingLock lock;\n LOG(INFO) << \"client end. pid = \" << client_info->pid();\n CrashService* self = static_cast(context);\n ::InterlockedIncrement(&self->clients_terminated_);\n\n if (!self->sender_)\n return;\n\n \/\/ When we are instructed to send reports we need to exit if there are\n \/\/ no more clients to service. The next client that runs will start us.\n \/\/ Only chrome.exe starts crash_service with a non-zero max_reports.\n if (self->clients_connected_ > self->clients_terminated_)\n return;\n if (self->sender_->max_reports_per_day() > 0) {\n \/\/ Wait for the other thread to send crashes, if applicable. The sender\n \/\/ thread takes the sending_ lock, so the sleep is just to give it a\n \/\/ chance to start.\n ::Sleep(1000);\n AutoLock lock(self->sending_);\n \/\/ Some people can restart chrome very fast, check again if we have\n \/\/ a new client before exiting for real.\n if (self->clients_connected_ == self->clients_terminated_) {\n LOG(INFO) << \"zero clients. exiting\";\n ::PostMessage(g_top_window, WM_CLOSE, 0, 0);\n }\n }\n}\n\nvoid CrashService::OnClientDumpRequest(void* context,\n const google_breakpad::ClientInfo* client_info,\n const std::wstring* file_path) {\n ProcessingLock lock;\n\n if (!file_path) {\n LOG(ERROR) << \"dump with no file path\";\n return;\n }\n if (!client_info) {\n LOG(ERROR) << \"dump with no client info\";\n return;\n }\n\n DWORD pid = client_info->pid();\n LOG(INFO) << \"dump for pid = \" << pid << \" is \" << *file_path;\n\n CrashService* self = static_cast(context);\n if (!self) {\n LOG(ERROR) << \"dump with no context\";\n return;\n }\n\n CrashMap map;\n CustomInfoToMap(client_info, self->reporter_tag_, &map);\n\n if (!WriteCustomInfoToFile(*file_path, map)) {\n LOG(ERROR) << \"could not write custom info file\";\n }\n\n if (!self->sender_)\n return;\n\n \/\/ Send the crash dump using a worker thread. This operation has retry\n \/\/ logic in case there is no internet connection at the time.\n DumpJobInfo* dump_job = new DumpJobInfo(pid, self, map, *file_path);\n if (!::QueueUserWorkItem(&CrashService::AsyncSendDump,\n dump_job, WT_EXECUTELONGFUNCTION)) {\n LOG(ERROR) << \"could not queue job\";\n }\n}\n\n\/\/ We are going to try sending the report several times. If we can't send,\n\/\/ we sleep from one minute to several hours depending on the retry round.\nunsigned long CrashService::AsyncSendDump(void* context) {\n if (!context)\n return 0;\n\n DumpJobInfo* info = static_cast(context);\n\n std::wstring report_id = L\"\";\n\n const DWORD kOneMinute = 60*1000;\n const DWORD kOneHour = 60*kOneMinute;\n\n const DWORD kSleepSchedule[] = {\n 24*kOneHour,\n 8*kOneHour,\n 4*kOneHour,\n kOneHour,\n 15*kOneMinute,\n 0};\n\n int retry_round = arraysize(kSleepSchedule) - 1;\n\n do {\n ::Sleep(kSleepSchedule[retry_round]);\n {\n \/\/ Take the server lock while sending. This also prevent early\n \/\/ termination of the service object.\n AutoLock lock(info->self->sending_);\n LOG(INFO) << \"trying to send report for pid = \" << info->pid;\n google_breakpad::ReportResult send_result\n = info->self->sender_->SendCrashReport(kCrashReportURL, info->map,\n info->dump_path, &report_id);\n switch (send_result) {\n case google_breakpad::RESULT_FAILED:\n report_id = L\"\";\n break;\n case google_breakpad::RESULT_REJECTED:\n report_id = L\"\";\n ++info->self->requests_handled_;\n retry_round = 0;\n break;\n case google_breakpad::RESULT_SUCCEEDED:\n ++info->self->requests_sent_;\n ++info->self->requests_handled_;\n retry_round = 0;\n break;\n case google_breakpad::RESULT_THROTTLED:\n report_id = L\"\";\n break;\n default:\n report_id = L\"\";\n break;\n };\n }\n\n LOG(INFO) << \"dump for pid =\" << info->pid << \" crash2 id =\" << report_id;\n --retry_round;\n } while(retry_round >= 0);\n\n if (!::DeleteFileW(info->dump_path.c_str()))\n LOG(WARNING) << \"could not delete \" << info->dump_path;\n\n delete info;\n return 0;\n}\n\nint CrashService::ProcessingLoop() {\n MSG msg;\n while (GetMessage(&msg, NULL, 0, 0)) {\n TranslateMessage(&msg);\n DispatchMessage(&msg);\n }\n\n LOG(INFO) << \"session ending..\";\n while (ProcessingLock::IsWorking()) {\n ::Sleep(50);\n }\n\n LOG(INFO) << \"clients connected :\" << clients_connected_;\n LOG(INFO) << \"clients terminated :\" << clients_terminated_;\n LOG(INFO) << \"dumps serviced :\" << requests_handled_;\n LOG(INFO) << \"dumps reported :\" << requests_sent_;\n\n return static_cast(msg.wParam);\n}\n\n<|endoftext|>"} {"text":"#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \n#include \n#include \"adapters\/joystickadapter.h\"\n\n#include \n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n configTreeModel.populateModel();\n ui->configTree->setModel(configTreeModel.model());\n mdiArea = ui->mainDisplayArea;\n connect(mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),\n this, SLOT(updateMenus()));\n windowMapper = new QSignalMapper(this);\n connect(windowMapper, SIGNAL(mapped(QWidget*)),\n this, SLOT(setActiveSubWindow(QWidget*)));\n\n ui->hardwareStatusList->addItem(\"Joystick\");\n connect(ui->hardwareStatusList, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(openHardwareView(QModelIndex)));\n\n setupMenus();\n updateWindowMenu();\n\n _joystick = new Joystick;\n}\n\nvoid MainWindow::setupMenus()\n{\n connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close()));\n connect(ui->menuWindow, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));\n connect(ui->actionClose_2, SIGNAL(triggered()), mdiArea, SLOT(closeActiveSubWindow()));\n connect(ui->actionClose_All, SIGNAL(triggered()), mdiArea, SLOT(closeAllSubWindows()));\n connect(ui->actionCascade, SIGNAL(triggered()), mdiArea, SLOT(cascadeSubWindows()));\n connect(ui->actionTile, SIGNAL(triggered()), mdiArea, SLOT(tileSubWindows()));\n}\n\nMainWindow::~MainWindow()\n{\n delete _joystick;\n delete ui;\n}\n\nvoid MainWindow::openHardwareView(QModelIndex index)\n{\n if(index.row()==0)\n {\n if(MDIWindow* window = findWindowWithTitle(\"Joystick\"))\n {\n if(!window->isVisible())\n window->show();\n }\n else\n {\n using namespace std;\n MDIWindow *newWindow = new MDIWindow;\n newWindow->setWindowTitle(\"Joystick\");\n JoystickAdapter *adapter = new JoystickAdapter(_joystick);\n newWindow->setLayout(new QGridLayout);\n newWindow->layout()->addWidget(adapter);\n mdiArea->addSubWindow(newWindow);\n newWindow->show();\n }\n }\n updateWindowMenu();\n}\n\nvoid MainWindow::on_actionFullscreen_triggered()\n{\n if(ui->actionFullscreen->isChecked())\n this->showFullScreen();\n else\n this->showNormal();\n}\n\nvoid MainWindow::updateMenus()\n{\n bool hasMdiChild = (activeMdiChild() != 0);\n\n ui->actionTile->setEnabled(hasMdiChild);\n ui->actionCascade->setEnabled(hasMdiChild);\n ui->actionClose_2->setEnabled(hasMdiChild);\n ui->actionClose_All->setEnabled(hasMdiChild);\n}\n\nvoid MainWindow::updateWindowMenu()\n{\n for(int i = ui->menuWindow->actions().size()-1; i > 5; i--)\n {\n ui->menuWindow->removeAction(ui->menuWindow->actions().at(i));\n }\n\n QList windows = mdiArea->subWindowList();\n\n for (int i = 0; i < windows.size(); ++i) {\n MDIWindow *child = qobject_cast(windows.at(i)->widget());\n\n QString text = windows.at(i)->windowTitle();\n QAction *action = ui->menuWindow->addAction(text);\n action->setCheckable(true);\n action ->setChecked(child == activeMdiChild());\n connect(action, SIGNAL(triggered()), windowMapper, SLOT(map()));\n windowMapper->setMapping(action, windows.at(i));\n }\n}\n\nMDIWindow* MainWindow::activeMdiChild()\n{\n if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())\n return qobject_cast(activeSubWindow->widget());\n return 0;\n}\n\nvoid MainWindow::setActiveSubWindow(QWidget *window)\n{\n if (!window)\n return;\n mdiArea->setActiveSubWindow(qobject_cast(window));\n}\n\nMDIWindow* MainWindow::findWindowWithTitle(QString title)\n{\n foreach(QMdiSubWindow *window, mdiArea->subWindowList())\n {\n MDIWindow *mdiChild = qobject_cast(window->widget());\n if(mdiChild && mdiChild->windowTitle() == title)\n return mdiChild;\n }\n return 0;\n}\nPrepares openHardwareView(...) to be expanded to handle other hardware besides the joystick.#include \"mainwindow.h\"\n#include \"ui_mainwindow.h\"\n#include \n#include \n#include \"adapters\/joystickadapter.h\"\n\n#include \n\nMainWindow::MainWindow(QWidget *parent) :\n QMainWindow(parent),\n ui(new Ui::MainWindow)\n{\n ui->setupUi(this);\n configTreeModel.populateModel();\n ui->configTree->setModel(configTreeModel.model());\n mdiArea = ui->mainDisplayArea;\n connect(mdiArea, SIGNAL(subWindowActivated(QMdiSubWindow*)),\n this, SLOT(updateMenus()));\n windowMapper = new QSignalMapper(this);\n connect(windowMapper, SIGNAL(mapped(QWidget*)),\n this, SLOT(setActiveSubWindow(QWidget*)));\n\n ui->hardwareStatusList->addItem(\"Joystick\");\n connect(ui->hardwareStatusList, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(openHardwareView(QModelIndex)));\n\n setupMenus();\n updateWindowMenu();\n\n _joystick = new Joystick;\n}\n\nvoid MainWindow::setupMenus()\n{\n connect(ui->actionClose, SIGNAL(triggered()), this, SLOT(close()));\n connect(ui->menuWindow, SIGNAL(aboutToShow()), this, SLOT(updateWindowMenu()));\n connect(ui->actionClose_2, SIGNAL(triggered()), mdiArea, SLOT(closeActiveSubWindow()));\n connect(ui->actionClose_All, SIGNAL(triggered()), mdiArea, SLOT(closeAllSubWindows()));\n connect(ui->actionCascade, SIGNAL(triggered()), mdiArea, SLOT(cascadeSubWindows()));\n connect(ui->actionTile, SIGNAL(triggered()), mdiArea, SLOT(tileSubWindows()));\n}\n\nMainWindow::~MainWindow()\n{\n delete _joystick;\n delete ui;\n}\n\nvoid MainWindow::openHardwareView(QModelIndex index)\n{\n QString labelText = ui->hardwareStatusList->item(index.row())->text();\n if(MDIWindow* window = findWindowWithTitle(labelText))\n {\n if(!window->isVisible())\n window->show();\n }\n else\n {\n using namespace std;\n MDIWindow *newWindow = new MDIWindow;\n newWindow->setWindowTitle(labelText);\n newWindow->setLayout(new QGridLayout);\n\n \/\/JoystickAdapter *adapter = new JoystickAdapter(_joystick);\n QWidget* adapter;\n\n if(labelText == \"Joystick\")\n {\n adapter = new JoystickAdapter(_joystick);\n }\n else\n {\n adapter = new QWidget();\n }\n\n newWindow->layout()->addWidget(adapter);\n\n mdiArea->addSubWindow(newWindow);\n newWindow->show();\n }\n\n updateWindowMenu();\n}\n\nvoid MainWindow::on_actionFullscreen_triggered()\n{\n if(ui->actionFullscreen->isChecked())\n this->showFullScreen();\n else\n this->showNormal();\n}\n\nvoid MainWindow::updateMenus()\n{\n bool hasMdiChild = (activeMdiChild() != 0);\n\n ui->actionTile->setEnabled(hasMdiChild);\n ui->actionCascade->setEnabled(hasMdiChild);\n ui->actionClose_2->setEnabled(hasMdiChild);\n ui->actionClose_All->setEnabled(hasMdiChild);\n}\n\nvoid MainWindow::updateWindowMenu()\n{\n for(int i = ui->menuWindow->actions().size()-1; i > 5; i--)\n {\n ui->menuWindow->removeAction(ui->menuWindow->actions().at(i));\n }\n\n QList windows = mdiArea->subWindowList();\n\n for (int i = 0; i < windows.size(); ++i) {\n MDIWindow *child = qobject_cast(windows.at(i)->widget());\n\n QString text = windows.at(i)->windowTitle();\n QAction *action = ui->menuWindow->addAction(text);\n action->setCheckable(true);\n action ->setChecked(child == activeMdiChild());\n connect(action, SIGNAL(triggered()), windowMapper, SLOT(map()));\n windowMapper->setMapping(action, windows.at(i));\n }\n}\n\nMDIWindow* MainWindow::activeMdiChild()\n{\n if (QMdiSubWindow *activeSubWindow = mdiArea->activeSubWindow())\n return qobject_cast(activeSubWindow->widget());\n return 0;\n}\n\nvoid MainWindow::setActiveSubWindow(QWidget *window)\n{\n if (!window)\n return;\n mdiArea->setActiveSubWindow(qobject_cast(window));\n}\n\nMDIWindow* MainWindow::findWindowWithTitle(QString title)\n{\n foreach(QMdiSubWindow *window, mdiArea->subWindowList())\n {\n MDIWindow *mdiChild = qobject_cast(window->widget());\n if(mdiChild && mdiChild->windowTitle() == title)\n return mdiChild;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"microoptimization<|endoftext|>"} {"text":"#include \"Nearest.h\"\n\nusing namespace std;\n\nnamespace nearest {\n\n vector nearestN(const vector& points, int N) {\n if (points.empty() || N == 0) {\n return vector();\n }\n return nearestN(points, N, {0.0, 0.0, 0.0}, INFINITY);\n }\n\n vector nearestN(const vector& points,\n int N,\n const Point& reference,\n double distanceThreshold) {\n\n assert(distanceThreshold >= 0 && N >= 0);\n vector temp;\n temp.insert(temp.begin(), points.begin(), points.end());\n\n \/\/ filtering vector to remove all points far then distance from reference\n temp.erase(remove_if(temp.begin(),\n temp.end(),\n [&reference, distanceThreshold](const Point& p){\n return reference.dist(p) > distanceThreshold;\n }),\n temp.end());\n\n sort(temp.begin(), temp.end(),\n [&reference](const Point& p1, const Point& p2) {\n return reference.dist_square(p1) < reference.dist_square(p2);\n });\n\n auto sz = min(static_cast(temp.size()), N);\n temp.resize(sz);\n return temp;\n }\n}\nsmall optimizations#include \"Nearest.h\"\n\nusing namespace std;\n\nnamespace nearest {\n\n vector nearestN(const vector& points, int N) {\n if (points.empty() || N == 0) {\n return vector();\n }\n return nearestN(points, N, {0.0, 0.0, 0.0}, INFINITY);\n }\n\n vector nearestN(const vector& points,\n int N,\n const Point& reference,\n double distanceThreshold) {\n\n assert(distanceThreshold >= 0 && N >= 0);\n if (points.empty() || N == 0) {\n return vector();\n }\n vector temp;\n temp.insert(temp.begin(), points.begin(), points.end());\n\n \/\/ filtering vector to remove all points far then distance from reference\n temp.erase(remove_if(temp.begin(),\n temp.end(),\n [&reference, distanceThreshold](const Point& p){\n return reference.dist(p) > distanceThreshold;\n }),\n temp.end());\n\n sort(temp.begin(), temp.end(),\n [&reference](const Point& p1, const Point& p2) {\n return reference.dist_square(p1) < reference.dist_square(p2);\n });\n\n auto sz = min(static_cast(temp.size()), N);\n temp.resize(sz);\n return temp;\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Renderer.cpp\n *\n * Renders the box2d content\n *\/\n\n#ifndef PINBALL_BOT_RENDERER\n#define PINBALL_BOT_RENDERER\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#ifdef __APPLE__\n#include \n#include \n#else\n#ifdef _WIN32\n #include \n#endif\n#include \n#include \n#endif\n\nclass Renderer : public b2Draw{\n\n\tprivate:\n\n\t\tconst float NUMERATOR\t\t\t= 7.0f;\n\t\tconst float DENOMINATOR\t\t\t= 9.0f;\n\n\t\tconst float SCALING\t\t\t\t= NUMERATOR \/ DENOMINATOR;\n\t\tconst float PADDING_PERCENT\t\t= (DENOMINATOR - NUMERATOR) \/ DENOMINATOR \/ 2;\n\n\t\tint\t\twidth;\n\t\tint\t\theight;\n\n\t\tint\t\toneMeterInPX;\n\n\t\tSDL_Window*\t\twindow;\n\t\tSDL_Renderer*\trenderer;\n\n\t\t\/**\n\t\t * Converts Box2D meters into screen pixels\n\t\t * @param\tmeters\t\tfloat\t\tThe amount of meters to convert\n\t\t * @return\t\t\t\tint\t\t\tThe rounded amount of corresponding screen pixels\n\t\t *\/\n\t\tint metersToPixels(const float &meters){\n\t\t\treturn round(meters * oneMeterInPX);\n\t\t}\n\n\t\t\/**\n\t\t * Converts a Box2D vector into screen coordinates using metersToPixels()\n\t\t * @param\tposition\tb2Vec2\t\tThe Box2D vector to convert\n\t\t * @return\t\t\t\tb2vec2\t\tThe converted Box2D vector\n\t\t *\/\n\t\tb2Vec2 toScreenCoords(const b2Vec2 &position){\n\t\t\treturn b2Vec2 (\n\t\t\t\t\tround(width * PADDING_PERCENT) + metersToPixels(position.x),\n\t\t\t\t\tround(height * PADDING_PERCENT) + metersToPixels(position.y)\n\t\t\t);\n\t\t}\n\n\tpublic:\n\n\t\t\/**\n\t\t * Inits all required values based on the given window width\/height and the DPI\n\t\t *\/\n\t\tRenderer(int width, int height) : width(width), height(height){\n\n\t\t\tSDL_Init( \/*SDL_INIT_EVERYTHING*\/SDL_INIT_VIDEO );\n\n\t\t\twindow = SDL_CreateWindow(\n\t\t\t\t\"PinballBot\",\t\t\t\t\t\t\/\/ window title\n\t\t\t\t0,\t\t\t\t\t\t\t\t\t\/\/ initial x position\n\t\t\t\t0,\t\t\t\t\t\t\t\t\t\/\/ initial y position\n\t\t\t\tthis->width,\t\t\t\t\t\t\/\/ width, in pixels\n\t\t\t\tthis->height,\t\t\t\t\t\t\/\/ height, in pixels\n\t\t\t\tSDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI \/\/enables retina support\n\t\t\t);\n\n\t\t\tif (window == nullptr) {\n\t\t\t\tprintf(\"Could not create window: %s\\n\", SDL_GetError());\n\t\t\t\tSDL_Quit();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/updates the width and height if there's a high DPI and calc other vars afterwards\n\t\t\tSDL_GL_GetDrawableSize(window, &this->width, &this->height);\n\n\t\t\toneMeterInPX = round(SCALING * this->height); \/* one meter is equal to half of the width of the window *\/\n\n\t\t\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\t\t\tSDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); \/\/white background\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\n\t\t\/**\n\t\t * Uses SDL functions to remove objects\n\t\t *\/\n\t\t~Renderer(){\n\t\t\tSDL_DestroyWindow(window);\n\t\t\tSDL_Quit();\n\t\t}\n\n\t\t\/**\n\t\t * Redraws the scene onto the window\n\t\t * @return\tvoid\n\t\t *\/\n\t\tvoid redraw(){\n\n\t\t\t\/\/filledCircleColor(renderer, 320, 91, 10, createRGBA(255,0,0,255));\n\n\t\t\tSDL_RenderPresent(renderer);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\n\t\t\/**\n\t\t * Draws a polygon\n\t\t * @param\tvertices\t\tb2Vec2\t\tThe vertices of the polygon\n\t\t * @param\tvertexCount\t\tint32\t\tThe amount of vertices\n\t\t * @param\tred\t\t\t\tUint8\t\tThe amount of red\tin the color\n\t\t * @param\tgreen\t\t\tUint8\t\tThe amount of green\tin the color\n\t\t * @param\tblue\t\t\tUint8\t\tThe amount of blue\tin the color\n\t\t * @param\talpha\t\t\tUint8\t\tThe opacity of the color\n\t\t * @param\tfilled\t\t\tbool\t\tDraw a filled polygon or just the outlines?\n\t\t * @return\tvoid\n\t\t *\/\n\t\tvoid dPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){\n\t\t\tstd::vector x(vertexCount);\n\t\t\tstd::vector y(vertexCount);\n\n\t\t\tfor(int i=0;iSDL window centered\/*\n * Renderer.cpp\n *\n * Renders the box2d content\n *\/\n\n#ifndef PINBALL_BOT_RENDERER\n#define PINBALL_BOT_RENDERER\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#ifdef __APPLE__\n#include \n#include \n#else\n#ifdef _WIN32\n #include \n#endif\n#include \n#include \n#endif\n\nclass Renderer : public b2Draw{\n\n\tprivate:\n\n\t\tconst float NUMERATOR\t\t\t= 7.0f;\n\t\tconst float DENOMINATOR\t\t\t= 9.0f;\n\n\t\tconst float SCALING\t\t\t\t= NUMERATOR \/ DENOMINATOR;\n\t\tconst float PADDING_PERCENT\t\t= (DENOMINATOR - NUMERATOR) \/ DENOMINATOR \/ 2;\n\n\t\tint\t\twidth;\n\t\tint\t\theight;\n\n\t\tint\t\toneMeterInPX;\n\n\t\tSDL_Window*\t\twindow;\n\t\tSDL_Renderer*\trenderer;\n\n\t\t\/**\n\t\t * Converts Box2D meters into screen pixels\n\t\t * @param\tmeters\t\tfloat\t\tThe amount of meters to convert\n\t\t * @return\t\t\t\tint\t\t\tThe rounded amount of corresponding screen pixels\n\t\t *\/\n\t\tint metersToPixels(const float &meters){\n\t\t\treturn round(meters * oneMeterInPX);\n\t\t}\n\n\t\t\/**\n\t\t * Converts a Box2D vector into screen coordinates using metersToPixels()\n\t\t * @param\tposition\tb2Vec2\t\tThe Box2D vector to convert\n\t\t * @return\t\t\t\tb2vec2\t\tThe converted Box2D vector\n\t\t *\/\n\t\tb2Vec2 toScreenCoords(const b2Vec2 &position){\n\t\t\treturn b2Vec2 (\n\t\t\t\t\tround(width * PADDING_PERCENT) + metersToPixels(position.x),\n\t\t\t\t\tround(height * PADDING_PERCENT) + metersToPixels(position.y)\n\t\t\t);\n\t\t}\n\n\tpublic:\n\n\t\t\/**\n\t\t * Inits all required values based on the given window width\/height and the DPI\n\t\t *\/\n\t\tRenderer(int width, int height) : width(width), height(height){\n\n\t\t\tSDL_Init( \/*SDL_INIT_EVERYTHING*\/SDL_INIT_VIDEO );\n\n\t\t\twindow = SDL_CreateWindow(\n\t\t\t\t\"PinballBot\",\t\t\t\t\t\t\/\/ window title\n\t\t\t\tSDL_WINDOWPOS_CENTERED,\t\t\t\t\/\/ initial x position\n\t\t\t\tSDL_WINDOWPOS_CENTERED,\t\t\t\t\/\/ initial y position\n\t\t\t\tthis->width,\t\t\t\t\t\t\/\/ width, in pixels\n\t\t\t\tthis->height,\t\t\t\t\t\t\/\/ height, in pixels\n\t\t\t\tSDL_WINDOW_OPENGL | SDL_WINDOW_ALLOW_HIGHDPI \/\/enables retina support\n\t\t\t);\n\n\t\t\tif (window == nullptr) {\n\t\t\t\tprintf(\"Could not create window: %s\\n\", SDL_GetError());\n\t\t\t\tSDL_Quit();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/updates the width and height if there's a high DPI and calc other vars afterwards\n\t\t\tSDL_GL_GetDrawableSize(window, &this->width, &this->height);\n\n\t\t\toneMeterInPX = round(SCALING * this->height); \/* one meter is equal to half of the width of the window *\/\n\n\t\t\trenderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);\n\t\t\tSDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_ADD);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); \/\/white background\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\n\t\t\/**\n\t\t * Uses SDL functions to remove objects\n\t\t *\/\n\t\t~Renderer(){\n\t\t\tSDL_DestroyWindow(window);\n\t\t\tSDL_Quit();\n\t\t}\n\n\t\t\/**\n\t\t * Redraws the scene onto the window\n\t\t * @return\tvoid\n\t\t *\/\n\t\tvoid redraw(){\n\n\t\t\t\/\/filledCircleColor(renderer, 320, 91, 10, createRGBA(255,0,0,255));\n\n\t\t\tSDL_RenderPresent(renderer);\n\n\t\t\tSDL_SetRenderDrawColor(renderer, 255, 255, 255, 255);\n\t\t\tSDL_RenderClear(renderer);\n\t\t}\n\n\t\t\/**\n\t\t * Draws a polygon\n\t\t * @param\tvertices\t\tb2Vec2\t\tThe vertices of the polygon\n\t\t * @param\tvertexCount\t\tint32\t\tThe amount of vertices\n\t\t * @param\tred\t\t\t\tUint8\t\tThe amount of red\tin the color\n\t\t * @param\tgreen\t\t\tUint8\t\tThe amount of green\tin the color\n\t\t * @param\tblue\t\t\tUint8\t\tThe amount of blue\tin the color\n\t\t * @param\talpha\t\t\tUint8\t\tThe opacity of the color\n\t\t * @param\tfilled\t\t\tbool\t\tDraw a filled polygon or just the outlines?\n\t\t * @return\tvoid\n\t\t *\/\n\t\tvoid dPolygon(const b2Vec2* vertices, int32 vertexCount, Uint8 red, Uint8 green, Uint8 blue, Uint8 alpha, bool filled){\n\t\t\tstd::vector x(vertexCount);\n\t\t\tstd::vector y(vertexCount);\n\n\t\t\tfor(int i=0;i"} {"text":"\/\/ Makes distance matrix based on procrustes RMS between maps\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/range-v3.hh\"\n#include \"acmacs-base\/quicklook.hh\"\n#include \"acmacs-base\/color-gradient.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n#include \"acmacs-chart-2\/procrustes.hh\"\n#include \"acmacs-chart-2\/common.hh\"\n#include \"acmacs-chart-2\/stress.hh\"\n#include \"acmacs-chart-2\/randomizer.hh\"\n#include \"acmacs-chart-2\/bounding-ball.hh\"\n#include \"acmacs-draw\/surface-cairo.hh\"\n#include \"acmacs-draw\/drawi-generator.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing namespace acmacs::argv;\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n std::string_view help_pre() const override { return \"compare titers of mutiple tables\"; }\n argument charts{*this, arg_name{\"chart\"}, mandatory};\n\n option output{*this, 'o', desc{\"output .drawi file\"}};\n option pdf_output{*this, \"pdf\", desc{\"output .pdf file\"}};\n option number_of_optimizations{*this, 'n', dflt{100ul}};\n option minimum_column_basis{*this, 'm', dflt{\"none\"}};\n option number_of_dimensions{*this, 'd', dflt{2ul}};\n option rough{*this, \"rough\"};\n};\n\nint main(int argc, char* const argv[])\n{\n using namespace std::string_view_literals;\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n const auto precision = (opt.rough) ? acmacs::chart::optimization_precision::rough : acmacs::chart::optimization_precision::fine;\n\n std::vector charts;\n for (const auto& filename : opt.charts)\n charts.emplace_back(acmacs::chart::import_from_file(filename));\n\n const auto chart_name = [](const auto& chart) {\n if (const auto date = chart.info()->date(); !date.empty())\n return *date;\n else\n return chart.info()->make_name();\n };\n\n for (auto& chart : charts) {\n chart.projections_modify()->remove_all();\n chart.relax(acmacs::chart::number_of_optimizations_t{*opt.number_of_optimizations}, acmacs::chart::MinimumColumnBasis{opt.minimum_column_basis},\n acmacs::number_of_dimensions_t{*opt.number_of_dimensions}, acmacs::chart::use_dimension_annealing::no, acmacs::chart::optimization_options{precision});\n chart.projections_modify()->sort();\n \/\/ AD_DEBUG(\"{} {:9.4f}\", chart_name(chart), chart.projections()->best()->stress());\n }\n\n acmacs::chart::TableDistances table_distances;\n for (size_t t1 = 0; t1 < (charts.size() - 1); ++t1) {\n for (size_t t2 = t1 + 1; t2 < charts.size(); ++t2) {\n acmacs::chart::CommonAntigensSera common(charts[t1], charts[t2], acmacs::chart::CommonAntigensSera::match_level_t::strict);\n if (!common.points().empty()) {\n const auto procrustes_data = acmacs::chart::procrustes(*charts[t1].projection(0), *charts[t2].projection(0), common.points(), acmacs::chart::procrustes_scaling_t::no);\n table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, procrustes_data.rms);\n AD_DEBUG(\"{} {} {:6.4f}\", chart_name(charts[t1]), chart_name(charts[t2]), procrustes_data.rms);\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------\n \/\/ make-module, also for chart-table-compare\n\n acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, charts.size());\n stress.table_distances() = table_distances;\n\n double best_stress{9e99};\n acmacs::Layout best_layout(charts.size(), stress.number_of_dimensions());\n for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) {\n acmacs::Layout layout(charts.size(), stress.number_of_dimensions());\n acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt);\n for (auto point_no : acmacs::range(layout.number_of_points()))\n layout.update(point_no, rnd.get(stress.number_of_dimensions()));\n\n const auto status1 =\n acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough);\n \/\/ fmt::print(\"{:3d} stress: {} <- {} iterations: {}\\n\", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations);\n if (status1.final_stress < best_stress) {\n best_stress = status1.final_stress;\n best_layout = layout;\n }\n }\n AD_DEBUG(\"best_stress: {}\", best_stress);\n\n if (opt.output) {\n std::vector years;\n acmacs::drawi::Generator gen;\n const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)};\n gen.viewport().set_from_center_size(bb.center(), bb.hv_diameter_whole_number());\n for (const auto t1 : range_from_0_to(charts.size())) {\n const auto label = chart_name(charts[t1]);\n gen.add().coord(best_layout[t1]).label(label);\n if (label.size() >= 4 && (label[0] == '1' || label[0] == '2'))\n years.push_back(label.substr(0, 4));\n }\n gen.add().shape(acmacs::drawi::Generator::Point::Triangle).fill(GREEN).size(Pixels{10}).label_size(Pixels{7}).label_offset({0.0, 1.2});\n\n sort_unique(years);\n if (years.size() > 1) {\n for (const auto [no, year] : ranges::views::zip(ranges::views::iota(0ul), years)) {\n AD_DEBUG(\"{:2d} {}\", no, year);\n gen.add().select(\"name\"sv, fmt::format(\"~{}\", year)).fill(acmacs::color::perceptually_uniform_heatmap(years.size(), no));\n }\n }\n\n const auto title = fmt::format(\"{} {} {} {} {}-{}\", charts[0].info()->lab(), charts[0].info()->virus_type(), charts[0].lineage(), charts[0].info()->assay(), years.front(), years.back());\n gen.title(title);\n \/\/ AD_DEBUG(\"title: \\\"{}\\\"\", title);\n\n gen.generate(opt.output);\n\n if (opt.pdf_output)\n acmacs::run_and_detach({\"drawi\", opt.output->data(), opt.pdf_output->data(), \"--open\"}, 0);\n }\n }\n catch (std::exception& err) {\n AD_ERROR(\"{}\", err);\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nchart-table-map-compare\/\/ Makes distance matrix based on procrustes RMS between maps\n\n#include \"acmacs-base\/argv.hh\"\n#include \"acmacs-base\/range-v3.hh\"\n#include \"acmacs-base\/quicklook.hh\"\n#include \"acmacs-base\/color-gradient.hh\"\n#include \"acmacs-chart-2\/factory-import.hh\"\n#include \"acmacs-chart-2\/chart-modify.hh\"\n#include \"acmacs-chart-2\/procrustes.hh\"\n#include \"acmacs-chart-2\/common.hh\"\n#include \"acmacs-chart-2\/stress.hh\"\n#include \"acmacs-chart-2\/randomizer.hh\"\n#include \"acmacs-chart-2\/bounding-ball.hh\"\n#include \"acmacs-draw\/surface-cairo.hh\"\n#include \"acmacs-draw\/drawi-generator.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\nusing namespace acmacs::argv;\nstruct Options : public argv\n{\n Options(int a_argc, const char* const a_argv[], on_error on_err = on_error::exit) : argv() { parse(a_argc, a_argv, on_err); }\n\n std::string_view help_pre() const override { return \"compare titers of mutiple tables\"; }\n argument charts{*this, arg_name{\"chart\"}, mandatory};\n\n option output{*this, 'o', desc{\"output .drawi file\"}};\n option pdf_output{*this, \"pdf\", desc{\"output .pdf file\"}};\n option number_of_optimizations{*this, 'n', dflt{100ul}};\n option minimum_column_basis{*this, 'm', dflt{\"none\"}};\n option number_of_dimensions{*this, 'd', dflt{2ul}};\n option rough{*this, \"rough\"};\n};\n\nint main(int argc, char* const argv[])\n{\n using namespace std::string_view_literals;\n int exit_code = 0;\n try {\n Options opt(argc, argv);\n const auto precision = (opt.rough) ? acmacs::chart::optimization_precision::rough : acmacs::chart::optimization_precision::fine;\n\n std::vector charts;\n for (const auto& filename : opt.charts)\n charts.emplace_back(acmacs::chart::import_from_file(filename));\n\n const auto chart_name = [](const auto& chart) {\n if (const auto date = chart.info()->date(); !date.empty())\n return *date;\n else\n return chart.info()->make_name();\n };\n\n for (auto& chart : charts) {\n chart.projections_modify()->remove_all();\n chart.relax(acmacs::chart::number_of_optimizations_t{*opt.number_of_optimizations}, acmacs::chart::MinimumColumnBasis{opt.minimum_column_basis},\n acmacs::number_of_dimensions_t{*opt.number_of_dimensions}, acmacs::chart::use_dimension_annealing::no, acmacs::chart::optimization_options{precision});\n chart.projections_modify()->sort();\n AD_DEBUG(\"{} {:9.4f}\", chart_name(chart), chart.projections()->best()->stress());\n }\n\n acmacs::chart::TableDistances table_distances;\n for (size_t t1 = 0; t1 < (charts.size() - 1); ++t1) {\n for (size_t t2 = t1 + 1; t2 < charts.size(); ++t2) {\n acmacs::chart::CommonAntigensSera common(charts[t1], charts[t2], acmacs::chart::CommonAntigensSera::match_level_t::strict);\n if (!common.points().empty()) {\n const auto procrustes_data = acmacs::chart::procrustes(*charts[t1].projection(0), *charts[t2].projection(0), common.points(), acmacs::chart::procrustes_scaling_t::no);\n if (!std::isnan(procrustes_data.rms))\n table_distances.add_value(acmacs::chart::Titer::Regular, t1, t2, procrustes_data.rms);\n AD_DEBUG(\"{} {} {:6.4f}\", chart_name(charts[t1]), chart_name(charts[t2]), procrustes_data.rms);\n }\n }\n }\n\n \/\/ ----------------------------------------------------------------------\n \/\/ make-module, also for chart-table-compare\n\n acmacs::chart::Stress stress(acmacs::number_of_dimensions_t{2}, charts.size());\n stress.table_distances() = table_distances;\n\n double best_stress{9e99};\n acmacs::Layout best_layout(charts.size(), stress.number_of_dimensions());\n for ([[maybe_unused]] auto attempt : acmacs::range(*opt.number_of_optimizations)) {\n acmacs::Layout layout(charts.size(), stress.number_of_dimensions());\n acmacs::chart::LayoutRandomizerPlain rnd(10.0, std::nullopt);\n for (auto point_no : acmacs::range(layout.number_of_points()))\n layout.update(point_no, rnd.get(stress.number_of_dimensions()));\n\n const auto status1 =\n acmacs::chart::optimize(acmacs::chart::optimization_method::alglib_cg_pca, stress, layout.data(), layout.data() + layout.size(), acmacs::chart::optimization_precision::rough);\n \/\/ fmt::print(\"{:3d} stress: {} <- {} iterations: {}\\n\", attempt, status1.final_stress, status1.initial_stress, status1.number_of_iterations);\n if (status1.final_stress < best_stress) {\n best_stress = status1.final_stress;\n best_layout = layout;\n }\n }\n AD_DEBUG(\"best_stress: {}\", best_stress);\n\n if (opt.output) {\n std::vector years;\n acmacs::drawi::Generator gen;\n const acmacs::BoundingBall bb{minimum_bounding_ball(best_layout)};\n gen.viewport().set_from_center_size(bb.center(), bb.hv_diameter_whole_number());\n for (const auto t1 : range_from_0_to(charts.size())) {\n const auto label = chart_name(charts[t1]);\n gen.add().coord(best_layout[t1]).label(label);\n if (label.size() >= 4 && (label[0] == '1' || label[0] == '2'))\n years.push_back(label.substr(0, 4));\n }\n gen.add().shape(acmacs::drawi::Generator::Point::Triangle).fill(GREEN).size(Pixels{10}).label_size(Pixels{7}).label_offset({0.0, 1.2});\n\n sort_unique(years);\n if (years.size() > 1) {\n for (const auto [no, year] : ranges::views::zip(ranges::views::iota(0ul), years)) {\n AD_DEBUG(\"{:2d} {}\", no, year);\n gen.add().select(\"name\"sv, fmt::format(\"~{}\", year)).fill(acmacs::color::perceptually_uniform_heatmap(years.size(), no));\n }\n }\n\n const auto title = fmt::format(\"{} {} {} {} {}-{}\", charts[0].info()->lab(), charts[0].info()->virus_type(), charts[0].lineage(), charts[0].info()->assay(), years.front(), years.back());\n gen.title(title);\n \/\/ AD_DEBUG(\"title: \\\"{}\\\"\", title);\n\n gen.generate(opt.output);\n\n if (opt.pdf_output)\n acmacs::run_and_detach({\"drawi\", opt.output->data(), opt.pdf_output->data(), \"--open\"}, 0);\n }\n }\n catch (std::exception& err) {\n AD_ERROR(\"{}\", err);\n exit_code = 2;\n }\n return exit_code;\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDerivativeImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \"itkImage.h\"\n#include \"itkDerivativeImageFilter.h\"\n#include \"itkNullImageToImageFilterDriver.txx\"\n\nint itkDerivativeImageFilterTest(int , char * [] )\n{\n \/\/ try\n {\n typedef itk::Image ImageType;\n\n \/\/ Set up filter\n itk::DerivativeImageFilter::Pointer filter\n = itk::DerivativeImageFilter::New();\n filter->SetOrder(1);\n filter->SetDirection(1);\n std::cout << \"About to execute\" << std::endl;\n \/\/ Run Test\n itk::Size<3> sz;\n sz[0]=256;\n sz[1]=256;\n sz[2]=5;\n itk::NullImageToImageFilterDriver< ImageType, ImageType >\n test1;\n test1.SetImageSize(sz);\n test1.SetFilter(filter.GetPointer());\n test1.Execute();\n std::cout << \"Finished executing\" << std::endl;\n }\n\/\/ catch(itk::ExceptionObject &err)\n\/\/ {\n\/\/ (&err)->Print(std::cerr);\n\/\/ return 1;\n\/\/ } \n return 0; \n}\nENH: added a filter watcher.\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkDerivativeImageFilterTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n Copyright (c) 2002 Insight Consortium. All rights reserved.\n See ITKCopyright.txt or http:\/\/www.itk.org\/HTML\/Copyright.htm for details.\n\n This software is distributed WITHOUT ANY WARRANTY; without even \n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR \n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \n#include \"itkImage.h\"\n#include \"itkDerivativeImageFilter.h\"\n#include \"itkNullImageToImageFilterDriver.txx\"\n#include \"itkFilterWatcher.h\"\n\nint itkDerivativeImageFilterTest(int , char * [] )\n{\n \/\/ try\n {\n typedef itk::Image ImageType;\n\n \/\/ Set up filter\n itk::DerivativeImageFilter::Pointer filter\n = itk::DerivativeImageFilter::New();\n FilterWatcher watcher(filter);\n\n filter->SetOrder(1);\n filter->SetDirection(1);\n std::cout << \"About to execute\" << std::endl;\n \/\/ Run Test\n itk::Size<3> sz;\n sz[0]=256;\n sz[1]=256;\n sz[2]=5;\n itk::NullImageToImageFilterDriver< ImageType, ImageType >\n test1;\n test1.SetImageSize(sz);\n test1.SetFilter(filter.GetPointer());\n test1.Execute();\n std::cout << \"Finished executing\" << std::endl;\n }\n\/\/ catch(itk::ExceptionObject &err)\n\/\/ {\n\/\/ (&err)->Print(std::cerr);\n\/\/ return 1;\n\/\/ } \n return 0; \n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRigid3DPerspectiveTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \n\n#include \"itkRigid3DPerspectiveTransform.h\"\n#include \"vnl\/vnl_vector_fixed.h\"\n#include \"itkVector.h\"\n\n\n\n\nint main(int argc,char *argv[])\n{\n\n\n typedef itk::Rigid3DPerspectiveTransform TransformType;\n\n const double epsilon = 1e-10;\n const unsigned int N = 3;\n\n\n bool Ok = true;\n\n\n \/* Create a 3D identity transformation and show its parameters *\/\n {\n TransformType::Pointer identityTransform = TransformType::New();\n TransformType::OffsetType offset = identityTransform->GetOffset();\n std::cout << \"Vector from instantiating an identity transform: \";\n std::cout << offset << std::endl;\n\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Identity doesn't have a null offset\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n\n \n \/* Create a Rigid 3D transform with translation *\/\n {\n TransformType::Pointer translation = TransformType::New();\n TransformType::OffsetType ioffset;\n ioffset = 1,4,9;\n\n translation->SetOffset( ioffset );\n\n TransformType::OffsetType offset = translation->GetOffset();\n std::cout << \"pure Translation test: \";\n std::cout << offset << std::endl;\n\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Get Offset differs from SetOffset value \" << std::endl;\n return EXIT_FAILURE;\n }\n\n {\n \/\/ Translate an itk::Point\n TransformType::InputPointType p;\n p = 10,10,10;\n TransformType::InputPointType q;\n q = p + ioffset;\n TransformType::OutputPointType r;\n r = translation->TransformPoint( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating point: \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an itk::Point \" << std::endl;\n }\n }\n\n {\n \/\/ Translate an itk::Vector\n TransformType::InputVectorType p;\n p = 10,10,10;\n TransformType::OutputVectorType q;\n q = translation->TransformVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating vector: \" << p << std::endl;\n std::cerr << \"Reported Result is : \" << q << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an itk::Vector \" << std::endl;\n }\n }\n\n {\n \/\/ Translate an itk::CovariantVector\n TransformType::InputCovariantVectorType p;\n p = 10,10,10;\n TransformType::OutputCovariantVectorType q;\n q = translation->TransformCovariantVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating covariant vector: \" << p << std::endl;\n std::cerr << \"Reported Result is : \" << q << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an itk::CovariantVector \" << std::endl;\n }\n }\n\n \n {\n \/\/ Translate a vnl_vector\n TransformType::InputVnlVectorType p;\n p[0] = 11;\n p[1] = 7;\n p[2] = 15;\n TransformType::OutputVnlVectorType q;\n q = translation->TransformVnlVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating vnl_vector: \" << p << std::endl;\n std::cerr << \"Reported Result is : \" << q << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an vnl_Vector \" << std::endl;\n }\n }\n\n\n\n\n }\n\n \n \/* Create a Rigid 3D transform with rotation *\/\n {\n TransformType::Pointer rotation = TransformType::New();\n\n itk::Vector axis;\n axis = 1,1,1;\n\n const double angle = (atan(1.0)\/45.0)*120.0; \/\/ turn 120 degrees\n\n \/\/ this rotation will permute the axis x->y, y->z, z->x\n rotation->SetRotation( axis, angle );\n\n TransformType::OffsetType offset = rotation->GetOffset();\n std::cout << \"pure Rotation test: \";\n std::cout << offset << std::endl;\n\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Get Offset differs from null in rotation \" << std::endl;\n return EXIT_FAILURE;\n }\n\n {\n \/\/ Rotate an itk::Point\n TransformType::InputPointType p;\n p = 1,4,9;\n TransformType::OutputPointType q;\n q[0] = p[1];\n q[1] = p[2];\n q[2] = p[0];\n\n TransformType::OutputPointType r;\n r = rotation->TransformPoint( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating point : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok rotating an itk::Point \" << std::endl;\n }\n }\n\n {\n \/\/ Translate an itk::Vector\n TransformType::InputVectorType p;\n p = 1,4,9;\n TransformType::OutputVectorType q;\n q[0] = p[1];\n q[1] = p[2];\n q[2] = p[0];\n\n TransformType::OutputVectorType r;\n r = rotation->TransformVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating vector : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok rotating an itk::Vector \" << std::endl;\n }\n }\n\n\n {\n \/\/ Translate an itk::CovariantVector\n TransformType::InputCovariantVectorType p;\n p = 1,4,9;\n TransformType::OutputCovariantVectorType q;\n q[0] = p[1];\n q[1] = p[2];\n q[2] = p[0];\n\n TransformType::OutputCovariantVectorType r;\n r = rotation->TransformCovariantVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating covariant vector : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok rotating an itk::CovariantVector \" << std::endl;\n }\n }\n\n \n {\n \/\/ Translate a vnl_vector\n TransformType::InputVnlVectorType p;\n p[0] = 1;\n p[1] = 4;\n p[2] = 9;\n\n TransformType::OutputVnlVectorType q;\n\n q[0] = p[1];\n q[1] = p[2];\n q[2] = p[0];\n\n TransformType::OutputVnlVectorType r;\n r = rotation->TransformVnlVector( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error rotating vnl_vector : \" << p << std::endl;\n std::cerr << \"Result should be : \" << q << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok rotating an vnl_Vector \" << std::endl;\n }\n }\n\n\n\n\n }\n\n \n return EXIT_SUCCESS;\n\n}\nFIX: Test corrected for testing for perspective. Tests for vectors removed\/*=========================================================================\n\n Program: Insight Segmentation & Registration Toolkit\n Module: itkRigid3DPerspectiveTransformTest.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\nCopyright (c) 2001 Insight Consortium\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * The name of the Insight Consortium, nor the names of any consortium members,\n nor of any contributors, may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \n\n#include \"itkRigid3DPerspectiveTransform.h\"\n#include \"vnl\/vnl_vector_fixed.h\"\n#include \"itkVector.h\"\n\n\n\n\nint main(int argc,char *argv[])\n{\n\n\n typedef itk::Rigid3DPerspectiveTransform TransformType;\n\n const double epsilon = 1e-10;\n const unsigned int N = 3;\n \n const double focal = 100.0;\n const double width = 100.0;\n const double height = 100.0;\n\n\n bool Ok = true;\n\n\n \/* Create a 3D identity transformation and show its parameters *\/\n {\n TransformType::Pointer identityTransform = TransformType::New();\n identityTransform->SetFocalDistance( focal );\n identityTransform->SetHeight( height );\n identityTransform->SetWidth( width );\n\n TransformType::OffsetType offset = identityTransform->GetOffset();\n std::cout << \"Vector from instantiating an identity transform: \";\n std::cout << offset << std::endl;\n\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Identity doesn't have a null offset\" << std::endl;\n return EXIT_FAILURE;\n }\n }\n\n\n \n \/* Create a Rigid 3D transform with translation *\/\n {\n TransformType::Pointer translation = TransformType::New();\n translation->SetFocalDistance( focal );\n translation->SetHeight( height );\n translation->SetWidth( width );\n\n TransformType::OffsetType ioffset;\n ioffset.Fill(0.0);\n\n translation->SetOffset( ioffset );\n\n TransformType::OffsetType offset = translation->GetOffset();\n std::cout << \"pure Translation test: \";\n std::cout << offset << std::endl;\n\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Get Offset differs from SetOffset value \" << std::endl;\n return EXIT_FAILURE;\n }\n\n {\n \/\/ Project an itk::Point\n TransformType::InputPointType p;\n p.Fill(0.0);\n TransformType::InputPointType q;\n q = p + ioffset;\n TransformType::OutputPointType s;\n const double factor = height\/(q[2]+focal);\n s[0] = q[0] * factor + width\/2.0;\n s[1] = q[1] * factor + height\/2.0;\n TransformType::OutputPointType r;\n r = translation->TransformPoint( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating point: \" << p << std::endl;\n std::cerr << \"Result should be : \" << s << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an itk::Point \" << std::endl;\n }\n }\n\n {\n \/\/ Projecting an itk::Point\n TransformType::InputPointType p;\n p[0] = 10;\n p[1] = 10;\n p[2] = 10;\n TransformType::InputPointType q;\n q = p + ioffset;\n TransformType::OutputPointType s;\n const double factor = height\/(q[2]+focal);\n s[0] = q[0] * factor + width\/2.0;\n s[1] = q[1] * factor + height\/2.0;\n TransformType::OutputPointType r;\n r = translation->TransformPoint( p );\n for(unsigned int i=0; i epsilon )\n {\n Ok = false;\n break; \n }\n }\n if( !Ok )\n { \n std::cerr << \"Error translating point: \" << p << std::endl;\n std::cerr << \"Result should be : \" << s << std::endl;\n std::cerr << \"Reported Result is : \" << r << std::endl;\n return EXIT_FAILURE;\n }\n else\n {\n std::cout << \"Ok translating an itk::Point \" << std::endl;\n }\n }\n\n\n }\n\n \n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/io\/stream_base.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/string_io.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/blob.hpp\"\n#include \n#include \n\nusing namespace flusspferd;\nusing namespace flusspferd::io;\n\nstream_base::stream_base(object const &o, std::streambuf *p)\n : native_object_base(o), streambuf(p)\n{\n register_native_method(\"readWhole\", &stream_base::read_whole);\n register_native_method(\"read\", &stream_base::read);\n register_native_method(\"readWholeBlob\", &stream_base::read_whole_blob);\n register_native_method(\"readBlob\", &stream_base::read_blob);\n register_native_method(\"write\", &stream_base::write);\n register_native_method(\"print\", &stream_base::print);\n register_native_method(\"flush\", &stream_base::flush);\n\n define_property(\"fieldSeparator\", string(\" \"));\n define_property(\"recordSeparator\", string(\"\\n\"));\n define_property(\"autoflush\", false);\n}\n\nstream_base::~stream_base()\n{}\n\nvoid stream_base::set_streambuf(std::streambuf *p) {\n streambuf = p;\n}\n\nstd::streambuf *stream_base::get_streambuf() {\n return streambuf;\n}\n\nobject stream_base::class_info::create_prototype() {\n local_root_scope scope;\n\n object proto = create_object();\n\n create_native_method(proto, \"readWhole\", 0);\n create_native_method(proto, \"read\", 1);\n create_native_method(proto, \"readWholeBlob\", 0);\n create_native_method(proto, \"readBlob\", 1);\n create_native_method(proto, \"write\", 1);\n create_native_method(proto, \"print\", 0);\n create_native_method(proto, \"flush\", 0);\n\n return proto;\n}\n\nstring stream_base::read_whole() {\n std::string data;\n char buf[4096];\n\n std::streamsize length;\n\n do { \n length = streambuf->sgetn(buf, sizeof(buf));\n if (length < 0)\n length = 0;\n data.append(buf, length);\n } while (length > 0);\n\n return string(data);\n}\n\nobject stream_base::read_whole_blob() {\n unsigned const N = 4096;\n\n std::vector data;\n\n std::streamsize length;\n\n do {\n data.resize(data.size() + N);\n length = streambuf->sgetn(&data[data.size() - N], N);\n if (length < 0)\n length = 0;\n data.resize(data.size() - N + length);\n } while (length > 0);\n\n return create_native_object(\n object(), (unsigned char const *)&data[0], data.size());\n}\n\nstring stream_base::read(unsigned size) {\n if (!size)\n size = 4096;\n\n boost::scoped_array buf(new char[size + 1]);\n\n std::streamsize length = streambuf->sgetn(buf.get(), size);\n if (length < 0)\n length = 0;\n buf[length] = '\\0';\n\n return string(buf.get());\n}\n\nobject stream_base::read_blob(unsigned size) {\n if (!size)\n size = 4096;\n\n boost::scoped_array buf(new char[size]);\n\n std::streamsize length = streambuf->sgetn(buf.get(), size);\n if (length < 0)\n length = 0;\n\n return create_native_object(\n object(),\n (unsigned char const *) buf.get(),\n length);\n}\n\nvoid stream_base::write(value const &data) {\n if (data.is_string()) {\n string text = data.get_string();\n char const *str = text.c_str();\n streambuf->sputn(text.c_str(), std::strlen(str));\n } else if (data.is_object()) {\n blob &b = flusspferd::get_native(data.get_object());\n streambuf->sputn((char const*) b.get_data(), b.size());\n } else {\n throw exception(\"Cannot write non-object non-string value to Stream\");\n }\n \/\/TODO slow?\n if (get_property(\"autoflush\").to_boolean())\n flush();\n}\n\nvoid stream_base::print(call_context &x) {\n local_root_scope scope;\n\n value delim_v = get_property(\"fieldSeparator\");\n string delim;\n if (!delim_v.is_void_or_null())\n delim = delim_v.to_string();\n\n std::size_t n = x.arg.size();\n for (std::size_t i = 0; i < n; ++i) {\n write(x.arg[i].to_string());\n if (i < n - 1)\n write(delim);\n }\n\n value record_v = get_property(\"recordSeparator\");\n if (!record_v.is_void_or_null())\n write(record_v.to_string());\n\n flush();\n}\n\nvoid stream_base::flush() {\n streambuf->pubsync();\n}\nIO: make print([1,2,3]) behave same as print(1,2,3);\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/io\/stream_base.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/string_io.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/blob.hpp\"\n#include \n#include \n\nusing namespace flusspferd;\nusing namespace flusspferd::io;\n\nstream_base::stream_base(object const &o, std::streambuf *p)\n : native_object_base(o), streambuf(p)\n{\n register_native_method(\"readWhole\", &stream_base::read_whole);\n register_native_method(\"read\", &stream_base::read);\n register_native_method(\"readWholeBlob\", &stream_base::read_whole_blob);\n register_native_method(\"readBlob\", &stream_base::read_blob);\n register_native_method(\"write\", &stream_base::write);\n register_native_method(\"print\", &stream_base::print);\n register_native_method(\"flush\", &stream_base::flush);\n\n define_property(\"fieldSeparator\", string(\" \"));\n define_property(\"recordSeparator\", string(\"\\n\"));\n define_property(\"autoflush\", false);\n}\n\nstream_base::~stream_base()\n{}\n\nvoid stream_base::set_streambuf(std::streambuf *p) {\n streambuf = p;\n}\n\nstd::streambuf *stream_base::get_streambuf() {\n return streambuf;\n}\n\nobject stream_base::class_info::create_prototype() {\n local_root_scope scope;\n\n object proto = create_object();\n\n create_native_method(proto, \"readWhole\", 0);\n create_native_method(proto, \"read\", 1);\n create_native_method(proto, \"readWholeBlob\", 0);\n create_native_method(proto, \"readBlob\", 1);\n create_native_method(proto, \"write\", 1);\n create_native_method(proto, \"print\", 0);\n create_native_method(proto, \"flush\", 0);\n\n return proto;\n}\n\nstring stream_base::read_whole() {\n std::string data;\n char buf[4096];\n\n std::streamsize length;\n\n do { \n length = streambuf->sgetn(buf, sizeof(buf));\n if (length < 0)\n length = 0;\n data.append(buf, length);\n } while (length > 0);\n\n return string(data);\n}\n\nobject stream_base::read_whole_blob() {\n unsigned const N = 4096;\n\n std::vector data;\n\n std::streamsize length;\n\n do {\n data.resize(data.size() + N);\n length = streambuf->sgetn(&data[data.size() - N], N);\n if (length < 0)\n length = 0;\n data.resize(data.size() - N + length);\n } while (length > 0);\n\n return create_native_object(\n object(), (unsigned char const *)&data[0], data.size());\n}\n\nstring stream_base::read(unsigned size) {\n if (!size)\n size = 4096;\n\n boost::scoped_array buf(new char[size + 1]);\n\n std::streamsize length = streambuf->sgetn(buf.get(), size);\n if (length < 0)\n length = 0;\n buf[length] = '\\0';\n\n return string(buf.get());\n}\n\nobject stream_base::read_blob(unsigned size) {\n if (!size)\n size = 4096;\n\n boost::scoped_array buf(new char[size]);\n\n std::streamsize length = streambuf->sgetn(buf.get(), size);\n if (length < 0)\n length = 0;\n\n return create_native_object(\n object(),\n (unsigned char const *) buf.get(),\n length);\n}\n\nvoid stream_base::write(value const &data) {\n if (data.is_string()) {\n string text = data.get_string();\n char const *str = text.c_str();\n streambuf->sputn(text.c_str(), std::strlen(str));\n } else if (data.is_object()) {\n blob &b = flusspferd::get_native(data.get_object());\n streambuf->sputn((char const*) b.get_data(), b.size());\n } else {\n throw exception(\"Cannot write non-object non-string value to Stream\");\n }\n \/\/TODO slow?\n if (get_property(\"autoflush\").to_boolean())\n flush();\n}\n\nvoid stream_base::print(call_context &x) {\n local_root_scope scope;\n\n value delim_v = get_property(\"fieldSeparator\");\n string delim;\n if (!delim_v.is_void_or_null())\n delim = delim_v.to_string();\n\n \/\/ If passed a single array as an arugment, treat it as the arguments. i.e:\n \/\/ print([1,2,3]) would produces same output as print(1,2,3);\n\n if (x.arg.size() == 1 && x.arg[0].is_object() &&\n x.arg[0].get_object().is_array())\n {\n array a = x.arg[0].get_object();\n std::size_t n = a.get_length();\n for (std::size_t i = 0; i < n; ++i) {\n write(a.get_element(i).to_string());\n if (i < n - 1)\n write(delim);\n }\n }\n else {\n std::size_t n = x.arg.size();\n for (std::size_t i = 0; i < n; ++i) {\n write(x.arg[i].to_string());\n if (i < n - 1)\n write(delim);\n }\n }\n\n value record_v = get_property(\"recordSeparator\");\n if (!record_v.is_void_or_null())\n write(record_v.to_string());\n\n flush();\n}\n\nvoid stream_base::flush() {\n streambuf->pubsync();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"structures\/affectation.h\"\n#include \"structures\/deductions.h\"\n#include \"structures\/CL_proof.h\"\n#include \"structures\/formula.h\"\n#include \"structures\/clause.h\"\n#include \"solvers\/dpll.h\"\n#include \"config.h\"\n\n#define CONFLICT_GRAPH_FILE_NAME \"\/tmp\/conflict_graph.dot\"\n#define CL_PROOF_FILE_NAME \"\/tmp\/CL_proof.tex\"\n\nusing namespace satsolver;\n\n#define AS_AFF(a, l) (a.is_true(l) ? l : -l)\n\nvoid make_conflict_graph(const Deductions &deductions, const Affectation &aff, int root, int literal) {\n FILE *graph_file = NULL;\n \n graph_file = fopen(CONFLICT_GRAPH_FILE_NAME, \"w\");\n fprintf(graph_file, \"digraph G {\\n\");\n \n \/\/ Arêtes\n deductions.print_edges(graph_file,aff) ;\n \n \/\/ Noeuds\n deductions.print_UIP(graph_file,aff,root,literal) ;\n fprintf(graph_file, \"\\t%d [color = \\\"red\\\"];\\n\", literal);\n fprintf(graph_file, \"}\\n\");\n fclose(graph_file);\n}\n\nunsigned int cl_interact(const Deductions &deductions, const Affectation &aff, int last_bet, int literal, bool *with_proof) {\n char mode;\n unsigned int steps;\n assert(deductions.has_variable(abs(literal)));\n std::cout << \"Conflict on literal \" << literal << \". Action? [g\/r\/c\/s\/t] \";\n assert(with_proof);\n *with_proof = false;\n while (true) {\n std::cin >> mode;\n switch (mode) {\n case 'g':\n make_conflict_graph(deductions, aff, last_bet, literal);\n return 1;\n case 'r':\n if (!WITH_CL) {\n std::cout << \"Clause learning is not enabled. Use -CL. [g\/r\/c\/s\/t]. \" << std::endl;\n continue;\n }\n *with_proof = true;\n return 1;\n case 'c':\n return 1;\n case 's':\n std::cin >> steps;\n return steps;\n case 't':\n CL_INTERACT = false;\n return 0;\n default:\n std::cout << \"Invalid character [g\/r\/c\/s\/t]. \";\n continue;\n }\n }\n}\n\nstd::shared_ptr learn_clause(const Deductions &deductions, const std::vector> &mem, const Affectation &aff, int nb_variables, int literal, CLProof *proof) {\n (void) aff;\n long unsigned int mem_top = mem.size()-1; \/\/ The index in the memory “stack” of the literal we are making the resolution on.\n std::unordered_set clause(deductions.get_deduced_from(literal)), clause2;\n assert(clause.find(literal) != clause.end());\n mem_top--;\n while (mem.at(mem_top).second) {\n literal = mem.at(mem_top).first;\n assert(mem.at(mem_top).first == literal);\n clause2 = deductions.get_deduced_from(literal); \/\/ This is the clause we will make the resolution with\n if (!clause2.size())\n break;\n\n if (clause.find(-literal) == clause.end())\n break;\n assert(clause2.find(literal) != clause.end());\n \/\/ Resolution\n \/\/ TODO: Replace 0 with the clause id.\n proof->insert_top(literal, std::make_pair(0, Clause(nb_variables, clause)), std::make_pair(0, Clause(nb_variables, clause2)));\n clause.erase(clause.find(-literal));\n clause2.erase(clause2.find(literal));\n clause.insert(clause2.begin(), clause2.end());\n\n mem_top--;\n }\n return std::shared_ptr(new Clause(nb_variables, clause));\n}\n\nAffectation* satsolver::solve(Formula *formula) {\n int literal;\n bool with_proof;\n CLProof *proof;\n unsigned int clause_id;\n bool contains_false_clause;\n unsigned int skip_conflicts = 1; \/\/ Number of conflicts we will skip before showing another prompt\n int last_bet = 0; \/\/ Used for generating the graph.\n while(formula->get_aff()->get_nb_unknown() != 0 && !formula->only_true_clauses(NULL)) {\n formula->get_ded()->print() ;\n if(!WITH_WL && (literal = formula->monome(&clause_id))) {\n \/\/ We set the clause identified by “claused_id” as the one which\n \/\/ made us deduce the value of the literal.\n formula->deduce_true(literal, clause_id); \/\/ Return value ignored, WITH_WL is false\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n else if((literal = formula->isolated_literal(&clause_id))) {\n\t formula->deduce_true(literal,-1) ;\n }\n else {\n literal = formula->choose_literal(HEURISTIC) ;\n if (WITH_WL)\n contains_false_clause = !formula->bet_true(literal);\n else {\n formula->bet_true(literal);\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n last_bet = literal;\n }\n while(contains_false_clause) {\n if (CL_INTERACT && --skip_conflicts == 0) {\n assert(last_bet);\n skip_conflicts = cl_interact(*formula->get_ded(), formula->get_aff(), last_bet, literal, &with_proof);\n }\n if (WITH_CL) {\n proof = new CLProof(formula->to_clauses_vector()[clause_id]);\n learn_clause(*formula->get_ded(), formula->get_mem(), formula->get_aff(), formula->get_nb_variables(), literal, proof);\n if (with_proof)\n proof->to_latex_file(CL_PROOF_FILE_NAME);\n delete proof;\n }\n literal = formula->back() ;\n last_bet = -last_bet;\n if(literal == 0)\n throw Conflict() ;\n if (WITH_WL)\n contains_false_clause = !formula->deduce_false(literal,-1);\n else {\n formula->deduce_false(literal, -1);\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n }\n }\n return formula->get_aff() ;\n}\nRevert \"Fix handling of 'r' in command-line interaction.\"#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"structures\/affectation.h\"\n#include \"structures\/deductions.h\"\n#include \"structures\/CL_proof.h\"\n#include \"structures\/formula.h\"\n#include \"structures\/clause.h\"\n#include \"solvers\/dpll.h\"\n#include \"config.h\"\n\n#define CONFLICT_GRAPH_FILE_NAME \"\/tmp\/conflict_graph.dot\"\n#define CL_PROOF_FILE_NAME \"\/tmp\/CL_proof.tex\"\n\nusing namespace satsolver;\n\n#define AS_AFF(a, l) (a.is_true(l) ? l : -l)\n\nvoid make_conflict_graph(const Deductions &deductions, const Affectation &aff, int root, int literal) {\n FILE *graph_file = NULL;\n \n graph_file = fopen(CONFLICT_GRAPH_FILE_NAME, \"w\");\n fprintf(graph_file, \"digraph G {\\n\");\n \n \/\/ Arêtes\n deductions.print_edges(graph_file,aff) ;\n \n \/\/ Noeuds\n deductions.print_UIP(graph_file,aff,root,literal) ;\n fprintf(graph_file, \"\\t%d [color = \\\"red\\\"];\\n\", literal);\n fprintf(graph_file, \"}\\n\");\n fclose(graph_file);\n}\n\nunsigned int cl_interact(const Deductions &deductions, const Affectation &aff, int last_bet, int literal, bool *with_proof) {\n char mode;\n unsigned int steps;\n assert(deductions.has_variable(abs(literal)));\n std::cout << \"Conflict on literal \" << literal << \". Action? [g\/r\/c\/s\/t] \";\n assert(with_proof);\n *with_proof = false;\n while (true) {\n std::cin >> mode;\n switch (mode) {\n case 'g':\n make_conflict_graph(deductions, aff, last_bet, literal);\n return 1;\n case 'r':\n if (!WITH_CL) {\n std::cout << \"Clause learning is not enabled. Use -CL. [g\/r\/c\/s\/t]. \" << std::endl;\n continue;\n }\n *with_proof = true;\n return 0;\n case 'c':\n return 1;\n case 's':\n std::cin >> steps;\n return steps;\n case 't':\n CL_INTERACT = false;\n return 0;\n default:\n std::cout << \"Invalid character [g\/r\/c\/s\/t]. \";\n continue;\n }\n }\n}\n\nstd::shared_ptr learn_clause(const Deductions &deductions, const std::vector> &mem, const Affectation &aff, int nb_variables, int literal, CLProof *proof) {\n (void) aff;\n long unsigned int mem_top = mem.size()-1; \/\/ The index in the memory “stack” of the literal we are making the resolution on.\n std::unordered_set clause(deductions.get_deduced_from(literal)), clause2;\n assert(clause.find(literal) != clause.end());\n mem_top--;\n while (mem.at(mem_top).second) {\n literal = mem.at(mem_top).first;\n assert(mem.at(mem_top).first == literal);\n clause2 = deductions.get_deduced_from(literal); \/\/ This is the clause we will make the resolution with\n if (!clause2.size())\n break;\n\n if (clause.find(-literal) == clause.end())\n break;\n assert(clause2.find(literal) != clause.end());\n \/\/ Resolution\n \/\/ TODO: Replace 0 with the clause id.\n proof->insert_top(literal, std::make_pair(0, Clause(nb_variables, clause)), std::make_pair(0, Clause(nb_variables, clause2)));\n clause.erase(clause.find(-literal));\n clause2.erase(clause2.find(literal));\n clause.insert(clause2.begin(), clause2.end());\n\n mem_top--;\n }\n return std::shared_ptr(new Clause(nb_variables, clause));\n}\n\nAffectation* satsolver::solve(Formula *formula) {\n int literal;\n bool with_proof;\n CLProof *proof;\n unsigned int clause_id;\n bool contains_false_clause;\n unsigned int skip_conflicts = 1; \/\/ Number of conflicts we will skip before showing another prompt\n int last_bet = 0; \/\/ Used for generating the graph.\n while(formula->get_aff()->get_nb_unknown() != 0 && !formula->only_true_clauses(NULL)) {\n formula->get_ded()->print() ;\n if(!WITH_WL && (literal = formula->monome(&clause_id))) {\n \/\/ We set the clause identified by “claused_id” as the one which\n \/\/ made us deduce the value of the literal.\n formula->deduce_true(literal, clause_id); \/\/ Return value ignored, WITH_WL is false\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n else if((literal = formula->isolated_literal(&clause_id))) {\n\t formula->deduce_true(literal,-1) ;\n }\n else {\n literal = formula->choose_literal(HEURISTIC) ;\n if (WITH_WL)\n contains_false_clause = !formula->bet_true(literal);\n else {\n formula->bet_true(literal);\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n last_bet = literal;\n }\n while(contains_false_clause) {\n if (CL_INTERACT && --skip_conflicts == 0) {\n assert(last_bet);\n skip_conflicts = cl_interact(*formula->get_ded(), formula->get_aff(), last_bet, literal, &with_proof);\n }\n if (WITH_CL) {\n proof = new CLProof(formula->to_clauses_vector()[clause_id]);\n learn_clause(*formula->get_ded(), formula->get_mem(), formula->get_aff(), formula->get_nb_variables(), literal, proof);\n if (with_proof)\n proof->to_latex_file(CL_PROOF_FILE_NAME);\n delete proof;\n }\n literal = formula->back() ;\n last_bet = -last_bet;\n if(literal == 0)\n throw Conflict() ;\n if (WITH_WL)\n contains_false_clause = !formula->deduce_false(literal,-1);\n else {\n formula->deduce_false(literal, -1);\n contains_false_clause = formula->contains_false_clause(&clause_id);\n }\n }\n }\n return formula->get_aff() ;\n}\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2007 Tokutek Inc. All rights reserved.\"\n#ident \"$Id: perf_nop.cc 45903 2012-07-19 13:06:39Z leifwalsh $\"\n#include \"test.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"threaded_stress_test_helpers.h\"\n\n\/\/ The intent of this test is to measure the throughput of the test infrastructure executing a nop\n\/\/ on multiple threads.\n\nDB_TXN** txns;\nint num_txns;\n\nstatic int commit_and_create_txn(\n DB_TXN* UU(txn), \n ARG arg, \n void* UU(operation_extra), \n void* UU(stats_extra)\n ) \n{\n int rand_txn_id = random() % num_txns;\n int r = txns[rand_txn_id]->commit(txns[rand_txn_id], 0);\n CKERR(r);\n r = arg->env->txn_begin(arg->env, 0, &txns[rand_txn_id], arg->txn_type); \n CKERR(r);\n return 0;\n}\n\nstatic void\nstress_table(DB_ENV* env, DB** dbp, struct cli_args *cli_args) {\n if (verbose) printf(\"starting running of stress\\n\");\n\n num_txns = cli_args->txn_size;\n XCALLOC_N(num_txns, txns);\n for (int i = 0; i < num_txns; i++) {\n int r = env->txn_begin(env, 0, &txns[i], DB_TXN_SNAPSHOT); \n CKERR(r);\n }\n \n struct arg myarg;\n arg_init(&myarg, dbp, env, cli_args);\n myarg.operation = commit_and_create_txn;\n \n run_workers(&myarg, 1, cli_args->time_of_test, false, cli_args);\n\n for (int i = 0; i < num_txns; i++) {\n int chk_r = txns[i]->commit(txns[i], 0);\n CKERR(chk_r);\n }\n toku_free(txns);\n num_txns = 0;\n}\n\nint\ntest_main(int argc, char *const argv[]) {\n num_txns = 0;\n txns = NULL;\n struct cli_args args = get_default_args_for_perf();\n parse_stress_test_args(argc, argv, &args);\n args.single_txn = true;\n \/\/ this test is all about transactions, make the DB small\n args.num_elements = 1;\n args.num_DBs= 1; \n stress_test_main(&args);\n return 0;\n}\nrefs #5404, add a comment explaining what the test does\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2007 Tokutek Inc. All rights reserved.\"\n#ident \"$Id: perf_nop.cc 45903 2012-07-19 13:06:39Z leifwalsh $\"\n#include \"test.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"threaded_stress_test_helpers.h\"\n\n\/\/ The intent of this test is to measure how fast a single thread can \n\/\/ commit and create transactions when there exist N transactions.\n\nDB_TXN** txns;\nint num_txns;\n\nstatic int commit_and_create_txn(\n DB_TXN* UU(txn), \n ARG arg, \n void* UU(operation_extra), \n void* UU(stats_extra)\n ) \n{\n int rand_txn_id = random() % num_txns;\n int r = txns[rand_txn_id]->commit(txns[rand_txn_id], 0);\n CKERR(r);\n r = arg->env->txn_begin(arg->env, 0, &txns[rand_txn_id], arg->txn_type); \n CKERR(r);\n return 0;\n}\n\nstatic void\nstress_table(DB_ENV* env, DB** dbp, struct cli_args *cli_args) {\n if (verbose) printf(\"starting running of stress\\n\");\n\n num_txns = cli_args->txn_size;\n XCALLOC_N(num_txns, txns);\n for (int i = 0; i < num_txns; i++) {\n int r = env->txn_begin(env, 0, &txns[i], DB_TXN_SNAPSHOT); \n CKERR(r);\n }\n \n struct arg myarg;\n arg_init(&myarg, dbp, env, cli_args);\n myarg.operation = commit_and_create_txn;\n \n run_workers(&myarg, 1, cli_args->time_of_test, false, cli_args);\n\n for (int i = 0; i < num_txns; i++) {\n int chk_r = txns[i]->commit(txns[i], 0);\n CKERR(chk_r);\n }\n toku_free(txns);\n num_txns = 0;\n}\n\nint\ntest_main(int argc, char *const argv[]) {\n num_txns = 0;\n txns = NULL;\n struct cli_args args = get_default_args_for_perf();\n parse_stress_test_args(argc, argv, &args);\n args.single_txn = true;\n \/\/ this test is all about transactions, make the DB small\n args.num_elements = 1;\n args.num_DBs= 1; \n stress_test_main(&args);\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"sotarviclient.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"logger.h\"\n#include \"types.h\"\n\nchar service_names[6][12] = {\"notify\", \"start\", \"chunk\",\n \"finish\", \"getpackages\", \"abort\"};\n\nvoid callbackWrapper(int fd, void *service_data, const char *parameters) {\n (void)fd;\n SotaRVIClient *client = (SotaRVIClient *)((void **)service_data)[0];\n std::string service((char *)((void **)service_data)[1]);\n Json::Reader reader;\n Json::Value json;\n reader.parse(parameters, json);\n\n if (service == \"notify\") {\n client->sendEvent(\n boost::make_shared(event::UpdateAvailable(\n data::UpdateAvailable::fromJson(json[0][\"update_available\"]))));\n } else if (service == \"start\") {\n client->invokeAck(json[0][\"update_id\"].asString());\n } else if (service == \"chunk\") {\n client->saveChunk(json[0]);\n } else if (service == \"finish\") {\n client->downloadComplete(json[0]);\n } else if (service == \"getpackages\") {\n LOGGER_LOG(LVL_error, \"service \" << service << \"not implemented yet\");\n }\n}\n\nSotaRVIClient::SotaRVIClient(const Config &config_in,\n event::Channel *events_channel_in)\n : config(config_in), events_channel(events_channel_in) {\n std::string client_config(\".\/config\/\" + config.rvi.client_config);\n rvi = rviInit(const_cast(client_config.c_str()));\n if (!rvi) {\n throw std::runtime_error(\"cannot initialize rvi with config file \" +\n client_config);\n }\n connection = rviConnect(rvi, config.rvi.node_host.c_str(),\n config.rvi.node_port.c_str());\n\n if (connection <= 0) {\n LOGGER_LOG(LVL_error, \"cannot connect to rvi node\");\n }\n unsigned int services_count =\n sizeof(service_names) \/ sizeof(service_names[0]);\n void *pointers[2];\n pointers[0] = (void *)(this);\n for (unsigned int i = 0; i < services_count; ++i) {\n pointers[1] = (void *)service_names[i];\n int stat = rviRegisterService(\n rvi, (std::string(\"sota\/\") + service_names[i]).c_str(), callbackWrapper,\n pointers, sizeof(pointers));\n if (stat) {\n LOGGER_LOG(LVL_error, \"unable to register \" << service_names[i]);\n }\n services[service_names[i]] =\n std::string(\"genivi.org\/\" + config.device.uuid + \"\/\") +\n service_names[i];\n }\n LOGGER_LOG(LVL_info, \"rvi services registered!!\");\n boost::thread(boost::bind(&SotaRVIClient::run, this));\n}\n\nvoid SotaRVIClient::sendEvent(\n const boost::shared_ptr &event) {\n *events_channel << event;\n}\n\nvoid SotaRVIClient::run() {\n while (true) {\n int result = rviProcessInput(rvi, &connection, 1);\n if (result != 0) {\n LOGGER_LOG(LVL_error, \"rviProcessInput error: \" << result);\n }\n }\n}\n\nvoid SotaRVIClient::startDownload(const data::UpdateRequestId &update_id) {\n Json::Value value;\n value[\"device\"] = config.device.uuid;\n value[\"update_id\"] = update_id;\n value[\"services\"] = services;\n Json::Value params(Json::arrayValue);\n params.append(value);\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/start\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/start, return code is \"\n << stat);\n}\n\nvoid SotaRVIClient::invokeAck(const std::string &update_id) {\n std::vector chunks = chunks_map[update_id];\n\n Json::Value value;\n value[\"device\"] = config.device.uuid;\n value[\"update_id\"] = update_id;\n value[\"chunks\"] = Json::arrayValue;\n\n for (std::vector::iterator it = chunks.begin(); it != chunks.end();\n ++it) {\n value[\"chunks\"].append(*it);\n }\n Json::Value params(Json::arrayValue);\n params.append(value);\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/ack\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/ack, return code is \"\n << stat);\n}\n\nvoid SotaRVIClient::saveChunk(const Json::Value &chunk_json) {\n std::string b64_text = chunk_json[\"bytes\"].asString();\n\n unsigned long long paddChars =\n std::count(b64_text.begin(), b64_text.end(), '=');\n std::replace(b64_text.begin(), b64_text.end(), '=', 'A');\n std::string output(base64_to_bin(b64_text.begin()),\n base64_to_bin(b64_text.end()));\n output.erase(output.end() - paddChars, output.end());\n\n std::ofstream update_file(\n config.device.packages_dir + chunk_json[\"update_id\"].asString(),\n std::ios::out | std::ios::app | std::ios::binary);\n update_file << output;\n update_file.close();\n\n chunks_map[chunk_json[\"update_id\"].asString()].push_back(\n chunk_json[\"index\"].asInt());\n invokeAck(chunk_json[\"update_id\"].asString());\n}\n\nvoid SotaRVIClient::downloadComplete(const Json::Value ¶meters) {\n data::DownloadComplete download_complete;\n download_complete.update_id = parameters[\"update_id\"].asString();\n download_complete.signature = parameters[\"signature\"].asString();\n download_complete.update_image =\n config.device.packages_dir + download_complete.update_id;\n sendEvent(boost::make_shared(download_complete));\n}\n\nvoid SotaRVIClient::sendUpdateReport(data::UpdateReport update_report) {\n Json::Value params(Json::arrayValue);\n params.append(update_report.toJson());\n\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/report\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/report, return code is \"\n << stat);\n chunks_map.erase(update_report.update_id);\n}\nwait 5 seconds on RviProcessInput error#include \"sotarviclient.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"logger.h\"\n#include \"types.h\"\n\nchar service_names[6][12] = {\"notify\", \"start\", \"chunk\",\n \"finish\", \"getpackages\", \"abort\"};\n\nvoid callbackWrapper(int fd, void *service_data, const char *parameters) {\n (void)fd;\n SotaRVIClient *client = (SotaRVIClient *)((void **)service_data)[0];\n std::string service((char *)((void **)service_data)[1]);\n Json::Reader reader;\n Json::Value json;\n reader.parse(parameters, json);\n\n if (service == \"notify\") {\n client->sendEvent(\n boost::make_shared(event::UpdateAvailable(\n data::UpdateAvailable::fromJson(json[0][\"update_available\"]))));\n } else if (service == \"start\") {\n client->invokeAck(json[0][\"update_id\"].asString());\n } else if (service == \"chunk\") {\n client->saveChunk(json[0]);\n } else if (service == \"finish\") {\n client->downloadComplete(json[0]);\n } else if (service == \"getpackages\") {\n LOGGER_LOG(LVL_error, \"service \" << service << \"not implemented yet\");\n }\n}\n\nSotaRVIClient::SotaRVIClient(const Config &config_in,\n event::Channel *events_channel_in)\n : config(config_in), events_channel(events_channel_in) {\n std::string client_config(\".\/config\/\" + config.rvi.client_config);\n rvi = rviInit(const_cast(client_config.c_str()));\n if (!rvi) {\n throw std::runtime_error(\"cannot initialize rvi with config file \" +\n client_config);\n }\n connection = rviConnect(rvi, config.rvi.node_host.c_str(),\n config.rvi.node_port.c_str());\n\n if (connection <= 0) {\n LOGGER_LOG(LVL_error, \"cannot connect to rvi node\");\n }\n unsigned int services_count =\n sizeof(service_names) \/ sizeof(service_names[0]);\n void *pointers[2];\n pointers[0] = (void *)(this);\n for (unsigned int i = 0; i < services_count; ++i) {\n pointers[1] = (void *)service_names[i];\n int stat = rviRegisterService(\n rvi, (std::string(\"sota\/\") + service_names[i]).c_str(), callbackWrapper,\n pointers, sizeof(pointers));\n if (stat) {\n LOGGER_LOG(LVL_error, \"unable to register \" << service_names[i]);\n }\n services[service_names[i]] =\n std::string(\"genivi.org\/\" + config.device.uuid + \"\/\") +\n service_names[i];\n }\n LOGGER_LOG(LVL_info, \"rvi services registered!!\");\n boost::thread(boost::bind(&SotaRVIClient::run, this));\n}\n\nvoid SotaRVIClient::sendEvent(\n const boost::shared_ptr &event) {\n *events_channel << event;\n}\n\nvoid SotaRVIClient::run() {\n while (true) {\n int result = rviProcessInput(rvi, &connection, 1);\n if (result != 0) {\n LOGGER_LOG(LVL_error, \"rviProcessInput error: \" << result);\n sleep(5);\n }\n }\n}\n\nvoid SotaRVIClient::startDownload(const data::UpdateRequestId &update_id) {\n Json::Value value;\n value[\"device\"] = config.device.uuid;\n value[\"update_id\"] = update_id;\n value[\"services\"] = services;\n Json::Value params(Json::arrayValue);\n params.append(value);\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/start\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/start, return code is \"\n << stat);\n}\n\nvoid SotaRVIClient::invokeAck(const std::string &update_id) {\n std::vector chunks = chunks_map[update_id];\n\n Json::Value value;\n value[\"device\"] = config.device.uuid;\n value[\"update_id\"] = update_id;\n value[\"chunks\"] = Json::arrayValue;\n\n for (std::vector::iterator it = chunks.begin(); it != chunks.end();\n ++it) {\n value[\"chunks\"].append(*it);\n }\n Json::Value params(Json::arrayValue);\n params.append(value);\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/ack\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/ack, return code is \"\n << stat);\n}\n\nvoid SotaRVIClient::saveChunk(const Json::Value &chunk_json) {\n std::string b64_text = chunk_json[\"bytes\"].asString();\n\n unsigned long long paddChars =\n std::count(b64_text.begin(), b64_text.end(), '=');\n std::replace(b64_text.begin(), b64_text.end(), '=', 'A');\n std::string output(base64_to_bin(b64_text.begin()),\n base64_to_bin(b64_text.end()));\n output.erase(output.end() - paddChars, output.end());\n\n std::ofstream update_file(\n config.device.packages_dir + chunk_json[\"update_id\"].asString(),\n std::ios::out | std::ios::app | std::ios::binary);\n update_file << output;\n update_file.close();\n\n chunks_map[chunk_json[\"update_id\"].asString()].push_back(\n chunk_json[\"index\"].asInt());\n invokeAck(chunk_json[\"update_id\"].asString());\n}\n\nvoid SotaRVIClient::downloadComplete(const Json::Value ¶meters) {\n data::DownloadComplete download_complete;\n download_complete.update_id = parameters[\"update_id\"].asString();\n download_complete.signature = parameters[\"signature\"].asString();\n download_complete.update_image =\n config.device.packages_dir + download_complete.update_id;\n sendEvent(boost::make_shared(download_complete));\n}\n\nvoid SotaRVIClient::sendUpdateReport(data::UpdateReport update_report) {\n Json::Value params(Json::arrayValue);\n params.append(update_report.toJson());\n\n int stat = rviInvokeService(rvi, \"genivi.org\/backend\/sota\/report\",\n Json::FastWriter().write(params).c_str());\n LOGGER_LOG(LVL_info, \"invoked genivi.org\/backend\/sota\/report, return code is \"\n << stat);\n chunks_map.erase(update_report.update_id);\n}\n<|endoftext|>"} {"text":"\/**\n * @file Frame.cpp\n *\n * Handling signal frames.\n *\n * This file is part of the Aquila DSP library.\n * Aquila is free software, licensed under the MIT\/X11 License. A copy of\n * the license is provided with the library in the LICENSE file.\n *\n * @package Aquila\n * @version 3.0.0-dev\n * @author Zbigniew Siciarz\n * @date 2007-2010\n * @license http:\/\/www.opensource.org\/licenses\/mit-license.php MIT\n * @since 0.2.2\n *\/\n\n#include \"Frame.h\"\n\nnamespace Aquila\n{\n \/**\n * Creates the frame object - sets signal source and frame boundaries.\n *\n * Frame should not change original data, so the source is a const\n * reference.\n *\n * @param source const reference to signal source\n * @param indexBegin position of first sample of this frame in the source\n * @param indexEnd position of last sample of this frame in the source\n *\/\n Frame::Frame(const SignalSource& source, unsigned int indexBegin,\n unsigned int indexEnd):\n m_source(&source), m_begin(indexBegin), m_end(indexEnd)\n {\n }\n\n \/**\n * Copy constructor.\n *\n * @param other reference to another frame\n *\/\n Frame::Frame(const Frame &other):\n m_source(other.m_source), m_begin(other.m_begin), m_end(other.m_end)\n {\n }\n\n \/**\n * Assignes another frame to this one using copy-and-swap idiom.\n *\n * @param other reference to another frame\n * @return reference to the current object\n *\/\n Frame& Frame::operator=(const Frame& other)\n {\n Frame temp(other);\n swap(temp);\n\n return *this;\n }\n}\nAdded frame size clipping when the frame end points beyond last source sample.\/**\n * @file Frame.cpp\n *\n * Handling signal frames.\n *\n * This file is part of the Aquila DSP library.\n * Aquila is free software, licensed under the MIT\/X11 License. A copy of\n * the license is provided with the library in the LICENSE file.\n *\n * @package Aquila\n * @version 3.0.0-dev\n * @author Zbigniew Siciarz\n * @date 2007-2010\n * @license http:\/\/www.opensource.org\/licenses\/mit-license.php MIT\n * @since 0.2.2\n *\/\n\n#include \"Frame.h\"\n\nnamespace Aquila\n{\n \/**\n * Creates the frame object - sets signal source and frame boundaries.\n *\n * Frame should not change original data, so the source is a const\n * reference.\n *\n * @param source const reference to signal source\n * @param indexBegin position of first sample of this frame in the source\n * @param indexEnd position of last sample of this frame in the source\n *\/\n Frame::Frame(const SignalSource& source, unsigned int indexBegin,\n unsigned int indexEnd):\n m_source(&source), m_begin(indexBegin),\n m_end((indexEnd > source.getSamplesCount()) ? source.getSamplesCount() : indexEnd)\n {\n }\n\n \/**\n * Copy constructor.\n *\n * @param other reference to another frame\n *\/\n Frame::Frame(const Frame &other):\n m_source(other.m_source), m_begin(other.m_begin), m_end(other.m_end)\n {\n }\n\n \/**\n * Assignes another frame to this one using copy-and-swap idiom.\n *\n * @param other reference to another frame\n * @return reference to the current object\n *\/\n Frame& Frame::operator=(const Frame& other)\n {\n Frame temp(other);\n swap(temp);\n\n return *this;\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\/*\n* Author(s):\n* - Chris Kilner \n* - Cedric Gestes \n*\n* Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n\n#ifndef _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\n#define _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\n\n# include \n# include \n# include \n# include \n# include \n# include \n# include \n\/\/# include \n\nnamespace qi {\n namespace detail {\n\n#define _QI_SIMPLE_SIGNATURE(THETYPE, THENAME) \\\n template <> \\\n struct signature { \\\n static std::string &value(std::string &val) { \\\n val += THENAME; \\\n return val; \\\n } \\\n };\n\n#define _QI_LIST_SIGNATURE(TYPE) \\\n template \\\n struct signature< TYPE > { \\\n static std::string &value(std::string &val) { \\\n val += \"[\"; \\\n qi::detail::signature::value(val); \\\n val += \"]\"; \\\n return val; \\\n } \\\n };\n\n#define _QI_MAP_SIGNATURE(TYPE) \\\n template \\\n struct signature< TYPE > { \\\n static std::string &value(std::string &val) { \\\n val += \"{\"; \\\n qi::detail::signature::value(val); \\\n qi::detail::signature::value(val); \\\n val += \"}\"; \\\n return val; \\\n } \\\n };\n\n\n template \n struct signature {\n static std::string &value(std::string &val) {\n val += \"UNKNOWN\";\n return val;\n }\n };\n\n _QI_SIMPLE_SIGNATURE(void , \"v\");\n _QI_SIMPLE_SIGNATURE(bool , \"b\");\n _QI_SIMPLE_SIGNATURE(char , \"c\");\n _QI_SIMPLE_SIGNATURE(int , \"i\");\n _QI_SIMPLE_SIGNATURE(float , \"f\");\n _QI_SIMPLE_SIGNATURE(double , \"d\");\n _QI_SIMPLE_SIGNATURE(qi::Value , \"m\");\n\n \/\/pointer\n template \n struct signature >::type> {\n static std::string &value(std::string &val) {\n qi::detail::signature::value(val);\n val += \"*\"; return val;\n }\n };\n\n \/\/& and const are not used for function signature, it's only a compiler detail\n template \n struct signature {\n static std::string &value(std::string &val) {\n return qi::detail::signature::value(val);\n }\n };\n\n template \n struct signature {\n static std::string &value(std::string &val) {\n return qi::detail::signature::value(val);\n }\n };\n\n }\n}\n\n#endif \/\/ _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\nsignature: X instead of UNKNOWN on error#pragma once\n\/*\n* Author(s):\n* - Chris Kilner \n* - Cedric Gestes \n*\n* Copyright (C) 2010 Aldebaran Robotics\n*\/\n\n\n#ifndef _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\n#define _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\n\n# include \n# include \n# include \n# include \n# include \n# include \n# include \n\/\/# include \n\nnamespace qi {\n namespace detail {\n\n#define _QI_SIMPLE_SIGNATURE(THETYPE, THENAME) \\\n template <> \\\n struct signature { \\\n static std::string &value(std::string &val) { \\\n val += THENAME; \\\n return val; \\\n } \\\n };\n\n#define _QI_LIST_SIGNATURE(TYPE) \\\n template \\\n struct signature< TYPE > { \\\n static std::string &value(std::string &val) { \\\n val += \"[\"; \\\n qi::detail::signature::value(val); \\\n val += \"]\"; \\\n return val; \\\n } \\\n };\n\n#define _QI_MAP_SIGNATURE(TYPE) \\\n template \\\n struct signature< TYPE > { \\\n static std::string &value(std::string &val) { \\\n val += \"{\"; \\\n qi::detail::signature::value(val); \\\n qi::detail::signature::value(val); \\\n val += \"}\"; \\\n return val; \\\n } \\\n };\n\n\n template \n struct signature {\n static std::string &value(std::string &val) {\n val += \"X\";\n return val;\n }\n };\n\n _QI_SIMPLE_SIGNATURE(void , \"v\");\n _QI_SIMPLE_SIGNATURE(bool , \"b\");\n _QI_SIMPLE_SIGNATURE(char , \"c\");\n _QI_SIMPLE_SIGNATURE(int , \"i\");\n _QI_SIMPLE_SIGNATURE(float , \"f\");\n _QI_SIMPLE_SIGNATURE(double , \"d\");\n _QI_SIMPLE_SIGNATURE(qi::Value , \"m\");\n\n \/\/pointer\n template \n struct signature >::type> {\n static std::string &value(std::string &val) {\n qi::detail::signature::value(val);\n val += \"*\"; return val;\n }\n };\n\n \/\/& and const are not used for function signature, it's only a compiler detail\n template \n struct signature {\n static std::string &value(std::string &val) {\n return qi::detail::signature::value(val);\n }\n };\n\n template \n struct signature {\n static std::string &value(std::string &val) {\n return qi::detail::signature::value(val);\n }\n };\n\n }\n}\n\n#endif \/\/ _QIMESSAGING_SIGNATURE_DETAIL_TYPE_SIGNATURE_HPP_\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \"type.hpp\"\n\nnamespace spn {\n\t\/\/! 表現に何ビット使うか計算\n\t\/*! +1すればMSBの取得にもつかえる *\/\n\ttemplate \n\tstruct NBits {\n\t\tenum { result=1+NBits<((N)>>1)>::result };\n\t};\n\ttemplate <>\n\tstruct NBits<0> {\n\t\tenum { result=1 };\n\t};\n\ttemplate <>\n\tstruct NBits<1> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! NをLで何回割れるか(と、その余り)\n\ttemplate \n\tstruct NDivide {\n\t\ttypedef NDivide Lower;\n\t\tenum { result=Lower::result + ((N>=L) ? 1 : 0),\n\t\t\t\tsum=N + Lower::sum,\n\t\t\t\todd=Lower::odd };\n\t};\n\ttemplate \n\tstruct NDivide<0, L, N2> {\n\t\tenum { result=0,\n\t\t\t\tsum=0,\n\t\t\t\todd=N2 };\n\t};\n\n\t\/\/! コンパイル時累乗\n\ttemplate \n\tstruct NPow {\n\t\tenum { result=NPow::result * N };\n\t};\n\ttemplate \n\tstruct NPow {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! 引数のペアを全てXORしたものをORする\n\tinline int X_OrArgs() { return 0; }\n\ttemplate \n\tinline T X_OrArgs(const T& t0, const T& t1, Args... args) {\n\t\treturn (t0^t1) | X_OrArgs(args...);\n\t}\n\n\t\/\/! 定数Nの使用ビット\n\ttemplate \n\tstruct BitLength {\n\t\tenum { length = BitLength<(N>>1)>::length + 1 };\n\t};\n\ttemplate <>\n\tstruct BitLength<0> {\n\t\tenum { length = 0 };\n\t};\n\n\t\/\/! ビットフィールド定義用\n\ttemplate \n\tstruct BitF {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t};\n\t\/\/! 特定のビットを対象として値を取得 & 代入\n\t\/*! \\param T 値を保持する型 (unsigned)\n\t * \t\\param OFS ビットオフセット\n\t * \t\\param LEN ビット長 *\/\n\ttemplate \n\tclass BitOp {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t\tT&\t_value;\n\t\tconstexpr static T MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits;\n\t\tconstexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\tpublic:\n\t\ttemplate \n\t\tBitOp(P* ptr): _value(*(T*)ptr) {}\n\t\tBitOp(T* ptr): _value(*ptr) {}\n\t\tBitOp(T& ref): _value(ref) {}\n\n\t\ttemplate \n\t\tBitOp& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_value &= ~MASK;\n\t\t\t_value |= (T(v)<> OFS) & MASKLOW;\n\t\t}\n\t};\n\t\/\/! ワードに対するビット操作\n\t\/*! \\param WORD 値を保持する型\n\t * \t\\param OFS 下位ビット位置\n\t * \t\\param LEN 処理対象ビット幅 *\/\n\ttemplate \n\tclass BitSub {\n\t\tconst static WORD MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\tusing Word = WORD;\n\t\tWord&\t_word;\n\n\tpublic:\n\t\tBitSub(Word& w): _word(w) {}\n\n\t\ttemplate \n\t\tBitSub& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_word &= ~MASK;\n\t\t\t_word |= (Word(v)<> OFS) & MASKLOW;\n\t\t}\n\t\t\/\/! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目\n\t\ttemplate \n\t\tvoid swap(BitSub& bs) noexcept {\n\t\t\tWord val0(*this);\n\t\t\t(*this) = Word(bs);\n\t\t\tbs = val0;\n\t\t}\n\t};\n\t\/\/! テンプレートにてビットフィールドを定義\n\t\/*! \\param T 値を保持する型\n\t \\*param Args ビットフィールドを定義するBitOpクラス *\/\n\ttemplate \n\tstruct BitDef : CType {\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits;\n\t\tconstexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\t\tusing Word = T;\n\t};\n\t\/\/! ビットフィールドテンプレートクラス\n\t\/*! \\example\n\t\tstruct MyDef : BitDef, BitF<14,6>, BitF<20,12>> {\t
\n\t\t\t\tenum { VAL0, VAL1, VAL2 }; };\t\t\t\t\t\t\t\t\t
\n\t\tusing Value = BitField;\t\t\t\t\t\t\t\t\t\t\t
\n\t\tValue value;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\tvalue.at() = 128;\t\t\t\t\t\t\t\t\t\t\t
\n\t\tint toGet = value.at();\n\n\t\t\\param BF BitDefクラス *\/\n\ttemplate \n\tstruct BitField : BF {\n\t\t\/\/ BF(CTypes)から総サイズとオフセット計算\n\t\tconstexpr static int maxbit = BF::template Size<>::maxbit,\n\t\t\t\t\t\t\tbuffsize = ((maxbit-1)\/8)+1;\n\t\tusing Word = typename BF::Word;\n\t\tconstexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {};\n\n\t\tWord _word;\n\n\t\tBitField() = default;\n\t\tBitField(const BitField& bf): _word(bf.value()) {}\n\t\tBitField(const Word& w): _word(w) {}\n\t\tWord& value() { return _word; }\n\t\tconst Word& value() const { return _word; }\n\n\t\ttemplate \n\t\tusing BFAt = typename BF::template At::type;\n\t\ttemplate \n\t\tusing BitSubT = BitSub::offset, BFAt::length>;\n\n\t\t\/\/! ビット領域参照\n\t\ttemplate \n\t\tBitSubT at() {\n\t\t\treturn BitSubT(_word);\n\t\t}\n\t\t\/\/! ビットフィールド値取得\n\t\ttemplate \n\t\tWord at() const {\n\t\t\treturn BitSubT::get(_word);\n\t\t}\n\t\t\/\/! ビット幅マスク取得\n\t\ttemplate \n\t\tstatic Word length_mask() {\n\t\t\treturn (Word(1) << BFAt::length) - 1;\n\t\t}\n\t\t\/\/! ビットマスク取得\n\t\ttemplate \n\t\tstatic Word mask() {\n\t\t\tauto ret = length_mask();\n\t\t\treturn ret << BFAt::offset;\n\t\t}\n\n\t\t\/\/! ビットフィールドで使う場所以外をゼロクリアした値を取得\n\t\tWord cleanedValue() const {\n\t\t\tconstexpr Word msk = (1 << maxbit)-1;\n\t\t\treturn value() & msk;\n\t\t}\n\t\tbool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); }\n\t\tbool operator != (const BitField& bf) const { return !(this->operator == (bf)); }\n\t\tbool operator < (const BitField& bf) const {\n\t\t\treturn cleanedValue() < bf.cleanedValue();\n\t\t}\n\t};\n\n\t\/\/! コンパイル時計算\n\tnamespace CTBit {\n\t\ttemplate \n\t\tstruct MSB_N { constexpr static int result = 1 + MSB_N<(N >> 1)>::result; };\n\t\ttemplate <>\n\t\tstruct MSB_N<1> { constexpr static int result = 0; };\n\t\ttemplate <>\n\t\tstruct MSB_N<0> { constexpr static int result = 0; };\n\t\ttemplate \n\t\tstruct LowClear { constexpr static unsigned int result = 1 << MSB_N::result; };\n\t};\n\tstruct Bit {\n\t\tstatic bool Check(uint32_t val, uint32_t flag) {\n\t\t\treturn val & flag;\n\t\t}\n\t\tstatic void Clear(uint32_t& val, uint32_t flag) {\n\t\t\tval &= ~flag;\n\t\t}\n\t\tstatic void Set(uint32_t& val, uint32_t flag) {\n\t\t\tval |= flag;\n\t\t}\n\t\t\/\/! ビットチェックした結果を返し、ビットは消去する\n\t\tstatic bool ChClear(uint32_t& val, uint32_t flag) {\n\t\t\tbool bRet = Check(val, flag);\n\t\t\tClear(val, flag);\n\t\t\treturn bRet;\n\t\t}\n\t\t\/\/! 入力値の一番左のビットだけを残す\n\t\ttemplate ::value>::type*>\n\t\tstatic T LowClear(T x) {\n\t\t\tx = x | (x >> 1);\n\t\t\tx = x | (x >> 2);\n\t\t\tx = x | (x >> 4);\n\t\t\tx = x | (x >> 8);\n\t\t\tx = x | (x >>16);\n\t\t\treturn x & ~(x>>1);\n\t\t}\n\t\t\/\/! ビットが幾つ立っているか数える\n\t\tstatic int Count(uint32_t v) {\n\t\t\tuint32_t tmp = v & 0xaaaaaaaa;\n\t\t\tv &= 0x55555555;\n\t\t\tv = v + (tmp >> 1);\n\t\t\ttmp = v & 0xcccccccc;\n\t\t\tv &= 0x33333333;\n\t\t\tv = v + (tmp >> 2);\n\t\t\ttmp = v & 0xf0f0f0f0;\n\t\t\tv &= 0x0f0f0f0f;\n\t\t\tv = v + (tmp >> 4);\n\t\t\ttmp = v & 0xff00ff00;\n\t\t\tv &= 0x00ff00ff;\n\t\t\tv = v + (tmp >> 8);\n\t\t\ttmp = v & 0xffff0000;\n\t\t\tv &= 0x0000ffff;\n\t\t\tv = v + (tmp >> 16);\n\t\t\treturn v;\n\t\t}\n\t\t\/\/! 入力値が0なら0, それ以外は~0を返す\n\t\tstatic int32_t ZeroOrFull(int32_t v) {\n\t\t\treturn (v | -v) >> 31;\n\t\t}\n\n\t\t\/\/ ビットの位置を計算\n\t\t#ifdef USEASM_BITSEARCH\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x01, %%eax;\"\n\t\t\t\t\t\"bsrl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x80000000, %%eax;\"\n\t\t\t\t\t\"bsfl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t#else\n\t\t\tconst static char NLRZ_TABLE[33];\n\t\t\t\/\/! most significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は0を返す *\/\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tx |= 0x01;\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27];\n\t\t\t}\n\t\t\t\/\/! least significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は31を返す *\/\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tx |= 0x80000000;\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27];\n\t\t\t}\n\t\t#endif\n\n\t\t\/\/! 32bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB32(uint32_t v) {\n\t\t\tuint32_t a = v<<24,\n\t\t\t\tb = (v&0xff00)<<8,\n\t\t\t\tc = (v>>8)&0xff00,\n\t\t\t\td = v>>24;\n\t\t\treturn a|b|c|d;\n\t\t}\n\t\t\/\/! 16bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB16(uint32_t v) {\n\t\t\tuint32_t a = (v>>8)&0xff,\n\t\t\t\tb = (v&0xff)<<8;\n\t\t\treturn a|b;\n\t\t}\n\t};\n}\nnamespace std {\n\ttemplate \n\tinline void swap(spn::BitSub&& b0, spn::BitSub&& b1) { b0.swap(b1); }\n\ttemplate \n\tinline void swap(spn::BitSub&& b0, spn::BitSub& b1) { b0.swap(b1); }\n\ttemplate \n\tinline void swap(spn::BitSub& b0, spn::BitSub&& b1) { b0.swap(b1); }\n}\nBitField: ビットマスクの生成箇所を修正#pragma once\n#include \n#include \n#include \"type.hpp\"\n\nnamespace spn {\n\t\/\/! 表現に何ビット使うか計算\n\t\/*! +1すればMSBの取得にもつかえる *\/\n\ttemplate \n\tstruct NBits {\n\t\tenum { result=1+NBits<((N)>>1)>::result };\n\t};\n\ttemplate <>\n\tstruct NBits<0> {\n\t\tenum { result=1 };\n\t};\n\ttemplate <>\n\tstruct NBits<1> {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! NをLで何回割れるか(と、その余り)\n\ttemplate \n\tstruct NDivide {\n\t\ttypedef NDivide Lower;\n\t\tenum { result=Lower::result + ((N>=L) ? 1 : 0),\n\t\t\t\tsum=N + Lower::sum,\n\t\t\t\todd=Lower::odd };\n\t};\n\ttemplate \n\tstruct NDivide<0, L, N2> {\n\t\tenum { result=0,\n\t\t\t\tsum=0,\n\t\t\t\todd=N2 };\n\t};\n\n\t\/\/! コンパイル時累乗\n\ttemplate \n\tstruct NPow {\n\t\tenum { result=NPow::result * N };\n\t};\n\ttemplate \n\tstruct NPow {\n\t\tenum { result=1 };\n\t};\n\n\t\/\/! 引数のペアを全てXORしたものをORする\n\tinline int X_OrArgs() { return 0; }\n\ttemplate \n\tinline T X_OrArgs(const T& t0, const T& t1, Args... args) {\n\t\treturn (t0^t1) | X_OrArgs(args...);\n\t}\n\n\t\/\/! 定数Nの使用ビット\n\ttemplate \n\tstruct BitLength {\n\t\tenum { length = BitLength<(N>>1)>::length + 1 };\n\t};\n\ttemplate <>\n\tstruct BitLength<0> {\n\t\tenum { length = 0 };\n\t};\n\n\t\/\/! ビットフィールド定義用\n\ttemplate \n\tstruct BitF {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t};\n\t\/\/! 特定のビットを対象として値を取得 & 代入\n\t\/*! \\param T 値を保持する型 (unsigned)\n\t * \t\\param OFS ビットオフセット\n\t * \t\\param LEN ビット長 *\/\n\ttemplate \n\tclass BitOp {\n\t\tenum { offset=OFS,\n\t\tlength=LEN };\n\t\tT&\t_value;\n\t\tconstexpr static T MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits;\n\t\tconstexpr static int Dummy[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\tpublic:\n\t\ttemplate \n\t\tBitOp(P* ptr): _value(*(T*)ptr) {}\n\t\tBitOp(T* ptr): _value(*ptr) {}\n\t\tBitOp(T& ref): _value(ref) {}\n\n\t\ttemplate \n\t\tBitOp& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_value &= ~MASK;\n\t\t\t_value |= (T(v)<> OFS) & MASKLOW;\n\t\t}\n\t};\n\t\/\/! ワードに対するビット操作\n\t\/*! \\param WORD 値を保持する型\n\t * \t\\param OFS 下位ビット位置\n\t * \t\\param LEN 処理対象ビット幅 *\/\n\ttemplate \n\tclass BitSub {\n\t\tconst static WORD MASKLOW = ((1 << LEN) - 1),\n\t\tMASK = MASKLOW << OFS;\n\t\tusing Word = WORD;\n\t\tWord&\t_word;\n\n\tpublic:\n\t\tBitSub(Word& w): _word(w) {}\n\n\t\ttemplate \n\t\tBitSub& operator = (const V v) {\n\t\t\t\/\/ ビットクリア\n\t\t\t_word &= ~MASK;\n\t\t\t_word |= (Word(v)<> OFS) & MASKLOW;\n\t\t}\n\t\t\/\/! 違う基本型やビット位置でも交換可能だが、サイズ違いは駄目\n\t\ttemplate \n\t\tvoid swap(BitSub& bs) noexcept {\n\t\t\tWord val0(*this);\n\t\t\t(*this) = Word(bs);\n\t\t\tbs = val0;\n\t\t}\n\t};\n\t\/\/! テンプレートにてビットフィールドを定義\n\t\/*! \\param T 値を保持する型\n\t \\*param Args ビットフィールドを定義するBitOpクラス *\/\n\ttemplate \n\tstruct BitDef : CType {\n\t\t\/\/ Tが非数値型だったりsignedな型ならコンパイルエラーを起こす\n\t\tusing Limits = std::numeric_limits;\n\t\tconstexpr static int UnsignedCheck[Limits::is_specialized && Limits::is_integer && !Limits::is_signed ? 0 : -1] = {};\n\n\t\tusing Word = T;\n\t};\n\t\/\/! ビットフィールドテンプレートクラス\n\t\/*! \\example\n\t\tstruct MyDef : BitDef, BitF<14,6>, BitF<20,12>> {\t
\n\t\t\t\tenum { VAL0, VAL1, VAL2 }; };\t\t\t\t\t\t\t\t\t
\n\t\tusing Value = BitField;\t\t\t\t\t\t\t\t\t\t\t
\n\t\tValue value;\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t
\n\t\tvalue.at() = 128;\t\t\t\t\t\t\t\t\t\t\t
\n\t\tint toGet = value.at();\n\n\t\t\\param BF BitDefクラス *\/\n\ttemplate \n\tstruct BitField : BF {\n\t\t\/\/ BF(CTypes)から総サイズとオフセット計算\n\t\tconstexpr static int maxbit = BF::template Size<>::maxbit,\n\t\t\t\t\t\t\tbuffsize = ((maxbit-1)\/8)+1;\n\t\tusing Word = typename BF::Word;\n\t\tconstexpr static int WordCheck[buffsize > sizeof(Word) ? -1 : 0] = {};\n\n\t\tWord _word;\n\n\t\tBitField() = default;\n\t\tBitField(const BitField& bf): _word(bf.value()) {}\n\t\tBitField(const Word& w): _word(w) {}\n\t\tWord& value() { return _word; }\n\t\tconst Word& value() const { return _word; }\n\n\t\ttemplate \n\t\tusing BFAt = typename BF::template At::type;\n\t\ttemplate \n\t\tusing BitSubT = BitSub::offset, BFAt::length>;\n\n\t\t\/\/! ビット領域参照\n\t\ttemplate \n\t\tBitSubT at() {\n\t\t\treturn BitSubT(_word);\n\t\t}\n\t\t\/\/! ビットフィールド値取得\n\t\ttemplate \n\t\tWord at() const {\n\t\t\treturn BitSubT::get(_word);\n\t\t}\n\t\t\/\/! ビット幅マスク取得\n\t\ttemplate \n\t\tstatic Word length_mask() {\n\t\t\treturn (Word(1) << BFAt::length) - 1;\n\t\t}\n\t\t\/\/! ビットマスク取得\n\t\ttemplate \n\t\tstatic Word mask() {\n\t\t\tauto ret = length_mask();\n\t\t\treturn ret << BFAt::offset;\n\t\t}\n\n\t\t\/\/! ビットフィールドで使う場所以外をゼロクリアした値を取得\n\t\tWord cleanedValue() const {\n\t\t\tconstexpr Word msk = (maxbit >= 64) ? ~0 : ((uint64_t(1) << maxbit)-1);\n\t\t\treturn value() & msk;\n\t\t}\n\t\tbool operator == (const BitField& bf) const { return cleanedValue() == bf.cleanedValue(); }\n\t\tbool operator != (const BitField& bf) const { return !(this->operator == (bf)); }\n\t\tbool operator < (const BitField& bf) const {\n\t\t\treturn cleanedValue() < bf.cleanedValue();\n\t\t}\n\t};\n\n\t\/\/! コンパイル時計算\n\tnamespace CTBit {\n\t\ttemplate \n\t\tstruct MSB_N { constexpr static int result = 1 + MSB_N<(N >> 1)>::result; };\n\t\ttemplate <>\n\t\tstruct MSB_N<1> { constexpr static int result = 0; };\n\t\ttemplate <>\n\t\tstruct MSB_N<0> { constexpr static int result = 0; };\n\t\ttemplate \n\t\tstruct LowClear { constexpr static unsigned int result = 1 << MSB_N::result; };\n\t};\n\tstruct Bit {\n\t\tstatic bool Check(uint32_t val, uint32_t flag) {\n\t\t\treturn val & flag;\n\t\t}\n\t\tstatic void Clear(uint32_t& val, uint32_t flag) {\n\t\t\tval &= ~flag;\n\t\t}\n\t\tstatic void Set(uint32_t& val, uint32_t flag) {\n\t\t\tval |= flag;\n\t\t}\n\t\t\/\/! ビットチェックした結果を返し、ビットは消去する\n\t\tstatic bool ChClear(uint32_t& val, uint32_t flag) {\n\t\t\tbool bRet = Check(val, flag);\n\t\t\tClear(val, flag);\n\t\t\treturn bRet;\n\t\t}\n\t\t\/\/! 入力値の一番左のビットだけを残す\n\t\ttemplate ::value>::type*>\n\t\tstatic T LowClear(T x) {\n\t\t\tx = x | (x >> 1);\n\t\t\tx = x | (x >> 2);\n\t\t\tx = x | (x >> 4);\n\t\t\tx = x | (x >> 8);\n\t\t\tx = x | (x >>16);\n\t\t\treturn x & ~(x>>1);\n\t\t}\n\t\t\/\/! ビットが幾つ立っているか数える\n\t\tstatic int Count(uint32_t v) {\n\t\t\tuint32_t tmp = v & 0xaaaaaaaa;\n\t\t\tv &= 0x55555555;\n\t\t\tv = v + (tmp >> 1);\n\t\t\ttmp = v & 0xcccccccc;\n\t\t\tv &= 0x33333333;\n\t\t\tv = v + (tmp >> 2);\n\t\t\ttmp = v & 0xf0f0f0f0;\n\t\t\tv &= 0x0f0f0f0f;\n\t\t\tv = v + (tmp >> 4);\n\t\t\ttmp = v & 0xff00ff00;\n\t\t\tv &= 0x00ff00ff;\n\t\t\tv = v + (tmp >> 8);\n\t\t\ttmp = v & 0xffff0000;\n\t\t\tv &= 0x0000ffff;\n\t\t\tv = v + (tmp >> 16);\n\t\t\treturn v;\n\t\t}\n\t\t\/\/! 入力値が0なら0, それ以外は~0を返す\n\t\tstatic int32_t ZeroOrFull(int32_t v) {\n\t\t\treturn (v | -v) >> 31;\n\t\t}\n\n\t\t\/\/ ビットの位置を計算\n\t\t#ifdef USEASM_BITSEARCH\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x01, %%eax;\"\n\t\t\t\t\t\"bsrl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tuint32_t ret;\n\t\t\t\tasm(\"movl %1, %%eax;\"\n\t\t\t\t\t\"orl $0x80000000, %%eax;\"\n\t\t\t\t\t\"bsfl %%eax, %0;\"\n\t\t\t\t\t:\"=r\" (ret)\n\t\t\t\t\t:\"r\" (x)\n\t\t\t\t\t:\"%eax\"\n\t\t\t\t);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t#else\n\t\t\tconst static char NLRZ_TABLE[33];\n\t\t\t\/\/! most significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は0を返す *\/\n\t\t\tstatic uint32_t MSB_N(uint32_t x) {\n\t\t\t\tx |= 0x01;\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * LowClear(x) >> 27];\n\t\t\t}\n\t\t\t\/\/! least significant bit を取得\n\t\t\t\/*! もし入力値が0の場合は31を返す *\/\n\t\t\tstatic uint32_t LSB_N(uint32_t x) {\n\t\t\t\tx |= 0x80000000;\n\t\t\t\treturn NLRZ_TABLE[0x0aec7cd2U * (x & -x) >> 27];\n\t\t\t}\n\t\t#endif\n\n\t\t\/\/! 32bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB32(uint32_t v) {\n\t\t\tuint32_t a = v<<24,\n\t\t\t\tb = (v&0xff00)<<8,\n\t\t\t\tc = (v>>8)&0xff00,\n\t\t\t\td = v>>24;\n\t\t\treturn a|b|c|d;\n\t\t}\n\t\t\/\/! 16bit値のエンディアン変換 [little -> bit]\n\t\tstatic uint32_t LtoB16(uint32_t v) {\n\t\t\tuint32_t a = (v>>8)&0xff,\n\t\t\t\tb = (v&0xff)<<8;\n\t\t\treturn a|b;\n\t\t}\n\t};\n}\nnamespace std {\n\ttemplate \n\tinline void swap(spn::BitSub&& b0, spn::BitSub&& b1) { b0.swap(b1); }\n\ttemplate \n\tinline void swap(spn::BitSub&& b0, spn::BitSub& b1) { b0.swap(b1); }\n\ttemplate \n\tinline void swap(spn::BitSub& b0, spn::BitSub&& b1) { b0.swap(b1); }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \"subscription.h\"\n#include \"..\/..\/result.h\"\n#include \"..\/..\/helper\/windows\/helper.h\"\n\nusing std::wstring;\nusing std::ostringstream;\nusing std::wostringstream;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nSubscription::Subscription(\n ChannelID channel,\n HANDLE root,\n const wstring &path,\n WindowsWorkerPlatform *platform\n) :\n command{0},\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n terminating{false},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n{\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n}\n\nSubscription::~Subscription()\n{\n CloseHandle(root);\n}\n\nResult<> Subscription::schedule(LPOVERLAPPED_COMPLETION_ROUTINE fn)\n{\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n fn \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n}\n\nResult<> Subscription::use_network_size()\n{\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n}\n\nBYTE *Subscription::get_written(DWORD written_size)\n{\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n}\n\nwstring Subscription::make_absolute(const wstring &sub_path)\n{\n wostringstream out;\n\n out << path;\n if (path.back() != L'\\\\' && sub_path.front() != L'\\\\') {\n out << L'\\\\';\n }\n out << sub_path;\n\n return out.str();\n}\n\nResult<> Subscription::stop(const CommandID cmd)\n{\n if (terminating) return ok_result();\n\n bool success = CancelIo(root);\n if (!success) return windows_error_result<>(\"Unable to cancel pending I\/O\");\n\n terminating = true;\n command = cmd;\n\n return ok_result();\n}\nPrevent calls to ReadDirectoryChangesW on terminating Subscriptions#include \n#include \n#include \n#include \n#include \n\n#include \"subscription.h\"\n#include \"..\/..\/log.h\"\n#include \"..\/..\/result.h\"\n#include \"..\/..\/helper\/windows\/helper.h\"\n\nusing std::wstring;\nusing std::ostringstream;\nusing std::wostringstream;\nusing std::endl;\n\nconst DWORD DEFAULT_BUFFER_SIZE = 1024 * 1024;\nconst DWORD NETWORK_BUFFER_SIZE = 64 * 1024;\n\nSubscription::Subscription(\n ChannelID channel,\n HANDLE root,\n const wstring &path,\n WindowsWorkerPlatform *platform\n) :\n command{0},\n channel{channel},\n platform{platform},\n path{path},\n root{root},\n terminating{false},\n buffer_size{DEFAULT_BUFFER_SIZE},\n buffer{new BYTE[buffer_size]},\n written{new BYTE[buffer_size]}\n{\n ZeroMemory(&overlapped, sizeof(OVERLAPPED));\n overlapped.hEvent = this;\n}\n\nSubscription::~Subscription()\n{\n CloseHandle(root);\n}\n\nResult<> Subscription::schedule(LPOVERLAPPED_COMPLETION_ROUTINE fn)\n{\n if (terminating) {\n LOGGER << \"Declining to schedule a new change callback for channel \" << channel\n << \" because the subscription is terminating.\" << endl;\n return ok_result();\n }\n LOGGER << \"Scheduling the next change callback for channel \" << channel << \".\" << endl;\n\n int success = ReadDirectoryChangesW(\n root, \/\/ root directory handle\n buffer.get(), \/\/ result buffer\n buffer_size, \/\/ result buffer size\n TRUE, \/\/ recursive\n FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES\n | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE | FILE_NOTIFY_CHANGE_LAST_ACCESS\n | FILE_NOTIFY_CHANGE_CREATION | FILE_NOTIFY_CHANGE_SECURITY, \/\/ change flags\n NULL, \/\/ bytes returned\n &overlapped, \/\/ overlapped\n fn \/\/ completion routine\n );\n if (!success) {\n return windows_error_result<>(\"Unable to subscribe to filesystem events\");\n }\n\n return ok_result();\n}\n\nResult<> Subscription::use_network_size()\n{\n if (buffer_size <= NETWORK_BUFFER_SIZE) {\n ostringstream out(\"Buffer size of \");\n out\n << buffer_size\n << \" is already lower than the network buffer size \"\n << NETWORK_BUFFER_SIZE;\n return error_result(out.str());\n }\n\n buffer_size = NETWORK_BUFFER_SIZE;\n buffer.reset(new BYTE[buffer_size]);\n written.reset(new BYTE[buffer_size]);\n\n return ok_result();\n}\n\nBYTE *Subscription::get_written(DWORD written_size)\n{\n memcpy(written.get(), buffer.get(), written_size);\n return written.get();\n}\n\nwstring Subscription::make_absolute(const wstring &sub_path)\n{\n wostringstream out;\n\n out << path;\n if (path.back() != L'\\\\' && sub_path.front() != L'\\\\') {\n out << L'\\\\';\n }\n out << sub_path;\n\n return out.str();\n}\n\nResult<> Subscription::stop(const CommandID cmd)\n{\n if (terminating) return ok_result();\n\n bool success = CancelIo(root);\n if (!success) return windows_error_result<>(\"Unable to cancel pending I\/O\");\n\n terminating = true;\n command = cmd;\n\n return ok_result();\n}\n<|endoftext|>"} {"text":"#include \"client_socket.h\"\n\n#include \n\nusing boost::asio::ip::tcp;\n\nClient_socket::Client_socket ( std::string address, std::string service ) :\n io_service ( std::make_shared < boost::asio::io_service > () ),\n socket ( new tcp::socket ( *io_service ) )\n{\n tcp::resolver resolver ( *io_service );\n tcp::resolver::query query ( address, service );\n tcp::resolver::iterator endpoint_iterator = resolver.resolve ( query );\n\n boost::asio::connect ( *socket, endpoint_iterator );\n}\n\nClient_socket::Client_socket (\n std::unique_ptr < tcp::socket >&& socket,\n std::shared_ptr < boost::asio::io_service > io_service\n ) :\n io_service ( io_service ),\n socket ( std::move ( socket ) )\n{}\n\nstd::string Client_socket::read_line ()\n{\n while ( next_lines.empty () )\n {\n std::vector < char > buffer ( 1024 );\n\n size_t len = ( *socket ).read_some ( boost::asio::buffer ( buffer ) );\n\n std::string data_string = std::string ( buffer.begin (), buffer.begin () + len );\n\n std::string line;\n std::stringstream ss ( std::string ( buffer.begin (), buffer.begin () + len ) );\n while ( ( std::getline ( ss, line, '\\n' ) ) )\n {\n line = line_rest + line;\n line_rest.clear ();\n while ( line.back () == '\\n' || line.back () == '\\r' )\n {\n line.pop_back ();\n }\n next_lines.push_back ( line );\n }\n\n if ( buffer.back () != '\\n' )\n {\n line_rest = next_lines.back ();\n next_lines.pop_back ();\n }\n }\n\n std::string line = next_lines.front ();\n next_lines.pop_front ();\n return line;\n}\n\nvoid Client_socket::send ( std::string message )\n{\n boost::asio::write ( *socket, boost::asio::buffer ( message ) );\n}\nFix Bug in Client_socket#include \"client_socket.h\"\n\n#include \n\nusing boost::asio::ip::tcp;\n\nClient_socket::Client_socket ( std::string address, std::string service ) :\n io_service ( std::make_shared < boost::asio::io_service > () ),\n socket ( new tcp::socket ( *io_service ) )\n{\n tcp::resolver resolver ( *io_service );\n tcp::resolver::query query ( address, service );\n tcp::resolver::iterator endpoint_iterator = resolver.resolve ( query );\n\n boost::asio::connect ( *socket, endpoint_iterator );\n}\n\nClient_socket::Client_socket (\n std::unique_ptr < tcp::socket >&& socket,\n std::shared_ptr < boost::asio::io_service > io_service\n ) :\n io_service ( io_service ),\n socket ( std::move ( socket ) )\n{}\n\nstd::string Client_socket::read_line ()\n{\n while ( next_lines.empty () )\n {\n std::vector < char > buffer ( 1024 );\n\n size_t len = ( *socket ).read_some ( boost::asio::buffer ( buffer ) );\n\n std::string data_string = std::string ( buffer.begin (), buffer.begin () + len );\n\n std::string line;\n std::string buffer_string = std::string ( buffer.begin (), buffer.begin () + len );\n std::stringstream ss ( buffer_string );\n while ( ( std::getline ( ss, line, '\\n' ) ) )\n {\n line = line_rest + line;\n line_rest.clear ();\n while ( line.back () == '\\n' || line.back () == '\\r' )\n {\n line.pop_back ();\n }\n next_lines.push_back ( line );\n }\n\n if ( buffer_string.back () != '\\n' )\n {\n line_rest = next_lines.back ();\n next_lines.pop_back ();\n }\n }\n\n std::string line = next_lines.front ();\n next_lines.pop_front ();\n return line;\n}\n\nvoid Client_socket::send ( std::string message )\n{\n boost::asio::write ( *socket, boost::asio::buffer ( message ) );\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart \n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if !defined(NDEBUG)\n#define TRACE(msg...) logTrace(\"HttpClient\", msg)\n#else\n#warning \"No NDEBUG set\"\n#define TRACE(msg...) do {} while (0)\n#endif\n\nnamespace xzero::http::client {\n\ntemplate static bool isConnectionHeader(const T& name) { \/\/ {{{\n static const std::vector connectionHeaderFields = {\n \"Connection\",\n \"Content-Length\",\n \"Close\",\n \"Keep-Alive\",\n \"TE\",\n \"Trailer\",\n \"Transfer-Encoding\",\n \"Upgrade\",\n };\n\n for (const auto& test: connectionHeaderFields)\n if (iequals(name, test))\n return true;\n\n return false;\n} \/\/ }}}\n\nHttpClient::HttpClient(Executor* executor,\n const InetAddress& upstream)\n : HttpClient(executor,\n upstream,\n 10_seconds, \/\/ connectTimeout\n 5_minutes, \/\/ readTimeout\n 10_seconds, \/\/ writeTimeout\n 60_seconds) { \/\/ keepAlive\n}\n\nHttpClient::HttpClient(Executor* executor,\n const InetAddress& upstream,\n Duration connectTimeout,\n Duration readTimeout,\n Duration writeTimeout,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(std::bind(&HttpClient::createTcp, this,\n upstream,\n connectTimeout,\n readTimeout,\n writeTimeout)),\n keepAlive_(keepAlive),\n endpoint_(),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(Executor* executor,\n RefPtr upstream,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(),\n keepAlive_(keepAlive),\n endpoint_(upstream),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(Executor* executor,\n CreateEndPoint endpointCreator,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(endpointCreator),\n keepAlive_(keepAlive),\n endpoint_(),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(HttpClient&& other)\n : executor_(other.executor_),\n createEndPoint_(std::move(other.createEndPoint_)),\n keepAlive_(std::move(other.keepAlive_)),\n endpoint_(std::move(other.endpoint_)),\n request_(std::move(other.request_)),\n listener_(other.listener_),\n isListenerOwned_(other.isListenerOwned_) {\n other.isListenerOwned_ = false;\n}\n\nFuture> HttpClient::createTcp(InetAddress address,\n Duration connectTimeout,\n Duration readTimeout,\n Duration writeTimeout) {\n if (request_.scheme() == \"https\") {\n TRACE(\"createTcp: https\");\n auto createApplicationConnection = [this](const std::string& protocolName,\n TcpEndPoint* endpoint) {\n endpoint->setConnection(listener_,\n endpoint,\n executor_);\n };\n Promise> promise;\n Future> f = SslEndPoint::connect(address, \n connectTimeout,\n readTimeout,\n writeTimeout,\n executor_,\n request_.headers().get(\"Host\"),\n {\"http\/1.1\"},\n createApplicationConnection);\n f.onSuccess(promise);\n f.onFailure(promise);\n return promise.future();\n } else {\n TRACE(\"createTcp: http\");\n return TcpEndPoint::connect(address,\n connectTimeout,\n readTimeout,\n writeTimeout,\n executor_);\n }\n}\n\nFuture HttpClient::send(const std::string& method,\n const Uri& url,\n const HeaderFieldList& headers) {\n return send(Request{HttpVersion::VERSION_1_1,\n method,\n url.toString(),\n headers,\n false,\n HugeBuffer()});\n}\n\nFuture HttpClient::send(const Request& request) {\n Promise promise;\n\n request_ = request;\n listener_ = new ResponseBuilder(promise);\n isListenerOwned_ = true;\n\n execute();\n\n return promise.future();\n}\n\nvoid HttpClient::send(const Request& request,\n HttpListener* responseListener) {\n request_ = request;\n listener_ = responseListener;\n isListenerOwned_ = false;\n\n execute();\n}\n\nvoid HttpClient::execute() {\n Future> f = createEndPoint_();\n\n f.onSuccess([this](RefPtr ep) {\n TRACE(\"endpoint created\");\n endpoint_ = ep;\n\n if (!endpoint_->connection()) {\n TRACE(\"creating connection: http\/1.1\");\n endpoint_->setConnection(listener_, endpoint_.get(), executor_);\n }\n\n TRACE(\"getting channel\");\n HttpTransport* channel = reinterpret_cast(endpoint_->connection());\n channel->setListener(listener_);\n TRACE(\"sending request\");\n channel->send(request_, nullptr);\n TRACE(\"sending request body\");\n channel->send(request_.getContent().getBuffer(), nullptr);\n TRACE(\"mark completed!\");\n channel->completed();\n });\n\n f.onFailure([this](std::error_code ec) {\n logError(\"HttpClient\", \"Failed to connect. $0\", ec.message());\n });\n}\n\n\/\/ {{{ ResponseBuilder\nHttpClient::ResponseBuilder::ResponseBuilder(Promise promise)\n : promise_(promise),\n response_() {\n TRACE(\"ResponseBuilder.ctor\");\n}\n\nvoid HttpClient::ResponseBuilder::onMessageBegin(HttpVersion version,\n HttpStatus code,\n const BufferRef& text) {\n TRACE(\"ResponseBuilder.onMessageBegin($0, $1, $2)\", version, (int)code, text);\n\n response_.setVersion(version);\n response_.setStatus(code);\n response_.setReason(text.str());\n}\n\nvoid HttpClient::ResponseBuilder::onMessageHeader(const BufferRef& name,\n const BufferRef& value) {\n TRACE(\"ResponseBuilder.onMessageHeader($0, $1)\", name, value);\n\n response_.headers().push_back(name.str(), value.str());\n}\n\nvoid HttpClient::ResponseBuilder::onMessageHeaderEnd() {\n TRACE(\"ResponseBuilder.onMessageHeaderEnd()\");\n}\n\nvoid HttpClient::ResponseBuilder::onMessageContent(const BufferRef& chunk) {\n TRACE(\"ResponseBuilder.onMessageContent(BufferRef) $0 bytes\", chunk.size());\n response_.content().write(chunk);\n}\n\nvoid HttpClient::ResponseBuilder::onMessageContent(FileView&& chunk) {\n TRACE(\"ResponseBuilder.onMessageContent(FileView) $0 bytes\", chunk.size());\n response_.content().write(std::move(chunk));\n}\n\nvoid HttpClient::ResponseBuilder::onMessageEnd() {\n TRACE(\"ResponseBuilder.onMessageEnd()\");\n response_.setContentLength(response_.content().size());\n promise_.success(response_);\n delete this;\n}\n\nvoid HttpClient::ResponseBuilder::onError(std::error_code ec) {\n logError(\"ResponseBuilder\", \"Error. $0; $1\", ec.message());\n promise_.failure(ec);\n delete this;\n}\n\/\/ }}}\n\n} \/\/ namespace xzero::http::client\n[xzero] HttpClient: fixed crash and dropped debug prints from prior WIP check-in\/\/ This file is part of the \"x0\" project, http:\/\/github.com\/christianparpart\/x0>\n\/\/ (c) 2009-2017 Christian Parpart \n\/\/\n\/\/ Licensed under the MIT License (the \"License\"); you may not use this\n\/\/ file except in compliance with the License. You may obtain a copy of\n\/\/ the License at: http:\/\/opensource.org\/licenses\/MIT\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if !defined(NDEBUG)\n#define TRACE(msg...) logTrace(\"HttpClient\", msg)\n#else\n#warning \"No NDEBUG set\"\n#define TRACE(msg...) do {} while (0)\n#endif\n\nnamespace xzero::http::client {\n\ntemplate static bool isConnectionHeader(const T& name) { \/\/ {{{\n static const std::vector connectionHeaderFields = {\n \"Connection\",\n \"Content-Length\",\n \"Close\",\n \"Keep-Alive\",\n \"TE\",\n \"Trailer\",\n \"Transfer-Encoding\",\n \"Upgrade\",\n };\n\n for (const auto& test: connectionHeaderFields)\n if (iequals(name, test))\n return true;\n\n return false;\n} \/\/ }}}\n\nHttpClient::HttpClient(Executor* executor,\n const InetAddress& upstream)\n : HttpClient(executor,\n upstream,\n 10_seconds, \/\/ connectTimeout\n 5_minutes, \/\/ readTimeout\n 10_seconds, \/\/ writeTimeout\n 60_seconds) { \/\/ keepAlive\n}\n\nHttpClient::HttpClient(Executor* executor,\n const InetAddress& upstream,\n Duration connectTimeout,\n Duration readTimeout,\n Duration writeTimeout,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(std::bind(&HttpClient::createTcp, this,\n upstream,\n connectTimeout,\n readTimeout,\n writeTimeout)),\n keepAlive_(keepAlive),\n endpoint_(),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(Executor* executor,\n RefPtr upstream,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(),\n keepAlive_(keepAlive),\n endpoint_(upstream),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(Executor* executor,\n CreateEndPoint endpointCreator,\n Duration keepAlive)\n : executor_(executor),\n createEndPoint_(endpointCreator),\n keepAlive_(keepAlive),\n endpoint_(),\n request_(),\n listener_(),\n isListenerOwned_(false) {\n}\n\nHttpClient::HttpClient(HttpClient&& other)\n : executor_(other.executor_),\n createEndPoint_(std::move(other.createEndPoint_)),\n keepAlive_(std::move(other.keepAlive_)),\n endpoint_(std::move(other.endpoint_)),\n request_(std::move(other.request_)),\n listener_(other.listener_),\n isListenerOwned_(other.isListenerOwned_) {\n other.isListenerOwned_ = false;\n}\n\nFuture> HttpClient::createTcp(InetAddress address,\n Duration connectTimeout,\n Duration readTimeout,\n Duration writeTimeout) {\n if (request_.scheme() == \"https\") {\n TRACE(\"createTcp: https\");\n auto createApplicationConnection = [this](const std::string& protocolName,\n TcpEndPoint* endpoint) {\n endpoint->setConnection(listener_,\n endpoint,\n executor_);\n };\n Promise> promise;\n Future> f = SslEndPoint::connect(address, \n connectTimeout,\n readTimeout,\n writeTimeout,\n executor_,\n request_.headers().get(\"Host\"),\n {\"http\/1.1\"},\n createApplicationConnection);\n f.onSuccess(promise);\n f.onFailure(promise);\n return promise.future();\n } else {\n TRACE(\"createTcp: http\");\n return TcpEndPoint::connect(address,\n connectTimeout,\n readTimeout,\n writeTimeout,\n executor_);\n }\n}\n\nFuture HttpClient::send(const std::string& method,\n const Uri& url,\n const HeaderFieldList& headers) {\n return send(Request{HttpVersion::VERSION_1_1,\n method,\n url.toString(),\n headers,\n false,\n HugeBuffer()});\n}\n\nFuture HttpClient::send(const Request& request) {\n Promise promise;\n\n request_ = request;\n listener_ = new ResponseBuilder(promise);\n isListenerOwned_ = true;\n\n execute();\n\n return promise.future();\n}\n\nvoid HttpClient::send(const Request& request,\n HttpListener* responseListener) {\n request_ = request;\n listener_ = responseListener;\n isListenerOwned_ = false;\n\n execute();\n}\n\nvoid HttpClient::execute() {\n Future> f = createEndPoint_();\n\n f.onSuccess([this](RefPtr ep) {\n TRACE(\"endpoint created\");\n endpoint_ = ep;\n\n if (!endpoint_->connection()) {\n TRACE(\"creating connection: http\/1.1\");\n endpoint_->setConnection(listener_, endpoint_.get(), executor_);\n }\n\n \/\/ dynamic_cast, as we're having most-likely multiple inheritance here\n HttpTransport* channel = dynamic_cast(endpoint_->connection());\n assert(channel != nullptr);\n\n channel->setListener(listener_);\n channel->send(request_, nullptr);\n channel->send(request_.getContent().getBuffer(), nullptr);\n channel->completed();\n });\n\n f.onFailure([this](std::error_code ec) {\n logError(\"HttpClient\", \"Failed to connect. $0\", ec.message());\n });\n}\n\n\/\/ {{{ ResponseBuilder\nHttpClient::ResponseBuilder::ResponseBuilder(Promise promise)\n : promise_(promise),\n response_() {\n TRACE(\"ResponseBuilder.ctor\");\n}\n\nvoid HttpClient::ResponseBuilder::onMessageBegin(HttpVersion version,\n HttpStatus code,\n const BufferRef& text) {\n TRACE(\"ResponseBuilder.onMessageBegin($0, $1, $2)\", version, (int)code, text);\n\n response_.setVersion(version);\n response_.setStatus(code);\n response_.setReason(text.str());\n}\n\nvoid HttpClient::ResponseBuilder::onMessageHeader(const BufferRef& name,\n const BufferRef& value) {\n TRACE(\"ResponseBuilder.onMessageHeader($0, $1)\", name, value);\n\n response_.headers().push_back(name.str(), value.str());\n}\n\nvoid HttpClient::ResponseBuilder::onMessageHeaderEnd() {\n TRACE(\"ResponseBuilder.onMessageHeaderEnd()\");\n}\n\nvoid HttpClient::ResponseBuilder::onMessageContent(const BufferRef& chunk) {\n TRACE(\"ResponseBuilder.onMessageContent(BufferRef) $0 bytes\", chunk.size());\n response_.content().write(chunk);\n}\n\nvoid HttpClient::ResponseBuilder::onMessageContent(FileView&& chunk) {\n TRACE(\"ResponseBuilder.onMessageContent(FileView) $0 bytes\", chunk.size());\n response_.content().write(std::move(chunk));\n}\n\nvoid HttpClient::ResponseBuilder::onMessageEnd() {\n TRACE(\"ResponseBuilder.onMessageEnd()\");\n response_.setContentLength(response_.content().size());\n promise_.success(response_);\n delete this;\n}\n\nvoid HttpClient::ResponseBuilder::onError(std::error_code ec) {\n logError(\"ResponseBuilder\", \"Error. $0; $1\", ec.message());\n promise_.failure(ec);\n delete this;\n}\n\/\/ }}}\n\n} \/\/ namespace xzero::http::client\n<|endoftext|>"} {"text":"\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2009-2010 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n#ident \"$Id$\"\n\n\/***********\n * The purpose of this file is to implement the high-level logic for \n * taking a checkpoint.\n *\n * There are three locks used for taking a checkpoint. They are listed below.\n *\n * NOTE: The reader-writer locks may be held by either multiple clients \n * or the checkpoint function. (The checkpoint function has the role\n * of the writer, the clients have the reader roles.)\n *\n * - multi_operation_lock\n * This is a new reader-writer lock.\n * This lock is held by the checkpoint function only for as long as is required to \n * to set all the \"pending\" bits and to create the checkpoint-in-progress versions\n * of the header and translation table (btt).\n * The following operations must take the multi_operation_lock:\n * - any set of operations that must be atomic with respect to begin checkpoint\n *\n * - checkpoint_safe_lock\n * This is a new reader-writer lock.\n * This lock is held for the entire duration of the checkpoint.\n * It is used to prevent more than one checkpoint from happening at a time\n * (the checkpoint function is non-re-entrant), and to prevent certain operations\n * that should not happen during a checkpoint. \n * The following operations must take the checkpoint_safe lock:\n * - delete a dictionary\n * - rename a dictionary\n * The application can use this lock to disable checkpointing during other sensitive\n * operations, such as making a backup copy of the database.\n *\n * Once the \"pending\" bits are set and the snapshots are taken of the header and btt,\n * most normal database operations are permitted to resume.\n *\n *\n *\n *****\/\n\n#include \n#include \n\n#include \"fttypes.h\"\n#include \"cachetable.h\"\n#include \"log-internal.h\"\n#include \"logger.h\"\n#include \"checkpoint.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Engine status\n\/\/\n\/\/ Status is intended for display to humans to help understand system behavior.\n\/\/ It does not need to be perfectly thread-safe.\n\nstatic CHECKPOINT_STATUS_S cp_status;\n\n#define STATUS_INIT(k,t,l) { \\\n cp_status.status[k].keyname = #k; \\\n cp_status.status[k].type = t; \\\n cp_status.status[k].legend = \"checkpoint: \" l; \\\n }\n\nstatic void\nstatus_init(void) {\n \/\/ Note, this function initializes the keyname, type, and legend fields.\n \/\/ Value fields are initialized to zero by compiler.\n\n STATUS_INIT(CP_PERIOD, UINT64, \"period\");\n STATUS_INIT(CP_FOOTPRINT, UINT64, \"footprint\");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_BEGIN, UNIXTIME, \"last checkpoint began \");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_BEGIN_COMPLETE, UNIXTIME, \"last complete checkpoint began \");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_END, UNIXTIME, \"last complete checkpoint ended\");\n STATUS_INIT(CP_LAST_LSN, UINT64, \"last complete checkpoint LSN\");\n STATUS_INIT(CP_CHECKPOINT_COUNT, UINT64, \"checkpoints taken \");\n STATUS_INIT(CP_CHECKPOINT_COUNT_FAIL, UINT64, \"checkpoints failed\");\n STATUS_INIT(CP_WAITERS_NOW, UINT64, \"waiters now\");\n STATUS_INIT(CP_WAITERS_MAX, UINT64, \"waiters max\");\n STATUS_INIT(CP_CLIENT_WAIT_ON_MO, UINT64, \"non-checkpoint client wait on mo lock\");\n STATUS_INIT(CP_CLIENT_WAIT_ON_CS, UINT64, \"non-checkpoint client wait on cs lock\");\n cp_status.initialized = true;\n}\n#undef STATUS_INIT\n\n#define STATUS_VALUE(x) cp_status.status[x].value.num\n\nvoid\ntoku_checkpoint_get_status(CACHETABLE ct, CHECKPOINT_STATUS statp) {\n if (!cp_status.initialized)\n status_init();\n STATUS_VALUE(CP_PERIOD) = toku_get_checkpoint_period_unlocked(ct);\n *statp = cp_status;\n}\n\n\n\nstatic LSN last_completed_checkpoint_lsn;\n\nstatic toku_pthread_rwlock_t checkpoint_safe_lock;\nstatic toku_pthread_rwlock_t multi_operation_lock;\n\nstatic bool initialized = false; \/\/ sanity check\nstatic volatile bool locked_mo = false; \/\/ true when the multi_operation write lock is held (by checkpoint)\nstatic volatile bool locked_cs = false; \/\/ true when the checkpoint_safe write lock is held (by checkpoint)\n\n\n\/\/ Note following static functions are called from checkpoint internal logic only,\n\/\/ and use the \"writer\" calls for locking and unlocking.\n\n\nstatic void\nmulti_operation_lock_init(void) {\n pthread_rwlockattr_t attr;\n pthread_rwlockattr_init(&attr);\n#if defined(HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP)\n pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);\n#else\n \/\/ TODO: need to figure out how to make writer-preferential rwlocks\n \/\/ happen on osx\n#endif\n toku_pthread_rwlock_init(&multi_operation_lock, &attr); \n pthread_rwlockattr_destroy(&attr);\n locked_mo = false;\n}\n\nstatic void\nmulti_operation_lock_destroy(void) {\n toku_pthread_rwlock_destroy(&multi_operation_lock);\n}\n\nstatic void \nmulti_operation_checkpoint_lock(void) {\n toku_pthread_rwlock_wrlock(&multi_operation_lock); \n locked_mo = true;\n}\n\nstatic void \nmulti_operation_checkpoint_unlock(void) {\n locked_mo = false;\n toku_pthread_rwlock_wrunlock(&multi_operation_lock); \n}\n\nstatic void\ncheckpoint_safe_lock_init(void) {\n toku_pthread_rwlock_init(&checkpoint_safe_lock, NULL); \n locked_cs = false;\n}\n\nstatic void\ncheckpoint_safe_lock_destroy(void) {\n toku_pthread_rwlock_destroy(&checkpoint_safe_lock); \n}\n\nstatic void \ncheckpoint_safe_checkpoint_lock(void) {\n toku_pthread_rwlock_wrlock(&checkpoint_safe_lock); \n locked_cs = true;\n}\n\nstatic void \ncheckpoint_safe_checkpoint_unlock(void) {\n locked_cs = false;\n toku_pthread_rwlock_wrunlock(&checkpoint_safe_lock); \n}\n\n\n\/\/ toku_xxx_client_(un)lock() functions are only called from client code,\n\/\/ never from checkpoint code, and use the \"reader\" interface to the lock functions.\n\nvoid \ntoku_multi_operation_client_lock(void) {\n if (locked_mo)\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_CLIENT_WAIT_ON_MO), 1);\n toku_pthread_rwlock_rdlock(&multi_operation_lock); \n}\n\nvoid \ntoku_multi_operation_client_unlock(void) {\n toku_pthread_rwlock_rdunlock(&multi_operation_lock); \n}\n\nvoid \ntoku_checkpoint_safe_client_lock(void) {\n if (locked_cs)\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_CLIENT_WAIT_ON_CS), 1);\n toku_pthread_rwlock_rdlock(&checkpoint_safe_lock); \n toku_multi_operation_client_lock();\n}\n\nvoid \ntoku_checkpoint_safe_client_unlock(void) {\n toku_pthread_rwlock_rdunlock(&checkpoint_safe_lock); \n toku_multi_operation_client_unlock();\n}\n\n\n\n\/\/ Initialize the checkpoint mechanism, must be called before any client operations.\nvoid\ntoku_checkpoint_init(void) {\n multi_operation_lock_init();\n checkpoint_safe_lock_init();\n initialized = true;\n}\n\nvoid\ntoku_checkpoint_destroy(void) {\n multi_operation_lock_destroy();\n checkpoint_safe_lock_destroy();\n initialized = false;\n}\n\nstatic bool checkpoint_caller_is_aggressive(checkpoint_caller_t caller_id) { \n bool retval;\n switch (caller_id) {\n case SCHEDULED_CHECKPOINT:\n case CLIENT_CHECKPOINT:\n retval = false;\n break;\n case TXN_COMMIT_CHECKPOINT: \n case STARTUP_CHECKPOINT: \n case UPGRADE_CHECKPOINT:\n case RECOVERY_CHECKPOINT:\n case SHUTDOWN_CHECKPOINT:\n retval = true;\n break;\n }\n return retval;\n}\n\n#define SET_CHECKPOINT_FOOTPRINT(x) STATUS_VALUE(CP_FOOTPRINT) = footprint_offset + x\n\n\n\/\/ Take a checkpoint of all currently open dictionaries\nint \ntoku_checkpoint(CHECKPOINTER cp, TOKULOGGER logger,\n void (*callback_f)(void*), void * extra,\n void (*callback2_f)(void*), void * extra2,\n checkpoint_caller_t caller_id) {\n int r;\n int footprint_offset = (int) caller_id * 1000;\n\n assert(initialized);\n\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_WAITERS_NOW), 1);\n checkpoint_safe_checkpoint_lock();\n (void) __sync_fetch_and_sub(&STATUS_VALUE(CP_WAITERS_NOW), 1);\n\n if (STATUS_VALUE(CP_WAITERS_NOW) > STATUS_VALUE(CP_WAITERS_MAX))\n STATUS_VALUE(CP_WAITERS_MAX) = STATUS_VALUE(CP_WAITERS_NOW); \/\/ threadsafe, within checkpoint_safe lock\n\n SET_CHECKPOINT_FOOTPRINT(10);\n multi_operation_checkpoint_lock();\n SET_CHECKPOINT_FOOTPRINT(20);\n toku_ft_open_close_lock();\n \n SET_CHECKPOINT_FOOTPRINT(30);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN) = time(NULL);\n r = toku_cachetable_begin_checkpoint(cp);\n\n toku_ft_open_close_unlock();\n multi_operation_checkpoint_unlock();\n\n SET_CHECKPOINT_FOOTPRINT(40);\n if (r==0) {\n if (callback_f) {\n callback_f(extra); \/\/ callback is called with checkpoint_safe_lock still held\n }\n bool aggressive = checkpoint_caller_is_aggressive(caller_id);\n r = toku_cachetable_end_checkpoint(cp, aggressive, callback2_f, extra2);\n }\n SET_CHECKPOINT_FOOTPRINT(50);\n if (r==0 && logger) {\n last_completed_checkpoint_lsn = logger->last_completed_checkpoint_lsn;\n r = toku_logger_maybe_trim_log(logger, last_completed_checkpoint_lsn);\n STATUS_VALUE(CP_LAST_LSN) = last_completed_checkpoint_lsn.lsn;\n }\n\n SET_CHECKPOINT_FOOTPRINT(60);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_END) = time(NULL);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN_COMPLETE) = STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN);\n\n if (r == 0)\n STATUS_VALUE(CP_CHECKPOINT_COUNT)++;\n else\n STATUS_VALUE(CP_CHECKPOINT_COUNT_FAIL)++;\n\n STATUS_VALUE(CP_FOOTPRINT) = 0;\n checkpoint_safe_checkpoint_unlock();\n return r;\n}\n\n#include \nvoid __attribute__((__constructor__)) toku_checkpoint_helgrind_ignore(void);\nvoid\ntoku_checkpoint_helgrind_ignore(void) {\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&cp_status, sizeof cp_status);\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&locked_mo, sizeof locked_mo);\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&locked_cs, sizeof locked_cs);\n}\n\n#undef SET_CHECKPOINT_FOOTPRINT\n#undef STATUS_VALUE\nrefs #5467 fix -Wmaybe-uninitialized warning when compiling with optimizations\/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- *\/\n\/\/ vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:\n#ident \"Copyright (c) 2009-2010 Tokutek Inc. All rights reserved.\"\n#ident \"The technology is licensed by the Massachusetts Institute of Technology, Rutgers State University of New Jersey, and the Research Foundation of State University of New York at Stony Brook under United States of America Serial No. 11\/760379 and to the patents and\/or patent applications resulting from it.\"\n#ident \"$Id$\"\n\n\/***********\n * The purpose of this file is to implement the high-level logic for \n * taking a checkpoint.\n *\n * There are three locks used for taking a checkpoint. They are listed below.\n *\n * NOTE: The reader-writer locks may be held by either multiple clients \n * or the checkpoint function. (The checkpoint function has the role\n * of the writer, the clients have the reader roles.)\n *\n * - multi_operation_lock\n * This is a new reader-writer lock.\n * This lock is held by the checkpoint function only for as long as is required to \n * to set all the \"pending\" bits and to create the checkpoint-in-progress versions\n * of the header and translation table (btt).\n * The following operations must take the multi_operation_lock:\n * - any set of operations that must be atomic with respect to begin checkpoint\n *\n * - checkpoint_safe_lock\n * This is a new reader-writer lock.\n * This lock is held for the entire duration of the checkpoint.\n * It is used to prevent more than one checkpoint from happening at a time\n * (the checkpoint function is non-re-entrant), and to prevent certain operations\n * that should not happen during a checkpoint. \n * The following operations must take the checkpoint_safe lock:\n * - delete a dictionary\n * - rename a dictionary\n * The application can use this lock to disable checkpointing during other sensitive\n * operations, such as making a backup copy of the database.\n *\n * Once the \"pending\" bits are set and the snapshots are taken of the header and btt,\n * most normal database operations are permitted to resume.\n *\n *\n *\n *****\/\n\n#include \n#include \n\n#include \"fttypes.h\"\n#include \"cachetable.h\"\n#include \"log-internal.h\"\n#include \"logger.h\"\n#include \"checkpoint.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Engine status\n\/\/\n\/\/ Status is intended for display to humans to help understand system behavior.\n\/\/ It does not need to be perfectly thread-safe.\n\nstatic CHECKPOINT_STATUS_S cp_status;\n\n#define STATUS_INIT(k,t,l) { \\\n cp_status.status[k].keyname = #k; \\\n cp_status.status[k].type = t; \\\n cp_status.status[k].legend = \"checkpoint: \" l; \\\n }\n\nstatic void\nstatus_init(void) {\n \/\/ Note, this function initializes the keyname, type, and legend fields.\n \/\/ Value fields are initialized to zero by compiler.\n\n STATUS_INIT(CP_PERIOD, UINT64, \"period\");\n STATUS_INIT(CP_FOOTPRINT, UINT64, \"footprint\");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_BEGIN, UNIXTIME, \"last checkpoint began \");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_BEGIN_COMPLETE, UNIXTIME, \"last complete checkpoint began \");\n STATUS_INIT(CP_TIME_LAST_CHECKPOINT_END, UNIXTIME, \"last complete checkpoint ended\");\n STATUS_INIT(CP_LAST_LSN, UINT64, \"last complete checkpoint LSN\");\n STATUS_INIT(CP_CHECKPOINT_COUNT, UINT64, \"checkpoints taken \");\n STATUS_INIT(CP_CHECKPOINT_COUNT_FAIL, UINT64, \"checkpoints failed\");\n STATUS_INIT(CP_WAITERS_NOW, UINT64, \"waiters now\");\n STATUS_INIT(CP_WAITERS_MAX, UINT64, \"waiters max\");\n STATUS_INIT(CP_CLIENT_WAIT_ON_MO, UINT64, \"non-checkpoint client wait on mo lock\");\n STATUS_INIT(CP_CLIENT_WAIT_ON_CS, UINT64, \"non-checkpoint client wait on cs lock\");\n cp_status.initialized = true;\n}\n#undef STATUS_INIT\n\n#define STATUS_VALUE(x) cp_status.status[x].value.num\n\nvoid\ntoku_checkpoint_get_status(CACHETABLE ct, CHECKPOINT_STATUS statp) {\n if (!cp_status.initialized)\n status_init();\n STATUS_VALUE(CP_PERIOD) = toku_get_checkpoint_period_unlocked(ct);\n *statp = cp_status;\n}\n\n\n\nstatic LSN last_completed_checkpoint_lsn;\n\nstatic toku_pthread_rwlock_t checkpoint_safe_lock;\nstatic toku_pthread_rwlock_t multi_operation_lock;\n\nstatic bool initialized = false; \/\/ sanity check\nstatic volatile bool locked_mo = false; \/\/ true when the multi_operation write lock is held (by checkpoint)\nstatic volatile bool locked_cs = false; \/\/ true when the checkpoint_safe write lock is held (by checkpoint)\n\n\n\/\/ Note following static functions are called from checkpoint internal logic only,\n\/\/ and use the \"writer\" calls for locking and unlocking.\n\n\nstatic void\nmulti_operation_lock_init(void) {\n pthread_rwlockattr_t attr;\n pthread_rwlockattr_init(&attr);\n#if defined(HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP)\n pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);\n#else\n \/\/ TODO: need to figure out how to make writer-preferential rwlocks\n \/\/ happen on osx\n#endif\n toku_pthread_rwlock_init(&multi_operation_lock, &attr); \n pthread_rwlockattr_destroy(&attr);\n locked_mo = false;\n}\n\nstatic void\nmulti_operation_lock_destroy(void) {\n toku_pthread_rwlock_destroy(&multi_operation_lock);\n}\n\nstatic void \nmulti_operation_checkpoint_lock(void) {\n toku_pthread_rwlock_wrlock(&multi_operation_lock); \n locked_mo = true;\n}\n\nstatic void \nmulti_operation_checkpoint_unlock(void) {\n locked_mo = false;\n toku_pthread_rwlock_wrunlock(&multi_operation_lock); \n}\n\nstatic void\ncheckpoint_safe_lock_init(void) {\n toku_pthread_rwlock_init(&checkpoint_safe_lock, NULL); \n locked_cs = false;\n}\n\nstatic void\ncheckpoint_safe_lock_destroy(void) {\n toku_pthread_rwlock_destroy(&checkpoint_safe_lock); \n}\n\nstatic void \ncheckpoint_safe_checkpoint_lock(void) {\n toku_pthread_rwlock_wrlock(&checkpoint_safe_lock); \n locked_cs = true;\n}\n\nstatic void \ncheckpoint_safe_checkpoint_unlock(void) {\n locked_cs = false;\n toku_pthread_rwlock_wrunlock(&checkpoint_safe_lock); \n}\n\n\n\/\/ toku_xxx_client_(un)lock() functions are only called from client code,\n\/\/ never from checkpoint code, and use the \"reader\" interface to the lock functions.\n\nvoid \ntoku_multi_operation_client_lock(void) {\n if (locked_mo)\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_CLIENT_WAIT_ON_MO), 1);\n toku_pthread_rwlock_rdlock(&multi_operation_lock); \n}\n\nvoid \ntoku_multi_operation_client_unlock(void) {\n toku_pthread_rwlock_rdunlock(&multi_operation_lock); \n}\n\nvoid \ntoku_checkpoint_safe_client_lock(void) {\n if (locked_cs)\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_CLIENT_WAIT_ON_CS), 1);\n toku_pthread_rwlock_rdlock(&checkpoint_safe_lock); \n toku_multi_operation_client_lock();\n}\n\nvoid \ntoku_checkpoint_safe_client_unlock(void) {\n toku_pthread_rwlock_rdunlock(&checkpoint_safe_lock); \n toku_multi_operation_client_unlock();\n}\n\n\n\n\/\/ Initialize the checkpoint mechanism, must be called before any client operations.\nvoid\ntoku_checkpoint_init(void) {\n multi_operation_lock_init();\n checkpoint_safe_lock_init();\n initialized = true;\n}\n\nvoid\ntoku_checkpoint_destroy(void) {\n multi_operation_lock_destroy();\n checkpoint_safe_lock_destroy();\n initialized = false;\n}\n\nstatic bool checkpoint_caller_is_aggressive(checkpoint_caller_t caller_id) { \n bool retval;\n switch (caller_id) {\n case SCHEDULED_CHECKPOINT:\n case CLIENT_CHECKPOINT:\n retval = false;\n break;\n case TXN_COMMIT_CHECKPOINT:\n case STARTUP_CHECKPOINT:\n case UPGRADE_CHECKPOINT:\n case RECOVERY_CHECKPOINT:\n case SHUTDOWN_CHECKPOINT:\n retval = true;\n break;\n default:\n abort();\n }\n return retval;\n}\n\n#define SET_CHECKPOINT_FOOTPRINT(x) STATUS_VALUE(CP_FOOTPRINT) = footprint_offset + x\n\n\n\/\/ Take a checkpoint of all currently open dictionaries\nint \ntoku_checkpoint(CHECKPOINTER cp, TOKULOGGER logger,\n void (*callback_f)(void*), void * extra,\n void (*callback2_f)(void*), void * extra2,\n checkpoint_caller_t caller_id) {\n int r;\n int footprint_offset = (int) caller_id * 1000;\n\n assert(initialized);\n\n (void) __sync_fetch_and_add(&STATUS_VALUE(CP_WAITERS_NOW), 1);\n checkpoint_safe_checkpoint_lock();\n (void) __sync_fetch_and_sub(&STATUS_VALUE(CP_WAITERS_NOW), 1);\n\n if (STATUS_VALUE(CP_WAITERS_NOW) > STATUS_VALUE(CP_WAITERS_MAX))\n STATUS_VALUE(CP_WAITERS_MAX) = STATUS_VALUE(CP_WAITERS_NOW); \/\/ threadsafe, within checkpoint_safe lock\n\n SET_CHECKPOINT_FOOTPRINT(10);\n multi_operation_checkpoint_lock();\n SET_CHECKPOINT_FOOTPRINT(20);\n toku_ft_open_close_lock();\n \n SET_CHECKPOINT_FOOTPRINT(30);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN) = time(NULL);\n r = toku_cachetable_begin_checkpoint(cp);\n\n toku_ft_open_close_unlock();\n multi_operation_checkpoint_unlock();\n\n SET_CHECKPOINT_FOOTPRINT(40);\n if (r==0) {\n if (callback_f) {\n callback_f(extra); \/\/ callback is called with checkpoint_safe_lock still held\n }\n bool aggressive = checkpoint_caller_is_aggressive(caller_id);\n r = toku_cachetable_end_checkpoint(cp, aggressive, callback2_f, extra2);\n }\n SET_CHECKPOINT_FOOTPRINT(50);\n if (r==0 && logger) {\n last_completed_checkpoint_lsn = logger->last_completed_checkpoint_lsn;\n r = toku_logger_maybe_trim_log(logger, last_completed_checkpoint_lsn);\n STATUS_VALUE(CP_LAST_LSN) = last_completed_checkpoint_lsn.lsn;\n }\n\n SET_CHECKPOINT_FOOTPRINT(60);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_END) = time(NULL);\n STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN_COMPLETE) = STATUS_VALUE(CP_TIME_LAST_CHECKPOINT_BEGIN);\n\n if (r == 0)\n STATUS_VALUE(CP_CHECKPOINT_COUNT)++;\n else\n STATUS_VALUE(CP_CHECKPOINT_COUNT_FAIL)++;\n\n STATUS_VALUE(CP_FOOTPRINT) = 0;\n checkpoint_safe_checkpoint_unlock();\n return r;\n}\n\n#include \nvoid __attribute__((__constructor__)) toku_checkpoint_helgrind_ignore(void);\nvoid\ntoku_checkpoint_helgrind_ignore(void) {\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&cp_status, sizeof cp_status);\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&locked_mo, sizeof locked_mo);\n HELGRIND_VALGRIND_HG_DISABLE_CHECKING(&locked_cs, sizeof locked_cs);\n}\n\n#undef SET_CHECKPOINT_FOOTPRINT\n#undef STATUS_VALUE\n<|endoftext|>"} {"text":"re-enable get\/set 1d\/2d\/3d\/4d<|endoftext|>"} {"text":"Format code using clang-format version 11.0.0 (Fedora 11.0.0-2.fc33)<|endoftext|>"} {"text":"\/*\n** Author(s):\n** - Herve Cuche \n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \n#include \"src\/transport_socket_p.hpp\"\n\nnamespace qi\n{\n TransportSocketPrivate::TransportSocketPrivate(TransportSocket *socket)\n : tcd(NULL)\n , connected(false)\n , readHdr(true)\n , msg(0)\n , self(socket)\n {\n }\n\n TransportSocketPrivate::~TransportSocketPrivate()\n {\n }\n\n\/\/ if msecs < 0 no timeout\n bool TransportSocketPrivate::waitForConnected(int msecs)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocket\") << \"socket is not connected.\";\n return false;\n }\n\n \/\/ no timeout\n if (msecs < 0)\n {\n while (!isConnected())\n ;\n\n return true;\n }\n\n while (!isConnected() && msecs > 0)\n {\n qi::os::msleep(1);\n msecs--;\n }\n\n \/\/ timeout\n if (msecs == 0)\n return false;\n\n return true;\n }\n\n bool TransportSocketPrivate::waitForDisconnected(int msecs)\n {\n if (!isConnected())\n return true;\n\n \/\/ no timeout\n if (msecs < 0)\n {\n while (isConnected())\n ;\n\n return true;\n }\n\n while (isConnected() && msecs > 0)\n {\n qi::os::msleep(1);\n msecs--;\n }\n\n \/\/ timeout\n if (msecs == 0)\n return false;\n\n return true;\n }\n\n bool TransportSocketPrivate::waitForId(int id, int msecs)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocket\") << \"socket is not connected.\";\n return false;\n }\n\n std::map::iterator it;\n {\n {\n boost::mutex::scoped_lock l(mtx);\n it = msgSend.find(id);\n if (it != msgSend.end())\n return true;\n if (!isConnected())\n return false;\n if (msecs > 0)\n cond.timed_wait(l, boost::posix_time::milliseconds(msecs));\n else\n cond.wait(l);\n it = msgSend.find(id);\n if (it != msgSend.end())\n return true;\n }\n }\n return false;\n }\n\n bool TransportSocketPrivate::read(int id, qi::Message *msg)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocket\") << \"socket is not connected.\";\n return false;\n }\n\n std::map::iterator it;\n {\n boost::mutex::scoped_lock l(mtx);\n it = msgSend.find(id);\n if (it != msgSend.end())\n {\n *msg = *it->second;\n delete it->second;\n msgSend.erase(it);\n return true;\n }\n }\n\n qiLogError(\"qimessaging.TransportSocket\") << \"message #\" << id\n << \" could not be found.\";\n\n return false;\n }\n\n void TransportSocketPrivate::setCallbacks(TransportSocketInterface *delegate)\n {\n tcd = delegate;\n }\n\n bool TransportSocketPrivate::isConnected()\n {\n return connected;\n }\n}\nFix none optimistic connect\/*\n** Author(s):\n** - Herve Cuche \n**\n** Copyright (C) 2012 Aldebaran Robotics\n*\/\n\n#include \n#include \"src\/transport_socket_p.hpp\"\n\nnamespace qi\n{\n TransportSocketPrivate::TransportSocketPrivate(TransportSocket *socket)\n : tcd(NULL)\n , connected(false)\n , readHdr(true)\n , msg(0)\n , self(socket)\n {\n }\n\n TransportSocketPrivate::~TransportSocketPrivate()\n {\n }\n\n\/\/ if msecs < 0 no timeout\n bool TransportSocketPrivate::waitForConnected(int msecs)\n {\n \/\/ no timeout\n if (msecs < 0)\n {\n while (!isConnected())\n ;\n\n return true;\n }\n\n while (!isConnected() && msecs > 0)\n {\n qi::os::msleep(1);\n msecs--;\n }\n\n \/\/ timeout\n if (msecs == 0)\n return false;\n\n return true;\n }\n\n bool TransportSocketPrivate::waitForDisconnected(int msecs)\n {\n \/\/ no timeout\n if (msecs < 0)\n {\n while (isConnected())\n ;\n\n return true;\n }\n\n while (isConnected() && msecs > 0)\n {\n qi::os::msleep(1);\n msecs--;\n }\n\n \/\/ timeout\n if (msecs == 0)\n return false;\n\n return true;\n }\n\n bool TransportSocketPrivate::waitForId(int id, int msecs)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocket\") << \"socket is not connected.\";\n return false;\n }\n\n std::map::iterator it;\n {\n {\n boost::mutex::scoped_lock l(mtx);\n it = msgSend.find(id);\n if (it != msgSend.end())\n return true;\n if (!isConnected())\n return false;\n if (msecs > 0)\n cond.timed_wait(l, boost::posix_time::milliseconds(msecs));\n else\n cond.wait(l);\n it = msgSend.find(id);\n if (it != msgSend.end())\n return true;\n }\n }\n return false;\n }\n\n bool TransportSocketPrivate::read(int id, qi::Message *msg)\n {\n if (!isConnected())\n {\n qiLogError(\"qimessaging.TransportSocket\") << \"socket is not connected.\";\n return false;\n }\n\n std::map::iterator it;\n {\n boost::mutex::scoped_lock l(mtx);\n it = msgSend.find(id);\n if (it != msgSend.end())\n {\n *msg = *it->second;\n delete it->second;\n msgSend.erase(it);\n return true;\n }\n }\n\n qiLogError(\"qimessaging.TransportSocket\") << \"message #\" << id\n << \" could not be found.\";\n\n return false;\n }\n\n void TransportSocketPrivate::setCallbacks(TransportSocketInterface *delegate)\n {\n tcd = delegate;\n }\n\n bool TransportSocketPrivate::isConnected()\n {\n return connected;\n }\n}\n<|endoftext|>"} {"text":"Updates for Qt 5 migration needed for Mac OS X 10.8+<|endoftext|>"} {"text":"\/\/ Copyright 2017 Rick van Schijndel\n\n#include \n#include \n\n#include \n#include \n\n#include \"logo.h\"\n#include \"player_dick.h\"\n#include \"game_state.h\"\n#include \"asset.h\"\n#include \"player.h\"\n\n#ifdef U8X8_HAVE_HW_SPI\n#include \n#endif\n#ifdef U8X8_HAVE_HW_I2C\n#include \n#endif\n\nconst uint8_t kButtonPin = D3;\nconst uint8_t kScreenWidth = 128;\nconst uint8_t kScreenHeight = 64;\n\n\/\/ Global game state\ngameState game_state = start;\n\n\/\/ The player in the game\nPlayer player;\n\n\/\/ Assets\nAsset player_asset(player_width, player_height, player_bits);\nAsset logo_asset(bootup_width, bootup_height, bootup_bits);\n\n\/\/ The display object\nU8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0);\n\nBounce button;\n\nvoid setupButton() {\n pinMode(kButtonPin, INPUT_PULLUP);\n button.attach(kButtonPin);\n button.interval(10);\n}\n\nvoid setupGraphics() {\n u8g2.begin();\n u8g2.setFlipMode(0);\n u8g2.setFont(u8g2_font_artossans8_8r);\n}\n\nvoid setup(void) {\n setupGraphics();\n setupButton();\n Serial.begin(115200);\n}\n\n\ninline void nextGameState() {\n game_state = static_cast((game_state + 1) % (gameOver + 1));\n}\n\nvoid drawPlayer(uint16_t y = 0) {\n int16_t y_position_from_ground = kScreenHeight - player_asset.getHeight() - y;\n int16_t player_x = ((kScreenWidth \/ 3) - (player_asset.getHeight() \/ 2));\n u8g2.drawXBM(\n player_x,\n y_position_from_ground,\n player_asset.getHeight(),\n player_asset.getHeight(),\n player_asset.getBitmap());\n}\n\nvoid drawObstacles() {\n \/\/ TODO: draw obstacles according to the values in some array\n}\n\n\nvoid drawBootupScreen() {\n int16_t logoMiddleX = (kScreenWidth \/ 2) - (bootup_width \/ 2);\n int16_t logoMiddleY = (kScreenHeight \/ 2) - (bootup_height \/ 2);\n u8g2.drawXBM(\n logoMiddleX,\n logoMiddleY,\n bootup_width,\n bootup_height,\n bootup_bits);\n}\n\nvoid drawGameOver() {\n static const uint8_t x_pos_gameover = 20;\n static const uint8_t y_pos_gameover = 20;\n u8g2.drawStr(x_pos_gameover, y_pos_gameover, \"GAME OVER\");\n \/\/ TODO: draw fancy asset?\n}\n\n\nvoid drawScore() {\n static const uint8_t kScoreX = 20;\n static const uint8_t kScoreY = 60;\n static const size_t kScoreBufferSize = 20;\n char score_buffer[kScoreBufferSize];\n snprintf(score_buffer, kScoreBufferSize, \"Score: %u\", player.getScore());\n u8g2.drawStr(kScoreX, kScoreY, score_buffer);\n}\n\nvoid drawHiscoreScreen() {\n static const uint8_t kHiscoreX = 0;\n static const uint8_t kHiscoreY = 20;\n u8g2.drawStr(kHiscoreX, kHiscoreY, \"HI SCORES\");\n \/\/ TODO: draw hi scores\n}\n\nbool collisionDetected() {\n \/*\n if player_right_x_position >= obstacle_left_x_position and\n player_left_x_position <= obstacle_right_x_position\n player_bottom_y_position <= obstacle_top_y_position\n *\/\n\n \/\/ TODO: implement algorithm, remove auto logic\n return player.getScore() > (unsigned)random(100, 250);\n}\n\nvoid updateObstaclePosition() {\n \/\/ TODO\n}\n\nvoid resetGame() {\n player = Player();\n}\n\nvoid updateGameLogic(bool button_pressed) {\n switch (game_state) {\n case start:\n {\n if (button_pressed) {\n nextGameState();\n }\n break;\n }\n case hiscore:\n {\n if (button_pressed) {\n nextGameState();\n }\n break;\n }\n case play:\n {\n if (button_pressed) {\n if (player.onGround()) {\n player.jump();\n }\n }\n\n player.updateYPosition();\n updateObstaclePosition();\n\n if (collisionDetected()) {\n nextGameState();\n break;\n }\n \/\/ happens after collision detection, so score will only get higher\n \/\/ if player does not collide\n player.updateScore();\n break;\n }\n case gameOver:\n {\n if (button_pressed) {\n resetGame();\n nextGameState();\n }\n break;\n }\n default:\n {\n Serial.println(\"Invalid game state\");\n break;\n }\n }\n}\n\nvoid updateGameGraphics() {\n \/\/ clear buffer to start drawing\n u8g2.clearBuffer();\n\n \/\/ update graphics\n switch (game_state) {\n case start:\n {\n drawBootupScreen();\n break;\n }\n case hiscore:\n {\n drawHiscoreScreen();\n break;\n }\n case play:\n {\n drawPlayer(player.getYPosition());\n drawObstacles();\n break;\n }\n case gameOver:\n {\n drawGameOver();\n drawScore();\n break;\n }\n default:\n {\n Serial.println(\"invalid game state\");\n break;\n }\n }\n\n \/\/ draw everything on the screen\n u8g2.sendBuffer();\n}\n\nvoid loop(void) {\n \/\/ In the loop so it's only true once, after this it's false again.\n \/\/ This is so it won't think the button is pressed again every loop.\n bool buttonPressed = false;\n\n if (button.update()) {\n buttonPressed = button.read();\n Serial.println(\"Button update\");\n }\n\n updateGameLogic(buttonPressed);\n updateGameGraphics();\n}\nFixed player asset being drawn incorrectly\/\/ Copyright 2017 Rick van Schijndel\n\n#include \n#include \n\n#include \n#include \n\n#include \"logo.h\"\n#include \"player_dick.h\"\n#include \"game_state.h\"\n#include \"asset.h\"\n#include \"player.h\"\n\n#ifdef U8X8_HAVE_HW_SPI\n#include \n#endif\n#ifdef U8X8_HAVE_HW_I2C\n#include \n#endif\n\nconst uint8_t kButtonPin = D3;\nconst uint8_t kScreenWidth = 128;\nconst uint8_t kScreenHeight = 64;\n\n\/\/ Global game state\ngameState game_state = start;\n\n\/\/ The player in the game\nPlayer player;\n\n\/\/ Assets\nAsset player_asset(player_width, player_height, player_bits);\nAsset logo_asset(bootup_width, bootup_height, bootup_bits);\n\n\/\/ The display object\nU8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0);\n\nBounce button;\n\nvoid setupButton() {\n pinMode(kButtonPin, INPUT_PULLUP);\n button.attach(kButtonPin);\n button.interval(10);\n}\n\nvoid setupGraphics() {\n u8g2.begin();\n u8g2.setFlipMode(0);\n u8g2.setFont(u8g2_font_artossans8_8r);\n}\n\nvoid setup(void) {\n setupGraphics();\n setupButton();\n Serial.begin(115200);\n}\n\n\ninline void nextGameState() {\n game_state = static_cast((game_state + 1) % (gameOver + 1));\n}\n\nvoid drawPlayer(uint16_t y = 0) {\n int16_t y_position_from_ground = kScreenHeight - player_asset.getHeight() - y;\n int16_t player_x = ((kScreenWidth \/ 3) - (player_asset.getWidth() \/ 2));\n u8g2.drawXBM(\n player_x,\n y_position_from_ground,\n player_asset.getWidth(),\n player_asset.getHeight(),\n player_asset.getBitmap());\n}\n\nvoid drawObstacles() {\n \/\/ TODO: draw obstacles according to the values in some array\n}\n\n\nvoid drawBootupScreen() {\n int16_t logoMiddleX = (kScreenWidth \/ 2) - (bootup_width \/ 2);\n int16_t logoMiddleY = (kScreenHeight \/ 2) - (bootup_height \/ 2);\n u8g2.drawXBM(\n logoMiddleX,\n logoMiddleY,\n bootup_width,\n bootup_height,\n bootup_bits);\n}\n\nvoid drawGameOver() {\n static const uint8_t x_pos_gameover = 20;\n static const uint8_t y_pos_gameover = 20;\n u8g2.drawStr(x_pos_gameover, y_pos_gameover, \"GAME OVER\");\n \/\/ TODO: draw fancy asset?\n}\n\n\nvoid drawScore() {\n static const uint8_t kScoreX = 20;\n static const uint8_t kScoreY = 60;\n static const size_t kScoreBufferSize = 20;\n char score_buffer[kScoreBufferSize];\n snprintf(score_buffer, kScoreBufferSize, \"Score: %u\", player.getScore());\n u8g2.drawStr(kScoreX, kScoreY, score_buffer);\n}\n\nvoid drawHiscoreScreen() {\n static const uint8_t kHiscoreX = 0;\n static const uint8_t kHiscoreY = 20;\n u8g2.drawStr(kHiscoreX, kHiscoreY, \"HI SCORES\");\n \/\/ TODO: draw hi scores\n}\n\nbool collisionDetected() {\n \/*\n if player_right_x_position >= obstacle_left_x_position and\n player_left_x_position <= obstacle_right_x_position\n player_bottom_y_position <= obstacle_top_y_position\n *\/\n\n \/\/ TODO: implement algorithm, remove auto logic\n return player.getScore() > (unsigned)random(100, 250);\n}\n\nvoid updateObstaclePosition() {\n \/\/ TODO\n}\n\nvoid resetGame() {\n player = Player();\n}\n\nvoid updateGameLogic(bool button_pressed) {\n switch (game_state) {\n case start:\n {\n if (button_pressed) {\n nextGameState();\n }\n break;\n }\n case hiscore:\n {\n if (button_pressed) {\n nextGameState();\n }\n break;\n }\n case play:\n {\n if (button_pressed) {\n if (player.onGround()) {\n player.jump();\n }\n }\n\n player.updateYPosition();\n updateObstaclePosition();\n\n if (collisionDetected()) {\n nextGameState();\n break;\n }\n \/\/ happens after collision detection, so score will only get higher\n \/\/ if player does not collide\n player.updateScore();\n break;\n }\n case gameOver:\n {\n if (button_pressed) {\n resetGame();\n nextGameState();\n }\n break;\n }\n default:\n {\n Serial.println(\"Invalid game state\");\n break;\n }\n }\n}\n\nvoid updateGameGraphics() {\n \/\/ clear buffer to start drawing\n u8g2.clearBuffer();\n\n \/\/ update graphics\n switch (game_state) {\n case start:\n {\n drawBootupScreen();\n break;\n }\n case hiscore:\n {\n drawHiscoreScreen();\n break;\n }\n case play:\n {\n drawPlayer(player.getYPosition());\n drawObstacles();\n break;\n }\n case gameOver:\n {\n drawGameOver();\n drawScore();\n break;\n }\n default:\n {\n Serial.println(\"invalid game state\");\n break;\n }\n }\n\n \/\/ draw everything on the screen\n u8g2.sendBuffer();\n}\n\nvoid loop(void) {\n \/\/ In the loop so it's only true once, after this it's false again.\n \/\/ This is so it won't think the button is pressed again every loop.\n bool buttonPressed = false;\n\n if (button.update()) {\n buttonPressed = button.read();\n Serial.println(\"Button update\");\n }\n\n updateGameLogic(buttonPressed);\n updateGameGraphics();\n}\n<|endoftext|>"} {"text":"Added C++ version of tinyTest<|endoftext|>"} {"text":"\/*******************************************************************************\/\n\/* Bela Csound Rendering functions *\/\n\/* *\/\n\/*******************************************************************************\/\n\n#include \n#include \n#include \n#include \n\nstatic int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);\nstatic int CloseMidiInDevice(CSOUND *csound, void *userData);\nstatic int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,\n\t\t\tint nbytes);\n\nstruct csChan {\n std::vector data;\n std::stringstream name;\n};\n\nstruct csData{\n Csound *csound;\n int blocksize;\n int res;\n int count;\n csChan channel[8];\n};\n \ncsData* gCsData;\n\nbool setup(BelaContext *context, void *userData)\n{\n Csound *csound = new Csound();\n const char *csdfile = \"my.csd\"; \/* CSD name *\/\n int numArgs = 8;\n char *args[] = { \"csound\", csdfile, \"-iadc\", \"-odac\", \"-+rtaudio=null\",\n\t\t \"--realtime\", \"--daemon\", \"-Mhw:1,0,0\"};\n \n gCsData = new csData;\n csound->SetHostImplementedAudioIO(1,0);\n csound>SetHostImplementedMIDIIO(1);\n csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);\n csound->SetExternalMidiReadCallback(ReadMidiData);\n csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);\n gCsData->res = csound->Compile(numArgs, args);\n gCsData->csound = csound;\n gCsData->blocksize =\n csound->GetKsmps()*userData->csound->GetNchnls();\n gCsData->count = 0;\n \n \/* set up the channels *\/\n for(int i; i < context->analogInChannels; i++) {\n gCsData.channel[i].data.resize(csound->GetKsmps());\n gCsData.channel[i].name << \"analogue\" << i+1;\n }\n \n if(gCsData->res != 0) return false;\n else return true;\n}\n\nvoid render(BelaContext *context, void *Data)\n{\n csData *userData = gCsData;\n if(gCsData->res == 0) {\n int n,i,k,count, frmcount,blocksize,res;\n MYFLT scal = userData->csound->Get0dBFS();\n MYFLT* audioIn = userData->csound->GetSpin();\n MYFLT* audioOut = userData->csound->GetSpout();\n int nchnls = userData->csound->GetNchnls();\n int chns = nchnls;\n int an_chns = context->analogInChannels;\n CsChan *channel = userData->channel;\n float frm = 0, incr = ((float) context->analogFrames)\/context->audioFrames;\n int an_chans = context->analogInChannels;\n count = userData->count;\n blocksize = userData->blocksize;\n \n\n \/* this is called when Csound is not running *\/\n if(count < 0) {\n for(n = 0; n < context->audioFrames; n++){\n\tfor(i = 0; i < context->audioOutChannels; i++){\n\t audioWrite(context,n,i,0);\n\t}\n }\n return;\n }\n\n if(chns > context->audioOutChannels)\n chns = context->audioOutChannels;\n \n \/* this is where Csound is called *\/\n for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){\n if(count == blocksize) {\n\t\/* set the channels *\/\n\tfor(i = 0; i < an_chns; i++) {\n csound->SetChannel(channel[i].name.str().c_str(),\n\t\t\t &(channel[i].data[0]));\n\t}\n\t\/* run csound *\/\n\tif((res = userData->csound->PerformKsmps()) == 0) count = 0;\n\telse {\n\t count = -1;\n\t break;\n\t}\n }\n \/* read\/write audio data *\/\n for(i = 0; i < chns; i++){\n\taudioIn[count+i] = audioRead(context,n,i);\n\taudioWrite(context,n,i,audioOut[count+i]\/scal);\n }\n \n \/* read analogue data \n analogue frame pos gets incremented according to the\n ratio analogFrames\/audioFrames.\n *\/\n frmcount = count\/nchnls;\n for(i = 0; i < an_chns; i++) {\n\tk = (int) frm;\n channel[i].data[frmcount] = analogRead(context,k,i);\n }\t\n }\n gCsData->res = res;\n userData->count = count;\n }\n}\n\nvoid cleanup(BelaContext *context, void *Data)\n{\n csData *userData = gCsData;\n delete userData->csound;\n delete userData;\n}\n\n\/** MIDI Input functions \n *\/\nint OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {\n CsMIDI *midiData = new CsMIDI;\n Midi &midi = midiData->midi;\n midi.readFrom(dev);\n midi.enableParser(false);\n *userData = (void *) midiData;\n}\n\nint CloseMidiInDevice(CSOUND *csound, void *userData) {\n CsMIDI *midiData = (CsMIDI *) userData;\n delete midiData;\n}\n\nint ReadMidiData(CSOUND *csound, void *userData,\n unsigned char *mbuf, int nbytes) {\n int n = 0;\n CsMIDI *midiData = (CsMIDI *) userData;\n Midi &midi = midiData->midi;\n \n while((byte = midi.getInput()) > 0) {\n *mbuf++ = (unsigned char) byte;\n if(++n == nbytes) break;\n }\n \n return n;\t\t\t\t \n}\nbela MIDI\/*******************************************************************************\/\n\/* Bela Csound Rendering functions *\/\n\/* *\/\n\/*******************************************************************************\/\n\n#include \n#include \n#include \n#include \n\nstatic int OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev);\nstatic int CloseMidiInDevice(CSOUND *csound, void *userData);\nstatic int ReadMidiData(CSOUND *csound, void *userData, unsigned char *mbuf,\n\t\t\tint nbytes);\n\nstruct csChan {\n std::vector data;\n std::stringstream name;\n};\n\nstruct csData{\n Csound *csound;\n int blocksize;\n int res;\n int count;\n csChan channel[8];\n};\n\nstruct CsMIDI {\n Midi midi;\n}\n \ncsData* gCsData;\n\nbool setup(BelaContext *context, void *userData)\n{\n Csound *csound = new Csound();\n const char *csdfile = \"my.csd\"; \/* CSD name *\/\n int numArgs = 8;\n char *args[] = { \"csound\", csdfile, \"-iadc\", \"-odac\", \"-+rtaudio=null\",\n\t\t \"--realtime\", \"--daemon\", \"-Mhw:1,0,0\"};\n \n gCsData = new csData;\n csound->SetHostImplementedAudioIO(1,0);\n csound>SetHostImplementedMIDIIO(1);\n csound->SetExternalMidiInOpenCallback(OpenMidiInDevice);\n csound->SetExternalMidiReadCallback(ReadMidiData);\n csound->SetExternalMidiInCloseCallback(CloseMidiInDevice);\n gCsData->res = csound->Compile(numArgs, args);\n gCsData->csound = csound;\n gCsData->blocksize =\n csound->GetKsmps()*userData->csound->GetNchnls();\n gCsData->count = 0;\n \n \/* set up the channels *\/\n for(int i; i < context->analogInChannels; i++) {\n gCsData.channel[i].data.resize(csound->GetKsmps());\n gCsData.channel[i].name << \"analogue\" << i+1;\n }\n \n if(gCsData->res != 0) return false;\n else return true;\n}\n\nvoid render(BelaContext *context, void *Data)\n{\n csData *userData = gCsData;\n if(gCsData->res == 0) {\n int n,i,k,count, frmcount,blocksize,res;\n MYFLT scal = userData->csound->Get0dBFS();\n MYFLT* audioIn = userData->csound->GetSpin();\n MYFLT* audioOut = userData->csound->GetSpout();\n int nchnls = userData->csound->GetNchnls();\n int chns = nchnls;\n int an_chns = context->analogInChannels;\n CsChan *channel = userData->channel;\n float frm = 0, incr = ((float) context->analogFrames)\/context->audioFrames;\n int an_chans = context->analogInChannels;\n count = userData->count;\n blocksize = userData->blocksize;\n \n\n \/* this is called when Csound is not running *\/\n if(count < 0) {\n for(n = 0; n < context->audioFrames; n++){\n\tfor(i = 0; i < context->audioOutChannels; i++){\n\t audioWrite(context,n,i,0);\n\t}\n }\n return;\n }\n\n if(chns > context->audioOutChannels)\n chns = context->audioOutChannels;\n \n \/* this is where Csound is called *\/\n for(n = 0; n < context->audioFrames; n++, frm+=incr, count+=nchnls){\n if(count == blocksize) {\n\t\/* set the channels *\/\n\tfor(i = 0; i < an_chns; i++) {\n csound->SetChannel(channel[i].name.str().c_str(),\n\t\t\t &(channel[i].data[0]));\n\t}\n\t\/* run csound *\/\n\tif((res = userData->csound->PerformKsmps()) == 0) count = 0;\n\telse {\n\t count = -1;\n\t break;\n\t}\n }\n \/* read\/write audio data *\/\n for(i = 0; i < chns; i++){\n\taudioIn[count+i] = audioRead(context,n,i);\n\taudioWrite(context,n,i,audioOut[count+i]\/scal);\n }\n \n \/* read analogue data \n analogue frame pos gets incremented according to the\n ratio analogFrames\/audioFrames.\n *\/\n frmcount = count\/nchnls;\n for(i = 0; i < an_chns; i++) {\n\tk = (int) frm;\n channel[i].data[frmcount] = analogRead(context,k,i);\n }\t\n }\n gCsData->res = res;\n userData->count = count;\n }\n}\n\nvoid cleanup(BelaContext *context, void *Data)\n{\n csData *userData = gCsData;\n delete userData->csound;\n delete userData;\n}\n\n\/** MIDI Input functions \n *\/\nint OpenMidiInDevice(CSOUND *csound, void **userData, const char *dev) {\n CsMIDI *midiData = new CsMIDI;\n Midi &midi = midiData->midi;\n midi.readFrom(dev);\n midi.enableParser(false);\n *userData = (void *) midiData;\n}\n\nint CloseMidiInDevice(CSOUND *csound, void *userData) {\n CsMIDI *midiData = (CsMIDI *) userData;\n delete midiData;\n}\n\nint ReadMidiData(CSOUND *csound, void *userData,\n unsigned char *mbuf, int nbytes) {\n int n = 0;\n CsMIDI *midiData = (CsMIDI *) userData;\n Midi &midi = midiData->midi;\n \n while((byte = midi.getInput()) > 0) {\n *mbuf++ = (unsigned char) byte;\n if(++n == nbytes) break;\n }\n \n return n;\t\t\t\t \n}\n<|endoftext|>"} {"text":"Add suffix array<|endoftext|>"} {"text":"\/\/ Time: O(1)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n \/*\n * @param a: The first integer\n * @param b: The second integer\n * @return: The sum of a and b\n *\/\n int aplusb(int a, int b) {\n while (b != 0) {\n int carry = a & b;\n a ^= b;\n b = carry << 1;\n }\n return a;\n }\n};\n\nclass Solution2 {\npublic:\n \/*\n * @param a: The first integer\n * @param b: The second integer\n * @return: The sum of a and b\n *\/\n int aplusb(int a, int b) {\n if (b == 0) {\n return a;\n }\n return aplusb(a ^ b, (a & b) << 1);\n }\n};\nUpdate a-b-problem.cpp\/\/ Time: O(logn) = O(32)\n\/\/ Space: O(1)\n\nclass Solution {\npublic:\n \/*\n * @param a: The first integer\n * @param b: The second integer\n * @return: The sum of a and b\n *\/\n int aplusb(int a, int b) {\n while (b != 0) {\n int carry = a & b;\n a ^= b;\n b = carry << 1;\n }\n return a;\n }\n};\n\nclass Solution2 {\npublic:\n \/*\n * @param a: The first integer\n * @param b: The second integer\n * @return: The sum of a and b\n *\/\n int aplusb(int a, int b) {\n if (b == 0) {\n return a;\n }\n return aplusb(a ^ b, (a & b) << 1);\n }\n};\n<|endoftext|>"} {"text":"\/************************************************************************************\\\nThis source file is part of the KS(X) audio library *\nFor latest info, see http:\/\/code.google.com\/p\/libxal\/ *\n**************************************************************************************\nCopyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic *\n* *\n* This program is free software; you can redistribute it and\/or modify it under *\n* the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php *\n\\************************************************************************************\/\n#include \n#include \n#include \n#include \n\n#ifndef __APPLE__\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#include \"AudioManager.h\"\n#include \"Category.h\"\n#include \"Mutex.h\"\n#include \"SimpleSound.h\"\n#include \"SoundBuffer.h\"\n#include \"Source.h\"\n#include \"StreamSound.h\"\n#include \"Thread.h\"\n#include \"Util.h\"\n\nnamespace xal\n{\n\/******* GLOBAL ********************************************************\/\n\t\n\tAudioManager* mgr;\n\n\tvoid init(chstr deviceName, bool threaded, float updateTime)\n\t{\n\t\tmgr = new AudioManager();\n\t\tmgr->init(deviceName, threaded, updateTime);\n\t}\n\t\n\tvoid destroy()\n\t{\n\t\tdelete mgr;\n\t}\n\t\n\tvoid xal_writelog(chstr text)\n\t{\n\t\tprintf(\"%s\\n\", text.c_str());\n\t}\n\t\n\tvoid (*gLogFunction)(chstr) = xal_writelog;\n\tALCdevice* gDevice;\n\tALCcontext* gContext;\n\n\tvoid setLogFunction(void (*function)(chstr))\n\t{\n\t\tgLogFunction = function;\n\t}\n\t\n\/******* CONSTRUCT \/ DESTRUCT ******************************************\/\n\n\tAudioManager::AudioManager() : deviceName(\"\"), updateTime(0.01f),\n\t\tsources(harray()), gain(1.0f),\n\t\tcategories(std::map()),\n\t\tsounds(std::map()), thread(NULL), mutex(NULL)\n\t{\n\t}\n\t\n\tvoid AudioManager::init(chstr deviceName, bool threaded, float updateTime)\n\t{\n\t\tthis->logMessage(\"Initializing XAL\");\n\t\tif (deviceName == \"nosound\")\n\t\t{\n\t\t\tthis->deviceName = \"nosound\";\n\t\t\tthis->logMessage(\"- Audio is disabled\");\n\t\t\treturn;\n\t\t}\n\t\tthis->logMessage(\"Initializing OpenAL\");\n\t\tALCdevice* currentDevice = alcOpenDevice(deviceName.c_str());\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tthis->deviceName = alcGetString(currentDevice, ALC_DEVICE_SPECIFIER);\n\t\tthis->logMessage(\"Audio device: \" + this->deviceName);\n\t\tALCcontext* currentContext = alcCreateContext(currentDevice, NULL);\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\talcMakeContextCurrent(currentContext);\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\talGenSources(XAL_MAX_SOURCES, this->sourceIds);\n\t\tgDevice = currentDevice;\n\t\tgContext = currentContext;\n\t\tthis->deviceName = deviceName;\n\t\tif (threaded)\n\t\t{\n\t\t\tthis->logMessage(\"Starting Thread Management\");\n\t\t\tthis->updateTime = updateTime;\n\t\t\tthis->mutex = new Mutex();\n\t\t\tthis->thread = new Thread();\n\t\t\tthis->thread->start();\n\t\t}\n\t}\n\n\tAudioManager::~AudioManager()\n\t{\n\t\tif (this->mutex != NULL)\n\t\t{\n\t\t\tthis->mutex->lock();\n\t\t\tthis->thread->join();\n\t\t\tthis->mutex->unlock();\n\t\t\tdelete this->thread;\n\t\t\tdelete this->mutex;\n\t\t}\n\t\tfor (std::map::iterator it = this->sounds.begin(); it != this->sounds.end(); it++)\n\t\t{\n\t\t\tdelete it->second;\n\t\t}\n\t\tfor (std::map::iterator it = this->categories.begin(); it != this->categories.end(); it++)\n\t\t{\n\t\t\tdelete it->second;\n\t\t}\n\t\tthis->logMessage(\"Destroying OpenAL\");\n\t\tif (gDevice)\n\t\t{\n\t\t\twhile (this->sources.size() > 0)\n\t\t\t{\n\t\t\t\tthis->sources[0]->unlock();\n\t\t\t\tthis->sources[0]->stop();\n\t\t\t\tthis->destroySource(this->sources[0]);\n\t\t\t}\n\t\t\talDeleteSources(XAL_MAX_SOURCES, this->sourceIds);\n\t\t\talcMakeContextCurrent(NULL);\n\t\t\talcDestroyContext(gContext);\n\t\t\talcCloseDevice(gDevice);\n\t\t}\n\t}\n\t\n\/******* PROPERTIES ****************************************************\/\n\n\tvoid AudioManager::logMessage(chstr message)\n\t{\n\t\tgLogFunction(message);\n\t}\n\t\n\tbool AudioManager::isEnabled()\n\t{\n\t\treturn (gDevice != NULL);\n\t}\n\n\tvoid AudioManager::update()\n\t{\n\t\tthis->update(this->updateTime);\n\t}\n\t\n\tvoid AudioManager::update(float k)\n\t{\n\t\tif (this->deviceName != \"nosound\")\n\t\t{\n\t\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t\t{\n\t\t\t\t(*it)->update(k);\n\t\t\t}\n\t\t\tharray sources(this->sources);\n\t\t\tfor (Source** it = sources.iterate(); it; it = sources.next())\n\t\t\t{\n\t\t\t\tif (!(*it)->isBound())\n\t\t\t\t{\n\t\t\t\t\t(*it)->getSound()->unbindSource(*it);\n\t\t\t\t\tthis->destroySource(*it);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tunsigned int AudioManager::allocateSourceId()\n\t{\n\t\tharray allocated;\n\t\tunsigned int id = 0;\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\tid = (*it)->getSourceId();\n\t\t\tif (id != 0)\n\t\t\t{\n\t\t\t\tallocated += id;\n\t\t\t}\n\t\t}\n\t\tharray unallocated(this->sourceIds, XAL_MAX_SOURCES);\n\t\tunallocated -= allocated;\n\t\tif (unallocated.size() > 0)\n\t\t{\n\t\t\treturn unallocated[0];\n\t\t}\n\t\tthis->logMessage(\"Audio Manager: Unable to allocate audio source!\");\n\t\treturn 0;\n\t}\n\n\tSource* AudioManager::createSource(SoundBuffer* sound)\n\t{\n\t\tSource* source = new Source(sound);\n\t\tthis->sources += source;\n\t\treturn source;\n\t}\n\t\n\tvoid AudioManager::destroySource(Source* source)\n\t{\n\t\tthis->sources -= source;\n\t\tdelete source;\n\t}\n\n\tSound* AudioManager::getSound(chstr name)\n\t{\n\t\tif (this->sounds.find(name) == this->sounds.end())\n\t\t{\n\t\t\treturn NULL;\n\t\t}\n\t\treturn this->sounds[name];\n\t}\n\t\n\tSound* AudioManager::createSound(chstr filename, chstr categoryName, chstr prefix)\n\t{\n\t\tCategory* category = this->getCategoryByName(categoryName);\n\t\tSoundBuffer* sound;\n\t\tif (category->isStreamed())\n\t\t{\n\t\t\tsound = new StreamSound(filename, categoryName, prefix);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsound = new SimpleSound(filename, categoryName, prefix);\n\t\t}\n\t\tif (!sound->load())\n\t\t{\n\t\t\treturn NULL;\n\t\t}\n\t\tthis->sounds[sound->getName()] = sound;\n\t\treturn sound;\n\t}\n\n\tharray AudioManager::createSoundsFromPath(chstr path, chstr prefix)\n\t{\n\t\tharray result;\n\t\thstr category;\n\t\tharray dirs = getPathDirectories(path);\n\t\tfor (hstr* it = dirs.iterate(); it; it = dirs.next())\n\t\t{\n\t\t\tcategory = (*it).rsplit(\"\/\").pop_back();\n\t\t\tresult += this->createSoundsFromPath(hsprintf(\"%s\/%s\", path.c_str(), (*it).c_str()), category, prefix);\n\t\t}\n\t\treturn result;\n\t}\n\n\tharray AudioManager::createSoundsFromPath(chstr path, chstr category, chstr prefix)\n\t{\n\t\tthis->createCategory(category);\n\t\tharray result;\n\t\tharray files = getPathFilesRecursive(path);\n\t\tSoundBuffer* sound;\n\t\tfor (hstr* it = files.iterate(); it; it = files.next())\n\t\t{\n\t\t\tsound = (SoundBuffer*)this->createSound(hsprintf(\"%s\/%s\", path.c_str(), (*it).c_str()), category, prefix);\n\t\t\tif (sound != NULL)\n\t\t\t{\n\t\t\t\tresult += sound->getName();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid AudioManager::destroySound(SoundBuffer* sound)\n\t{\n\t\tstd::map::iterator it = this->sounds.begin();\n\t\tfor (;it != this->sounds.end(); it++)\n\t\t{\n\t\t\tif (it->second == sound)\n\t\t\t{\n\t\t\t\tthis->sounds.erase(it);\n\t\t\t\tdelete it->second;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid AudioManager::destroySoundsWithPrefix(chstr prefix)\n\t{\n\t\tharray deleteList;\n\t\tstd::map::iterator it = this->sounds.begin();\n\t\tfor (;it != this->sounds.end(); it++)\n\t\t{\n\t\t\tif (it->first.starts_with(prefix))\n\t\t\t{\n\t\t\t\tdelete it->second;\n\t\t\t\tdeleteList.push_back(it->first);\n\t\t\t}\n\t\t}\n\t\tfor (hstr* it = deleteList.iterate(); it ; it = deleteList.next())\n\t\t{\n\t\t\tthis->sounds.erase(*it);\n\t\t}\n\t}\n\n\tvoid AudioManager::createCategory(chstr name, bool streamed)\n\t{\n\t\tif (this->categories.find(name) == this->categories.end())\n\t\t{\n\t\t\tthis->categories[name] = new Category(name, streamed);\n\t\t}\n\t}\n\n\tCategory* AudioManager::getCategoryByName(chstr name)\n\t{\n\t\tif (this->categories.find(name) == this->categories.end())\n\t\t{\n\t\t\tthrow (\"Audio Manager: Category '\" + name + \"' does not exist!\").c_str();\n\t\t}\n\t\treturn this->categories[name];\n\t}\n\n\tvoid AudioManager::setCategoryGain(chstr name, float gain)\n\t{\n\t\tthis->getCategoryByName(name)->setGain(gain);\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\tif ((*it)->getSound()->getCategory()->getName() == name)\n\t\t\t{\n\t\t\t\talSourcef((*it)->getSourceId(), AL_GAIN, gain * (*it)->getGain() * this->gain);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid AudioManager::stopAll(float fadeTime)\n\t{\n\t\twhile (this->sources.size() > 0)\n\t\t{\n\t\t\tthis->sources[0]->unlock();\n\t\t\tthis->sources[0]->stop(fadeTime);\n\t\t\tthis->destroySource(this->sources[0]);\n\t\t}\n\t}\n\t\n\tvoid AudioManager::stopCategory(chstr category, float fadeTime)\n\t{\n\t\tharray sources(this->sources);\n\t\tfor (Source** it = sources.iterate(); it; it = sources.next())\n\t\t{\n\t\t\tif ((*it)->getSound()->getCategory()->getName() == category)\n\t\t\t{\n\t\t\t\t(*it)->unlock();\n\t\t\t\t(*it)->stop(fadeTime);\n\t\t\t\tthis->destroySource(*it);\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n- fixed problems with AudioManager::stopAll and AudioManager::stopCategory\/************************************************************************************\\\nThis source file is part of the KS(X) audio library *\nFor latest info, see http:\/\/code.google.com\/p\/libxal\/ *\n**************************************************************************************\nCopyright (c) 2010 Kresimir Spes (kreso@cateia.com), Boris Mikic *\n* *\n* This program is free software; you can redistribute it and\/or modify it under *\n* the terms of the BSD license: http:\/\/www.opensource.org\/licenses\/bsd-license.php *\n\\************************************************************************************\/\n#include \n#include \n#include \n#include \n\n#ifndef __APPLE__\n#include \n#include \n#else\n#include \n#include \n#endif\n\n#include \"AudioManager.h\"\n#include \"Category.h\"\n#include \"Mutex.h\"\n#include \"SimpleSound.h\"\n#include \"SoundBuffer.h\"\n#include \"Source.h\"\n#include \"StreamSound.h\"\n#include \"Thread.h\"\n#include \"Util.h\"\n\nnamespace xal\n{\n\/******* GLOBAL ********************************************************\/\n\t\n\tAudioManager* mgr;\n\n\tvoid init(chstr deviceName, bool threaded, float updateTime)\n\t{\n\t\tmgr = new AudioManager();\n\t\tmgr->init(deviceName, threaded, updateTime);\n\t}\n\t\n\tvoid destroy()\n\t{\n\t\tdelete mgr;\n\t}\n\t\n\tvoid xal_writelog(chstr text)\n\t{\n\t\tprintf(\"%s\\n\", text.c_str());\n\t}\n\t\n\tvoid (*gLogFunction)(chstr) = xal_writelog;\n\tALCdevice* gDevice;\n\tALCcontext* gContext;\n\n\tvoid setLogFunction(void (*function)(chstr))\n\t{\n\t\tgLogFunction = function;\n\t}\n\t\n\/******* CONSTRUCT \/ DESTRUCT ******************************************\/\n\n\tAudioManager::AudioManager() : deviceName(\"\"), updateTime(0.01f),\n\t\tsources(harray()), gain(1.0f),\n\t\tcategories(std::map()),\n\t\tsounds(std::map()), thread(NULL), mutex(NULL)\n\t{\n\t}\n\t\n\tvoid AudioManager::init(chstr deviceName, bool threaded, float updateTime)\n\t{\n\t\tthis->logMessage(\"Initializing XAL\");\n\t\tif (deviceName == \"nosound\")\n\t\t{\n\t\t\tthis->deviceName = \"nosound\";\n\t\t\tthis->logMessage(\"- Audio is disabled\");\n\t\t\treturn;\n\t\t}\n\t\tthis->logMessage(\"Initializing OpenAL\");\n\t\tALCdevice* currentDevice = alcOpenDevice(deviceName.c_str());\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\tthis->deviceName = alcGetString(currentDevice, ALC_DEVICE_SPECIFIER);\n\t\tthis->logMessage(\"Audio device: \" + this->deviceName);\n\t\tALCcontext* currentContext = alcCreateContext(currentDevice, NULL);\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\talcMakeContextCurrent(currentContext);\n\t\tif (alcGetError(currentDevice) != ALC_NO_ERROR)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\talGenSources(XAL_MAX_SOURCES, this->sourceIds);\n\t\tgDevice = currentDevice;\n\t\tgContext = currentContext;\n\t\tthis->deviceName = deviceName;\n\t\tif (threaded)\n\t\t{\n\t\t\tthis->logMessage(\"Starting Thread Management\");\n\t\t\tthis->updateTime = updateTime;\n\t\t\tthis->mutex = new Mutex();\n\t\t\tthis->thread = new Thread();\n\t\t\tthis->thread->start();\n\t\t}\n\t}\n\n\tAudioManager::~AudioManager()\n\t{\n\t\tif (this->mutex != NULL)\n\t\t{\n\t\t\tthis->mutex->lock();\n\t\t\tthis->thread->join();\n\t\t\tthis->mutex->unlock();\n\t\t\tdelete this->thread;\n\t\t\tdelete this->mutex;\n\t\t}\n\t\tfor (std::map::iterator it = this->sounds.begin(); it != this->sounds.end(); it++)\n\t\t{\n\t\t\tdelete it->second;\n\t\t}\n\t\tfor (std::map::iterator it = this->categories.begin(); it != this->categories.end(); it++)\n\t\t{\n\t\t\tdelete it->second;\n\t\t}\n\t\tthis->logMessage(\"Destroying OpenAL\");\n\t\tif (gDevice)\n\t\t{\n\t\t\twhile (this->sources.size() > 0)\n\t\t\t{\n\t\t\t\tthis->sources[0]->unlock();\n\t\t\t\tthis->sources[0]->stop();\n\t\t\t\tthis->destroySource(this->sources[0]);\n\t\t\t}\n\t\t\talDeleteSources(XAL_MAX_SOURCES, this->sourceIds);\n\t\t\talcMakeContextCurrent(NULL);\n\t\t\talcDestroyContext(gContext);\n\t\t\talcCloseDevice(gDevice);\n\t\t}\n\t}\n\t\n\/******* PROPERTIES ****************************************************\/\n\n\tvoid AudioManager::logMessage(chstr message)\n\t{\n\t\tgLogFunction(message);\n\t}\n\t\n\tbool AudioManager::isEnabled()\n\t{\n\t\treturn (gDevice != NULL);\n\t}\n\n\tvoid AudioManager::update()\n\t{\n\t\tthis->update(this->updateTime);\n\t}\n\t\n\tvoid AudioManager::update(float k)\n\t{\n\t\tif (this->deviceName != \"nosound\")\n\t\t{\n\t\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t\t{\n\t\t\t\t(*it)->update(k);\n\t\t\t}\n\t\t\tharray sources(this->sources);\n\t\t\tfor (Source** it = sources.iterate(); it; it = sources.next())\n\t\t\t{\n\t\t\t\tif (!(*it)->isBound())\n\t\t\t\t{\n\t\t\t\t\t(*it)->getSound()->unbindSource(*it);\n\t\t\t\t\tthis->destroySource(*it);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tunsigned int AudioManager::allocateSourceId()\n\t{\n\t\tharray allocated;\n\t\tunsigned int id = 0;\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\tid = (*it)->getSourceId();\n\t\t\tif (id != 0)\n\t\t\t{\n\t\t\t\tallocated += id;\n\t\t\t}\n\t\t}\n\t\tharray unallocated(this->sourceIds, XAL_MAX_SOURCES);\n\t\tunallocated -= allocated;\n\t\tif (unallocated.size() > 0)\n\t\t{\n\t\t\treturn unallocated[0];\n\t\t}\n\t\tthis->logMessage(\"Audio Manager: Unable to allocate audio source!\");\n\t\treturn 0;\n\t}\n\n\tSource* AudioManager::createSource(SoundBuffer* sound)\n\t{\n\t\tSource* source = new Source(sound);\n\t\tthis->sources += source;\n\t\treturn source;\n\t}\n\t\n\tvoid AudioManager::destroySource(Source* source)\n\t{\n\t\tthis->sources -= source;\n\t\tdelete source;\n\t}\n\n\tSound* AudioManager::getSound(chstr name)\n\t{\n\t\tif (this->sounds.find(name) == this->sounds.end())\n\t\t{\n\t\t\treturn NULL;\n\t\t}\n\t\treturn this->sounds[name];\n\t}\n\t\n\tSound* AudioManager::createSound(chstr filename, chstr categoryName, chstr prefix)\n\t{\n\t\tCategory* category = this->getCategoryByName(categoryName);\n\t\tSoundBuffer* sound;\n\t\tif (category->isStreamed())\n\t\t{\n\t\t\tsound = new StreamSound(filename, categoryName, prefix);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tsound = new SimpleSound(filename, categoryName, prefix);\n\t\t}\n\t\tif (!sound->load())\n\t\t{\n\t\t\treturn NULL;\n\t\t}\n\t\tthis->sounds[sound->getName()] = sound;\n\t\treturn sound;\n\t}\n\n\tharray AudioManager::createSoundsFromPath(chstr path, chstr prefix)\n\t{\n\t\tharray result;\n\t\thstr category;\n\t\tharray dirs = getPathDirectories(path);\n\t\tfor (hstr* it = dirs.iterate(); it; it = dirs.next())\n\t\t{\n\t\t\tcategory = (*it).rsplit(\"\/\").pop_back();\n\t\t\tresult += this->createSoundsFromPath(hsprintf(\"%s\/%s\", path.c_str(), (*it).c_str()), category, prefix);\n\t\t}\n\t\treturn result;\n\t}\n\n\tharray AudioManager::createSoundsFromPath(chstr path, chstr category, chstr prefix)\n\t{\n\t\tthis->createCategory(category);\n\t\tharray result;\n\t\tharray files = getPathFilesRecursive(path);\n\t\tSoundBuffer* sound;\n\t\tfor (hstr* it = files.iterate(); it; it = files.next())\n\t\t{\n\t\t\tsound = (SoundBuffer*)this->createSound(hsprintf(\"%s\/%s\", path.c_str(), (*it).c_str()), category, prefix);\n\t\t\tif (sound != NULL)\n\t\t\t{\n\t\t\t\tresult += sound->getName();\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid AudioManager::destroySound(SoundBuffer* sound)\n\t{\n\t\tstd::map::iterator it = this->sounds.begin();\n\t\tfor (;it != this->sounds.end(); it++)\n\t\t{\n\t\t\tif (it->second == sound)\n\t\t\t{\n\t\t\t\tthis->sounds.erase(it);\n\t\t\t\tdelete it->second;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tvoid AudioManager::destroySoundsWithPrefix(chstr prefix)\n\t{\n\t\tharray deleteList;\n\t\tstd::map::iterator it = this->sounds.begin();\n\t\tfor (;it != this->sounds.end(); it++)\n\t\t{\n\t\t\tif (it->first.starts_with(prefix))\n\t\t\t{\n\t\t\t\tdelete it->second;\n\t\t\t\tdeleteList.push_back(it->first);\n\t\t\t}\n\t\t}\n\t\tfor (hstr* it = deleteList.iterate(); it ; it = deleteList.next())\n\t\t{\n\t\t\tthis->sounds.erase(*it);\n\t\t}\n\t}\n\n\tvoid AudioManager::createCategory(chstr name, bool streamed)\n\t{\n\t\tif (this->categories.find(name) == this->categories.end())\n\t\t{\n\t\t\tthis->categories[name] = new Category(name, streamed);\n\t\t}\n\t}\n\n\tCategory* AudioManager::getCategoryByName(chstr name)\n\t{\n\t\tif (this->categories.find(name) == this->categories.end())\n\t\t{\n\t\t\tthrow (\"Audio Manager: Category '\" + name + \"' does not exist!\").c_str();\n\t\t}\n\t\treturn this->categories[name];\n\t}\n\n\tvoid AudioManager::setCategoryGain(chstr name, float gain)\n\t{\n\t\tthis->getCategoryByName(name)->setGain(gain);\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\tif ((*it)->getSound()->getCategory()->getName() == name)\n\t\t\t{\n\t\t\t\talSourcef((*it)->getSourceId(), AL_GAIN, gain * (*it)->getGain() * this->gain);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid AudioManager::stopAll(float fadeTime)\n\t{\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\t(*it)->unlock();\n\t\t\t(*it)->stop(fadeTime);\n\t\t}\n\t}\n\t\n\tvoid AudioManager::stopCategory(chstr category, float fadeTime)\n\t{\n\t\tfor (Source** it = this->sources.iterate(); it; it = this->sources.next())\n\t\t{\n\t\t\tif ((*it)->getSound()->getCategory()->getName() == category)\n\t\t\t{\n\t\t\t\t(*it)->unlock();\n\t\t\t\t(*it)->stop(fadeTime);\n\t\t\t}\n\t\t}\n\t}\n\t\n}\n<|endoftext|>"} {"text":"\n#include \"stdafx.h\"\n#include \"common.h\"\n#include \"util\\fixes.h\"\n#include \"python\\pythonglobal.h\"\n#include \"python\\python_header.h\"\n#include \"obj.h\"\n#include \"d20.h\"\n#include \"gamesystems\/objects\/objsystem.h\"\n#include \"condition.h\"\n#include \"critter.h\"\n#include \"combat.h\"\n#include \"gamesystems\/gamesystems.h\"\n#include \"history.h\"\n#include \"python\/python_integration_spells.h\"\n#include \"gamesystems\/objects\/objevent.h\"\n#include \"gamesystems\/particlesystems.h\"\n#include \"damage.h\"\n\n\nvoid PyPerformTouchAttack_PatchedCallToHitProcessing(D20Actn * pd20A, D20Actn d20A, uint32_t savedesi, uint32_t retaddr, PyObject * pyObjCaller, PyObject * pyTupleArgs);\nvoid enlargeSpellRestoreModelScaleHook(objHndl objHnd);\nvoid enlargeSpellIncreaseModelScaleHook(objHndl objHnd);\n\nclass SpellConditionFixes : public TempleFix {\npublic:\n\tconst char* name() override {\n\t\treturn \"Spell Condition Fixes (for buggy spell effects)\";\n\t}\n\n\tvoid VampiricTouchFix();\n\tvoid enlargePersonModelScaleFix(); \/\/ fixes ambiguous float point calculations that resulted in cumulative roundoff errors\n\t\n\tstatic int ImmunityCheckHandler(DispatcherCallbackArgs args);\n\n\tstatic int StinkingCloudObjEvent(DispatcherCallbackArgs args);\n\n\tvoid apply() override {\n\t\t\n\t\tVampiricTouchFix();\n\t\tenlargePersonModelScaleFix();\n\n\t\treplaceFunction(0x100CAF30, StinkingCloudObjEvent);\n\n\t\tstatic int (*orgImmunityCheckHandler )(DispatcherCallbackArgs)= replaceFunction(0x100ED650, [](DispatcherCallbackArgs args)\n\t\t{\n\t\t\tif (!ImmunityCheckHandler(args))\n\t\t\t\treturn orgImmunityCheckHandler(args);\n\t\t\treturn 0;\n\t\t});\n\t\t\n\t}\n} spellConditionFixes;\n\n\nvoid SpellConditionFixes::VampiricTouchFix()\n{\n\twriteHex(0x102E0A24, \"EA 00\");\n\twriteHex(0x102E0A28, \"D0 43 0C 10\");\n\twriteHex(0x102E0A2C, \"F0 09 2E 10\");\n\n\twriteHex(0x102E0A8C, \"D0 8F 0E 10\");\n\n\twriteHex(0x102E0AC4, \"A6\");\n\twriteHex(0x102E0AC8, \"20 76 0D 10\");\n\n\twriteHex(0x102E0B00, \"A6\");\n\twriteHex(0x102E0B04, \"B0 BA 0C 10\");\n\n\n\t\/\/Perform Touch Attack mod:\n\tredirectCall(0x100B2CC9, PyPerformTouchAttack_PatchedCallToHitProcessing);\n\treturn;\n}\n\nvoid SpellConditionFixes::enlargePersonModelScaleFix()\n{\n\tredirectCall(0x100CD45C, enlargeSpellIncreaseModelScaleHook);\n\tredirectCall(0x100D84DE, enlargeSpellRestoreModelScaleHook); \/\/ sp152 enlarge \n\tredirectCall(0x100D9C22, enlargeSpellRestoreModelScaleHook); \/\/ sp404 righteous might\n\n}\n\nint SpellConditionFixes::ImmunityCheckHandler(DispatcherCallbackArgs args)\n{\n\t\/*\n\t\tthe dispatch is performed from the functions:\n\t\t0x100C3810 CheckSpellResistance\n\t\t0x1008D830 PerformCastSpell\n\t*\/\n\tauto dispIo23 = dispatch.DispIoCheckIoType23(args.dispIO);\n\tif (dispIo23->returnVal == 1)\n\t\treturn 1;\n\t\n\n\n\n\tDispIoTypeImmunityTrigger dispIo21;\n\tdispIo21.condNode = args.subDispNode->condNode;\n\tauto dispatcher = objSystem->GetObject(args.objHndCaller)->GetDispatcher();\n\tif (!dispatch.dispatcherValid(dispatcher))\n\t\treturn 1;\n\t\n\tint immType = 10;\n\tfor (; immType <= 16; immType++){\n\t\tdispatch.DispatcherProcessor(dispatcher, dispTypeImmunityTrigger, immType, &dispIo21);\n\t\tif (dispIo21.interrupt == 1)\n\t\t\tbreak;\n\t}\n\tif (immType > 16)\n\t\treturn 1;\n\n\n\tif (immType == 0x10) \/\/ immunity special\n\t{\n\t\tif (args.subDispNode->subDispDef->data1 == 0x4) \/\/ necklace of adaptation (NEW!)\n\t\t{\n\t\t\tif (dispIo23->spellPkt->spellEnum == 65 || dispIo23->spellPkt->spellEnum == 460) \/\/ Cloudkill and Stinking Cloud\n\t\t\t{\n\t\t\t\thistSys.CreateFromFreeText(fmt::format(\"{} protected by Necklace of Adaptation!\\n\",description.getDisplayName(args.objHndCaller )).c_str());\n\t\t\t\tdispIo23->returnVal = 1;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif (immType != 10)\n\t\treturn 0;\n\n\tauto immSpellId = conds.CondNodeGetArg(args.subDispNode->condNode, 0);\n\tSpellPacketBody immSpellPkt;\n\tif (!spellSys.GetSpellPacketBody(immSpellId, &immSpellPkt))\n\t\treturn 1;\n\n\tif (dispIo23->flag == 0)\n\t\treturn 0;\n\n\n\tif (immSpellPkt.spellEnum != 368\n\t\t&& (immSpellPkt.spellEnum < 370 || immSpellPkt.spellEnum > 372)) {\n\t\t\/\/ prot from alignment spells\n\t\treturn 0;\n\t}\n\tSpellEntry offendingSpellEntry;\n\tspellSys.spellRegistryCopy(dispIo23->spellPkt->spellEnum, &offendingSpellEntry);\n\n\tif (!(offendingSpellEntry.spellDescriptorBitmask & 0x4000)) \/\/Mind Affecting\n\t\treturn 0;\n\n\tauto caster = dispIo23->spellPkt->caster;\n\t\n\tif (!caster)\n\t\treturn 0;\n\n\tif (!objects.IsCritter(caster))\n\t\treturn 0;\n\n\tif ( offendingSpellEntry.aiTypeBitmask && ( 1< 1)\n\t{\n\t\tPyObject * pyarg2 = PyTuple_GetItem(pyTupleArgs, 1);\n\t\tif (PyType_IsSubtype(pyarg2->ob_type, &PyInt_Type))\n\t\t{\n\t\t\tif (PyLong_AsLong( pyarg2) != 0)\n\t\t\t{\n\t\t\t\tpd20A->d20Caf = D20CAF_TOUCH_ATTACK; \/\/ sans D20CAF_RANGED\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\td20Sys.ToHitProc(pd20A);\n\treturn;\n\t\n}\n\nvoid __cdecl enlargeSpellRestoreModelScaleHook(objHndl objHnd)\n{\n\t\/\/ patches for spellRemove function (disgusting hardcoded shit! bah!)\n\tuint32_t modelScale = objects.getInt32(objHnd, obj_f_model_scale);\n\tmodelScale *= 5;\n\tmodelScale \/= 9;\n\tobjects.setInt32(objHnd, obj_f_model_scale, modelScale);\n}\n\nvoid enlargeSpellIncreaseModelScaleHook(objHndl objHnd)\n{\n\tuint32_t modelScale = objects.getInt32(objHnd, obj_f_model_scale);\n\tmodelScale *= 9;\n\tmodelScale \/= 5;\n\tobjects.setInt32(objHnd, obj_f_model_scale, modelScale);\n}\n\n\n\nint SpellConditionFixes::StinkingCloudObjEvent(DispatcherCallbackArgs args)\n{\n\tDispIoObjEvent* dispIo = dispatch.DispIoCheckIoType17(args.dispIO);\n\tauto condEvtId = args.GetCondArg(2);\n\tif (dispIo->evtId == condEvtId)\t{\n\n\t\tauto spellId = args.GetCondArg(0);\n\t\tSpellPacketBody spellPkt(spellId);\n\t\tif (!spellPkt.spellId){\n\t\t\tlogger->warn(\"StinkingCloudObjEvent: Unable to fetch spell! ID {}\", spellId);\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/*\n\t\t\tAoE Entered; \n\t\t\t - add the target to the Spell's Target List\n\t\t\t - Do a saving throw\n\t\t*\/\n\t\tif (args.dispKey == DK_OnEnterAoE && (args.GetData1() == 0))\n\t\t{\n\n\t\t\tpySpellIntegration.SpellSoundPlay(&spellPkt, SpellEvent::SpellStruck);\n\t\t\tpySpellIntegration.SpellTrigger(spellId, SpellEvent::AreaOfEffectHit);\n\n\t\t\tif (spellSys.CheckSpellResistance(&spellPkt, dispIo->tgt) == 1)\n\t\t\t\treturn 0;\n\n\t\t\tauto partsysId = gameSystems->GetParticleSys().CreateAtObj(\"sp-Stinking Cloud Hit\", dispIo->tgt);\n\t\t\tspellPkt.AddTarget(dispIo->tgt, partsysId, 1);\n\t\t\tif (damage.SavingThrowSpell(dispIo->tgt, spellPkt.caster, spellPkt.dc, SavingThrowType::Fortitude, 0, spellPkt.spellId ))\t{\n\t\t\t\t\/* \n\t\t\t\t\tsave succeeded; add the \"Hit Pre\" condition, which will attempt \n\t\t\t\t\tto apply the condition in the subsequent turns\n\t\t\t\t*\/\n\t\t\t\tconds.AddTo(dispIo->tgt, \"sp-Stinking Cloud Hit Pre\", { static_cast(spellPkt.spellId), spellPkt.durationRemaining, static_cast(dispIo->evtId) });\n\t\t\t} else\n\t\t\t{\n\t\t\t\t\/*\n\t\t\t\t\tSave failed; apply the condition\n\t\t\t\t*\/\n\t\t\t\tconds.AddTo(dispIo->tgt,\"sp-Stinking Cloud Hit\", { static_cast(spellPkt.spellId), spellPkt.durationRemaining, static_cast(dispIo->evtId), 0 });\n\t\t\t}\n\t\t}\n\t\t\/*\n\t\t\tAoE exited;\n\t\t\t - If \"Hit Pre\" (identified by data1 = 223), remove the condition so the character doesn't keep making saves outside the cloud\n\t\t\t - If \"Hit\" (identified by data1 = 222), reduce the remaining duration to 1d4+1\n\t\t*\/\n\t\telse if (args.dispKey == DK_OnLeaveAoE)\n\t\t{\n\t\t\tif (args.GetData1() == 222) \/\/ the sp-Stinking Cloud Hit condition\n\t\t\t{\n\t\t\t\targs.SetCondArg(3,1);\n\t\t\t\tauto rollResult = Dice::Roll(1,4,1);\n\t\t\t\targs.SetCondArg(1, rollResult); \/\/ sets the remaining duration to 1d4+1\n\t\t\t\thistSys.CreateFromFreeText(fmt::format(\"{} exited Stinking Cloud; Nauseated for {} more rounds.\\n\", description.getDisplayName(dispIo->tgt), rollResult).c_str());\n\t\t\t}\n\t\t\telse if (args.GetData1() == 223) \/\/ the sp-Stinking Cloud Hit Pre condition\n\t\t\t{\n\t\t\t\t\/\/ remove the condition (cloud has been exited)\n\t\t\t\t\/\/ it will get re-added if the target re-enters via this same callback (see above)\n\t\t\t\tconds.ConditionRemove(dispIo->tgt, args.subDispNode->condNode);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (!spellPkt.UpdateSpellsCastRegistry() )\t{\n\t\t\tlogger->warn(\"StinkingCloudObjEvent: Unable to save update SpellPacket!\");\n\t\t\treturn 0;\n\t\t}\n\t\tpySpellIntegration.UpdateSpell(spellId);\n\t}\n\treturn 0;\n\t\n};Fix for Shocking Grasp doing d8 instead of d6 damage dice\n#include \"stdafx.h\"\n#include \"common.h\"\n#include \"util\\fixes.h\"\n#include \"python\\pythonglobal.h\"\n#include \"python\\python_header.h\"\n#include \"obj.h\"\n#include \"d20.h\"\n#include \"gamesystems\/objects\/objsystem.h\"\n#include \"condition.h\"\n#include \"critter.h\"\n#include \"combat.h\"\n#include \"gamesystems\/gamesystems.h\"\n#include \"history.h\"\n#include \"python\/python_integration_spells.h\"\n#include \"gamesystems\/objects\/objevent.h\"\n#include \"gamesystems\/particlesystems.h\"\n#include \"damage.h\"\n\n\nvoid PyPerformTouchAttack_PatchedCallToHitProcessing(D20Actn * pd20A, D20Actn d20A, uint32_t savedesi, uint32_t retaddr, PyObject * pyObjCaller, PyObject * pyTupleArgs);\nvoid enlargeSpellRestoreModelScaleHook(objHndl objHnd);\nvoid enlargeSpellIncreaseModelScaleHook(objHndl objHnd);\n\nclass SpellConditionFixes : public TempleFix {\npublic:\n\tconst char* name() override {\n\t\treturn \"Spell Condition Fixes (for buggy spell effects)\";\n\t}\n\n\tvoid VampiricTouchFix();\n\tvoid enlargePersonModelScaleFix(); \/\/ fixes ambiguous float point calculations that resulted in cumulative roundoff errors\n\t\n\tstatic int ImmunityCheckHandler(DispatcherCallbackArgs args);\n\n\tstatic int StinkingCloudObjEvent(DispatcherCallbackArgs args);\n\n\tvoid apply() override {\n\t\t\n\t\tVampiricTouchFix();\n\t\tenlargePersonModelScaleFix();\n\n\t\treplaceFunction(0x100CAF30, StinkingCloudObjEvent);\n\n\t\tstatic int (*orgImmunityCheckHandler )(DispatcherCallbackArgs)= replaceFunction(0x100ED650, [](DispatcherCallbackArgs args)\n\t\t{\n\t\t\tif (!ImmunityCheckHandler(args))\n\t\t\t\treturn orgImmunityCheckHandler(args);\n\t\t\treturn 0;\n\t\t});\n\t\t\n\n\t\t\/\/ Fix for Shocking Grasp doing d8 instead of d6 damage\n\t\tchar sgWriteVal = 6;\n\t\twrite(0x100DD9DF + 1, &sgWriteVal, sizeof(char));\n\t}\n} spellConditionFixes;\n\n\nvoid SpellConditionFixes::VampiricTouchFix()\n{\n\twriteHex(0x102E0A24, \"EA 00\");\n\twriteHex(0x102E0A28, \"D0 43 0C 10\");\n\twriteHex(0x102E0A2C, \"F0 09 2E 10\");\n\n\twriteHex(0x102E0A8C, \"D0 8F 0E 10\");\n\n\twriteHex(0x102E0AC4, \"A6\");\n\twriteHex(0x102E0AC8, \"20 76 0D 10\");\n\n\twriteHex(0x102E0B00, \"A6\");\n\twriteHex(0x102E0B04, \"B0 BA 0C 10\");\n\n\n\t\/\/Perform Touch Attack mod:\n\tredirectCall(0x100B2CC9, PyPerformTouchAttack_PatchedCallToHitProcessing);\n\treturn;\n}\n\nvoid SpellConditionFixes::enlargePersonModelScaleFix()\n{\n\tredirectCall(0x100CD45C, enlargeSpellIncreaseModelScaleHook);\n\tredirectCall(0x100D84DE, enlargeSpellRestoreModelScaleHook); \/\/ sp152 enlarge \n\tredirectCall(0x100D9C22, enlargeSpellRestoreModelScaleHook); \/\/ sp404 righteous might\n\n}\n\nint SpellConditionFixes::ImmunityCheckHandler(DispatcherCallbackArgs args)\n{\n\t\/*\n\t\tthe dispatch is performed from the functions:\n\t\t0x100C3810 CheckSpellResistance\n\t\t0x1008D830 PerformCastSpell\n\t*\/\n\tauto dispIo23 = dispatch.DispIoCheckIoType23(args.dispIO);\n\tif (dispIo23->returnVal == 1)\n\t\treturn 1;\n\t\n\n\n\n\tDispIoTypeImmunityTrigger dispIo21;\n\tdispIo21.condNode = args.subDispNode->condNode;\n\tauto dispatcher = objSystem->GetObject(args.objHndCaller)->GetDispatcher();\n\tif (!dispatch.dispatcherValid(dispatcher))\n\t\treturn 1;\n\t\n\tint immType = 10;\n\tfor (; immType <= 16; immType++){\n\t\tdispatch.DispatcherProcessor(dispatcher, dispTypeImmunityTrigger, immType, &dispIo21);\n\t\tif (dispIo21.interrupt == 1)\n\t\t\tbreak;\n\t}\n\tif (immType > 16)\n\t\treturn 1;\n\n\n\tif (immType == 0x10) \/\/ immunity special\n\t{\n\t\tif (args.subDispNode->subDispDef->data1 == 0x4) \/\/ necklace of adaptation (NEW!)\n\t\t{\n\t\t\tif (dispIo23->spellPkt->spellEnum == 65 || dispIo23->spellPkt->spellEnum == 460) \/\/ Cloudkill and Stinking Cloud\n\t\t\t{\n\t\t\t\thistSys.CreateFromFreeText(fmt::format(\"{} protected by Necklace of Adaptation!\\n\",description.getDisplayName(args.objHndCaller )).c_str());\n\t\t\t\tdispIo23->returnVal = 1;\n\t\t\t\treturn 1;\n\t\t\t}\n\n\t\t}\n\t}\n\n\tif (immType != 10)\n\t\treturn 0;\n\n\tauto immSpellId = conds.CondNodeGetArg(args.subDispNode->condNode, 0);\n\tSpellPacketBody immSpellPkt;\n\tif (!spellSys.GetSpellPacketBody(immSpellId, &immSpellPkt))\n\t\treturn 1;\n\n\tif (dispIo23->flag == 0)\n\t\treturn 0;\n\n\n\tif (immSpellPkt.spellEnum != 368\n\t\t&& (immSpellPkt.spellEnum < 370 || immSpellPkt.spellEnum > 372)) {\n\t\t\/\/ prot from alignment spells\n\t\treturn 0;\n\t}\n\tSpellEntry offendingSpellEntry;\n\tspellSys.spellRegistryCopy(dispIo23->spellPkt->spellEnum, &offendingSpellEntry);\n\n\tif (!(offendingSpellEntry.spellDescriptorBitmask & 0x4000)) \/\/Mind Affecting\n\t\treturn 0;\n\n\tauto caster = dispIo23->spellPkt->caster;\n\t\n\tif (!caster)\n\t\treturn 0;\n\n\tif (!objects.IsCritter(caster))\n\t\treturn 0;\n\n\tif ( offendingSpellEntry.aiTypeBitmask && ( 1< 1)\n\t{\n\t\tPyObject * pyarg2 = PyTuple_GetItem(pyTupleArgs, 1);\n\t\tif (PyType_IsSubtype(pyarg2->ob_type, &PyInt_Type))\n\t\t{\n\t\t\tif (PyLong_AsLong( pyarg2) != 0)\n\t\t\t{\n\t\t\t\tpd20A->d20Caf = D20CAF_TOUCH_ATTACK; \/\/ sans D20CAF_RANGED\n\t\t\t}\n\t\t}\n\t}\n\t\n\n\td20Sys.ToHitProc(pd20A);\n\treturn;\n\t\n}\n\nvoid __cdecl enlargeSpellRestoreModelScaleHook(objHndl objHnd)\n{\n\t\/\/ patches for spellRemove function (disgusting hardcoded shit! bah!)\n\tuint32_t modelScale = objects.getInt32(objHnd, obj_f_model_scale);\n\tmodelScale *= 5;\n\tmodelScale \/= 9;\n\tobjects.setInt32(objHnd, obj_f_model_scale, modelScale);\n}\n\nvoid enlargeSpellIncreaseModelScaleHook(objHndl objHnd)\n{\n\tuint32_t modelScale = objects.getInt32(objHnd, obj_f_model_scale);\n\tmodelScale *= 9;\n\tmodelScale \/= 5;\n\tobjects.setInt32(objHnd, obj_f_model_scale, modelScale);\n}\n\n\n\nint SpellConditionFixes::StinkingCloudObjEvent(DispatcherCallbackArgs args)\n{\n\tDispIoObjEvent* dispIo = dispatch.DispIoCheckIoType17(args.dispIO);\n\tauto condEvtId = args.GetCondArg(2);\n\tif (dispIo->evtId == condEvtId)\t{\n\n\t\tauto spellId = args.GetCondArg(0);\n\t\tSpellPacketBody spellPkt(spellId);\n\t\tif (!spellPkt.spellId){\n\t\t\tlogger->warn(\"StinkingCloudObjEvent: Unable to fetch spell! ID {}\", spellId);\n\t\t\treturn 0;\n\t\t}\n\n\t\t\/*\n\t\t\tAoE Entered; \n\t\t\t - add the target to the Spell's Target List\n\t\t\t - Do a saving throw\n\t\t*\/\n\t\tif (args.dispKey == DK_OnEnterAoE && (args.GetData1() == 0))\n\t\t{\n\n\t\t\tpySpellIntegration.SpellSoundPlay(&spellPkt, SpellEvent::SpellStruck);\n\t\t\tpySpellIntegration.SpellTrigger(spellId, SpellEvent::AreaOfEffectHit);\n\n\t\t\tif (spellSys.CheckSpellResistance(&spellPkt, dispIo->tgt) == 1)\n\t\t\t\treturn 0;\n\n\t\t\tauto partsysId = gameSystems->GetParticleSys().CreateAtObj(\"sp-Stinking Cloud Hit\", dispIo->tgt);\n\t\t\tspellPkt.AddTarget(dispIo->tgt, partsysId, 1);\n\t\t\tif (damage.SavingThrowSpell(dispIo->tgt, spellPkt.caster, spellPkt.dc, SavingThrowType::Fortitude, 0, spellPkt.spellId ))\t{\n\t\t\t\t\/* \n\t\t\t\t\tsave succeeded; add the \"Hit Pre\" condition, which will attempt \n\t\t\t\t\tto apply the condition in the subsequent turns\n\t\t\t\t*\/\n\t\t\t\tconds.AddTo(dispIo->tgt, \"sp-Stinking Cloud Hit Pre\", { static_cast(spellPkt.spellId), spellPkt.durationRemaining, static_cast(dispIo->evtId) });\n\t\t\t} else\n\t\t\t{\n\t\t\t\t\/*\n\t\t\t\t\tSave failed; apply the condition\n\t\t\t\t*\/\n\t\t\t\tconds.AddTo(dispIo->tgt,\"sp-Stinking Cloud Hit\", { static_cast(spellPkt.spellId), spellPkt.durationRemaining, static_cast(dispIo->evtId), 0 });\n\t\t\t}\n\t\t}\n\t\t\/*\n\t\t\tAoE exited;\n\t\t\t - If \"Hit Pre\" (identified by data1 = 223), remove the condition so the character doesn't keep making saves outside the cloud\n\t\t\t - If \"Hit\" (identified by data1 = 222), reduce the remaining duration to 1d4+1\n\t\t*\/\n\t\telse if (args.dispKey == DK_OnLeaveAoE)\n\t\t{\n\t\t\tif (args.GetData1() == 222) \/\/ the sp-Stinking Cloud Hit condition\n\t\t\t{\n\t\t\t\targs.SetCondArg(3,1);\n\t\t\t\tauto rollResult = Dice::Roll(1,4,1);\n\t\t\t\targs.SetCondArg(1, rollResult); \/\/ sets the remaining duration to 1d4+1\n\t\t\t\thistSys.CreateFromFreeText(fmt::format(\"{} exited Stinking Cloud; Nauseated for {} more rounds.\\n\", description.getDisplayName(dispIo->tgt), rollResult).c_str());\n\t\t\t}\n\t\t\telse if (args.GetData1() == 223) \/\/ the sp-Stinking Cloud Hit Pre condition\n\t\t\t{\n\t\t\t\t\/\/ remove the condition (cloud has been exited)\n\t\t\t\t\/\/ it will get re-added if the target re-enters via this same callback (see above)\n\t\t\t\tconds.ConditionRemove(dispIo->tgt, args.subDispNode->condNode);\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\n\t\tif (!spellPkt.UpdateSpellsCastRegistry() )\t{\n\t\t\tlogger->warn(\"StinkingCloudObjEvent: Unable to save update SpellPacket!\");\n\t\t\treturn 0;\n\t\t}\n\t\tpySpellIntegration.UpdateSpell(spellId);\n\t}\n\treturn 0;\n\t\n};<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: hangulhanjadlg.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 17:42:06 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef SVX_HANGUL_HANJA_DLG_HXX\n#define SVX_HANGUL_HANJA_DLG_HXX\n\n#ifndef _SV_DIALOG_HXX\n#include \n#endif\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef SVX_HANGUL_HANJA_CONVERSION_HXX\n#include \"hangulhanja.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n\n#include \/\/ for auto_ptr\n\nclass SvxCommonLinguisticControl;\n\/\/.............................................................................\nnamespace svx\n{\n\/\/.............................................................................\n\n \/\/=========================================================================\n \/\/= HangulHanjaConversionDialog\n \/\/=========================================================================\n\n class HangulHanjaConversionDialog : public ModalDialog\n {\n private:\n ::std::auto_ptr< SvxCommonLinguisticControl >\n m_pPlayground; \/\/ oder matters: before all other controls!\n\n PushButton m_aFind;\n ListBox m_aSuggestions;\n FixedText m_aFormat;\n RadioButton m_aSimpleConversion;\n RadioButton m_aHangulBracketed;\n RadioButton m_aHanjaBracketed;\n ::std::auto_ptr< RadioButton > m_pHanjaAbove;\n ::std::auto_ptr< RadioButton > m_pHanjaBelow;\n ::std::auto_ptr< RadioButton > m_pHangulAbove;\n ::std::auto_ptr< RadioButton > m_pHangulBelow;\n FixedText m_aConversion;\n CheckBox m_aHangulOnly;\n CheckBox m_aHanjaOnly;\n CheckBox m_aReplaceByChar;\n\n CheckBox* m_pIgnoreNonPrimary;\n bool m_bDocumentMode;\n \/\/ are we working for a document? This is normally true, but in case\n \/\/ the user uses the \"find\" functionality, we switch to working\n \/\/ with what the user entered, which then does not have any relation to\n \/\/ the document anymore. Some functionality must be disabled then\n\n public:\n HangulHanjaConversionDialog(\n Window* _pParent,\n HangulHanjaConversion::ConversionDirection _ePrimaryDirection );\n ~HangulHanjaConversionDialog( );\n\n public:\n void SetIgnoreHdl( const Link& _rHdl );\n void SetIgnoreAllHdl( const Link& _rHdl );\n void SetChangeHdl( const Link& _rHdl );\n void SetChangeAllHdl( const Link& _rHdl );\n\n void SetClickByCharacterHdl( const Link& _rHdl );\n void SetConversionFormatChangedHdl( const Link& _rHdl );\n void SetFindHdl( const Link& _rHdl );\n\n String GetCurrentString( ) const;\n void SetCurrentString(\n const String& _rNewString,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rSuggestions,\n bool _bOriginatesFromDocument = true\n );\n\n void FocusSuggestion( );\n\n \/\/ retrieves the current suggestion\n String GetCurrentSuggestion( ) const;\n\n void SetConversionFormat( HangulHanjaConversion::ConversionFormat _eType );\n HangulHanjaConversion::ConversionFormat GetConversionFormat( ) const;\n\n void SetByCharacter( sal_Bool _bByCharacter );\n sal_Bool GetByCharacter( ) const;\n\n \/\/ should text which does not fit the primary conversion direction be ignored\n void SetUseBothDirections( sal_Bool _bBoth ) const;\n sal_Bool GetUseBothDirections( ) const;\n\n private:\n DECL_LINK( OnClose, void* );\n DECL_LINK( OnSuggestionModified, void* );\n DECL_LINK( OnSuggestionSelected, void* );\n\n \/\/ fill the suggestion list box with suggestions for the actual input\n void FillSuggestions( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rSuggestions );\n };\n\n\/\/.............................................................................\n} \/\/ namespace svx\n\/\/.............................................................................\n\n#endif \/\/ SVX_HANGUL_HANJA_HXX\nINTEGRATION: CWS tl01 (1.2.120); FILE MERGED 2004\/03\/18 13:40:23 gt 1.2.120.6: #111170# 2004\/03\/16 13:55:23 gt 1.2.120.5: #111170# hangul hanja conversion options dlg 2004\/03\/11 16:14:11 gt 1.2.120.4: #111170# intermediate changes 2003\/11\/18 11:40:19 tl 1.2.120.3: #109443# include statement fixed 2003\/11\/02 18:01:40 gt 1.2.120.2: #111170# common ui 2003\/08\/29 09:44:54 tl 1.2.120.1: #110177# Hangul\/Hanja conversion for Sdr objects (EditEngine)\/*************************************************************************\n *\n * $RCSfile: hangulhanjadlg.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: obo $ $Date: 2004-04-27 15:46:58 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef SVX_HANGUL_HANJA_DLG_HXX\n#define SVX_HANGUL_HANJA_DLG_HXX\n\n#ifndef _SV_DIALOG_HXX\n#include \n#endif\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n#ifndef _SV_LSTBOX_HXX\n#include \n#endif\n#ifndef _SV_COMBOBOX_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef _SV_SCRBAR_HXX\n#include \n#endif\n#ifndef _SVX_CHECKLBX_HXX\n#include \"checklbx.hxx\"\n#endif\n#ifndef SVX_HANGUL_HANJA_CONVERSION_HXX\n#include \"hangulhanja.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_\n#include \n#endif\n#ifndef _UNO_LINGU_HXX\n#include \"unolingu.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_LINGUISTIC2_XCONVERSIONDICTIONARYLIST_HPP_\n#include \n#endif\n\n\n#include \/\/ for auto_ptr\n\nclass SvxCommonLinguisticControl;\n\/\/.............................................................................\nnamespace svx\n{\n\/\/.............................................................................\n\n \/\/=========================================================================\n \/\/= HangulHanjaConversionDialog\n \/\/=========================================================================\n\n class HangulHanjaConversionDialog : public ModalDialog\n {\n private:\n ::std::auto_ptr< SvxCommonLinguisticControl >\n m_pPlayground; \/\/ order matters: before all other controls!\n\n PushButton m_aFind;\n ListBox m_aSuggestions;\n FixedText m_aFormat;\n RadioButton m_aSimpleConversion;\n RadioButton m_aHangulBracketed;\n RadioButton m_aHanjaBracketed;\n ::std::auto_ptr< RadioButton > m_pHanjaAbove;\n ::std::auto_ptr< RadioButton > m_pHanjaBelow;\n ::std::auto_ptr< RadioButton > m_pHangulAbove;\n ::std::auto_ptr< RadioButton > m_pHangulBelow;\n FixedText m_aConversion;\n CheckBox m_aHangulOnly;\n CheckBox m_aHanjaOnly;\n CheckBox m_aReplaceByChar;\n\n CheckBox* m_pIgnoreNonPrimary;\n bool m_bDocumentMode;\n \/\/ are we working for a document? This is normally true, but in case\n \/\/ the user uses the \"find\" functionality, we switch to working\n \/\/ with what the user entered, which then does not have any relation to\n \/\/ the document anymore. Some functionality must be disabled then\n public:\n HangulHanjaConversionDialog(\n Window* _pParent,\n HangulHanjaConversion::ConversionDirection _ePrimaryDirection );\n ~HangulHanjaConversionDialog( );\n\n public:\n void SetIgnoreHdl( const Link& _rHdl );\n void SetIgnoreAllHdl( const Link& _rHdl );\n void SetChangeHdl( const Link& _rHdl );\n void SetChangeAllHdl( const Link& _rHdl );\n void SetOptionsHdl( const Link& _rHdl );\n\n void SetClickByCharacterHdl( const Link& _rHdl );\n void SetConversionFormatChangedHdl( const Link& _rHdl );\n void SetFindHdl( const Link& _rHdl );\n\n String GetCurrentString( ) const;\n void SetCurrentString(\n const String& _rNewString,\n const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rSuggestions,\n bool _bOriginatesFromDocument = true\n );\n\n void FocusSuggestion( );\n\n \/\/ retrieves the current suggestion\n String GetCurrentSuggestion( ) const;\n\n void SetConversionFormat( HangulHanjaConversion::ConversionFormat _eType );\n HangulHanjaConversion::ConversionFormat GetConversionFormat( ) const;\n\n void SetByCharacter( sal_Bool _bByCharacter );\n sal_Bool GetByCharacter( ) const;\n\n \/\/ should text which does not fit the primary conversion direction be ignored\n void SetUseBothDirections( sal_Bool _bBoth ) const;\n sal_Bool GetUseBothDirections( ) const;\n\n \/\/ enables or disbales the checkboxes for ruby formatted replacements\n void EnableRubySupport( sal_Bool bVal );\n\n private:\n DECL_LINK( OnClose, void* );\n DECL_LINK( OnOption, void* );\n DECL_LINK( OnSuggestionModified, void* );\n DECL_LINK( OnSuggestionSelected, void* );\n\n \/\/ fill the suggestion list box with suggestions for the actual input\n void FillSuggestions( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rSuggestions );\n };\n\n\n class HHDictList\n {\n private:\n ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XConversionDictionary > >\n m_aList;\n sal_uInt32 m_nNew; \/\/ position where the next dictionary will be inserted\n protected:\n public:\n HHDictList( void );\n virtual ~HHDictList();\n\n void Clear( void );\n void Add( ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XConversionDictionary > _xDict );\n sal_uInt32 Count( void ) const;\n ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XConversionDictionary >\n Get( sal_uInt32 _nInd );\n String GetName( sal_uInt32 _nInd );\n bool GetIsActive( sal_uInt32 _nInd );\n };\n\n\n class HangulHanjaOptionsDialog : public ModalDialog\n {\n private:\n FixedText m_aUserdefdictFT;\n SvxCheckListBox m_aDictsLB;\n FixedLine m_aOptionsFL;\n CheckBox m_aIgnorepostCB;\n CheckBox m_aAutocloseCB;\n CheckBox m_aShowrecentlyfirstCB;\n CheckBox m_aAutoreplaceuniqueCB;\n PushButton m_aNewPB;\n PushButton m_aEditPB;\n PushButton m_aDeletePB;\n OKButton m_aOkPB;\n CancelButton m_aCancelPB;\n HelpButton m_aHelpPB;\n\n SvLBoxButtonData* m_pCheckButtonData;\n\n HHDictList m_aDictList;\n\n DECL_LINK( OkHdl, void* );\n DECL_LINK( OnNew, void* );\n DECL_LINK( OnEdit, void* );\n DECL_LINK( OnDelete, void* );\n DECL_LINK( DictsLB_SelectHdl, void* );\n DECL_LINK( NewDictHdl, void* );\n DECL_LINK( EditDictHdl, void* );\n DECL_LINK( DeleteDictHdl, void* );\n\n void Init( void ); \/\/ reads settings from core and init controls\n public:\n HangulHanjaOptionsDialog( Window* _pParent );\n virtual ~HangulHanjaOptionsDialog();\n\n void AddDict( const String& _rName, bool _bChecked );\n };\n\n\n class HangulHanjaNewDictDialog : public ModalDialog\n {\n private:\n FixedLine m_aNewDictFL;\n FixedText m_aDictNameFT;\n Edit m_aDictNameED;\n OKButton m_aOkBtn;\n CancelButton m_aCancelBtn;\n HelpButton m_aHelpBtn;\n\n bool m_bEntered;\n\n DECL_LINK( OKHdl, void* );\n DECL_LINK( ModifyHdl, void* );\n protected:\n public:\n HangulHanjaNewDictDialog( Window* _pParent );\n virtual ~HangulHanjaNewDictDialog();\n\n bool GetName( String& _rRetName ) const;\n };\n\n\n class SuggestionList;\n\n class SuggestionEdit : public Edit\n {\n private:\n SuggestionEdit* m_pPrev;\n SuggestionEdit* m_pNext;\n ScrollBar& m_rScrollBar;\n\n bool ShouldScroll( bool _bUp ) const;\n void DoJump( bool _bUp );\n public:\n SuggestionEdit( Window* pParent, const ResId& rResId,\n ScrollBar& _rScrollBar,\n SuggestionEdit* _pPrev, SuggestionEdit* _pNext );\n virtual ~SuggestionEdit();\n virtual long PreNotify( NotifyEvent& rNEvt );\n };\n\n\n class HangulHanjaEditDictDialog : public ModalDialog\n {\n private:\n enum EditState\n {\n ES_NIL, \/\/ neither original nor suggestion(s) entered\n ES_NEW_ORG_EMPTY, \/\/ a new original was entered, no suggestion(s)\n ES_NEW_SUGG, \/\/ no original was entered but at least one suggestion\n ES_NEW_ORG_SUGG, \/\/ a new original and at least one suggestion was entered\n ES_EXIST_ORG, \/\/ while typing, an existing entry matched\n ES_EXIST_ORG_MOD \/\/ an existing entry has been modified\n };\n EditState m_eState;\n const String m_aEditHintText;\n HHDictList& m_rDictList;\n sal_uInt32 m_nCurrentDict;\n\n String m_aOriginal;\n SuggestionList* m_pSuggestions;\n\n FixedText m_aBookFT;\n ListBox m_aBookLB;\n FixedText m_aOriginalFT;\n ComboBox m_aOriginalLB;\n CheckBox m_aReplacebycharCB;\n FixedText m_aSuggestionsFT;\n SuggestionEdit m_aEdit1;\n SuggestionEdit m_aEdit2;\n SuggestionEdit m_aEdit3;\n SuggestionEdit m_aEdit4;\n ScrollBar m_aScrollSB;\n PushButton m_aNewPB;\n PushButton m_aDeletePB;\n HelpButton m_aHelpPB;\n CancelButton m_aClosePB;\n\n bool m_bModified;\n bool m_bNew;\n sal_uInt16 m_nTopPos;\n\n DECL_LINK( OriginalModifyHdl, void* );\n DECL_LINK( OriginalFocusLostHdl, void* );\n DECL_LINK( ScrollHdl, void* );\n DECL_LINK( EditModifyHdl1, Edit* );\n DECL_LINK( EditModifyHdl2, Edit* );\n DECL_LINK( EditModifyHdl3, Edit* );\n DECL_LINK( EditModifyHdl4, Edit* );\n DECL_LINK( EditFocusLostHdl1, Edit* );\n DECL_LINK( EditFocusLostHdl2, Edit* );\n DECL_LINK( EditFocusLostHdl3, Edit* );\n DECL_LINK( EditFocusLostHdl4, Edit* );\n\n DECL_LINK( BookLBSelectHdl, void* );\n DECL_LINK( OriginalLBSelectHdl, void* );\n DECL_LINK( NewPBPushHdl, void* );\n DECL_LINK( DeletePBPushHdl, void* );\n\n void Init( sal_uInt32 _nSelDict );\n void UpdateOriginalLB( void );\n void UpdateSuggestions( void );\n void UpdateSuggestions( const ::com::sun::star::uno::Sequence< ::rtl::OUString >& _rSuggestions );\n void Leave( void );\n void CheckNewState( void );\n \/\/ checks if enough data is entered to enable \"New\" Button and set Button state accordingly\n void SetSuggestion( const String& _rText, sal_uInt16 _nEntryNum );\n void ResetSuggestion( sal_uInt16 _nEntryNum );\n void SetEditText( Edit& _rEdit, sal_uInt16 _nEntryNum );\n void EditModify( Edit* _pEdit, sal_uInt8 _nEntryOffset );\n void EditFocusLost( Edit* _pEdit, sal_uInt8 _nEntryOffset );\n public:\n HangulHanjaEditDictDialog( Window* _pParent, HHDictList& _rDictList, sal_uInt32 _nSelDict );\n ~HangulHanjaEditDictDialog();\n\n void UpdateScrollbar( void );\n };\n\n\/\/.............................................................................\n} \/\/ namespace svx\n\/\/.............................................................................\n\n#endif \/\/ SVX_HANGUL_HANJA_HXX\n<|endoftext|>"} {"text":"#include \"ConstantProp.hpp\"\n\nusing namespace IR;\n\nvoid determineGlobalConstants()\n{\n for(auto& s : IR::ir)\n {\n auto subr = s.second;\n auto writes = subr->getWrites();\n for(auto v : writes)\n {\n if(v->isGlobal())\n {\n IR::globalConstants[v] = false;\n }\n }\n }\n}\n\n\/\/Convert a constant expression to another type\n\/\/conv->value must already be folded and be constant\nstatic Expression* convertConstant(Converted* conv)\n{\n if(auto intConst = dynamic_cast(conv->value))\n {\n \/\/do the conversion which tests for overflow\n return intConst->convert(conv->type);\n }\n else if(auto floatConst = dynamic_cast(conv->value))\n {\n return floatConst->convert(conv->type);\n }\n else if(auto enumConst = dynamic_cast(conv->value))\n {\n return enumConst->convert(conv->type);\n }\n \/\/array\/struct\/tuple constants can be converted implicitly\n \/\/to each other (all use CompoundLiteral) but individual\n \/\/members (primitives) may need conversion\n else if(auto compLit = dynamic_cast(conv->value))\n {\n \/\/attempt to fold all elements (can't proceed unless every\n \/\/one is a constant)\n bool allConstant = true;\n for(auto& mem : compLit->members)\n allConstant = allConstant && foldExpression(mem);\n if(!allConstant)\n return false;\n if(auto st = dynamic_cast(conv->type))\n {\n }\n else if(auto tt = dynamic_cast(conv->type))\n {\n }\n else if(auto mt = dynamic_cast(conv->type))\n {\n expr = new MapConstant;\n \/\/convert key\/value pairs to \n }\n }\n}\n\n\/\/Try to fold an expression, bottom-up\n\/\/Can fold all constants in one pass\n\/\/\n\/\/Return true if any IR changes are made\n\/\/Set constant to true if expr is now, or was already, a constant\nstatic bool foldExpression(Expression*& expr)\n{\n if(dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr))\n {\n \/\/already completely folded constant, nothing to do\n return true;\n }\n else if(auto conv = dynamic_cast(expr))\n {\n foldExpression(conv->value);\n if(conv->value->constant())\n {\n expr = convertConstant(conv);\n return true;\n }\n else\n {\n return false;\n }\n }\n {\n \/\/already constant and nothing to do\n constant = true;\n return false;\n }\n else if(auto& binArith = dynamic_cast(expr))\n {\n bool lhsConstant = false;\n bool rhsConstant = false;\n foldExpression(binArith->lhs, lhsConstant);\n foldExpression(binArith->rhs, rhsConstant);\n if(lhsConstant && rhsConstant)\n {\n constant = true;\n return true;\n }\n else\n {\n return false;\n }\n }\n else if(\n}\n\nbool constantFold(IR::SubroutineIR* subr)\n{\n \/\/every expression (including parts of an assignment LHS)\n \/\/may be folded (i.e. myArray[5 + 3] = 8 % 3)\n \/\/\n \/\/recursivly attempt to fold expressions bottom-up,\n \/\/remembering which input expressions are constants\n}\n\nbool constantPropagation(SubroutineIR* subr)\n{\n bool update = false;\n \/\/First, go through each BB and replace general Expressions\n \/\/with constants wherever possible (constant folding)\n \/\/\n \/\/Also record which variables hold constant values at exit of BBs\n \/\/\n \/\/Then do constant propagation dataflow analysis across BBs\n \/\/\n \/\/VarExprs of constant variables can then be replaced by constant\n for(auto bb : subr->blocks)\n {\n for(int i = bb->start; i < bb->end; i++)\n {\n Statement* stmt = subr->stmts[i];\n }\n }\n return update;\n}\n\nImproved global constant analysis#include \"ConstantProp.hpp\"\n\nusing namespace IR;\n\nvoid determineGlobalConstants()\n{\n for(auto& s : IR::ir)\n {\n auto subr = s.second;\n for(auto stmt : subr->stmts)\n {\n auto outputs = stmt->getOutput();\n for(auto out : outputs)\n {\n auto writes = out->getWrites();\n for(auto w : writes)\n {\n if(w->isGlobal())\n {\n \/\/there is an assignment to w,\n \/\/so w is not a constant\n IR::globalConstants[w] = false;\n }\n }\n }\n }\n }\n}\n\n\/\/Convert a constant expression to another type\n\/\/conv->value must already be folded and be constant\nstatic Expression* convertConstant(Converted* conv)\n{\n if(auto intConst = dynamic_cast(conv->value))\n {\n \/\/do the conversion which tests for overflow\n return intConst->convert(conv->type);\n }\n else if(auto floatConst = dynamic_cast(conv->value))\n {\n return floatConst->convert(conv->type);\n }\n else if(auto enumConst = dynamic_cast(conv->value))\n {\n return enumConst->convert(conv->type);\n }\n \/\/array\/struct\/tuple constants can be converted implicitly\n \/\/to each other (all use CompoundLiteral) but individual\n \/\/members (primitives) may need conversion\n else if(auto compLit = dynamic_cast(conv->value))\n {\n \/\/attempt to fold all elements (can't proceed unless every\n \/\/one is a constant)\n bool allConstant = true;\n for(auto& mem : compLit->members)\n allConstant = allConstant && foldExpression(mem);\n if(!allConstant)\n return false;\n if(auto st = dynamic_cast(conv->type))\n {\n }\n else if(auto tt = dynamic_cast(conv->type))\n {\n }\n else if(auto mt = dynamic_cast(conv->type))\n {\n expr = new MapConstant;\n \/\/convert key\/value pairs to \n }\n }\n}\n\n\/\/Try to fold an expression, bottom-up\n\/\/Can fold all constants in one pass\n\/\/\n\/\/Return true if any IR changes are made\n\/\/Set constant to true if expr is now, or was already, a constant\nstatic bool foldExpression(Expression*& expr)\n{\n if(dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr) ||\n dynamic_cast(expr))\n {\n \/\/already completely folded constant, nothing to do\n return true;\n }\n else if(auto conv = dynamic_cast(expr))\n {\n foldExpression(conv->value);\n if(conv->value->constant())\n {\n expr = convertConstant(conv);\n return true;\n }\n else\n {\n return false;\n }\n }\n {\n \/\/already constant and nothing to do\n constant = true;\n return false;\n }\n else if(auto& binArith = dynamic_cast(expr))\n {\n bool lhsConstant = false;\n bool rhsConstant = false;\n foldExpression(binArith->lhs, lhsConstant);\n foldExpression(binArith->rhs, rhsConstant);\n if(lhsConstant && rhsConstant)\n {\n constant = true;\n return true;\n }\n else\n {\n return false;\n }\n }\n else if(\n}\n\nbool constantFold(IR::SubroutineIR* subr)\n{\n \/\/every expression (including parts of an assignment LHS)\n \/\/may be folded (i.e. myArray[5 + 3] = 8 % 3)\n \/\/\n \/\/recursivly attempt to fold expressions bottom-up,\n \/\/remembering which input expressions are constants\n}\n\nbool constantPropagation(SubroutineIR* subr)\n{\n bool update = false;\n \/\/First, go through each BB and replace general Expressions\n \/\/with constants wherever possible (constant folding)\n \/\/\n \/\/Also record which variables hold constant values at exit of BBs\n \/\/\n \/\/Then do constant propagation dataflow analysis across BBs\n \/\/\n \/\/VarExprs of constant variables can then be replaced by constant\n for(auto bb : subr->blocks)\n {\n for(int i = bb->start; i < bb->end; i++)\n {\n Statement* stmt = subr->stmts[i];\n }\n }\n return update;\n}\n\n<|endoftext|>"} {"text":"#include \"CssTokenizer.h\"\n\nCssTokenizer::CssTokenizer(istream* in){\n this->in = in;\n line = 1;\n column = 0;\n readChar();\n}\n\nCssTokenizer::~CssTokenizer(){\n}\n\nvoid CssTokenizer::readChar(){\n if (in != NULL) {\n \/\/ Last char was a newline. Increment the line counter.\n if (lastReadEq('\\n')) {\n line++;\n column = 0;\n }\n \n in->get(lastRead);\n\n \/\/ check for end of file or escape key\n if(in->eof() || lastRead == 27) \n in = NULL;\n else if (in->fail() || in->bad())\n throw new IOException(\"Error reading input\");\n\n if (!lastReadEq('\\n')) \/\/ count chars that aren't newlines\n column++; \n }\n}\n\nToken::Type CssTokenizer::readNextToken(){\n if (in == NULL) {\n currentToken.type = Token::EOS;\n return Token::EOS;\n }\n\n currentToken.clear();\n switch (lastRead) {\n case '@':\n currentToken.type = Token::ATKEYWORD;\n currentToken.add(lastRead);\n readChar();\n if (!readIdent()) {\n currentToken.type = Token::OTHER;\n }\n break;\n \n case '#':\n currentToken.type = Token::HASH;\n currentToken.add(lastRead);\n readChar();\n if (!readName()) {\n throw new ParseException(&lastRead,\n \"name following '#'\");\n }\n break;\n \n case '-':\n currentToken.add(lastRead);\n readChar();\n if (readNum()) {\n currentToken.type = Token::NUMBER;\n if (lastReadEq('%')) {\n currentToken.type = Token::PERCENTAGE;\n currentToken.add(lastRead);\n readChar();\n } else if (readIdent()) \n currentToken.type = Token::DIMENSION;\n } else if (readIdent()) {\n currentToken.type = Token::IDENTIFIER;\n if (lastRead == '(') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::FUNCTION;\n }\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '~':\n currentToken.add(lastRead);\n readChar();\n if (lastRead == '=') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::INCLUDES;\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '|':\n currentToken.add(lastRead);\n readChar();\n if (lastRead == '=') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::DASHMATCH;\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '\/':\n currentToken.add(lastRead);\n readChar();\n if (readComment()) \n currentToken.type = Token::COMMENT;\n else\n currentToken.type = Token::OTHER;\n break;\n \n case ';':\n currentToken.type = Token::DELIMITER;\n currentToken.add(lastRead);\n readChar();\n break;\n case ':':\n currentToken.type = Token::COLON;\n currentToken.add(lastRead);\n readChar();\n break;\n case '{':\n currentToken.type = Token::BRACKET_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case '}':\n currentToken.type = Token::BRACKET_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n case '(':\n currentToken.type = Token::PAREN_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case ')':\n currentToken.type = Token::PAREN_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n case '[':\n currentToken.type = Token::BRACE_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case ']':\n currentToken.type = Token::BRACE_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n\n default:\n if (readString()) \n currentToken.type = Token::STRING;\n else if (readNum()) {\n currentToken.type = Token::NUMBER;\n if (lastRead == '%') {\n currentToken.type = Token::PERCENTAGE;\n currentToken.add(lastRead);\n readChar();\n } else if (readIdent()) \n currentToken.type = Token::DIMENSION;\n \n } else if (readIdent()) {\n currentToken.type = Token::IDENTIFIER;\n\n if (currentToken.str == \"url\" && readUrl())\n currentToken.type = Token::URL;\n else if (currentToken.str == \"u\" && lastReadEq('+')) {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::UNICODE_RANGE;\n readUnicodeRange();\n } else if (lastReadEq('(')) {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::FUNCTION;\n }\n } else if (readWhitespace()) {\n currentToken.type = Token::WHITESPACE;\n while (readWhitespace()) {};\n } \n }\n return currentToken.type;\n}\n\n\nbool CssTokenizer::readIdent () {\n if (lastReadEq('-')) {\n currentToken.add(lastRead);\n readChar();\n }\n if (!readNMStart())\n return false;\n else\n while (readNMChar()) {}\n return true;\n}\n\nbool CssTokenizer::readName () {\n if (!readNMChar())\n return false;\n while (readNMChar()) {}\n return true;\n}\n\nbool CssTokenizer::readNMStart () {\n if (in == NULL)\n return false;\n \n if (lastReadEq('_') ||\n lastReadInRange('a', 'z') ||\n lastReadInRange('A', 'Z')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return (readNonAscii() || readEscape());\n}\nbool CssTokenizer::readNonAscii () {\n if (in == NULL)\n return false;\n \n if (lastRead >= 0) {\n return false;\n } else {\n currentToken.add(lastRead);\n readChar();\n return true;\n } \n}\nbool CssTokenizer::readEscape () {\n if (!lastReadEq('\\\\'))\n return false;\n currentToken.add(lastRead);\n readChar();\n \n if (readUnicode()) \n return true; \n else if (!lastReadEq('\\n') &&\n !lastReadEq('\\r') &&\n !lastReadEq('\\f')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return false;\n}\nbool CssTokenizer::readUnicode () {\n if (!lastReadIsHex())\n return false;\n\n \/\/ [0-9a-f]{1,6}(\\r\\n|[ \\n\\r\\t\\f])?\n for (int i=0; i < 6; i++) {\n if (readWhitespace())\n break;\n currentToken.add(lastRead);\n readChar();\n if (!lastReadIsHex()) {\n \/*throw new ParseException(&lastRead,\n \"hex code(0-9a-f) in unicode character\");*\/\n \/* Just ignore and assume the unicode stops here *\/\n break;\n }\n }\n return true;\n}\n\nbool CssTokenizer::readNMChar () {\n if (in == NULL)\n return false;\n \n if (lastReadEq('_') ||\n lastReadInRange('a', 'z') ||\n lastReadInRange('A', 'Z') ||\n lastReadIsDigit() ||\n lastReadEq('-')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return (readNonAscii() || readEscape());\n}\n\nbool CssTokenizer::readNum () {\n if (!lastReadIsDigit() && !lastReadEq('.'))\n return false;\n while (lastReadIsDigit()) {\n currentToken.add(lastRead);\n readChar();\n }\n if (lastReadEq('.')) {\n currentToken.add(lastRead);\n readChar();\n\n while (lastReadIsDigit()) {\n currentToken.add(lastRead);\n readChar();\n }\n }\n return true;\n}\n\nbool CssTokenizer::readString() {\n if (!lastReadEq('\"') && !lastReadEq('\\''))\n return false;\n char delim = lastRead;\n\n currentToken.add(lastRead);\n readChar();\n while (in != NULL) {\n if (lastReadEq(delim)) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else if (lastReadEq('\\n') ||\n lastReadEq('\\r') ||\n lastReadEq('\\f')) {\n throw new ParseException(\"end of line\",\n \"end of string\");\n } else if (lastReadEq('\\\\'))\n \/\/ note that even though readEscape() returns false it still\n \/\/ eats the '\\'.\n readEscape() || readNewline();\n else {\n currentToken.add(lastRead);\n readChar();\n }\n }\n throw new ParseException(\"end of input\",\n \"end of string\");\n return false;\n}\n\nbool CssTokenizer::readNewline () {\n if (lastReadEq('\\r')) {\n currentToken.add(lastRead);\n readChar();\n if (lastReadEq('\\n')) {\n currentToken.add(lastRead);\n readChar();\n }\n return true;\n } else if (lastReadEq('\\n') ||\n lastReadEq('\\f')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return false;\n}\n\nbool CssTokenizer::readWhitespace () {\n if (!lastReadEq(' ') &&\n !lastReadEq('\\t') &&\n !lastReadEq('\\r') &&\n !lastReadEq('\\n') &&\n !lastReadEq('\\f'))\n return false;\n \n currentToken.add(lastRead);\n readChar();\n return true;\n}\n\nbool CssTokenizer::readUrl() {\n string urlchars = \"!#$%&*-[]-~\";\n \n if (!lastReadEq('('))\n return false;\n currentToken.add(lastRead);\n readChar();\n while(readWhitespace()) {};\n \n if (readString()) {\n if (lastReadEq(')')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n }\n\n while (in != NULL) {\n if (readWhitespace() || lastReadEq(')')) {\n while (readWhitespace()) {};\n if (lastReadEq(')')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n } else if (in != NULL && urlchars.find(lastRead)) {\n currentToken.add(lastRead);\n readChar();\n } else if (!readNonAscii() &&\n !readEscape()) {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n }\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n return false;\n}\n\n\nbool CssTokenizer::readComment () {\n if (!lastReadEq('*'))\n return false;\n currentToken.add(lastRead);\n readChar();\n while (in != NULL) {\n if (lastReadEq('*')) {\n currentToken.add(lastRead);\n readChar();\n \n if (lastReadEq('\/')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n }\n }\n currentToken.add(lastRead);\n readChar();\n }\n throw new ParseException(&lastRead,\n \"end of comment (*\/)\");\n return false;\n}\n\nbool CssTokenizer::readUnicodeRange () {\n if (in == NULL)\n return false;\n for (int i=0; i < 6; i++) {\n if (!lastReadIsHex())\n break;\n currentToken.add(lastRead);\n readChar();\n }\n if (!lastReadEq('-'))\n return true;\n \n for (int i=0; i < 6; i++) {\n if (!lastReadIsHex())\n break;\n currentToken.add(lastRead);\n readChar();\n }\n return true;\n}\n\nToken* CssTokenizer::getToken(){\n return ¤tToken;\n}\nToken::Type CssTokenizer::getTokenType() {\n return currentToken.type;\n}\n\nunsigned int CssTokenizer::getLineNumber(){\n return line;\n}\nunsigned int CssTokenizer::getColumn(){\n return column;\n}\n\nbool CssTokenizer::lastReadEq(char c) {\n return (in != NULL && lastRead == c);\n}\n\nbool CssTokenizer::lastReadInRange(char c1, char c2) {\n return (in != NULL && lastRead >= c1 && lastRead <= c2);\n}\nbool CssTokenizer::lastReadIsDigit() {\n return (in != NULL &&\n lastReadInRange('0', '9'));\n}\nbool CssTokenizer::lastReadIsHex() {\n return (in != NULL &&\n (lastReadIsDigit() ||\n lastReadInRange('a', 'f') ||\n lastReadInRange('A', 'F')));\n}\nCleaning up CssTokenizer.cpp.#include \"CssTokenizer.h\"\n\nCssTokenizer::CssTokenizer(istream* in){\n this->in = in;\n line = 1;\n column = 0;\n readChar();\n}\n\nCssTokenizer::~CssTokenizer(){\n}\n\nvoid CssTokenizer::readChar(){\n if (in == NULL) \n return;\n \n \/\/ Last char was a newline. Increment the line counter.\n if (lastReadEq('\\n')) {\n line++;\n column = 0;\n }\n \n in->get(lastRead);\n\n \/\/ check for end of file or escape key\n if(in->eof() || lastRead == 27) \n in = NULL;\n else if (in->fail() || in->bad())\n throw new IOException(\"Error reading input\");\n\n if (!lastReadEq('\\n')) \/\/ count chars that aren't newlines\n column++; \n}\n\nToken::Type CssTokenizer::readNextToken(){\n if (in == NULL) {\n currentToken.type = Token::EOS;\n return Token::EOS;\n }\n\n currentToken.clear();\n switch (lastRead) {\n case '@':\n currentToken.type = Token::ATKEYWORD;\n currentToken.add(lastRead);\n readChar();\n if (!readIdent()) {\n currentToken.type = Token::OTHER;\n }\n break;\n \n case '#':\n currentToken.type = Token::HASH;\n currentToken.add(lastRead);\n readChar();\n if (!readName()) {\n throw new ParseException(&lastRead,\n \"name following '#'\");\n }\n break;\n \n case '-':\n currentToken.add(lastRead);\n readChar();\n if (readNum()) {\n currentToken.type = Token::NUMBER;\n if (lastReadEq('%')) {\n currentToken.type = Token::PERCENTAGE;\n currentToken.add(lastRead);\n readChar();\n } else if (readIdent()) \n currentToken.type = Token::DIMENSION;\n } else if (readIdent()) {\n currentToken.type = Token::IDENTIFIER;\n if (lastRead == '(') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::FUNCTION;\n }\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '~':\n currentToken.add(lastRead);\n readChar();\n if (lastRead == '=') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::INCLUDES;\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '|':\n currentToken.add(lastRead);\n readChar();\n if (lastRead == '=') {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::DASHMATCH;\n } else\n currentToken.type = Token::OTHER;\n break;\n \n case '\/':\n currentToken.add(lastRead);\n readChar();\n if (readComment()) \n currentToken.type = Token::COMMENT;\n else\n currentToken.type = Token::OTHER;\n break;\n \n case ';':\n currentToken.type = Token::DELIMITER;\n currentToken.add(lastRead);\n readChar();\n break;\n case ':':\n currentToken.type = Token::COLON;\n currentToken.add(lastRead);\n readChar();\n break;\n case '{':\n currentToken.type = Token::BRACKET_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case '}':\n currentToken.type = Token::BRACKET_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n case '(':\n currentToken.type = Token::PAREN_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case ')':\n currentToken.type = Token::PAREN_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n case '[':\n currentToken.type = Token::BRACE_OPEN;\n currentToken.add(lastRead);\n readChar();\n break;\n case ']':\n currentToken.type = Token::BRACE_CLOSED;\n currentToken.add(lastRead);\n readChar();\n break;\n\n default:\n if (readString()) \n currentToken.type = Token::STRING;\n else if (readNum()) {\n currentToken.type = Token::NUMBER;\n if (lastRead == '%') {\n currentToken.type = Token::PERCENTAGE;\n currentToken.add(lastRead);\n readChar();\n } else if (readIdent()) \n currentToken.type = Token::DIMENSION;\n \n } else if (readIdent()) {\n currentToken.type = Token::IDENTIFIER;\n\n if (currentToken.str == \"url\" && readUrl())\n currentToken.type = Token::URL;\n else if (currentToken.str == \"u\" && lastReadEq('+')) {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::UNICODE_RANGE;\n readUnicodeRange();\n } else if (lastReadEq('(')) {\n currentToken.add(lastRead);\n readChar();\n currentToken.type = Token::FUNCTION;\n }\n } else if (readWhitespace()) {\n currentToken.type = Token::WHITESPACE;\n while (readWhitespace()) {};\n }\n break;\n }\n\n return currentToken.type;\n}\n\n\nbool CssTokenizer::readIdent () {\n if (lastReadEq('-')) {\n currentToken.add(lastRead);\n readChar();\n }\n if (!readNMStart())\n return false;\n else\n while (readNMChar()) {}\n return true;\n}\n\nbool CssTokenizer::readName () {\n if (!readNMChar())\n return false;\n while (readNMChar()) {}\n return true;\n}\n\nbool CssTokenizer::readNMStart () {\n if (in == NULL)\n return false;\n \n if (lastReadEq('_') ||\n lastReadInRange('a', 'z') ||\n lastReadInRange('A', 'Z')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return (readNonAscii() || readEscape());\n}\nbool CssTokenizer::readNonAscii () {\n if (in == NULL)\n return false;\n \n if (lastRead >= 0) {\n return false;\n } else {\n currentToken.add(lastRead);\n readChar();\n return true;\n } \n}\nbool CssTokenizer::readEscape () {\n if (!lastReadEq('\\\\'))\n return false;\n currentToken.add(lastRead);\n readChar();\n \n if (readUnicode()) \n return true; \n else if (!lastReadEq('\\n') &&\n !lastReadEq('\\r') &&\n !lastReadEq('\\f')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return false;\n}\nbool CssTokenizer::readUnicode () {\n if (!lastReadIsHex())\n return false;\n\n \/\/ [0-9a-f]{1,6}(\\r\\n|[ \\n\\r\\t\\f])?\n for (int i=0; i < 6; i++) {\n currentToken.add(lastRead);\n readChar();\n if (readWhitespace() || !lastReadIsHex())\n break;\n }\n return true;\n}\n\nbool CssTokenizer::readNMChar () {\n if (in == NULL)\n return false;\n \n if (lastReadEq('_') ||\n lastReadInRange('a', 'z') ||\n lastReadInRange('A', 'Z') ||\n lastReadIsDigit() ||\n lastReadEq('-')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return (readNonAscii() || readEscape());\n}\n\nbool CssTokenizer::readNum () {\n if (!lastReadIsDigit() && !lastReadEq('.'))\n return false;\n while (lastReadIsDigit()) {\n currentToken.add(lastRead);\n readChar();\n }\n if (lastReadEq('.')) {\n currentToken.add(lastRead);\n readChar();\n\n while (lastReadIsDigit()) {\n currentToken.add(lastRead);\n readChar();\n }\n }\n return true;\n}\n\nbool CssTokenizer::readString() {\n if (!lastReadEq('\"') && !lastReadEq('\\''))\n return false;\n char delim = lastRead;\n\n currentToken.add(lastRead);\n readChar();\n while (in != NULL) {\n if (lastReadEq(delim)) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else if (lastReadEq('\\n') ||\n lastReadEq('\\r') ||\n lastReadEq('\\f')) {\n throw new ParseException(\"end of line\",\n \"end of string\");\n } else if (lastReadEq('\\\\'))\n \/\/ note that even though readEscape() returns false it still\n \/\/ eats the '\\'.\n readEscape() || readNewline();\n else {\n currentToken.add(lastRead);\n readChar();\n }\n }\n throw new ParseException(\"end of input\",\n \"end of string\");\n return false;\n}\n\nbool CssTokenizer::readNewline () {\n if (lastReadEq('\\r')) {\n currentToken.add(lastRead);\n readChar();\n if (lastReadEq('\\n')) {\n currentToken.add(lastRead);\n readChar();\n }\n return true;\n } else if (lastReadEq('\\n') ||\n lastReadEq('\\f')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return false;\n}\n\nbool CssTokenizer::readWhitespace () {\n if (lastReadEq(' ') ||\n lastReadEq('\\t') ||\n lastReadEq('\\r') ||\n lastReadEq('\\n') ||\n lastReadEq('\\f')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else\n return false;\n}\n\nbool CssTokenizer::readUrl() {\n string urlchars = \"!#$%&*-[]-~\";\n \n if (!lastReadEq('('))\n return false;\n currentToken.add(lastRead);\n readChar();\n while(readWhitespace()) {};\n \n if (readString()) {\n if (lastReadEq(')')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n }\n\n while (in != NULL) {\n if (readWhitespace() || lastReadEq(')')) {\n while (readWhitespace()) {};\n if (lastReadEq(')')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n } else {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n } else if (in != NULL && urlchars.find(lastRead)) {\n currentToken.add(lastRead);\n readChar();\n } else if (!readNonAscii() &&\n !readEscape()) {\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n }\n }\n throw new ParseException(&lastRead,\n \"end of url (')')\");\n return false;\n}\n\n\nbool CssTokenizer::readComment () {\n if (!lastReadEq('*'))\n return false;\n currentToken.add(lastRead);\n readChar();\n while (in != NULL) {\n if (lastReadEq('*')) {\n currentToken.add(lastRead);\n readChar();\n \n if (lastReadEq('\/')) {\n currentToken.add(lastRead);\n readChar();\n return true;\n }\n }\n currentToken.add(lastRead);\n readChar();\n }\n throw new ParseException(&lastRead,\n \"end of comment (*\/)\");\n return false;\n}\n\nbool CssTokenizer::readUnicodeRange () {\n if (in == NULL)\n return false;\n for (int i=0; i < 6; i++) {\n if (!lastReadIsHex())\n break;\n currentToken.add(lastRead);\n readChar();\n }\n if (!lastReadEq('-'))\n return true;\n \n for (int i=0; i < 6; i++) {\n if (!lastReadIsHex())\n break;\n currentToken.add(lastRead);\n readChar();\n }\n return true;\n}\n\nToken* CssTokenizer::getToken(){\n return ¤tToken;\n}\nToken::Type CssTokenizer::getTokenType() {\n return currentToken.type;\n}\n\nunsigned int CssTokenizer::getLineNumber(){\n return line;\n}\nunsigned int CssTokenizer::getColumn(){\n return column;\n}\n\nbool CssTokenizer::lastReadEq(char c) {\n return (in != NULL && lastRead == c);\n}\n\nbool CssTokenizer::lastReadInRange(char c1, char c2) {\n return (in != NULL && lastRead >= c1 && lastRead <= c2);\n}\nbool CssTokenizer::lastReadIsDigit() {\n return (in != NULL &&\n lastReadInRange('0', '9'));\n}\nbool CssTokenizer::lastReadIsHex() {\n return (in != NULL &&\n (lastReadIsDigit() ||\n lastReadInRange('a', 'f') ||\n lastReadInRange('A', 'F')));\n}\n<|endoftext|>"} {"text":"\/* -*- mode:C++; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg\n *\/\n#pragma once\n\n#include \"util\/compiler.hh\"\n#include \n#include \n\n#define KERNEL_CLM __attribute__((section (\".kernel_clm\")))\n#define KERNEL_CLM_HOT __attribute__((section (\".kernel_clm.hot\")))\n\nnamespace mythos {\n\n class KernelCLM\n {\n public:\n static void init(size_t size) {\n blockSize = size;\n offset = 0;\n }\n static size_t getBlockSize() { return blockSize; }\n static size_t getOffset(size_t threadID) { return threadID*blockSize; }\n static size_t getOffset() { return get(&offset); }\n static void initOffset(size_t threadID) { setAt(threadID, &offset, threadID*blockSize); }\n\n template\n ALWAYS_INLINE static void set(uintptr_t& var, T* value) {\n setWord(reinterpret_cast(&var), reinterpret_cast(value));\n }\n\n ALWAYS_INLINE static void set(size_t* var, size_t value) {\n setWord(var, value);\n }\n\n template\n ALWAYS_INLINE static void setAt(size_t threadID, T* var, T value) {\n auto ptr = reinterpret_cast(var) + threadID*blockSize;\n *reinterpret_cast(ptr) = value;\n }\n\n template\n ALWAYS_INLINE static T* get(uintptr_t const& var) {\n return reinterpret_cast(getWord(reinterpret_cast(&var)));\n }\n\n ALWAYS_INLINE static size_t get(size_t const* var) {\n return getWord(var);\n }\n\n ALWAYS_INLINE static size_t getAt(size_t threadID, size_t const* var) {\n char const *ptr = reinterpret_cast(var) + threadID*blockSize;\n return *reinterpret_cast(ptr);\n }\n\n template\n ALWAYS_INLINE static T* toLocal(T* var) {\n return reinterpret_cast(reinterpret_cast(var)+getOffset());\n }\n\n protected:\n static void setWord(uint64_t* addr, uint64_t value) {\n asm(\"movq %1,%%gs:%0\" : : \"m\" (*addr), \"ri\" (value));\n }\n\n static uint64_t getWord(uint64_t const* addr) {\n uint64_t value;\n asm(\"movq %%gs:%1,%0\" : \"=r\" (value) : \"m\" (*addr));\n return value;\n }\n\n static size_t blockSize;\n static size_t offset KERNEL_CLM_HOT;\n };\n\n template\n class CoreLocal\n {\n public:\n ALWAYS_INLINE T const* addr() const { return KernelCLM::toLocal(&var); }\n ALWAYS_INLINE T* addr() { return KernelCLM::toLocal(&var); }\n ALWAYS_INLINE T const* operator->() const { return addr(); }\n ALWAYS_INLINE T* operator->() { return addr(); }\n ALWAYS_INLINE T& operator*() { return *addr(); }\n ALWAYS_INLINE T const& operator*() const { return *addr(); }\n\n ALWAYS_INLINE T const& get() const { return *addr(); }\n ALWAYS_INLINE void set(T const& value) { *addr() = value; }\n protected:\n T var;\n };\n\n template<>\n class CoreLocal\n {\n public:\n ALWAYS_INLINE size_t get() const { return KernelCLM::get(&var); }\n ALWAYS_INLINE void set(size_t value) { return KernelCLM::set(&var, value); }\n \/\/ ALWAYS_INLINE size_t operator[](size_t threadID) { return KernelCLM::getAt(threadID, &var); }\n ALWAYS_INLINE void setAt(size_t threadID, size_t value) { KernelCLM::setAt(threadID, &var, value); }\n ALWAYS_INLINE CoreLocal& operator= (size_t value) { set(value); return *this; }\n ALWAYS_INLINE operator size_t () const { return get(); }\n protected:\n size_t var;\n };\n\n template\n class CoreLocal\n {\n public:\n ALWAYS_INLINE T* get() const { return KernelCLM::get(var); }\n ALWAYS_INLINE void set(T* value) { KernelCLM::set(var, value); }\n \/\/ ALWAYS_INLINE T* operator[](size_t threadID) {\n \/\/ return reinterpret_cast(KernelCLM::getAt(threadID, reinterpret_cast(&var)));\n \/\/ }\n ALWAYS_INLINE void setAt(size_t threadID, T* value) { KernelCLM::setAt(threadID, &var, uintptr_t(value)); }\n ALWAYS_INLINE T* operator-> () const { return get(); }\n ALWAYS_INLINE T& operator* () const { return *get(); }\n ALWAYS_INLINE CoreLocal& operator= (T* value) { set(value); return *this; }\n \/\/ ALWAYS_INLINE operator T* () const { return get(); }\n protected:\n uintptr_t var;\n };\n\n template<>\n class CoreLocal\n {\n public:\n ALWAYS_INLINE void* get() const { return KernelCLM::get(var); }\n ALWAYS_INLINE void set(void* value) { KernelCLM::set(var, value); }\n ALWAYS_INLINE CoreLocal& operator= (void* value) { set(value); return *this; }\n ALWAYS_INLINE operator void* () const { return get(); }\n protected:\n uintptr_t var;\n };\n\n} \/\/ namespace mythos\ninit CLM\/* -*- mode:C++; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg\n *\/\n#pragma once\n\n#include \"util\/compiler.hh\"\n#include \n#include \n\n#define KERNEL_CLM __attribute__((section (\".kernel_clm\")))\n#define KERNEL_CLM_HOT __attribute__((section (\".kernel_clm.hot\")))\n\nextern char CLM_BLOCKEND;\n\nnamespace mythos {\n\n class KernelCLM\n {\n public:\n static void init(size_t size) {\n blockSize = size;\n offset = 0;\n memset(&CLM_BLOCKEND, 0, size * (MYTHOS_MAX_THREADS - 1));\n }\n static size_t getBlockSize() { return blockSize; }\n static size_t getOffset(size_t threadID) { return threadID*blockSize; }\n static size_t getOffset() { return get(&offset); }\n static void initOffset(size_t threadID) { setAt(threadID, &offset, threadID*blockSize); }\n\n template\n ALWAYS_INLINE static void set(uintptr_t& var, T* value) {\n setWord(reinterpret_cast(&var), reinterpret_cast(value));\n }\n\n ALWAYS_INLINE static void set(size_t* var, size_t value) {\n setWord(var, value);\n }\n\n template\n ALWAYS_INLINE static void setAt(size_t threadID, T* var, T value) {\n auto ptr = reinterpret_cast(var) + threadID*blockSize;\n *reinterpret_cast(ptr) = value;\n }\n\n template\n ALWAYS_INLINE static T* get(uintptr_t const& var) {\n return reinterpret_cast(getWord(reinterpret_cast(&var)));\n }\n\n ALWAYS_INLINE static size_t get(size_t const* var) {\n return getWord(var);\n }\n\n ALWAYS_INLINE static size_t getAt(size_t threadID, size_t const* var) {\n char const *ptr = reinterpret_cast(var) + threadID*blockSize;\n return *reinterpret_cast(ptr);\n }\n\n template\n ALWAYS_INLINE static T* toLocal(T* var) {\n return reinterpret_cast(reinterpret_cast(var)+getOffset());\n }\n\n protected:\n static void setWord(uint64_t* addr, uint64_t value) {\n asm(\"movq %1,%%gs:%0\" : : \"m\" (*addr), \"ri\" (value));\n }\n\n static uint64_t getWord(uint64_t const* addr) {\n uint64_t value;\n asm(\"movq %%gs:%1,%0\" : \"=r\" (value) : \"m\" (*addr));\n return value;\n }\n\n static size_t blockSize;\n static size_t offset KERNEL_CLM_HOT;\n };\n\n template\n class CoreLocal\n {\n public:\n ALWAYS_INLINE T const* addr() const { return KernelCLM::toLocal(&var); }\n ALWAYS_INLINE T* addr() { return KernelCLM::toLocal(&var); }\n ALWAYS_INLINE T const* operator->() const { return addr(); }\n ALWAYS_INLINE T* operator->() { return addr(); }\n ALWAYS_INLINE T& operator*() { return *addr(); }\n ALWAYS_INLINE T const& operator*() const { return *addr(); }\n\n ALWAYS_INLINE T const& get() const { return *addr(); }\n ALWAYS_INLINE void set(T const& value) { *addr() = value; }\n protected:\n T var;\n };\n\n template<>\n class CoreLocal\n {\n public:\n ALWAYS_INLINE size_t get() const { return KernelCLM::get(&var); }\n ALWAYS_INLINE void set(size_t value) { return KernelCLM::set(&var, value); }\n \/\/ ALWAYS_INLINE size_t operator[](size_t threadID) { return KernelCLM::getAt(threadID, &var); }\n ALWAYS_INLINE void setAt(size_t threadID, size_t value) { KernelCLM::setAt(threadID, &var, value); }\n ALWAYS_INLINE CoreLocal& operator= (size_t value) { set(value); return *this; }\n ALWAYS_INLINE operator size_t () const { return get(); }\n protected:\n size_t var;\n };\n\n template\n class CoreLocal\n {\n public:\n ALWAYS_INLINE T* get() const { return KernelCLM::get(var); }\n ALWAYS_INLINE void set(T* value) { KernelCLM::set(var, value); }\n \/\/ ALWAYS_INLINE T* operator[](size_t threadID) {\n \/\/ return reinterpret_cast(KernelCLM::getAt(threadID, reinterpret_cast(&var)));\n \/\/ }\n ALWAYS_INLINE void setAt(size_t threadID, T* value) { KernelCLM::setAt(threadID, &var, uintptr_t(value)); }\n ALWAYS_INLINE T* operator-> () const { return get(); }\n ALWAYS_INLINE T& operator* () const { return *get(); }\n ALWAYS_INLINE CoreLocal& operator= (T* value) { set(value); return *this; }\n \/\/ ALWAYS_INLINE operator T* () const { return get(); }\n protected:\n uintptr_t var;\n };\n\n template<>\n class CoreLocal\n {\n public:\n ALWAYS_INLINE void* get() const { return KernelCLM::get(var); }\n ALWAYS_INLINE void set(void* value) { KernelCLM::set(var, value); }\n ALWAYS_INLINE CoreLocal& operator= (void* value) { set(value); return *this; }\n ALWAYS_INLINE operator void* () const { return get(); }\n protected:\n uintptr_t var;\n };\n\n} \/\/ namespace mythos\n<|endoftext|>"} {"text":"Template edit<|endoftext|>"} {"text":"\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\n#include \"SiconosConfig.h\"\n\n#include \"BlockCSRMatrix.hpp\"\n#include \n#include \"NonSmoothLaw.hpp\"\n\n#include \"NewtonEulerDS.hpp\"\n#include \"NewtonEulerR.hpp\"\n#include \"SimulationGraphs.hpp\"\n\n#include \"Tools.hpp\"\n\n\/\/ Default constructor: empty matrix\nBlockCSRMatrix::BlockCSRMatrix():\n _nr(0), \n _blockCSR(new CompressedRowMat()), \n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n _diagsize0(new IndexInt()),\n _diagsize1(new IndexInt()),\n rowPos(new IndexInt()),\n colPos(new IndexInt())\n{}\n\n\/\/ Constructor with dimensions\nBlockCSRMatrix::BlockCSRMatrix(unsigned int nRow):\n _nr(nRow),\n \/\/ Only square-blocks matrices for the moment (ie nRow = nr = nrol)\n \n \/\/ Allocate memory and fill in the matrix rowPos, rowCol ... are\n \/\/ initialized with nr to reserve at first step the maximum possible\n \/\/ (according to given nr) space in memory. Thus a future resize\n \/\/ will not require memory allocation or copy.\n _blockCSR(new CompressedRowMat(_nr, _nr)),\n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix),\n _diagsize0(new IndexInt(_nr)),\n _diagsize1(new IndexInt(_nr)),\n rowPos(new IndexInt(_nr)),\n colPos(new IndexInt(_nr))\n{}\n\n\/\/ Basic constructor\nBlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet):\n _nr(indexSet->size()), \n _blockCSR(new CompressedRowMat(_nr, _nr)),\n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n _diagsize0(new IndexInt(_nr)),\n _diagsize1(new IndexInt(_nr)),\n rowPos(new IndexInt(_nr)),\n colPos(new IndexInt(_nr))\n{\n fill(indexSet);\n}\n\nBlockCSRMatrix::~BlockCSRMatrix()\n{}\n\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::InteractionsGraph indexSet)\n{\n \/\/ ======> Aim: find inter1 and inter2 both in indexSets[level] and which\n \/\/ have common DynamicalSystems. Then get the corresponding matrix\n \/\/ from map blocks.\n\n assert(indexSet);\n\n \/\/ Number of blocks in a row = number of active constraints.\n _nr = indexSet->size();\n\n \/\/ (re)allocate memory for ublas matrix\n _blockCSR->resize(_nr, _nr, false);\n\n _diagsize0->resize(_nr);\n _diagsize1->resize(_nr);\n\n \/\/ === Loop through \"active\" Interactions (ie present in\n \/\/ indexSets[level]) ===\n\n\n int sizeV = 0;\n\n InteractionsGraph::VIterator vi, viend;\n for (std11::tie(vi, viend) = indexSet->vertices();\n vi != viend; ++vi)\n {\n SP::Interaction inter = indexSet->bundle(*vi);\n\n assert(inter->nonSmoothLaw()->size() > 0);\n\n sizeV += inter->nonSmoothLaw()->size();\n (*_diagsize0)[indexSet->index(*vi)] = sizeV;\n (*_diagsize1)[indexSet->index(*vi)] = sizeV;\n assert((*_diagsize0)[indexSet->index(*vi)] > 0);\n assert((*_diagsize1)[indexSet->index(*vi)] > 0);\n\n (*_blockCSR)(indexSet->index(*vi), indexSet->index(*vi)) =\n indexSet->properties(*vi).block->getArray();\n }\n\n InteractionsGraph::EIterator ei, eiend;\n for (std11::tie(ei, eiend) = indexSet->edges();\n ei != eiend; ++ei)\n {\n InteractionsGraph::VDescriptor vd1 = indexSet->source(*ei);\n InteractionsGraph::VDescriptor vd2 = indexSet->target(*ei);\n SP::Interaction inter1 = indexSet->bundle(vd1);\n SP::Interaction inter2 = indexSet->bundle(vd2);\n\n assert(indexSet->index(vd1) < _nr);\n assert(indexSet->index(vd2) < _nr);\n\n assert(indexSet->is_vertex(inter2));\n\n assert(vd2 == indexSet->descriptor(inter2));\n assert(indexSet->index(vd2) == indexSet->index(indexSet->descriptor(inter2)));\n\n\n unsigned int pos = indexSet->index(vd1);\n unsigned int col = indexSet->index(vd2);\n\n assert(pos != col);\n\n (*_blockCSR)(std::min(pos, col), std::max(pos, col)) =\n indexSet->properties(*ei).upper_block->getArray();\n\n (*_blockCSR)(std::max(pos, col), std::min(pos, col)) =\n indexSet->properties(*ei).lower_block->getArray();\n }\n}\n\nvoid BlockCSRMatrix::fillM(SP::InteractionsGraph indexSet)\n{\n assert(indexSet);\n\n \/* on adjoint graph a dynamical system may be on several edges *\/\n std::map involvedDS;\n InteractionsGraph::EIterator ei, eiend;\n for(std11::tie(ei, eiend) = indexSet->edges();\n ei != eiend; ++ei)\n {\n if (Type::value(*indexSet->bundle(*ei)) != Type::NewtonEulerDS)\n {\n RuntimeException::selfThrow(\"BlockCSRMatrix::fillM only for Newton EulerDS\");\n }\n\n _nr = 0;\n \n if (involvedDS.find(indexSet->bundle(*ei)) == involvedDS.end())\n {\n _nr++;\n involvedDS[indexSet->bundle(*ei)] = true;\n _blockCSR->resize(_nr, _nr, false);\n\n (*_blockCSR)(_nr-1, _nr-1) = std11::static_pointer_cast\n (indexSet->bundle(*ei))->mass()->getArray();\n }\n }\n \n _diagsize0->resize(involvedDS.size());\n _diagsize1->resize(involvedDS.size());\n\n \/* here we suppose NewtonEuler with 6 dofs *\/\n \/* it cannot be another case at this point *\/\n unsigned int index, ac;\n for (index = 0, ac = 6; \n index < involvedDS.size();\n ++index, ac+=6)\n {\n (*_diagsize0)[index] = ac;\n (*_diagsize1)[index] = ac;\n }\n \n}\n\nvoid BlockCSRMatrix::fillH(SP::InteractionsGraph indexSet)\n{\n assert(indexSet);\n\n \/* on adjoint graph a dynamical system may be on several edges *\/\n std::map involvedDS;\n InteractionsGraph::EIterator ei, eiend;\n {\n unsigned int index;\n for(std11::tie(ei, eiend) = indexSet->edges(), index=0;\n ei != eiend; ++ei, ++index)\n {\n if (involvedDS.find(indexSet->bundle(*ei)) == involvedDS.end())\n {\n if (Type::value(*indexSet->bundle(*ei)) != Type::NewtonEulerDS)\n {\n RuntimeException::selfThrow(\"BlockCSRMatrix::fillH only for Newton EulerDS\");\n }\n involvedDS[indexSet->bundle(*ei)] = index;\n }\n }\n }\n\n _nr = involvedDS.size();\n\n _blockCSR->resize(_nr, _nr, false);\n\n InteractionsGraph::VIterator vi, viend;\n for(std11::tie(vi, viend) = indexSet->vertices();\n vi != viend; ++vi)\n {\n\n SP::DynamicalSystem first = SP::DynamicalSystem();\n unsigned int pos=0, col=0;\n InteractionsGraph::EDescriptor ed1, ed2;\n InteractionsGraph::OEIterator oei, oeiend;\n for(std11::tie(oei, oeiend) = indexSet->out_edges(*vi);\n oei != oeiend; ++oei)\n {\n if (!first)\n {\n first = indexSet->bundle(*oei);\n col = involvedDS[first];\n pos = involvedDS[first];\n }\n else\n {\n if (indexSet->bundle(*oei) != first)\n {\n pos = involvedDS[indexSet->bundle(*oei)];\n }\n }\n }\n\n (*_blockCSR)(std::min(pos, col), std::max(pos, col)) = \n std11::static_pointer_cast(indexSet->bundle(*vi)->relation())->jachqT()->getArray();\n \n (*_blockCSR)(std::max(pos, col), std::min(pos, col)) = \n std11::static_pointer_cast(indexSet->bundle(*vi)->relation())->jachqT()->getArray();\n \n }\n \n _diagsize0->resize(involvedDS.size());\n _diagsize1->resize(involvedDS.size());\n \n \/* only NewtonEulerFrom3DLocalFrameR *\/\n unsigned int index, ac0, ac1;\n for (index= 0, ac0 = 6, ac1 = 3; \n index < involvedDS.size();\n ++index, ac0 +=6, ac1 +=3)\n {\n (*_diagsize0)[index] = ac0;\n (*_diagsize1)[index] = ac1;\n }\n \n}\n\n\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::DynamicalSystemsSet DSSet,\n MapOfDSMatrices& DSblocks)\n{\n RuntimeException::selfThrow\n (\" BlockCSRMatrix::fill(DynamicalSystemsSet* DSSet, MapOfDSMatrices& DSblocks), Not Yet Implemented\");\n}\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::InteractionsGraph indexSet,\n SP::DynamicalSystemsSet DSSet,\n MapOfInteractionMapOfDSMatrices& interactionDSBlocks)\n{\n RuntimeException::selfThrow\n (\" BlockCSRMatrix::fill(DynamicalSystemsSet* DSSet, MapOfDSMatrices& DSblocks), Not Yet Implemented\");\n}\n\n\n\/\/ convert _blockCSR to numerics structure\nvoid BlockCSRMatrix::convert()\n{\n _sparseBlockStructuredMatrix->blocknumber0 = _nr;\n _sparseBlockStructuredMatrix->blocknumber1 = _nr; \/\/ nc not always set\n _sparseBlockStructuredMatrix->nbblocks = (*_blockCSR).nnz();\n \/\/ Next copies: pointer links!!\n _sparseBlockStructuredMatrix->blocksize0 = &((*_diagsize0)[0]);\n _sparseBlockStructuredMatrix->blocksize1 = &((*_diagsize1)[0]); \/\/ nr = nc\n\n \/\/ boost\n _sparseBlockStructuredMatrix->filled1 = (*_blockCSR).filled1();\n _sparseBlockStructuredMatrix->filled2 = (*_blockCSR).filled2();\n _sparseBlockStructuredMatrix->index1_data = &((*_blockCSR).index1_data()[0]);\n if (_nr > 0)\n {\n _sparseBlockStructuredMatrix->index2_data = &((*_blockCSR).index2_data()[0]);\n _sparseBlockStructuredMatrix->block = &((*_blockCSR).value_data()[0]);\n };\n\n \/\/ \/\/ Loop through the non-null blocks\n \/\/ for (SpMatIt1 i1 = _blockCSR->begin1(); i1 != _blockCSR->end1(); ++i1)\n \/\/ {\n \/\/ for (SpMatIt2 i2 = i1.begin(); i2 != i1.end(); ++i2)\n \/\/ {\n \/\/ block[i] = *i2;\n \/\/ }\n \/\/ }\n}\n\n\/\/ Display data\nvoid BlockCSRMatrix::display() const\n{\n std::cout << \"----- Sparse Block Matrix with \"\n << _nr << \" blocks in a row\/col and \"\n << _blockCSR->nnz()\n << \" non-null blocks\" <filled1() <filled2() <index1_data().begin(), _blockCSR->index1_data().end());\n std::cout <index2_data().begin(), _blockCSR->index2_data().end());\n std::cout <begin(), _diagsize0->end());\n print(_diagsize1->begin(), _diagsize1->end());\n}\n\nunsigned int BlockCSRMatrix::getNbNonNullBlocks() const\n{\n return _blockCSR->nnz();\n};\n\n[kernel] add debug output.\/* Siconos is a program dedicated to modeling, simulation and control\n * of non smooth dynamical systems.\n *\n * Copyright 2016 INRIA.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n*\/\n\n#include \"SiconosConfig.h\"\n\n#include \"BlockCSRMatrix.hpp\"\n#include \n#include \"NonSmoothLaw.hpp\"\n\n#include \"NewtonEulerDS.hpp\"\n#include \"NewtonEulerR.hpp\"\n#include \"SimulationGraphs.hpp\"\n\n#include \"Tools.hpp\"\n\n\/\/ #define DEBUG_STDOUT\n\/\/ #define DEBUG_MESSAGES 1\n#include \"debug.h\"\n\n\/\/ Default constructor: empty matrix\nBlockCSRMatrix::BlockCSRMatrix():\n _nr(0),\n _blockCSR(new CompressedRowMat()),\n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n _diagsize0(new IndexInt()),\n _diagsize1(new IndexInt()),\n rowPos(new IndexInt()),\n colPos(new IndexInt())\n{}\n\n\/\/ Constructor with dimensions\nBlockCSRMatrix::BlockCSRMatrix(unsigned int nRow):\n _nr(nRow),\n \/\/ Only square-blocks matrices for the moment (ie nRow = nr = nrol)\n\n \/\/ Allocate memory and fill in the matrix rowPos, rowCol ... are\n \/\/ initialized with nr to reserve at first step the maximum possible\n \/\/ (according to given nr) space in memory. Thus a future resize\n \/\/ will not require memory allocation or copy.\n _blockCSR(new CompressedRowMat(_nr, _nr)),\n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n _diagsize0(new IndexInt(_nr)),\n _diagsize1(new IndexInt(_nr)),\n rowPos(new IndexInt(_nr)),\n colPos(new IndexInt(_nr))\n{}\n\n\/\/ Basic constructor\nBlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet):\n _nr(indexSet->size()), \n _blockCSR(new CompressedRowMat(_nr, _nr)),\n _sparseBlockStructuredMatrix(new SparseBlockStructuredMatrix()),\n _diagsize0(new IndexInt(_nr)),\n _diagsize1(new IndexInt(_nr)),\n rowPos(new IndexInt(_nr)),\n colPos(new IndexInt(_nr))\n{\n DEBUG_BEGIN(\"BlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet)\\n\");\n fill(indexSet);\n DEBUG_END(\"BlockCSRMatrix::BlockCSRMatrix(SP::InteractionsGraph indexSet)\\n\");\n}\n\nBlockCSRMatrix::~BlockCSRMatrix()\n{}\n\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::InteractionsGraph indexSet)\n{\n \/\/ ======> Aim: find inter1 and inter2 both in indexSets[level] and which\n \/\/ have common DynamicalSystems. Then get the corresponding matrix\n \/\/ from map blocks.\n\n assert(indexSet);\n\n \/\/ Number of blocks in a row = number of active constraints.\n _nr = indexSet->size();\n\n \/\/ (re)allocate memory for ublas matrix\n _blockCSR->resize(_nr, _nr, false);\n\n _diagsize0->resize(_nr);\n _diagsize1->resize(_nr);\n\n \/\/ === Loop through \"active\" Interactions (ie present in\n \/\/ indexSets[level]) ===\n\n\n int sizeV = 0;\n\n InteractionsGraph::VIterator vi, viend;\n for (std11::tie(vi, viend) = indexSet->vertices();\n vi != viend; ++vi)\n {\n SP::Interaction inter = indexSet->bundle(*vi);\n\n assert(inter->nonSmoothLaw()->size() > 0);\n\n sizeV += inter->nonSmoothLaw()->size();\n (*_diagsize0)[indexSet->index(*vi)] = sizeV;\n (*_diagsize1)[indexSet->index(*vi)] = sizeV;\n assert((*_diagsize0)[indexSet->index(*vi)] > 0);\n assert((*_diagsize1)[indexSet->index(*vi)] > 0);\n\n (*_blockCSR)(indexSet->index(*vi), indexSet->index(*vi)) =\n indexSet->properties(*vi).block->getArray();\n }\n\n InteractionsGraph::EIterator ei, eiend;\n for (std11::tie(ei, eiend) = indexSet->edges();\n ei != eiend; ++ei)\n {\n InteractionsGraph::VDescriptor vd1 = indexSet->source(*ei);\n InteractionsGraph::VDescriptor vd2 = indexSet->target(*ei);\n SP::Interaction inter1 = indexSet->bundle(vd1);\n SP::Interaction inter2 = indexSet->bundle(vd2);\n\n assert(indexSet->index(vd1) < _nr);\n assert(indexSet->index(vd2) < _nr);\n\n assert(indexSet->is_vertex(inter2));\n\n assert(vd2 == indexSet->descriptor(inter2));\n assert(indexSet->index(vd2) == indexSet->index(indexSet->descriptor(inter2)));\n\n\n unsigned int pos = indexSet->index(vd1);\n unsigned int col = indexSet->index(vd2);\n\n assert(pos != col);\n\n (*_blockCSR)(std::min(pos, col), std::max(pos, col)) =\n indexSet->properties(*ei).upper_block->getArray();\n\n (*_blockCSR)(std::max(pos, col), std::min(pos, col)) =\n indexSet->properties(*ei).lower_block->getArray();\n }\n DEBUG_EXPR(display(););\n}\n\nvoid BlockCSRMatrix::fillM(SP::InteractionsGraph indexSet)\n{\n assert(indexSet);\n\n \/* on adjoint graph a dynamical system may be on several edges *\/\n std::map involvedDS;\n InteractionsGraph::EIterator ei, eiend;\n for(std11::tie(ei, eiend) = indexSet->edges();\n ei != eiend; ++ei)\n {\n if (Type::value(*indexSet->bundle(*ei)) != Type::NewtonEulerDS)\n {\n RuntimeException::selfThrow(\"BlockCSRMatrix::fillM only for Newton EulerDS\");\n }\n\n _nr = 0;\n \n if (involvedDS.find(indexSet->bundle(*ei)) == involvedDS.end())\n {\n _nr++;\n involvedDS[indexSet->bundle(*ei)] = true;\n _blockCSR->resize(_nr, _nr, false);\n\n (*_blockCSR)(_nr-1, _nr-1) = std11::static_pointer_cast\n (indexSet->bundle(*ei))->mass()->getArray();\n }\n }\n \n _diagsize0->resize(involvedDS.size());\n _diagsize1->resize(involvedDS.size());\n\n \/* here we suppose NewtonEuler with 6 dofs *\/\n \/* it cannot be another case at this point *\/\n unsigned int index, ac;\n for (index = 0, ac = 6; \n index < involvedDS.size();\n ++index, ac+=6)\n {\n (*_diagsize0)[index] = ac;\n (*_diagsize1)[index] = ac;\n }\n \n}\n\nvoid BlockCSRMatrix::fillH(SP::InteractionsGraph indexSet)\n{\n assert(indexSet);\n\n \/* on adjoint graph a dynamical system may be on several edges *\/\n std::map involvedDS;\n InteractionsGraph::EIterator ei, eiend;\n {\n unsigned int index;\n for(std11::tie(ei, eiend) = indexSet->edges(), index=0;\n ei != eiend; ++ei, ++index)\n {\n if (involvedDS.find(indexSet->bundle(*ei)) == involvedDS.end())\n {\n if (Type::value(*indexSet->bundle(*ei)) != Type::NewtonEulerDS)\n {\n RuntimeException::selfThrow(\"BlockCSRMatrix::fillH only for Newton EulerDS\");\n }\n involvedDS[indexSet->bundle(*ei)] = index;\n }\n }\n }\n\n _nr = involvedDS.size();\n\n _blockCSR->resize(_nr, _nr, false);\n\n InteractionsGraph::VIterator vi, viend;\n for(std11::tie(vi, viend) = indexSet->vertices();\n vi != viend; ++vi)\n {\n\n SP::DynamicalSystem first = SP::DynamicalSystem();\n unsigned int pos=0, col=0;\n InteractionsGraph::EDescriptor ed1, ed2;\n InteractionsGraph::OEIterator oei, oeiend;\n for(std11::tie(oei, oeiend) = indexSet->out_edges(*vi);\n oei != oeiend; ++oei)\n {\n if (!first)\n {\n first = indexSet->bundle(*oei);\n col = involvedDS[first];\n pos = involvedDS[first];\n }\n else\n {\n if (indexSet->bundle(*oei) != first)\n {\n pos = involvedDS[indexSet->bundle(*oei)];\n }\n }\n }\n\n (*_blockCSR)(std::min(pos, col), std::max(pos, col)) = \n std11::static_pointer_cast(indexSet->bundle(*vi)->relation())->jachqT()->getArray();\n \n (*_blockCSR)(std::max(pos, col), std::min(pos, col)) = \n std11::static_pointer_cast(indexSet->bundle(*vi)->relation())->jachqT()->getArray();\n \n }\n \n _diagsize0->resize(involvedDS.size());\n _diagsize1->resize(involvedDS.size());\n \n \/* only NewtonEulerFrom3DLocalFrameR *\/\n unsigned int index, ac0, ac1;\n for (index= 0, ac0 = 6, ac1 = 3; \n index < involvedDS.size();\n ++index, ac0 +=6, ac1 +=3)\n {\n (*_diagsize0)[index] = ac0;\n (*_diagsize1)[index] = ac1;\n }\n \n}\n\n\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::DynamicalSystemsSet DSSet,\n MapOfDSMatrices& DSblocks)\n{\n RuntimeException::selfThrow\n (\" BlockCSRMatrix::fill(DynamicalSystemsSet* DSSet, MapOfDSMatrices& DSblocks), Not Yet Implemented\");\n}\n\/\/ Fill the SparseMat\nvoid BlockCSRMatrix::fill(SP::InteractionsGraph indexSet,\n SP::DynamicalSystemsSet DSSet,\n MapOfInteractionMapOfDSMatrices& interactionDSBlocks)\n{\n RuntimeException::selfThrow\n (\" BlockCSRMatrix::fill(DynamicalSystemsSet* DSSet, MapOfDSMatrices& DSblocks), Not Yet Implemented\");\n}\n\n\n\/\/ convert _blockCSR to numerics structure\nvoid BlockCSRMatrix::convert()\n{\n _sparseBlockStructuredMatrix->blocknumber0 = _nr;\n _sparseBlockStructuredMatrix->blocknumber1 = _nr; \/\/ nc not always set\n _sparseBlockStructuredMatrix->nbblocks = (*_blockCSR).nnz();\n \/\/ Next copies: pointer links!!\n _sparseBlockStructuredMatrix->blocksize0 = &((*_diagsize0)[0]);\n _sparseBlockStructuredMatrix->blocksize1 = &((*_diagsize1)[0]); \/\/ nr = nc\n\n \/\/ boost\n _sparseBlockStructuredMatrix->filled1 = (*_blockCSR).filled1();\n _sparseBlockStructuredMatrix->filled2 = (*_blockCSR).filled2();\n _sparseBlockStructuredMatrix->index1_data = &((*_blockCSR).index1_data()[0]);\n if (_nr > 0)\n {\n _sparseBlockStructuredMatrix->index2_data = &((*_blockCSR).index2_data()[0]);\n _sparseBlockStructuredMatrix->block = &((*_blockCSR).value_data()[0]);\n };\n\n \/\/ \/\/ Loop through the non-null blocks\n \/\/ for (SpMatIt1 i1 = _blockCSR->begin1(); i1 != _blockCSR->end1(); ++i1)\n \/\/ {\n \/\/ for (SpMatIt2 i2 = i1.begin(); i2 != i1.end(); ++i2)\n \/\/ {\n \/\/ block[i] = *i2;\n \/\/ }\n \/\/ }\n}\n\n\/\/ Display data\nvoid BlockCSRMatrix::display() const\n{\n std::cout << \"----- Sparse Block Matrix with \"\n << _nr << \" blocks in a row\/col and \"\n << _blockCSR->nnz()\n << \" non-null blocks\" <filled1() <filled2() <index1_data().size()\" << _blockCSR->index1_data().size() << std::endl;\n print(_blockCSR->index1_data().begin(), _blockCSR->index1_data().end(),\"index1_data\", \"\\t\");\n\n assert(_blockCSR->index2_data().size() >= _blockCSR->filled2() );\n\n std::cout << \"_blockCSR->index2_data().size()\" << _blockCSR->index2_data().size() << std::endl;\n print(_blockCSR->index2_data().begin(), _blockCSR->index2_data().end(), \"index2_data (column number for each block)\", \"\\t\");\n\n std::cout << \"last column number \"<< _blockCSR->index2_data()[_blockCSR->filled2()-1] << \" for block \" << _blockCSR->filled2() << std::endl;\n print(_diagsize0->begin(), _diagsize0->end(),\"_diagsize0 , sum of row sizes of the diagonal blocks\", \"\\t\" );\n print(_diagsize1->begin(), _diagsize1->end(),\"_diagsize1 , sum of col sizes of the diagonal blocks\", \"\\t\" );\n}\n\nunsigned int BlockCSRMatrix::getNbNonNullBlocks() const\n{\n return _blockCSR->nnz();\n};\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n\n#include \"EDDIFrontEnd.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"DebugStopWatch.hpp\"\n#include \"Options.hpp\"\n#include \"StringPool.hpp\"\n#include \"Type.hpp\"\n\n#include \"parser\/SpiritParser.hpp\"\n\n#include \"ast\/SourceFile.hpp\"\n\n\/\/Annotators\n#include \"ast\/DefaultValues.hpp\"\n#include \"ast\/ContextAnnotator.hpp\"\n#include \"ast\/FunctionsAnnotator.hpp\"\n#include \"ast\/VariablesAnnotator.hpp\"\n#include \"ast\/StructuresAnnotator.hpp\"\n\n\/\/Checkers\n#include \"ast\/StringChecker.hpp\"\n#include \"ast\/TypeChecker.hpp\"\n\n\/\/Visitors\n#include \"ast\/DependenciesResolver.hpp\"\n#include \"ast\/OptimizationEngine.hpp\"\n#include \"ast\/TransformerEngine.hpp\"\n#include \"ast\/WarningsEngine.hpp\"\n#include \"ast\/Printer.hpp\"\n\n#include \"mtac\/Compiler.hpp\"\n#include \"mtac\/RegisterAllocation.hpp\"\n\nusing namespace eddic;\n\nvoid checkForMain();\n\nstd::shared_ptr EDDIFrontEnd::compile(const std::string& file){\n parser::SpiritParser parser;\n\n \/\/The program to build\n ast::SourceFile program;\n\n \/\/Parse the file into the program\n bool parsing = parser.parse(file, program); \n\n \/\/If the parsing was sucessfully\n if(parsing){\n set_string_pool(std::make_shared());\n\n \/\/Read dependencies\n resolveDependencies(program, parser);\n\n \/\/Apply some cleaning transformations\n ast::cleanAST(program);\n\n \/\/Annotate the AST with more informations\n ast::defineDefaultValues(program);\n\n \/\/Fill the string pool\n ast::checkStrings(program, *pool);\n\n \/\/Add some more informations to the AST\n ast::defineStructures(program);\n ast::defineMemberFunctions(program);\n ast::defineContexts(program);\n ast::defineVariables(program);\n ast::defineFunctions(program);\n\n \/\/Static analysis\n ast::checkTypes(program);\n\n \/\/Check for warnings\n ast::checkForWarnings(program);\n\n \/\/Check that there is a main in the program\n checkForMain();\n\n \/\/Transform the AST\n ast::transformAST(program);\n\n \/\/Optimize the AST\n ast::optimizeAST(program, *pool);\n\n \/\/If the user asked for it, print the Abstract Syntax Tree\n if(option_defined(\"ast\") || option_defined(\"ast-only\")){\n ast::Printer printer;\n printer.print(program);\n }\n \n \/\/If the user wants only the AST prints, it is not necessary to compile the AST\n if(option_defined(\"ast-only\")){\n return nullptr;\n }\n\n std::shared_ptr mtacProgram = std::make_shared();\n\n \/\/Generate Three-Address-Code language\n mtac::Compiler compiler;\n compiler.compile(program, pool, mtacProgram);\n\n return mtacProgram;\n }\n\n \/\/If the parsing fails, the error is already printed to the console\n return nullptr;\n}\n\nvoid checkForMain(){\n if(!symbols.exists(\"main\")){\n throw SemanticalException(\"Your program must contain a main function\"); \n }\n\n auto function = symbols.getFunction(\"main\");\n\n if(function->parameters.size() > 1){\n throw SemanticalException(\"The signature of your main function is not valid\");\n }\n\n if(function->parameters.size() == 1){\n auto type = function->parameters[0].paramType;\n \n if(type->data_type() != STRING || !type->is_array()){\n throw SemanticalException(\"The signature of your main function is not valid\");\n }\n }\n}\nCheck for main with new mangling\/\/=======================================================================\n\/\/ Copyright Baptiste Wicht 2011.\n\/\/ Distributed under the Boost Software License, Version 1.0.\n\/\/ (See accompanying file LICENSE_1_0.txt or copy at\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\n\/\/=======================================================================\n\n#include \n\n#include \"EDDIFrontEnd.hpp\"\n#include \"SemanticalException.hpp\"\n#include \"DebugStopWatch.hpp\"\n#include \"Options.hpp\"\n#include \"StringPool.hpp\"\n#include \"Type.hpp\"\n\n#include \"parser\/SpiritParser.hpp\"\n\n#include \"ast\/SourceFile.hpp\"\n\n\/\/Annotators\n#include \"ast\/DefaultValues.hpp\"\n#include \"ast\/ContextAnnotator.hpp\"\n#include \"ast\/FunctionsAnnotator.hpp\"\n#include \"ast\/VariablesAnnotator.hpp\"\n#include \"ast\/StructuresAnnotator.hpp\"\n\n\/\/Checkers\n#include \"ast\/StringChecker.hpp\"\n#include \"ast\/TypeChecker.hpp\"\n\n\/\/Visitors\n#include \"ast\/DependenciesResolver.hpp\"\n#include \"ast\/OptimizationEngine.hpp\"\n#include \"ast\/TransformerEngine.hpp\"\n#include \"ast\/WarningsEngine.hpp\"\n#include \"ast\/Printer.hpp\"\n\n#include \"mtac\/Compiler.hpp\"\n#include \"mtac\/RegisterAllocation.hpp\"\n\nusing namespace eddic;\n\nvoid checkForMain();\n\nstd::shared_ptr EDDIFrontEnd::compile(const std::string& file){\n parser::SpiritParser parser;\n\n \/\/The program to build\n ast::SourceFile program;\n\n \/\/Parse the file into the program\n bool parsing = parser.parse(file, program); \n\n \/\/If the parsing was sucessfully\n if(parsing){\n set_string_pool(std::make_shared());\n\n \/\/Read dependencies\n resolveDependencies(program, parser);\n\n \/\/Apply some cleaning transformations\n ast::cleanAST(program);\n\n \/\/Annotate the AST with more informations\n ast::defineDefaultValues(program);\n\n \/\/Fill the string pool\n ast::checkStrings(program, *pool);\n\n \/\/Add some more informations to the AST\n ast::defineStructures(program);\n ast::defineMemberFunctions(program);\n ast::defineContexts(program);\n ast::defineVariables(program);\n ast::defineFunctions(program);\n\n \/\/Static analysis\n ast::checkTypes(program);\n\n \/\/Check for warnings\n ast::checkForWarnings(program);\n\n \/\/Check that there is a main in the program\n checkForMain();\n\n \/\/Transform the AST\n ast::transformAST(program);\n\n \/\/Optimize the AST\n ast::optimizeAST(program, *pool);\n\n \/\/If the user asked for it, print the Abstract Syntax Tree\n if(option_defined(\"ast\") || option_defined(\"ast-only\")){\n ast::Printer printer;\n printer.print(program);\n }\n \n \/\/If the user wants only the AST prints, it is not necessary to compile the AST\n if(option_defined(\"ast-only\")){\n return nullptr;\n }\n\n std::shared_ptr mtacProgram = std::make_shared();\n\n \/\/Generate Three-Address-Code language\n mtac::Compiler compiler;\n compiler.compile(program, pool, mtacProgram);\n\n return mtacProgram;\n }\n\n \/\/If the parsing fails, the error is already printed to the console\n return nullptr;\n}\n\nvoid checkForMain(){\n std::shared_ptr function;\n if(symbols.exists(\"_F4main\")){\n function = symbols.getFunction(\"_F4main\");\n } else if (symbols.exists(\"_F4mainAI\")){\n function = symbols.getFunction(\"_F4mainAI\");\n } else {\n throw SemanticalException(\"The program does not contain a valid main function\"); \n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(port): the ifdefs in here are a first step towards trying to determine\n\/\/ the correct abstraction for all the OS functionality required at this\n\/\/ stage of process initialization. It should not be taken as a final\n\/\/ abstraction.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#if defined(OS_LINUX)\n#include \n#endif\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug_util.h\"\n#include \"base\/icu_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/string_util.h\"\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n#include \"chrome\/app\/scoped_ole_initializer.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_counters.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/common\/sandbox_init_wrapper.h\"\n#if defined(OS_WIN)\n#include \"sandbox\/src\/sandbox.h\"\n#include \"tools\/memory_watcher\/memory_watcher.h\"\n#endif\n#if defined(OS_MACOSX)\n#include \"third_party\/WebKit\/WebKit\/mac\/WebCoreSupport\/WebSystemInterface.h\"\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\nextern int RendererMain(const MainFunctionParams&);\nextern int PluginMain(const MainFunctionParams&);\nextern int WorkerMain(const MainFunctionParams&);\n\n#if defined(OS_WIN)\n\/\/ TODO(erikkay): isn't this already defined somewhere?\n#define DLLEXPORT __declspec(dllexport)\n\n\/\/ We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.\nextern \"C\" {\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sandbox_info,\n TCHAR* command_line);\n}\n#elif defined(OS_POSIX)\nextern \"C\" {\nint ChromeMain(int argc, const char** argv);\n}\n#endif\n\nnamespace {\n\n#if defined(OS_WIN)\nconst wchar_t kProfilingDll[] = L\"memory_watcher.dll\";\n\n\/\/ Load the memory profiling DLL. All it needs to be activated\n\/\/ is to be loaded. Return true on success, false otherwise.\nbool LoadMemoryProfiler() {\n HMODULE prof_module = LoadLibrary(kProfilingDll);\n return prof_module != NULL;\n}\n\nCAppModule _Module;\n\n#pragma optimize(\"\", off)\n\/\/ Handlers for invalid parameter and pure call. They generate a breakpoint to\n\/\/ tell breakpad that it needs to dump the process.\nvoid InvalidParameter(const wchar_t* expression, const wchar_t* function,\n const wchar_t* file, unsigned int line,\n uintptr_t reserved) {\n __debugbreak();\n}\n\nvoid PureCall() {\n __debugbreak();\n}\n\nint OnNoMemory(size_t memory_size) {\n __debugbreak();\n \/\/ Return memory_size so it is not optimized out. Make sure the return value\n \/\/ is at least 1 so malloc\/new is retried, especially useful when under a\n \/\/ debugger.\n return memory_size ? static_cast(memory_size) : 1;\n}\n\n\/\/ Handlers to silently dump the current process when there is an assert in\n\/\/ chrome.\nvoid ChromeAssert(const std::string& str) {\n \/\/ Get the breakpad pointer from chrome.exe\n typedef void (__stdcall *DumpProcessFunction)();\n DumpProcessFunction DumpProcess = reinterpret_cast(\n ::GetProcAddress(::GetModuleHandle(L\"chrome.exe\"), \"DumpProcess\"));\n if (DumpProcess)\n DumpProcess();\n}\n\n#pragma optimize(\"\", on)\n\n\/\/ Early versions of Chrome incorrectly registered a chromehtml: URL handler.\n\/\/ Later versions fixed the registration but in some cases (e.g. Vista and non-\n\/\/ admin installs) the fix could not be applied. This prevents Chrome to be\n\/\/ launched with the incorrect format.\n\/\/ CORRECT: -- \"chromehtml:\"\n\/\/ INVALID: \"chromehtml:\"\nbool IncorrectChromeHtmlArguments(const std::wstring& command_line) {\n const wchar_t kChromeHtml[] = L\"-- \\\"chromehtml:\";\n const wchar_t kOffset = 5; \/\/ Where chromehtml: starts in above\n std::wstring command_line_lower = command_line;\n\n \/\/ We are only searching for ASCII characters so this is OK.\n StringToLowerASCII(&command_line_lower);\n\n std::wstring::size_type pos = command_line_lower.find(\n kChromeHtml + kOffset);\n\n if (pos == std::wstring::npos)\n return false;\n\n \/\/ The browser is being launched with chromehtml: somewhere on the command\n \/\/ line. We will not launch unless it's preceded by the -- switch terminator.\n if (pos >= kOffset) {\n if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1,\n command_line_lower.begin() + pos - kOffset)) {\n return false;\n }\n }\n\n return true;\n}\n\n#endif \/\/ OS_WIN\n\n\/\/ Register the invalid param handler and pure call handler to be able to\n\/\/ notify breakpad when it happens.\nvoid RegisterInvalidParamHandler() {\n#if defined(OS_WIN)\n _set_invalid_parameter_handler(InvalidParameter);\n _set_purecall_handler(PureCall);\n \/\/ Gather allocation failure.\n _set_new_handler(&OnNoMemory);\n \/\/ Make sure malloc() calls the new handler too.\n _set_new_mode(1);\n#endif\n}\n\nvoid SetupCRT(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n#else\n if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) {\n _CrtSetReportMode(_CRT_ASSERT, 0);\n }\n#endif\n\n \/\/ Enable the low fragmentation heap for the CRT heap. The heap is not changed\n \/\/ if the process is run under the debugger is enabled or if certain gflags\n \/\/ are set.\n bool use_lfh = false;\n if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt))\n use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt)\n != L\"false\";\n if (use_lfh) {\n void* crt_heap = reinterpret_cast(_get_heap_handle());\n ULONG enable_lfh = 2;\n HeapSetInformation(crt_heap, HeapCompatibilityInformation,\n &enable_lfh, sizeof(enable_lfh));\n }\n#endif\n}\n\n\/\/ Enable the heap profiler if the appropriate command-line switch is\n\/\/ present, bailing out of the app we can't.\nvoid EnableHeapProfiler(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n if (parsed_command_line.HasSwitch(switches::kMemoryProfiling))\n if (!LoadMemoryProfiler())\n exit(-1);\n#endif\n}\n\nvoid CommonSubprocessInit() {\n \/\/ Initialize ResourceBundle which handles files loaded from external\n \/\/ sources. The language should have been passed in to us from the\n \/\/ browser process as a command line flag.\n ResourceBundle::InitSharedInstance(std::wstring());\n\n#if defined(OS_WIN)\n \/\/ HACK: Let Windows know that we have started. This is needed to suppress\n \/\/ the IDC_APPSTARTING cursor from being displayed for a prolonged period\n \/\/ while a subprocess is starting.\n PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);\n MSG msg;\n PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);\n#endif\n}\n\n} \/\/ namespace\n\n#if defined(OS_WIN)\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sandbox_info,\n TCHAR* command_line) {\n#elif defined(OS_POSIX)\nint ChromeMain(int argc, const char** argv) {\n#endif\n\n#if defined(OS_MACOSX)\n DebugUtil::DisableOSCrashDumps();\n#endif\n RegisterInvalidParamHandler();\n\n \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n base::AtExitManager exit_manager;\n\n \/\/ We need this pool for all the objects created before we get to the\n \/\/ event loop, but we don't want to leave them hanging around until the\n \/\/ app quits. Each \"main\" needs to flush this pool right before it goes into\n \/\/ its main event loop to get rid of the cruft.\n base::ScopedNSAutoreleasePool autorelease_pool;\n\n \/\/ Initialize the command line.\n#if defined(OS_WIN)\n CommandLine::Init(0, NULL);\n#else\n CommandLine::Init(argc, argv);\n#endif\n const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n\n#if defined(OS_WIN)\n \/\/ Must do this before any other usage of command line!\n if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string()))\n return 1;\n#endif\n\n int browser_pid;\n std::wstring process_type =\n parsed_command_line.GetSwitchValue(switches::kProcessType);\n if (process_type.empty()) {\n browser_pid = base::GetCurrentProcId();\n } else {\n std::wstring channel_name =\n parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n browser_pid = StringToInt(WideToASCII(channel_name));\n DCHECK(browser_pid != 0);\n }\n SetupCRT(parsed_command_line);\n\n \/\/ Initialize the Chrome path provider.\n chrome::RegisterPathProvider();\n\n \/\/ Initialize the Stats Counters table. With this initialized,\n \/\/ the StatsViewer can be utilized to read counters outside of\n \/\/ Chrome. These lines can be commented out to effectively turn\n \/\/ counters 'off'. The table is created and exists for the life\n \/\/ of the process. It is not cleaned up.\n \/\/ TODO(port): we probably need to shut this down correctly to avoid\n \/\/ leaking shared memory regions on posix platforms.\n std::string statsfile =\n StringPrintf(\"%s-%d\", chrome::kStatsFilename, browser_pid);\n StatsTable *stats_table = new StatsTable(statsfile,\n chrome::kStatsMaxThreads, chrome::kStatsMaxCounters);\n StatsTable::set_current(stats_table);\n\n StatsScope\n startup_timer(chrome::Counters::chrome_main());\n\n \/\/ Enable the heap profiler as early as possible!\n EnableHeapProfiler(parsed_command_line);\n\n \/\/ Enable Message Loop related state asap.\n if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer))\n MessageLoop::EnableHistogrammer(true);\n\n \/\/ Checks if the sandbox is enabled in this process and initializes it if this\n \/\/ is the case. The crash handler depends on this so it has to be done before\n \/\/ its initialization.\n SandboxInitWrapper sandbox_wrapper;\n#if defined(OS_WIN)\n sandbox_wrapper.SetServices(sandbox_info);\n#endif\n sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type);\n\n#if defined(OS_WIN)\n _Module.Init(NULL, instance);\n#endif\n\n \/\/ Notice a user data directory override if any\n const std::wstring user_data_dir =\n parsed_command_line.GetSwitchValue(switches::kUserDataDir);\n if (!user_data_dir.empty())\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir);\n\n bool single_process =\n#if defined (GOOGLE_CHROME_BUILD)\n \/\/ This is an unsupported and not fully tested mode, so don't enable it for\n \/\/ official Chrome builds.\n false;\n#else\n parsed_command_line.HasSwitch(switches::kSingleProcess);\n#endif\n if (single_process)\n RenderProcessHost::set_run_renderer_in_process(true);\n#if defined(OS_MACOSX)\n \/\/ TODO(port-mac): This is from renderer_main_platform_delegate.cc.\n \/\/ shess tried to refactor things appropriately, but it sprawled out\n \/\/ of control because different platforms needed different styles of\n \/\/ initialization. Try again once we understand the process\n \/\/ architecture needed and where it should live.\n if (single_process)\n InitWebCoreSystemInterface();\n#endif\n\n bool icu_result = icu_util::Initialize();\n CHECK(icu_result);\n\n logging::OldFileDeletionState file_state =\n logging::APPEND_TO_OLD_LOG_FILE;\n if (process_type.empty()) {\n file_state = logging::DELETE_OLD_LOG_FILE;\n }\n logging::InitChromeLogging(parsed_command_line, file_state);\n\n#ifdef NDEBUG\n if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) &&\n parsed_command_line.HasSwitch(switches::kEnableDCHECK)) {\n#if defined(OS_WIN)\n logging::SetLogReportHandler(ChromeAssert);\n#endif\n }\n#endif \/\/ NDEBUG\n\n if (!process_type.empty())\n CommonSubprocessInit();\n\n startup_timer.Stop(); \/\/ End of Startup Time Measurement.\n\n MainFunctionParams main_params(parsed_command_line, sandbox_wrapper,\n &autorelease_pool);\n\n \/\/ TODO(port): turn on these main() functions as they've been de-winified.\n int rv = -1;\n if (process_type == switches::kRendererProcess) {\n rv = RendererMain(main_params);\n } else if (process_type == switches::kPluginProcess) {\n#if defined(OS_WIN)\n rv = PluginMain(main_params);\n#endif\n } else if (process_type == switches::kWorkerProcess) {\n#if defined(OS_WIN)\n rv = WorkerMain(main_params);\n#endif\n } else if (process_type.empty()) {\n#if defined(OS_LINUX)\n \/\/ gtk_init() can change |argc| and |argv|, but nobody else uses them.\n gtk_init(&argc, const_cast(&argv));\n#endif\n\n ScopedOleInitializer ole_initializer;\n rv = BrowserMain(main_params);\n } else {\n NOTREACHED() << \"Unknown process type\";\n }\n\n if (!process_type.empty()) {\n ResourceBundle::CleanupSharedInstance();\n }\n\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n _CrtDumpMemoryLeaks();\n#endif \/\/ _CRTDBG_MAP_ALLOC\n\n _Module.Term();\n#endif\n\n logging::CleanupChromeLogging();\n\n return rv;\n}\nPipe fatal GTK messages through our logging system.\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ TODO(port): the ifdefs in here are a first step towards trying to determine\n\/\/ the correct abstraction for all the OS functionality required at this\n\/\/ stage of process initialization. It should not be taken as a final\n\/\/ abstraction.\n\n#include \"build\/build_config.h\"\n\n#if defined(OS_WIN)\n#include \n#include \n#include \n#include \n#include \n#endif\n\n#if defined(OS_LINUX)\n#include \n#endif\n\n#include \"base\/at_exit.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug_util.h\"\n#include \"base\/icu_util.h\"\n#include \"base\/message_loop.h\"\n#include \"base\/path_service.h\"\n#include \"base\/process_util.h\"\n#include \"base\/scoped_nsautorelease_pool.h\"\n#include \"base\/stats_table.h\"\n#include \"base\/string_util.h\"\n#if defined(OS_WIN)\n#include \"base\/win_util.h\"\n#endif\n#include \"chrome\/app\/scoped_ole_initializer.h\"\n#include \"chrome\/browser\/renderer_host\/render_process_host.h\"\n#include \"chrome\/common\/chrome_constants.h\"\n#include \"chrome\/common\/chrome_counters.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/logging_chrome.h\"\n#include \"chrome\/common\/main_function_params.h\"\n#include \"chrome\/common\/resource_bundle.h\"\n#include \"chrome\/common\/sandbox_init_wrapper.h\"\n#if defined(OS_WIN)\n#include \"sandbox\/src\/sandbox.h\"\n#include \"tools\/memory_watcher\/memory_watcher.h\"\n#endif\n#if defined(OS_MACOSX)\n#include \"third_party\/WebKit\/WebKit\/mac\/WebCoreSupport\/WebSystemInterface.h\"\n#endif\n\nextern int BrowserMain(const MainFunctionParams&);\nextern int RendererMain(const MainFunctionParams&);\nextern int PluginMain(const MainFunctionParams&);\nextern int WorkerMain(const MainFunctionParams&);\n\n#if defined(OS_WIN)\n\/\/ TODO(erikkay): isn't this already defined somewhere?\n#define DLLEXPORT __declspec(dllexport)\n\n\/\/ We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.\nextern \"C\" {\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sandbox_info,\n TCHAR* command_line);\n}\n#elif defined(OS_POSIX)\nextern \"C\" {\nint ChromeMain(int argc, const char** argv);\n}\n#endif\n\nnamespace {\n\n#if defined(OS_WIN)\nconst wchar_t kProfilingDll[] = L\"memory_watcher.dll\";\n\n\/\/ Load the memory profiling DLL. All it needs to be activated\n\/\/ is to be loaded. Return true on success, false otherwise.\nbool LoadMemoryProfiler() {\n HMODULE prof_module = LoadLibrary(kProfilingDll);\n return prof_module != NULL;\n}\n\nCAppModule _Module;\n\n#pragma optimize(\"\", off)\n\/\/ Handlers for invalid parameter and pure call. They generate a breakpoint to\n\/\/ tell breakpad that it needs to dump the process.\nvoid InvalidParameter(const wchar_t* expression, const wchar_t* function,\n const wchar_t* file, unsigned int line,\n uintptr_t reserved) {\n __debugbreak();\n}\n\nvoid PureCall() {\n __debugbreak();\n}\n\nint OnNoMemory(size_t memory_size) {\n __debugbreak();\n \/\/ Return memory_size so it is not optimized out. Make sure the return value\n \/\/ is at least 1 so malloc\/new is retried, especially useful when under a\n \/\/ debugger.\n return memory_size ? static_cast(memory_size) : 1;\n}\n\n\/\/ Handlers to silently dump the current process when there is an assert in\n\/\/ chrome.\nvoid ChromeAssert(const std::string& str) {\n \/\/ Get the breakpad pointer from chrome.exe\n typedef void (__stdcall *DumpProcessFunction)();\n DumpProcessFunction DumpProcess = reinterpret_cast(\n ::GetProcAddress(::GetModuleHandle(L\"chrome.exe\"), \"DumpProcess\"));\n if (DumpProcess)\n DumpProcess();\n}\n\n#pragma optimize(\"\", on)\n\n\/\/ Early versions of Chrome incorrectly registered a chromehtml: URL handler.\n\/\/ Later versions fixed the registration but in some cases (e.g. Vista and non-\n\/\/ admin installs) the fix could not be applied. This prevents Chrome to be\n\/\/ launched with the incorrect format.\n\/\/ CORRECT: -- \"chromehtml:\"\n\/\/ INVALID: \"chromehtml:\"\nbool IncorrectChromeHtmlArguments(const std::wstring& command_line) {\n const wchar_t kChromeHtml[] = L\"-- \\\"chromehtml:\";\n const wchar_t kOffset = 5; \/\/ Where chromehtml: starts in above\n std::wstring command_line_lower = command_line;\n\n \/\/ We are only searching for ASCII characters so this is OK.\n StringToLowerASCII(&command_line_lower);\n\n std::wstring::size_type pos = command_line_lower.find(\n kChromeHtml + kOffset);\n\n if (pos == std::wstring::npos)\n return false;\n\n \/\/ The browser is being launched with chromehtml: somewhere on the command\n \/\/ line. We will not launch unless it's preceded by the -- switch terminator.\n if (pos >= kOffset) {\n if (equal(kChromeHtml, kChromeHtml + arraysize(kChromeHtml) - 1,\n command_line_lower.begin() + pos - kOffset)) {\n return false;\n }\n }\n\n return true;\n}\n\n#endif \/\/ OS_WIN\n\n#if defined(OS_LINUX)\nstatic void GtkFatalLogHandler(const gchar* log_domain,\n GLogLevelFlags log_level,\n const gchar* message,\n gpointer userdata) {\n if (!log_domain)\n log_domain = \"\";\n if (!message)\n message = \"\";\n\n NOTREACHED() << \"GTK: (\" << log_domain << \"): \" << message;\n}\n#endif\n\n\/\/ Register the invalid param handler and pure call handler to be able to\n\/\/ notify breakpad when it happens.\nvoid RegisterInvalidParamHandler() {\n#if defined(OS_WIN)\n _set_invalid_parameter_handler(InvalidParameter);\n _set_purecall_handler(PureCall);\n \/\/ Gather allocation failure.\n _set_new_handler(&OnNoMemory);\n \/\/ Make sure malloc() calls the new handler too.\n _set_new_mode(1);\n#endif\n}\n\nvoid SetupCRT(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n _CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);\n#else\n if (!parsed_command_line.HasSwitch(switches::kDisableBreakpad)) {\n _CrtSetReportMode(_CRT_ASSERT, 0);\n }\n#endif\n\n \/\/ Enable the low fragmentation heap for the CRT heap. The heap is not changed\n \/\/ if the process is run under the debugger is enabled or if certain gflags\n \/\/ are set.\n bool use_lfh = false;\n if (parsed_command_line.HasSwitch(switches::kUseLowFragHeapCrt))\n use_lfh = parsed_command_line.GetSwitchValue(switches::kUseLowFragHeapCrt)\n != L\"false\";\n if (use_lfh) {\n void* crt_heap = reinterpret_cast(_get_heap_handle());\n ULONG enable_lfh = 2;\n HeapSetInformation(crt_heap, HeapCompatibilityInformation,\n &enable_lfh, sizeof(enable_lfh));\n }\n#endif\n}\n\n\/\/ Enable the heap profiler if the appropriate command-line switch is\n\/\/ present, bailing out of the app we can't.\nvoid EnableHeapProfiler(const CommandLine& parsed_command_line) {\n#if defined(OS_WIN)\n if (parsed_command_line.HasSwitch(switches::kMemoryProfiling))\n if (!LoadMemoryProfiler())\n exit(-1);\n#endif\n}\n\nvoid CommonSubprocessInit() {\n \/\/ Initialize ResourceBundle which handles files loaded from external\n \/\/ sources. The language should have been passed in to us from the\n \/\/ browser process as a command line flag.\n ResourceBundle::InitSharedInstance(std::wstring());\n\n#if defined(OS_WIN)\n \/\/ HACK: Let Windows know that we have started. This is needed to suppress\n \/\/ the IDC_APPSTARTING cursor from being displayed for a prolonged period\n \/\/ while a subprocess is starting.\n PostThreadMessage(GetCurrentThreadId(), WM_NULL, 0, 0);\n MSG msg;\n PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);\n#endif\n}\n\n} \/\/ namespace\n\n#if defined(OS_WIN)\nDLLEXPORT int __cdecl ChromeMain(HINSTANCE instance,\n sandbox::SandboxInterfaceInfo* sandbox_info,\n TCHAR* command_line) {\n#elif defined(OS_POSIX)\nint ChromeMain(int argc, const char** argv) {\n#endif\n\n#if defined(OS_MACOSX)\n DebugUtil::DisableOSCrashDumps();\n#endif\n RegisterInvalidParamHandler();\n\n \/\/ The exit manager is in charge of calling the dtors of singleton objects.\n base::AtExitManager exit_manager;\n\n \/\/ We need this pool for all the objects created before we get to the\n \/\/ event loop, but we don't want to leave them hanging around until the\n \/\/ app quits. Each \"main\" needs to flush this pool right before it goes into\n \/\/ its main event loop to get rid of the cruft.\n base::ScopedNSAutoreleasePool autorelease_pool;\n\n \/\/ Initialize the command line.\n#if defined(OS_WIN)\n CommandLine::Init(0, NULL);\n#else\n CommandLine::Init(argc, argv);\n#endif\n const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();\n\n#if defined(OS_WIN)\n \/\/ Must do this before any other usage of command line!\n if (::IncorrectChromeHtmlArguments(parsed_command_line.command_line_string()))\n return 1;\n#endif\n\n int browser_pid;\n std::wstring process_type =\n parsed_command_line.GetSwitchValue(switches::kProcessType);\n if (process_type.empty()) {\n browser_pid = base::GetCurrentProcId();\n } else {\n std::wstring channel_name =\n parsed_command_line.GetSwitchValue(switches::kProcessChannelID);\n\n browser_pid = StringToInt(WideToASCII(channel_name));\n DCHECK(browser_pid != 0);\n }\n SetupCRT(parsed_command_line);\n\n \/\/ Initialize the Chrome path provider.\n chrome::RegisterPathProvider();\n\n \/\/ Initialize the Stats Counters table. With this initialized,\n \/\/ the StatsViewer can be utilized to read counters outside of\n \/\/ Chrome. These lines can be commented out to effectively turn\n \/\/ counters 'off'. The table is created and exists for the life\n \/\/ of the process. It is not cleaned up.\n \/\/ TODO(port): we probably need to shut this down correctly to avoid\n \/\/ leaking shared memory regions on posix platforms.\n std::string statsfile =\n StringPrintf(\"%s-%d\", chrome::kStatsFilename, browser_pid);\n StatsTable *stats_table = new StatsTable(statsfile,\n chrome::kStatsMaxThreads, chrome::kStatsMaxCounters);\n StatsTable::set_current(stats_table);\n\n StatsScope\n startup_timer(chrome::Counters::chrome_main());\n\n \/\/ Enable the heap profiler as early as possible!\n EnableHeapProfiler(parsed_command_line);\n\n \/\/ Enable Message Loop related state asap.\n if (parsed_command_line.HasSwitch(switches::kMessageLoopHistogrammer))\n MessageLoop::EnableHistogrammer(true);\n\n \/\/ Checks if the sandbox is enabled in this process and initializes it if this\n \/\/ is the case. The crash handler depends on this so it has to be done before\n \/\/ its initialization.\n SandboxInitWrapper sandbox_wrapper;\n#if defined(OS_WIN)\n sandbox_wrapper.SetServices(sandbox_info);\n#endif\n sandbox_wrapper.InitializeSandbox(parsed_command_line, process_type);\n\n#if defined(OS_WIN)\n _Module.Init(NULL, instance);\n#endif\n\n \/\/ Notice a user data directory override if any\n const std::wstring user_data_dir =\n parsed_command_line.GetSwitchValue(switches::kUserDataDir);\n if (!user_data_dir.empty())\n PathService::Override(chrome::DIR_USER_DATA, user_data_dir);\n\n bool single_process =\n#if defined (GOOGLE_CHROME_BUILD)\n \/\/ This is an unsupported and not fully tested mode, so don't enable it for\n \/\/ official Chrome builds.\n false;\n#else\n parsed_command_line.HasSwitch(switches::kSingleProcess);\n#endif\n if (single_process)\n RenderProcessHost::set_run_renderer_in_process(true);\n#if defined(OS_MACOSX)\n \/\/ TODO(port-mac): This is from renderer_main_platform_delegate.cc.\n \/\/ shess tried to refactor things appropriately, but it sprawled out\n \/\/ of control because different platforms needed different styles of\n \/\/ initialization. Try again once we understand the process\n \/\/ architecture needed and where it should live.\n if (single_process)\n InitWebCoreSystemInterface();\n#endif\n\n bool icu_result = icu_util::Initialize();\n CHECK(icu_result);\n\n logging::OldFileDeletionState file_state =\n logging::APPEND_TO_OLD_LOG_FILE;\n if (process_type.empty()) {\n file_state = logging::DELETE_OLD_LOG_FILE;\n }\n logging::InitChromeLogging(parsed_command_line, file_state);\n\n#ifdef NDEBUG\n if (parsed_command_line.HasSwitch(switches::kSilentDumpOnDCHECK) &&\n parsed_command_line.HasSwitch(switches::kEnableDCHECK)) {\n#if defined(OS_WIN)\n logging::SetLogReportHandler(ChromeAssert);\n#endif\n }\n#endif \/\/ NDEBUG\n\n if (!process_type.empty())\n CommonSubprocessInit();\n\n startup_timer.Stop(); \/\/ End of Startup Time Measurement.\n\n MainFunctionParams main_params(parsed_command_line, sandbox_wrapper,\n &autorelease_pool);\n\n \/\/ TODO(port): turn on these main() functions as they've been de-winified.\n int rv = -1;\n if (process_type == switches::kRendererProcess) {\n rv = RendererMain(main_params);\n } else if (process_type == switches::kPluginProcess) {\n#if defined(OS_WIN)\n rv = PluginMain(main_params);\n#endif\n } else if (process_type == switches::kWorkerProcess) {\n#if defined(OS_WIN)\n rv = WorkerMain(main_params);\n#endif\n } else if (process_type.empty()) {\n#if defined(OS_LINUX)\n \/\/ gtk_init() can change |argc| and |argv|, but nobody else uses them.\n gtk_init(&argc, const_cast(&argv));\n \/\/ Register GTK assertions to go through our logging system.\n g_log_set_handler(NULL, \/\/ All logging domains.\n static_cast(G_LOG_FLAG_RECURSION |\n G_LOG_FLAG_FATAL |\n G_LOG_LEVEL_ERROR |\n G_LOG_LEVEL_CRITICAL |\n G_LOG_LEVEL_WARNING),\n GtkFatalLogHandler,\n NULL);\n#endif\n\n ScopedOleInitializer ole_initializer;\n rv = BrowserMain(main_params);\n } else {\n NOTREACHED() << \"Unknown process type\";\n }\n\n if (!process_type.empty()) {\n ResourceBundle::CleanupSharedInstance();\n }\n\n#if defined(OS_WIN)\n#ifdef _CRTDBG_MAP_ALLOC\n _CrtDumpMemoryLeaks();\n#endif \/\/ _CRTDBG_MAP_ALLOC\n\n _Module.Term();\n#endif\n\n logging::CleanupChromeLogging();\n\n return rv;\n}\n<|endoftext|>"} {"text":"\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2015, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"TerminalWidget.h\"\n\n#include \n#include \n#include \n#include \n\nTerminalWidget::TerminalWidget(QWidget *parent, QString dir) : QTextEdit(parent){\n \/\/Setup the text widget\n this->setLineWrapMode(QTextEdit::WidgetWidth);\n \/\/this->setReadOnly(true); \/\/the key event catch will do the process\/widget forwarding\n \/\/this->setPlainText(\"WARNING: This utility is still incomplete and does not function properly yet\");\n \n \/\/Create\/open the TTY port\n PROC = new TTYProcess(this);\n qDebug() << \"Open new TTY\";\n \/\/int fd;\n bool ok = PROC->startTTY( QProcessEnvironment::systemEnvironment().value(\"SHELL\",\"\/bin\/sh\") );\n qDebug() << \" - opened:\" << ok;\n this->setEnabled(PROC->isOpen());\n\n \/\/Connect the signals\/slots\n connect(PROC, SIGNAL(readyRead()), this, SLOT(UpdateText()) );\n connect(PROC, SIGNAL(processClosed()), this, SLOT(ShellClosed()) );\n \n}\n\nTerminalWidget::~TerminalWidget(){\n aboutToClose();\n}\n\nvoid TerminalWidget::aboutToClose(){\n if(PROC->isOpen()){ PROC->closeTTY(); } \/\/TTY PORT\n}\n\n\/\/ ==================\n\/\/ PRIVATE\n\/\/ ==================\nvoid TerminalWidget::applyData(QByteArray data){\n \/\/Quick global replacement (this widget reads both as newlines)\n data = data.replace(\"\\r\\n\",\"\\n\");\n \/\/Iterate through the data and apply it when possible\n for(int i=0; itextCursor().deletePreviousChar();\n this->moveCursor(QTextCursor::Left, QTextCursor::MoveAnchor);\n }else if( data.at(i)=='\\x1B' ){\n \/\/ANSI Control Code start\n \/\/Look for the end of the code\n int end = -1;\n for(int j=1; j<(data.size()-i) && end<0; j++){\n if(QChar(data.at(i+j)).isLetter()){ end = j; }\n }\n if(end<0){ return; } \/\/skip everything else - no end to code found\n applyANSI(data.mid(i+1, end));\n i+=end; \/\/move the final loop along - already handled these bytes\n \n }else{\n \/\/Special Check: if inserting text within a line, clear the rest of this line first\n if(i==0 && this->textCursor().position() < this->document()->characterCount()-1){\n applyANSI(\"[K\");\n }\n \/\/Plaintext character - just add it here\n this->insertPlainText( QChar(data.at(i)) );\n }\n \n } \/\/end loop over data\n}\n\nvoid TerminalWidget::applyANSI(QByteArray code){\n \/\/Note: the first byte is often the \"[\" character\n \/\/qDebug() << \"Handle ANSI:\" << code;\n \/\/CURSOR MOVEMENT\n if( code.endsWith(\"A\") ){ \/\/Move Up\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"B\")){ \/\/Move Down\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"C\")){ \/\/Move Forward\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n for(int i=0; imoveCursor(QTextCursor::Right, QTextCursor::MoveAnchor); }\n \/\/this->textCursor().movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"D\")){ \/\/Move Back\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n for(int i=0; imoveCursor(QTextCursor::Left, QTextCursor::MoveAnchor); }\n \/\/this->textCursor().movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"E\")){ \/\/Move Next\/down Lines (go to beginning)\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::NextRow, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"F\")){ \/\/Move Previous\/up Lines (go to beginning)\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::PreviousRow, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"G\")){ \/\/Move to specific column\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().setPosition(num);\n }else if(code.endsWith(\"H\") || code.endsWith(\"f\") ){ \/\/Move to specific position (row\/column)\n int mid = code.indexOf(\";\");\n if(mid>0){\n int numR, numC; numR = numC = 1;\n if(mid >=3){ numR = code.mid(1,mid-1).toInt(); }\n if(mid < code.size()-1){ numC = code.mid(mid+1,code.size()-mid-1).toInt(); }\n \/\/this->textCursor().setPosition(\n qDebug() << \"Set Text Position (absolute):\" << \"Row:\" << numR << \"Col:\" << numC;\n \/\/ TO-DO\n }\n \n \/\/ DISPLAY CLEAR CODES\n }else if(code.endsWith(\"J\")){ \/\/ED - Erase Display\n \n }else if(code.endsWith(\"K\")){ \/\/EL - Erase in Line\n int num = 0;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n qDebug() << \"Erase Number\" << num;\n \/\/Now determine what should be cleared based on code\n if(num==1){\n\t \n }else if(num==2){\n\t \n }else{\n \/\/Clear from current cursor to end of line\n for(int i=this->textCursor().position(); idocument()->characterCount()+1; i++){\n \/\/while(this->document()->characterAt(this->textCursor().position())!=QChar('\\n') && this->textCursor().position() < this->document()->characterCount()){\n\tif(this->document()->characterAt(this->textCursor().position())=='\\n'){ break; }\n this->textCursor().deleteChar();\n }\n }\n }\n}\n\n\/\/Outgoing Data parsing\nvoid TerminalWidget::sendKeyPress(int key){\n QByteArray ba;\n \/\/Check for special keys\n switch(key){\n case Qt::Key_Delete:\n\tba.append(\"\\x7F\");\n break;\n case Qt::Key_Backspace:\n\tba.append(\"\\x08\"); \n break;\n case Qt::Key_Left:\n\tba.append(\"\\x1b[D\");\n break;\n case Qt::Key_Right:\n\tba.append(\"\\x1b[C\");\n break;\n case Qt::Key_Up:\n ba.append(\"\\x1b[A\");\n break;\n case Qt::Key_Down:\n ba.append(\"\\x1b[B\");\n break;\n }\n \n \/\/qDebug() << \"Forward Input:\" << txt << ev->key() << ba;\n if(!ba.isEmpty()){ PROC->writeTTY(ba); }\n}\n\n\/\/ ==================\n\/\/ PRIVATE SLOTS\n\/\/ ==================\nvoid TerminalWidget::UpdateText(){\n \/\/read the data from the process\n \/\/qDebug() << \"UpdateText\";\n if(!PROC->isOpen()){ return; }\n applyData(PROC->readTTY());\n \/\/adjust the scrollbar as needed\n this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum());\n}\n\nvoid TerminalWidget::ShellClosed(){\n emit ProcessClosed(this->whatsThis());\n}\n\n\/\/ ==================\n\/\/ PROTECTED\n\/\/ ==================\nvoid TerminalWidget::keyPressEvent(QKeyEvent *ev){\n\t\n if(ev->text().isEmpty() || ev->text()==\"\\b\" ){\n sendKeyPress(ev->key());\n }else{\n QByteArray ba; ba.append(ev->text()); \/\/avoid any byte conversions\n PROC->writeTTY(ba);\n }\n \n ev->ignore();\n}\n\nvoid TerminalWidget::mousePressEvent(QMouseEvent *ev){\n this->setFocus();\n Q_UNUSED(ev);\n}\n\nvoid TerminalWidget::mouseDoubleClickEvent(QMouseEvent *ev){\n Q_UNUSED(ev);\t\n}\n\nvoid TerminalWidget::contextMenuEvent(QContextMenuEvent *ev){\n Q_UNUSED(ev);\t\n}\n\nvoid TerminalWidget::resizeEvent(QResizeEvent *ev){\n if(!PROC->isOpen()){ return; }\n QSize pix = ev->size(); \/\/pixels\n QSize chars; \n chars.setWidth( pix.width()\/this->fontMetrics().width(\"W\") );\n chars.setHeight( pix.height()\/this->fontMetrics().lineSpacing() );\n \n PROC->setTerminalSize(chars,pix);\n QTextEdit::resizeEvent(ev);\n}\nFinish getting the special keys handled in lumina-terminal. Now the terminal is completely functional - I just have other special ANSI codes (colors for particular text) to implement still (but this is just for appearance-sake).\/\/===========================================\n\/\/ Lumina-DE source code\n\/\/ Copyright (c) 2015, Ken Moore\n\/\/ Available under the 3-clause BSD license\n\/\/ See the LICENSE file for full details\n\/\/===========================================\n#include \"TerminalWidget.h\"\n\n#include \n#include \n#include \n#include \n\nTerminalWidget::TerminalWidget(QWidget *parent, QString dir) : QTextEdit(parent){\n \/\/Setup the text widget\n this->setLineWrapMode(QTextEdit::WidgetWidth);\n \/\/this->setReadOnly(true); \/\/the key event catch will do the process\/widget forwarding\n \/\/this->setPlainText(\"WARNING: This utility is still incomplete and does not function properly yet\");\n \n \/\/Create\/open the TTY port\n PROC = new TTYProcess(this);\n qDebug() << \"Open new TTY\";\n \/\/int fd;\n bool ok = PROC->startTTY( QProcessEnvironment::systemEnvironment().value(\"SHELL\",\"\/bin\/sh\") );\n qDebug() << \" - opened:\" << ok;\n this->setEnabled(PROC->isOpen());\n\n \/\/Connect the signals\/slots\n connect(PROC, SIGNAL(readyRead()), this, SLOT(UpdateText()) );\n connect(PROC, SIGNAL(processClosed()), this, SLOT(ShellClosed()) );\n \n}\n\nTerminalWidget::~TerminalWidget(){\n aboutToClose();\n}\n\nvoid TerminalWidget::aboutToClose(){\n if(PROC->isOpen()){ PROC->closeTTY(); } \/\/TTY PORT\n}\n\n\/\/ ==================\n\/\/ PRIVATE\n\/\/ ==================\nvoid TerminalWidget::applyData(QByteArray data){\n \/\/Quick global replacement (this widget reads both as newlines)\n data = data.replace(\"\\r\\n\",\"\\n\");\n \/\/Iterate through the data and apply it when possible\n for(int i=0; itextCursor().deletePreviousChar();\n this->moveCursor(QTextCursor::Left, QTextCursor::MoveAnchor);\n }else if( data.at(i)=='\\x1B' ){\n \/\/ANSI Control Code start\n \/\/Look for the end of the code\n int end = -1;\n for(int j=1; j<(data.size()-i) && end<0; j++){\n if(QChar(data.at(i+j)).isLetter()){ end = j; }\n }\n if(end<0){ return; } \/\/skip everything else - no end to code found\n applyANSI(data.mid(i+1, end));\n i+=end; \/\/move the final loop along - already handled these bytes\n \n }else{\n \/\/Special Check: if inserting text within a line, clear the rest of this line first\n if(i==0 && this->textCursor().position() < this->document()->characterCount()-1){\n applyANSI(\"[K\");\n }\n \/\/Plaintext character - just add it here\n this->insertPlainText( QChar(data.at(i)) );\n }\n \n } \/\/end loop over data\n}\n\nvoid TerminalWidget::applyANSI(QByteArray code){\n \/\/Note: the first byte is often the \"[\" character\n \/\/qDebug() << \"Handle ANSI:\" << code;\n \/\/CURSOR MOVEMENT\n if( code.endsWith(\"A\") ){ \/\/Move Up\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::Up, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"B\")){ \/\/Move Down\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::Down, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"C\")){ \/\/Move Forward\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n for(int i=0; imoveCursor(QTextCursor::Right, QTextCursor::MoveAnchor); }\n \/\/this->textCursor().movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"D\")){ \/\/Move Back\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n for(int i=0; imoveCursor(QTextCursor::Left, QTextCursor::MoveAnchor); }\n \/\/this->textCursor().movePosition(QTextCursor::Left, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"E\")){ \/\/Move Next\/down Lines (go to beginning)\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::NextRow, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"F\")){ \/\/Move Previous\/up Lines (go to beginning)\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().movePosition(QTextCursor::PreviousRow, QTextCursor::MoveAnchor, num);\n }else if(code.endsWith(\"G\")){ \/\/Move to specific column\n int num = 1;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n this->textCursor().setPosition(num);\n }else if(code.endsWith(\"H\") || code.endsWith(\"f\") ){ \/\/Move to specific position (row\/column)\n int mid = code.indexOf(\";\");\n if(mid>0){\n int numR, numC; numR = numC = 1;\n if(mid >=3){ numR = code.mid(1,mid-1).toInt(); }\n if(mid < code.size()-1){ numC = code.mid(mid+1,code.size()-mid-1).toInt(); }\n \/\/this->textCursor().setPosition(\n qDebug() << \"Set Text Position (absolute):\" << \"Row:\" << numR << \"Col:\" << numC;\n \/\/ TO-DO\n }\n \n \/\/ DISPLAY CLEAR CODES\n }else if(code.endsWith(\"J\")){ \/\/ED - Erase Display\n \n }else if(code.endsWith(\"K\")){ \/\/EL - Erase in Line\n int num = 0;\n if(code.size()>2){ num = code.mid(1, code.size()-2).toInt(); } \/\/everything in the middle\n qDebug() << \"Erase Number\" << num;\n \/\/Now determine what should be cleared based on code\n if(num==1){\n \/\/Clear from current cursor to beginning of line\n for(int i=this->textCursor().position(); i>=0; i--){\n\tif(this->document()->characterAt(this->textCursor().position())=='\\n'){ break; }\n this->textCursor().deleteChar();\n }\t \n }else if(num==2){\n \/\/Clear the entire line\n \/\/ rewind the starting point to the beginning of the line\n int start = this->document()->find(\"\\n\", this->textCursor().position(), QTextDocument::FindBackward).position();\n for(int i=start+1; idocument()->characterCount()+1; i++){\n\tif(this->document()->characterAt(this->textCursor().position())=='\\n'){ break; }\n this->textCursor().deleteChar();\n }\n }else{\n \/\/Clear from current cursor to end of line\n for(int i=this->textCursor().position(); idocument()->characterCount()+1; i++){\n\tif(this->document()->characterAt(this->textCursor().position())=='\\n'){ break; }\n this->textCursor().deleteChar();\n }\n }\n }\n}\n\n\/\/Outgoing Data parsing\nvoid TerminalWidget::sendKeyPress(int key){\n QByteArray ba;\n \/\/Check for special keys\n switch(key){\n case Qt::Key_Delete:\n\tba.append(\"\\x7F\");\n break;\n case Qt::Key_Backspace:\n\tba.append(\"\\x08\"); \n break;\n case Qt::Key_Left:\n\tba.append(\"\\x1b[D\");\n break;\n case Qt::Key_Right:\n\tba.append(\"\\x1b[C\");\n break;\n case Qt::Key_Up:\n ba.append(\"\\x1b[A\");\n break;\n case Qt::Key_Down:\n ba.append(\"\\x1b[B\");\n break;\n }\n \n \/\/qDebug() << \"Forward Input:\" << txt << ev->key() << ba;\n if(!ba.isEmpty()){ PROC->writeTTY(ba); }\n}\n\n\/\/ ==================\n\/\/ PRIVATE SLOTS\n\/\/ ==================\nvoid TerminalWidget::UpdateText(){\n \/\/read the data from the process\n \/\/qDebug() << \"UpdateText\";\n if(!PROC->isOpen()){ return; }\n applyData(PROC->readTTY());\n \/\/adjust the scrollbar as needed\n this->verticalScrollBar()->setValue(this->verticalScrollBar()->maximum());\n}\n\nvoid TerminalWidget::ShellClosed(){\n emit ProcessClosed(this->whatsThis());\n}\n\n\/\/ ==================\n\/\/ PROTECTED\n\/\/ ==================\nvoid TerminalWidget::keyPressEvent(QKeyEvent *ev){\n\t\n if(ev->text().isEmpty() || ev->text()==\"\\b\" ){\n sendKeyPress(ev->key());\n }else{\n QByteArray ba; ba.append(ev->text()); \/\/avoid any byte conversions\n PROC->writeTTY(ba);\n }\n \n ev->ignore();\n}\n\nvoid TerminalWidget::mousePressEvent(QMouseEvent *ev){\n this->setFocus();\n Q_UNUSED(ev);\n}\n\nvoid TerminalWidget::mouseDoubleClickEvent(QMouseEvent *ev){\n Q_UNUSED(ev);\t\n}\n\nvoid TerminalWidget::contextMenuEvent(QContextMenuEvent *ev){\n Q_UNUSED(ev);\t\n}\n\nvoid TerminalWidget::resizeEvent(QResizeEvent *ev){\n if(!PROC->isOpen()){ return; }\n QSize pix = ev->size(); \/\/pixels\n QSize chars; \n chars.setWidth( pix.width()\/this->fontMetrics().width(\"W\") );\n chars.setHeight( pix.height()\/this->fontMetrics().lineSpacing() );\n \n PROC->setTerminalSize(chars,pix);\n QTextEdit::resizeEvent(ev);\n}\n<|endoftext|>"} {"text":"Eliminate memory leak due to circular shared_ptr<|endoftext|>"} {"text":"More VS fixes (huehue)<|endoftext|>"} {"text":"\n\/\/Implementations of the AST objects\n\/\/Much of the logic of creating these comes from bison grammar\n\n#include \"node.h\"\n\n\nvoid Node::describe() {\n\tprintf(\"Found generic node object with no fields\\n\");\n}\n\nvoid Expression::describe() {\n\tprintf(\"Found generic Expression object with no fields\\n\");\n}\n\nvoid Statement::describe() {\n\tprintf(\"Found generic statement object with no fields\\n\");\n}\n\nInteger::Integer(int64_t value) {\n\tthis->value = value;\n}\n\nvoid Integer::describe() {\n\tprintf(\"Found Literal Integer: %i\\n\", (int)value);\n}\n\nFloat::Float(double value) {\n\tthis->value = value;\n}\n\nvoid Float::describe() {\n\tprintf(\"Found Float: %f\\n\", value);\n}\n\nIdentifier::Identifier(char* name) {\n\tsize_t length = strlen(name);\n\tthis->name = (char*)GC_MALLOC(length+1);\n\tmemcpy(this->name,name,length);\n\t\/\/It's good practice to keep our own copy\n}\n\nvoid Identifier::describe() {\n\tprintf(\"Found Identifier: %s\\n\",name);\n}\n\nNullaryOperator::NullaryOperator(int64_t op) {\n\tthis->op = op;\n}\n\nvoid NullaryOperator::describe() {\n\tprintf(\"Found Nullary Operator\\n\");\n}\n\nUnaryOperator::UnaryOperator(int64_t op, Expression* exp) {\n\tthis->op = op;\n\tthis->exp = exp;\n}\n\nvoid UnaryOperator::describe() {\n\tprintf(\"Found Unary Operator\\n\");\n}\n\nBinaryOperator::BinaryOperator(Expression* left, int64_t op, Expression* right) {\n\tthis->op = op;\n\tthis->left = left;\n\tthis->right = right;\n}\n\nvoid BinaryOperator::describe() {\n\tprintf(\"Found Binary Operator %d\\n\",(int)this->op);\n}\n\nAssignment::Assignment(Identifier* left, Expression* right) {\n\tthis->left = left;\n\tthis->right = right;\n}\n\nvoid Assignment::describe() {\n\tprintf(\"Found Assignment: %s\\n\",left->name);\n}\n\nBlock::Block(vector>* statements) {\n\tthis->statements = statements;\n}\n\nvoid Block::describe() {\n\tprintf(\"Found Block\\n\");\n}\n\nBlock::Block() {\n\tthis->statements = NULL;\n}\n\nFunctionCall::FunctionCall(Identifier* ident, vector>* args) {\n\tthis->ident = ident;\n\tthis->args = args;\n}\n\nvoid FunctionCall::describe() {\n\tprintf(\"Found Function Call: %s\\n\",ident->name);\n}\n\nKeyword::Keyword(char* name) {\n\tsize_t length = strlen(name);\n\tthis->name = (char*)GC_MALLOC(length+1);\n\tmemcpy(this->name,name,length);\n}\n\nvoid Keyword::describe() {\n\tprintf(\"Found Keyword: %s\\n\",name);\n}\n\nVariableDefinition::VariableDefinition(Keyword* type, Identifier* ident, Expression* exp) {\n\tthis->type = type;\n\tthis->ident = ident;\n\tthis->exp = exp;\n}\n\nvoid VariableDefinition::describe() {\n\tprintf(\"Found Variable Declaration: type='%s' identifier='%s'\\n\",type->name,\n\t\tident->name);\n}\n\nFunctionDefinition::FunctionDefinition(Keyword* type, Identifier* ident, vector>* args,\n\t Block* block) {\n\tthis->type = type;\n\tthis->ident = ident;\n\tthis->args = args;\n\tthis->block = block;\n}\n\nvoid FunctionDefinition::describe() {\n\tprintf(\"Found Function Definition: %s\\n\",ident->name);\n}\n\nExpressionStatement::ExpressionStatement(Expression* exp) {\n\tthis->exp = exp;\n}\n\nvoid ExpressionStatement::describe() {\n\tprintf(\"Expression(s) converted into statements\\n\");\n}\n\nReturnStatement::ReturnStatement(Expression* exp) {\n\tthis->exp = exp;\n}\n\nvoid ReturnStatement::describe() {\n\tif (exp) {\n\t printf(\"Found return statement with expression\\n\");\n\t} else {\n\t printf(\"Found return statement, statement returns void\\n\");\n\t}\n}\n\nAssignStatement::AssignStatement(Expression* target,Expression* valxp) {\n\tthis->target = target;\n\tthis->valxp = valxp;\n}\n\nvoid AssignStatement::describe() {\n\tprintf(\"Found Assignment Statement\\n\");\n}\n\nStructureDefinition::StructureDefinition(Identifier* ident,Block* block) {\n\tthis->ident = ident;\n\tthis->block = block;\n}\n\nvoid StructureDefinition::describe() {\n\tprintf(\"Found Structure Definition: %s\\n\",ident->name);\n}\n\nStructureDeclaration::StructureDeclaration(Identifier* type,Identifier* ident) {\n\tthis->type = type;\n\tthis->ident = ident;\n}\n\nvoid StructureDeclaration::describe() {\n\tprintf(\"Found Structure Declaration: type='%s' identifier='%s'\\n\",\n\t\ttype->name,ident->name);\n}\n\nChanges to output messages, use GC_MALLOC_ATMOC\n\/\/Implementations of the AST objects\n\/\/Much of the logic of creating these comes from bison grammar\n\n#include \"node.h\"\n\n\nvoid Node::describe() {\n\tprintf(\"---Found generic node object with no fields.\");\n\tprintf(\"---This SHOULD BE AN ERROR.\");\n}\n\nvoid Expression::describe() {\n\tprintf(\"---Found generic Expression object with no fields\\n\");\n}\n\nvoid Statement::describe() {\n\tprintf(\"---Found generic statement object with no fields\\n\");\n}\n\nInteger::Integer(int64_t value) {\n\tthis->value = value;\n}\n\nvoid Integer::describe() {\n\tprintf(\"---Found Literal Integer: %i\\n\", (int)value);\n}\n\nFloat::Float(double value) {\n\tthis->value = value;\n}\n\nvoid Float::describe() {\n\tprintf(\"---Found Float: %f\\n\", value);\n}\n\nIdentifier::Identifier(char* name) {\n\tsize_t length = strlen(name);\n\tthis->name = (char*)GC_MALLOC_ATOMIC(length+1);\n\tmemcpy(this->name,name,length);\n\t\/\/Its good practice to keep our own copy\n}\n\nvoid Identifier::describe() {\n\tprintf(\"---Found Identifier: %s\\n\",name);\n}\n\nNullaryOperator::NullaryOperator(int64_t op) {\n\tthis->op = op;\n}\n\nvoid NullaryOperator::describe() {\n\tprintf(\"---Found Nullary Operator\\n\");\n}\n\nUnaryOperator::UnaryOperator(int64_t op, Expression* exp) {\n\tthis->op = op;\n\tthis->exp = exp;\n}\n\nvoid UnaryOperator::describe() {\n\tprintf(\"---Found Unary Operator\\n\");\n}\n\nBinaryOperator::BinaryOperator(Expression* left, int64_t op, Expression* right) {\n\tthis->op = op;\n\tthis->left = left;\n\tthis->right = right;\n}\n\nvoid BinaryOperator::describe() {\n\tprintf(\"---Found Binary Operator %d\\n\",(int)this->op);\n}\n\nAssignment::Assignment(Identifier* left, Expression* right) {\n\tthis->left = left;\n\tthis->right = right;\n}\n\nvoid Assignment::describe() {\n\tprintf(\"---Found Assignment: %s\\n\",left->name);\n}\n\nBlock::Block(vector>* statements) {\n\tthis->statements = statements;\n}\n\nvoid Block::describe() {\n\tprintf(\"---Found Block\\n\");\n}\n\nBlock::Block() {\n\tthis->statements = NULL;\n}\n\nFunctionCall::FunctionCall(Identifier* ident, vector>* args) {\n\tthis->ident = ident;\n\tthis->args = args;\n}\n\nvoid FunctionCall::describe() {\n\tprintf(\"---Found Function Call: %s\\n\",ident->name);\n}\n\nKeyword::Keyword(char* name) {\n\tsize_t length = strlen(name);\n\tthis->name = (char*)GC_MALLOC_ATOMIC(length+1);\n\tmemcpy(this->name,name,length);\n}\n\nvoid Keyword::describe() {\n\tprintf(\"---Found Keyword: %s\\n\",name);\n}\n\nVariableDefinition::VariableDefinition(Keyword* type, Identifier* ident, Expression* exp) {\n\tthis->type = type;\n\tthis->ident = ident;\n\tthis->exp = exp;\n}\n\nvoid VariableDefinition::describe() {\n\tprintf(\"---Found Variable Declaration: type='%s' identifier='%s'\\n\",\n\t\ttype->name,ident->name);\n}\n\nFunctionDefinition::FunctionDefinition(Keyword* type, Identifier* ident,\n\t vector>* args,\n\t Block* block) {\n\tthis->type = type;\n\tthis->ident = ident;\n\tthis->args = args;\n\tthis->block = block;\n}\n\nvoid FunctionDefinition::describe() {\n\tprintf(\"---Found Function Definition: %s\\n\",ident->name);\n}\n\nExpressionStatement::ExpressionStatement(Expression* exp) {\n\tthis->exp = exp;\n}\n\nvoid ExpressionStatement::describe() {\n\tprintf(\"---Expression(s) converted into statements\\n\");\n}\n\nReturnStatement::ReturnStatement(Expression* exp) {\n\tthis->exp = exp;\n}\n\nvoid ReturnStatement::describe() {\n\tif (exp) {\n\t printf(\"---Found return statement with expression\\n\");\n\t} else {\n\t printf(\"---Found return statement, statement returns void\\n\");\n\t}\n}\n\nAssignStatement::AssignStatement(Expression* target,Expression* valxp) {\n\tthis->target = target;\n\tthis->valxp = valxp;\n}\n\nvoid AssignStatement::describe() {\n\tprintf(\"---Found Assignment Statement\\n\");\n}\n\nStructureDefinition::StructureDefinition(Identifier* ident,Block* block) {\n\tthis->ident = ident;\n\tthis->block = block;\n}\n\nvoid StructureDefinition::describe() {\n\tprintf(\"---Found Structure Definition: %s\\n\",ident->name);\n}\n\nStructureDeclaration::StructureDeclaration(Identifier* type,Identifier* ident) {\n\tthis->type = type;\n\tthis->ident = ident;\n}\n\nvoid StructureDeclaration::describe() {\n\tprintf(\"---Found Structure Declaration: type='%s' identifier='%s'\\n\",\n\t\ttype->name,ident->name);\n}\n\n<|endoftext|>"} {"text":"#include \"BaseCorrespondenceFilter.hpp\"\n\nnamespace registration {\n\nBaseCorrespondenceFilter::BaseCorrespondenceFilter()\n{\n \/\/ctor\n}\n\nBaseCorrespondenceFilter::~BaseCorrespondenceFilter()\n{\n \/\/dtor\n}\n\n\nvoid BaseCorrespondenceFilter::set_output(FeatureMat * const ioCorrespondingFeatures,\n VecDynFloat * const ioCorrespondingFlags)\n{\n _ioCorrespondingFeatures = ioCorrespondingFeatures;\n _ioCorrespondingFlags = ioCorrespondingFlags;\n\n}\/\/end set_output\n\nvoid BaseCorrespondenceFilter::_affinity_to_correspondences(){\n \/*\n # GOAL\n This function computes all the corresponding features and flags,\n when the affinity for a set of features and flags is given.\n\n # PARAMETERS\n -_flagRoundingLimit:\n Flags are binary. Anything over this double is rounded up, whereas anything\n under it is rounded down. A suggested cut-off is 0.9, which means that if\n an element flagged zero contributes 10 percent or to the affinity, the\n corresponding element should be flagged a zero as well.\n\n # RESULT\n -outCorrespondingFeatures\n -outCorrespondingFlags\n *\/\n\n \/\/# Simple computation of corresponding features and flags\n *_ioCorrespondingFeatures = _affinity * (*_inTargetFeatures);\n *_ioCorrespondingFlags = _affinity * (*_inTargetFlags);\n\n \/\/# Flag correction.\n \/\/## Flags are binary. We will round them down if lower than the flag\n \/\/## rounding limit (see explanation in parameter description).\n if (_flagThreshold >= 1.0f) {std::cerr << \"corresponding flag threshold equals \" << _flagThreshold << \" but has to be between 0.0 and 1.0!\" < _flagThreshold){\n (*_ioCorrespondingFlags)[i] = 1.0;\n }\n else {\n (*_ioCorrespondingFlags)[i] = 0.0;\n }\n }\n}\n\n}\/\/namespace registration\nFloating and corresponding flags are always merged now, also for non-symmetric correspondences.#include \"BaseCorrespondenceFilter.hpp\"\n\nnamespace registration {\n\nBaseCorrespondenceFilter::BaseCorrespondenceFilter()\n{\n \/\/ctor\n}\n\nBaseCorrespondenceFilter::~BaseCorrespondenceFilter()\n{\n \/\/dtor\n}\n\n\nvoid BaseCorrespondenceFilter::set_output(FeatureMat * const ioCorrespondingFeatures,\n VecDynFloat * const ioCorrespondingFlags)\n{\n _ioCorrespondingFeatures = ioCorrespondingFeatures;\n _ioCorrespondingFlags = ioCorrespondingFlags;\n\n}\/\/end set_output\n\nvoid BaseCorrespondenceFilter::_affinity_to_correspondences(){\n \/*\n # GOAL\n This function computes all the corresponding features and flags,\n when the affinity for a set of features and flags is given.\n\n # PARAMETERS\n -_flagRoundingLimit:\n Flags are binary. Anything over this double is rounded up, whereas anything\n under it is rounded down. A suggested cut-off is 0.9, which means that if\n an element flagged zero contributes 10 percent or to the affinity, the\n corresponding element should be flagged a zero as well.\n\n # RESULT\n -outCorrespondingFeatures\n -outCorrespondingFlags\n *\/\n\n \/\/# Simple computation of corresponding features and flags\n *_ioCorrespondingFeatures = _affinity * (*_inTargetFeatures);\n *_ioCorrespondingFlags = _affinity * (*_inTargetFlags);\n\n \/\/# Flag correction.\n \/\/## Flags are binary. We will round them down if lower than the flag\n \/\/## rounding limit (see explanation in parameter description).\n if (_flagThreshold >= 1.0f) {std::cerr << \"corresponding flag threshold equals \" << _flagThreshold << \" but has to be between 0.0 and 1.0!\" < _flagThreshold){\n (*_ioCorrespondingFlags)[i] = 1.0;\n }\n else {\n (*_ioCorrespondingFlags)[i] = 0.0;\n }\n }\n\n \/\/# Merge corresponding and floating flags\n (*_ioCorrespondingFlags) = (*_ioCorrespondingFlags).cwiseProduct(*_inFloatingFlags);\n}\n\n}\/\/namespace registration\n<|endoftext|>"} {"text":"\/** @package TBTKTools\n * @file main.cpp\n * @brief Estimates the DOS using random smapling of LDOS.\n *\n * Reads model from text file and estimates the DOS using the\n * ChebyshevSolver.\n *\n * Takes filename of file to parse as first argument.\n *\n * @author Kristofer Björsnon\n *\/\n\n#include \"Model.h\"\n#include \"FileParser.h\"\n#include \"ChebyshevSolver.h\"\n#include \"CPropertyExtractor.h\"\n#include \"DOS.h\"\n#include \"FileWriter.h\"\n#include \"Util.h\"\n#include \"GPUResourceManager.h\"\n#include \"Streams.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace TBTK;\n\nconst complex i(0, 1);\nint main(int argc, char **argv){\n\tUtil::Streams::openLog();\n\tint isVerbose\t\t= false;\n\tint forceGPU\t\t= false;\n\tint forceCPU\t\t= false;\n\tint numSamples\t\t= 100;\n\tint scaleFactor\t\t= 20;\n\tint numCoefficients\t= 5000;\n\tint energyResolution\t= 10000;\n\n\twhile(true){\n\t\tstatic struct option long_options[] = {\n\t\t\t\/\/Sets flags.\n\t\t\t{\"verbose\",\t\tno_argument,\t\t&isVerbose,\t1},\n\t\t\t{\"use-gpu\",\t\tno_argument,\t\t&forceGPU,\t1},\n\t\t\t{\"use-cpu\",\t\tno_argument,\t\t&forceCPU,\t1},\n\t\t\t\/\/Does not set flags.\n\t\t\t{\"scale-factor\",\trequired_argument,\t0,\t\t's'},\n\t\t\t{\"coefficients\",\trequired_argument,\t0,\t\t'c'},\n\t\t\t{\"energy-resolution\",\trequired_argument,\t0,\t\t'r'},\n\t\t\t{\"samples\",\t\trequired_argument,\t0,\t\t'S'},\n\t\t\t{0,\t\t\t0,\t\t\t0,\t\t0}\n\t\t};\n\n\t\tint option_index = 0;\n\t\tint c = getopt_long(argc, argv, \"s:c:r:S:\", long_options, &option_index);\n\t\tif(c == -1)\n\t\t\tbreak;\n\n\t\tswitch(c){\n\t\tcase 0:\n\t\t\t\/\/If the option sets a flag, do nothing.\n\t\t\tif(long_options[option_index].flag != 0)\n\t\t\t\tbreak;\n\t\t\tcout << \"option \" << long_options[option_index].name;\n\t\t\tif(optarg)\n\t\t\t\tcout << \" with argument \" << optarg;\n\t\t\tcout << \"\\n\";\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tscaleFactor = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tnumCoefficients = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tenergyResolution = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tnumSamples = atoi(optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tcout << \"Error: Unknown argument.\\n\";\n\t\t\texit(1);\n\t\t}\n\t}\n\n\t\/\/Supress output if not verbose\n\tif(!isVerbose){\n\t\tUtil::Streams::setStdMuteOut();\n\t\tUtil::Streams::setStdMuteErr();\n\t}\n\n\t\/\/Get input file name\n\tif(argc != optind+1){\n\t\tcout << \"Input file missing.\\n\";\n\t\texit(1);\n\t}\n\tstring fileName = argv[optind];\n\n\t\/\/Use GPU if devices\n\tbool useGPU;\n\tif(GPUResourceManager::getInstance().getNumDevices() > 0)\n\t\tuseGPU = true;\n\telse\n\t\tuseGPU = false;\n\n\tif(forceGPU && forceCPU){\n\t\tUtil::Streams::err << \"Error: --use-cpu and --use-gpu cannot be simultaneously specified.\\n\";\n\t\texit(1);\n\t}\n\tif(forceGPU)\n\t\tuseGPU = true;\n\tif(forceCPU)\n\t\tuseGPU = false;\n\n\t\/\/Parse model from file and setup output target\n\tModel *model = FileParser::readModel(fileName);\n\tmodel->constructCOO();\n\n\tFileWriter::setFileName(\"TBTKResults.h5\");\n\n\t\/\/Setup ChebyshevSolver and corresponding PropertyExtractor\n\tChebyshevSolver cSolver;\n\tcSolver.setModel(model);\n\tcSolver.setScaleFactor(scaleFactor);\n\n\tCPropertyExtractor pe(\n\t\t&cSolver,\n\t\tnumCoefficients,\n\t\tenergyResolution,\n\t\tuseGPU,\n\t\tfalse,\n\t\ttrue,\n\t\t-scaleFactor,\n\t\tscaleFactor\n\t);\n\n\t\/\/Initialize randomization and dos\n\tsrand(time(NULL));\n\tdouble *dosData = new double[energyResolution];\n\tfor(int n = 0; n < energyResolution; n++)\n\t\tdosData[n] = 0.;\n\n\t\/\/Main loop: Repeatedly calculate LDOS for random sites\n\tfor(int n = 0; n < numSamples; n++){\n\t\t\/\/Print progress\n\t\tcout << \".\" << flush;\n\t\tif(n%10 == 9)\n\t\t\tcout << \" \";\n\t\tif(n%50 == 49)\n\t\t\tcout << \"\\n\";\n\n\t\t\/\/Get new random index\n\t\tint b = rand()%model->getBasisSize();\n\t\tIndex index = model->getAmplitudeSet()->tree.getPhysicalIndex(b);\n\n\t\t\/\/Calculate LDOS\n\t\tProperty::LDOS *ldos = pe.calculateLDOS(\n\t\t\tindex,\n\t\t\tindex.getUnitRange()\n\t\t);\n\n\t\t\/\/Add calculated LDOS to total DOS\n\t\tconst double *data = ldos->getData();\n\t\tfor(int e = 0; e < energyResolution; e++)\n\t\t\tdosData[e] += data[e]\/(double)numSamples;\n\n\t\t\/\/Free memory\n\t\tdelete ldos;\n\n\t}\n\tcout << \"\\n\";\n\n\t\/\/Write DOS to file\n\tProperty::DOS dos(-scaleFactor, scaleFactor, energyResolution, dosData);\n\tFileWriter::writeDOS(&dos);\n\n\tdelete [] dosData;\n\n\tUtil::Streams::closeLog();\n\treturn 0;\n}\nUpdated EstimateDOS to use TBTKAssert and TBTKExit\/** @package TBTKTools\n * @file main.cpp\n * @brief Estimates the DOS using random smapling of LDOS.\n *\n * Reads model from text file and estimates the DOS using the\n * ChebyshevSolver.\n *\n * Takes filename of file to parse as first argument.\n *\n * @author Kristofer Björsnon\n *\/\n\n#include \"Model.h\"\n#include \"FileParser.h\"\n#include \"ChebyshevSolver.h\"\n#include \"CPropertyExtractor.h\"\n#include \"DOS.h\"\n#include \"FileWriter.h\"\n#include \"Util.h\"\n#include \"GPUResourceManager.h\"\n#include \"Streams.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace TBTK;\n\nconst complex i(0, 1);\nint main(int argc, char **argv){\n\tUtil::Streams::openLog();\n\tint isVerbose\t\t= false;\n\tint forceGPU\t\t= false;\n\tint forceCPU\t\t= false;\n\tint numSamples\t\t= 100;\n\tint scaleFactor\t\t= 20;\n\tint numCoefficients\t= 5000;\n\tint energyResolution\t= 10000;\n\n\twhile(true){\n\t\tstatic struct option long_options[] = {\n\t\t\t\/\/Sets flags.\n\t\t\t{\"verbose\",\t\tno_argument,\t\t&isVerbose,\t1},\n\t\t\t{\"use-gpu\",\t\tno_argument,\t\t&forceGPU,\t1},\n\t\t\t{\"use-cpu\",\t\tno_argument,\t\t&forceCPU,\t1},\n\t\t\t\/\/Does not set flags.\n\t\t\t{\"scale-factor\",\trequired_argument,\t0,\t\t's'},\n\t\t\t{\"coefficients\",\trequired_argument,\t0,\t\t'c'},\n\t\t\t{\"energy-resolution\",\trequired_argument,\t0,\t\t'r'},\n\t\t\t{\"samples\",\t\trequired_argument,\t0,\t\t'S'},\n\t\t\t{0,\t\t\t0,\t\t\t0,\t\t0}\n\t\t};\n\n\t\tint option_index = 0;\n\t\tint c = getopt_long(argc, argv, \"s:c:r:S:\", long_options, &option_index);\n\t\tif(c == -1)\n\t\t\tbreak;\n\n\t\tswitch(c){\n\t\tcase 0:\n\t\t\t\/\/If the option sets a flag, do nothing.\n\t\t\tif(long_options[option_index].flag != 0)\n\t\t\t\tbreak;\n\t\t\tcout << \"option \" << long_options[option_index].name;\n\t\t\tif(optarg)\n\t\t\t\tcout << \" with argument \" << optarg;\n\t\t\tcout << \"\\n\";\n\t\t\tbreak;\n\t\tcase 's':\n\t\t\tscaleFactor = atof(optarg);\n\t\t\tbreak;\n\t\tcase 'c':\n\t\t\tnumCoefficients = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'r':\n\t\t\tenergyResolution = atoi(optarg);\n\t\t\tbreak;\n\t\tcase 'S':\n\t\t\tnumSamples = atoi(optarg);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tTBTKExit(\n\t\t\t\t\"EstimateDOS\",\n\t\t\t\t\"Unknown argument.\",\n\t\t\t\t\"\"\n\t\t\t);\n\t\t}\n\t}\n\n\t\/\/Supress output if not verbose\n\tif(!isVerbose)\n\t\tUtil::Streams::setStdMuteOut();\n\n\t\/\/Get input file name\n\tTBTKAssert(\n\t\targc == optind+1,\n\t\t\"EstimateDOS\",\n\t\t\"Input file missing.\",\n\t\t\"\"\n\t);\n\tstring fileName = argv[optind];\n\n\t\/\/Use GPU if devices\n\tbool useGPU;\n\tif(GPUResourceManager::getInstance().getNumDevices() > 0)\n\t\tuseGPU = true;\n\telse\n\t\tuseGPU = false;\n\n\tTBTKAssert(\n\t\t!(forceGPU && forceCPU),\n\t\t\"EstimateDOS\",\n\t\t\"--use-cpu and --use-gpu cannot be simultaneously specified.\",\n\t\t\"\"\n\t);\n\tif(forceGPU)\n\t\tuseGPU = true;\n\tif(forceCPU)\n\t\tuseGPU = false;\n\n\t\/\/Parse model from file and setup output target\n\tModel *model = FileParser::readModel(fileName);\n\tmodel->constructCOO();\n\n\tFileWriter::setFileName(\"TBTKResults.h5\");\n\n\t\/\/Setup ChebyshevSolver and corresponding PropertyExtractor\n\tChebyshevSolver cSolver;\n\tcSolver.setModel(model);\n\tcSolver.setScaleFactor(scaleFactor);\n\n\tCPropertyExtractor pe(\n\t\t&cSolver,\n\t\tnumCoefficients,\n\t\tenergyResolution,\n\t\tuseGPU,\n\t\tfalse,\n\t\ttrue,\n\t\t-scaleFactor,\n\t\tscaleFactor\n\t);\n\n\t\/\/Initialize randomization and dos\n\tsrand(time(NULL));\n\tdouble *dosData = new double[energyResolution];\n\tfor(int n = 0; n < energyResolution; n++)\n\t\tdosData[n] = 0.;\n\n\t\/\/Main loop: Repeatedly calculate LDOS for random sites\n\tfor(int n = 0; n < numSamples; n++){\n\t\t\/\/Print progress\n\t\tcout << \".\" << flush;\n\t\tif(n%10 == 9)\n\t\t\tcout << \" \";\n\t\tif(n%50 == 49)\n\t\t\tcout << \"\\n\";\n\n\t\t\/\/Get new random index\n\t\tint b = rand()%model->getBasisSize();\n\t\tIndex index = model->getAmplitudeSet()->tree.getPhysicalIndex(b);\n\n\t\t\/\/Calculate LDOS\n\t\tProperty::LDOS *ldos = pe.calculateLDOS(\n\t\t\tindex,\n\t\t\tindex.getUnitRange()\n\t\t);\n\n\t\t\/\/Add calculated LDOS to total DOS\n\t\tconst double *data = ldos->getData();\n\t\tfor(int e = 0; e < energyResolution; e++)\n\t\t\tdosData[e] += data[e]\/(double)numSamples;\n\n\t\t\/\/Free memory\n\t\tdelete ldos;\n\n\t}\n\tcout << \"\\n\";\n\n\t\/\/Write DOS to file\n\tProperty::DOS dos(-scaleFactor, scaleFactor, energyResolution, dosData);\n\tFileWriter::writeDOS(&dos);\n\n\tdelete [] dosData;\n\n\tUtil::Streams::closeLog();\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_HXX_INTERNAL\n #error \"Please #include instead of this file\"\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::type_void_adapter\n\nnamespace abc {\n\n\/*! DOC:3395 Move constructors and exceptions\n\nIn this section, “move constructor” will strictly refer to class::class(class &&).\n\nAll classes must provide move constructors and assignment operators if the copy constructor would\nresult in execution of exception-prone code (e.g. resource allocation).\n\nBecause move constructors are employed widely in container classes that need to provide strong\nexception guarantee (fully transacted operation) even in case of moves, move constructors must not\nthrow exceptions. This requirement is relaxed for moves that involve two different classes, since\nthese will not be used by container classes.\n*\/\n\n\/\/! Encapsulates raw constructors, destructors and assignment operators for a type.\nstruct type_void_adapter {\npublic:\n \/*! Prototype of a function that copies items from one array to another.\n\n @param pDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param pSrcBegin\n Pointer to the first item to copy.\n @param pSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n typedef void (* copy_fn)(void * pDstBegin, void const * pSrcBegin, void const * pSrcEnd);\n\n \/*! Prototype of a function that destructs a range of items in an array.\n\n @param pBegin\n Pointer to the first item to destruct.\n @param pEnd\n Pointer to beyond the last item to destruct.\n *\/\n typedef void (* destr_fn)(void const * pBegin, void const * pEnd);\n\n \/*! Prototype of a function that compares two values for equality.\n\n @param p1\n Pointer to the first item.\n @param p2\n Pointer to the second item.\n @return\n true if the items are equal, or false otherwise.\n *\/\n typedef bool (* equal_fn)(void const * p1, void const * p2);\n\n \/*! Prototype of a function that moves items from one array to another.\n\n @param pDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param pSrcBegin\n Pointer to the first item to move.\n @param pSrcEnd\n Pointer to beyond the last item to move.\n *\/\n typedef void (* move_fn)(void * pDstBegin, void * pSrcBegin, void * pSrcEnd);\n\npublic:\n \/\/! Size of a variable of this type, in bytes.\n std::size_t cb;\n \/\/! Function to copy items from one array to another.\n copy_fn copy_constr;\n \/\/! Function to destruct items in an array.\n destr_fn destruct;\n \/\/! Function to compare two items for equality.\n equal_fn equal;\n \/\/! Function to move items from one array to another.\n move_fn move_constr;\n\npublic:\n \/\/! Constructor.\n type_void_adapter() :\n cb(0),\n copy_constr(nullptr),\n destruct(nullptr),\n equal(nullptr),\n move_constr(nullptr) {\n }\n\n \/\/! Initializes this->copy_constr.\n template \n void set_copy_fn() {\n copy_constr = reinterpret_cast(_typed_copy_constr::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!copy_constr) {\n _typed_copy_constr::type>(nullptr, nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->destruct.\n template \n void set_destr_fn() {\n destruct = reinterpret_cast(_typed_destruct::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!destruct) {\n _typed_destruct::type>(nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->equal.\n template \n void set_equal_fn() {\n equal = reinterpret_cast(_typed_equal::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!equal) {\n _typed_equal::type>(nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->move_constr.\n template \n void set_move_fn() {\n move_constr = reinterpret_cast(_typed_move_constr::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!move_constr) {\n _typed_move_constr::type>(nullptr, nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->cb.\n template \n void set_size() {\n cb = sizeof(T);\n }\n\nprivate:\n \/*! Copies a range of items from one array to another, overwriting any existing contents in the\n destination.\n\n @param ptDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param ptSrcBegin\n Pointer to the first item to copy.\n @param ptSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n#if ABC_HOST_MSC\n \/* MSC applies SFINAE too late, and when asked to get the address of the *one and only* valid\n version of _typed_copy_constr() (see non-MSC code in the #else branch), it will raise an error\n saying it doesn’t know which one to choose. *\/\n template \n static void _typed_copy_constr(T * ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd) {\n if (std::has_trivial_copy_constructor::value) {\n \/\/ No constructor, fastest copy possible.\n memory::copy(ptDstBegin, ptSrcBegin, static_cast(ptSrcEnd - ptSrcBegin));\n } else {\n \/\/ Assume that since it’s not trivial, it can throw exceptions, so perform a transactional\n \/\/ copy.\n T * ptDst = ptDstBegin;\n try {\n for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(*ptSrc);\n }\n } catch (...) {\n \/\/ Undo (destruct) all the copies instantiated.\n while (--ptDst >= ptDstBegin) {\n ptDst->~T();\n }\n throw;\n }\n }\n }\n#else \/\/if ABC_HOST_MSC\n \/\/ Only enabled if the copy constructor is trivial.\n template \n static void _typed_copy_constr(\n typename std::enable_if::value, T *>::type ptDstBegin,\n T const * ptSrcBegin, T const * ptSrcEnd\n ) {\n \/\/ No constructor, fastest copy possible.\n memory::copy(ptDstBegin, ptSrcBegin, static_cast(ptSrcEnd - ptSrcBegin));\n }\n \/\/ Only enabled if the copy constructor is not trivial.\n template \n static void _typed_copy_constr(\n typename std::enable_if::value, T *>::type ptDstBegin,\n T const * ptSrcBegin, T const * ptSrcEnd\n ) {\n \/\/ Assume that since it’s not trivial, it can throw exceptions, so perform a transactional\n \/\/ copy.\n T * ptDst = ptDstBegin;\n try {\n for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(*ptSrc);\n }\n } catch (...) {\n \/\/ Undo (destruct) all the copies instantiated.\n while (--ptDst >= ptDstBegin) {\n ptDst->~T();\n }\n throw;\n }\n }\n#endif \/\/if ABC_HOST_MSC … else\n\n \/*! Destructs a range of items in an array.\n\n @param ptBegin\n Pointer to the first item to destruct.\n @param ptEnd\n Pointer to beyond the last item to destruct.\n *\/\n template \n static void _typed_destruct(T const * ptBegin, T const * ptEnd) {\n#ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS\n if (!std::is_trivially_destructible::value) {\n#else\n if (!std::has_trivial_destructor::value) {\n#endif\n \/\/ The destructor is not a no-op.\n for (T const * pt = ptBegin; pt < ptEnd; ++pt) {\n pt->~T();\n }\n }\n }\n\n \/*! Compares two values for equality.\n\n @param pt1\n Pointer to the first item.\n @param pt2\n Pointer to the second item.\n @return\n true if the items are equal, or false otherwise.\n *\/\n template \n static bool _typed_equal(T const * pt1, T const * pt2) {\n return *pt1 == *pt2;\n }\n\n \/*! Moves a range of items from one array to another, overwriting any existing contents in the\n destination.\n\n @param ptDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param ptSrcBegin\n Pointer to the first item to copy.\n @param ptSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n template \n static void _typed_move_constr(T * ptDstBegin, T * ptSrcBegin, T * ptSrcEnd) {\n for (T * ptSrc = ptSrcBegin, * ptDst = ptDstBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(std::move(*ptSrc));\n }\n }\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nSupport C++11 type traits in more places\/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-\n\nCopyright 2010, 2011, 2012, 2013, 2014\nRaffaello D. Di Napoli\n\nThis file is part of Abaclade.\n\nAbaclade is free software: you can redistribute it and\/or modify it under the terms of the GNU\nGeneral Public License as published by the Free Software Foundation, either version 3 of the\nLicense, or (at your option) any later version.\n\nAbaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General\nPublic License for more details.\n\nYou should have received a copy of the GNU General Public License along with Abaclade. If not, see\n.\n--------------------------------------------------------------------------------------------------*\/\n\n#ifndef _ABACLADE_HXX_INTERNAL\n #error \"Please #include instead of this file\"\n#endif\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ abc::type_void_adapter\n\nnamespace abc {\n\n\/*! DOC:3395 Move constructors and exceptions\n\nIn this section, “move constructor” will strictly refer to class::class(class &&).\n\nAll classes must provide move constructors and assignment operators if the copy constructor would\nresult in execution of exception-prone code (e.g. resource allocation).\n\nBecause move constructors are employed widely in container classes that need to provide strong\nexception guarantee (fully transacted operation) even in case of moves, move constructors must not\nthrow exceptions. This requirement is relaxed for moves that involve two different classes, since\nthese will not be used by container classes.\n*\/\n\n\/\/! Encapsulates raw constructors, destructors and assignment operators for a type.\nstruct type_void_adapter {\npublic:\n \/*! Prototype of a function that copies items from one array to another.\n\n @param pDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param pSrcBegin\n Pointer to the first item to copy.\n @param pSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n typedef void (* copy_fn)(void * pDstBegin, void const * pSrcBegin, void const * pSrcEnd);\n\n \/*! Prototype of a function that destructs a range of items in an array.\n\n @param pBegin\n Pointer to the first item to destruct.\n @param pEnd\n Pointer to beyond the last item to destruct.\n *\/\n typedef void (* destr_fn)(void const * pBegin, void const * pEnd);\n\n \/*! Prototype of a function that compares two values for equality.\n\n @param p1\n Pointer to the first item.\n @param p2\n Pointer to the second item.\n @return\n true if the items are equal, or false otherwise.\n *\/\n typedef bool (* equal_fn)(void const * p1, void const * p2);\n\n \/*! Prototype of a function that moves items from one array to another.\n\n @param pDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param pSrcBegin\n Pointer to the first item to move.\n @param pSrcEnd\n Pointer to beyond the last item to move.\n *\/\n typedef void (* move_fn)(void * pDstBegin, void * pSrcBegin, void * pSrcEnd);\n\npublic:\n \/\/! Size of a variable of this type, in bytes.\n std::size_t cb;\n \/\/! Function to copy items from one array to another.\n copy_fn copy_constr;\n \/\/! Function to destruct items in an array.\n destr_fn destruct;\n \/\/! Function to compare two items for equality.\n equal_fn equal;\n \/\/! Function to move items from one array to another.\n move_fn move_constr;\n\npublic:\n \/\/! Constructor.\n type_void_adapter() :\n cb(0),\n copy_constr(nullptr),\n destruct(nullptr),\n equal(nullptr),\n move_constr(nullptr) {\n }\n\n \/\/! Initializes this->copy_constr.\n template \n void set_copy_fn() {\n copy_constr = reinterpret_cast(_typed_copy_constr::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!copy_constr) {\n _typed_copy_constr::type>(nullptr, nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->destruct.\n template \n void set_destr_fn() {\n destruct = reinterpret_cast(_typed_destruct::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!destruct) {\n _typed_destruct::type>(nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->equal.\n template \n void set_equal_fn() {\n equal = reinterpret_cast(_typed_equal::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!equal) {\n _typed_equal::type>(nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->move_constr.\n template \n void set_move_fn() {\n move_constr = reinterpret_cast(_typed_move_constr::type>);\n#if ABC_HOST_GCC && ABC_HOST_GCC < 40700\n \/\/ Force instantiating the template, even if (obviously) never executed.\n if (!move_constr) {\n _typed_move_constr::type>(nullptr, nullptr, nullptr);\n }\n#endif\n }\n\n \/\/! Initializes this->cb.\n template \n void set_size() {\n cb = sizeof(T);\n }\n\nprivate:\n \/*! Copies a range of items from one array to another, overwriting any existing contents in the\n destination.\n\n @param ptDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param ptSrcBegin\n Pointer to the first item to copy.\n @param ptSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n#if ABC_HOST_MSC\n \/* MSC applies SFINAE too late, and when asked to get the address of the *one and only* valid\n version of _typed_copy_constr() (see non-MSC code in the #else branch), it will raise an error\n saying it doesn’t know which one to choose. *\/\n template \n static void _typed_copy_constr(T * ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd) {\n if (std::has_trivial_copy_constructor::value) {\n \/\/ No constructor, fastest copy possible.\n memory::copy(ptDstBegin, ptSrcBegin, static_cast(ptSrcEnd - ptSrcBegin));\n } else {\n \/\/ Assume that since it’s not trivial, it can throw exceptions, so perform a transactional\n \/\/ copy.\n T * ptDst = ptDstBegin;\n try {\n for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(*ptSrc);\n }\n } catch (...) {\n \/\/ Undo (destruct) all the copies instantiated.\n while (--ptDst >= ptDstBegin) {\n ptDst->~T();\n }\n throw;\n }\n }\n }\n#else \/\/if ABC_HOST_MSC\n \/\/ Only enabled if the copy constructor is trivial.\n template \n static void _typed_copy_constr(\n typename std::enable_if<\n#ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS\n std::is_trivially_copy_constructible::value,\n#else\n std::has_trivial_copy_constructor::value,\n#endif\n T *>::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd\n ) {\n \/\/ No constructor, fastest copy possible.\n memory::copy(ptDstBegin, ptSrcBegin, static_cast(ptSrcEnd - ptSrcBegin));\n }\n \/\/ Only enabled if the copy constructor is not trivial.\n template \n static void _typed_copy_constr(\n typename std::enable_if<\n#ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS\n !std::is_trivially_copy_constructible::value,\n#else\n !std::has_trivial_copy_constructor::value,\n#endif\n T * >::type ptDstBegin, T const * ptSrcBegin, T const * ptSrcEnd\n ) {\n \/\/ Assume that since it’s not trivial, it can throw exceptions, so perform a transactional\n \/\/ copy.\n T * ptDst = ptDstBegin;\n try {\n for (T const * ptSrc = ptSrcBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(*ptSrc);\n }\n } catch (...) {\n \/\/ Undo (destruct) all the copies instantiated.\n while (--ptDst >= ptDstBegin) {\n ptDst->~T();\n }\n throw;\n }\n }\n#endif \/\/if ABC_HOST_MSC … else\n\n \/*! Destructs a range of items in an array.\n\n @param ptBegin\n Pointer to the first item to destruct.\n @param ptEnd\n Pointer to beyond the last item to destruct.\n *\/\n template \n static void _typed_destruct(T const * ptBegin, T const * ptEnd) {\n#ifdef ABC_CXX_STL_CXX11_TYPE_TRAITS\n if (!std::is_trivially_destructible::value) {\n#else\n if (!std::has_trivial_destructor::value) {\n#endif\n \/\/ The destructor is not a no-op.\n for (T const * pt = ptBegin; pt < ptEnd; ++pt) {\n pt->~T();\n }\n }\n }\n\n \/*! Compares two values for equality.\n\n @param pt1\n Pointer to the first item.\n @param pt2\n Pointer to the second item.\n @return\n true if the items are equal, or false otherwise.\n *\/\n template \n static bool _typed_equal(T const * pt1, T const * pt2) {\n return *pt1 == *pt2;\n }\n\n \/*! Moves a range of items from one array to another, overwriting any existing contents in the\n destination.\n\n @param ptDstBegin\n Pointer to the start of the destination array. The items are supposed to be uninitialized.\n @param ptSrcBegin\n Pointer to the first item to copy.\n @param ptSrcEnd\n Pointer to beyond the last item to copy.\n *\/\n template \n static void _typed_move_constr(T * ptDstBegin, T * ptSrcBegin, T * ptSrcEnd) {\n for (T * ptSrc = ptSrcBegin, * ptDst = ptDstBegin; ptSrc < ptSrcEnd; ++ptSrc, ++ptDst) {\n ::new(ptDst) T(std::move(*ptSrc));\n }\n }\n};\n\n} \/\/namespace abc\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\n#include \"proctor\/detector.h\"\n#include \"proctor\/proctor.h\"\n#include \"proctor\/proposer.h\"\n#include \"proctor\/registration_proposer.h\"\n#include \"proctor\/detector_visualizer.h\"\n\nnamespace pcl {\n namespace proctor {\n \/** create the viewports to be used by top candidates *\/\n class create_viewports {\n public:\n create_viewports(PointCloud::ConstPtr sentinel) : sentinel(sentinel) {}\n void operator()(visualization::PCLVisualizer &v) {\n for (int ci = 0; ci < Detector::num_registration; ci++) {\n int vp;\n v.createViewPort(double(ci) \/ Detector::num_registration, 0, double(ci + 1) \/ Detector::num_registration, 1, vp);\n {\n stringstream ss;\n ss << \"candidate_\" << ci;\n v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);\n }\n {\n stringstream ss;\n ss << \"aligned_\" << ci;\n v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);\n }\n }\n }\n private:\n PointCloud::ConstPtr sentinel;\n };\n\n \/** show a candidate model as the specified candidate *\/\n class show_candidate {\n public:\n show_candidate(int ci, PointCloud::ConstPtr candidate) : ci(ci), candidate(candidate) {}\n void operator()(visualization::PCLVisualizer &v) {\n {\n stringstream ss;\n ss << \"candidate_\" << ci;\n v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom(candidate, 0xc0, 0x00, 0x40), ss.str());\n }\n {\n stringstream ss;\n ss << \"aligned_\" << ci;\n v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom(candidate, 0xc0, 0x00, 0x40), ss.str());\n }\n }\n private:\n int ci;\n PointCloud::ConstPtr candidate;\n };\n\n \/** show an aligned point cloud in the specified viewport *\/\n class show_aligned {\n public:\n show_aligned(int ci, PointCloud::ConstPtr aligned) : ci(ci), aligned(aligned) {}\n void operator()(visualization::PCLVisualizer &v) {\n stringstream ss;\n ss << \"aligned_\" << ci;\n v.updatePointCloud(aligned, visualization::PointCloudColorHandlerCustom(aligned, 0xff, 0xff, 0xff), ss.str());\n }\n private:\n int ci;\n PointCloud::ConstPtr aligned;\n };\n\n class visualization_callback {\n public:\n visualization_callback(int ci, visualization::CloudViewer *vis) : ci(ci), vis(vis) {}\n void operator()(const PointCloud &cloud_src,\n const vector &indices_src,\n const PointCloud &cloud_tgt,\n const vector &indices_tgt) {\n \/\/ make a copy of the cloud. expensive.\n PointCloud::ConstPtr aligned (new PointCloud(cloud_src));\n vis->runOnVisualizationThreadOnce(show_aligned(ci, aligned));\n }\n private:\n int ci;\n visualization::CloudViewer *vis;\n };\n\n \/** Detector *\/\n const double Detector::keypoint_separation = 0.1;\n const int Detector::max_votes = 100;\n const int Detector::num_registration = 4;\n\n \/* Trains a single model *\/\n void Detector::train(Scene &scene) {\n srand(0);\n if (detector_vis_) {\n detector_vis_->addCloud(scene.id, scene.cloud);\n }\n\n IndicesPtr keypoints = computeKeypoints(scene.cloud);\n PointCloud::Ptr features = obtainFeatures(scene, keypoints, false);\n\n Entry e;\n e.cloud = scene.cloud;\n e.indices = keypoints;\n e.features = features;\n e.tree = KdTree::Ptr(new KdTreeFLANN());\n e.tree->setInputCloud(e.features);\n\n (*database_)[scene.id] = e;\n }\n\n std::string Detector::query(Scene &scene, float *classifier, double *registration) {\n cout << \"detector testing \" << scene.id << endl;\n\n Entry e;\n e.cloud = scene.cloud;\n timer.start();\n e.indices = computeKeypoints(e.cloud);\n timer.stop(KEYPOINTS_TESTING);\n timer.start();\n e.features = obtainFeatures(scene, e.indices, true);\n timer.stop(COMPUTE_FEATURES_TESTING);\n\n memset(classifier, 0, Config::num_models * sizeof(*classifier));\n clock_t totalTime = 0;\n float time = 0;\n\n StopWatch s;\n\n std::vector all_ids;\n for (std::map::iterator db_it = database_->begin(); db_it != database_->end(); db_it++)\n {\n all_ids.push_back((*db_it).first);\n }\n\n std::vector proposed;\n proposer_->setDatabase(database_);\n proposer_->getProposed(num_registration, e, all_ids, proposed);\n\n RegistrationProposer reg_proposer;\n std::vector picked;\n reg_proposer.setDatabase(database_);\n reg_proposer.getProposed(1, e, proposed, picked);\n\n return picked[0];\n }\n\n void Detector::enableVisualization(DetectorVisualizer *vis) {\n detector_vis_ = vis;\n }\n\n void Detector::printTimer() {\n printf(\n \"select training keypoints: %10.3f sec\\n\"\n \"obtain training features: %10.3f sec\\n\"\n \"build feature tree: %10.3f sec\\n\"\n \"select testing keypoints: %10.3f sec\\n\"\n \"compute testing features: %10.3f sec\\n\"\n \"voting classifier: %10.3f sec\\n\"\n \"initial alignment: %10.3f sec\\n\"\n \"ICP: %10.3f sec\\n\",\n timer[KEYPOINTS_TRAINING],\n timer[OBTAIN_FEATURES_TRAINING],\n timer[BUILD_TREE],\n timer[KEYPOINTS_TESTING],\n timer[COMPUTE_FEATURES_TESTING],\n timer[VOTING_CLASSIFIER],\n timer[IA_RANSAC],\n timer[ICP]\n );\n }\n\n IndicesPtr Detector::computeKeypoints(PointCloud::Ptr cloud) {\n IndicesPtr indices (new vector());\n PointCloud leaves;\n UniformSampling us;\n us.setRadiusSearch(keypoint_separation);\n us.setInputCloud(cloud);\n us.compute(leaves);\n indices->assign(leaves.points.begin(), leaves.points.end()); \/\/ can't use operator=, probably because of different allocators\n\n return indices;\n }\n\n PointCloud::Ptr Detector::computeFeatures(PointCloud::Ptr cloud, IndicesPtr indices) {\n cout << \"computing features on \" << indices->size() << \" points\" << endl;\n PointCloud::Ptr features (new PointCloud());\n FPFHEstimation fpfh;\n fpfh.setRadiusSearch(0.1);\n fpfh.setInputCloud(cloud);\n fpfh.setIndices(indices);\n search::KdTree::Ptr kdt (new search::KdTree());\n fpfh.setSearchMethod(kdt);\n fpfh.setInputNormals(cloud);\n fpfh.compute(*features);\n if (features->points.size() != indices->size())\n cout << \"got \" << features->points.size() << \" features from \" << indices->size() << \" points\" << endl;\n return features;\n }\n\n \/\/ TODO Enum for is_test_phase\n PointCloud::Ptr Detector::obtainFeatures(Scene &scene, IndicesPtr indices, bool is_test_phase, bool cache) {\n if (cache == false)\n {\n PointCloud::Ptr features = computeFeatures(scene.cloud, indices);\n return features;\n }\n else\n {\n std::string name_str = std::string(\"feature_\") + scene.id;\n\n if (is_test_phase) {\n name_str += \"_test\";\n }\n else {\n name_str += \"_train\";\n }\n\n name_str += \".pcd\";\n\n const char *name = name_str.c_str();\n\n if (ifstream(name)) {\n PointCloud::Ptr features (new PointCloud());\n io::loadPCDFile(name, *features);\n \/\/if (features->points.size() != indices->size())\n \/\/cout << \"got \" << features->points.size() << \" features from \" << indices->size() << \" points\" << endl;\n return features;\n } else {\n PointCloud::Ptr features = computeFeatures(scene.cloud, indices);\n io::savePCDFileBinary(name, *features);\n return features;\n }\n }\n }\n }\n}\nRemove old visualization code.#include \n\n#include \n#include \n#include \n#include \n\n#include \"proctor\/detector.h\"\n#include \"proctor\/proctor.h\"\n#include \"proctor\/proposer.h\"\n#include \"proctor\/registration_proposer.h\"\n#include \"proctor\/detector_visualizer.h\"\n\nnamespace pcl {\n namespace proctor {\n \/** Detector *\/\n const double Detector::keypoint_separation = 0.1;\n const int Detector::max_votes = 100;\n const int Detector::num_registration = 4;\n\n \/* Trains a single model *\/\n void Detector::train(Scene &scene) {\n srand(0);\n if (detector_vis_) {\n detector_vis_->addCloud(scene.id, scene.cloud);\n }\n\n IndicesPtr keypoints = computeKeypoints(scene.cloud);\n PointCloud::Ptr features = obtainFeatures(scene, keypoints, false);\n\n Entry e;\n e.cloud = scene.cloud;\n e.indices = keypoints;\n e.features = features;\n e.tree = KdTree::Ptr(new KdTreeFLANN());\n e.tree->setInputCloud(e.features);\n\n (*database_)[scene.id] = e;\n }\n\n std::string Detector::query(Scene &scene, float *classifier, double *registration) {\n cout << \"detector testing \" << scene.id << endl;\n\n Entry e;\n e.cloud = scene.cloud;\n timer.start();\n e.indices = computeKeypoints(e.cloud);\n timer.stop(KEYPOINTS_TESTING);\n timer.start();\n e.features = obtainFeatures(scene, e.indices, true);\n timer.stop(COMPUTE_FEATURES_TESTING);\n\n memset(classifier, 0, Config::num_models * sizeof(*classifier));\n clock_t totalTime = 0;\n float time = 0;\n\n StopWatch s;\n\n std::vector all_ids;\n for (std::map::iterator db_it = database_->begin(); db_it != database_->end(); db_it++)\n {\n all_ids.push_back((*db_it).first);\n }\n\n std::vector proposed;\n proposer_->setDatabase(database_);\n proposer_->getProposed(num_registration, e, all_ids, proposed);\n\n RegistrationProposer reg_proposer;\n std::vector picked;\n reg_proposer.setDatabase(database_);\n reg_proposer.getProposed(1, e, proposed, picked);\n\n return picked[0];\n }\n\n void Detector::enableVisualization(DetectorVisualizer *vis) {\n detector_vis_ = vis;\n }\n\n void Detector::printTimer() {\n printf(\n \"select training keypoints: %10.3f sec\\n\"\n \"obtain training features: %10.3f sec\\n\"\n \"build feature tree: %10.3f sec\\n\"\n \"select testing keypoints: %10.3f sec\\n\"\n \"compute testing features: %10.3f sec\\n\"\n \"voting classifier: %10.3f sec\\n\"\n \"initial alignment: %10.3f sec\\n\"\n \"ICP: %10.3f sec\\n\",\n timer[KEYPOINTS_TRAINING],\n timer[OBTAIN_FEATURES_TRAINING],\n timer[BUILD_TREE],\n timer[KEYPOINTS_TESTING],\n timer[COMPUTE_FEATURES_TESTING],\n timer[VOTING_CLASSIFIER],\n timer[IA_RANSAC],\n timer[ICP]\n );\n }\n\n IndicesPtr Detector::computeKeypoints(PointCloud::Ptr cloud) {\n IndicesPtr indices (new vector());\n PointCloud leaves;\n UniformSampling us;\n us.setRadiusSearch(keypoint_separation);\n us.setInputCloud(cloud);\n us.compute(leaves);\n indices->assign(leaves.points.begin(), leaves.points.end()); \/\/ can't use operator=, probably because of different allocators\n\n return indices;\n }\n\n PointCloud::Ptr Detector::computeFeatures(PointCloud::Ptr cloud, IndicesPtr indices) {\n cout << \"computing features on \" << indices->size() << \" points\" << endl;\n PointCloud::Ptr features (new PointCloud());\n FPFHEstimation fpfh;\n fpfh.setRadiusSearch(0.1);\n fpfh.setInputCloud(cloud);\n fpfh.setIndices(indices);\n search::KdTree::Ptr kdt (new search::KdTree());\n fpfh.setSearchMethod(kdt);\n fpfh.setInputNormals(cloud);\n fpfh.compute(*features);\n if (features->points.size() != indices->size())\n cout << \"got \" << features->points.size() << \" features from \" << indices->size() << \" points\" << endl;\n return features;\n }\n\n \/\/ TODO Enum for is_test_phase\n PointCloud::Ptr Detector::obtainFeatures(Scene &scene, IndicesPtr indices, bool is_test_phase, bool cache) {\n if (cache == false)\n {\n PointCloud::Ptr features = computeFeatures(scene.cloud, indices);\n return features;\n }\n else\n {\n std::string name_str = std::string(\"feature_\") + scene.id;\n\n if (is_test_phase) {\n name_str += \"_test\";\n }\n else {\n name_str += \"_train\";\n }\n\n name_str += \".pcd\";\n\n const char *name = name_str.c_str();\n\n if (ifstream(name)) {\n PointCloud::Ptr features (new PointCloud());\n io::loadPCDFile(name, *features);\n \/\/if (features->points.size() != indices->size())\n \/\/cout << \"got \" << features->points.size() << \" features from \" << indices->size() << \" points\" << endl;\n return features;\n } else {\n PointCloud::Ptr features = computeFeatures(scene.cloud, indices);\n io::savePCDFileBinary(name, *features);\n return features;\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\nnamespace cilantro {\n template \n class NormalEstimation {\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n NormalEstimation(const ConstVectorSetMatrixMap &points, size_t max_leaf_size = 10)\n : points_(points),\n kd_tree_ptr_(new KDTree(points, max_leaf_size)),\n kd_tree_owned_(true),\n view_point_(Vector::Zero())\n {}\n\n NormalEstimation(const KDTree &kd_tree)\n : points_(kd_tree.getPointsMatrixMap()),\n kd_tree_ptr_(&kd_tree),\n kd_tree_owned_(false),\n view_point_(Vector::Zero())\n {}\n\n ~NormalEstimation() {\n if (kd_tree_owned_) delete kd_tree_ptr_;\n }\n\n inline const Vector& getViewPoint() const { return view_point_; }\n\n inline NormalEstimation& setViewPoint(const Eigen::Ref> &vp) { view_point_ = vp; return *this; }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureKNN(VectorSet &normals, VectorSet &curvatures, size_t k) const {\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return *this;\n }\n\n inline VectorSet estimateNormalsKNN(size_t k) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return normals;\n }\n\n inline VectorSet estimateCurvatureKNN(size_t k) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureRadius(VectorSet &normals, VectorSet &curvatures, ScalarT radius) const {\n compute_radius_(normals, curvatures, radius);\n return *this;\n }\n\n inline VectorSet estimateNormalsRadius(ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::RADIUS, 0, radius*radius));\n return normals;\n }\n\n inline VectorSet estimateCurvatureRadius(ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::RADIUS, 0, radius*radius));\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureKNNInRadius(VectorSet &normals, VectorSet &curvatures, size_t k, ScalarT radius) const {\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius*radius));\n return *this;\n }\n\n inline VectorSet estimateNormalsKNNInRadius(size_t k, ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius*radius));\n return normals;\n }\n\n inline VectorSet estimateCurvatureKNNInRadius(size_t k, ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius*radius));\n return curvatures;\n }\n\n template \n inline const NormalEstimation& estimateNormalsAndCurvature(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n compute_(normals, curvatures, nh);\n return *this;\n }\n\n template \n inline VectorSet estimateNormals(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, nh);\n return normals;\n }\n\n template \n inline VectorSet estimateCurvature(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, nh);\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvature(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n compute_nh_(normals, curvatures, nh);\n return *this;\n }\n\n inline VectorSet estimateNormals(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_nh_(normals, curvatures, nh);\n return normals;\n }\n\n inline VectorSet estimateCurvature(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_nh_(normals, curvatures, nh);\n return curvatures;\n }\n\n private:\n ConstVectorSetMatrixMap points_;\n const KDTree *kd_tree_ptr_;\n bool kd_tree_owned_;\n Vector view_point_;\n\n void compute_nh_(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n switch (nh.type) {\n case NeighborhoodType::KNN:\n compute_(normals, curvatures, nh);\n break;\n case NeighborhoodType::RADIUS:\n compute_(normals, curvatures, nh);\n break;\n case NeighborhoodType::KNN_IN_RADIUS:\n compute_(normals, curvatures, nh);\n break;\n }\n }\n\n template \n void compute_(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n size_t dim = points_.rows();\n size_t num_points = points_.cols();\n\n normals.resize(dim, num_points);\n curvatures.resize(1, num_points);\n\n std::vector neighbors;\n std::vector distances;\n#pragma omp parallel for shared (normals) private (neighbors, distances)\n for (size_t i = 0; i < num_points; i++) {\n kd_tree_ptr_->template search(points_.col(i), nh, neighbors, distances);\n if (neighbors.size() < dim) {\n normals.col(i).setConstant(std::numeric_limits::quiet_NaN());\n curvatures[i] = std::numeric_limits::quiet_NaN();\n continue;\n }\n VectorSet neighborhood(dim, neighbors.size());\n for (size_t j = 0; j < neighbors.size(); j++) {\n neighborhood.col(j) = points_.col(neighbors[j]);\n }\n PrincipalComponentAnalysis pca(neighborhood);\n normals.col(i) = pca.getEigenVectors().col(dim-1);\n if (normals.col(i).dot(view_point_ - points_.col(i)) < 0.0) {\n normals.col(i) *= -1.0;\n }\n curvatures[i] = pca.getEigenValues()[dim-1]\/pca.getEigenValues().sum();\n }\n }\n\n };\n\n typedef NormalEstimation NormalEstimation2D;\n typedef NormalEstimation NormalEstimation3D;\n}\nNormalEstimation fixes#pragma once\n\n#include \n#include \n\nnamespace cilantro {\n template \n class NormalEstimation {\n public:\n EIGEN_MAKE_ALIGNED_OPERATOR_NEW\n\n NormalEstimation(const ConstVectorSetMatrixMap &points, size_t max_leaf_size = 10)\n : points_(points),\n kd_tree_ptr_(new KDTree(points, max_leaf_size)),\n kd_tree_owned_(true),\n view_point_(Vector::Zero())\n {}\n\n NormalEstimation(const KDTree &kd_tree)\n : points_(kd_tree.getPointsMatrixMap()),\n kd_tree_ptr_(&kd_tree),\n kd_tree_owned_(false),\n view_point_(Vector::Zero())\n {}\n\n ~NormalEstimation() {\n if (kd_tree_owned_) delete kd_tree_ptr_;\n }\n\n inline const Vector& getViewPoint() const { return view_point_; }\n\n inline NormalEstimation& setViewPoint(const Eigen::Ref> &vp) { view_point_ = vp; return *this; }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureKNN(VectorSet &normals, VectorSet &curvatures, size_t k) const {\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return *this;\n }\n\n inline VectorSet estimateNormalsKNN(size_t k) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return normals;\n }\n\n inline VectorSet estimateCurvatureKNN(size_t k) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN, k, 0.0));\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureRadius(VectorSet &normals, VectorSet &curvatures, ScalarT radius) const {\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::RADIUS, 0, radius));\n return *this;\n }\n\n inline VectorSet estimateNormalsRadius(ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::RADIUS, 0, radius));\n return normals;\n }\n\n inline VectorSet estimateCurvatureRadius(ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::RADIUS, 0, radius));\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvatureKNNInRadius(VectorSet &normals, VectorSet &curvatures, size_t k, ScalarT radius) const {\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius));\n return *this;\n }\n\n inline VectorSet estimateNormalsKNNInRadius(size_t k, ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius));\n return normals;\n }\n\n inline VectorSet estimateCurvatureKNNInRadius(size_t k, ScalarT radius) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, NeighborhoodSpecification(NeighborhoodType::KNN_IN_RADIUS, k, radius));\n return curvatures;\n }\n\n template \n inline const NormalEstimation& estimateNormalsAndCurvature(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n compute_(normals, curvatures, nh);\n return *this;\n }\n\n template \n inline VectorSet estimateNormals(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, nh);\n return normals;\n }\n\n template \n inline VectorSet estimateCurvature(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_(normals, curvatures, nh);\n return curvatures;\n }\n\n inline const NormalEstimation& estimateNormalsAndCurvature(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n compute_nh_(normals, curvatures, nh);\n return *this;\n }\n\n inline VectorSet estimateNormals(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_nh_(normals, curvatures, nh);\n return normals;\n }\n\n inline VectorSet estimateCurvature(const NeighborhoodSpecification &nh) const {\n VectorSet normals;\n VectorSet curvatures;\n compute_nh_(normals, curvatures, nh);\n return curvatures;\n }\n\n private:\n ConstVectorSetMatrixMap points_;\n const KDTree *kd_tree_ptr_;\n bool kd_tree_owned_;\n Vector view_point_;\n\n void compute_nh_(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n switch (nh.type) {\n case NeighborhoodType::KNN:\n compute_(normals, curvatures, nh);\n break;\n case NeighborhoodType::RADIUS:\n compute_(normals, curvatures, nh);\n break;\n case NeighborhoodType::KNN_IN_RADIUS:\n compute_(normals, curvatures, nh);\n break;\n }\n }\n\n template \n void compute_(VectorSet &normals, VectorSet &curvatures, const NeighborhoodSpecification &nh) const {\n NeighborhoodSpecification nh_sq(nh);\n nh_sq.radius = nh_sq.radius*nh_sq.radius;\n\n size_t dim = points_.rows();\n size_t num_points = points_.cols();\n\n normals.resize(dim, num_points);\n curvatures.resize(1, num_points);\n\n std::vector neighbors;\n std::vector distances;\n#pragma omp parallel for shared (normals) private (neighbors, distances)\n for (size_t i = 0; i < num_points; i++) {\n kd_tree_ptr_->template search(points_.col(i), nh_sq, neighbors, distances);\n if (neighbors.size() < dim) {\n normals.col(i).setConstant(std::numeric_limits::quiet_NaN());\n curvatures[i] = std::numeric_limits::quiet_NaN();\n continue;\n }\n VectorSet neighborhood(dim, neighbors.size());\n for (size_t j = 0; j < neighbors.size(); j++) {\n neighborhood.col(j) = points_.col(neighbors[j]);\n }\n PrincipalComponentAnalysis pca(neighborhood);\n normals.col(i) = pca.getEigenVectors().col(dim-1);\n if (normals.col(i).dot(view_point_ - points_.col(i)) < 0.0) {\n normals.col(i) *= -1.0;\n }\n curvatures[i] = pca.getEigenValues()[dim-1]\/pca.getEigenValues().sum();\n }\n }\n\n };\n\n typedef NormalEstimation NormalEstimation2D;\n typedef NormalEstimation NormalEstimation3D;\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n * @copyright defined in eosio\/LICENSE.txt\n *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"config.hpp\"\n\nusing namespace appbase;\nusing namespace eosio;\n\nnamespace fc {\n std::unordered_map& get_appender_map();\n}\n\nnamespace detail {\n\nvoid configure_logging(const bfs::path& config_path)\n{\n try {\n try {\n fc::configure_logging(config_path);\n } catch (...) {\n elog(\"Error reloading logging.json\");\n throw;\n }\n } catch (const fc::exception& e) {\n elog(\"${e}\", (\"e\",e.to_detail_string()));\n } catch (const boost::exception& e) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n } catch (const std::exception& e) {\n elog(\"${e}\", (\"e\",e.what()));\n } catch (...) {\n \/\/ empty\n }\n}\n\n} \/\/ namespace detail\n\nvoid logging_conf_loop()\n{\n std::shared_ptr sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));\n sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int \/*num*\/) {\n if(!err)\n {\n ilog(\"Received HUP. Reloading logging configuration.\");\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n ::detail::configure_logging(config_path);\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n logging_conf_loop();\n }\n });\n}\n\nvoid initialize_logging()\n{\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n fc::configure_logging(config_path); \/\/ intentionally allowing exceptions to escape\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n\n logging_conf_loop();\n}\n\nenum return_codes {\n OTHER_FAIL = -2,\n INITIALIZE_FAIL = -1,\n SUCCESS = 0,\n BAD_ALLOC = 1,\n DATABASE_DIRTY = 2,\n FIXED_REVERSIBLE = 3,\n EXTRACTED_GENESIS = 4,\n NODE_MANAGEMENT_SUCCESS = 5\n};\n\nint main(int argc, char** argv)\n{\n try {\n app().set_version(eosio::nodeos::config::version);\n\n auto root = fc::app_path();\n app().set_default_data_dir(root \/ \"eosio\/nodeos\/data\" );\n app().set_default_config_dir(root \/ \"eosio\/nodeos\/config\" );\n http_plugin::set_defaults({\n .address_config_prefix = \"\",\n .default_unix_socket_path = \"\",\n .default_http_port = 8888\n });\n if(!app().initialize(argc, argv))\n return INITIALIZE_FAIL;\n initialize_logging();\n ilog(\"nodeos version ${ver}\", (\"ver\", app().version_string()));\n ilog(\"eosio root is ${root}\", (\"root\", root.string()));\n ilog(\"nodeos using configuration file ${c}\", (\"c\", app().full_config_file_path().string()));\n ilog(\"nodeos data directory is ${d}\", (\"d\", app().data_dir().string()));\n app().startup();\n app().exec();\n } catch( const extract_genesis_state_exception& e ) {\n return EXTRACTED_GENESIS;\n } catch( const fixed_reversible_db_exception& e ) {\n return FIXED_REVERSIBLE;\n } catch( const node_management_success& e ) {\n return NODE_MANAGEMENT_SUCCESS;\n } catch( const fc::exception& e ) {\n if( e.code() == fc::std_exception_code ) {\n if( e.top_message().find( \"database dirty flag set\" ) != std::string::npos ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( e.top_message().find( \"database metadata dirty flag set\" ) != std::string::npos ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n }\n }\n elog( \"${e}\", (\"e\", e.to_detail_string()));\n return OTHER_FAIL;\n } catch( const boost::interprocess::bad_alloc& e ) {\n elog(\"bad alloc\");\n return BAD_ALLOC;\n } catch( const boost::exception& e ) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n return OTHER_FAIL;\n } catch( const std::runtime_error& e ) {\n if( std::string(e.what()) == \"database dirty flag set\" ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( std::string(e.what()) == \"database metadata dirty flag set\" ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else {\n elog( \"${e}\", (\"e\",e.what()));\n }\n return OTHER_FAIL;\n } catch( const std::exception& e ) {\n elog(\"${e}\", (\"e\",e.what()));\n return OTHER_FAIL;\n } catch( ... ) {\n elog(\"unknown exception\");\n return OTHER_FAIL;\n }\n\n return SUCCESS;\n}\nRemove unneeded include.\/**\n * @file\n * @copyright defined in eosio\/LICENSE.txt\n *\/\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"config.hpp\"\n\nusing namespace appbase;\nusing namespace eosio;\n\nnamespace fc {\n std::unordered_map& get_appender_map();\n}\n\nnamespace detail {\n\nvoid configure_logging(const bfs::path& config_path)\n{\n try {\n try {\n fc::configure_logging(config_path);\n } catch (...) {\n elog(\"Error reloading logging.json\");\n throw;\n }\n } catch (const fc::exception& e) {\n elog(\"${e}\", (\"e\",e.to_detail_string()));\n } catch (const boost::exception& e) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n } catch (const std::exception& e) {\n elog(\"${e}\", (\"e\",e.what()));\n } catch (...) {\n \/\/ empty\n }\n}\n\n} \/\/ namespace detail\n\nvoid logging_conf_loop()\n{\n std::shared_ptr sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));\n sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int \/*num*\/) {\n if(!err)\n {\n ilog(\"Received HUP. Reloading logging configuration.\");\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n ::detail::configure_logging(config_path);\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n logging_conf_loop();\n }\n });\n}\n\nvoid initialize_logging()\n{\n auto config_path = app().get_logging_conf();\n if(fc::exists(config_path))\n fc::configure_logging(config_path); \/\/ intentionally allowing exceptions to escape\n for(auto iter : fc::get_appender_map())\n iter.second->initialize(app().get_io_service());\n\n logging_conf_loop();\n}\n\nenum return_codes {\n OTHER_FAIL = -2,\n INITIALIZE_FAIL = -1,\n SUCCESS = 0,\n BAD_ALLOC = 1,\n DATABASE_DIRTY = 2,\n FIXED_REVERSIBLE = 3,\n EXTRACTED_GENESIS = 4,\n NODE_MANAGEMENT_SUCCESS = 5\n};\n\nint main(int argc, char** argv)\n{\n try {\n app().set_version(eosio::nodeos::config::version);\n\n auto root = fc::app_path();\n app().set_default_data_dir(root \/ \"eosio\/nodeos\/data\" );\n app().set_default_config_dir(root \/ \"eosio\/nodeos\/config\" );\n http_plugin::set_defaults({\n .address_config_prefix = \"\",\n .default_unix_socket_path = \"\",\n .default_http_port = 8888\n });\n if(!app().initialize(argc, argv))\n return INITIALIZE_FAIL;\n initialize_logging();\n ilog(\"nodeos version ${ver}\", (\"ver\", app().version_string()));\n ilog(\"eosio root is ${root}\", (\"root\", root.string()));\n ilog(\"nodeos using configuration file ${c}\", (\"c\", app().full_config_file_path().string()));\n ilog(\"nodeos data directory is ${d}\", (\"d\", app().data_dir().string()));\n app().startup();\n app().exec();\n } catch( const extract_genesis_state_exception& e ) {\n return EXTRACTED_GENESIS;\n } catch( const fixed_reversible_db_exception& e ) {\n return FIXED_REVERSIBLE;\n } catch( const node_management_success& e ) {\n return NODE_MANAGEMENT_SUCCESS;\n } catch( const fc::exception& e ) {\n if( e.code() == fc::std_exception_code ) {\n if( e.top_message().find( \"database dirty flag set\" ) != std::string::npos ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( e.top_message().find( \"database metadata dirty flag set\" ) != std::string::npos ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n }\n }\n elog( \"${e}\", (\"e\", e.to_detail_string()));\n return OTHER_FAIL;\n } catch( const boost::interprocess::bad_alloc& e ) {\n elog(\"bad alloc\");\n return BAD_ALLOC;\n } catch( const boost::exception& e ) {\n elog(\"${e}\", (\"e\",boost::diagnostic_information(e)));\n return OTHER_FAIL;\n } catch( const std::runtime_error& e ) {\n if( std::string(e.what()) == \"database dirty flag set\" ) {\n elog( \"database dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else if( std::string(e.what()) == \"database metadata dirty flag set\" ) {\n elog( \"database metadata dirty flag set (likely due to unclean shutdown): replay required\" );\n return DATABASE_DIRTY;\n } else {\n elog( \"${e}\", (\"e\",e.what()));\n }\n return OTHER_FAIL;\n } catch( const std::exception& e ) {\n elog(\"${e}\", (\"e\",e.what()));\n return OTHER_FAIL;\n } catch( ... ) {\n elog(\"unknown exception\");\n return OTHER_FAIL;\n }\n\n return SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2017 Sony Corporation. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/** RandomShift\n *\/\n#ifndef __NBLA_FUNCTION_RANDOM_SHIFT_HPP__\n#define __NBLA_FUNCTION_RANDOM_SHIFT_HPP__\n\n#include \n#include \n#include \n\n#include \n\nnamespace nbla {\n\nNBLA_REGISTER_FUNCTION_HEADER(RandomShift, const vector &, const string &,\n float, int, int);\n\n\/** RandomShift randomly shifts the array elements within the specified range.\n\nInputs:\n- N-D array.\n\nOutputs:\n- N-D array.\n\n@tparam T Data type for computation.\n@param shift Max absolute amount to shift elements. For example, to shift image\ndata horizontally by +-2 pixels and vertically by +-3 pixels, specify (3,2).\n@param border_mode Specify how to process the ends of arrays whose values will\nbe undetermined as a result of shifting. nearest: The data at the ends of the\noriginal array is copied and used. reflect: Original data reflected at the ends\nof the original array is used.\n\\ingroup FunctionImplGrp\n*\/\n\ntemplate \nclass RandomShift : public BaseFunction &, const string &,\n float, int, int> {\nprotected:\n vector shifts_;\n string border_mode_;\n int base_axis_;\n\n int size_;\n\n const T constant_value_;\n const int CVAL_INDEX = -1;\n\n \/\/ This variable is an array to realize different shift amount for each data.\n vector>> addr_table_;\n\n int seed_;\n std::mt19937 rgen_;\n\npublic:\n RandomShift(const Context &ctx, const vector &shifts,\n const string &border_mode, float constant_value, int base_axis,\n int seed)\n : BaseFunction(ctx, shifts, border_mode, constant_value, base_axis, seed),\n shifts_(shifts), border_mode_(border_mode), base_axis_(base_axis),\n constant_value_(constant_value), seed_(seed) {}\n virtual ~RandomShift() {}\n virtual shared_ptr copy() const {\n return create_RandomShift(ctx_, shifts_, border_mode_, constant_value_,\n base_axis_, seed_);\n }\n virtual vector in_types() { return vector{get_dtype()}; }\n virtual vector out_types() { return vector{get_dtype()}; }\n virtual int min_inputs() { return 1; }\n virtual int min_outputs() { return 1; }\n virtual string name() { return \"RandomShift\"; }\n virtual vector allowed_array_classes() {\n return SingletonManager::get()->array_classes();\n }\n\nprotected:\n NBLA_API virtual void setup_impl(const Variables &inputs,\n const Variables &outputs);\n NBLA_API virtual void forward_impl(const Variables &inputs,\n const Variables &outputs);\n NBLA_API virtual void backward_impl(const Variables &inputs,\n const Variables &outputs,\n const vector &propagate_down,\n const vector &accum);\n\n vector> prepare_addr_table(const Variables &inputs,\n const vector &shifts);\n\nprivate:\n void shift_recursive(const Variable *inp, const T *x, T *y, int x_offset,\n int y_offset, int dim, int &shift_index);\n void shift_backward_recursive(const Variable *inp, const T *dy, T *dx,\n int x_offset, int y_offset, int dim,\n int &shift_index);\n};\n}\n#endif\nfix format for random_shift.\/\/ Copyright (c) 2017 Sony Corporation. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/** RandomShift\n *\/\n#ifndef __NBLA_FUNCTION_RANDOM_SHIFT_HPP__\n#define __NBLA_FUNCTION_RANDOM_SHIFT_HPP__\n\n#include \n#include \n#include \n\n#include \n\nnamespace nbla {\n\nNBLA_REGISTER_FUNCTION_HEADER(RandomShift, const vector &, const string &,\n float, int, int);\n\n\/** RandomShift randomly shifts the array elements within the specified range.\n\nInputs:\n- N-D array.\n\nOutputs:\n- N-D array.\n\n@tparam T Data type for computation.\n@param shift Max absolute amount to shift elements. For example, to shift image\ndata horizontally by +-2 pixels and vertically by +-3 pixels, specify (3,2).\n@param border_mode Specify how to process the ends of arrays whose values will\nbe undetermined as a result of shifting. nearest: The data at the ends of the\noriginal array is copied and used. reflect: Original data reflected at the ends\nof the original array is used.\n\\ingroup FunctionImplGrp\n*\/\n\ntemplate \nclass RandomShift : public BaseFunction &, const string &,\n float, int, int> {\nprotected:\n vector shifts_;\n string border_mode_;\n int base_axis_;\n\n int size_;\n\n const T constant_value_;\n const int CVAL_INDEX = -1;\n\n \/\/ This variable is an array to realize different shift amount for each data.\n vector>> addr_table_;\n\n int seed_;\n std::mt19937 rgen_;\n\npublic:\n RandomShift(const Context &ctx, const vector &shifts,\n const string &border_mode, float constant_value, int base_axis,\n int seed)\n : BaseFunction(ctx, shifts, border_mode, constant_value, base_axis, seed),\n shifts_(shifts), border_mode_(border_mode), base_axis_(base_axis),\n constant_value_(constant_value), seed_(seed) {}\n virtual ~RandomShift() {}\n virtual shared_ptr copy() const {\n return create_RandomShift(ctx_, shifts_, border_mode_, constant_value_,\n base_axis_, seed_);\n }\n virtual vector in_types() { return vector{get_dtype()}; }\n virtual vector out_types() { return vector{get_dtype()}; }\n virtual int min_inputs() { return 1; }\n virtual int min_outputs() { return 1; }\n virtual string name() { return \"RandomShift\"; }\n virtual vector allowed_array_classes() {\n return SingletonManager::get()->array_classes();\n }\n\nprotected:\n NBLA_API virtual void setup_impl(const Variables &inputs,\n const Variables &outputs);\n NBLA_API virtual void forward_impl(const Variables &inputs,\n const Variables &outputs);\n NBLA_API virtual void backward_impl(const Variables &inputs,\n const Variables &outputs,\n const vector &propagate_down,\n const vector &accum);\n\n vector> prepare_addr_table(const Variables &inputs,\n const vector &shifts);\n\nprivate:\n void shift_recursive(const Variable *inp, const T *x, T *y, int x_offset,\n int y_offset, int dim, int &shift_index);\n void shift_backward_recursive(const Variable *inp, const T *dy, T *dx,\n int x_offset, int y_offset, int dim,\n int &shift_index);\n};\n}\n#endif\n<|endoftext|>"} {"text":"\/*\n * This file is part of otf2xx (https:\/\/github.com\/tud-zih-energy\/otf2xx)\n * otf2xx - A wrapper for the Open Trace Format 2 library\n *\n * Copyright (c) 2013-2016, Technische Universität Dresden, Germany\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/*\n * otf2xx - reference.hpp\n *\n * Copyright (c) 2014 TU Dresden\n *\n * All rights reserved.\n *\n * author: Mario Bielert \n *\n *\/\n\n#ifndef INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\n#define INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nnamespace otf2\n{\n\n\/**\n * @brief gives a free reference number for a set of definitions\n *\n * This class generates free reference numbers for definitons. For this\n * task, it needs to know every used reference number first.\n *\n * Therefore you need to register every definition.\n *\n * \\note The algorithm for generating a number is undefined.\n *\n * \\tparam Definition The definition for which it should generate numbers\n *\/\ntemplate \nclass reference_generator\n{\npublic:\n typedef RefType ref_type;\n\n template \n void register_definition(const Definition& def)\n {\n static_assert(std::is_constructible::value,\n \"Trying to register a definition with a different id space\");\n\n register_reference(static_cast(def.ref()));\n }\n\n void register_reference(ref_type ref)\n {\n if (old_max == ref_type::undefined())\n {\n old_max = ref.get();\n return;\n }\n\n using std::max;\n\n old_max = max(ref.get(), old_max);\n }\n\n template \n RefType2 next()\n {\n static_assert(std::is_constructible::value,\n \"Trying to get a reference for a definition with a different id space\");\n\n if (ref_type::undefined() == old_max + 1)\n {\n make_exception(\"Cannot generate a new unused reference number\");\n }\n\n return ++old_max;\n }\n\nprivate:\n typename ref_type::ref_type old_max = -1;\n};\n\nclass trace_reference_generator\n{\n template \n struct make_generator\n {\n using type = reference_generator>;\n };\n\n using generators =\n tmp::apply_t,\n std::tuple>;\n\n template \n auto& get_generator()\n {\n using generator = typename make_generator::type;\n static_assert(tmp::contains(),\n \"Cannot get a generator for this definition!\");\n return std::get(ref_generators_);\n }\n\npublic:\n template \n void register_definition(const Definition& def)\n {\n get_generator().register_definition(def);\n }\n\n template \n void operator()(const Definition& def)\n {\n register_definition(def);\n }\n\n template \n typename Definition::reference_type next()\n {\n \/\/ TMP-code-obfuscator was here\n return get_generator().template next();\n }\n\nprivate:\n \/\/\/ std::tuple of reference_generator for each definition (tag)\n generators ref_generators_;\n};\n\n} \/\/ namespace otf2\n\n#endif \/\/ INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\nAdds peak() method to reference generators\/*\n * This file is part of otf2xx (https:\/\/github.com\/tud-zih-energy\/otf2xx)\n * otf2xx - A wrapper for the Open Trace Format 2 library\n *\n * Copyright (c) 2013-2016, Technische Universität Dresden, Germany\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * * Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n *\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * * Neither the name of the copyright holder nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n *\/\n\n\/*\n * otf2xx - reference.hpp\n *\n * Copyright (c) 2014 TU Dresden\n *\n * All rights reserved.\n *\n * author: Mario Bielert \n *\n *\/\n\n#ifndef INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\n#define INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\nnamespace otf2\n{\n\n\/**\n * @brief gives a free reference number for a set of definitions\n *\n * This class generates free reference numbers for definitons. For this\n * task, it needs to know every used reference number first.\n *\n * Therefore you need to register every definition.\n *\n * \\note The algorithm for generating a number is undefined.\n *\n * \\tparam Definition The definition for which it should generate numbers\n *\/\ntemplate \nclass reference_generator\n{\npublic:\n typedef RefType ref_type;\n\n template \n void register_definition(const Definition& def)\n {\n static_assert(std::is_constructible::value,\n \"Trying to register a definition with a different id space\");\n\n register_reference(static_cast(def.ref()));\n }\n\n void register_reference(ref_type ref)\n {\n if (old_max == ref_type::undefined())\n {\n old_max = ref.get();\n return;\n }\n\n using std::max;\n\n old_max = max(ref.get(), old_max);\n }\n\n template \n RefType2 next()\n {\n static_assert(std::is_constructible::value,\n \"Trying to get a reference for a definition with a different id space\");\n\n if (ref_type::undefined() == old_max + 1)\n {\n make_exception(\"Cannot generate a new unused reference number\");\n }\n\n return ++old_max;\n }\n\n template \n RefType2 peak()\n {\n static_assert(std::is_constructible::value,\n \"Trying to get a reference for a definition with a different id space\");\n return old_max + 1;\n }\n\nprivate:\n typename ref_type::ref_type old_max = -1;\n};\n\nclass trace_reference_generator\n{\n template \n struct make_generator\n {\n using type = reference_generator>;\n };\n\n using generators =\n tmp::apply_t,\n std::tuple>;\n\n template \n auto& get_generator()\n {\n using generator = typename make_generator::type;\n static_assert(tmp::contains(),\n \"Cannot get a generator for this definition!\");\n return std::get(ref_generators_);\n }\n\npublic:\n template \n void register_definition(const Definition& def)\n {\n get_generator().register_definition(def);\n }\n\n template \n void operator()(const Definition& def)\n {\n register_definition(def);\n }\n\n template \n typename Definition::reference_type next()\n {\n \/\/ TMP-code-obfuscator was here\n return get_generator().template next();\n }\n\n template \n typename Definition::reference_type peak()\n {\n \/\/ TMP-code-obfuscator was here\n return get_generator().template peak();\n }\n\nprivate:\n \/\/\/ std::tuple of reference_generator for each definition (tag)\n generators ref_generators_;\n};\n\n} \/\/ namespace otf2\n\n#endif \/\/ INCLUDE_OTF2XX_REFERENCE_GENERATOR_HPP\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#include \"..\/simd\/type_traits.h\"\n\nnamespace MATH_NAMESPACE\n{\n\ntemplate \nMATH_FUNC\ninline basic_ray::basic_ray(vector<3, T> const& o, vector<3, T> const& d)\n : ori(o)\n , dir(d)\n{\n}\n\n\nnamespace simd\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ SIMD conversions\n\/\/\n\n\/\/ pack ---------------------------------------------------\n\ntemplate \ninline basic_ray::type> pack(\n std::array, N> const& rays\n )\n{\n using U = typename float_from_simd_width::type;\n using float_array = typename aligned_array::type;\n\n float_array ori_x;\n float_array ori_y;\n float_array ori_z;\n\n float_array dir_x;\n float_array dir_y;\n float_array dir_z;\n\n for (size_t i = 0; i < N; ++i)\n {\n ori_x[i] = rays[i].ori.x;\n ori_y[i] = rays[i].ori.y;\n ori_z[i] = rays[i].ori.z;\n\n dir_x[i] = rays[i].dir.x;\n dir_y[i] = rays[i].dir.y;\n dir_z[i] = rays[i].dir.z;\n }\n\n return basic_ray(\n vector<3, U>(ori_x, ori_y, ori_z),\n vector<3, U>(dir_x, dir_y, dir_z)\n );\n}\n\n} \/\/ simd\n} \/\/ MATH_NAMESPACE\nAdd simd::unpack(basic_ray)\/\/ This file is distributed under the MIT license.\n\/\/ See the LICENSE file for details.\n\n#include \n\n#include \"..\/simd\/type_traits.h\"\n\nnamespace MATH_NAMESPACE\n{\n\ntemplate \nMATH_FUNC\ninline basic_ray::basic_ray(vector<3, T> const& o, vector<3, T> const& d)\n : ori(o)\n , dir(d)\n{\n}\n\n\nnamespace simd\n{\n\n\/\/-------------------------------------------------------------------------------------------------\n\/\/ SIMD conversions\n\/\/\n\n\/\/ pack ---------------------------------------------------\n\ntemplate \ninline basic_ray::type> pack(\n std::array, N> const& rays\n )\n{\n using U = typename float_from_simd_width::type;\n using float_array = typename aligned_array::type;\n\n float_array ori_x;\n float_array ori_y;\n float_array ori_z;\n\n float_array dir_x;\n float_array dir_y;\n float_array dir_z;\n\n for (size_t i = 0; i < N; ++i)\n {\n ori_x[i] = rays[i].ori.x;\n ori_y[i] = rays[i].ori.y;\n ori_z[i] = rays[i].ori.z;\n\n dir_x[i] = rays[i].dir.x;\n dir_y[i] = rays[i].dir.y;\n dir_z[i] = rays[i].dir.z;\n }\n\n return basic_ray(\n vector<3, U>(ori_x, ori_y, ori_z),\n vector<3, U>(dir_x, dir_y, dir_z)\n );\n}\n\n\/\/ unpack -------------------------------------------------\n\ntemplate <\n typename FloatT,\n typename = typename std::enable_if::value>::type\n >\ninline auto unpack(basic_ray const& ray)\n -> std::array, num_elements::value>\n{\n using float_array = typename aligned_array::type;\n\n float_array ori_x;\n float_array ori_y;\n float_array ori_z;\n\n float_array dir_x;\n float_array dir_y;\n float_array dir_z;\n\n store(ori_x, ray.ori.x);\n store(ori_y, ray.ori.y);\n store(ori_z, ray.ori.z);\n\n store(dir_x, ray.dir.x);\n store(dir_y, ray.dir.y);\n store(dir_z, ray.dir.z);\n\n std::array, num_elements::value> result;\n\n for (int i = 0; i < num_elements::value; ++i)\n {\n result[i].ori.x = ori_x[i];\n result[i].ori.y = ori_y[i];\n result[i].ori.z = ori_z[i];\n\n result[i].dir.x = dir_x[i];\n result[i].dir.y = dir_y[i];\n result[i].dir.z = dir_z[i];\n }\n\n return result;\n}\n\n} \/\/ simd\n} \/\/ MATH_NAMESPACE\n<|endoftext|>"} {"text":"\/* RTcmix - Copyright (C) 2004 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include \n#include \n#include \n#include \n#include \n\nstatic float *newFloats(float *oldptr, int oldlen, int *newlen)\n{\n\tfloat *ptr = NULL;\n\tif (oldptr == NULL) {\n\t\tptr = (float *) malloc(*newlen * sizeof(float));\n\t}\n\telse {\n\t\tfloat *newptr = (float *) realloc(oldptr, *newlen * sizeof(float));\n\t\tif (newptr) {\n\t\t\tptr = newptr;\n\t\t\t\/\/ Zero out new portion.\n\t\t\tfor (int n = oldlen; n < *newlen; ++n)\n\t\t\t\tptr[n] = 0.0f;\n\t\t}\n\t\telse {\n\t\t\t*newlen = oldlen;\t\/\/ notify caller that realloc failed\n\t\t\tptr = oldptr;\n\t\t}\n\t}\n\treturn ptr;\n}\n\nOcomb::Ocomb(float SR, float loopTime, float reverbTime) : _sr(SR)\n{\n\tinit(loopTime, loopTime, reverbTime);\n}\n\nOcomb::Ocomb(float SR, float loopTime, float maxLoopTime, float reverbTime)\n\t: _sr(SR)\n{\n\tinit(loopTime, maxLoopTime, reverbTime);\n}\n\nvoid Ocomb::init(float loopTime, float maxLoopTime, float reverbTime)\n{\n\tassert(maxLoopTime > 0.0);\n\tassert(maxLoopTime >= loopTime);\n\n\t_len = (int) (maxLoopTime * _sr + 0.5);\n\t_dline = newFloats(NULL, 0, &_len);\n\tclear();\n\t_delsamps = (int) (loopTime * _sr + 0.5);\n\tsetReverbTime(reverbTime);\n\t_pointer = 0;\n}\n\nOcomb::~Ocomb()\n{\n\tfree(_dline);\n}\n\nvoid Ocomb::clear()\n{\n\tfor (int i = 0; i < _len; i++)\n\t\t_dline[i] = 0.0;\n}\n\nvoid Ocomb::setReverbTime(float reverbTime)\n{\n\tassert(reverbTime > 0.0);\n\t_gain = pow(0.001, ((float) _delsamps \/ _sr) \/ reverbTime);\n}\n\nfloat Ocomb::next(float input)\n{\n\tif (_pointer == _len)\n\t\t_pointer = 0;\n\tfloat out = _dline[_pointer];\n\t_dline[_pointer++] = (out * _gain) + input;\n\treturn out;\n}\n\nfloat Ocomb::next(float input, int delaySamps)\n{\n\tif (delaySamps >= _len) {\n\t\t\/\/ Make a guess at how big the new array should be.\n\t\tint newlen = (delaySamps < _len * 2) ? _len * 2 : _len + delaySamps;\n\t\tprintf(\"Ocomb resizing from %d to %d\\n\", _len, newlen);\n\t\t_dline = newFloats(_dline, _len, &newlen);\n\t\tif (newlen > _len) {\n\t\t\t_len = newlen;\n\t\t}\n\t\telse {\n\t\t\tprintf(\"Ocomb resize failed! Limiting delay.\\n\");\n\t\t\tdelaySamps = _len - 1;\n\t\t}\n\t}\n\t_delsamps = delaySamps;\n\tif (_pointer >= _delsamps)\n\t\t_pointer = 0;\n\tfloat out = _dline[_pointer];\n\t_dline[_pointer++] = (out * _gain) + input;\n\treturn out;\n}\n\nFixed >= which should be >\/* RTcmix - Copyright (C) 2004 The RTcmix Development Team\n See ``AUTHORS'' for a list of contributors. See ``LICENSE'' for\n the license to this software and for a DISCLAIMER OF ALL WARRANTIES.\n*\/\n#include \n#include \n#include \n#include \n#include \n\nstatic float *newFloats(float *oldptr, int oldlen, int *newlen)\n{\n\tfloat *ptr = NULL;\n\tif (oldptr == NULL) {\n\t\tptr = (float *) malloc(*newlen * sizeof(float));\n\t}\n\telse {\n\t\tfloat *newptr = (float *) realloc(oldptr, *newlen * sizeof(float));\n\t\tif (newptr) {\n\t\t\tptr = newptr;\n\t\t\t\/\/ Zero out new portion.\n\t\t\tfor (int n = oldlen; n < *newlen; ++n)\n\t\t\t\tptr[n] = 0.0f;\n\t\t}\n\t\telse {\n\t\t\t*newlen = oldlen;\t\/\/ notify caller that realloc failed\n\t\t\tptr = oldptr;\n\t\t}\n\t}\n\treturn ptr;\n}\n\nOcomb::Ocomb(float SR, float loopTime, float reverbTime) : _sr(SR)\n{\n\tinit(loopTime, loopTime, reverbTime);\n}\n\nOcomb::Ocomb(float SR, float loopTime, float maxLoopTime, float reverbTime)\n\t: _sr(SR)\n{\n\tinit(loopTime, maxLoopTime, reverbTime);\n}\n\nvoid Ocomb::init(float loopTime, float maxLoopTime, float reverbTime)\n{\n\tassert(maxLoopTime > 0.0);\n\tassert(maxLoopTime >= loopTime);\n\n\t_len = (int) (maxLoopTime * _sr + 0.5);\n\t_dline = newFloats(NULL, 0, &_len);\n\tclear();\n\t_delsamps = (int) (loopTime * _sr + 0.5);\n\tsetReverbTime(reverbTime);\n\t_pointer = 0;\n}\n\nOcomb::~Ocomb()\n{\n\tfree(_dline);\n}\n\nvoid Ocomb::clear()\n{\n\tfor (int i = 0; i < _len; i++)\n\t\t_dline[i] = 0.0;\n}\n\nvoid Ocomb::setReverbTime(float reverbTime)\n{\n\tassert(reverbTime > 0.0);\n\t_gain = pow(0.001, ((float) _delsamps \/ _sr) \/ reverbTime);\n}\n\nfloat Ocomb::next(float input)\n{\n\tif (_pointer == _len)\n\t\t_pointer = 0;\n\tfloat out = _dline[_pointer];\n\t_dline[_pointer++] = (out * _gain) + input;\n\treturn out;\n}\n\nfloat Ocomb::next(float input, int delaySamps)\n{\n\tif (delaySamps > _len) {\n\t\t\/\/ Make a guess at how big the new array should be.\n\t\tint newlen = (delaySamps < _len * 2) ? _len * 2 : _len + delaySamps;\n\t\tprintf(\"Ocomb resizing from %d to %d\\n\", _len, newlen);\n\t\t_dline = newFloats(_dline, _len, &newlen);\n\t\tif (newlen > _len) {\n\t\t\t_len = newlen;\n\t\t}\n\t\telse {\n\t\t\tprintf(\"Ocomb resize failed! Limiting delay.\\n\");\n\t\t\tdelaySamps = _len - 1;\n\t\t}\n\t}\n\t_delsamps = delaySamps;\n\tif (_pointer >= _delsamps)\n\t\t_pointer = 0;\n\tfloat out = _dline[_pointer];\n\t_dline[_pointer++] = (out * _gain) + input;\n\treturn out;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.\n *\/\n \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nnamespace Fabric\n{\n namespace MR\n {\n ValueProducer::ValueProducer()\n {\n }\n \n ValueProducer::ComputeState::ComputeState( RC::ConstHandle const &valueProducer )\n : m_valueProducer( valueProducer )\n {\n }\n \n void ValueProducer::ComputeState::produceJSON( Util::JSONGenerator &jg ) const\n {\n RC::ConstHandle valueDesc = m_valueProducer->getValueDesc();\n \n size_t allocSize = valueDesc->getAllocSize();\n void *valueData = alloca( allocSize );\n memset( valueData, 0, allocSize );\n produce( valueData );\n valueDesc->generateJSON( valueData, jg );\n valueDesc->disposeData( valueData );\n }\n \n struct ProduceJSONAsyncCallbackData\n {\n RC::Handle computeState;\n Util::JSONObjectGenerator *jsonObjectGenerator;\n };\n\n void ValueProducer::ComputeState::produceJSONAsync(\n Util::JSONObjectGenerator &jsonObjectGenerator,\n void (*finishedCallback)( void * ),\n void *finishedUserdata\n )\n {\n ProduceJSONAsyncCallbackData *produceJSONAsyncCallbackData = new ProduceJSONAsyncCallbackData;\n produceJSONAsyncCallbackData->computeState = this;\n produceJSONAsyncCallbackData->jsonObjectGenerator = &jsonObjectGenerator;\n \n MT::ThreadPool::Instance()->executeParallelAsync(\n MT::tlsLogCollector.get(),\n 1,\n &ValueProducer::ComputeState::ProduceJSONAsyncCallback,\n produceJSONAsyncCallbackData,\n MT::ThreadPool::Idle,\n finishedCallback,\n finishedUserdata\n );\n }\n \n void ValueProducer::ComputeState::ProduceJSONAsyncCallback(\n void *userdata,\n size_t index\n )\n {\n ProduceJSONAsyncCallbackData *produceJSONAsyncCallbackData = static_cast( userdata );\n {\n Util::JSONGenerator jg = produceJSONAsyncCallbackData->jsonObjectGenerator->makeMember( \"result\" );\n produceJSONAsyncCallbackData->computeState->produceJSON( jg );\n }\n delete produceJSONAsyncCallbackData;\n }\n };\n};\nMR: minor Windows build break\/*\n * Copyright 2010-2011 Fabric Technologies Inc. All rights reserved.\n *\/\n \n#include \n#include \n#include \n#include \n\n#if !defined(FABRIC_OS_WINDOWS)\n #include \n#endif\n\n#include \n\nnamespace Fabric\n{\n namespace MR\n {\n ValueProducer::ValueProducer()\n {\n }\n \n ValueProducer::ComputeState::ComputeState( RC::ConstHandle const &valueProducer )\n : m_valueProducer( valueProducer )\n {\n }\n \n void ValueProducer::ComputeState::produceJSON( Util::JSONGenerator &jg ) const\n {\n RC::ConstHandle valueDesc = m_valueProducer->getValueDesc();\n \n size_t allocSize = valueDesc->getAllocSize();\n void *valueData = alloca( allocSize );\n memset( valueData, 0, allocSize );\n produce( valueData );\n valueDesc->generateJSON( valueData, jg );\n valueDesc->disposeData( valueData );\n }\n \n struct ProduceJSONAsyncCallbackData\n {\n RC::Handle computeState;\n Util::JSONObjectGenerator *jsonObjectGenerator;\n };\n\n void ValueProducer::ComputeState::produceJSONAsync(\n Util::JSONObjectGenerator &jsonObjectGenerator,\n void (*finishedCallback)( void * ),\n void *finishedUserdata\n )\n {\n ProduceJSONAsyncCallbackData *produceJSONAsyncCallbackData = new ProduceJSONAsyncCallbackData;\n produceJSONAsyncCallbackData->computeState = this;\n produceJSONAsyncCallbackData->jsonObjectGenerator = &jsonObjectGenerator;\n \n MT::ThreadPool::Instance()->executeParallelAsync(\n MT::tlsLogCollector.get(),\n 1,\n &ValueProducer::ComputeState::ProduceJSONAsyncCallback,\n produceJSONAsyncCallbackData,\n MT::ThreadPool::Idle,\n finishedCallback,\n finishedUserdata\n );\n }\n \n void ValueProducer::ComputeState::ProduceJSONAsyncCallback(\n void *userdata,\n size_t index\n )\n {\n ProduceJSONAsyncCallbackData *produceJSONAsyncCallbackData = static_cast( userdata );\n {\n Util::JSONGenerator jg = produceJSONAsyncCallbackData->jsonObjectGenerator->makeMember( \"result\" );\n produceJSONAsyncCallbackData->computeState->produceJSON( jg );\n }\n delete produceJSONAsyncCallbackData;\n }\n };\n};\n<|endoftext|>"} {"text":"#ifndef ecmdDataBuffer_H\n#define ecmdDataBuffer_H\n\n\/\/ Copyright **********************************************************\n\/\/ \n\/\/ File ecmdDataBuffer.H \n\/\/ \n\/\/ IBM Confidential \n\/\/ OCO Source Materials \n\/\/ 9400 Licensed Internal Code \n\/\/ (C) COPYRIGHT IBM CORP. 2003\n\/\/ \n\/\/ The source code for this program is not published or otherwise \n\/\/ divested of its trade secrets, irrespective of what has been \n\/\/ deposited with the U.S. Copyright Office. \n\/\/ \n\/\/ End Copyright ******************************************************\n\n\/**\n * @file ecmdDataBuffer.H\n * @brief Provides a means to handle data from the eCMD C API\n *\n * DataBuffers handle data in a Big Endian fashion with Bit 0 being the MSB\n*\/\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/\/ Constants\n\/\/----------------------------------------------------------------------\n\n\/\/--------------------------------------------------------------------\n\/\/ Macros\n\/\/--------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/\/ Global Variables\n\/\/----------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/\/ User Types\n\/\/----------------------------------------------------------------------\n\n\nclass ecmdDataBuffer {\n\n\n\n\n};\n\n\n#endif\n\n \necmdDataBuffer.H filled out with more functions#ifndef ecmdDataBuffer_H\n#define ecmdDataBuffer_H\n\n\/\/ Copyright **********************************************************\n\/\/ \n\/\/ File ecmdDataBuffer.H \n\/\/ \n\/\/ IBM Confidential \n\/\/ OCO Source Materials \n\/\/ 9400 Licensed Internal Code \n\/\/ (C) COPYRIGHT IBM CORP. 2003\n\/\/ \n\/\/ The source code for this program is not published or otherwise \n\/\/ divested of its trade secrets, irrespective of what has been \n\/\/ deposited with the U.S. Copyright Office. \n\/\/ \n\/\/ End Copyright ******************************************************\n\n\/**\n * @file ecmdDataBuffer.H\n * @brief Provides a means to handle data from the eCMD C API\n *\n * DataBuffers handle data in a Big Endian fashion with Bit 0 being the MSB\n*\/\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------\n#include \n\n\/\/----------------------------------------------------------------------\n\/\/ Constants\n\/\/----------------------------------------------------------------------\n\n\/\/--------------------------------------------------------------------\n\/\/ Macros\n\/\/--------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/\/ Global Variables\n\/\/----------------------------------------------------------------------\n\n\/\/----------------------------------------------------------------------\n\/\/ User Types\n\/\/----------------------------------------------------------------------\n\n\nclass ecmdDataBuffer {\n\n public:\n\n \/**\n * @brief Default Constructor\n *\/\n ecmdDataBuffer();\n\n \/**\n * @brief Constructor\n * @param numBits Size of data to initialize in bits\n * @post ecmdDataBuffer is initialzed with a buffer\n *\/\n ecmdDataBuffer(int numBits); \n\n \/**\n * @brief Default Destructor\n *\/\n ~ecmdDataBuffer();\n\n \/\/ Member Functions\n \/** @name Buffer Size Function *\/\n \/\/@{\n \/**\n * @brief Return the length of the buffer in words\n * @retval Buffer length in words\n *\/\n int getWordLength() const;\n \/**\n * @brief Return the length of the buffer in bits\n * @retval Buffer length in bits\n *\/\n int getBitLength() const;\n \/**\n * @brief Reinitialize the Buffer to specified length\n * @param newnumwords Length of new buffer in words\n * @post Buffer is reinitialized\n *\n * NOTE : All data stored in buffer will be lost\n *\/\n void setWordLength(int newnumwords); \n \/**\n * @brief Reinitialize the Buffer to specified length\n * @param newnumbits Length of new buffer in bits\n * @post Buffer is reinitialized\n *\n * NOTE : All data stored in buffer will be lost\n *\/\n void setBitLength(int newnumbits);\n \/\/@}\n\n\n\n \/** @name Bit\/Word Manipulation Functions *\/\n \/\/@{\n \/**\n * @brief Turn on a bit in buffer\n * @param bit Bit in buffer to turn on\n *\/\n void setBit(int bit);\n \/**\n * @brief Turn on a bit in buffer\n * @param bit start bit in buffer to turn on\n * @param len Number of consecutive bits from start bit to turn on\n *\/\n void setBit(int bit, int len);\n \/**\n * @brief Turn on a bit in buffer\n * @param bitoffset bit in buffer to turn on\n * @param datastr Character value to set bit - can be \"0\", \"1\", \"X\"\n *\/\n void setBit(int bitoffset, const char* datastr); \/\/ data can be 0,1,'x','X' \n \/**\n * @brief Set a word of data in buffer\n * @param wordoffset Offset of word to set\n * @param value 32 bits of data to put into word\n *\/\n void setWord(int wordoffset, uint32_t value);\n\n \/**\n * @brief Fetch a word from ecmdDataBuffer\n * @param wordoffset Offset of word to fetch\n * @retval Value of word requested\n *\/\n uint32_t getWord(int wordoffset);\n\n \/**\n * @brief Clear a bit in buffer\n * @param bit Bit in buffer to turn off\n *\/\n void clearBit(int bit);\n \/**\n * @brief Clear multiple bits in buffer\n * @param bit Start bit in buffer to turn off\n * @param len Number of consecutive bits from start bit to off\n *\/\n void clearBit(int bit, int len);\n\n \/**\n * @brief Invert bit\n * @param bit Bit in buffer to invert\n *\/\n void flipBit(int bit);\n \/**\n * @brief Invert multiple bits\n * @param bit Start bit in buffer to invert\n * @param len Number of consecutive bits to invert\n *\/\n void flipBit(int bit, int len);\n\n \/**\n * @brief Test if bit is set\n * @param bit Bit to test\n * @retval 1 if bit is set - 0 if bit is clear\n *\/\n int isBitSet(int bit);\n \/**\n * @brief Test if multiple bits are set\n * @param bit Start bit to test\n * @param len Number of consecutive bits to test\n * @retval 1 if bit is set - 0 if bit is clear\n *\/\n int isBitSet(int bit, int len);\n \/**\n * @brief Test if bit is clear\n * @param bit Bit to test\n * @retval 1 if bit is clear - 0 if bit is set\n *\/\n int isBitClear(int bit);\n \/**\n * @brief Test if multiple bits are clear\n * @param bit Start bit to test\n * @param len Number of consecutive bits to test\n * @retval 1 if bit is clear - 0 if bit is set\n *\/\n int isBitClear(int bit, int len);\n \/**\n * @brief Count number of bits set in a range\n * @param bit Start bit to test\n * @param len Number of consecutive bits to test\n * @retval Number of bits set in range\n *\/ \n int getNumBitsSet(int bit, int len);\n \/\/@}\n\n\n \/** @name Buffer Manipulation Functions *\/\n \/\/@{\n \/**\n * @brief Shift data to right\n * @param shiftnum Number of bits to shift\n * @post Bits in buffer are shifted to right by specified number of bits - data is shifted off the end\n *\/\n void shiftRight(int shiftnum);\n \/**\n * @brief Shift data to left\n * @param shiftnum Number of bits to shift\n * @post Bits in buffer are shifted to left by specified number of bits - data is shifted off the beginning\n *\/\n void shiftLeft(int shiftnum);\n \/**\n * @brief Rotate data to right\n * @param rotatenum Number of bits to rotate\n * @post Bits in buffer are rotated to the right by specified number of bits - data is rotated to the beginning\n *\/\n void rotateRight(int rotatenum);\n \/**\n * @brief Rotate data to left\n * @param rotatenum Number of bits to rotate\n * @post Bits in buffer are rotated to the left by specified number of bits - data is rotated to the end\n *\/\n void rotateLeft(int rotatenum);\n\n \/**\n * @brief Clear entire buffer to 0's\n *\/\n void flushTo0();\n \/**\n * @brief Set entire buffer to 1's\n *\/\n void flushTo1();\n \/**\n * @brief Invert entire buffer\n *\/\n void invert(); \/* Performs bit inversion on entire DataBuffer class *\/\n\n \/**\n * @brief Insert part of another DataBuffer into this one\n * @param bufferIn DataBuffer to copy data from - data is taken left aligned\n * @param start Start bit to insert to\n * @param len Length of bits to insert\n * @post Data is copied from bufferIn to this DataBuffer in specified location\n *\/\n void insert(ecmdDataBuffer & bufferIn, int start, int len);\n \/**\n * @brief Insert a uint32_t array into this DataBuffer\n * @param datain uint32_t array to copy into this DataBuffer - data is taken left aligned\n * @param start Start bit to insert into\n * @param len Length of bits to insert\n * @post Data is copied from datain into this DataBuffer at specified location\n *\/\n void insert(uint32_t * datain, int start, int len);\n \/**\n * @brief Insert a uint32_t into the DataBuffer\n * @param datain uint32_t value to copy into DataBuffer - data is taken left aligned\n * @param start Start bit to insert into\n * @param len Length of bits to insert (must be <= 32)\n * @post Data is copied from datain into this DataBuffer at specified location\n *\/\n void insert(uint32_t datain, int start, int len);\n \/**\n * @brief Copy data from this DataBuffer into another\n * @param bufferOut DataBuffer to copy into - data is placed left aligned\n * @param start Start bit of data to copy\n * @param len Length of consecutive bits to copy\n * @post Data is copied from specified location in this DataBuffer to bufferOut\n *\/\n void extract(ecmdDataBuffer & bufferOut, int start, int len);\n \/**\n * @brief Copy data from this DataBuffer into another\n * @param outdata uint32_t buffer to copy into - data is placed left aligned - must be pre-allocated\n * @param start Start bit of data to copy\n * @param len Length of consecutive bits to copy\n * @post Data is copied from specified location in this DataBuffer to outdata\n *\/\n void extract(uint32_t * outdata, int start, int len);\n\n \/* these functions OR the datain into the DataBuffer buffer *\/\n \/**\n * @brief OR data into DataBuffer\n * @param bufferIn DataBuffer to OR data from - data is taken left aligned\n * @param startbit Start bit to OR to\n * @param len Length of bits to OR\n * @post Data is ORed from bufferIn to this DataBuffer in specified location\n *\/\n void setOr(ecmdDataBuffer & bufferIn, int startbit, int len);\n \/**\n * @brief OR data into DataBuffer\n * @param datain uint32_t buffer to OR data from - data is taken left aligned\n * @param startbit Start bit to OR to\n * @param len Length of bits to OR\n * @post Data is ORed from datain to this DataBuffer in specified location\n *\/\n void setOr(uint32_t * datain, int startbit, int len);\n \/**\n * @brief OR data into DataBuffer\n * @param datain uint32_t to OR data from - data is taken left aligned\n * @param startbit Start bit to OR to\n * @param len Length of bits to OR (must be <= 32)\n * @post Data is ORed from datain to this DataBuffer in specified location\n *\/\n void setOr(uint32_t datain, int startbit, int len);\n \/**\n * @brief OR data into DataBuffer\n * @param bufferIn DataBuffer to OR data from - data is taken left aligned\n * @post Entire data is ORed from bufferIn to this DataBuffer\n *\/\n void merge(ecmdDataBuffer & bufferIn); \/\/ does a setor on the whole buffer\n\n \/* these functions AND the datain into the DataBuffer buffer *\/\n \/**\n * @brief AND data into DataBuffer\n * @param bufferIn Bitvector to AND data from - data is taken left aligned\n * @param startbit Start bit to AND to\n * @param len Length of bits to AND\n * @post Data is ANDed from bufferIn to this DataBuffer in specified location\n *\/\n void setAnd(ecmdDataBuffer & bufferIn, int startbit, int len);\n \/**\n * @brief AND data into DataBuffer\n * @param datain uint32_t buffer to AND data from - data is taken left aligned\n * @param startbit Start bit to AND to\n * @param len Length of bits to AND\n * @post Data is ANDed from datain to this DataBuffer in specified location\n *\/\n void setAnd(uint32_t *datain, int startbit, int len);\n \/**\n * @brief AND data into DataBuffer\n * @param datain uint32_t to AND data from - data is taken left aligned\n * @param startbit Start bit to AND to\n * @param len Length of bits to AND (must be <= 32)\n * @post Data is ANDed from datain to this DataBuffer in specified location\n *\/\n void setAnd(uint32_t datain, int startbit, int len);\n\n \/**\n * @brief Copy entire contents of this ecmdDataBuffer into newcopy \n * @param copyBuffer DataBuffer to copy data into\n * @post copyBuffer is an exact duplicate of this DataBuffer\n *\/\n void copy(ecmdDataBuffer & copyBuffer); \/\/ Copies data into other\n\n \/* These are only to be used to apply a buffer to the entire ecmdDataBuffer, not just sections *\/\n \/**\n * @brief Copy buffer into this ecmdDataBuffer\n * @param buf Buffer to copy from\n * @param bytes Byte length to copy\n *\/\n void memCopyIn(uint32_t* buf, int bytes); \/* Does a memcpy from supplied buffer into ecmdDataBuffer *\/\n \/**\n * @brief Copy DataBuffer into supplied uint32_t buffer\n * @param buf Buffer to copy into - must be pre-allocated\n * @param bytes Byte length to copy\n *\/\n void memCopyOut(uint32_t* buf, int bytes); \/* Does a memcpy from ecmdDataBuffer into supplied buffer *\/\n\n \/\/@}\n\n\n \/** @name Parity Functions *\/\n \/\/@{\n \/**\n * @brief Generate odd parity over a range of bits\n * @param start Start bit of range\n * @param stop Stop bit of range\n * @retval 0 or 1 depending on parity of range\n *\/\n int oddParity(int start, int stop);\n \/**\n * @brief Generate even parity over a range of bits\n * @param start Start bit of range\n * @param stop Stop bit of range\n * @retval 0 or 1 depending on parity of range\n *\/\n int evenParity(int start, int stop);\n \/**\n * @brief Generate odd parity over a range of bits and insert into DataBuffer\n * @param start Start bit of range\n * @param stop Stop bit of range\n * @param insertpos Bit position to insert parity\n * @retval 0 on success - nonzero on failure\n *\/\n int oddParity(int start, int stop, int insertpos); \n \/**\n * @brief Generate even parity over a range of bits and insert into DataBuffer\n * @param start Start bit of range\n * @param stop Stop bit of range\n * @param insertpos Bit position to insert parity\n * @retval 0 on success - nonzero on failure\n *\/\n int evenParity(int start, int stop, int insertpos); \n \/\/@}\n\n\n \/** @name Buffer Character Conversion Functions *\/\n \/\/@{\n \/**\n * @brief Return Data as a hex left aligned char string\n * @param start Start bit of data to convert\n * @param bitlen Number of consecutive bits to convert\n * @retval String containing requested data\n *\/\n const char* genHexLeftStr(int start, int bitlen);\n \/**\n * @brief Return Data as a hex right aligned char string\n * @param start Start bit of data to convert\n * @param bitlen Number of consecutive bits to convert\n * @retval String containing requested data\n *\/\n const char* genHexRightStr(int start, int bitlen); \n \/**\n * @brief Return Data as a binary char string\n * @param start Start bit of data to convert\n * @param bitlen Number of consecutive bits to convert\n * @retval String containing requested data\n *\/\n const char* genBinStr(int start, int bitlen); \n \/**\n * @brief Return entire buffer as a hex left aligned char string\n * @retval String containing requested data\n *\/\n const char* genHexLeftStr();\n \/**\n * @brief Return entire buffer as a hex right aligned char string\n * @retval String containing requested data\n *\/\n const char* genHexRightStr(); \n \/**\n * @brief Return entire buffer as a binary char string\n * @retval String containing requested data\n *\/\n const char* genBinStr();\n \/\/@}\n\n \/** @name Simulation Buffer Functions *\/\n \/\/@{\n \/**\n * @brief Check Entire buffer for any X-state values\n * @retval 1 if xstate found 0 if none\n *\/\n int isXstate(); \/* check the whole DataBuffer *\/\n \/**\n * @brief Check section buffer for any X-state values\n * @param start Start bit to test\n * @param length Number of consecutive bits to test\n * @retval 1 if xstate found 0 if none\n *\/\n int isXstate(int start, int length); \/* check subset *\/\n\n \/\/@}\n\n \/** @name Error Functions *\/\n \/\/@{\n int getError() const { return err; } \/* return > 0 if error *\/\n char* getErrorStr() { return errstr; }\n void setErrorMode(int mode) { errmode = mode; }\n \/* mode & 0x1 : store in errstr *\/\n \/* mode & 0x2 : print to stdout *\/\n \/* mode & 0x4 : print to stderr *\/\n \/\/@}\n\n\n private:\n int numwords;\n int numbits;\n uint32_t * data;\n uint32_t * real_data;\n char* dataoutstr; \/* buffer for gethexlstr functions *\/\n char* datastr; \/* binary or x data *\/\n void filldatastr(char fillchar);\n char* errstr;\n int err;\n int errmode;\n void seterr(int errcode, const char* str); \n\n ecmdDataBuffer(const ecmdDataBuffer &other);\n \n\n\n};\n\n\n#endif \/* ecmdDataBuffer_H *\/\n\n \n<|endoftext|>"} {"text":"#ifndef STAN_MATH_OPENCL_KERNELS_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP\n#define STAN_MATH_OPENCL_KERNELS_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP\n#ifdef STAN_OPENCL\n\n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* neg_binomial_2_log_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n\n \/**\n * GPU implementation of Generalized Linear Model (GLM)\n * with Negative-Binomial-2 distribution and log link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[out] logp_global partially summed log probabilty (1 value per work\n * group)\n * @param[out] theta_derivative_global intermediate variable used in the model\n * @param[out] theta_derivative_sum partially summed theta_derivative_global\n * (1 value per work group)\n * @param[out] phi_derivative_global derivative with respect to phi\n * @param[in] y_global failures count vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param[in] phi_global (vector of) precision parameter(s)\n * @param N number of cases\n * @param M number of attributes\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param is_phi_vector 0 or 1 - whether phi is a vector (alternatively it\n * is a scalar)\n * @param need_theta_derivative whether theta_derivative needs to be\n * computed\n * @param need_theta_derivative_sum whether theta_derivative_sum needs to be\n * computed\n * @param need_phi_derivative whether phi_derivative needs to be computed\n * @param need_phi_derivative_sum whether phi_derivative_sum needs to be\n * computed\n * @param need_logp1 interpreted as boolean - whether first part logp_global\n * needs to be computed\n * @param need_logp2 interpreted as boolean - whether second part logp_global\n * needs to be computed\n * @param need_logp3 interpreted as boolean - whether third part logp_global\n * needs to be computed\n * @param need_logp4 interpreted as boolean - whether fourth part logp_global\n * needs to be computed\n * @param need_logp5 interpreted as boolean - whether fifth part logp_global\n * needs to be computed\n *\/\n __kernel void neg_binomial_2_log_glm(\n __global double* logp_global, __global double* theta_derivative_global,\n __global double* theta_derivative_sum,\n __global double* phi_derivative_global, const __global int* y_global,\n const __global double* x, const __global double* alpha,\n const __global double* beta, const __global double* phi_global,\n const int N, const int M, const int is_alpha_vector,\n const int is_phi_vector, const int need_theta_derivative,\n const int need_theta_derivative_sum, const int need_phi_derivative,\n const int need_phi_derivative_sum, const int need_logp1,\n const int need_logp2, const int need_logp3, const int need_logp4,\n const int need_logp5) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wgid = get_group_id(0);\n\n __local double res_loc[LOCAL_SIZE_];\n double logp = 0;\n double phi_derivative = 0;\n double theta_derivative = 0;\n\n \/\/ Most calculations only happen for relevant data within next if.\n \/\/ Exceptions are reductions between threads that need barriers.\n if (gid < N) {\n double theta = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n theta += x[j + gid] * beta[i];\n }\n double phi = phi_global[gid * is_phi_vector];\n double y = y_global[gid];\n if (!isfinite(theta) || y < 0 || !isfinite(phi)) {\n logp = NAN;\n }\n theta += alpha[gid * is_alpha_vector];\n double log_phi = log(phi);\n double logsumexp_theta_logphi;\n if (theta > log_phi) {\n logsumexp_theta_logphi = theta + log1p(exp(log_phi - theta));\n } else {\n logsumexp_theta_logphi = log_phi + log1p(exp(theta - log_phi));\n }\n double y_plus_phi = y + phi;\n if (need_logp1) {\n logp -= lgamma(y + 1);\n }\n if (need_logp2) {\n logp -= lgamma(phi);\n if (phi != 0) {\n logp += phi * log(phi);\n }\n }\n if (need_logp3) {\n logp -= y_plus_phi * logsumexp_theta_logphi;\n }\n if (need_logp4) {\n logp += y * theta;\n }\n if (need_logp5) {\n logp += lgamma(y_plus_phi);\n }\n double theta_exp = exp(theta);\n theta_derivative = y - theta_exp * y_plus_phi \/ (theta_exp + phi);\n if (need_theta_derivative) {\n theta_derivative_global[gid] = theta_derivative;\n }\n if (need_phi_derivative) {\n phi_derivative = 1 - y_plus_phi \/ (theta_exp + phi) + log_phi\n - logsumexp_theta_logphi + digamma(y_plus_phi)\n - digamma(phi);\n if (!need_phi_derivative_sum) {\n phi_derivative_global[gid] = phi_derivative;\n }\n }\n }\n\n \/\/ Sum logp, calculated by different threads.\n \/\/ Since we can't sum between different work groups, we emit one number\n \/\/ per work group. These must be summed on CPU for final result.\n res_loc[lid] = logp;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n logp_global[wgid] = res_loc[0];\n }\n\n if (need_theta_derivative_sum) {\n \/\/ Sum theta_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = theta_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n theta_derivative_sum[wgid] = res_loc[0];\n }\n }\n\n if (need_phi_derivative_sum) {\n \/\/ Sum phi_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = phi_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n phi_derivative_global[wgid] = res_loc[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/subtract.hpp subtract() \\endlink\n *\/\nconst kernel_cl\n neg_binomial_2_log_glm(\"neg_binomial_2_log_glm\",\n {digamma_device_function,\n neg_binomial_2_log_glm_kernel_code},\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n[Jenkins] auto-formatting by clang-format version 5.0.0-3~16.04.1 (tags\/RELEASE_500\/final)#ifndef STAN_MATH_OPENCL_KERNELS_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP\n#define STAN_MATH_OPENCL_KERNELS_NEG_BINOMIAL_2_LOG_GLM_LPMF_HPP\n#ifdef STAN_OPENCL\n\n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace opencl_kernels {\n\n\/\/ \\cond\nstatic const char* neg_binomial_2_log_glm_kernel_code = STRINGIFY(\n \/\/ \\endcond\n\n \/**\n * GPU implementation of Generalized Linear Model (GLM)\n * with Negative-Binomial-2 distribution and log link function.\n *\n * Must be run with at least N threads and local size equal to LOCAL_SIZE_.\n * @param[out] logp_global partially summed log probabilty (1 value per work\n * group)\n * @param[out] theta_derivative_global intermediate variable used in the\n * model\n * @param[out] theta_derivative_sum partially summed theta_derivative_global\n * (1 value per work group)\n * @param[out] phi_derivative_global derivative with respect to phi\n * @param[in] y_global failures count vector parameter\n * @param[in] x design matrix\n * @param[in] alpha intercept (in log odds)\n * @param[in] beta weight vector\n * @param[in] phi_global (vector of) precision parameter(s)\n * @param N number of cases\n * @param M number of attributes\n * @param is_alpha_vector 0 or 1 - whether alpha is a vector (alternatively\n * it is a scalar)\n * @param is_phi_vector 0 or 1 - whether phi is a vector (alternatively it\n * is a scalar)\n * @param need_theta_derivative whether theta_derivative needs to be\n * computed\n * @param need_theta_derivative_sum whether theta_derivative_sum needs to be\n * computed\n * @param need_phi_derivative whether phi_derivative needs to be computed\n * @param need_phi_derivative_sum whether phi_derivative_sum needs to be\n * computed\n * @param need_logp1 interpreted as boolean - whether first part logp_global\n * needs to be computed\n * @param need_logp2 interpreted as boolean - whether second part\n * logp_global needs to be computed\n * @param need_logp3 interpreted as boolean - whether third part logp_global\n * needs to be computed\n * @param need_logp4 interpreted as boolean - whether fourth part\n * logp_global needs to be computed\n * @param need_logp5 interpreted as boolean - whether fifth part logp_global\n * needs to be computed\n *\/\n __kernel void neg_binomial_2_log_glm(\n __global double* logp_global, __global double* theta_derivative_global,\n __global double* theta_derivative_sum,\n __global double* phi_derivative_global, const __global int* y_global,\n const __global double* x, const __global double* alpha,\n const __global double* beta, const __global double* phi_global,\n const int N, const int M, const int is_alpha_vector,\n const int is_phi_vector, const int need_theta_derivative,\n const int need_theta_derivative_sum, const int need_phi_derivative,\n const int need_phi_derivative_sum, const int need_logp1,\n const int need_logp2, const int need_logp3, const int need_logp4,\n const int need_logp5) {\n const int gid = get_global_id(0);\n const int lid = get_local_id(0);\n const int lsize = get_local_size(0);\n const int wgid = get_group_id(0);\n\n __local double res_loc[LOCAL_SIZE_];\n double logp = 0;\n double phi_derivative = 0;\n double theta_derivative = 0;\n\n \/\/ Most calculations only happen for relevant data within next if.\n \/\/ Exceptions are reductions between threads that need barriers.\n if (gid < N) {\n double theta = 0;\n for (int i = 0, j = 0; i < M; i++, j += N) {\n theta += x[j + gid] * beta[i];\n }\n double phi = phi_global[gid * is_phi_vector];\n double y = y_global[gid];\n if (!isfinite(theta) || y < 0 || !isfinite(phi)) {\n logp = NAN;\n }\n theta += alpha[gid * is_alpha_vector];\n double log_phi = log(phi);\n double logsumexp_theta_logphi;\n if (theta > log_phi) {\n logsumexp_theta_logphi = theta + log1p(exp(log_phi - theta));\n } else {\n logsumexp_theta_logphi = log_phi + log1p(exp(theta - log_phi));\n }\n double y_plus_phi = y + phi;\n if (need_logp1) {\n logp -= lgamma(y + 1);\n }\n if (need_logp2) {\n logp -= lgamma(phi);\n if (phi != 0) {\n logp += phi * log(phi);\n }\n }\n if (need_logp3) {\n logp -= y_plus_phi * logsumexp_theta_logphi;\n }\n if (need_logp4) {\n logp += y * theta;\n }\n if (need_logp5) {\n logp += lgamma(y_plus_phi);\n }\n double theta_exp = exp(theta);\n theta_derivative = y - theta_exp * y_plus_phi \/ (theta_exp + phi);\n if (need_theta_derivative) {\n theta_derivative_global[gid] = theta_derivative;\n }\n if (need_phi_derivative) {\n phi_derivative = 1 - y_plus_phi \/ (theta_exp + phi) + log_phi\n - logsumexp_theta_logphi + digamma(y_plus_phi)\n - digamma(phi);\n if (!need_phi_derivative_sum) {\n phi_derivative_global[gid] = phi_derivative;\n }\n }\n }\n\n \/\/ Sum logp, calculated by different threads.\n \/\/ Since we can't sum between different work groups, we emit one number\n \/\/ per work group. These must be summed on CPU for final result.\n res_loc[lid] = logp;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n logp_global[wgid] = res_loc[0];\n }\n\n if (need_theta_derivative_sum) {\n \/\/ Sum theta_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = theta_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n theta_derivative_sum[wgid] = res_loc[0];\n }\n }\n\n if (need_phi_derivative_sum) {\n \/\/ Sum phi_derivative, calculated by different threads.\n barrier(CLK_LOCAL_MEM_FENCE);\n res_loc[lid] = phi_derivative;\n barrier(CLK_LOCAL_MEM_FENCE);\n for (int step = lsize \/ REDUCTION_STEP_SIZE; step > 0;\n step \/= REDUCTION_STEP_SIZE) {\n if (lid < step) {\n for (int i = 1; i < REDUCTION_STEP_SIZE; i++) {\n res_loc[lid] += res_loc[lid + step * i];\n }\n }\n barrier(CLK_LOCAL_MEM_FENCE);\n }\n if (lid == 0) {\n phi_derivative_global[wgid] = res_loc[0];\n }\n }\n }\n \/\/ \\cond\n);\n\/\/ \\endcond\n\n\/**\n * See the docs for \\link kernels\/subtract.hpp subtract() \\endlink\n *\/\nconst kernel_cl\n neg_binomial_2_log_glm(\"neg_binomial_2_log_glm\",\n {digamma_device_function,\n neg_binomial_2_log_glm_kernel_code},\n {{\"REDUCTION_STEP_SIZE\", 4}, {\"LOCAL_SIZE_\", 64}});\n\n} \/\/ namespace opencl_kernels\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n#endif\n<|endoftext|>"} {"text":"#include \n#include \"Values.h\"\n#include \"lvalue.h\"\n\n#include \n\nusing namespace std;\n\ntemplate static shared_ptr reboxArray(jl_value_t *jlarray)\n{\n shared_ptr value;\n V *p = (V*)jl_array_data(jlarray);\n int ndims = jl_array_ndims(jlarray);\n vector dims;\n\n\n for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));\n\n nj::Array *array = new nj::Array(dims);\n \nprintf(\"In rebox array: dim = %lu\\n\",dims.size());\n\n value.reset(array);\n memcpy(array->ptr(),p,array->size()*sizeof(V));\n return value;\n}\n\nstatic shared_ptr getArrayValue(jl_value_t *jlarray)\n{\n shared_ptr value;\n jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));\n\nprintf(\"In getArray Value\\n\");\n \n if(jl_is_int64(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int32(elementType)) value = reboxArray(jlarray);\n else if(jl_is_float64(elementType)) value = reboxArray(jlarray); \n else if(jl_is_float32(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint64(elementType)) value = reboxArray(jlarray); \n else if(jl_is_uint32(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int8(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int16(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint8(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint16(elementType)) value = reboxArray(jlarray);\n\n return value;\n}\n\nvector> nj::lvalue(jl_value_t *jlvalue)\n{\n vector> res;\n\n if(jl_is_null(jlvalue))\n {\n shared_ptr value(new nj::Null);\n res.push_back(value);\n }\n else if(jl_is_array(jlvalue))\n {\n res.push_back(getArrayValue(jlvalue));\n }\n else\n { \n shared_ptr value;\n\n if(jl_is_int64(jlvalue)) value.reset(new nj::Int64(jl_unbox_int64(jlvalue)));\n else if(jl_is_int32(jlvalue)) value.reset(new nj::Int32(jl_unbox_int32(jlvalue)));\n else if(jl_is_float64(jlvalue)) value.reset(new nj::Float64(jl_unbox_float64(jlvalue)));\n else if(jl_is_float32(jlvalue)) value.reset(new nj::Float32(jl_unbox_float32(jlvalue)));\n else if(jl_is_uint64(jlvalue)) value.reset(new nj::UInt64(jl_unbox_uint64(jlvalue)));\n else if(jl_is_uint32(jlvalue)) value.reset(new nj::UInt32(jl_unbox_uint32(jlvalue)));\n else if(jl_is_int8(jlvalue)) value.reset(new nj::Char(jl_unbox_int8(jlvalue)));\n else if(jl_is_int16(jlvalue)) value.reset(new nj::Int16(jl_unbox_int16(jlvalue)));\n else if(jl_is_uint8(jlvalue)) value.reset(new nj::UChar(jl_unbox_uint8(jlvalue)));\n else if(jl_is_uint16(jlvalue)) value.reset(new nj::UInt16(jl_unbox_uint16(jlvalue)));\n else if(jl_is_ascii_string(jlvalue)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jlvalue)));\n\n if(value.get()) res.push_back(value);\n }\n return res;\n}\nMore debugging Changed check for array element type#include \n#include \"Values.h\"\n#include \"lvalue.h\"\n\n#include \n\nusing namespace std;\n\ntemplate static shared_ptr reboxArray(jl_value_t *jlarray)\n{\n shared_ptr value;\n V *p = (V*)jl_array_data(jlarray);\n int ndims = jl_array_ndims(jlarray);\n vector dims;\n\n\n for(int dim = 0;dim < ndims;dim++) dims.push_back(jl_array_dim(jlarray,dim));\n\n nj::Array *array = new nj::Array(dims);\n \nprintf(\"In rebox array: dim = %lu\\n\",dims.size());\n\n value.reset(array);\n memcpy(array->ptr(),p,array->size()*sizeof(V));\n return value;\n}\n\nstatic shared_ptr getArrayValue(jl_value_t *jlarray)\n{\n shared_ptr value;\n jl_value_t *elementType = jl_tparam0(jl_typeof(jlarray));\n\nprintf(\"In getArray Value\\n\");\n \n if(jl_is_int64(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int32(elementType)) value = reboxArray(jlarray);\n else if(elementType == (jl_value_t*)jl_float64_type) value = reboxArray(jlarray); \n else if(jl_is_float32(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint64(elementType)) value = reboxArray(jlarray); \n else if(jl_is_uint32(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int8(elementType)) value = reboxArray(jlarray);\n else if(jl_is_int16(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint8(elementType)) value = reboxArray(jlarray);\n else if(jl_is_uint16(elementType)) value = reboxArray(jlarray);\n\n return value;\n}\n\nvector> nj::lvalue(jl_value_t *jlvalue)\n{\n vector> res;\n\n if(jl_is_null(jlvalue))\n {\n shared_ptr value(new nj::Null);\n res.push_back(value);\n }\n else if(jl_is_array(jlvalue))\n {\n res.push_back(getArrayValue(jlvalue));\n }\n else\n { \n shared_ptr value;\n\n if(jl_is_int64(jlvalue)) value.reset(new nj::Int64(jl_unbox_int64(jlvalue)));\n else if(jl_is_int32(jlvalue)) value.reset(new nj::Int32(jl_unbox_int32(jlvalue)));\n else if(jl_is_float64(jlvalue)) value.reset(new nj::Float64(jl_unbox_float64(jlvalue)));\n else if(jl_is_float32(jlvalue)) value.reset(new nj::Float32(jl_unbox_float32(jlvalue)));\n else if(jl_is_uint64(jlvalue)) value.reset(new nj::UInt64(jl_unbox_uint64(jlvalue)));\n else if(jl_is_uint32(jlvalue)) value.reset(new nj::UInt32(jl_unbox_uint32(jlvalue)));\n else if(jl_is_int8(jlvalue)) value.reset(new nj::Char(jl_unbox_int8(jlvalue)));\n else if(jl_is_int16(jlvalue)) value.reset(new nj::Int16(jl_unbox_int16(jlvalue)));\n else if(jl_is_uint8(jlvalue)) value.reset(new nj::UChar(jl_unbox_uint8(jlvalue)));\n else if(jl_is_uint16(jlvalue)) value.reset(new nj::UInt16(jl_unbox_uint16(jlvalue)));\n else if(jl_is_ascii_string(jlvalue)) value.reset(new nj::String((char*)jl_unbox_voidpointer(jlvalue)));\n\n if(value.get()) res.push_back(value);\n }\n return res;\n}\n<|endoftext|>"} {"text":"\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include \"packet\/frame.h\"\n\n#include \"gitsha1.h\"\n#include \"angle.h\"\n#include \"blink.h\"\n#include \"simplebicycle.h\"\n#include \"usbconfig.h\"\n#include \"saconfig.h\"\n\n#include \"parameters.h\"\n\n#include \n\nnamespace {\n \/* sensors *\/\n Analog analog;\n Encoder encoder(sa::RLS_ENC, sa::RLS_ENC_INDEX_CFG);\n\n struct __attribute__((__packed__)) pose_t {\n float x; \/* m *\/\n float y; \/* m *\/\n float pitch; \/* rad *\/\n float yaw; \/* rad *\/\n float roll; \/* rad *\/\n float steer; \/* rad *\/\n float v; \/* m\/s * Wheel angle and radius are not considered here.\n * Computation must occur during visualization *\/\n uint8_t timestamp; \/* Converted from system ticks to milliseconds\n * and contains only the least significant bits *\/\n }; \/* 29 bytes *\/\n\n pose_t pose = {};\n\n using namespace packet::frame;\n std::array packet_buffer;\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initialize a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activate the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the blink thread and print state monitor *\/\n chBlinkThreadCreateStatic();\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000); \/* trigger ADC conversion at 1 kHz *\/\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n * The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS\n * and must be changed to use as analog output.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(sa::KOLLM_DAC, sa::KOLLM_DAC_CFG);\n\n \/*\n * Initialize bicycle with default parameters, dt = 0.005 s, v = 5 m\/s.\n *\/\n model::SimpleBicycle bicycle;\n\n \/* transmit git sha information, block until receiver is ready *\/\n uint8_t bytes_written = packet::frame::stuff(g_GITSHA1, packet_buffer.data(), 7);\n while ((SDU1.config->usbp->state != USB_ACTIVE) || (SDU1.state != SDU_READY)) {\n chThdSleepMilliseconds(10);\n }\n streamWrite(&SDU1, packet_buffer.data(), bytes_written);\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n while (true) {\n systime_t starttime = chVTGetSystemTime();\n\n constexpr float roll_torque = 0.0f;\n\n \/* get sensor measurements *\/\n float steer_torque = static_cast(analog.get_adc12()*2.0f*sa::MAX_KISTLER_TORQUE\/4096 -\n sa::MAX_KISTLER_TORQUE);\n float motor_torque = static_cast(\n analog.get_adc13()*2.0f*sa::MAX_KOLLMORGEN_TORQUE\/4096 -\n sa::MAX_KOLLMORGEN_TORQUE);\n float steer_angle = angle::encoder_count(encoder);\n\n (void)motor_torque; \/* remove build warning for unused variable *\/\n\n \/* yaw angle, just use previous state value *\/\n float yaw_angle = angle::wrap(bicycle.pose().yaw);\n\n \/* simulate bicycle *\/\n bicycle.update(roll_torque, steer_torque, yaw_angle, steer_angle);\n\n \/* generate an example torque output for testing *\/\n float feedback_torque = bicycle.handlebar_feedback_torque();\n dacsample_t aout = static_cast(\n (feedback_torque\/21.0f * 2048) + 2048); \/* reduce output to half of full range *\/\n dacPutChannelX(sa::KOLLM_DAC, 0, aout);\n\n pose = pose_t{}; \/* reset pose to zero *\/\n pose.x = bicycle.pose().x;\n pose.y = bicycle.pose().y;\n pose.pitch = angle::wrap(bicycle.pose().pitch);\n pose.yaw = angle::wrap(bicycle.pose().yaw);\n pose.roll = angle::wrap(bicycle.pose().roll);\n pose.steer = angle::wrap(bicycle.pose().steer);\n pose.v = bicycle.v();\n pose.timestamp = static_cast(ST2MS(chVTGetSystemTime()));\n \/*\n * Timing information\n * (replaced chVTGetSystemTIme() with chSysGetRealtimeCounterX() and two uint32_t timing related fields added to\n * pose_t)\n * - Debug mode with all ChibiOS debug configuration options enabled: computation ~3.1 ms, tx ~20 us\n * - Release mode: computation ~200 us, tx ~10 us\n *\n * TODO: Pose message should be transmitted asynchronously.\n * After starting transmission, the simulation should start to calculate pose for the next timestep.\n * This is currently not necessary given the observed timings.\n *\/\n bytes_written = packet::frame::stuff(&pose, packet_buffer.data(), sizeof(pose));\n streamWrite(&SDU1, packet_buffer.data(), bytes_written);\n\n systime_t dt = MS2ST(static_cast(1000*bicycle.dt()));\n systime_t sleeptime = dt + starttime - chVTGetSystemTime();\n if (sleeptime >= dt) {\n \/\/chDbgAssert(false, \"deadline missed\");\n continue;\n }\n chThdSleep(sleeptime);\n }\n}\nChange bicycle forward velocity to 3.0 m\/s\/*\n ChibiOS - Copyright (C) 2006..2015 Giovanni Di Sirio\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*\/\n\n#include \"ch.h\"\n#include \"hal.h\"\n\n#include \"analog.h\"\n#include \"encoder.h\"\n#include \"packet\/frame.h\"\n\n#include \"gitsha1.h\"\n#include \"angle.h\"\n#include \"blink.h\"\n#include \"simplebicycle.h\"\n#include \"usbconfig.h\"\n#include \"saconfig.h\"\n\n#include \"parameters.h\"\n\n#include \n\nnamespace {\n constexpr float v = 3.0;\n \/* sensors *\/\n Analog analog;\n Encoder encoder(sa::RLS_ENC, sa::RLS_ENC_INDEX_CFG);\n\n struct __attribute__((__packed__)) pose_t {\n float x; \/* m *\/\n float y; \/* m *\/\n float pitch; \/* rad *\/\n float yaw; \/* rad *\/\n float roll; \/* rad *\/\n float steer; \/* rad *\/\n float v; \/* m\/s * Wheel angle and radius are not considered here.\n * Computation must occur during visualization *\/\n uint8_t timestamp; \/* Converted from system ticks to milliseconds\n * and contains only the least significant bits *\/\n }; \/* 29 bytes *\/\n\n pose_t pose = {};\n\n using namespace packet::frame;\n std::array packet_buffer;\n} \/\/ namespace\n\n\/*\n * Application entry point.\n *\/\nint main(void) {\n\n \/*\n * System initializations.\n * - HAL initialization, this also initializes the configured device drivers\n * and performs the board-specific initializations.\n * - Kernel initialization, the main() function becomes a thread and the\n * RTOS is active.\n *\/\n halInit();\n chSysInit();\n\n \/*\n * Initialize a serial-over-USB CDC driver.\n *\/\n sduObjectInit(&SDU1);\n sduStart(&SDU1, &serusbcfg);\n\n \/*\n * Activate the USB driver and then the USB bus pull-up on D+.\n * Note, a delay is inserted in order to not have to disconnect the cable\n * after a reset.\n *\/\n board_usb_lld_disconnect_bus(); \/\/usbDisconnectBus(serusbcfg.usbp);\n chThdSleepMilliseconds(1500);\n usbStart(serusbcfg.usbp, &usbcfg);\n board_usb_lld_connect_bus(); \/\/usbConnectBus(serusbcfg.usbp);\n\n \/* create the blink thread and print state monitor *\/\n chBlinkThreadCreateStatic();\n\n \/*\n * Start sensors.\n * Encoder:\n * Initialize encoder driver 5 on pins PA0, PA1 (EXT2-4, EXT2-8).\n *\/\n palSetLineMode(LINE_TIM5_CH1, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n palSetLineMode(LINE_TIM5_CH2, PAL_MODE_ALTERNATE(2) | PAL_STM32_PUPDR_FLOATING);\n encoder.start();\n analog.start(1000); \/* trigger ADC conversion at 1 kHz *\/\n\n \/*\n * Set torque measurement enable line low.\n * The output of the Kistler torque sensor is not valid until after a falling edge\n * on the measurement line and it is held low. The 'LINE_TORQUE_MEAS_EN' line is\n * reversed due to NPN switch Q1.\n *\/\n palClearLine(LINE_TORQUE_MEAS_EN);\n chThdSleepMilliseconds(1);\n palSetLine(LINE_TORQUE_MEAS_EN);\n\n \/*\n * Start DAC1 driver and set output pin as analog as suggested in Reference Manual.\n * The default line configuration is OUTPUT_OPENDRAIN_PULLUP for SPI1_ENC1_NSS\n * and must be changed to use as analog output.\n *\/\n palSetLineMode(LINE_KOLLM_ACTL_TORQUE, PAL_MODE_INPUT_ANALOG);\n dacStart(sa::KOLLM_DAC, sa::KOLLM_DAC_CFG);\n\n \/*\n * Initialize bicycle with default parameters, dt = 0.005 s.\n *\/\n model::SimpleBicycle bicycle(v);\n\n \/* transmit git sha information, block until receiver is ready *\/\n uint8_t bytes_written = packet::frame::stuff(g_GITSHA1, packet_buffer.data(), 7);\n while ((SDU1.config->usbp->state != USB_ACTIVE) || (SDU1.state != SDU_READY)) {\n chThdSleepMilliseconds(10);\n }\n streamWrite(&SDU1, packet_buffer.data(), bytes_written);\n\n \/*\n * Normal main() thread activity, in this demo it simulates the bicycle\n * dynamics in real-time (roughly).\n *\/\n while (true) {\n systime_t starttime = chVTGetSystemTime();\n\n constexpr float roll_torque = 0.0f;\n\n \/* get sensor measurements *\/\n float steer_torque = static_cast(analog.get_adc12()*2.0f*sa::MAX_KISTLER_TORQUE\/4096 -\n sa::MAX_KISTLER_TORQUE);\n float motor_torque = static_cast(\n analog.get_adc13()*2.0f*sa::MAX_KOLLMORGEN_TORQUE\/4096 -\n sa::MAX_KOLLMORGEN_TORQUE);\n float steer_angle = angle::encoder_count(encoder);\n\n (void)motor_torque; \/* remove build warning for unused variable *\/\n\n \/* yaw angle, just use previous state value *\/\n float yaw_angle = angle::wrap(bicycle.pose().yaw);\n\n \/* simulate bicycle *\/\n bicycle.update(roll_torque, steer_torque, yaw_angle, steer_angle);\n\n \/* generate an example torque output for testing *\/\n float feedback_torque = bicycle.handlebar_feedback_torque();\n dacsample_t aout = static_cast(\n (feedback_torque\/21.0f * 2048) + 2048); \/* reduce output to half of full range *\/\n dacPutChannelX(sa::KOLLM_DAC, 0, aout);\n\n pose = pose_t{}; \/* reset pose to zero *\/\n pose.x = bicycle.pose().x;\n pose.y = bicycle.pose().y;\n pose.pitch = angle::wrap(bicycle.pose().pitch);\n pose.yaw = angle::wrap(bicycle.pose().yaw);\n pose.roll = angle::wrap(bicycle.pose().roll);\n pose.steer = angle::wrap(bicycle.pose().steer);\n pose.v = bicycle.v();\n pose.timestamp = static_cast(ST2MS(chVTGetSystemTime()));\n \/*\n * Timing information\n * (replaced chVTGetSystemTIme() with chSysGetRealtimeCounterX() and two uint32_t timing related fields added to\n * pose_t)\n * - Debug mode with all ChibiOS debug configuration options enabled: computation ~3.1 ms, tx ~20 us\n * - Release mode: computation ~200 us, tx ~10 us\n *\n * TODO: Pose message should be transmitted asynchronously.\n * After starting transmission, the simulation should start to calculate pose for the next timestep.\n * This is currently not necessary given the observed timings.\n *\/\n bytes_written = packet::frame::stuff(&pose, packet_buffer.data(), sizeof(pose));\n streamWrite(&SDU1, packet_buffer.data(), bytes_written);\n\n systime_t dt = MS2ST(static_cast(1000*bicycle.dt()));\n systime_t sleeptime = dt + starttime - chVTGetSystemTime();\n if (sleeptime >= dt) {\n \/\/chDbgAssert(false, \"deadline missed\");\n continue;\n }\n chThdSleep(sleeptime);\n }\n}\n<|endoftext|>"} {"text":"#include \n\nnamespace GDE\n{\n \nbool Log::initialized = false;\ntime_t Log::rawtime;\nstd::string Log::logFileName;\n\n void Log::init(){\n if(!initialized){\n logFileName = \"log.txt\";\n initialized = true;\n std::cout << \"Sistema de Log inicializado\" << std::endl;\n Log::info(\"init\", \"Sistema de Log inicializado\");\n }\n }\n\n void Log::info(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer[20];\n struct tm * timeinfo;\n timeinfo = localtime(&rawtime);\n strftime(buffer, 20, \"%d\/%m\/%y %X \", timeinfo);\n logFile << buffer << \"INFO: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n \n void Log::debug(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer [20];\n struct tm * timeinfo;\n timeinfo = localtime (&rawtime);\n strftime (buffer,20,\"%d\/%m\/%y %X \",timeinfo);\n logFile << buffer << \"DEBUG: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n \n void Log::error(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer [20];\n struct tm * timeinfo;\n timeinfo = localtime (&rawtime);\n strftime (buffer,20,\"%d\/%m\/%y %X \",timeinfo);\n logFile << buffer << \"ERROR: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n}\nFix de estilo#include \n\nnamespace GDE\n{\n \nbool Log::initialized = false;\ntime_t Log::rawtime;\nstd::string Log::logFileName;\n\n void Log::init(){\n if(!initialized)\n\t\t{\n logFileName = \"log.txt\";\n initialized = true;\n std::cout << \"Sistema de Log inicializado\" << std::endl;\n Log::info(\"init\", \"Sistema de Log inicializado\");\n }\n }\n\n void Log::info(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer[20];\n struct tm * timeinfo;\n timeinfo = localtime(&rawtime);\n strftime(buffer, 20, \"%d\/%m\/%y %X \", timeinfo);\n logFile << buffer << \"INFO: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n \n void Log::debug(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer [20];\n struct tm * timeinfo;\n timeinfo = localtime (&rawtime);\n strftime (buffer,20,\"%d\/%m\/%y %X \",timeinfo);\n logFile << buffer << \"DEBUG: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n \n void Log::error(std::string tag, std::string text)\n {\n if (!initialized)\n {\n std::cout << \"El sistema de log no ha sido inicializado, por favor, inicielo mediante GDE::Log::init()\" << std::endl;\n return;\n }\n std::ofstream logFile(logFileName.c_str(), std::ofstream::app);\n time (&rawtime);\n char buffer [20];\n struct tm * timeinfo;\n timeinfo = localtime (&rawtime);\n strftime (buffer,20,\"%d\/%m\/%y %X \",timeinfo);\n logFile << buffer << \"ERROR: \" << tag << \": \" << text << std::endl;\n logFile.close();\n }\n}\n<|endoftext|>"} {"text":"#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"GroupManager.h\"\n#include \"Group.h\"\n#include \"inifile\/iniFile.h\"\n#include \"ChatColor.h\"\n#include \"Root.h\"\n\n\n\n\n\ntypedef std::map< AString, cGroup* > GroupMap;\n\n\n\n\n\nstruct cGroupManager::sGroupManagerState\n{\n\tGroupMap Groups;\n};\n\n\n\n\n\ncGroupManager::~cGroupManager()\n{\n\tfor (GroupMap::iterator itr = m_pState->Groups.begin(); itr != m_pState->Groups.end(); ++itr)\n\t{\n\t\tdelete itr->second;\n\t\titr->second = NULL;\n\t}\n\tm_pState->Groups.clear();\n\n\tdelete m_pState;\n\tm_pState = NULL;\n}\n\n\n\n\n\ncGroupManager::cGroupManager()\n\t: m_pState( new sGroupManagerState)\n{\n\tLOGD(\"-- Loading Groups --\");\n\t\n\tif (!LoadGroups())\n\t{\n\t\tLOGWARNING(\"ERROR: Groups could not load!\");\n\t}\n\tif (!CheckUsers())\n\t{\n\t\tLOGWARNING(\"ERROR: User file could not be found!\");\n\t}\n\t\n\tLOGD(\"-- Groups Successfully Loaded --\");\n}\n\n\n\n\n\nvoid cGroupManager::GenerateDefaultUsersIni(cIniFile & a_IniFile)\n{\n\tLOGWARN(\"Regenerating users.ini, all users will be reset\");\n\ta_IniFile.AddHeaderComment(\" This file stores the players' groups.\");\n\ta_IniFile.AddHeaderComment(\" The format is:\");\n\ta_IniFile.AddHeaderComment(\" [PlayerName]\");\n\ta_IniFile.AddHeaderComment(\" Groups = GroupName1, GroupName2, ...\");\n\n\ta_IniFile.WriteFile(\"users.ini\");\n}\n\n\n\n\n\nbool cGroupManager::CheckUsers()\n{\n\tcIniFile IniFile;\n\tif (!IniFile.ReadFile(\"users.ini\"))\n\t{\n\t\tGenerateDefaultUsersIni(IniFile);\n\t\treturn true;\n\t}\n\t\n\tint NumKeys = IniFile.GetNumKeys();\n\tfor (int i = 0; i < NumKeys; i++)\n\t{\n\t\tAString Player = IniFile.GetKeyName(i);\n\t\tAString Groups = IniFile.GetValue(Player, \"Groups\", \"\");\n\t\tif (Groups.empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tAStringVector Split = StringSplitAndTrim(Groups, \",\");\n\t\tfor (AStringVector::const_iterator itr = Split.begin(), end = Split.end(); itr != end; ++itr)\n\t\t{\n\t\t\tif (!ExistsGroup(*itr))\n\t\t\t{\n\t\t\t\tLOGWARNING(\"The group %s for player %s was not found!\", Split[i].c_str(), Player.c_str());\n\t\t\t}\n\t\t} \/\/ for itr - Split[]\n\t} \/\/ for i - ini file keys\n\t\/\/ Always return true for now, just but we can handle writefile fails later.\n\treturn true;\n}\n\n\n\n\n\nbool cGroupManager::LoadGroups()\n{\n\tcIniFile IniFile;\n\tif (!IniFile.ReadFile(\"groups.ini\"))\n\t{\n\t\tLOGWARNING(\"Regenerating groups.ini, all groups will be reset\");\n\t\tIniFile.AddHeaderComment(\" This is the MCServer permissions manager groups file\");\n\t\tIniFile.AddHeaderComment(\" It stores all defined groups such as Administrators, Players, or Moderators\");\n\n\t\tIniFile.SetValue(\"Owner\", \"Permissions\", \"*\", true);\n\t\tIniFile.SetValue(\"Owner\", \"Color\", \"2\", true);\n\n\t\tIniFile.SetValue(\"Moderator\", \"Permissions\", \"core.time, core.item, core.tpa, core.tpaccept, core.ban, core.unban, core.save-all, core.toggledownfall\");\n\t\tIniFile.SetValue(\"Moderator\", \"Color\", \"2\", true);\n\t\tIniFile.SetValue(\"Moderator\", \"Inherits\", \"Player\", true);\n\n\t\tIniFile.SetValue(\"Player\", \"Permissions\", \"core.portal\", true);\n\t\tIniFile.SetValue(\"Player\", \"Color\", \"f\", true);\n\t\tIniFile.SetValue(\"Player\", \"Inherits\", \"Default\", true);\n\n\t\tIniFile.SetValue(\"Default\", \"Permissions\", \"core.help, core.plugins, core.spawn, core.worlds, core.back, core.motd, core.build, core.locate, core.viewdistance\", true);\n\t\tIniFile.SetValue(\"Default\", \"Color\", \"f\", true);\n\n\t\tIniFile.WriteFile(\"groups.ini\");\n\t}\n\n\tint NumKeys = IniFile.GetNumKeys();\n\tfor (int i = 0; i < NumKeys; i++)\n\t{\n\t\tAString KeyName = IniFile.GetKeyName(i);\n\t\tcGroup * Group = GetGroup(KeyName.c_str());\n\t\t\n\t\tGroup->ClearPermission(); \/\/ Needed in case the groups are reloaded.\n\n\t\tLOGD(\"Loading group %s\", KeyName.c_str());\n\n\t\tGroup->SetName(KeyName);\n\t\tAString Color = IniFile.GetValue(KeyName, \"Color\", \"-\");\n\t\tif ((Color != \"-\") && (Color.length() >= 1))\n\t\t{\n\t\t\tGroup->SetColor(cChatColor::Delimiter + AString(&Color[0]));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tGroup->SetColor(cChatColor::White);\n\t\t}\n\n\t\tAString Commands = IniFile.GetValue(KeyName, \"Commands\", \"\");\n\t\tif (!Commands.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Commands, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->AddCommand(Split[i]);\n\t\t\t}\n\t\t}\n\n\t\tAString Permissions = IniFile.GetValue(KeyName, \"Permissions\", \"\");\n\t\tif (!Permissions.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Permissions, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->AddPermission(Split[i]);\n\t\t\t}\n\t\t}\n\n\t\tAString Groups = IniFile.GetValue(KeyName, \"Inherits\", \"\");\n\t\tif (!Groups.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Groups, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->InheritFrom(GetGroup(Split[i].c_str()));\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Always return true, we can handle writefile fails later.\n\treturn true;\n}\n\n\n\n\n\nbool cGroupManager::ExistsGroup( const AString & a_Name)\n{\n\tGroupMap::iterator itr = m_pState->Groups.find( a_Name);\n\treturn ( itr != m_pState->Groups.end());\n}\n\n\n\n\n\ncGroup* cGroupManager::GetGroup( const AString & a_Name)\n{\n\tGroupMap::iterator itr = m_pState->Groups.find( a_Name);\n\tif (itr != m_pState->Groups.end())\n\t{\n\t\treturn itr->second;\n\t}\n\n\tcGroup* Group = new cGroup();\n\tm_pState->Groups[a_Name] = Group;\n\n\treturn Group;\n}\n\n\n\n\nUse AString(1, Color[0])#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"GroupManager.h\"\n#include \"Group.h\"\n#include \"inifile\/iniFile.h\"\n#include \"ChatColor.h\"\n#include \"Root.h\"\n\n\n\n\n\ntypedef std::map< AString, cGroup* > GroupMap;\n\n\n\n\n\nstruct cGroupManager::sGroupManagerState\n{\n\tGroupMap Groups;\n};\n\n\n\n\n\ncGroupManager::~cGroupManager()\n{\n\tfor (GroupMap::iterator itr = m_pState->Groups.begin(); itr != m_pState->Groups.end(); ++itr)\n\t{\n\t\tdelete itr->second;\n\t\titr->second = NULL;\n\t}\n\tm_pState->Groups.clear();\n\n\tdelete m_pState;\n\tm_pState = NULL;\n}\n\n\n\n\n\ncGroupManager::cGroupManager()\n\t: m_pState( new sGroupManagerState)\n{\n\tLOGD(\"-- Loading Groups --\");\n\t\n\tif (!LoadGroups())\n\t{\n\t\tLOGWARNING(\"ERROR: Groups could not load!\");\n\t}\n\tif (!CheckUsers())\n\t{\n\t\tLOGWARNING(\"ERROR: User file could not be found!\");\n\t}\n\t\n\tLOGD(\"-- Groups Successfully Loaded --\");\n}\n\n\n\n\n\nvoid cGroupManager::GenerateDefaultUsersIni(cIniFile & a_IniFile)\n{\n\tLOGWARN(\"Regenerating users.ini, all users will be reset\");\n\ta_IniFile.AddHeaderComment(\" This file stores the players' groups.\");\n\ta_IniFile.AddHeaderComment(\" The format is:\");\n\ta_IniFile.AddHeaderComment(\" [PlayerName]\");\n\ta_IniFile.AddHeaderComment(\" Groups = GroupName1, GroupName2, ...\");\n\n\ta_IniFile.WriteFile(\"users.ini\");\n}\n\n\n\n\n\nbool cGroupManager::CheckUsers()\n{\n\tcIniFile IniFile;\n\tif (!IniFile.ReadFile(\"users.ini\"))\n\t{\n\t\tGenerateDefaultUsersIni(IniFile);\n\t\treturn true;\n\t}\n\t\n\tint NumKeys = IniFile.GetNumKeys();\n\tfor (int i = 0; i < NumKeys; i++)\n\t{\n\t\tAString Player = IniFile.GetKeyName(i);\n\t\tAString Groups = IniFile.GetValue(Player, \"Groups\", \"\");\n\t\tif (Groups.empty())\n\t\t{\n\t\t\tcontinue;\n\t\t}\n\t\tAStringVector Split = StringSplitAndTrim(Groups, \",\");\n\t\tfor (AStringVector::const_iterator itr = Split.begin(), end = Split.end(); itr != end; ++itr)\n\t\t{\n\t\t\tif (!ExistsGroup(*itr))\n\t\t\t{\n\t\t\t\tLOGWARNING(\"The group %s for player %s was not found!\", Split[i].c_str(), Player.c_str());\n\t\t\t}\n\t\t} \/\/ for itr - Split[]\n\t} \/\/ for i - ini file keys\n\t\/\/ Always return true for now, just but we can handle writefile fails later.\n\treturn true;\n}\n\n\n\n\n\nbool cGroupManager::LoadGroups()\n{\n\tcIniFile IniFile;\n\tif (!IniFile.ReadFile(\"groups.ini\"))\n\t{\n\t\tLOGWARNING(\"Regenerating groups.ini, all groups will be reset\");\n\t\tIniFile.AddHeaderComment(\" This is the MCServer permissions manager groups file\");\n\t\tIniFile.AddHeaderComment(\" It stores all defined groups such as Administrators, Players, or Moderators\");\n\n\t\tIniFile.SetValue(\"Owner\", \"Permissions\", \"*\", true);\n\t\tIniFile.SetValue(\"Owner\", \"Color\", \"2\", true);\n\n\t\tIniFile.SetValue(\"Moderator\", \"Permissions\", \"core.time, core.item, core.tpa, core.tpaccept, core.ban, core.unban, core.save-all, core.toggledownfall\");\n\t\tIniFile.SetValue(\"Moderator\", \"Color\", \"2\", true);\n\t\tIniFile.SetValue(\"Moderator\", \"Inherits\", \"Player\", true);\n\n\t\tIniFile.SetValue(\"Player\", \"Permissions\", \"core.portal\", true);\n\t\tIniFile.SetValue(\"Player\", \"Color\", \"f\", true);\n\t\tIniFile.SetValue(\"Player\", \"Inherits\", \"Default\", true);\n\n\t\tIniFile.SetValue(\"Default\", \"Permissions\", \"core.help, core.plugins, core.spawn, core.worlds, core.back, core.motd, core.build, core.locate, core.viewdistance\", true);\n\t\tIniFile.SetValue(\"Default\", \"Color\", \"f\", true);\n\n\t\tIniFile.WriteFile(\"groups.ini\");\n\t}\n\n\tint NumKeys = IniFile.GetNumKeys();\n\tfor (int i = 0; i < NumKeys; i++)\n\t{\n\t\tAString KeyName = IniFile.GetKeyName(i);\n\t\tcGroup * Group = GetGroup(KeyName.c_str());\n\t\t\n\t\tGroup->ClearPermission(); \/\/ Needed in case the groups are reloaded.\n\n\t\tLOGD(\"Loading group %s\", KeyName.c_str());\n\n\t\tGroup->SetName(KeyName);\n\t\tAString Color = IniFile.GetValue(KeyName, \"Color\", \"-\");\n\t\tif ((Color != \"-\") && (Color.length() >= 1))\n\t\t{\n\t\t\tGroup->SetColor(cChatColor::Delimiter + AString(1, Color[0]));\n\t\t}\n\t\telse\n\t\t{\n\t\t\tGroup->SetColor(cChatColor::White);\n\t\t}\n\n\t\tAString Commands = IniFile.GetValue(KeyName, \"Commands\", \"\");\n\t\tif (!Commands.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Commands, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->AddCommand(Split[i]);\n\t\t\t}\n\t\t}\n\n\t\tAString Permissions = IniFile.GetValue(KeyName, \"Permissions\", \"\");\n\t\tif (!Permissions.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Permissions, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->AddPermission(Split[i]);\n\t\t\t}\n\t\t}\n\n\t\tAString Groups = IniFile.GetValue(KeyName, \"Inherits\", \"\");\n\t\tif (!Groups.empty())\n\t\t{\n\t\t\tAStringVector Split = StringSplitAndTrim(Groups, \",\");\n\t\t\tfor (size_t i = 0; i < Split.size(); i++)\n\t\t\t{\n\t\t\t\tGroup->InheritFrom(GetGroup(Split[i].c_str()));\n\t\t\t}\n\t\t}\n\t}\n\t\/\/ Always return true, we can handle writefile fails later.\n\treturn true;\n}\n\n\n\n\n\nbool cGroupManager::ExistsGroup( const AString & a_Name)\n{\n\tGroupMap::iterator itr = m_pState->Groups.find( a_Name);\n\treturn ( itr != m_pState->Groups.end());\n}\n\n\n\n\n\ncGroup* cGroupManager::GetGroup( const AString & a_Name)\n{\n\tGroupMap::iterator itr = m_pState->Groups.find( a_Name);\n\tif (itr != m_pState->Groups.end())\n\t{\n\t\treturn itr->second;\n\t}\n\n\tcGroup* Group = new cGroup();\n\tm_pState->Groups[a_Name] = Group;\n\n\treturn Group;\n}\n\n\n\n\n<|endoftext|>"} {"text":"#include \"InputManager.h\"\n\nInputManager::InputManager()\n{\n \/\/ TODO Make this map configurable \/ built from a file\n mKeyToEventMappings.insert( \n std::pair(Key::Q, Event::Quit) );\n mKeyToEventMappings.insert( \n std::pair(Key::Escape, Event::Quit) );\n\n mKeyToEventMappings.insert( \n std::pair(Key::Left, Event::MoveLeft) );\n mKeyToEventMappings.insert( \n std::pair(Key::Right, Event::MoveRight) );\n mKeyToEventMappings.insert( \n std::pair(Key::Up, Event::MoveForward) );\n mKeyToEventMappings.insert( \n std::pair(Key::Up, Event::MoveBack) );\n}\n\nInputManager::~InputManager()\n{\n EventMapping_T::iterator it;\n\n for(it = mEventMappings.begin(); it != mEventMappings.end(); it++) {\n if(it->second) {\n delete it->second;\n }\n }\n\n mEventMappings.clear();\n}\n\nvoid InputManager::injectKeyDown(KeyboardEvent event)\n{\n event.isDown = true;\n mEventMappings[ mKeyToEventMappings[event.key] ]->call(event);\n}\n\nvoid InputManager::injectKeyUp(KeyboardEvent event)\n{\n event.isDown = false;\n mEventMappings[ mKeyToEventMappings[event.key] ]->call(event);\n}\n\nvoid InputManager::injectMouseDown()\n{\n}\n\nvoid InputManager::injectMouseUp()\n{\n}\n\nvoid InputManager::injectMouseMoved()\n{\n}\n\nvoid InputManager::injectMouseDoubleClick()\n{\n}\n\nvoid InputManager::injectMouseWheel()\n{\n}\nOk, I have no idea how that was working. Some strange coincidence with the key codes I guess#include \"InputManager.h\"\n\nInputManager::InputManager()\n{\n \/\/ TODO Make this map configurable \/ built from a file\n mKeyToEventMappings.insert( \n std::pair(Key::Q, Event::Quit) );\n mKeyToEventMappings.insert( \n std::pair(Key::Escape, Event::Quit) );\n\n mKeyToEventMappings.insert( \n std::pair(Key::Left, Event::MoveLeft) );\n mKeyToEventMappings.insert( \n std::pair(Key::Right, Event::MoveRight) );\n mKeyToEventMappings.insert( \n std::pair(Key::Up, Event::MoveForward) );\n mKeyToEventMappings.insert( \n std::pair(Key::Down, Event::MoveBack) );\n}\n\nInputManager::~InputManager()\n{\n EventMapping_T::iterator it;\n\n for(it = mEventMappings.begin(); it != mEventMappings.end(); it++) {\n if(it->second) {\n delete it->second;\n }\n }\n\n mEventMappings.clear();\n}\n\nvoid InputManager::injectKeyDown(KeyboardEvent event)\n{\n event.isDown = true;\n mEventMappings[ mKeyToEventMappings[event.key] ]->call(event);\n}\n\nvoid InputManager::injectKeyUp(KeyboardEvent event)\n{\n event.isDown = false;\n mEventMappings[ mKeyToEventMappings[event.key] ]->call(event);\n}\n\nvoid InputManager::injectMouseDown()\n{\n}\n\nvoid InputManager::injectMouseUp()\n{\n}\n\nvoid InputManager::injectMouseMoved()\n{\n}\n\nvoid InputManager::injectMouseDoubleClick()\n{\n}\n\nvoid InputManager::injectMouseWheel()\n{\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textconversion_zh.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 17:25:31 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::i18n;\nusing namespace com::sun::star::linguistic2;\nusing namespace com::sun::star::uno;\nusing namespace rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/ defined in stc_char.cxx and stc_word.cxx generated from stc_char.dic and stc_word.dic\n\/\/ by genconv_dict\nextern const sal_uInt16* getSTC_CharIndex_S2T();\nextern const sal_Unicode* getSTC_CharData_S2T();\nextern const sal_uInt16* getSTC_CharIndex_S2V();\nextern const sal_Unicode* getSTC_CharData_S2V();\nextern const sal_uInt16* getSTC_CharIndex_T2S();\nextern const sal_Unicode* getSTC_CharData_T2S();\n\nextern const sal_uInt16* getSTC_WordIndex_S2T(sal_Int32 &count);\nextern const sal_uInt16* getSTC_WordIndex_T2S(sal_Int32 &count);\nextern const sal_uInt16* getSTC_WordEntry_S2T();\nextern const sal_uInt16* getSTC_WordEntry_T2S();\nextern const sal_Unicode* getSTC_WordData(sal_Int32 &count);\n\nTextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )\n{\n Reference < XInterface > xI;\n xI = xMSF->createInstance(\n OUString::createFromAscii( \"com.sun.star.linguistic2.ConversionDictionaryList\" ));\n if ( xI.is() )\n xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;\n\n implementationName = \"com.sun.star.i18n.TextConversion_zh\";\n}\n\nsal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)\n{\n sal_Unicode address = Index[ch>>8];\n if (address != 0xFFFF)\n address = Data[address + (ch & 0xFF)];\n return (address != 0xFFFF) ? address : ch;\n}\n\nOUString SAL_CALL getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)\n{\n const sal_Unicode *Data;\n const sal_uInt16 *Index;\n\n if (toSChinese) {\n Data = getSTC_CharData_T2S();\n Index = getSTC_CharIndex_T2S();\n } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {\n Data = getSTC_CharData_S2V();\n Index = getSTC_CharIndex_S2V();\n } else {\n Data = getSTC_CharData_S2T();\n Index = getSTC_CharIndex_S2T();\n }\n\n rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); \/\/ defined in x_rtl_ustring.h\n for (sal_Int32 i = 0; i < nLength; i++)\n newStr->buffer[i] =\n getOneCharConversion(aText[nStartPos+i], Data, Index);\n return OUString( newStr->buffer, nLength);\n}\n\nOUString SAL_CALL TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)\n{\n sal_Int32 dictLen = 0;\n const sal_Unicode *wordData = getSTC_WordData(dictLen);\n sal_Int32 maxLen = 0;\n const sal_uInt16 *index;\n const sal_uInt16 *entry;\n const sal_Unicode *charData;\n const sal_uInt16 *charIndex;\n\n if (toSChinese) {\n index = getSTC_WordIndex_T2S(maxLen);\n entry = getSTC_WordEntry_T2S();\n charData = getSTC_CharData_T2S();\n charIndex = getSTC_CharIndex_T2S();\n } else {\n index = getSTC_WordIndex_S2T(maxLen);\n entry = getSTC_WordEntry_S2T();\n if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {\n charData = getSTC_CharData_S2V();\n charIndex = getSTC_CharIndex_S2V();\n } else {\n charData = getSTC_CharData_S2T();\n charIndex = getSTC_CharIndex_S2T();\n }\n }\n\n if ((!wordData || !index || !entry) && !xCDL.is()) \/\/ no word mapping defined, do char2char conversion.\n return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n\n rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength*2 ); \/\/ defined in x_rtl_ustring.h\n sal_Int32 currPos = 0, count = 0;\n while (currPos < nLength) {\n sal_Int32 len = nLength - currPos;\n sal_Bool found = sal_False;\n if (len > maxLen)\n len = maxLen;\n for (; len > 0 && ! found; len--) {\n OUString word = aText.copy(nStartPos + currPos, len);\n sal_Int32 current = 0;\n \/\/ user dictionary\n if (xCDL.is()) {\n Sequence < OUString > conversions;\n try {\n conversions = xCDL->queryConversions(word, 0, len,\n aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,\n \/*toSChinese ?*\/ ConversionDirection_FROM_LEFT \/*: ConversionDirection_FROM_RIGHT*\/,\n nConversionOptions);\n }\n catch ( NoSupportException & ) {\n \/\/ clear reference (when there is no user dictionary) in order\n \/\/ to not always have to catch this exception again\n \/\/ in further calls. (save time)\n xCDL = 0;\n }\n catch (...) {\n \/\/ catch all other exceptions to allow\n \/\/ querying the system dictionary in the next line\n }\n if (conversions.getLength() > 0) {\n while (current < conversions[0].getLength())\n newStr->buffer[count++] = conversions[0][current++];\n currPos += word.getLength();\n found = sal_True;\n }\n }\n\n if (!found && index[len+1] - index[len] > 0) {\n sal_Int32 bottom = (sal_Int32) index[len];\n sal_Int32 top = (sal_Int32) index[len+1] - 1;\n\n while (bottom <= top && !found) {\n current = (top + bottom) \/ 2;\n const sal_Int32 result = word.compareTo(wordData + entry[current]);\n if (result < 0)\n top = current - 1;\n else if (result > 0)\n bottom = current + 1;\n else {\n if (toSChinese) \/\/ Traditionary\/Simplified conversion,\n for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);\n else \/\/ Simplified\/Traditionary conversion, forwards search for next word\n current = entry[current] + word.getLength() + 1;\n while (wordData[current])\n newStr->buffer[count++] = wordData[current++];\n currPos += word.getLength();\n found = sal_True;\n }\n }\n }\n }\n if (!found) {\n newStr->buffer[count++] =\n getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);\n currPos++;\n }\n }\n return OUString( newStr->buffer, count);\n}\n\nTextConversionResult SAL_CALL\nTextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,\n const Locale& aLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n TextConversionResult result;\n\n result.Candidates.realloc(1);\n result.Candidates[0] = getConversion( aText, nStartPos, nLength, aLocale, nConversionType, nConversionOptions);\n result.Boundary.startPos = nStartPos;\n result.Boundary.endPos = nStartPos + nLength;\n\n return result;\n}\n\nOUString SAL_CALL\nTextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,\n const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n if (rLocale.Language.equalsAscii(\"zh\") &&\n ( nConversionType == TextConversionType::TO_SCHINESE ||\n nConversionType == TextConversionType::TO_TCHINESE) ) {\n\n aLocale=rLocale;\n sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;\n\n if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)\n \/\/ char to char dictionary\n return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n else\n \/\/ word to word dictionary\n return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n } else\n throw NoSupportException(); \/\/ Conversion type is not supported in this service.\n}\n\nsal_Bool SAL_CALL\nTextConversion_zh::interactiveConversion( const Locale& aLocale, sal_Int16 nTextConversionType, sal_Int32 nTextConversionOptions )\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n return sal_False;\n}\n\n} } } }\nINTEGRATION: CWS textconversion (1.4.30); FILE MERGED 2005\/10\/27 01:05:55 tl 1.4.30.3: RESYNC: (1.4-1.5); FILE MERGED 2005\/08\/15 18:26:59 khong 1.4.30.2: #124006# return zero length offset when in\/out strings are simple one to one mapping 2005\/07\/18 20:55:21 khong 1.4.30.1: #124006# add extended text conversion API\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: textconversion_zh.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2005-11-08 09:15:56 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace com::sun::star::lang;\nusing namespace com::sun::star::i18n;\nusing namespace com::sun::star::linguistic2;\nusing namespace com::sun::star::uno;\nusing namespace rtl;\n\nnamespace com { namespace sun { namespace star { namespace i18n {\n\n\/\/ defined in stc_char.cxx and stc_word.cxx generated from stc_char.dic and stc_word.dic\n\/\/ by genconv_dict\nextern const sal_uInt16* getSTC_CharIndex_S2T();\nextern const sal_Unicode* getSTC_CharData_S2T();\nextern const sal_uInt16* getSTC_CharIndex_S2V();\nextern const sal_Unicode* getSTC_CharData_S2V();\nextern const sal_uInt16* getSTC_CharIndex_T2S();\nextern const sal_Unicode* getSTC_CharData_T2S();\n\nextern const sal_uInt16* getSTC_WordIndex_S2T(sal_Int32 &count);\nextern const sal_uInt16* getSTC_WordIndex_T2S(sal_Int32 &count);\nextern const sal_uInt16* getSTC_WordEntry_S2T();\nextern const sal_uInt16* getSTC_WordEntry_T2S();\nextern const sal_Unicode* getSTC_WordData(sal_Int32 &count);\n\nTextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )\n{\n Reference < XInterface > xI;\n xI = xMSF->createInstance(\n OUString::createFromAscii( \"com.sun.star.linguistic2.ConversionDictionaryList\" ));\n if ( xI.is() )\n xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;\n\n implementationName = \"com.sun.star.i18n.TextConversion_zh\";\n}\n\nsal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)\n{\n sal_Unicode address = Index[ch>>8];\n if (address != 0xFFFF)\n address = Data[address + (ch & 0xFF)];\n return (address != 0xFFFF) ? address : ch;\n}\n\nOUString SAL_CALL getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)\n{\n const sal_Unicode *Data;\n const sal_uInt16 *Index;\n\n if (toSChinese) {\n Data = getSTC_CharData_T2S();\n Index = getSTC_CharIndex_T2S();\n } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {\n Data = getSTC_CharData_S2V();\n Index = getSTC_CharIndex_S2V();\n } else {\n Data = getSTC_CharData_S2T();\n Index = getSTC_CharIndex_S2T();\n }\n\n rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); \/\/ defined in x_rtl_ustring.h\n for (sal_Int32 i = 0; i < nLength; i++)\n newStr->buffer[i] =\n getOneCharConversion(aText[nStartPos+i], Data, Index);\n return OUString( newStr->buffer, nLength);\n}\n\nOUString SAL_CALL TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence& offset)\n{\n sal_Int32 dictLen = 0;\n const sal_Unicode *wordData = getSTC_WordData(dictLen);\n sal_Int32 maxLen = 0;\n const sal_uInt16 *index;\n const sal_uInt16 *entry;\n const sal_Unicode *charData;\n const sal_uInt16 *charIndex;\n sal_Bool one2one=sal_True;\n\n if (toSChinese) {\n index = getSTC_WordIndex_T2S(maxLen);\n entry = getSTC_WordEntry_T2S();\n charData = getSTC_CharData_T2S();\n charIndex = getSTC_CharIndex_T2S();\n } else {\n index = getSTC_WordIndex_S2T(maxLen);\n entry = getSTC_WordEntry_S2T();\n if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {\n charData = getSTC_CharData_S2V();\n charIndex = getSTC_CharIndex_S2V();\n } else {\n charData = getSTC_CharData_S2T();\n charIndex = getSTC_CharIndex_S2T();\n }\n }\n\n if ((!wordData || !index || !entry) && !xCDL.is()) \/\/ no word mapping defined, do char2char conversion.\n return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n\n rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); \/\/ defined in x_rtl_ustring.h\n sal_Int32 currPos = 0, count = 0;\n while (currPos < nLength) {\n sal_Int32 len = nLength - currPos;\n sal_Bool found = sal_False;\n if (len > maxLen)\n len = maxLen;\n for (; len > 0 && ! found; len--) {\n OUString word = aText.copy(nStartPos + currPos, len);\n sal_Int32 current = 0;\n \/\/ user dictionary\n if (xCDL.is()) {\n Sequence < OUString > conversions;\n try {\n conversions = xCDL->queryConversions(word, 0, len,\n aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,\n \/*toSChinese ?*\/ ConversionDirection_FROM_LEFT \/*: ConversionDirection_FROM_RIGHT*\/,\n nConversionOptions);\n }\n catch ( NoSupportException & ) {\n \/\/ clear reference (when there is no user dictionary) in order\n \/\/ to not always have to catch this exception again\n \/\/ in further calls. (save time)\n xCDL = 0;\n }\n catch (...) {\n \/\/ catch all other exceptions to allow\n \/\/ querying the system dictionary in the next line\n }\n if (conversions.getLength() > 0) {\n if (offset.getLength() > 0) {\n if (word.getLength() != conversions[0].getLength())\n one2one=sal_False;\n while (current < conversions[0].getLength()) {\n offset[count] = nStartPos + currPos + (current *\n word.getLength() \/ conversions[0].getLength());\n newStr->buffer[count++] = conversions[0][current++];\n }\n offset[count-1] = nStartPos + currPos + word.getLength() - 1;\n } else {\n while (current < conversions[0].getLength())\n newStr->buffer[count++] = conversions[0][current++];\n }\n currPos += word.getLength();\n found = sal_True;\n }\n }\n\n if (!found && index[len+1] - index[len] > 0) {\n sal_Int32 bottom = (sal_Int32) index[len];\n sal_Int32 top = (sal_Int32) index[len+1] - 1;\n\n while (bottom <= top && !found) {\n current = (top + bottom) \/ 2;\n const sal_Int32 result = word.compareTo(wordData + entry[current]);\n if (result < 0)\n top = current - 1;\n else if (result > 0)\n bottom = current + 1;\n else {\n if (toSChinese) \/\/ Traditionary\/Simplified conversion,\n for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);\n else \/\/ Simplified\/Traditionary conversion, forwards search for next word\n current = entry[current] + word.getLength() + 1;\n sal_Int32 start=current;\n if (offset.getLength() > 0) {\n if (word.getLength() != OUString(&wordData[current]).getLength())\n one2one=sal_False;\n sal_Int32 convertedLength=OUString(&wordData[current]).getLength();\n while (wordData[current]) {\n offset[count]=nStartPos + currPos + ((current-start) *\n word.getLength() \/ convertedLength);\n newStr->buffer[count++] = wordData[current++];\n }\n offset[count-1]=nStartPos + currPos + word.getLength() - 1;\n } else {\n while (wordData[current])\n newStr->buffer[count++] = wordData[current++];\n }\n currPos += word.getLength();\n found = sal_True;\n }\n }\n }\n }\n if (!found) {\n if (offset.getLength() > 0)\n offset[count]=nStartPos+currPos;\n newStr->buffer[count++] =\n getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);\n currPos++;\n }\n }\n if (offset.getLength() > 0)\n offset.realloc(one2one ? 0 : count);\n return OUString( newStr->buffer, count);\n}\n\nTextConversionResult SAL_CALL\nTextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,\n const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n TextConversionResult result;\n\n result.Candidates.realloc(1);\n result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);\n result.Boundary.startPos = nStartPos;\n result.Boundary.endPos = nStartPos + nLength;\n\n return result;\n}\n\nOUString SAL_CALL\nTextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,\n const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n if (rLocale.Language.equalsAscii(\"zh\") &&\n ( nConversionType == TextConversionType::TO_SCHINESE ||\n nConversionType == TextConversionType::TO_TCHINESE) ) {\n\n aLocale=rLocale;\n sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;\n\n if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)\n \/\/ char to char dictionary\n return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n else {\n Sequence offset;\n \/\/ word to word dictionary\n return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);\n }\n } else\n throw NoSupportException(); \/\/ Conversion type is not supported in this service.\n}\n\nOUString SAL_CALL\nTextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,\n const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence& offset)\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n if (rLocale.Language.equalsAscii(\"zh\") &&\n ( nConversionType == TextConversionType::TO_SCHINESE ||\n nConversionType == TextConversionType::TO_TCHINESE) ) {\n\n aLocale=rLocale;\n sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;\n\n if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) {\n offset.realloc(0);\n \/\/ char to char dictionary\n return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);\n } else {\n if (offset.getLength() < 2*nLength)\n offset.realloc(2*nLength);\n \/\/ word to word dictionary\n return getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);\n }\n } else\n throw NoSupportException(); \/\/ Conversion type is not supported in this service.\n}\n\nsal_Bool SAL_CALL\nTextConversion_zh::interactiveConversion( const Locale& rLocale, sal_Int16 nTextConversionType, sal_Int32 nTextConversionOptions )\n throw( RuntimeException, IllegalArgumentException, NoSupportException )\n{\n return sal_False;\n}\n\n} } } }\n<|endoftext|>"} {"text":"void VZEROSurveyToAlignment(){\n\n \/\/ Macro to convert survey data into alignment data. \n \/\/ The position of four fiducial marks, sticked on the \n \/\/ entrance face of the V0C box is converted into the \n \/\/ global position of the box. Positions given by surveyers \n \/\/ are extracted from Survey Data Base. \n\n if(!gGeoManager) TGeoManager::Import(\"geometry.root\");\n\n TClonesArray *array = new TClonesArray(\"AliAlignObjMatrix\",10);\n TClonesArray &mobj = *array;\n \n Double_t l_vect[3]={0.,0.,0.}; \/\/ a local vector (the origin)\n Double_t g_vect[3]; \/\/ vector corresp. to it in global RS\n Double_t m_vect[3]; \/\/ vector corresp. to it in mother RS\n \n \/\/ ************* get global matrix *******************\n TGeoHMatrix *g3 = AliGeomManager::GetMatrix(\"VZERO\/V0C\");\n \n \/\/ this is used below as the ideal global matrix\n\n \/\/ ************* get local matrix *******************\n TGeoNode* n3 = gGeoManager->GetCurrentNode();\n TGeoHMatrix* l3 = n3->GetMatrix(); \n\n \/\/ point coordinates in the global RS\n g3->LocalToMaster(l_vect,g_vect);\n cout<LocalToMaster(l_vect,m_vect);\n cout< local x\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ A-------------|-------------B\n \/\/\n \/\/ local z exiting the plane of the screen\n \n Double_t gA[3], gB[3], gC[3], gD[3];\n g3->LocalToMaster(A,gA);\n g3->LocalToMaster(B,gB);\n g3->LocalToMaster(C,gC);\n g3->LocalToMaster(D,gD);\n cout<FillFromLocalFile(\"Survey_835615_V0.txt\");\n size = so->GetEntries();\n\n Printf(\"Title: \\\"%s\\\"\", so->GetReportTitle().Data());\n Printf(\"Date: \\\"%s\\\"\", so->GetReportDate().Data());\n Printf(\"Detector: \\\"%s\\\"\", so->GetDetector().Data());\n Printf(\"URL: \\\"%s\\\"\", so->GetURL().Data());\n Printf(\"Number: \\\"%d\\\"\", so->GetReportNumber());\n Printf(\"Version: \\\"%d\\\"\", so->GetReportVersion());\n Printf(\"Observations: \\\"%s\\\"\", so->GetObservations().Data());\n Printf(\"Coordinate System: \\\"%s\\\"\", so->GetCoordSys().Data());\n Printf(\"Measurement Units: \\\"%s\\\"\", so->GetUnits().Data());\n Printf(\"Nr Columns: \\\"%d\\\" \\n\", so->GetNrColumns());\n \n TObjArray *colNames = so->GetColumnNames();\n \n TObjArray *points = so->GetData();\n const char namePoint[4] = \"6001\";\n Double_t coordinates[4][3];\n\/\/ Printf(\" ******* %c ******* \\n\\n \", namePoint[0]); \n Printf(\"Relevant points to be used for alignment procedure (in mm):\"); \n for (Int_t i = 0; i < points->GetEntries(); ++i) {\n if(((AliSurveyPoint *) points->At(i))->GetPointName()[0] == namePoint[0]) {\n Printf(\"Point %d --> \\\"%s\\\" %f %f %f \", i, \n ((AliSurveyPoint *) points->At(i))->GetPointName().Data(),\n\t ((AliSurveyPoint *) points->At(i))->GetX(),\n\t ((AliSurveyPoint *) points->At(i))->GetY(),\n\t ((AliSurveyPoint *) points->At(i))->GetZ() ); \n\t if(i > 10){\n\t coordinates[i-11][0] = (AliSurveyPoint *) points->At(i))->GetX();\n\t coordinates[i-11][1] = (AliSurveyPoint *) points->At(i))->GetY();\n\t coordinates[i-11][2] = (AliSurveyPoint *) points->At(i))->GetZ(); } \n }\n } \n \n Double_t ngA[3], ngB[3], ngC[3], ngD[3];\n\n for(Int_t i=0; i<3; i++) \n { ngA[i] = coordinates[0][i] \/ 10.0 ; \n ngD[i] = coordinates[1][i] \/ 10.0 ;\n ngB[i] = coordinates[2][i] \/ 10.0 ; \n ngC[i] = coordinates[3][i] \/ 10.0 ; }\n \n cout<1.e-8){\n s = Double_t(1.)\/sizen ; \/\/normalization factor\n }else{\n return 0;\n }\n\n \/\/ plane expressed in the hessian normal form, see:\n \/\/ http:\/\/mathworld.wolfram.com\/HessianNormalForm.html\n \/\/ the first three are the coordinates of the orthonormal vector\n \/\/ the fourth coordinate is equal to the distance from the origin\n for(i=0;i<3;i++){\n plane[i] = n[i] * s;\n }\n plane[3] = -( plane[0] * ngA[0] + plane[1] * ngA[1] + plane[2] * ngA[2] );\n\/\/ cout<1.e-8){\n for(i=0;i<3;i++){\n ab[i] \/= sx;\n }\n cout<<\"x direction \"<1.e-8){\n for(i=0;i<3;i++){\n bc[i] \/= sy;\n }\n cout<<\"y direction \"<Inverse(); \/\/now equal to the inverse of g3\n gdelta.MultiplyLeft(&ng);\n Int_t index = 0;\n \n \/\/ if the volume is in the look-up table use something like this instead:\n \/\/ AliGeomManager::LayerToVolUID(AliGeomManager::kTOF,i); \n \n \/\/AliAlignObjMatrix* mobj[0] = new AliAlignObjMatrix(\"VZERO\/V0C\",index,gdelta,kTRUE);\n \n new(mobj[0]) AliAlignObjMatrix(\"VZERO\/V0C\",index,gdelta,kTRUE);\n \n if(!gSystem->Getenv(\"$TOCDB\")){\n \/\/ save on file\n TFile f(\"V0Survey.root\",\"RECREATE\");\n if(!f) cerr<<\"cannot open file for output\\n\";\n f.cd();\n f.WriteObject(array,\"V0SurveyObjs \",\"kSingleKey\");\n f.Close();\n }else{\n \/\/ save in CDB storage\n AliCDBManager* cdb = AliCDBManager::Instance();\n AliCDBStorage* storage = cdb->GetStorage(\"local:\/\/$ALICE_ROOT\");\n AliCDBMetaData* mda = new AliCDBMetaData();\n mda->SetResponsible(\"Brigitte Cheynis\");\n mda->SetComment(\"Alignment objects for V0 survey\");\n mda->SetAliRootVersion(gSystem->Getenv(\"$ARVERSION\"));\n AliCDBId id(\"VZERO\/Align\/Data\",0,9999999);\n storage->Put(array,id,mda);\n }\n\n array->Delete();\n\n}\nAliAlignObjMatrix replaced by AliAlignObjParamsvoid VZEROSurveyToAlignment(){\n\n \/\/ Macro to convert survey data into alignment data. \n \/\/ The position of four fiducial marks, sticked on the \n \/\/ entrance face of the V0C box is converted into the \n \/\/ global position of the box. Positions given by surveyers \n \/\/ are extracted from Survey Data Base. \n\n if(!gGeoManager) TGeoManager::Import(\"geometry.root\");\n\n\/\/ TClonesArray *array = new TClonesArray(\"AliAlignObjMatrix\",10);\n TClonesArray *array = new TClonesArray(\"AliAlignObjParams\",10);\n TClonesArray &mobj = *array;\n \n Double_t l_vect[3]={0.,0.,0.}; \/\/ local vector (the origin)\n Double_t g_vect[3]; \/\/ vector corresp. to it in global RS\n Double_t m_vect[3]; \/\/ vector corresp. to it in mother RS\n \n \/\/ ************* get global matrix g3 *******************\n \/\/ TGeoHMatrix *g3 = AliGeomManager::GetMatrix(\"VZERO\/V0C\");\n TGeoHMatrix *g3 = gGeoManager->GetCurrentMatrix();\n \/\/ this is used below as the IDEAL global matrix\n\n \/\/ ************* get local matrix l3 *******************\n TGeoNode* n3 = gGeoManager->GetCurrentNode();\n TGeoHMatrix *l3 = n3->GetMatrix(); \n \n \/\/ point coordinates in the global RS\n g3->LocalToMaster(l_vect,g_vect);\n cout<LocalToMaster(l_vect,m_vect);\n cout< local x\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ | | |\n \/\/ A-------------|-------------B\n \/\/\n \/\/ local z exiting the plane of the screen\n \n Double_t gA[3], gB[3], gC[3], gD[3];\n g3->LocalToMaster(A,gA);\n g3->LocalToMaster(B,gB);\n g3->LocalToMaster(C,gC);\n g3->LocalToMaster(D,gD);\n cout<FillFromLocalFile(\"Survey_835615_V0.txt\");\n Int_t size = so->GetEntries();\n\n Printf(\"Title: \\\"%s\\\"\", so->GetReportTitle().Data());\n Printf(\"Date: \\\"%s\\\"\", so->GetReportDate().Data());\n Printf(\"Detector: \\\"%s\\\"\", so->GetDetector().Data());\n Printf(\"URL: \\\"%s\\\"\", so->GetURL().Data());\n Printf(\"Number: \\\"%d\\\"\", so->GetReportNumber());\n Printf(\"Version: \\\"%d\\\"\", so->GetReportVersion());\n Printf(\"Observations: \\\"%s\\\"\", so->GetObservations().Data());\n Printf(\"Coordinate System: \\\"%s\\\"\", so->GetCoordSys().Data());\n Printf(\"Measurement Units: \\\"%s\\\"\", so->GetUnits().Data());\n Printf(\"Nr Columns: \\\"%d\\\" \\n\", so->GetNrColumns());\n \n TObjArray *colNames = so->GetColumnNames();\n \n TObjArray *points = so->GetData();\n const char namePoint[4] = \"6001\";\n Double_t coordinates[4][3];\n\/\/ Printf(\" ******* %c ******* \\n\\n \", namePoint[0]); \n Printf(\"Relevant points to be used for alignment procedure (in mm):\"); \n for (Int_t i = 0; i < points->GetEntries(); ++i) {\n if(((AliSurveyPoint *) points->At(i))->GetPointName()[0] == namePoint[0]) {\n Printf(\"Point %d --> \\\"%s\\\" %f %f %f \", i, \n ((AliSurveyPoint *) points->At(i))->GetPointName().Data(),\n\t ((AliSurveyPoint *) points->At(i))->GetX(),\n\t ((AliSurveyPoint *) points->At(i))->GetY(),\n\t ((AliSurveyPoint *) points->At(i))->GetZ() ); \n\t if(i > 10){\n\t coordinates[i-11][0] = (AliSurveyPoint *) points->At(i))->GetX();\n\t coordinates[i-11][1] = (AliSurveyPoint *) points->At(i))->GetY();\n\t coordinates[i-11][2] = (AliSurveyPoint *) points->At(i))->GetZ(); } \n }\n } \n \n Double_t ngA[3], ngB[3], ngC[3], ngD[3];\n\n for(Int_t i=0; i<3; i++) \n { ngA[i] = coordinates[0][i] \/ 10.0 ; \n ngD[i] = coordinates[1][i] \/ 10.0 ;\n ngB[i] = coordinates[2][i] \/ 10.0 ; \n ngC[i] = coordinates[3][i] \/ 10.0 ; }\n \n cout<1.e-8){\n s = Double_t(1.)\/sizen ; \/\/normalization factor\n }else{\n return 0;\n }\n\n \/\/ plane expressed in the hessian normal form, see:\n \/\/ http:\/\/mathworld.wolfram.com\/HessianNormalForm.html\n \/\/ the first three are the coordinates of the orthonormal vector\n \/\/ the fourth coordinate is equal to the distance from the origin\n for(i=0;i<3;i++){\n plane[i] = n[i] * s;\n }\n plane[3] = -( plane[0] * ngA[0] + plane[1] * ngA[1] + plane[2] * ngA[2] );\n\/\/ cout<1.e-8){\n for(i=0;i<3;i++){\n ab[i] \/= sx;\n }\n cout<<\"x direction \"<1.e-8){\n for(i=0;i<3;i++){\n bc[i] \/= sy;\n }\n cout<<\"y direction \"<Inverse(); \/\/now equal to the inverse of g3\n gdelta.MultiplyLeft(&ng);\n Int_t index = 0;\n \n \/\/ if the volume is in the look-up table use something like this instead:\n \/\/ AliGeomManager::LayerToVolUID(AliGeomManager::kTOF,i); \n \n \/\/AliAlignObjMatrix* mobj[0] = new AliAlignObjMatrix(\"VZERO\/V0C\",index,gdelta,kTRUE);\n \/\/ new(mobj[0]) AliAlignObjMatrix(\"VZERO\/V0C\",index,gdelta,kTRUE);\n\n new(mobj[0]) AliAlignObjParams(\"VZERO\/V0C\",index,gdelta,kTRUE);\n \n if(!gSystem->Getenv(\"$TOCDB\")){\n \/\/ save on file\n TFile f(\"V0Survey.root\",\"RECREATE\");\n if(!f) cerr<<\"cannot open file for output\\n\";\n f.cd();\n f.WriteObject(array,\"V0SurveyObjs \",\"kSingleKey\");\n f.Close();\n }else{\n \/\/ save in CDB storage\n AliCDBManager* cdb = AliCDBManager::Instance();\n AliCDBStorage* storage = cdb->GetStorage(\"local:\/\/$ALICE_ROOT\");\n AliCDBMetaData* mda = new AliCDBMetaData();\n mda->SetResponsible(\"Brigitte Cheynis\");\n mda->SetComment(\"Alignment objects for V0 survey\");\n mda->SetAliRootVersion(gSystem->Getenv(\"$ARVERSION\"));\n AliCDBId id(\"VZERO\/Align\/Data\",0,9999999);\n storage->Put(array,id,mda);\n }\n \n cout<<\"\\n********* Alignment constants contained in alignment object ***********\\n\";\n cout<<\"*************** deduced from surveyed fiducial marks : ****************\\n\";\n array->Print();\n \n AliAlignObjParams* itsalobj = (AliAlignObjParams*) mobj.UncheckedAt(0);\n itsalobj->ApplyToGeometry();\t\n \n array->Delete();\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ninline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {\n const auto x {a.x - b.x};\n const auto y {a.y - b.y};\n return x*x + y*y;\n}\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n WaypointManager()\n : sequence_ {},\n now_goal_ {sequence_.waypoints.end()}\n {\n }\n\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n sequence_ = req.goal_sequence;\n now_goal_ = sequence_.waypoints.begin();\n res.success = true;\n res.message = \"update waypoints\";\n return true;\n }\n\n const geometry_msgs::Point& point() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before point()\"};\n return now_goal_->position;\n }\n\n const geometry_msgs::Quaternion& quaternion() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before quaternion()\"};\n return now_goal_->orientation;\n }\n\n double radius() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal_->radius;\n }\n\n bool next()\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before next()\"}; \/\/ wrong way.\n if (++now_goal_ == sequence_.waypoints.end())\n return false; \/\/ correct way: this is last one.\n return true;\n }\n\n bool is_end() const noexcept\n {\n return sequence_.waypoints.end() == now_goal_;\n }\n\n explicit operator bool() noexcept\n {\n return !is_end();\n }\n\n [[deprecated]]\n const goal_sender_msgs::Waypoint& get() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before get()\"};\n return *now_goal_;\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n decltype(sequence_.waypoints)::iterator now_goal_;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) \/\/ buffer is lvalue\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::Point operator()(std::string parent, std::string child) const\n {\n const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};\n geometry_msgs::Point point;\n point.x = ts.transform.translation.x;\n point.y = ts.transform.translation.y;\n return point;\n }\n\nprivate:\n const tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n using MoveBaseActionClient = actionlib::SimpleActionClient;\n\n GoalSender(WaypointManager& point_manager,\n MoveBaseActionClient& move_base_client,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n move_base_client_ {move_base_client},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n if (!point_manager_)\n return; \/\/ no work\n if (is_reach()) {\n point_manager_.next();\n send_goal();\n }\n }\n\nprivate:\n bool is_reach() const\n {\n const auto robot_point {lookupper_(\"\/map\", \"\/base_link\")};\n const auto waypoint_point {point_manager_.point()};\n const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};\n\n const auto radius {point_manager_.radius()};\n const auto sqr_radius {radius * radius};\n\n if (sqr_distance < sqr_radius) \/\/ into valid range\n return true;\n return false;\n }\n\n void send_goal() const\n {\n if (!point_manager_) { \/\/ finish waypoint\n move_base_client_.cancelGoal(); \/\/ cancel moveing\n ROS_INFO(\"Finish waypoints\");\n return;\n }\n\n move_base_msgs::MoveBaseGoal goal;\n goal.target_pose.pose.position = point_manager_.point();\n goal.target_pose.pose.orientation = point_manager_.quaternion();\n goal.target_pose.header.frame_id = \"\/map\";\n goal.target_pose.header.stamp = ros::Time::now();\n move_base_client_.sendGoal(goal); \/\/ send waypoint\n }\n\n WaypointManager& point_manager_;\n MoveBaseActionClient& move_base_client_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<\n goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender::MoveBaseActionClient move_base_client {\"move_base\", true};\n move_base_client.waitForServer();\n\n GoalSender goal_sender {point_manager, move_base_client, lookupper};\n\n ros::Rate rate {10};\n while (ros::ok()) {\n ros::spinOnce();\n goal_sender.once();\n }\n}\nFix running speed#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ninline double squaring_distance(const geometry_msgs::Point& a, const geometry_msgs::Point& b) {\n const auto x {a.x - b.x};\n const auto y {a.y - b.y};\n return x*x + y*y;\n}\n\n\/**\n * Waypoint update service manager\n *\/\nclass WaypointManager\n{\npublic:\n WaypointManager()\n : sequence_ {},\n now_goal_ {sequence_.waypoints.end()}\n {\n }\n\n bool operator()(goal_sender_msgs::ApplyGoals::Request& req,\n goal_sender_msgs::ApplyGoals::Response& res){\n sequence_ = req.goal_sequence;\n now_goal_ = sequence_.waypoints.begin();\n res.success = true;\n res.message = \"update waypoints\";\n return true;\n }\n\n const geometry_msgs::Point& point() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before point()\"};\n return now_goal_->position;\n }\n\n const geometry_msgs::Quaternion& quaternion() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before quaternion()\"};\n return now_goal_->orientation;\n }\n\n double radius() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before radius()\"};\n return now_goal_->radius;\n }\n\n bool next()\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before next()\"}; \/\/ wrong way.\n if (++now_goal_ == sequence_.waypoints.end())\n return false; \/\/ correct way: this is last one.\n return true;\n }\n\n bool is_end() const noexcept\n {\n return sequence_.waypoints.end() == now_goal_;\n }\n\n explicit operator bool() noexcept\n {\n return !is_end();\n }\n\n [[deprecated]]\n const goal_sender_msgs::Waypoint& get() const\n {\n if (is_end()) throw std::logic_error {\"range error: Please check is_end() before get()\"};\n return *now_goal_;\n }\n\nprivate:\n goal_sender_msgs::GoalSequence sequence_;\n decltype(sequence_.waypoints)::iterator now_goal_;\n};\n\n\/**\n * Tf lookup API\n *\/\nclass TfPositionManager\n{\npublic:\n explicit TfPositionManager(tf2_ros::Buffer& tfBuffer) \/\/ buffer is lvalue\n : buffer_ {tfBuffer}\n {\n }\n\n geometry_msgs::Point operator()(std::string parent, std::string child) const\n {\n const auto ts {buffer_.lookupTransform(parent, child, ros::Time(0))};\n geometry_msgs::Point point;\n point.x = ts.transform.translation.x;\n point.y = ts.transform.translation.y;\n return point;\n }\n\nprivate:\n const tf2_ros::Buffer& buffer_;\n};\n\nclass GoalSender\n{\npublic:\n using MoveBaseActionClient = actionlib::SimpleActionClient;\n\n GoalSender(WaypointManager& point_manager,\n MoveBaseActionClient& move_base_client,\n TfPositionManager lookupper)\n : point_manager_ {point_manager},\n move_base_client_ {move_base_client},\n lookupper_ {lookupper}\n {\n }\n\n void once()\n {\n if (!point_manager_)\n return; \/\/ no work\n if (is_reach()) {\n point_manager_.next();\n send_goal();\n }\n }\n\nprivate:\n bool is_reach() const\n {\n const auto robot_point {lookupper_(\"\/map\", \"\/base_link\")};\n const auto waypoint_point {point_manager_.point()};\n const auto sqr_distance {squaring_distance(robot_point, waypoint_point)};\n\n const auto radius {point_manager_.radius()};\n const auto sqr_radius {radius * radius};\n\n if (sqr_distance < sqr_radius) \/\/ into valid range\n return true;\n return false;\n }\n\n void send_goal() const\n {\n if (!point_manager_) { \/\/ finish waypoint\n move_base_client_.cancelGoal(); \/\/ cancel moveing\n ROS_INFO(\"Finish waypoints\");\n return;\n }\n\n move_base_msgs::MoveBaseGoal goal;\n goal.target_pose.pose.position = point_manager_.point();\n goal.target_pose.pose.orientation = point_manager_.quaternion();\n goal.target_pose.header.frame_id = \"\/map\";\n goal.target_pose.header.stamp = ros::Time::now();\n move_base_client_.sendGoal(goal); \/\/ send waypoint\n }\n\n WaypointManager& point_manager_;\n MoveBaseActionClient& move_base_client_;\n TfPositionManager lookupper_;\n};\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"goal_sender\");\n ros::NodeHandle nh {};\n\n WaypointManager point_manager {};\n ros::ServiceServer srv {\n nh.advertiseService<\n goal_sender_msgs::ApplyGoals::Request,\n goal_sender_msgs::ApplyGoals::Response>(\n \"apply_goals\", point_manager)};\n\n tf2_ros::Buffer tfBuffer;\n tf2_ros::TransformListener tfListener {tfBuffer};\n TfPositionManager lookupper {tfBuffer};\n\n GoalSender::MoveBaseActionClient move_base_client {\"move_base\", true};\n move_base_client.waitForServer();\n\n GoalSender goal_sender {point_manager, move_base_client, lookupper};\n\n ros::Rate rate {10};\n while (ros::ok()) {\n ros::spinOnce();\n goal_sender.once();\n rate.sleep();\n }\n}\n<|endoftext|>"} {"text":"\/*\n * This file is part of Clockwork.\n *\n * Copyright (c) 2013-2016 Jeremy Othieno.\n *\n * The MIT License (MIT)\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#ifndef CLOCKWORK_POLYGON_RENDERER_HH\n#define CLOCKWORK_POLYGON_RENDERER_HH\n\n#include \"Renderer.hh\"\n#include \"RandomShadingShaderProgram.hh\"\n#include \"FlatShadingShaderProgram.hh\"\n#include \"GouraudShadingShaderProgram.hh\"\n#include \"PhongShadingShaderProgram.hh\"\n#include \"CelShadingShaderProgram.hh\"\n#include \"DepthMapShaderProgram.hh\"\n#include \"NormalMapShaderProgram.hh\"\n#include \"BumpMapShaderProgram.hh\"\n#include \"TextureMapShaderProgram.hh\"\n\n\nnamespace clockwork {\n\/**\n *\n *\/\ntemplate\nclass PolygonRenderer : public Renderer {\npublic:\n\tusing Fragment = typename Renderer::Fragment;\n\tusing Varying = typename Renderer::Varying;\n\tusing Vertex = typename Renderer::Vertex;\n\tusing VertexArray = typename Renderer::VertexArray;\n\t\/**\n\t * Sanitizes the rendering context and makes sure it is compatible with this renderer.\n\t *\/\n\tstatic void sanitizeRenderingContext(RenderingContext&);\n\t\/**\n\t * Rearranges the specified set of vertices into a collection of geometric primitives.\n\t *\/\n\tstatic void primitiveAssembly(const RenderingContext&, VertexArray&);\n\t\/**\n\t * Removes vertices that are not visible on the screen.\n\t *\/\n\tstatic void clip(const RenderingContext&, VertexArray&);\n\t\/**\n\t * Converts the specified vertices into fragments that are written to the given framebuffer.\n\t * @param context the rendering context.\n\t * @param vertices the vertices to convert.\n\t * @param framebuffer the framebuffer where fragments will be written to.\n\t *\/\n\tstatic void rasterize(\n\t\tconst RenderingContext& context,\n\t\tconst VertexArray& vertices,\n\t\tFramebuffer& framebuffer\n\t);\n};\n\/**\n *\n *\/\nclass RandomShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass FlatShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass GouraudShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass PhongShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass CelShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass DepthMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass NormalMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass BumpMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass TextureMapRenderer :\npublic PolygonRenderer {};\n\n\ntemplate void\nPolygonRenderer::sanitizeRenderingContext(RenderingContext& context) {\n\t\/\/ The Polygon renderer only draws triangle primitives so if the primitive topology\n\t\/\/ is not set to Triangle, TriangleStrip or TriangleFan, it will be set to TriangleStrip.\n\tauto& t = context.primitiveTopology;\n\tif (t != PrimitiveTopology::Triangle && t != PrimitiveTopology::TriangleStrip && t != PrimitiveTopology::TriangleFan) {\n\t\tt = PrimitiveTopology::TriangleStrip;\n\t}\n}\n\n\ntemplate void\nPolygonRenderer::primitiveAssembly(const RenderingContext&, VertexArray& vertices) {\n\t\/\/ TODO This will only generate triangle primitives. Implement TriangleStrip and\n\t\/\/ TriangleLoop generation.\n\tstatic const auto lessThan = [](const Vertex& a, const Vertex& b) {\n\t\tconst auto& pa = a.position;\n\t\tconst auto& pb = b.position;\n\t\tif (qFuzzyCompare(1.0 + pa.y(), 1.0 + pb.y())) {\n\t\t\tif (qFuzzyCompare(1.0 + pa.x(), 1.0 + pb.x())) {\n\t\t\t\treturn pa.z() < pb.z();\n\t\t\t} else {\n\t\t\t\treturn pa.x() < pb.x();\n\t\t\t}\n\t\t} else {\n\t\t\treturn pa.y() < pb.y();\n\t\t}\n\t};\n\t\/\/ If the triangle primitive is not correctly formed for the scanline algorithm,\n\t\/\/ then tessellate two triangle primitives that fit our needs.\n\tfor (auto it = vertices.begin(); it != vertices.end();) {\n\t\tconst auto& from = it;\n\t\tconst auto& to = it + 3;\n\n\t\tstd::sort(from, to, lessThan); \/\/ Note: std::sort processes the range [first, last[.\n\n\t\t\/\/ Tessellate the primitive, if need be.\n\t\tconst auto& V0 = it[0];\n\t\tconst auto& V1 = it[1];\n\t\tconst auto& V2 = it[2];\n\n\t\tconst auto& p0 = V0.position;\n\t\tconst auto& p1 = V1.position;\n\t\tconst auto& p2 = V2.position;\n\n\t\tconst bool tessellate = !qFuzzyCompare(1.0 + p0.y(), 1.0 + p1.y()) && !qFuzzyCompare(1.0 + p1.y(), 1.0 + p2.y());\n\t\tif (tessellate) {\n\t\t\t\/\/ Create a new output that will be used to create two new primitives.\n\t\t\tauto V = Vertex::lerp(V0, V2, (p1.y() - p0.y()) \/ (p2.y() - p0.y()));\n\t\t\tV.position.setY(p1.y());\n\t\t\t\/\/V.position.z = 0; \/\/FIXME Depth needs to be interpolated between V1 and O3.\n\n\t\t\t\/\/ Create two new triangle primitives: {V0, V1, V} and {V1, V, V2}. Since the\n\t\t\t\/\/ original array of outputs is {V0, V1, V2}, it becomes {V0, V1, V, V1, V, V2}.\n\t\t\tit = vertices.insert(it + 2, V);\n\t\t\tit = vertices.insert(it + 1, V1);\n\t\t\tit = vertices.insert(it + 1, V);\n\t\t\tit = std::next(it, 2);\n\t\t} else {\n\t\t\tit = to;\n\t\t}\n\t}\n}\n\n\ntemplate void\nPolygonRenderer::clip(const RenderingContext&, VertexArray&) {}\n\n\ntemplate void\nPolygonRenderer::rasterize(\n\tconst RenderingContext& context,\n\tconst VertexArray& vertices,\n\tFramebuffer& framebuffer\n) {\n\tfor (auto it = vertices.begin(); it != vertices.end(); it += 3) {\n\t\tconst auto* a = &it[1];\n\t\tconst auto* b = &it[0];\n\t\tconst auto* c = &it[2];\n\t\tif (qFuzzyCompare(1.0 + a->position.y(), 1.0 + b->position.y())) {\n\t\t\ta = &it[0];\n\t\t\tb = &it[2];\n\t\t\tc = &it[1];\n\t\t}\n\n\t\tconst double ay = std::round(a->position.y());\n\t\tconst double by = std::round(b->position.y());\n\t\t\/\/const double cy = ay; \/\/ since a and c are colinear.\n\t\tconst double dy = by - ay; \/\/ or by - cy.\n\n\t\t\/\/ If the dy is relatively small, all 3 points are considered colinear.\n\t\tconstexpr double EPSILON = 1e-5;\n\t\tif (std::abs(dy) < EPSILON) {\n\t\t\t\/\/ TODO Handle cases where all 3 vertices are colinear.\n\t\t} else {\n\t\t\tauto ymin = static_cast(ay);\n\t\t\tauto ymax = static_cast(by);\n\t\t\tif (ymin > ymax) {\n\t\t\t\tstd::swap(ymin, ymax);\n\t\t\t}\n\t\t\tfor (auto y = ymin; y <= ymax; ++y) {\n\t\t\t\tconst double p = (y - ay) \/ dy;\n\t\t\t\tconst auto from = Vertex::lerp(*a, *b, p);\n\t\t\t\tconst auto to = Vertex::lerp(*c, *b, p);\n\n\t\t\t\tconst double Fx = std::round(from.position.x());\n\t\t\t\tconst double Tx = std::round(to.position.x());\n\t\t\t\tconst double dx = Tx - Fx;\n\n\t\t\t\t\/\/ If dx is relatively small, the 'from' and 'to' vertices are\n\t\t\t\t\/\/ considered identical so there's no need to interpolate any\n\t\t\t\t\/\/ new vertices between them.\n\t\t\t\tif (std::abs(dx) < EPSILON) {\n\t\t\t\t\tT::fragmentProcessing(context, Fragment(from), framebuffer);\n\t\t\t\t} else {\n\t\t\t\t\tauto xmin = static_cast(Fx);\n\t\t\t\t\tauto xmax = static_cast(Tx);\n\t\t\t\t\tif (xmin > xmax) {\n\t\t\t\t\t\tstd::swap(xmin, xmax);\n\t\t\t\t\t}\n\t\t\t\t\tfor (auto x = xmin; x <= xmax; ++x) {\n\t\t\t\t\t\tconst double p = (x - Fx) \/ dx;\n\t\t\t\t\t\tconst auto vertex = Vertex::lerp(from, to, p);\n\t\t\t\t\t\tFragment fragment(vertex);\n\t\t\t\t\t\tfragment.x = x;\n\t\t\t\t\t\tfragment.y = y;\n\t\t\t\t\t\tT::fragmentProcessing(context, fragment, framebuffer);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n} \/\/ namespace clockwork\n\n#endif \/\/ CLOCKWORK_POLYGON_RENDERER_HH\nRefactor the scanline algorithm implementation\/*\n * This file is part of Clockwork.\n *\n * Copyright (c) 2013-2016 Jeremy Othieno.\n *\n * The MIT License (MIT)\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\/\n#ifndef CLOCKWORK_POLYGON_RENDERER_HH\n#define CLOCKWORK_POLYGON_RENDERER_HH\n\n#include \"Renderer.hh\"\n#include \"RandomShadingShaderProgram.hh\"\n#include \"FlatShadingShaderProgram.hh\"\n#include \"GouraudShadingShaderProgram.hh\"\n#include \"PhongShadingShaderProgram.hh\"\n#include \"CelShadingShaderProgram.hh\"\n#include \"DepthMapShaderProgram.hh\"\n#include \"NormalMapShaderProgram.hh\"\n#include \"BumpMapShaderProgram.hh\"\n#include \"TextureMapShaderProgram.hh\"\n\n\nnamespace clockwork {\n\/**\n *\n *\/\ntemplate\nclass PolygonRenderer : public Renderer {\npublic:\n\tusing Fragment = typename Renderer::Fragment;\n\tusing Varying = typename Renderer::Varying;\n\tusing Vertex = typename Renderer::Vertex;\n\tusing VertexArray = typename Renderer::VertexArray;\n\t\/**\n\t * Sanitizes the rendering context and makes sure it is compatible with this renderer.\n\t *\/\n\tstatic void sanitizeRenderingContext(RenderingContext&);\n\t\/**\n\t * Rearranges the specified set of vertices into a collection of geometric primitives.\n\t *\/\n\tstatic void primitiveAssembly(const RenderingContext&, VertexArray&);\n\t\/**\n\t * Removes vertices that are not visible on the screen.\n\t *\/\n\tstatic void clip(const RenderingContext&, VertexArray&);\n\t\/**\n\t * Converts the specified vertices into fragments that are written to the given framebuffer.\n\t * @param context the rendering context.\n\t * @param vertices the vertices to convert.\n\t * @param framebuffer the framebuffer where fragments will be written to.\n\t *\/\n\tstatic void rasterize(\n\t\tconst RenderingContext& context,\n\t\tconst VertexArray& vertices,\n\t\tFramebuffer& framebuffer\n\t);\n};\n\/**\n *\n *\/\nclass RandomShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass FlatShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass GouraudShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass PhongShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass CelShadingRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass DepthMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass NormalMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass BumpMapRenderer :\npublic PolygonRenderer {};\n\/**\n *\n *\/\nclass TextureMapRenderer :\npublic PolygonRenderer {};\n\n\ntemplate void\nPolygonRenderer::sanitizeRenderingContext(RenderingContext& context) {\n\t\/\/ The Polygon renderer only draws triangle primitives so if the primitive topology\n\t\/\/ is not set to Triangle, TriangleStrip or TriangleFan, it will be set to TriangleStrip.\n\tauto& t = context.primitiveTopology;\n\tif (t != PrimitiveTopology::Triangle && t != PrimitiveTopology::TriangleStrip && t != PrimitiveTopology::TriangleFan) {\n\t\tt = PrimitiveTopology::TriangleStrip;\n\t}\n}\n\n\ntemplate void\nPolygonRenderer::primitiveAssembly(const RenderingContext&, VertexArray& vertices) {\n\t\/\/ TODO This will only generate triangle primitives. Implement TriangleStrip and\n\t\/\/ TriangleLoop generation.\n\tstatic const auto lessThan = [](const Vertex& a, const Vertex& b) {\n\t\tconst auto& pa = a.position;\n\t\tconst auto& pb = b.position;\n\t\tif (qFuzzyCompare(1.0 + pa.y(), 1.0 + pb.y())) {\n\t\t\tif (qFuzzyCompare(1.0 + pa.x(), 1.0 + pb.x())) {\n\t\t\t\treturn pa.z() < pb.z();\n\t\t\t} else {\n\t\t\t\treturn pa.x() < pb.x();\n\t\t\t}\n\t\t} else {\n\t\t\treturn pa.y() < pb.y();\n\t\t}\n\t};\n\t\/\/ If the triangle primitive is not correctly formed for the scanline algorithm,\n\t\/\/ then tessellate two triangle primitives that fit our needs.\n\tfor (auto it = vertices.begin(); it != vertices.end();) {\n\t\tconst auto& from = it;\n\t\tconst auto& to = it + 3;\n\n\t\tstd::sort(from, to, lessThan); \/\/ Note: std::sort processes the range [first, last[.\n\n\t\t\/\/ Tessellate the primitive, if need be.\n\t\tconst auto& V0 = it[0];\n\t\tconst auto& V1 = it[1];\n\t\tconst auto& V2 = it[2];\n\n\t\tconst auto& p0 = V0.position;\n\t\tconst auto& p1 = V1.position;\n\t\tconst auto& p2 = V2.position;\n\n\t\tconst bool tessellate = !qFuzzyCompare(1.0 + p0.y(), 1.0 + p1.y()) && !qFuzzyCompare(1.0 + p1.y(), 1.0 + p2.y());\n\t\tif (tessellate) {\n\t\t\t\/\/ Create a new output that will be used to create two new primitives.\n\t\t\tauto V = Vertex::lerp(V0, V2, (p1.y() - p0.y()) \/ (p2.y() - p0.y()));\n\t\t\tV.position.setY(p1.y());\n\t\t\t\/\/V.position.z = 0; \/\/FIXME Depth needs to be interpolated between V1 and O3.\n\n\t\t\t\/\/ Create two new triangle primitives: {V0, V1, V} and {V1, V, V2}. Since the\n\t\t\t\/\/ original array of outputs is {V0, V1, V2}, it becomes {V0, V1, V, V1, V, V2}.\n\t\t\tit = vertices.insert(it + 2, V);\n\t\t\tit = vertices.insert(it + 1, V1);\n\t\t\tit = vertices.insert(it + 1, V);\n\t\t\tit = std::next(it, 2);\n\t\t} else {\n\t\t\tit = to;\n\t\t}\n\t}\n}\n\n\ntemplate void\nPolygonRenderer::clip(const RenderingContext&, VertexArray&) {}\n\n\ntemplate void\nPolygonRenderer::rasterize(\n\tconst RenderingContext& context,\n\tconst VertexArray& vertices,\n\tFramebuffer& framebuffer\n) {\n\tfor (auto it = vertices.begin(); it != vertices.end(); it += 3) {\n\t\tconst auto* a = &it[1];\n\t\tconst auto* b = &it[0];\n\t\tconst auto* c = &it[2];\n\t\tif (qFuzzyCompare(1.0 + a->position.y(), 1.0 + b->position.y())) {\n\t\t\ta = &it[0];\n\t\t\tb = &it[2];\n\t\t\tc = &it[1];\n\t\t}\n\n\t\tconst int ay = qRound(a->position.y());\n\t\tconst int by = qRound(b->position.y());\n\/\/\t\tconst int cy = ay; \/\/ since a and c are colinear.\n\t\tconst int dy = by - ay; \/\/ or by - cy.\n\n\t\tint ymin = ay;\n\t\tint ymax = by;\n\t\tif (ymax < ymin) {\n\t\t\tstd::swap(ymin, ymax);\n\t\t}\n\t\tfor (int y = ymin; y <= ymax; ++y) {\n\t\t\tconst qreal p = (y - ay) \/ static_cast(dy);\n\t\t\tconst Vertex from(Vertex::lerp(*a, *b, p));\n\t\t\tconst Vertex to(Vertex::lerp(*c, *b, p));\n\n\t\t\tconst int Fx = qRound(from.position.x());\n\t\t\tconst int Tx = qRound(to.position.x());\n\t\t\tconst int dx = Tx - Fx;\n\n\t\t\t\/\/ If dx is equal to zero, the 'from' and 'to' vertices are\n\t\t\t\/\/ considered identical so there's no need to interpolate any\n\t\t\t\/\/ new vertices between them.\n\t\t\tif (dx == 0) {\n\t\t\t\tT::fragmentProcessing(context, Fragment(from), framebuffer);\n\t\t\t} else {\n\t\t\t\tint xmin = Fx;\n\t\t\t\tint xmax = Tx;\n\t\t\t\tif (xmax < xmin) {\n\t\t\t\t\tstd::swap(xmin, xmax);\n\t\t\t\t}\n\t\t\t\tfor (int x = xmin; x <= xmax; ++x) {\n\t\t\t\t\tconst qreal p = (x - Fx) \/ static_cast(dx);\n\t\t\t\t\tFragment fragment(Vertex::lerp(from, to, p));\n\t\t\t\t\tfragment.x = x;\n\t\t\t\t\tfragment.y = y;\n\t\t\t\t\tT::fragmentProcessing(context, fragment, framebuffer);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n} \/\/ namespace clockwork\n\n#endif \/\/ CLOCKWORK_POLYGON_RENDERER_HH\n<|endoftext|>"} {"text":"\/* Twofold-Qt\n * (C) Copyright 2014 HicknHack Software GmbH\n *\n * The original code can be found at:\n * https:\/\/github.com\/hicknhack-software\/Twofold-Qt\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"Twofold\/Engine.h\"\n\n#include \n#include \n#include \n\nclass TestBenchmark : public QObject\n{\n Q_OBJECT\n\npublic:\n TestBenchmark();\n\nprivate Q_SLOTS:\n void prepare();\n void execute_data();\n void execute();\n void calls();\n void exceptions();\n\nprivate:\n Twofold::Engine engine;\n QVariantHash context;\n Twofold::PreparedTemplate prepared;\n Twofold::Target target;\n};\n\n#include \"TestBenchmark.moc\"\n\n#define TEMPLATE_REPETITION 1000\n\nclass FakeTextLoader : public Twofold::TextLoader\n{\npublic:\n Result load(const QString &name) const\n {\n static const QString templateText1 = QString::fromLatin1(R\"EXAMPLE(\nfor(var i = 0; i <= 10000; i++) {\n | Das ist ein kurzer Text! #{i}\n # include \"lib.twofold\"\n}\n|---------------------------------\n|\nfunction structFieldHeader(type) {\n |#{ type.name }\n |struct #{ type.name } {\n |};\n}\n\nif (type.isArray) {\n | \/\/ #{ type.name } Type is an Array #{type.text}\"\n = structFieldHeader(type);\n}\n\n |class #{ name } {\n for(var i = 0; i < baseNames.length; i++) {\n | #{ (i==0 ? ':' : ',') } public #{ baseNames[i] }\n }\n|};\n)EXAMPLE\"\n ).arg(TEMPLATE_REPETITION);\n\n static const QString templateText2 = R\"EXAMPLE(\n|Line 1 included\n|Line 2 incldued\n)EXAMPLE\";\n\n return (name != \"lib.twofold\")\n ? Result { Success, QString(), templateText1 }\n : Result { Success, QString(), templateText2 };\n }\n};\n\nTestBenchmark::TestBenchmark()\n : engine(std::make_shared(),\n std::make_shared())\n#if defined(_MSC_VER) && _MSC_VER < 1900\n , prepared({})\n , target({})\n#endif\n{\n QObject* pType = new QObject();\n pType->setProperty( \"isArray\", true );\n pType->setProperty( \"name\", \"TestArray\" );\n\n QStringList baseNames;\n baseNames.append( \"base1\" );\n baseNames.append( \"base2\" );\n baseNames.append( \"base3\" );\n\n context.insert( \"type\", QVariant::fromValue(pType) );\n context.insert( \"baseNames\", baseNames );\n context.insert( \"name\", \"Main\" );\n}\n\nvoid TestBenchmark::prepare()\n{\n QBENCHMARK {\n engine.prepare(\"TextTemplate.twofold\");\n }\n}\n\nvoid TestBenchmark::execute_data()\n{\n prepared = engine.prepare(\"TextTemplate.twofold\");\n}\n\nvoid TestBenchmark::execute()\n{\n QBENCHMARK {\n engine.exec(prepared, context);\n }\n}\n\nextern int func(int x, int y);\nextern int func_except(int x, int y);\n\nint func(int x, int y) {\n return (x + y);\n}\n\nint func_except(int x, int y) {\n throw (x + y);\n}\n\nvoid TestBenchmark::calls()\n{\n int r = 1;\n QBENCHMARK {\n r *= func(49, 430);\n }\n}\n\nvoid TestBenchmark::exceptions()\n{\n int r = 1;\n QBENCHMARK {\n try {\n func_except(49, 430);\n }\n catch(int x) {\n r *= x;\n }\n }\n}\n\nQTEST_GUILESS_MAIN(TestBenchmark)\nadded missing string argument\/* Twofold-Qt\n * (C) Copyright 2014 HicknHack Software GmbH\n *\n * The original code can be found at:\n * https:\/\/github.com\/hicknhack-software\/Twofold-Qt\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"Twofold\/Engine.h\"\n\n#include \n#include \n#include \n\nclass TestBenchmark : public QObject\n{\n Q_OBJECT\n\npublic:\n TestBenchmark();\n\nprivate Q_SLOTS:\n void prepare();\n void execute_data();\n void execute();\n void calls();\n void exceptions();\n\nprivate:\n Twofold::Engine engine;\n QVariantHash context;\n Twofold::PreparedTemplate prepared;\n Twofold::Target target;\n};\n\n#include \"TestBenchmark.moc\"\n\n#define TEMPLATE_REPETITION 1000\n\nclass FakeTextLoader : public Twofold::TextLoader\n{\npublic:\n Result load(const QString &name) const\n {\n static const QString templateText1 = QString::fromLatin1(R\"EXAMPLE(\nfor(var i = 0; i <= %1; i++) {\n | Das ist ein kurzer Text! #{i}\n # include \"lib.twofold\"\n}\n|---------------------------------\n|\nfunction structFieldHeader(type) {\n |#{ type.name }\n |struct #{ type.name } {\n |};\n}\n\nif (type.isArray) {\n | \/\/ #{ type.name } Type is an Array #{type.text}\"\n = structFieldHeader(type);\n}\n\n |class #{ name } {\n for(var i = 0; i < baseNames.length; i++) {\n | #{ (i==0 ? ':' : ',') } public #{ baseNames[i] }\n }\n|};\n)EXAMPLE\"\n ).arg(TEMPLATE_REPETITION);\n\n static const QString templateText2 = R\"EXAMPLE(\n|Line 1 included\n|Line 2 incldued\n)EXAMPLE\";\n\n return (name != \"lib.twofold\")\n ? Result { Success, QString(), templateText1 }\n : Result { Success, QString(), templateText2 };\n }\n};\n\nTestBenchmark::TestBenchmark()\n : engine(std::make_shared(),\n std::make_shared())\n#if defined(_MSC_VER) && _MSC_VER < 1900\n , prepared({})\n , target({})\n#endif\n{\n QObject* pType = new QObject();\n pType->setProperty( \"isArray\", true );\n pType->setProperty( \"name\", \"TestArray\" );\n\n QStringList baseNames;\n baseNames.append( \"base1\" );\n baseNames.append( \"base2\" );\n baseNames.append( \"base3\" );\n\n context.insert( \"type\", QVariant::fromValue(pType) );\n context.insert( \"baseNames\", baseNames );\n context.insert( \"name\", \"Main\" );\n}\n\nvoid TestBenchmark::prepare()\n{\n QBENCHMARK {\n engine.prepare(\"TextTemplate.twofold\");\n }\n}\n\nvoid TestBenchmark::execute_data()\n{\n prepared = engine.prepare(\"TextTemplate.twofold\");\n}\n\nvoid TestBenchmark::execute()\n{\n QBENCHMARK {\n engine.exec(prepared, context);\n }\n}\n\nextern int func(int x, int y);\nextern int func_except(int x, int y);\n\nint func(int x, int y) {\n return (x + y);\n}\n\nint func_except(int x, int y) {\n throw (x + y);\n}\n\nvoid TestBenchmark::calls()\n{\n int r = 1;\n QBENCHMARK {\n r *= func(49, 430);\n }\n}\n\nvoid TestBenchmark::exceptions()\n{\n int r = 1;\n QBENCHMARK {\n try {\n func_except(49, 430);\n }\n catch(int x) {\n r *= x;\n }\n }\n}\n\nQTEST_GUILESS_MAIN(TestBenchmark)\n<|endoftext|>"} {"text":"\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: 2021-12-11\n\/\/\n\/\/\n\/\/ Copyright (c) 2021 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#define N_METADATA_STRUCT(Struct) template<> struct n_metadata_member_definitions : public ::neam::metadata::internal::member_definition_base\n\n#define N_MEMBER_DEF_EX(Struct, Member) ::neam::metadata::internal::member_definition\n\n\/\/\/ \\brief Entry in the member_list type of serializable structs\n#define N_MEMBER_DEF(Member) ::neam::metadata::internal::member_definition\n\nnamespace neam::metadata::internal\n{\n template\n struct member_definition_base\n {\n using struct_type = T;\n };\n\n template\n struct member_definition\n {\n static constexpr size_t size = sizeof(Type);\n static constexpr size_t offset = Offset;\n using type = Type;\n static constexpr ct::string_holder name = Name;\n };\n}\n\ntemplate struct n_metadata_member_definitions {static_assert(!std::is_same_v, \"No member definition for type T\");};\n\ntemplate using n_metadata_member_list = typename n_metadata_member_definitions::member_list;\n\nnamespace neam::metadata::concepts\n{\n \/\/\/ \\brief A struct with metadata allows for an easy and semi-automatic serialization of compound types\n \/\/\/\n \/\/\/ Here is a serializable struct:\n \/\/\/\n \/\/\/ struct MyAwesomeStruct\n \/\/\/ {\n \/\/\/ unsigned some_member = 0;\n \/\/\/ std::vector< std::map< int, SomeOtherStruct > > stuff;\n \/\/\/ raw_data binary_blob;\n \/\/\/ };\n \/\/\/ N_METADATA_STRUCT(MyAwesomeStruct)\n \/\/\/ {\n \/\/\/ using member_list = ct::list\n \/\/\/ <\n \/\/\/ N_MEMBER(some_member),\n \/\/\/ N_MEMBER(stuff),\n \/\/\/ N_MEMBER(binary_blob),\n \/\/\/ >;\n \/\/\/ };\n template\n concept StructWithMetadata = requires(T v)\n {\n ct::list::size::member_list>;\n };\n}\n\nAdd support for template types\/\/\n\/\/ created by : Timothée Feuillet\n\/\/ date: 2021-12-11\n\/\/\n\/\/\n\/\/ Copyright (c) 2021 Timothée Feuillet\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\/\/\n\n#pragma once\n\n#include \n#include \n#include \n\n#define N_METADATA_STRUCT(Struct) template<> struct n_metadata_member_definitions : public ::neam::metadata::internal::member_definition_base\n\n\n#define N_METADATA_STRUCT_TPL(Struct, ...) struct n_metadata_member_definitions> : public ::neam::metadata::internal::member_definition_base>\n\n#define N_DECLARE_STRUCT_TYPE_TPL(Struct, ...) using struct_type = Struct<__VA_ARGS__>\n\n#define N_MEMBER_DEF_EX(Struct, Member) ::neam::metadata::internal::member_definition\n\n\/\/\/ \\brief Entry in the member_list type of serializable structs\n#define N_MEMBER_DEF(Member) ::neam::metadata::internal::member_definition\n\nnamespace neam::metadata::internal\n{\n template\n struct member_definition_base\n {\n using struct_type = T;\n };\n\n template\n struct member_definition\n {\n static constexpr size_t size = sizeof(Type);\n static constexpr size_t offset = Offset;\n using type = Type;\n static constexpr ct::string_holder name = Name;\n };\n}\n\ntemplate struct n_metadata_member_definitions {static_assert(!std::is_same_v, \"No member definition for type T\");};\n\ntemplate using n_metadata_member_list = typename n_metadata_member_definitions::member_list;\n\nnamespace neam::metadata::concepts\n{\n \/\/\/ \\brief A struct with metadata allows for an easy and semi-automatic serialization of compound types\n \/\/\/\n \/\/\/ Here is a serializable struct:\n \/\/\/\n \/\/\/ struct MyAwesomeStruct\n \/\/\/ {\n \/\/\/ unsigned some_member = 0;\n \/\/\/ std::vector< std::map< int, SomeOtherStruct > > stuff;\n \/\/\/ raw_data binary_blob;\n \/\/\/ };\n \/\/\/ N_METADATA_STRUCT(MyAwesomeStruct)\n \/\/\/ {\n \/\/\/ using member_list = ct::list\n \/\/\/ <\n \/\/\/ N_MEMBER(some_member),\n \/\/\/ N_MEMBER(stuff),\n \/\/\/ N_MEMBER(binary_blob),\n \/\/\/ >;\n \/\/\/ };\n template\n concept StructWithMetadata = requires(T v)\n {\n ct::list::size::member_list>;\n };\n}\n\n<|endoftext|>"} {"text":"\/*\nAn Botan example application which emulates a poorly written version of bzip2\n\nWritten by Jack Lloyd (lloyd@randombit.net), Jun 9, 2001\n\nThis file is in the public domain\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(BOTAN_EXT_COMPRESSOR_BZIP2)\n #include \n#else\n #error \"You didn't compile the bzip module into Botan\"\n#endif\n\nconst std::string SUFFIX = \".bz2\";\n\nint main(int argc, char* argv[])\n {\n if(argc < 2)\n {\n std::cout << \"Usage: \" << argv[0]\n << \" [-s] [-d] [-1...9] \" << std::endl;\n return 1;\n }\n\n\n std::vector files;\n bool decompress = false, small = false;\n int level = 9;\n\n for(int j = 1; argv[j] != 0; j++)\n {\n if(std::strcmp(argv[j], \"-d\") == 0) { decompress = true; continue; }\n if(std::strcmp(argv[j], \"-s\") == 0) { small = true; continue; }\n if(std::strcmp(argv[j], \"-1\") == 0) { level = 1; continue; }\n if(std::strcmp(argv[j], \"-2\") == 0) { level = 2; continue; }\n if(std::strcmp(argv[j], \"-3\") == 0) { level = 3; continue; }\n if(std::strcmp(argv[j], \"-4\") == 0) { level = 4; continue; }\n if(std::strcmp(argv[j], \"-5\") == 0) { level = 5; continue; }\n if(std::strcmp(argv[j], \"-6\") == 0) { level = 6; continue; }\n if(std::strcmp(argv[j], \"-7\") == 0) { level = 7; continue; }\n if(std::strcmp(argv[j], \"-8\") == 0) { level = 8; continue; }\n if(std::strcmp(argv[j], \"-9\") == 0) { level = 9; continue; }\n files.push_back(argv[j]);\n }\n\n try {\n\n Botan::Filter* bzip;\n if(decompress)\n bzip = new Botan::Bzip_Decompression(small);\n else\n bzip = new Botan::Bzip_Compression(level);\n\n Botan::Pipe pipe(bzip);\n\n for(unsigned int j = 0; j != files.size(); j++)\n {\n std::string infile = files[j], outfile = files[j];\n if(!decompress)\n outfile = outfile += SUFFIX;\n else\n outfile = outfile.replace(outfile.find(SUFFIX),\n SUFFIX.length(), \"\");\n\n std::ifstream in(infile.c_str());\n std::ofstream out(outfile.c_str());\n if(!in)\n {\n std::cout << \"ERROR: could not read \" << infile << std::endl;\n continue;\n }\n if(!out)\n {\n std::cout << \"ERROR: could not write \" << outfile << std::endl;\n continue;\n }\n\n pipe.start_msg();\n in >> pipe;\n pipe.end_msg();\n pipe.set_default_msg(j);\n out << pipe;\n\n in.close();\n out.close();\n }\n }\n catch(std::exception& e)\n {\n std::cout << \"Exception caught: \" << e.what() << std::endl;\n return 1;\n }\n return 0;\n }\nFail at runtime if bzip2 is not compiled in, instead of compile time\/*\nAn Botan example application which emulates a poorly written version of bzip2\n\nWritten by Jack Lloyd (lloyd@randombit.net), Jun 9, 2001\n\nThis file is in the public domain\n*\/\n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(BOTAN_EXT_COMPRESSOR_BZIP2)\n #include \n#endif\n\nconst std::string SUFFIX = \".bz2\";\n\nint main(int argc, char* argv[])\n {\n if(argc < 2)\n {\n std::cout << \"Usage: \" << argv[0]\n << \" [-s] [-d] [-1...9] \" << std::endl;\n return 1;\n }\n\n\n std::vector files;\n bool decompress = false, small = false;\n int level = 9;\n\n for(int j = 1; argv[j] != 0; j++)\n {\n if(std::strcmp(argv[j], \"-d\") == 0) { decompress = true; continue; }\n if(std::strcmp(argv[j], \"-s\") == 0) { small = true; continue; }\n if(std::strcmp(argv[j], \"-1\") == 0) { level = 1; continue; }\n if(std::strcmp(argv[j], \"-2\") == 0) { level = 2; continue; }\n if(std::strcmp(argv[j], \"-3\") == 0) { level = 3; continue; }\n if(std::strcmp(argv[j], \"-4\") == 0) { level = 4; continue; }\n if(std::strcmp(argv[j], \"-5\") == 0) { level = 5; continue; }\n if(std::strcmp(argv[j], \"-6\") == 0) { level = 6; continue; }\n if(std::strcmp(argv[j], \"-7\") == 0) { level = 7; continue; }\n if(std::strcmp(argv[j], \"-8\") == 0) { level = 8; continue; }\n if(std::strcmp(argv[j], \"-9\") == 0) { level = 9; continue; }\n files.push_back(argv[j]);\n }\n\n try {\n\n Botan::Filter* bzip = 0;\n#ifdef BOTAN_EXT_COMPRESSOR_BZIP2\n if(decompress)\n bzip = new Botan::Bzip_Decompression(small);\n else\n bzip = new Botan::Bzip_Compression(level);\n#endif\n\n if(!bzip)\n {\n std::cout << \"Sorry, support for bzip2 not compiled into Botan\\n\";\n return 1;\n }\n\n Botan::Pipe pipe(bzip);\n\n for(unsigned int j = 0; j != files.size(); j++)\n {\n std::string infile = files[j], outfile = files[j];\n if(!decompress)\n outfile = outfile += SUFFIX;\n else\n outfile = outfile.replace(outfile.find(SUFFIX),\n SUFFIX.length(), \"\");\n\n std::ifstream in(infile.c_str());\n std::ofstream out(outfile.c_str());\n if(!in)\n {\n std::cout << \"ERROR: could not read \" << infile << std::endl;\n continue;\n }\n if(!out)\n {\n std::cout << \"ERROR: could not write \" << outfile << std::endl;\n continue;\n }\n\n pipe.start_msg();\n in >> pipe;\n pipe.end_msg();\n pipe.set_default_msg(j);\n out << pipe;\n\n in.close();\n out.close();\n }\n }\n catch(std::exception& e)\n {\n std::cout << \"Exception caught: \" << e.what() << std::endl;\n return 1;\n }\n return 0;\n }\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkShader.h\"\n\nnamespace skiagm {\n\nclass BigMatrixGM : public GM {\npublic:\n BigMatrixGM() {\n this->setBGColor(0xFF66AA99);\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"bigmatrix\");\n }\n\n virtual SkISize onISize() {\n return make_isize(50, 50);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkMatrix m;\n m.reset();\n m.setRotate(33 * SK_Scalar1);\n m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1);\n m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1);\n canvas->concat(m);\n\n SkPaint paint;\n paint.setColor(SK_ColorRED);\n paint.setAntiAlias(true);\n\n m.invert(&m);\n\n SkPath path;\n\n SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1};\n SkScalar small = 1 \/ (500 * SK_Scalar1);\n\n m.mapPoints(&pt, 1);\n path.addCircle(pt.fX, pt.fY, small);\n canvas->drawPath(path, paint);\n\n pt.set(30 * SK_Scalar1, 10 * SK_Scalar1);\n m.mapPoints(&pt, 1);\n SkRect rect = {pt.fX - small, pt.fY - small,\n pt.fX + small, pt.fY + small};\n canvas->drawRect(rect, paint);\n\n SkBitmap bmp;\n bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n bmp.allocPixels();\n bmp.lockPixels();\n uint32_t* pixels = reinterpret_cast(bmp.getPixels());\n pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00);\n pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00);\n pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00);\n pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF);\n bmp.unlockPixels();\n pt.set(30 * SK_Scalar1, 30 * SK_Scalar1);\n m.mapPoints(&pt, 1);\n SkShader* shader = SkShader::CreateBitmapShader(\n bmp,\n SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n SkMatrix s;\n s.reset();\n s.setScale(SK_Scalar1 \/ 1000, SK_Scalar1 \/ 1000);\n shader->setLocalMatrix(s);\n paint.setShader(shader)->unref();\n paint.setAntiAlias(false);\n paint.setFilterBitmap(true);\n rect.setLTRB(pt.fX - small, pt.fY - small,\n pt.fX + small, pt.fY + small);\n canvas->drawRect(rect, paint);\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new BigMatrixGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n\nsilence warning\n\/*\n * Copyright 2012 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"gm.h\"\n\n#include \"SkColorPriv.h\"\n#include \"SkShader.h\"\n\nnamespace skiagm {\n\nclass BigMatrixGM : public GM {\npublic:\n BigMatrixGM() {\n this->setBGColor(0xFF66AA99);\n }\n\nprotected:\n virtual SkString onShortName() {\n return SkString(\"bigmatrix\");\n }\n\n virtual SkISize onISize() {\n return make_isize(50, 50);\n }\n\n virtual void onDraw(SkCanvas* canvas) {\n SkMatrix m;\n m.reset();\n m.setRotate(33 * SK_Scalar1);\n m.postScale(3000 * SK_Scalar1, 3000 * SK_Scalar1);\n m.postTranslate(6000 * SK_Scalar1, -5000 * SK_Scalar1);\n canvas->concat(m);\n\n SkPaint paint;\n paint.setColor(SK_ColorRED);\n paint.setAntiAlias(true);\n\n bool success = m.invert(&m);\n\n SkPath path;\n\n SkPoint pt = {10 * SK_Scalar1, 10 * SK_Scalar1};\n SkScalar small = 1 \/ (500 * SK_Scalar1);\n\n m.mapPoints(&pt, 1);\n path.addCircle(pt.fX, pt.fY, small);\n canvas->drawPath(path, paint);\n\n pt.set(30 * SK_Scalar1, 10 * SK_Scalar1);\n m.mapPoints(&pt, 1);\n SkRect rect = {pt.fX - small, pt.fY - small,\n pt.fX + small, pt.fY + small};\n canvas->drawRect(rect, paint);\n\n SkBitmap bmp;\n bmp.setConfig(SkBitmap::kARGB_8888_Config, 2, 2);\n bmp.allocPixels();\n bmp.lockPixels();\n uint32_t* pixels = reinterpret_cast(bmp.getPixels());\n pixels[0] = SkPackARGB32(0xFF, 0xFF, 0x00, 0x00);\n pixels[1] = SkPackARGB32(0xFF, 0x00, 0xFF, 0x00);\n pixels[2] = SkPackARGB32(0x80, 0x00, 0x00, 0x00);\n pixels[3] = SkPackARGB32(0xFF, 0x00, 0x00, 0xFF);\n bmp.unlockPixels();\n pt.set(30 * SK_Scalar1, 30 * SK_Scalar1);\n m.mapPoints(&pt, 1);\n SkShader* shader = SkShader::CreateBitmapShader(\n bmp,\n SkShader::kRepeat_TileMode,\n SkShader::kRepeat_TileMode);\n SkMatrix s;\n s.reset();\n s.setScale(SK_Scalar1 \/ 1000, SK_Scalar1 \/ 1000);\n shader->setLocalMatrix(s);\n paint.setShader(shader)->unref();\n paint.setAntiAlias(false);\n paint.setFilterBitmap(true);\n rect.setLTRB(pt.fX - small, pt.fY - small,\n pt.fX + small, pt.fY + small);\n canvas->drawRect(rect, paint);\n }\n\nprivate:\n typedef GM INHERITED;\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic GM* MyFactory(void*) { return new BigMatrixGM; }\nstatic GMRegistry reg(MyFactory);\n\n}\n\n<|endoftext|>"} {"text":"#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"shared.hpp\"\r\n#include \"controller.hpp\"\r\n#include \"logging.hpp\"\r\n#include \"invoker.hpp\"\r\n#include \"export.hpp\"\r\n#include \"client\\client.hpp\"\r\n#include \"extensions.hpp\"\r\n#include \"shared\\functions.hpp\"\r\n\r\nINITIALIZE_EASYLOGGINGPP\r\n\r\nextern \"C\"\r\n{\r\n __declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function);\r\n};\r\n\r\n\r\n\r\nstatic char version[] = \"1.0\";\r\n\r\nstd::string get_command(const std::string & input) {\r\n size_t cmd_end;\r\n std::string command;\r\n\r\n cmd_end = input.find(':');\r\n if (cmd_end < 1) {\r\n return \"\";\r\n }\r\n\r\n return input.substr(0, cmd_end);\r\n}\r\n\r\nstd::atomic_bool _threaded = false;\r\n\r\nvoid __stdcall RVExtension(char *output, int outputSize, const char *function) {\r\n DebugBreak();\r\n ZERO_OUTPUT();\r\n \r\n \/\/ Get the command, then the command args\r\n std::string input = function;\r\n\r\n std::string command = get_command(input);\r\n bool block_execute = false;\r\n\r\n std::string argument_str;\r\n if (command.length() > 1 && input.length() > command.length() + 1) {\r\n argument_str = input.substr(command.length() + 1, (input.length() + 1 - command.length()));\r\n }\r\n intercept::arguments _args(argument_str);\r\n\r\n std::string result = \"-1\";\r\n _threaded = false;\r\n if (command.size() < 1) {\r\n output[0] = 0x00;\r\n return;\r\n }\r\n if (command == \"version\") {\r\n result = version;\r\n }\r\n else if (command == \"echo\") {\r\n result = function;\r\n }\r\n else if (command == \"async\") {\r\n _threaded = true;\r\n result = \"0\";\r\n }\r\n else if (command == \"stop\") {\r\n _threaded = false;\r\n }\r\n\r\n if (command == \"init_patch\") {\r\n uintptr_t game_state_addr = (uintptr_t)*(uintptr_t *)((uintptr_t)output + outputSize + 8);\r\n intercept::loader::get().do_function_walk(game_state_addr);\r\n return;\r\n }\r\n\r\n if (command == \"block_execute\") {\r\n block_execute = true;\r\n command = _args.as_string(0);\r\n _threaded = false;\r\n }\r\n if (block_execute) {\r\n intercept::invoker::get().allow_access();\r\n }\r\n intercept::controller::get().call(command, _args, result, _threaded);\r\n if (block_execute) {\r\n intercept::invoker::get().deny_access();\r\n }\r\n if (result.length() > 0) {\r\n sprintf_s(output, outputSize, \"%s\", result.c_str());\r\n }\r\n EXTENSION_RETURN();\r\n}\r\n\r\n\r\n\r\n\r\nintercept::client_functions intercept::client::host::functions;\r\n\r\n\r\nvoid Init(void) {\r\n intercept::client::host::functions = intercept::extensions::get().functions;\r\n el::Configurations conf;\r\n\r\n conf.setGlobally(el::ConfigurationType::Filename, \"logs\/intercept_dll.log\");\r\n conf.setGlobally(el::ConfigurationType::MaxLogFileSize, \"10240\");\r\n#ifdef _DEBUG\r\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"[%datetime] - %level - {%loc}t:%thread- %msg\");\r\n conf.setGlobally(el::ConfigurationType::PerformanceTracking, \"true\");\r\n#else\r\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"%datetime-{%level}- %msg\");\r\n#endif\r\n el::Loggers::setDefaultConfigurations(conf, true);\r\n\r\n LOG(INFO) << \"Intercept DLL Loaded\";\r\n}\r\n\r\nvoid Cleanup(void) {\r\n\r\n}\r\n\r\n\r\nBOOL APIENTRY DllMain(HMODULE hModule,\r\n DWORD ul_reason_for_call,\r\n LPVOID lpReserved\r\n )\r\n{\r\n switch (ul_reason_for_call)\r\n {\r\n case DLL_PROCESS_ATTACH:\r\n Init();\r\n break;\r\n case DLL_THREAD_ATTACH:\r\n case DLL_THREAD_DETACH:\r\n case DLL_PROCESS_DETACH:\r\n Cleanup();\r\n break;\r\n }\r\n return TRUE;\r\n}\r\nDon't commit DebugBreaks!#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"shared.hpp\"\r\n#include \"controller.hpp\"\r\n#include \"logging.hpp\"\r\n#include \"invoker.hpp\"\r\n#include \"export.hpp\"\r\n#include \"client\\client.hpp\"\r\n#include \"extensions.hpp\"\r\n#include \"shared\\functions.hpp\"\r\n\r\nINITIALIZE_EASYLOGGINGPP\r\n\r\nextern \"C\"\r\n{\r\n __declspec(dllexport) void __stdcall RVExtension(char *output, int outputSize, const char *function);\r\n};\r\n\r\n\r\n\r\nstatic char version[] = \"1.0\";\r\n\r\nstd::string get_command(const std::string & input) {\r\n size_t cmd_end;\r\n std::string command;\r\n\r\n cmd_end = input.find(':');\r\n if (cmd_end < 1) {\r\n return \"\";\r\n }\r\n\r\n return input.substr(0, cmd_end);\r\n}\r\n\r\nstd::atomic_bool _threaded = false;\r\n\r\nvoid __stdcall RVExtension(char *output, int outputSize, const char *function) {\r\n ZERO_OUTPUT();\r\n \r\n \/\/ Get the command, then the command args\r\n std::string input = function;\r\n\r\n std::string command = get_command(input);\r\n bool block_execute = false;\r\n\r\n std::string argument_str;\r\n if (command.length() > 1 && input.length() > command.length() + 1) {\r\n argument_str = input.substr(command.length() + 1, (input.length() + 1 - command.length()));\r\n }\r\n intercept::arguments _args(argument_str);\r\n\r\n std::string result = \"-1\";\r\n _threaded = false;\r\n if (command.size() < 1) {\r\n output[0] = 0x00;\r\n return;\r\n }\r\n if (command == \"version\") {\r\n result = version;\r\n }\r\n else if (command == \"echo\") {\r\n result = function;\r\n }\r\n else if (command == \"async\") {\r\n _threaded = true;\r\n result = \"0\";\r\n }\r\n else if (command == \"stop\") {\r\n _threaded = false;\r\n }\r\n\r\n if (command == \"init_patch\") {\r\n uintptr_t game_state_addr = (uintptr_t)*(uintptr_t *)((uintptr_t)output + outputSize + 8);\r\n intercept::loader::get().do_function_walk(game_state_addr);\r\n return;\r\n }\r\n\r\n if (command == \"block_execute\") {\r\n block_execute = true;\r\n command = _args.as_string(0);\r\n _threaded = false;\r\n }\r\n if (block_execute) {\r\n intercept::invoker::get().allow_access();\r\n }\r\n intercept::controller::get().call(command, _args, result, _threaded);\r\n if (block_execute) {\r\n intercept::invoker::get().deny_access();\r\n }\r\n if (result.length() > 0) {\r\n sprintf_s(output, outputSize, \"%s\", result.c_str());\r\n }\r\n EXTENSION_RETURN();\r\n}\r\n\r\n\r\n\r\n\r\nintercept::client_functions intercept::client::host::functions;\r\n\r\n\r\nvoid Init(void) {\r\n intercept::client::host::functions = intercept::extensions::get().functions;\r\n el::Configurations conf;\r\n\r\n conf.setGlobally(el::ConfigurationType::Filename, \"logs\/intercept_dll.log\");\r\n conf.setGlobally(el::ConfigurationType::MaxLogFileSize, \"10240\");\r\n#ifdef _DEBUG\r\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"[%datetime] - %level - {%loc}t:%thread- %msg\");\r\n conf.setGlobally(el::ConfigurationType::PerformanceTracking, \"true\");\r\n#else\r\n el::Loggers::reconfigureAllLoggers(el::ConfigurationType::Format, \"%datetime-{%level}- %msg\");\r\n#endif\r\n el::Loggers::setDefaultConfigurations(conf, true);\r\n\r\n LOG(INFO) << \"Intercept DLL Loaded\";\r\n}\r\n\r\nvoid Cleanup(void) {\r\n\r\n}\r\n\r\n\r\nBOOL APIENTRY DllMain(HMODULE hModule,\r\n DWORD ul_reason_for_call,\r\n LPVOID lpReserved\r\n )\r\n{\r\n switch (ul_reason_for_call)\r\n {\r\n case DLL_PROCESS_ATTACH:\r\n Init();\r\n break;\r\n case DLL_THREAD_ATTACH:\r\n case DLL_THREAD_DETACH:\r\n case DLL_PROCESS_DETACH:\r\n Cleanup();\r\n break;\r\n }\r\n return TRUE;\r\n}\r\n<|endoftext|>"} {"text":"\/* Copyright (c) 2013, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tepollsocket.h\"\n#include \"tepollhttpsocket.h\"\n#include \"tepoll.h\"\n#include \"tsendbuffer.h\"\n#include \"tfcore.h\"\n\nclass SendData;\n\nstatic int sendBufSize = 0;\nstatic int recvBufSize = 0;\n\n\nTEpollSocket *TEpollSocket::accept(int listeningSocket)\n{\n struct sockaddr_storage addr;\n socklen_t addrlen = sizeof(addr);\n\n int actfd = tf_accept4(listeningSocket, (sockaddr *)&addr, &addrlen, SOCK_CLOEXEC | SOCK_NONBLOCK);\n int err = errno;\n if (Q_UNLIKELY(actfd < 0)) {\n if (err != EAGAIN) {\n tSystemWarn(\"Failed accept. errno:%d\", err);\n }\n return NULL;\n }\n\n return create(actfd, QHostAddress((sockaddr *)&addr));\n}\n\n\nTEpollSocket *TEpollSocket::create(int socketDescriptor, const QHostAddress &address)\n{\n TEpollSocket *sock = 0;\n\n if (Q_LIKELY(socketDescriptor > 0)) {\n sock = new TEpollHttpSocket(socketDescriptor, address);\n sock->moveToThread(Tf::app()->thread());\n\n initBuffer(socketDescriptor);\n }\n\n return sock;\n}\n\n\nTSendBuffer *TEpollSocket::createSendBuffer(const QByteArray &header, const QFileInfo &file, bool autoRemove, const TAccessLogger &logger)\n{\n return new TSendBuffer(header, file, autoRemove, logger);\n}\n\n\nTSendBuffer *TEpollSocket::createSendBuffer(const QByteArray &data)\n{\n return new TSendBuffer(data);\n}\n\n\nvoid TEpollSocket::initBuffer(int socketDescriptor)\n{\n const int BUF_SIZE = 128 * 1024;\n\n if (Q_UNLIKELY(sendBufSize == 0)) {\n \/\/ Creates a common buffer\n int res;\n socklen_t optlen;\n\n optlen = sizeof(int);\n res = getsockopt(socketDescriptor, SOL_SOCKET, SO_SNDBUF, &sendBufSize, &optlen);\n if (res < 0)\n sendBufSize = BUF_SIZE;\n\n optlen = sizeof(int);\n res = getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &recvBufSize, &optlen);\n if (res < 0)\n recvBufSize = BUF_SIZE;\n\n }\n}\n\n\nTEpollSocket::TEpollSocket(int socketDescriptor, const QHostAddress &address)\n : deleting(false), myWorkerCounter(0), pollIn(false), pollOut(false),\n sd(socketDescriptor), uuid(), clientAddr(address)\n{\n uuid = QUuid::createUuid().toByteArray(); \/\/ not thread safe\n uuid = uuid.mid(1, uuid.length() - 2);\n tSystemDebug(\"TEpollSocket id:%s\", uuid.data());\n}\n\n\nTEpollSocket::~TEpollSocket()\n{\n tSystemDebug(\"TEpollSocket::destructor\");\n\n close();\n\n for (auto p : sendBuf) {\n delete p;\n }\n sendBuf.clear();\n}\n\n\n\/*!\n Receives data\n @return 0:success -1:error\n *\/\nint TEpollSocket::recv()\n{\n int ret = 0;\n int err = 0;\n int len;\n\n for (;;) {\n void *buf = getRecvBuffer(recvBufSize);\n errno = 0;\n len = tf_recv(sd, buf, recvBufSize, 0);\n err = errno;\n\n if (len <= 0) {\n break;\n }\n\n \/\/ Read successfully\n seekRecvBuffer(len);\n }\n\n if (len < 0) {\n switch (err) {\n case EAGAIN:\n break;\n\n case ECONNRESET:\n tSystemDebug(\"Socket disconnected : sd:%d errno:%d\", sd, err);\n ret = -1;\n break;\n\n default:\n tSystemError(\"Failed recv : sd:%d errno:%d\", sd, err);\n ret = -1;\n break;\n }\n }\n return ret;\n}\n\n\/*!\n Sends data\n @return 0:success -1:error\n *\/\nint TEpollSocket::send()\n{\n if (sendBuf.isEmpty()) {\n pollOut = true;\n return 0;\n }\n pollOut = false;\n\n if (deleting.load()) {\n return 0;\n }\n\n int ret = 0;\n int err = 0;\n int len;\n\n while (!sendBuf.isEmpty()) {\n TSendBuffer *buf = sendBuf.first();\n TAccessLogger &logger = buf->accessLogger();\n\n err = 0;\n for (;;) {\n len = sendBufSize;\n void *data = buf->getData(len);\n if (len == 0) {\n break;\n }\n\n errno = 0;\n len = tf_send(sd, data, len, MSG_NOSIGNAL);\n err = errno;\n\n if (len <= 0) {\n break;\n }\n\n \/\/ Sent successfully\n buf->seekData(len);\n logger.setResponseBytes(logger.responseBytes() + len);\n }\n\n if (buf->atEnd()) {\n logger.write(); \/\/ Writes access log\n delete sendBuf.dequeue(); \/\/ delete send-buffer obj\n }\n\n if (len < 0) {\n switch (err) {\n case EAGAIN:\n break;\n\n case EPIPE: \/\/ FALL THROUGH\n case ECONNRESET:\n tSystemDebug(\"Socket disconnected : sd:%d errno:%d\", sd, err);\n logger.setResponseBytes(-1);\n ret = -1;\n break;\n\n default:\n tSystemError(\"Failed send : sd:%d errno:%d len:%d\", sd, err, len);\n logger.setResponseBytes(-1);\n ret = -1;\n break;\n }\n\n break;\n }\n }\n return ret;\n}\n\n\nvoid TEpollSocket::enqueueSendData(TSendBuffer *buffer)\n{\n sendBuf << buffer;\n}\n\n\nvoid TEpollSocket::setSocketDescpriter(int socketDescriptor)\n{\n sd = socketDescriptor;\n}\n\n\nvoid TEpollSocket::close()\n{\n if (sd > 0) {\n tf_close(sd);\n sd = 0;\n }\n}\n\n\nvoid TEpollSocket::sendData(const QByteArray &header, QIODevice *body, bool autoRemove, const TAccessLogger &accessLogger)\n{\n if (!deleting.load()) {\n TEpoll::instance()->setSendData(this, header, body, autoRemove, accessLogger);\n }\n}\n\n\nvoid TEpollSocket::sendData(const QByteArray &data)\n{\n if (!deleting.load()) {\n TEpoll::instance()->setSendData(this, data);\n }\n}\n\n\nvoid TEpollSocket::disconnect()\n{\n if (!deleting.load())\n TEpoll::instance()->setDisconnect(this);\n}\n\n\nvoid TEpollSocket::switchToWebSocket(const THttpRequestHeader &header)\n{\n if (!deleting.load())\n TEpoll::instance()->setSwitchToWebSocket(this, header);\n}\n\n\nqint64 TEpollSocket::bufferedBytes() const\n{\n qint64 ret = 0;\n for (auto &d : sendBuf) {\n ret += d->arrayBuffer.size();\n if (d->bodyFile) {\n ret += d->bodyFile->size();\n }\n }\n return ret;\n}\n\n\nint TEpollSocket::bufferedListCount() const\n{\n return sendBuf.count();\n}\n\n\nvoid TEpollSocket::deleteLater()\n{\n tSystemDebug(\"TEpollSocket::deleteLater countWorker:%d\", (int)myWorkerCounter);\n deleting = true;\n if ((int)myWorkerCounter == 0) {\n QObject::deleteLater();\n }\n}\nbugfix of recv of TEpollSocket.\/* Copyright (c) 2013, AOYAMA Kazuharu\n * All rights reserved.\n *\n * This software may be used and distributed according to the terms of\n * the New BSD License, which is incorporated herein by reference.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"tepollsocket.h\"\n#include \"tepollhttpsocket.h\"\n#include \"tepoll.h\"\n#include \"tsendbuffer.h\"\n#include \"tfcore.h\"\n\nclass SendData;\n\nstatic int sendBufSize = 0;\nstatic int recvBufSize = 0;\n\n\nTEpollSocket *TEpollSocket::accept(int listeningSocket)\n{\n struct sockaddr_storage addr;\n socklen_t addrlen = sizeof(addr);\n\n int actfd = tf_accept4(listeningSocket, (sockaddr *)&addr, &addrlen, SOCK_CLOEXEC | SOCK_NONBLOCK);\n int err = errno;\n if (Q_UNLIKELY(actfd < 0)) {\n if (err != EAGAIN) {\n tSystemWarn(\"Failed accept. errno:%d\", err);\n }\n return NULL;\n }\n\n return create(actfd, QHostAddress((sockaddr *)&addr));\n}\n\n\nTEpollSocket *TEpollSocket::create(int socketDescriptor, const QHostAddress &address)\n{\n TEpollSocket *sock = 0;\n\n if (Q_LIKELY(socketDescriptor > 0)) {\n sock = new TEpollHttpSocket(socketDescriptor, address);\n sock->moveToThread(Tf::app()->thread());\n\n initBuffer(socketDescriptor);\n }\n\n return sock;\n}\n\n\nTSendBuffer *TEpollSocket::createSendBuffer(const QByteArray &header, const QFileInfo &file, bool autoRemove, const TAccessLogger &logger)\n{\n return new TSendBuffer(header, file, autoRemove, logger);\n}\n\n\nTSendBuffer *TEpollSocket::createSendBuffer(const QByteArray &data)\n{\n return new TSendBuffer(data);\n}\n\n\nvoid TEpollSocket::initBuffer(int socketDescriptor)\n{\n const int BUF_SIZE = 128 * 1024;\n\n if (Q_UNLIKELY(sendBufSize == 0)) {\n \/\/ Creates a common buffer\n int res;\n socklen_t optlen;\n\n optlen = sizeof(int);\n res = getsockopt(socketDescriptor, SOL_SOCKET, SO_SNDBUF, &sendBufSize, &optlen);\n if (res < 0)\n sendBufSize = BUF_SIZE;\n\n optlen = sizeof(int);\n res = getsockopt(socketDescriptor, SOL_SOCKET, SO_RCVBUF, &recvBufSize, &optlen);\n if (res < 0)\n recvBufSize = BUF_SIZE;\n\n }\n}\n\n\nTEpollSocket::TEpollSocket(int socketDescriptor, const QHostAddress &address)\n : deleting(false), myWorkerCounter(0), pollIn(false), pollOut(false),\n sd(socketDescriptor), uuid(), clientAddr(address)\n{\n uuid = QUuid::createUuid().toByteArray(); \/\/ not thread safe\n uuid = uuid.mid(1, uuid.length() - 2);\n tSystemDebug(\"TEpollSocket id:%s\", uuid.data());\n}\n\n\nTEpollSocket::~TEpollSocket()\n{\n tSystemDebug(\"TEpollSocket::destructor\");\n\n close();\n\n for (auto p : sendBuf) {\n delete p;\n }\n sendBuf.clear();\n}\n\n\n\/*!\n Receives data\n @return 0:success -1:error\n *\/\nint TEpollSocket::recv()\n{\n int ret = 0;\n int err = 0;\n int len;\n\n for (;;) {\n void *buf = getRecvBuffer(recvBufSize);\n errno = 0;\n len = tf_recv(sd, buf, recvBufSize, 0);\n err = errno;\n\n if (len <= 0) {\n break;\n }\n\n \/\/ Read successfully\n seekRecvBuffer(len);\n }\n\n if (len < 0 || err > 0) {\n switch (err) {\n case EAGAIN:\n break;\n\n case ECONNRESET:\n tSystemDebug(\"Socket disconnected : sd:%d errno:%d\", sd, err);\n ret = -1;\n break;\n\n default:\n tSystemError(\"Failed recv : sd:%d errno:%d len:%d\", sd, err, len);\n ret = -1;\n break;\n }\n }\n return ret;\n}\n\n\/*!\n Sends data\n @return 0:success -1:error\n *\/\nint TEpollSocket::send()\n{\n if (sendBuf.isEmpty()) {\n pollOut = true;\n return 0;\n }\n pollOut = false;\n\n if (deleting.load()) {\n return 0;\n }\n\n int ret = 0;\n int err = 0;\n int len;\n\n while (!sendBuf.isEmpty()) {\n TSendBuffer *buf = sendBuf.first();\n TAccessLogger &logger = buf->accessLogger();\n\n err = 0;\n for (;;) {\n len = sendBufSize;\n void *data = buf->getData(len);\n if (len == 0) {\n break;\n }\n\n errno = 0;\n len = tf_send(sd, data, len, MSG_NOSIGNAL);\n err = errno;\n\n if (len <= 0) {\n break;\n }\n\n \/\/ Sent successfully\n buf->seekData(len);\n logger.setResponseBytes(logger.responseBytes() + len);\n }\n\n if (buf->atEnd()) {\n logger.write(); \/\/ Writes access log\n delete sendBuf.dequeue(); \/\/ delete send-buffer obj\n }\n\n if (len < 0) {\n switch (err) {\n case EAGAIN:\n break;\n\n case EPIPE: \/\/ FALL THROUGH\n case ECONNRESET:\n tSystemDebug(\"Socket disconnected : sd:%d errno:%d\", sd, err);\n logger.setResponseBytes(-1);\n ret = -1;\n break;\n\n default:\n tSystemError(\"Failed send : sd:%d errno:%d len:%d\", sd, err, len);\n logger.setResponseBytes(-1);\n ret = -1;\n break;\n }\n\n break;\n }\n }\n return ret;\n}\n\n\nvoid TEpollSocket::enqueueSendData(TSendBuffer *buffer)\n{\n sendBuf << buffer;\n}\n\n\nvoid TEpollSocket::setSocketDescpriter(int socketDescriptor)\n{\n sd = socketDescriptor;\n}\n\n\nvoid TEpollSocket::close()\n{\n if (sd > 0) {\n tf_close(sd);\n sd = 0;\n }\n}\n\n\nvoid TEpollSocket::sendData(const QByteArray &header, QIODevice *body, bool autoRemove, const TAccessLogger &accessLogger)\n{\n if (!deleting.load()) {\n TEpoll::instance()->setSendData(this, header, body, autoRemove, accessLogger);\n }\n}\n\n\nvoid TEpollSocket::sendData(const QByteArray &data)\n{\n if (!deleting.load()) {\n TEpoll::instance()->setSendData(this, data);\n }\n}\n\n\nvoid TEpollSocket::disconnect()\n{\n if (!deleting.load())\n TEpoll::instance()->setDisconnect(this);\n}\n\n\nvoid TEpollSocket::switchToWebSocket(const THttpRequestHeader &header)\n{\n if (!deleting.load())\n TEpoll::instance()->setSwitchToWebSocket(this, header);\n}\n\n\nqint64 TEpollSocket::bufferedBytes() const\n{\n qint64 ret = 0;\n for (auto &d : sendBuf) {\n ret += d->arrayBuffer.size();\n if (d->bodyFile) {\n ret += d->bodyFile->size();\n }\n }\n return ret;\n}\n\n\nint TEpollSocket::bufferedListCount() const\n{\n return sendBuf.count();\n}\n\n\nvoid TEpollSocket::deleteLater()\n{\n tSystemDebug(\"TEpollSocket::deleteLater countWorker:%d\", (int)myWorkerCounter);\n deleting = true;\n if ((int)myWorkerCounter == 0) {\n QObject::deleteLater();\n }\n}\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n#include \"applications\/include\/makevolume_core.h\"\n\nTEST(Applications_Makevolume, indexing_single_entry_array) {\n long unsigned index[1] = {1};\n float array[100] = {5};\n\n ASSERT_EQ(index[0], indexing(1, array)[0]);\n}\n\nTEST(Applications_Makevolume, indexing_simple_array) {\n long unsigned index[5] = {1, 2, 3, 4, 5};\n float array[5] = {5, 6, 7, 8, 9};\n\n long unsigned* result = indexing(5, array);\n \n for (int i = 0; i < 5; i++)\n ASSERT_EQ(index[i], result[i]);\n}\n\nTEST(Applications_Makevolume, indexing_reverse_array) {\n long unsigned index[4] = {4, 3, 2, 1};\n float array[4] = {1000.97, 234.1, 200, 1.32435};\n\n long unsigned* result = indexing(4, array);\n\n for (int i = 0; i < 4; i++)\n ASSERT_EQ(index[i], result[i]);\n} \nAdded random test#include \"gtest\/gtest.h\"\n#include \"applications\/include\/makevolume_core.h\"\n\nTEST(Applications_Makevolume, indexing_single_entry_array) {\n long unsigned index[1] = {1};\n float array[100] = {5};\n\n ASSERT_EQ(index[0], indexing(1, array)[0]);\n}\n\nTEST(Applications_Makevolume, indexing_simple_array) {\n long unsigned index[5] = {1, 2, 3, 4, 5};\n float array[5] = {5, 6, 7, 8, 9};\n\n long unsigned* result = indexing(5, array);\n \n for (int i = 0; i < 5; i++)\n ASSERT_EQ(index[i], result[i]);\n}\n\nTEST(Applications_Makevolume, indexing_reverse_array) {\n long unsigned index[4] = {4, 3, 2, 1};\n float array[4] = {1000.97, 234.1, 200, 1.32435};\n\n long unsigned* result = indexing(4, array);\n\n for (int i = 0; i < 4; i++)\n ASSERT_EQ(index[i], result[i]);\n}\n\nTEST(Applications_Makevolume, indexing_random_array) {\n long unsigned index[10] = {1, 3, 6, 4, 7, 2, 8, 5, 10, 9};\n float array[10] = {3.34, 8.234, 4.1, 6.1324, 10.354235, 5.12, 7.123, 9.2345, 12.32, 11.0};\n\n long unsigned* result = indexing(10, array);\n\n for (int i = 0; i < 10; i++)\n ASSERT_EQ(index[i], result[i]);\n} \n<|endoftext|>"} {"text":"\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"Creeper.h\"\n#include \"..\/World.h\"\n#include \"..\/Entities\/ProjectileEntity.h\"\n#include \"..\/Entities\/Player.h\"\n\n\n\n\n\ncCreeper::cCreeper(void) :\n\tsuper(\"Creeper\", mtCreeper, \"mob.creeper.say\", \"mob.creeper.say\", 0.6, 1.8),\n\tm_bIsBlowing(false),\n\tm_bIsCharged(false),\n\tm_BurnedWithFlintAndSteel(false),\n\tm_ExplodingTimer(0)\n{\n}\n\n\n\n\n\nvoid cCreeper::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)\n{\n\tsuper::Tick(a_Dt, a_Chunk);\n\n\tif (!TargetIsInRange() && !m_BurnedWithFlintAndSteel)\n\t{\n\t\tif (m_bIsBlowing)\n\t\t{\n\t\t\tm_ExplodingTimer = 0;\n\t\t\tm_bIsBlowing = false;\n\t\t\tm_World->BroadcastEntityMetadata(*this);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (m_bIsBlowing)\n\t\t{\n\t\t\tm_ExplodingTimer += 1;\n\t\t}\n\n\t\tif ((m_ExplodingTimer == 30) && (GetHealth() > 0.0)) \/\/ only explode when not already dead\n\t\t{\n\t\t\tm_World->DoExplosionAt((m_bIsCharged ? 5 : 3), GetPosX(), GetPosY(), GetPosZ(), false, esMonster, this);\n\t\t\tDestroy(); \/\/ Just in case we aren't killed by the explosion\n\t\t}\n\t}\n}\n\n\n\n\n\nvoid cCreeper::GetDrops(cItems & a_Drops, cEntity * a_Killer)\n{\n\tif (m_ExplodingTimer == 30)\n\t{\n\t\t\/\/ Exploded creepers drop naught but charred flesh, which Minecraft doesn't have\n\t\treturn;\n\t}\n\n\tunsigned int LootingLevel = 0;\n\tif (a_Killer != nullptr)\n\t{\n\t\tLootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting);\n\t}\n\tAddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_GUNPOWDER);\n\n\t\/\/ If the creeper was killed by a skeleton, add a random music disc drop:\n\tif (\n\t\t(a_Killer != nullptr) &&\n\t\ta_Killer->IsProjectile() &&\n\t\t((reinterpret_cast(a_Killer))->GetCreatorUniqueID() != cEntity::INVALID_ID))\n\t{\n\t\tclass cProjectileCreatorCallback : public cEntityCallback\n\t\t{\n\t\tpublic:\n\t\t\tcProjectileCreatorCallback(void) {}\n\n\t\t\tvirtual bool Item(cEntity * a_Entity) override\n\t\t\t{\n\t\t\t\tif (a_Entity->IsMob() && ((reinterpret_cast(a_Entity))->GetMobType() == mtSkeleton))\n\t\t\t\t{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} PCC;\n\t\tif (GetWorld()->DoWithEntityByID((reinterpret_cast(a_Killer))->GetCreatorUniqueID(), PCC))\n\t\t{\n\t\t\tAddRandomDropItem(a_Drops, 1, 1, static_cast(m_World->GetTickRandomNumber(11) + E_ITEM_FIRST_DISC));\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cCreeper::DoTakeDamage(TakeDamageInfo & a_TDI)\n{\n\tif (!super::DoTakeDamage(a_TDI))\n\t{\n\t\treturn false;\n\t}\n\n\tif (a_TDI.DamageType == dtLightning)\n\t{\n\t\tm_bIsCharged = true;\n\t}\n\n\tm_World->BroadcastEntityMetadata(*this);\n\treturn true;\n}\n\n\n\n\n\nbool cCreeper::Attack(std::chrono::milliseconds a_Dt)\n{\n\tUNUSED(a_Dt);\n\n\tif (!m_bIsBlowing)\n\t{\n\t\tm_World->BroadcastSoundEffect(\"game.tnt.primed\", GetPosX(), GetPosY(), GetPosZ(), 1.f, (0.75f + (static_cast((GetUniqueID() * 23) % 32)) \/ 64));\n\t\tm_bIsBlowing = true;\n\t\tm_World->BroadcastEntityMetadata(*this);\n\t\t\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n\n\n\nvoid cCreeper::OnRightClicked(cPlayer & a_Player)\n{\n\tif ((a_Player.GetEquippedItem().m_ItemType == E_ITEM_FLINT_AND_STEEL))\n\t{\n\t\tif (!a_Player.IsGameModeCreative())\n\t\t{\n\t\t\ta_Player.UseEquippedItem();\n\t\t}\n\t\tm_World->BroadcastSoundEffect(\"game.tnt.primed\", GetPosX(), GetPosY(), GetPosZ(), 1.f, (0.75f + (static_cast((GetUniqueID() * 23) % 32)) \/ 64));\n\t\tm_bIsBlowing = true;\n\t\tm_World->BroadcastEntityMetadata(*this);\n\t\tm_BurnedWithFlintAndSteel = true;\n\t}\n}\n\nFixed creeper calling TargetIsInRange with null m_Target\n#include \"Globals.h\" \/\/ NOTE: MSVC stupidness requires this to be the same across all modules\n\n#include \"Creeper.h\"\n#include \"..\/World.h\"\n#include \"..\/Entities\/ProjectileEntity.h\"\n#include \"..\/Entities\/Player.h\"\n\n\n\n\n\ncCreeper::cCreeper(void) :\n\tsuper(\"Creeper\", mtCreeper, \"mob.creeper.say\", \"mob.creeper.say\", 0.6, 1.8),\n\tm_bIsBlowing(false),\n\tm_bIsCharged(false),\n\tm_BurnedWithFlintAndSteel(false),\n\tm_ExplodingTimer(0)\n{\n}\n\n\n\n\n\nvoid cCreeper::Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk)\n{\n\tsuper::Tick(a_Dt, a_Chunk);\n\n\tif ((m_Target == nullptr) || (!TargetIsInRange() && !m_BurnedWithFlintAndSteel))\n\t{\n\t\tif (m_bIsBlowing)\n\t\t{\n\t\t\tm_ExplodingTimer = 0;\n\t\t\tm_bIsBlowing = false;\n\t\t\tm_World->BroadcastEntityMetadata(*this);\n\t\t}\n\t}\n\telse\n\t{\n\t\tif (m_bIsBlowing)\n\t\t{\n\t\t\tm_ExplodingTimer += 1;\n\t\t}\n\n\t\tif ((m_ExplodingTimer == 30) && (GetHealth() > 0.0)) \/\/ only explode when not already dead\n\t\t{\n\t\t\tm_World->DoExplosionAt((m_bIsCharged ? 5 : 3), GetPosX(), GetPosY(), GetPosZ(), false, esMonster, this);\n\t\t\tDestroy(); \/\/ Just in case we aren't killed by the explosion\n\t\t}\n\t}\n}\n\n\n\n\n\nvoid cCreeper::GetDrops(cItems & a_Drops, cEntity * a_Killer)\n{\n\tif (m_ExplodingTimer == 30)\n\t{\n\t\t\/\/ Exploded creepers drop naught but charred flesh, which Minecraft doesn't have\n\t\treturn;\n\t}\n\n\tunsigned int LootingLevel = 0;\n\tif (a_Killer != nullptr)\n\t{\n\t\tLootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting);\n\t}\n\tAddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_GUNPOWDER);\n\n\t\/\/ If the creeper was killed by a skeleton, add a random music disc drop:\n\tif (\n\t\t(a_Killer != nullptr) &&\n\t\ta_Killer->IsProjectile() &&\n\t\t((reinterpret_cast(a_Killer))->GetCreatorUniqueID() != cEntity::INVALID_ID))\n\t{\n\t\tclass cProjectileCreatorCallback : public cEntityCallback\n\t\t{\n\t\tpublic:\n\t\t\tcProjectileCreatorCallback(void) {}\n\n\t\t\tvirtual bool Item(cEntity * a_Entity) override\n\t\t\t{\n\t\t\t\tif (a_Entity->IsMob() && ((reinterpret_cast(a_Entity))->GetMobType() == mtSkeleton))\n\t\t\t\t{\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} PCC;\n\t\tif (GetWorld()->DoWithEntityByID((reinterpret_cast(a_Killer))->GetCreatorUniqueID(), PCC))\n\t\t{\n\t\t\tAddRandomDropItem(a_Drops, 1, 1, static_cast(m_World->GetTickRandomNumber(11) + E_ITEM_FIRST_DISC));\n\t\t}\n\t}\n}\n\n\n\n\n\nbool cCreeper::DoTakeDamage(TakeDamageInfo & a_TDI)\n{\n\tif (!super::DoTakeDamage(a_TDI))\n\t{\n\t\treturn false;\n\t}\n\n\tif (a_TDI.DamageType == dtLightning)\n\t{\n\t\tm_bIsCharged = true;\n\t}\n\n\tm_World->BroadcastEntityMetadata(*this);\n\treturn true;\n}\n\n\n\n\n\nbool cCreeper::Attack(std::chrono::milliseconds a_Dt)\n{\n\tUNUSED(a_Dt);\n\n\tif (!m_bIsBlowing)\n\t{\n\t\tm_World->BroadcastSoundEffect(\"game.tnt.primed\", GetPosX(), GetPosY(), GetPosZ(), 1.f, (0.75f + (static_cast((GetUniqueID() * 23) % 32)) \/ 64));\n\t\tm_bIsBlowing = true;\n\t\tm_World->BroadcastEntityMetadata(*this);\n\n\t\treturn true;\n\t}\n\treturn false;\n}\n\n\n\n\n\nvoid cCreeper::OnRightClicked(cPlayer & a_Player)\n{\n\tif ((a_Player.GetEquippedItem().m_ItemType == E_ITEM_FLINT_AND_STEEL))\n\t{\n\t\tif (!a_Player.IsGameModeCreative())\n\t\t{\n\t\t\ta_Player.UseEquippedItem();\n\t\t}\n\t\tm_World->BroadcastSoundEffect(\"game.tnt.primed\", GetPosX(), GetPosY(), GetPosZ(), 1.f, (0.75f + (static_cast((GetUniqueID() * 23) % 32)) \/ 64));\n\t\tm_bIsBlowing = true;\n\t\tm_World->BroadcastEntityMetadata(*this);\n\t\tm_BurnedWithFlintAndSteel = true;\n\t}\n}\n\n<|endoftext|>"} {"text":"core: fix MSA build<|endoftext|>"} {"text":"\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/\n\/\/ osdep.cc\n\/\/ \n\/\/ Provide definition of library functions that are missing on various\n\/\/ systems. The only reason this is a .cc file rather than a .c file\n\/\/ is so that it can include bochs.h. Bochs.h includes all the required\n\/\/ system headers, with appropriate #ifdefs for different compilers and \n\/\/ platforms.\n\/\/\n\n#include \"bochs.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Missing library functions. These should work on any platform \n\/\/ that needs them.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if !BX_HAVE_SNPRINTF\n\/* XXX use real snprintf *\/\n\/* if they don't have snprintf, just use sprintf *\/\nint bx_snprintf (char *s, size_t maxlen, const char *format, ...)\n{\n va_list arg;\n int done;\n\n va_start (arg, format);\n done = vsprintf (s, format, arg);\n va_end (arg);\n\n return done;\n}\n#endif \/* !BX_HAVE_SNPRINTF *\/\n\n\n#if (!BX_HAVE_STRTOULL && !BX_HAVE_STRTOUQ)\n\/* taken from glibc-2.2.2: strtod.c, and stripped down a lot. There are \n still a few leftover references to decimal points and exponents, \n but it works for bases 10 and 16 *\/\n\n#define RETURN(val,end)\t\t\t\t\t\t\t \\\n do { if (endptr != NULL) *endptr = (char *) (end);\t\t \\\n\t return val; } while (0)\n\nBit64u\nbx_strtoull (const char *nptr, char **endptr, int baseignore)\n{\n int negative;\t\t\t\/* The sign of the number. *\/\n int exponent;\t\t\t\/* Exponent of the number. *\/\n\n \/* Numbers starting `0X' or `0x' have to be processed with base 16. *\/\n int base = 10;\n\n \/* Number of bits currently in result value. *\/\n int bits;\n\n \/* Running pointer after the last character processed in the string. *\/\n const char *cp, *tp;\n \/* Start of significant part of the number. *\/\n const char *startp, *start_of_digits;\n \/* Total number of digit and number of digits in integer part. *\/\n int dig_no;\n \/* Contains the last character read. *\/\n char c;\n\n long long n = 0;\n char const *p;\n\n \/* Prepare number representation. *\/\n exponent = 0;\n negative = 0;\n bits = 0;\n\n \/* Parse string to get maximal legal prefix. We need the number of\n characters of the integer part, the fractional part and the exponent. *\/\n cp = nptr - 1;\n \/* Ignore leading white space. *\/\n do\n c = *++cp;\n while (isspace (c));\n\n \/* Get sign of the result. *\/\n if (c == '-')\n {\n negative = 1;\n c = *++cp;\n }\n else if (c == '+')\n c = *++cp;\n\n if (c < '0' || c > '9')\n {\n \/* It is really a text we do not recognize. *\/\n RETURN (0, nptr);\n }\n\n \/* First look whether we are faced with a hexadecimal number. *\/\n if (c == '0' && tolower (cp[1]) == 'x')\n {\n \/* Okay, it is a hexa-decimal number. Remember this and skip\n\t the characters. BTW: hexadecimal numbers must not be\n\t grouped. *\/\n base = 16;\n cp += 2;\n c = *cp;\n }\n\n \/* Record the start of the digits, in case we will check their grouping. *\/\n start_of_digits = startp = cp;\n\n \/* Ignore leading zeroes. This helps us to avoid useless computations. *\/\n while (c == '0')\n c = *++cp;\n\n \/* If no other digit but a '0' is found the result is 0.0.\n Return current read pointer. *\/\n if ((c < '0' || c > '9')\n && (base == 16 && (c < tolower ('a') || c > tolower ('f')))\n && (base == 16 && (cp == start_of_digits || tolower (c) != 'p'))\n && (base != 16 && tolower (c) != 'e'))\n {\n tp = start_of_digits;\n \/* If TP is at the start of the digits, there was no correctly\n\t grouped prefix of the string; so no number found. *\/\n RETURN (0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp);\n }\n\n \/* Remember first significant digit and read following characters until the\n decimal point, exponent character or any non-FP number character. *\/\n startp = cp;\n dig_no = 0;\n while (1)\n {\n if ((c >= '0' && c <= '9')\n\t || (base == 16 && tolower (c) >= 'a' && tolower (c) <= 'f'))\n\t++dig_no;\n else\n\tbreak;\n c = *++cp;\n }\n\n \/* The whole string is parsed. Store the address of the next character. *\/\n if (endptr)\n *endptr = (char *) cp;\n\n if (dig_no == 0) \n return 0;\n\n for (p=start_of_digits; p!=cp; p++) {\n n = n * (long long)base;\n c = tolower (*p);\n c = (c >= 'a') ? (10+c-'a') : c-'0';\n n = n + (long long)c;\n \/\/printf (\"after shifting in digit %c, n is %lld\\n\", *p, n);\n }\n return negative? -n : n;\n}\n#endif \/* !BX_HAVE_STRTOULL *\/\n\n#if BX_TEST_STRTOULL_MAIN\n\/* test driver for strtoull. Do not compile by default. *\/\nint main (int argc, char **argv)\n{\n char buf[256], *endbuf;\n long l;\n long long ll;\n while (1) {\n printf (\"Enter a long int: \");\n gets (buf);\n l = strtoul (buf, &endbuf, 10);\n printf (\"As a long, %ld\\n\", l);\n printf (\"Endbuf is at buf[%d]\\n\", endbuf-buf);\n ll = bx_strtoull (buf, &endbuf, 10);\n printf (\"As a long long, %lld\\n\", ll);\n printf (\"Endbuf is at buf[%d]\\n\", endbuf-buf);\n }\n return 0;\n}\n#endif \/* BX_TEST_STRTOULL_MAIN *\/\n\n#if !BX_HAVE_STRDUP\n\/* XXX use real strdup *\/\nchar *bx_strdup(const char *str)\n{\n\tchar *temp;\n\t\n\ttemp = malloc(strlen(str));\n\tsprintf(temp, \"%s\", str);\n\treturn temp;\n\t\n\t\/\/ Well, I'm sure this isn't how strdup is REALLY implemented,\n\t\/\/ but it works...\n}\n#endif \/* !BX_HAVE_STRDUP *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Missing library functions, implemented for MacOS only\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if BX_WITH_MACOS\n\/\/ these functions are part of MacBochs. They are not intended to be\n\/\/ portable!\n#include \n#include \n\nint fd_read(char *buffer, Bit32u offset, Bit32u bytes)\n{\n\tOSErr err;\n\tIOParam param;\n\t\n\tparam.ioRefNum=-5; \/\/ Refnum of the floppy disk driver\n\tparam.ioVRefNum=1;\n\tparam.ioPosMode=fsFromStart;\n\tparam.ioPosOffset=offset;\n\tparam.ioBuffer=buffer;\n\tparam.ioReqCount=bytes;\n\terr = PBReadSync((union ParamBlockRec *)(¶m));\n\treturn param.ioActCount;\n}\n\nint fd_write(char *buffer, Bit32u offset, Bit32u bytes)\n{\n\tOSErr\t\terr;\n\tIOParam\tparam;\n\t\n\tparam.ioRefNum=-5; \/\/ Refnum of the floppy disk driver\n\tparam.ioVRefNum=1;\n\tparam.ioPosMode=fsFromStart;\n\tparam.ioPosOffset=offset;\n\tparam.ioBuffer=buffer;\n\tparam.ioReqCount=bytes;\n\terr = PBWriteSync((union ParamBlockRec *)(¶m));\n\treturn param.ioActCount;\n}\n\nint fd_stat(struct stat *buf)\n{\n\tOSErr\t\terr;\n\tDrvSts\tstatus;\n\tint\t\t\tresult;\n\t\n\tresult = 0;\n\terr = DriveStatus(1, &status);\n\tif (status.diskInPlace <1 || status.diskInPlace > 2)\n\t\tresult = -1;\n\tbuf->st_mode = S_IFCHR;\n\treturn result;\n}\n#endif \/* BX_WITH_MACOS *\/\n- Patch from Mike Lerwill turn \"long long\" into Bit64s\/\/ Copyright (C) 2001 MandrakeSoft S.A.\n\/\/\n\/\/ MandrakeSoft S.A.\n\/\/ 43, rue d'Aboukir\n\/\/ 75002 Paris - France\n\/\/ http:\/\/www.linux-mandrake.com\/\n\/\/ http:\/\/www.mandrakesoft.com\/\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\/\/\n\/\/ osdep.cc\n\/\/ \n\/\/ Provide definition of library functions that are missing on various\n\/\/ systems. The only reason this is a .cc file rather than a .c file\n\/\/ is so that it can include bochs.h. Bochs.h includes all the required\n\/\/ system headers, with appropriate #ifdefs for different compilers and \n\/\/ platforms.\n\/\/\n\n#include \"bochs.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Missing library functions. These should work on any platform \n\/\/ that needs them.\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if !BX_HAVE_SNPRINTF\n\/* XXX use real snprintf *\/\n\/* if they don't have snprintf, just use sprintf *\/\nint bx_snprintf (char *s, size_t maxlen, const char *format, ...)\n{\n va_list arg;\n int done;\n\n va_start (arg, format);\n done = vsprintf (s, format, arg);\n va_end (arg);\n\n return done;\n}\n#endif \/* !BX_HAVE_SNPRINTF *\/\n\n\n#if (!BX_HAVE_STRTOULL && !BX_HAVE_STRTOUQ)\n\/* taken from glibc-2.2.2: strtod.c, and stripped down a lot. There are \n still a few leftover references to decimal points and exponents, \n but it works for bases 10 and 16 *\/\n\n#define RETURN(val,end)\t\t\t\t\t\t\t \\\n do { if (endptr != NULL) *endptr = (char *) (end);\t\t \\\n\t return val; } while (0)\n\nBit64u\nbx_strtoull (const char *nptr, char **endptr, int baseignore)\n{\n int negative;\t\t\t\/* The sign of the number. *\/\n int exponent;\t\t\t\/* Exponent of the number. *\/\n\n \/* Numbers starting `0X' or `0x' have to be processed with base 16. *\/\n int base = 10;\n\n \/* Number of bits currently in result value. *\/\n int bits;\n\n \/* Running pointer after the last character processed in the string. *\/\n const char *cp, *tp;\n \/* Start of significant part of the number. *\/\n const char *startp, *start_of_digits;\n \/* Total number of digit and number of digits in integer part. *\/\n int dig_no;\n \/* Contains the last character read. *\/\n char c;\n\n Bit64s n = 0;\n char const *p;\n\n \/* Prepare number representation. *\/\n exponent = 0;\n negative = 0;\n bits = 0;\n\n \/* Parse string to get maximal legal prefix. We need the number of\n characters of the integer part, the fractional part and the exponent. *\/\n cp = nptr - 1;\n \/* Ignore leading white space. *\/\n do\n c = *++cp;\n while (isspace (c));\n\n \/* Get sign of the result. *\/\n if (c == '-')\n {\n negative = 1;\n c = *++cp;\n }\n else if (c == '+')\n c = *++cp;\n\n if (c < '0' || c > '9')\n {\n \/* It is really a text we do not recognize. *\/\n RETURN (0, nptr);\n }\n\n \/* First look whether we are faced with a hexadecimal number. *\/\n if (c == '0' && tolower (cp[1]) == 'x')\n {\n \/* Okay, it is a hexa-decimal number. Remember this and skip\n\t the characters. BTW: hexadecimal numbers must not be\n\t grouped. *\/\n base = 16;\n cp += 2;\n c = *cp;\n }\n\n \/* Record the start of the digits, in case we will check their grouping. *\/\n start_of_digits = startp = cp;\n\n \/* Ignore leading zeroes. This helps us to avoid useless computations. *\/\n while (c == '0')\n c = *++cp;\n\n \/* If no other digit but a '0' is found the result is 0.0.\n Return current read pointer. *\/\n if ((c < '0' || c > '9')\n && (base == 16 && (c < tolower ('a') || c > tolower ('f')))\n && (base == 16 && (cp == start_of_digits || tolower (c) != 'p'))\n && (base != 16 && tolower (c) != 'e'))\n {\n tp = start_of_digits;\n \/* If TP is at the start of the digits, there was no correctly\n\t grouped prefix of the string; so no number found. *\/\n RETURN (0, tp == start_of_digits ? (base == 16 ? cp - 1 : nptr) : tp);\n }\n\n \/* Remember first significant digit and read following characters until the\n decimal point, exponent character or any non-FP number character. *\/\n startp = cp;\n dig_no = 0;\n while (1)\n {\n if ((c >= '0' && c <= '9')\n\t || (base == 16 && tolower (c) >= 'a' && tolower (c) <= 'f'))\n\t++dig_no;\n else\n\tbreak;\n c = *++cp;\n }\n\n \/* The whole string is parsed. Store the address of the next character. *\/\n if (endptr)\n *endptr = (char *) cp;\n\n if (dig_no == 0) \n return 0;\n\n for (p=start_of_digits; p!=cp; p++) {\n n = n * (Bit64s)base;\n c = tolower (*p);\n c = (c >= 'a') ? (10+c-'a') : c-'0';\n n = n + (Bit64s)c;\n \/\/printf (\"after shifting in digit %c, n is %lld\\n\", *p, n);\n }\n return negative? -n : n;\n}\n#endif \/* !BX_HAVE_STRTOULL *\/\n\n#if BX_TEST_STRTOULL_MAIN\n\/* test driver for strtoull. Do not compile by default. *\/\nint main (int argc, char **argv)\n{\n char buf[256], *endbuf;\n long l;\n Bit64s ll;\n while (1) {\n printf (\"Enter a long int: \");\n gets (buf);\n l = strtoul (buf, &endbuf, 10);\n printf (\"As a long, %ld\\n\", l);\n printf (\"Endbuf is at buf[%d]\\n\", endbuf-buf);\n ll = bx_strtoull (buf, &endbuf, 10);\n printf (\"As a long long, %lld\\n\", ll);\n printf (\"Endbuf is at buf[%d]\\n\", endbuf-buf);\n }\n return 0;\n}\n#endif \/* BX_TEST_STRTOULL_MAIN *\/\n\n#if !BX_HAVE_STRDUP\n\/* XXX use real strdup *\/\nchar *bx_strdup(const char *str)\n{\n\tchar *temp;\n\t\n\ttemp = malloc(strlen(str));\n\tsprintf(temp, \"%s\", str);\n\treturn temp;\n\t\n\t\/\/ Well, I'm sure this isn't how strdup is REALLY implemented,\n\t\/\/ but it works...\n}\n#endif \/* !BX_HAVE_STRDUP *\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Missing library functions, implemented for MacOS only\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#if BX_WITH_MACOS\n\/\/ these functions are part of MacBochs. They are not intended to be\n\/\/ portable!\n#include \n#include \n\nint fd_read(char *buffer, Bit32u offset, Bit32u bytes)\n{\n\tOSErr err;\n\tIOParam param;\n\t\n\tparam.ioRefNum=-5; \/\/ Refnum of the floppy disk driver\n\tparam.ioVRefNum=1;\n\tparam.ioPosMode=fsFromStart;\n\tparam.ioPosOffset=offset;\n\tparam.ioBuffer=buffer;\n\tparam.ioReqCount=bytes;\n\terr = PBReadSync((union ParamBlockRec *)(¶m));\n\treturn param.ioActCount;\n}\n\nint fd_write(char *buffer, Bit32u offset, Bit32u bytes)\n{\n\tOSErr\t\terr;\n\tIOParam\tparam;\n\t\n\tparam.ioRefNum=-5; \/\/ Refnum of the floppy disk driver\n\tparam.ioVRefNum=1;\n\tparam.ioPosMode=fsFromStart;\n\tparam.ioPosOffset=offset;\n\tparam.ioBuffer=buffer;\n\tparam.ioReqCount=bytes;\n\terr = PBWriteSync((union ParamBlockRec *)(¶m));\n\treturn param.ioActCount;\n}\n\nint fd_stat(struct stat *buf)\n{\n\tOSErr\t\terr;\n\tDrvSts\tstatus;\n\tint\t\t\tresult;\n\t\n\tresult = 0;\n\terr = DriveStatus(1, &status);\n\tif (status.diskInPlace <1 || status.diskInPlace > 2)\n\t\tresult = -1;\n\tbuf->st_mode = S_IFCHR;\n\treturn result;\n}\n#endif \/* BX_WITH_MACOS *\/\n<|endoftext|>"} {"text":"\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2021 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n#ifndef __YLIKUUTIO_CALLBACK_CALLBACK_ENGINE_HPP_INCLUDED\n#define __YLIKUUTIO_CALLBACK_CALLBACK_ENGINE_HPP_INCLUDED\n\n#include \"input_parameters_and_any_value_to_any_value_callback_with_universe.hpp\"\n#include \"code\/ylikuutio\/data\/any_value.hpp\"\n#include \"code\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include standard headers\n#include \/\/ std::size_t\n#include \/\/ std::make_shared, std::shared_ptr\n#include \/\/ std::queue\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace yli::ontology\n{\n class Universe;\n}\n\nnamespace yli::callback\n{\n class CallbackObject;\n\n class CallbackEngine\n {\n \/\/ `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.\n \/\/ `CallbackEngine` provides a way to create callback chains.\n \/\/\n \/\/ Hierarchy of callbacks:\n \/\/\n \/\/ CallbackEngine\n \/\/ ^\n \/\/ CallbackObject\n \/\/ ^\n \/\/ CallbackParameter\n \/\/\n \/\/ How to use.\n \/\/ 1. Create a new `CallbackEngine`. No callbacks have been\n \/\/ defined yet. Calling `CallbackEngine.execute(nullptr)` at this\n \/\/ point will simply go through an empty vector and\n \/\/ practically won't do anything interesting.\n \/\/ 2. Create a new `CallbackObject`, give pointer to the\n \/\/ recently created `CallbackEngine` as input parameter.\n \/\/ 3. If the callback has parameter[s], create a new\n \/\/ `CallbackParameter` for each parameter, give `CallbackObject`\n \/\/ as input parameter for the `CallbackParameter` constructor.\n\n public:\n void bind_callback_object(yli::callback::CallbackObject* const callback_object);\n\n \/\/ constructor.\n CallbackEngine();\n\n \/\/ constructor.\n CallbackEngine(yli::ontology::Universe* const universe);\n\n \/\/ destructor.\n ~CallbackEngine();\n\n yli::callback::CallbackObject* create_callback_object();\n yli::callback::CallbackObject* create_callback_object(const InputParametersAndAnyValueToAnyValueCallbackWithUniverse callback);\n\n \/\/ execute all callbacks with a parameter.\n std::shared_ptr execute(std::shared_ptr any_value);\n\n std::size_t get_n_of_return_values() const;\n std::shared_ptr get_nth_return_value(std::size_t n) const;\n std::shared_ptr get_previous_return_value() const;\n\n yli::ontology::Universe* get_universe() const;\n\n private:\n \/\/ `CallbackEngine` is not an `Entity`.\n \/\/ Therefore they are not descendants of the `Universe`.\n \/\/ Some `CallbackEngine`s just have a pointer to the `Universe`.\n yli::ontology::Universe* universe { nullptr };\n\n \/\/ this method sets a callback object pointer.\n void set_callback_object_pointer(const std::size_t childID, yli::callback::CallbackObject* const child_pointer);\n\n std::vector callback_object_pointer_vector;\n std::queue free_callback_objectID_queue;\n std::size_t number_of_callback_objects { 0 };\n\n std::vector> return_values;\n };\n}\n\n#endif\n`CallbackEngine`: make 1 parameter constructor `explicit`.\/\/ Ylikuutio - A 3D game and simulation engine.\n\/\/\n\/\/ Copyright (C) 2015-2021 Antti Nuortimo.\n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as\n\/\/ published by the Free Software Foundation, either version 3 of the\n\/\/ License, or (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with this program. If not, see .\n\n#ifndef __YLIKUUTIO_CALLBACK_CALLBACK_ENGINE_HPP_INCLUDED\n#define __YLIKUUTIO_CALLBACK_CALLBACK_ENGINE_HPP_INCLUDED\n\n#include \"input_parameters_and_any_value_to_any_value_callback_with_universe.hpp\"\n#include \"code\/ylikuutio\/data\/any_value.hpp\"\n#include \"code\/ylikuutio\/hierarchy\/hierarchy_templates.hpp\"\n\n\/\/ Include standard headers\n#include \/\/ std::size_t\n#include \/\/ std::make_shared, std::shared_ptr\n#include \/\/ std::queue\n#include \/\/ std::string\n#include \/\/ std::vector\n\nnamespace yli::ontology\n{\n class Universe;\n}\n\nnamespace yli::callback\n{\n class CallbackObject;\n\n class CallbackEngine\n {\n \/\/ `CallbackEngine` is an object that contains some callbacks and hashmaps that are used for input and output parameters.\n \/\/ `CallbackEngine` provides a way to create callback chains.\n \/\/\n \/\/ Hierarchy of callbacks:\n \/\/\n \/\/ CallbackEngine\n \/\/ ^\n \/\/ CallbackObject\n \/\/ ^\n \/\/ CallbackParameter\n \/\/\n \/\/ How to use.\n \/\/ 1. Create a new `CallbackEngine`. No callbacks have been\n \/\/ defined yet. Calling `CallbackEngine.execute(nullptr)` at this\n \/\/ point will simply go through an empty vector and\n \/\/ practically won't do anything interesting.\n \/\/ 2. Create a new `CallbackObject`, give pointer to the\n \/\/ recently created `CallbackEngine` as input parameter.\n \/\/ 3. If the callback has parameter[s], create a new\n \/\/ `CallbackParameter` for each parameter, give `CallbackObject`\n \/\/ as input parameter for the `CallbackParameter` constructor.\n\n public:\n void bind_callback_object(yli::callback::CallbackObject* const callback_object);\n\n \/\/ constructor.\n CallbackEngine();\n\n \/\/ constructor.\n explicit CallbackEngine(yli::ontology::Universe* const universe);\n\n \/\/ destructor.\n ~CallbackEngine();\n\n yli::callback::CallbackObject* create_callback_object();\n yli::callback::CallbackObject* create_callback_object(const InputParametersAndAnyValueToAnyValueCallbackWithUniverse callback);\n\n \/\/ execute all callbacks with a parameter.\n std::shared_ptr execute(std::shared_ptr any_value);\n\n std::size_t get_n_of_return_values() const;\n std::shared_ptr get_nth_return_value(std::size_t n) const;\n std::shared_ptr get_previous_return_value() const;\n\n yli::ontology::Universe* get_universe() const;\n\n private:\n \/\/ `CallbackEngine` is not an `Entity`.\n \/\/ Therefore they are not descendants of the `Universe`.\n \/\/ Some `CallbackEngine`s just have a pointer to the `Universe`.\n yli::ontology::Universe* universe { nullptr };\n\n \/\/ this method sets a callback object pointer.\n void set_callback_object_pointer(const std::size_t childID, yli::callback::CallbackObject* const child_pointer);\n\n std::vector callback_object_pointer_vector;\n std::queue free_callback_objectID_queue;\n std::size_t number_of_callback_objects { 0 };\n\n std::vector> return_values;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"#include \"physicsEntity.h\"\n\n\/\/\n\/\/ CONSTRUCTORS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\nPhysicsEntity::PhysicsEntity( QString pathToModel, QString pathToTexture, \n btScalar mass, btTransform startingState )\n : m_pathToModel( pathToModel ), m_pathToTexture( pathToTexture ),\n m_mass( mass )\n{\n ModelLoader::loadModel( pathToModel, m_model, m_numVertices );\n ModelLoader::loadTriMesh( pathToModel, m_triMesh );\n\n \/\/ Initialize Bullet\n m_collisionShape = new btBvhTriangleMeshShape( m_triMesh, true );\n\n m_motionState = new btDefaultMotionState( startingState );\n \n Inertia = btVector3( 0, 0, 0 );\n\n m_collisionShape->calculateLocalInertia( m_mass, Inertia );\n m_rigidBodyCI = new btRigidBody::btRigidBodyConstructionInfo( \n m_mass, m_motionState, m_collisionShape, Inertia );\n\n RigidBody = new btRigidBody( *m_rigidBodyCI );\n\n \/\/ make static objects kinematic\n \/\/ see http:\/\/www.cse.unr.edu\/~fredh\/class\/480\/F2015\/proj\/PA08\/PA8.php\n if( mass == 0 )\n {\n RigidBody->setCollisionFlags(RigidBody->getCollisionFlags() | \n btCollisionObject::CF_KINEMATIC_OBJECT);\n RigidBody->setActivationState(DISABLE_DEACTIVATION);\n }\n}\n\nPhysicsEntity::~PhysicsEntity()\n{\n teardownGL();\n\n delete m_triMesh;\n delete m_collisionShape;\n delete m_motionState;\n delete m_rigidBodyCI;\n delete RigidBody;\n}\n\n\/\/\n\/\/ RENDERABLE FUNCTINOS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\nvoid PhysicsEntity::initializeGL()\n{\n initializeOpenGLFunctions();\n\n \/\/ Create the shader this entity will use\n m_program = new QOpenGLShaderProgram();\n m_program->addShaderFromSourceFile( QOpenGLShader::Vertex, \n PATH_TO_V_SHADER );\n m_program->addShaderFromSourceFile( QOpenGLShader::Fragment, \n PATH_TO_F_SHADER );\n m_program->link();\n m_program->bind();\n\n \/\/ Cache the Uniform Locations\n m_modelWorld = m_program->uniformLocation( \"model_to_world\" );\n m_worldEye = m_program->uniformLocation( \"world_to_eye\" );\n m_eyeClip = m_program->uniformLocation( \"eye_to_clip\" );\n\n \/\/ Create the Texture Buffer Object\n m_texture = new QOpenGLTexture( QImage( m_pathToTexture ).mirrored() );\n m_texture->setMinificationFilter( QOpenGLTexture::LinearMipMapLinear );\n m_texture->setMagnificationFilter( QOpenGLTexture::Linear );\n\n \/\/ Create the Vertex Buffer Object\n m_vbo = new QOpenGLBuffer();\n m_vbo->create();\n m_vbo->bind();\n m_vbo->setUsagePattern( QOpenGLBuffer::StaticDraw );\n m_vbo->allocate( m_model, m_numVertices * sizeof( m_model[0] ) );\n\n \/\/ Create the Vertex Array Object\n m_vao = new QOpenGLVertexArrayObject();\n m_vao->create();\n m_vao->bind();\n m_program->enableAttributeArray( 0 );\n m_program->enableAttributeArray( 1 );\n m_program->setAttributeBuffer( 0,\n GL_FLOAT,\n Vertex::positionOffset(),\n Vertex::PositionTupleSize,\n Vertex::stride() );\n m_program->setAttributeBuffer( 1,\n GL_FLOAT,\n Vertex::uvOffset(),\n Vertex::UVTupleSize,\n Vertex::stride() );\n\n \/\/ Release all in order\n m_vao->release();\n m_vbo->release();\n m_texture->release();\n m_program->release();\n}\n\nvoid PhysicsEntity::paintGL( Camera3D& camera, QMatrix4x4& projection )\n{\n m_program->bind();\n\n m_program->setUniformValue( m_worldEye, camera.toMatrix() );\n m_program->setUniformValue( m_eyeClip, projection );\n\n m_vao->bind();\n m_texture->bind();\n\n m_program->setUniformValue( m_modelWorld, Transform );\n\n glDrawArrays( GL_TRIANGLES, 0, m_numVertices );\n\n m_texture->release();\n m_vao->release();\n m_program->release();\n}\n\nvoid PhysicsEntity::update()\n{\n}\n\nvoid PhysicsEntity::teardownGL()\n{\n delete m_vbo;\n delete m_vao;\n delete m_program;\n delete m_model;\n delete m_texture;\n}COLLISION WORKS.#include \"physicsEntity.h\"\n\n\/\/\n\/\/ CONSTRUCTORS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\n\nPhysicsEntity::PhysicsEntity( QString pathToModel, QString pathToTexture, \n btScalar mass, btTransform startingState )\n : m_pathToModel( pathToModel ), m_pathToTexture( pathToTexture ),\n m_mass( mass )\n{\n ModelLoader::loadModel( pathToModel, m_model, m_numVertices );\n ModelLoader::loadTriMesh( pathToModel, m_triMesh );\n\n \/\/ Initialize Bullet\n if( mass == 0 )\n m_collisionShape = new btBvhTriangleMeshShape( m_triMesh, true );\n else\n m_collisionShape = new btConvexTriangleMeshShape( m_triMesh );\n\n m_motionState = new btDefaultMotionState( startingState );\n \n Inertia = btVector3( 0, 0, 0 );\n\n m_collisionShape->calculateLocalInertia( m_mass, Inertia );\n m_rigidBodyCI = new btRigidBody::btRigidBodyConstructionInfo( \n m_mass, m_motionState, m_collisionShape, Inertia );\n\n RigidBody = new btRigidBody( *m_rigidBodyCI );\n\n \/\/ make static objects kinematic\n \/\/ see http:\/\/www.cse.unr.edu\/~fredh\/class\/480\/F2015\/proj\/PA08\/PA8.php\n if( mass == 0 )\n {\n RigidBody->setCollisionFlags(RigidBody->getCollisionFlags() | \n btCollisionObject::CF_KINEMATIC_OBJECT);\n RigidBody->setActivationState(DISABLE_DEACTIVATION);\n }\n}\n\nPhysicsEntity::~PhysicsEntity()\n{\n teardownGL();\n\n delete m_triMesh;\n delete m_collisionShape;\n delete m_motionState;\n delete m_rigidBodyCI;\n delete RigidBody;\n}\n\n\/\/\n\/\/ RENDERABLE FUNCTINOS \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\nvoid PhysicsEntity::initializeGL()\n{\n initializeOpenGLFunctions();\n\n \/\/ Create the shader this entity will use\n m_program = new QOpenGLShaderProgram();\n m_program->addShaderFromSourceFile( QOpenGLShader::Vertex, \n PATH_TO_V_SHADER );\n m_program->addShaderFromSourceFile( QOpenGLShader::Fragment, \n PATH_TO_F_SHADER );\n m_program->link();\n m_program->bind();\n\n \/\/ Cache the Uniform Locations\n m_modelWorld = m_program->uniformLocation( \"model_to_world\" );\n m_worldEye = m_program->uniformLocation( \"world_to_eye\" );\n m_eyeClip = m_program->uniformLocation( \"eye_to_clip\" );\n\n \/\/ Create the Texture Buffer Object\n m_texture = new QOpenGLTexture( QImage( m_pathToTexture ).mirrored() );\n m_texture->setMinificationFilter( QOpenGLTexture::LinearMipMapLinear );\n m_texture->setMagnificationFilter( QOpenGLTexture::Linear );\n\n \/\/ Create the Vertex Buffer Object\n m_vbo = new QOpenGLBuffer();\n m_vbo->create();\n m_vbo->bind();\n m_vbo->setUsagePattern( QOpenGLBuffer::StaticDraw );\n m_vbo->allocate( m_model, m_numVertices * sizeof( m_model[0] ) );\n\n \/\/ Create the Vertex Array Object\n m_vao = new QOpenGLVertexArrayObject();\n m_vao->create();\n m_vao->bind();\n m_program->enableAttributeArray( 0 );\n m_program->enableAttributeArray( 1 );\n m_program->setAttributeBuffer( 0,\n GL_FLOAT,\n Vertex::positionOffset(),\n Vertex::PositionTupleSize,\n Vertex::stride() );\n m_program->setAttributeBuffer( 1,\n GL_FLOAT,\n Vertex::uvOffset(),\n Vertex::UVTupleSize,\n Vertex::stride() );\n\n \/\/ Release all in order\n m_vao->release();\n m_vbo->release();\n m_texture->release();\n m_program->release();\n}\n\nvoid PhysicsEntity::paintGL( Camera3D& camera, QMatrix4x4& projection )\n{\n m_program->bind();\n\n m_program->setUniformValue( m_worldEye, camera.toMatrix() );\n m_program->setUniformValue( m_eyeClip, projection );\n\n m_vao->bind();\n m_texture->bind();\n\n m_program->setUniformValue( m_modelWorld, Transform );\n\n glDrawArrays( GL_TRIANGLES, 0, m_numVertices );\n\n m_texture->release();\n m_vao->release();\n m_program->release();\n}\n\nvoid PhysicsEntity::update()\n{\n}\n\nvoid PhysicsEntity::teardownGL()\n{\n delete m_vbo;\n delete m_vao;\n delete m_program;\n delete m_model;\n delete m_texture;\n}<|endoftext|>"} {"text":"\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/bridge.h\"\n\n#include \n\n#include \"mlir\/IR\/Module.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/PassManager.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/Passes.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/passes.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/bridge_logger.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/dump_mlir_util.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/error_util.h\"\n\nnamespace mlir {\nnamespace {\n\/\/ Add logger to bridge passmanager.\nvoid EnableLogging(PassManager *pm) {\n \/\/ Print the whole module after each pass, which requires disabling\n \/\/ multi-threading as well.\n pm->getContext()->disableMultithreading();\n pm->enableIRPrinting(std::make_unique(\n \/*print_module_scope=*\/true));\n pm->enableTiming(std::make_unique());\n}\n} \/\/ namespace\n\nnamespace TFTPU {\nnamespace {\nvoid AddGraphExportLoweringPasses(OpPassManager &pm) {\n auto add_pass = [&](std::unique_ptr pass) {\n pm.addNestedPass(std::move(pass));\n pm.addPass(CreateBreakUpIslandsPass());\n };\n\n pm.addNestedPass(CreateFunctionalToExecutorDialectConversionPass());\n add_pass(TFDevice::CreateParallelizeEmbeddingParamsOpsPass());\n pm.addPass(TFDevice::CreateReplicateToIslandPass());\n pm.addPass(CreateBreakUpIslandsPass());\n add_pass(TFDevice::CreateParallelExecuteToIslandsPass());\n add_pass(TFDevice::CreateLaunchToDeviceAttributePass());\n}\n\ntensorflow::Status RunTPUBridge(\n ModuleOp module, bool enable_logging,\n llvm::function_ref pipeline_builder) {\n PassManager bridge(module.getContext());\n ::tensorflow::applyTensorflowAndCLOptions(bridge);\n if (enable_logging) EnableLogging(&bridge);\n\n \/\/ Populate a passmanager with the list of passes that implement the bridge.\n pipeline_builder(bridge);\n\n \/\/ Add set of passes to lower back to graph (from tf_executor).\n AddGraphExportLoweringPasses(bridge);\n\n \/\/ Run the bridge on the module, in case of failure, the `diag_handler`\n \/\/ converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.\n mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());\n LogicalResult result = bridge.run(module);\n (void)result;\n return diag_handler.ConsumeStatus();\n}\n} \/\/ namespace\n\nvoid CreateTPUBridgePipeline(OpPassManager &pm) {\n pm.addNestedPass(tf_executor::CreateTFExecutorGraphPruningPass());\n \/\/ It is assumed at this stage there are no V1 control flow ops as Graph\n \/\/ functionalization is ran before import. Ops can be lifted out of\n \/\/ tf_executor dialect islands\/graphs.\n pm.addNestedPass(CreateExecutorDialectToFunctionalConversionPass());\n \/\/ Run shape inference so that tf_executor\/tf_device ops created later will\n \/\/ likely to inherit more concrete types.\n pm.addPass(TF::CreateTFShapeInferencePass());\n \/\/ Encode this in its own scope so that func_pm is not mistakenly used\n \/\/ later on.\n {\n pm.addPass(CreateTPUClusterFormationPass());\n OpPassManager &func_pm = pm.nest();\n \/\/ Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass\n \/\/ because DecomposeResourceOpsPass uses pattern rewriter which hoists\n \/\/ changed constants out of tf_device.Launch.\n func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());\n func_pm.addPass(CreateTPUHostComputationExpansionPass());\n func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());\n }\n \/\/ Run another shape inference pass because resource decomposition might have\n \/\/ created new partial types.\n pm.addPass(TF::CreateTFShapeInferencePass());\n pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());\n pm.addPass(mlir::createInlinerPass());\n pm.addPass(CreateTPUClusterCleanupAttributesPass());\n pm.addPass(TFDevice::CreateResourceOpLiftingPass());\n pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());\n pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());\n pm.addPass(CreateTPUOutsideCompilationClusterPass());\n pm.addPass(CreateTPUExtractOutsideCompilationPass());\n\n pm.addNestedPass(tf_executor::CreateTFExecutorConstantSinkingPass());\n pm.addPass(TF::CreateResourceDeviceInferencePass());\n pm.addPass(TFDevice::CreateClusterOutliningPass());\n pm.addPass(CreateTPUDynamicPaddingMapperPass());\n pm.addPass(CreateTPUResourceReadForWritePass());\n pm.addPass(CreateTPUShardingIdentificationPass());\n pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());\n pm.addPass(CreateTPURewritePass());\n pm.addPass(createSymbolDCEPass());\n pm.addNestedPass(TFDevice::CreateReplicateInvariantOpHoistingPass());\n pm.addNestedPass(CreateTPUDynamicLayoutPass());\n pm.addNestedPass(CreateTPUMergeVariablesWithExecutePass());\n pm.addNestedPass(CreateTPUColocateCompositeResourceOps());\n pm.addPass(CreateTPUVariableReformattingPass());\n pm.addPass(TF::CreateTFRegionControlFlowToFunctional());\n}\n\nvoid CreateTPUBridgePipelineV1(OpPassManager &pm) {\n pm.addPass(TF::CreateTFShapeInferencePass());\n \/\/ For V1 compatibility, we process a module where the graph does not have\n \/\/ feeds and fetched. We extract first the TPU computation in a submodule,\n \/\/ where it'll be in a function with args and returned values, much more like\n \/\/ a TF v2 module. We can then run the usual pipeline on this nested module.\n \/\/ Afterward we inline back in the parent module and delete the nested one.\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());\n OpPassManager &nested_module = pm.nest();\n CreateTPUBridgePipeline(nested_module);\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());\n}\n\ntensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {\n return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);\n}\ntensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {\n return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);\n}\n\n} \/\/ namespace TFTPU\n\nnamespace TF {\n\ntensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,\n bool enable_logging,\n bool enable_inliner) {\n PassManager bridge(module.getContext());\n if (enable_logging) EnableLogging(&bridge);\n\n StandardPipelineOptions pipeline_options;\n pipeline_options.enable_inliner.setValue(enable_inliner);\n CreateTFStandardPipeline(bridge, pipeline_options);\n mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());\n LogicalResult result = bridge.run(module);\n (void)result;\n return diag_handler.ConsumeStatus();\n}\n\n} \/\/ namespace TF\n} \/\/ namespace mlir\nAdd TPUDevicePropagation pass to TPU bridge pipeline.\/* Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/bridge.h\"\n\n#include \n\n#include \"mlir\/IR\/Module.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/PassManager.h\" \/\/ from @llvm-project\n#include \"mlir\/Transforms\/Passes.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/transforms\/passes.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/bridge_logger.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/dump_mlir_util.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/utils\/error_util.h\"\n\nnamespace mlir {\nnamespace {\n\/\/ Add logger to bridge passmanager.\nvoid EnableLogging(PassManager *pm) {\n \/\/ Print the whole module after each pass, which requires disabling\n \/\/ multi-threading as well.\n pm->getContext()->disableMultithreading();\n pm->enableIRPrinting(std::make_unique(\n \/*print_module_scope=*\/true));\n pm->enableTiming(std::make_unique());\n}\n} \/\/ namespace\n\nnamespace TFTPU {\nnamespace {\nvoid AddGraphExportLoweringPasses(OpPassManager &pm) {\n auto add_pass = [&](std::unique_ptr pass) {\n pm.addNestedPass(std::move(pass));\n pm.addPass(CreateBreakUpIslandsPass());\n };\n\n pm.addNestedPass(CreateFunctionalToExecutorDialectConversionPass());\n add_pass(TFDevice::CreateParallelizeEmbeddingParamsOpsPass());\n pm.addPass(TFDevice::CreateReplicateToIslandPass());\n pm.addPass(CreateBreakUpIslandsPass());\n add_pass(TFDevice::CreateParallelExecuteToIslandsPass());\n add_pass(TFDevice::CreateLaunchToDeviceAttributePass());\n pm.addNestedPass(CreateTPUDevicePropagationPass());\n}\n\ntensorflow::Status RunTPUBridge(\n ModuleOp module, bool enable_logging,\n llvm::function_ref pipeline_builder) {\n PassManager bridge(module.getContext());\n ::tensorflow::applyTensorflowAndCLOptions(bridge);\n if (enable_logging) EnableLogging(&bridge);\n\n \/\/ Populate a passmanager with the list of passes that implement the bridge.\n pipeline_builder(bridge);\n\n \/\/ Add set of passes to lower back to graph (from tf_executor).\n AddGraphExportLoweringPasses(bridge);\n\n \/\/ Run the bridge on the module, in case of failure, the `diag_handler`\n \/\/ converts MLIR errors emitted to the MLIRContext into a tensorflow::Status.\n mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());\n LogicalResult result = bridge.run(module);\n (void)result;\n return diag_handler.ConsumeStatus();\n}\n} \/\/ namespace\n\nvoid CreateTPUBridgePipeline(OpPassManager &pm) {\n pm.addNestedPass(tf_executor::CreateTFExecutorGraphPruningPass());\n \/\/ It is assumed at this stage there are no V1 control flow ops as Graph\n \/\/ functionalization is ran before import. Ops can be lifted out of\n \/\/ tf_executor dialect islands\/graphs.\n pm.addNestedPass(CreateExecutorDialectToFunctionalConversionPass());\n \/\/ Run shape inference so that tf_executor\/tf_device ops created later will\n \/\/ likely to inherit more concrete types.\n pm.addPass(TF::CreateTFShapeInferencePass());\n \/\/ Encode this in its own scope so that func_pm is not mistakenly used\n \/\/ later on.\n {\n pm.addPass(CreateTPUClusterFormationPass());\n OpPassManager &func_pm = pm.nest();\n \/\/ Place DecomposeResourceOpsPass before TFExecutorConstantSinking pass\n \/\/ because DecomposeResourceOpsPass uses pattern rewriter which hoists\n \/\/ changed constants out of tf_device.Launch.\n func_pm.addPass(TFDevice::CreateDecomposeResourceOpsPass());\n func_pm.addPass(CreateTPUHostComputationExpansionPass());\n func_pm.addPass(CreateTPUUpdateEmbeddingEnqueueOpInputsPass());\n }\n \/\/ Run another shape inference pass because resource decomposition might have\n \/\/ created new partial types.\n pm.addPass(TF::CreateTFShapeInferencePass());\n pm.addPass(TF::CreateTFFunctionalControlFlowToRegions());\n pm.addPass(mlir::createInlinerPass());\n pm.addPass(CreateTPUClusterCleanupAttributesPass());\n pm.addPass(TFDevice::CreateResourceOpLiftingPass());\n pm.addPass(TFDevice::CreateMarkOpsForOutsideCompilationPass());\n pm.addPass(CreateTPUExtractHeadTailOutsideCompilationPass());\n pm.addPass(CreateTPUOutsideCompilationClusterPass());\n pm.addPass(CreateTPUExtractOutsideCompilationPass());\n\n pm.addNestedPass(tf_executor::CreateTFExecutorConstantSinkingPass());\n pm.addPass(TF::CreateResourceDeviceInferencePass());\n pm.addPass(TFDevice::CreateClusterOutliningPass());\n pm.addPass(CreateTPUDynamicPaddingMapperPass());\n pm.addPass(CreateTPUResourceReadForWritePass());\n pm.addPass(CreateTPUShardingIdentificationPass());\n pm.addPass(TFDevice::CreateAnnotateParameterReplicationPass());\n pm.addPass(CreateTPURewritePass());\n pm.addPass(createSymbolDCEPass());\n pm.addNestedPass(TFDevice::CreateReplicateInvariantOpHoistingPass());\n pm.addNestedPass(CreateTPUDynamicLayoutPass());\n pm.addNestedPass(CreateTPUMergeVariablesWithExecutePass());\n pm.addNestedPass(CreateTPUColocateCompositeResourceOps());\n pm.addPass(CreateTPUVariableReformattingPass());\n pm.addPass(TF::CreateTFRegionControlFlowToFunctional());\n}\n\nvoid CreateTPUBridgePipelineV1(OpPassManager &pm) {\n pm.addPass(TF::CreateTFShapeInferencePass());\n \/\/ For V1 compatibility, we process a module where the graph does not have\n \/\/ feeds and fetched. We extract first the TPU computation in a submodule,\n \/\/ where it'll be in a function with args and returned values, much more like\n \/\/ a TF v2 module. We can then run the usual pipeline on this nested module.\n \/\/ Afterward we inline back in the parent module and delete the nested one.\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandCoarseningPass());\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandOutliningPass());\n OpPassManager &nested_module = pm.nest();\n CreateTPUBridgePipeline(nested_module);\n pm.addPass(tf_executor::CreateTFExecutorTPUV1IslandInliningPass());\n}\n\ntensorflow::Status TPUBridge(ModuleOp module, bool enable_logging) {\n return RunTPUBridge(module, enable_logging, CreateTPUBridgePipeline);\n}\ntensorflow::Status TPUBridgeV1Compat(ModuleOp module, bool enable_logging) {\n return RunTPUBridge(module, enable_logging, CreateTPUBridgePipelineV1);\n}\n\n} \/\/ namespace TFTPU\n\nnamespace TF {\n\ntensorflow::Status RunBridgeWithStandardPipeline(ModuleOp module,\n bool enable_logging,\n bool enable_inliner) {\n PassManager bridge(module.getContext());\n if (enable_logging) EnableLogging(&bridge);\n\n StandardPipelineOptions pipeline_options;\n pipeline_options.enable_inliner.setValue(enable_inliner);\n CreateTFStandardPipeline(bridge, pipeline_options);\n mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext());\n LogicalResult result = bridge.run(module);\n (void)result;\n return diag_handler.ConsumeStatus();\n}\n\n} \/\/ namespace TF\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"\/\/ ConClient.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n#include \"Console.h\"\n#include \"cxxopts.hpp\"\n\n#ifdef _WIN32\nint _tmain(int argc, _TCHAR* argv[]) {\n#else \/* _WIN32 *\/\nint main(int argc, char* argv[]) {\n#endif \/* _WIN32 *\/\n using std::cout;\n using std::endl;\n\n std::string host;\n std::string file;\n bool keepOpen = false;\n\n cxxopts::Options options(\"remoteconsole.exe\", \"MegaMol Remote Lua Console Client\");\n options.add_options()\n (\"open\", \"open host\", cxxopts::value())\n (\"source\", \"source file\", cxxopts::value())\n (\"keep-open\", \"keep open\")\n (\"help\", \"print help\")\n ;\n\n try {\n options.parse(argc, argv);\n } catch (...) {\n std::cout << options.help({ \"\" }) << std::endl;\n exit(0);\n }\n\n if (options.count(\"help\")) {\n std::cout << options.help({ \"\" }) << std::endl;\n exit(0);\n }\n\n \/\/ greeting text\n printGreeting();\n\n host = options[\"open\"].as();\n file = options[\"source\"].as();\n keepOpen = options[\"keep-open\"].as();\n\n\n \/\/ Prepare our context and socket\n zmq::context_t context(1);\n zmq::socket_t socket(context, ZMQ_REQ);\n Connection conn(socket);\n\n if (!host.empty()) {\n cout << \"Connecting \\\"\" << host << \"\\\" ... \";\n try {\n conn.Connect(host);\n cout << endl\n << \"\\tConnected\" << endl\n << endl;\n\n } catch (std::exception& ex) {\n cout << endl\n << \"ERR Socket connection failed: \" << ex.what() << endl\n << endl;\n } catch (...) {\n cout << endl\n << \"ERR Socket connection failed: unknown exception\" << endl\n << endl;\n }\n }\n\n if (!file.empty()) { \n runScript(conn, file);\n\n } else {\n keepOpen = true;\n }\n\n if (keepOpen) {\n interactiveConsole(conn);\n }\n\n return 0;\n}\n\nfix for new cxxopts interface\/\/ ConClient.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \n#include \n#include \n#include \n#include \"Console.h\"\n#include \"cxxopts.hpp\"\n\n#ifdef _WIN32\nint _tmain(int argc, _TCHAR* argv[]) {\n#else \/* _WIN32 *\/\nint main(int argc, char* argv[]) {\n#endif \/* _WIN32 *\/\n using std::cout;\n using std::endl;\n\n std::string host;\n std::string file;\n bool keepOpen = false;\n\n cxxopts::Options options(\"remoteconsole.exe\", \"MegaMol Remote Lua Console Client\");\n options.add_options()\n (\"open\", \"open host\", cxxopts::value())\n (\"source\", \"source file\", cxxopts::value())\n (\"keep-open\", \"keep open\")\n (\"help\", \"print help\")\n ;\n\n try {\n\n auto parseRes = options.parse(argc, argv);\n\n if (parseRes.count(\"help\")) {\n std::cout << options.help({ \"\" }) << std::endl;\n exit(0);\n }\n\n \/\/ greeting text\n printGreeting();\n\n if (parseRes.count(\"open\")) host = parseRes[\"open\"].as();\n if (parseRes.count(\"source\")) file = parseRes[\"source\"].as();\n if (parseRes.count(\"keep-open\")) keepOpen = parseRes[\"keep-open\"].as();\n\n\n \/\/ Prepare our context and socket\n zmq::context_t context(1);\n zmq::socket_t socket(context, ZMQ_REQ);\n Connection conn(socket);\n\n if (!host.empty()) {\n cout << \"Connecting \\\"\" << host << \"\\\" ... \";\n try {\n conn.Connect(host);\n cout << endl\n << \"\\tConnected\" << endl\n << endl;\n\n } catch (std::exception& ex) {\n cout << endl\n << \"ERR Socket connection failed: \" << ex.what() << endl\n << endl;\n } catch (...) {\n cout << endl\n << \"ERR Socket connection failed: unknown exception\" << endl\n << endl;\n }\n }\n\n if (!file.empty()) {\n runScript(conn, file);\n\n } else {\n keepOpen = true;\n }\n\n if (keepOpen) {\n interactiveConsole(conn);\n }\n\n } catch (...) {\n std::cout << options.help({ \"\" }) << std::endl;\n exit(0);\n }\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/* $Id$ *\/\n\n\/*\n Produces the data needed to calculate the quality assurance. \n All data must be mergeable objects.\n Y. Schutz CERN July 2007\n*\/\n\n\/\/ --- ROOT system ---\n#include \n#include \n#include \n#include \n#include \n\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliESDCaloCluster.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n#include \"AliPHOSDigit.h\"\n#include \"AliPHOSHit.h\"\n#include \"AliPHOSQualAssDataMaker.h\"\n#include \"AliPHOSCpvRecPoint.h\" \n#include \"AliPHOSEmcRecPoint.h\" \n#include \"AliPHOSRecParticle.h\" \n#include \"AliPHOSTrackSegment.h\" \n#include \"AliPHOSRawDecoder.h\"\n\nClassImp(AliPHOSQualAssDataMaker)\n \n\/\/____________________________________________________________________________ \n AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker() : \n AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kPHOS), \"PHOS Quality Assurance Data Maker\")\n{\n \/\/ ctor\n}\n\n\/\/____________________________________________________________________________ \nAliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker(const AliPHOSQualAssDataMaker& qadm) :\n AliQualAssDataMaker()\n{\n \/\/copy ctor \n SetName((const char*)qadm.GetName()) ; \n SetTitle((const char*)qadm.GetTitle()); \n}\n\n\/\/__________________________________________________________________\nAliPHOSQualAssDataMaker& AliPHOSQualAssDataMaker::operator = (const AliPHOSQualAssDataMaker& qadm )\n{\n \/\/ Equal operator.\n this->~AliPHOSQualAssDataMaker();\n new(this) AliPHOSQualAssDataMaker(qadm);\n return *this;\n}\n \n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::EndOfDetectorCycle()\n{\n \/\/Detector specific actions at end of cycle\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitESDs()\n{\n \/\/create ESDs histograms in ESDs subdir\n TH1F * h0 = new TH1F(\"hPhosESDs\", \"ESDs energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ; \n Add2ESDsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosESDsMul\", \"ESDs multiplicity distribution in PHOS\", 100, 0., 100) ; \n h1->Sumw2() ;\n Add2ESDsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitHits()\n{\n \/\/ create Hits histograms in Hits subdir\n TH1F * h0 = new TH1F(\"hPhosHits\", \"Hits energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2HitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosHitsMul\", \"Hits multiplicity distribution in PHOS\", 500, 0., 10000) ; \n h1->Sumw2() ;\n Add2HitsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitDigits()\n{\n \/\/ create Digits histograms in Digits subdir\n TH1I * h0 = new TH1I(\"hPhosDigits\", \"Digits amplitude distribution in PHOS\", 500, 0, 5000) ; \n h0->Sumw2() ;\n Add2DigitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosDigitsMul\", \"Digits multiplicity distribution in PHOS\", 500, 0, 1000) ; \n h1->Sumw2() ;\n Add2DigitsList(h1, 0) ;\n}\n\n\/\/____________________________________________________________________________ \n\/\/void AliPHOSQualAssDataMaker::InitRecParticles()\n\/\/{\n\/\/ \/\/ create Reconstructed particles histograms in RecParticles subdir\n\/\/ fhRecParticles = new TH1F(\"hPhosRecParticles\", \"RecParticles energy distribution in PHOS\", 100, 0., 100.) ; \n\/\/ fhRecParticles->Sumw2() ;\n\/\/ fhRecParticlesMul = new TH1I(\"hPhosRecParticlesMul\", \"RecParticles multiplicity distribution in PHOS\", 100, 0, 100) ; \n\/\/ fhRecParticlesMul->Sumw2() ;\n\/\/}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitRecPoints()\n{\n \/\/ create Reconstructed Points histograms in RecPoints subdir\n TH1F * h0 = new TH1F(\"hEmcPhosRecPoints\", \"EMCA RecPoints energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2RecPointsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hEmcPhosRecPointsMul\", \"EMCA RecPoints multiplicity distribution in PHOS\", 100, 0, 100) ; \n h1->Sumw2() ;\n Add2RecPointsList(h1, 1) ;\n\n TH1F * h2 = new TH1F(\"hCpvPhosRecPoints\", \"CPV RecPoints energy distribution in PHOS\", 100, 0., 100.) ; \n h2->Sumw2() ;\n Add2RecPointsList(h2, 2) ;\n TH1I * h3 = new TH1I(\"hCpvPhosRecPointsMul\", \"CPV RecPoints multiplicity distribution in PHOS\", 100, 0, 100) ; \n h3->Sumw2() ;\n Add2RecPointsList(h3, 3) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitRaws()\n{\n \/\/ create Raws histograms in Raws subdir\n TH1I * h0 = new TH1I(\"hPhosModules\", \"Hits in EMCA PHOS modules\", 6, 0, 6) ; \n h0->Sumw2() ;\n Add2RawsList(h0, 0) ;\n const Int_t modMax = 5 ; \n TH2I * h1[modMax] ; \n for (Int_t mod = 0; mod < modMax; mod++) {\n char name[16] ; \n sprintf(name, \"hPHOSMod%d\", mod) ; \n char title[32] ; \n sprintf(title, \"Raws x Columns for PHOS module %d\", mod+1) ; \n h1[mod] = new TH2I(name, title, 64, 0, 63, 56, 0, 55) ; \n Add2RawsList(h1[mod], mod+1) ;\n }\n TH1F * h6 = new TH1F(\"hPhosRawtime\", \"Time of raw hits in PHOS\", 100, 0, 100.) ; \n h6->Sumw2() ;\n Add2RawsList(h6, 6) ;\n TH1F * h7 = new TH1F(\"hPhosRawEnergy\", \"Energy of raw hits in PHOS\", 1000, 0., 1200.) ; \n h7->Sumw2() ;\n Add2RawsList(h7, 7) ;\n \n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitSDigits()\n{\n \/\/ create SDigits histograms in SDigits subdir\n TH1F * h0 = new TH1F(\"hPhosSDigits\", \"SDigits energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2SDigitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosSDigitsMul\", \"SDigits multiplicity distribution in PHOS\", 500, 0, 10000) ; \n h1->Sumw2() ;\n Add2SDigitsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \n\/\/void AliPHOSQualAssDataMaker::InitTrackSegments()\n\/\/{\n\/\/ \/\/ create Track Segments histograms in TrackSegments subdir\n\/\/ fhTrackSegments = new TH1F(\"hPhosTrackSegments\", \"TrackSegments EMC-CPV distance in PHOS\", 500, 0., 5000.) ; \n\/\/ fhTrackSegments->Sumw2() ;\n\/\/ fhTrackSegmentsMul = new TH1I(\"hPhosTrackSegmentsMul\", \"TrackSegments multiplicity distribution in PHOS\", 100, 0, 100) ; \n\/\/ fhTrackSegmentsMul->Sumw2() ;\n\/\/}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeESDs(AliESDEvent * esd)\n{\n \/\/ make QA data from ESDs\n \n Int_t maxClu = esd->GetNumberOfPHOSClusters() ; \n Int_t index = 0, count = 0 ; \n for ( index = 0 ; index < maxClu; index++ ) {\n AliESDCaloCluster * clu = esd->GetCaloCluster(index) ;\n GetESDsData(0)->Fill(clu->E()) ;\n count++ ; \n }\n GetESDsData(1)->Fill(count) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeHits(TClonesArray * hits)\n{\n \/\/make QA data from Hits\n\n GetHitsData(1)->Fill(hits->GetEntriesFast()) ; \n TIter next(hits) ; \n AliPHOSHit * hit ; \n while ( (hit = dynamic_cast(next())) ) {\n GetHitsData(0)->Fill( hit->GetEnergy()) ;\n }\n}\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeDigits(TClonesArray * digits)\n{\n \/\/ makes data from Digits\n\n GetDigitsData(1)->Fill(digits->GetEntriesFast()) ; \n TIter next(digits) ; \n AliPHOSDigit * digit ; \n while ( (digit = dynamic_cast(next())) ) {\n GetDigitsData(0)->Fill( digit->GetEnergy()) ;\n } \n}\n\n\/\/____________________________________________________________________________\n\/\/ void AliPHOSQualAssDataMaker::MakeRecParticles(TTree * recpar)\n\/\/ {\n\/\/ \/\/ makes data from RecParticles\n\n\/\/ TClonesArray * recparticles = dynamic_cast(fData) ; \n\/\/ fhRecParticlesMul->Fill(recparticles->GetEntriesFast()) ; \n\/\/ TIter next(recparticles) ; \n\/\/ AliPHOSRecParticle * recparticle ; \n\/\/ while ( (recparticle = dynamic_cast(next())) ) {\n\/\/ fhRecParticles->Fill( recparticle->Energy()) ;\n\/\/ }\n\/\/ }\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeRaws(AliRawReader* rawReader)\n{\n rawReader->Reset() ; \n AliPHOSRawDecoder decoder(rawReader);\n decoder.SetOldRCUFormat(kTRUE);\n Int_t count = 0 ; \n while (decoder.NextDigit()) {\n Int_t module = decoder.GetModule() ;\n Int_t row = decoder.GetRow() ;\n Int_t col = decoder.GetColumn() ;\n Double_t time = decoder.GetTime() ;\n Double_t energy = decoder.GetEnergy() ; \n GetRawsData(0)->Fill(module) ; \n GetRawsData(module)->Fill(row, col) ; \n GetRawsData(6)->Fill(time) ; \n GetRawsData(7)->Fill(energy) ; \n AliInfo(Form(\" %d %d %d %d %f %f\\n\", count, module, row, col, time, energy)) ;\n count++ ; \n } \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeRecPoints(TTree * clustersTree)\n{\n {\n \/\/ makes data from RecPoints\n TBranch *emcbranch = clustersTree->GetBranch(\"PHOSEmcRP\");\n if (!emcbranch) { \n AliError(\"can't get the branch with the PHOS EMC clusters !\");\n return;\n }\n TObjArray * emcrecpoints = new TObjArray(100) ;\n emcbranch->SetAddress(&emcrecpoints);\n emcbranch->GetEntry(0);\n \n GetRecPointsData(1)->Fill(emcrecpoints->GetEntriesFast()) ; \n TIter next(emcrecpoints) ; \n AliPHOSEmcRecPoint * rp ; \n while ( (rp = dynamic_cast(next())) ) {\n GetRecPointsData(0)->Fill( rp->GetEnergy()) ;\n }\n emcrecpoints->Delete();\n delete emcrecpoints;\n }\n {\n TBranch *cpvbranch = clustersTree->GetBranch(\"PHOSCpvRP\");\n if (!cpvbranch) { \n AliError(\"can't get the branch with the PHOS CPV clusters !\");\n return;\n }\n TObjArray *cpvrecpoints = new TObjArray(100) ;\n cpvbranch->SetAddress(&cpvrecpoints);\n cpvbranch->GetEntry(0);\n \n GetRecPointsData(1)->Fill(cpvrecpoints->GetEntriesFast()) ; \n TIter next(cpvrecpoints) ; \n AliPHOSCpvRecPoint * rp ; \n while ( (rp = dynamic_cast(next())) ) {\n GetRecPointsData(0)->Fill( rp->GetEnergy()) ;\n }\n cpvrecpoints->Delete();\n delete cpvrecpoints;\n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeSDigits(TClonesArray * sdigits)\n{\n \/\/ makes data from SDigits\n \n\tGetSDigitsData(1)->Fill(sdigits->GetEntriesFast()) ; \n TIter next(sdigits) ; \n AliPHOSDigit * sdigit ; \n while ( (sdigit = dynamic_cast(next())) ) {\n GetSDigitsData(0)->Fill( sdigit->GetEnergy()) ;\n } \n}\n\n\/\/____________________________________________________________________________\n\/\/ void AliPHOSQualAssDataMaker::MakeTrackSegments(TTree * ts)\n\/\/ {\n\/\/ \/\/ makes data from TrackSegments\n\n\/\/ TClonesArray * tracksegments = dynamic_cast(fData) ;\n\n\/\/ fhTrackSegmentsMul->Fill(tracksegments->GetEntriesFast()) ; \n\/\/ TIter next(tracksegments) ; \n\/\/ AliPHOSTrackSegment * ts ; \n\/\/ while ( (ts = dynamic_cast(next())) ) {\n\/\/ fhTrackSegments->Fill( ts->GetCpvDistance()) ;\n\/\/ } \n\/\/ }\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::StartOfDetectorCycle()\n{\n \/\/Detector specific actions at start of cycle\n \n}\nMini bug corrected\/**************************************************************************\n * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\n\n\/* $Id$ *\/\n\n\/*\n Produces the data needed to calculate the quality assurance. \n All data must be mergeable objects.\n Y. Schutz CERN July 2007\n*\/\n\n\/\/ --- ROOT system ---\n#include \n#include \n#include \n#include \n#include \n\n\/\/ --- Standard library ---\n\n\/\/ --- AliRoot header files ---\n#include \"AliESDCaloCluster.h\"\n#include \"AliESDEvent.h\"\n#include \"AliLog.h\"\n#include \"AliPHOSDigit.h\"\n#include \"AliPHOSHit.h\"\n#include \"AliPHOSQualAssDataMaker.h\"\n#include \"AliPHOSCpvRecPoint.h\" \n#include \"AliPHOSEmcRecPoint.h\" \n#include \"AliPHOSRecParticle.h\" \n#include \"AliPHOSTrackSegment.h\" \n#include \"AliPHOSRawDecoder.h\"\n\nClassImp(AliPHOSQualAssDataMaker)\n \n\/\/____________________________________________________________________________ \n AliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker() : \n AliQualAssDataMaker(AliQualAss::GetDetName(AliQualAss::kPHOS), \"PHOS Quality Assurance Data Maker\")\n{\n \/\/ ctor\n}\n\n\/\/____________________________________________________________________________ \nAliPHOSQualAssDataMaker::AliPHOSQualAssDataMaker(const AliPHOSQualAssDataMaker& qadm) :\n AliQualAssDataMaker()\n{\n \/\/copy ctor \n SetName((const char*)qadm.GetName()) ; \n SetTitle((const char*)qadm.GetTitle()); \n}\n\n\/\/__________________________________________________________________\nAliPHOSQualAssDataMaker& AliPHOSQualAssDataMaker::operator = (const AliPHOSQualAssDataMaker& qadm )\n{\n \/\/ Equal operator.\n this->~AliPHOSQualAssDataMaker();\n new(this) AliPHOSQualAssDataMaker(qadm);\n return *this;\n}\n \n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::EndOfDetectorCycle()\n{\n \/\/Detector specific actions at end of cycle\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitESDs()\n{\n \/\/create ESDs histograms in ESDs subdir\n TH1F * h0 = new TH1F(\"hPhosESDs\", \"ESDs energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ; \n Add2ESDsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosESDsMul\", \"ESDs multiplicity distribution in PHOS\", 100, 0., 100) ; \n h1->Sumw2() ;\n Add2ESDsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitHits()\n{\n \/\/ create Hits histograms in Hits subdir\n TH1F * h0 = new TH1F(\"hPhosHits\", \"Hits energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2HitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosHitsMul\", \"Hits multiplicity distribution in PHOS\", 500, 0., 10000) ; \n h1->Sumw2() ;\n Add2HitsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitDigits()\n{\n \/\/ create Digits histograms in Digits subdir\n TH1I * h0 = new TH1I(\"hPhosDigits\", \"Digits amplitude distribution in PHOS\", 500, 0, 5000) ; \n h0->Sumw2() ;\n Add2DigitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosDigitsMul\", \"Digits multiplicity distribution in PHOS\", 500, 0, 1000) ; \n h1->Sumw2() ;\n Add2DigitsList(h1, 0) ;\n}\n\n\/\/____________________________________________________________________________ \n\/\/void AliPHOSQualAssDataMaker::InitRecParticles()\n\/\/{\n\/\/ \/\/ create Reconstructed particles histograms in RecParticles subdir\n\/\/ fhRecParticles = new TH1F(\"hPhosRecParticles\", \"RecParticles energy distribution in PHOS\", 100, 0., 100.) ; \n\/\/ fhRecParticles->Sumw2() ;\n\/\/ fhRecParticlesMul = new TH1I(\"hPhosRecParticlesMul\", \"RecParticles multiplicity distribution in PHOS\", 100, 0, 100) ; \n\/\/ fhRecParticlesMul->Sumw2() ;\n\/\/}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitRecPoints()\n{\n \/\/ create Reconstructed Points histograms in RecPoints subdir\n TH1F * h0 = new TH1F(\"hEmcPhosRecPoints\", \"EMCA RecPoints energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2RecPointsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hEmcPhosRecPointsMul\", \"EMCA RecPoints multiplicity distribution in PHOS\", 100, 0, 100) ; \n h1->Sumw2() ;\n Add2RecPointsList(h1, 1) ;\n\n TH1F * h2 = new TH1F(\"hCpvPhosRecPoints\", \"CPV RecPoints energy distribution in PHOS\", 100, 0., 100.) ; \n h2->Sumw2() ;\n Add2RecPointsList(h2, 2) ;\n TH1I * h3 = new TH1I(\"hCpvPhosRecPointsMul\", \"CPV RecPoints multiplicity distribution in PHOS\", 100, 0, 100) ; \n h3->Sumw2() ;\n Add2RecPointsList(h3, 3) ;\n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitRaws()\n{\n \/\/ create Raws histograms in Raws subdir\n TH1I * h0 = new TH1I(\"hPhosModules\", \"Hits in EMCA PHOS modules\", 6, 0, 6) ; \n h0->Sumw2() ;\n Add2RawsList(h0, 0) ;\n const Int_t modMax = 5 ; \n TH2I * h1[modMax] ; \n char name[32] ; \n char title[32] ; \n for (Int_t mod = 0; mod < modMax; mod++) {\n sprintf(title, \"Raws x Columns for PHOS module %d\", mod+1) ; \n sprintf(name, \"hPHOSxyMod%d\", mod+1) ; \n h1[mod] = new TH2I(name, title, 64, 0, 63, 56, 0, 55) ; \n Add2RawsList(h1[mod], mod+1) ;\n }\n TH1F * h6 = new TH1F(\"hPhosRawtime\", \"Time of raw hits in PHOS\", 100, 0, 100.) ; \n h6->Sumw2() ;\n Add2RawsList(h6, 6) ;\n TH1F * h7 = new TH1F(\"hPhosRawEnergy\", \"Energy of raw hits in PHOS\", 1000, 0., 1200.) ; \n h7->Sumw2() ;\n Add2RawsList(h7, 7) ;\n \n}\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::InitSDigits()\n{\n \/\/ create SDigits histograms in SDigits subdir\n TH1F * h0 = new TH1F(\"hPhosSDigits\", \"SDigits energy distribution in PHOS\", 100, 0., 100.) ; \n h0->Sumw2() ;\n Add2SDigitsList(h0, 0) ;\n TH1I * h1 = new TH1I(\"hPhosSDigitsMul\", \"SDigits multiplicity distribution in PHOS\", 500, 0, 10000) ; \n h1->Sumw2() ;\n Add2SDigitsList(h1, 1) ;\n}\n\n\/\/____________________________________________________________________________ \n\/\/void AliPHOSQualAssDataMaker::InitTrackSegments()\n\/\/{\n\/\/ \/\/ create Track Segments histograms in TrackSegments subdir\n\/\/ fhTrackSegments = new TH1F(\"hPhosTrackSegments\", \"TrackSegments EMC-CPV distance in PHOS\", 500, 0., 5000.) ; \n\/\/ fhTrackSegments->Sumw2() ;\n\/\/ fhTrackSegmentsMul = new TH1I(\"hPhosTrackSegmentsMul\", \"TrackSegments multiplicity distribution in PHOS\", 100, 0, 100) ; \n\/\/ fhTrackSegmentsMul->Sumw2() ;\n\/\/}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeESDs(AliESDEvent * esd)\n{\n \/\/ make QA data from ESDs\n \n Int_t maxClu = esd->GetNumberOfPHOSClusters() ; \n Int_t index = 0, count = 0 ; \n for ( index = 0 ; index < maxClu; index++ ) {\n AliESDCaloCluster * clu = esd->GetCaloCluster(index) ;\n GetESDsData(0)->Fill(clu->E()) ;\n count++ ; \n }\n GetESDsData(1)->Fill(count) ;\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeHits(TClonesArray * hits)\n{\n \/\/make QA data from Hits\n\n GetHitsData(1)->Fill(hits->GetEntriesFast()) ; \n TIter next(hits) ; \n AliPHOSHit * hit ; \n while ( (hit = dynamic_cast(next())) ) {\n GetHitsData(0)->Fill( hit->GetEnergy()) ;\n }\n}\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeDigits(TClonesArray * digits)\n{\n \/\/ makes data from Digits\n\n GetDigitsData(1)->Fill(digits->GetEntriesFast()) ; \n TIter next(digits) ; \n AliPHOSDigit * digit ; \n while ( (digit = dynamic_cast(next())) ) {\n GetDigitsData(0)->Fill( digit->GetEnergy()) ;\n } \n}\n\n\/\/____________________________________________________________________________\n\/\/ void AliPHOSQualAssDataMaker::MakeRecParticles(TTree * recpar)\n\/\/ {\n\/\/ \/\/ makes data from RecParticles\n\n\/\/ TClonesArray * recparticles = dynamic_cast(fData) ; \n\/\/ fhRecParticlesMul->Fill(recparticles->GetEntriesFast()) ; \n\/\/ TIter next(recparticles) ; \n\/\/ AliPHOSRecParticle * recparticle ; \n\/\/ while ( (recparticle = dynamic_cast(next())) ) {\n\/\/ fhRecParticles->Fill( recparticle->Energy()) ;\n\/\/ }\n\/\/ }\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeRaws(AliRawReader* rawReader)\n{\n rawReader->Reset() ; \n AliPHOSRawDecoder decoder(rawReader);\n decoder.SetOldRCUFormat(kTRUE);\n Int_t count = 0 ; \n while (decoder.NextDigit()) {\n Int_t module = decoder.GetModule() ;\n Int_t row = decoder.GetRow() ;\n Int_t col = decoder.GetColumn() ;\n Double_t time = decoder.GetTime() ;\n Double_t energy = decoder.GetEnergy() ; \n GetRawsData(0)->Fill(module) ; \n GetRawsData(module)->Fill(row, col) ; \n GetRawsData(6)->Fill(time) ; \n GetRawsData(7)->Fill(energy) ; \n \/\/AliInfo(Form(\" %d %d %d %d %f %f\\n\", count, module, row, col, time, energy)) ;\n count++ ; \n } \n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeRecPoints(TTree * clustersTree)\n{\n {\n \/\/ makes data from RecPoints\n TBranch *emcbranch = clustersTree->GetBranch(\"PHOSEmcRP\");\n if (!emcbranch) { \n AliError(\"can't get the branch with the PHOS EMC clusters !\");\n return;\n }\n TObjArray * emcrecpoints = new TObjArray(100) ;\n emcbranch->SetAddress(&emcrecpoints);\n emcbranch->GetEntry(0);\n \n GetRecPointsData(1)->Fill(emcrecpoints->GetEntriesFast()) ; \n TIter next(emcrecpoints) ; \n AliPHOSEmcRecPoint * rp ; \n while ( (rp = dynamic_cast(next())) ) {\n GetRecPointsData(0)->Fill( rp->GetEnergy()) ;\n }\n emcrecpoints->Delete();\n delete emcrecpoints;\n }\n {\n TBranch *cpvbranch = clustersTree->GetBranch(\"PHOSCpvRP\");\n if (!cpvbranch) { \n AliError(\"can't get the branch with the PHOS CPV clusters !\");\n return;\n }\n TObjArray *cpvrecpoints = new TObjArray(100) ;\n cpvbranch->SetAddress(&cpvrecpoints);\n cpvbranch->GetEntry(0);\n \n GetRecPointsData(1)->Fill(cpvrecpoints->GetEntriesFast()) ; \n TIter next(cpvrecpoints) ; \n AliPHOSCpvRecPoint * rp ; \n while ( (rp = dynamic_cast(next())) ) {\n GetRecPointsData(0)->Fill( rp->GetEnergy()) ;\n }\n cpvrecpoints->Delete();\n delete cpvrecpoints;\n }\n}\n\n\/\/____________________________________________________________________________\nvoid AliPHOSQualAssDataMaker::MakeSDigits(TClonesArray * sdigits)\n{\n \/\/ makes data from SDigits\n \n\tGetSDigitsData(1)->Fill(sdigits->GetEntriesFast()) ; \n TIter next(sdigits) ; \n AliPHOSDigit * sdigit ; \n while ( (sdigit = dynamic_cast(next())) ) {\n GetSDigitsData(0)->Fill( sdigit->GetEnergy()) ;\n } \n}\n\n\/\/____________________________________________________________________________\n\/\/ void AliPHOSQualAssDataMaker::MakeTrackSegments(TTree * ts)\n\/\/ {\n\/\/ \/\/ makes data from TrackSegments\n\n\/\/ TClonesArray * tracksegments = dynamic_cast(fData) ;\n\n\/\/ fhTrackSegmentsMul->Fill(tracksegments->GetEntriesFast()) ; \n\/\/ TIter next(tracksegments) ; \n\/\/ AliPHOSTrackSegment * ts ; \n\/\/ while ( (ts = dynamic_cast(next())) ) {\n\/\/ fhTrackSegments->Fill( ts->GetCpvDistance()) ;\n\/\/ } \n\/\/ }\n\n\/\/____________________________________________________________________________ \nvoid AliPHOSQualAssDataMaker::StartOfDetectorCycle()\n{\n \/\/Detector specific actions at start of cycle\n \n}\n<|endoftext|>"} {"text":"\/*\n PubSubClient.cpp - A simple client for MQTT.\n Nicholas O'Leary\n http:\/\/knolleary.net\n*\/\n\n#include \"PubSubClient.h\"\n#include \n\nPubSubClient::PubSubClient(Client& c) :\n _callback(NULL),\n _client(&c),\n _max_retries(10)\n{}\n\nPubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :\n _callback(NULL),\n _client(&c),\n _max_retries(10),\n server_ip(ip),\n server_port(port)\n{}\n\nPubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :\n _callback(NULL),\n _client(&c),\n _max_retries(10),\n server_port(port),\n server_hostname(hostname)\n{}\n\nPubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {\n server_hostname = \"\";\n server_ip = ip;\n server_port = port;\n return *this;\n}\n\nPubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {\n server_hostname = hostname;\n server_port = port;\n return *this;\n}\n\nvoid PubSubClient::_process_message(MQTT::Message* msg) {\n switch (msg->type()) {\n case MQTT::PUBLISH:\n {\n MQTT::Publish *pub = static_cast(msg);\t\/\/ RTTI is disabled on embedded, so no dynamic_cast<>()\n\n if (_callback)\n\t_callback(*pub);\n\n if (pub->qos() == 1) {\n\tMQTT::PublishAck puback(pub->packet_id());\n\tpuback.send(*_client);\n\tlastOutActivity = millis();\n\n } else if (pub->qos() == 2) {\n\tuint8_t retries = 0;\n\n\t{\n\t MQTT::PublishRec pubrec(pub->packet_id());\n\t if (!send_reliably(&pubrec))\n\t return;\n\t}\n\n\t{\n\t MQTT::PublishComp pubcomp(pub->packet_id());\n\t pubcomp.send(*_client);\n\t lastOutActivity = millis();\n\t}\n }\n }\n break;\n\n case MQTT::PINGREQ:\n {\n MQTT::PingResp pr;\n pr.send(*_client);\n lastOutActivity = millis();\n }\n break;\n\n case MQTT::PINGRESP:\n pingOutstanding = false;\n }\n}\n\nbool PubSubClient::wait_for(MQTT::message_type match_type, uint16_t match_pid) {\n while (!_client->available()) {\n if (millis() - lastInActivity > keepalive * 1000UL)\n return false;\n yield();\n }\n\n while (millis() < lastInActivity + (keepalive * 1000)) {\n \/\/ Read the packet and check it\n MQTT::Message *msg = MQTT::readPacket(*_client);\n if (msg != NULL) {\n lastInActivity = millis();\n\n if (msg->type() == match_type) {\n\tuint8_t pid = msg->packet_id();\n\tdelete msg;\n\tif (match_pid)\n\t return pid == match_pid;\n\treturn true;\n }\n\n _process_message(msg);\n delete msg;\n }\n\n yield();\n }\n\n return false;\n}\n\nbool PubSubClient::send_reliably(MQTT::Message* msg) {\n MQTT::message_type r_type = msg->response_type();\n uint16_t pid = msg->packet_id();\n\n uint8_t retries = 0;\n send:\n msg->send(*_client);\n lastOutActivity = millis();\n\n if (r_type == MQTT::None)\n return true;\n\n if (!wait_for(r_type, pid)) {\n if (retries < _max_retries) {\n retries++;\n goto send;\n }\n return false;\n }\n return true;\n}\n\nbool PubSubClient::connect(String id) {\n if (connected())\n return false;\n\n return connect(id, \"\", 0, false, \"\");\n}\n\nbool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {\n if (connected())\n return false;\n\n MQTT::Connect conn(id);\n if (willTopic.length())\n conn.set_will(willTopic, willMessage, willQos, willRetain);\n return connect(conn);\n}\n\nbool PubSubClient::connect(MQTT::Connect &conn) {\n if (connected())\n return false;\n\n int result = 0;\n\n if (server_hostname.length() > 0)\n result = _client->connect(server_hostname.c_str(), server_port);\n else\n result = _client->connect(server_ip, server_port);\n\n if (!result) {\n _client->stop();\n return false;\n }\n\n pingOutstanding = false;\n nextMsgId = 1;\t\t\/\/ Init the next packet id\n lastInActivity = millis();\t\/\/ Init this so that wait_for() doesn't think we've already timed-out\n keepalive = conn.keepalive();\t\/\/ Store the keepalive period from this connection\n\n bool ret = send_reliably(&conn);\n if (!ret)\n _client->stop();\n\n return ret;\n}\n\nbool PubSubClient::loop() {\n if (!connected())\n return false;\n\n unsigned long t = millis();\n if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {\n if (pingOutstanding) {\n _client->stop();\n return false;\n } else {\n MQTT::Ping ping;\n ping.send(*_client);\n lastInActivity = lastOutActivity = t;\n pingOutstanding = true;\n }\n }\n if (_client->available()) {\n \/\/ Read the packet and check it\n MQTT::Message *msg = MQTT::readPacket(*_client);\n if (msg != NULL) {\n lastInActivity = millis();\n _process_message(msg);\n delete msg;\n }\n }\n return true;\n}\n\nbool PubSubClient::publish(String topic, String payload) {\n if (!connected())\n return false;\n\n MQTT::Publish pub(topic, payload);\n return publish(pub);\n}\n\nbool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {\n if (!connected())\n return false;\n\n MQTT::Publish pub(topic, const_cast(payload), plength);\n pub.set_retain(retained);\n return publish(pub);\n}\n\nbool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {\n if (!connected())\n return false;\n\n MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);\n pub.set_retain(retained);\n return publish(pub);\n}\n\nbool PubSubClient::publish(MQTT::Publish &pub) {\n if (!connected())\n return false;\n\n switch (pub.qos()) {\n case 0:\n pub.send(*_client);\n lastOutActivity = millis();\n break;\n\n case 1:\n if (!send_reliably(&pub))\n return false;\n break;\n\n case 2:\n {\n if (!send_reliably(&pub))\n\treturn false;\n\n MQTT::PublishRel pubrel(pub.packet_id());\n if (!send_reliably(&pubrel))\n\treturn false;\n }\n break;\n }\n return true;\n}\n\nbool PubSubClient::subscribe(String topic, uint8_t qos) {\n if (!connected())\n return false;\n\n if (qos > 2)\n return false;\n\n MQTT::Subscribe sub(next_packet_id(), topic, qos);\n return subscribe(sub);\n}\n\nbool PubSubClient::subscribe(MQTT::Subscribe &sub) {\n if (!connected())\n return false;\n\n if (!send_reliably(&sub))\n return false;\n\n return true;\n}\n\nbool PubSubClient::unsubscribe(String topic) {\n if (!connected())\n return false;\n\n MQTT::Unsubscribe unsub(next_packet_id(), topic);\n return unsubscribe(unsub);\n}\n\nbool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {\n if (!connected())\n return false;\n\n if (!send_reliably(&unsub))\n return false;\n\n return true;\n}\n\nvoid PubSubClient::disconnect() {\n MQTT::Disconnect discon;\n discon.send(*_client);\n _client->stop();\n lastInActivity = lastOutActivity = millis();\n}\n\nbool PubSubClient::connected() {\n bool rc = _client->connected();\n if (!rc)\n _client->stop();\n\n return rc;\n}\nCheck make sure we're connected before trying to disconnect\/*\n PubSubClient.cpp - A simple client for MQTT.\n Nicholas O'Leary\n http:\/\/knolleary.net\n*\/\n\n#include \"PubSubClient.h\"\n#include \n\nPubSubClient::PubSubClient(Client& c) :\n _callback(NULL),\n _client(&c),\n _max_retries(10)\n{}\n\nPubSubClient::PubSubClient(Client& c, IPAddress &ip, uint16_t port) :\n _callback(NULL),\n _client(&c),\n _max_retries(10),\n server_ip(ip),\n server_port(port)\n{}\n\nPubSubClient::PubSubClient(Client& c, String hostname, uint16_t port) :\n _callback(NULL),\n _client(&c),\n _max_retries(10),\n server_port(port),\n server_hostname(hostname)\n{}\n\nPubSubClient& PubSubClient::set_server(IPAddress &ip, uint16_t port) {\n server_hostname = \"\";\n server_ip = ip;\n server_port = port;\n return *this;\n}\n\nPubSubClient& PubSubClient::set_server(String hostname, uint16_t port) {\n server_hostname = hostname;\n server_port = port;\n return *this;\n}\n\nvoid PubSubClient::_process_message(MQTT::Message* msg) {\n switch (msg->type()) {\n case MQTT::PUBLISH:\n {\n MQTT::Publish *pub = static_cast(msg);\t\/\/ RTTI is disabled on embedded, so no dynamic_cast<>()\n\n if (_callback)\n\t_callback(*pub);\n\n if (pub->qos() == 1) {\n\tMQTT::PublishAck puback(pub->packet_id());\n\tpuback.send(*_client);\n\tlastOutActivity = millis();\n\n } else if (pub->qos() == 2) {\n\tuint8_t retries = 0;\n\n\t{\n\t MQTT::PublishRec pubrec(pub->packet_id());\n\t if (!send_reliably(&pubrec))\n\t return;\n\t}\n\n\t{\n\t MQTT::PublishComp pubcomp(pub->packet_id());\n\t pubcomp.send(*_client);\n\t lastOutActivity = millis();\n\t}\n }\n }\n break;\n\n case MQTT::PINGREQ:\n {\n MQTT::PingResp pr;\n pr.send(*_client);\n lastOutActivity = millis();\n }\n break;\n\n case MQTT::PINGRESP:\n pingOutstanding = false;\n }\n}\n\nbool PubSubClient::wait_for(MQTT::message_type match_type, uint16_t match_pid) {\n while (!_client->available()) {\n if (millis() - lastInActivity > keepalive * 1000UL)\n return false;\n yield();\n }\n\n while (millis() < lastInActivity + (keepalive * 1000)) {\n \/\/ Read the packet and check it\n MQTT::Message *msg = MQTT::readPacket(*_client);\n if (msg != NULL) {\n lastInActivity = millis();\n\n if (msg->type() == match_type) {\n\tuint8_t pid = msg->packet_id();\n\tdelete msg;\n\tif (match_pid)\n\t return pid == match_pid;\n\treturn true;\n }\n\n _process_message(msg);\n delete msg;\n }\n\n yield();\n }\n\n return false;\n}\n\nbool PubSubClient::send_reliably(MQTT::Message* msg) {\n MQTT::message_type r_type = msg->response_type();\n uint16_t pid = msg->packet_id();\n\n uint8_t retries = 0;\n send:\n msg->send(*_client);\n lastOutActivity = millis();\n\n if (r_type == MQTT::None)\n return true;\n\n if (!wait_for(r_type, pid)) {\n if (retries < _max_retries) {\n retries++;\n goto send;\n }\n return false;\n }\n return true;\n}\n\nbool PubSubClient::connect(String id) {\n if (connected())\n return false;\n\n return connect(id, \"\", 0, false, \"\");\n}\n\nbool PubSubClient::connect(String id, String willTopic, uint8_t willQos, bool willRetain, String willMessage) {\n if (connected())\n return false;\n\n MQTT::Connect conn(id);\n if (willTopic.length())\n conn.set_will(willTopic, willMessage, willQos, willRetain);\n return connect(conn);\n}\n\nbool PubSubClient::connect(MQTT::Connect &conn) {\n if (connected())\n return false;\n\n int result = 0;\n\n if (server_hostname.length() > 0)\n result = _client->connect(server_hostname.c_str(), server_port);\n else\n result = _client->connect(server_ip, server_port);\n\n if (!result) {\n _client->stop();\n return false;\n }\n\n pingOutstanding = false;\n nextMsgId = 1;\t\t\/\/ Init the next packet id\n lastInActivity = millis();\t\/\/ Init this so that wait_for() doesn't think we've already timed-out\n keepalive = conn.keepalive();\t\/\/ Store the keepalive period from this connection\n\n bool ret = send_reliably(&conn);\n if (!ret)\n _client->stop();\n\n return ret;\n}\n\nbool PubSubClient::loop() {\n if (!connected())\n return false;\n\n unsigned long t = millis();\n if ((t - lastInActivity > keepalive * 1000UL) || (t - lastOutActivity > keepalive * 1000UL)) {\n if (pingOutstanding) {\n _client->stop();\n return false;\n } else {\n MQTT::Ping ping;\n ping.send(*_client);\n lastInActivity = lastOutActivity = t;\n pingOutstanding = true;\n }\n }\n if (_client->available()) {\n \/\/ Read the packet and check it\n MQTT::Message *msg = MQTT::readPacket(*_client);\n if (msg != NULL) {\n lastInActivity = millis();\n _process_message(msg);\n delete msg;\n }\n }\n return true;\n}\n\nbool PubSubClient::publish(String topic, String payload) {\n if (!connected())\n return false;\n\n MQTT::Publish pub(topic, payload);\n return publish(pub);\n}\n\nbool PubSubClient::publish(String topic, const uint8_t* payload, uint32_t plength, bool retained) {\n if (!connected())\n return false;\n\n MQTT::Publish pub(topic, const_cast(payload), plength);\n pub.set_retain(retained);\n return publish(pub);\n}\n\nbool PubSubClient::publish_P(String topic, PGM_P payload, uint32_t plength, bool retained) {\n if (!connected())\n return false;\n\n MQTT::Publish pub = MQTT::Publish_P(topic, payload, plength);\n pub.set_retain(retained);\n return publish(pub);\n}\n\nbool PubSubClient::publish(MQTT::Publish &pub) {\n if (!connected())\n return false;\n\n switch (pub.qos()) {\n case 0:\n pub.send(*_client);\n lastOutActivity = millis();\n break;\n\n case 1:\n if (!send_reliably(&pub))\n return false;\n break;\n\n case 2:\n {\n if (!send_reliably(&pub))\n\treturn false;\n\n MQTT::PublishRel pubrel(pub.packet_id());\n if (!send_reliably(&pubrel))\n\treturn false;\n }\n break;\n }\n return true;\n}\n\nbool PubSubClient::subscribe(String topic, uint8_t qos) {\n if (!connected())\n return false;\n\n if (qos > 2)\n return false;\n\n MQTT::Subscribe sub(next_packet_id(), topic, qos);\n return subscribe(sub);\n}\n\nbool PubSubClient::subscribe(MQTT::Subscribe &sub) {\n if (!connected())\n return false;\n\n if (!send_reliably(&sub))\n return false;\n\n return true;\n}\n\nbool PubSubClient::unsubscribe(String topic) {\n if (!connected())\n return false;\n\n MQTT::Unsubscribe unsub(next_packet_id(), topic);\n return unsubscribe(unsub);\n}\n\nbool PubSubClient::unsubscribe(MQTT::Unsubscribe &unsub) {\n if (!connected())\n return false;\n\n if (!send_reliably(&unsub))\n return false;\n\n return true;\n}\n\nvoid PubSubClient::disconnect() {\n if (!connected())\n return;\n\n MQTT::Disconnect discon;\n discon.send(*_client);\n _client->stop();\n lastInActivity = lastOutActivity = millis();\n}\n\nbool PubSubClient::connected() {\n bool rc = _client->connected();\n if (!rc)\n _client->stop();\n\n return rc;\n}\n<|endoftext|>"} {"text":"\/\/ Test that lsan handles tls correctly for many threads\n\/\/ RUN: LSAN_BASE=\"report_objects=1:use_stacks=0:use_registers=0\"\n\/\/ RUN: %clangxx_lsan %s -DUSE_THREAD -o %t-thread\n\/\/ RUN: %clangxx_lsan %s -DUSE_PTHREAD -o %t-pthread\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=0\" not %run %t-thread 2>&1 | FileCheck %s\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=1\" %run %t-thread 2>&1\n\/\/ RUN: %env_lsan_opts=\"\" %run %t-thread 2>&1\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=0\" not %run %t-pthread 2>&1 | FileCheck %s\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=1\" %run %t-pthread 2>&1\n\/\/ RUN: %env_lsan_opts=\"\" %run %t-pthread 2>&1\n\n#include \n#include \n#include \n#include \n#include \n\nstatic const int NUM_THREADS = 10;\n\npthread_cond_t cond = PTHREAD_COND_INITIALIZER;\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\nint finished = 0;\n\n#if USE_THREAD\n__thread void *ptr1;\n__thread void *ptr2;\n__thread void *ptr3;\n__thread void *ptr4;\n__thread void *ptr5;\n\nvoid alloc() {\n ptr1 = malloc(1111);\n ptr2 = malloc(2222);\n ptr3 = malloc(3333);\n ptr4 = malloc(4444);\n ptr5 = malloc(5555);\n}\n\n#elif USE_PTHREAD\n\/\/ We won't be able to create the maximum number of keys, due to other users\n\/\/ of the tls, but we'll use as many keys as we can before failing to create\n\/\/ a new key.\npthread_key_t keys[PTHREAD_KEYS_MAX];\nstatic const int PTHREAD_KEY_INVALID = 0xffffffff;\n\nvoid alloc() {\n for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {\n void *ptr = malloc(123);\n if ((keys[i] == PTHREAD_KEY_INVALID) || pthread_setspecific(keys[i], ptr)) {\n free(ptr);\n break;\n }\n }\n}\n\nvoid pthread_destructor(void *arg) {\n assert(0 && \"pthread destructors shouldn't be called\");\n}\n#endif\n\nvoid *thread_start(void *arg) {\n alloc();\n\n pthread_mutex_lock(&mutex);\n finished++;\n pthread_mutex_unlock(&mutex);\n\n \/\/ don't exit, to intentionally leak tls data\n while (1)\n sleep(100);\n}\n\nint main() {\n#if USE_PTHREAD\n for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {\n if (pthread_key_create(&keys[i], pthread_destructor)) {\n keys[i] = PTHREAD_KEY_INVALID;\n break;\n }\n }\n#endif\n\n pthread_t thread[NUM_THREADS];\n for (int i = 0; i < NUM_THREADS; ++i) {\n assert(0 == pthread_create(&thread[i], 0, thread_start, 0));\n }\n \/\/ spin until all threads have finished\n while (finished < NUM_THREADS)\n sleep(1);\n exit(0);\n}\n\n\/\/ CHECK: LeakSanitizer: detected memory leaks\n\/\/ CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:\n[LSAN-ARM] Marking new test unsupported on ARMHF due to bot failures\/\/ Test that lsan handles tls correctly for many threads\n\/\/ RUN: LSAN_BASE=\"report_objects=1:use_stacks=0:use_registers=0\"\n\/\/ RUN: %clangxx_lsan %s -DUSE_THREAD -o %t-thread\n\/\/ RUN: %clangxx_lsan %s -DUSE_PTHREAD -o %t-pthread\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=0\" not %run %t-thread 2>&1 | FileCheck %s\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=1\" %run %t-thread 2>&1\n\/\/ RUN: %env_lsan_opts=\"\" %run %t-thread 2>&1\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=0\" not %run %t-pthread 2>&1 | FileCheck %s\n\/\/ RUN: %env_lsan_opts=$LSAN_BASE:\"use_tls=1\" %run %t-pthread 2>&1\n\/\/ RUN: %env_lsan_opts=\"\" %run %t-pthread 2>&1\n\n\/\/ Patch r303906 did not fix all the problems.\n\/\/ UNSUPPORTED: arm-linux,armhf-linux\n\n#include \n#include \n#include \n#include \n#include \n\nstatic const int NUM_THREADS = 10;\n\npthread_cond_t cond = PTHREAD_COND_INITIALIZER;\npthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;\nint finished = 0;\n\n#if USE_THREAD\n__thread void *ptr1;\n__thread void *ptr2;\n__thread void *ptr3;\n__thread void *ptr4;\n__thread void *ptr5;\n\nvoid alloc() {\n ptr1 = malloc(1111);\n ptr2 = malloc(2222);\n ptr3 = malloc(3333);\n ptr4 = malloc(4444);\n ptr5 = malloc(5555);\n}\n\n#elif USE_PTHREAD\n\/\/ We won't be able to create the maximum number of keys, due to other users\n\/\/ of the tls, but we'll use as many keys as we can before failing to create\n\/\/ a new key.\npthread_key_t keys[PTHREAD_KEYS_MAX];\nstatic const int PTHREAD_KEY_INVALID = 0xffffffff;\n\nvoid alloc() {\n for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {\n void *ptr = malloc(123);\n if ((keys[i] == PTHREAD_KEY_INVALID) || pthread_setspecific(keys[i], ptr)) {\n free(ptr);\n break;\n }\n }\n}\n\nvoid pthread_destructor(void *arg) {\n assert(0 && \"pthread destructors shouldn't be called\");\n}\n#endif\n\nvoid *thread_start(void *arg) {\n alloc();\n\n pthread_mutex_lock(&mutex);\n finished++;\n pthread_mutex_unlock(&mutex);\n\n \/\/ don't exit, to intentionally leak tls data\n while (1)\n sleep(100);\n}\n\nint main() {\n#if USE_PTHREAD\n for (int i = 0; i < PTHREAD_KEYS_MAX; ++i) {\n if (pthread_key_create(&keys[i], pthread_destructor)) {\n keys[i] = PTHREAD_KEY_INVALID;\n break;\n }\n }\n#endif\n\n pthread_t thread[NUM_THREADS];\n for (int i = 0; i < NUM_THREADS; ++i) {\n assert(0 == pthread_create(&thread[i], 0, thread_start, 0));\n }\n \/\/ spin until all threads have finished\n while (finished < NUM_THREADS)\n sleep(1);\n exit(0);\n}\n\n\/\/ CHECK: LeakSanitizer: detected memory leaks\n\/\/ CHECK: SUMMARY: {{(Leak|Address)}}Sanitizer:\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fsfactory.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 14:56:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#include \"fsfactory.hxx\"\n\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \"cppuhelper\/factory.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include \n#endif\n\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"fsstorage.hxx\"\n\n\nusing namespace ::com::sun::star;\n\n\/\/-------------------------------------------------------------------------\n\/\/ Checks whether it is a file URL that represents a folder\nsal_Bool isLocalNotFile_Impl( ::rtl::OUString aURL )\n{\n sal_Bool bResult = sal_False;\n\n ::rtl::OUString aSystemPath;\n ::ucb::ContentBroker* pBroker = ::ucb::ContentBroker::get();\n if ( !pBroker )\n throw uno::RuntimeException();\n\n uno::Reference< ::com::sun::star::ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n aSystemPath = ::ucb::getSystemPathFromFileURL( xManager, aURL );\n }\n catch ( uno::Exception& )\n {\n }\n\n if ( aSystemPath.getLength() != 0 )\n {\n \/\/ it is a local file URL, check that it is not a file\n try\n {\n uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > xDummyEnv;\n ::ucb::Content aContent( aURL, xDummyEnv );\n bResult = aContent.isFolder();\n }\n catch( uno::Exception& )\n {\n bResult = sal_True;\n }\n }\n\n return bResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::impl_staticGetSupportedServiceNames()\n{\n uno::Sequence< ::rtl::OUString > aRet(2);\n aRet[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.embed.FileSystemStorageFactory\");\n aRet[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.FileSystemStorageFactory\");\n return aRet;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL FSStorageFactory::impl_staticGetImplementationName()\n{\n return ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.FileSystemStorageFactory\");\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::impl_staticCreateSelfInstance(\n const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )\n{\n return uno::Reference< uno::XInterface >( *new FSStorageFactory( xServiceManager ) );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstance()\n throw ( uno::Exception,\n uno::RuntimeException )\n{\n ::rtl::OUString aTempURL;\n\n aTempURL = ::utl::TempFile( NULL, sal_True ).GetURL();\n\n if ( !aTempURL.getLength() )\n throw uno::RuntimeException(); \/\/ TODO: can not create tempfile\n\n ::ucb::Content aResultContent( aTempURL, uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );\n\n return uno::Reference< uno::XInterface >(\n static_cast< OWeakObject* >( new FSStorage( aResultContent,\n embed::ElementModes::READWRITE,\n uno::Sequence< beans::PropertyValue >(),\n m_xFactory ) ),\n uno::UNO_QUERY );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstanceWithArguments(\n const uno::Sequence< uno::Any >& aArguments )\n throw ( uno::Exception,\n uno::RuntimeException )\n{\n \/\/ The request for storage can be done with up to three arguments\n\n \/\/ The first argument specifies a source for the storage\n \/\/ it must be URL.\n \/\/ The second value is a mode the storage should be open in.\n \/\/ And the third value is a media descriptor.\n\n sal_Int32 nArgNum = aArguments.getLength();\n OSL_ENSURE( nArgNum < 4, \"Wrong parameter number\" );\n\n if ( !nArgNum )\n return createInstance();\n\n \/\/ first try to retrieve storage open mode if any\n \/\/ by default the storage will be open in readonly mode\n sal_Int32 nStorageMode = embed::ElementModes::READ;\n if ( nArgNum >= 2 )\n {\n if( !( aArguments[1] >>= nStorageMode ) )\n {\n OSL_ENSURE( sal_False, \"Wrong second argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n \/\/ it's allways possible to read written storage in this implementation\n nStorageMode |= embed::ElementModes::READ;\n }\n\n \/\/ retrieve storage source URL\n ::rtl::OUString aURL;\n\n if ( aArguments[0] >>= aURL )\n {\n if ( !aURL.getLength() )\n {\n OSL_ENSURE( sal_False, \"Empty URL is provided!\\n\" );\n throw uno::Exception(); \/\/ TODO: illegal argument\n }\n }\n else\n {\n OSL_ENSURE( sal_False, \"Wrong first argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n\n \/\/ retrieve mediadescriptor and set storage properties\n uno::Sequence< beans::PropertyValue > aDescr;\n uno::Sequence< beans::PropertyValue > aPropsToSet;\n\n if ( nArgNum >= 3 )\n {\n if( aArguments[2] >>= aDescr )\n {\n aPropsToSet.realloc(1);\n aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( \"URL\" );\n aPropsToSet[0].Value <<= aURL;\n\n for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )\n {\n if ( aDescr[nInd].Name.equalsAscii( \"InteractionHandler\" ) )\n {\n aPropsToSet.realloc( ++nNumArgs );\n aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;\n aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;\n break;\n }\n else\n OSL_ENSURE( sal_False, \"Unacceptable property, will be ignored!\\n\" );\n }\n }\n else\n {\n OSL_ENSURE( sal_False, \"Wrong third argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n }\n\n \/\/ allow to use other ucp's\n \/\/ if ( !isLocalNotFile_Impl( aURL ) )\n if ( aURL.equalsIgnoreAsciiCaseAsciiL( \"vnd.sun.star.pkg\", 16 )\n || aURL.equalsIgnoreAsciiCaseAsciiL( \"vnd.sun.star.zip\", 16 )\n || ::utl::UCBContentHelper::IsDocument( aURL ) )\n {\n OSL_ENSURE( sal_False, \"File system storages can be based only on file URLs!\\n\" ); \/\/ ???\n throw uno::Exception(); \/\/ TODO: illegal argument\n }\n\n if ( ( nStorageMode & embed::ElementModes::WRITE ) && !( nStorageMode & embed::ElementModes::NOCREATE ) )\n FSStorage::MakeFolderNoUI( aURL, sal_False );\n else if ( !::utl::UCBContentHelper::IsFolder( aURL ) )\n throw io::IOException(); \/\/ there is no such folder\n\n ::ucb::Content aResultContent( aURL, uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >() );\n\n \/\/ create storage based on source\n return uno::Reference< uno::XInterface >(\n static_cast< OWeakObject* >( new FSStorage( aResultContent, nStorageMode, aPropsToSet, m_xFactory ) ),\n uno::UNO_QUERY );\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL FSStorageFactory::getImplementationName()\n throw ( uno::RuntimeException )\n{\n return impl_staticGetImplementationName();\n}\n\n\/\/-------------------------------------------------------------------------\nsal_Bool SAL_CALL FSStorageFactory::supportsService( const ::rtl::OUString& ServiceName )\n throw ( uno::RuntimeException )\n{\n uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();\n\n for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )\n if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )\n return sal_True;\n\n return sal_False;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::getSupportedServiceNames()\n throw ( uno::RuntimeException )\n{\n return impl_staticGetSupportedServiceNames();\n}\n\n\/\/-------------------------------------------------------------------------\n\nextern \"C\"\n{\nSAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment (\n const sal_Char ** ppEnvTypeName, uno_Environment ** \/* ppEnv *\/)\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nSAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo (\n void * \/* pServiceManager *\/, void * pRegistryKey)\n{\n if (pRegistryKey)\n {\n uno::Reference< registry::XRegistryKey > xRegistryKey (\n reinterpret_cast< registry::XRegistryKey*>(pRegistryKey));\n\n uno::Reference< registry::XRegistryKey > xNewKey;\n xNewKey = xRegistryKey->createKey(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) +\n FSStorageFactory::impl_staticGetImplementationName() +\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\")));\n\n const uno::Sequence< ::rtl::OUString > aServices (\n FSStorageFactory::impl_staticGetSupportedServiceNames());\n for( sal_Int32 i = 0; i < aServices.getLength(); i++ )\n xNewKey->createKey( aServices.getConstArray()[i] );\n\n return sal_True;\n }\n return sal_False;\n}\n\nSAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory (\n const sal_Char * pImplementationName, void * pServiceManager, void * \/* pRegistryKey *\/)\n{\n void * pResult = 0;\n if (pServiceManager)\n {\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n if (FSStorageFactory::impl_staticGetImplementationName().compareToAscii (pImplementationName) == 0)\n {\n xFactory = cppu::createOneInstanceFactory (\n reinterpret_cast< lang::XMultiServiceFactory* >(pServiceManager),\n FSStorageFactory::impl_staticGetImplementationName(),\n FSStorageFactory::impl_staticCreateSelfInstance,\n FSStorageFactory::impl_staticGetSupportedServiceNames() );\n }\n if (xFactory.is())\n {\n xFactory->acquire();\n pResult = xFactory.get();\n }\n }\n return pResult;\n}\n\n} \/\/ extern \"C\"\n\nINTEGRATION: CWS bgdlremove (1.7.186); FILE MERGED 2007\/05\/18 11:32:07 kso 1.7.186.1: #i77419# - cleanup of ucbhelper namespaces.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: fsfactory.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: ihi $ $Date: 2007-06-05 18:26:04 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#include \"fsfactory.hxx\"\n\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \"cppuhelper\/factory.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_UCB_XSIMPLEFILEACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_EMBED_ELEMENTMODES_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSEEKABLE_HPP_\n#include \n#endif\n\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \"fsstorage.hxx\"\n\n\nusing namespace ::com::sun::star;\n\n\/\/-------------------------------------------------------------------------\n\/\/ Checks whether it is a file URL that represents a folder\nsal_Bool isLocalNotFile_Impl( ::rtl::OUString aURL )\n{\n sal_Bool bResult = sal_False;\n\n ::rtl::OUString aSystemPath;\n ::ucbhelper::ContentBroker* pBroker = ::ucbhelper::ContentBroker::get();\n if ( !pBroker )\n throw uno::RuntimeException();\n\n uno::Reference< ucb::XContentProviderManager > xManager =\n pBroker->getContentProviderManagerInterface();\n try\n {\n aSystemPath = ::ucbhelper::getSystemPathFromFileURL( xManager, aURL );\n }\n catch ( uno::Exception& )\n {\n }\n\n if ( aSystemPath.getLength() != 0 )\n {\n \/\/ it is a local file URL, check that it is not a file\n try\n {\n uno::Reference< ucb::XCommandEnvironment > xDummyEnv;\n ::ucbhelper::Content aContent( aURL, xDummyEnv );\n bResult = aContent.isFolder();\n }\n catch( uno::Exception& )\n {\n bResult = sal_True;\n }\n }\n\n return bResult;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::impl_staticGetSupportedServiceNames()\n{\n uno::Sequence< ::rtl::OUString > aRet(2);\n aRet[0] = ::rtl::OUString::createFromAscii(\"com.sun.star.embed.FileSystemStorageFactory\");\n aRet[1] = ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.FileSystemStorageFactory\");\n return aRet;\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL FSStorageFactory::impl_staticGetImplementationName()\n{\n return ::rtl::OUString::createFromAscii(\"com.sun.star.comp.embed.FileSystemStorageFactory\");\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::impl_staticCreateSelfInstance(\n const uno::Reference< lang::XMultiServiceFactory >& xServiceManager )\n{\n return uno::Reference< uno::XInterface >( *new FSStorageFactory( xServiceManager ) );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstance()\n throw ( uno::Exception,\n uno::RuntimeException )\n{\n ::rtl::OUString aTempURL;\n\n aTempURL = ::utl::TempFile( NULL, sal_True ).GetURL();\n\n if ( !aTempURL.getLength() )\n throw uno::RuntimeException(); \/\/ TODO: can not create tempfile\n\n ::ucbhelper::Content aResultContent(\n aTempURL, uno::Reference< ucb::XCommandEnvironment >() );\n\n return uno::Reference< uno::XInterface >(\n static_cast< OWeakObject* >(\n new FSStorage( aResultContent,\n embed::ElementModes::READWRITE,\n uno::Sequence< beans::PropertyValue >(),\n m_xFactory ) ),\n uno::UNO_QUERY );\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Reference< uno::XInterface > SAL_CALL FSStorageFactory::createInstanceWithArguments(\n const uno::Sequence< uno::Any >& aArguments )\n throw ( uno::Exception,\n uno::RuntimeException )\n{\n \/\/ The request for storage can be done with up to three arguments\n\n \/\/ The first argument specifies a source for the storage\n \/\/ it must be URL.\n \/\/ The second value is a mode the storage should be open in.\n \/\/ And the third value is a media descriptor.\n\n sal_Int32 nArgNum = aArguments.getLength();\n OSL_ENSURE( nArgNum < 4, \"Wrong parameter number\" );\n\n if ( !nArgNum )\n return createInstance();\n\n \/\/ first try to retrieve storage open mode if any\n \/\/ by default the storage will be open in readonly mode\n sal_Int32 nStorageMode = embed::ElementModes::READ;\n if ( nArgNum >= 2 )\n {\n if( !( aArguments[1] >>= nStorageMode ) )\n {\n OSL_ENSURE( sal_False, \"Wrong second argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n \/\/ it's allways possible to read written storage in this implementation\n nStorageMode |= embed::ElementModes::READ;\n }\n\n \/\/ retrieve storage source URL\n ::rtl::OUString aURL;\n\n if ( aArguments[0] >>= aURL )\n {\n if ( !aURL.getLength() )\n {\n OSL_ENSURE( sal_False, \"Empty URL is provided!\\n\" );\n throw uno::Exception(); \/\/ TODO: illegal argument\n }\n }\n else\n {\n OSL_ENSURE( sal_False, \"Wrong first argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n\n \/\/ retrieve mediadescriptor and set storage properties\n uno::Sequence< beans::PropertyValue > aDescr;\n uno::Sequence< beans::PropertyValue > aPropsToSet;\n\n if ( nArgNum >= 3 )\n {\n if( aArguments[2] >>= aDescr )\n {\n aPropsToSet.realloc(1);\n aPropsToSet[0].Name = ::rtl::OUString::createFromAscii( \"URL\" );\n aPropsToSet[0].Value <<= aURL;\n\n for ( sal_Int32 nInd = 0, nNumArgs = 1; nInd < aDescr.getLength(); nInd++ )\n {\n if ( aDescr[nInd].Name.equalsAscii( \"InteractionHandler\" ) )\n {\n aPropsToSet.realloc( ++nNumArgs );\n aPropsToSet[nNumArgs-1].Name = aDescr[nInd].Name;\n aPropsToSet[nNumArgs-1].Value = aDescr[nInd].Value;\n break;\n }\n else\n OSL_ENSURE( sal_False, \"Unacceptable property, will be ignored!\\n\" );\n }\n }\n else\n {\n OSL_ENSURE( sal_False, \"Wrong third argument!\\n\" );\n throw uno::Exception(); \/\/ TODO: Illegal argument\n }\n }\n\n \/\/ allow to use other ucp's\n \/\/ if ( !isLocalNotFile_Impl( aURL ) )\n if ( aURL.equalsIgnoreAsciiCaseAsciiL( \"vnd.sun.star.pkg\", 16 )\n || aURL.equalsIgnoreAsciiCaseAsciiL( \"vnd.sun.star.zip\", 16 )\n || ::utl::UCBContentHelper::IsDocument( aURL ) )\n {\n OSL_ENSURE( sal_False, \"File system storages can be based only on file URLs!\\n\" ); \/\/ ???\n throw uno::Exception(); \/\/ TODO: illegal argument\n }\n\n if ( ( nStorageMode & embed::ElementModes::WRITE ) && !( nStorageMode & embed::ElementModes::NOCREATE ) )\n FSStorage::MakeFolderNoUI( aURL, sal_False );\n else if ( !::utl::UCBContentHelper::IsFolder( aURL ) )\n throw io::IOException(); \/\/ there is no such folder\n\n ::ucbhelper::Content aResultContent(\n aURL, uno::Reference< ucb::XCommandEnvironment >() );\n\n \/\/ create storage based on source\n return uno::Reference< uno::XInterface >(\n static_cast< OWeakObject* >( new FSStorage( aResultContent,\n nStorageMode,\n aPropsToSet,\n m_xFactory ) ),\n uno::UNO_QUERY );\n}\n\n\/\/-------------------------------------------------------------------------\n::rtl::OUString SAL_CALL FSStorageFactory::getImplementationName()\n throw ( uno::RuntimeException )\n{\n return impl_staticGetImplementationName();\n}\n\n\/\/-------------------------------------------------------------------------\nsal_Bool SAL_CALL FSStorageFactory::supportsService( const ::rtl::OUString& ServiceName )\n throw ( uno::RuntimeException )\n{\n uno::Sequence< ::rtl::OUString > aSeq = impl_staticGetSupportedServiceNames();\n\n for ( sal_Int32 nInd = 0; nInd < aSeq.getLength(); nInd++ )\n if ( ServiceName.compareTo( aSeq[nInd] ) == 0 )\n return sal_True;\n\n return sal_False;\n}\n\n\/\/-------------------------------------------------------------------------\nuno::Sequence< ::rtl::OUString > SAL_CALL FSStorageFactory::getSupportedServiceNames()\n throw ( uno::RuntimeException )\n{\n return impl_staticGetSupportedServiceNames();\n}\n\n\/\/-------------------------------------------------------------------------\n\nextern \"C\"\n{\nSAL_DLLPUBLIC_EXPORT void SAL_CALL component_getImplementationEnvironment (\n const sal_Char ** ppEnvTypeName, uno_Environment ** \/* ppEnv *\/)\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\nSAL_DLLPUBLIC_EXPORT sal_Bool SAL_CALL component_writeInfo (\n void * \/* pServiceManager *\/, void * pRegistryKey)\n{\n if (pRegistryKey)\n {\n uno::Reference< registry::XRegistryKey > xRegistryKey (\n reinterpret_cast< registry::XRegistryKey*>(pRegistryKey));\n\n uno::Reference< registry::XRegistryKey > xNewKey;\n xNewKey = xRegistryKey->createKey(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\") ) +\n FSStorageFactory::impl_staticGetImplementationName() +\n ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( \"\/UNO\/SERVICES\")));\n\n const uno::Sequence< ::rtl::OUString > aServices (\n FSStorageFactory::impl_staticGetSupportedServiceNames());\n for( sal_Int32 i = 0; i < aServices.getLength(); i++ )\n xNewKey->createKey( aServices.getConstArray()[i] );\n\n return sal_True;\n }\n return sal_False;\n}\n\nSAL_DLLPUBLIC_EXPORT void * SAL_CALL component_getFactory (\n const sal_Char * pImplementationName, void * pServiceManager, void * \/* pRegistryKey *\/)\n{\n void * pResult = 0;\n if (pServiceManager)\n {\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n if (FSStorageFactory::impl_staticGetImplementationName().compareToAscii (pImplementationName) == 0)\n {\n xFactory = cppu::createOneInstanceFactory (\n reinterpret_cast< lang::XMultiServiceFactory* >(pServiceManager),\n FSStorageFactory::impl_staticGetImplementationName(),\n FSStorageFactory::impl_staticCreateSelfInstance,\n FSStorageFactory::impl_staticGetSupportedServiceNames() );\n }\n if (xFactory.is())\n {\n xFactory->acquire();\n pResult = xFactory.get();\n }\n }\n return pResult;\n}\n\n} \/\/ extern \"C\"\n\n<|endoftext|>"} {"text":"#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/concurrency\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include \n#include \n#include \n#include \n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": lock()... \";\n\n bool done = false;\n const int max_attempts = 60;\n\n for (int attempt = 1; attempt <= max_attempts; attempt++)\n {\n sftp_file file = sftp_open\n (\n sftp.get(),\n mutex_file_name.c_str(),\n O_CREAT | O_EXCL,\n S_IRUSR\n );\n\n if (file)\n {\n done = true;\n sftp_close(file);\n break;\n }\n else\n {\n if (trace)\n std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n }\n\n if (trace)\n {\n if (done)\n std::cerr << \"done.\\n\";\n else\n std::cerr << \"timeout.\\n\";\n }\n\n if (!done)\n throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": unlock()\\n\";\n\n if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n int64_t SSH_Connection::raw_pull(Writable_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": pull()... \";\n\n int64_t server_position = 0;\n\n try\n {\n ssh::SFTP_Attributes attributes\n (\n sftp_stat(sftp.get(), remote_file_name.c_str())\n );\n\n server_position = int64_t(attributes.get()->size);\n }\n catch (const joedb::Exception &)\n {\n }\n\n const int64_t client_position = client_journal.get_checkpoint_position();\n\n if (client_position < server_position)\n {\n std::vector v(size_t(server_position - client_position));\n\n if (trace)\n std::cerr << v.size() << \" bytes... \";\n\n sftp_file file = sftp_open\n (\n sftp.get(),\n remote_file_name.c_str(),\n O_RDONLY,\n S_IRUSR | S_IWUSR\n );\n\n if (file)\n {\n const int seek_result = sftp_seek64(file, uint64_t(client_position));\n if (seek_result < 0)\n {\n sftp_close(file);\n throw Exception(\"Error while seeking\");\n }\n\n ssize_t total_read = 0;\n\n while (total_read < ssize_t(v.size()))\n {\n const ssize_t read_result = sftp_read\n (\n file,\n &v[size_t(total_read)],\n v.size() - size_t(total_read)\n );\n\n if (read_result < 0)\n {\n sftp_close(file);\n throw Exception(\"Error during sftp_read\");\n }\n\n total_read += read_result;\n if (trace)\n std::cerr << read_result << ' ';\n }\n\n sftp_close(file);\n client_journal.append_raw_tail(v);\n }\n else\n throw Exception(\"Could not open remote file for reading\");\n }\n else if (server_position > 0 && client_position > server_position)\n throw Exception(\"Trying to pull when ahead of server\");\n\n if (trace)\n std::cerr << \"done.\\n\";\n\n return server_position;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n Readonly_Journal &client_journal,\n int64_t server_position\n )\n {\n if (trace)\n std::cerr << full_remote_name << \": push()... \";\n\n const int64_t client_position = client_journal.get_checkpoint_position();\n if (client_position > server_position)\n {\n std::vector v(client_journal.get_raw_tail(server_position));\n\n if (trace)\n std::cerr << v.size() << \" bytes... \";\n\n sftp_file file = sftp_open\n (\n sftp.get(),\n remote_file_name.c_str(),\n O_WRONLY | O_CREAT,\n S_IRUSR | S_IWUSR\n );\n\n const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n if (file)\n {\n \/\/\n \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n \/\/\n \/\/ The maximum size of a packet is in practise determined by the client\n \/\/ (the maximum size of read or write requests that it sends, plus a few\n \/\/ bytes of packet overhead). All servers SHOULD support packets of at\n \/\/ least 34000 bytes (where the packet size refers to the full length,\n \/\/ including the header above). This should allow for reads and writes of\n \/\/ at most 32768 bytes.\n \/\/\n const size_t max_block_size = 32768;\n const size_t size = v.size();\n size_t written = 0;\n\n while (seek_result >= 0 && written < size)\n {\n size_t block_size = size - written;\n\n if (block_size > max_block_size)\n block_size = max_block_size;\n\n const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n if (result <= 0)\n break;\n\n written += size_t(result);\n }\n\n sftp_close(file);\n\n if (written < size)\n throw Exception(\"Incomplete write during push\");\n }\n else\n throw Exception(\"Could not open remote file for writing\");\n }\n\n if (trace)\n std::cerr << \"done.\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::string user,\n std::string host,\n int port,\n std::string remote_file_name,\n bool trace,\n int ssh_log_level\n ):\n remote_file_name(remote_file_name),\n trace(trace),\n mutex_file_name(remote_file_name + \".mutex\"),\n full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n session\n (\n user,\n host,\n port,\n ssh_log_level\n ),\n sftp(session)\n {\n }\n}\n\n#endif\nSSH_Connection: fail to pull if remote file does not exist#ifdef JOEDB_HAS_SSH\n\n#include \"joedb\/concurrency\/SSH_Connection.h\"\n#include \"joedb\/Exception.h\"\n\n#include \n#include \n#include \n#include \n\n\/\/\n\/\/ Windows does not define those\n\/\/\n#ifndef S_IRUSR\n#define\tS_IRUSR\t0000400\n#endif\n\n#ifndef S_IWUSR\n#define\tS_IWUSR\t0000200\n#endif\n\nnamespace joedb\n{\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::lock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": lock()... \";\n\n bool done = false;\n const int max_attempts = 60;\n\n for (int attempt = 1; attempt <= max_attempts; attempt++)\n {\n sftp_file file = sftp_open\n (\n sftp.get(),\n mutex_file_name.c_str(),\n O_CREAT | O_EXCL,\n S_IRUSR\n );\n\n if (file)\n {\n done = true;\n sftp_close(file);\n break;\n }\n else\n {\n if (trace)\n std::cerr << \"Retrying(\" << attempt << \"\/\" << max_attempts << \")... \";\n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n }\n\n if (trace)\n {\n if (done)\n std::cerr << \"done.\\n\";\n else\n std::cerr << \"timeout.\\n\";\n }\n\n if (!done)\n throw Exception(\"SSH_Connection::lock: timeout\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::unlock()\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": unlock()\\n\";\n\n if (sftp_unlink(sftp.get(), mutex_file_name.c_str()) < 0)\n throw Exception(\"Error removing remote mutex\");\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n int64_t SSH_Connection::raw_pull(Writable_Journal &client_journal)\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n {\n if (trace)\n std::cerr << full_remote_name << \": pull()... \";\n\n int64_t server_position = 0;\n\n try\n {\n ssh::SFTP_Attributes attributes\n (\n sftp_stat(sftp.get(), remote_file_name.c_str())\n );\n\n server_position = int64_t(attributes.get()->size);\n }\n catch (const joedb::Exception &)\n {\n throw Exception(\"Could not stat remote file\");\n }\n\n const int64_t client_position = client_journal.get_checkpoint_position();\n\n if (client_position < server_position)\n {\n std::vector v(size_t(server_position - client_position));\n\n if (trace)\n std::cerr << v.size() << \" bytes... \";\n\n sftp_file file = sftp_open\n (\n sftp.get(),\n remote_file_name.c_str(),\n O_RDONLY,\n S_IRUSR | S_IWUSR\n );\n\n if (file)\n {\n const int seek_result = sftp_seek64(file, uint64_t(client_position));\n if (seek_result < 0)\n {\n sftp_close(file);\n throw Exception(\"Error while seeking\");\n }\n\n ssize_t total_read = 0;\n\n while (total_read < ssize_t(v.size()))\n {\n const ssize_t read_result = sftp_read\n (\n file,\n &v[size_t(total_read)],\n v.size() - size_t(total_read)\n );\n\n if (read_result < 0)\n {\n sftp_close(file);\n throw Exception(\"Error during sftp_read\");\n }\n\n total_read += read_result;\n if (trace)\n std::cerr << read_result << ' ';\n }\n\n sftp_close(file);\n client_journal.append_raw_tail(v);\n }\n else\n throw Exception(\"Could not open remote file for reading\");\n }\n else if (client_position > server_position)\n throw Exception(\"Trying to pull when ahead of server\");\n\n if (trace)\n std::cerr << \"done.\\n\";\n\n return server_position;\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n void SSH_Connection::raw_push\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n Readonly_Journal &client_journal,\n int64_t server_position\n )\n {\n if (trace)\n std::cerr << full_remote_name << \": push()... \";\n\n const int64_t client_position = client_journal.get_checkpoint_position();\n if (client_position > server_position)\n {\n std::vector v(client_journal.get_raw_tail(server_position));\n\n if (trace)\n std::cerr << v.size() << \" bytes... \";\n\n sftp_file file = sftp_open\n (\n sftp.get(),\n remote_file_name.c_str(),\n O_WRONLY | O_CREAT,\n S_IRUSR | S_IWUSR\n );\n\n const int seek_result = sftp_seek64(file, uint64_t(server_position));\n\n if (file)\n {\n \/\/\n \/\/ https:\/\/tools.ietf.org\/html\/draft-ietf-secsh-filexfer-00\n \/\/\n \/\/ The maximum size of a packet is in practise determined by the client\n \/\/ (the maximum size of read or write requests that it sends, plus a few\n \/\/ bytes of packet overhead). All servers SHOULD support packets of at\n \/\/ least 34000 bytes (where the packet size refers to the full length,\n \/\/ including the header above). This should allow for reads and writes of\n \/\/ at most 32768 bytes.\n \/\/\n const size_t max_block_size = 32768;\n const size_t size = v.size();\n size_t written = 0;\n\n while (seek_result >= 0 && written < size)\n {\n size_t block_size = size - written;\n\n if (block_size > max_block_size)\n block_size = max_block_size;\n\n const ssize_t result = sftp_write(file, v.data() + written, block_size);\n\n if (result <= 0)\n break;\n\n written += size_t(result);\n }\n\n sftp_close(file);\n\n if (written < size)\n throw Exception(\"Incomplete write during push\");\n }\n else\n throw Exception(\"Could not open remote file for writing\");\n }\n\n if (trace)\n std::cerr << \"done.\\n\";\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n SSH_Connection::SSH_Connection\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n (\n std::string user,\n std::string host,\n int port,\n std::string remote_file_name,\n bool trace,\n int ssh_log_level\n ):\n remote_file_name(remote_file_name),\n trace(trace),\n mutex_file_name(remote_file_name + \".mutex\"),\n full_remote_name(user + \"@\" + host + \":\" + remote_file_name),\n session\n (\n user,\n host,\n port,\n ssh_log_level\n ),\n sftp(session)\n {\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: headertablistbox.hxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 13:15:41 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _HEADERTABLISTBOX_HXX\n#define _HEADERTABLISTBOX_HXX\n\n#ifndef _HEADBAR_HXX\n#include \n#endif\n#ifndef _SVTABBX_HXX\n#include \n#endif\n\n\nclass _HeaderTabListBox : public Control\n{\nprivate:\n SvHeaderTabListBox maListBox;\n HeaderBar maHeaderBar;\nprotected:\n DECL_LINK( HeaderEndDrag_Impl, HeaderBar* );\n virtual long Notify( NotifyEvent& rNEvt );\npublic:\n _HeaderTabListBox( Window* pParent, const ResId& rId );\n virtual ~_HeaderTabListBox();\n\n inline SvHeaderTabListBox& GetListBox( void );\n inline HeaderBar& GetHeaderBar( void );\n\n void ConnectElements( void );\n \/\/ should be called after all manipulations on elements are done\n \/\/ calcs real sizes depending on sizes of this\n void Show( BOOL bVisible = TRUE, USHORT nFlags = 0 ); \/\/ same meaning as Windows::Show()\n void Enable( BOOL bEnable = TRUE, BOOL bChild = TRUE ); \/\/ same meaning as Windows::Enable()\n};\n\ninline SvHeaderTabListBox& _HeaderTabListBox::GetListBox( void )\n{\n return maListBox;\n}\n\ninline HeaderBar& _HeaderTabListBox::GetHeaderBar( void )\n{\n return maHeaderBar;\n}\n\n\n#endif\nINTEGRATION: CWS ooo19126 (1.2.830); FILE MERGED 2005\/09\/05 14:25:16 rt 1.2.830.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: headertablistbox.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 23:23:59 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _HEADERTABLISTBOX_HXX\n#define _HEADERTABLISTBOX_HXX\n\n#ifndef _HEADBAR_HXX\n#include \n#endif\n#ifndef _SVTABBX_HXX\n#include \n#endif\n\n\nclass _HeaderTabListBox : public Control\n{\nprivate:\n SvHeaderTabListBox maListBox;\n HeaderBar maHeaderBar;\nprotected:\n DECL_LINK( HeaderEndDrag_Impl, HeaderBar* );\n virtual long Notify( NotifyEvent& rNEvt );\npublic:\n _HeaderTabListBox( Window* pParent, const ResId& rId );\n virtual ~_HeaderTabListBox();\n\n inline SvHeaderTabListBox& GetListBox( void );\n inline HeaderBar& GetHeaderBar( void );\n\n void ConnectElements( void );\n \/\/ should be called after all manipulations on elements are done\n \/\/ calcs real sizes depending on sizes of this\n void Show( BOOL bVisible = TRUE, USHORT nFlags = 0 ); \/\/ same meaning as Windows::Show()\n void Enable( BOOL bEnable = TRUE, BOOL bChild = TRUE ); \/\/ same meaning as Windows::Enable()\n};\n\ninline SvHeaderTabListBox& _HeaderTabListBox::GetListBox( void )\n{\n return maListBox;\n}\n\ninline HeaderBar& _HeaderTabListBox::GetHeaderBar( void )\n{\n return maHeaderBar;\n}\n\n\n#endif\n<|endoftext|>"} {"text":"\/\/ @(#)root\/thread:$Id$\n\/\/ Authors: Enric Tejedor CERN 12\/09\/2016\n\/\/ Philippe Canal FNAL 12\/09\/2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TReentrantRWLock\n \\brief An implementation of a reentrant read-write lock with a\n configurable internal mutex\/lock (default Spin Lock).\n\nThis class provides an implementation of a rreentrant ead-write lock\nthat uses an internal lock and a condition variable to synchronize\nreaders and writers when necessary.\n\nThe implementation allows a single reader to take the write lock without\nreleasing the reader lock. It also allows the writer to take a read lock.\nIn other word, the lock is re-entrant for both reading and writing.\n\nThe implementation tries to make faster the scenario when readers come\nand go but there is no writer. In that case, readers will not pay the\nprice of taking the internal spin lock.\n\nMoreover, this RW lock tries to be fair with writers, giving them the\npossibility to claim the lock and wait for only the remaining readers,\nthus preventing starvation.\n*\/\n\n#include \"ROOT\/TReentrantRWLock.hxx\"\n#include \"ROOT\/TSpinMutex.hxx\"\n#include \"TMutex.h\"\n#include \"TError.h\"\n#include \n\nusing namespace ROOT;\n\nInternal::UniqueLockRecurseCount::UniqueLockRecurseCount()\n{\n static bool singleton = false;\n if (singleton) {\n ::Fatal(\"UniqueLockRecurseCount Ctor\", \"Only one TReentrantRWLock using a UniqueLockRecurseCount is allowed.\");\n }\n singleton = true;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Acquire the lock in read mode.\ntemplate \nTVirtualRWMutex::Hint_t *TReentrantRWLock::ReadLock()\n{\n ++fReaderReservation;\n\n \/\/ if (fReaders == std::numeric_limits::max()) {\n \/\/ ::Fatal(\"TRWSpinLock::WriteLock\", \"Too many recursions in TRWSpinLock!\");\n \/\/ }\n\n auto local = fRecurseCounts.GetLocal();\n\n TVirtualRWMutex::Hint_t *hint = nullptr;\n\n if (!fWriter) {\n \/\/ There is no writer, go freely to the critical section\n ++fReaders;\n --fReaderReservation;\n\n hint = fRecurseCounts.IncrementReadCount(local, fMutex);\n\n } else if (! fRecurseCounts.IsNotCurrentWriter(local)) {\n\n --fReaderReservation;\n \/\/ This can run concurrently with another thread trying to get\n \/\/ the read lock and ending up in the next section (\"Wait for writers, if any\")\n \/\/ which need to also get the local readers count and thus can\n \/\/ modify the map.\n hint = fRecurseCounts.IncrementReadCount(local, fMutex);\n ++fReaders;\n\n } else {\n \/\/ A writer claimed the RW lock, we will need to wait on the\n \/\/ internal lock\n --fReaderReservation;\n\n std::unique_lock lock(fMutex);\n\n \/\/ Wait for writers, if any\n if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {\n auto readerCount = fRecurseCounts.GetLocalReadersCount(local);\n if (readerCount == 0)\n fCond.wait(lock, [this] { return !fWriter; });\n \/\/ else\n \/\/ There is a writer **but** we have outstanding readers\n \/\/ locks, this must mean that the writer is actually\n \/\/ waiting on this thread to release its read locks.\n \/\/ This can be done in only two ways:\n \/\/ * request the writer lock\n \/\/ * release the reader lock\n \/\/ Either way, this thread needs to proceed to\n \/\/ be able to reach a point whether it does one\n \/\/ of the two.\n }\n\n hint = fRecurseCounts.IncrementReadCount(local);\n\n \/\/ This RW lock now belongs to the readers\n ++fReaders;\n\n lock.unlock();\n }\n\n return hint;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Release the lock in read mode.\ntemplate \nvoid TReentrantRWLock::ReadUnLock(TVirtualRWMutex::Hint_t *hint)\n{\n size_t *localReaderCount;\n if (!hint) {\n \/\/ This should be very rare.\n auto local = fRecurseCounts.GetLocal();\n std::lock_guard lock(fMutex);\n localReaderCount = &(fRecurseCounts.GetLocalReadersCount(local));\n } else {\n localReaderCount = reinterpret_cast(hint);\n }\n\n --fReaders;\n if (fWriterReservation && fReaders == 0) {\n \/\/ We still need to lock here to prevent interleaving with a writer\n std::lock_guard lock(fMutex);\n\n --(*localReaderCount);\n\n \/\/ Make sure you wake up a writer, if any\n \/\/ Note: spurrious wakeups are okay, fReaders\n \/\/ will be checked again in WriteLock\n fCond.notify_all();\n } else {\n\n --(*localReaderCount);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Acquire the lock in write mode.\ntemplate \nTVirtualRWMutex::Hint_t *TReentrantRWLock::WriteLock()\n{\n ++fWriterReservation;\n\n std::unique_lock lock(fMutex);\n\n auto local = fRecurseCounts.GetLocal();\n\n \/\/ Release this thread's reader lock(s)\n auto &readerCount = fRecurseCounts.GetLocalReadersCount(local);\n TVirtualRWMutex::Hint_t *hint = reinterpret_cast(&readerCount);\n\n fReaders -= readerCount;\n\n \/\/ Wait for other writers, if any\n if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {\n if (readerCount && fReaders == 0) {\n \/\/ we decrease fReaders to zero, let's wake up the\n \/\/ other writer.\n fCond.notify_all();\n }\n fCond.wait(lock, [this] { return !fWriter; });\n }\n\n \/\/ Claim the lock for this writer\n fWriter = true;\n fRecurseCounts.SetIsWriter(local);\n\n \/\/ Wait until all reader reservations finish\n while (fReaderReservation) {\n };\n\n \/\/ Wait for remaining readers\n fCond.wait(lock, [this] { return fReaders == 0; });\n\n \/\/ Restore this thread's reader lock(s)\n fReaders += readerCount;\n\n --fWriterReservation;\n\n lock.unlock();\n\n return hint;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Release the lock in write mode.\ntemplate \nvoid TReentrantRWLock::WriteUnLock(TVirtualRWMutex::Hint_t *)\n{\n \/\/ We need to lock here to prevent interleaving with a reader\n std::lock_guard lock(fMutex);\n\n if (!fWriter || fRecurseCounts.fWriteRecurse == 0) {\n Error(\"TReentrantRWLock::WriteUnLock\", \"Write lock already released for %p\", this);\n return;\n }\n\n fRecurseCounts.DecrementWriteCount();\n\n if (!fRecurseCounts.fWriteRecurse) {\n fWriter = false;\n\n auto local = fRecurseCounts.GetLocal();\n fRecurseCounts.ResetIsWriter(local);\n\n \/\/ Notify all potential readers\/writers that are waiting\n fCond.notify_all();\n }\n}\n\nnamespace {\ntemplate \nstruct TReentrantRWLockState: public TVirtualMutex::State {\n int fReadersCount = 0;\n size_t *fReadersCountLoc = nullptr;\n size_t fWriteRecurse = 0;\n bool fIsWriter = false;\n};\n}\n\ntemplate \nstd::unique_ptr TReentrantRWLock::Reset()\n{\n using State_t = TReentrantRWLockState;\n\n std::unique_ptr pState(new State_t);\n auto local = fRecurseCounts.GetLocal();\n\n {\n std::unique_lock lock(fMutex);\n pState->fReadersCountLoc = &(fRecurseCounts.GetLocalReadersCount(local));\n }\n size_t &readerCount(*(pState->fReadersCountLoc));\n\n pState->fReadersCount = readerCount;\n\n if (fWriter && !fRecurseCounts.IsNotCurrentWriter(local)) {\n\n \/\/ We are holding the write lock.\n pState->fIsWriter = true;\n pState->fWriteRecurse = fRecurseCounts.fWriteRecurse;\n\n \/\/ Now set the lock (and potential read locks) for immediate release.\n fReaders -= readerCount;\n fRecurseCounts.fWriteRecurse = 1;\n\n *(pState->fReadersCountLoc) = 0;\n\n \/\/ Release this thread's write lock\n WriteUnLock(reinterpret_cast(pState->fReadersCountLoc));\n } else if (readerCount) {\n \/\/ Now set the lock for release.\n fReaders -= (readerCount-1);\n *(pState->fReadersCountLoc) = 1;\n\n \/\/ Release this thread's reader lock(s)\n ReadUnLock(reinterpret_cast(pState->fReadersCountLoc));\n }\n\n \/\/ Do something.\n \/\/::Fatal(\"Reset()\", \"Not implemented, contact pcanal@fnal.gov\");\n return std::move(pState);\n}\n\ntemplate \nvoid TReentrantRWLock::Restore(std::unique_ptr &&state)\n{\n TReentrantRWLockState *pState = dynamic_cast *>(state.get());\n if (!pState) {\n if (state) {\n SysError(\"Restore\", \"LOGIC ERROR - invalid state object!\");\n return;\n }\n \/\/ No state, do nothing.\n return;\n }\n\n if (pState->fIsWriter) {\n WriteLock();\n \/\/ Now that we go the lock, fix up the recursion count.\n std::unique_lock lock(fMutex);\n fRecurseCounts.fWriteRecurse = pState->fWriteRecurse;\n *(pState->fReadersCountLoc) = pState->fReadersCount;\n fReaders += pState->fReadersCount;\n } else {\n ReadLock();\n \/\/ Now that we go the read lock, fix up the local recursion count.\n assert( pState->fReadersCount >= 1 );\n auto readerCount = pState->fReadersCount;\n\n std::unique_lock lock(fMutex);\n *(pState->fReadersCountLoc) = pState->fReadersCount;\n fReaders += readerCount - 1;\n }\n\n \/\/ Do something.\n \/\/::Fatal(\"Restore()\", \"Not implemented, contact pcanal@fnal.gov\");\n}\n\nnamespace ROOT {\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\n\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\n}\nFix typo in comment\/\/ @(#)root\/thread:$Id$\n\/\/ Authors: Enric Tejedor CERN 12\/09\/2016\n\/\/ Philippe Canal FNAL 12\/09\/2016\n\n\/*************************************************************************\n * Copyright (C) 1995-2016, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/** \\class TReentrantRWLock\n \\brief An implementation of a reentrant read-write lock with a\n configurable internal mutex\/lock (default Spin Lock).\n\nThis class provides an implementation of a reentrant read-write lock\nthat uses an internal lock and a condition variable to synchronize\nreaders and writers when necessary.\n\nThe implementation allows a single reader to take the write lock without\nreleasing the reader lock. It also allows the writer to take a read lock.\nIn other word, the lock is re-entrant for both reading and writing.\n\nThe implementation tries to make faster the scenario when readers come\nand go but there is no writer. In that case, readers will not pay the\nprice of taking the internal spin lock.\n\nMoreover, this RW lock tries to be fair with writers, giving them the\npossibility to claim the lock and wait for only the remaining readers,\nthus preventing starvation.\n*\/\n\n#include \"ROOT\/TReentrantRWLock.hxx\"\n#include \"ROOT\/TSpinMutex.hxx\"\n#include \"TMutex.h\"\n#include \"TError.h\"\n#include \n\nusing namespace ROOT;\n\nInternal::UniqueLockRecurseCount::UniqueLockRecurseCount()\n{\n static bool singleton = false;\n if (singleton) {\n ::Fatal(\"UniqueLockRecurseCount Ctor\", \"Only one TReentrantRWLock using a UniqueLockRecurseCount is allowed.\");\n }\n singleton = true;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Acquire the lock in read mode.\ntemplate \nTVirtualRWMutex::Hint_t *TReentrantRWLock::ReadLock()\n{\n ++fReaderReservation;\n\n \/\/ if (fReaders == std::numeric_limits::max()) {\n \/\/ ::Fatal(\"TRWSpinLock::WriteLock\", \"Too many recursions in TRWSpinLock!\");\n \/\/ }\n\n auto local = fRecurseCounts.GetLocal();\n\n TVirtualRWMutex::Hint_t *hint = nullptr;\n\n if (!fWriter) {\n \/\/ There is no writer, go freely to the critical section\n ++fReaders;\n --fReaderReservation;\n\n hint = fRecurseCounts.IncrementReadCount(local, fMutex);\n\n } else if (! fRecurseCounts.IsNotCurrentWriter(local)) {\n\n --fReaderReservation;\n \/\/ This can run concurrently with another thread trying to get\n \/\/ the read lock and ending up in the next section (\"Wait for writers, if any\")\n \/\/ which need to also get the local readers count and thus can\n \/\/ modify the map.\n hint = fRecurseCounts.IncrementReadCount(local, fMutex);\n ++fReaders;\n\n } else {\n \/\/ A writer claimed the RW lock, we will need to wait on the\n \/\/ internal lock\n --fReaderReservation;\n\n std::unique_lock lock(fMutex);\n\n \/\/ Wait for writers, if any\n if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {\n auto readerCount = fRecurseCounts.GetLocalReadersCount(local);\n if (readerCount == 0)\n fCond.wait(lock, [this] { return !fWriter; });\n \/\/ else\n \/\/ There is a writer **but** we have outstanding readers\n \/\/ locks, this must mean that the writer is actually\n \/\/ waiting on this thread to release its read locks.\n \/\/ This can be done in only two ways:\n \/\/ * request the writer lock\n \/\/ * release the reader lock\n \/\/ Either way, this thread needs to proceed to\n \/\/ be able to reach a point whether it does one\n \/\/ of the two.\n }\n\n hint = fRecurseCounts.IncrementReadCount(local);\n\n \/\/ This RW lock now belongs to the readers\n ++fReaders;\n\n lock.unlock();\n }\n\n return hint;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Release the lock in read mode.\ntemplate \nvoid TReentrantRWLock::ReadUnLock(TVirtualRWMutex::Hint_t *hint)\n{\n size_t *localReaderCount;\n if (!hint) {\n \/\/ This should be very rare.\n auto local = fRecurseCounts.GetLocal();\n std::lock_guard lock(fMutex);\n localReaderCount = &(fRecurseCounts.GetLocalReadersCount(local));\n } else {\n localReaderCount = reinterpret_cast(hint);\n }\n\n --fReaders;\n if (fWriterReservation && fReaders == 0) {\n \/\/ We still need to lock here to prevent interleaving with a writer\n std::lock_guard lock(fMutex);\n\n --(*localReaderCount);\n\n \/\/ Make sure you wake up a writer, if any\n \/\/ Note: spurrious wakeups are okay, fReaders\n \/\/ will be checked again in WriteLock\n fCond.notify_all();\n } else {\n\n --(*localReaderCount);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Acquire the lock in write mode.\ntemplate \nTVirtualRWMutex::Hint_t *TReentrantRWLock::WriteLock()\n{\n ++fWriterReservation;\n\n std::unique_lock lock(fMutex);\n\n auto local = fRecurseCounts.GetLocal();\n\n \/\/ Release this thread's reader lock(s)\n auto &readerCount = fRecurseCounts.GetLocalReadersCount(local);\n TVirtualRWMutex::Hint_t *hint = reinterpret_cast(&readerCount);\n\n fReaders -= readerCount;\n\n \/\/ Wait for other writers, if any\n if (fWriter && fRecurseCounts.IsNotCurrentWriter(local)) {\n if (readerCount && fReaders == 0) {\n \/\/ we decrease fReaders to zero, let's wake up the\n \/\/ other writer.\n fCond.notify_all();\n }\n fCond.wait(lock, [this] { return !fWriter; });\n }\n\n \/\/ Claim the lock for this writer\n fWriter = true;\n fRecurseCounts.SetIsWriter(local);\n\n \/\/ Wait until all reader reservations finish\n while (fReaderReservation) {\n };\n\n \/\/ Wait for remaining readers\n fCond.wait(lock, [this] { return fReaders == 0; });\n\n \/\/ Restore this thread's reader lock(s)\n fReaders += readerCount;\n\n --fWriterReservation;\n\n lock.unlock();\n\n return hint;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ Release the lock in write mode.\ntemplate \nvoid TReentrantRWLock::WriteUnLock(TVirtualRWMutex::Hint_t *)\n{\n \/\/ We need to lock here to prevent interleaving with a reader\n std::lock_guard lock(fMutex);\n\n if (!fWriter || fRecurseCounts.fWriteRecurse == 0) {\n Error(\"TReentrantRWLock::WriteUnLock\", \"Write lock already released for %p\", this);\n return;\n }\n\n fRecurseCounts.DecrementWriteCount();\n\n if (!fRecurseCounts.fWriteRecurse) {\n fWriter = false;\n\n auto local = fRecurseCounts.GetLocal();\n fRecurseCounts.ResetIsWriter(local);\n\n \/\/ Notify all potential readers\/writers that are waiting\n fCond.notify_all();\n }\n}\n\nnamespace {\ntemplate \nstruct TReentrantRWLockState: public TVirtualMutex::State {\n int fReadersCount = 0;\n size_t *fReadersCountLoc = nullptr;\n size_t fWriteRecurse = 0;\n bool fIsWriter = false;\n};\n}\n\ntemplate \nstd::unique_ptr TReentrantRWLock::Reset()\n{\n using State_t = TReentrantRWLockState;\n\n std::unique_ptr pState(new State_t);\n auto local = fRecurseCounts.GetLocal();\n\n {\n std::unique_lock lock(fMutex);\n pState->fReadersCountLoc = &(fRecurseCounts.GetLocalReadersCount(local));\n }\n size_t &readerCount(*(pState->fReadersCountLoc));\n\n pState->fReadersCount = readerCount;\n\n if (fWriter && !fRecurseCounts.IsNotCurrentWriter(local)) {\n\n \/\/ We are holding the write lock.\n pState->fIsWriter = true;\n pState->fWriteRecurse = fRecurseCounts.fWriteRecurse;\n\n \/\/ Now set the lock (and potential read locks) for immediate release.\n fReaders -= readerCount;\n fRecurseCounts.fWriteRecurse = 1;\n\n *(pState->fReadersCountLoc) = 0;\n\n \/\/ Release this thread's write lock\n WriteUnLock(reinterpret_cast(pState->fReadersCountLoc));\n } else if (readerCount) {\n \/\/ Now set the lock for release.\n fReaders -= (readerCount-1);\n *(pState->fReadersCountLoc) = 1;\n\n \/\/ Release this thread's reader lock(s)\n ReadUnLock(reinterpret_cast(pState->fReadersCountLoc));\n }\n\n \/\/ Do something.\n \/\/::Fatal(\"Reset()\", \"Not implemented, contact pcanal@fnal.gov\");\n return std::move(pState);\n}\n\ntemplate \nvoid TReentrantRWLock::Restore(std::unique_ptr &&state)\n{\n TReentrantRWLockState *pState = dynamic_cast *>(state.get());\n if (!pState) {\n if (state) {\n SysError(\"Restore\", \"LOGIC ERROR - invalid state object!\");\n return;\n }\n \/\/ No state, do nothing.\n return;\n }\n\n if (pState->fIsWriter) {\n WriteLock();\n \/\/ Now that we go the lock, fix up the recursion count.\n std::unique_lock lock(fMutex);\n fRecurseCounts.fWriteRecurse = pState->fWriteRecurse;\n *(pState->fReadersCountLoc) = pState->fReadersCount;\n fReaders += pState->fReadersCount;\n } else {\n ReadLock();\n \/\/ Now that we go the read lock, fix up the local recursion count.\n assert( pState->fReadersCount >= 1 );\n auto readerCount = pState->fReadersCount;\n\n std::unique_lock lock(fMutex);\n *(pState->fReadersCountLoc) = pState->fReadersCount;\n fReaders += readerCount - 1;\n }\n\n \/\/ Do something.\n \/\/::Fatal(\"Restore()\", \"Not implemented, contact pcanal@fnal.gov\");\n}\n\nnamespace ROOT {\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\n\ntemplate class TReentrantRWLock;\ntemplate class TReentrantRWLock;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"dg\/SystemDependenceGraph\/DependenceGraph.h\"\n#include \"dg\/SystemDependenceGraph\/DGNode.h\"\n#include \"dg\/SystemDependenceGraph\/DGNodeCall.h\"\n#include \"dg\/SystemDependenceGraph\/DGArgumentPair.h\"\n#include \"dg\/SystemDependenceGraph\/DGParameters.h\"\n\nnamespace dg {\nnamespace sdg {\n\n\/\/ ------------------------------------------------------------------\n\/\/ -- Parameters --\n\/\/ ------------------------------------------------------------------\n\nDGArgumentPair::DGArgumentPair(DGParameters& p)\n: DGElement(p.getDG(), DGElementType::ARG_PAIR),\n _parameters(p), _input(p.getDG()), _output(p.getDG()) {}\n\nDGActualParameters::DGActualParameters(DGNodeCall& call)\n: DGParameters(call.getDG()), _call(call) {}\n\nDGNodeArtificial& DGFormalParameters::createVarArg() {\n auto& dg = getDG();\n _vararg.reset(&dg.createArtificial());\n return *_vararg.get();\n}\n\nDGNode& DGParameters::createNoReturn() {\n auto& dg = getDG();\n _noreturn.reset(&dg.createArtificial());\n return *_noreturn.get();\n}\n\n\n\/\/ ------------------------------------------------------------------\n\/\/ -- Node --\n\/\/ ------------------------------------------------------------------\n\nunsigned DGNode::getNewID(DependenceGraph& g) {\n assert(_id == 0 && \"Used outside of ctor\");\n return g.getNextNodeID();\n}\n\nDGNode::DGNode(DependenceGraph& g, DGElementType t)\n: DGElement(g, t), _id(getNewID(g)) {}\n\n\n} \/\/ namespace sdg\n} \/\/ namespace dg\n\nsdg: remove invalid assertion#include \n\n#include \"dg\/SystemDependenceGraph\/DependenceGraph.h\"\n#include \"dg\/SystemDependenceGraph\/DGNode.h\"\n#include \"dg\/SystemDependenceGraph\/DGNodeCall.h\"\n#include \"dg\/SystemDependenceGraph\/DGArgumentPair.h\"\n#include \"dg\/SystemDependenceGraph\/DGParameters.h\"\n\nnamespace dg {\nnamespace sdg {\n\n\/\/ ------------------------------------------------------------------\n\/\/ -- Parameters --\n\/\/ ------------------------------------------------------------------\n\nDGArgumentPair::DGArgumentPair(DGParameters& p)\n: DGElement(p.getDG(), DGElementType::ARG_PAIR),\n _parameters(p), _input(p.getDG()), _output(p.getDG()) {}\n\nDGActualParameters::DGActualParameters(DGNodeCall& call)\n: DGParameters(call.getDG()), _call(call) {}\n\nDGNodeArtificial& DGFormalParameters::createVarArg() {\n auto& dg = getDG();\n _vararg.reset(&dg.createArtificial());\n return *_vararg.get();\n}\n\nDGNode& DGParameters::createNoReturn() {\n auto& dg = getDG();\n _noreturn.reset(&dg.createArtificial());\n return *_noreturn.get();\n}\n\n\n\/\/ ------------------------------------------------------------------\n\/\/ -- Node --\n\/\/ ------------------------------------------------------------------\n\nunsigned DGNode::getNewID(DependenceGraph& g) {\n return g.getNextNodeID();\n}\n\nDGNode::DGNode(DependenceGraph& g, DGElementType t)\n: DGElement(g, t), _id(getNewID(g)) {}\n\n\n} \/\/ namespace sdg\n} \/\/ namespace dg\n\n<|endoftext|>"} {"text":"#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nclass SetRequestMessageExt : public SetRequestMessage {\n public:\n SetRequestMessageExt() : SetRequestMessage() {}\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nclass SetResponseMessageExt : public SetResponseMessage {\n public:\n SetResponseMessageExt() : SetResponseMessage() {}\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nTEST(MessageTest, SetRequest__Constructor_01) {\n \/\/ public methods\n \/\/ SetRequestMessage();\n\n SetRequestMessage request;\n\n EXPECT_EQ(15, request.size());\n EXPECT_EQ(0, request.get_sequence_id());\n EXPECT_EQ(0, request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, request.type());\n EXPECT_EQ(true, request.is_request());\n EXPECT_EQ(0, request.request_id());\n\n EXPECT_EQ(false, request.get_priority());\n EXPECT_EQ(\"\", request.get_target_path());\n EXPECT_EQ(\"\", request.get_permission_token());\n EXPECT_EQ(false, request.get_no_stream());\n EXPECT_EQ(0, request.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__Constructor_02) {\n \/\/ SetRequestMessage(const SetRequestMessage&);\n\n const SetRequestMessage src__request;\n SetRequestMessage target__request(src__request);\n\n EXPECT_EQ(15, target__request.size());\n EXPECT_EQ(0, target__request.get_sequence_id());\n EXPECT_EQ(0, target__request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, target__request.type());\n EXPECT_EQ(true, target__request.is_request());\n EXPECT_EQ(0, target__request.request_id());\n\n EXPECT_EQ(false, target__request.get_priority());\n EXPECT_EQ(\"\", target__request.get_target_path());\n EXPECT_EQ(\"\", target__request.get_permission_token());\n EXPECT_EQ(false, target__request.get_no_stream());\n EXPECT_EQ(0, target__request.get_alias_count());\n\n std::string target_path(\"path\/to\/abc\");\n target__request.set_target_path(target_path);\n\n EXPECT_EQ(\"\", src__request.get_target_path());\n EXPECT_EQ(target_path, target__request.get_target_path());\n\n EXPECT_EQ(29, target__request.size());\n}\n\nTEST(MessageTest, SetRequest__Constructor_03) {\n \/\/ SetRequestMessage(const uint8_t* data, size_t size);\n\n const uint8_t data[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0, 0x4, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};\n size_t data_size = sizeof(data) \/ sizeof(uint8_t);\n\n SetRequestMessage request(data, data_size);\n\n EXPECT_EQ(15, request.size());\n EXPECT_EQ(0, request.get_sequence_id());\n EXPECT_EQ(0, request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, request.type());\n EXPECT_EQ(true, request.is_request());\n EXPECT_EQ(0, request.request_id());\n\n EXPECT_EQ(false, request.get_priority());\n EXPECT_EQ(\"\", request.get_target_path());\n EXPECT_EQ(\"\", request.get_permission_token());\n EXPECT_EQ(false, request.get_no_stream());\n EXPECT_EQ(0, request.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__Constructor_04) {\n \/\/ SetRequestMessage(const uint8_t* data, size_t size);\n\n SetRequestMessage request;\n request.set_target_path(\"\/request\");\n SetRequestMessage other = request;\n EXPECT_EQ(\"\/request\", other.get_target_path());\n other.set_target_path(\"\/other\");\n EXPECT_EQ(\"\/request\", request.get_target_path());\n EXPECT_EQ(\"\/other\", other.get_target_path());\n\n EXPECT_EQ(24, other.size());\n EXPECT_EQ(0, other.get_sequence_id());\n EXPECT_EQ(0, other.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, other.type());\n EXPECT_EQ(true, other.is_request());\n EXPECT_EQ(0, other.request_id());\n\n EXPECT_EQ(false, other.get_priority());\n EXPECT_EQ(\"\/other\", other.get_target_path());\n EXPECT_EQ(\"\", other.get_permission_token());\n EXPECT_EQ(false, other.get_no_stream());\n EXPECT_EQ(0, other.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__get_set_options) {\n \/\/ SetOptions get_set_options() const;\n\n SetRequestMessage request;\n SetOptions option = request.get_set_options();\n\n EXPECT_EQ(1, sizeof(option));\n}\n\nTEST(MessageTest, SetRequest__update_static_header) {\n \/\/ void update_static_header();\n SetRequestMessageExt request;\n request.size();\n\n uint8_t expect_values[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0};\n EXPECT_EQ(true,\n request.check_static_headers(\n expect_values, sizeof(expect_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetRequest__priority) {\n SetRequestMessage request;\n\n EXPECT_EQ(false, request.get_priority());\n request.set_priority(true);\n EXPECT_EQ(true, request.get_priority());\n}\n\nTEST(MessageTest, SetRequest__target_path) {\n SetRequestMessage request;\n\n EXPECT_EQ(\"\", request.get_target_path());\n request.set_target_path(\"path\/to\/node\");\n EXPECT_EQ(\"path\/to\/node\", request.get_target_path());\n}\n\nTEST(MessageTest, SetRequest__permission_token) {\n \/\/ TODO: to be implemented\n SetRequestMessage request;\n\n EXPECT_EQ(\"\", request.get_permission_token());\n request.set_permission_token(\"permission-token\");\n EXPECT_EQ(\"permission-token\", request.get_permission_token());\n}\n\nTEST(MessageTest, SetRequest__no_stream) {\n SetRequestMessage request;\n\n EXPECT_EQ(false, request.get_no_stream());\n request.set_no_stream(true);\n EXPECT_EQ(true, request.get_no_stream());\n}\n\nTEST(MessageTest, SetRequest__write) {\n SetRequestMessage request;\n\n request.set_target_path(\"path\/to\/dsa\");\n request.set_no_stream(true);\n\n request.size();\n\n uint8_t buf[1024];\n request.write(buf);\n\n uint8_t expected_values[] = {0x1e, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x4, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80,\n 0x0b, 0x0, 0x70, 0x61, 0x74, 0x68, 0x2f, 0x74,\n 0x6f, 0x2f, 0x64, 0x73, 0x61, 0x11};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetRequest__dynamic_structure) {\n SetRequestMessage request;\n\n \/\/ request.set_status(MessageStatus::Closed);\n request.set_sequence_id(1234); \/\/ no effect\n request.set_page_id(4321); \/\/ no effect\n request.set_alias_count(11);\n request.set_priority(true);\n \/\/ request.set_no_stream(); \/\/ TODO: TBI\n \/\/ request.set_qos(1); \/\/\n \/\/ request.set_queue_size();\n \/\/ request.set_queue_time();\n \/\/ request.set_base_path();\n \/\/ request.skippable();\n \/\/ request.set_max_permission();\n request.set_permission_token(\"ptoken\");\n request.set_target_path(\"\/target\/path\");\n \/\/ request.set_source_path(\"\/source\/path\"); \/\/ no effect\n\n request.size();\n\n uint8_t buf[1024];\n request.write(buf);\n\n uint8_t expected_values[] = {\n 0x2f, 0x0, 0x0, 0x0, 0x2f, 0x0, 0x04, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x10, 0x02, 0xe1, 0x10, 0x0, 0x0, 0x08, 0x0b, 0x80,\n 0x0c, 0x0, 0x2f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x2f, 0x70, 0x61,\n 0x74, 0x68, 0x60, 0x06, 0x0, 0x70, 0x74, 0x6f, 0x6b, 0x65, 0x6e};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetResponse__Constructor) {\n SetResponseMessage response;\n\n EXPECT_EQ(15, response.size());\n EXPECT_EQ(0, response.get_sequence_id());\n EXPECT_EQ(0, response.get_page_id());\n EXPECT_EQ(MessageType::SetResponse, response.type());\n EXPECT_EQ(false, response.is_request());\n EXPECT_EQ(0, response.request_id());\n}\n\nTEST(MessageTest, SetResponse__source_path) {\n SetResponseMessage response;\n\n EXPECT_EQ(\"\", response.get_source_path());\n response.set_source_path(\"\/source\/path\");\n EXPECT_EQ(\"\/source\/path\", response.get_source_path());\n}\n\nTEST(MessageTest, SetResponse__status) {\n SetResponseMessage response;\n\n static const MessageStatus message_status_all[]{\n MessageStatus::Ok,\n MessageStatus::Initializing,\n MessageStatus::Refreshed,\n MessageStatus::NotAvailable,\n MessageStatus::Closed,\n MessageStatus::Disconnected,\n MessageStatus::PermissionDenied,\n MessageStatus::InvalidMessage,\n MessageStatus::InvalidParameter,\n MessageStatus::Busy,\n MessageStatus::AliasLoop,\n MessageStatus::ConnectionError,\n };\n for (const auto status : message_status_all) {\n response.set_status(status);\n EXPECT_EQ(status, response.get_status());\n }\n}\n\nTEST(MessageTest, SetResponse__write) {\n SetResponseMessage response;\n\n response.set_source_path(\"source\/path\");\n response.set_status(MessageStatus::Busy);\n\n response.size();\n\n uint8_t buf[1024];\n response.write(buf);\n\n uint8_t expected_values[] = {0x11, 0x0, 0x0, 0x0, 0x11, 0x0, 0x84, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x28};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetResponse__dynamic_structure) {\n SetResponseMessage response;\n\n response.set_status(MessageStatus::Closed);\n response.set_sequence_id(1234); \/\/ no effect\n response.set_page_id(4321); \/\/ no effect\n \/\/ response.set_alias_count(11);\n \/\/ response.set_priority(0x80); \/\/ TODO: TBI\n \/\/ response.set_no_stream();\n \/\/ response.set_qos(1); \/\/\n \/\/ response.set_queue_size();\n \/\/ response.set_queue_time();\n \/\/ response.set_base_path();\n \/\/ response.skippable();\n \/\/ response.set_max_permission();\n \/\/ response.set_permission_token();\n \/\/ response.set_target_path(\"\/target\/path\");\n response.set_source_path(\"\/source\/path\"); \/\/ no effect\n\n response.size();\n\n uint8_t buf[1024];\n response.write(buf);\n\n uint8_t expected_values[] = {0x11, 0x0, 0x0, 0x0, 0x11, 0x0, 0x84, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\ncorrect set message's unittest#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nclass SetRequestMessageExt : public SetRequestMessage {\n public:\n SetRequestMessageExt() : SetRequestMessage() {}\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nclass SetResponseMessageExt : public SetResponseMessage {\n public:\n SetResponseMessageExt() : SetResponseMessage() {}\n\n bool check_static_headers(uint8_t *expected_values, size_t size) {\n uint8_t buf[1024];\n static_headers.write(buf);\n\n return (memcmp(expected_values, buf, size) == 0);\n }\n};\n\nTEST(MessageTest, SetRequest__Constructor_01) {\n \/\/ public methods\n \/\/ SetRequestMessage();\n\n SetRequestMessage request;\n\n EXPECT_EQ(15, request.size());\n EXPECT_EQ(0, request.get_sequence_id());\n EXPECT_EQ(0, request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, request.type());\n EXPECT_EQ(true, request.is_request());\n EXPECT_EQ(0, request.request_id());\n\n EXPECT_EQ(false, request.get_priority());\n EXPECT_EQ(\"\", request.get_target_path());\n EXPECT_EQ(\"\", request.get_permission_token());\n EXPECT_EQ(false, request.get_no_stream());\n EXPECT_EQ(0, request.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__Constructor_02) {\n \/\/ SetRequestMessage(const SetRequestMessage&);\n\n const SetRequestMessage src__request;\n SetRequestMessage target__request(src__request);\n\n EXPECT_EQ(15, target__request.size());\n EXPECT_EQ(0, target__request.get_sequence_id());\n EXPECT_EQ(0, target__request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, target__request.type());\n EXPECT_EQ(true, target__request.is_request());\n EXPECT_EQ(0, target__request.request_id());\n\n EXPECT_EQ(false, target__request.get_priority());\n EXPECT_EQ(\"\", target__request.get_target_path());\n EXPECT_EQ(\"\", target__request.get_permission_token());\n EXPECT_EQ(false, target__request.get_no_stream());\n EXPECT_EQ(0, target__request.get_alias_count());\n\n std::string target_path(\"path\/to\/abc\");\n target__request.set_target_path(target_path);\n\n EXPECT_EQ(\"\", src__request.get_target_path());\n EXPECT_EQ(target_path, target__request.get_target_path());\n\n EXPECT_EQ(29, target__request.size());\n}\n\nTEST(MessageTest, SetRequest__Constructor_03) {\n \/\/ SetRequestMessage(const uint8_t* data, size_t size);\n\n const uint8_t data[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0, 0x4, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0};\n size_t data_size = sizeof(data) \/ sizeof(uint8_t);\n\n SetRequestMessage request(data, data_size);\n\n EXPECT_EQ(15, request.size());\n EXPECT_EQ(0, request.get_sequence_id());\n EXPECT_EQ(0, request.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, request.type());\n EXPECT_EQ(true, request.is_request());\n EXPECT_EQ(0, request.request_id());\n\n EXPECT_EQ(false, request.get_priority());\n EXPECT_EQ(\"\", request.get_target_path());\n EXPECT_EQ(\"\", request.get_permission_token());\n EXPECT_EQ(false, request.get_no_stream());\n EXPECT_EQ(0, request.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__Constructor_04) {\n \/\/ SetRequestMessage(const uint8_t* data, size_t size);\n\n SetRequestMessage request;\n request.set_target_path(\"\/request\");\n SetRequestMessage other = request;\n EXPECT_EQ(\"\/request\", other.get_target_path());\n other.set_target_path(\"\/other\");\n EXPECT_EQ(\"\/request\", request.get_target_path());\n EXPECT_EQ(\"\/other\", other.get_target_path());\n\n EXPECT_EQ(24, other.size());\n EXPECT_EQ(0, other.get_sequence_id());\n EXPECT_EQ(0, other.get_page_id());\n EXPECT_EQ(MessageType::SetRequest, other.type());\n EXPECT_EQ(true, other.is_request());\n EXPECT_EQ(0, other.request_id());\n\n EXPECT_EQ(false, other.get_priority());\n EXPECT_EQ(\"\/other\", other.get_target_path());\n EXPECT_EQ(\"\", other.get_permission_token());\n EXPECT_EQ(false, other.get_no_stream());\n EXPECT_EQ(0, other.get_alias_count());\n}\n\nTEST(MessageTest, SetRequest__get_set_options) {\n \/\/ SetOptions get_set_options() const;\n\n SetRequestMessage request;\n SetOptions option = request.get_set_options();\n\n EXPECT_EQ(1, sizeof(option));\n}\n\nTEST(MessageTest, SetRequest__update_static_header) {\n \/\/ void update_static_header();\n SetRequestMessageExt request;\n request.size();\n\n uint8_t expect_values[] = {0xf, 0x0, 0x0, 0x0, 0xf, 0x0};\n EXPECT_EQ(true,\n request.check_static_headers(\n expect_values, sizeof(expect_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetRequest__priority) {\n SetRequestMessage request;\n\n EXPECT_EQ(false, request.get_priority());\n request.set_priority(true);\n EXPECT_EQ(true, request.get_priority());\n}\n\nTEST(MessageTest, SetRequest__target_path) {\n SetRequestMessage request;\n\n EXPECT_EQ(\"\", request.get_target_path());\n request.set_target_path(\"path\/to\/node\");\n EXPECT_EQ(\"path\/to\/node\", request.get_target_path());\n}\n\nTEST(MessageTest, SetRequest__permission_token) {\n \/\/ TODO: to be implemented\n SetRequestMessage request;\n\n EXPECT_EQ(\"\", request.get_permission_token());\n request.set_permission_token(\"permission-token\");\n EXPECT_EQ(\"permission-token\", request.get_permission_token());\n}\n\nTEST(MessageTest, SetRequest__no_stream) {\n SetRequestMessage request;\n\n EXPECT_EQ(false, request.get_no_stream());\n request.set_no_stream(true);\n EXPECT_EQ(true, request.get_no_stream());\n}\n\nTEST(MessageTest, SetRequest__write) {\n SetRequestMessage request;\n\n request.set_target_path(\"path\/to\/dsa\");\n request.set_no_stream(true);\n\n request.size();\n\n uint8_t buf[1024];\n request.write(buf);\n\n uint8_t expected_values[] = {0x1e, 0x0, 0x0, 0x0, 0x1e, 0x0, 0x4, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80,\n 0x0b, 0x0, 0x70, 0x61, 0x74, 0x68, 0x2f, 0x74,\n 0x6f, 0x2f, 0x64, 0x73, 0x61, 0x11};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetRequest__dynamic_structure) {\n SetRequestMessage request;\n\n \/\/ request.set_status(MessageStatus::Closed);\n request.set_sequence_id(1234); \/\/ no effect\n request.set_page_id(4321);\n request.set_alias_count(11);\n request.set_priority(true);\n request.set_no_stream(true);\n \/\/ request.set_qos(1); \/\/\n \/\/ request.set_queue_size();\n \/\/ request.set_queue_time();\n \/\/ request.set_base_path();\n \/\/ request.skippable();\n \/\/ request.set_max_permission();\n request.set_permission_token(\"ptoken\");\n request.set_target_path(\"\/target\/path\");\n \/\/ request.set_source_path(\"\/source\/path\"); \/\/ no effect\n\n request.size();\n\n uint8_t buf[1024];\n request.write(buf);\n\n uint8_t expected_values[] = {\n 0x30, 0x0, 0x0, 0x0, 0x30, 0x0, 0x04, 0x0, 0x0, 0x0, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x10, 0x02, 0xe1, 0x10, 0x0, 0x0, 0x08, 0x0b, 0x80,\n 0x0c, 0x0, 0x2f, 0x74, 0x61, 0x72, 0x67, 0x65, 0x74, 0x2f, 0x70, 0x61,\n 0x74, 0x68, 0x60, 0x06, 0x0, 0x70, 0x74, 0x6f, 0x6b, 0x65, 0x6e, 0x11};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetResponse__Constructor) {\n SetResponseMessage response;\n\n EXPECT_EQ(15, response.size());\n EXPECT_EQ(0, response.get_sequence_id());\n EXPECT_EQ(0, response.get_page_id());\n EXPECT_EQ(MessageType::SetResponse, response.type());\n EXPECT_EQ(false, response.is_request());\n EXPECT_EQ(0, response.request_id());\n}\n\nTEST(MessageTest, SetResponse__source_path) {\n SetResponseMessage response;\n\n EXPECT_EQ(\"\", response.get_source_path());\n response.set_source_path(\"\/source\/path\");\n EXPECT_EQ(\"\/source\/path\", response.get_source_path());\n}\n\nTEST(MessageTest, SetResponse__status) {\n SetResponseMessage response;\n\n static const MessageStatus message_status_all[]{\n MessageStatus::Ok,\n MessageStatus::Initializing,\n MessageStatus::Refreshed,\n MessageStatus::NotAvailable,\n MessageStatus::Closed,\n MessageStatus::Disconnected,\n MessageStatus::PermissionDenied,\n MessageStatus::InvalidMessage,\n MessageStatus::InvalidParameter,\n MessageStatus::Busy,\n MessageStatus::AliasLoop,\n MessageStatus::ConnectionError,\n };\n for (const auto status : message_status_all) {\n response.set_status(status);\n EXPECT_EQ(status, response.get_status());\n }\n}\n\nTEST(MessageTest, SetResponse__write) {\n SetResponseMessage response;\n\n response.set_source_path(\"source\/path\");\n response.set_status(MessageStatus::Busy);\n\n response.size();\n\n uint8_t buf[1024];\n response.write(buf);\n\n uint8_t expected_values[] = {0x11, 0x0, 0x0, 0x0, 0x11, 0x0, 0x84, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x28};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n\nTEST(MessageTest, SetResponse__dynamic_structure) {\n SetResponseMessage response;\n\n response.set_status(MessageStatus::Closed);\n response.set_sequence_id(1234); \/\/ no effect\n response.set_page_id(4321); \/\/ no effect\n \/\/ response.set_alias_count(11);\n \/\/ response.set_priority(true);\n \/\/ response.set_no_stream(true);\n \/\/ response.set_qos(1); \/\/\n \/\/ response.set_queue_size();\n \/\/ response.set_queue_time();\n \/\/ response.set_base_path();\n \/\/ response.skippable();\n \/\/ response.set_max_permission();\n \/\/ response.set_permission_token();\n \/\/ response.set_target_path(\"\/target\/path\");\n response.set_source_path(\"\/source\/path\"); \/\/ no effect\n\n response.size();\n\n uint8_t buf[1024];\n response.write(buf);\n\n uint8_t expected_values[] = {0x11, 0x0, 0x0, 0x0, 0x11, 0x0, 0x84, 0x0, 0x0,\n 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10};\n\n EXPECT_EQ(0, memcmp(expected_values, buf,\n sizeof(expected_values) \/ sizeof(uint8_t)));\n}\n<|endoftext|>"} {"text":"#include \"dsa\/network.h\"\n#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nTEST(RequesterTest, basic_flow) {\n\n shared_ptr_ app;\n ASSERT_NO_FATAL_FAILURE(app.reset(new App(\"RequesterTest\")));\n\n app->async_start(2);\n\n Server::Config server_config(\"\/test\/path\", 8080);\n Client::Config client_config(\"127.0.0.1\", 8080);\n\n\n ServerPtr tcp_server(app->new_server(Server::TCP, server_config));\n tcp_server->start();\n\n app->sleep(500);\n\n ClientPtr tcp_client(app->new_client(Client::TCP, client_config));\n tcp_client->connect();\n\n \/\/ requester = client->session()->requester();\n\n \/\/ stream = requester.subscribe(\"\/abc\", func);\n \/\/ stream.close();\n\n \/\/ Construct a subscribe message request\n SubscribeRequestMessage subscribe_request;\n subscribe_request.set_qos(StreamQos::_2);\n subscribe_request.set_target_path(\"\/path\/name\");\n\n shared_ptr_ b = make_shared_(256);\n subscribe_request.write(b->data());\n\n app->sleep(2000);\n\n app->graceful_stop(1000);\n\n app->wait();\n}\ncorrect the unittest#include \"dsa\/network.h\"\n#include \"dsa\/message.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace dsa;\n\nTEST(RequesterTest, basic_flow) {\n\n shared_ptr_ app;\n ASSERT_NO_FATAL_FAILURE(app.reset(new App(\"RequesterTest\")));\n\n app->async_start(2);\n\n Server::Config server_config(\"\/test\/path\", 8080);\n Client::Config client_config(\"127.0.0.1\", 8080);\n\n\n ServerPtr tcp_server(app->new_server(Server::TCP, server_config));\n tcp_server->start();\n\n app->sleep(500);\n\n ClientPtr tcp_client(app->new_client(Client::TCP, client_config));\n tcp_client->connect();\n\n \/\/ requester = client->session()->requester();\n\n \/\/ stream = requester.subscribe(\"\/abc\", func);\n \/\/ stream.close();\n\n \/\/ Construct a subscribe message request\n SubscribeRequestMessage subscribe_request;\n subscribe_request.set_qos(StreamQos::_2);\n subscribe_request.set_target_path(\"\/path\/name\");\n\n shared_ptr_ b = make_shared_(256);\n \/\/ subscribe_request.write(b->data());\n\n app->sleep(2000);\n\n app->graceful_stop(1000);\n\n app->wait();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2010-2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"U16InputStream.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nconst char* U16InputStream::DefaultEncoding = \"utf-8\";\n\nnamespace {\n\nstruct Override\n{\n const char* input;\n const char* replacement;\n};\n\n\/\/ cf. HTML Living Standard 13.2.2.2 Character encodings\n\/\/ cf. http:\/\/bugs.icu-project.org\/trac\/browser\/icu\/trunk\/source\/data\/mappings\/convrtrs.txt\nOverride overrides[] = {\n { \"euc-kr\", \"windows-949\" },\n { \"euc-jp\", \"windows-51932\" }, \/\/ ucnv_open() may not understand 'CP51932'.\n { \"gb2312\", \"GBK\" },\n { \"gb_2312-80\", \"GBK\" },\n \/\/ { \"iso-2022-jp\", \"CP50220\" }, \/\/ ucnv_open() may not understand 'CP50220'; iso-2022-jp appears to be the same as CP50220 in ICU.\n { \"iso-8859-1\", \"windows-1252\" },\n { \"iso-8859-9\", \"windows-1254\" },\n { \"iso-8859-11\", \"windows-874\" },\n { \"ks_c_5601-1987\", \"windows-949\" },\n { \"shift_jis\", \"Windows-31j\" },\n { \"tis-620\", \"windows-874\" },\n { \"us-ascii\", \"windows-1252\" }\n};\n\n} \/\/ namespace\n\nU16InputStream::U16InputStream(std::istream& stream, const std::string& optionalEncoding) :\n confidence(Certain),\n encoding(optionalEncoding),\n stream(stream)\n{\n initializeConverter();\n encoding = checkEncoding(encoding);\n if (encoding.empty())\n confidence = Tentative;\n}\n\nU16InputStream::~U16InputStream()\n{\n if (converter)\n ucnv_close(converter);\n}\n\nconst char* U16InputStream::skipSpace(const char* p)\n{\n while (*p) {\n if (strchr(\" \\t\\r\\n\\f\", *p) == 0)\n return p;\n ++p;\n }\n return p;\n};\n\n\nconst char* U16InputStream::skipOver(const char* p, const char* target, size_t length)\n{\n while (*p) {\n if (strncmp(p, target, length) == 0)\n return p + length;\n ++p;\n }\n return p;\n};\n\nvoid U16InputStream::detect(const char* p)\n{\n if (confidence != Tentative)\n return;\n if (strncmp(p, \"\\xfe\\xff\", 2) == 0) {\n encoding = \"utf-16be\";\n confidence = Irrelevant;\n return;\n }\n if (strncmp(p, \"\\xff\\xfe\", 2) == 0) {\n encoding = \"utf-16le\";\n confidence = Irrelevant;\n return;\n }\n if (strncmp(p, \"\\xef\\xbb\\xbf\", 3) == 0) {\n encoding = \"utf-8\";\n confidence = Irrelevant;\n return;\n }\n encoding = \"\";\n}\n\nstd::string U16InputStream::checkEncoding(std::string value)\n{\n \/\/ Remove any leading or trailing space characters\n std::string::iterator i = value.begin();\n while (i < value.end() && strchr(\"\\t\\n\\f\\r \", *i))\n ++i;\n value.erase(value.begin(), i);\n int j;\n for (j = value.length(); 0 < j && strchr(\"\\t\\n\\f\\r \", value[j - 1]); --j)\n ;\n value.erase(j, value.length());\n\n if (value.empty())\n return \"\";\n\n \/\/ Override character encoding\n for (Override* override = overrides;\n override < &overrides[sizeof overrides \/ sizeof overrides[0]];\n ++override) {\n if (!strcasecmp(value.c_str(), override->input)) {\n value = override->replacement;\n break;\n }\n }\n return value;\n}\n\nvoid U16InputStream::setEncoding(std::string value)\n{\n value = checkEncoding(value);\n if (value.empty())\n value = DefaultEncoding;\n\n \/\/ Re-check encoding with ICU for conversion\n UErrorCode error = U_ZERO_ERROR;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter) {\n value = DefaultEncoding;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter)\n eof = true;\n }\n encoding = value;\n}\n\nvoid U16InputStream::initializeConverter()\n{\n flush = false;\n eof = !stream;\n converter = 0;\n source = sourceLimit = sourceBuffer;\n target = targetBuffer;\n nextChar = target;\n lastChar = 0;\n}\n\nvoid U16InputStream::updateSource()\n{\n assert(!flush);\n size_t count = sourceLimit - source;\n if (0 < count && sourceBuffer != source)\n memmove(sourceBuffer, source, count);\n source = sourceBuffer;\n sourceLimit = sourceBuffer + count;\n count = ChunkSize - count;\n if (0 < count) {\n stream.read(sourceLimit, count);\n count = stream.gcount();\n if (!converter) {\n if (encoding.empty()) {\n sourceLimit[count] = '\\0';\n detect(sourceLimit);\n }\n setEncoding(encoding);\n }\n sourceLimit += count;\n if (count == 0)\n flush = true;\n }\n}\n\nvoid U16InputStream::readChunk()\n{\n nextChar = target = targetBuffer;\n updateSource();\n UErrorCode err = U_ZERO_ERROR;\n ucnv_toUnicode(converter,\n reinterpret_cast(&target),\n reinterpret_cast(targetBuffer) + ChunkSize,\n const_cast(&source),\n sourceLimit, 0, flush, &err);\n}\n\nU16InputStream::operator std::u16string()\n{\n std::u16string text;\n char16_t c;\n while (getChar(c))\n text += c;\n return text;\n}(U16InputStream::detect) : Support the utf-16 encodings without BOM; cf. at-charset-029.\/*\n * Copyright 2010-2012 Esrille Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"U16InputStream.h\"\n\n#include \n#include \n\n#include \n\n#include \n\nconst char* U16InputStream::DefaultEncoding = \"utf-8\";\n\nnamespace {\n\nstruct Override\n{\n const char* input;\n const char* replacement;\n};\n\n\/\/ cf. HTML Living Standard 13.2.2.2 Character encodings\n\/\/ cf. http:\/\/bugs.icu-project.org\/trac\/browser\/icu\/trunk\/source\/data\/mappings\/convrtrs.txt\nOverride overrides[] = {\n { \"euc-kr\", \"windows-949\" },\n { \"euc-jp\", \"windows-51932\" }, \/\/ ucnv_open() may not understand 'CP51932'.\n { \"gb2312\", \"GBK\" },\n { \"gb_2312-80\", \"GBK\" },\n \/\/ { \"iso-2022-jp\", \"CP50220\" }, \/\/ ucnv_open() may not understand 'CP50220'; iso-2022-jp appears to be the same as CP50220 in ICU.\n { \"iso-8859-1\", \"windows-1252\" },\n { \"iso-8859-9\", \"windows-1254\" },\n { \"iso-8859-11\", \"windows-874\" },\n { \"ks_c_5601-1987\", \"windows-949\" },\n { \"shift_jis\", \"Windows-31j\" },\n { \"tis-620\", \"windows-874\" },\n { \"us-ascii\", \"windows-1252\" }\n};\n\n} \/\/ namespace\n\nU16InputStream::U16InputStream(std::istream& stream, const std::string& optionalEncoding) :\n confidence(Certain),\n encoding(optionalEncoding),\n stream(stream)\n{\n initializeConverter();\n encoding = checkEncoding(encoding);\n if (encoding.empty())\n confidence = Tentative;\n}\n\nU16InputStream::~U16InputStream()\n{\n if (converter)\n ucnv_close(converter);\n}\n\nconst char* U16InputStream::skipSpace(const char* p)\n{\n while (*p) {\n if (strchr(\" \\t\\r\\n\\f\", *p) == 0)\n return p;\n ++p;\n }\n return p;\n};\n\n\nconst char* U16InputStream::skipOver(const char* p, const char* target, size_t length)\n{\n while (*p) {\n if (strncmp(p, target, length) == 0)\n return p + length;\n ++p;\n }\n return p;\n};\n\nvoid U16InputStream::detect(const char* p)\n{\n static char le[] = { 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74, 0x00 };\n static char be[] = { 0x00, 0x40, 0x00, 0x63, 0x00, 0x68, 0x00, 0x61, 0x00, 0x72, 0x00, 0x73, 0x00, 0x65, 0x00, 0x74 };\n\n if (confidence != Tentative)\n return;\n if (strncmp(p, \"\\xfe\\xff\", 2) == 0 || strncmp(p, be, sizeof(be)) == 0) {\n encoding = \"utf-16be\";\n confidence = Irrelevant;\n return;\n }\n if (strncmp(p, \"\\xff\\xfe\", 2) == 0 || strncmp(p, le, sizeof(le)) == 0) {\n encoding = \"utf-16le\";\n confidence = Irrelevant;\n return;\n }\n if (strncmp(p, \"\\xef\\xbb\\xbf\", 3) == 0) {\n encoding = \"utf-8\";\n confidence = Irrelevant;\n return;\n }\n encoding = \"\";\n}\n\nstd::string U16InputStream::checkEncoding(std::string value)\n{\n \/\/ Remove any leading or trailing space characters\n std::string::iterator i = value.begin();\n while (i < value.end() && strchr(\"\\t\\n\\f\\r \", *i))\n ++i;\n value.erase(value.begin(), i);\n int j;\n for (j = value.length(); 0 < j && strchr(\"\\t\\n\\f\\r \", value[j - 1]); --j)\n ;\n value.erase(j, value.length());\n\n if (value.empty())\n return \"\";\n\n \/\/ Override character encoding\n for (Override* override = overrides;\n override < &overrides[sizeof overrides \/ sizeof overrides[0]];\n ++override) {\n if (!strcasecmp(value.c_str(), override->input)) {\n value = override->replacement;\n break;\n }\n }\n return value;\n}\n\nvoid U16InputStream::setEncoding(std::string value)\n{\n value = checkEncoding(value);\n if (value.empty())\n value = DefaultEncoding;\n\n \/\/ Re-check encoding with ICU for conversion\n UErrorCode error = U_ZERO_ERROR;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter) {\n value = DefaultEncoding;\n converter = ucnv_open(value.c_str(), &error);\n if (!converter)\n eof = true;\n }\n encoding = value;\n}\n\nvoid U16InputStream::initializeConverter()\n{\n flush = false;\n eof = !stream;\n converter = 0;\n source = sourceLimit = sourceBuffer;\n target = targetBuffer;\n nextChar = target;\n lastChar = 0;\n}\n\nvoid U16InputStream::updateSource()\n{\n assert(!flush);\n size_t count = sourceLimit - source;\n if (0 < count && sourceBuffer != source)\n memmove(sourceBuffer, source, count);\n source = sourceBuffer;\n sourceLimit = sourceBuffer + count;\n count = ChunkSize - count;\n if (0 < count) {\n stream.read(sourceLimit, count);\n count = stream.gcount();\n if (!converter) {\n if (encoding.empty()) {\n sourceLimit[count] = '\\0';\n detect(sourceLimit);\n }\n setEncoding(encoding);\n }\n sourceLimit += count;\n if (count == 0)\n flush = true;\n }\n}\n\nvoid U16InputStream::readChunk()\n{\n nextChar = target = targetBuffer;\n updateSource();\n UErrorCode err = U_ZERO_ERROR;\n ucnv_toUnicode(converter,\n reinterpret_cast(&target),\n reinterpret_cast(targetBuffer) + ChunkSize,\n const_cast(&source),\n sourceLimit, 0, flush, &err);\n}\n\nU16InputStream::operator std::u16string()\n{\n std::u16string text;\n char16_t c;\n while (getChar(c))\n text += c;\n return text;\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n#include \"encoder.h\"\n#include \"CreateModule.h\"\n\n\/**\n * @brief Gives a std::string representation of a primitive type\n * \n * @param x Primitive type such as int, double, long\n * @return std::string conversion of param x\n *\/\ntemplate std::string to_string(T x) {\n\treturn static_cast((std::ostringstream() << std::dec << x)).str();\n}\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nint selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\t\n\t\/\/ STUFF WE DONT UNDERSTAND, AND DONT NEED TO\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/ Libraries to load\n\tstd::string bodyLibName = \"bodyinfo\";\n\tstd::string movementLibName = \"movementtools\";\n\t\n\t\/\/ Name of camera module in library\n\tstd::string bodyModuleName = \"BodyInfo\";\n\tstd::string movementModuleName = \"MovementTools\";\n\n\t\/\/ Set broker name, ip and port, finding first available port from 54000\n\tconst std::string brokerName = \"MotionTimingBroker\";\n\tint brokerPort = qi::os::findAvailablePort(54000);\n\tconst std::string brokerIp = \"0.0.0.0\";\n\t\n\t\/\/ Default parent port and ip\n\tint pport = 9559;\n\tstd::string pip = \"127.0.0.1\";\n\t\n\t\/\/ Need this for SOAP serialisation of floats to work\n\tsetlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Create a broker\n\tboost::shared_ptr broker;\n\ttry\n\t{\n\t\tbroker = AL::ALBroker::createBroker(\n\t\t\t\tbrokerName,\n\t\t\t\tbrokerIp,\n\t\t\t\tbrokerPort,\n\t\t\t\tpip,\n\t\t\t\tpport,\n\t\t\t\t0);\n\t}\n\t\/\/ Throw error and quit if a broker could not be created\n\tcatch(...)\n\t{\n\t\tstd::cerr << \"Failed to connect broker to: \"\n\t\t\t << pip\n\t\t\t << \":\"\n\t\t\t << pport\n\t\t\t << std::endl;\n\t\tAL::ALBrokerManager::getInstance()->killAllBroker();\n\t\tAL::ALBrokerManager::kill();\n\n\t\treturn 1;\n\t}\n\n\t\/\/ Add the broker to NAOqi\n\tAL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());\n\tAL::ALBrokerManager::getInstance()->addBroker(broker);\n\n\tCreateModule(movementLibName, movementModuleName, broker, false, true);\n\tCreateModule(bodyLibName, bodyModuleName, broker, false, true);\n\t\n\tAL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);\n\tAL::ALProxy movementToolsProxy(movementModuleName, pip, pport);\n\tAL::ALMotionProxy motion(pip, pport);\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/END OF STUFF WE DONT UNDERSTAND, BREATHE NOW\n\t\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\tint action_forwards = FORWARD;\n\tint action_backwards = BACKWARD;\n\tint chosen_action = &action_forwards;\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(action_forwards,0);\n\tinitiator_queue.enqueueWithPriority(action_backwards,0);\n\t\n\t\/\/create encoder\n\tEncoder encoder();\n\tencoder.calibrate();\n\t\n\t\/\/create the state space\n\tStateSpace space(initiator_queue);\n\tspace.setAngleBins(100);\n\tspace.setVelocityBins(50);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta= M_PI * encoder.GetAngle()\/180;\n\t\tcurrent_state.theta_dot=(current_state.theta - old_state.theta)\/700; \/\/Needs actual time\n\t\tcurrent_state.robot_state=chosen_action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\t(chosen_action)?movementToolsProxy.callVoid(\"swingForwards\"):movementToolsProxy.callVoid(\"swingBackwards\");\n\t}\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nint selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return &(it->first);\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\n\nUpdate Main.cpp#include \n#include \n#include \n#include \n#include \n#include \"StateSpace.h\"\n#include \"PriorityQueue.h\"\n#include \"State.h\"\n#include \"encoder.h\"\n#include \"CreateModule.h\"\n\n\/**\n * @brief Gives a std::string representation of a primitive type\n * \n * @param x Primitive type such as int, double, long\n * @return std::string conversion of param x\n *\/\ntemplate std::string to_string(T x) {\n\treturn static_cast((std::ostringstream() << std::dec << x)).str();\n}\n\n\/\/function to calculate a temperature for the select action function as a function of time\ndouble temperature();\n\n\/\/function to select next action\nint selectAction(PriorityQueue& a_queue);\n\n\/\/function to update a q value\nvoid updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma);\n\nint main()\n{\t\n\t\/\/ STUFF WE DONT UNDERSTAND, AND DONT NEED TO\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/ Libraries to load\n\tstd::string bodyLibName = \"bodyinfo\";\n\tstd::string movementLibName = \"movementtools\";\n\t\n\t\/\/ Name of camera module in library\n\tstd::string bodyModuleName = \"BodyInfo\";\n\tstd::string movementModuleName = \"MovementTools\";\n\n\t\/\/ Set broker name, ip and port, finding first available port from 54000\n\tconst std::string brokerName = \"MotionTimingBroker\";\n\tint brokerPort = qi::os::findAvailablePort(54000);\n\tconst std::string brokerIp = \"0.0.0.0\";\n\t\n\t\/\/ Default parent port and ip\n\tint pport = 9559;\n\tstd::string pip = \"127.0.0.1\";\n\t\n\t\/\/ Need this for SOAP serialisation of floats to work\n\tsetlocale(LC_NUMERIC, \"C\");\n\n\t\/\/ Create a broker\n\tboost::shared_ptr broker;\n\ttry\n\t{\n\t\tbroker = AL::ALBroker::createBroker(\n\t\t\t\tbrokerName,\n\t\t\t\tbrokerIp,\n\t\t\t\tbrokerPort,\n\t\t\t\tpip,\n\t\t\t\tpport,\n\t\t\t\t0);\n\t}\n\t\/\/ Throw error and quit if a broker could not be created\n\tcatch(...)\n\t{\n\t\tstd::cerr << \"Failed to connect broker to: \"\n\t\t\t << pip\n\t\t\t << \":\"\n\t\t\t << pport\n\t\t\t << std::endl;\n\t\tAL::ALBrokerManager::getInstance()->killAllBroker();\n\t\tAL::ALBrokerManager::kill();\n\n\t\treturn 1;\n\t}\n\n\t\/\/ Add the broker to NAOqi\n\tAL::ALBrokerManager::setInstance(broker->fBrokerManager.lock());\n\tAL::ALBrokerManager::getInstance()->addBroker(broker);\n\n\tCreateModule(movementLibName, movementModuleName, broker, false, true);\n\tCreateModule(bodyLibName, bodyModuleName, broker, false, true);\n\t\n\tAL::ALProxy bodyInfoProxy(bodyModuleName, pip, pport);\n\tAL::ALProxy movementToolsProxy(movementModuleName, pip, pport);\n\tAL::ALMotionProxy motion(pip, pport);\n\t\/\/__________________________________________________________________________________________\n\t\/\/__________________________________________________________________________________________\n\t\/\/END OF STUFF WE DONT UNDERSTAND, BREATHE NOW\n\t\n\t\/\/learning factor\n\tconst double alpha=0.5;\n\t\/\/discount factor\n\tconst double gamma=0.5;\n\t\n\t\/\/seed rng\n\tstd::srand(std::time(NULL));\n\t\n\tint action_forwards = FORWARD;\n\tint action_backwards = BACKWARD;\n\tint chosen_action = action_forwards;\n\t\n\t\/\/create a priority queue to copy to all the state space priority queues\n\tPriorityQueue initiator_queue(MAX);\n\tinitiator_queue.enqueueWithPriority(action_forwards,0);\n\tinitiator_queue.enqueueWithPriority(action_backwards,0);\n\t\n\t\/\/create encoder\n\tEncoder encoder();\n\tencoder.calibrate();\n\t\n\t\/\/create the state space\n\tStateSpace space(initiator_queue);\n\tspace.setAngleBins(100);\n\tspace.setVelocityBins(50);\n\t\n\t\/\/state objects\n\tState current_state(0,0,FORWARD);\n\tState old_state(0,0,FORWARD);\n\t\n\twhile(true)\n\t{\n\t\tcurrent_state.theta= M_PI * encoder.GetAngle()\/180;\n\t\tcurrent_state.theta_dot=(current_state.theta - old_state.theta)\/700; \/\/Needs actual time\n\t\tcurrent_state.robot_state=chosen_action;\n\t\t\n\t\tupdateQ(space, chosen_action, old_state, current_state, alpha, gamma);\n\t\t\n\t\told_state=current_state;\n\t\t\n\t\tchosen_action=selectAction(space[current_state]);\n\t\t\n\t\t(chosen_action)?movementToolsProxy.callVoid(\"swingForwards\"):movementToolsProxy.callVoid(\"swingBackwards\");\n\t}\n\t\n\treturn 1;\n}\n\ndouble temperature()\n{\n\treturn std::time(NULL);\n}\n\n\/\/function is fed with a priority queue of action-values \n\/\/generates Boltzmann distribution of these action-values\n\/\/and selects an action based on probabilities \nint selectAction(PriorityQueue& a_queue)\n{\t\n\ttypedef PriorityQueue PQ;\n\ttypedef std::vector< std::pair > Vec_Pair;\n\ttypedef std::pair Pair;\n\t\n\tdouble sum= 0;\n\tint i = 0;\n\t\n\tint size = a_queue.getSize();\n\tVec_Pair action_vec(size);\n\t\n\t\/\/Calculate partition function by iterating over action-values\n\tfor(PQ::const_iterator iter = a_queue.begin(),end=a_queue.end(); iter < end; ++iter)\n\t{\n\t\tsum += std::exp((iter->second)\/temperature());\n\t}\n\t\/\/Calculate boltzmann factors for action-values\n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t it->first = a_queue[i].first;\n\t it->second = std::exp(a_queue[i].second \/temperature()) \/ sum;\n\t ++i;\n\t}\n\t\n\t\/\/calculate cumulative probability distribution \n\tfor(Vec_Pair::iterator it1 = action_vec.begin()++,it2 = action_vec.begin(),end=action_vec.end(); it < end; ++it1,++it2)\n\t{\n\t it1->second += it2->second;\n\t}\n\t\n\t\/\/generate RN between 0 and 1\n\tdouble rand_num = static_cast(rand()\/ (RAND_MAX));\n\t\n\t\/\/select action based on probability \n\tfor(Vec_Pair::iterator it = action_vec.begin(),end=action_vec.end(); it < end; ++it)\n\t{\n\t\t\/\/if RN falls within cumulative probability bin return the corresponding action\n\t\tif(rand_num < it->second)return it->first;\n\t}\n \t\n\treturn NULL; \/\/note that this line should never be reached\n}\n\nvoid updateQ(StateSpace & space, int action, State & new_state, State & old_state, double alpha, double gamma)\n{\n \/\/oldQ value reference\n double oldQ = space[old_state].search(action).second;\n \n \/\/reward given to current state \n double R = new_state.getReward();\n \n \/\/optimal Q value for new state i.e. first element \n double maxQ = space[current_state].peekFront().second;\n \n \/\/new Q value determined by Q learning algorithm\n double newQ = oldQ + alpha * (R + (gamma * maxQ) - oldQ);\n \n \/\/ change priority of action to new Q value\n space[old_state].changePriority(action, newQ);\n}\n\n<|endoftext|>"} {"text":"\/\/* This file is part of Zapdos, an open-source\n\/\/* application for the simulation of plasmas\n\/\/* https:\/\/github.com\/shannon-lab\/zapdos\n\/\/*\n\/\/* Zapdos is powered by the MOOSE Framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"LymberopoulosElectronBC.h\"\n\nregisterMooseObject(\"ZapdosApp\", LymberopoulosElectronBC);\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"ks\", \"The recombination coefficient\");\n params.addRequiredParam(\"gamma\", \"The secondary electron coefficient\");\n params.addRequiredCoupledVar(\"potential\", \"The electric potential\");\n params.addRequiredCoupledVar(\"ion\", \"The ion density.\");\n params.addRequiredParam(\"position_units\", \"Units of position.\");\n params.addClassDescription(\"Simpified kinetic electron boundary condition\"\n \"(Based on DOI: https:\/\/doi.org\/10.1063\/1.352926)\");\n return params;\n}\n\nLymberopoulosElectronBC::LymberopoulosElectronBC(const InputParameters & parameters)\n : IntegratedBC(parameters),\n\n _r_units(1. \/ getParam(\"position_units\")),\n _ks(getParam(\"ks\")),\n _gamma(getParam(\"gamma\")),\n\n \/\/ Coupled Variables\n _grad_potential(coupledGradient(\"potential\")),\n _potential_id(coupled(\"potential\")),\n _Arp(coupledValue(\"ion\")),\n _grad_Arp(coupledGradient(\"ion\")),\n _Arp_id(coupled(\"ion\")),\n\n _muion(getMaterialProperty(\"mu\" + (*getVar(\"ion\", 0)).name())),\n _diffion(getMaterialProperty(\"diff\" + (*getVar(\"ion\", 0)).name())),\n\n _sign(1)\n{\n}\n\nReal\nLymberopoulosElectronBC::computeQpResidual()\n{\n\n RealVectorValue _ion_flux =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _ion_flux = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units *\n (_sign * _ks * std::exp(_u[_qp]) * _normals[_qp] * _normals[_qp] -\n _gamma * _ion_flux * _normals[_qp]);\n}\n\nReal\nLymberopoulosElectronBC::computeQpJacobian()\n{\n\n RealVectorValue _ion_flux =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _ion_flux = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units *\n (_sign * _ks * std::exp(_u[_qp]) * _phi[_j][_qp] * _normals[_qp] * _normals[_qp]);\n}\n\nReal\nLymberopoulosElectronBC::computeQpOffDiagJacobian(unsigned int jvar) \/\/ need to fix\n{\n if (jvar == _potential_id)\n {\n\n RealVectorValue _d_ion_flux_d_V =\n (_muion[_qp] * -_grad_phi[_j][_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _d_ion_flux_d_V = (_muion[_qp] * -_grad_phi[_j][_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units * ((-_gamma * _d_ion_flux_d_V * _normals[_qp]));\n }\n\n else if (jvar == _Arp_id)\n {\n\n RealVectorValue _d_ion_flux_d_ion =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]) * _phi[_j][_qp]);\n\n \/\/ RealVectorValue _d_ion_flux_d_ion = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) * _phi[_j][_qp] -\n \/\/ _diffion[_qp] * (std::exp(_Arp[_qp]) * _grad_phi[_j][_qp] * _r_units +\n \/\/ std::exp(_Arp[_qp]) * _phi[_j][_qp] * _grad_Arp[_qp] * _r_units));\n\n return _test[_i][_qp] * _r_units * ((-_gamma * _d_ion_flux_d_ion * _normals[_qp]));\n }\n\n else\n return 0.0;\n}\nMove comment in LymberopoulosElectronBC to avoid clang format complaint\/\/* This file is part of Zapdos, an open-source\n\/\/* application for the simulation of plasmas\n\/\/* https:\/\/github.com\/shannon-lab\/zapdos\n\/\/*\n\/\/* Zapdos is powered by the MOOSE Framework\n\/\/* https:\/\/www.mooseframework.org\n\/\/*\n\/\/* Licensed under LGPL 2.1, please see LICENSE for details\n\/\/* https:\/\/www.gnu.org\/licenses\/lgpl-2.1.html\n\n#include \"LymberopoulosElectronBC.h\"\n\nregisterMooseObject(\"ZapdosApp\", LymberopoulosElectronBC);\n\ntemplate <>\nInputParameters\nvalidParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"ks\", \"The recombination coefficient\");\n params.addRequiredParam(\"gamma\", \"The secondary electron coefficient\");\n params.addRequiredCoupledVar(\"potential\", \"The electric potential\");\n params.addRequiredCoupledVar(\"ion\", \"The ion density.\");\n params.addRequiredParam(\"position_units\", \"Units of position.\");\n params.addClassDescription(\"Simpified kinetic electron boundary condition\"\n \"(Based on DOI: https:\/\/doi.org\/10.1063\/1.352926)\");\n return params;\n}\n\nLymberopoulosElectronBC::LymberopoulosElectronBC(const InputParameters & parameters)\n : IntegratedBC(parameters),\n\n _r_units(1. \/ getParam(\"position_units\")),\n _ks(getParam(\"ks\")),\n _gamma(getParam(\"gamma\")),\n\n \/\/ Coupled Variables\n _grad_potential(coupledGradient(\"potential\")),\n _potential_id(coupled(\"potential\")),\n _Arp(coupledValue(\"ion\")),\n _grad_Arp(coupledGradient(\"ion\")),\n _Arp_id(coupled(\"ion\")),\n\n _muion(getMaterialProperty(\"mu\" + (*getVar(\"ion\", 0)).name())),\n _diffion(getMaterialProperty(\"diff\" + (*getVar(\"ion\", 0)).name())),\n\n _sign(1)\n{\n}\n\nReal\nLymberopoulosElectronBC::computeQpResidual()\n{\n\n RealVectorValue _ion_flux =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _ion_flux = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units *\n (_sign * _ks * std::exp(_u[_qp]) * _normals[_qp] * _normals[_qp] -\n _gamma * _ion_flux * _normals[_qp]);\n}\n\nReal\nLymberopoulosElectronBC::computeQpJacobian()\n{\n\n RealVectorValue _ion_flux =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _ion_flux = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units *\n (_sign * _ks * std::exp(_u[_qp]) * _phi[_j][_qp] * _normals[_qp] * _normals[_qp]);\n}\n\n\/\/ need to fix\nReal\nLymberopoulosElectronBC::computeQpOffDiagJacobian(unsigned int jvar)\n{\n if (jvar == _potential_id)\n {\n\n RealVectorValue _d_ion_flux_d_V =\n (_muion[_qp] * -_grad_phi[_j][_qp] * _r_units * std::exp(_Arp[_qp]));\n\n \/\/ RealVectorValue _d_ion_flux_d_V = (_muion[_qp] * -_grad_phi[_j][_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) -\n \/\/ _diffion[_qp] * std::exp(_Arp[_qp]) * _grad_Arp[_qp] * _r_units);\n\n return _test[_i][_qp] * _r_units * ((-_gamma * _d_ion_flux_d_V * _normals[_qp]));\n }\n\n else if (jvar == _Arp_id)\n {\n\n RealVectorValue _d_ion_flux_d_ion =\n (_muion[_qp] * -_grad_potential[_qp] * _r_units * std::exp(_Arp[_qp]) * _phi[_j][_qp]);\n\n \/\/ RealVectorValue _d_ion_flux_d_ion = (_muion[_qp] * -_grad_potential[_qp] * _r_units *\n \/\/ std::exp(_Arp[_qp]) * _phi[_j][_qp] -\n \/\/ _diffion[_qp] * (std::exp(_Arp[_qp]) * _grad_phi[_j][_qp] * _r_units +\n \/\/ std::exp(_Arp[_qp]) * _phi[_j][_qp] * _grad_Arp[_qp] * _r_units));\n\n return _test[_i][_qp] * _r_units * ((-_gamma * _d_ion_flux_d_ion * _normals[_qp]));\n }\n\n else\n return 0.0;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nconst char* greet(void) {\n return \"Hello, PyBoost\";\n}\n\nclass World {\n std::string message_;\n\n World(const World&) = delete;\n World& operator=(const World&) = delete;\npublic:\n World(void) = default;\n ~World(void) = default;\n\n World(const char* msg)\n : message_(msg) {\n }\n\n void set_msg(const std::string& message) {\n message_ = message;\n }\n\n std::string get_msg(void) const {\n return message_;\n }\n};\n\nclass WorldWrapper : public World {\n PyObject* self_{};\npublic:\n WorldWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n WorldWrapper(PyObject* self, const char* msg)\n : World(msg)\n , self_(self) {\n boost::python::xincref(self_);\n }\n\n ~WorldWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nstruct Var {\n std::string name;\n float value{};\n\n Var(const char* n = \"\")\n : name(n) {\n }\n};\n\nclass VarWrapper : public Var {\n PyObject* self_{};\npublic:\n VarWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n VarWrapper(PyObject* self, const char* name)\n : Var(name)\n , self_(self) {\n }\n\n ~VarWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nclass Num {\n float value_{};\n\n Num(const Num&) = delete;\n Num& operator=(const Num&) = delete;\npublic:\n Num(void) = default;\n ~Num(void) = default;\n\n void set(float value) {\n value_ = value;\n }\n\n float get(void) const {\n return value_;\n }\n};\n\nclass NumWrapper : public Num {\n PyObject* self_{};\npublic:\n NumWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n ~NumWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nstruct Base {\n virtual ~Base(void) {}\n virtual std::string get_name(void) const {\n return \"Base\";\n }\n};\n\nstruct Derived : public Base {\n virtual std::string get_name(void) const override {\n return \"Derived\";\n }\n};\n\nstatic void print_base(Base* b) {\n std::cout << \"Base name: \" << b->get_name() << std::endl;\n}\n\nstatic void print_derived(Derived* d) {\n std::cout << \"Derived name: \" << d->get_name() << std::endl;\n}\n\nBase* base_factory(void) {\n return new Derived();\n}\n\nstruct VirtualBase {\n virtual ~VirtualBase(void) {}\n virtual int get_value(void) const {\n return 0;\n }\n};\n\nstruct VirtualBaseWrap\n : public VirtualBase, public boost::python::wrapper {\n virtual int get_value(void) const override {\n if (boost::python::override f = get_override(\"get_value\"))\n return f();\n return VirtualBase::get_value();\n }\n\n int default_get_value(void) const {\n return VirtualBase::get_value();\n }\n};\n\nBOOST_PYTHON_MODULE(pyboost) {\n boost::python::def(\"greet\", greet);\n\n boost::python::class_, boost::noncopyable>(\"World\")\n .def(boost::python::init())\n .def(\"set_msg\", &World::set_msg)\n .def(\"get_msg\", &World::get_msg);\n\n boost::python::class_, boost::noncopyable>(\"Var\")\n .def(boost::python::init())\n .def_readonly(\"name\", &Var::name)\n .def_readwrite(\"value\", &Var::value);\n\n boost::python::class_, boost::noncopyable>(\"Num\")\n .add_property(\"rvalue\", &Num::get)\n .add_property(\"value\", &Num::get, &Num::set);\n\n boost::python::class_(\"Base\")\n .def(\"get_name\", &Base::get_name);\n boost::python::class_>(\"Derived\")\n .def(\"get_name\", &Derived::get_name);\n boost::python::def(\"print_base\", print_base);\n boost::python::def(\"print_derived\", print_derived);\n boost::python::def(\"base_factory\", base_factory,\n boost::python::return_value_policy());\n\n boost::python::class_(\"VirtualBase\")\n .def(\"get_value\",\n &VirtualBase::get_value, &VirtualBaseWrap::default_get_value);\n}\n:construction: chore(pyboost): add unit base demo for pyboost\/\/ Copyright (c) 2018 ASMlover. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nconst char* greet(void) {\n return \"Hello, PyBoost\";\n}\n\nstruct UnitBase {\n std::string basename;\n\n UnitBase(void) {\n }\n\n UnitBase(const char* name)\n : basename(name) {\n }\n\n virtual ~UnitBase(void) {\n }\n\n std::string get_name(void) const {\n return basename;\n }\n};\n\nclass World {\n std::string message_;\n\n World(const World&) = delete;\n World& operator=(const World&) = delete;\npublic:\n World(void) = default;\n ~World(void) = default;\n\n World(const char* msg)\n : message_(msg) {\n }\n\n void set_msg(const std::string& message) {\n message_ = message;\n }\n\n std::string get_msg(void) const {\n return message_;\n }\n};\n\nclass WorldWrapper : public World {\n PyObject* self_{};\npublic:\n WorldWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n WorldWrapper(PyObject* self, const char* msg)\n : World(msg)\n , self_(self) {\n boost::python::xincref(self_);\n }\n\n ~WorldWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nstruct Var {\n std::string name;\n float value{};\n\n Var(const char* n = \"\")\n : name(n) {\n }\n};\n\nclass VarWrapper : public Var {\n PyObject* self_{};\npublic:\n VarWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n VarWrapper(PyObject* self, const char* name)\n : Var(name)\n , self_(self) {\n }\n\n ~VarWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nclass Num {\n float value_{};\n\n Num(const Num&) = delete;\n Num& operator=(const Num&) = delete;\npublic:\n Num(void) = default;\n ~Num(void) = default;\n\n void set(float value) {\n value_ = value;\n }\n\n float get(void) const {\n return value_;\n }\n};\n\nclass NumWrapper : public Num {\n PyObject* self_{};\npublic:\n NumWrapper(PyObject* self)\n : self_(self) {\n boost::python::xincref(self_);\n }\n\n ~NumWrapper(void) {\n boost::python::xdecref(self_);\n }\n};\n\nstruct Base {\n virtual ~Base(void) {}\n virtual std::string get_name(void) const {\n return \"Base\";\n }\n};\n\nstruct Derived : public Base {\n virtual std::string get_name(void) const override {\n return \"Derived\";\n }\n};\n\nstatic void print_base(Base* b) {\n std::cout << \"Base name: \" << b->get_name() << std::endl;\n}\n\nstatic void print_derived(Derived* d) {\n std::cout << \"Derived name: \" << d->get_name() << std::endl;\n}\n\nBase* base_factory(void) {\n return new Derived();\n}\n\nstruct VirtualBase {\n virtual ~VirtualBase(void) {}\n virtual int get_value(void) const {\n return 0;\n }\n};\n\nstruct VirtualBaseWrap\n : public VirtualBase, public boost::python::wrapper {\n virtual int get_value(void) const override {\n if (boost::python::override f = get_override(\"get_value\"))\n return f();\n return VirtualBase::get_value();\n }\n\n int default_get_value(void) const {\n return VirtualBase::get_value();\n }\n};\n\nBOOST_PYTHON_MODULE(pyboost) {\n boost::python::def(\"greet\", greet);\n\n boost::python::class_(\"UnitBase\")\n .def(boost::python::init())\n .def_readwrite(\"basename\", &UnitBase::basename)\n .def(\"get_name\", &UnitBase::get_name);\n\n boost::python::class_, boost::noncopyable>(\"World\")\n .def(boost::python::init())\n .def(\"set_msg\", &World::set_msg)\n .def(\"get_msg\", &World::get_msg);\n\n boost::python::class_, boost::noncopyable>(\"Var\")\n .def(boost::python::init())\n .def_readonly(\"name\", &Var::name)\n .def_readwrite(\"value\", &Var::value);\n\n boost::python::class_, boost::noncopyable>(\"Num\")\n .add_property(\"rvalue\", &Num::get)\n .add_property(\"value\", &Num::get, &Num::set);\n\n boost::python::class_(\"Base\")\n .def(\"get_name\", &Base::get_name);\n boost::python::class_>(\"Derived\")\n .def(\"get_name\", &Derived::get_name);\n boost::python::def(\"print_base\", print_base);\n boost::python::def(\"print_derived\", print_derived);\n boost::python::def(\"base_factory\", base_factory,\n boost::python::return_value_policy());\n\n boost::python::class_(\"VirtualBase\")\n .def(\"get_value\",\n &VirtualBase::get_value, &VirtualBaseWrap::default_get_value);\n}\n<|endoftext|>"} {"text":"#include \"catch2\/catch.hpp\"\n#include \"ApprovalTests.hpp\"\n\n#include \"GildedRose.h\"\n\nTEST_CASE(\"Foo\") {\n\n vector items;\n items.push_back(Item(\"foo\", 0, 0));\n GildedRose app(items);\n app.updateQuality();\n REQUIRE(\"fixme\" == app.items[0].name);\n\n}\nstarting position should include item printer#include \n#include \"ApprovalTests.hpp\"\n\n#include \"GildedRose.h\"\n\nstd::ostream& operator<<(std::ostream& os, const Item& obj)\n{\n return os\n << \"name: \" << obj.name\n << \", sellIn: \" << obj.sellIn\n << \", quality: \" << obj.quality;\n}\n\nTEST_CASE(\"UpdateQuality\") {\n\n vector items;\n items.push_back(Item(\"foo\", 0, 0));\n GildedRose app(items);\n app.updateQuality();\n REQUIRE(\"foo\" == app.items[0].name);\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\/\n\/* editor_plugin_settings.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"editor_plugin_settings.h\"\n\n#include \"core\/io\/config_file.h\"\n#include \"core\/os\/file_access.h\"\n#include \"core\/os\/main_loop.h\"\n#include \"core\/project_settings.h\"\n#include \"editor_node.h\"\n#include \"editor_scale.h\"\n#include \"scene\/gui\/margin_container.h\"\n\nvoid EditorPluginSettings::_notification(int p_what) {\n\n\tif (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {\n\t\tupdate_plugins();\n\t} else if (p_what == Node::NOTIFICATION_READY) {\n\t\tplugin_config_dialog->connect(\"plugin_ready\", EditorNode::get_singleton(), \"_on_plugin_ready\");\n\t\tplugin_list->connect(\"button_pressed\", this, \"_cell_button_pressed\");\n\t}\n}\n\nvoid EditorPluginSettings::update_plugins() {\n\n\tplugin_list->clear();\n\n\tDirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);\n\tError err = da->change_dir(\"res:\/\/addons\");\n\tif (err != OK) {\n\t\tmemdelete(da);\n\t\treturn;\n\t}\n\n\tupdating = true;\n\n\tTreeItem *root = plugin_list->create_item();\n\n\tda->list_dir_begin();\n\n\tString d = da->get_next();\n\n\tVector plugins;\n\n\twhile (d != String()) {\n\n\t\tbool dir = da->current_is_dir();\n\t\tString path = \"res:\/\/addons\/\" + d + \"\/plugin.cfg\";\n\n\t\tif (dir && FileAccess::exists(path)) {\n\n\t\t\tplugins.push_back(d);\n\t\t}\n\n\t\td = da->get_next();\n\t}\n\n\tda->list_dir_end();\n\tmemdelete(da);\n\n\tplugins.sort();\n\n\tfor (int i = 0; i < plugins.size(); i++) {\n\n\t\tRef cf;\n\t\tcf.instance();\n\t\tString path = \"res:\/\/addons\/\" + plugins[i] + \"\/plugin.cfg\";\n\n\t\tError err2 = cf->load(path);\n\n\t\tif (err2 != OK) {\n\t\t\tWARN_PRINTS(\"Can't load plugin config: \" + path);\n\t\t} else {\n\t\t\tbool key_missing = false;\n\n\t\t\tif (!cf->has_section_key(\"plugin\", \"name\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/name\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"author\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/author\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"version\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/version\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"description\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/description\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"script\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/script\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\n\t\t\tif (!key_missing) {\n\t\t\t\tString d2 = plugins[i];\n\t\t\t\tString name = cf->get_value(\"plugin\", \"name\");\n\t\t\t\tString author = cf->get_value(\"plugin\", \"author\");\n\t\t\t\tString version = cf->get_value(\"plugin\", \"version\");\n\t\t\t\tString description = cf->get_value(\"plugin\", \"description\");\n\t\t\t\tString script = cf->get_value(\"plugin\", \"script\");\n\n\t\t\t\tTreeItem *item = plugin_list->create_item(root);\n\t\t\t\titem->set_text(0, name);\n\t\t\t\titem->set_tooltip(0, TTR(\"Name:\") + \" \" + name + \"\\n\" + TTR(\"Path:\") + \" \" + path + \"\\n\" + TTR(\"Main Script:\") + \" \" + script + \"\\n\" + TTR(\"Description:\") + \" \" + description);\n\t\t\t\titem->set_metadata(0, d2);\n\t\t\t\titem->set_text(1, version);\n\t\t\t\titem->set_metadata(1, script);\n\t\t\t\titem->set_text(2, author);\n\t\t\t\titem->set_metadata(2, description);\n\t\t\t\titem->set_cell_mode(3, TreeItem::CELL_MODE_RANGE);\n\t\t\t\titem->set_range_config(3, 0, 1, 1);\n\t\t\t\titem->set_text(3, \"Inactive,Active\");\n\t\t\t\titem->set_editable(3, true);\n\t\t\t\titem->add_button(4, get_icon(\"Edit\", \"EditorIcons\"), BUTTON_PLUGIN_EDIT, false, TTR(\"Edit Plugin\"));\n\n\t\t\t\tif (EditorNode::get_singleton()->is_addon_plugin_enabled(d2)) {\n\t\t\t\t\titem->set_custom_color(3, get_color(\"success_color\", \"Editor\"));\n\t\t\t\t\titem->set_range(3, 1);\n\t\t\t\t} else {\n\t\t\t\t\titem->set_custom_color(3, get_color(\"disabled_font_color\", \"Editor\"));\n\t\t\t\t\titem->set_range(3, 0);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tupdating = false;\n}\n\nvoid EditorPluginSettings::_plugin_activity_changed() {\n\n\tif (updating)\n\t\treturn;\n\n\tTreeItem *ti = plugin_list->get_edited();\n\tERR_FAIL_COND(!ti);\n\tbool active = ti->get_range(3);\n\tString name = ti->get_metadata(0);\n\n\tEditorNode::get_singleton()->set_addon_plugin_enabled(name, active, true);\n\n\tbool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);\n\n\tif (is_active != active) {\n\t\tupdating = true;\n\t\tti->set_range(3, is_active ? 1 : 0);\n\t\tupdating = false;\n\t}\n\n\tif (is_active)\n\t\tti->set_custom_color(3, get_color(\"success_color\", \"Editor\"));\n\telse\n\t\tti->set_custom_color(3, get_color(\"disabled_font_color\", \"Editor\"));\n}\n\nvoid EditorPluginSettings::_create_clicked() {\n\tplugin_config_dialog->config(\"\");\n\tplugin_config_dialog->popup_centered();\n}\n\nvoid EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, int p_id) {\n\tTreeItem *item = Object::cast_to(p_item);\n\tif (!item)\n\t\treturn;\n\tif (p_id == BUTTON_PLUGIN_EDIT) {\n\t\tif (p_column == 4) {\n\t\t\tString dir = item->get_metadata(0);\n\t\t\tplugin_config_dialog->config(\"res:\/\/addons\/\" + dir + \"\/plugin.cfg\");\n\t\t\tplugin_config_dialog->popup_centered();\n\t\t}\n\t}\n}\n\nvoid EditorPluginSettings::_bind_methods() {\n\n\tClassDB::bind_method(\"update_plugins\", &EditorPluginSettings::update_plugins);\n\tClassDB::bind_method(\"_create_clicked\", &EditorPluginSettings::_create_clicked);\n\tClassDB::bind_method(\"_plugin_activity_changed\", &EditorPluginSettings::_plugin_activity_changed);\n\tClassDB::bind_method(\"_cell_button_pressed\", &EditorPluginSettings::_cell_button_pressed);\n}\n\nEditorPluginSettings::EditorPluginSettings() {\n\n\tplugin_config_dialog = memnew(PluginConfigDialog);\n\tplugin_config_dialog->config(\"\");\n\tadd_child(plugin_config_dialog);\n\n\tHBoxContainer *title_hb = memnew(HBoxContainer);\n\ttitle_hb->add_child(memnew(Label(TTR(\"Installed Plugins:\"))));\n\ttitle_hb->add_spacer();\n\tcreate_plugin = memnew(Button(TTR(\"Create\")));\n\tcreate_plugin->connect(\"pressed\", this, \"_create_clicked\");\n\ttitle_hb->add_child(create_plugin);\n\tupdate_list = memnew(Button(TTR(\"Update\")));\n\tupdate_list->connect(\"pressed\", this, \"update_plugins\");\n\ttitle_hb->add_child(update_list);\n\tadd_child(title_hb);\n\n\tplugin_list = memnew(Tree);\n\tplugin_list->set_v_size_flags(SIZE_EXPAND_FILL);\n\tplugin_list->set_columns(5);\n\tplugin_list->set_column_titles_visible(true);\n\tplugin_list->set_column_title(0, TTR(\"Name:\"));\n\tplugin_list->set_column_title(1, TTR(\"Version:\"));\n\tplugin_list->set_column_title(2, TTR(\"Author:\"));\n\tplugin_list->set_column_title(3, TTR(\"Status:\"));\n\tplugin_list->set_column_title(4, TTR(\"Edit:\"));\n\tplugin_list->set_column_expand(0, true);\n\tplugin_list->set_column_expand(1, false);\n\tplugin_list->set_column_expand(2, false);\n\tplugin_list->set_column_expand(3, false);\n\tplugin_list->set_column_expand(4, false);\n\tplugin_list->set_column_min_width(1, 100 * EDSCALE);\n\tplugin_list->set_column_min_width(2, 250 * EDSCALE);\n\tplugin_list->set_column_min_width(3, 80 * EDSCALE);\n\tplugin_list->set_column_min_width(4, 40 * EDSCALE);\n\tplugin_list->set_hide_root(true);\n\tplugin_list->connect(\"item_edited\", this, \"_plugin_activity_changed\");\n\n\tVBoxContainer *mc = memnew(VBoxContainer);\n\tmc->add_child(plugin_list);\n\tmc->set_v_size_flags(SIZE_EXPAND_FILL);\n\tmc->set_h_size_flags(SIZE_EXPAND_FILL);\n\n\tadd_child(mc);\n\n\tupdating = false;\n}\nUse checkbox for plugin status instead of option list\/*************************************************************************\/\n\/* editor_plugin_settings.cpp *\/\n\/*************************************************************************\/\n\/* This file is part of: *\/\n\/* GODOT ENGINE *\/\n\/* https:\/\/godotengine.org *\/\n\/*************************************************************************\/\n\/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. *\/\n\/* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). *\/\n\/* *\/\n\/* Permission is hereby granted, free of charge, to any person obtaining *\/\n\/* a copy of this software and associated documentation files (the *\/\n\/* \"Software\"), to deal in the Software without restriction, including *\/\n\/* without limitation the rights to use, copy, modify, merge, publish, *\/\n\/* distribute, sublicense, and\/or sell copies of the Software, and to *\/\n\/* permit persons to whom the Software is furnished to do so, subject to *\/\n\/* the following conditions: *\/\n\/* *\/\n\/* The above copyright notice and this permission notice shall be *\/\n\/* included in all copies or substantial portions of the Software. *\/\n\/* *\/\n\/* THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, *\/\n\/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF *\/\n\/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*\/\n\/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY *\/\n\/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, *\/\n\/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE *\/\n\/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\/\n\/*************************************************************************\/\n\n#include \"editor_plugin_settings.h\"\n\n#include \"core\/io\/config_file.h\"\n#include \"core\/os\/file_access.h\"\n#include \"core\/os\/main_loop.h\"\n#include \"core\/project_settings.h\"\n#include \"editor_node.h\"\n#include \"editor_scale.h\"\n#include \"scene\/gui\/margin_container.h\"\n\nvoid EditorPluginSettings::_notification(int p_what) {\n\n\tif (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {\n\t\tupdate_plugins();\n\t} else if (p_what == Node::NOTIFICATION_READY) {\n\t\tplugin_config_dialog->connect(\"plugin_ready\", EditorNode::get_singleton(), \"_on_plugin_ready\");\n\t\tplugin_list->connect(\"button_pressed\", this, \"_cell_button_pressed\");\n\t}\n}\n\nvoid EditorPluginSettings::update_plugins() {\n\n\tplugin_list->clear();\n\n\tDirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);\n\tError err = da->change_dir(\"res:\/\/addons\");\n\tif (err != OK) {\n\t\tmemdelete(da);\n\t\treturn;\n\t}\n\n\tupdating = true;\n\n\tTreeItem *root = plugin_list->create_item();\n\n\tda->list_dir_begin();\n\n\tString d = da->get_next();\n\n\tVector plugins;\n\n\twhile (d != String()) {\n\n\t\tbool dir = da->current_is_dir();\n\t\tString path = \"res:\/\/addons\/\" + d + \"\/plugin.cfg\";\n\n\t\tif (dir && FileAccess::exists(path)) {\n\n\t\t\tplugins.push_back(d);\n\t\t}\n\n\t\td = da->get_next();\n\t}\n\n\tda->list_dir_end();\n\tmemdelete(da);\n\n\tplugins.sort();\n\n\tfor (int i = 0; i < plugins.size(); i++) {\n\n\t\tRef cf;\n\t\tcf.instance();\n\t\tString path = \"res:\/\/addons\/\" + plugins[i] + \"\/plugin.cfg\";\n\n\t\tError err2 = cf->load(path);\n\n\t\tif (err2 != OK) {\n\t\t\tWARN_PRINTS(\"Can't load plugin config: \" + path);\n\t\t} else {\n\t\t\tbool key_missing = false;\n\n\t\t\tif (!cf->has_section_key(\"plugin\", \"name\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/name\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"author\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/author\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"version\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/version\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"description\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/description\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\t\t\tif (!cf->has_section_key(\"plugin\", \"script\")) {\n\t\t\t\tWARN_PRINTS(\"Plugin config misses \\\"plugin\/script\\\" key: \" + path);\n\t\t\t\tkey_missing = true;\n\t\t\t}\n\n\t\t\tif (!key_missing) {\n\t\t\t\tString d2 = plugins[i];\n\t\t\t\tString name = cf->get_value(\"plugin\", \"name\");\n\t\t\t\tString author = cf->get_value(\"plugin\", \"author\");\n\t\t\t\tString version = cf->get_value(\"plugin\", \"version\");\n\t\t\t\tString description = cf->get_value(\"plugin\", \"description\");\n\t\t\t\tString script = cf->get_value(\"plugin\", \"script\");\n\n\t\t\t\tTreeItem *item = plugin_list->create_item(root);\n\t\t\t\titem->set_text(0, name);\n\t\t\t\titem->set_tooltip(0, TTR(\"Name:\") + \" \" + name + \"\\n\" + TTR(\"Path:\") + \" \" + path + \"\\n\" + TTR(\"Main Script:\") + \" \" + script + \"\\n\" + TTR(\"Description:\") + \" \" + description);\n\t\t\t\titem->set_metadata(0, d2);\n\t\t\t\titem->set_text(1, version);\n\t\t\t\titem->set_metadata(1, script);\n\t\t\t\titem->set_text(2, author);\n\t\t\t\titem->set_metadata(2, description);\n\t\t\t\titem->set_cell_mode(3, TreeItem::CELL_MODE_CHECK);\n\t\t\t\titem->set_text(3, TTR(\"Enable\"));\n\t\t\t\tbool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(d2);\n\t\t\t\titem->set_checked(3, is_active);\n\t\t\t\titem->set_editable(3, true);\n\t\t\t\titem->add_button(4, get_icon(\"Edit\", \"EditorIcons\"), BUTTON_PLUGIN_EDIT, false, TTR(\"Edit Plugin\"));\n\t\t\t}\n\t\t}\n\t}\n\n\tupdating = false;\n}\n\nvoid EditorPluginSettings::_plugin_activity_changed() {\n\n\tif (updating)\n\t\treturn;\n\n\tTreeItem *ti = plugin_list->get_edited();\n\tERR_FAIL_COND(!ti);\n\tbool active = ti->is_checked(3);\n\tString name = ti->get_metadata(0);\n\n\tEditorNode::get_singleton()->set_addon_plugin_enabled(name, active, true);\n\n\tbool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);\n\n\tif (is_active != active) {\n\t\tupdating = true;\n\t\tti->set_checked(3, is_active);\n\t\tupdating = false;\n\t}\n}\n\nvoid EditorPluginSettings::_create_clicked() {\n\tplugin_config_dialog->config(\"\");\n\tplugin_config_dialog->popup_centered();\n}\n\nvoid EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, int p_id) {\n\tTreeItem *item = Object::cast_to(p_item);\n\tif (!item)\n\t\treturn;\n\tif (p_id == BUTTON_PLUGIN_EDIT) {\n\t\tif (p_column == 4) {\n\t\t\tString dir = item->get_metadata(0);\n\t\t\tplugin_config_dialog->config(\"res:\/\/addons\/\" + dir + \"\/plugin.cfg\");\n\t\t\tplugin_config_dialog->popup_centered();\n\t\t}\n\t}\n}\n\nvoid EditorPluginSettings::_bind_methods() {\n\n\tClassDB::bind_method(\"update_plugins\", &EditorPluginSettings::update_plugins);\n\tClassDB::bind_method(\"_create_clicked\", &EditorPluginSettings::_create_clicked);\n\tClassDB::bind_method(\"_plugin_activity_changed\", &EditorPluginSettings::_plugin_activity_changed);\n\tClassDB::bind_method(\"_cell_button_pressed\", &EditorPluginSettings::_cell_button_pressed);\n}\n\nEditorPluginSettings::EditorPluginSettings() {\n\n\tplugin_config_dialog = memnew(PluginConfigDialog);\n\tplugin_config_dialog->config(\"\");\n\tadd_child(plugin_config_dialog);\n\n\tHBoxContainer *title_hb = memnew(HBoxContainer);\n\ttitle_hb->add_child(memnew(Label(TTR(\"Installed Plugins:\"))));\n\ttitle_hb->add_spacer();\n\tcreate_plugin = memnew(Button(TTR(\"Create\")));\n\tcreate_plugin->connect(\"pressed\", this, \"_create_clicked\");\n\ttitle_hb->add_child(create_plugin);\n\tupdate_list = memnew(Button(TTR(\"Update\")));\n\tupdate_list->connect(\"pressed\", this, \"update_plugins\");\n\ttitle_hb->add_child(update_list);\n\tadd_child(title_hb);\n\n\tplugin_list = memnew(Tree);\n\tplugin_list->set_v_size_flags(SIZE_EXPAND_FILL);\n\tplugin_list->set_columns(5);\n\tplugin_list->set_column_titles_visible(true);\n\tplugin_list->set_column_title(0, TTR(\"Name:\"));\n\tplugin_list->set_column_title(1, TTR(\"Version:\"));\n\tplugin_list->set_column_title(2, TTR(\"Author:\"));\n\tplugin_list->set_column_title(3, TTR(\"Status:\"));\n\tplugin_list->set_column_title(4, TTR(\"Edit:\"));\n\tplugin_list->set_column_expand(0, true);\n\tplugin_list->set_column_expand(1, false);\n\tplugin_list->set_column_expand(2, false);\n\tplugin_list->set_column_expand(3, false);\n\tplugin_list->set_column_expand(4, false);\n\tplugin_list->set_column_min_width(1, 100 * EDSCALE);\n\tplugin_list->set_column_min_width(2, 250 * EDSCALE);\n\tplugin_list->set_column_min_width(3, 80 * EDSCALE);\n\tplugin_list->set_column_min_width(4, 40 * EDSCALE);\n\tplugin_list->set_hide_root(true);\n\tplugin_list->connect(\"item_edited\", this, \"_plugin_activity_changed\");\n\n\tVBoxContainer *mc = memnew(VBoxContainer);\n\tmc->add_child(plugin_list);\n\tmc->set_v_size_flags(SIZE_EXPAND_FILL);\n\tmc->set_h_size_flags(SIZE_EXPAND_FILL);\n\n\tadd_child(mc);\n\n\tupdating = false;\n}\n<|endoftext|>"} {"text":"\/* TrainingData.cpp\n *\n * Kubo Ryosuke\n *\/\n\n#include \"learn\/training_data\/TrainingData.hpp\"\n#include \"core\/record\/Record.hpp\"\n#include \"core\/record\/CsaReader.hpp\"\n#include \"common\/file_system\/Directory.hpp\"\n#include \n\nnamespace sunfish {\n\nbool TrainingDataGenerator::writeToFile(const char* path) const {\n std::ofstream file(path, std::ios::out | std::ios::binary);\n if (!file) {\n LOG(error) << \"could not open a file: \" << path;\n return false;\n }\n\n for (auto ite = trainingData_.begin(); ite != trainingData_.end(); ite++) {\n char sfenSize = static_cast(ite->sfen.size());\n file.write(&sfenSize, sizeof(sfenSize));\n file.write(ite->sfen.c_str(), ite->sfen.size());\n uint16_t move = ite->move.serialize16();\n file.write(reinterpret_cast(&move), sizeof(move));\n }\n file.close();\n\n return true;\n}\n\nbool TrainingDataGenerator::loadCsaFiles(const char* dir) {\n Directory directory(dir);\n auto files = directory.files(\"*.csa\");\n\n if (files.size() == 0) {\n LOG(error) << \".csa files not found\";\n return false;\n }\n\n for (auto ite = files.begin(); ite != files.end(); ite++) {\n std::ifstream file(*ite);\n if (!file) {\n LOG(error) << \"could not open a file: \" << *ite;\n continue;\n }\n Record record;\n CsaReader::read(file, record);\n file.close();\n\n Position pos = record.initialPosition;\n for (const auto& move : record.moveList) {\n auto sfen = pos.toStringSFEN();\n trainingData_.push_back({ std::move(sfen), move });\n\n Piece captured;\n if (!pos.doMove(move, captured)) {\n LOG(error) << \"an illegal move is detected: \" << move.toString(pos) << \"\\n\"\n << pos.toString();\n break;\n }\n }\n }\n\n return true;\n}\n\nvoid TrainingDataGenerator::shuffle(Random& random) {\n random.shuffle(trainingData_.begin(), trainingData_.end());\n}\n\nTrainingDataReader::~TrainingDataReader() {\n file_.close();\n}\n\nbool TrainingDataReader::open(const char* path) {\n file_.open(path, std::ios::in | std::ios::binary);\n return file_.operator bool();\n}\n\n\nbool TrainingDataReader::read(TrainingDataElement& elem) {\n char sfenSize;\n file_.read(&sfenSize, sizeof(sfenSize));\n if (file_.eof()) {\n return false;\n }\n\n char sfen[sfenSize+1];\n memset(sfen, 0, sizeof(sfen));\n file_.read(sfen, sfenSize);\n\n uint16_t move;\n file_.read(reinterpret_cast(&move), sizeof(move));\n\n elem.sfen = sfen;\n elem.move = Move::deserialize(move);\n\n return true;\n}\n\n} \/\/ namespace sunfish\nFix TrainingDataReader\/* TrainingData.cpp\n *\n * Kubo Ryosuke\n *\/\n\n#include \"learn\/training_data\/TrainingData.hpp\"\n#include \"core\/record\/Record.hpp\"\n#include \"core\/record\/CsaReader.hpp\"\n#include \"common\/file_system\/Directory.hpp\"\n#include \n\nnamespace sunfish {\n\nbool TrainingDataGenerator::writeToFile(const char* path) const {\n std::ofstream file(path, std::ios::out | std::ios::binary);\n if (!file) {\n LOG(error) << \"could not open a file: \" << path;\n return false;\n }\n\n for (auto ite = trainingData_.begin(); ite != trainingData_.end(); ite++) {\n char sfenSize = static_cast(ite->sfen.size());\n file.write(&sfenSize, sizeof(sfenSize));\n file.write(ite->sfen.c_str(), ite->sfen.size());\n uint16_t move = ite->move.serialize16();\n file.write(reinterpret_cast(&move), sizeof(move));\n }\n file.close();\n\n return true;\n}\n\nbool TrainingDataGenerator::loadCsaFiles(const char* dir) {\n Directory directory(dir);\n auto files = directory.files(\"*.csa\");\n\n if (files.size() == 0) {\n LOG(error) << \".csa files not found\";\n return false;\n }\n\n for (auto ite = files.begin(); ite != files.end(); ite++) {\n std::ifstream file(*ite);\n if (!file) {\n LOG(error) << \"could not open a file: \" << *ite;\n continue;\n }\n Record record;\n CsaReader::read(file, record);\n file.close();\n\n Position pos = record.initialPosition;\n for (const auto& move : record.moveList) {\n auto sfen = pos.toStringSFEN();\n trainingData_.push_back({ std::move(sfen), move });\n\n Piece captured;\n if (!pos.doMove(move, captured)) {\n LOG(error) << \"an illegal move is detected: \" << move.toString(pos) << \"\\n\"\n << pos.toString();\n break;\n }\n }\n }\n\n return true;\n}\n\nvoid TrainingDataGenerator::shuffle(Random& random) {\n random.shuffle(trainingData_.begin(), trainingData_.end());\n}\n\nTrainingDataReader::~TrainingDataReader() {\n if (file_.is_open()) {\n file_.close();\n }\n}\n\nbool TrainingDataReader::open(const char* path) {\n file_.open(path, std::ios::in | std::ios::binary);\n return !file_.fail();\n}\n\n\nbool TrainingDataReader::read(TrainingDataElement& elem) {\n char sfenSize;\n file_.read(&sfenSize, sizeof(sfenSize));\n if (file_.eof()) {\n return false;\n }\n\n char sfen[sfenSize+1];\n memset(sfen, 0, sizeof(sfen));\n file_.read(sfen, sfenSize);\n\n uint16_t move;\n file_.read(reinterpret_cast(&move), sizeof(move));\n\n elem.sfen = sfen;\n elem.move = Move::deserialize(move);\n\n return true;\n}\n\n} \/\/ namespace sunfish\n<|endoftext|>"} {"text":"\n\/\/@HEADER\n\/\/ ************************************************************************\n\/\/ \n\/\/ HPCG: Simple Conjugate Gradient Benchmark Code\n\/\/ Questions? Contact Michael A. Heroux (maherou@sandia.gov) \n\/\/ \n\/\/ ************************************************************************\n\/\/@HEADER\n\n#ifndef SPARSEMATRIX_HPP\n#define SPARSEMATRIX_HPP\n\n#include \n#include \n#include \"Geometry.hpp\"\n#ifdef DETAILEDDEBUG\n#include \n#endif\n\nstruct SparseMatrix_STRUCT {\n char *title;\n global_int_t totalNumberOfRows;\n global_int_t totalNumberOfNonzeros;\n local_int_t localNumberOfRows;\n local_int_t localNumberOfColumns; \/\/ Must be defined in make_local_matrix\n global_int_t localNumberOfNonzeros; \/\/Make this a globlal since it can get big\n char * nonzerosInRow; \/\/ The number of nonzeros in a row will always be 27 or fewer\n global_int_t ** mtxIndG;\n local_int_t ** mtxIndL;\n double ** matrixValues;\n double ** matrixDiagonal;\n std::map< global_int_t, local_int_t > globalToLocalMap;\n std::vector< global_int_t > localToGlobalMap;\n\n#ifndef HPCG_NOMPI\n local_int_t numberOfExternalValues;\n int numberOfSendNeighbors;\n local_int_t totalToBeSent;\n local_int_t *elementsToSend;\n int *neighbors;\n local_int_t *receiveLength;\n local_int_t *sendLength;\n double *sendBuffer;\n#endif\n};\ntypedef struct SparseMatrix_STRUCT SparseMatrix;\n\ninline void initializeMatrix(SparseMatrix & A) {\n\tA.title = 0;\n\tA.totalNumberOfRows = 0;\n\tA.totalNumberOfNonzeros = 0;\n\tA.localNumberOfRows = 0;\n\tA.localNumberOfColumns = 0;\n\tA.localNumberOfNonzeros = 0;\n\tA.nonzerosInRow = 0;\n\tA.mtxIndG = 0;\n\tA.mtxIndL = 0;\n\tA.matrixValues = 0;\n\tA.matrixDiagonal = 0;\n\n\t#ifndef HPCG_NOMPI\n\tA.numberOfExternalValues = 0;\n\tA.numberOfSendNeighbors = 0;\n\tA.totalToBeSent = 0;\n\tA.elementsToSend = 0;\n\tA.neighbors = 0;\n\tA.receiveLength = 0;\n\tA.sendLength = 0;\n\tA.sendBuffer = 0;\n\t#endif\n\treturn;\n}\n\ninline void destroyMatrix(SparseMatrix & A) {\n\n\tfor (int i = 0; i< A.localNumberOfRows; ++i) {\n\t\tdelete [] A.matrixValues[i];\n\t\tdelete [] A.mtxIndG[i];\n\t\tdelete [] A.mtxIndL[i];\n\t}\n\tif(A.title) delete [] A.title;\n\tif(A.nonzerosInRow) delete [] A.nonzerosInRow;\n\tif(A.mtxIndG) delete [] A.mtxIndG;\n\tif(A.mtxIndL) delete [] A.mtxIndL;\n\tif(A.matrixValues) delete [] A.matrixValues;\n\tif(A.matrixDiagonal) delete [] A.matrixDiagonal;\n\t\n#ifndef HPCG_NOMPI\n\tif(A.elementsToSend) delete [] A.elementsToSend;\n\tif(A.neighbors) delete [] A.neighbors;\n\tif(A.receiveLength) delete [] A.receiveLength;\n\tif(A.sendLength) delete [] A.sendLength;\n\tif(A.sendBuffer) delete [] A.sendBuffer;\n#endif\n\tinitializeMatrix(A);\n\treturn;\n}\n\ninline int getRankOfMatrixRow(const Geometry & geom, const SparseMatrix & A, global_int_t index) {\n\t\/\/ For the global row id given in the argument index, return the MPI process rank that is assigned that row\n\tint gnx = geom.nx*geom.npx;\n\tint gny = geom.ny*geom.npy;\n\n\tint iz = index\/(gny*gnx);\n\tint iy = (index-iz*gny*gnx)\/gnx;\n\tint ix = index%gnx;\n\tint ipz = iz\/geom.nz;\n\tint ipy = iy\/geom.ny;\n\tint ipx = ix\/geom.nx;\n\tint rank = ipx+ipy*geom.npx+ipz*geom.npy*geom.npx;\n#ifdef DETAILEDDEBUG\n\t\/\/std::cout << \"In getRank, rank = \" << geom.rank << \" index, gnx, gny, ipz, ipy, ipx, rank = \" << index << \" \" << gnx << \" \" << \" \" << gny << \" \" << ipz << \" \" << ipy << \" \" << ipx << \" \" << rank << std::endl;\n#endif\n\treturn(rank);\n\n}\n\n#endif \/\/ SPARSEMATRIX_HPP\n\nAdded a member to store optimization data.\n\/\/@HEADER\n\/\/ ************************************************************************\n\/\/ \n\/\/ HPCG: Simple Conjugate Gradient Benchmark Code\n\/\/ Questions? Contact Michael A. Heroux (maherou@sandia.gov) \n\/\/ \n\/\/ ************************************************************************\n\/\/@HEADER\n\n#ifndef SPARSEMATRIX_HPP\n#define SPARSEMATRIX_HPP\n\n#include \n#include \n#include \"Geometry.hpp\"\n#ifdef DETAILEDDEBUG\n#include \n#endif\n\nstruct SparseMatrix_STRUCT {\n char *title;\n global_int_t totalNumberOfRows;\n global_int_t totalNumberOfNonzeros;\n local_int_t localNumberOfRows;\n local_int_t localNumberOfColumns; \/\/ Must be defined in make_local_matrix\n global_int_t localNumberOfNonzeros; \/\/Make this a globlal since it can get big\n char * nonzerosInRow; \/\/ The number of nonzeros in a row will always be 27 or fewer\n global_int_t ** mtxIndG;\n local_int_t ** mtxIndL;\n double ** matrixValues;\n double ** matrixDiagonal;\n std::map< global_int_t, local_int_t > globalToLocalMap;\n std::vector< global_int_t > localToGlobalMap;\n\n \/*\n This is for storing optimized data structres created in OptimizeProblem and\n used inside optimized spmv().\n *\/\n void *optimization_data;\n\n#ifndef HPCG_NOMPI\n local_int_t numberOfExternalValues;\n int numberOfSendNeighbors;\n local_int_t totalToBeSent;\n local_int_t *elementsToSend;\n int *neighbors;\n local_int_t *receiveLength;\n local_int_t *sendLength;\n double *sendBuffer;\n#endif\n};\ntypedef struct SparseMatrix_STRUCT SparseMatrix;\n\ninline void initializeMatrix(SparseMatrix & A) {\n\tA.title = 0;\n\tA.totalNumberOfRows = 0;\n\tA.totalNumberOfNonzeros = 0;\n\tA.localNumberOfRows = 0;\n\tA.localNumberOfColumns = 0;\n\tA.localNumberOfNonzeros = 0;\n\tA.nonzerosInRow = 0;\n\tA.mtxIndG = 0;\n\tA.mtxIndL = 0;\n\tA.matrixValues = 0;\n\tA.matrixDiagonal = 0;\n\n\t#ifndef HPCG_NOMPI\n\tA.numberOfExternalValues = 0;\n\tA.numberOfSendNeighbors = 0;\n\tA.totalToBeSent = 0;\n\tA.elementsToSend = 0;\n\tA.neighbors = 0;\n\tA.receiveLength = 0;\n\tA.sendLength = 0;\n\tA.sendBuffer = 0;\n\t#endif\n\treturn;\n}\n\ninline void destroyMatrix(SparseMatrix & A) {\n\n\tfor (int i = 0; i< A.localNumberOfRows; ++i) {\n\t\tdelete [] A.matrixValues[i];\n\t\tdelete [] A.mtxIndG[i];\n\t\tdelete [] A.mtxIndL[i];\n\t}\n\tif(A.title) delete [] A.title;\n\tif(A.nonzerosInRow) delete [] A.nonzerosInRow;\n\tif(A.mtxIndG) delete [] A.mtxIndG;\n\tif(A.mtxIndL) delete [] A.mtxIndL;\n\tif(A.matrixValues) delete [] A.matrixValues;\n\tif(A.matrixDiagonal) delete [] A.matrixDiagonal;\n\t\n#ifndef HPCG_NOMPI\n\tif(A.elementsToSend) delete [] A.elementsToSend;\n\tif(A.neighbors) delete [] A.neighbors;\n\tif(A.receiveLength) delete [] A.receiveLength;\n\tif(A.sendLength) delete [] A.sendLength;\n\tif(A.sendBuffer) delete [] A.sendBuffer;\n#endif\n\tinitializeMatrix(A);\n\treturn;\n}\n\ninline int getRankOfMatrixRow(const Geometry & geom, const SparseMatrix & A, global_int_t index) {\n\t\/\/ For the global row id given in the argument index, return the MPI process rank that is assigned that row\n\tint gnx = geom.nx*geom.npx;\n\tint gny = geom.ny*geom.npy;\n\n\tint iz = index\/(gny*gnx);\n\tint iy = (index-iz*gny*gnx)\/gnx;\n\tint ix = index%gnx;\n\tint ipz = iz\/geom.nz;\n\tint ipy = iy\/geom.ny;\n\tint ipx = ix\/geom.nx;\n\tint rank = ipx+ipy*geom.npx+ipz*geom.npy*geom.npx;\n#ifdef DETAILEDDEBUG\n\t\/\/std::cout << \"In getRank, rank = \" << geom.rank << \" index, gnx, gny, ipz, ipy, ipx, rank = \" << index << \" \" << gnx << \" \" << \" \" << gny << \" \" << ipz << \" \" << ipy << \" \" << ipx << \" \" << rank << std::endl;\n#endif\n\treturn(rank);\n\n}\n\n#endif \/\/ SPARSEMATRIX_HPP\n\n<|endoftext|>"} {"text":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetCachedFunctionTest\n\n#include \"JPetCachedFunction\/JPetCachedFunction.h\"\n#include \"JPetLoggerInclude.h\"\n#include \n\nusing namespace jpet_common_tools;\n\/\/\/ Returns Time-over-threshold for given deposited energy\n\/\/\/ the current parametrization is par1 + par2 * eDep\n\/\/\/ Returned value in ps, and eDep is given in keV.\ndouble getToT1(double eDep, double par1 = -91958., double par2 = 19341.)\n{\n if (eDep < 0. ) return 0.;\n double value = par1 + eDep * par2;\n return value;\n}\n\nBOOST_AUTO_TEST_SUITE(JPetCachedFunctionTestSuite)\n\nBOOST_AUTO_TEST_CASE(getTot_params)\n{\n JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n JPetCachedFunction1D func(params, Range(100, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_EQUAL(func.getParams().fParams.size(), 2);\n BOOST_CHECK_EQUAL(func.getParams().fParams[0], -91958.);\n BOOST_CHECK_EQUAL(func.getParams().fParams[1], 19341.);\n BOOST_CHECK_EQUAL(func.getValues().size(), 100);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 100);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n auto vals = func.getValues();\n}\n\nBOOST_AUTO_TEST_CASE(getTot_standardFunc)\n{\n JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n JPetCachedFunction1D func(params, Range( 10000, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0.), getToT1(0.), 0.1);\n BOOST_CHECK_CLOSE(func(1.), getToT1(1.), 0.1);\n BOOST_CHECK_CLOSE(func(10.), getToT1(10.), 0.1);\n BOOST_CHECK_CLOSE(func(59.5), getToT1(59.5), 0.1);\n BOOST_CHECK_CLOSE(func(99.9), getToT1(99.9), 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(getTot_quadratic)\n{\n JPetCachedFunctionParams params(\"pol2\", {1., 1., 1.}); \/\/\/ 1 + x + x^2\n JPetCachedFunction1D func(params, Range(10000, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0), 1., 0.1);\n BOOST_CHECK_CLOSE(func(1), 3., 0.1);\n BOOST_CHECK_CLOSE(func(2), 7., 0.1);\n BOOST_CHECK_CLOSE(func(3), 13., 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(cached_2D)\n{\n JPetCachedFunctionParams params(\"[0] + [1] * x + [2] * y\", {1., 1., 2.}); \/\/\/ 1 + x + 2 * y\n JPetCachedFunction2D func(params, Range(100, 0., 100.), Range(100, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0., 0.), 1., 0.1);\n BOOST_CHECK_CLOSE(func(1, 1.), 4., 0.1);\n BOOST_CHECK_CLOSE(func(0., 1.), 3., 0.1);\n BOOST_CHECK_CLOSE(func(1., 0.), 2., 0.1);\n BOOST_CHECK_EQUAL(func.getRange().first.fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().first.fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().first.fMax, 100, 0.1);\n BOOST_CHECK_EQUAL(func.getRange().second.fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().second.fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().second.fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(cached_log)\n{\n JPetCachedFunctionParams params(\"[0] + [1] * TMath::Log(x)\", {1., -2.}); \/\/\/ 1 + -2 * log(x)\n JPetCachedFunction1D func(params, Range(10000, 2., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(2.), -0.386294, 0.1);\n BOOST_CHECK_CLOSE(func(3.), -1.19696, 0.1);\n BOOST_CHECK_CLOSE(func(99.), -8.19005, 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 2, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\nBOOST_AUTO_TEST_SUITE_END()\nRemove repated line in tests#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE JPetCachedFunctionTest\n\n#include \"JPetCachedFunction\/JPetCachedFunction.h\"\n#include \"JPetLoggerInclude.h\"\n#include \n\nusing namespace jpet_common_tools;\n\/\/\/ Returns Time-over-threshold for given deposited energy\n\/\/\/ the current parametrization is par1 + par2 * eDep\n\/\/\/ Returned value in ps, and eDep is given in keV.\ndouble getToT1(double eDep, double par1 = -91958., double par2 = 19341.)\n{\n if (eDep < 0. ) return 0.;\n double value = par1 + eDep * par2;\n return value;\n}\n\nBOOST_AUTO_TEST_SUITE(JPetCachedFunctionTestSuite)\n\nBOOST_AUTO_TEST_CASE(getTot_params)\n{\n JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n JPetCachedFunction1D func(params, Range(100, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_EQUAL(func.getParams().fParams.size(), 2);\n BOOST_CHECK_EQUAL(func.getParams().fParams[0], -91958.);\n BOOST_CHECK_EQUAL(func.getParams().fParams[1], 19341.);\n BOOST_CHECK_EQUAL(func.getValues().size(), 100);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n auto vals = func.getValues();\n}\n\nBOOST_AUTO_TEST_CASE(getTot_standardFunc)\n{\n JPetCachedFunctionParams params(\"pol1\", { -91958., 19341.});\n JPetCachedFunction1D func(params, Range( 10000, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0.), getToT1(0.), 0.1);\n BOOST_CHECK_CLOSE(func(1.), getToT1(1.), 0.1);\n BOOST_CHECK_CLOSE(func(10.), getToT1(10.), 0.1);\n BOOST_CHECK_CLOSE(func(59.5), getToT1(59.5), 0.1);\n BOOST_CHECK_CLOSE(func(99.9), getToT1(99.9), 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(getTot_quadratic)\n{\n JPetCachedFunctionParams params(\"pol2\", {1., 1., 1.}); \/\/\/ 1 + x + x^2\n JPetCachedFunction1D func(params, Range(10000, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0), 1., 0.1);\n BOOST_CHECK_CLOSE(func(1), 3., 0.1);\n BOOST_CHECK_CLOSE(func(2), 7., 0.1);\n BOOST_CHECK_CLOSE(func(3), 13., 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(cached_2D)\n{\n JPetCachedFunctionParams params(\"[0] + [1] * x + [2] * y\", {1., 1., 2.}); \/\/\/ 1 + x + 2 * y\n JPetCachedFunction2D func(params, Range(100, 0., 100.), Range(100, 0., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(0., 0.), 1., 0.1);\n BOOST_CHECK_CLOSE(func(1, 1.), 4., 0.1);\n BOOST_CHECK_CLOSE(func(0., 1.), 3., 0.1);\n BOOST_CHECK_CLOSE(func(1., 0.), 2., 0.1);\n BOOST_CHECK_EQUAL(func.getRange().first.fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().first.fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().first.fMax, 100, 0.1);\n BOOST_CHECK_EQUAL(func.getRange().second.fBins, 100);\n BOOST_CHECK_CLOSE(func.getRange().second.fMin, 0, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().second.fMax, 100, 0.1);\n}\n\nBOOST_AUTO_TEST_CASE(cached_log)\n{\n JPetCachedFunctionParams params(\"[0] + [1] * TMath::Log(x)\", {1., -2.}); \/\/\/ 1 + -2 * log(x)\n JPetCachedFunction1D func(params, Range(10000, 2., 100.));\n BOOST_CHECK(func.getParams().fValidFunction);\n BOOST_CHECK_CLOSE(func(2.), -0.386294, 0.1);\n BOOST_CHECK_CLOSE(func(3.), -1.19696, 0.1);\n BOOST_CHECK_CLOSE(func(99.), -8.19005, 0.1);\n BOOST_CHECK_EQUAL(func.getRange().fBins, 10000);\n BOOST_CHECK_CLOSE(func.getRange().fMin, 2, 0.1);\n BOOST_CHECK_CLOSE(func.getRange().fMax, 100, 0.1);\n}\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/===- SymbolTable.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Symbol table is a bag of all known symbols. We put all symbols of\n\/\/ all input files to the symbol table. The symbol table is basically\n\/\/ a hash table with the logic to resolve symbol name conflicts using\n\/\/ the symbol types.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SymbolTable.h\"\n#include \"Config.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Support\/StringSaver.h\"\n\nusing namespace llvm;\nusing namespace llvm::object;\nusing namespace llvm::ELF;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ All input object files must be for the same architecture\n\/\/ (e.g. it does not make sense to link x86 object files with\n\/\/ MIPS object files.) This function checks for that error.\ntemplate static bool isCompatible(InputFile *FileP) {\n auto *F = dyn_cast>(FileP);\n if (!F)\n return true;\n if (F->getELFKind() == Config->EKind && F->getEMachine() == Config->EMachine)\n return true;\n StringRef A = F->getName();\n StringRef B = Config->Emulation;\n if (B.empty())\n B = Config->FirstElf->getName();\n error(A + \" is incompatible with \" + B);\n return false;\n}\n\n\/\/ Returns \"(internal)\", \"foo.a(bar.o)\" or \"baz.o\".\nstatic std::string getFilename(InputFile *F) {\n if (!F)\n return \"(internal)\";\n if (!F->ArchiveName.empty())\n return (F->ArchiveName + \"(\" + F->getName() + \")\").str();\n return F->getName();\n}\n\n\/\/ Add symbols in File to the symbol table.\ntemplate \nvoid SymbolTable::addFile(std::unique_ptr File) {\n InputFile *FileP = File.get();\n if (!isCompatible(FileP))\n return;\n\n \/\/ .a file\n if (auto *F = dyn_cast(FileP)) {\n ArchiveFiles.emplace_back(cast(File.release()));\n F->parse();\n for (Lazy &Sym : F->getLazySymbols())\n addLazy(&Sym);\n return;\n }\n\n \/\/ Lazy object file\n if (auto *F = dyn_cast(FileP)) {\n LazyObjectFiles.emplace_back(cast(File.release()));\n F->parse();\n for (Lazy &Sym : F->getLazySymbols())\n addLazy(&Sym);\n return;\n }\n\n if (Config->Trace)\n llvm::outs() << getFilename(FileP) << \"\\n\";\n\n \/\/ .so file\n if (auto *F = dyn_cast>(FileP)) {\n \/\/ DSOs are uniquified not by filename but by soname.\n F->parseSoName();\n if (!SoNames.insert(F->getSoName()).second)\n return;\n\n SharedFiles.emplace_back(cast>(File.release()));\n F->parseRest();\n for (SharedSymbol &B : F->getSharedSymbols())\n resolve(&B);\n return;\n }\n\n \/\/ LLVM bitcode file\n if (auto *F = dyn_cast(FileP)) {\n BitcodeFiles.emplace_back(cast(File.release()));\n F->parse(ComdatGroups);\n for (SymbolBody *B : F->getSymbols())\n if (B)\n resolve(B);\n return;\n }\n\n \/\/ Regular object file\n auto *F = cast>(FileP);\n ObjectFiles.emplace_back(cast>(File.release()));\n F->parse(ComdatGroups);\n for (SymbolBody *B : F->getNonLocalSymbols())\n resolve(B);\n}\n\ntemplate void SymbolTable::addCombinedLtoObject() {\n if (BitcodeFiles.empty())\n return;\n\n \/\/ Compile bitcode files.\n Lto.reset(new BitcodeCompiler);\n for (const std::unique_ptr &F : BitcodeFiles)\n Lto->add(*F);\n std::vector> IFs = Lto->compile();\n\n \/\/ Replace bitcode symbols.\n for (auto &IF : IFs) {\n ObjectFile *Obj = cast>(IF.release());\n\n llvm::DenseSet DummyGroups;\n Obj->parse(DummyGroups);\n for (SymbolBody *Body : Obj->getNonLocalSymbols()) {\n Symbol *Sym = insert(Body);\n if (!Sym->Body->isUndefined() && Body->isUndefined())\n continue;\n Sym->Body = Body;\n }\n ObjectFiles.emplace_back(Obj);\n }\n}\n\n\/\/ Add an undefined symbol.\ntemplate \nSymbolBody *SymbolTable::addUndefined(StringRef Name) {\n auto *Sym = new (Alloc)\n UndefinedElf(Name, STB_GLOBAL, STV_DEFAULT, \/*Type*\/ 0, false);\n resolve(Sym);\n return Sym;\n}\n\n\/\/ Add an undefined symbol. Unlike addUndefined, that symbol\n\/\/ doesn't have to be resolved, thus \"opt\" (optional).\ntemplate \nSymbolBody *SymbolTable::addUndefinedOpt(StringRef Name) {\n auto *Sym = new (Alloc)\n UndefinedElf(Name, STB_GLOBAL, STV_HIDDEN, \/*Type*\/ 0, true);\n resolve(Sym);\n return Sym;\n}\n\ntemplate \nDefinedRegular *SymbolTable::addAbsolute(StringRef Name,\n uint8_t Visibility) {\n \/\/ Pass nullptr because absolute symbols have no corresponding input sections.\n auto *Sym = new (Alloc) DefinedRegular(Name, STB_GLOBAL, Visibility);\n resolve(Sym);\n return Sym;\n}\n\ntemplate \nSymbolBody *SymbolTable::addSynthetic(StringRef Name,\n OutputSectionBase &Sec,\n uintX_t Val) {\n auto *Sym = new (Alloc) DefinedSynthetic(Name, Val, Sec);\n resolve(Sym);\n return Sym;\n}\n\n\/\/ Add Name as an \"ignored\" symbol. An ignored symbol is a regular\n\/\/ linker-synthesized defined symbol, but is only defined if needed.\ntemplate \nDefinedRegular *SymbolTable::addIgnored(StringRef Name,\n uint8_t Visibility) {\n if (!find(Name))\n return nullptr;\n return addAbsolute(Name, Visibility);\n}\n\n\/\/ Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.\n\/\/ Used to implement --wrap.\ntemplate void SymbolTable::wrap(StringRef Name) {\n if (Symtab.count(Name) == 0)\n return;\n StringSaver Saver(Alloc);\n Symbol *Sym = addUndefined(Name)->Backref;\n Symbol *Real = addUndefined(Saver.save(\"__real_\" + Name))->Backref;\n Symbol *Wrap = addUndefined(Saver.save(\"__wrap_\" + Name))->Backref;\n Real->Body = Sym->Body;\n Sym->Body = Wrap->Body;\n}\n\n\/\/ Returns a file from which symbol B was created.\n\/\/ If B does not belong to any file, returns a nullptr.\ntemplate InputFile *SymbolTable::findFile(SymbolBody *B) {\n for (const std::unique_ptr> &F : ObjectFiles) {\n ArrayRef Syms = F->getSymbols();\n if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())\n return F.get();\n }\n for (const std::unique_ptr &F : BitcodeFiles) {\n ArrayRef Syms = F->getSymbols();\n if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())\n return F.get();\n }\n return nullptr;\n}\n\n\/\/ Construct a string in the form of \"Sym in File1 and File2\".\n\/\/ Used to construct an error message.\ntemplate \nstd::string SymbolTable::conflictMsg(SymbolBody *Old, SymbolBody *New) {\n InputFile *F1 = findFile(Old);\n InputFile *F2 = findFile(New);\n StringRef Sym = Old->getName();\n return demangle(Sym) + \" in \" + getFilename(F1) + \" and \" + getFilename(F2);\n}\n\n\/\/ This function resolves conflicts if there's an existing symbol with\n\/\/ the same name. Decisions are made based on symbol type.\ntemplate void SymbolTable::resolve(SymbolBody *New) {\n Symbol *Sym = insert(New);\n if (Sym->Body == New)\n return;\n\n SymbolBody *Existing = Sym->Body;\n\n if (auto *L = dyn_cast(Existing)) {\n if (New->isUndefined()) {\n addMemberFile(New, L);\n return;\n }\n \/\/ Found a definition for something also in an archive.\n \/\/ Ignore the archive definition.\n Sym->Body = New;\n return;\n }\n\n if (New->isTls() != Existing->isTls()) {\n error(\"TLS attribute mismatch for symbol: \" + conflictMsg(Existing, New));\n return;\n }\n\n \/\/ compare() returns -1, 0, or 1 if the lhs symbol is less preferable,\n \/\/ equivalent (conflicting), or more preferable, respectively.\n int Comp = Existing->compare(New);\n if (Comp == 0) {\n std::string S = \"duplicate symbol: \" + conflictMsg(Existing, New);\n if (Config->AllowMultipleDefinition)\n warning(S);\n else\n error(S);\n return;\n }\n if (Comp < 0)\n Sym->Body = New;\n}\n\nstatic uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {\n if (VA == STV_DEFAULT)\n return VB;\n if (VB == STV_DEFAULT)\n return VA;\n return std::min(VA, VB);\n}\n\nstatic bool shouldExport(SymbolBody *B) {\n if (Config->Shared || Config->ExportDynamic) {\n \/\/ Export most symbols except for those that do not need to be exported.\n return !B->CanOmitFromDynSym;\n }\n \/\/ Make sure we preempt DSO symbols with default visibility.\n return B->isShared() && B->getVisibility() == STV_DEFAULT;\n}\n\n\/\/ Find an existing symbol or create and insert a new one.\ntemplate Symbol *SymbolTable::insert(SymbolBody *New) {\n StringRef Name = New->getName();\n unsigned NumSyms = SymVector.size();\n auto P = Symtab.insert(std::make_pair(Name, NumSyms));\n Symbol *Sym;\n if (P.second) {\n Sym = new (Alloc) Symbol;\n Sym->Body = New;\n Sym->Visibility = STV_DEFAULT;\n Sym->IsUsedInRegularObj = false;\n Sym->ExportDynamic = false;\n Sym->VersionScriptGlobal = !Config->VersionScript;\n SymVector.push_back(Sym);\n } else {\n Sym = SymVector[P.first->second];\n }\n New->Backref = Sym;\n\n \/\/ Merge in the new symbol's visibility. DSO symbols do not affect visibility\n \/\/ in the output.\n if (!New->isShared())\n Sym->Visibility = getMinVisibility(Sym->Visibility, New->getVisibility());\n Sym->ExportDynamic = Sym->ExportDynamic || shouldExport(New);\n SymbolBody::Kind K = New->kind();\n if (K == SymbolBody::DefinedRegularKind ||\n K == SymbolBody::DefinedCommonKind ||\n K == SymbolBody::DefinedSyntheticKind ||\n K == SymbolBody::UndefinedElfKind)\n Sym->IsUsedInRegularObj = true;\n return Sym;\n}\n\ntemplate SymbolBody *SymbolTable::find(StringRef Name) {\n auto It = Symtab.find(Name);\n if (It == Symtab.end())\n return nullptr;\n return SymVector[It->second]->Body;\n}\n\ntemplate void SymbolTable::addLazy(Lazy *L) {\n Symbol *Sym = insert(L);\n SymbolBody *Cur = Sym->Body;\n if (Cur == L)\n return;\n if (Cur->isUndefined()) {\n Sym->Body = L;\n addMemberFile(Cur, L);\n }\n}\n\ntemplate \nvoid SymbolTable::addMemberFile(SymbolBody *Undef, Lazy *L) {\n \/\/ Weak undefined symbols should not fetch members from archives.\n \/\/ If we were to keep old symbol we would not know that an archive member was\n \/\/ available if a strong undefined symbol shows up afterwards in the link.\n \/\/ If a strong undefined symbol never shows up, this lazy symbol will\n \/\/ get to the end of the link and must be treated as the weak undefined one.\n \/\/ We already marked this symbol as used when we added it to the symbol table,\n \/\/ but we also need to preserve its binding and type.\n if (Undef->isWeak()) {\n \/\/ FIXME: Consider moving these members to Symbol.\n L->Binding = Undef->Binding;\n L->Type = Undef->Type;\n return;\n }\n\n \/\/ Fetch a member file that has the definition for L.\n \/\/ getMember returns nullptr if the member was already read from the library.\n if (std::unique_ptr File = L->getFile())\n addFile(std::move(File));\n}\n\n\/\/ This function takes care of the case in which shared libraries depend on\n\/\/ the user program (not the other way, which is usual). Shared libraries\n\/\/ may have undefined symbols, expecting that the user program provides\n\/\/ the definitions for them. An example is BSD's __progname symbol.\n\/\/ We need to put such symbols to the main program's .dynsym so that\n\/\/ shared libraries can find them.\n\/\/ Except this, we ignore undefined symbols in DSOs.\ntemplate void SymbolTable::scanShlibUndefined() {\n for (std::unique_ptr> &File : SharedFiles)\n for (StringRef U : File->getUndefinedSymbols())\n if (SymbolBody *Sym = find(U))\n if (Sym->isDefined())\n Sym->Backref->ExportDynamic = true;\n}\n\n\/\/ This function process the dynamic list option by marking all the symbols\n\/\/ to be exported in the dynamic table.\ntemplate void SymbolTable::scanDynamicList() {\n for (StringRef S : Config->DynamicList)\n if (SymbolBody *B = find(S))\n B->Backref->ExportDynamic = true;\n}\n\n\/\/ This function processes the --version-script option by marking all global\n\/\/ symbols with the VersionScriptGlobal flag, which acts as a filter on the\n\/\/ dynamic symbol table.\ntemplate void SymbolTable::scanVersionScript() {\n for (StringRef S : Config->VersionScriptGlobals)\n if (SymbolBody *B = find(S))\n B->Backref->VersionScriptGlobal = true;\n}\n\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\nAdd comments.\/\/===- SymbolTable.cpp ----------------------------------------------------===\/\/\n\/\/\n\/\/ The LLVM Linker\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ Symbol table is a bag of all known symbols. We put all symbols of\n\/\/ all input files to the symbol table. The symbol table is basically\n\/\/ a hash table with the logic to resolve symbol name conflicts using\n\/\/ the symbol types.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"SymbolTable.h\"\n#include \"Config.h\"\n#include \"Error.h\"\n#include \"Symbols.h\"\n#include \"llvm\/Bitcode\/ReaderWriter.h\"\n#include \"llvm\/Support\/StringSaver.h\"\n\nusing namespace llvm;\nusing namespace llvm::object;\nusing namespace llvm::ELF;\n\nusing namespace lld;\nusing namespace lld::elf;\n\n\/\/ All input object files must be for the same architecture\n\/\/ (e.g. it does not make sense to link x86 object files with\n\/\/ MIPS object files.) This function checks for that error.\ntemplate static bool isCompatible(InputFile *FileP) {\n auto *F = dyn_cast>(FileP);\n if (!F)\n return true;\n if (F->getELFKind() == Config->EKind && F->getEMachine() == Config->EMachine)\n return true;\n StringRef A = F->getName();\n StringRef B = Config->Emulation;\n if (B.empty())\n B = Config->FirstElf->getName();\n error(A + \" is incompatible with \" + B);\n return false;\n}\n\n\/\/ Returns \"(internal)\", \"foo.a(bar.o)\" or \"baz.o\".\nstatic std::string getFilename(InputFile *F) {\n if (!F)\n return \"(internal)\";\n if (!F->ArchiveName.empty())\n return (F->ArchiveName + \"(\" + F->getName() + \")\").str();\n return F->getName();\n}\n\n\/\/ Add symbols in File to the symbol table.\ntemplate \nvoid SymbolTable::addFile(std::unique_ptr File) {\n InputFile *FileP = File.get();\n if (!isCompatible(FileP))\n return;\n\n \/\/ .a file\n if (auto *F = dyn_cast(FileP)) {\n ArchiveFiles.emplace_back(cast(File.release()));\n F->parse();\n for (Lazy &Sym : F->getLazySymbols())\n addLazy(&Sym);\n return;\n }\n\n \/\/ Lazy object file\n if (auto *F = dyn_cast(FileP)) {\n LazyObjectFiles.emplace_back(cast(File.release()));\n F->parse();\n for (Lazy &Sym : F->getLazySymbols())\n addLazy(&Sym);\n return;\n }\n\n if (Config->Trace)\n llvm::outs() << getFilename(FileP) << \"\\n\";\n\n \/\/ .so file\n if (auto *F = dyn_cast>(FileP)) {\n \/\/ DSOs are uniquified not by filename but by soname.\n F->parseSoName();\n if (!SoNames.insert(F->getSoName()).second)\n return;\n\n SharedFiles.emplace_back(cast>(File.release()));\n F->parseRest();\n for (SharedSymbol &B : F->getSharedSymbols())\n resolve(&B);\n return;\n }\n\n \/\/ LLVM bitcode file\n if (auto *F = dyn_cast(FileP)) {\n BitcodeFiles.emplace_back(cast(File.release()));\n F->parse(ComdatGroups);\n for (SymbolBody *B : F->getSymbols())\n if (B)\n resolve(B);\n return;\n }\n\n \/\/ Regular object file\n auto *F = cast>(FileP);\n ObjectFiles.emplace_back(cast>(File.release()));\n F->parse(ComdatGroups);\n for (SymbolBody *B : F->getNonLocalSymbols())\n resolve(B);\n}\n\n\/\/ This function is where all the optimizations of link-time\n\/\/ optimization happens. When LTO is in use, some input files are\n\/\/ not in native object file format but in the LLVM bitcode format.\n\/\/ This function compiles bitcode files into a few big native files\n\/\/ using LLVM functions and replaces bitcode symbols with the results.\n\/\/ Because all bitcode files that consist of a program are passed\n\/\/ to the compiler at once, it can do whole-program optimization.\ntemplate void SymbolTable::addCombinedLtoObject() {\n if (BitcodeFiles.empty())\n return;\n\n \/\/ Compile bitcode files.\n Lto.reset(new BitcodeCompiler);\n for (const std::unique_ptr &F : BitcodeFiles)\n Lto->add(*F);\n std::vector> IFs = Lto->compile();\n\n \/\/ Replace bitcode symbols.\n for (auto &IF : IFs) {\n ObjectFile *Obj = cast>(IF.release());\n\n llvm::DenseSet DummyGroups;\n Obj->parse(DummyGroups);\n for (SymbolBody *Body : Obj->getNonLocalSymbols()) {\n Symbol *Sym = insert(Body);\n if (!Sym->Body->isUndefined() && Body->isUndefined())\n continue;\n Sym->Body = Body;\n }\n ObjectFiles.emplace_back(Obj);\n }\n}\n\n\/\/ Add an undefined symbol.\ntemplate \nSymbolBody *SymbolTable::addUndefined(StringRef Name) {\n auto *Sym = new (Alloc)\n UndefinedElf(Name, STB_GLOBAL, STV_DEFAULT, \/*Type*\/ 0, false);\n resolve(Sym);\n return Sym;\n}\n\n\/\/ Add an undefined symbol. Unlike addUndefined, that symbol\n\/\/ doesn't have to be resolved, thus \"opt\" (optional).\ntemplate \nSymbolBody *SymbolTable::addUndefinedOpt(StringRef Name) {\n auto *Sym = new (Alloc)\n UndefinedElf(Name, STB_GLOBAL, STV_HIDDEN, \/*Type*\/ 0, true);\n resolve(Sym);\n return Sym;\n}\n\ntemplate \nDefinedRegular *SymbolTable::addAbsolute(StringRef Name,\n uint8_t Visibility) {\n \/\/ Pass nullptr because absolute symbols have no corresponding input sections.\n auto *Sym = new (Alloc) DefinedRegular(Name, STB_GLOBAL, Visibility);\n resolve(Sym);\n return Sym;\n}\n\ntemplate \nSymbolBody *SymbolTable::addSynthetic(StringRef Name,\n OutputSectionBase &Sec,\n uintX_t Val) {\n auto *Sym = new (Alloc) DefinedSynthetic(Name, Val, Sec);\n resolve(Sym);\n return Sym;\n}\n\n\/\/ Add Name as an \"ignored\" symbol. An ignored symbol is a regular\n\/\/ linker-synthesized defined symbol, but is only defined if needed.\ntemplate \nDefinedRegular *SymbolTable::addIgnored(StringRef Name,\n uint8_t Visibility) {\n if (!find(Name))\n return nullptr;\n return addAbsolute(Name, Visibility);\n}\n\n\/\/ Rename SYM as __wrap_SYM. The original symbol is preserved as __real_SYM.\n\/\/ Used to implement --wrap.\ntemplate void SymbolTable::wrap(StringRef Name) {\n if (Symtab.count(Name) == 0)\n return;\n StringSaver Saver(Alloc);\n Symbol *Sym = addUndefined(Name)->Backref;\n Symbol *Real = addUndefined(Saver.save(\"__real_\" + Name))->Backref;\n Symbol *Wrap = addUndefined(Saver.save(\"__wrap_\" + Name))->Backref;\n Real->Body = Sym->Body;\n Sym->Body = Wrap->Body;\n}\n\n\/\/ Returns a file from which symbol B was created.\n\/\/ If B does not belong to any file, returns a nullptr.\ntemplate InputFile *SymbolTable::findFile(SymbolBody *B) {\n for (const std::unique_ptr> &F : ObjectFiles) {\n ArrayRef Syms = F->getSymbols();\n if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())\n return F.get();\n }\n for (const std::unique_ptr &F : BitcodeFiles) {\n ArrayRef Syms = F->getSymbols();\n if (std::find(Syms.begin(), Syms.end(), B) != Syms.end())\n return F.get();\n }\n return nullptr;\n}\n\n\/\/ Construct a string in the form of \"Sym in File1 and File2\".\n\/\/ Used to construct an error message.\ntemplate \nstd::string SymbolTable::conflictMsg(SymbolBody *Old, SymbolBody *New) {\n InputFile *F1 = findFile(Old);\n InputFile *F2 = findFile(New);\n StringRef Sym = Old->getName();\n return demangle(Sym) + \" in \" + getFilename(F1) + \" and \" + getFilename(F2);\n}\n\n\/\/ This function resolves conflicts if there's an existing symbol with\n\/\/ the same name. Decisions are made based on symbol type.\ntemplate void SymbolTable::resolve(SymbolBody *New) {\n Symbol *Sym = insert(New);\n if (Sym->Body == New)\n return;\n\n SymbolBody *Existing = Sym->Body;\n\n if (auto *L = dyn_cast(Existing)) {\n if (New->isUndefined()) {\n addMemberFile(New, L);\n return;\n }\n \/\/ Found a definition for something also in an archive.\n \/\/ Ignore the archive definition.\n Sym->Body = New;\n return;\n }\n\n if (New->isTls() != Existing->isTls()) {\n error(\"TLS attribute mismatch for symbol: \" + conflictMsg(Existing, New));\n return;\n }\n\n \/\/ compare() returns -1, 0, or 1 if the lhs symbol is less preferable,\n \/\/ equivalent (conflicting), or more preferable, respectively.\n int Comp = Existing->compare(New);\n if (Comp == 0) {\n std::string S = \"duplicate symbol: \" + conflictMsg(Existing, New);\n if (Config->AllowMultipleDefinition)\n warning(S);\n else\n error(S);\n return;\n }\n if (Comp < 0)\n Sym->Body = New;\n}\n\nstatic uint8_t getMinVisibility(uint8_t VA, uint8_t VB) {\n if (VA == STV_DEFAULT)\n return VB;\n if (VB == STV_DEFAULT)\n return VA;\n return std::min(VA, VB);\n}\n\nstatic bool shouldExport(SymbolBody *B) {\n if (Config->Shared || Config->ExportDynamic) {\n \/\/ Export most symbols except for those that do not need to be exported.\n return !B->CanOmitFromDynSym;\n }\n \/\/ Make sure we preempt DSO symbols with default visibility.\n return B->isShared() && B->getVisibility() == STV_DEFAULT;\n}\n\n\/\/ Find an existing symbol or create and insert a new one.\ntemplate Symbol *SymbolTable::insert(SymbolBody *New) {\n StringRef Name = New->getName();\n unsigned NumSyms = SymVector.size();\n auto P = Symtab.insert(std::make_pair(Name, NumSyms));\n Symbol *Sym;\n if (P.second) {\n Sym = new (Alloc) Symbol;\n Sym->Body = New;\n Sym->Visibility = STV_DEFAULT;\n Sym->IsUsedInRegularObj = false;\n Sym->ExportDynamic = false;\n Sym->VersionScriptGlobal = !Config->VersionScript;\n SymVector.push_back(Sym);\n } else {\n Sym = SymVector[P.first->second];\n }\n New->Backref = Sym;\n\n \/\/ Merge in the new symbol's visibility. DSO symbols do not affect visibility\n \/\/ in the output.\n if (!New->isShared())\n Sym->Visibility = getMinVisibility(Sym->Visibility, New->getVisibility());\n Sym->ExportDynamic = Sym->ExportDynamic || shouldExport(New);\n SymbolBody::Kind K = New->kind();\n if (K == SymbolBody::DefinedRegularKind ||\n K == SymbolBody::DefinedCommonKind ||\n K == SymbolBody::DefinedSyntheticKind ||\n K == SymbolBody::UndefinedElfKind)\n Sym->IsUsedInRegularObj = true;\n return Sym;\n}\n\ntemplate SymbolBody *SymbolTable::find(StringRef Name) {\n auto It = Symtab.find(Name);\n if (It == Symtab.end())\n return nullptr;\n return SymVector[It->second]->Body;\n}\n\ntemplate void SymbolTable::addLazy(Lazy *L) {\n Symbol *Sym = insert(L);\n SymbolBody *Cur = Sym->Body;\n if (Cur == L)\n return;\n if (Cur->isUndefined()) {\n Sym->Body = L;\n addMemberFile(Cur, L);\n }\n}\n\ntemplate \nvoid SymbolTable::addMemberFile(SymbolBody *Undef, Lazy *L) {\n \/\/ Weak undefined symbols should not fetch members from archives.\n \/\/ If we were to keep old symbol we would not know that an archive member was\n \/\/ available if a strong undefined symbol shows up afterwards in the link.\n \/\/ If a strong undefined symbol never shows up, this lazy symbol will\n \/\/ get to the end of the link and must be treated as the weak undefined one.\n \/\/ We already marked this symbol as used when we added it to the symbol table,\n \/\/ but we also need to preserve its binding and type.\n if (Undef->isWeak()) {\n \/\/ FIXME: Consider moving these members to Symbol.\n L->Binding = Undef->Binding;\n L->Type = Undef->Type;\n return;\n }\n\n \/\/ Fetch a member file that has the definition for L.\n \/\/ getMember returns nullptr if the member was already read from the library.\n if (std::unique_ptr File = L->getFile())\n addFile(std::move(File));\n}\n\n\/\/ This function takes care of the case in which shared libraries depend on\n\/\/ the user program (not the other way, which is usual). Shared libraries\n\/\/ may have undefined symbols, expecting that the user program provides\n\/\/ the definitions for them. An example is BSD's __progname symbol.\n\/\/ We need to put such symbols to the main program's .dynsym so that\n\/\/ shared libraries can find them.\n\/\/ Except this, we ignore undefined symbols in DSOs.\ntemplate void SymbolTable::scanShlibUndefined() {\n for (std::unique_ptr> &File : SharedFiles)\n for (StringRef U : File->getUndefinedSymbols())\n if (SymbolBody *Sym = find(U))\n if (Sym->isDefined())\n Sym->Backref->ExportDynamic = true;\n}\n\n\/\/ This function process the dynamic list option by marking all the symbols\n\/\/ to be exported in the dynamic table.\ntemplate void SymbolTable::scanDynamicList() {\n for (StringRef S : Config->DynamicList)\n if (SymbolBody *B = find(S))\n B->Backref->ExportDynamic = true;\n}\n\n\/\/ This function processes the --version-script option by marking all global\n\/\/ symbols with the VersionScriptGlobal flag, which acts as a filter on the\n\/\/ dynamic symbol table.\ntemplate void SymbolTable::scanVersionScript() {\n for (StringRef S : Config->VersionScriptGlobals)\n if (SymbolBody *B = find(S))\n B->Backref->VersionScriptGlobal = true;\n}\n\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\ntemplate class elf::SymbolTable;\n<|endoftext|>"} {"text":"#include \"StreamServer.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nStreamServer::StreamServer() {\n\tIce::CommunicatorPtr ic;\n\ttry {\n\t\tic = Ice::initialize();\n\t\tIce::ObjectPrx obj = ic->stringToProxy(\"IceStorm\/TopicManager:tcp -h 80.240.129.188 -p 9999\");\n\t\tIceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(obj);\n\t\tIceStorm::TopicPrx topic;\n\t\twhile (!topic) {\n\t\t\ttry {\n\t\t\t\ttopic = topicManager->retrieve(\"StreamPlayerNotifs\");\n\t\t\t} catch (const IceStorm::NoSuchTopic&) {\n\t\t\t\ttry {\n\t\t\t\t\ttopic = topicManager->create(\"StreamPlayerNotifs\");\n\t\t\t\t} catch(const IceStorm::TopicExists&) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tIce::ObjectPrx pub = topic->getPublisher()->ice_twoway();\n\t\tmonitor = MonitorPrx::uncheckedCast(pub);\n\t} catch (const Ice::Exception& e) {\n\t\tstd::cerr << e << '\\n';\n\t}\n\tvlc = libvlc_new(0, NULL);\n}\n\nstd::string StreamServer::selectSong(const Song& s, const Ice::Current& c) {\n\tstd::cout << \"Selecting song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn \"\";\n\tIce::IPConnectionInfo* ipCoInfo = dynamic_cast(c.con->getInfo().get());\n\tauto duration = std::chrono::system_clock::now().time_since_epoch();\n\tstd::string token = ipCoInfo->remoteAddress.substr(7) + \".\" + std::to_string(ipCoInfo->remotePort) + \".\" + std::to_string(std::chrono::duration_cast(duration).count());\n\tstd::string ssout = \"#transcode{acodec=mp3,ab=128,channels=2,\" \\\n\t\t\t\t\t\t \"samplerate=44100}:http{dst=:8090\/\"+token+\".mp3}\";\n\tconst char* sout = ssout.c_str();\n\tstd::string path = \"songs\/\"+s.path;\n\tlibvlc_vlm_add_broadcast(vlc, token.c_str(), path.c_str(), sout, 0, nullptr, true, false);\n\tstd::cout << \"Selected song (\" << token << \")\\n\";\n\treturn token;\n}\n\nvoid StreamServer::playSong(const std::string& token, const Ice::Current&) {\n\tstd::cout << \"Playing song (\" << token << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn;\n\tlibvlc_vlm_play_media(vlc, token.c_str());\n}\n\nvoid StreamServer::stopSong(const std::string& token, const Ice::Current&) {\n\tstd::cout << \"Stopping song (\" << token << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn;\n\tlibvlc_vlm_stop_media(vlc, token.c_str());\n}\n\nvoid StreamServer::addSong(const Song& s, const Ice::Current&) {\n\tstd::cout << \"Adding song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tsongs.push_back(s);\n\tmonitor->report(\"add\", s);\n}\n\nvoid StreamServer::removeSong(const Song& s, const Ice::Current&) {\n\tstd::cout << \"Removing song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tfor(int i = 0; i < songs.size(); ++i) {\n\t\tif(songs[i].artist == s.artist && songs[i].title == s.title)\n\t\t\tsongs.erase(songs.begin()+(i--));\n\t}\n\tmonitor->report(\"del\", s);\n}\n\nstd::vector StreamServer::searchSong(const std::string& artist, const std::string& title, const Ice::Current&) {\n\tstd::cout << \"Searching song (\" << artist << \", \" << title << \")\\n\";\n\tstd::vector output;\n\tfor(int i = 0; i < songs.size(); ++i) {\n\t\tif(artist.empty() && title.empty()) {\n\t\t\toutput.push_back(songs[i]);\n\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t} else if(artist.empty() || title.empty()) {\n\t\t\tif((title.empty() && songs[i].artist == artist)\n\t\t\t\t\t|| (artist.empty() && songs[i].title == title)) {\n\t\t\t\toutput.push_back(songs[i]);\n\t\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t\t}\n\t\t} else if(songs[i].artist == artist && songs[i].title == title) {\n\t\t\toutput.push_back(songs[i]);\n\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t}\n\t}\n\tstd::cout << \"Search finished\\n\";\n\treturn output;\n}\n\nvoid StreamServer::uploadFile(const std::string& name, const ByteSeq& data, const Ice::Current& c) {\n\tFILE* file;\n\tstd::string path = \"..\/songs\/\" + name;\n\tfile = fopen(path.c_str(), \"a+\");\n\tfseek(file, 0, SEEK_END);\n\tfwrite(&data[0], 1, data.size(), file);\n\tfclose(file);\n}\nfix file upload#include \"StreamServer.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nStreamServer::StreamServer() {\n\tIce::CommunicatorPtr ic;\n\ttry {\n\t\tic = Ice::initialize();\n\t\tIce::ObjectPrx obj = ic->stringToProxy(\"IceStorm\/TopicManager:tcp -h 80.240.129.188 -p 9999\");\n\t\tIceStorm::TopicManagerPrx topicManager = IceStorm::TopicManagerPrx::checkedCast(obj);\n\t\tIceStorm::TopicPrx topic;\n\t\twhile (!topic) {\n\t\t\ttry {\n\t\t\t\ttopic = topicManager->retrieve(\"StreamPlayerNotifs\");\n\t\t\t} catch (const IceStorm::NoSuchTopic&) {\n\t\t\t\ttry {\n\t\t\t\t\ttopic = topicManager->create(\"StreamPlayerNotifs\");\n\t\t\t\t} catch(const IceStorm::TopicExists&) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tIce::ObjectPrx pub = topic->getPublisher()->ice_twoway();\n\t\tmonitor = MonitorPrx::uncheckedCast(pub);\n\t} catch (const Ice::Exception& e) {\n\t\tstd::cerr << e << '\\n';\n\t}\n\tvlc = libvlc_new(0, NULL);\n}\n\nstd::string StreamServer::selectSong(const Song& s, const Ice::Current& c) {\n\tstd::cout << \"Selecting song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn \"\";\n\tIce::IPConnectionInfo* ipCoInfo = dynamic_cast(c.con->getInfo().get());\n\tauto duration = std::chrono::system_clock::now().time_since_epoch();\n\tstd::string token = ipCoInfo->remoteAddress.substr(7) + \".\" + std::to_string(ipCoInfo->remotePort) + \".\" + std::to_string(std::chrono::duration_cast(duration).count());\n\tstd::string ssout = \"#transcode{acodec=mp3,ab=128,channels=2,\" \\\n\t\t\t\t\t\t \"samplerate=44100}:http{dst=:8090\/\"+token+\".mp3}\";\n\tconst char* sout = ssout.c_str();\n\tstd::string path = \"songs\/\"+s.path;\n\tlibvlc_vlm_add_broadcast(vlc, token.c_str(), path.c_str(), sout, 0, nullptr, true, false);\n\tstd::cout << \"Selected song (\" << token << \")\\n\";\n\treturn token;\n}\n\nvoid StreamServer::playSong(const std::string& token, const Ice::Current&) {\n\tstd::cout << \"Playing song (\" << token << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn;\n\tlibvlc_vlm_play_media(vlc, token.c_str());\n}\n\nvoid StreamServer::stopSong(const std::string& token, const Ice::Current&) {\n\tstd::cout << \"Stopping song (\" << token << \")\\n\";\n\tif(vlc == nullptr)\n\t\treturn;\n\tlibvlc_vlm_stop_media(vlc, token.c_str());\n}\n\nvoid StreamServer::addSong(const Song& s, const Ice::Current&) {\n\tstd::cout << \"Adding song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tsongs.push_back(s);\n\tmonitor->report(\"add\", s);\n}\n\nvoid StreamServer::removeSong(const Song& s, const Ice::Current&) {\n\tstd::cout << \"Removing song (\" << s.artist << \", \" << s.title << \")\\n\";\n\tfor(int i = 0; i < songs.size(); ++i) {\n\t\tif(songs[i].artist == s.artist && songs[i].title == s.title)\n\t\t\tsongs.erase(songs.begin()+(i--));\n\t}\n\tmonitor->report(\"del\", s);\n}\n\nstd::vector StreamServer::searchSong(const std::string& artist, const std::string& title, const Ice::Current&) {\n\tstd::cout << \"Searching song (\" << artist << \", \" << title << \")\\n\";\n\tstd::vector output;\n\tfor(int i = 0; i < songs.size(); ++i) {\n\t\tif(artist.empty() && title.empty()) {\n\t\t\toutput.push_back(songs[i]);\n\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t} else if(artist.empty() || title.empty()) {\n\t\t\tif((title.empty() && songs[i].artist == artist)\n\t\t\t\t\t|| (artist.empty() && songs[i].title == title)) {\n\t\t\t\toutput.push_back(songs[i]);\n\t\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t\t}\n\t\t} else if(songs[i].artist == artist && songs[i].title == title) {\n\t\t\toutput.push_back(songs[i]);\n\t\t\tstd::cout << \"Found song (\" << songs[i].artist << \", \" << songs[i].title << \")\\n\";\n\t\t}\n\t}\n\tstd::cout << \"Search finished\\n\";\n\treturn output;\n}\n\nvoid StreamServer::uploadFile(const std::string& name, const ByteSeq& data, const Ice::Current& c) {\n\tFILE* file;\n\tstd::string path = \"songs\/\" + name + \".mp3\";\n\tstd::cout << path << std::endl;\n\tfile = fopen(path.c_str(), \"a+\");\n\tfseek(file, 0, SEEK_END);\n\tfwrite(&data[0], 1, data.size(), file);\n\tfclose(file);\n}\n<|endoftext|>"} {"text":"#include \"networkmanager.h\"\n#include \"..\/networkhelper.h\"\n#include \"..\/log\/logger.h\"\n#include \"..\/scheduler\/scheduler.h\"\n#include \"..\/task\/taskexecutor.h\"\n#include \"..\/settings.h\"\n#include \"..\/timing\/immediatetiming.h\"\n#include \"..\/timing\/periodictiming.h\"\n\n#include \"tcpsocket.h\"\n#include \"udpsocket.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nLOGGER(NetworkManager);\n\nclass PeerRequest\n{\npublic:\n QVariant toVariant()\n {\n QVariantMap map;\n map.insert(\"type\", \"peer_request\");\n map.insert(\"connectionId\", connectionId);\n map.insert(\"definition\", measurementDefinition);\n map.insert(\"measurement\", measurement);\n map.insert(\"peer\", peer);\n map.insert(\"port\", port);\n map.insert(\"protocol\", protocol);\n return map;\n }\n\n static PeerRequest fromVariant(const QVariant& variant)\n {\n QVariantMap map = variant.toMap();\n\n PeerRequest request;\n request.connectionId = map.value(\"connectionId\").toUuid();\n request.measurementDefinition = map.value(\"definition\");\n request.measurement = map.value(\"measurement\").toString();\n request.peer = map.value(\"peer\").toString();\n request.port = map.value(\"port\").toUInt();\n request.protocol = (NetworkManager::SocketType)map.value(\"protocol\").toInt();\n return request;\n }\n\n QUuid connectionId;\n QVariant measurementDefinition;\n QString measurement;\n QString peer;\n quint16 port;\n NetworkManager::SocketType protocol;\n};\n\nclass NetworkManager::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(NetworkManager* q)\n : q(q)\n {\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n }\n\n NetworkManager* q;\n\n \/\/ Properties\n QMutex mutex;\n QHash objectHash;\n QHash socketHash;\n\n QTimer timer;\n QPointer socket;\n QPointer scheduler;\n QPointer settings;\n\n QSet handledConnectionIds;\n\n quint16 localPort;\n\n QNetworkConfigurationManager ncm;\n\n \/\/ Functions\n QAbstractSocket* createSocket(NetworkManager::SocketType socketType);\n\n void updateSocket();\n void updateTimer();\n void processDatagram(const QByteArray& datagram, const QHostAddress& host, quint16 port);\n\npublic slots:\n void socketDestroyed(QObject* obj);\n void responseChanged();\n void timeout();\n void onDatagramReady();\n};\n\nQAbstractSocket *NetworkManager::Private::createSocket(NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = NULL;\n\n switch (socketType)\n {\n case TcpSocket:\n socket = new ::TcpSocket;\n break;\n\n case UdpSocket:\n socket = new ::UdpSocket;\n break;\n\n case UtpSocket:\n \/\/socket = new UtpSocket;\n break;\n\n default:\n break;\n }\n\n if (socket)\n {\n connect(socket, SIGNAL(destroyed(QObject*)), this, SLOT(socketDestroyed(QObject*)));\n }\n\n return socket;\n}\n\nvoid NetworkManager::Private::socketDestroyed(QObject *obj)\n{\n QString hostname = objectHash.key(obj);\n if (hostname.isEmpty())\n {\n return;\n }\n\n objectHash.remove(hostname);\n socketHash.remove(hostname);\n}\n\nvoid NetworkManager::Private::updateSocket()\n{\n if (!socket.isNull())\n {\n delete socket.data();\n socket.clear();\n }\n\n QString keepaliveAddress = settings->config()->keepaliveAddress();\n RemoteHost remote = NetworkHelper::remoteHost(keepaliveAddress);\n if (!remote.isValid())\n {\n return;\n }\n\n localPort = remote.port;\n\n socket = qobject_cast( q->createConnection(NetworkManager::UdpSocket) );\n socket->setParent(this);\n connect(socket.data(), SIGNAL(readyRead()), this, SLOT(onDatagramReady()));\n if (!socket->bind(remote.port))\n {\n LOG_ERROR(QString(\"Unable to bind port %1: %2\").arg(remote.port).arg(socket->errorString()));\n }\n}\n\nvoid NetworkManager::Private::updateTimer()\n{\n TimingPtr timing = settings->config()->keepaliveSchedule();\n if (!timing)\n {\n return;\n }\n\n QSharedPointer periodicTiming = timing.dynamicCast();\n Q_ASSERT(periodicTiming);\n\n int interval = periodicTiming->period();\n if (interval < 1000)\n {\n LOG_INFO(\"Keepalive interval < 1 sec will not be accepted.\");\n return;\n }\n else\n {\n LOG_INFO(QString(\"Keepalive set to %1 sec.\").arg(interval\/1000));\n }\n\n timer.setInterval(interval);\n timer.start();\n}\n\nclass NetworkManagerMeasurementObserver : public MeasurementObserver\n{\npublic:\n NetworkManager* networkManager;\n NetworkManager::SocketType socketType;\n quint16 localPort;\n\n QHostAddress host;\n quint16 port;\n\n \/\/ MeasurementObserver interface\n void created(const MeasurementPtr &measurement)\n {\n QAbstractSocket* socket = networkManager->createConnection(socketType);\n\n QUdpSocket* udpSocket = qobject_cast(socket);\n if (!udpSocket->bind(localPort))\n {\n LOG_ERROR(\"Cannot bind socket\");\n return;\n }\n\n \/\/ ACK the connection\n udpSocket->writeDatagram(QByteArray(), host, port);\n measurement->setPeerSocket(udpSocket);\n }\n};\n\nvoid NetworkManager::Private::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n QString hostAndPort = QString(\"%1:%2\").arg(host.toString()).arg(port);\n if (datagram.isEmpty())\n {\n LOG_DEBUG(QString(\"Received empty datagram from %1\").arg(hostAndPort));\n return;\n }\n\n LOG_DEBUG(QString(\"Received datagram from %1: %2\").arg(hostAndPort).arg(QString::fromUtf8(datagram)));\n\/\/ if (settings->config()->keepaliveAddress() == hostAndPort) {\n \/\/ Master server\n QJsonParseError error;\n QJsonDocument document = QJsonDocument::fromJson(datagram, &error);\n\n if (error.error == QJsonParseError::NoError)\n {\n PeerRequest request = PeerRequest::fromVariant(document.toVariant());\n\n if (handledConnectionIds.contains(request.connectionId))\n {\n LOG_DEBUG(\"Connection id is already handled, skipping second try\");\n return;\n }\n\n handledConnectionIds.insert(request.connectionId);\n\n MeasurementObserver* observer = NULL;\n if (request.protocol == NetworkManager::UdpSocket)\n {\n NetworkManagerMeasurementObserver* tempObs = new NetworkManagerMeasurementObserver;\n tempObs->networkManager = q;\n tempObs->socketType = request.protocol;\n tempObs->localPort = 5106; \/\/ FIXME: Don't hardcode this here\n tempObs->host = host; \/\/request.peer;\n tempObs->port = port;\n\n observer = tempObs;\n }\n\n \/\/ FIXME: We can't assign the Peer socket to Measurement since this is created in a separate thread\n \/\/ and we can't access.\n\n TimingPtr timing(new ImmediateTiming);\n TestDefinitionPtr testDefinition(new TestDefinition(request.connectionId, request.measurement, timing, request.measurementDefinition));\n\n \/\/ Bypass scheduler and run directly on the executor\n scheduler->executor()->execute(testDefinition, observer);\n }\n else\n {\n LOG_ERROR(QString(\"Invalid JSon: %1\").arg(error.errorString()));\n }\n\/\/ } else {\n \/\/ TODO: Process incoming data\n\/\/ }\n}\n\nvoid NetworkManager::Private::responseChanged()\n{\n updateSocket();\n updateTimer();\n\n \/\/ Send the first timeout now\n timeout();\n}\n\nvoid NetworkManager::Private::timeout()\n{\n RemoteHost remote = NetworkHelper::remoteHost(settings->config()->keepaliveAddress());\n if (!remote.isValid())\n {\n LOG_INFO(\"Invalid keepalive host\");\n return;\n }\n\n QString sessionId = settings->sessionId();\n if (sessionId.isEmpty())\n {\n LOG_INFO(\"Empty session id\");\n return;\n }\n\n QStringList srcIp;\n srcIp.append( NetworkHelper::localIpAddress().toString() );\n\n QVariantMap map;\n map.insert(\"type\", \"keepalive\");\n map.insert(\"session_id\", sessionId);\n map.insert(\"src_ip\", srcIp);\n map.insert(\"src_port\", localPort);\n\n QByteArray data = QJsonDocument::fromVariant(map).toJson();\n socket->writeDatagram(data, QHostAddress(remote.host), remote.port);\n\n LOG_INFO(\"Alive packet sent\");\n}\n\nvoid NetworkManager::Private::onDatagramReady()\n{\n while (socket->hasPendingDatagrams())\n {\n QByteArray datagram;\n datagram.resize(socket->pendingDatagramSize());\n\n QHostAddress host;\n quint16 port;\n socket->readDatagram(datagram.data(), datagram.size(), &host, &port);\n\n \/\/ Process the datagram\n processDatagram(datagram, host, port);\n }\n}\n\nNetworkManager::NetworkManager(QObject *parent)\n: QObject(parent)\n, d(new Private(this))\n{\n}\n\nNetworkManager::~NetworkManager()\n{\n delete d;\n}\n\nbool NetworkManager::init(Scheduler* scheduler, Settings *settings)\n{\n connect(settings->config(), SIGNAL(responseChanged()), d, SLOT(responseChanged()));\n\n d->scheduler = scheduler;\n d->settings = settings;\n d->responseChanged();\n\n emit d->ncm.updateConfigurations();\n\n return true;\n}\n\nvoid NetworkManager::setRunning(bool running)\n{\n if (isRunning() == running)\n {\n return;\n }\n\n if ( !running )\n {\n d->timer.stop();\n }\n else\n {\n d->updateTimer();\n }\n}\n\nbool NetworkManager::isRunning() const\n{\n return d->timer.isActive();\n}\n\nbool NetworkManager::onMobileConnection() const\n{\n QList confList = d->ncm.allConfigurations(QNetworkConfiguration::Active);\n\n foreach(QNetworkConfiguration conf, confList)\n {\n QNetworkConfiguration::BearerType type = conf.bearerType();\n if (type != QNetworkConfiguration::BearerEthernet && type != QNetworkConfiguration::BearerWLAN)\n {\n return true;\n }\n }\n\n return false;\n}\n\nQAbstractSocket *NetworkManager::connection(const QString &hostname, NetworkManager::SocketType socketType) const\n{\n return d->socketHash.value(hostname);\n}\n\nQAbstractSocket *NetworkManager::createConnection(NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = d->createSocket(socketType);\n if ( !socket )\n {\n qDebug() << \"Unknown socket type requested\";\n return NULL;\n }\n\n \/\/d->socketHash.insert(hostname, socket);\n \/\/d->objectHash.insert(hostname, socket);\n\n return socket;\n}\n\nQAbstractSocket *NetworkManager::establishConnection(const QString &hostname, const QString &measurement, const QVariant &definition, NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = d->createSocket(socketType);\n if ( !socket )\n {\n qDebug() << \"Unknown socket type requested\";\n return NULL;\n }\n\n RemoteHost remote = NetworkHelper::remoteHost(hostname);\n RemoteHost aliveRemote = NetworkHelper::remoteHost(d->settings->config()->keepaliveAddress());\n\n if (!aliveRemote.isValid())\n {\n LOG_ERROR(QString(\"Invalid alive remote: '%1' can't talk to alive server\").arg(d->settings->config()->keepaliveAddress()));\n delete socket;\n return NULL;\n }\n\n PeerRequest request;\n request.connectionId = QUuid::createUuid();\n request.measurement = measurement;\n request.measurementDefinition = definition;\n request.peer = remote.host;\n request.port = aliveRemote.port;\n request.protocol = socketType;\n\n \/\/ If for some reason our packet gets routed back to us, don't handle it\n d->handledConnectionIds.insert(request.connectionId);\n\n QUdpSocket* testSocket = d->socket.data();\n if ( socketType != TcpSocket )\n {\n if (!socket->bind(remote.port))\n {\n LOG_ERROR(QString(\"Unable to bind source port to %1\").arg(remote.port));\n delete socket;\n return NULL;\n }\n\n QUdpSocket* udpSocket = qobject_cast(socket);\n udpSocket->writeDatagram(QByteArray(), QHostAddress(remote.host), remote.port);\n\n testSocket = udpSocket;\n }\n\n QByteArray data = QJsonDocument::fromVariant(request.toVariant()).toJson();\n\n \/\/ Step one: Send test offer to peer directly\n testSocket->writeDatagram(data, QHostAddress(remote.host), d->localPort);\n\n \/\/ Step two: Send test offer to peer via alive-server\n testSocket->writeDatagram(data, QHostAddress(aliveRemote.host), aliveRemote.port);\n\n LOG_TRACE(\"Sent test offer to peer and alive-server\");\n\n if ( socketType != UdpSocket )\n {\n \/\/ Final step: Connect to remote host\n \/\/if (socket->waitForReadyRead(5000))\n \/\/ return socket;\n\n const int tries = 20;\n for (int i=0; i < tries; ++i)\n {\n socket->connectToHost(remote.host, remote.port);\n if (socket->waitForConnected(5000\/tries))\n {\n return socket;\n }\n }\n\n LOG_ERROR(QString(\"Unable to connect tcp socket in %3 tries to %1: %2\").arg(hostname).arg(socket->errorString()).arg(tries));\n }\n else\n {\n if (!testSocket->waitForReadyRead(5000))\n {\n LOG_ERROR(\"Remote did not answer for 5 sec, aborting connection.\");\n }\n else\n {\n \/\/ TODO: Read the first (empty) datagram\n QHostAddress packetHost;\n testSocket->readDatagram(0, 0, &packetHost);\n\n if (packetHost != QHostAddress(remote.host))\n {\n LOG_ERROR(\"Received connection packet from wrong host!\");\n }\n else\n {\n return socket;\n }\n }\n }\n\n delete socket;\n return NULL;\n}\n\nQTcpServer *NetworkManager::createServerSocket()\n{\n \/\/ TODO: Connect to traffic counter\n QTcpServer* server = new QTcpServer;\n return server;\n}\n\n#include \"networkmanager.moc\"\nShow error message if something with the keepalive server goes wrong#include \"networkmanager.h\"\n#include \"..\/networkhelper.h\"\n#include \"..\/log\/logger.h\"\n#include \"..\/scheduler\/scheduler.h\"\n#include \"..\/task\/taskexecutor.h\"\n#include \"..\/settings.h\"\n#include \"..\/timing\/immediatetiming.h\"\n#include \"..\/timing\/periodictiming.h\"\n\n#include \"tcpsocket.h\"\n#include \"udpsocket.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nLOGGER(NetworkManager);\n\nclass PeerRequest\n{\npublic:\n QVariant toVariant()\n {\n QVariantMap map;\n map.insert(\"type\", \"peer_request\");\n map.insert(\"connectionId\", connectionId);\n map.insert(\"definition\", measurementDefinition);\n map.insert(\"measurement\", measurement);\n map.insert(\"peer\", peer);\n map.insert(\"port\", port);\n map.insert(\"protocol\", protocol);\n return map;\n }\n\n static PeerRequest fromVariant(const QVariant& variant)\n {\n QVariantMap map = variant.toMap();\n\n PeerRequest request;\n request.connectionId = map.value(\"connectionId\").toUuid();\n request.measurementDefinition = map.value(\"definition\");\n request.measurement = map.value(\"measurement\").toString();\n request.peer = map.value(\"peer\").toString();\n request.port = map.value(\"port\").toUInt();\n request.protocol = (NetworkManager::SocketType)map.value(\"protocol\").toInt();\n return request;\n }\n\n QUuid connectionId;\n QVariant measurementDefinition;\n QString measurement;\n QString peer;\n quint16 port;\n NetworkManager::SocketType protocol;\n};\n\nclass NetworkManager::Private : public QObject\n{\n Q_OBJECT\n\npublic:\n Private(NetworkManager* q)\n : q(q)\n {\n connect(&timer, SIGNAL(timeout()), this, SLOT(timeout()));\n }\n\n NetworkManager* q;\n\n \/\/ Properties\n QMutex mutex;\n QHash objectHash;\n QHash socketHash;\n\n QTimer timer;\n QPointer socket;\n QPointer scheduler;\n QPointer settings;\n\n QSet handledConnectionIds;\n\n quint16 localPort;\n\n QNetworkConfigurationManager ncm;\n\n \/\/ Functions\n QAbstractSocket* createSocket(NetworkManager::SocketType socketType);\n\n void updateSocket();\n void updateTimer();\n void processDatagram(const QByteArray& datagram, const QHostAddress& host, quint16 port);\n\npublic slots:\n void socketDestroyed(QObject* obj);\n void responseChanged();\n void timeout();\n void onDatagramReady();\n};\n\nQAbstractSocket *NetworkManager::Private::createSocket(NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = NULL;\n\n switch (socketType)\n {\n case TcpSocket:\n socket = new ::TcpSocket;\n break;\n\n case UdpSocket:\n socket = new ::UdpSocket;\n break;\n\n case UtpSocket:\n \/\/socket = new UtpSocket;\n break;\n\n default:\n break;\n }\n\n if (socket)\n {\n connect(socket, SIGNAL(destroyed(QObject*)), this, SLOT(socketDestroyed(QObject*)));\n }\n\n return socket;\n}\n\nvoid NetworkManager::Private::socketDestroyed(QObject *obj)\n{\n QString hostname = objectHash.key(obj);\n if (hostname.isEmpty())\n {\n return;\n }\n\n objectHash.remove(hostname);\n socketHash.remove(hostname);\n}\n\nvoid NetworkManager::Private::updateSocket()\n{\n if (!socket.isNull())\n {\n delete socket.data();\n socket.clear();\n }\n\n QString keepaliveAddress = settings->config()->keepaliveAddress();\n RemoteHost remote = NetworkHelper::remoteHost(keepaliveAddress);\n if (!remote.isValid())\n {\n return;\n }\n\n localPort = remote.port;\n\n socket = qobject_cast( q->createConnection(NetworkManager::UdpSocket) );\n socket->setParent(this);\n connect(socket.data(), SIGNAL(readyRead()), this, SLOT(onDatagramReady()));\n if (!socket->bind(remote.port))\n {\n LOG_ERROR(QString(\"Unable to bind port %1: %2\").arg(remote.port).arg(socket->errorString()));\n }\n}\n\nvoid NetworkManager::Private::updateTimer()\n{\n TimingPtr timing = settings->config()->keepaliveSchedule();\n if (!timing)\n {\n return;\n }\n\n QSharedPointer periodicTiming = timing.dynamicCast();\n Q_ASSERT(periodicTiming);\n\n int interval = periodicTiming->period();\n if (interval < 1000)\n {\n LOG_INFO(\"Keepalive interval < 1 sec will not be accepted.\");\n return;\n }\n else\n {\n LOG_INFO(QString(\"Keepalive set to %1 sec.\").arg(interval\/1000));\n }\n\n timer.setInterval(interval);\n timer.start();\n}\n\nclass NetworkManagerMeasurementObserver : public MeasurementObserver\n{\npublic:\n NetworkManager* networkManager;\n NetworkManager::SocketType socketType;\n quint16 localPort;\n\n QHostAddress host;\n quint16 port;\n\n \/\/ MeasurementObserver interface\n void created(const MeasurementPtr &measurement)\n {\n QAbstractSocket* socket = networkManager->createConnection(socketType);\n\n QUdpSocket* udpSocket = qobject_cast(socket);\n if (!udpSocket->bind(localPort))\n {\n LOG_ERROR(\"Cannot bind socket\");\n return;\n }\n\n \/\/ ACK the connection\n udpSocket->writeDatagram(QByteArray(), host, port);\n measurement->setPeerSocket(udpSocket);\n }\n};\n\nvoid NetworkManager::Private::processDatagram(const QByteArray &datagram, const QHostAddress &host, quint16 port)\n{\n QString hostAndPort = QString(\"%1:%2\").arg(host.toString()).arg(port);\n if (datagram.isEmpty())\n {\n LOG_DEBUG(QString(\"Received empty datagram from %1\").arg(hostAndPort));\n return;\n }\n\n LOG_DEBUG(QString(\"Received datagram from %1: %2\").arg(hostAndPort).arg(QString::fromUtf8(datagram)));\n\/\/ if (settings->config()->keepaliveAddress() == hostAndPort) {\n \/\/ Master server\n QJsonParseError error;\n QJsonDocument document = QJsonDocument::fromJson(datagram, &error);\n\n if (error.error == QJsonParseError::NoError)\n {\n QJsonObject root = document.object();\n\n QString replyError = root.value(\"error\").toString();\n if ( !replyError.isEmpty() )\n {\n LOG_ERROR(QString(\"Error from server: %1\").arg(root.value(\"error\").toString()));\n return;\n }\n\n PeerRequest request = PeerRequest::fromVariant(document.toVariant());\n\n if (handledConnectionIds.contains(request.connectionId))\n {\n LOG_DEBUG(\"Connection id is already handled, skipping second try\");\n return;\n }\n\n handledConnectionIds.insert(request.connectionId);\n\n MeasurementObserver* observer = NULL;\n if (request.protocol == NetworkManager::UdpSocket)\n {\n NetworkManagerMeasurementObserver* tempObs = new NetworkManagerMeasurementObserver;\n tempObs->networkManager = q;\n tempObs->socketType = request.protocol;\n tempObs->localPort = 5106; \/\/ FIXME: Don't hardcode this here\n tempObs->host = host; \/\/request.peer;\n tempObs->port = port;\n\n observer = tempObs;\n }\n\n \/\/ FIXME: We can't assign the Peer socket to Measurement since this is created in a separate thread\n \/\/ and we can't access.\n\n TimingPtr timing(new ImmediateTiming);\n TestDefinitionPtr testDefinition(new TestDefinition(request.connectionId, request.measurement, timing, request.measurementDefinition));\n\n \/\/ Bypass scheduler and run directly on the executor\n scheduler->executor()->execute(testDefinition, observer);\n }\n else\n {\n LOG_ERROR(QString(\"Invalid JSon: %1\").arg(error.errorString()));\n }\n\/\/ } else {\n \/\/ TODO: Process incoming data\n\/\/ }\n}\n\nvoid NetworkManager::Private::responseChanged()\n{\n updateSocket();\n updateTimer();\n\n \/\/ Send the first timeout now\n timeout();\n}\n\nvoid NetworkManager::Private::timeout()\n{\n RemoteHost remote = NetworkHelper::remoteHost(settings->config()->keepaliveAddress());\n if (!remote.isValid())\n {\n LOG_INFO(\"Invalid keepalive host\");\n return;\n }\n\n QString sessionId = settings->sessionId();\n if (sessionId.isEmpty())\n {\n LOG_INFO(\"Empty session id\");\n return;\n }\n\n QStringList srcIp;\n srcIp.append( NetworkHelper::localIpAddress().toString() );\n\n QVariantMap map;\n map.insert(\"type\", \"keepalive\");\n map.insert(\"session_id\", sessionId);\n map.insert(\"src_ip\", srcIp);\n map.insert(\"src_port\", localPort);\n\n QByteArray data = QJsonDocument::fromVariant(map).toJson();\n socket->writeDatagram(data, QHostAddress(remote.host), remote.port);\n\n LOG_INFO(\"Alive packet sent\");\n}\n\nvoid NetworkManager::Private::onDatagramReady()\n{\n while (socket->hasPendingDatagrams())\n {\n QByteArray datagram;\n datagram.resize(socket->pendingDatagramSize());\n\n QHostAddress host;\n quint16 port;\n socket->readDatagram(datagram.data(), datagram.size(), &host, &port);\n\n \/\/ Process the datagram\n processDatagram(datagram, host, port);\n }\n}\n\nNetworkManager::NetworkManager(QObject *parent)\n: QObject(parent)\n, d(new Private(this))\n{\n}\n\nNetworkManager::~NetworkManager()\n{\n delete d;\n}\n\nbool NetworkManager::init(Scheduler* scheduler, Settings *settings)\n{\n connect(settings->config(), SIGNAL(responseChanged()), d, SLOT(responseChanged()));\n\n d->scheduler = scheduler;\n d->settings = settings;\n d->responseChanged();\n\n emit d->ncm.updateConfigurations();\n\n return true;\n}\n\nvoid NetworkManager::setRunning(bool running)\n{\n if (isRunning() == running)\n {\n return;\n }\n\n if ( !running )\n {\n d->timer.stop();\n }\n else\n {\n d->updateTimer();\n }\n}\n\nbool NetworkManager::isRunning() const\n{\n return d->timer.isActive();\n}\n\nbool NetworkManager::onMobileConnection() const\n{\n QList confList = d->ncm.allConfigurations(QNetworkConfiguration::Active);\n\n foreach(QNetworkConfiguration conf, confList)\n {\n QNetworkConfiguration::BearerType type = conf.bearerType();\n if (type != QNetworkConfiguration::BearerEthernet && type != QNetworkConfiguration::BearerWLAN)\n {\n return true;\n }\n }\n\n return false;\n}\n\nQAbstractSocket *NetworkManager::connection(const QString &hostname, NetworkManager::SocketType socketType) const\n{\n return d->socketHash.value(hostname);\n}\n\nQAbstractSocket *NetworkManager::createConnection(NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = d->createSocket(socketType);\n if ( !socket )\n {\n qDebug() << \"Unknown socket type requested\";\n return NULL;\n }\n\n \/\/d->socketHash.insert(hostname, socket);\n \/\/d->objectHash.insert(hostname, socket);\n\n return socket;\n}\n\nQAbstractSocket *NetworkManager::establishConnection(const QString &hostname, const QString &measurement, const QVariant &definition, NetworkManager::SocketType socketType)\n{\n QAbstractSocket* socket = d->createSocket(socketType);\n if ( !socket )\n {\n qDebug() << \"Unknown socket type requested\";\n return NULL;\n }\n\n RemoteHost remote = NetworkHelper::remoteHost(hostname);\n RemoteHost aliveRemote = NetworkHelper::remoteHost(d->settings->config()->keepaliveAddress());\n\n if (!aliveRemote.isValid())\n {\n LOG_ERROR(QString(\"Invalid alive remote: '%1' can't talk to alive server\").arg(d->settings->config()->keepaliveAddress()));\n delete socket;\n return NULL;\n }\n\n PeerRequest request;\n request.connectionId = QUuid::createUuid();\n request.measurement = measurement;\n request.measurementDefinition = definition;\n request.peer = remote.host;\n request.port = aliveRemote.port;\n request.protocol = socketType;\n\n \/\/ If for some reason our packet gets routed back to us, don't handle it\n d->handledConnectionIds.insert(request.connectionId);\n\n QUdpSocket* testSocket = d->socket.data();\n if ( socketType != TcpSocket )\n {\n if (!socket->bind(remote.port))\n {\n LOG_ERROR(QString(\"Unable to bind source port to %1\").arg(remote.port));\n delete socket;\n return NULL;\n }\n\n QUdpSocket* udpSocket = qobject_cast(socket);\n udpSocket->writeDatagram(QByteArray(), QHostAddress(remote.host), remote.port);\n\n testSocket = udpSocket;\n }\n\n QByteArray data = QJsonDocument::fromVariant(request.toVariant()).toJson();\n\n \/\/ Step one: Send test offer to peer directly\n testSocket->writeDatagram(data, QHostAddress(remote.host), d->localPort);\n\n \/\/ Step two: Send test offer to peer via alive-server\n testSocket->writeDatagram(data, QHostAddress(aliveRemote.host), aliveRemote.port);\n\n LOG_TRACE(\"Sent test offer to peer and alive-server\");\n\n if ( socketType != UdpSocket )\n {\n \/\/ Final step: Connect to remote host\n \/\/if (socket->waitForReadyRead(5000))\n \/\/ return socket;\n\n const int tries = 20;\n for (int i=0; i < tries; ++i)\n {\n socket->connectToHost(remote.host, remote.port);\n if (socket->waitForConnected(5000\/tries))\n {\n return socket;\n }\n }\n\n LOG_ERROR(QString(\"Unable to connect tcp socket in %3 tries to %1: %2\").arg(hostname).arg(socket->errorString()).arg(tries));\n }\n else\n {\n if (!testSocket->waitForReadyRead(5000))\n {\n LOG_ERROR(\"Remote did not answer for 5 sec, aborting connection.\");\n }\n else\n {\n \/\/ TODO: Read the first (empty) datagram\n QHostAddress packetHost;\n testSocket->readDatagram(0, 0, &packetHost);\n\n if (packetHost != QHostAddress(remote.host))\n {\n LOG_ERROR(\"Received connection packet from wrong host!\");\n }\n else\n {\n return socket;\n }\n }\n }\n\n delete socket;\n return NULL;\n}\n\nQTcpServer *NetworkManager::createServerSocket()\n{\n \/\/ TODO: Connect to traffic counter\n QTcpServer* server = new QTcpServer;\n return server;\n}\n\n#include \"networkmanager.moc\"\n<|endoftext|>"} {"text":"struct B { int i; };\nstruct D : public B {};\nint D::*dp = &D::i;\n\nMake test more interestingstruct B { int i, j; };\nstruct D : public B {};\nint D::*di = &D::i;\nint D::*dj = &D::j;\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\nnamespace CustomRunInThisContext {\n using v8::FunctionCallbackInfo;\n using v8::Local;\n using v8::Object;\n using v8::Script;\n using v8::ScriptCompiler;\n using v8::ScriptOrigin;\n using v8::String;\n using v8::TryCatch;\n using v8::UnboundScript;\n using v8::Value;\n using v8::MaybeLocal;\n\n static void RunInThisContextCached(const FunctionCallbackInfo& args) {\n if (!args[0]->IsString() || !args[1]->IsString()) {\n Nan::ThrowTypeError(\"Filename and script must be strings\");\n return;\n }\n\n Local code = args[0]->ToString(args.GetIsolate());\n Local filename = args[1]->ToString(args.GetIsolate());\n\n uint8_t *bufferData = nullptr;\n size_t bufferLength = 0;\n if (args[2]->IsObject()) {\n Local bufferObj = args[2]->ToObject();\n bufferData = reinterpret_cast(node::Buffer::Data(bufferObj));\n bufferLength = node::Buffer::Length(bufferObj);\n }\n\n auto cachedData = new ScriptCompiler::CachedData(bufferData, bufferLength);\n ScriptOrigin origin(filename);\n ScriptCompiler::Source source(code, origin, cachedData);\n MaybeLocal maybe_unbound_script = ScriptCompiler::CompileUnboundScript(\n args.GetIsolate(),\n &source,\n ScriptCompiler::CompileOptions::kConsumeCodeCache\n );\n\n Local unbound_script;\n if (!maybe_unbound_script.ToLocal(&unbound_script)) return;\n\n Nan::TryCatch try_catch;\n Local