text
stringlengths
54
60.6k
<commit_before>#include "Epatest.hpp" #include "src/set_manipulators.hpp" #include "src/jplace_util.hpp" #include "src/Range.hpp" #include <vector> #include <iostream> using namespace std; TEST(set_manipulators, find_collapse_equal_sequences) { // buildup MSA msa; msa.append(string("T"), string("AGCTAGCT")); msa.append(string("C"), string("AGCCAGCT")); msa.append(string("G"), string("AGCGAGCT")); msa.append(string("A"), string("AGCAAGCT")); msa.append(string("t1"), string("AGCTAGCT")); msa.append(string("c1"), string("AGCCAGCT")); msa.append(string("g1"), string("AGCGAGCT")); msa.append(string("a1"), string("AGCAAGCT")); msa.append(string("t2"), string("AGCTAGCT")); msa.append(string("c2"), string("AGCCAGCT")); // test find_collapse_equal_sequences(msa); EXPECT_EQ(msa.size(), 4); EXPECT_EQ(msa[0].header_list().size(), 3); EXPECT_EQ(msa[1].header_list().size(), 3); EXPECT_EQ(msa[2].header_list().size(), 2); EXPECT_EQ(msa[3].header_list().size(), 2); // for (auto &s : msa) // for (auto &head : s.header_list()) // cout << head << endl; } TEST(set_manipulators, get_valid_range) { string s1("---------GGGCCCGTAT-------");//(9,19) string s2("GGGCCCGTAT-------"); //(0,10) string s3("-GGGC---CCG-TAT"); //(1,15) Range r; r = get_valid_range(s1); EXPECT_EQ(r.begin, 9); EXPECT_EQ(r.span, 10); r = get_valid_range(s2); EXPECT_EQ(r.begin, 0); EXPECT_EQ(r.span, 10); r = get_valid_range(s3); EXPECT_EQ(r.begin, 1); EXPECT_EQ(r.span, 14); } TEST(set_manipulators, discard_bottom_x_percent) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a({0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}); vector<double> weights_b({0.01,0.02,0.005,0.002,0.94,0.003,0.02}); unsigned int num_expected[3] = {4,4,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_bottom_x_percent(sample, 0.5); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } } TEST(set_manipulators, discard_by_accumulated_threshold) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a({0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}); vector<double> weights_b({0.01,0.02,0.005,0.002,0.94,0.003,0.02}); unsigned int num_expected[3] = {5,2,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_by_accumulated_threshold(sample, 0.95); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } // string inv("blorp"); // cout << sample_to_jplace_string(sample, inv); } TEST(set_manipulators, discard_by_support_threshold) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a{0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}; vector<double> weights_b{0.01,0.02,0.005,0.002,0.94,0.003,0.02}; unsigned int num_expected[3] = {6,3,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_by_support_threshold(sample, 0.01); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } } <commit_msg>added test for merge sample function<commit_after>#include "Epatest.hpp" #include "src/set_manipulators.hpp" #include "src/jplace_util.hpp" #include "src/Range.hpp" #include <vector> #include <iostream> using namespace std; TEST(set_manipulators, merge_sample) { // setup Sample sample_1; Sample sample_2; unsigned int s_a = 0, s_b = 1, s_c = 2, s_d = 3; sample_1.emplace_back(s_a, 0); sample_1.back().emplace_back(1,-10,0.9,0.9); sample_1.emplace_back(s_b, 0); sample_1.back().emplace_back(2,-10,0.9,0.9); sample_1.emplace_back(s_c, 0); sample_1.back().emplace_back(3,-10,0.9,0.9); assert(sample_1.size() == 3); assert(sample_1[0].size() == 1); assert(sample_1[1].size() == 1); assert(sample_1[2].size() == 1); sample_2.emplace_back(s_c, 0); sample_2.back().emplace_back(1,-10,0.9,0.9); sample_2.emplace_back(s_b, 0); sample_2.back().emplace_back(0,-10,0.9,0.9); sample_2.emplace_back(s_d, 0); sample_2.back().emplace_back(3,-10,0.9,0.9); assert(sample_2.size() == 3); assert(sample_2[0].size() == 1); assert(sample_2[1].size() == 1); assert(sample_2[2].size() == 1); merge(sample_1, sample_2); EXPECT_EQ(sample_1.size(), 4); EXPECT_EQ(sample_1[0].size(), 1); EXPECT_EQ(sample_1[1].size(), 2); EXPECT_EQ(sample_1[2].size(), 2); EXPECT_EQ(sample_1[3].size(), 1); } TEST(set_manipulators, find_collapse_equal_sequences) { // buildup MSA msa; msa.append(string("T"), string("AGCTAGCT")); msa.append(string("C"), string("AGCCAGCT")); msa.append(string("G"), string("AGCGAGCT")); msa.append(string("A"), string("AGCAAGCT")); msa.append(string("t1"), string("AGCTAGCT")); msa.append(string("c1"), string("AGCCAGCT")); msa.append(string("g1"), string("AGCGAGCT")); msa.append(string("a1"), string("AGCAAGCT")); msa.append(string("t2"), string("AGCTAGCT")); msa.append(string("c2"), string("AGCCAGCT")); // test find_collapse_equal_sequences(msa); EXPECT_EQ(msa.size(), 4); EXPECT_EQ(msa[0].header_list().size(), 3); EXPECT_EQ(msa[1].header_list().size(), 3); EXPECT_EQ(msa[2].header_list().size(), 2); EXPECT_EQ(msa[3].header_list().size(), 2); // for (auto &s : msa) // for (auto &head : s.header_list()) // cout << head << endl; } TEST(set_manipulators, get_valid_range) { string s1("---------GGGCCCGTAT-------");//(9,19) string s2("GGGCCCGTAT-------"); //(0,10) string s3("-GGGC---CCG-TAT"); //(1,15) Range r; r = get_valid_range(s1); EXPECT_EQ(r.begin, 9); EXPECT_EQ(r.span, 10); r = get_valid_range(s2); EXPECT_EQ(r.begin, 0); EXPECT_EQ(r.span, 10); r = get_valid_range(s3); EXPECT_EQ(r.begin, 1); EXPECT_EQ(r.span, 14); } TEST(set_manipulators, discard_bottom_x_percent) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a({0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}); vector<double> weights_b({0.01,0.02,0.005,0.002,0.94,0.003,0.02}); unsigned int num_expected[3] = {4,4,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_bottom_x_percent(sample, 0.5); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } } TEST(set_manipulators, discard_by_accumulated_threshold) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a({0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}); vector<double> weights_b({0.01,0.02,0.005,0.002,0.94,0.003,0.02}); unsigned int num_expected[3] = {5,2,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_by_accumulated_threshold(sample, 0.95); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } // string inv("blorp"); // cout << sample_to_jplace_string(sample, inv); } TEST(set_manipulators, discard_by_support_threshold) { // setup Sample sample; unsigned int s_a = 0, s_b = 1, s_c = 2; sample.emplace_back(s_a, 0); vector<double> weights_a{0.001,0.23,0.05,0.02,0.4,0.009,0.2,0.09}; vector<double> weights_b{0.01,0.02,0.005,0.002,0.94,0.003,0.02}; unsigned int num_expected[3] = {6,3,1}; for (auto n : weights_a) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_b, 0); for (auto n : weights_b) { sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(n); } sample.emplace_back(s_c, 0); sample.back().emplace_back(1,-10,0.9,0.9); sample.back().back().lwr(1.0); // tests discard_by_support_threshold(sample, 0.01); int i =0; for (auto pq : sample) { unsigned int num = 0; for (auto p : pq) { (void)p; num++; } EXPECT_EQ(num, num_expected[i++]); } } <|endoftext|>
<commit_before>/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ (test suite) | | |__ | | | | | | version 2.1.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "catch.hpp" #define private public #include "json.hpp" using nlohmann::json; TEST_CASE("lexer class") { SECTION("scan") { SECTION("structural characters") { CHECK((json::lexer("[", 1).scan() == json::lexer::token_type::begin_array)); CHECK((json::lexer("]", 1).scan() == json::lexer::token_type::end_array)); CHECK((json::lexer("{", 1).scan() == json::lexer::token_type::begin_object)); CHECK((json::lexer("}", 1).scan() == json::lexer::token_type::end_object)); CHECK((json::lexer(",", 1).scan() == json::lexer::token_type::value_separator)); CHECK((json::lexer(":", 1).scan() == json::lexer::token_type::name_separator)); } SECTION("literal names") { CHECK((json::lexer("null", 4).scan() == json::lexer::token_type::literal_null)); CHECK((json::lexer("true", 4).scan() == json::lexer::token_type::literal_true)); CHECK((json::lexer("false", 5).scan() == json::lexer::token_type::literal_false)); } SECTION("numbers") { CHECK((json::lexer("0", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("1", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("2", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("3", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("4", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("5", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("6", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("7", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("8", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("9", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("-0", 2).scan() == json::lexer::token_type::value_integer)); CHECK((json::lexer("-1", 2).scan() == json::lexer::token_type::value_integer)); CHECK((json::lexer("1.1", 3).scan() == json::lexer::token_type::value_float)); CHECK((json::lexer("-1.1", 4).scan() == json::lexer::token_type::value_float)); CHECK((json::lexer("1E10", 4).scan() == json::lexer::token_type::value_float)); } SECTION("whitespace") { // result is end_of_input, because not token is following CHECK((json::lexer(" ", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\t", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\n", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\r", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer(" \t\n\r\n\t ", 7).scan() == json::lexer::token_type::end_of_input)); } } SECTION("token_type_name") { CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::uninitialized)) == "<uninitialized>")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::literal_true)) == "true literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::literal_false)) == "false literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::literal_null)) == "null literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::value_string)) == "string literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::value_unsigned)) == "number literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::value_integer)) == "number literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::value_float)) == "number literal")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::begin_array)) == "'['")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::begin_object)) == "'{'")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::end_array)) == "']'")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::end_object)) == "'}'")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::name_separator)) == "':'")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::value_separator)) == "','")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::parse_error)) == "<parse error>")); CHECK((json::lexer::token_type_name(std::string(json::lexer::token_type::end_of_input)) == "end of input")); } SECTION("parse errors on first character") { for (int c = 1; c < 128; ++c) { // create string from the ASCII code const auto s = std::string(1, static_cast<char>(c)); // store scan() result const auto res = json::lexer(s.c_str(), 1).scan(); switch (c) { // single characters that are valid tokens case ('['): case (']'): case ('{'): case ('}'): case (','): case (':'): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): { CHECK((res != json::lexer::token_type::parse_error)); break; } // whitespace case (' '): case ('\t'): case ('\n'): case ('\r'): { CHECK((res == json::lexer::token_type::end_of_input)); break; } // anything else is not expected default: { CHECK((res == json::lexer::token_type::parse_error)); break; } } } } /* NOTE: to_unicode function has been removed SECTION("to_unicode") { // lexer to call to_unicode on json::lexer dummy_lexer("", 0); CHECK(dummy_lexer.to_unicode(0x1F4A9) == "💩"); CHECK_THROWS_AS(dummy_lexer.to_unicode(0x200000), json::parse_error); CHECK_THROWS_WITH(dummy_lexer.to_unicode(0x200000), "[json.exception.parse_error.103] parse error: code points above 0x10FFFF are invalid"); } */ } <commit_msg>:hammer: fixed test case<commit_after>/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ (test suite) | | |__ | | | | | | version 2.1.1 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. Copyright (c) 2013-2017 Niels Lohmann <http://nlohmann.me>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "catch.hpp" #define private public #include "json.hpp" using nlohmann::json; TEST_CASE("lexer class") { SECTION("scan") { SECTION("structural characters") { CHECK((json::lexer("[", 1).scan() == json::lexer::token_type::begin_array)); CHECK((json::lexer("]", 1).scan() == json::lexer::token_type::end_array)); CHECK((json::lexer("{", 1).scan() == json::lexer::token_type::begin_object)); CHECK((json::lexer("}", 1).scan() == json::lexer::token_type::end_object)); CHECK((json::lexer(",", 1).scan() == json::lexer::token_type::value_separator)); CHECK((json::lexer(":", 1).scan() == json::lexer::token_type::name_separator)); } SECTION("literal names") { CHECK((json::lexer("null", 4).scan() == json::lexer::token_type::literal_null)); CHECK((json::lexer("true", 4).scan() == json::lexer::token_type::literal_true)); CHECK((json::lexer("false", 5).scan() == json::lexer::token_type::literal_false)); } SECTION("numbers") { CHECK((json::lexer("0", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("1", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("2", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("3", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("4", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("5", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("6", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("7", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("8", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("9", 1).scan() == json::lexer::token_type::value_unsigned)); CHECK((json::lexer("-0", 2).scan() == json::lexer::token_type::value_integer)); CHECK((json::lexer("-1", 2).scan() == json::lexer::token_type::value_integer)); CHECK((json::lexer("1.1", 3).scan() == json::lexer::token_type::value_float)); CHECK((json::lexer("-1.1", 4).scan() == json::lexer::token_type::value_float)); CHECK((json::lexer("1E10", 4).scan() == json::lexer::token_type::value_float)); } SECTION("whitespace") { // result is end_of_input, because not token is following CHECK((json::lexer(" ", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\t", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\n", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer("\r", 1).scan() == json::lexer::token_type::end_of_input)); CHECK((json::lexer(" \t\n\r\n\t ", 7).scan() == json::lexer::token_type::end_of_input)); } } SECTION("token_type_name") { CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::uninitialized)) == "<uninitialized>")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::literal_true)) == "true literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::literal_false)) == "false literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::literal_null)) == "null literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::value_string)) == "string literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::value_unsigned)) == "number literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::value_integer)) == "number literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::value_float)) == "number literal")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::begin_array)) == "'['")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::begin_object)) == "'{'")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::end_array)) == "']'")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::end_object)) == "'}'")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::name_separator)) == "':'")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::value_separator)) == "','")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::parse_error)) == "<parse error>")); CHECK((std::string(json::lexer::token_type_name(json::lexer::token_type::end_of_input)) == "end of input")); } SECTION("parse errors on first character") { for (int c = 1; c < 128; ++c) { // create string from the ASCII code const auto s = std::string(1, static_cast<char>(c)); // store scan() result const auto res = json::lexer(s.c_str(), 1).scan(); switch (c) { // single characters that are valid tokens case ('['): case (']'): case ('{'): case ('}'): case (','): case (':'): case ('0'): case ('1'): case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): { CHECK((res != json::lexer::token_type::parse_error)); break; } // whitespace case (' '): case ('\t'): case ('\n'): case ('\r'): { CHECK((res == json::lexer::token_type::end_of_input)); break; } // anything else is not expected default: { CHECK((res == json::lexer::token_type::parse_error)); break; } } } } /* NOTE: to_unicode function has been removed SECTION("to_unicode") { // lexer to call to_unicode on json::lexer dummy_lexer("", 0); CHECK(dummy_lexer.to_unicode(0x1F4A9) == "💩"); CHECK_THROWS_AS(dummy_lexer.to_unicode(0x200000), json::parse_error); CHECK_THROWS_WITH(dummy_lexer.to_unicode(0x200000), "[json.exception.parse_error.103] parse error: code points above 0x10FFFF are invalid"); } */ } <|endoftext|>
<commit_before>/**********************************************************\ This file is distributed under the MIT License. See accompanying file LICENSE for details. tests/SpeedMapTester.cpp \**********************************************************/ #include "TestSettings.h" #ifdef TEST_SPEED_MAP #include "../../momo/stdish/unordered_map.h" #include "../../momo/stdish/map.h" #include "../../momo/stdish/pool_allocator.h" #include "../../momo/details/HashBucketLim4.h" #include <string> #include <iostream> #include <sstream> #include <chrono> #include <unordered_map> #include <map> #include <random> class SpeedMapTesterKey { public: SpeedMapTesterKey(SpeedMapTesterKey* ptr, uint32_t value) MOMO_NOEXCEPT : mPtr(ptr), mValue(value) { } uint32_t GetPtrValue() const MOMO_NOEXCEPT { return mPtr->mValue; } bool operator==(const SpeedMapTesterKey& key) const MOMO_NOEXCEPT { return GetPtrValue() == key.GetPtrValue(); } bool operator<(const SpeedMapTesterKey& key) const MOMO_NOEXCEPT { return GetPtrValue() < key.GetPtrValue(); } friend void swap(SpeedMapTesterKey& key1, SpeedMapTesterKey& key2) MOMO_NOEXCEPT { std::swap(key1.mPtr, key2.mPtr); } private: SpeedMapTesterKey* mPtr; uint32_t mValue; }; namespace std { template<> struct hash<SpeedMapTesterKey> { size_t operator()(const SpeedMapTesterKey& key) const MOMO_NOEXCEPT { return std::hash<uint32_t>()(key.GetPtrValue()); } }; } template<typename TKey> class SpeedMapTester { public: typedef TKey Key; private: class Timer { private: #if defined(_MSC_VER) && _MSC_VER < 1900 typedef std::chrono::system_clock Clock; #else typedef std::chrono::steady_clock Clock; #endif public: Timer(const std::string& title, std::ostream& stream) : mStream(stream) { mStream << title << std::flush; mStartTime = Clock::now(); } ~Timer() { auto diff = Clock::now() - mStartTime; auto count = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count(); mStream << count << std::endl; } private: std::ostream& mStream; std::chrono::time_point<Clock> mStartTime; }; public: explicit SpeedMapTester(size_t count, std::ostream& stream = std::cout); template<typename Allocator> void TestStdUnorderedMap(const std::string& mapTitle) { typedef std::unordered_map<Key, uint32_t, std::hash<Key>, std::equal_to<Key>, Allocator> Map; pvTestMap<Map>(mapTitle); } template<typename HashBucket> void TestHashMap(const std::string& mapTitle) { typedef momo::stdish::unordered_map<Key, uint32_t, std::hash<Key>, std::equal_to<Key>, std::allocator<std::pair<const Key, uint32_t>>, momo::HashMap<Key, uint32_t, momo::HashTraitsStd<Key, std::hash<Key>, std::equal_to<Key>, HashBucket>>> Map; pvTestMap<Map>(mapTitle); } template<typename Allocator> void TestStdMap(const std::string& mapTitle) { typedef std::map<Key, uint32_t, std::less<Key>, Allocator> Map; pvTestMap<Map>(mapTitle); } template<typename TreeNode> void TestTreeMap(const std::string& mapTitle) { typedef momo::stdish::map<Key, uint32_t, std::less<Key>, std::allocator<std::pair<const Key, uint32_t>>, momo::TreeMap<Key, uint32_t, momo::TreeTraitsStd<Key, std::less<Key>, TreeNode>>> Map; pvTestMap<Map>(mapTitle); } void TestAll() { TestStdUnorderedMap<std::allocator<std::pair<const Key, uint32_t>>>("std::unordered_map"); TestHashMap<momo::HashBucketLimP<>>("HashMapLimP"); TestHashMap<momo::HashBucketOneI1>("HashMapOneI1"); //TestHashMap<momo::HashBucketLimP1<>>("HashMapLimP1"); //TestHashMap<momo::HashBucketUnlimP<>>("HashMapUnlimP"); //TestHashMap<momo::HashBucketLim4<>>("HashMapLim4"); TestStdMap<momo::stdish::pool_allocator<std::pair<const Key, uint32_t>>>("std::map + pool_allocator"); TestTreeMap<momo::TreeNode<32, 4, momo::MemPoolParams<>, true>>("TreeNodeSwp"); TestTreeMap<momo::TreeNode<32, 4, momo::MemPoolParams<>, false>>("TreeNodePrm"); } private: template<typename Map> void pvTestMap(const std::string& mapTitle) { Map map; std::mt19937 mt; { Timer timer(mapTitle + " insert: ", mStream); for (const Key& key : mKeys) map[key] = 0; } std::shuffle(mKeys.GetBegin(), mKeys.GetEnd(), mt); { Timer timer(mapTitle + " find: ", mStream); for (const Key& key : mKeys) map[key] = 0; } std::shuffle(mKeys.GetBegin(), mKeys.GetEnd(), mt); { Timer timer(mapTitle + " erase: ", mStream); for (const Key& key : mKeys) map.erase(key); } } private: momo::Array<Key> mKeys; std::ostream& mStream; }; template<> SpeedMapTester<SpeedMapTesterKey>::SpeedMapTester(size_t count, std::ostream& stream) : mStream(stream) { std::mt19937 mt; mKeys.Reserve(count); for (size_t i = 0; i < count; ++i) mKeys.AddBack(SpeedMapTesterKey(mKeys.GetItems() + i, mt())); std::shuffle(mKeys.GetBegin(), mKeys.GetEnd(), mt); } template<> SpeedMapTester<uint32_t>::SpeedMapTester(size_t count, std::ostream& stream) : mStream(stream) { std::mt19937 mt; mKeys.Reserve(count); for (size_t i = 0; i < count; ++i) mKeys.AddBack(mt()); } template<> SpeedMapTester<std::string>::SpeedMapTester(size_t count, std::ostream& stream) : mStream(stream) { std::mt19937 mt; mKeys.Reserve(count); for (size_t i = 0; i < count; ++i) { std::stringstream sstream; sstream << mt(); mKeys.AddBack(sstream.str()); } } void TestSpeedMap() { #ifdef NDEBUG const size_t count = 1 << 21; #else const size_t count = 1 << 12; #endif SpeedMapTester<SpeedMapTesterKey> speedMapTester(count, std::cout); //SpeedMapTester<uint32_t> speedMapTester(count, std::cout); //SpeedMapTester<std::string> speedMapTester(count, std::cout); for (size_t i = 0; i < 3; ++i) { std::cout << std::endl; speedMapTester.TestAll(); } } static int testSpeedMap = (TestSpeedMap(), 0); #endif // TEST_SPEED_MAP <commit_msg>SpeedMapTester<commit_after>/**********************************************************\ This file is distributed under the MIT License. See accompanying file LICENSE for details. tests/SpeedMapTester.cpp \**********************************************************/ #include "TestSettings.h" #ifdef TEST_SPEED_MAP #include "../../momo/stdish/unordered_map.h" #include "../../momo/stdish/map.h" #include "../../momo/stdish/pool_allocator.h" #include "../../momo/details/HashBucketLim4.h" #include <string> #include <iostream> #include <sstream> #include <chrono> #include <unordered_map> #include <map> #include <random> class SpeedMapKey { public: explicit SpeedMapKey(uint32_t* ptr) MOMO_NOEXCEPT : mPtr(ptr) { } uint32_t GetInt() const MOMO_NOEXCEPT { return *mPtr; } bool operator==(const SpeedMapKey& key) const MOMO_NOEXCEPT { return GetInt() == key.GetInt(); } bool operator<(const SpeedMapKey& key) const MOMO_NOEXCEPT { return GetInt() < key.GetInt(); } private: uint32_t* mPtr; }; namespace std { template<> struct hash<SpeedMapKey> { size_t operator()(const SpeedMapKey& key) const MOMO_NOEXCEPT { return std::hash<uint32_t>()(key.GetInt()); } }; } template<typename Key> class SpeedMapKeys; template<> class SpeedMapKeys<SpeedMapKey> : public momo::Array<SpeedMapKey> { public: SpeedMapKeys(size_t count, std::mt19937& random) { mInts.Reserve(count); Reserve(count); for (size_t i = 0; i < count; ++i) { mInts.AddBackNogrow(random()); AddBackNogrow(SpeedMapKey(mInts.GetItems() + i)); } std::shuffle(GetBegin(), GetEnd(), random); } private: momo::Array<uint32_t> mInts; }; template<> class SpeedMapKeys<uint32_t> : public momo::Array<uint32_t> { public: SpeedMapKeys(size_t count, std::mt19937& random) { Reserve(count); for (size_t i = 0; i < count; ++i) AddBackNogrow(random()); } }; template<> class SpeedMapKeys<std::string> : public momo::Array<std::string> { public: SpeedMapKeys(size_t count, std::mt19937& random) { Reserve(count); for (size_t i = 0; i < count; ++i) { std::stringstream sstream; sstream << random(); AddBackNogrow(sstream.str()); } } }; template<typename TKey> class SpeedMapTester { public: typedef TKey Key; typedef uint32_t Value; typedef SpeedMapKeys<Key> Keys; private: class Timer { private: #if defined(_MSC_VER) && _MSC_VER < 1900 typedef std::chrono::system_clock Clock; #else typedef std::chrono::steady_clock Clock; #endif public: Timer(const std::string& title, std::ostream& stream) : mStream(stream) { mStream << title << std::flush; mStartTime = Clock::now(); } ~Timer() { auto diff = Clock::now() - mStartTime; auto count = std::chrono::duration_cast<std::chrono::milliseconds>(diff).count(); mStream << count << std::endl; } private: std::ostream& mStream; std::chrono::time_point<Clock> mStartTime; }; public: explicit SpeedMapTester(size_t count, std::ostream& stream = std::cout) : mRandom(), mKeys(count, mRandom), mStream(stream) { } template<typename Allocator> void TestStdUnorderedMap(const std::string& mapTitle) { typedef std::unordered_map<Key, Value, std::hash<Key>, std::equal_to<Key>, Allocator> Map; pvTestMap<Map>(mapTitle); } template<typename HashBucket> void TestHashMap(const std::string& mapTitle) { typedef momo::stdish::unordered_map<Key, Value, std::hash<Key>, std::equal_to<Key>, std::allocator<std::pair<const Key, Value>>, momo::HashMap<Key, Value, momo::HashTraitsStd<Key, std::hash<Key>, std::equal_to<Key>, HashBucket>>> Map; pvTestMap<Map>(mapTitle); } template<typename Allocator> void TestStdMap(const std::string& mapTitle) { typedef std::map<Key, Value, std::less<Key>, Allocator> Map; pvTestMap<Map>(mapTitle); } template<typename TreeNode> void TestTreeMap(const std::string& mapTitle) { typedef momo::stdish::map<Key, Value, std::less<Key>, std::allocator<std::pair<const Key, Value>>, momo::TreeMap<Key, Value, momo::TreeTraitsStd<Key, std::less<Key>, TreeNode>>> Map; pvTestMap<Map>(mapTitle); } void TestAll() { TestStdUnorderedMap<std::allocator<std::pair<const Key, Value>>>("std::unordered_map"); TestHashMap<momo::HashBucketLimP<>>("HashMapLimP"); TestHashMap<momo::HashBucketOneI1>("HashMapOneI1"); //TestHashMap<momo::HashBucketLimP1<>>("HashMapLimP1"); //TestHashMap<momo::HashBucketUnlimP<>>("HashMapUnlimP"); //TestHashMap<momo::HashBucketLim4<>>("HashMapLim4"); TestStdMap<momo::stdish::pool_allocator<std::pair<const Key, Value>>>("std::map + pool_allocator"); TestTreeMap<momo::TreeNode<32, 4, momo::MemPoolParams<>, true>>("TreeNodeSwp"); TestTreeMap<momo::TreeNode<32, 4, momo::MemPoolParams<>, false>>("TreeNodePrm"); } private: template<typename Map> void pvTestMap(const std::string& mapTitle) { Map map; { Timer timer(mapTitle + " insert: ", mStream); for (const Key& key : mKeys) map[key] = 0; } std::shuffle(mKeys.GetBegin(), mKeys.GetEnd(), mRandom); { Timer timer(mapTitle + " find: ", mStream); for (const Key& key : mKeys) map[key] = 0; } std::shuffle(mKeys.GetBegin(), mKeys.GetEnd(), mRandom); { Timer timer(mapTitle + " erase: ", mStream); for (const Key& key : mKeys) map.erase(key); } } private: std::mt19937 mRandom; Keys mKeys; std::ostream& mStream; }; void TestSpeedMap() { #ifdef NDEBUG const size_t count = 1 << 21; #else const size_t count = 1 << 12; #endif SpeedMapTester<SpeedMapKey> speedMapTester(count); //SpeedMapTester<uint32_t> speedMapTester(count); //SpeedMapTester<std::string> speedMapTester(count); for (size_t i = 0; i < 3; ++i) { std::cout << std::endl; speedMapTester.TestAll(); } } static int testSpeedMap = (TestSpeedMap(), 0); #endif // TEST_SPEED_MAP <|endoftext|>
<commit_before>#define DEBUG 1 /** * File : B2.cpp * Author : Kazune Takahashi * Created : 11/24/2019, 3:04:17 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- UnionFind ----- class UnionFind { int N; vector<int> par; public: UnionFind() : N{0} {} UnionFind(int N) : N{N}, par(N, -1) {} bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; return true; } int size(int x) { return -par[root(x)]; } int count_parts() { int ans{0}; for (auto i = 0; i < N; i++) { if (root(i) < 0) { ++ans; } } return ans; } private: int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } }; // ----- main() ----- vector<int> rev(vector<int> const &P) { vector<int> Q(P.size()); for (auto i = 0; i < static_cast<int>(P.size()); i++) { Q[P[i]] = i; } return Q; } void flush(int N, int K, UnionFind &uf) { if (uf.size(N - K + 1) == 1) { cout << uf.count_parts() - 1 << endl; } else { cout << uf.count_parts() << endl; } } vector<int> ascend_sum(int N, int K, vector<int> const &P) { vector<int> ascend(N - 1); for (auto i = 0; i < N - 1; i++) { ascend[i] = P[i] < P[i + 1] ? 0 : 1; } vector<int> res(N, 0); for (auto i = 1; i < N; i++) { res[i] = res[i - 1] + ascend[i - 1]; } return res; } void connect_origin(int N, int K, vector<int> const &P, UnionFind &uf) { vector<int> A{ascend_sum(N, K, P)}; #if DEBUG == 1 for (auto i = 0; i < N; i++) { cerr << "A[" << i << "] = " << A[i] << endl; } #endif for (auto i = 0; i <= N - K; i++) { if (A[i + K] - A[i] == 0) { uf.merge(i, N - K + 1); } } } vector<bool> is_mini(int N, int K, vector<int> const &Q) { vector<bool> res(N, false); set<int> S; for (auto e : Q) { S.insert(e); if (0 <= e && e <= N - K - 1) { auto it{S.find(e)}; ++it; if (it == S.end() || *it - e > K) { res[e] = true; } } } return res; } vector<bool> is_maxi(int N, int K, vector<int> const &Q) { vector<bool> res(N, false); set<int> S; for (auto e : Q) { S.insert(e); if (K <= e && e <= N - 1) { auto it{S.find(e)}; auto it0{it}; --it0; if (it == S.begin() || e - *it0 > K) { res[e] = true; } } } return res; } void connect_adjacent(int N, int K, vector<int> const &P, UnionFind &uf) { vector<int> Q{rev(P)}; vector<int> R(Q); reverse(R.begin(), R.end()); vector<bool> mini{is_mini(N, K, Q)}, maxi{is_maxi(N, K, R)}; for (auto i = 0; i < N - K; i++) { if (mini[i] && maxi[i + K]) { uf.merge(i, i + 1); } } } int main() { int N, K; cin >> N >> K; vector<int> P(N); for (auto i = 0; i < N; i++) { cin >> P[i]; } UnionFind uf(N - K + 2); // the node N - K + 1 is origin. connect_origin(N, K, P, uf); connect_adjacent(N, K, P, uf); flush(N, K, uf); } <commit_msg>tried B2.cpp to 'B'<commit_after>#define DEBUG 1 /** * File : B2.cpp * Author : Kazune Takahashi * Created : 11/24/2019, 3:04:17 PM * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> #include <algorithm> #include <vector> #include <string> #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> #include <set> #include <unordered_map> #include <unordered_set> #include <bitset> #include <functional> #include <random> #include <chrono> #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> // ----- boost ----- #include <boost/rational.hpp> // ----- using directives and manipulations ----- using boost::rational; using namespace std; using ll = long long; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{x % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator==(const Mint &a) const { return x == a.x; } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } // ----- UnionFind ----- class UnionFind { int N; vector<int> par; public: UnionFind() : N{0} {} UnionFind(int N) : N{N}, par(N, -1) {} bool is_same(int x, int y) { return root(x) == root(y); } bool merge(int x, int y) { x = root(x); y = root(y); if (x == y) { return false; } if (par[x] > par[y]) { swap(x, y); } par[x] += par[y]; par[y] = x; #if DEBUG == 1 cerr << "merge(" << x << ", " << y << ")" << endl; #endif return true; } int size(int x) { return -par[root(x)]; } int count_parts() { int ans{0}; for (auto i = 0; i < N; i++) { if (root(i) < 0) { ++ans; } } return ans; } private: int root(int x) { if (par[x] < 0) { return x; } return par[x] = root(par[x]); } }; // ----- main() ----- vector<int> rev(vector<int> const &P) { vector<int> Q(P.size()); for (auto i = 0; i < static_cast<int>(P.size()); i++) { Q[P[i]] = i; } return Q; } void flush(int N, int K, UnionFind &uf) { if (uf.size(N - K + 1) == 1) { cout << uf.count_parts() - 1 << endl; } else { cout << uf.count_parts() << endl; } } vector<int> ascend_sum(int N, int K, vector<int> const &P) { vector<int> ascend(N - 1); for (auto i = 0; i < N - 1; i++) { ascend[i] = P[i] < P[i + 1] ? 0 : 1; } vector<int> res(N, 0); for (auto i = 1; i < N; i++) { res[i] = res[i - 1] + ascend[i - 1]; } return res; } void connect_origin(int N, int K, vector<int> const &P, UnionFind &uf) { vector<int> A{ascend_sum(N, K, P)}; for (auto i = 0; i <= N - K; i++) { if (A[i + K] - A[i] == 0) { uf.merge(i, N - K + 1); } } } vector<bool> is_mini(int N, int K, vector<int> const &Q) { vector<bool> res(N, false); set<int> S; for (auto e : Q) { S.insert(e); if (0 <= e && e <= N - K - 1) { auto it{S.find(e)}; ++it; if (it == S.end() || *it - e > K) { res[e] = true; } } } return res; } vector<bool> is_maxi(int N, int K, vector<int> const &Q) { vector<bool> res(N, false); set<int> S; for (auto e : Q) { S.insert(e); if (K <= e && e <= N - 1) { auto it{S.find(e)}; auto it0{it}; --it0; if (it == S.begin() || e - *it0 > K) { res[e] = true; } } } return res; } void connect_adjacent(int N, int K, vector<int> const &P, UnionFind &uf) { vector<int> Q{rev(P)}; vector<int> R(Q); reverse(R.begin(), R.end()); vector<bool> mini{is_mini(N, K, Q)}, maxi{is_maxi(N, K, R)}; for (auto i = 0; i < N - K; i++) { if (mini[i] && maxi[i + K]) { uf.merge(i, i + 1); } } } int main() { int N, K; cin >> N >> K; vector<int> P(N); for (auto i = 0; i < N; i++) { cin >> P[i]; } UnionFind uf(N - K + 2); // the node N - K + 1 is origin. connect_origin(N, K, P, uf); connect_adjacent(N, K, P, uf); flush(N, K, uf); } <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /*! * \file tstCommIndexer.cpp * \author Stuart Slattery * \date Wed May 25 12:36:14 2011 * \brief CommIndexer class unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <DTK_CommIndexer.hpp> #include "Teuchos_UnitTestHarness.hpp" #include "Teuchos_RCP.hpp" #include "Teuchos_ArrayView.hpp" #include "Teuchos_DefaultComm.hpp" #include "Teuchos_CommHelpers.hpp" //---------------------------------------------------------------------------// // HELPER FUNCTIONS //---------------------------------------------------------------------------// // Get the default communicator. template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, duplicate_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); RCP_Comm local_comm = global_comm->duplicate(); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, split_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); int rank = global_comm->getRank(); RCP_Comm local_comm = global_comm->split( 0, rank ); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, inverse_split_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); int inverse_rank = global_comm->getSize() - global_comm->getRank() - 1; RCP_Comm local_comm = global_comm->split( 0, inverse_rank); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, subcommunicator_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); std::vector<int> sub_ranks; for ( int n = 0; n < global_comm->getSize(); ++n ) { if ( n % 2 == 0 ) { sub_ranks.push_back(n); } } Teuchos::ArrayView<int> sub_ranks_view( sub_ranks ); RCP_Comm local_comm = global_comm->createSubcommunicator( sub_ranks_view ); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); if ( global_comm->getRank() % 2 == 0 ) { TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } else { TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == -1 ); } } //---------------------------------------------------------------------------// // end of tstCommIndexer.cpp //---------------------------------------------------------------------------// <commit_msg>fixing parallel failure in comm indexer test<commit_after>//----------------------------------*-C++-*----------------------------------// /*! * \file tstCommIndexer.cpp * \author Stuart Slattery * \date Wed May 25 12:36:14 2011 * \brief CommIndexer class unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <cmath> #include <sstream> #include <DTK_CommIndexer.hpp> #include "Teuchos_UnitTestHarness.hpp" #include "Teuchos_RCP.hpp" #include "Teuchos_ArrayView.hpp" #include "Teuchos_DefaultComm.hpp" #include "Teuchos_CommHelpers.hpp" //---------------------------------------------------------------------------// // HELPER FUNCTIONS //---------------------------------------------------------------------------// // Get the default communicator. template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, duplicate_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); RCP_Comm local_comm = global_comm->duplicate(); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, split_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); int rank = global_comm->getRank(); RCP_Comm local_comm = global_comm->split( 0, rank ); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, inverse_split_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); int inverse_rank = global_comm->getSize() - global_comm->getRank() - 1; RCP_Comm local_comm = global_comm->split( 0, inverse_rank); CommIndexer indexer( global_comm, local_comm ); TEST_ASSERT( (int) indexer.size() == local_comm->getSize() ); TEST_ASSERT( indexer.l2g( local_comm->getRank() ) == global_comm->getRank() ); } //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( CommIndexer, subcommunicator_test ) { using namespace DataTransferKit; typedef Teuchos::RCP<const Teuchos::Comm<int> > RCP_Comm; RCP_Comm global_comm = getDefaultComm<int>(); std::vector<int> sub_ranks; for ( int n = 0; n < global_comm->getSize(); ++n ) { if ( n % 2 == 0 ) { sub_ranks.push_back(n); } } RCP_Comm local_comm = global_comm->createSubcommunicator( sub_ranks() ); CommIndexer indexer( global_comm, local_comm ); if ( global_comm->getRank() % 2 == 0 ) { TEST_ASSERT( Teuchos::nonnull(local_comm) ); TEST_EQUALITY( (int) indexer.size(), local_comm->getSize() ); TEST_EQUALITY( indexer.l2g( local_comm->getRank() ), global_comm->getRank() ); } else { TEST_ASSERT( Teuchos::is_null(local_comm) ); } TEST_EQUALITY( indexer.l2g(-32), -1 ); } //---------------------------------------------------------------------------// // end of tstCommIndexer.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before> #ifdef SK_DEVELOPER #include "SampleCode.h" #include "SkOSMenu.h" #include "DebuggerViews.h" static const char gIsDebuggerQuery[] = "is-debugger"; class DebuggerView : public SampleView { public: DebuggerView(const char* data, size_t size) { fData.append(size, data); fCommandsVisible = true; fCommandsResizing = false; fStateVisible = true; fStateResizing = false; fCommands = new DebuggerCommandsView; fCommands->setVisibleP(fCommandsVisible); this->attachChildToFront(fCommands)->unref(); fState = new DebuggerStateView; fState->setVisibleP(fStateVisible); this->attachChildToFront(fState)->unref(); fAtomsToRead = 0; fDisplayClip = false; fDumper = new SkDebugDumper(this->getSinkID(), fCommands->getSinkID(), fState->getSinkID()); fDumper->unload(); fAtomBounds.reset(); fFrameBounds.reset(); SkDumpCanvas* dumpCanvas = new SkDumpCanvas(fDumper); SkGPipeReader* dumpReader = new SkGPipeReader(dumpCanvas); if (size > 0) { int offset = 0; int frameBound = 0; size_t bytesRead; while (static_cast<unsigned>(offset) < size) { SkGPipeReader::Status s = dumpReader->playback(data + offset, size - offset, SkGPipeReader::kReadAtom_PlaybackFlag, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); offset += bytesRead; if (SkGPipeReader::kDone_Status == s) { fDumper->dump(dumpCanvas, SkDumpCanvas::kNULL_Verb, "End of Frame", NULL); delete dumpReader; delete dumpCanvas; dumpCanvas = new SkDumpCanvas(fDumper); dumpReader = new SkGPipeReader(dumpCanvas); frameBound = offset; } fAtomBounds.append(1, &offset); fFrameBounds.append(1, &frameBound); } } delete dumpReader; delete dumpCanvas; fDumper->load(); } ~DebuggerView() { fAtomBounds.reset(); fFrameBounds.reset(); delete fDumper; } virtual void requestMenu(SkOSMenu* menu) { menu->setTitle("Debugger"); menu->appendSwitch("Show Commands", "Commands", this->getSinkID(), fCommandsVisible); menu->appendSwitch("Show State", "State", this->getSinkID(), fStateVisible); menu->appendSwitch("Display Clip", "Clip", this->getSinkID(), fDisplayClip); } void goToAtom(int atom) { if (atom != fAtomsToRead) { fAtomsToRead = atom; this->inval(NULL); } } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Debugger"); return true; } if (evt->isType(gIsDebuggerQuery)) { return true; } return this->INHERITED::onQuery(evt); } virtual bool onEvent(const SkEvent& evt) { if (SkOSMenu::FindSwitchState(evt, "Commands", &fCommandsVisible) || SkOSMenu::FindSwitchState(evt, "State", &fStateVisible)) { fCommands->setVisibleP(fCommandsVisible); fState->setVisibleP(fStateVisible); fStateOffset = (fCommandsVisible) ? fCommands->width() : 0; fState->setSize(this->width() - fStateOffset, fState->height()); fState->setLoc(fStateOffset, this->height() - fState->height()); this->inval(NULL); return true; } if (SkOSMenu::FindSwitchState(evt, "Clip", &fDisplayClip)) { this->inval(NULL); return true; } return this->INHERITED::onEvent(evt); } virtual void onDrawContent(SkCanvas* canvas) { if (fData.count() <= 0) return; SkAutoCanvasRestore acr(canvas, true); canvas->translate(fStateOffset, 0); int lastFrameBound = fFrameBounds[fAtomsToRead]; int toBeRead = fAtomBounds[fAtomsToRead] - lastFrameBound; int firstChunk = (fAtomsToRead > 0) ? fAtomBounds[fAtomsToRead - 1] - lastFrameBound: 0; if (toBeRead > 0) { SkDumpCanvas* dumpCanvas = new SkDumpCanvas(fDumper); SkGPipeReader* dumpReader = new SkGPipeReader(dumpCanvas); SkGPipeReader* reader = new SkGPipeReader(canvas); fDumper->disable(); int offset = 0; size_t bytesRead; SkGPipeReader::Status s; //Read the first chunk if (offset < firstChunk && firstChunk < toBeRead) { s = dumpReader->playback(fData.begin() + offset, firstChunk - offset); SkASSERT(SkGPipeReader::kError_Status != s); s = reader->playback(fData.begin() + offset, firstChunk - offset, 0, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); if (SkGPipeReader::kDone_Status == s){ delete dumpReader; delete dumpCanvas; dumpCanvas = new SkDumpCanvas(fDumper); dumpReader = new SkGPipeReader(dumpCanvas); delete reader; reader = new SkGPipeReader(canvas); } offset += bytesRead; } SkASSERT(offset == firstChunk); //Then read the current atom fDumper->enable(); s = dumpReader->playback(fData.begin() + offset, toBeRead - offset, SkGPipeReader::kReadAtom_PlaybackFlag); SkASSERT(SkGPipeReader::kError_Status != s); s = reader->playback(fData.begin() + offset, toBeRead - offset, SkGPipeReader::kReadAtom_PlaybackFlag, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); delete reader; delete dumpReader; delete dumpCanvas; if (fDisplayClip) { SkPaint p; p.setColor(0x440000AA); SkPath path; canvas->getTotalClip().getBoundaryPath(&path); canvas->drawPath(path, p); } } } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { return new Click(this); } virtual bool onClick(SkView::Click* click) { SkPoint prev = click->fPrev; SkPoint curr = click->fCurr; bool handled = true; switch (click->fState) { case SkView::Click::kDown_State: if (SkScalarAbs(curr.fX - fCommands->width()) <= SKDEBUGGER_RESIZEBARSIZE) { fCommandsResizing = true; } else if (SkScalarAbs(curr.fY - (this->height() - fState->height())) <= SKDEBUGGER_RESIZEBARSIZE && curr.fX > fCommands->width()) { fStateResizing = true; } else if (curr.fX < fCommands->width()) { fAtomsToRead = fCommands->selectHighlight( SkScalarFloorToInt(curr.fY)); } else handled = false; break; case SkView::Click::kMoved_State: if (fCommandsResizing) fCommands->setSize(curr.fX, this->height()); else if (fStateResizing) fState->setSize(this->width(), this->height() - curr.fY); else if (curr.fX < fCommands->width()) { if (curr.fY - prev.fY < 0) { fCommands->scrollDown(); } if (curr.fY - prev.fY > 0) { fCommands->scrollUp(); } } else handled = false; break; case SkView::Click::kUp_State: fStateResizing = fCommandsResizing = false; break; default: break; } fStateOffset = fCommands->width(); fState->setSize(this->width() - fStateOffset, fState->height()); fState->setLoc(fStateOffset, this->height() - fState->height()); if (handled) this->inval(NULL); return handled; } virtual void onSizeChange() { this->INHERITED::onSizeChange(); fCommands->setSize(CMD_WIDTH, this->height()); fCommands->setLoc(0, 0); fState->setSize(this->width() - CMD_WIDTH, SkFloatToScalar(INFO_HEIGHT)); fState->setLoc(CMD_WIDTH, this->height() - SkFloatToScalar(INFO_HEIGHT)); } private: DebuggerCommandsView* fCommands; DebuggerStateView* fState; bool fCommandsResizing; bool fCommandsVisible; bool fStateResizing; bool fStateVisible; float fStateOffset; bool fDisplayClip; int fAtomsToRead; SkTDArray<int> fAtomBounds; SkTDArray<int> fFrameBounds; SkTDArray<char> fData; SkDebugDumper* fDumper; typedef SampleView INHERITED; }; /////////////////////////////////////////////////////////////////////////////// SkView* create_debugger(const char* data, size_t size); SkView* create_debugger(const char* data, size_t size) { return SkNEW_ARGS(DebuggerView, (data, size)); }; bool is_debugger(SkView* view); bool is_debugger(SkView* view) { SkEvent isDebugger(gIsDebuggerQuery); return view->doQuery(&isDebugger); } #endif<commit_msg>add LF at end of file<commit_after> #ifdef SK_DEVELOPER #include "SampleCode.h" #include "SkOSMenu.h" #include "DebuggerViews.h" static const char gIsDebuggerQuery[] = "is-debugger"; class DebuggerView : public SampleView { public: DebuggerView(const char* data, size_t size) { fData.append(size, data); fCommandsVisible = true; fCommandsResizing = false; fStateVisible = true; fStateResizing = false; fCommands = new DebuggerCommandsView; fCommands->setVisibleP(fCommandsVisible); this->attachChildToFront(fCommands)->unref(); fState = new DebuggerStateView; fState->setVisibleP(fStateVisible); this->attachChildToFront(fState)->unref(); fAtomsToRead = 0; fDisplayClip = false; fDumper = new SkDebugDumper(this->getSinkID(), fCommands->getSinkID(), fState->getSinkID()); fDumper->unload(); fAtomBounds.reset(); fFrameBounds.reset(); SkDumpCanvas* dumpCanvas = new SkDumpCanvas(fDumper); SkGPipeReader* dumpReader = new SkGPipeReader(dumpCanvas); if (size > 0) { int offset = 0; int frameBound = 0; size_t bytesRead; while (static_cast<unsigned>(offset) < size) { SkGPipeReader::Status s = dumpReader->playback(data + offset, size - offset, SkGPipeReader::kReadAtom_PlaybackFlag, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); offset += bytesRead; if (SkGPipeReader::kDone_Status == s) { fDumper->dump(dumpCanvas, SkDumpCanvas::kNULL_Verb, "End of Frame", NULL); delete dumpReader; delete dumpCanvas; dumpCanvas = new SkDumpCanvas(fDumper); dumpReader = new SkGPipeReader(dumpCanvas); frameBound = offset; } fAtomBounds.append(1, &offset); fFrameBounds.append(1, &frameBound); } } delete dumpReader; delete dumpCanvas; fDumper->load(); } ~DebuggerView() { fAtomBounds.reset(); fFrameBounds.reset(); delete fDumper; } virtual void requestMenu(SkOSMenu* menu) { menu->setTitle("Debugger"); menu->appendSwitch("Show Commands", "Commands", this->getSinkID(), fCommandsVisible); menu->appendSwitch("Show State", "State", this->getSinkID(), fStateVisible); menu->appendSwitch("Display Clip", "Clip", this->getSinkID(), fDisplayClip); } void goToAtom(int atom) { if (atom != fAtomsToRead) { fAtomsToRead = atom; this->inval(NULL); } } protected: virtual bool onQuery(SkEvent* evt) { if (SampleCode::TitleQ(*evt)) { SampleCode::TitleR(evt, "Debugger"); return true; } if (evt->isType(gIsDebuggerQuery)) { return true; } return this->INHERITED::onQuery(evt); } virtual bool onEvent(const SkEvent& evt) { if (SkOSMenu::FindSwitchState(evt, "Commands", &fCommandsVisible) || SkOSMenu::FindSwitchState(evt, "State", &fStateVisible)) { fCommands->setVisibleP(fCommandsVisible); fState->setVisibleP(fStateVisible); fStateOffset = (fCommandsVisible) ? fCommands->width() : 0; fState->setSize(this->width() - fStateOffset, fState->height()); fState->setLoc(fStateOffset, this->height() - fState->height()); this->inval(NULL); return true; } if (SkOSMenu::FindSwitchState(evt, "Clip", &fDisplayClip)) { this->inval(NULL); return true; } return this->INHERITED::onEvent(evt); } virtual void onDrawContent(SkCanvas* canvas) { if (fData.count() <= 0) return; SkAutoCanvasRestore acr(canvas, true); canvas->translate(fStateOffset, 0); int lastFrameBound = fFrameBounds[fAtomsToRead]; int toBeRead = fAtomBounds[fAtomsToRead] - lastFrameBound; int firstChunk = (fAtomsToRead > 0) ? fAtomBounds[fAtomsToRead - 1] - lastFrameBound: 0; if (toBeRead > 0) { SkDumpCanvas* dumpCanvas = new SkDumpCanvas(fDumper); SkGPipeReader* dumpReader = new SkGPipeReader(dumpCanvas); SkGPipeReader* reader = new SkGPipeReader(canvas); fDumper->disable(); int offset = 0; size_t bytesRead; SkGPipeReader::Status s; //Read the first chunk if (offset < firstChunk && firstChunk < toBeRead) { s = dumpReader->playback(fData.begin() + offset, firstChunk - offset); SkASSERT(SkGPipeReader::kError_Status != s); s = reader->playback(fData.begin() + offset, firstChunk - offset, 0, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); if (SkGPipeReader::kDone_Status == s){ delete dumpReader; delete dumpCanvas; dumpCanvas = new SkDumpCanvas(fDumper); dumpReader = new SkGPipeReader(dumpCanvas); delete reader; reader = new SkGPipeReader(canvas); } offset += bytesRead; } SkASSERT(offset == firstChunk); //Then read the current atom fDumper->enable(); s = dumpReader->playback(fData.begin() + offset, toBeRead - offset, SkGPipeReader::kReadAtom_PlaybackFlag); SkASSERT(SkGPipeReader::kError_Status != s); s = reader->playback(fData.begin() + offset, toBeRead - offset, SkGPipeReader::kReadAtom_PlaybackFlag, &bytesRead); SkASSERT(SkGPipeReader::kError_Status != s); delete reader; delete dumpReader; delete dumpCanvas; if (fDisplayClip) { SkPaint p; p.setColor(0x440000AA); SkPath path; canvas->getTotalClip().getBoundaryPath(&path); canvas->drawPath(path, p); } } } virtual SkView::Click* onFindClickHandler(SkScalar x, SkScalar y) { return new Click(this); } virtual bool onClick(SkView::Click* click) { SkPoint prev = click->fPrev; SkPoint curr = click->fCurr; bool handled = true; switch (click->fState) { case SkView::Click::kDown_State: if (SkScalarAbs(curr.fX - fCommands->width()) <= SKDEBUGGER_RESIZEBARSIZE) { fCommandsResizing = true; } else if (SkScalarAbs(curr.fY - (this->height() - fState->height())) <= SKDEBUGGER_RESIZEBARSIZE && curr.fX > fCommands->width()) { fStateResizing = true; } else if (curr.fX < fCommands->width()) { fAtomsToRead = fCommands->selectHighlight( SkScalarFloorToInt(curr.fY)); } else handled = false; break; case SkView::Click::kMoved_State: if (fCommandsResizing) fCommands->setSize(curr.fX, this->height()); else if (fStateResizing) fState->setSize(this->width(), this->height() - curr.fY); else if (curr.fX < fCommands->width()) { if (curr.fY - prev.fY < 0) { fCommands->scrollDown(); } if (curr.fY - prev.fY > 0) { fCommands->scrollUp(); } } else handled = false; break; case SkView::Click::kUp_State: fStateResizing = fCommandsResizing = false; break; default: break; } fStateOffset = fCommands->width(); fState->setSize(this->width() - fStateOffset, fState->height()); fState->setLoc(fStateOffset, this->height() - fState->height()); if (handled) this->inval(NULL); return handled; } virtual void onSizeChange() { this->INHERITED::onSizeChange(); fCommands->setSize(CMD_WIDTH, this->height()); fCommands->setLoc(0, 0); fState->setSize(this->width() - CMD_WIDTH, SkFloatToScalar(INFO_HEIGHT)); fState->setLoc(CMD_WIDTH, this->height() - SkFloatToScalar(INFO_HEIGHT)); } private: DebuggerCommandsView* fCommands; DebuggerStateView* fState; bool fCommandsResizing; bool fCommandsVisible; bool fStateResizing; bool fStateVisible; float fStateOffset; bool fDisplayClip; int fAtomsToRead; SkTDArray<int> fAtomBounds; SkTDArray<int> fFrameBounds; SkTDArray<char> fData; SkDebugDumper* fDumper; typedef SampleView INHERITED; }; /////////////////////////////////////////////////////////////////////////////// SkView* create_debugger(const char* data, size_t size); SkView* create_debugger(const char* data, size_t size) { return SkNEW_ARGS(DebuggerView, (data, size)); }; bool is_debugger(SkView* view); bool is_debugger(SkView* view) { SkEvent isDebugger(gIsDebuggerQuery); return view->doQuery(&isDebugger); } #endif <|endoftext|>
<commit_before>#include <ros/ros.h> #include "arduino.h" //#include <core_msgs/Odom.h> #include <buzzmobile/CarPose.h> //#include <core_msgs/MotionCommand.h> #include <std_msgs/Bool.h> using namespace std; const double ticksPerRev = 3600; const double wheelCirc = 2.198; ros::Publisher encoder_pub; ros::Subscriber command_sub; ros::Subscriber horn_sub; Arduino arduino; //int odom_sequence = 0; ros::Time last_command_time; ros::Duration keep_alive_frequency(1.0); //void odometry_callback(int, float); //void command_callback(core_msgs::MotionCommand::ConstPtr); void command_callback(buzzmobile::CarPose::ConstPtr); void horn_callback(std_msgs::Bool::ConstPtr); void keep_alive_callback(const ros::TimerEvent&); int main(int argc, char **argv) { ros::init(argc, argv, "car_interface"); //arduino.open("/dev/arduino_motor_controller", 9600); arduino.open("/dev/ttyACM0", 9600); //arduino.setOdometryCallback(odometry_callback); ros::NodeHandle node_handle; last_command_time = ros::Time::now(); //encoder_pub = node_handle.advertise<core_msgs::Odom>("encoder_odom", 1000); command_sub = node_handle.subscribe("car_pose", 1, command_callback); //horn_sub = node_handle.subscribe("car_horn", 1, horn_callback); ros::Timer keepAliveTimer = node_handle.createTimer(keep_alive_frequency, keep_alive_callback); ros::spin(); return 0; } void keep_alive_callback(const ros::TimerEvent&) { ROS_INFO("Keep alive callback called"); // 1 sec command frequency required to maintain velocity if((ros::Time::now() - last_command_time) > keep_alive_frequency) { arduino.setSpeed(0); } } /** void odometry_callback(int tickCount, float steeringAngle) { core_msgs::Odom msg; msg.distance_travelled = (tickCount * wheelCirc) / ticksPerRev; msg.steering_angle = steeringAngle; msg.header.seq = odom_sequence++; msg.header.stamp = ros::Time::now(); encoder_pub.publish(msg); }*/ //void command_callback(core_msgs::MotionCommand::ConstPtr cmd) { void command_callback(buzzmobile::CarPose::ConstPtr cmd) { ROS_INFO("Command received, speed: %f, angle: %f", cmd->velocity, cmd->angle); //arduino.setSpeed(cmd->speed); arduino.setSpeed(cmd->velocity); arduino.setSteering(cmd->angle); arduino.setHorn(cmd->horn); last_command_time = cmd->header.stamp; } //void horn_callback(std_msgs::Bool::ConstPtr msg) { //ROS_INFO("Turning %s horn.", (msg->data ? "on" : "off")); //arduino.setHorn(msg->data); //} <commit_msg>Comment out unused horn_subs in car_interface<commit_after>#include <ros/ros.h> #include "arduino.h" //#include <core_msgs/Odom.h> #include <buzzmobile/CarPose.h> //#include <core_msgs/MotionCommand.h> #include <std_msgs/Bool.h> using namespace std; const double ticksPerRev = 3600; const double wheelCirc = 2.198; ros::Publisher encoder_pub; ros::Subscriber command_sub; //ros::Subscriber horn_sub; Arduino arduino; //int odom_sequence = 0; ros::Time last_command_time; ros::Duration keep_alive_frequency(1.0); //void odometry_callback(int, float); //void command_callback(core_msgs::MotionCommand::ConstPtr); void command_callback(buzzmobile::CarPose::ConstPtr); //void horn_callback(std_msgs::Bool::ConstPtr); void keep_alive_callback(const ros::TimerEvent&); int main(int argc, char **argv) { ros::init(argc, argv, "car_interface"); //arduino.open("/dev/arduino_motor_controller", 9600); arduino.open("/dev/ttyACM0", 9600); //arduino.setOdometryCallback(odometry_callback); ros::NodeHandle node_handle; last_command_time = ros::Time::now(); //encoder_pub = node_handle.advertise<core_msgs::Odom>("encoder_odom", 1000); command_sub = node_handle.subscribe("car_pose", 1, command_callback); //horn_sub = node_handle.subscribe("car_horn", 1, horn_callback); ros::Timer keepAliveTimer = node_handle.createTimer(keep_alive_frequency, keep_alive_callback); ros::spin(); return 0; } void keep_alive_callback(const ros::TimerEvent&) { ROS_INFO("Keep alive callback called"); // 1 sec command frequency required to maintain velocity if((ros::Time::now() - last_command_time) > keep_alive_frequency) { arduino.setSpeed(0); } } /** void odometry_callback(int tickCount, float steeringAngle) { core_msgs::Odom msg; msg.distance_travelled = (tickCount * wheelCirc) / ticksPerRev; msg.steering_angle = steeringAngle; msg.header.seq = odom_sequence++; msg.header.stamp = ros::Time::now(); encoder_pub.publish(msg); }*/ //void command_callback(core_msgs::MotionCommand::ConstPtr cmd) { void command_callback(buzzmobile::CarPose::ConstPtr cmd) { ROS_INFO("Command received, speed: %f, angle: %f", cmd->velocity, cmd->angle); //arduino.setSpeed(cmd->speed); arduino.setSpeed(cmd->velocity); arduino.setSteering(cmd->angle); arduino.setHorn(cmd->horn); last_command_time = cmd->header.stamp; } //void horn_callback(std_msgs::Bool::ConstPtr msg) { //ROS_INFO("Turning %s horn.", (msg->data ? "on" : "off")); //arduino.setHorn(msg->data); //} <|endoftext|>
<commit_before>/* * Copyright (C) 2010 Stephen F. Booth <me@sbooth.org> * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Stephen F. Booth nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <CoreServices/CoreServices.h> #include <iomanip> #include "CFOperatorOverloads.h" #define BUFFER_LENGTH 512 std::ostream& operator<<(std::ostream& out, CFStringRef s) { assert(NULL != s); char buf [BUFFER_LENGTH]; CFIndex totalCharacters = CFStringGetLength(s); CFIndex currentCharacter = 0; CFIndex charactersConverted = 0; CFIndex bytesWritten; while(currentCharacter < totalCharacters) { charactersConverted = CFStringGetBytes(s, CFRangeMake(currentCharacter, totalCharacters), kCFStringEncodingUTF8, 0, false, reinterpret_cast<UInt8 *>(buf), BUFFER_LENGTH, &bytesWritten); currentCharacter += charactersConverted; out.write(buf, bytesWritten); }; return out; } std::ostream& operator<<(std::ostream& out, CFURLRef u) { assert(NULL != u); CFStringRef s = CFURLGetString(u); if(CFStringHasPrefix(s, CFSTR("file:"))) { CFStringRef displayName = NULL; OSStatus result = LSCopyDisplayNameForURL(u, &displayName); if(noErr == result && NULL != displayName) { out << displayName; CFRelease(displayName), displayName = NULL; } } else out << s; return out; } // Most of this is stolen from Apple's CAStreamBasicDescription::Print() std::ostream& operator<<(std::ostream& out, const AudioStreamBasicDescription& format) { unsigned char formatID [5]; *(UInt32 *)formatID = OSSwapHostToBigInt32(format.mFormatID); formatID[4] = '\0'; // General description out << format.mChannelsPerFrame << " ch, " << format.mSampleRate << " Hz, '" << formatID << "' (0x" << std::hex << std::setw(8) << std::setfill('0') << format.mFormatFlags << std::dec << ") "; if(kAudioFormatLinearPCM == format.mFormatID) { // Bit depth UInt32 fractionalBits = ((0x3f << 7)/*kLinearPCMFormatFlagsSampleFractionMask*/ & format.mFormatFlags) >> 7/*kLinearPCMFormatFlagsSampleFractionShift*/; if(0 < fractionalBits) out << (format.mBitsPerChannel - fractionalBits) << "." << fractionalBits; else out << format.mBitsPerChannel; out << "-bit"; // Endianness bool isInterleaved = !(kAudioFormatFlagIsNonInterleaved & format.mFormatFlags); UInt32 interleavedChannelCount = (isInterleaved ? format.mChannelsPerFrame : 1); UInt32 sampleSize = (0 < format.mBytesPerFrame && 0 < interleavedChannelCount ? format.mBytesPerFrame / interleavedChannelCount : 0); if(1 < sampleSize) out << ((kLinearPCMFormatFlagIsBigEndian & format.mFormatFlags) ? " big-endian" : " little-endian"); // Sign bool isInteger = !(kLinearPCMFormatFlagIsFloat & format.mFormatFlags); if(isInteger) out << ((kLinearPCMFormatFlagIsSignedInteger & format.mFormatFlags) ? " signed" : " unsigned"); // Integer or floating out << (isInteger ? " integer" : " float"); // Packedness if(0 < sampleSize && ((sampleSize << 3) != format.mBitsPerChannel)) out << ((kLinearPCMFormatFlagIsPacked & format.mFormatFlags) ? ", packed in " : ", unpacked in ") << sampleSize << " bytes"; // Alignment if((0 < sampleSize && ((sampleSize << 3) != format.mBitsPerChannel)) || (0 != (format.mBitsPerChannel & 7))) out << ((kLinearPCMFormatFlagIsAlignedHigh & format.mFormatFlags) ? " high-aligned" : " low-aligned"); if(!isInterleaved) out << ", deinterleaved"; } else if(kAudioFormatAppleLossless == format.mFormatID) { UInt32 sourceBitDepth = 0; switch(format.mFormatFlags) { case kAppleLosslessFormatFlag_16BitSourceData: sourceBitDepth = 16; break; case kAppleLosslessFormatFlag_20BitSourceData: sourceBitDepth = 20; break; case kAppleLosslessFormatFlag_24BitSourceData: sourceBitDepth = 24; break; case kAppleLosslessFormatFlag_32BitSourceData: sourceBitDepth = 32; break; } if(0 != sourceBitDepth) out << "from " << sourceBitDepth << "-bit source, "; else out << "from UNKNOWN source bit depth, "; out << format.mFramesPerPacket << " frames/packet"; } else out << format.mBitsPerChannel << " bits/channel, " << format.mBytesPerPacket << " bytes/packet, " << format.mFramesPerPacket << " frames/packet, " << format.mBytesPerFrame << " bytes/frame"; return out; } <commit_msg>Better NULL handling<commit_after>/* * Copyright (C) 2010 Stephen F. Booth <me@sbooth.org> * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of Stephen F. Booth nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <CoreServices/CoreServices.h> #include <iomanip> #include "CFOperatorOverloads.h" #define BUFFER_LENGTH 512 std::ostream& operator<<(std::ostream& out, CFStringRef s) { if(NULL == s) { out << "(null)"; return out; } char buf [BUFFER_LENGTH]; CFIndex totalCharacters = CFStringGetLength(s); CFIndex currentCharacter = 0; CFIndex charactersConverted = 0; CFIndex bytesWritten; while(currentCharacter < totalCharacters) { charactersConverted = CFStringGetBytes(s, CFRangeMake(currentCharacter, totalCharacters), kCFStringEncodingUTF8, 0, false, reinterpret_cast<UInt8 *>(buf), BUFFER_LENGTH, &bytesWritten); currentCharacter += charactersConverted; out.write(buf, bytesWritten); }; return out; } std::ostream& operator<<(std::ostream& out, CFURLRef u) { if(NULL == u) { out << "(null)"; return out; } CFStringRef s = CFURLGetString(u); if(CFStringHasPrefix(s, CFSTR("file:"))) { CFStringRef displayName = NULL; OSStatus result = LSCopyDisplayNameForURL(u, &displayName); if(noErr == result && NULL != displayName) { out << displayName; CFRelease(displayName), displayName = NULL; } } else out << s; return out; } // Most of this is stolen from Apple's CAStreamBasicDescription::Print() std::ostream& operator<<(std::ostream& out, const AudioStreamBasicDescription& format) { unsigned char formatID [5]; *(UInt32 *)formatID = OSSwapHostToBigInt32(format.mFormatID); formatID[4] = '\0'; // General description out << format.mChannelsPerFrame << " ch, " << format.mSampleRate << " Hz, '" << formatID << "' (0x" << std::hex << std::setw(8) << std::setfill('0') << format.mFormatFlags << std::dec << ") "; if(kAudioFormatLinearPCM == format.mFormatID) { // Bit depth UInt32 fractionalBits = ((0x3f << 7)/*kLinearPCMFormatFlagsSampleFractionMask*/ & format.mFormatFlags) >> 7/*kLinearPCMFormatFlagsSampleFractionShift*/; if(0 < fractionalBits) out << (format.mBitsPerChannel - fractionalBits) << "." << fractionalBits; else out << format.mBitsPerChannel; out << "-bit"; // Endianness bool isInterleaved = !(kAudioFormatFlagIsNonInterleaved & format.mFormatFlags); UInt32 interleavedChannelCount = (isInterleaved ? format.mChannelsPerFrame : 1); UInt32 sampleSize = (0 < format.mBytesPerFrame && 0 < interleavedChannelCount ? format.mBytesPerFrame / interleavedChannelCount : 0); if(1 < sampleSize) out << ((kLinearPCMFormatFlagIsBigEndian & format.mFormatFlags) ? " big-endian" : " little-endian"); // Sign bool isInteger = !(kLinearPCMFormatFlagIsFloat & format.mFormatFlags); if(isInteger) out << ((kLinearPCMFormatFlagIsSignedInteger & format.mFormatFlags) ? " signed" : " unsigned"); // Integer or floating out << (isInteger ? " integer" : " float"); // Packedness if(0 < sampleSize && ((sampleSize << 3) != format.mBitsPerChannel)) out << ((kLinearPCMFormatFlagIsPacked & format.mFormatFlags) ? ", packed in " : ", unpacked in ") << sampleSize << " bytes"; // Alignment if((0 < sampleSize && ((sampleSize << 3) != format.mBitsPerChannel)) || (0 != (format.mBitsPerChannel & 7))) out << ((kLinearPCMFormatFlagIsAlignedHigh & format.mFormatFlags) ? " high-aligned" : " low-aligned"); if(!isInterleaved) out << ", deinterleaved"; } else if(kAudioFormatAppleLossless == format.mFormatID) { UInt32 sourceBitDepth = 0; switch(format.mFormatFlags) { case kAppleLosslessFormatFlag_16BitSourceData: sourceBitDepth = 16; break; case kAppleLosslessFormatFlag_20BitSourceData: sourceBitDepth = 20; break; case kAppleLosslessFormatFlag_24BitSourceData: sourceBitDepth = 24; break; case kAppleLosslessFormatFlag_32BitSourceData: sourceBitDepth = 32; break; } if(0 != sourceBitDepth) out << "from " << sourceBitDepth << "-bit source, "; else out << "from UNKNOWN source bit depth, "; out << format.mFramesPerPacket << " frames/packet"; } else out << format.mBitsPerChannel << " bits/channel, " << format.mBytesPerPacket << " bytes/packet, " << format.mFramesPerPacket << " frames/packet, " << format.mBytesPerFrame << " bytes/frame"; return out; } <|endoftext|>
<commit_before>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd) { *lineEnd = false; while ((*source != ' ') && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == ' ') || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->active = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->active = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->index = nodes.size(); node->type = AS_UNKNOWN; node->active = true; nodes.push_back(node); nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[AS_T1] = "T1"; friendlyTypeStrings[AS_T2] = "T2"; friendlyTypeStrings[AS_COMP] = "COMP"; friendlyTypeStrings[AS_EDU] = "Educational Institution"; friendlyTypeStrings[AS_IX] = "IX"; friendlyTypeStrings[AS_NIC] = "NIC"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if (node) { Json::Value as = root[members[i]]; node->name = as[1].asString(); node->rawTextDescription = as[5].asString(); node->dateRegistered = as[3].asString(); node->address = as[7].asString(); node->city = as[8].asString(); node->state = as[9].asString(); node->postalCode = as[10].asString(); node->country = as[11].asString(); node->hasLatLong = true; node->latitude = as[12].asFloat()*2.0*3.14159/360.0; node->longitude = as[13].asFloat()*2.0*3.14159/360.0; } } } } void MapData::createNodeBoxes() { for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->active) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } <commit_msg>Better strings for network types.<commit_after>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd) { *lineEnd = false; while ((*source != ' ') && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == ' ') || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->active = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->active = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->index = nodes.size(); node->type = AS_UNKNOWN; node->active = true; nodes.push_back(node); nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[AS_T1] = "Large ISP"; friendlyTypeStrings[AS_T2] = "Small ISP"; friendlyTypeStrings[AS_COMP] = "Customer Network"; friendlyTypeStrings[AS_EDU] = "University"; friendlyTypeStrings[AS_IX] = "Internet Exchange Point"; friendlyTypeStrings[AS_NIC] = "Network Information Center"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if (node) { Json::Value as = root[members[i]]; node->name = as[1].asString(); node->rawTextDescription = as[5].asString(); node->dateRegistered = as[3].asString(); node->address = as[7].asString(); node->city = as[8].asString(); node->state = as[9].asString(); node->postalCode = as[10].asString(); node->country = as[11].asString(); node->hasLatLong = true; node->latitude = as[12].asFloat()*2.0*3.14159/360.0; node->longitude = as[13].asFloat()*2.0*3.14159/360.0; } } } } void MapData::createNodeBoxes() { for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->active) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkDirectory.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDirectory.h" #include "vtkDebugLeaks.h" vtkCxxRevisionMacro(vtkDirectory, "1.16"); //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkDirectory); //---------------------------------------------------------------------------- vtkDirectory* vtkDirectory::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkDirectory"); #endif return new vtkDirectory; } vtkDirectory::vtkDirectory() : Path(0), Files(0), NumberOfFiles(0) { } vtkDirectory::~vtkDirectory() { for(int i =0; i < this->NumberOfFiles; i++) { delete [] this->Files[i]; } delete [] this->Files; delete [] this->Path; } void vtkDirectory::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if(!this->Path) { os << indent << "Directory not open\n"; return; } os << indent << "Directory for: " << this->Path << "\n"; os << indent << "Contains the following files:\n"; indent = indent.GetNextIndent(); for(int i =0; i < this->NumberOfFiles; i++) { os << indent << this->Files[i] << "\n"; } } // First microsoft compilers #ifdef _MSC_VER #include <windows.h> #include <io.h> #include <ctype.h> #include <direct.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> int vtkDirectory::Open(const char* name) { char* buf=0; int n = static_cast<int>(strlen(name)); if (name[n - 1] == '/') { buf = new char[n + 1 + 1]; sprintf(buf, "%s*", name); } else { buf = new char[n + 2 + 1]; sprintf(buf, "%s/*", name); } struct _finddata_t data; // data of current file // First count the number of files in the directory long srchHandle = _findfirst(buf, &data); if (srchHandle == -1) { this->NumberOfFiles = 0; _findclose(srchHandle); delete[] buf; return 0; } this->NumberOfFiles = 1; while(_findnext(srchHandle, &data) != -1) { this->NumberOfFiles++; } this->Files = new char*[this->NumberOfFiles]; // close the handle _findclose(srchHandle); // Now put them into the file array srchHandle = _findfirst(buf, &data); delete [] buf; if (srchHandle == -1) { this->NumberOfFiles = 0; _findclose(srchHandle); return 0; } // Loop through names int i = 0; do { this->Files[i] = strcpy(new char[strlen(data.name)+1], data.name); i++; } while (_findnext(srchHandle, &data) != -1); this->Path = strcpy(new char[strlen(name)+1], name); return _findclose(srchHandle) != -1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return _getcwd(buf, len); } #else // Now the POSIX style directory access #include <sys/types.h> #include <dirent.h> #include <unistd.h> int vtkDirectory::Open(const char* name) { DIR* dir = opendir(name); if (!dir) { return 0; } this->NumberOfFiles = 0; dirent* d =0; for (d = readdir(dir); d; d = readdir(dir)) { this->NumberOfFiles++; } this->Files = new char*[this->NumberOfFiles]; closedir(dir); dir = opendir(name); if (!dir) { return 0; } int i = 0; for (d = readdir(dir); d; d = readdir(dir)) { this->Files[i] = strcpy(new char[strlen(d->d_name)+1], d->d_name); i++; } this->Path = strcpy(new char[strlen(name)+1], name); closedir(dir); return 1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return getcwd(buf, len); } #endif const char* vtkDirectory::GetFile(int index) { if(index >= this->NumberOfFiles || index < 0) { vtkErrorMacro( << "Bad index for GetFile on vtkDirectory\n"); return 0; } return this->Files[index]; } <commit_msg>Support for borland.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkDirectory.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkDirectory.h" #include "vtkDebugLeaks.h" vtkCxxRevisionMacro(vtkDirectory, "1.17"); //---------------------------------------------------------------------------- // Needed when we don't use the vtkStandardNewMacro. vtkInstantiatorNewMacro(vtkDirectory); //---------------------------------------------------------------------------- vtkDirectory* vtkDirectory::New() { #ifdef VTK_DEBUG_LEAKS vtkDebugLeaks::ConstructClass("vtkDirectory"); #endif return new vtkDirectory; } vtkDirectory::vtkDirectory() : Path(0), Files(0), NumberOfFiles(0) { } vtkDirectory::~vtkDirectory() { for(int i =0; i < this->NumberOfFiles; i++) { delete [] this->Files[i]; } delete [] this->Files; delete [] this->Path; } void vtkDirectory::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); if(!this->Path) { os << indent << "Directory not open\n"; return; } os << indent << "Directory for: " << this->Path << "\n"; os << indent << "Contains the following files:\n"; indent = indent.GetNextIndent(); for(int i =0; i < this->NumberOfFiles; i++) { os << indent << this->Files[i] << "\n"; } } // First microsoft and borland compilers #if defined(_MSC_VER) || defined(__BORLANDC__) #include <windows.h> #include <io.h> #include <ctype.h> #include <direct.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> int vtkDirectory::Open(const char* name) { char* buf=0; int n = static_cast<int>(strlen(name)); if (name[n - 1] == '/') { buf = new char[n + 1 + 1]; sprintf(buf, "%s*", name); } else { buf = new char[n + 2 + 1]; sprintf(buf, "%s/*", name); } struct _finddata_t data; // data of current file // First count the number of files in the directory long srchHandle = _findfirst(buf, &data); if (srchHandle == -1) { this->NumberOfFiles = 0; _findclose(srchHandle); delete[] buf; return 0; } this->NumberOfFiles = 1; while(_findnext(srchHandle, &data) != -1) { this->NumberOfFiles++; } this->Files = new char*[this->NumberOfFiles]; // close the handle _findclose(srchHandle); // Now put them into the file array srchHandle = _findfirst(buf, &data); delete [] buf; if (srchHandle == -1) { this->NumberOfFiles = 0; _findclose(srchHandle); return 0; } // Loop through names int i = 0; do { this->Files[i] = strcpy(new char[strlen(data.name)+1], data.name); i++; } while (_findnext(srchHandle, &data) != -1); this->Path = strcpy(new char[strlen(name)+1], name); return _findclose(srchHandle) != -1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return _getcwd(buf, len); } #else // Now the POSIX style directory access #include <sys/types.h> #include <dirent.h> #include <unistd.h> int vtkDirectory::Open(const char* name) { DIR* dir = opendir(name); if (!dir) { return 0; } this->NumberOfFiles = 0; dirent* d =0; for (d = readdir(dir); d; d = readdir(dir)) { this->NumberOfFiles++; } this->Files = new char*[this->NumberOfFiles]; closedir(dir); dir = opendir(name); if (!dir) { return 0; } int i = 0; for (d = readdir(dir); d; d = readdir(dir)) { this->Files[i] = strcpy(new char[strlen(d->d_name)+1], d->d_name); i++; } this->Path = strcpy(new char[strlen(name)+1], name); closedir(dir); return 1; } const char* vtkDirectory::GetCurrentWorkingDirectory(char* buf, unsigned int len) { return getcwd(buf, len); } #endif const char* vtkDirectory::GetFile(int index) { if(index >= this->NumberOfFiles || index < 0) { vtkErrorMacro( << "Bad index for GetFile on vtkDirectory\n"); return 0; } return this->Files[index]; } <|endoftext|>
<commit_before>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/included/unit_test.hpp> #include "core/sstring.hh" #include "database.hh" static sstring some_keyspace("ks"); static sstring some_column_family("cf"); static atomic_cell::one make_atomic_cell(bytes value) { return atomic_cell::one::make_live(0, ttl_opt{}, std::move(value)); }; BOOST_AUTO_TEST_CASE(test_mutation_is_applied) { auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type)); column_family cf(s); column_definition& r1_col = *s->get_column_definition("r1"); partition_key key = to_bytes("key1"); clustering_key c_key = s->clustering_key_type->decompose_value({int32_type->decompose(2)}); mutation m(key, s); m.set_clustered_cell(c_key, r1_col, make_atomic_cell(int32_type->decompose(3))); cf.apply(std::move(m)); row& r = cf.find_or_create_row(key, c_key); auto i = r.find(r1_col.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_atomic_cell(); BOOST_REQUIRE(cell.is_live()); BOOST_REQUIRE(int32_type->equal(cell.value(), int32_type->decompose(3))); } BOOST_AUTO_TEST_CASE(test_row_tombstone_updates) { auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); clustering_key c_key1 = s->clustering_key_type->decompose_value( {int32_type->decompose(1)} ); clustering_key c_key2 = s->clustering_key_type->decompose_value( {int32_type->decompose(2)} ); auto ttl = gc_clock::now() + std::chrono::seconds(1); mutation m(key, s); m.p.apply_row_tombstone(s, c_key1, tombstone(1, ttl)); m.p.apply_row_tombstone(s, c_key2, tombstone(0, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key1), tombstone(1, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(0, ttl)); m.p.apply_row_tombstone(s, c_key2, tombstone(1, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(1, ttl)); } BOOST_AUTO_TEST_CASE(test_map_mutations) { auto my_map_type = map_type_impl::get_instance(int32_type, utf8_type, true); auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_map_type}}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); auto& column = *s->get_column_definition("s1"); map_type_impl::mutation mmut1{{int32_type->decompose(101), make_atomic_cell(utf8_type->decompose(sstring("101")))}}; mutation m1(key, s); m1.set_static_cell(column, my_map_type->serialize_mutation_form(mmut1)); cf.apply(m1); map_type_impl::mutation mmut2{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102")))}}; mutation m2(key, s); m2.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2)); cf.apply(m2); map_type_impl::mutation mmut3{{int32_type->decompose(103), make_atomic_cell(utf8_type->decompose(sstring("103")))}}; mutation m3(key, s); m3.set_static_cell(column, my_map_type->serialize_mutation_form(mmut3)); cf.apply(m3); map_type_impl::mutation mmut2o{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102 override")))}}; mutation m2o(key, s); m2o.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2o)); cf.apply(m2o); row& r = cf.find_or_create_partition(key).static_row(); auto i = r.find(column.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_collection_mutation(); auto muts = my_map_type->deserialize_mutation_form(cell.data); BOOST_REQUIRE(muts.size() == 3); // FIXME: more strict tests } BOOST_AUTO_TEST_CASE(test_set_mutations) { auto my_set_type = set_type_impl::get_instance(int32_type, true); auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_set_type}}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); auto& column = *s->get_column_definition("s1"); map_type_impl::mutation mmut1{{int32_type->decompose(101), make_atomic_cell({})}}; mutation m1(key, s); m1.set_static_cell(column, my_set_type->serialize_mutation_form(mmut1)); cf.apply(m1); map_type_impl::mutation mmut2{{int32_type->decompose(102), make_atomic_cell({})}}; mutation m2(key, s); m2.set_static_cell(column, my_set_type->serialize_mutation_form(mmut2)); cf.apply(m2); map_type_impl::mutation mmut3{{int32_type->decompose(103), make_atomic_cell({})}}; mutation m3(key, s); m3.set_static_cell(column, my_set_type->serialize_mutation_form(mmut3)); cf.apply(m3); map_type_impl::mutation mmut2o{{int32_type->decompose(102), make_atomic_cell({})}}; mutation m2o(key, s); m2o.set_static_cell(column, my_set_type->serialize_mutation_form(mmut2o)); cf.apply(m2o); row& r = cf.find_or_create_partition(key).static_row(); auto i = r.find(column.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_collection_mutation(); auto muts = my_set_type->deserialize_mutation_form(cell.data); BOOST_REQUIRE(muts.size() == 3); // FIXME: more strict tests } <commit_msg>tests: add list_type mutation test<commit_after>/* * Copyright 2015 Cloudius Systems */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/included/unit_test.hpp> #include "core/sstring.hh" #include "database.hh" #include "utils/UUID_gen.hh" static sstring some_keyspace("ks"); static sstring some_column_family("cf"); static atomic_cell::one make_atomic_cell(bytes value) { return atomic_cell::one::make_live(0, ttl_opt{}, std::move(value)); }; BOOST_AUTO_TEST_CASE(test_mutation_is_applied) { auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type)); column_family cf(s); column_definition& r1_col = *s->get_column_definition("r1"); partition_key key = to_bytes("key1"); clustering_key c_key = s->clustering_key_type->decompose_value({int32_type->decompose(2)}); mutation m(key, s); m.set_clustered_cell(c_key, r1_col, make_atomic_cell(int32_type->decompose(3))); cf.apply(std::move(m)); row& r = cf.find_or_create_row(key, c_key); auto i = r.find(r1_col.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_atomic_cell(); BOOST_REQUIRE(cell.is_live()); BOOST_REQUIRE(int32_type->equal(cell.value(), int32_type->decompose(3))); } BOOST_AUTO_TEST_CASE(test_row_tombstone_updates) { auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {{"r1", int32_type}}, {}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); clustering_key c_key1 = s->clustering_key_type->decompose_value( {int32_type->decompose(1)} ); clustering_key c_key2 = s->clustering_key_type->decompose_value( {int32_type->decompose(2)} ); auto ttl = gc_clock::now() + std::chrono::seconds(1); mutation m(key, s); m.p.apply_row_tombstone(s, c_key1, tombstone(1, ttl)); m.p.apply_row_tombstone(s, c_key2, tombstone(0, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key1), tombstone(1, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(0, ttl)); m.p.apply_row_tombstone(s, c_key2, tombstone(1, ttl)); BOOST_REQUIRE_EQUAL(m.p.tombstone_for_row(s, c_key2), tombstone(1, ttl)); } BOOST_AUTO_TEST_CASE(test_map_mutations) { auto my_map_type = map_type_impl::get_instance(int32_type, utf8_type, true); auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_map_type}}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); auto& column = *s->get_column_definition("s1"); map_type_impl::mutation mmut1{{int32_type->decompose(101), make_atomic_cell(utf8_type->decompose(sstring("101")))}}; mutation m1(key, s); m1.set_static_cell(column, my_map_type->serialize_mutation_form(mmut1)); cf.apply(m1); map_type_impl::mutation mmut2{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102")))}}; mutation m2(key, s); m2.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2)); cf.apply(m2); map_type_impl::mutation mmut3{{int32_type->decompose(103), make_atomic_cell(utf8_type->decompose(sstring("103")))}}; mutation m3(key, s); m3.set_static_cell(column, my_map_type->serialize_mutation_form(mmut3)); cf.apply(m3); map_type_impl::mutation mmut2o{{int32_type->decompose(102), make_atomic_cell(utf8_type->decompose(sstring("102 override")))}}; mutation m2o(key, s); m2o.set_static_cell(column, my_map_type->serialize_mutation_form(mmut2o)); cf.apply(m2o); row& r = cf.find_or_create_partition(key).static_row(); auto i = r.find(column.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_collection_mutation(); auto muts = my_map_type->deserialize_mutation_form(cell.data); BOOST_REQUIRE(muts.size() == 3); // FIXME: more strict tests } BOOST_AUTO_TEST_CASE(test_set_mutations) { auto my_set_type = set_type_impl::get_instance(int32_type, true); auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_set_type}}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); auto& column = *s->get_column_definition("s1"); map_type_impl::mutation mmut1{{int32_type->decompose(101), make_atomic_cell({})}}; mutation m1(key, s); m1.set_static_cell(column, my_set_type->serialize_mutation_form(mmut1)); cf.apply(m1); map_type_impl::mutation mmut2{{int32_type->decompose(102), make_atomic_cell({})}}; mutation m2(key, s); m2.set_static_cell(column, my_set_type->serialize_mutation_form(mmut2)); cf.apply(m2); map_type_impl::mutation mmut3{{int32_type->decompose(103), make_atomic_cell({})}}; mutation m3(key, s); m3.set_static_cell(column, my_set_type->serialize_mutation_form(mmut3)); cf.apply(m3); map_type_impl::mutation mmut2o{{int32_type->decompose(102), make_atomic_cell({})}}; mutation m2o(key, s); m2o.set_static_cell(column, my_set_type->serialize_mutation_form(mmut2o)); cf.apply(m2o); row& r = cf.find_or_create_partition(key).static_row(); auto i = r.find(column.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_collection_mutation(); auto muts = my_set_type->deserialize_mutation_form(cell.data); BOOST_REQUIRE(muts.size() == 3); // FIXME: more strict tests } BOOST_AUTO_TEST_CASE(test_list_mutations) { auto my_list_type = list_type_impl::get_instance(int32_type, true); auto s = make_lw_shared(schema(some_keyspace, some_column_family, {{"p1", utf8_type}}, {{"c1", int32_type}}, {}, {{"s1", my_list_type}}, utf8_type)); column_family cf(s); partition_key key = to_bytes("key1"); auto key_type = timeuuid_type; auto& column = *s->get_column_definition("s1"); auto make_key = [] { return timeuuid_type->decompose(utils::UUID_gen::get_time_UUID()); }; collection_type_impl::mutation mmut1{{make_key(), make_atomic_cell(int32_type->decompose(101))}}; mutation m1(key, s); m1.set_static_cell(column, my_list_type->serialize_mutation_form(mmut1)); cf.apply(m1); collection_type_impl::mutation mmut2{{make_key(), make_atomic_cell(int32_type->decompose(102))}}; mutation m2(key, s); m2.set_static_cell(column, my_list_type->serialize_mutation_form(mmut2)); cf.apply(m2); collection_type_impl::mutation mmut3{{make_key(), make_atomic_cell(int32_type->decompose(103))}}; mutation m3(key, s); m3.set_static_cell(column, my_list_type->serialize_mutation_form(mmut3)); cf.apply(m3); collection_type_impl::mutation mmut2o{{make_key(), make_atomic_cell(int32_type->decompose(102))}}; mutation m2o(key, s); m2o.set_static_cell(column, my_list_type->serialize_mutation_form(mmut2o)); cf.apply(m2o); row& r = cf.find_or_create_partition(key).static_row(); auto i = r.find(column.id); BOOST_REQUIRE(i != r.end()); auto cell = i->second.as_collection_mutation(); auto muts = my_list_type->deserialize_mutation_form(cell.data); BOOST_REQUIRE(muts.size() == 4); // FIXME: more strict tests } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "SelectVolumeWidget.h" #include "ui_SelectVolumeWidget.h" #include <pqApplicationCore.h> #include <pqSettings.h> #include <vtkBoundingBox.h> #include <vtkBoxRepresentation.h> #include <vtkBoxWidget2.h> #include <vtkCommand.h> #include <vtkEventQtSlotConnect.h> #include <vtkImageData.h> #include <vtkInteractorObserver.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkRendererCollection.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <vtkSmartPointer.h> #include <vtkSmartVolumeMapper.h> #include <vtkTrivialProducer.h> #include <vtkVolume.h> #include <vtkVolumeProperty.h> #include <QHBoxLayout> #include <QSettings> #include "ActiveObjects.h" #include "Utilities.h" namespace tomviz { class SelectVolumeWidget::CWInternals { public: vtkNew<vtkBoxWidget2> boxWidget; vtkSmartPointer<vtkRenderWindowInteractor> interactor; vtkNew<vtkEventQtSlotConnect> eventLink; Ui::SelectVolumeWidget ui; int dataExtent[6]; double dataOrigin[3]; double dataSpacing[3]; double dataPosition[3]; vtkBoundingBox dataBoundingBox; void bounds(int bs[6]) const { int index = 0; bs[index++] = this->ui.startX->value(); bs[index++] = this->ui.endX->value(); bs[index++] = this->ui.startY->value(); bs[index++] = this->ui.endY->value(); bs[index++] = this->ui.startZ->value(); bs[index++] = this->ui.endZ->value(); } void blockSpinnerSignals(bool block) { ui.startX->blockSignals(block); ui.startY->blockSignals(block); ui.startZ->blockSignals(block); ui.endX->blockSignals(block); ui.endY->blockSignals(block); ui.endZ->blockSignals(block); } }; SelectVolumeWidget::SelectVolumeWidget(const double origin[3], const double spacing[3], const int extent[6], const int currentVolume[6], const double position[3], QWidget* p) : Superclass(p), Internals(new SelectVolumeWidget::CWInternals()) { vtkRenderWindowInteractor* iren = ActiveObjects::instance().activeView()->GetRenderWindow()->GetInteractor(); this->Internals->interactor = iren; for (int i = 0; i < 3; ++i) { this->Internals->dataOrigin[i] = origin[i]; this->Internals->dataSpacing[i] = spacing[i]; this->Internals->dataExtent[2 * i] = extent[2 * i]; this->Internals->dataExtent[2 * i + 1] = extent[2 * i + 1]; this->Internals->dataPosition[i] = position[i]; } double bounds[6]; for (int i = 0; i < 6; ++i) { bounds[i] = this->Internals->dataOrigin[i >> 1] + this->Internals->dataSpacing[i >> 1] * this->Internals->dataExtent[i] + this->Internals->dataPosition[i >> 1]; } vtkNew<vtkBoxRepresentation> boxRep; boxRep->GetOutlineProperty()->SetColor(offWhite); boxRep->GetOutlineProperty()->SetAmbient(0.0); boxRep->GetOutlineProperty()->SetLighting(false); boxRep->GetSelectedOutlineProperty()->SetColor(offWhite); boxRep->GetSelectedOutlineProperty()->SetAmbient(0.0); boxRep->GetSelectedOutlineProperty()->SetLighting(false); boxRep->SetPlaceFactor(1.0); boxRep->PlaceWidget(bounds); boxRep->HandlesOn(); this->Internals->boxWidget->SetTranslationEnabled(1); this->Internals->boxWidget->SetScalingEnabled(1); this->Internals->boxWidget->SetRotationEnabled(0); this->Internals->boxWidget->SetMoveFacesEnabled(1); this->Internals->boxWidget->SetInteractor(iren); this->Internals->boxWidget->SetRepresentation(boxRep.GetPointer()); this->Internals->boxWidget->SetPriority(1); this->Internals->boxWidget->EnabledOn(); this->Internals->eventLink->Connect(this->Internals->boxWidget.GetPointer(), vtkCommand::InteractionEvent, this, SLOT(interactionEnd(vtkObject*))); iren->GetRenderWindow()->Render(); Ui::SelectVolumeWidget& ui = this->Internals->ui; ui.setupUi(this); double e[6]; std::copy(extent, extent + 6, e); this->Internals->dataBoundingBox.SetBounds(e); // Set ranges and default values ui.startX->setRange(extent[0], extent[1]); ui.startX->setValue(currentVolume[0]); ui.startY->setRange(extent[2], extent[3]); ui.startY->setValue(currentVolume[2]); ui.startZ->setRange(extent[4], extent[5]); ui.startZ->setValue(currentVolume[4]); ui.endX->setRange(extent[0], extent[1]); ui.endX->setValue(currentVolume[1]); ui.endY->setRange(extent[2], extent[3]); ui.endY->setValue(currentVolume[3]); ui.endZ->setRange(extent[4], extent[5]); ui.endZ->setValue(currentVolume[5]); this->connect(ui.startX, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.startY, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.startZ, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endX, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endY, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endZ, SIGNAL(editingFinished()), this, SLOT(valueChanged())); // force through the current values pulled from the operator and set above this->valueChanged(); } SelectVolumeWidget::~SelectVolumeWidget() { this->Internals->boxWidget->SetInteractor(nullptr); this->Internals->interactor->GetRenderWindow()->Render(); } void SelectVolumeWidget::interactionEnd(vtkObject* caller) { Q_UNUSED(caller); double* boxBounds = this->Internals->boxWidget->GetRepresentation()->GetBounds(); double* spacing = this->Internals->dataSpacing; double* origin = this->Internals->dataOrigin; double dataBounds[6]; int dim = 0; for (int i = 0; i < 6; i++) { dataBounds[i] = (boxBounds[i] - origin[dim]) / spacing[dim]; dim += i % 2 ? 1 : 0; } this->updateBounds(dataBounds); } void SelectVolumeWidget::updateBounds(int* bounds) { double* spacing = this->Internals->dataSpacing; double* origin = this->Internals->dataOrigin; double* position = this->Internals->dataPosition; double newBounds[6]; int dim = 0; for (int i = 0; i < 6; i++) { newBounds[i] = (bounds[i] * spacing[dim]) + origin[dim] + position[dim]; dim += i % 2 ? 1 : 0; } this->Internals->boxWidget->GetRepresentation()->PlaceWidget(newBounds); this->Internals->interactor->GetRenderWindow()->Render(); } void SelectVolumeWidget::getExtentOfSelection(int extent[6]) { this->Internals->bounds(extent); } void SelectVolumeWidget::getBoundsOfSelection(double bounds[6]) { double* boxBounds = this->Internals->boxWidget->GetRepresentation()->GetBounds(); for (int i = 0; i < 6; ++i) { bounds[i] = boxBounds[i]; } } void SelectVolumeWidget::updateBounds(double* newBounds) { Ui::SelectVolumeWidget& ui = this->Internals->ui; this->Internals->blockSpinnerSignals(true); double bnds[6]; for (int i = 0; i < 3; ++i) { bnds[2 * i] = newBounds[2 * i] - this->Internals->dataPosition[i]; bnds[2 * i + 1] = newBounds[2 * i] - this->Internals->dataPosition[i]; } vtkBoundingBox newBoundingBox(bnds); if (this->Internals->dataBoundingBox.Intersects(newBoundingBox)) { ui.startX->setValue(vtkMath::Round(newBounds[0])); ui.startY->setValue(vtkMath::Round(newBounds[2])); ui.startZ->setValue(vtkMath::Round(newBounds[4])); ui.endX->setValue(vtkMath::Round(newBounds[1])); ui.endY->setValue(vtkMath::Round(newBounds[3])); ui.endZ->setValue(vtkMath::Round(newBounds[5])); } // If there is no intersection use data extent else { ui.startX->setValue(this->Internals->dataExtent[0]); ui.startY->setValue(this->Internals->dataExtent[2]); ui.startZ->setValue(this->Internals->dataExtent[4]); ui.endX->setValue(this->Internals->dataExtent[1]); ui.endY->setValue(this->Internals->dataExtent[3]); ui.endZ->setValue(this->Internals->dataExtent[5]); } this->Internals->blockSpinnerSignals(false); } void SelectVolumeWidget::valueChanged() { QSpinBox* sBox = qobject_cast<QSpinBox*>(this->sender()); if (sBox) { Ui::SelectVolumeWidget& ui = this->Internals->ui; QSpinBox* inputBoxes[6] = { ui.startX, ui.endX, ui.startY, ui.endY, ui.startZ, ui.endZ }; int senderIndex = -1; for (int i = 0; i < 6; ++i) { if (inputBoxes[i] == sBox) { senderIndex = i; } } int component = senderIndex / 2; int end = senderIndex % 2; if (end == 0) { if (inputBoxes[component * 2]->value() > inputBoxes[component * 2 + 1]->value()) { inputBoxes[component * 2 + 1]->setValue( inputBoxes[component * 2]->value()); } } else { if (inputBoxes[component * 2]->value() > inputBoxes[component * 2 + 1]->value()) { inputBoxes[component * 2]->setValue( inputBoxes[component * 2 + 1]->value()); } } } int cropVolume[6]; this->Internals->bounds(cropVolume); this->updateBounds(cropVolume); } void SelectVolumeWidget::dataMoved(double x, double y, double z) { this->Internals->dataPosition[0] = x; this->Internals->dataPosition[1] = y; this->Internals->dataPosition[2] = z; int cropVolume[6]; this->Internals->bounds(cropVolume); this->updateBounds(cropVolume); } } <commit_msg>Fix volume selection widget bounding box initialization<commit_after>/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ******************************************************************************/ #include "SelectVolumeWidget.h" #include "ui_SelectVolumeWidget.h" #include <pqApplicationCore.h> #include <pqSettings.h> #include <vtkBoundingBox.h> #include <vtkBoxRepresentation.h> #include <vtkBoxWidget2.h> #include <vtkCommand.h> #include <vtkEventQtSlotConnect.h> #include <vtkImageData.h> #include <vtkInteractorObserver.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkRendererCollection.h> #include <vtkSMSourceProxy.h> #include <vtkSMViewProxy.h> #include <vtkSmartPointer.h> #include <vtkSmartVolumeMapper.h> #include <vtkTrivialProducer.h> #include <vtkVolume.h> #include <vtkVolumeProperty.h> #include <QHBoxLayout> #include <QSettings> #include "ActiveObjects.h" #include "Utilities.h" namespace tomviz { class SelectVolumeWidget::CWInternals { public: vtkNew<vtkBoxWidget2> boxWidget; vtkSmartPointer<vtkRenderWindowInteractor> interactor; vtkNew<vtkEventQtSlotConnect> eventLink; Ui::SelectVolumeWidget ui; int dataExtent[6]; double dataOrigin[3]; double dataSpacing[3]; double dataPosition[3]; vtkBoundingBox dataBoundingBox; void bounds(int bs[6]) const { int index = 0; bs[index++] = this->ui.startX->value(); bs[index++] = this->ui.endX->value(); bs[index++] = this->ui.startY->value(); bs[index++] = this->ui.endY->value(); bs[index++] = this->ui.startZ->value(); bs[index++] = this->ui.endZ->value(); } void blockSpinnerSignals(bool block) { ui.startX->blockSignals(block); ui.startY->blockSignals(block); ui.startZ->blockSignals(block); ui.endX->blockSignals(block); ui.endY->blockSignals(block); ui.endZ->blockSignals(block); } }; SelectVolumeWidget::SelectVolumeWidget(const double origin[3], const double spacing[3], const int extent[6], const int currentVolume[6], const double position[3], QWidget* p) : Superclass(p), Internals(new SelectVolumeWidget::CWInternals()) { vtkRenderWindowInteractor* iren = ActiveObjects::instance().activeView()->GetRenderWindow()->GetInteractor(); this->Internals->interactor = iren; for (int i = 0; i < 3; ++i) { this->Internals->dataOrigin[i] = origin[i]; this->Internals->dataSpacing[i] = spacing[i]; this->Internals->dataExtent[2 * i] = extent[2 * i]; this->Internals->dataExtent[2 * i + 1] = extent[2 * i + 1]; this->Internals->dataPosition[i] = position[i]; } double bounds[6]; for (int i = 0; i < 6; ++i) { bounds[i] = this->Internals->dataOrigin[i >> 1] + this->Internals->dataSpacing[i >> 1] * this->Internals->dataExtent[i] + this->Internals->dataPosition[i >> 1]; } vtkNew<vtkBoxRepresentation> boxRep; boxRep->GetOutlineProperty()->SetColor(offWhite); boxRep->GetOutlineProperty()->SetAmbient(0.0); boxRep->GetOutlineProperty()->SetLighting(false); boxRep->GetSelectedOutlineProperty()->SetColor(offWhite); boxRep->GetSelectedOutlineProperty()->SetAmbient(0.0); boxRep->GetSelectedOutlineProperty()->SetLighting(false); boxRep->SetPlaceFactor(1.0); boxRep->PlaceWidget(bounds); boxRep->HandlesOn(); this->Internals->boxWidget->SetTranslationEnabled(1); this->Internals->boxWidget->SetScalingEnabled(1); this->Internals->boxWidget->SetRotationEnabled(0); this->Internals->boxWidget->SetMoveFacesEnabled(1); this->Internals->boxWidget->SetInteractor(iren); this->Internals->boxWidget->SetRepresentation(boxRep.GetPointer()); this->Internals->boxWidget->SetPriority(1); this->Internals->boxWidget->EnabledOn(); this->Internals->eventLink->Connect(this->Internals->boxWidget.GetPointer(), vtkCommand::InteractionEvent, this, SLOT(interactionEnd(vtkObject*))); iren->GetRenderWindow()->Render(); Ui::SelectVolumeWidget& ui = this->Internals->ui; ui.setupUi(this); double e[6]; std::copy(extent, extent + 6, e); this->Internals->dataBoundingBox.SetBounds(e); // Set ranges and default values ui.startX->setRange(extent[0], extent[1]); ui.startX->setValue(currentVolume[0]); ui.startY->setRange(extent[2], extent[3]); ui.startY->setValue(currentVolume[2]); ui.startZ->setRange(extent[4], extent[5]); ui.startZ->setValue(currentVolume[4]); ui.endX->setRange(extent[0], extent[1]); ui.endX->setValue(currentVolume[1]); ui.endY->setRange(extent[2], extent[3]); ui.endY->setValue(currentVolume[3]); ui.endZ->setRange(extent[4], extent[5]); ui.endZ->setValue(currentVolume[5]); this->connect(ui.startX, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.startY, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.startZ, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endX, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endY, SIGNAL(editingFinished()), this, SLOT(valueChanged())); this->connect(ui.endZ, SIGNAL(editingFinished()), this, SLOT(valueChanged())); // force through the current values pulled from the operator and set above this->valueChanged(); } SelectVolumeWidget::~SelectVolumeWidget() { this->Internals->boxWidget->SetInteractor(nullptr); this->Internals->interactor->GetRenderWindow()->Render(); } void SelectVolumeWidget::interactionEnd(vtkObject* caller) { Q_UNUSED(caller); double* boxBounds = this->Internals->boxWidget->GetRepresentation()->GetBounds(); double* spacing = this->Internals->dataSpacing; double* origin = this->Internals->dataOrigin; double dataBounds[6]; int dim = 0; for (int i = 0; i < 6; i++) { dataBounds[i] = (boxBounds[i] - origin[dim]) / spacing[dim]; dim += i % 2 ? 1 : 0; } this->updateBounds(dataBounds); } void SelectVolumeWidget::updateBounds(int* bounds) { double* spacing = this->Internals->dataSpacing; double* origin = this->Internals->dataOrigin; double* position = this->Internals->dataPosition; double newBounds[6]; int dim = 0; for (int i = 0; i < 6; i++) { newBounds[i] = (bounds[i] * spacing[dim]) + origin[dim] + position[dim]; dim += i % 2 ? 1 : 0; } this->Internals->boxWidget->GetRepresentation()->PlaceWidget(newBounds); this->Internals->interactor->GetRenderWindow()->Render(); } void SelectVolumeWidget::getExtentOfSelection(int extent[6]) { this->Internals->bounds(extent); } void SelectVolumeWidget::getBoundsOfSelection(double bounds[6]) { double* boxBounds = this->Internals->boxWidget->GetRepresentation()->GetBounds(); for (int i = 0; i < 6; ++i) { bounds[i] = boxBounds[i]; } } void SelectVolumeWidget::updateBounds(double* newBounds) { Ui::SelectVolumeWidget& ui = this->Internals->ui; this->Internals->blockSpinnerSignals(true); double bnds[6]; for (int i = 0; i < 3; ++i) { bnds[2 * i] = newBounds[2 * i] - this->Internals->dataPosition[i]; bnds[2 * i + 1] = newBounds[2 * i + 1] - this->Internals->dataPosition[i]; } vtkBoundingBox newBoundingBox(bnds); if (this->Internals->dataBoundingBox.Intersects(newBoundingBox)) { ui.startX->setValue(vtkMath::Round(newBounds[0])); ui.startY->setValue(vtkMath::Round(newBounds[2])); ui.startZ->setValue(vtkMath::Round(newBounds[4])); ui.endX->setValue(vtkMath::Round(newBounds[1])); ui.endY->setValue(vtkMath::Round(newBounds[3])); ui.endZ->setValue(vtkMath::Round(newBounds[5])); } // If there is no intersection use data extent else { ui.startX->setValue(this->Internals->dataExtent[0]); ui.startY->setValue(this->Internals->dataExtent[2]); ui.startZ->setValue(this->Internals->dataExtent[4]); ui.endX->setValue(this->Internals->dataExtent[1]); ui.endY->setValue(this->Internals->dataExtent[3]); ui.endZ->setValue(this->Internals->dataExtent[5]); } this->Internals->blockSpinnerSignals(false); } void SelectVolumeWidget::valueChanged() { QSpinBox* sBox = qobject_cast<QSpinBox*>(this->sender()); if (sBox) { Ui::SelectVolumeWidget& ui = this->Internals->ui; QSpinBox* inputBoxes[6] = { ui.startX, ui.endX, ui.startY, ui.endY, ui.startZ, ui.endZ }; int senderIndex = -1; for (int i = 0; i < 6; ++i) { if (inputBoxes[i] == sBox) { senderIndex = i; } } int component = senderIndex / 2; int end = senderIndex % 2; if (end == 0) { if (inputBoxes[component * 2]->value() > inputBoxes[component * 2 + 1]->value()) { inputBoxes[component * 2 + 1]->setValue( inputBoxes[component * 2]->value()); } } else { if (inputBoxes[component * 2]->value() > inputBoxes[component * 2 + 1]->value()) { inputBoxes[component * 2]->setValue( inputBoxes[component * 2 + 1]->value()); } } } int cropVolume[6]; this->Internals->bounds(cropVolume); this->updateBounds(cropVolume); } void SelectVolumeWidget::dataMoved(double x, double y, double z) { this->Internals->dataPosition[0] = x; this->Internals->dataPosition[1] = y; this->Internals->dataPosition[2] = z; int cropVolume[6]; this->Internals->bounds(cropVolume); this->updateBounds(cropVolume); } } <|endoftext|>
<commit_before>/* * Copyright 2013 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ConsoleManager.h" #include <string> #include <vector> #include <iostream> #include <exception> #include <stdexcept> using namespace tis; /// @name printHelp /// @brief prints complete overview over possible actions void printHelp () { std::cout << "\ntis_network - network module for GigE cameras" << "\n\nusage: tis_network [command] - execute specified command" << "\n or: tis_network [command] -c <camera> - execute command for given camera\n\n\n" << "Available commands:\n" << " list - list all available GigE cameras\n" << " info - print all information for camera\n" << " set - configure camera settings\n" << " forceip - force ip onto camera\n" << " rescue - broadcasts to MAC given settings\n" << " upload - upload new firmware to camera\n" << " help - print this text\n" << std::endl; std::cout << "\nAvailable parameter:\n" << " -h - same as help\n" << " -i - same as info\n" << " -l - same as list\n" << " ip=X.X.X.X - specifiy persistent ip that camera shall use\n" << " subnet=X.X.X.X - specifiy persistent subnetmask that camera shall use\n" << " gateway=X.X.X.X - specifiy persistent gateway that camera shall use\n" << " dhcp=on/off - toggle dhcp state\n" << " static=on/off - toggle static ip state\n" << " name=\"xyz\" - set name for camera; maximum 15 characters\n" << " firmware=firmware.zip - file containing new firmware\n" << std::endl; std::cout << "Camera identification is possible via:\n" << " --serial -s - serial number of camera\n" << " --name -n - user defined name of camera\n" << " --mac -m - MAC of camera\n" << std::endl; std::cout << "Examples:\n\n" << " tis_network set gateway=192.168.0.1 -s 46210199\n" << " tis_network forceip ip=192.168.0.100 subnet=255.255.255.0 gateway=192.168.0.1 -s 46210199\n\n" << std::endl; } void handleCommandlineArguments (const int argc, char* argv[]) { if (argc == 1) { printHelp(); return; } // std::string makes things easier to handle // we don;t need the program name itself and just ignore it std::vector<std::string> args(argv+1, argv + argc); try { for (const auto& arg : args) { if ((arg.compare("help") == 0) || (arg.compare("-h") == 0)) { printHelp(); return; } else if ((arg.compare("list") == 0) || (arg.compare("-l") == 0)) { listCameras(); break; } else if ((arg.compare("info") == 0) || arg.compare("-i") == 0) { if (argc <= 2) { std::cout << "Not enough arguments." << std::endl; return; } printCameraInformation(args); break; } else if (arg.compare("set") == 0) { if (argc <= 2) { std::cout << "Not enough arguments." << std::endl; return; } setCamera(args); break; } else if (arg.compare("forceip") == 0) { std::cout << "\n!!! Using the 'forceip' is DEPRECATED !!!" "\nThis command got replaced by the 'rescue' command and will be " "removed in the future!\n" << std::endl; rescue(args); break; } else if (arg.compare("upload") == 0) { upgradeFirmware(args); break; } else if (arg.compare("rescue") == 0) { rescue(args); break; } else { std::cout << "Unknown parameter \"" << arg << "\"\n" << std::endl; return; } } } catch (std::exception& exc) { std::cout << "\n" << exc.what() << "\n" << std::endl; exit(1); } } int main (int argc, char* argv[]) { handleCommandlineArguments(argc, argv); return 0; } <commit_msg>camera-ip-conf: Update usage text<commit_after>/* * Copyright 2013 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ConsoleManager.h" #include <string> #include <vector> #include <iostream> #include <exception> #include <stdexcept> #include <libgen.h> using namespace tis; /// @name printHelp /// @brief prints complete overview over possible actions void printHelp (char *execName) { std::cout << "\n" << execName << " - configuration tool for The Imaging Source GigE cameras" << "\n\nusage: " << execName << " [command] [args] - execute specified command\n\n" << "Available commands:\n" << " list - list all available GigE cameras\n" << " info - print all information for camera\n" << " set - permanently configure camera settings\n" << " rescue - temporarily set network addresses\n" << " upload - upload new firmware to camera\n" << " help - print this text\n" << std::endl; std::cout << "\nAvailable parameters:\n" << " -h - same as help\n" << " -i - same as info\n" << " -l - same as list\n" << " ip=X.X.X.X - ip address to be set\n" << " subnet=X.X.X.X - subnetmask to be set\n" << " gateway=X.X.X.X - gateway to be set\n" << " dhcp=on/off - toggle dhcp state\n" << " static=on/off - toggle static ip state\n" << " name=\"xyz\" - set name for camera; maximum 15 characters\n" << " firmware=firmware.zip - file containing new firmware\n" << std::endl; std::cout << "Camera identification:\n" << " --serial -s - serial number of camera\n" << " --name -n - user defined name of camera\n" << " --mac -m - MAC of camera\n" << std::endl; std::cout << "Examples:\n\n" << " Temporarily set a fixed IP address, gateway and subnet mask for the camera\n" << " with the serial number 27710767. The camera does not need to be on the same\n" << " subnet:\n\n" << " " << execName << " rescue ip=192.168.1.100 gateway=192.168.1.1 subnet=255.255.255.0 -s 27710767\n\n" << " Permanently set a fixed IP adress on the same camera. Camera needs to be\n" << " on the same subnet:\n\n" << " " << execName << " set ip=192.168.1.100 gateway=192.168.1.1 subnet=255.255.255.0 -s 27710767\n" << std::endl; } void handleCommandlineArguments (const int argc, char* argv[]) { if (argc == 1) { printHelp(basename(argv[0])); return; } // std::string makes things easier to handle // we don;t need the program name itself and just ignore it std::vector<std::string> args(argv+1, argv + argc); try { for (const auto& arg : args) { if ((arg.compare("help") == 0) || (arg.compare("-h") == 0)) { printHelp(basename(argv[0])); return; } else if ((arg.compare("list") == 0) || (arg.compare("-l") == 0)) { listCameras(); break; } else if ((arg.compare("info") == 0) || arg.compare("-i") == 0) { if (argc <= 2) { std::cout << "Not enough arguments." << std::endl; return; } printCameraInformation(args); break; } else if (arg.compare("set") == 0) { if (argc <= 2) { std::cout << "Not enough arguments." << std::endl; return; } setCamera(args); break; } else if (arg.compare("forceip") == 0) { std::cout << "\n!!! Using the 'forceip' is DEPRECATED !!!" "\nThis command got replaced by the 'rescue' command and will be " "removed in the future!\n" << std::endl; rescue(args); break; } else if (arg.compare("upload") == 0) { upgradeFirmware(args); break; } else if (arg.compare("rescue") == 0) { rescue(args); break; } else { std::cout << "Unknown parameter \"" << arg << "\"\n" << std::endl; return; } } } catch (std::exception& exc) { std::cout << "\n" << exc.what() << "\n" << std::endl; exit(1); } } int main (int argc, char* argv[]) { handleCommandlineArguments(argc, argv); return 0; } <|endoftext|>
<commit_before>#include "AssimpSceneImporter.hpp" #include "Model.hpp" #include "ImportedScene.hpp" #include "../inanity/File.hpp" #include "../inanity/deps/assimp/repo/include/assimp/Importer.hpp" #include "../inanity/deps/assimp/repo/include/assimp/scene.h" #include "../inanity/deps/assimp/repo/include/assimp/mesh.h" BEGIN_INANITY_OIL AssimpSceneImporter::AssimpSceneImporter() {} AssimpSceneImporter::~AssimpSceneImporter() {} ptr<ImportedScene> AssimpSceneImporter::Import(ptr<File> file) { BEGIN_TRY(); Assimp::Importer importer; const aiScene* aScene = importer.ReadFileFromMemory(file->GetData(), file->GetSize(), // calculate tangents and binormals aiProcess_CalcTangentSpace | // this flag is required for index buffer aiProcess_JoinIdenticalVertices | // only 3-vertex faces aiProcess_Triangulate | // optimize order of vertices aiProcess_ImproveCacheLocality | // sort by primitive type aiProcess_SortByPType | // get right Y uv coord aiProcess_FlipUVs | // CW order aiProcess_FlipWindingOrder ); if(!aScene) THROW(String("Assimp failed: ") + importer.GetErrorString()); ptr<ImportedScene> scene = NEW(ImportedScene()); ImportedScene::Models& models = scene->GetModels(); // assimp calls models "meshes" // so assimp's "mesh" is really a mesh + material, i.e. model models.resize(aScene->mNumMeshes); for(size_t i = 0; i < models.size(); ++i) { aiMesh* aMesh = aScene->mMeshes[i]; size_t verticesCount = aMesh->mNumVertices; aiVector3D* positions = aMesh->mVertices; aiVector3D* normals = aMesh->mNormals; aiVector3D* tangents = aMesh->mTangents; aiVector3D* bitangents = aMesh->mBitangents; aiVector3D* textureCoords = aMesh->mTextureCoords[0]; } return scene; END_TRY("Can't import scene with assimp"); } END_INANITY_OIL <commit_msg>AssimpSceneImporter work-in-progress<commit_after>#include "AssimpSceneImporter.hpp" #include "Model.hpp" #include "ImportedScene.hpp" #include "Material.hpp" #include "../inanity/graphics/RawMesh.hpp" #include "../inanity/graphics/VertexLayout.hpp" #include "../inanity/MemoryFile.hpp" #include "../inanity/Exception.hpp" #include "../inanity/deps/assimp/repo/include/assimp/Importer.hpp" #include "../inanity/deps/assimp/repo/include/assimp/scene.h" #include "../inanity/deps/assimp/repo/include/assimp/mesh.h" #include "../inanity/deps/assimp/repo/include/assimp/postprocess.h" using namespace Inanity::Graphics; BEGIN_INANITY_OIL AssimpSceneImporter::AssimpSceneImporter() {} AssimpSceneImporter::~AssimpSceneImporter() {} ptr<ImportedScene> AssimpSceneImporter::Import(ptr<File> file) { BEGIN_TRY(); Assimp::Importer importer; const aiScene* aScene = importer.ReadFileFromMemory(file->GetData(), file->GetSize(), // calculate tangents and binormals aiProcess_CalcTangentSpace | // this flag is required for index buffer aiProcess_JoinIdenticalVertices | // only 3-vertex faces aiProcess_Triangulate | // optimize order of vertices aiProcess_ImproveCacheLocality | // sort by primitive type aiProcess_SortByPType | // get right Y uv coord aiProcess_FlipUVs | // CW order aiProcess_FlipWindingOrder ); if(!aScene) THROW(String("Assimp failed: ") + importer.GetErrorString()); ptr<ImportedScene> scene = NEW(ImportedScene()); ImportedScene::Models& models = scene->GetModels(); // assimp calls models "meshes" // so assimp's "mesh" is really a mesh + material, i.e. model models.resize(aScene->mNumMeshes); for(size_t i = 0; i < models.size(); ++i) { const aiMesh* aMesh = aScene->mMeshes[i]; // convert vertices size_t verticesCount = aMesh->mNumVertices; const aiVector3D* positions = aMesh->mVertices; const aiVector3D* tangents = aMesh->mTangents; const aiVector3D* bitangents = aMesh->mBitangents; const aiVector3D* normals = aMesh->mNormals; const aiVector3D* textureCoords = aMesh->mTextureCoords[0]; struct Vertex { vec3 position; vec3 tangent; vec3 binormal; vec3 normal; vec2 texcoord; }; auto c3 = [](const aiVector3D& v) { return vec3(v.x, v.y, v.z); }; auto c2 = [](const aiVector3D& v) { return vec2(v.x, v.y); }; ptr<MemoryFile> verticesFile = NEW(MemoryFile(verticesCount * sizeof(Vertex))); Vertex* vertices = (Vertex*)verticesFile->GetData(); for(size_t i = 0; i < verticesCount; ++i) { Vertex& vertex = vertices[i]; vertex.position = c3(positions[i]); vertex.tangent = c3(tangents[i]); vertex.binormal = c3(bitangents[i]); vertex.normal = c3(normals[i]); vertex.texcoord = c2(textureCoords[i]); } // convert indices size_t facesCount = aMesh->mNumFaces; const aiFace* faces = aMesh->mFaces; size_t indicesCount = facesCount * 3; ptr<MemoryFile> indicesFile; // if we have to use big indices if(indicesCount > 0x10000) { indicesFile = NEW(MemoryFile(facesCount * 3 * sizeof(unsigned int))); unsigned int* indices = (unsigned int*)indicesFile->GetData(); for(size_t i = 0; i < facesCount; ++i) { const aiFace& face = faces[i]; for(size_t j = 0; j < 3; ++j) indices[i * 3 + j] = face.mIndices[j]; } } // else we can use small indices else { indicesFile = NEW(MemoryFile(facesCount * 3 * sizeof(unsigned short))); unsigned short* indices = (unsigned short*)indicesFile->GetData(); for(size_t i = 0; i < facesCount; ++i) { const aiFace& face = faces[i]; for(size_t j = 0; j < 3; ++j) indices[i * 3 + j] = (unsigned short)face.mIndices[j]; } } models.push_back(NEW(Model(NEW(RawMesh(verticesFile, nullptr, indicesFile)), nullptr))); } return scene; END_TRY("Can't import scene with assimp"); } END_INANITY_OIL <|endoftext|>
<commit_before>#include <experimental/filesystem> #include <deque> #include <algorithm> namespace Baikal { namespace fs = std::experimental::filesystem; inline bool is_dot(fs::path const &path) { std::string const &filename = path.string(); return filename.size() == 1 && filename[0] == '.'; } inline bool is_dotdot(fs::path const &path) { std::string const &filename = path.string(); return filename.size() == 2 && filename[0] == '.' && filename[1] == '.'; } bool FindFilenameFromCaseInsensitive(std::string const &req_filename, std::string &actual_filename, bool resolve_symlinks = true) { const fs::path file_path(req_filename); // First, check if file with required filename exists if (fs::exists(file_path)) { actual_filename = req_filename; return true; } // Split path to components std::deque<fs::path> components; for (auto &f : file_path.relative_path()) { components.push_back(f); } // Start from the current directory fs::path result = fs::current_path(); while (!components.empty()) { // Get a path component fs::path c = std::move(components.front()); components.pop_front(); if (is_dot(c)) // <path>/. { // Ensure that this is a directory and skip the dot if (!fs::is_directory(result)) { // Is not a directory return false; } } else if (is_dotdot(c)) // <path>/.. { result /= c; if (!fs::exists(result)) { // Upper directory is not exist return false; } } else // <path>/<other symbols> { // The path doesn't exist if (!fs::exists(result / c)) { // Path in this letter case doesn't exist... // But we'll try to find it in another case bool component_found = false; if (!fs::is_directory(result)) { // Something went wrong, we're not in a directory return false; } for (auto const &entry : fs::directory_iterator(result)) { // Get only name of the folder/file fs::path found_name = entry.path().filename(); // Move to lower case and compare path strings std::string path_str = found_name.string(); std::transform(path_str.begin(), path_str.end(), path_str.begin(), ::tolower); std::string req_str = c.string(); std::transform(req_str.begin(), req_str.end(), req_str.begin(), ::tolower); if (path_str == req_str) { // Found! component_found = true; result /= found_name; break; } } // Give up, the path really doesn't exist if (!component_found) { return false; } } else { // If the path exists, simply concatenate the result with the component result /= c; } // If the result is a symbolic link, resolve it if (fs::is_symlink(result) && resolve_symlinks) { // Get a target of the link fs::path target = fs::read_symlink(result); if (target.is_absolute()) { // The target is an absolute path // Start from the root folder on the next iteration result = target.root_path(); // And remove the root folder target = target.relative_path(); } else { // If the target is a relative path // Start from the base folder of the link on the next iteration result.remove_filename(); } // Push resolved components of the link to the container components.insert(components.begin(), target.begin(), target.end()); } } } // Final check if (!fs::exists(result)) { return false; } actual_filename = result.string(); return true; } } // namespace Baikal <commit_msg>Remove 'fs' shortcut<commit_after>#include <experimental/filesystem> #include <deque> #include <algorithm> namespace Baikal { inline bool is_dot(std::experimental::filesystem::path const &path) { std::string const &filename = path.string(); return filename.size() == 1 && filename[0] == '.'; } inline bool is_dotdot(std::experimental::filesystem::path const &path) { std::string const &filename = path.string(); return filename.size() == 2 && filename[0] == '.' && filename[1] == '.'; } bool FindFilenameFromCaseInsensitive(std::string const &req_filename, std::string &actual_filename, bool resolve_symlinks = true) { const std::experimental::filesystem::path file_path(req_filename); // First, check if file with required filename exists if (std::experimental::filesystem::exists(file_path)) { actual_filename = req_filename; return true; } // Split path to components std::deque<std::experimental::filesystem::path> components; for (auto &f : file_path.relative_path()) { components.push_back(f); } // Start from the current directory std::experimental::filesystem::path result = std::experimental::filesystem::current_path(); while (!components.empty()) { // Get a path component std::experimental::filesystem::path c = std::move(components.front()); components.pop_front(); if (is_dot(c)) // <path>/. { // Ensure that this is a directory and skip the dot if (!std::experimental::filesystem::is_directory(result)) { // Is not a directory return false; } } else if (is_dotdot(c)) // <path>/.. { result /= c; if (!std::experimental::filesystem::exists(result)) { // Upper directory is not exist return false; } } else // <path>/<other symbols> { // The path doesn't exist if (!std::experimental::filesystem::exists(result / c)) { // Path in this letter case doesn't exist... // But we'll try to find it in another case bool component_found = false; if (!std::experimental::filesystem::is_directory(result)) { // Something went wrong, we're not in a directory return false; } for (auto const &entry : std::experimental::filesystem::directory_iterator(result)) { // Get only name of the folder/file std::experimental::filesystem::path found_name = entry.path().filename(); // Move to lower case and compare path strings std::string path_str = found_name.string(); std::transform(path_str.begin(), path_str.end(), path_str.begin(), ::tolower); std::string req_str = c.string(); std::transform(req_str.begin(), req_str.end(), req_str.begin(), ::tolower); if (path_str == req_str) { // Found! component_found = true; result /= found_name; break; } } // Give up, the path really doesn't exist if (!component_found) { return false; } } else { // If the path exists, simply concatenate the result with the component result /= c; } // If the result is a symbolic link, resolve it if (std::experimental::filesystem::is_symlink(result) && resolve_symlinks) { // Get a target of the link std::experimental::filesystem::path target = std::experimental::filesystem::read_symlink(result); if (target.is_absolute()) { // The target is an absolute path // Start from the root folder on the next iteration result = target.root_path(); // And remove the root folder target = target.relative_path(); } else { // If the target is a relative path // Start from the base folder of the link on the next iteration result.remove_filename(); } // Push resolved components of the link to the container components.insert(components.begin(), target.begin(), target.end()); } } } // Final check if (!std::experimental::filesystem::exists(result)) { return false; } actual_filename = result.string(); return true; } } // namespace Baikal <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVOLImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkVOLImageIOFactory.h" #include "itkImage.h" int itkVOLImageIOTest(int ac, char* av[]) { if(ac < 2) { std::cerr << "Usage: " << av[0] << " Image\n"; return 1; } // Register at least one factory capable of producing // VOL image file readers itk::VOLImageIOFactory::RegisterOneFactory(); typedef unsigned char PixelType; typedef itk::Image<PixelType, 4> myImage; itk::ImageFileReader<myImage>::Pointer reader = itk::ImageFileReader<myImage>::New(); //reader->DebugOn(); reader->SetFileName(av[1]); try { reader->Update(); } catch (itk::ImageFileReaderException& e) { std::cout << "exception in file reader \n" << e.GetDescription(); return EXIT_FAILURE; } myImage::Pointer image = reader->GetOutput(); image->Print(std::cout); myImage::RegionType region = image->GetLargestPossibleRegion(); std::cout << "region " << region; return EXIT_SUCCESS; } <commit_msg>ENH: print parameters of header<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkVOLImageIOTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "itkImageFileReader.h" #include "itkVOLImageIOFactory.h" #include "itkVOLImageIO.h" #include "itkImage.h" int itkVOLImageIOTest(int ac, char* av[]) { if(ac < 2) { std::cerr << "Usage: " << av[0] << std::endl; return 1; } // Register at least one factory capable of producing // VOL image file readers itk::VOLImageIOFactory::RegisterOneFactory(); typedef unsigned char PixelType; typedef itk::Image<PixelType, 4> myImage; itk::VOLImageIO::Pointer io; io = itk::VOLImageIO::New(); itk::ImageFileReader<myImage>::Pointer reader = itk::ImageFileReader<myImage>::New(); //reader->DebugOn(); reader->SetFileName(av[1]); reader->SetImageIO(io); try { reader->Update(); } catch (itk::ImageFileReaderException& e) { std::cerr << "exception in file reader " << std::endl; std::cerr << e.GetDescription() << std::endl; std::cerr << e.GetLocation() << std::endl; return EXIT_FAILURE; } myImage::Pointer image = reader->GetOutput(); image->Print(std::cout); myImage::RegionType region = image->GetLargestPossibleRegion(); std::cerr << "region " << region << std::endl; // This is where we call all of the Get Functions to increase coverage. std::cerr << "File_type " << io->GetFile_type() << std::endl; std::cerr << "File_rev " << io->GetFile_rev() << std::endl; std::cerr << "Description " << io->GetDescription() << std::endl; std::cerr << "Date " << io->GetDate() << std::endl; std::cerr << "Time " << io->GetTime() << std::endl; std::cerr << "Patient " << io->GetPatient() << std::endl; std::cerr << "Clinic " << io->GetClinic() << std::endl; std::cerr << "NumEchoFrames " << io->GetNumEchoFrames() << std::endl; std::cerr << "NumDopFrames " << io->GetNumDopFrames() << std::endl; std::cerr << "Dopmode " << io->GetDopmode() << std::endl; std::cerr << "EchoLPF " << io->GetEchoLPF() << std::endl; std::cerr << "DopLPF " << io->GetDopLPF() << std::endl; std::cerr << "Repetition " << io->GetRepetition() << std::endl; std::cerr << "Xducer_name " << io->GetXducer_name() << std::endl; std::cerr << "Xducer_ID " << io->GetXducer_ID() << std::endl; std::cerr << "Xducer_freq " << io->GetXducer_freq() << std::endl; std::cerr << "Depth " << io->GetDepth() << std::endl; std::cerr << "Default_depth " << io->GetDefault_depth() << std::endl; std::cerr << "App_name " << io->GetApp_name() << std::endl; std::cerr << "Application " << io->GetApplication() << std::endl; std::cerr << "Scan_fmt " << io->GetScan_fmt() << std::endl; std::cerr << "Dataset_name " << io->GetDataset_name() << std::endl; std::cerr << "First_tx_line " << io->GetFirst_tx_line() << std::endl; std::cerr << "Last_tx_line " << io->GetLast_tx_line() << std::endl; std::cerr << "Lines " << io->GetLines() << std::endl; std::cerr << "Az_lines " << io->GetAz_lines() << std::endl; std::cerr << "Az_angle " << io->GetAz_angle() << std::endl; std::cerr << "Az_angular_separation " << io->GetAz_angular_separation() << std::endl; std::cerr << "El_lines" << io->GetEl_lines() << std::endl; std::cerr << "El_angle " << io->GetEl_angle() << std::endl; std::cerr << "El_angular_separation " << io->GetEl_angular_separation() << std::endl; std::cerr << "Tx_offset " << io->GetTx_offset() << std::endl; std::cerr << "Rx_offset " << io->GetRx_offset() << std::endl; std::cerr << "MclkFreq " << io->GetMclkFreq() << std::endl; std::cerr << "SampleSize " << io->GetSampleSize() << std::endl; std::cerr << "Mclk2Size " << io->GetMclk2Size() << std::endl; std::cerr << "SampleRate " << io->GetSampleRate() << std::endl; std::cerr << "LineGroupSize " << io->GetLineGroupSize() << std::endl; std::cerr << "NumECGSamples " << io->GetNumECGSamples() << std::endl; std::cerr << "GrayImageSize " << io->GetGrayImageSize() << std::endl; std::cerr << "DopplerImageSize " << io->GetDopplerImageSize() << std::endl; std::cerr << "EcgSize " << io->GetEcgSize() << std::endl; std::cerr << "MiscDataSize " << io->GetMiscDataSize() << std::endl; std::cerr << "GrayImageOffset " << io->GetGrayImageOffset() << std::endl; std::cerr << "DopplerImageOffset " << io->GetDopplerImageOffset() << std::endl; std::cerr << "EcgOffset " << io->GetEcgOffset() << std::endl; std::cerr << "MiscDataOffset " << io->GetMiscDataOffset() << std::endl; std::cerr << "File_control_timing_type " << io->GetFile_control_timing_type() << std::endl; std::cerr << "DopplerVolInfo " << io->GetDopplerVolInfo() << std::endl; std::cerr << "ScanDepthCount " << io->GetScanDepthCount() << std::endl; std::cerr << "ScanDepth " << io->GetScanDepth() << std::endl; std::cerr << "Az_sector_tilt " << io->GetAz_sector_tilt() << std::endl; std::cerr << "Elev_sector_tilt " << io->GetElev_sector_tilt() << std::endl; std::cerr << "DopplerSegData " << io->GetDopplerSegData() << std::endl; std::cerr << "FrameRate " << io->GetFrameRate() << std::endl; std::cerr << "Sweepspeed " << io->GetSweepspeed() << std::endl; std::cerr << "Update_interval " << io->GetUpdate_interval() << std::endl; std::cerr << "Contrast_on " << io->GetContrast_on() << std::endl; std::cerr << "Comp_curve_p0_x " << io->GetComp_curve_p0_x() << std::endl; std::cerr << "Comp_curve_p0_y " << io->GetComp_curve_p0_y() << std::endl; std::cerr << "Comp_curve_p1_x " << io->GetComp_curve_p1_x() << std::endl; std::cerr << "Comp_curve_p1_y " << io->GetComp_curve_p1_y() << std::endl; std::cerr << "Comp_curve_p2_x " << io->GetComp_curve_p2_x() << std::endl; std::cerr << "Comp_curve_p2_y " << io->GetComp_curve_p2_y() << std::endl; std::cerr << "Comp_curve_p3_x " << io->GetComp_curve_p3_x() << std::endl; std::cerr << "Comp_curve_p3_y " << io->GetComp_curve_p3_y() << std::endl; std::cerr << "Comp_curve_scaling_index " << io->GetComp_curve_scaling_index() << std::endl; std::cerr << "Echo_reject " << io->GetEcho_reject() << std::endl; std::cerr << "Mt_tp " << io->GetMt_tp() << std::endl; std::cerr << "True_axis_defined " << io->GetTrue_axis_defined() << std::endl; std::cerr << "True_axis_on " << io->GetTrue_axis_on() << std::endl; std::cerr << "Parallel_x_tilt " << io->GetParallel_x_tilt() << std::endl; std::cerr << "Parallel_y_tilt " << io->GetParallel_y_tilt() << std::endl; std::cerr << "Parallel_depth " << io->GetParallel_depth() << std::endl; std::cerr << "Parallel_spacing " << io->GetParallel_spacing() << std::endl; std::cerr << "Parallel_thickness " << io->GetParallel_thickness() << std::endl; std::cerr << "Viewport_transform_flags " << io->GetViewport_transform_flags() << std::endl; std::cerr << "Stress_mode " << io->GetStress_mode() << std::endl; std::cerr << "Stress_label " << io->GetStress_label() << std::endl; std::cerr << "Heart_rate " << io->GetHeart_rate() << std::endl; std::cerr << "Stage_timer_value " << io->GetStage_timer_value() << std::endl; std::cerr << "Ecg_display_on " << io->GetEcg_display_on() << std::endl; std::cerr << "Blanking " << io->GetBlanking() << std::endl; std::cerr << "Samples " << io->GetSamples() << std::endl; std::cerr << "ColorImageSize " << io->GetColorImageSize() << std::endl; std::cerr << "ColorImageOffset " << io->GetColorImageOffset() << std::endl; std::cerr << "Oag_params " << io->GetOag_params() << std::endl; std::cerr << "Cscanfmt " << io->GetCscanfmt() << std::endl; std::cerr << "Oaglinear " << io->GetOaglinear() << std::endl; std::cerr << "Maxradius " << io->GetMaxradius() << std::endl; std::cerr << "Anglescale " << io->GetAnglescale() << std::endl; std::cerr << "Skinoffset " << io->GetSkinoffset() << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#pragma once #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wdocumentation" #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wshadow" #endif // #include <range/v3/core.hpp> // #include <range/v3/algorithm.hpp> #include <range/v3/all.hpp> #pragma GCC diagnostic pop // https://github.com/JeffGarland/range_by_example // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>range-v3 updated<commit_after>#pragma once #pragma GCC diagnostic push #ifdef __clang__ #pragma GCC diagnostic ignored "-Wdocumentation" #pragma GCC diagnostic ignored "-Wdocumentation-unknown-command" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wshadow" #endif // #include <range/v3/core.hpp> // #include <range/v3/algorithm.hpp> #include <range/v3/all.hpp> #pragma GCC diagnostic pop // https://github.com/JeffGarland/range_by_example // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include "CSceneEffectManager.h" #include "CSceneManager.h" #include "CTextureLoader.h" #include "CShaderLoader.h" #include <algorithm> CSceneEffectManager::SRenderPass::SRenderPass() : Pass(ERenderPass::Default) {} bool const CSceneEffectManager::SRenderPass::operator == (SRenderPass const & rhs) { return Target == rhs.Target && Pass == rhs.Pass; } CSceneEffectManager::SPostProcessPass::SPostProcessPass() : Target(0), Shader(0), SetTarget(true) {} void CSceneEffectManager::SPostProcessPass::begin() { if (SetTarget) { if (Target) Target->bind(); else glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } glDisable(GL_DEPTH_TEST); Context = new CShaderContext(* Shader); } void CSceneEffectManager::SPostProcessPass::end() { if (! Context) begin(); for (std::map<std::string, CTexture *>::iterator it = Textures.begin(); it != Textures.end(); ++ it) Context->bindTexture(it->first, it->second); for (std::map<std::string, float>::iterator it = Floats.begin(); it != Floats.end(); ++ it) Context->uniform(it->first, it->second); for (std::map<std::string, int>::iterator it = Ints.begin(); it != Ints.end(); ++ it) Context->uniform(it->first, it->second); for (std::map<std::string, SColorAf>::iterator it = Colors.begin(); it != Colors.end(); ++ it) Context->uniform(it->first, it->second); Context->bindBufferObject("aPosition", CSceneManager::getQuadHandle(), 2); glDrawArrays(GL_QUADS, 0, 4); if (SetTarget) glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_DEPTH_TEST); delete Context; } void CSceneEffectManager::SPostProcessPass::doPass() { begin(); end(); } CSceneEffectManager::CSceneEffectManager(CSceneManager * sceneManager) : EnabledEffects(0), SceneManager(sceneManager), NormalPassTarget(0), NormalPassTexture(0), RandomNormalsTexture(0), BlurHorizontal(0), BlurVertical(0), BlendShader(0), White(0), Black(0), Magenta(0), Timer(0.f) { SSAOShader = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "SSAO.frag"); BlendShader = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "Blend.frag"); BlurVertical = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "BlurV.frag"); BlurHorizontal = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "BlurH.frag"); QuadCopy = CShaderLoader::loadShader("FBO/QuadCopy"); HeatCopy = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "FBO/HeatCopy.frag"); White = new CTexture(SColorf(1.f, 1.f, 1.f)); Black = new CTexture(SColorf(0.f, 0.f, 0.f)); Magenta = new CTexture(SColorf(1.f, 0.f, 1.f)); //CImage * HeatOffsetTextureImage = CTextureLoader::loadImage("HeatOffset.bmp"); STextureCreationFlags Flags; Flags.Filter = GL_LINEAR; Flags.MipMaps = false; Flags.Wrap = GL_MIRRORED_REPEAT; //HeatOffsetTexture = new CTexture(HeatOffsetTextureImage, Flags); //CImage * WaterOffsetTextureImage = CTextureLoader::loadImage("WaterOffset.bmp"); //WaterOffsetTexture = new CTexture(WaterOffsetTextureImage, Flags); ScratchTarget1 = new CFrameBufferObject(); ScratchTexture1 = new CTexture(SceneManager->getScreenSize(), true, Flags); ScratchTarget1->attach(ScratchTexture1, GL_COLOR_ATTACHMENT0); BloomResultTarget = new CFrameBufferObject(); BloomResultTexture = new CTexture(SceneManager->getScreenSize(), true); BloomResultTarget->attach(BloomResultTexture, GL_COLOR_ATTACHMENT0); SRenderPass DefaultPass; DefaultPass.Pass = ERenderPass::Default; DefaultPass.Target = SceneManager->getSceneFrameBuffer(); RenderPasses.push_back(DefaultPass); Loaded = BlendShader && QuadCopy; if (! Loaded) std::cerr << "Failed to load required shaders for effects manager - all effects disabled." << std::endl; } #include <CApplication.h> bool const CSceneEffectManager::isLoaded() const { return Loaded; } void CSceneEffectManager::apply() { if (isEffectEnabled(ESE_SSAO)) { // Draw SSAO effect SPostProcessPass SSAOPass; SSAOPass.Textures["normalMap"] = NormalPassTexture; SSAOPass.Textures["rnm"] = RandomNormalsTexture; SSAOPass.Target = SSAOResultTarget; SSAOPass.Shader = SSAOShader; SSAOPass.doPass(); if (isEffectEnabled(ESE_SSAO_BLUR)) { SPostProcessPass SSAOBlurPass1; SSAOBlurPass1.Textures["uTexColor"] = SSAOResultTexture; SSAOBlurPass1.Target = ScratchTarget1; SSAOBlurPass1.Shader = BlurVertical; SSAOBlurPass1.doPass(); SPostProcessPass SSAOBlurPass2; SSAOBlurPass2.Textures["uTexColor"] = ScratchTexture1; SSAOBlurPass2.Target = SSAOResultTarget; SSAOBlurPass2.Shader = BlurHorizontal; SSAOBlurPass2.doPass(); } } if (isEffectEnabled(ESE_BLOOM)) { // BLUR H SPostProcessPass BloomBlurPass1; BloomBlurPass1.Textures["uTexColor"] = SceneManager->getSceneFrameTexture(); BloomBlurPass1.Target = ScratchTarget1; BloomBlurPass1.Shader = BlurHorizontal; BloomBlurPass1.doPass(); // BLUR V SPostProcessPass BloomBlurPass2; BloomBlurPass2.Textures["uTexColor"] = ScratchTexture1; BloomBlurPass2.Target = BloomResultTarget; BloomBlurPass2.Shader = BlurVertical; BloomBlurPass2.doPass(); } if (EnabledEffects) { // Final Blend SPostProcessPass BlendPass; BlendPass.Textures["scene"] = SceneManager->getSceneFrameTexture(); BlendPass.Textures["ssao"] = isEffectEnabled(ESE_SSAO) ? SSAOResultTexture : White; BlendPass.Textures["bloom"] = isEffectEnabled(ESE_BLOOM) ? BloomResultTexture : Magenta; BlendPass.Target = ScratchTarget1; BlendPass.Shader = BlendShader; BlendPass.doPass(); // Copy results back into scene SPostProcessPass FinalPass; FinalPass.Textures["uTexColor"] = ScratchTexture1; FinalPass.Target = SceneManager->getSceneFrameBuffer(); if (isEffectEnabled(ESE_HEAT_WAVE) || isEffectEnabled(ESE_WATER_DISTORT)) { Timer += CApplication::get().getElapsedTime(); if (isEffectEnabled(ESE_HEAT_WAVE)) FinalPass.Textures["uHeatOffset"] = HeatOffsetTexture; else if (isEffectEnabled(ESE_WATER_DISTORT)) FinalPass.Textures["uHeatOffset"] = WaterOffsetTexture; FinalPass.Floats["uTimer"] = Timer * 0.04f; FinalPass.Target = SceneManager->getSceneFrameBuffer(); FinalPass.Shader = HeatCopy; } else { FinalPass.Shader = QuadCopy; } FinalPass.doPass(); } } void CSceneEffectManager::setEffectEnabled(ESceneEffect const Effect, bool const Enabled) { if (Enabled) { if (Effect) EnabledEffects |= Effect; else EnabledEffects = -1; } else { if (Effect) EnabledEffects ^= Effect; else EnabledEffects = 0; } switch (Effect) { case ESE_SSAO: { SRenderPass normalsPass; normalsPass.Pass = ERenderPass::ModelSpaceNormals; normalsPass.Target = NormalPassTarget; if (Enabled) { RenderPasses.push_back(normalsPass); if (! NormalPassTarget) { NormalPassTarget = new CFrameBufferObject(); NormalPassTexture = new CTexture(SceneManager->getScreenSize(), true); NormalPassTarget->attach(NormalPassTexture, GL_COLOR_ATTACHMENT0); NormalPassTarget->attach(new CRenderBufferObject(GL_DEPTH_COMPONENT, SceneManager->getScreenSize()), GL_DEPTH_ATTACHMENT); SSAOResultTarget = new CFrameBufferObject(); SSAOResultTexture = new CTexture(SceneManager->getScreenSize(), true); SSAOResultTarget->attach(SSAOResultTexture, GL_COLOR_ATTACHMENT0); RandomNormalsTexture = CTextureLoader::loadTexture("SSAO/RandNormals.bmp"); } } else { RenderPasses.erase(std::remove(RenderPasses.begin(), RenderPasses.end(), normalsPass), RenderPasses.end()); } break; } case ESE_SSAO_BLUR: break; case ESE_BLOOM: break; } } bool const CSceneEffectManager::isEffectEnabled(ESceneEffect const Effect) { return (EnabledEffects & Effect) != 0; } <commit_msg>+ Fixed bitfield clearing for scene effects<commit_after>#include "CSceneEffectManager.h" #include "CSceneManager.h" #include "CTextureLoader.h" #include "CShaderLoader.h" #include <algorithm> CSceneEffectManager::SRenderPass::SRenderPass() : Pass(ERenderPass::Default) {} bool const CSceneEffectManager::SRenderPass::operator == (SRenderPass const & rhs) { return Target == rhs.Target && Pass == rhs.Pass; } CSceneEffectManager::SPostProcessPass::SPostProcessPass() : Target(0), Shader(0), SetTarget(true) {} void CSceneEffectManager::SPostProcessPass::begin() { if (SetTarget) { if (Target) Target->bind(); else glBindFramebuffer(GL_FRAMEBUFFER, 0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } glDisable(GL_DEPTH_TEST); Context = new CShaderContext(* Shader); } void CSceneEffectManager::SPostProcessPass::end() { if (! Context) begin(); for (std::map<std::string, CTexture *>::iterator it = Textures.begin(); it != Textures.end(); ++ it) Context->bindTexture(it->first, it->second); for (std::map<std::string, float>::iterator it = Floats.begin(); it != Floats.end(); ++ it) Context->uniform(it->first, it->second); for (std::map<std::string, int>::iterator it = Ints.begin(); it != Ints.end(); ++ it) Context->uniform(it->first, it->second); for (std::map<std::string, SColorAf>::iterator it = Colors.begin(); it != Colors.end(); ++ it) Context->uniform(it->first, it->second); Context->bindBufferObject("aPosition", CSceneManager::getQuadHandle(), 2); glDrawArrays(GL_QUADS, 0, 4); if (SetTarget) glBindFramebuffer(GL_FRAMEBUFFER, 0); glEnable(GL_DEPTH_TEST); delete Context; } void CSceneEffectManager::SPostProcessPass::doPass() { begin(); end(); } CSceneEffectManager::CSceneEffectManager(CSceneManager * sceneManager) : EnabledEffects(0), SceneManager(sceneManager), NormalPassTarget(0), NormalPassTexture(0), RandomNormalsTexture(0), BlurHorizontal(0), BlurVertical(0), BlendShader(0), White(0), Black(0), Magenta(0), Timer(0.f) { SSAOShader = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "SSAO.frag"); BlendShader = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "Blend.frag"); BlurVertical = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "BlurV.frag"); BlurHorizontal = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "BlurH.frag"); QuadCopy = CShaderLoader::loadShader("FBO/QuadCopy"); HeatCopy = CShaderLoader::loadShader("FBO/QuadCopyUV.glsl", "FBO/HeatCopy.frag"); White = new CTexture(SColorf(1.f, 1.f, 1.f)); Black = new CTexture(SColorf(0.f, 0.f, 0.f)); Magenta = new CTexture(SColorf(1.f, 0.f, 1.f)); //CImage * HeatOffsetTextureImage = CTextureLoader::loadImage("HeatOffset.bmp"); STextureCreationFlags Flags; Flags.Filter = GL_LINEAR; Flags.MipMaps = false; Flags.Wrap = GL_MIRRORED_REPEAT; //HeatOffsetTexture = new CTexture(HeatOffsetTextureImage, Flags); //CImage * WaterOffsetTextureImage = CTextureLoader::loadImage("WaterOffset.bmp"); //WaterOffsetTexture = new CTexture(WaterOffsetTextureImage, Flags); ScratchTarget1 = new CFrameBufferObject(); ScratchTexture1 = new CTexture(SceneManager->getScreenSize(), true, Flags); ScratchTarget1->attach(ScratchTexture1, GL_COLOR_ATTACHMENT0); BloomResultTarget = new CFrameBufferObject(); BloomResultTexture = new CTexture(SceneManager->getScreenSize(), true); BloomResultTarget->attach(BloomResultTexture, GL_COLOR_ATTACHMENT0); SRenderPass DefaultPass; DefaultPass.Pass = ERenderPass::Default; DefaultPass.Target = SceneManager->getSceneFrameBuffer(); RenderPasses.push_back(DefaultPass); Loaded = BlendShader && QuadCopy; if (! Loaded) std::cerr << "Failed to load required shaders for effects manager - all effects disabled." << std::endl; } #include <CApplication.h> bool const CSceneEffectManager::isLoaded() const { return Loaded; } void CSceneEffectManager::apply() { if (isEffectEnabled(ESE_SSAO)) { // Draw SSAO effect SPostProcessPass SSAOPass; SSAOPass.Textures["normalMap"] = NormalPassTexture; SSAOPass.Textures["rnm"] = RandomNormalsTexture; SSAOPass.Target = SSAOResultTarget; SSAOPass.Shader = SSAOShader; SSAOPass.doPass(); if (isEffectEnabled(ESE_SSAO_BLUR)) { SPostProcessPass SSAOBlurPass1; SSAOBlurPass1.Textures["uTexColor"] = SSAOResultTexture; SSAOBlurPass1.Target = ScratchTarget1; SSAOBlurPass1.Shader = BlurVertical; SSAOBlurPass1.doPass(); SPostProcessPass SSAOBlurPass2; SSAOBlurPass2.Textures["uTexColor"] = ScratchTexture1; SSAOBlurPass2.Target = SSAOResultTarget; SSAOBlurPass2.Shader = BlurHorizontal; SSAOBlurPass2.doPass(); } } if (isEffectEnabled(ESE_BLOOM)) { // BLUR H SPostProcessPass BloomBlurPass1; BloomBlurPass1.Textures["uTexColor"] = SceneManager->getSceneFrameTexture(); BloomBlurPass1.Target = ScratchTarget1; BloomBlurPass1.Shader = BlurHorizontal; BloomBlurPass1.doPass(); // BLUR V SPostProcessPass BloomBlurPass2; BloomBlurPass2.Textures["uTexColor"] = ScratchTexture1; BloomBlurPass2.Target = BloomResultTarget; BloomBlurPass2.Shader = BlurVertical; BloomBlurPass2.doPass(); } if (EnabledEffects) { // Final Blend SPostProcessPass BlendPass; BlendPass.Textures["scene"] = SceneManager->getSceneFrameTexture(); BlendPass.Textures["ssao"] = isEffectEnabled(ESE_SSAO) ? SSAOResultTexture : White; BlendPass.Textures["bloom"] = isEffectEnabled(ESE_BLOOM) ? BloomResultTexture : Magenta; BlendPass.Target = ScratchTarget1; BlendPass.Shader = BlendShader; BlendPass.doPass(); // Copy results back into scene SPostProcessPass FinalPass; FinalPass.Textures["uTexColor"] = ScratchTexture1; FinalPass.Target = SceneManager->getSceneFrameBuffer(); if (isEffectEnabled(ESE_HEAT_WAVE) || isEffectEnabled(ESE_WATER_DISTORT)) { Timer += CApplication::get().getElapsedTime(); if (isEffectEnabled(ESE_HEAT_WAVE)) FinalPass.Textures["uHeatOffset"] = HeatOffsetTexture; else if (isEffectEnabled(ESE_WATER_DISTORT)) FinalPass.Textures["uHeatOffset"] = WaterOffsetTexture; FinalPass.Floats["uTimer"] = Timer * 0.04f; FinalPass.Target = SceneManager->getSceneFrameBuffer(); FinalPass.Shader = HeatCopy; } else { FinalPass.Shader = QuadCopy; } FinalPass.doPass(); } } void CSceneEffectManager::setEffectEnabled(ESceneEffect const Effect, bool const Enabled) { if (Enabled) { if (Effect) EnabledEffects |= Effect; else EnabledEffects = -1; } else { if (Effect) EnabledEffects &= ~Effect; else EnabledEffects = 0; } switch (Effect) { case ESE_SSAO: { SRenderPass normalsPass; normalsPass.Pass = ERenderPass::ModelSpaceNormals; normalsPass.Target = NormalPassTarget; if (Enabled) { RenderPasses.push_back(normalsPass); if (! NormalPassTarget) { NormalPassTarget = new CFrameBufferObject(); NormalPassTexture = new CTexture(SceneManager->getScreenSize(), true); NormalPassTarget->attach(NormalPassTexture, GL_COLOR_ATTACHMENT0); NormalPassTarget->attach(new CRenderBufferObject(GL_DEPTH_COMPONENT, SceneManager->getScreenSize()), GL_DEPTH_ATTACHMENT); SSAOResultTarget = new CFrameBufferObject(); SSAOResultTexture = new CTexture(SceneManager->getScreenSize(), true); SSAOResultTarget->attach(SSAOResultTexture, GL_COLOR_ATTACHMENT0); RandomNormalsTexture = CTextureLoader::loadTexture("SSAO/RandNormals.bmp"); } } else { RenderPasses.erase(std::remove(RenderPasses.begin(), RenderPasses.end(), normalsPass), RenderPasses.end()); } break; } case ESE_SSAO_BLUR: break; case ESE_BLOOM: break; } } bool const CSceneEffectManager::isEffectEnabled(ESceneEffect const Effect) { return (EnabledEffects & Effect) != 0; } <|endoftext|>
<commit_before>// Time: O(n^2) // Space: O(n) class Solution { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size()); partial_sum(A.begin(), A.end(), sum_from_start.begin()); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { int k = i; while (k <= j) { if (sum_from_start[j] - sum_from_start[k] + A[k] >= start && sum_from_start[j] - sum_from_start[k] + A[k] <= end) { ++result; } ++k; } } return result; } }; <commit_msg>Update subarray-sum-ii.cpp<commit_after>// Time: O(nlogn) // Space: O(n) class Solution { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { if (sum_from_start[j + 1] >= start) { auto l = lower_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1, sum_from_start[j + 1] - end); auto r = upper_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1, sum_from_start[j + 1] - start); if (l != sum_from_start.begin() + j + 1) { result += (r - sum_from_start.begin()) - (l - sum_from_start.begin()); } } } return result; } }; // Time: O(n^2) // Space: O(n) class Solution2 { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { int k = i; while (k <= j) { if (sum_from_start[j + 1] - sum_from_start[k] >= start && sum_from_start[j + 1] - sum_from_start[k] <= end) { ++result; } ++k; } } return result; } }; <|endoftext|>
<commit_before><commit_msg>Add the ARM variant<commit_after><|endoftext|>
<commit_before>// Time: O(nlogn) // Space: O(n) // Binary search solution. class Solution { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { auto left = lower_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1, sum_from_start[j + 1] - end); auto right = upper_bound(sum_from_start.begin(), sum_from_start.begin() + j + 1, sum_from_start[j + 1] - start); result += (right - sum_from_start.begin()) - (left - sum_from_start.begin()); } return result; } }; // Time: O(n^2) // Space: O(n) class Solution2 { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { int k = i; while (k <= j) { if (sum_from_start[j + 1] - sum_from_start[k] >= start && sum_from_start[j + 1] - sum_from_start[k] <= end) { ++result; } ++k; } } return result; } }; <commit_msg>Update subarray-sum-ii.cpp<commit_after>// Time: O(nlogn) // Space: O(n) // Binary search solution. class Solution { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { const auto left = lower_bound(sum_from_start.cbegin(), sum_from_start.cbegin() + j + 1, sum_from_start[j + 1] - end); const auto right = upper_bound(sum_from_start.cbegin(), sum_from_start.cbegin() + j + 1, sum_from_start[j + 1] - start); result += (right - sum_from_start.cbegin()) - (left - sum_from_start.cbegin()); } return result; } }; // Time: O(n^2) // Space: O(n) class Solution2 { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // sum_from_start[i] denotes sum for 0 ~ i - 1. vector<int> sum_from_start(A.size() + 1); partial_sum(A.begin(), A.end(), sum_from_start.begin() + 1); int result = 0; for (int i = 0, j = 0; j < A.size(); ++j) { int k = i; while (k <= j) { if (sum_from_start[j + 1] - sum_from_start[k] >= start && sum_from_start[j + 1] - sum_from_start[k] <= end) { ++result; } ++k; } } return result; } }; <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <string.h> #include <dxftblrd.hxx> //----------------------------------DXFLType----------------------------------- DXFLType::DXFLType() { pSucc=NULL; nFlags=0; nDashCount=0; } void DXFLType::Read(DXFGroupReader & rDGR) { long nDashIndex=-1; while (rDGR.Read()!=0) { switch (rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 3: m_sDescription = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 73: if (nDashIndex!=-1) { rDGR.SetError(); return; } nDashCount=rDGR.GetI(); if (nDashCount>DXF_MAX_DASH_COUNT) { nDashCount=DXF_MAX_DASH_COUNT; } nDashIndex=0; break; case 40: fPatternLength=rDGR.GetF(); break; case 49: if (nDashCount==-1) { rDGR.SetError(); return; } if (nDashIndex<nDashCount) { fDash[nDashIndex++]=rDGR.GetF(); } break; } } } //----------------------------------DXFLayer----------------------------------- DXFLayer::DXFLayer() { pSucc=NULL; nFlags=0; nColor=-1; } void DXFLayer::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 6: m_sLineType = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 62: nColor=rDGR.GetI(); break; } } } //----------------------------------DXFStyle----------------------------------- DXFStyle::DXFStyle() { pSucc=NULL; nFlags=0; fHeight=0.0; fWidthFak=1.0; fOblAngle=0.0; nTextGenFlags=0; fLastHeightUsed=0.0; } void DXFStyle::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 3: m_sPrimFontFile = OString(rDGR.GetS()); break; case 4: m_sBigFontFile = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 40: fHeight=rDGR.GetF(); break; case 41: fWidthFak=rDGR.GetF(); break; case 42: fLastHeightUsed=rDGR.GetF(); break; case 50: fOblAngle=rDGR.GetF(); break; case 71: nTextGenFlags=rDGR.GetI(); break; } } } //----------------------------------DXFVPort----------------------------------- DXFVPort::DXFVPort() { pSucc=NULL; nFlags=0; fMinX=0; fMinY=0; fMaxX=0; fMaxY=0; fCenterX=0; fCenterY=0; fSnapBaseX=0; fSnapBaseY=0; fSnapSapcingX=0; fSnapSpacingY=0; fGridX=0; fGridY=0; aDirection=DXFVector(0,0,1); aTarget=DXFVector(0,0,0); fHeight=0; fAspectRatio=0; fLensLength=0; fFrontClipPlane=0; fBackClipPlane=0; fTwistAngle=0; nStatus=0; nID=0; nMode=0; nCircleZoomPercent=0; nFastZoom=0; nUCSICON=0; nSnap=0; nGrid=0; nSnapStyle=0; nSnapIsopair=0; } void DXFVPort::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 10: fMinX=rDGR.GetF(); break; case 11: fMaxX=rDGR.GetF(); break; case 12: fCenterX=rDGR.GetF(); break; case 13: fSnapBaseX=rDGR.GetF(); break; case 14: fSnapSapcingX=rDGR.GetF(); break; case 15: fGridX=rDGR.GetF(); break; case 16: aDirection.fx=rDGR.GetF(); break; case 17: aTarget.fx=rDGR.GetF(); break; case 20: fMinY=rDGR.GetF(); break; case 21: fMaxY=rDGR.GetF(); break; case 22: fCenterY=rDGR.GetF(); break; case 23: fSnapBaseY=rDGR.GetF(); break; case 24: fSnapSpacingY=rDGR.GetF(); break; case 25: fGridY=rDGR.GetF(); break; case 26: aDirection.fy=rDGR.GetF(); break; case 27: aTarget.fy=rDGR.GetF(); break; case 36: aDirection.fz=rDGR.GetF(); break; case 37: aTarget.fz=rDGR.GetF(); break; case 40: fHeight=rDGR.GetF(); break; case 41: fAspectRatio=rDGR.GetF(); break; case 42: fLensLength=rDGR.GetF(); break; case 43: fFrontClipPlane=rDGR.GetF(); break; case 44: fBackClipPlane=rDGR.GetF(); break; case 51: fTwistAngle=rDGR.GetF(); break; case 68: nStatus=rDGR.GetI(); break; case 69: nID=rDGR.GetI(); break; case 70: nFlags=rDGR.GetI(); break; case 71: nMode=rDGR.GetI(); break; case 72: nCircleZoomPercent=rDGR.GetI(); break; case 73: nFastZoom=rDGR.GetI(); break; case 74: nUCSICON=rDGR.GetI(); break; case 75: nSnap=rDGR.GetI(); break; case 76: nGrid=rDGR.GetI(); break; case 77: nSnapStyle=rDGR.GetI(); break; case 78: nSnapIsopair=rDGR.GetI(); break; } } } //----------------------------------DXFTables---------------------------------- DXFTables::DXFTables() { pLTypes=NULL; pLayers=NULL; pStyles=NULL; pVPorts=NULL; } DXFTables::~DXFTables() { Clear(); } void DXFTables::Read(DXFGroupReader & rDGR) { DXFLType * * ppLT, * pLT; DXFLayer * * ppLa, * pLa; DXFStyle * * ppSt, * pSt; DXFVPort * * ppVP, * pVP; ppLT=&pLTypes; while(*ppLT!=NULL) ppLT=&((*ppLT)->pSucc); ppLa=&pLayers; while(*ppLa!=NULL) ppLa=&((*ppLa)->pSucc); ppSt=&pStyles; while(*ppSt!=NULL) ppSt=&((*ppSt)->pSucc); ppVP=&pVPorts; while(*ppVP!=NULL) ppVP=&((*ppVP)->pSucc); for (;;) { while (rDGR.GetG()!=0) rDGR.Read(); if (strcmp(rDGR.GetS(),"EOF")==0 || strcmp(rDGR.GetS(),"ENDSEC")==0) break; else if (strcmp(rDGR.GetS(),"LTYPE")==0) { pLT=new DXFLType; pLT->Read(rDGR); *ppLT=pLT; ppLT=&(pLT->pSucc); } else if (strcmp(rDGR.GetS(),"LAYER")==0) { pLa=new DXFLayer; pLa->Read(rDGR); *ppLa=pLa; ppLa=&(pLa->pSucc); } else if (strcmp(rDGR.GetS(),"STYLE")==0) { pSt=new DXFStyle; pSt->Read(rDGR); *ppSt=pSt; ppSt=&(pSt->pSucc); } else if (strcmp(rDGR.GetS(),"VPORT")==0) { pVP=new DXFVPort; pVP->Read(rDGR); *ppVP=pVP; ppVP=&(pVP->pSucc); } else rDGR.Read(); } } void DXFTables::Clear() { DXFLType * pLT; DXFLayer * pLa; DXFStyle * pSt; DXFVPort * pVP; while (pStyles!=NULL) { pSt=pStyles; pStyles=pSt->pSucc; delete pSt; } while (pLayers!=NULL) { pLa=pLayers; pLayers=pLa->pSucc; delete pLa; } while (pLTypes!=NULL) { pLT=pLTypes; pLTypes=pLT->pSucc; delete pLT; } while (pVPorts!=NULL) { pVP=pVPorts; pVPorts=pVP->pSucc; delete pVP; } } DXFLType * DXFTables::SearchLType(OString const& rName) const { DXFLType * p; for (p=pLTypes; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } DXFLayer * DXFTables::SearchLayer(OString const& rName) const { DXFLayer * p; for (p=pLayers; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } DXFVPort * DXFTables::SearchVPort(OString const& rName) const { DXFVPort * p; for (p=pVPorts; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>coverity#707818 Uninitialized scalar field<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #include <string.h> #include <dxftblrd.hxx> //----------------------------------DXFLType----------------------------------- DXFLType::DXFLType() : pSucc(NULL) , nFlags(0) , nDashCount(0) , fPatternLength(0.0) { } void DXFLType::Read(DXFGroupReader & rDGR) { long nDashIndex=-1; while (rDGR.Read()!=0) { switch (rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 3: m_sDescription = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 73: if (nDashIndex!=-1) { rDGR.SetError(); return; } nDashCount=rDGR.GetI(); if (nDashCount>DXF_MAX_DASH_COUNT) { nDashCount=DXF_MAX_DASH_COUNT; } nDashIndex=0; break; case 40: fPatternLength=rDGR.GetF(); break; case 49: if (nDashCount==-1) { rDGR.SetError(); return; } if (nDashIndex<nDashCount) { fDash[nDashIndex++]=rDGR.GetF(); } break; } } } //----------------------------------DXFLayer----------------------------------- DXFLayer::DXFLayer() { pSucc=NULL; nFlags=0; nColor=-1; } void DXFLayer::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 6: m_sLineType = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 62: nColor=rDGR.GetI(); break; } } } //----------------------------------DXFStyle----------------------------------- DXFStyle::DXFStyle() { pSucc=NULL; nFlags=0; fHeight=0.0; fWidthFak=1.0; fOblAngle=0.0; nTextGenFlags=0; fLastHeightUsed=0.0; } void DXFStyle::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 3: m_sPrimFontFile = OString(rDGR.GetS()); break; case 4: m_sBigFontFile = OString(rDGR.GetS()); break; case 70: nFlags=rDGR.GetI(); break; case 40: fHeight=rDGR.GetF(); break; case 41: fWidthFak=rDGR.GetF(); break; case 42: fLastHeightUsed=rDGR.GetF(); break; case 50: fOblAngle=rDGR.GetF(); break; case 71: nTextGenFlags=rDGR.GetI(); break; } } } //----------------------------------DXFVPort----------------------------------- DXFVPort::DXFVPort() { pSucc=NULL; nFlags=0; fMinX=0; fMinY=0; fMaxX=0; fMaxY=0; fCenterX=0; fCenterY=0; fSnapBaseX=0; fSnapBaseY=0; fSnapSapcingX=0; fSnapSpacingY=0; fGridX=0; fGridY=0; aDirection=DXFVector(0,0,1); aTarget=DXFVector(0,0,0); fHeight=0; fAspectRatio=0; fLensLength=0; fFrontClipPlane=0; fBackClipPlane=0; fTwistAngle=0; nStatus=0; nID=0; nMode=0; nCircleZoomPercent=0; nFastZoom=0; nUCSICON=0; nSnap=0; nGrid=0; nSnapStyle=0; nSnapIsopair=0; } void DXFVPort::Read(DXFGroupReader & rDGR) { while (rDGR.Read()!=0) { switch(rDGR.GetG()) { case 2: m_sName = OString(rDGR.GetS()); break; case 10: fMinX=rDGR.GetF(); break; case 11: fMaxX=rDGR.GetF(); break; case 12: fCenterX=rDGR.GetF(); break; case 13: fSnapBaseX=rDGR.GetF(); break; case 14: fSnapSapcingX=rDGR.GetF(); break; case 15: fGridX=rDGR.GetF(); break; case 16: aDirection.fx=rDGR.GetF(); break; case 17: aTarget.fx=rDGR.GetF(); break; case 20: fMinY=rDGR.GetF(); break; case 21: fMaxY=rDGR.GetF(); break; case 22: fCenterY=rDGR.GetF(); break; case 23: fSnapBaseY=rDGR.GetF(); break; case 24: fSnapSpacingY=rDGR.GetF(); break; case 25: fGridY=rDGR.GetF(); break; case 26: aDirection.fy=rDGR.GetF(); break; case 27: aTarget.fy=rDGR.GetF(); break; case 36: aDirection.fz=rDGR.GetF(); break; case 37: aTarget.fz=rDGR.GetF(); break; case 40: fHeight=rDGR.GetF(); break; case 41: fAspectRatio=rDGR.GetF(); break; case 42: fLensLength=rDGR.GetF(); break; case 43: fFrontClipPlane=rDGR.GetF(); break; case 44: fBackClipPlane=rDGR.GetF(); break; case 51: fTwistAngle=rDGR.GetF(); break; case 68: nStatus=rDGR.GetI(); break; case 69: nID=rDGR.GetI(); break; case 70: nFlags=rDGR.GetI(); break; case 71: nMode=rDGR.GetI(); break; case 72: nCircleZoomPercent=rDGR.GetI(); break; case 73: nFastZoom=rDGR.GetI(); break; case 74: nUCSICON=rDGR.GetI(); break; case 75: nSnap=rDGR.GetI(); break; case 76: nGrid=rDGR.GetI(); break; case 77: nSnapStyle=rDGR.GetI(); break; case 78: nSnapIsopair=rDGR.GetI(); break; } } } //----------------------------------DXFTables---------------------------------- DXFTables::DXFTables() { pLTypes=NULL; pLayers=NULL; pStyles=NULL; pVPorts=NULL; } DXFTables::~DXFTables() { Clear(); } void DXFTables::Read(DXFGroupReader & rDGR) { DXFLType * * ppLT, * pLT; DXFLayer * * ppLa, * pLa; DXFStyle * * ppSt, * pSt; DXFVPort * * ppVP, * pVP; ppLT=&pLTypes; while(*ppLT!=NULL) ppLT=&((*ppLT)->pSucc); ppLa=&pLayers; while(*ppLa!=NULL) ppLa=&((*ppLa)->pSucc); ppSt=&pStyles; while(*ppSt!=NULL) ppSt=&((*ppSt)->pSucc); ppVP=&pVPorts; while(*ppVP!=NULL) ppVP=&((*ppVP)->pSucc); for (;;) { while (rDGR.GetG()!=0) rDGR.Read(); if (strcmp(rDGR.GetS(),"EOF")==0 || strcmp(rDGR.GetS(),"ENDSEC")==0) break; else if (strcmp(rDGR.GetS(),"LTYPE")==0) { pLT=new DXFLType; pLT->Read(rDGR); *ppLT=pLT; ppLT=&(pLT->pSucc); } else if (strcmp(rDGR.GetS(),"LAYER")==0) { pLa=new DXFLayer; pLa->Read(rDGR); *ppLa=pLa; ppLa=&(pLa->pSucc); } else if (strcmp(rDGR.GetS(),"STYLE")==0) { pSt=new DXFStyle; pSt->Read(rDGR); *ppSt=pSt; ppSt=&(pSt->pSucc); } else if (strcmp(rDGR.GetS(),"VPORT")==0) { pVP=new DXFVPort; pVP->Read(rDGR); *ppVP=pVP; ppVP=&(pVP->pSucc); } else rDGR.Read(); } } void DXFTables::Clear() { DXFLType * pLT; DXFLayer * pLa; DXFStyle * pSt; DXFVPort * pVP; while (pStyles!=NULL) { pSt=pStyles; pStyles=pSt->pSucc; delete pSt; } while (pLayers!=NULL) { pLa=pLayers; pLayers=pLa->pSucc; delete pLa; } while (pLTypes!=NULL) { pLT=pLTypes; pLTypes=pLT->pSucc; delete pLT; } while (pVPorts!=NULL) { pVP=pVPorts; pVPorts=pVP->pSucc; delete pVP; } } DXFLType * DXFTables::SearchLType(OString const& rName) const { DXFLType * p; for (p=pLTypes; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } DXFLayer * DXFTables::SearchLayer(OString const& rName) const { DXFLayer * p; for (p=pLayers; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } DXFVPort * DXFTables::SearchVPort(OString const& rName) const { DXFVPort * p; for (p=pVPorts; p!=NULL; p=p->pSucc) { if (rName == p->m_sName) break; } return p; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/* * Arithmetic for prime fields GF(p) * * (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke * 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/gfp_element.h> #include <botan/numthry.h> #include <botan/internal/def_powm.h> #include <botan/internal/mp_asm.h> #include <botan/internal/mp_asmi.h> namespace Botan { GFpElement& GFpElement::operator+=(const GFpElement& rhs) { m_value += rhs.m_value; if(m_value >= mod_p) m_value -= mod_p; return *this; } GFpElement& GFpElement::operator-=(const GFpElement& rhs) { m_value -= rhs.m_value; if(m_value.is_negative()) m_value += mod_p; return *this; } GFpElement& GFpElement::operator*=(u32bit rhs) { m_value *= rhs; m_value %= mod_p; return *this; } GFpElement& GFpElement::operator*=(const GFpElement& rhs) { m_value *= rhs.m_value; m_value %= mod_p; return *this; } GFpElement& GFpElement::operator/=(const GFpElement& rhs) { GFpElement inv_rhs(rhs); inv_rhs.inverse_in_place(); *this *= inv_rhs; return *this; } GFpElement& GFpElement::inverse_in_place() { m_value = inverse_mod(m_value, mod_p); return *this; } GFpElement& GFpElement::negate() { m_value = mod_p - m_value; return *this; } void GFpElement::swap(GFpElement& other) { std::swap(m_value, other.m_value); std::swap(mod_p, other.mod_p); } bool operator==(const GFpElement& lhs, const GFpElement& rhs) { return (lhs.get_p() == rhs.get_p() && lhs.get_value() == rhs.get_value()); } GFpElement operator+(const GFpElement& lhs, const GFpElement& rhs) { // consider the case that lhs and rhs both use montgm: // then += returns an element which uses montgm. // thus the return value of op+ here will be an element // using montgm in this case GFpElement result(lhs); result += rhs; return result; } GFpElement operator-(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result(lhs); result -= rhs; return result; } GFpElement operator-(const GFpElement& lhs) { return(GFpElement(lhs)).negate(); } GFpElement operator*(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result(lhs); result *= rhs; return result; } GFpElement operator*(const GFpElement& lhs, u32bit rhs) { GFpElement result(lhs); result *= rhs; return result; } GFpElement operator*(u32bit lhs, const GFpElement& rhs) { return rhs*lhs; } GFpElement operator/(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result (lhs); result /= rhs; return result; } SecureVector<byte> FE2OSP(const GFpElement& elem) { return BigInt::encode_1363(elem.get_value(), elem.get_p().bytes()); } GFpElement OS2FEP(MemoryRegion<byte> const& os, BigInt p) { return GFpElement(p, BigInt::decode(os.begin(), os.size())); } GFpElement inverse(const GFpElement& elem) { return GFpElement(elem).inverse_in_place(); } } <commit_msg>Remove include of unused headers<commit_after>/* * Arithmetic for prime fields GF(p) * * (C) 2007 Martin Doering, Christoph Ludwig, Falko Strenzke * 2008-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/gfp_element.h> #include <botan/numthry.h> namespace Botan { GFpElement& GFpElement::operator+=(const GFpElement& rhs) { m_value += rhs.m_value; if(m_value >= mod_p) m_value -= mod_p; return *this; } GFpElement& GFpElement::operator-=(const GFpElement& rhs) { m_value -= rhs.m_value; if(m_value.is_negative()) m_value += mod_p; return *this; } GFpElement& GFpElement::operator*=(u32bit rhs) { m_value *= rhs; m_value %= mod_p; return *this; } GFpElement& GFpElement::operator*=(const GFpElement& rhs) { m_value *= rhs.m_value; m_value %= mod_p; return *this; } GFpElement& GFpElement::operator/=(const GFpElement& rhs) { GFpElement inv_rhs(rhs); inv_rhs.inverse_in_place(); *this *= inv_rhs; return *this; } GFpElement& GFpElement::inverse_in_place() { m_value = inverse_mod(m_value, mod_p); return *this; } GFpElement& GFpElement::negate() { m_value = mod_p - m_value; return *this; } void GFpElement::swap(GFpElement& other) { std::swap(m_value, other.m_value); std::swap(mod_p, other.mod_p); } bool operator==(const GFpElement& lhs, const GFpElement& rhs) { return (lhs.get_p() == rhs.get_p() && lhs.get_value() == rhs.get_value()); } GFpElement operator+(const GFpElement& lhs, const GFpElement& rhs) { // consider the case that lhs and rhs both use montgm: // then += returns an element which uses montgm. // thus the return value of op+ here will be an element // using montgm in this case GFpElement result(lhs); result += rhs; return result; } GFpElement operator-(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result(lhs); result -= rhs; return result; } GFpElement operator-(const GFpElement& lhs) { return(GFpElement(lhs)).negate(); } GFpElement operator*(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result(lhs); result *= rhs; return result; } GFpElement operator*(const GFpElement& lhs, u32bit rhs) { GFpElement result(lhs); result *= rhs; return result; } GFpElement operator*(u32bit lhs, const GFpElement& rhs) { return rhs*lhs; } GFpElement operator/(const GFpElement& lhs, const GFpElement& rhs) { GFpElement result (lhs); result /= rhs; return result; } SecureVector<byte> FE2OSP(const GFpElement& elem) { return BigInt::encode_1363(elem.get_value(), elem.get_p().bytes()); } GFpElement OS2FEP(MemoryRegion<byte> const& os, BigInt p) { return GFpElement(p, BigInt::decode(os.begin(), os.size())); } GFpElement inverse(const GFpElement& elem) { return GFpElement(elem).inverse_in_place(); } } <|endoftext|>
<commit_before>// // Created by vrosca on 1/21/17. // #include "ProviderFactory.hpp" #include "Providers/ArrivalsProvider.hpp" #include "Providers/DeparturesProvider.hpp" #include "Providers/AutocompleteProvider.hpp" #include "Providers/ErrorProvider.hpp" ProviderFactory* ProviderFactory::instance = nullptr; ProviderFactory& ProviderFactory::GetInstance() { if (instance == nullptr) { instance = new ProviderFactory(); } return *instance; } Provider* ProviderFactory::produce (json request) { try { std::string action = request["action"].get<std::string>(); if (action == "arrivals") return new ArrivalsProvider( request["station"].get<std::string>(), request["country"].get<std::string>(), Calendar::fromJSON(request["time"])); else if (action == "departures") return new DeparturesProvider( request["station"].get<std::string>(), request["country"].get<std::string>(), Calendar::fromJSON(request["time"])); else if (action == "autocomplete") return new AutocompleteProvider( request["prefix"].get<std::string>(), request["lat"], request["lng"]); else throw std::ios_base::failure("Field action missing from request"); } catch (std::domain_error &e) { Logger::GetInstance().loge("Invalid request to database"); Logger::GetInstance().loge(e.what()); return new ErrorProvider ("Invalid request to database"); } }<commit_msg>Detect missing action error<commit_after>// // Created by vrosca on 1/21/17. // #include "ProviderFactory.hpp" #include "Providers/ArrivalsProvider.hpp" #include "Providers/DeparturesProvider.hpp" #include "Providers/AutocompleteProvider.hpp" #include "Providers/ErrorProvider.hpp" ProviderFactory* ProviderFactory::instance = nullptr; ProviderFactory& ProviderFactory::GetInstance() { if (instance == nullptr) { instance = new ProviderFactory(); } return *instance; } Provider* ProviderFactory::produce (json request) { try { std::string action = request["action"].get<std::string>(); if (action == "arrivals") return new ArrivalsProvider( request["station"].get<std::string>(), request["country"].get<std::string>(), Calendar::fromJSON(request["time"])); else if (action == "departures") return new DeparturesProvider( request["station"].get<std::string>(), request["country"].get<std::string>(), Calendar::fromJSON(request["time"])); else if (action == "autocomplete") return new AutocompleteProvider( request["prefix"].get<std::string>(), request["lat"], request["lng"]); else return new ErrorProvider("Field action missing from request"); } catch (std::domain_error &e) { Logger::GetInstance().loge("Invalid request to database"); Logger::GetInstance().loge(e.what()); return new ErrorProvider ("The request is missing field"); } }<|endoftext|>
<commit_before>/** * @file ct2ctml.cpp * * $Author$ * $Revision$ * $Date$ */ // Copyright 2001 California Institute of Technology // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ct_defs.h" #include "ctexceptions.h" #include <fstream> #include <string> #include <stdlib.h> #include <time.h> #include "ctml.h" using namespace Cantera; namespace ctml { // return the full path to the Python interpreter. Use // environment variable PYTHON_CMD if it is set, otherwise use the // definition PYTHON_EXE if it is defined. Failing that, return // the string 'python'. static string pypath() { string s = "python"; const char* py = getenv("PYTHON_CMD"); if (py) { s = string(py); } #ifdef PYTHON_EXE else { s = string(PYTHON_EXE); } #endif return s; } static bool checkPython() { time_t aclock; time( &aclock ); int ia = static_cast<int>(aclock); string path = tmpDir() + "/.check"+int2str(ia)+".pyw"; ofstream f(path.c_str()); if (!f) { throw CanteraError("checkPython","cannot open "+path+" for writing"); } f << "from Cantera import ctml_writer\n"; f.close(); int ierr = 0; #ifdef WIN32 string cmd = "cmd /C "+pypath() + " " + path + ">> log 2>&1"; #else string cmd = pypath() + " " + path + " &> " + tmpDir() + "/log"; #endif try { ierr = system(cmd.c_str()); if (ierr != 0) { string msg; msg = cmd +"\n\n########################################################################\n\n" "The Cantera Python interface is required in order to process\n" "Cantera input files, but it does not seem to be correctly installed.\n\n" "Check that you can invoke the Python interpreter with \n" "the command \"python\", and that typing \"from Cantera import *\" \n" "at the Python prompt does not produce an error. If Python on your system\n" "is invoked with some other command, set environment variable PYTHON_CMD\n" "to the full path to the Python interpreter. \n\n" "#########################################################################\n\n"; writelog(msg); return false; } } catch (...) { return false; } #ifdef WIN32 cmd = "cmd /C rm " + path; #else cmd = "rm -f " + path; try { system(cmd.c_str()); } catch (...) { ; } #endif return true; } void ct2ctml(const char* file) { time_t aclock; time( &aclock ); int ia = static_cast<int>(aclock); string path = tmpDir()+"/.cttmp"+int2str(ia)+".pyw"; ofstream f(path.c_str()); if (!f) { throw CanteraError("ct2ctml","cannot open "+path+" for writing."); } f << "from ctml_writer import *\n" << "import sys, os, os.path\n" << "file = \"" << file << "\"\n" << "base = os.path.basename(file)\n" << "root, ext = os.path.splitext(base)\n" << "dataset(root)\n" << "execfile(file)\n" << "write()\n"; f.close(); #ifdef WIN32 string cmd = pypath() + " " + path + "> ct2ctml.log 2>&1"; #else string cmd = pypath() + " " + path + " &> ct2ctml.log"; #endif #ifdef DEBUG_PATHS cout << "ct2ctml: executing the command " << cmd << endl; #endif int ierr = 0; try { ierr = system(cmd.c_str()); } catch (...) { ierr = -10; } /* * HKM -> This next section may seem a bit weird. However, * it is in response to an issue that arises when * running cantera with cygwin, using cygwin's * python intepreter. Basically, the xml file is * written to the local directory by the last * system command. Then, the xml file is read * immediately after by an ifstream() c++ * command. Unfortunately, it seems that the * directory info is not being synched fast enough * so that the ifstream() read fails, even * though the file is actually there. Putting in a * sleep system call here fixes this problem. Also, * having the xml file pre-existing fixes the * problem as well. There may be more direct ways * to fix this bug; however, I am not aware of them. */ #if defined(CYGWIN) #ifdef DEBUG_PATHS cout << "sleeping for 3 secs" << endl; #endif cmd = "sleep 3"; try { ierr = system(cmd.c_str()); } catch (...) { ierr = -10; } #endif try { char ch=0; string s = ""; ifstream ferr("ct2ctml.log"); if (ferr) { while (!ferr.eof()) { ferr.get(ch); s += ch; if (ch == '\n') { writelog(s); s = ""; } } ferr.close(); } } catch (...) { ; } if (ierr != 0) { string msg = cmd; bool pyok = checkPython(); if (!pyok) msg += "\nError in Python installation."; else msg += "\nCheck error messages above for syntax errors."; throw CanteraError("ct2ctml", "could not convert input file to CTML\n " "command line was: " + msg); } #ifndef DEBUG_PATHS #ifdef WIN32 cmd = "cmd /C rm " + path; #else cmd = "rm -f " + path; try { system(cmd.c_str()); } catch (...) { ; } #endif #endif } /** * Get an CTML tree from a file, possibly preprocessing the file * first. */ void get_CTML_Tree(XML_Node* rootPtr, string file) { string ff, ext = ""; // find the input file on the Cantera search path string inname = findInputFile(file); #ifdef DEBUG_PATHS cout <<"Found file: " << inname << endl; #endif if (inname == "") throw CanteraError("get_CTML_tree", "file "+file+" not found"); /** * Check whether or not the file is XML. If not, it will be first * processed with the preprocessor. */ string::size_type idot = inname.rfind('.'); if (idot != string::npos) { ext = inname.substr(idot, inname.size()); } if (ext != ".xml" && ext != ".ctml") { ct2ctml(inname.c_str()); ff = inname.substr(0,idot) + ".xml"; } else { ff = inname; } #ifdef DEBUG_PATHS cout << "Attempting to parse xml file " << ff << endl; #endif ifstream fin(ff.c_str()); if (!fin) { throw CanteraError("get_CTML_tree", "XML file " + ff + " not found"); } rootPtr->build(fin); fin.close(); } } <commit_msg>minor cleanup<commit_after>/** * @file ct2ctml.cpp * * $Author$ * $Revision$ * $Date$ */ // Copyright 2001 California Institute of Technology // turn off warnings under Windows #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "ct_defs.h" #include "ctexceptions.h" #include <fstream> #include <string> #include <stdlib.h> #include <time.h> #include "ctml.h" //#define DEBUG_PATHS using namespace Cantera; namespace ctml { // return the full path to the Python interpreter. Use // environment variable PYTHON_CMD if it is set, otherwise use the // definition PYTHON_EXE if it is defined. Failing that, return // the string 'python'. static string pypath() { string s = "python"; const char* py = getenv("PYTHON_CMD"); if (py) { string sp = stripws(string(py)); if (sp.size() > 0) s = sp; } #ifdef PYTHON_EXE else { string se = stripws(string(PYTHON_EXE)); if (se.size() > 0) s = se; } #endif return s; } static bool checkPython() { time_t aclock; time( &aclock ); int ia = static_cast<int>(aclock); string path = tmpDir() + "/.check"+int2str(ia)+".pyw"; ofstream f(path.c_str()); if (!f) { throw CanteraError("checkPython","cannot open "+path+" for writing"); } f << "from Cantera import ctml_writer\n"; f.close(); int ierr = 0; #ifdef WIN32 string cmd = "cmd /C "+pypath() + " " + path + ">> log 2>&1"; #else string cmd = pypath() + " " + path + " &> " + tmpDir() + "/log"; #endif try { ierr = system(cmd.c_str()); if (ierr != 0) { string msg; msg = cmd +"\n\n########################################################################\n\n" "The Cantera Python interface is required in order to process\n" "Cantera input files, but it does not seem to be correctly installed.\n\n" "Check that you can invoke the Python interpreter with \n" "the command \"python\", and that typing \"from Cantera import *\" \n" "at the Python prompt does not produce an error. If Python on your system\n" "is invoked with some other command, set environment variable PYTHON_CMD\n" "to the full path to the Python interpreter. \n\n" "#########################################################################\n\n"; writelog(msg); return false; } } catch (...) { return false; } #ifdef WIN32 cmd = "cmd /C rm " + path; #else cmd = "rm -f " + path; try { system(cmd.c_str()); } catch (...) { ; } #endif return true; } void ct2ctml(const char* file) { time_t aclock; time( &aclock ); int ia = static_cast<int>(aclock); string path = tmpDir()+"/.cttmp"+int2str(ia)+".pyw"; ofstream f(path.c_str()); if (!f) { throw CanteraError("ct2ctml","cannot open "+path+" for writing."); } f << "from ctml_writer import *\n" << "import sys, os, os.path\n" << "file = \"" << file << "\"\n" << "base = os.path.basename(file)\n" << "root, ext = os.path.splitext(base)\n" << "dataset(root)\n" << "execfile(file)\n" << "write()\n"; f.close(); #ifdef WIN32 string cmd = pypath() + " " + path + "> ct2ctml.log 2>&1"; #else string cmd = pypath() + " " + path + " &> ct2ctml.log"; #endif #ifdef DEBUG_PATHS writelog("ct2ctml: executing the command " + cmd + "\n"); #endif int ierr = 0; try { ierr = system(cmd.c_str()); } catch (...) { ierr = -10; } /* * HKM -> This next section may seem a bit weird. However, * it is in response to an issue that arises when * running cantera with cygwin, using cygwin's * python intepreter. Basically, the xml file is * written to the local directory by the last * system command. Then, the xml file is read * immediately after by an ifstream() c++ * command. Unfortunately, it seems that the * directory info is not being synched fast enough * so that the ifstream() read fails, even * though the file is actually there. Putting in a * sleep system call here fixes this problem. Also, * having the xml file pre-existing fixes the * problem as well. There may be more direct ways * to fix this bug; however, I am not aware of them. */ #if defined(CYGWIN) #ifdef DEBUG_PATHS writelog("sleeping for 3 secs+\n"); #endif cmd = "sleep 3"; try { ierr = system(cmd.c_str()); } catch (...) { ierr = -10; } #endif try { char ch=0; string s = ""; ifstream ferr("ct2ctml.log"); if (ferr) { while (!ferr.eof()) { ferr.get(ch); s += ch; if (ch == '\n') { writelog(s); s = ""; } } ferr.close(); } } catch (...) { ; } if (ierr != 0) { string msg = cmd; bool pyok = checkPython(); if (!pyok) msg += "\nError in Python installation."; else msg += "\nCheck error messages above for syntax errors."; throw CanteraError("ct2ctml", "could not convert input file to CTML\n " "command line was: " + msg); } #ifndef DEBUG_PATHS #ifdef WIN32 cmd = "cmd /C rm " + path; #else cmd = "rm -f " + path; try { if (ierr == 0) system(cmd.c_str()); } catch (...) { ; } #endif #endif } /** * Get an CTML tree from a file, possibly preprocessing the file * first. */ void get_CTML_Tree(XML_Node* rootPtr, string file) { string ff, ext = ""; // find the input file on the Cantera search path string inname = findInputFile(file); #ifdef DEBUG_PATHS writelog("Found file: "+inname+"\n"); #endif if (inname == "") throw CanteraError("get_CTML_tree", "file "+file+" not found"); /** * Check whether or not the file is XML. If not, it will be first * processed with the preprocessor. */ string::size_type idot = inname.rfind('.'); if (idot != string::npos) { ext = inname.substr(idot, inname.size()); } if (ext != ".xml" && ext != ".ctml") { ct2ctml(inname.c_str()); ff = inname.substr(0,idot) + ".xml"; } else { ff = inname; } #ifdef DEBUG_PATHS writelog("Attempting to parse xml file " + ff + "\n"); #endif ifstream fin(ff.c_str()); if (!fin) { throw CanteraError("get_CTML_tree", "XML file " + ff + " not found"); } rootPtr->build(fin); fin.close(); } } <|endoftext|>
<commit_before>#include <QRegExp> #include <QStringList> #include "HostMask" #include "Connection" using namespace QIRC; /// \brief Construct without server information Connection::Connection() : m_currentServer("127.0.0.1", 6667), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } /// \brief Construct from given ServerInfo Connection::Connection(const ServerInfo& si) : m_currentServer(si), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } /// \brief Construct from host/port Connection::Connection(QString h, quint16 p) : m_currentServer(h, p), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick ("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } Connection::~Connection() { if (m_tMessageQueue != NULL) { delete m_tMessageQueue; } if (m_socket != NULL) { delete m_socket; } } /// \brief Connect to IRC server void Connection::connect() { if (m_connected) { // already connected to a server; disconnect first disconnect(); } m_socket->connectToHost(m_currentServer.host(), m_currentServer.port()); } /// \brief Disconnect from IRC server void Connection::disconnect() { m_socket->disconnectFromHost(); } /// \brief Access current server for this connection ServerInfo Connection::server() const { return m_currentServer; } /// \brief Set current server for this connection /// /// \attention This method will disconnect from the current /// server and connect to the new one if they differ. void Connection::setServer(const ServerInfo& si) { if (si != m_currentServer) { // disconnect from current server if we're connected bool connStatus = m_connected; if (connStatus) disconnect(); m_currentServer = si; // only reconnect if we were previously connected if (connStatus) connect(); } } /// \brief Set current server for this connection void Connection::setServer(QString h, quint16 p) { ServerInfo si(h, p); setServer(si); } /// \brief Set up m_socket /// /// Creates the QTcpSocket instance for m_socket bool Connection::setupSocket() { if (m_socket != NULL) { qWarning() << "Called Connection::setupSocket with non-null m_socket!"; delete m_socket; } try { m_socket = new QTcpSocket(this); } catch (std::bad_alloc &ex) { qCritical() << "Caught std::bad_alloc when trying to setup " << "Connection::m_socket: " << ex.what(); return false; } // connect the socket's signals to our slots QObject::connect(m_socket, SIGNAL(connected()), this, SLOT(socket_connected())); QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(socket_disconnected())); QObject::connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socket_error(QAbstractSocket::SocketError))); QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(socket_readyRead())); return true; } /// \brief Slot for m_socket::connected() void Connection::socket_connected() { m_connected = true; // authenticate to server if we have a password set for // the connection authenticate(); emit connected(m_currentServer); } /// \brief Slot for m_socket::disconnected() void Connection::socket_disconnected() { m_messageQueue.clear(); m_connected = false; emit disconnected(m_currentServer); } /// \brief Slot for m_socket::error() /// /// This slot is connected to the error() signal of m_socket. /// It fetches the error message belonging to err and re-emits /// the signal to the controlling application as /// socketError(). /// /// \param err Socket error as received from m_socket's error() signal void Connection::socket_error(QAbstractSocket::SocketError err) { QString msg = m_socket->errorString(); qWarning() << "Connection::m_socket (connected to" << m_currentServer << ") generated an error: " << msg; emit socketError(err, msg); } /// \brief Slot for m_socket::readyRead() void Connection::socket_readyRead() { QString line; while (m_socket->canReadLine()) { line = m_socket->readLine(); if (!line.isNull()) { if (!parseMessage(line.trimmed())) { qDebug() << "Unable to parse message:" << line.trimmed(); } } } } /// \brief Set server password to new value void Connection::setServerPassword(QString password) { m_serverPassword = password; } /// \brief Return current server password QString Connection::serverPassword() const { return m_serverPassword; } /// \brief Set ident user ID void Connection::setIdent(QString ident) { m_ident = ident; } /// \brief Return current ident user ID QString Connection::ident() const { return m_ident; } /// \brief Set nickname to new value void Connection::setNick(QString nick) { m_nick = nick; } /// \brief Return current nickname QString Connection::nick() const { return m_nick; } /// \brief Set real name to use on IRC void Connection::setRealName(QString realName) { m_realName = realName; } /// \brief Return real name used on IRC QString Connection::realName() const { return m_realName; } /// \brief Send message to server /// /// Sends the given message to the IRC server. A message can be either /// queued or sent right away. The message Queue is checked by m_tMessageQueue /// every 10ms. /// /// \param msg Message text /// \param queued Flag to indicate wether the message should be queued /// or sent right away void Connection::sendMessage(QString msg, bool queued=true) { if (m_connected) { if (!queued) { QTextStream s(m_socket); s << msg.trimmed() << "\n"; } else { m_messageQueue.append(msg.trimmed() + "\n"); } } else { qWarning() << "Tried to use Connection::sendMessage() while " << "m_connected!=true! Message was:" << msg.trimmed(); } } /// \brief Authenticate connection /// /// Authenticates to the IRC server by sending USER/NICK messages. /// /// If m_serverPassword is set this method will also send a PASS /// message to the server to authenticate with a password before /// any of the others are sent. void Connection::authenticate() { if (!m_connected) { qWarning() << "Tried to use Connection::authenticat() while " << "m_connected!=true!"; } if (m_serverPassword.length() > 0) { sendMessage("PASS " + m_serverPassword, false); } // USER username hostname servername: realname sendMessage("USER " + m_ident + " " + m_currentServer.host() + " " + m_currentServer.host() + ": " + m_realName, false); // NICK nickname sendMessage("NICK " + m_nick, false); } /// \brief Are we currently connected? bool Connection::isConnected() const { return m_connected; } /// \brief Parse incoming message bool Connection::parseMessage(QString msg) { static const QRegExp reNOTICE_AUTH("^:(.+) NOTICE AUTH :(.+)$"); if (reNOTICE_AUTH.exactMatch(msg)) { QStringList tmp = reNOTICE_AUTH.capturedTexts(); QString serverName = tmp.value(1); QString message = tmp.value(2); emit irc_notice_auth(serverName, message); return true; } static const QRegExp reNumeric(":(.+) ([0-9]{3}) (.+) :(.+)$"); if (reNumeric.exactMatch(msg)) { QStringList tmp = reNumeric.capturedTexts(); QString serverName = tmp.value(1); int messageNumber = tmp.value(2).toInt(); QString target = tmp.value(3); QString message = tmp.value(4); // TODO(png): handle numeric messages according to RFC1459 return true; } static const QRegExp reNOTICE(":(.+)!(.+)@(.+) NOTICE ([\\w#\\-]+) :(.+)$"); if (reNOTICE.exactMatch(msg)) { QStringList tmp = reNOTICE.capturedTexts(); HostMask sender(tmp.value(1), tmp.value(2), tmp.value(3)); QString target = tmp.value(4); QString message = tmp.value(5); emit irc_notice(sender, target, message); return true; } static const QRegExp reMODE(":(.+)!(.+)@(.+) MODE ([\\w#\\-]+) :(.+)$"); if (reMODE.exactMatch(msg)) { QStringList tmp = reMODE.capturedTexts(); HostMask sender(tmp.value(1), tmp.value(2), tmp.value(3)); QString target = tmp.value(4); QString modeString = tmp.value(5); // TODO(png): emit signals for user/channel modes separately return true; } // PING: <servername> static const QRegExp rePING("^PING :(.+)$"); if (rePING.exactMatch(msg)) { QString serverName = rePING.capturedTexts().value(1); sendPong(serverName); emit irc_ping(serverName); return true; } return false; } /// \brief Send PONG response to PING command void Connection::sendPong(QString serverName) { sendMessage("PONG " + serverName, false); } /// \brief Setup queue for outbound messages bool Connection::setupMessageQueue() { try { m_tMessageQueue = new QTimer(this); } catch (std::bad_alloc& ex) { qCritical() << "Unable to allocate memory for " << "Connection::m_tMessageQueue:" << ex.what(); return false; } m_tMessageQueue->setInterval(10); QObject::connect(m_tMessageQueue, SIGNAL(timeout()), this, SLOT(timer_messageQueue())); return true; } /// \brief Slot for m_tMessageQueue::timeout() /// /// This slot is connected to the timeout() signal of m_tMessageQueue. /// It fetches the first message from the queue and sends it to the IRC /// server. If no messages are queued it simply does nothing. void Connection::timer_messageQueue() { if (!m_messageQueue.isEmpty()) { QString message = m_messageQueue.takeFirst(); QTextStream s(m_socket); s << message; } } <commit_msg>properly start/stop message queue timer on connect/disconnect events<commit_after>#include <QRegExp> #include <QStringList> #include "HostMask" #include "Connection" using namespace QIRC; /// \brief Construct without server information Connection::Connection() : m_currentServer("127.0.0.1", 6667), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } /// \brief Construct from given ServerInfo Connection::Connection(const ServerInfo& si) : m_currentServer(si), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } /// \brief Construct from host/port Connection::Connection(QString h, quint16 p) : m_currentServer(h, p), m_socket(NULL), m_serverPassword(""), m_connected(false), m_ident("QIRC"), m_nick ("QIRC"), m_realName("QIRC"), m_tMessageQueue(NULL) { if (!setupSocket()) { qCritical() << "Connection: Unable to setup m_socket!"; exit(1); } if (!setupMessageQueue()) { qCritical() << "Connection: Unable to setup m_tMessageQueue!"; exit(1); } } Connection::~Connection() { if (m_tMessageQueue != NULL) { delete m_tMessageQueue; } if (m_socket != NULL) { delete m_socket; } } /// \brief Connect to IRC server void Connection::connect() { if (m_connected) { // already connected to a server; disconnect first disconnect(); } m_socket->connectToHost(m_currentServer.host(), m_currentServer.port()); } /// \brief Disconnect from IRC server void Connection::disconnect() { m_socket->disconnectFromHost(); } /// \brief Access current server for this connection ServerInfo Connection::server() const { return m_currentServer; } /// \brief Set current server for this connection /// /// \attention This method will disconnect from the current /// server and connect to the new one if they differ. void Connection::setServer(const ServerInfo& si) { if (si != m_currentServer) { // disconnect from current server if we're connected bool connStatus = m_connected; if (connStatus) disconnect(); m_currentServer = si; // only reconnect if we were previously connected if (connStatus) connect(); } } /// \brief Set current server for this connection void Connection::setServer(QString h, quint16 p) { ServerInfo si(h, p); setServer(si); } /// \brief Set up m_socket /// /// Creates the QTcpSocket instance for m_socket bool Connection::setupSocket() { if (m_socket != NULL) { qWarning() << "Called Connection::setupSocket with non-null m_socket!"; delete m_socket; } try { m_socket = new QTcpSocket(this); } catch (std::bad_alloc &ex) { qCritical() << "Caught std::bad_alloc when trying to setup " << "Connection::m_socket: " << ex.what(); return false; } // connect the socket's signals to our slots QObject::connect(m_socket, SIGNAL(connected()), this, SLOT(socket_connected())); QObject::connect(m_socket, SIGNAL(disconnected()), this, SLOT(socket_disconnected())); QObject::connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socket_error(QAbstractSocket::SocketError))); QObject::connect(m_socket, SIGNAL(readyRead()), this, SLOT(socket_readyRead())); return true; } /// \brief Slot for m_socket::connected() void Connection::socket_connected() { m_connected = true; // authenticate to server if we have a password set for // the connection authenticate(); // start timer for outbound message queue m_tMessageQueue->start(); emit connected(m_currentServer); } /// \brief Slot for m_socket::disconnected() void Connection::socket_disconnected() { // stop timer for outbound message queue and clear the queue m_tMessageQueue->stop(); m_messageQueue.clear(); m_connected = false; emit disconnected(m_currentServer); } /// \brief Slot for m_socket::error() /// /// This slot is connected to the error() signal of m_socket. /// It fetches the error message belonging to err and re-emits /// the signal to the controlling application as /// socketError(). /// /// \param err Socket error as received from m_socket's error() signal void Connection::socket_error(QAbstractSocket::SocketError err) { QString msg = m_socket->errorString(); qWarning() << "Connection::m_socket (connected to" << m_currentServer << ") generated an error: " << msg; emit socketError(err, msg); } /// \brief Slot for m_socket::readyRead() void Connection::socket_readyRead() { QString line; while (m_socket->canReadLine()) { line = m_socket->readLine(); if (!line.isNull()) { if (!parseMessage(line.trimmed())) { qDebug() << "Unable to parse message:" << line.trimmed(); } } } } /// \brief Set server password to new value void Connection::setServerPassword(QString password) { m_serverPassword = password; } /// \brief Return current server password QString Connection::serverPassword() const { return m_serverPassword; } /// \brief Set ident user ID void Connection::setIdent(QString ident) { m_ident = ident; } /// \brief Return current ident user ID QString Connection::ident() const { return m_ident; } /// \brief Set nickname to new value void Connection::setNick(QString nick) { m_nick = nick; } /// \brief Return current nickname QString Connection::nick() const { return m_nick; } /// \brief Set real name to use on IRC void Connection::setRealName(QString realName) { m_realName = realName; } /// \brief Return real name used on IRC QString Connection::realName() const { return m_realName; } /// \brief Send message to server /// /// Sends the given message to the IRC server. A message can be either /// queued or sent right away. The message Queue is checked by m_tMessageQueue /// every 10ms. /// /// \param msg Message text /// \param queued Flag to indicate wether the message should be queued /// or sent right away void Connection::sendMessage(QString msg, bool queued=true) { if (m_connected) { if (!queued) { QTextStream s(m_socket); s << msg.trimmed() << "\n"; } else { m_messageQueue.append(msg.trimmed() + "\n"); } } else { qWarning() << "Tried to use Connection::sendMessage() while " << "m_connected!=true! Message was:" << msg.trimmed(); } } /// \brief Authenticate connection /// /// Authenticates to the IRC server by sending USER/NICK messages. /// /// If m_serverPassword is set this method will also send a PASS /// message to the server to authenticate with a password before /// any of the others are sent. void Connection::authenticate() { if (!m_connected) { qWarning() << "Tried to use Connection::authenticat() while " << "m_connected!=true!"; } if (m_serverPassword.length() > 0) { sendMessage("PASS " + m_serverPassword, false); } // USER username hostname servername: realname sendMessage("USER " + m_ident + " " + m_currentServer.host() + " " + m_currentServer.host() + ": " + m_realName, false); // NICK nickname sendMessage("NICK " + m_nick, false); } /// \brief Are we currently connected? bool Connection::isConnected() const { return m_connected; } /// \brief Parse incoming message bool Connection::parseMessage(QString msg) { static const QRegExp reNOTICE_AUTH("^:(.+) NOTICE AUTH :(.+)$"); if (reNOTICE_AUTH.exactMatch(msg)) { QStringList tmp = reNOTICE_AUTH.capturedTexts(); QString serverName = tmp.value(1); QString message = tmp.value(2); emit irc_notice_auth(serverName, message); return true; } static const QRegExp reNumeric(":(.+) ([0-9]{3}) (.+) :(.+)$"); if (reNumeric.exactMatch(msg)) { QStringList tmp = reNumeric.capturedTexts(); QString serverName = tmp.value(1); int messageNumber = tmp.value(2).toInt(); QString target = tmp.value(3); QString message = tmp.value(4); // TODO(png): handle numeric messages according to RFC1459 return true; } static const QRegExp reNOTICE(":(.+)!(.+)@(.+) NOTICE ([\\w#\\-]+) :(.+)$"); if (reNOTICE.exactMatch(msg)) { QStringList tmp = reNOTICE.capturedTexts(); HostMask sender(tmp.value(1), tmp.value(2), tmp.value(3)); QString target = tmp.value(4); QString message = tmp.value(5); emit irc_notice(sender, target, message); return true; } static const QRegExp reMODE(":(.+)!(.+)@(.+) MODE ([\\w#\\-]+) :(.+)$"); if (reMODE.exactMatch(msg)) { QStringList tmp = reMODE.capturedTexts(); HostMask sender(tmp.value(1), tmp.value(2), tmp.value(3)); QString target = tmp.value(4); QString modeString = tmp.value(5); // TODO(png): emit signals for user/channel modes separately return true; } // PING: <servername> static const QRegExp rePING("^PING :(.+)$"); if (rePING.exactMatch(msg)) { QString serverName = rePING.capturedTexts().value(1); sendPong(serverName); emit irc_ping(serverName); return true; } return false; } /// \brief Send PONG response to PING command void Connection::sendPong(QString serverName) { sendMessage("PONG " + serverName, false); } /// \brief Setup queue for outbound messages bool Connection::setupMessageQueue() { try { m_tMessageQueue = new QTimer(this); } catch (std::bad_alloc& ex) { qCritical() << "Unable to allocate memory for " << "Connection::m_tMessageQueue:" << ex.what(); return false; } m_tMessageQueue->setInterval(10); QObject::connect(m_tMessageQueue, SIGNAL(timeout()), this, SLOT(timer_messageQueue())); return true; } /// \brief Slot for m_tMessageQueue::timeout() /// /// This slot is connected to the timeout() signal of m_tMessageQueue. /// It fetches the first message from the queue and sends it to the IRC /// server. If no messages are queued it simply does nothing. void Connection::timer_messageQueue() { if (!m_messageQueue.isEmpty()) { QString message = m_messageQueue.takeFirst(); QTextStream s(m_socket); s << message; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkReflectionFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkReflectionFilter.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkIdList.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkReflectionFilter, "1.10"); vtkStandardNewMacro(vtkReflectionFilter); //--------------------------------------------------------------------------- vtkReflectionFilter::vtkReflectionFilter() { this->Plane = USE_X_MIN; this->Center = 0.0; } //--------------------------------------------------------------------------- vtkReflectionFilter::~vtkReflectionFilter() { } //--------------------------------------------------------------------------- void vtkReflectionFilter::FlipVector(float tuple[3], int mirrorDir[3]) { for(int j=0; j<3; j++) { tuple[j] *= mirrorDir[j]; } } //--------------------------------------------------------------------------- void vtkReflectionFilter::Execute() { vtkIdType i; vtkDataSet *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkPointData *inPD = input->GetPointData(); vtkPointData *outPD = output->GetPointData(); vtkCellData *inCD = input->GetCellData(); vtkCellData *outCD = output->GetCellData(); vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType numCells = input->GetNumberOfCells(); float bounds[6]; float tuple[3]; vtkPoints *outPoints; float point[3]; float constant[3] = {0.0, 0.0, 0.0}; int mirrorDir[3] = { 1, 1, 1}; int ptId, cellId, j; vtkGenericCell *cell = vtkGenericCell::New(); vtkIdList *ptIds = vtkIdList::New(); input->GetBounds(bounds); outPoints = vtkPoints::New(); outPoints->Allocate(2* numPts); output->Allocate(numCells * 2); outPD->CopyAllocate(inPD); outCD->CopyAllocate(inCD); vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals; vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals; vtkDataArray *outCellNormals; inPtVectors = inPD->GetVectors(); outPtVectors = outPD->GetVectors(); inPtNormals = inPD->GetNormals(); outPtNormals = outPD->GetNormals(); inCellVectors = inCD->GetVectors(); outCellVectors = outCD->GetVectors(); inCellNormals = inCD->GetNormals(); outCellNormals = outCD->GetNormals(); // Copy first points. for (i = 0; i < numPts; i++) { input->GetPoint(i, point); ptId = outPoints->InsertNextPoint(point); outPD->CopyData(inPD, i, ptId); } // Copy reflected points. switch (this->Plane) { case USE_X_MIN: constant[0] = 2*bounds[0]; mirrorDir[0] = -1; break; case USE_X_MAX: constant[0] = 2*bounds[1]; mirrorDir[0] = -1; break; case USE_X: constant[0] = this->Center; mirrorDir[0] = -1; break; case USE_Y_MIN: constant[1] = 2*bounds[2]; mirrorDir[1] = -1; break; case USE_Y_MAX: constant[1] = 2*bounds[3]; mirrorDir[1] = -1; break; case USE_Y: constant[1] = this->Center; mirrorDir[1] = -1; break; case USE_Z_MIN: constant[2] = 2*bounds[4]; mirrorDir[2] = -1; break; case USE_Z_MAX: constant[2] = 2*bounds[5]; mirrorDir[2] = -1; break; case USE_Z: constant[2] = this->Center; mirrorDir[2] = -1; break; } for (i = 0; i < numPts; i++) { input->GetPoint(i, point); ptId = outPoints->InsertNextPoint( mirrorDir[0]*point[0] + constant[0], mirrorDir[1]*point[1] + constant[1], mirrorDir[2]*point[2] + constant[2] ); outPD->CopyData(inPD, i, ptId); if (inPtVectors) { inPtVectors->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outPtVectors->SetTuple(ptId, tuple); } if (inPtNormals) { inPtNormals->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outPtNormals->SetTuple(ptId, tuple); } } int numCellPts, cellType; vtkIdType *newCellPts; vtkIdList *cellPts; // Copy original cells. for (i = 0; i < numCells; i++) { input->GetCellPoints(i, ptIds); output->InsertNextCell(input->GetCellType(i), ptIds); outCD->CopyData(inCD, i, i); } // Generate reflected cells. for (i = 0; i < numCells; i++) { input->GetCell(i, cell); numCellPts = cell->GetNumberOfPoints(); cellType = cell->GetCellType(); cellPts = cell->GetPointIds(); // Triangle strips with even number of triangles have // to be handled specially. A degenerate triangle is // introduce to flip all the triangles properly. if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0) { numCellPts++; newCellPts = new vtkIdType[numCellPts]; newCellPts[0] = cellPts->GetId(0) + numPts; newCellPts[1] = cellPts->GetId(2) + numPts; newCellPts[2] = cellPts->GetId(1) + numPts; newCellPts[3] = cellPts->GetId(2) + numPts; for (j = 4; j < numCellPts; j++) { newCellPts[j] = cellPts->GetId(j-1) + numPts; } } else { newCellPts = new vtkIdType[numCellPts]; for (j = numCellPts-1; j >= 0; j--) { newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts; } } cellId = output->InsertNextCell(cellType, numCellPts, newCellPts); delete [] newCellPts; outCD->CopyData(inCD, i, cellId); if (inCellVectors) { inCellVectors->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outCellVectors->SetTuple(cellId, tuple); } if (inCellNormals) { inCellNormals->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outCellNormals->SetTuple(cellId, tuple); } } cell->Delete(); ptIds->Delete(); output->SetPoints(outPoints); outPoints->Delete(); output->CheckAttributes(); } //--------------------------------------------------------------------------- void vtkReflectionFilter::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Plane: " << this->Plane << endl; } <commit_msg>ERR: Fix failed PrintSelf test<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkReflectionFilter.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkReflectionFilter.h" #include "vtkCellData.h" #include "vtkGenericCell.h" #include "vtkIdList.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkUnstructuredGrid.h" vtkCxxRevisionMacro(vtkReflectionFilter, "1.11"); vtkStandardNewMacro(vtkReflectionFilter); //--------------------------------------------------------------------------- vtkReflectionFilter::vtkReflectionFilter() { this->Plane = USE_X_MIN; this->Center = 0.0; } //--------------------------------------------------------------------------- vtkReflectionFilter::~vtkReflectionFilter() { } //--------------------------------------------------------------------------- void vtkReflectionFilter::FlipVector(float tuple[3], int mirrorDir[3]) { for(int j=0; j<3; j++) { tuple[j] *= mirrorDir[j]; } } //--------------------------------------------------------------------------- void vtkReflectionFilter::Execute() { vtkIdType i; vtkDataSet *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkPointData *inPD = input->GetPointData(); vtkPointData *outPD = output->GetPointData(); vtkCellData *inCD = input->GetCellData(); vtkCellData *outCD = output->GetCellData(); vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType numCells = input->GetNumberOfCells(); float bounds[6]; float tuple[3]; vtkPoints *outPoints; float point[3]; float constant[3] = {0.0, 0.0, 0.0}; int mirrorDir[3] = { 1, 1, 1}; int ptId, cellId, j; vtkGenericCell *cell = vtkGenericCell::New(); vtkIdList *ptIds = vtkIdList::New(); input->GetBounds(bounds); outPoints = vtkPoints::New(); outPoints->Allocate(2* numPts); output->Allocate(numCells * 2); outPD->CopyAllocate(inPD); outCD->CopyAllocate(inCD); vtkDataArray *inPtVectors, *outPtVectors, *inPtNormals, *outPtNormals; vtkDataArray *inCellVectors, *outCellVectors, *inCellNormals; vtkDataArray *outCellNormals; inPtVectors = inPD->GetVectors(); outPtVectors = outPD->GetVectors(); inPtNormals = inPD->GetNormals(); outPtNormals = outPD->GetNormals(); inCellVectors = inCD->GetVectors(); outCellVectors = outCD->GetVectors(); inCellNormals = inCD->GetNormals(); outCellNormals = outCD->GetNormals(); // Copy first points. for (i = 0; i < numPts; i++) { input->GetPoint(i, point); ptId = outPoints->InsertNextPoint(point); outPD->CopyData(inPD, i, ptId); } // Copy reflected points. switch (this->Plane) { case USE_X_MIN: constant[0] = 2*bounds[0]; mirrorDir[0] = -1; break; case USE_X_MAX: constant[0] = 2*bounds[1]; mirrorDir[0] = -1; break; case USE_X: constant[0] = this->Center; mirrorDir[0] = -1; break; case USE_Y_MIN: constant[1] = 2*bounds[2]; mirrorDir[1] = -1; break; case USE_Y_MAX: constant[1] = 2*bounds[3]; mirrorDir[1] = -1; break; case USE_Y: constant[1] = this->Center; mirrorDir[1] = -1; break; case USE_Z_MIN: constant[2] = 2*bounds[4]; mirrorDir[2] = -1; break; case USE_Z_MAX: constant[2] = 2*bounds[5]; mirrorDir[2] = -1; break; case USE_Z: constant[2] = this->Center; mirrorDir[2] = -1; break; } for (i = 0; i < numPts; i++) { input->GetPoint(i, point); ptId = outPoints->InsertNextPoint( mirrorDir[0]*point[0] + constant[0], mirrorDir[1]*point[1] + constant[1], mirrorDir[2]*point[2] + constant[2] ); outPD->CopyData(inPD, i, ptId); if (inPtVectors) { inPtVectors->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outPtVectors->SetTuple(ptId, tuple); } if (inPtNormals) { inPtNormals->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outPtNormals->SetTuple(ptId, tuple); } } int numCellPts, cellType; vtkIdType *newCellPts; vtkIdList *cellPts; // Copy original cells. for (i = 0; i < numCells; i++) { input->GetCellPoints(i, ptIds); output->InsertNextCell(input->GetCellType(i), ptIds); outCD->CopyData(inCD, i, i); } // Generate reflected cells. for (i = 0; i < numCells; i++) { input->GetCell(i, cell); numCellPts = cell->GetNumberOfPoints(); cellType = cell->GetCellType(); cellPts = cell->GetPointIds(); // Triangle strips with even number of triangles have // to be handled specially. A degenerate triangle is // introduce to flip all the triangles properly. if (cellType == VTK_TRIANGLE_STRIP && numCellPts % 2 == 0) { numCellPts++; newCellPts = new vtkIdType[numCellPts]; newCellPts[0] = cellPts->GetId(0) + numPts; newCellPts[1] = cellPts->GetId(2) + numPts; newCellPts[2] = cellPts->GetId(1) + numPts; newCellPts[3] = cellPts->GetId(2) + numPts; for (j = 4; j < numCellPts; j++) { newCellPts[j] = cellPts->GetId(j-1) + numPts; } } else { newCellPts = new vtkIdType[numCellPts]; for (j = numCellPts-1; j >= 0; j--) { newCellPts[numCellPts-1-j] = cellPts->GetId(j) + numPts; } } cellId = output->InsertNextCell(cellType, numCellPts, newCellPts); delete [] newCellPts; outCD->CopyData(inCD, i, cellId); if (inCellVectors) { inCellVectors->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outCellVectors->SetTuple(cellId, tuple); } if (inCellNormals) { inCellNormals->GetTuple(i, tuple); this->FlipVector(tuple, mirrorDir); outCellNormals->SetTuple(cellId, tuple); } } cell->Delete(); ptIds->Delete(); output->SetPoints(outPoints); outPoints->Delete(); output->CheckAttributes(); } //--------------------------------------------------------------------------- void vtkReflectionFilter::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Plane: " << this->Plane << endl; os << indent << "Center: " << this->Center << endl; } <|endoftext|>
<commit_before>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTrackGeometry.cxx /// @author Matthias Richter /// @date 2011-05-20 /// @brief Desciption of a track by a sequence of track points /// #include "AliHLTTrackGeometry.h" #include "AliHLTSpacePointContainer.h" #include "TObjArray.h" #include "TMarker.h" #include "TMath.h" #include "TH2.h" #include <memory> #include <iostream> #include <algorithm> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTrackGeometry) AliHLTTrackGeometry::AliHLTTrackGeometry() : TObject(), AliHLTLogging() , fTrackPoints() , fSelectionMasks() , fTrackId(-1) , fVerbosity(0) { /// standard constructor } AliHLTTrackGeometry::AliHLTTrackGeometry(const AliHLTTrackGeometry& src) : TObject(src), AliHLTLogging() , fTrackPoints(src.fTrackPoints) , fSelectionMasks(src.fSelectionMasks) , fTrackId(src.fTrackId) , fVerbosity(src.fVerbosity) { /// copy constructor } AliHLTTrackGeometry& AliHLTTrackGeometry::operator=(const AliHLTTrackGeometry& src) { /// assignment operator if (this!=&src) { fTrackPoints.assign(src.fTrackPoints.begin(), src.fTrackPoints.end()); fSelectionMasks.assign(src.fSelectionMasks.begin(), src.fSelectionMasks.end()); fTrackId=src.fTrackId; fVerbosity=src.fVerbosity; } return *this; } AliHLTTrackGeometry::~AliHLTTrackGeometry() { /// destructor } int AliHLTTrackGeometry::AddTrackPoint(const AliHLTTrackPoint& point, AliHLTUInt32_t selectionMask) { /// add a track point to the list vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), point); if (element==fTrackPoints.end()) { fTrackPoints.push_back(point); if (std::find(fSelectionMasks.begin(), fSelectionMasks.end(), selectionMask)==fSelectionMasks.end()) { fSelectionMasks.push_back(selectionMask); } } else { HLTError("track point of id %08x already existing", point.GetId()); return -EEXIST; } return 0; } void AliHLTTrackGeometry::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTTrackGeometry::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTTrackGeometry::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTTrackGeometry::Print" << endl; } void AliHLTTrackGeometry::Draw(Option_t *option) { /// Inherited from TObject, draw the track float scale=250; float center[2]={0.5,0.5}; int markerColor=1; int markerSize=1; int verbosity=0; TString strOption(option); std::auto_ptr<TObjArray> tokens(strOption.Tokenize(" ")); if (!tokens.get()) return; for (int i=0; i<tokens->GetEntriesFast(); i++) { if (!tokens->At(i)) continue; const char* key=""; TString arg=tokens->At(i)->GetName(); key="scale="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); scale=arg.Atof(); continue; } key="centerx="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[0]=arg.Atof(); continue; } key="centery="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[1]=arg.Atof(); continue; } key="markercolor="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerColor=arg.Atoi(); continue; } key="markersize="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerSize=arg.Atoi(); continue; } key="verbosity="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); verbosity=arg.Atoi(); continue; } } bool bFirstPoint=true; float firstalpha=0.0; for (vector<AliHLTTrackPoint>::const_iterator point=fTrackPoints.begin(); point!=fTrackPoints.end(); point++) { float alpha=GetPlaneAlpha(point->GetId()); float r=GetPlaneR(point->GetId()); float cosa=TMath::Cos(alpha); float sina=TMath::Sin(alpha); float x = r*sina + point->GetU()*cosa; float y =-r*cosa + point->GetU()*sina; if (verbosity>0) { HLTInfo("ID 0x%08x: x=% .4f y=% .4f alpha=% .4f", point->GetId(), r, point->GetU(), alpha); } int color=markerColor; if (bFirstPoint) { bFirstPoint=false; TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], 29); m->SetMarkerSize(2); m->SetMarkerColor(2); m->Draw("same"); firstalpha=alpha; } else { color+=int(9*TMath::Abs(alpha-firstalpha)/TMath::Pi()); } TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], point->GetV()>0?2:5); m->SetMarkerColor(color); m->SetMarkerSize(markerSize); m->Draw("same"); } } int AliHLTTrackGeometry::SetAssociatedSpacePoint(UInt_t planeId, UInt_t spacepointId, int status, float fdU, float fdV) { /// set the spacepoint associated with a track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; element->SetAssociatedSpacePoint(spacepointId, status); element->SetResidual(0, fdU); element->SetResidual(1, fdV); return 0; } int AliHLTTrackGeometry::GetAssociatedSpacePoint(UInt_t planeId, UInt_t& spacepointId) const { /// get the spacepoint associated with a track point /// return status flag if found, -ENOENT if no associated spacepoint found vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; if (!element->HaveAssociatedSpacePoint()) return -ENODATA; return element->GetAssociatedSpacePoint(spacepointId); } const AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) const { /// get const pointer to track point vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) { /// get const pointer to track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTSpacePointContainer* AliHLTTrackGeometry::ConvertToSpacePoints(bool /*bAssociated*/) const { /// create a collection of all points HLTError("implementation of child method missing"); return NULL; } int AliHLTTrackGeometry::AssociateSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); if (ids.size()>0) return 0; int result=AssociateSpacePoints(&ids[0], ids.size(), points); if (result>0) { HLTInfo("associated %d of %d space point(s) to track points", result, ids.size()); } return result; } int AliHLTTrackGeometry::AssociateSpacePoints(const AliHLTUInt32_t* trackpoints, AliHLTUInt32_t nofPoints, AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points if (nofPoints==0) return 0; if (trackpoints==NULL) return -EINVAL; int count=0; for (int i=nofPoints-1; i>=0; i--) { if (!points.Check(trackpoints[i])) { HLTWarning("can not find point id %08x", trackpoints[i]); continue; } float xyz[3]={points.GetX(trackpoints[i]), points.GetY(trackpoints[i]), points.GetZ(trackpoints[i])}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(trackpoints[i], xyz, planeId); if (result<0) { HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); SetAssociatedSpacePoint(planeId, trackpoints[i], 1, xyz[1]-element->GetU(), xyz[2]-element->GetV()); if (points.GetTrackID(trackpoints[i])<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), trackpoints[i]); HLTDebug("associating unused cluster %08x with track %d", trackpoints[i], GetTrackId()); } count++; } return count; } int AliHLTTrackGeometry::AssociateUnusedSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points int count=0; for (vector<AliHLTUInt32_t>::iterator mask=fSelectionMasks.begin(); mask!=fSelectionMasks.end(); mask++) { int subcount=0; const vector<AliHLTUInt32_t>* selectedPoints=points.GetClusterIDs(*mask); if (!selectedPoints) { HLTWarning("space point collection does not contain data for mask 0x%08x", *mask); continue; } for (vector<AliHLTUInt32_t>::const_iterator id=selectedPoints->begin(); id!=selectedPoints->end(); id++) { if (points.GetTrackID(*id)>=0) continue; float xyz[3]={points.GetX(*id), points.GetY(*id), points.GetZ(*id)}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(*id, xyz, planeId); if (result<0) { //HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", *id, xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { //HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", *id, xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, *id, 1); if (points.GetTrackID(*id)<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), *id); HLTDebug("associating unused cluster %08x with track %d", *id, GetTrackId()); } subcount++; } if (fVerbosity>0) { HLTInfo("associated %d of %d spacepoint(s) from selection 0x%08x to track %d", subcount, selectedPoints->size(), *mask, GetTrackId()); } count+=subcount; } return count; } int AliHLTTrackGeometry::FillResidual(int coordinate, TH2* histo) const { // fill residual histogram const vector<AliHLTTrackPoint>& trackPoints=TrackPoints(); for (vector<AliHLTTrackPoint>::const_iterator trackpoint=trackPoints.begin(); trackpoint!=trackPoints.end(); trackpoint++) { histo->Fill(GetPlaneR(trackpoint->GetId()), trackpoint->GetResidual(coordinate)); } return 0; } ostream& operator<<(ostream &out, const AliHLTTrackGeometry& p) { p.Print(out); return out; } <commit_msg>bugfix: suppress points without associated track point in residual calculation<commit_after>// $Id$ //************************************************************************** //* This file is property of and copyright by the ALICE HLT Project * //* ALICE Experiment at CERN, All rights reserved. * //* * //* Primary Authors: Matthias Richter <Matthias.Richter@ift.uib.no> * //* for The ALICE HLT Project. * //* * //* Permission to use, copy, modify and distribute this software and its * //* documentation strictly for non-commercial purposes is hereby granted * //* without fee, provided that the above copyright notice appears in all * //* copies and that both the copyright notice and this permission notice * //* appear in the supporting documentation. The authors make no claims * //* about the suitability of this software for any purpose. It is * //* provided "as is" without express or implied warranty. * //************************************************************************** /// @file AliHLTTrackGeometry.cxx /// @author Matthias Richter /// @date 2011-05-20 /// @brief Desciption of a track by a sequence of track points /// #include "AliHLTTrackGeometry.h" #include "AliHLTSpacePointContainer.h" #include "TObjArray.h" #include "TMarker.h" #include "TMath.h" #include "TH2.h" #include <memory> #include <iostream> #include <algorithm> /** ROOT macro for the implementation of ROOT specific class methods */ ClassImp(AliHLTTrackGeometry) AliHLTTrackGeometry::AliHLTTrackGeometry() : TObject(), AliHLTLogging() , fTrackPoints() , fSelectionMasks() , fTrackId(-1) , fVerbosity(0) { /// standard constructor } AliHLTTrackGeometry::AliHLTTrackGeometry(const AliHLTTrackGeometry& src) : TObject(src), AliHLTLogging() , fTrackPoints(src.fTrackPoints) , fSelectionMasks(src.fSelectionMasks) , fTrackId(src.fTrackId) , fVerbosity(src.fVerbosity) { /// copy constructor } AliHLTTrackGeometry& AliHLTTrackGeometry::operator=(const AliHLTTrackGeometry& src) { /// assignment operator if (this!=&src) { fTrackPoints.assign(src.fTrackPoints.begin(), src.fTrackPoints.end()); fSelectionMasks.assign(src.fSelectionMasks.begin(), src.fSelectionMasks.end()); fTrackId=src.fTrackId; fVerbosity=src.fVerbosity; } return *this; } AliHLTTrackGeometry::~AliHLTTrackGeometry() { /// destructor } int AliHLTTrackGeometry::AddTrackPoint(const AliHLTTrackPoint& point, AliHLTUInt32_t selectionMask) { /// add a track point to the list vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), point); if (element==fTrackPoints.end()) { fTrackPoints.push_back(point); if (std::find(fSelectionMasks.begin(), fSelectionMasks.end(), selectionMask)==fSelectionMasks.end()) { fSelectionMasks.push_back(selectionMask); } } else { HLTError("track point of id %08x already existing", point.GetId()); return -EEXIST; } return 0; } void AliHLTTrackGeometry::Clear(Option_t * /*option*/) { // internal cleanup } void AliHLTTrackGeometry::Print(Option_t *option) const { // print info Print(cout, option); } void AliHLTTrackGeometry::Print(ostream& out, Option_t */*option*/) const { // print to stream out << "AliHLTTrackGeometry::Print" << endl; } void AliHLTTrackGeometry::Draw(Option_t *option) { /// Inherited from TObject, draw the track float scale=250; float center[2]={0.5,0.5}; int markerColor=1; int markerSize=1; int verbosity=0; TString strOption(option); std::auto_ptr<TObjArray> tokens(strOption.Tokenize(" ")); if (!tokens.get()) return; for (int i=0; i<tokens->GetEntriesFast(); i++) { if (!tokens->At(i)) continue; const char* key=""; TString arg=tokens->At(i)->GetName(); key="scale="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); scale=arg.Atof(); continue; } key="centerx="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[0]=arg.Atof(); continue; } key="centery="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); center[1]=arg.Atof(); continue; } key="markercolor="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerColor=arg.Atoi(); continue; } key="markersize="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); markerSize=arg.Atoi(); continue; } key="verbosity="; if (arg.BeginsWith(key)) { arg.ReplaceAll(key, ""); verbosity=arg.Atoi(); continue; } } bool bFirstPoint=true; float firstalpha=0.0; for (vector<AliHLTTrackPoint>::const_iterator point=fTrackPoints.begin(); point!=fTrackPoints.end(); point++) { float alpha=GetPlaneAlpha(point->GetId()); float r=GetPlaneR(point->GetId()); float cosa=TMath::Cos(alpha); float sina=TMath::Sin(alpha); float x = r*sina + point->GetU()*cosa; float y =-r*cosa + point->GetU()*sina; if (verbosity>0) { HLTInfo("ID 0x%08x: x=% .4f y=% .4f alpha=% .4f", point->GetId(), r, point->GetU(), alpha); } int color=markerColor; if (bFirstPoint) { bFirstPoint=false; TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], 29); m->SetMarkerSize(2); m->SetMarkerColor(2); m->Draw("same"); firstalpha=alpha; } else { color+=int(9*TMath::Abs(alpha-firstalpha)/TMath::Pi()); } TMarker* m=new TMarker(x/(2*scale)+center[0], y/(2*scale)+center[1], point->GetV()>0?2:5); m->SetMarkerColor(color); m->SetMarkerSize(markerSize); m->Draw("same"); } } int AliHLTTrackGeometry::SetAssociatedSpacePoint(UInt_t planeId, UInt_t spacepointId, int status, float fdU, float fdV) { /// set the spacepoint associated with a track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; element->SetAssociatedSpacePoint(spacepointId, status); element->SetResidual(0, fdU); element->SetResidual(1, fdV); return 0; } int AliHLTTrackGeometry::GetAssociatedSpacePoint(UInt_t planeId, UInt_t& spacepointId) const { /// get the spacepoint associated with a track point /// return status flag if found, -ENOENT if no associated spacepoint found vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); if (element==fTrackPoints.end()) return -ENOENT; if (!element->HaveAssociatedSpacePoint()) return -ENODATA; return element->GetAssociatedSpacePoint(spacepointId); } const AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) const { /// get const pointer to track point vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTTrackGeometry::AliHLTTrackPoint* AliHLTTrackGeometry::GetTrackPoint(AliHLTUInt32_t id) { /// get const pointer to track point vector<AliHLTTrackPoint>::iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), id); if (element==fTrackPoints.end()) return NULL; return &(*element); } AliHLTSpacePointContainer* AliHLTTrackGeometry::ConvertToSpacePoints(bool /*bAssociated*/) const { /// create a collection of all points HLTError("implementation of child method missing"); return NULL; } int AliHLTTrackGeometry::AssociateSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points vector<AliHLTUInt32_t> ids; points.GetClusterIDs(ids); if (ids.size()>0) return 0; int result=AssociateSpacePoints(&ids[0], ids.size(), points); if (result>0) { HLTInfo("associated %d of %d space point(s) to track points", result, ids.size()); } return result; } int AliHLTTrackGeometry::AssociateSpacePoints(const AliHLTUInt32_t* trackpoints, AliHLTUInt32_t nofPoints, AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points if (nofPoints==0) return 0; if (trackpoints==NULL) return -EINVAL; int count=0; for (int i=nofPoints-1; i>=0; i--) { if (!points.Check(trackpoints[i])) { HLTWarning("can not find point id %08x", trackpoints[i]); continue; } float xyz[3]={points.GetX(trackpoints[i]), points.GetY(trackpoints[i]), points.GetZ(trackpoints[i])}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(trackpoints[i], xyz, planeId); if (result<0) { if (GetVerbosity()>0) HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", trackpoints[i], xyz[0], xyz[1], xyz[2]); continue; } vector<AliHLTTrackPoint>::const_iterator element = find(fTrackPoints.begin(), fTrackPoints.end(), planeId); SetAssociatedSpacePoint(planeId, trackpoints[i], 1, xyz[1]-element->GetU(), xyz[2]-element->GetV()); if (points.GetTrackID(trackpoints[i])<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), trackpoints[i]); HLTDebug("associating unused cluster %08x with track %d", trackpoints[i], GetTrackId()); } count++; } return count; } int AliHLTTrackGeometry::AssociateUnusedSpacePoints(AliHLTSpacePointContainer& points) { /// associate the track space points to the calculated track points int count=0; for (vector<AliHLTUInt32_t>::iterator mask=fSelectionMasks.begin(); mask!=fSelectionMasks.end(); mask++) { int subcount=0; const vector<AliHLTUInt32_t>* selectedPoints=points.GetClusterIDs(*mask); if (!selectedPoints) { HLTWarning("space point collection does not contain data for mask 0x%08x", *mask); continue; } for (vector<AliHLTUInt32_t>::const_iterator id=selectedPoints->begin(); id!=selectedPoints->end(); id++) { if (points.GetTrackID(*id)>=0) continue; float xyz[3]={points.GetX(*id), points.GetY(*id), points.GetZ(*id)}; AliHLTUInt32_t planeId=0; int result=FindMatchingTrackPoint(*id, xyz, planeId); if (result<0) { //HLTWarning("no associated track point found for space point id %08x x=%f y=%f z=%f", *id, xyz[0], xyz[1], xyz[2]); continue; } else if (result==0) { //HLTWarning("associated track point for space pointid %08x x=%f y=%f z=%f occupied", *id, xyz[0], xyz[1], xyz[2]); continue; } SetAssociatedSpacePoint(planeId, *id, 1); if (points.GetTrackID(*id)<0 && GetTrackId()>=0) { points.SetTrackID(GetTrackId(), *id); HLTDebug("associating unused cluster %08x with track %d", *id, GetTrackId()); } subcount++; } if (fVerbosity>0) { HLTInfo("associated %d of %d spacepoint(s) from selection 0x%08x to track %d", subcount, selectedPoints->size(), *mask, GetTrackId()); } count+=subcount; } return count; } int AliHLTTrackGeometry::FillResidual(int coordinate, TH2* histo) const { // fill residual histogram const vector<AliHLTTrackPoint>& trackPoints=TrackPoints(); for (vector<AliHLTTrackPoint>::const_iterator trackpoint=trackPoints.begin(); trackpoint!=trackPoints.end(); trackpoint++) { if (!trackpoint->HaveAssociatedSpacePoint()) continue; histo->Fill(GetPlaneR(trackpoint->GetId()), trackpoint->GetResidual(coordinate)); } return 0; } ostream& operator<<(ostream &out, const AliHLTTrackGeometry& p) { p.Print(out); return out; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" #include <iomanip> using namespace std; ConsoleUI::ConsoleUI() { _service.getScientists(); // gets information from file so it's used from the beginning. } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; while(true) { cout << "Select one of the following options: " << endl; cout << "======================================================================" << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "Remove - remove a programmer/computer scientist" << endl; cout << "List - show a list of all programmer's/computer scientist's" << endl; cout << "Search - search the list of programmer's/computer scientist's" << endl; cout << "Sort - sort list by name, gender, age or year of death" << endl; cout << "Quit - end program" << endl; cin >> command; forceLowerCase(command); if(command == "add") { userMenuAdd(); } else if(command == "remove") { userMenuRemove(); } else if(command == "list") { userMenuList(); } else if(command == "search") { userMenuSearch(); } else if(command == "sort") { userMenuSort(); } else if(command == "quit") { break; } else { cout << "Invalid input" << endl; } } } void ConsoleUI::userMenuAdd() { string name; string genderInput; char gender; int birthYear; int deathYear = 0; int age = 0; int a; while(true) { cout << "Enter the programmer's/computer scientist's name: "; cin.ignore(); getline(cin, name); // Check for gender while(true) { cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> genderInput; forceLowerCase(genderInput); if((genderInput == "m") || (genderInput == "f")) { gender = genderInput[0]; cin.clear(); cin.ignore(INT_MAX, '\n'); break; } else { cout << "Invalid input" << endl; } } // Check year of birth while(true) { bool inputCheck; do { cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; inputCheck = cin.fail(); if(inputCheck) { cout << "Invalid input" << endl; } cin.clear(); cin.ignore(INT_MAX, '\n'); }while(inputCheck); if(birthYear < 2016) // Just in case we find a programmer of the univers { break; } else { cout << "Invalid input" << endl; } } // Check when year of death (if dead) while(true) { bool inputCheck; do { cout << "Enter the programmer's/computer scientist's year of death (type 0 if not applicable): "; cin >> deathYear; inputCheck = cin.fail(); if(inputCheck) { cout << "Invalid input" << endl; } cin.clear(); cin.ignore(INT_MAX, '\n'); }while(inputCheck); if (deathYear == 0) { break; } else if(deathYear >= birthYear) { break; } else { cout << "Invalid input" << endl; } } // Check if input is correct cout << "Name: " << name << endl << "Gender: " << gender << endl << "Born: " << birthYear << endl; if(deathYear != 0) { cout << "Died: " << deathYear << endl; } else { cout << endl; } a = userCheckInput(); if (a == 0) { // false sama nafn if(_service.addScientist(name, gender, birthYear, deathYear, age)) { break; } else { int userInput; cout << "This name is allready taken, replace existing name(1), start over(2)" << endl; cin >> userInput; if(userInput == 1) { _service.removeScientist(name); _service.addScientist(name, gender, birthYear, deathYear, age); break; } } } else if (a == 2) { break; } } cout << endl; } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientists(); userMenuPrint(scientist); } void ConsoleUI::userMenuSearch() { string command; cout << "Select a search option: " << endl; cout << "======================================================================" << endl; cout << "Name - Search by name" << endl; cout << "Gender - Search by gender" << endl; cout << "Age - Search by age" << endl; cout << "Birth - search by year of birth" << endl; cout << "Death - search by year of death" << endl; cin >> command; cout << endl; forceLowerCase(command); if(command == "name") { string userInputName; cout << "Search by name: "; cin.ignore(); getline(cin, userInputName); vector<Scientist> scientist = _service.findScientistByName(userInputName); userMenuPrint(scientist); } else if(command == "gender") // findScientistByGender { char userInputGender; cout << "Search by gender: "; cin >> userInputGender; vector<Scientist> scientist = _service.findScientistByGender(userInputGender); userMenuPrint(scientist); } else if(command == "age") // findScientistByGender { int userInputAge; cout << "Search by age: "; cin >> userInputAge; vector<Scientist> scientist = _service.findScientistByAge(userInputAge); userMenuPrint(scientist); } else if(command == "birth") { int userInputBirth; cout << "Search by year of birth: "; cin >> userInputBirth; vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth); userMenuPrint(scientist); } else if(command == "death") { int userInputDeath; cout << "Search by year of death (0 for still alive): "; cin >> userInputDeath; vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath); userMenuPrint(scientist); } cout << endl; } void ConsoleUI::userMenuSort() { int userInput; cout << "Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)" << endl; cin >> userInput; _service.scientistSort(userInput); userMenuList(); } void ConsoleUI::userMenuPrint(vector<Scientist>scientist) { cout << string( 100, '\n' ); cout << left << setw(30) << "Scientist name:" << setw(10) << right << "gender:" << setw(10) << "born:" << setw(10) << "died:" << setw(10) << "age:" << endl; cout << "======================================================================" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << left << setw(30) << scientist[i].getName() << setw(10) << right << scientist[i].getGender() << setw(10) << scientist[i].getBirth(); if(scientist[i].getDeath() == 0) { cout << setw(10) << "-"; } else { cout << setw(10) << scientist[i].getDeath(); } cout << setw(10) << scientist[i].getAge() << endl; } cout << endl; } int ConsoleUI::userCheckInput() { // Check if all data is correct while(true) { char answear; cout << "Is this data correct? (input y/n) or press q to quit" << endl; cin >> answear; if(answear == 'y') { return 0; } else if (answear == 'n') { return 1; } else if (answear == 'q') { return 2; } else { cout << "Invalid input!"; } } } void ConsoleUI::userMenuRemove() { string userInputName; cout << "Remove a programmer/computer scientist: "; cin.ignore(); getline(cin, userInputName); _service.removeScientist(userInputName); } void ConsoleUI::forceLowerCase(string &command) { for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } } <commit_msg>Major UI Fix<commit_after>#include <iostream> #include <string> #include "consoleui.h" #include "scientist.h" #include <iomanip> using namespace std; ConsoleUI::ConsoleUI() { _service.getScientists(); // gets information from file so it's used from the beginning. } // Should not contain logic for individual commands, that should be in separate functions! void ConsoleUI::run() { string command; while(true) { cout << string( 100, '\n' ); // Clears screen cout << "Select one of the following options: " << endl; cout << "======================================================================" << endl; cout << "Add - add a programmer/computer scientist" << endl; cout << "Remove - remove a programmer/computer scientist" << endl; cout << "List - show a list of all programmer's/computer scientist's" << endl; cout << "Search - search the list of programmer's/computer scientist's" << endl; cout << "Sort - sort list by name, gender, age or year of death" << endl; cout << "Quit - end program" << endl; cin >> command; forceLowerCase(command); if(command == "add") { userMenuAdd(); } else if(command == "remove") { userMenuRemove(); } else if(command == "list") { userMenuList(); } else if(command == "search") { userMenuSearch(); } else if(command == "sort") { userMenuSort(); } else if(command == "quit") { cout << string( 100, '\n' ); // Clears screen break; } else { cout << "Invalid input" << endl; } } } void ConsoleUI::userMenuAdd() { string name; string genderInput; char gender; int birthYear; int deathYear = 0; int age = 0; int a; while(true) { cout << string( 100, '\n' ); // Clears screen cout << "Enter the programmer's/computer scientist's name: "; cin.ignore(); getline(cin, name); // Check for gender while(true) { cout << string( 100, '\n' ); // Clears screen cout << "Enter the programmer's/computer scientist's gender (m/f): "; cin >> genderInput; forceLowerCase(genderInput); if((genderInput == "m") || (genderInput == "f")) { gender = genderInput[0]; cin.clear(); cin.ignore(INT_MAX, '\n'); break; } else { cout << "Invalid input" << endl; } } // Check year of birth while(true) { bool inputCheck; do { cout << string( 100, '\n' ); // Clears screen cout << "Enter the programmer's/computer scientist's year of birth: "; cin >> birthYear; inputCheck = cin.fail(); if(inputCheck) { cout << "Invalid input" << endl; } cin.clear(); cin.ignore(INT_MAX, '\n'); }while(inputCheck); if(birthYear < 2016) // Just in case we find a programmer of the univers { break; } else { cout << "Invalid input" << endl; } } // Check when year of death (if dead) while(true) { bool inputCheck; do { cout << string( 100, '\n' ); // Clears screen cout << "Enter the programmer's/computer scientist's year of death (type 0 if not applicable): "; cin >> deathYear; inputCheck = cin.fail(); if(inputCheck) { cout << "Invalid input" << endl; } cin.clear(); cin.ignore(INT_MAX, '\n'); }while(inputCheck); if (deathYear == 0) { break; } else if(deathYear >= birthYear) { break; } else { cout << "Invalid input" << endl; } } // Check if input is correct cout << string( 100, '\n' ); // Clears screen cout << "Name: " << name << endl << "Gender: " << gender << endl << "Born: " << birthYear << endl; if(deathYear != 0) { cout << "Died: " << deathYear << endl; } else { cout << endl; } a = userCheckInput(); if (a == 0) { // false sama nafn if(_service.addScientist(name, gender, birthYear, deathYear, age)) { break; } else { int userInput; cout << string( 100, '\n' ); // Clears screen cout << "This name is allready taken, replace existing name(1), start over(2)" << endl; cin >> userInput; if(userInput == 1) { _service.removeScientist(name); _service.addScientist(name, gender, birthYear, deathYear, age); break; } } } else if (a == 2) { break; } } cout << endl; } void ConsoleUI::userMenuList() { vector<Scientist> scientist = _service.getScientists(); userMenuPrint(scientist); } void ConsoleUI::userMenuSearch() { string command; cout << string( 100, '\n' ); // Clears screen cout << "Select a search option: " << endl; cout << "======================================================================" << endl; cout << "Name - Search by name" << endl; cout << "Gender - Search by gender" << endl; cout << "Age - Search by age" << endl; cout << "Birth - search by year of birth" << endl; cout << "Death - search by year of death" << endl; cin >> command; cout << endl; forceLowerCase(command); if(command == "name") { string userInputName; cout << string( 100, '\n' ); // Clears screen cout << "Search by name: "; cin.ignore(); getline(cin, userInputName); vector<Scientist> scientist = _service.findScientistByName(userInputName); userMenuPrint(scientist); } else if(command == "gender") // findScientistByGender { char userInputGender; cout << string( 100, '\n' ); // Clears screen cout << "Search by gender: "; cin >> userInputGender; vector<Scientist> scientist = _service.findScientistByGender(userInputGender); userMenuPrint(scientist); } else if(command == "age") // findScientistByGender { int userInputAge; cout << string( 100, '\n' ); // Clears screen cout << "Search by age: "; cin >> userInputAge; vector<Scientist> scientist = _service.findScientistByAge(userInputAge); userMenuPrint(scientist); } else if(command == "birth") { int userInputBirth; cout << string( 100, '\n' ); // Clears screen cout << "Search by year of birth: "; cin >> userInputBirth; vector<Scientist> scientist = _service.findScientistByBirth(userInputBirth); userMenuPrint(scientist); } else if(command == "death") { int userInputDeath; cout << string( 100, '\n' ); // Clears screen cout << "Search by year of death (0 for still alive): "; cin >> userInputDeath; vector<Scientist> scientist = _service.findScientistByDeath(userInputDeath); userMenuPrint(scientist); } cout << endl; } void ConsoleUI::userMenuSort() { int userInput; cout << string( 100, '\n' ); // Clears screen cout << "Sort list by Name A-Z(1), Name Z-A(2), Gender(3), Year of Birth(4), Year of Death(5) or Age (6)" << endl; cin >> userInput; _service.scientistSort(userInput); userMenuList(); } void ConsoleUI::userMenuPrint(vector<Scientist>scientist) { cout << string( 100, '\n' ); cout << left << setw(30) << "Scientist name:" << setw(10) << right << "gender:" << setw(10) << "born:" << setw(10) << "died:" << setw(10) << "age:" << endl; cout << "======================================================================" << endl; for (size_t i = 0; i< scientist.size(); ++i) { cout << left << setw(30) << scientist[i].getName() << setw(10) << right << scientist[i].getGender() << setw(10) << scientist[i].getBirth(); if(scientist[i].getDeath() == 0) { cout << setw(10) << "-"; } else { cout << setw(10) << scientist[i].getDeath(); } cout << setw(10) << scientist[i].getAge() << endl; } cout << "======================================================================" << endl; cout << "To return to menu press m" << endl; string userInput = " "; while (userInput != "m") { cin >> userInput; } } int ConsoleUI::userCheckInput() { // Check if all data is correct while(true) { char answear; cout << "Is this data correct? (input y/n) or press q to quit" << endl; cin >> answear; if(answear == 'y') { return 0; } else if (answear == 'n') { return 1; } else if (answear == 'q') { return 2; } else { cout << "Invalid input!"; } } } void ConsoleUI::userMenuRemove() { string userInputName; cout << string( 100, '\n' ); // Clears screen cout << "Remove a programmer/computer scientist: "; cin.ignore(); getline(cin, userInputName); _service.removeScientist(userInputName); } void ConsoleUI::forceLowerCase(string &command) { for(unsigned int i = 0; i < command.length(); i++) // to make all lowercase, taken from c++ site { command[i] = tolower(command[i]); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkPanelMark.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPanelMark.h" #include "vtkContext2D.h" #include "vtkObjectFactory.h" #include "vtkTransform2D.h" //----------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkPanelMark, "1.3"); vtkStandardNewMacro(vtkPanelMark); //----------------------------------------------------------------------------- vtkPanelMark::vtkPanelMark() { } //----------------------------------------------------------------------------- vtkPanelMark::~vtkPanelMark() { } //----------------------------------------------------------------------------- vtkMark* vtkPanelMark::Add(int type) { vtkSmartPointer<vtkMark> m; m.TakeReference(vtkMark::CreateMark(type)); if (this->Marks.size() > 0) { m->Extend(this->Marks.back()); } this->Marks.push_back(m); m->SetParent(this); return m; } //----------------------------------------------------------------------------- void vtkPanelMark::Update() { this->MarkInstances.clear(); this->Left.Update(this); this->Right.Update(this); this->Top.Update(this); this->Bottom.Update(this); int numMarks = this->Marks.size(); // Create only a single instance if no real data is set on panel. vtkIdType numChildren = 1; vtkDataElement data = this->Data.GetData(this); if(data.IsValid()) { numChildren = data.GetNumberOfChildren(); } for (vtkIdType j = 0; j < numMarks; ++j) { for (vtkIdType i = 0; i < numChildren; ++i) { this->Index = i; this->Marks[j]->DataChanged(); this->Marks[j]->Update(); vtkSmartPointer<vtkMark> m; m.TakeReference(vtkMark::CreateMark(this->Marks[j]->GetType())); m->Extend(this->Marks[j]); m->SetParent(this->Marks[j]->GetParent()); m->SetParentMarkIndex(j); m->SetParentDataIndex(i); this->MarkInstances.push_back(m); } } } //----------------------------------------------------------------------------- bool vtkPanelMark::Paint(vtkContext2D* painter) { //TODO: Be smarter about the update this->Update(); if (!painter->GetTransform()) { vtkSmartPointer<vtkTransform2D> trans = vtkSmartPointer<vtkTransform2D>::New(); trans->Identity(); painter->SetTransform(trans); } double* left = this->Left.GetArray(this); double* bottom = this->Bottom.GetArray(this); size_t numMarks = this->Marks.size(); vtkDataElement data = this->Data.GetData(this); vtkIdType numChildren = 1; if(data.IsValid()) { numChildren = data.GetNumberOfChildren(); } for (size_t j = 0; j < numMarks; ++j) { for (vtkIdType i = 0; i < numChildren; ++i) { this->Index = i; painter->GetTransform()->Translate(left[i], bottom[i]); painter->SetTransform(painter->GetTransform()); this->MarkInstances[j*numChildren + i]->Paint(painter); painter->GetTransform()->Translate(-left[i], -bottom[i]); painter->SetTransform(painter->GetTransform()); } } return true; } //----------------------------------------------------------------------------- void vtkPanelMark::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } <commit_msg>COMP: Casting size_t to int now to silence all related warnings.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkPanelMark.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkPanelMark.h" #include "vtkContext2D.h" #include "vtkObjectFactory.h" #include "vtkTransform2D.h" //----------------------------------------------------------------------------- vtkCxxRevisionMacro(vtkPanelMark, "1.4"); vtkStandardNewMacro(vtkPanelMark); //----------------------------------------------------------------------------- vtkPanelMark::vtkPanelMark() { } //----------------------------------------------------------------------------- vtkPanelMark::~vtkPanelMark() { } //----------------------------------------------------------------------------- vtkMark* vtkPanelMark::Add(int type) { vtkSmartPointer<vtkMark> m; m.TakeReference(vtkMark::CreateMark(type)); if (this->Marks.size() > 0) { m->Extend(this->Marks.back()); } this->Marks.push_back(m); m->SetParent(this); return m; } //----------------------------------------------------------------------------- void vtkPanelMark::Update() { this->MarkInstances.clear(); this->Left.Update(this); this->Right.Update(this); this->Top.Update(this); this->Bottom.Update(this); int numMarks = static_cast<int>(this->Marks.size()); // Create only a single instance if no real data is set on panel. vtkIdType numChildren = 1; vtkDataElement data = this->Data.GetData(this); if(data.IsValid()) { numChildren = data.GetNumberOfChildren(); } for (vtkIdType j = 0; j < numMarks; ++j) { for (vtkIdType i = 0; i < numChildren; ++i) { this->Index = i; this->Marks[j]->DataChanged(); this->Marks[j]->Update(); vtkSmartPointer<vtkMark> m; m.TakeReference(vtkMark::CreateMark(this->Marks[j]->GetType())); m->Extend(this->Marks[j]); m->SetParent(this->Marks[j]->GetParent()); m->SetParentMarkIndex(j); m->SetParentDataIndex(i); this->MarkInstances.push_back(m); } } } //----------------------------------------------------------------------------- bool vtkPanelMark::Paint(vtkContext2D* painter) { //TODO: Be smarter about the update this->Update(); if (!painter->GetTransform()) { vtkSmartPointer<vtkTransform2D> trans = vtkSmartPointer<vtkTransform2D>::New(); trans->Identity(); painter->SetTransform(trans); } double* left = this->Left.GetArray(this); double* bottom = this->Bottom.GetArray(this); size_t numMarks = this->Marks.size(); vtkDataElement data = this->Data.GetData(this); vtkIdType numChildren = 1; if(data.IsValid()) { numChildren = data.GetNumberOfChildren(); } for (size_t j = 0; j < numMarks; ++j) { for (vtkIdType i = 0; i < numChildren; ++i) { this->Index = i; painter->GetTransform()->Translate(left[i], bottom[i]); painter->SetTransform(painter->GetTransform()); this->MarkInstances[j*numChildren + i]->Paint(painter); painter->GetTransform()->Translate(-left[i], -bottom[i]); painter->SetTransform(painter->GetTransform()); } } return true; } //----------------------------------------------------------------------------- void vtkPanelMark::PrintSelf(ostream &os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); } <|endoftext|>
<commit_before>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> #include <fstream> #include <assert.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif static const char *ASNS_AT_TOP[] = {"13768", "23498", "3", "15169", "714", "32934", "7847"}; //Peer1, Cogeco, MIT, google, apple, facebook, NASA static const int NUM_ASNS_AT_TOP = 7; NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd, char separator = ' ') { *lineEnd = false; while ((*source != separator) && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == separator) || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::resetToDefault() { for(int i = 0; i < nodes.size(); i++) { Node* node = nodes[i].get(); node->timelineActive = node->activeDefault; if(node->activeDefault) { node->positionX = node->defaultPositionX; node->positionY = node->defaultPositionY; node->importance = node->defaultImportance; } } connections = defaultConnections; visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->timelineActive = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; bool firstLoad = nodes.size() == 0; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); if (nodes.size() == 0) { LOG("initializing nodes vector (total %d)", numNodes); nodes.reserve(numNodes); nodes.resize(NUM_ASNS_AT_TOP); //LOG("nodes.size: %ld", nodes.size()); } int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->timelineActive = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->type = AS_UNKNOWN; node->timelineActive = true; //is it a special node? bool needInsert = false; for (int i=0; i<NUM_ASNS_AT_TOP; i++) { if (strcmp(token, ASNS_AT_TOP[i]) == 0) { node->index = i; needInsert = true; //LOG("found special at index %d", node->index); break; } } if (needInsert) { nodes[node->index] = node; } else { //regular nodes can just be appended. node->index = nodes.size(); nodes.push_back(node); } nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } if(node && firstLoad) { node->defaultPositionX = node->positionX; node->defaultPositionY = node->positionY; node->defaultImportance = node->importance; node->activeDefault = true; } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } if(firstLoad) { defaultConnections = connections; } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[(int)AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[(int)AS_T1] = "Large ISP"; friendlyTypeStrings[(int)AS_T2] = "Small ISP"; friendlyTypeStrings[(int)AS_COMP] = "Organization Network"; friendlyTypeStrings[(int)AS_EDU] = "University"; friendlyTypeStrings[(int)AS_IX] = "Internet Exchange Point"; friendlyTypeStrings[(int)AS_NIC] = "Network Information Center"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if (node) { Json::Value as = root[members[i]]; // node->name = as[1].asString(); // node->rawTextDescription = as[5].asString(); // node->dateRegistered = as[3].asString(); // node->address = as[7].asString(); // node->city = as[8].asString(); // node->state = as[9].asString(); // node->postalCode = as[10].asString(); // node->country = as[11].asString(); // node->hasLatLong = true; // node->latitude = as[12].asFloat()*2.0*3.14159/360.0; // node->longitude = as[13].asFloat()*2.0*3.14159/360.0; node->rawTextDescription = as[0].asString(); node->hasLatLong = true; node->latitude = as[1].asFloat()*2.0*3.14159/360.0; node->longitude = as[2].asFloat()*2.0*3.14159/360.0; } } } } void MapData::loadUnified(const std::string& text) { const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); nodes.reserve(numNodes); for (int i = 0; i < numNodes; i++) { NodePointer node = NodePointer(new Node()); node->timelineActive = true; node->activeDefault = true; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->asn = token; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); if(token[0] != '?') { node->rawTextDescription = token; } sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->type = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->hasLatLong = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->latitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->longitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionX = node->defaultPositionX = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionY = node->defaultPositionY = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->importance = node->defaultImportance = atof(token); assert(lineEnd); node->index = nodes.size(); nodes.push_back(node); nodesByAsn[node->asn] = node; } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodes[atoi(token)]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodes[atoi(token)]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } defaultConnections = connections; LOG("loaded default data: %d nodes, %d connections", (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::createNodeBoxes() { boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->isActive()) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } void MapData::dumpUnified(void) { std::ofstream out("/Users/nigel/Downloads/unified.txt"); out << nodes.size() << std::endl; out << connections.size() << std::endl; for(int i = 0; i < nodes.size(); i++) { std::string desc = nodes[i]->rawTextDescription; if(desc.length() == 0) { desc = "?"; } out << nodes[i]->asn << "\t" << desc << "\t" << nodes[i]->type << "\t" << nodes[i]->hasLatLong << "\t" << nodes[i]->latitude << "\t" << nodes[i]->longitude << "\t" << nodes[i]->positionX << "\t" << nodes[i]->positionY << "\t" << nodes[i]->importance << "\t" << std::endl; } for(int i = 0; i < connections.size(); i++) { out << connections[i]->first->index << " " << connections[i]->second->index << std::endl; } } <commit_msg>Change ASInfo loading so that it should handle geolocaiton that don't exist in the first timeline point properly.<commit_after>// // MapData // InternetMap // #include "MapData.hpp" #include "Node.hpp" #include "DisplayLines.hpp" #include "Connection.hpp" #include "IndexBox.hpp" #include "MapDisplay.hpp" #include <sstream> #include <stdlib.h> #include <fstream> #include <assert.h> // TODO: figure out how to do this right #ifdef ANDROID #include "jsoncpp/json.h" #else #include "json.h" #endif static const char *ASNS_AT_TOP[] = {"13768", "23498", "3", "15169", "714", "32934", "7847"}; //Peer1, Cogeco, MIT, google, apple, facebook, NASA static const int NUM_ASNS_AT_TOP = 7; NodePointer MapData::nodeAtIndex(unsigned int index) { return nodes[index]; } void split( std::vector<std::string> & theStringVector, /* Altered/returned value */ const std::string & theString, const std::string & theDelimiter) { size_t start = 0, end = 0; while ( end != std::string::npos) { end = theString.find( theDelimiter, start); // If at end, use length=maxLength. Else use length=end-start. theStringVector.push_back( theString.substr( start, (end == std::string::npos) ? std::string::npos : end - start)); // If at end, use start=maxSize. Else use start=end+delimiter. start = ( ( end > (std::string::npos - theDelimiter.size()) ) ? std::string::npos : end + theDelimiter.size()); } } static const int MAX_TOKEN_SIZE = 256; const char* nextToken(const char* source, char* token, bool* lineEnd, char separator = ' ') { *lineEnd = false; while ((*source != separator) && (*source != '\n') && (*source != 0)) { *token++ = *source++; } *lineEnd |= *source == '\n'; *token = 0; if(*source != 0) { while ((*source == separator) || (*source == '\n')) { source++; *lineEnd |= *source == '\n'; } } return source; } void MapData::resetToDefault() { for(int i = 0; i < nodes.size(); i++) { Node* node = nodes[i].get(); node->timelineActive = node->activeDefault; if(node->activeDefault) { node->positionX = node->defaultPositionX; node->positionY = node->defaultPositionY; node->importance = node->defaultImportance; } } connections = defaultConnections; visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromString(const std::string& text) { // Connections an boxes are always fully regenerated connections.erase(connections.begin(), connections.end()); // Mark all nodes as inactive (they will be reactivated if they are in the current data set) for(int i = 0; i < nodes.size(); i++) { nodes[i]->timelineActive = false; } const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; bool firstLoad = nodes.size() == 0; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); if (nodes.size() == 0) { LOG("initializing nodes vector (total %d)", numNodes); nodes.reserve(numNodes); nodes.resize(NUM_ASNS_AT_TOP); //LOG("nodes.size: %ld", nodes.size()); } int missingNodes = 0; for (int i = 0; i < numNodes; i++) { // Grab asn sourceText = nextToken(sourceText, token, &lineEnd); // check for matching existing node NodePointer node = nodesByAsn[token]; if(node) { // already thre, just mark as active node->timelineActive = true; } else { // Not there, create missingNodes++; node = NodePointer(new Node()); node->asn = token; node->type = AS_UNKNOWN; node->timelineActive = true; //is it a special node? bool needInsert = false; for (int i=0; i<NUM_ASNS_AT_TOP; i++) { if (strcmp(token, ASNS_AT_TOP[i]) == 0) { node->index = i; needInsert = true; //LOG("found special at index %d", node->index); break; } } if (needInsert) { nodes[node->index] = node; } else { //regular nodes can just be appended. node->index = nodes.size(); nodes.push_back(node); } nodesByAsn[node->asn] = node; } // Refill data that is unique to a particualar timeline position sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->importance = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionX = atof(token); } sourceText = nextToken(sourceText, token, &lineEnd); if(node) { node->positionY = atof(token); } if(node && firstLoad) { node->defaultPositionX = node->positionX; node->defaultPositionY = node->positionY; node->defaultImportance = node->importance; node->activeDefault = true; } } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodesByAsn[token]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodesByAsn[token]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } if(firstLoad) { defaultConnections = connections; } LOG("loaded data: %d nodes (this load), %d nodes (total), %d connections", missingNodes, (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::loadFromAttrString(const std::string& json){ std::map<std::string, int> asTypeDict; asTypeDict["abstained"] = AS_UNKNOWN; asTypeDict["t1"] = AS_T1; asTypeDict["t2"] = AS_T2; asTypeDict["comp"] = AS_COMP; asTypeDict["edu"] = AS_EDU; asTypeDict["ix"] = AS_IX; asTypeDict["nic"] = AS_NIC; std::map<int, std::string> friendlyTypeStrings; friendlyTypeStrings[(int)AS_UNKNOWN] = "Unknown Network Type"; friendlyTypeStrings[(int)AS_T1] = "Large ISP"; friendlyTypeStrings[(int)AS_T2] = "Small ISP"; friendlyTypeStrings[(int)AS_COMP] = "Organization Network"; friendlyTypeStrings[(int)AS_EDU] = "University"; friendlyTypeStrings[(int)AS_IX] = "Internet Exchange Point"; friendlyTypeStrings[(int)AS_NIC] = "Network Information Center"; std::vector<std::string> lines; split(lines, json, "\n"); for(unsigned int i = 0; i < lines.size(); i++) { std::string line = lines[i]; std::vector<std::string> aDesc; split(aDesc, line, "\t"); NodePointer node = nodesByAsn[aDesc[0]]; if(node){ node->type = asTypeDict[aDesc[7]]; node->typeString = friendlyTypeStrings[node->type]; node->rawTextDescription = aDesc[1]; } } // NSLog(@"attr load : %.2fms", ([NSDate timeIntervalSinceReferenceDate] - start) * 1000.0f); } void MapData::loadASInfo(const std::string& json){ Json::Value root; Json::Reader reader; bool success = reader.parse(json, root); if(success) { std::vector<std::string> members = root.getMemberNames(); for (unsigned int i = 0; i < members.size(); i++) { NodePointer node = nodesByAsn[members[i]]; if(!node) { node = NodePointer(new Node()); node->asn = members[i]; node->type = AS_UNKNOWN; node->timelineActive = false; node->index = nodes.size(); nodes.push_back(node); nodesByAsn[node->asn] = node; } if (node) { Json::Value as = root[members[i]]; // node->name = as[1].asString(); // node->rawTextDescription = as[5].asString(); // node->dateRegistered = as[3].asString(); // node->address = as[7].asString(); // node->city = as[8].asString(); // node->state = as[9].asString(); // node->postalCode = as[10].asString(); // node->country = as[11].asString(); // node->hasLatLong = true; // node->latitude = as[12].asFloat()*2.0*3.14159/360.0; // node->longitude = as[13].asFloat()*2.0*3.14159/360.0; node->rawTextDescription = as[0].asString(); node->hasLatLong = true; node->latitude = as[1].asFloat()*2.0*3.14159/360.0; node->longitude = as[2].asFloat()*2.0*3.14159/360.0; } } } } void MapData::loadUnified(const std::string& text) { const char* sourceText = text.c_str(); char token[MAX_TOKEN_SIZE]; bool lineEnd; int numNodes, numConnections; // Grab header data (node and connection counts) sourceText = nextToken(sourceText, token, &lineEnd); numNodes = atof(token); sourceText = nextToken(sourceText, token, &lineEnd); numConnections = atof(token); nodes.reserve(numNodes); for (int i = 0; i < numNodes; i++) { NodePointer node = NodePointer(new Node()); node->timelineActive = true; node->activeDefault = true; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->asn = token; sourceText = nextToken(sourceText, token, &lineEnd, '\t'); if(token[0] != '?') { node->rawTextDescription = token; } sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->type = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->hasLatLong = atoi(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->latitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->longitude = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionX = node->defaultPositionX = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->positionY = node->defaultPositionY = atof(token); sourceText = nextToken(sourceText, token, &lineEnd, '\t'); node->importance = node->defaultImportance = atof(token); assert(lineEnd); node->index = nodes.size(); nodes.push_back(node); nodesByAsn[node->asn] = node; } // Load connections for (int i = 0; i < numConnections; i++) { ConnectionPointer connection(new Connection()); sourceText = nextToken(sourceText, token, &lineEnd); connection->first = nodes[atoi(token)]; sourceText = nextToken(sourceText, token, &lineEnd); connection->second = nodes[atoi(token)]; if (connection->first && connection->second) { connection->first->connections.push_back(connection); connection->second->connections.push_back(connection); connections.push_back(connection); } } defaultConnections = connections; LOG("loaded default data: %d nodes, %d connections", (int)(nodes.size()), numConnections); visualization->activate(nodes); createNodeBoxes(); } void MapData::createNodeBoxes() { boxesForNodes.erase(boxesForNodes.begin(), boxesForNodes.end()); for (int k = 0; k < numberOfCellsZ; k++) { float z = IndexBoxMinZ + boxSizeZWithoutOverlap*k; for (int j = 0; j < numberOfCellsY; j++) { float y = IndexBoxMinY + boxSizeYWithoutOverlap*j; for(int i = 0; i < numberOfCellsX; i++) { float x = IndexBoxMinX + boxSizeXWithoutOverlap*i; IndexBoxPointer box = IndexBoxPointer(new IndexBox()); box->setCenter(Point3(x+boxSizeXWithoutOverlap/2, y+boxSizeYWithoutOverlap/2, z+boxSizeZWithoutOverlap/2)); box->setMinCorner(Point3(x, y, z)); box->setMaxCorner(Point3(x+boxSizeXWithoutOverlap, y+boxSizeYWithoutOverlap, z+boxSizeZWithoutOverlap)); boxesForNodes.push_back(box); } } } for (unsigned int i = 0; i < nodes.size(); i++) { NodePointer ptrNode = nodes.at(i); if(ptrNode->isActive()) { Point3 pos = visualization->nodePosition(ptrNode); IndexBoxPointer box = indexBoxForPoint(pos); box->indices.insert(i); } } } IndexBoxPointer MapData::indexBoxForPoint(const Point3& point) { int posX = (int)fabsf((point.getX() + fabsf(IndexBoxMinX))/boxSizeXWithoutOverlap); int posY = (int)fabsf((point.getY() + fabsf(IndexBoxMinY))/boxSizeYWithoutOverlap); int posZ = (int)fabsf((point.getZ() + fabsf(IndexBoxMinZ))/boxSizeZWithoutOverlap); int posInArray = posX + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*posY + (fabsf(IndexBoxMinX) + fabsf(IndexBoxMaxX))/boxSizeXWithoutOverlap*(fabsf(IndexBoxMinY)+fabsf(IndexBoxMaxY))/boxSizeYWithoutOverlap*posZ; return boxesForNodes[posInArray]; } void MapData::dumpUnified(void) { std::ofstream out("/Users/nigel/Downloads/unified.txt"); out << nodes.size() << std::endl; out << connections.size() << std::endl; for(int i = 0; i < nodes.size(); i++) { std::string desc = nodes[i]->rawTextDescription; if(desc.length() == 0) { desc = "?"; } out << nodes[i]->asn << "\t" << desc << "\t" << nodes[i]->type << "\t" << nodes[i]->hasLatLong << "\t" << nodes[i]->latitude << "\t" << nodes[i]->longitude << "\t" << nodes[i]->positionX << "\t" << nodes[i]->positionY << "\t" << nodes[i]->importance << "\t" << std::endl; } for(int i = 0; i < connections.size(); i++) { out << connections[i]->first->index << " " << connections[i]->second->index << std::endl; } } <|endoftext|>
<commit_before> #include <iostream> #include <string> #include <cstdlib> #define GUEST 0 #define ADMIN 1 #define BUYER 2 #define SELLER 3 #define FULL 4 int userType; using namespace std; int main() { cout << "*****************************************************" << endl; cout << "Welcome to the Ticket Selling Service" << endl; cout << "*****************************************************" << endl; string command; while (command.compare("exit") != 0) { cout << "\n" << endl; cout << "Enter your command:-> "; cin >> command; if (command.compare("login") == 0) { //login() cout << "Successfully Logged in !" << endl; } else if (command.compare("buy") == 0) { //buy() cout << "Successfully purchased tickets" << endl; } else if (command.compare("sell") == 0) { //sell() cout << "Successfully sold tickets" << endl; } else if (command.compare("addcredit") == 0) { //addcredit() cout << "Successfully added credit" << endl; } else if (command.compare("create") == 0) { //login() cout << "Successfully created new user !" << endl; } else { cout << "Unrecogonized command. Please try again" << endl; } } }<commit_msg>bug fixes main function<commit_after> #include <iostream> #include <string> #include <cstdlib> #define GUEST 0 #define ADMIN 1 #define BUYER 2 #define SELLER 3 #define FULL 4 int userType; using namespace std; int main() { cout << "*****************************************************" << endl; cout << "Welcome to the Ticket Selling Service" << endl; cout << "*****************************************************" << endl; string command; while (command.compare("exit") != 0) { cout << "\n" << endl; cout << "Enter your command:-> "; cin >> command; if (command.compare("login") == 0) { //login() cout << "Successfully Logged in !" << endl; } else if (command.compare("buy") == 0) { //buy() cout << "Successfully purchased tickets" << endl; } else if (command.compare("sell") == 0) { //sell() cout << "Successfully sold tickets" << endl; } else if (command.compare("addcredit") == 0) { //addcredit() cout << "Successfully added credit" << endl; } else if (command.compare("create") == 0) { //create() cout << "Successfully created new user !" << endl; } else { cout << "Unrecogonized command. Please try again" << endl; } } }<|endoftext|>
<commit_before>/** * Helpers used for binding method pointers to an instance if object. * Such bound function may be used as C-callback function. * * Adapted and extended solution described here: * http://p-nand-q.com/programming/cplusplus/using_member_functions_with_c_function_pointers.html * * TODO: add support for std::function * * @author mliszcz<liszcz.michal@gmail.com> * @license MIT */ #pragma once #include <array> #include <utility> namespace invoker { constexpr int SLOTS = 10; /** Plain old C callback. */ template<typename Ret, typename... Args> using FreeFnPtr = Ret (*)(Args...); /** C++ method. */ template<typename Clazz, typename Ret, typename... Args> using MethodPtr = Ret (Clazz::*)(Args...); /** * Slot that stores plain function as a method bound to an class instance. * @param TId Slot index type. */ template<typename TId, typename Clazz, typename Ret, typename... Args> class SlotBase { public: Clazz* clazz = nullptr; MethodPtr<Clazz, Ret, Args...> method = nullptr; FreeFnPtr<Ret, Args...> freefn = nullptr; SlotBase(FreeFnPtr<Ret, Args...> fp) : freefn(fp) { } static Ret staticInvoke(TId, Args...); }; /** * Derived SlotBase. There are *many* specializations created * at compile time, each with diffrent Id. */ template <int Id, typename Clazz, typename Ret, typename... Args> class IndexedSlot : public SlotBase<int, Clazz, Ret, Args...> { public: IndexedSlot() : SlotBase<int, Clazz, Ret, Args...> (&IndexedSlot<Id, Clazz, Ret, Args...>::staticImpl) { } static Ret staticImpl(Args... args) { return SlotBase<int, Clazz, Ret, Args...>::staticInvoke(Id, args...); } }; /** * Functor that wraps plain C function and its state. */ template<typename Clazz, typename Ret, typename... Args> class BoundFnPtr { public: template<std::size_t... Indices> static constexpr std::array<SlotBase<int, Clazz, Ret, Args...>*, sizeof...(Indices)> createSlotArrayInner(std::index_sequence<Indices...>) { return {{ new IndexedSlot<Indices, Clazz, Ret, Args...>()... }}; } template<std::size_t N> static constexpr std::array<SlotBase<int, Clazz, Ret, Args...>*, N> createSlotArray() { return createSlotArrayInner(std::make_index_sequence<N>{}); } static std::array<SlotBase<int, Clazz, Ret, Args...>*, SLOTS> genericarray; BoundFnPtr(Clazz* clazz, MethodPtr<Clazz, Ret, Args...> method) { for (int i=0; i<SLOTS; ++i) { if (genericarray[i]->clazz == nullptr) { genericarray[i]->clazz = clazz; genericarray[i]->method = method; index = i; freefn = genericarray[i]->freefn; return; } } throw std::runtime_error("No slot available"); } virtual ~BoundFnPtr() { genericarray[index]->clazz = nullptr; } operator FreeFnPtr<Ret, Args...>() const { return freefn; } private: FreeFnPtr<Ret, Args...> freefn; int index; }; template<typename Clazz, typename Ret, typename... Args> std::array<SlotBase<int, Clazz, Ret, Args...>*, SLOTS> BoundFnPtr<Clazz, Ret, Args...>::genericarray = BoundFnPtr<Clazz, Ret, Args...>::createSlotArray<SLOTS>(); template<typename TId, typename Clazz, typename Ret, typename... Args> Ret SlotBase<TId, Clazz, Ret, Args...>::staticInvoke(TId id, Args... args) { auto x = BoundFnPtr<Clazz, Ret, Args...>::genericarray; return ((x[id]->clazz)->*(x[id]->method))(args...); } } <commit_msg>invoker.hpp removed<commit_after><|endoftext|>
<commit_before>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_CARDS_HPP #define ROSETTASTONE_CARDS_HPP #include <Rosetta/Cards/Card.hpp> #include <vector> namespace RosettaStone { //! //! \brief Search filter structure. //! //! This structure stores the filter value for searching the card. //! struct SearchFilter { Rarity rarity = Rarity::INVALID; CardClass playerClass = CardClass::INVALID; CardType cardType = CardType::INVALID; Race race = Race::INVALID; GameTag gameTag = GameTag::INVALID; std::string name; size_t costMin = 0, costMax = 0; int attackMin = 0, attackMax = 0; size_t healthMin = 0, healthMax = 0; }; //! //! \brief Cards class. //! //! This class stores a list of cards and provides several search methods. //! class Cards { public: //! Deleted copy constructor. Cards(const Cards& cards) = delete; //! Deleted move constructor. Cards(Cards&& cards) = delete; //! Deleted copy assignment operator. Cards& operator=(const Cards& cards) = delete; //! Deleted move assignment operator. Cards& operator=(Cards&& cards) = delete; //! Returns an instance of Cards class. //! \return An instance of Cards class. static Cards& GetInstance(); //! Returns a list of all cards. //! \return A list of all cards. static const std::vector<Card>& GetAllCards(); //! Returns a card that matches \p id. //! \param id The ID of the card. //! \return A card that matches \p id. static Card FindCardByID(const std::string& id); //! Returns a list of cards that matches \p rarity. //! \param rarity The rarity of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByRarity(Rarity rarity); //! Returns a list of cards that matches \p cardClass. //! \param cardClass The class of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByClass(CardClass cardClass); //! Returns a list of cards that matches \p cardSet. //! \param cardSet The set of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardBySet(CardSet cardSet); //! Returns a list of cards that matches \p cardType. //! \param cardType The type of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByType(CardType cardType); //! Returns a list of cards that matches \p race. //! \param race The race of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByRace(Race race); //! Returns a card that matches \p name. //! \param name The name of the card. //! \return A card that matches condition. static Card FindCardByName(const std::string& name); //! Returns a list of cards whose cost is between \p minVal and \p maxVal. //! \param minVal The minimum cost value of the card. //! \param maxVal The maximum cost value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByCost(std::size_t minVal, std::size_t maxVal); //! Returns a list of cards whose attack is between \p minVal and \p maxVal. //! \param minVal The minimum attack value of the card. //! \param maxVal The maximum attack value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByAttack(int minVal, int maxVal); //! Returns a list of cards whose health is between \p minVal and \p maxVal. //! \param minVal The minimum health value of the card. //! \param maxVal The maximum health value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByHealth(int minVal, int maxVal); //! Returns a list of cards whose spell power is between \p minVal and \p maxVal. //! \param minVal The minimum spell power value of the card. //! \param maxVal The maximum spell power value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardBySpellPower(std::size_t minVal, std::size_t maxVal); //! Returns a list of cards that has \p gameTags. //! \param gameTags A list of game tag of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByGameTag(std::vector<GameTag> gameTags); //! Returns a hero card that matches \p cardClass. //! \param cardClass The class of the card. //! \return A hero card that matches condition. static Card GetHeroCard(CardClass cardClass); //! Returns a default hero power card that matches \p cardClass. //! \param cardClass The class of the card. //! \return A default hero power card that matches condition. static Card GetDefaultHeroPower(CardClass cardClass); private: //! Constructor: Loads card data. Cards(); //! Destructor: Releases card data. ~Cards(); static std::vector<Card> m_cards; }; } // namespace RosettaStone #endif // ROSETTASTONE_CARDS_HPP <commit_msg>fix: Correct sign compare warning message<commit_after>// Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon // We are making my contributions/submissions to this project solely in our // personal capacity and are not conveying any rights to any intellectual // property of any third parties. #ifndef ROSETTASTONE_CARDS_HPP #define ROSETTASTONE_CARDS_HPP #include <Rosetta/Cards/Card.hpp> #include <vector> namespace RosettaStone { //! //! \brief Search filter structure. //! //! This structure stores the filter value for searching the card. //! struct SearchFilter { Rarity rarity = Rarity::INVALID; CardClass playerClass = CardClass::INVALID; CardType cardType = CardType::INVALID; Race race = Race::INVALID; GameTag gameTag = GameTag::INVALID; std::string name; size_t costMin = 0, costMax = 0; int attackMin = 0, attackMax = 0; int healthMin = 0, healthMax = 0; }; //! //! \brief Cards class. //! //! This class stores a list of cards and provides several search methods. //! class Cards { public: //! Deleted copy constructor. Cards(const Cards& cards) = delete; //! Deleted move constructor. Cards(Cards&& cards) = delete; //! Deleted copy assignment operator. Cards& operator=(const Cards& cards) = delete; //! Deleted move assignment operator. Cards& operator=(Cards&& cards) = delete; //! Returns an instance of Cards class. //! \return An instance of Cards class. static Cards& GetInstance(); //! Returns a list of all cards. //! \return A list of all cards. static const std::vector<Card>& GetAllCards(); //! Returns a card that matches \p id. //! \param id The ID of the card. //! \return A card that matches \p id. static Card FindCardByID(const std::string& id); //! Returns a list of cards that matches \p rarity. //! \param rarity The rarity of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByRarity(Rarity rarity); //! Returns a list of cards that matches \p cardClass. //! \param cardClass The class of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByClass(CardClass cardClass); //! Returns a list of cards that matches \p cardSet. //! \param cardSet The set of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardBySet(CardSet cardSet); //! Returns a list of cards that matches \p cardType. //! \param cardType The type of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByType(CardType cardType); //! Returns a list of cards that matches \p race. //! \param race The race of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByRace(Race race); //! Returns a card that matches \p name. //! \param name The name of the card. //! \return A card that matches condition. static Card FindCardByName(const std::string& name); //! Returns a list of cards whose cost is between \p minVal and \p maxVal. //! \param minVal The minimum cost value of the card. //! \param maxVal The maximum cost value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByCost(std::size_t minVal, std::size_t maxVal); //! Returns a list of cards whose attack is between \p minVal and \p maxVal. //! \param minVal The minimum attack value of the card. //! \param maxVal The maximum attack value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByAttack(int minVal, int maxVal); //! Returns a list of cards whose health is between \p minVal and \p maxVal. //! \param minVal The minimum health value of the card. //! \param maxVal The maximum health value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByHealth(int minVal, int maxVal); //! Returns a list of cards whose spell power is between \p minVal and \p maxVal. //! \param minVal The minimum spell power value of the card. //! \param maxVal The maximum spell power value of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardBySpellPower(std::size_t minVal, std::size_t maxVal); //! Returns a list of cards that has \p gameTags. //! \param gameTags A list of game tag of the card. //! \return A list of cards that matches condition. static std::vector<Card> FindCardByGameTag(std::vector<GameTag> gameTags); //! Returns a hero card that matches \p cardClass. //! \param cardClass The class of the card. //! \return A hero card that matches condition. static Card GetHeroCard(CardClass cardClass); //! Returns a default hero power card that matches \p cardClass. //! \param cardClass The class of the card. //! \return A default hero power card that matches condition. static Card GetDefaultHeroPower(CardClass cardClass); private: //! Constructor: Loads card data. Cards(); //! Destructor: Releases card data. ~Cards(); static std::vector<Card> m_cards; }; } // namespace RosettaStone #endif // ROSETTASTONE_CARDS_HPP <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cachedprimitivebase.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 03:24:53 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include <canvas/base/cachedprimitivebase.hxx> #include <com/sun/star/rendering/RepaintResult.hpp> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/tools/canvastools.hxx> using namespace ::com::sun::star; #define IMPLEMENTATION_NAME "canvas::CachedPrimitiveBase" #define SERVICE_NAME "com.sun.star.rendering.CachedBitmap" namespace canvas { CachedPrimitiveBase::CachedPrimitiveBase( const rendering::ViewState& rUsedViewState, const uno::Reference< rendering::XCanvas >& rTarget, bool bFailForChangedViewTransform ) : CachedPrimitiveBase_Base( m_aMutex ), maUsedViewState( rUsedViewState ), mxTarget( rTarget ), mbFailForChangedViewTransform( bFailForChangedViewTransform ) { } CachedPrimitiveBase::~CachedPrimitiveBase() { } void SAL_CALL CachedPrimitiveBase::disposing() { ::osl::MutexGuard aGuard( m_aMutex ); maUsedViewState.Clip.clear(); mxTarget.clear(); } sal_Int8 SAL_CALL CachedPrimitiveBase::redraw( const rendering::ViewState& aState ) throw (lang::IllegalArgumentException, uno::RuntimeException) { ::basegfx::B2DHomMatrix aUsedTransformation; ::basegfx::B2DHomMatrix aNewTransformation; ::basegfx::unotools::homMatrixFromAffineMatrix( aUsedTransformation, maUsedViewState.AffineTransform ); ::basegfx::unotools::homMatrixFromAffineMatrix( aNewTransformation, aState.AffineTransform ); const bool bSameViewTransforms( aUsedTransformation == aNewTransformation ); if( mbFailForChangedViewTransform && !bSameViewTransforms ) { // differing transformations, don't try to draft the // output, just plain fail here. return rendering::RepaintResult::FAILED; } return doRedraw( aState, maUsedViewState, mxTarget, bSameViewTransforms ); } ::rtl::OUString SAL_CALL CachedPrimitiveBase::getImplementationName( ) throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) ); } sal_Bool SAL_CALL CachedPrimitiveBase::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) ); } uno::Sequence< ::rtl::OUString > SAL_CALL CachedPrimitiveBase::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) ); return aRet; } } <commit_msg>INTEGRATION: CWS changefileheader (1.3.92); FILE MERGED 2008/03/28 16:35:11 rt 1.3.92.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: cachedprimitivebase.cxx,v $ * $Revision: 1.4 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_canvas.hxx" #include <canvas/debug.hxx> #include <canvas/base/cachedprimitivebase.hxx> #include <com/sun/star/rendering/RepaintResult.hpp> #include <basegfx/matrix/b2dhommatrix.hxx> #include <basegfx/tools/canvastools.hxx> using namespace ::com::sun::star; #define IMPLEMENTATION_NAME "canvas::CachedPrimitiveBase" #define SERVICE_NAME "com.sun.star.rendering.CachedBitmap" namespace canvas { CachedPrimitiveBase::CachedPrimitiveBase( const rendering::ViewState& rUsedViewState, const uno::Reference< rendering::XCanvas >& rTarget, bool bFailForChangedViewTransform ) : CachedPrimitiveBase_Base( m_aMutex ), maUsedViewState( rUsedViewState ), mxTarget( rTarget ), mbFailForChangedViewTransform( bFailForChangedViewTransform ) { } CachedPrimitiveBase::~CachedPrimitiveBase() { } void SAL_CALL CachedPrimitiveBase::disposing() { ::osl::MutexGuard aGuard( m_aMutex ); maUsedViewState.Clip.clear(); mxTarget.clear(); } sal_Int8 SAL_CALL CachedPrimitiveBase::redraw( const rendering::ViewState& aState ) throw (lang::IllegalArgumentException, uno::RuntimeException) { ::basegfx::B2DHomMatrix aUsedTransformation; ::basegfx::B2DHomMatrix aNewTransformation; ::basegfx::unotools::homMatrixFromAffineMatrix( aUsedTransformation, maUsedViewState.AffineTransform ); ::basegfx::unotools::homMatrixFromAffineMatrix( aNewTransformation, aState.AffineTransform ); const bool bSameViewTransforms( aUsedTransformation == aNewTransformation ); if( mbFailForChangedViewTransform && !bSameViewTransforms ) { // differing transformations, don't try to draft the // output, just plain fail here. return rendering::RepaintResult::FAILED; } return doRedraw( aState, maUsedViewState, mxTarget, bSameViewTransforms ); } ::rtl::OUString SAL_CALL CachedPrimitiveBase::getImplementationName( ) throw (uno::RuntimeException) { return ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( IMPLEMENTATION_NAME ) ); } sal_Bool SAL_CALL CachedPrimitiveBase::supportsService( const ::rtl::OUString& ServiceName ) throw (uno::RuntimeException) { return ServiceName.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM ( SERVICE_NAME ) ); } uno::Sequence< ::rtl::OUString > SAL_CALL CachedPrimitiveBase::getSupportedServiceNames( ) throw (uno::RuntimeException) { uno::Sequence< ::rtl::OUString > aRet(1); aRet[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM ( SERVICE_NAME ) ); return aRet; } } <|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_tree /// \notebook /// This example illustrates how to make a Tree from variables or arrays /// in a C struct - without a dictionary, by creating the branches for /// builtin types (int, float, double) and arrays explicitly. /// See tree2a.C for the same example using a class with dictionary /// instead of a C-struct. /// /// In this example, we are mapping a C struct to one of the Geant3 /// common blocks /gctrak/. In the real life, this common will be filled /// by Geant3 at each step and only the Tree Fill function should be called. /// The example emulates the Geant3 step routines. /// /// to run the example, do: /// ~~~ /// .x tree2.C to execute with the Cling interpreter /// .x tree2.C++ to execute with native compiler /// ~~~ /// \macro_code /// /// \author Rene Brun #include "TFile.h" #include "TTree.h" #include "TBrowser.h" #include "TH2.h" #include "TRandom.h" #include "TCanvas.h" #include "TMath.h" #include "TROOT.h" const Int_t MAXMEC = 30; typedef struct { Float_t vect[7]; Float_t getot; Float_t gekin; Float_t vout[7]; Int_t nmec; Int_t lmec[MAXMEC]; Int_t namec[MAXMEC]; Int_t nstep; Int_t pid; Float_t destep; Float_t destel; Float_t safety; Float_t sleng; Float_t step; Float_t snext; Float_t sfield; Float_t tofg; Float_t gekrat; Float_t upwght; } Gctrak_t; void helixStep(Float_t step, Float_t *vect, Float_t *vout) { // extrapolate track in constant field Float_t field = 20; //magnetic field in kilogauss enum Evect {kX,kY,kZ,kPX,kPY,kPZ,kPP}; vout[kPP] = vect[kPP]; Float_t h4 = field*2.99792e-4; Float_t rho = -h4/vect[kPP]; Float_t tet = rho*step; Float_t tsint = tet*tet/6; Float_t sintt = 1 - tsint; Float_t sint = tet*sintt; Float_t cos1t = tet/2; Float_t f1 = step*sintt; Float_t f2 = step*cos1t; Float_t f3 = step*tsint*vect[kPZ]; Float_t f4 = -tet*cos1t; Float_t f5 = sint; Float_t f6 = tet*cos1t*vect[kPZ]; vout[kX] = vect[kX] + (f1*vect[kPX] - f2*vect[kPY]); vout[kY] = vect[kY] + (f1*vect[kPY] + f2*vect[kPX]); vout[kZ] = vect[kZ] + (f1*vect[kPZ] + f3); vout[kPX] = vect[kPX] + (f4*vect[kPX] - f5*vect[kPY]); vout[kPY] = vect[kPY] + (f4*vect[kPY] + f5*vect[kPX]); vout[kPZ] = vect[kPZ] + (f4*vect[kPZ] + f6); } void tree2w() { //create a Tree file tree2.root //create the file, the Tree and a few branches with //a subset of gctrak TFile f("tree2.root","recreate"); TTree t2("t2","a Tree with data from a fake Geant3"); Gctrak_t gstep; t2.Branch("vect",gstep.vect,"vect[7]/F"); t2.Branch("getot",&gstep.getot,"getot/F"); t2.Branch("gekin",&gstep.gekin,"gekin/F"); t2.Branch("nmec",&gstep.nmec,"nmec/I"); t2.Branch("lmec",gstep.lmec,"lmec[nmec]/I"); t2.Branch("destep",&gstep.destep,"destep/F"); t2.Branch("pid",&gstep.pid,"pid/I"); //Initialize particle parameters at first point Float_t px,py,pz,p,charge=0; Float_t vout[7]; Float_t mass = 0.137; Bool_t newParticle = kTRUE; gstep.step = 0.1; gstep.destep = 0; gstep.nmec = 0; gstep.pid = 0; //transport particles for (Int_t i=0;i<10000;i++) { //generate a new particle if necessary if (newParticle) { px = gRandom->Gaus(0,.02); py = gRandom->Gaus(0,.02); pz = gRandom->Gaus(0,.02); p = TMath::Sqrt(px*px+py*py+pz*pz); charge = 1; if (gRandom->Rndm() < 0.5) charge = -1; gstep.pid += 1; gstep.vect[0] = 0; gstep.vect[1] = 0; gstep.vect[2] = 0; gstep.vect[3] = px/p; gstep.vect[4] = py/p; gstep.vect[5] = pz/p; gstep.vect[6] = p*charge; gstep.getot = TMath::Sqrt(p*p + mass*mass); gstep.gekin = gstep.getot - mass; newParticle = kFALSE; } // fill the Tree with current step parameters t2.Fill(); //transport particle in magnetic field helixStep(gstep.step, gstep.vect, vout); //make one step //apply energy loss gstep.destep = gstep.step*gRandom->Gaus(0.0002,0.00001); gstep.gekin -= gstep.destep; gstep.getot = gstep.gekin + mass; gstep.vect[6] = charge*TMath::Sqrt(gstep.getot*gstep.getot - mass*mass); gstep.vect[0] = vout[0]; gstep.vect[1] = vout[1]; gstep.vect[2] = vout[2]; gstep.vect[3] = vout[3]; gstep.vect[4] = vout[4]; gstep.vect[5] = vout[5]; gstep.nmec = (Int_t)(5*gRandom->Rndm()); for (Int_t l=0;l<gstep.nmec;l++) gstep.lmec[l] = l; if (gstep.gekin < 0.001) newParticle = kTRUE; if (TMath::Abs(gstep.vect[2]) > 30) newParticle = kTRUE; } //save the Tree header. The file will be automatically closed //when going out of the function scope t2.Write(); } void tree2r() { //read the Tree generated by tree2w and fill one histogram //we are only interested by the destep branch. //note that we use "new" to create the TFile and TTree objects ! //because we want to keep these objects alive when we leave //this function. TFile *f = new TFile("tree2.root"); TTree *t2 = (TTree*)f->Get("t2"); static Float_t destep; TBranch *b_destep = t2->GetBranch("destep"); b_destep->SetAddress(&destep); //create one histogram TH1F *hdestep = new TH1F("hdestep","destep in Mev",100,1e-5,3e-5); //read only the destep branch for all entries Long64_t nentries = t2->GetEntries(); for (Long64_t i=0;i<nentries;i++) { b_destep->GetEntry(i); hdestep->Fill(destep); } //we do not close the file. //We want to keep the generated histograms //We fill a 3-d scatter plot with the particle step coordinates TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->SetFillColor(42); c1->Divide(1,2); c1->cd(1); hdestep->SetFillColor(45); hdestep->Fit("gaus"); c1->cd(2); gPad->SetFillColor(37); t2->SetMarkerColor(kRed); t2->Draw("vect[0]:vect[1]:vect[2]"); if (gROOT->IsBatch()) return; // invoke the x3d viewer gPad->GetViewer3D("x3d"); } void tree2() { tree2w(); tree2r(); } <commit_msg>Remove unused #includes.<commit_after>/// \file /// \ingroup tutorial_tree /// \notebook /// This example illustrates how to make a Tree from variables or arrays /// in a C struct - without a dictionary, by creating the branches for /// builtin types (int, float, double) and arrays explicitly. /// See tree2a.C for the same example using a class with dictionary /// instead of a C-struct. /// /// In this example, we are mapping a C struct to one of the Geant3 /// common blocks /gctrak/. In the real life, this common will be filled /// by Geant3 at each step and only the Tree Fill function should be called. /// The example emulates the Geant3 step routines. /// /// to run the example, do: /// ~~~ /// .x tree2.C to execute with the Cling interpreter /// .x tree2.C++ to execute with native compiler /// ~~~ /// \macro_code /// /// \author Rene Brun #include "TFile.h" #include "TTree.h" #include "TH2.h" #include "TRandom.h" #include "TCanvas.h" #include "TMath.h" const Int_t MAXMEC = 30; typedef struct { Float_t vect[7]; Float_t getot; Float_t gekin; Float_t vout[7]; Int_t nmec; Int_t lmec[MAXMEC]; Int_t namec[MAXMEC]; Int_t nstep; Int_t pid; Float_t destep; Float_t destel; Float_t safety; Float_t sleng; Float_t step; Float_t snext; Float_t sfield; Float_t tofg; Float_t gekrat; Float_t upwght; } Gctrak_t; void helixStep(Float_t step, Float_t *vect, Float_t *vout) { // extrapolate track in constant field Float_t field = 20; //magnetic field in kilogauss enum Evect {kX,kY,kZ,kPX,kPY,kPZ,kPP}; vout[kPP] = vect[kPP]; Float_t h4 = field*2.99792e-4; Float_t rho = -h4/vect[kPP]; Float_t tet = rho*step; Float_t tsint = tet*tet/6; Float_t sintt = 1 - tsint; Float_t sint = tet*sintt; Float_t cos1t = tet/2; Float_t f1 = step*sintt; Float_t f2 = step*cos1t; Float_t f3 = step*tsint*vect[kPZ]; Float_t f4 = -tet*cos1t; Float_t f5 = sint; Float_t f6 = tet*cos1t*vect[kPZ]; vout[kX] = vect[kX] + (f1*vect[kPX] - f2*vect[kPY]); vout[kY] = vect[kY] + (f1*vect[kPY] + f2*vect[kPX]); vout[kZ] = vect[kZ] + (f1*vect[kPZ] + f3); vout[kPX] = vect[kPX] + (f4*vect[kPX] - f5*vect[kPY]); vout[kPY] = vect[kPY] + (f4*vect[kPY] + f5*vect[kPX]); vout[kPZ] = vect[kPZ] + (f4*vect[kPZ] + f6); } void tree2w() { //create a Tree file tree2.root //create the file, the Tree and a few branches with //a subset of gctrak TFile f("tree2.root","recreate"); TTree t2("t2","a Tree with data from a fake Geant3"); Gctrak_t gstep; t2.Branch("vect",gstep.vect,"vect[7]/F"); t2.Branch("getot",&gstep.getot,"getot/F"); t2.Branch("gekin",&gstep.gekin,"gekin/F"); t2.Branch("nmec",&gstep.nmec,"nmec/I"); t2.Branch("lmec",gstep.lmec,"lmec[nmec]/I"); t2.Branch("destep",&gstep.destep,"destep/F"); t2.Branch("pid",&gstep.pid,"pid/I"); //Initialize particle parameters at first point Float_t px,py,pz,p,charge=0; Float_t vout[7]; Float_t mass = 0.137; Bool_t newParticle = kTRUE; gstep.step = 0.1; gstep.destep = 0; gstep.nmec = 0; gstep.pid = 0; //transport particles for (Int_t i=0;i<10000;i++) { //generate a new particle if necessary if (newParticle) { px = gRandom->Gaus(0,.02); py = gRandom->Gaus(0,.02); pz = gRandom->Gaus(0,.02); p = TMath::Sqrt(px*px+py*py+pz*pz); charge = 1; if (gRandom->Rndm() < 0.5) charge = -1; gstep.pid += 1; gstep.vect[0] = 0; gstep.vect[1] = 0; gstep.vect[2] = 0; gstep.vect[3] = px/p; gstep.vect[4] = py/p; gstep.vect[5] = pz/p; gstep.vect[6] = p*charge; gstep.getot = TMath::Sqrt(p*p + mass*mass); gstep.gekin = gstep.getot - mass; newParticle = kFALSE; } // fill the Tree with current step parameters t2.Fill(); //transport particle in magnetic field helixStep(gstep.step, gstep.vect, vout); //make one step //apply energy loss gstep.destep = gstep.step*gRandom->Gaus(0.0002,0.00001); gstep.gekin -= gstep.destep; gstep.getot = gstep.gekin + mass; gstep.vect[6] = charge*TMath::Sqrt(gstep.getot*gstep.getot - mass*mass); gstep.vect[0] = vout[0]; gstep.vect[1] = vout[1]; gstep.vect[2] = vout[2]; gstep.vect[3] = vout[3]; gstep.vect[4] = vout[4]; gstep.vect[5] = vout[5]; gstep.nmec = (Int_t)(5*gRandom->Rndm()); for (Int_t l=0;l<gstep.nmec;l++) gstep.lmec[l] = l; if (gstep.gekin < 0.001) newParticle = kTRUE; if (TMath::Abs(gstep.vect[2]) > 30) newParticle = kTRUE; } //save the Tree header. The file will be automatically closed //when going out of the function scope t2.Write(); } void tree2r() { //read the Tree generated by tree2w and fill one histogram //we are only interested by the destep branch. //note that we use "new" to create the TFile and TTree objects ! //because we want to keep these objects alive when we leave //this function. TFile *f = new TFile("tree2.root"); TTree *t2 = (TTree*)f->Get("t2"); static Float_t destep; TBranch *b_destep = t2->GetBranch("destep"); b_destep->SetAddress(&destep); //create one histogram TH1F *hdestep = new TH1F("hdestep","destep in Mev",100,1e-5,3e-5); //read only the destep branch for all entries Long64_t nentries = t2->GetEntries(); for (Long64_t i=0;i<nentries;i++) { b_destep->GetEntry(i); hdestep->Fill(destep); } //we do not close the file. //We want to keep the generated histograms //We fill a 3-d scatter plot with the particle step coordinates TCanvas *c1 = new TCanvas("c1","c1",600,800); c1->SetFillColor(42); c1->Divide(1,2); c1->cd(1); hdestep->SetFillColor(45); hdestep->Fit("gaus"); c1->cd(2); gPad->SetFillColor(37); t2->SetMarkerColor(kRed); t2->Draw("vect[0]:vect[1]:vect[2]"); if (gROOT->IsBatch()) return; // invoke the x3d viewer gPad->GetViewer3D("x3d"); } void tree2() { tree2w(); tree2r(); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_manager.h" #include <string> #include "base/command_line.h" #include "chrome/browser/autofill/autofill_dialog.h" #include "chrome/browser/autofill/autofill_infobar_delegate.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "webkit/glue/form_data.h" #include "webkit/glue/form_field.h" #include "webkit/glue/form_field_values.h" AutoFillManager::AutoFillManager(TabContents* tab_contents) : tab_contents_(tab_contents), personal_data_(NULL), infobar_(NULL) { DCHECK(tab_contents); personal_data_ = tab_contents_->profile()->GetPersonalDataManager(); } AutoFillManager::~AutoFillManager() { if (personal_data_) personal_data_->RemoveObserver(this); } // static void AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) { prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement); } // static void AutoFillManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false); prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, false); } void AutoFillManager::FormFieldValuesSubmitted( const webkit_glue::FormFieldValues& form) { if (!personal_data_) return; // Grab a copy of the form data. upload_form_structure_.reset(new FormStructure(form)); if (!upload_form_structure_->IsAutoFillable()) return; // Determine the possible field types. DeterminePossibleFieldTypes(upload_form_structure_.get()); PrefService* prefs = tab_contents_->profile()->GetPrefs(); bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown); if (!infobar_shown) { // Ask the user for permission to save form information. infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this)); } else if (IsAutoFillEnabled()) { HandleSubmit(); } } void AutoFillManager::FormsSeen( const std::vector<webkit_glue::FormFieldValues>& forms) { if (!IsAutoFillEnabled()) return; form_structures_.reset(); for (std::vector<webkit_glue::FormFieldValues>::const_iterator iter = forms.begin(); iter != forms.end(); ++iter) { FormStructure* form_structure = new FormStructure(*iter); DeterminePossibleFieldTypes(form_structure); form_structures_.push_back(form_structure); } } bool AutoFillManager::GetAutoFillSuggestions( int query_id, const webkit_glue::FormField& field) { if (!IsAutoFillEnabled()) return false; RenderViewHost* host = tab_contents_->render_view_host(); if (!host) return false; const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles(); if (profiles.empty()) return false; AutoFillFieldType type = UNKNOWN_TYPE; for (std::vector<FormStructure*>::iterator form = form_structures_.begin(); form != form_structures_.end(); ++form) { for (std::vector<AutoFillField*>::const_iterator iter = (*form)->begin(); iter != (*form)->end(); ++iter) { // The field list is terminated with a NULL AutoFillField, so don't try to // dereference it. if (!*iter) break; AutoFillField* form_field = *iter; if (*form_field != field) continue; if (form_field->possible_types().find(NAME_FIRST) != form_field->possible_types().end() || form_field->heuristic_type() == NAME_FIRST) { type = NAME_FIRST; break; } if (form_field->possible_types().find(NAME_FULL) != form_field->possible_types().end() || form_field->heuristic_type() == NAME_FULL) { type = NAME_FULL; break; } } } if (type == UNKNOWN_TYPE) return false; std::vector<string16> names; std::vector<string16> labels; for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin(); iter != profiles.end(); ++iter) { string16 name = (*iter)->GetFieldText(AutoFillType(type)); string16 label = (*iter)->Label(); // TODO(jhawkins): What if name.length() == 0? if (StartsWith(name, field.value(), false)) { names.push_back(name); labels.push_back(label); } } // No suggestions. if (names.empty()) return false; // TODO(jhawkins): If the default profile is in this list, set it as the // default suggestion index. host->AutoFillSuggestionsReturned(query_id, names, labels, -1); return true; } bool AutoFillManager::FillAutoFillFormData(int query_id, const FormData& form, const string16& name, const string16& label) { if (!IsAutoFillEnabled()) return false; RenderViewHost* host = tab_contents_->render_view_host(); if (!host) return false; const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles(); if (profiles.empty()) return false; const AutoFillProfile* profile = NULL; for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin(); iter != profiles.end(); ++iter) { if ((*iter)->Label() != label) continue; if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name && (*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name) continue; profile = *iter; break; } if (!profile) return false; FormData result = form; for (std::vector<FormStructure*>::const_iterator iter = form_structures_.begin(); iter != form_structures_.end(); ++iter) { const FormStructure* form_structure = *iter; if (*form_structure != form) continue; for (size_t i = 0; i < form_structure->field_count(); ++i) { const AutoFillField* field = form_structure->field(i); for (size_t j = 0; j < result.values.size(); ++j) { if (field->name() == result.elements[j]) { result.values[j] = profile->GetFieldText(AutoFillType(field->heuristic_type())); break; } } } } host->AutoFillFormDataFilled(query_id, result); return true; } void AutoFillManager::OnAutoFillDialogApply( std::vector<AutoFillProfile>* profiles, std::vector<CreditCard>* credit_cards) { DCHECK(personal_data_); // Save the personal data. personal_data_->SetProfiles(profiles); personal_data_->SetCreditCards(credit_cards); HandleSubmit(); } void AutoFillManager::OnPersonalDataLoaded() { DCHECK(personal_data_); // We might have been alerted that the PersonalDataManager has loaded, so // remove ourselves as observer. personal_data_->RemoveObserver(this); ShowAutoFillDialog( this, personal_data_->profiles(), personal_data_->credit_cards()); } void AutoFillManager::OnInfoBarAccepted() { DCHECK(personal_data_); PrefService* prefs = tab_contents_->profile()->GetPrefs(); prefs->SetBoolean(prefs::kAutoFillEnabled, true); // If the personal data manager has not loaded the data yet, set ourselves as // its observer so that we can listen for the OnPersonalDataLoaded signal. if (!personal_data_->IsDataLoaded()) personal_data_->SetObserver(this); else OnPersonalDataLoaded(); } void AutoFillManager::Reset() { upload_form_structure_.reset(); } void AutoFillManager::DeterminePossibleFieldTypes( FormStructure* form_structure) { DCHECK(personal_data_); // TODO(jhawkins): Update field text. form_structure->GetHeuristicAutoFillTypes(); for (size_t i = 0; i < form_structure->field_count(); i++) { const AutoFillField* field = form_structure->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); form_structure->set_possible_types(i, field_types); } } void AutoFillManager::HandleSubmit() { DCHECK(personal_data_); // If there wasn't enough data to import then we don't want to send an upload // to the server. if (!personal_data_->ImportFormData(form_structures_.get(), this)) return; UploadFormData(); } void AutoFillManager::UploadFormData() { std::string xml; bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml); DCHECK(ok); // TODO(jhawkins): Initiate the upload request thread. } bool AutoFillManager::IsAutoFillEnabled() { // The PersonalDataManager is NULL in OTR. if (!personal_data_) return false; PrefService* prefs = tab_contents_->profile()->GetPrefs(); // Migrate obsolete autofill pref. if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) { bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled); prefs->ClearPref(prefs::kFormAutofillEnabled); prefs->SetBoolean(prefs::kAutoFillEnabled, enabled); return enabled; } return prefs->GetBoolean(prefs::kAutoFillEnabled); } <commit_msg>Enable AutoFill++ by default for new profiles.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/autofill/autofill_manager.h" #include <string> #include "base/command_line.h" #include "chrome/browser/autofill/autofill_dialog.h" #include "chrome/browser/autofill/autofill_infobar_delegate.h" #include "chrome/browser/autofill/form_structure.h" #include "chrome/browser/pref_service.h" #include "chrome/browser/profile.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "webkit/glue/form_data.h" #include "webkit/glue/form_field.h" #include "webkit/glue/form_field_values.h" AutoFillManager::AutoFillManager(TabContents* tab_contents) : tab_contents_(tab_contents), personal_data_(NULL), infobar_(NULL) { DCHECK(tab_contents); personal_data_ = tab_contents_->profile()->GetPersonalDataManager(); } AutoFillManager::~AutoFillManager() { if (personal_data_) personal_data_->RemoveObserver(this); } // static void AutoFillManager::RegisterBrowserPrefs(PrefService* prefs) { prefs->RegisterDictionaryPref(prefs::kAutoFillDialogPlacement); } // static void AutoFillManager::RegisterUserPrefs(PrefService* prefs) { prefs->RegisterBooleanPref(prefs::kAutoFillInfoBarShown, false); prefs->RegisterBooleanPref(prefs::kAutoFillEnabled, true); } void AutoFillManager::FormFieldValuesSubmitted( const webkit_glue::FormFieldValues& form) { if (!personal_data_) return; // Grab a copy of the form data. upload_form_structure_.reset(new FormStructure(form)); if (!upload_form_structure_->IsAutoFillable()) return; // Determine the possible field types. DeterminePossibleFieldTypes(upload_form_structure_.get()); PrefService* prefs = tab_contents_->profile()->GetPrefs(); bool infobar_shown = prefs->GetBoolean(prefs::kAutoFillInfoBarShown); if (!infobar_shown) { // Ask the user for permission to save form information. infobar_.reset(new AutoFillInfoBarDelegate(tab_contents_, this)); } else if (IsAutoFillEnabled()) { HandleSubmit(); } } void AutoFillManager::FormsSeen( const std::vector<webkit_glue::FormFieldValues>& forms) { if (!IsAutoFillEnabled()) return; form_structures_.reset(); for (std::vector<webkit_glue::FormFieldValues>::const_iterator iter = forms.begin(); iter != forms.end(); ++iter) { FormStructure* form_structure = new FormStructure(*iter); DeterminePossibleFieldTypes(form_structure); form_structures_.push_back(form_structure); } } bool AutoFillManager::GetAutoFillSuggestions( int query_id, const webkit_glue::FormField& field) { if (!IsAutoFillEnabled()) return false; RenderViewHost* host = tab_contents_->render_view_host(); if (!host) return false; const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles(); if (profiles.empty()) return false; AutoFillFieldType type = UNKNOWN_TYPE; for (std::vector<FormStructure*>::iterator form = form_structures_.begin(); form != form_structures_.end(); ++form) { for (std::vector<AutoFillField*>::const_iterator iter = (*form)->begin(); iter != (*form)->end(); ++iter) { // The field list is terminated with a NULL AutoFillField, so don't try to // dereference it. if (!*iter) break; AutoFillField* form_field = *iter; if (*form_field != field) continue; if (form_field->possible_types().find(NAME_FIRST) != form_field->possible_types().end() || form_field->heuristic_type() == NAME_FIRST) { type = NAME_FIRST; break; } if (form_field->possible_types().find(NAME_FULL) != form_field->possible_types().end() || form_field->heuristic_type() == NAME_FULL) { type = NAME_FULL; break; } } } if (type == UNKNOWN_TYPE) return false; std::vector<string16> names; std::vector<string16> labels; for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin(); iter != profiles.end(); ++iter) { string16 name = (*iter)->GetFieldText(AutoFillType(type)); string16 label = (*iter)->Label(); // TODO(jhawkins): What if name.length() == 0? if (StartsWith(name, field.value(), false)) { names.push_back(name); labels.push_back(label); } } // No suggestions. if (names.empty()) return false; // TODO(jhawkins): If the default profile is in this list, set it as the // default suggestion index. host->AutoFillSuggestionsReturned(query_id, names, labels, -1); return true; } bool AutoFillManager::FillAutoFillFormData(int query_id, const FormData& form, const string16& name, const string16& label) { if (!IsAutoFillEnabled()) return false; RenderViewHost* host = tab_contents_->render_view_host(); if (!host) return false; const std::vector<AutoFillProfile*>& profiles = personal_data_->profiles(); if (profiles.empty()) return false; const AutoFillProfile* profile = NULL; for (std::vector<AutoFillProfile*>::const_iterator iter = profiles.begin(); iter != profiles.end(); ++iter) { if ((*iter)->Label() != label) continue; if ((*iter)->GetFieldText(AutoFillType(NAME_FIRST)) != name && (*iter)->GetFieldText(AutoFillType(NAME_FULL)) != name) continue; profile = *iter; break; } if (!profile) return false; FormData result = form; for (std::vector<FormStructure*>::const_iterator iter = form_structures_.begin(); iter != form_structures_.end(); ++iter) { const FormStructure* form_structure = *iter; if (*form_structure != form) continue; for (size_t i = 0; i < form_structure->field_count(); ++i) { const AutoFillField* field = form_structure->field(i); for (size_t j = 0; j < result.values.size(); ++j) { if (field->name() == result.elements[j]) { result.values[j] = profile->GetFieldText(AutoFillType(field->heuristic_type())); break; } } } } host->AutoFillFormDataFilled(query_id, result); return true; } void AutoFillManager::OnAutoFillDialogApply( std::vector<AutoFillProfile>* profiles, std::vector<CreditCard>* credit_cards) { DCHECK(personal_data_); // Save the personal data. personal_data_->SetProfiles(profiles); personal_data_->SetCreditCards(credit_cards); HandleSubmit(); } void AutoFillManager::OnPersonalDataLoaded() { DCHECK(personal_data_); // We might have been alerted that the PersonalDataManager has loaded, so // remove ourselves as observer. personal_data_->RemoveObserver(this); ShowAutoFillDialog( this, personal_data_->profiles(), personal_data_->credit_cards()); } void AutoFillManager::OnInfoBarAccepted() { DCHECK(personal_data_); PrefService* prefs = tab_contents_->profile()->GetPrefs(); prefs->SetBoolean(prefs::kAutoFillEnabled, true); // If the personal data manager has not loaded the data yet, set ourselves as // its observer so that we can listen for the OnPersonalDataLoaded signal. if (!personal_data_->IsDataLoaded()) personal_data_->SetObserver(this); else OnPersonalDataLoaded(); } void AutoFillManager::Reset() { upload_form_structure_.reset(); } void AutoFillManager::DeterminePossibleFieldTypes( FormStructure* form_structure) { DCHECK(personal_data_); // TODO(jhawkins): Update field text. form_structure->GetHeuristicAutoFillTypes(); for (size_t i = 0; i < form_structure->field_count(); i++) { const AutoFillField* field = form_structure->field(i); FieldTypeSet field_types; personal_data_->GetPossibleFieldTypes(field->value(), &field_types); form_structure->set_possible_types(i, field_types); } } void AutoFillManager::HandleSubmit() { DCHECK(personal_data_); // If there wasn't enough data to import then we don't want to send an upload // to the server. if (!personal_data_->ImportFormData(form_structures_.get(), this)) return; UploadFormData(); } void AutoFillManager::UploadFormData() { std::string xml; bool ok = upload_form_structure_->EncodeUploadRequest(false, &xml); DCHECK(ok); // TODO(jhawkins): Initiate the upload request thread. } bool AutoFillManager::IsAutoFillEnabled() { // The PersonalDataManager is NULL in OTR. if (!personal_data_) return false; PrefService* prefs = tab_contents_->profile()->GetPrefs(); // Migrate obsolete autofill pref. if (prefs->HasPrefPath(prefs::kFormAutofillEnabled)) { bool enabled = prefs->GetBoolean(prefs::kFormAutofillEnabled); prefs->ClearPref(prefs::kFormAutofillEnabled); prefs->SetBoolean(prefs::kAutoFillEnabled, enabled); return enabled; } return prefs->GetBoolean(prefs::kAutoFillEnabled); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/download/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(sleep_timeout_ms()); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); int64 client_file_size = 0; int64 server_file_size = 0; EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size)); EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size)); EXPECT_EQ(client_file_size, server_file_size); EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name)); } EXPECT_TRUE(DieFileDie(client_file, false)); } virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += FilePath::kSeparators[0]; download_dir_ = GetDownloadDirectory(); download_dir_ += FilePath::kSeparators[0]; } virtual void TearDown() { UITest::TearDown(); DieFileDie(save_dir_, true); } std::wstring save_dir_; std::wstring download_dir_; }; TEST_F(SavePageTest, SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } TEST_F(SavePageTest, FilenameFromPageTitle) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = download_dir_ + L"Test page for saving page feature.htm"; std::wstring dir = download_dir_ + L"Test page for saving page feature_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } // BUG 6514 TEST_F(SavePageTest, DISABLED_CleanFilenameFromPageTitle) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = download_dir_ + L"test.htm"; std::wstring dir = download_dir_ + L"test_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } <commit_msg>re-enable savepage ui test<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/string_util.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/browser/automation/url_request_mock_http_job.h" #include "chrome/browser/download/save_package.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/url_request/url_request_unittest.h" const std::wstring kTestDir = L"save_page"; class SavePageTest : public UITest { protected: SavePageTest() : UITest() {} void CheckFile(const std::wstring& client_file, const std::wstring& server_file, bool check_equal) { bool exist = false; for (int i = 0; i < 20; ++i) { if (file_util::PathExists(client_file)) { exist = true; break; } Sleep(sleep_timeout_ms()); } EXPECT_TRUE(exist); if (check_equal) { std::wstring server_file_name; ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &server_file_name)); server_file_name += L"\\" + kTestDir + L"\\" + server_file; ASSERT_TRUE(file_util::PathExists(server_file_name)); int64 client_file_size = 0; int64 server_file_size = 0; EXPECT_TRUE(file_util::GetFileSize(client_file, &client_file_size)); EXPECT_TRUE(file_util::GetFileSize(server_file_name, &server_file_size)); EXPECT_EQ(client_file_size, server_file_size); EXPECT_TRUE(file_util::ContentsEqual(client_file, server_file_name)); } EXPECT_TRUE(DieFileDie(client_file, false)); } virtual void SetUp() { UITest::SetUp(); EXPECT_TRUE(file_util::CreateNewTempDirectory(L"", &save_dir_)); save_dir_ += FilePath::kSeparators[0]; download_dir_ = GetDownloadDirectory(); download_dir_ += FilePath::kSeparators[0]; } virtual void TearDown() { UITest::TearDown(); DieFileDie(save_dir_, true); } std::wstring save_dir_; std::wstring download_dir_; }; TEST_F(SavePageTest, SaveHTMLOnly) { std::wstring file_name = L"a.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"a_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(full_file_name, file_name, true); EXPECT_FALSE(file_util::PathExists(dir)); } TEST_F(SavePageTest, SaveCompleteHTML) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"b_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); EXPECT_TRUE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_COMPLETE_HTML)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, NoSave) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = save_dir_ + file_name; std::wstring dir = save_dir_ + L"c_files"; scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(GURL(L"about:blank"))); WaitUntilTabCount(1); EXPECT_FALSE(tab->SavePage(full_file_name, dir, SavePackage::SAVE_AS_ONLY_HTML)); EXPECT_FALSE(WaitForDownloadShelfVisible(tab.get())); } TEST_F(SavePageTest, FilenameFromPageTitle) { std::wstring file_name = L"b.htm"; std::wstring full_file_name = download_dir_ + L"Test page for saving page feature.htm"; std::wstring dir = download_dir_ + L"Test page for saving page feature_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(dir + L"\\1.png", L"1.png", true); CheckFile(dir + L"\\1.css", L"1.css", true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } TEST_F(SavePageTest, CleanFilenameFromPageTitle) { std::wstring file_name = L"c.htm"; std::wstring full_file_name = download_dir_ + L"test.htm"; std::wstring dir = download_dir_ + L"test_files"; GURL url = URLRequestMockHTTPJob::GetMockUrl(kTestDir + L"/" + file_name); scoped_ptr<TabProxy> tab(GetActiveTab()); ASSERT_TRUE(tab->NavigateToURL(url)); WaitUntilTabCount(1); scoped_ptr<BrowserProxy> browser(automation()->GetBrowserWindow(0)); automation()->SavePackageShouldPromptUser(false); EXPECT_TRUE(browser->RunCommand(IDC_SAVE_PAGE)); EXPECT_TRUE(WaitForDownloadShelfVisible(tab.get())); automation()->SavePackageShouldPromptUser(true); CheckFile(full_file_name, file_name, false); EXPECT_TRUE(DieFileDie(full_file_name, false)); EXPECT_TRUE(DieFileDie(dir, true)); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_view.h" #include "chrome/browser/extensions/extension.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/resource_bundle.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" ExtensionView::ExtensionView( Extension* extension, const GURL& url, Profile* profile) : HWNDHtmlView(url, this, false), extension_(extension), profile_(profile) { // TODO(mpcomplete): query this from the renderer somehow? set_preferred_size(gfx::Size(100, 100)); } void ExtensionView::CreatingRenderer() { render_view_host()->AllowExtensionBindings(); } void ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) { ExtensionMessageService::GetInstance()->RegisterExtensionView(this); } WebPreferences ExtensionView::GetWebkitPrefs() { // TODO(mpcomplete): return some reasonable prefs. return WebPreferences(); } void ExtensionView::RunJavaScriptMessage( const std::wstring& message, const std::wstring& default_prompt, const GURL& frame_url, const int flags, IPC::Message* reply_msg, bool* did_suppress_message) { // Automatically cancel the javascript alert (otherwise the renderer hangs // indefinitely). *did_suppress_message = true; render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L""); } void ExtensionView::DidStartLoading(RenderViewHost* render_view_host, int32 page_id) { static const StringPiece toolstrip_css( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_EXTENSIONS_TOOLSTRIP_CSS)); render_view_host->InsertCSSInWebFrame(L"", toolstrip_css.as_string()); } <commit_msg>OCD fixing of style for the initializer list of ExtensionView. Review URL: http://codereview.chromium.org/56113<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/extensions/extension_view.h" #include "chrome/browser/extensions/extension.h" #include "chrome/browser/extensions/extension_message_service.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/common/resource_bundle.h" #include "grit/browser_resources.h" #include "grit/generated_resources.h" ExtensionView::ExtensionView(Extension* extension, const GURL& url, Profile* profile) : HWNDHtmlView(url, this, false), extension_(extension), profile_(profile) { // TODO(mpcomplete): query this from the renderer somehow? set_preferred_size(gfx::Size(100, 100)); } void ExtensionView::CreatingRenderer() { render_view_host()->AllowExtensionBindings(); } void ExtensionView::RenderViewCreated(RenderViewHost* render_view_host) { ExtensionMessageService::GetInstance()->RegisterExtensionView(this); } WebPreferences ExtensionView::GetWebkitPrefs() { // TODO(mpcomplete): return some reasonable prefs. return WebPreferences(); } void ExtensionView::RunJavaScriptMessage( const std::wstring& message, const std::wstring& default_prompt, const GURL& frame_url, const int flags, IPC::Message* reply_msg, bool* did_suppress_message) { // Automatically cancel the javascript alert (otherwise the renderer hangs // indefinitely). *did_suppress_message = true; render_view_host()->JavaScriptMessageBoxClosed(reply_msg, true, L""); } void ExtensionView::DidStartLoading(RenderViewHost* render_view_host, int32 page_id) { static const StringPiece toolstrip_css( ResourceBundle::GetSharedInstance().GetRawDataResource( IDR_EXTENSIONS_TOOLSTRIP_CSS)); render_view_host->InsertCSSInWebFrame(L"", toolstrip_css.as_string()); } <|endoftext|>
<commit_before>#include <ruby.h> #include <re2/re2.h> VALUE re2_mRE2; VALUE FullMatch(VALUE self, VALUE text, VALUE re) { if (RE2::FullMatch(StringValuePtr(text), StringValuePtr(re))) { return Qtrue; } else { return Qfalse; } } VALUE PartialMatch(VALUE self, VALUE text, VALUE re) { if (RE2::PartialMatch(StringValuePtr(text), StringValuePtr(re))) { return Qtrue; } else { return Qfalse; } } extern "C" void Init_re2() { re2_mRE2 = rb_define_module("RE2"); rb_define_singleton_method(re2_mRE2, "FullMatch", (VALUE (*)(...))FullMatch, 2); rb_define_singleton_method(re2_mRE2, "PartialMatch", (VALUE (*)(...))PartialMatch, 2); } <commit_msg>Module functions, not singleton methods.<commit_after>#include <ruby.h> #include <re2/re2.h> VALUE re2_mRE2; VALUE FullMatch(VALUE self, VALUE text, VALUE re) { if (RE2::FullMatch(StringValuePtr(text), StringValuePtr(re))) { return Qtrue; } else { return Qfalse; } } VALUE PartialMatch(VALUE self, VALUE text, VALUE re) { if (RE2::PartialMatch(StringValuePtr(text), StringValuePtr(re))) { return Qtrue; } else { return Qfalse; } } extern "C" void Init_re2() { re2_mRE2 = rb_define_module("RE2"); rb_define_module_function(re2_mRE2, "FullMatch", (VALUE (*)(...))FullMatch, 2); rb_define_module_function(re2_mRE2, "PartialMatch", (VALUE (*)(...))PartialMatch, 2); } <|endoftext|>
<commit_before>// Copyright 2013-2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // PKCS#11 s11.15: Random number generation functions // C_SeedRandom // C_GenerateRandom #include <cstdlib> #include "pkcs11test.h" using namespace std; // So sue me namespace pkcs11 { namespace test { TEST_F(ReadOnlySessionTest, SeedRandom) { // Additional seed data. Not actually particularly random. CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; if (g_token_flags & CKF_RNG) { EXPECT_CKR_OK(g_fns->C_SeedRandom(session_, seed, sizeof(seed))); } else { EXPECT_CKR(CKR_RANDOM_NO_RNG, g_fns->C_SeedRandom(session_, seed, sizeof(seed))); } } TEST(RNG, SeedRandomNoInit) { CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; EXPECT_CKR(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_SeedRandom(INVALID_SLOT_ID, seed, sizeof(seed))); } TEST_F(ReadOnlySessionTest, SeedRandomBadArguments) { EXPECT_CKR(CKR_ARGUMENTS_BAD, g_fns->C_SeedRandom(session_, nullptr, 1)); } TEST_F(PKCS11Test, SeedRandomNoSession) { CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; EXPECT_CKR(CKR_SESSION_HANDLE_INVALID, g_fns->C_SeedRandom(INVALID_SLOT_ID, seed, sizeof(seed))); } TEST_F(ReadOnlySessionTest, GenerateRandom) { CK_BYTE data[16]; if (g_token_flags & CKF_RNG) { EXPECT_CKR_OK(g_fns->C_GenerateRandom(session_, data, sizeof(data))); } else { EXPECT_CKR(CKR_RANDOM_NO_RNG, g_fns->C_GenerateRandom(session_, data, sizeof(data))); } } TEST(RNG, GenerateRandomNoInit) { CK_BYTE data[8]; EXPECT_CKR(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_SeedRandom(INVALID_SLOT_ID, data, sizeof(data))); } TEST_F(ReadOnlySessionTest, GenerateRandomBadArguments) { EXPECT_CKR(CKR_ARGUMENTS_BAD, g_fns->C_GenerateRandom(session_, nullptr, 1)); } TEST_F(PKCS11Test, GenerateRandomNoSession) { CK_BYTE data[16]; EXPECT_CKR(CKR_SESSION_HANDLE_INVALID, g_fns->C_GenerateRandom(INVALID_SLOT_ID, data, sizeof(data))); } } // namespace test } // namespace pkcs11 <commit_msg>Add a couple more random number tests<commit_after>// Copyright 2013-2014 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // PKCS#11 s11.15: Random number generation functions // C_SeedRandom // C_GenerateRandom #include <cstdlib> #include "pkcs11test.h" using namespace std; // So sue me namespace pkcs11 { namespace test { TEST_F(ReadOnlySessionTest, SeedRandom) { // Additional seed data. Not actually particularly random. CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; if (g_token_flags & CKF_RNG) { EXPECT_CKR_OK(g_fns->C_SeedRandom(session_, seed, sizeof(seed))); } else { EXPECT_CKR(CKR_RANDOM_NO_RNG, g_fns->C_SeedRandom(session_, seed, sizeof(seed))); } } TEST(RNG, SeedRandomNoInit) { CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; EXPECT_CKR(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_SeedRandom(INVALID_SLOT_ID, seed, sizeof(seed))); } TEST_F(ReadOnlySessionTest, SeedRandomBadArguments) { EXPECT_CKR(CKR_ARGUMENTS_BAD, g_fns->C_SeedRandom(session_, nullptr, 1)); } TEST_F(PKCS11Test, SeedRandomNoSession) { CK_BYTE seed[8] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; EXPECT_CKR(CKR_SESSION_HANDLE_INVALID, g_fns->C_SeedRandom(INVALID_SLOT_ID, seed, sizeof(seed))); } TEST_F(ReadOnlySessionTest, GenerateRandom) { CK_BYTE data[1024]; if (g_token_flags & CKF_RNG) { EXPECT_CKR_OK(g_fns->C_GenerateRandom(session_, data, sizeof(data))); EXPECT_CKR_OK(g_fns->C_GenerateRandom(session_, data, 10)); EXPECT_CKR_OK(g_fns->C_GenerateRandom(session_, data, 100)); CK_BYTE data2[100]; EXPECT_CKR_OK(g_fns->C_GenerateRandom(session_, data2, 100)); EXPECT_NE(0, memcmp(data, data2, 100)); } else { EXPECT_CKR(CKR_RANDOM_NO_RNG, g_fns->C_GenerateRandom(session_, data, sizeof(data))); } } TEST(RNG, GenerateRandomNoInit) { CK_BYTE data[8]; EXPECT_CKR(CKR_CRYPTOKI_NOT_INITIALIZED, g_fns->C_SeedRandom(INVALID_SLOT_ID, data, sizeof(data))); } TEST_F(ReadOnlySessionTest, GenerateRandomBadArguments) { EXPECT_CKR(CKR_ARGUMENTS_BAD, g_fns->C_GenerateRandom(session_, nullptr, 1)); } TEST_F(ReadOnlySessionTest, GenerateRandomNone) { CK_BYTE data[64]; if (g_token_flags & CKF_RNG) { CK_RV rv = g_fns->C_GenerateRandom(session_, data, 0); EXPECT_TRUE(rv == CKR_OK || rv == CKR_ARGUMENTS_BAD) << CK_RV_(rv); } } TEST_F(PKCS11Test, GenerateRandomNoSession) { CK_BYTE data[16]; EXPECT_CKR(CKR_SESSION_HANDLE_INVALID, g_fns->C_GenerateRandom(INVALID_SLOT_ID, data, sizeof(data))); } } // namespace test } // namespace pkcs11 <|endoftext|>
<commit_before>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> class LoggerPrivate { public: QSqlDatabase m_database; LoggerPrivate(); void initializeDatabase(); }; LoggerPrivate::LoggerPrivate() { m_database = QSqlDatabase::addDatabase( "QSQLITE" ); } void LoggerPrivate::initializeDatabase() { QSqlQuery createJobsTable( "CREATE TABLE IF NOT EXISTS jobs (id VARCHAR(255) PRIMARY KEY, name TEXT, status TEXT, description TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);" ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } } Logger::Logger(QObject *parent) : QObject(parent), d(new LoggerPrivate) { } Logger::~Logger() { delete d; } Logger &Logger::instance() { static Logger m_instance; return m_instance; } void Logger::setFilename(const QString &filename) { d->m_database.setDatabaseName( filename ); if ( !d->m_database.open() ) { qDebug() << "Failed to connect to database " << filename; } d->initializeDatabase(); } void Logger::setStatus(const QString &id, const QString &name, const QString &status, const QString &message) { QSqlQuery createJobsTable( QString("SELECT id FROM jobs WHERE id='%1';").arg(id) ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } else { if (!createJobsTable.next()) { QSqlQuery createStatus( QString("INSERT INTO jobs (id, name, status, description) VALUES ('%1', '%2', '%3', '%4');").arg(id).arg(name).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } else { QSqlQuery createStatus( QString("UPDATE jobs SET status='%2', description='%3' WHERE id='%1';").arg(id).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } } } <commit_msg>Update timestamps.<commit_after>// // This file is part of the Marble Virtual Globe. // // This program is free software licensed under the GNU LGPL. You can // find a copy of this license in LICENSE.txt in the top directory of // the source code. // // Copyright 2011 Dennis Nienhüser <earthwings@gentoo.org> // #include "logger.h" #include <QtCore/QDebug> #include <QtCore/QVariant> #include <QtSql/QSqlDatabase> #include <QtSql/QSqlQuery> #include <QtSql/QSqlError> class LoggerPrivate { public: QSqlDatabase m_database; LoggerPrivate(); void initializeDatabase(); }; LoggerPrivate::LoggerPrivate() { m_database = QSqlDatabase::addDatabase( "QSQLITE" ); } void LoggerPrivate::initializeDatabase() { QSqlQuery createJobsTable( "CREATE TABLE IF NOT EXISTS jobs (id VARCHAR(255) PRIMARY KEY, name TEXT, status TEXT, description TEXT, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP);" ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } } Logger::Logger(QObject *parent) : QObject(parent), d(new LoggerPrivate) { } Logger::~Logger() { delete d; } Logger &Logger::instance() { static Logger m_instance; return m_instance; } void Logger::setFilename(const QString &filename) { d->m_database.setDatabaseName( filename ); if ( !d->m_database.open() ) { qDebug() << "Failed to connect to database " << filename; } d->initializeDatabase(); } void Logger::setStatus(const QString &id, const QString &name, const QString &status, const QString &message) { QSqlQuery createJobsTable( QString("SELECT id FROM jobs WHERE id='%1';").arg(id) ); if ( createJobsTable.lastError().isValid() ) { qDebug() << "Error when executing query" << createJobsTable.lastQuery(); qDebug() << "Sql reports" << createJobsTable.lastError(); } else { if (!createJobsTable.next()) { QSqlQuery createStatus( QString("INSERT INTO jobs (id, name, status, description) VALUES ('%1', '%2', '%3', '%4');").arg(id).arg(name).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } else { QSqlQuery createStatus( QString("UPDATE jobs SET status='%2', description='%3', timestamp='CURRENT_TIMESTAMP' WHERE id='%1';").arg(id).arg(status).arg(message) ); if ( createStatus.lastError().isValid() ) { qDebug() << "Error when executing query" << createStatus.lastQuery(); qDebug() << "Sql reports" << createStatus.lastError(); } } } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <stdio.h> #include <QtCore> #include <QTextStream> #include <qservicemanager.h> #include <servicemetadata_p.h> #include <QString> #include <QDir> QT_USE_NAMESPACE QTM_USE_NAMESPACE class CommandProcessor : public QObject { Q_OBJECT public: CommandProcessor(QObject *parent = 0); ~CommandProcessor(); void execute(const QStringList &options, const QString &cmd, const QStringList &args); void showUsage(); static void showUsage(QTextStream *stream); int errorCode(); public slots: void browse(const QStringList &args); void search(const QStringList &args); void add(const QStringList &args); void remove(const QStringList &args); void dbusservice(const QStringList &args); private: bool setOptions(const QStringList &options); void setErrorCode(int error); void showAllEntries(); void showInterfaceInfo(const QServiceFilter &filter); void showInterfaceInfo(QList<QServiceInterfaceDescriptor> descriptors); void showServiceInfo(const QString &service); QServiceManager *serviceManager; QTextStream *stdoutStream; int m_error; }; CommandProcessor::CommandProcessor(QObject *parent) : QObject(parent), serviceManager(0), stdoutStream(new QTextStream(stdout)), m_error(0) { } CommandProcessor::~CommandProcessor() { delete stdoutStream; } void CommandProcessor::execute(const QStringList &options, const QString &cmd, const QStringList &args) { if (cmd.isEmpty()) { *stdoutStream << "Error: no command given\n\n"; showUsage(); return; } if (!setOptions(options)) return; int methodIndex = metaObject()->indexOfMethod(cmd.toAscii() + "(QStringList)"); if (methodIndex < 0) { *stdoutStream << "Bad command: " << cmd << "\n\n"; showUsage(); return; } if (!metaObject()->method(methodIndex).invoke(this, Q_ARG(QStringList, args))) *stdoutStream << "Cannot invoke method for command:" << cmd << '\n'; } void CommandProcessor::showUsage() { showUsage(stdoutStream); } void CommandProcessor::showUsage(QTextStream *stream) { *stream << "Usage: servicefw [options] <command> [command parameters]\n\n" "Commands:\n" "\tbrowse List all registered services\n" "\tsearch Search for a service or interface\n" "\tadd Register a service\n" "\tremove Unregister a service\n" "\tdbusservice Generates a .service file for D-Bus service autostart\n" "\n" "Options:\n" "\t--system Use the system-wide services database instead of the\n" "\t user-specific database\n" "\t--user Use the user-specific services database for add/remove.\n" "\t This is the default\n" "\n"; } void CommandProcessor::browse(const QStringList &args) { Q_UNUSED(args); showAllEntries(); } void CommandProcessor::search(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tsearch <service|interface [version]>\n\n" "Examples:\n" "\tsearch SomeService\n" "\tsearch com.nokia.SomeInterface\n" "\tsearch com.nokia.SomeInterface 3.5\n" "\tsearch com.nokia.SomeInterface 3.5+\n"; return; } const QString &name = args[0]; if (name.contains('.')) { QServiceFilter filter; if (args.count() > 1) { const QString &version = args[1]; bool minimumMatch = version.endsWith('+'); filter.setInterface(name, minimumMatch ? (version.mid(0, version.length()-1)) : version, minimumMatch ? QServiceFilter::MinimumVersionMatch : QServiceFilter::ExactVersionMatch); if (filter.interfaceName().isEmpty()) { // setInterface() failed *stdoutStream << "Error: invalid interface version: " << version << '\n'; return; } } else { filter.setInterface(name); } showInterfaceInfo(filter); } else { showServiceInfo(name); } } static const char * const errorTable[] = { "No error", //0 "Storage read error", "Invalid service location", "Invalid service xml", "Invalid service interface descriptor", "Service already exists", "Interface implementation already exists", "Loading of plug-in failed", "Service or interface not found", "Insufficient capabilities to access service", "Unknown error", }; void CommandProcessor::add(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tadd <service-xml-file>\n"; return; } const QString &xmlPath = args[0]; if (!QFile::exists(xmlPath)) { *stdoutStream << "Error: cannot find file " << xmlPath << '\n'; setErrorCode(11); return; } if (serviceManager->addService(xmlPath)) { *stdoutStream << "Registered service at " << xmlPath << '\n'; } else { int error = serviceManager->error(); if (error > 10) //map anything larger than 10 to 10 error = 10; *stdoutStream << "Error: cannot register service at " << xmlPath << " (" << errorTable[error] << ")" << '\n'; setErrorCode(error); } } void CommandProcessor::remove(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tremove <service-name>\n"; return; } const QString &service = args[0]; if (serviceManager->removeService(service)) *stdoutStream << "Unregistered service " << service << '\n'; else *stdoutStream << "Error: cannot unregister service " << service << '\n'; } void CommandProcessor::dbusservice(const QStringList &args) { if (args.isEmpty() || args.size() == 1) { *stdoutStream << "Usage:\n\tautostart <service-xml-file> <service-file>\n"; return; } #if defined(QT_NO_DBUS) *stdoutStream << "Error: no D-Bus module found in Qt\n"; return; #endif const QString &xmlPath = args[0]; if (!QFile::exists(xmlPath)) { *stdoutStream << "Error: cannot find xml file at " << xmlPath << '\n'; return; } const QString &servicePath = args[1]; if (!QFile::exists(servicePath)) { *stdoutStream << "Error: cannot find service file " << servicePath << '\n'; return; } QFile *f = new QFile(xmlPath); ServiceMetaData parser(f); if (!parser.extractMetadata()) { *stdoutStream << "Error: invalid service xml at " << xmlPath << '\n'; return; } const ServiceMetaDataResults results = parser.parseResults(); if (results.type != QService::InterProcess) { *stdoutStream << "Error: not an inter-process service xml at " << xmlPath << '\n'; return; } QString path; if (serviceManager->scope() == QService::UserScope) { // the d-bus xdg environment variable for the local service paths QString xdgPath = getenv("XDG_DATA_HOME"); if (xdgPath == "") { // if not supplied generate in default QDir dir(QDir::homePath()); dir.mkpath(".local/share/dbus-1/services/"); path = QDir::homePath() + "/.local/share/dbus-1/services/"; } else { path = xdgPath; } } else { path = "/usr/share/dbus-1/services/"; } const QString &name = "com.nokia.qtmobility.sfw." + results.name; const QString &exec = QFileInfo(args[1]).absoluteFilePath(); QStringList names; foreach (const QServiceInterfaceDescriptor &interface, results.interfaces) { names << interface.interfaceName(); } names.removeDuplicates(); for (int i = 0; i < names.size(); i++) { const QString &file = path + names.at(i) + ".service"; QFile data(file); if (data.open(QFile::WriteOnly)) { QTextStream out(&data); out << "[D-BUS Service]\n" << "Name=" << name << '\n' << "Exec=" << exec; data.close(); } else { *stdoutStream << "Error: cannot write to " << file << " (insufficient permissions)" << '\n'; return; } *stdoutStream << "Generated D-Bus autostart file " << file << '\n'; } } bool CommandProcessor::setOptions(const QStringList &options) { if (serviceManager) delete serviceManager; QService::Scope scope = QService::UserScope; QStringList opts = options; QMutableListIterator<QString> i(opts); while (i.hasNext()) { QString option = i.next(); if (option == "--system") { scope = QService::SystemScope; i.remove(); } else if (option == "--user") { scope = QService::UserScope; i.remove(); } } if (!opts.isEmpty()) { *stdoutStream << "Bad options: " << opts.join(" ") << "\n\n"; showUsage(); return false; } serviceManager = new QServiceManager(scope, this); return true; } void CommandProcessor::showAllEntries() { QStringList services = serviceManager->findServices(); if (services.isEmpty()) *stdoutStream << "No services found.\n"; else if (services.count() == 1) *stdoutStream << "Found 1 service.\n\n"; else *stdoutStream << "Found " << services.count() << " services.\n\n"; foreach (const QString &service, services) showServiceInfo(service); } void CommandProcessor::showInterfaceInfo(const QServiceFilter &filter) { QString interface = filter.interfaceName(); if (filter.majorVersion() >= 0 && filter.minorVersion() >= 0) { interface += QString(" %1.%2").arg(filter.majorVersion()).arg(filter.minorVersion()); if (filter.versionMatchRule() == QServiceFilter::MinimumVersionMatch) interface += '+'; } QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(filter); if (descriptors.isEmpty()) { *stdoutStream << "Interface " << interface << " not found.\n"; return; } *stdoutStream << interface << " is implemented by:\n"; foreach (const QServiceInterfaceDescriptor &desc, descriptors) *stdoutStream << '\t' << desc.serviceName() << '\n'; } void CommandProcessor::showServiceInfo(const QString &service) { QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(service); if (descriptors.isEmpty()) { *stdoutStream << "Service " << service << " not found.\n"; return; } QList<QServiceInterfaceDescriptor> pluginDesc; QList<QServiceInterfaceDescriptor> ipcDesc; foreach (const QServiceInterfaceDescriptor &desc, descriptors) { int serviceType = desc.attribute(QServiceInterfaceDescriptor::ServiceType).toInt(); if (serviceType == QService::Plugin) pluginDesc.append(desc); else ipcDesc.append(desc); } if (pluginDesc.size() > 0) { *stdoutStream << service; if (ipcDesc.size() > 0) *stdoutStream << " (Plugin):\n"; else *stdoutStream << ":\n"; QString description = pluginDesc[0].attribute( QServiceInterfaceDescriptor::ServiceDescription).toString(); if (!description.isEmpty()) *stdoutStream << '\t' << description << '\n'; *stdoutStream << "\tPlugin Library: "; showInterfaceInfo(pluginDesc); } if (ipcDesc.size() > 0) { *stdoutStream << service; if (pluginDesc.size() > 0) *stdoutStream << " (IPC):\n"; else *stdoutStream << ":\n"; QString description = ipcDesc[0].attribute( QServiceInterfaceDescriptor::ServiceDescription).toString(); if (!description.isEmpty()) *stdoutStream << '\t' << description << '\n'; *stdoutStream << "\tIPC Address: "; showInterfaceInfo(ipcDesc); } } void CommandProcessor::showInterfaceInfo(QList<QServiceInterfaceDescriptor> descriptors) { QService::Scope scope = descriptors[0].scope(); *stdoutStream << descriptors[0].attribute(QServiceInterfaceDescriptor::Location).toString() << '\n' << "\tScope: " << (scope == QService::SystemScope ? "All users" : "Current User") << '\n' << "\tImplements:\n"; foreach (const QServiceInterfaceDescriptor &desc, descriptors) { QStringList capabilities = desc.attribute( QServiceInterfaceDescriptor::Capabilities).toStringList(); *stdoutStream << "\t " << desc.interfaceName() << ' ' << desc.majorVersion() << '.' << desc.minorVersion() << (capabilities.isEmpty() ? "" : "\t{" + capabilities.join(", ") + "}") << "\n"; } } int CommandProcessor::errorCode() { return m_error; } void CommandProcessor::setErrorCode(int error) { m_error = error; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = QCoreApplication::arguments(); // check for at least one non-option argument bool exec = false; QStringList options; for (int i=1; i<args.count(); i++) { if (args[i].startsWith("--")) options += args[i]; else exec = true; } if (!exec || args.count() == 1 || args.value(1) == "--help" || args.value(1) == "-h") { QTextStream stream(stdout); CommandProcessor::showUsage(&stream); return 0; } CommandProcessor processor; processor.execute(options, args.value(options.count() + 1), args.mid(options.count() + 2)); return processor.errorCode(); } #include "servicefw.moc" <commit_msg>Fixed servicefw scope info<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Mobility Components. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <stdio.h> #include <QtCore> #include <QTextStream> #include <qservicemanager.h> #include <servicemetadata_p.h> #include <QString> #include <QDir> QT_USE_NAMESPACE QTM_USE_NAMESPACE class CommandProcessor : public QObject { Q_OBJECT public: CommandProcessor(QObject *parent = 0); ~CommandProcessor(); void execute(const QStringList &options, const QString &cmd, const QStringList &args); void showUsage(); static void showUsage(QTextStream *stream); int errorCode(); public slots: void browse(const QStringList &args); void search(const QStringList &args); void add(const QStringList &args); void remove(const QStringList &args); void dbusservice(const QStringList &args); private: bool setOptions(const QStringList &options); void setErrorCode(int error); void showAllEntries(); void showInterfaceInfo(const QServiceFilter &filter); void showInterfaceInfo(QList<QServiceInterfaceDescriptor> descriptors); void showServiceInfo(const QString &service); QServiceManager *serviceManager; QTextStream *stdoutStream; int m_error; }; CommandProcessor::CommandProcessor(QObject *parent) : QObject(parent), serviceManager(0), stdoutStream(new QTextStream(stdout)), m_error(0) { } CommandProcessor::~CommandProcessor() { delete stdoutStream; } void CommandProcessor::execute(const QStringList &options, const QString &cmd, const QStringList &args) { if (cmd.isEmpty()) { *stdoutStream << "Error: no command given\n\n"; showUsage(); return; } if (!setOptions(options)) return; int methodIndex = metaObject()->indexOfMethod(cmd.toAscii() + "(QStringList)"); if (methodIndex < 0) { *stdoutStream << "Bad command: " << cmd << "\n\n"; showUsage(); return; } if (!metaObject()->method(methodIndex).invoke(this, Q_ARG(QStringList, args))) *stdoutStream << "Cannot invoke method for command:" << cmd << '\n'; } void CommandProcessor::showUsage() { showUsage(stdoutStream); } void CommandProcessor::showUsage(QTextStream *stream) { *stream << "Usage: servicefw [options] <command> [command parameters]\n\n" "Commands:\n" "\tbrowse List all registered services\n" "\tsearch Search for a service or interface\n" "\tadd Register a service\n" "\tremove Unregister a service\n" "\tdbusservice Generates a .service file for D-Bus service autostart\n" "\n" "Options:\n" "\t--system Use the system-wide services database instead of the\n" "\t user-specific database\n" "\t--user Use the user-specific services database for add/remove.\n" "\t This is the default\n" "\n"; } void CommandProcessor::browse(const QStringList &args) { Q_UNUSED(args); showAllEntries(); } void CommandProcessor::search(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tsearch <service|interface [version]>\n\n" "Examples:\n" "\tsearch SomeService\n" "\tsearch com.nokia.SomeInterface\n" "\tsearch com.nokia.SomeInterface 3.5\n" "\tsearch com.nokia.SomeInterface 3.5+\n"; return; } const QString &name = args[0]; if (name.contains('.')) { QServiceFilter filter; if (args.count() > 1) { const QString &version = args[1]; bool minimumMatch = version.endsWith('+'); filter.setInterface(name, minimumMatch ? (version.mid(0, version.length()-1)) : version, minimumMatch ? QServiceFilter::MinimumVersionMatch : QServiceFilter::ExactVersionMatch); if (filter.interfaceName().isEmpty()) { // setInterface() failed *stdoutStream << "Error: invalid interface version: " << version << '\n'; return; } } else { filter.setInterface(name); } showInterfaceInfo(filter); } else { showServiceInfo(name); } } static const char * const errorTable[] = { "No error", //0 "Storage read error", "Invalid service location", "Invalid service xml", "Invalid service interface descriptor", "Service already exists", "Interface implementation already exists", "Loading of plug-in failed", "Service or interface not found", "Insufficient capabilities to access service", "Unknown error", }; void CommandProcessor::add(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tadd <service-xml-file>\n"; return; } const QString &xmlPath = args[0]; if (!QFile::exists(xmlPath)) { *stdoutStream << "Error: cannot find file " << xmlPath << '\n'; setErrorCode(11); return; } if (serviceManager->addService(xmlPath)) { *stdoutStream << "Registered service at " << xmlPath << '\n'; } else { int error = serviceManager->error(); if (error > 10) //map anything larger than 10 to 10 error = 10; *stdoutStream << "Error: cannot register service at " << xmlPath << " (" << errorTable[error] << ")" << '\n'; setErrorCode(error); } } void CommandProcessor::remove(const QStringList &args) { if (args.isEmpty()) { *stdoutStream << "Usage:\n\tremove <service-name>\n"; return; } const QString &service = args[0]; if (serviceManager->removeService(service)) *stdoutStream << "Unregistered service " << service << '\n'; else *stdoutStream << "Error: cannot unregister service " << service << '\n'; } void CommandProcessor::dbusservice(const QStringList &args) { if (args.isEmpty() || args.size() == 1) { *stdoutStream << "Usage:\n\tautostart <service-xml-file> <service-file>\n"; return; } #if defined(QT_NO_DBUS) *stdoutStream << "Error: no D-Bus module found in Qt\n"; return; #endif const QString &xmlPath = args[0]; if (!QFile::exists(xmlPath)) { *stdoutStream << "Error: cannot find xml file at " << xmlPath << '\n'; return; } const QString &servicePath = args[1]; if (!QFile::exists(servicePath)) { *stdoutStream << "Error: cannot find service file " << servicePath << '\n'; return; } QFile *f = new QFile(xmlPath); ServiceMetaData parser(f); if (!parser.extractMetadata()) { *stdoutStream << "Error: invalid service xml at " << xmlPath << '\n'; return; } const ServiceMetaDataResults results = parser.parseResults(); if (results.type != QService::InterProcess) { *stdoutStream << "Error: not an inter-process service xml at " << xmlPath << '\n'; return; } QString path; if (serviceManager->scope() == QService::UserScope) { // the d-bus xdg environment variable for the local service paths QString xdgPath = getenv("XDG_DATA_HOME"); if (xdgPath == "") { // if not supplied generate in default QDir dir(QDir::homePath()); dir.mkpath(".local/share/dbus-1/services/"); path = QDir::homePath() + "/.local/share/dbus-1/services/"; } else { path = xdgPath; } } else { path = "/usr/share/dbus-1/services/"; } const QString &name = "com.nokia.qtmobility.sfw." + results.name; const QString &exec = QFileInfo(args[1]).absoluteFilePath(); QStringList names; foreach (const QServiceInterfaceDescriptor &interface, results.interfaces) { names << interface.interfaceName(); } names.removeDuplicates(); for (int i = 0; i < names.size(); i++) { const QString &file = path + names.at(i) + ".service"; QFile data(file); if (data.open(QFile::WriteOnly)) { QTextStream out(&data); out << "[D-BUS Service]\n" << "Name=" << name << '\n' << "Exec=" << exec; data.close(); } else { *stdoutStream << "Error: cannot write to " << file << " (insufficient permissions)" << '\n'; return; } *stdoutStream << "Generated D-Bus autostart file " << file << '\n'; } } bool CommandProcessor::setOptions(const QStringList &options) { if (serviceManager) delete serviceManager; QService::Scope scope = QService::UserScope; QStringList opts = options; QMutableListIterator<QString> i(opts); while (i.hasNext()) { QString option = i.next(); if (option == "--system") { scope = QService::SystemScope; i.remove(); } else if (option == "--user") { scope = QService::UserScope; i.remove(); } } if (!opts.isEmpty()) { *stdoutStream << "Bad options: " << opts.join(" ") << "\n\n"; showUsage(); return false; } serviceManager = new QServiceManager(scope, this); return true; } void CommandProcessor::showAllEntries() { QStringList services = serviceManager->findServices(); if (services.isEmpty()) *stdoutStream << "No services found.\n"; else if (services.count() == 1) *stdoutStream << "Found 1 service.\n\n"; else *stdoutStream << "Found " << services.count() << " services.\n\n"; foreach (const QString &service, services) showServiceInfo(service); } void CommandProcessor::showInterfaceInfo(const QServiceFilter &filter) { QString interface = filter.interfaceName(); if (filter.majorVersion() >= 0 && filter.minorVersion() >= 0) { interface += QString(" %1.%2").arg(filter.majorVersion()).arg(filter.minorVersion()); if (filter.versionMatchRule() == QServiceFilter::MinimumVersionMatch) interface += '+'; } QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(filter); if (descriptors.isEmpty()) { *stdoutStream << "Interface " << interface << " not found.\n"; return; } *stdoutStream << interface << " is implemented by:\n"; foreach (const QServiceInterfaceDescriptor &desc, descriptors) *stdoutStream << '\t' << desc.serviceName() << '\n'; } void CommandProcessor::showServiceInfo(const QString &service) { QList<QServiceInterfaceDescriptor> descriptors = serviceManager->findInterfaces(service); if (descriptors.isEmpty()) { *stdoutStream << "Service " << service << " not found.\n"; return; } QList<QServiceInterfaceDescriptor> pluginDescs; QList<QServiceInterfaceDescriptor> ipcDescs; foreach (const QServiceInterfaceDescriptor &desc, descriptors) { int serviceType = desc.attribute(QServiceInterfaceDescriptor::ServiceType).toInt(); if (serviceType == QService::Plugin) pluginDescs.append(desc); else ipcDescs.append(desc); } if (pluginDescs.size() > 0) { *stdoutStream << service; if (ipcDescs.size() > 0) *stdoutStream << " (Plugin):\n"; else *stdoutStream << ":\n"; QString description = pluginDescs[0].attribute( QServiceInterfaceDescriptor::ServiceDescription).toString(); if (!description.isEmpty()) *stdoutStream << '\t' << description << '\n'; *stdoutStream << "\tPlugin Library: "; showInterfaceInfo(pluginDescs); } if (ipcDescs.size() > 0) { *stdoutStream << service; if (pluginDescs.size() > 0) *stdoutStream << " (IPC):\n"; else *stdoutStream << ":\n"; QString description = ipcDescs[0].attribute( QServiceInterfaceDescriptor::ServiceDescription).toString(); if (!description.isEmpty()) *stdoutStream << '\t' << description << '\n'; *stdoutStream << "\tIPC Address: "; showInterfaceInfo(ipcDescs); } } void CommandProcessor::showInterfaceInfo(QList<QServiceInterfaceDescriptor> descriptors) { QList<QServiceInterfaceDescriptor> systemList; QList<QServiceInterfaceDescriptor> userList; foreach (const QServiceInterfaceDescriptor &desc, descriptors) { if (desc.scope() == QService::SystemScope) systemList.append(desc); else userList.append(desc); } if (userList.size() > 0) { *stdoutStream << userList[0].attribute(QServiceInterfaceDescriptor::Location).toString() << '\n' << "\tUser Implements:\n"; foreach (const QServiceInterfaceDescriptor &desc, userList) { QStringList capabilities = desc.attribute( QServiceInterfaceDescriptor::Capabilities).toStringList(); *stdoutStream << "\t " << desc.interfaceName() << ' ' << desc.majorVersion() << '.' << desc.minorVersion() << (capabilities.isEmpty() ? "" : "\t{" + capabilities.join(", ") + "}") << "\n"; } } if (systemList.size() > 0) { if (userList.size() < 1) *stdoutStream << systemList[0].attribute(QServiceInterfaceDescriptor::Location).toString() << '\n'; *stdoutStream << "\tSystem Implements:\n"; foreach (const QServiceInterfaceDescriptor &desc, systemList) { QStringList capabilities = desc.attribute( QServiceInterfaceDescriptor::Capabilities).toStringList(); *stdoutStream << "\t " << desc.interfaceName() << ' ' << desc.majorVersion() << '.' << desc.minorVersion() << (capabilities.isEmpty() ? "" : "\t{" + capabilities.join(", ") + "}") << "\n"; } } } int CommandProcessor::errorCode() { return m_error; } void CommandProcessor::setErrorCode(int error) { m_error = error; } int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); QStringList args = QCoreApplication::arguments(); // check for at least one non-option argument bool exec = false; QStringList options; for (int i=1; i<args.count(); i++) { if (args[i].startsWith("--")) options += args[i]; else exec = true; } if (!exec || args.count() == 1 || args.value(1) == "--help" || args.value(1) == "-h") { QTextStream stream(stdout); CommandProcessor::showUsage(&stream); return 0; } CommandProcessor processor; processor.execute(options, args.value(options.count() + 1), args.mid(options.count() + 2)); return processor.errorCode(); } #include "servicefw.moc" <|endoftext|>
<commit_before><commit_msg>cppcheck: reduce scope of var in tools/ poly.cxx<commit_after><|endoftext|>
<commit_before>//===- tools/seec-view/SourceEditor/SourceEditor.cpp ----------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #include "seec/ICU/Resources.hpp" #include "seec/wxWidgets/StringConversion.hpp" #include "../ColourSchemeSettings.hpp" #include "../CommonMenus.hpp" #include "../LocaleSettings.hpp" #include "../SourceViewerSettings.hpp" #include "../TraceViewerApp.hpp" #include "SourceEditor.hpp" #include <wx/stc/stc.h> #include <wx/filedlg.h> #include <wx/filename.h> #include <wx/sizer.h> namespace { void setSTCPreferences(wxStyledTextCtrl &Text) { // Setup styles according to the user's colour scheme. auto &Scheme = *wxGetApp().getColourSchemeSettings().getColourScheme(); setupStylesFromColourScheme(Text, Scheme); // Set the lexer to C++. Text.SetLexer(wxSTC_LEX_CPP); // Setup the keywords used by Scintilla's C++ lexer. // TODO: this should be shared with SourceViewer UErrorCode Status = U_ZERO_ERROR; auto KeywordRes = seec::getResource("TraceViewer", getLocale(), Status, "ScintillaKeywords", "C"); if (U_SUCCESS(Status)) { auto Size = KeywordRes.getSize(); for (int32_t i = 0; i < Size; ++i) { auto UniStr = KeywordRes.getStringEx(i, Status); if (U_FAILURE(Status)) break; Text.SetKeyWords(i, seec::towxString(UniStr)); } } // Misc. settings. Text.SetExtraDescent(2); } } // anonymous namespace SourceEditorFrame::SourceEditorFrame() : m_ColourSchemeSettingsRegistration(), m_FileName(), m_Scintilla(nullptr) { if (!wxFrame::Create(nullptr, wxID_ANY, wxString())) return; m_Scintilla = new wxStyledTextCtrl(this); setSTCPreferences(*m_Scintilla); auto const TopSizer = new wxBoxSizer(wxVERTICAL); TopSizer->Add(m_Scintilla, wxSizerFlags(1).Expand()); SetSizerAndFit(TopSizer); // Listen for colour scheme changes. m_ColourSchemeSettingsRegistration = wxGetApp().getColourSchemeSettings().addListener( [=] (ColourSchemeSettings const &Settings) { setupStylesFromColourScheme(*m_Scintilla, *Settings.getColourScheme()); } ); // Setup the menus. auto menuBar = new wxMenuBar(); append(menuBar, createFileMenu({wxID_SAVE, wxID_SAVEAS})); { auto EditMenu = createEditMenu(); if (EditMenu.first) { EditMenu.first->Prepend(wxID_UNDO); EditMenu.first->Prepend(wxID_REDO); EditMenu.first->Prepend(wxID_CUT); EditMenu.first->Prepend(wxID_COPY); EditMenu.first->Prepend(wxID_PASTE); } append(menuBar, std::move(EditMenu)); } SetMenuBar(menuBar); // Setup the event handling. Bind(wxEVT_COMMAND_MENU_SELECTED, [this] (wxCommandEvent &) { this->Close(); }, wxID_CLOSE); Bind(wxEVT_COMMAND_MENU_SELECTED, &SourceEditorFrame::OnSave, this, wxID_SAVE); Bind(wxEVT_COMMAND_MENU_SELECTED, &SourceEditorFrame::OnSaveAs, this, wxID_SAVEAS); Bind(wxEVT_CLOSE_WINDOW, &SourceEditorFrame::OnClose, this); #define SEEC_FORWARD_COMMAND_TO_SCINTILLA(CMDID, METHOD) \ Bind(wxEVT_COMMAND_MENU_SELECTED, \ [=] (wxCommandEvent &) { m_Scintilla->METHOD(); }, CMDID) SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_UNDO, Undo); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_REDO, Redo); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_CUT, Cut); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_COPY, Copy); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_PASTE, Paste); #undef SEEC_FORWARD_COMMAND_TO_SCINTILLA // Notify the TraceViewerApp that we have been created. auto &App = wxGetApp(); App.addTopLevelWindow(this); } SourceEditorFrame::~SourceEditorFrame() { // Notify the TraceViewerApp that we have been destroyed. auto &App = wxGetApp(); App.removeTopLevelWindow(this); } void SourceEditorFrame::Open(wxFileName const &FileName) { if (m_Scintilla->LoadFile(FileName.GetFullPath())) { m_FileName = FileName; } } void SourceEditorFrame::OnSave(wxCommandEvent &Event) { if (!m_FileName.HasName()) { OnSaveAs(Event); return; } m_Scintilla->SaveFile(m_FileName.GetFullPath()); } void SourceEditorFrame::OnSaveAs(wxCommandEvent &Event) { auto const Res = seec::Resource("TraceViewer")["GUIText"]["SaveSource"]; wxFileDialog SaveDlg(this, seec::towxString(Res["Title"]), /* default dir */ wxEmptyString, /* default file */ wxEmptyString, seec::towxString(Res["FileType"]), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (SaveDlg.ShowModal() == wxID_CANCEL) return; m_FileName.Assign(SaveDlg.GetDirectory(), SaveDlg.GetFilename()); OnSave(Event); } void SourceEditorFrame::OnClose(wxCloseEvent &Ev) { if (m_Scintilla->IsModified()) { auto const Choices = Ev.CanVeto() ? (wxYES_NO | wxCANCEL) : (wxYES_NO); auto const Res = seec::Resource("TraceViewer")["SourceEditor"]; auto const Message = seec::towxString(Res["SaveClosingModifiedFile"]); while (true) { auto const Choice = wxMessageBox(Message, wxEmptyString, Choices); if (Choice == wxCANCEL && Ev.CanVeto()) { Ev.Veto(); return; } else if (Choice == wxYES) { wxCommandEvent Ev; OnSave(Ev); break; } else if (Choice == wxNO) { break; } } } Ev.Skip(); } <commit_msg>Correct compilation under MSW with wxWidgets 3.1.0.<commit_after>//===- tools/seec-view/SourceEditor/SourceEditor.cpp ----------------------===// // // SeeC // // This file is distributed under The MIT License (MIT). See LICENSE.TXT for // details. // //===----------------------------------------------------------------------===// /// /// \file /// //===----------------------------------------------------------------------===// #include "seec/ICU/Resources.hpp" #include "seec/Util/MakeFunction.hpp" #include "seec/wxWidgets/StringConversion.hpp" #include "../ColourSchemeSettings.hpp" #include "../CommonMenus.hpp" #include "../LocaleSettings.hpp" #include "../SourceViewerSettings.hpp" #include "../TraceViewerApp.hpp" #include "SourceEditor.hpp" #include <wx/stc/stc.h> #include <wx/filedlg.h> #include <wx/filename.h> #include <wx/sizer.h> namespace { void setSTCPreferences(wxStyledTextCtrl &Text) { // Setup styles according to the user's colour scheme. auto &Scheme = *wxGetApp().getColourSchemeSettings().getColourScheme(); setupStylesFromColourScheme(Text, Scheme); // Set the lexer to C++. Text.SetLexer(wxSTC_LEX_CPP); // Setup the keywords used by Scintilla's C++ lexer. // TODO: this should be shared with SourceViewer UErrorCode Status = U_ZERO_ERROR; auto KeywordRes = seec::getResource("TraceViewer", getLocale(), Status, "ScintillaKeywords", "C"); if (U_SUCCESS(Status)) { auto Size = KeywordRes.getSize(); for (int32_t i = 0; i < Size; ++i) { auto UniStr = KeywordRes.getStringEx(i, Status); if (U_FAILURE(Status)) break; Text.SetKeyWords(i, seec::towxString(UniStr)); } } // Misc. settings. Text.SetExtraDescent(2); } } // anonymous namespace SourceEditorFrame::SourceEditorFrame() : m_ColourSchemeSettingsRegistration(), m_FileName(), m_Scintilla(nullptr) { if (!wxFrame::Create(nullptr, wxID_ANY, wxString())) return; m_Scintilla = new wxStyledTextCtrl(this); setSTCPreferences(*m_Scintilla); auto const TopSizer = new wxBoxSizer(wxVERTICAL); TopSizer->Add(m_Scintilla, wxSizerFlags(1).Expand()); SetSizerAndFit(TopSizer); // Listen for colour scheme changes. m_ColourSchemeSettingsRegistration = wxGetApp().getColourSchemeSettings().addListener( [=] (ColourSchemeSettings const &Settings) { setupStylesFromColourScheme(*m_Scintilla, *Settings.getColourScheme()); } ); // Setup the menus. auto menuBar = new wxMenuBar(); append(menuBar, createFileMenu({wxID_SAVE, wxID_SAVEAS})); { auto EditMenu = createEditMenu(); if (EditMenu.first) { EditMenu.first->Prepend(wxID_UNDO); EditMenu.first->Prepend(wxID_REDO); EditMenu.first->Prepend(wxID_CUT); EditMenu.first->Prepend(wxID_COPY); EditMenu.first->Prepend(wxID_PASTE); } append(menuBar, std::move(EditMenu)); } SetMenuBar(menuBar); // Setup the event handling. Bind(wxEVT_COMMAND_MENU_SELECTED, seec::make_function([this] (wxCommandEvent &Ev) { this->Close(); }), wxID_CLOSE); Bind(wxEVT_COMMAND_MENU_SELECTED, &SourceEditorFrame::OnSave, this, wxID_SAVE); Bind(wxEVT_COMMAND_MENU_SELECTED, &SourceEditorFrame::OnSaveAs, this, wxID_SAVEAS); Bind(wxEVT_CLOSE_WINDOW, &SourceEditorFrame::OnClose, this); #define SEEC_FORWARD_COMMAND_TO_SCINTILLA(CMDID, METHOD) \ Bind(wxEVT_COMMAND_MENU_SELECTED, \ seec::make_function([=] (wxCommandEvent &) { m_Scintilla->METHOD(); }), \ CMDID) SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_UNDO, Undo); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_REDO, Redo); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_CUT, Cut); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_COPY, Copy); SEEC_FORWARD_COMMAND_TO_SCINTILLA(wxID_PASTE, Paste); #undef SEEC_FORWARD_COMMAND_TO_SCINTILLA // Notify the TraceViewerApp that we have been created. auto &App = wxGetApp(); App.addTopLevelWindow(this); } SourceEditorFrame::~SourceEditorFrame() { // Notify the TraceViewerApp that we have been destroyed. auto &App = wxGetApp(); App.removeTopLevelWindow(this); } void SourceEditorFrame::Open(wxFileName const &FileName) { if (m_Scintilla->LoadFile(FileName.GetFullPath())) { m_FileName = FileName; } } void SourceEditorFrame::OnSave(wxCommandEvent &Event) { if (!m_FileName.HasName()) { OnSaveAs(Event); return; } m_Scintilla->SaveFile(m_FileName.GetFullPath()); } void SourceEditorFrame::OnSaveAs(wxCommandEvent &Event) { auto const Res = seec::Resource("TraceViewer")["GUIText"]["SaveSource"]; wxFileDialog SaveDlg(this, seec::towxString(Res["Title"]), /* default dir */ wxEmptyString, /* default file */ wxEmptyString, seec::towxString(Res["FileType"]), wxFD_SAVE | wxFD_OVERWRITE_PROMPT); if (SaveDlg.ShowModal() == wxID_CANCEL) return; m_FileName.Assign(SaveDlg.GetDirectory(), SaveDlg.GetFilename()); OnSave(Event); } void SourceEditorFrame::OnClose(wxCloseEvent &Ev) { if (m_Scintilla->IsModified()) { auto const Choices = Ev.CanVeto() ? (wxYES_NO | wxCANCEL) : (wxYES_NO); auto const Res = seec::Resource("TraceViewer")["SourceEditor"]; auto const Message = seec::towxString(Res["SaveClosingModifiedFile"]); while (true) { auto const Choice = wxMessageBox(Message, wxEmptyString, Choices); if (Choice == wxCANCEL && Ev.CanVeto()) { Ev.Veto(); return; } else if (Choice == wxYES) { wxCommandEvent Ev; OnSave(Ev); break; } else if (Choice == wxNO) { break; } } } Ev.Skip(); } <|endoftext|>
<commit_before>#include "video_sampler.h" #include <c10/util/Logging.h> #include "util.h" // www.ffmpeg.org/doxygen/0.5/swscale-example_8c-source.html namespace ffmpeg { namespace { // Setup the data pointers and linesizes based on the specified image // parameters and the provided array. This sets up "planes" to point to a // "buffer" // NOTE: this is most likely culprit behind #3534 // // Args: // fmt: desired output video format // buffer: source constant image buffer (in different format) that will contain // the final image after SWScale planes: destination data pointer to be filled // lineSize: target destination linesize (always {0}) int preparePlanes( const VideoFormat& fmt, const uint8_t* buffer, uint8_t** planes, int* lineSize) { int result; // NOTE: 1 at the end of av_fill_arrays is the value used for alignment if ((result = av_image_fill_arrays( planes, lineSize, buffer, (AVPixelFormat)fmt.format, fmt.width, fmt.height, 1)) < 0) { LOG(ERROR) << "av_image_fill_arrays failed, err: " << Util::generateErrorDesc(result); } return result; } // Scale (and crop) the image slice in srcSlice and put the resulting scaled // slice to `planes` buffer, which is mapped to be `out` via preparePlanes as // `sws_scale` cannot access buffers directly. // // Args: // context: SWSContext allocated on line 119 (if crop, optional) or 163 (if // scale) srcSlice: frame data in YUV420P srcStride: the array containing the // strides for each plane of the source // image (from AVFrame->linesize[0]) // out: destination buffer // planes: indirect destination buffer (mapped to "out" via preparePlanes) // lines: destination linesize; constant {0} int transformImage( SwsContext* context, const uint8_t* const srcSlice[], int srcStride[], VideoFormat inFormat, VideoFormat outFormat, uint8_t* out, uint8_t* planes[], int lines[]) { int result; if ((result = preparePlanes(outFormat, out, planes, lines)) < 0) { return result; } if (context) { // NOTE: srcY stride always 0: this is a parameter of YUV format if ((result = sws_scale( context, srcSlice, srcStride, 0, inFormat.height, planes, lines)) < 0) { LOG(ERROR) << "sws_scale failed, err: " << Util::generateErrorDesc(result); return result; } } else if (inFormat.width == outFormat.width && inFormat.height == outFormat.height && inFormat.format == outFormat.format) { // Copy planes without using sws_scale if sws_getContext failed. av_image_copy( planes, lines, (const uint8_t**)srcSlice, srcStride, (AVPixelFormat)inFormat.format, inFormat.width, inFormat.height); } else { LOG(ERROR) << "Invalid scale context format " << inFormat.format; return AVERROR(EINVAL); } return 0; } } // namespace VideoSampler::VideoSampler(int swsFlags, int64_t loggingUuid) : swsFlags_(swsFlags), loggingUuid_(loggingUuid) {} VideoSampler::~VideoSampler() { cleanUp(); } void VideoSampler::shutdown() { cleanUp(); } bool VideoSampler::init(const SamplerParameters& params) { cleanUp(); if (params.out.video.cropImage != 0) { if (!Util::validateVideoFormat(params.out.video)) { LOG(ERROR) << "Invalid video format" << ", width: " << params.out.video.width << ", height: " << params.out.video.height << ", format: " << params.out.video.format << ", minDimension: " << params.out.video.minDimension << ", crop: " << params.out.video.cropImage; return false; } scaleFormat_.format = params.out.video.format; Util::setFormatDimensions( scaleFormat_.width, scaleFormat_.height, params.out.video.width, params.out.video.height, params.in.video.width, params.in.video.height, 0, 0, 1); if (!(scaleFormat_ == params_.out.video)) { // crop required cropContext_ = sws_getContext( params.out.video.width, params.out.video.height, (AVPixelFormat)params.out.video.format, params.out.video.width, params.out.video.height, (AVPixelFormat)params.out.video.format, swsFlags_, nullptr, nullptr, nullptr); if (!cropContext_) { LOG(ERROR) << "sws_getContext failed for crop context"; return false; } const auto scaleImageSize = av_image_get_buffer_size( (AVPixelFormat)scaleFormat_.format, scaleFormat_.width, scaleFormat_.height, 1); scaleBuffer_.resize(scaleImageSize); } } else { scaleFormat_ = params.out.video; } VLOG(1) << "Input format #" << loggingUuid_ << ", width " << params.in.video.width << ", height " << params.in.video.height << ", format " << params.in.video.format << ", minDimension " << params.in.video.minDimension << ", cropImage " << params.in.video.cropImage; VLOG(1) << "Scale format #" << loggingUuid_ << ", width " << scaleFormat_.width << ", height " << scaleFormat_.height << ", format " << scaleFormat_.format << ", minDimension " << scaleFormat_.minDimension << ", cropImage " << scaleFormat_.cropImage; VLOG(1) << "Crop format #" << loggingUuid_ << ", width " << params.out.video.width << ", height " << params.out.video.height << ", format " << params.out.video.format << ", minDimension " << params.out.video.minDimension << ", cropImage " << params.out.video.cropImage; // set output format params_ = params; scaleContext_ = sws_getContext( params.in.video.width, params.in.video.height, (AVPixelFormat)params.in.video.format, scaleFormat_.width, scaleFormat_.height, (AVPixelFormat)scaleFormat_.format, swsFlags_, nullptr, nullptr, nullptr); // sws_getContext might fail if in/out format == AV_PIX_FMT_PAL8 (png format) // Return true if input and output formats/width/height are identical // Check scaleContext_ for nullptr in transformImage to copy planes directly if (params.in.video.width == scaleFormat_.width && params.in.video.height == scaleFormat_.height && params.in.video.format == scaleFormat_.format) { return true; } return scaleContext_ != nullptr; } // Main body of the sample function called from one of the overloads below // // Args: // srcSlice: decoded AVFrame->data perpared buffer // srcStride: linesize (usually obtained from AVFrame->linesize) // out: return buffer (ByteStorage*) int VideoSampler::sample( const uint8_t* const srcSlice[], int srcStride[], ByteStorage* out) { int result; // scaled and cropped image int outImageSize = av_image_get_buffer_size( (AVPixelFormat)params_.out.video.format, params_.out.video.width, params_.out.video.height, 1); out->ensure(outImageSize); uint8_t* scalePlanes[4] = {nullptr}; int scaleLines[4] = {0}; // perform scale first if ((result = transformImage( scaleContext_, srcSlice, srcStride, params_.in.video, scaleFormat_, // for crop use internal buffer cropContext_ ? scaleBuffer_.data() : out->writableTail(), scalePlanes, scaleLines))) { return result; } // is crop required? if (cropContext_) { uint8_t* cropPlanes[4] = {nullptr}; int cropLines[4] = {0}; if (params_.out.video.height < scaleFormat_.height) { // Destination image is wider of source image: cut top and bottom for (size_t i = 0; i < 4 && scalePlanes[i] != nullptr; ++i) { scalePlanes[i] += scaleLines[i] * (scaleFormat_.height - params_.out.video.height) / 2; } } else { // Source image is wider of destination image: cut sides for (size_t i = 0; i < 4 && scalePlanes[i] != nullptr; ++i) { scalePlanes[i] += scaleLines[i] * (scaleFormat_.width - params_.out.video.width) / 2 / scaleFormat_.width; } } // crop image if ((result = transformImage( cropContext_, scalePlanes, scaleLines, params_.out.video, params_.out.video, out->writableTail(), cropPlanes, cropLines))) { return result; } } out->append(outImageSize); return outImageSize; } // Call from `video_stream.cpp::114` - occurs during file reads int VideoSampler::sample(AVFrame* frame, ByteStorage* out) { if (!frame) { return 0; // no flush for videos } return sample(frame->data, frame->linesize, out); } // Call from `video_stream.cpp::114` - not sure when this occurs int VideoSampler::sample(const ByteStorage* in, ByteStorage* out) { if (!in) { return 0; // no flush for videos } int result; uint8_t* inPlanes[4] = {nullptr}; int inLineSize[4] = {0}; if ((result = preparePlanes( params_.in.video, in->data(), inPlanes, inLineSize)) < 0) { return result; } return sample(inPlanes, inLineSize, out); } void VideoSampler::cleanUp() { if (scaleContext_) { sws_freeContext(scaleContext_); scaleContext_ = nullptr; } if (cropContext_) { sws_freeContext(cropContext_); cropContext_ = nullptr; scaleBuffer_.clear(); } } } // namespace ffmpeg <commit_msg>Fix linter (#6360)<commit_after>#include "video_sampler.h" #include <c10/util/Logging.h> #include "util.h" // www.ffmpeg.org/doxygen/0.5/swscale-example_8c-source.html namespace ffmpeg { namespace { // Setup the data pointers and linesizes based on the specified image // parameters and the provided array. This sets up "planes" to point to a // "buffer" // NOTE: this is most likely culprit behind #3534 // // Args: // fmt: desired output video format // buffer: source constant image buffer (in different format) that will contain // the final image after SWScale planes: destination data pointer to be filled // lineSize: target destination linesize (always {0}) int preparePlanes( const VideoFormat& fmt, const uint8_t* buffer, uint8_t** planes, int* lineSize) { int result; // NOTE: 1 at the end of av_fill_arrays is the value used for alignment if ((result = av_image_fill_arrays( planes, lineSize, buffer, (AVPixelFormat)fmt.format, fmt.width, fmt.height, 1)) < 0) { LOG(ERROR) << "av_image_fill_arrays failed, err: " << Util::generateErrorDesc(result); } return result; } // Scale (and crop) the image slice in srcSlice and put the resulting scaled // slice to `planes` buffer, which is mapped to be `out` via preparePlanes as // `sws_scale` cannot access buffers directly. // // Args: // context: SWSContext allocated on line 119 (if crop, optional) or 163 (if // scale) srcSlice: frame data in YUV420P srcStride: the array containing the // strides for each plane of the source // image (from AVFrame->linesize[0]) // out: destination buffer // planes: indirect destination buffer (mapped to "out" via preparePlanes) // lines: destination linesize; constant {0} int transformImage( SwsContext* context, const uint8_t* const srcSlice[], int srcStride[], VideoFormat inFormat, VideoFormat outFormat, uint8_t* out, uint8_t* planes[], int lines[]) { int result; if ((result = preparePlanes(outFormat, out, planes, lines)) < 0) { return result; } if (context) { // NOTE: srcY stride always 0: this is a parameter of YUV format if ((result = sws_scale( context, srcSlice, srcStride, 0, inFormat.height, planes, lines)) < 0) { LOG(ERROR) << "sws_scale failed, err: " << Util::generateErrorDesc(result); return result; } } else if ( inFormat.width == outFormat.width && inFormat.height == outFormat.height && inFormat.format == outFormat.format) { // Copy planes without using sws_scale if sws_getContext failed. av_image_copy( planes, lines, (const uint8_t**)srcSlice, srcStride, (AVPixelFormat)inFormat.format, inFormat.width, inFormat.height); } else { LOG(ERROR) << "Invalid scale context format " << inFormat.format; return AVERROR(EINVAL); } return 0; } } // namespace VideoSampler::VideoSampler(int swsFlags, int64_t loggingUuid) : swsFlags_(swsFlags), loggingUuid_(loggingUuid) {} VideoSampler::~VideoSampler() { cleanUp(); } void VideoSampler::shutdown() { cleanUp(); } bool VideoSampler::init(const SamplerParameters& params) { cleanUp(); if (params.out.video.cropImage != 0) { if (!Util::validateVideoFormat(params.out.video)) { LOG(ERROR) << "Invalid video format" << ", width: " << params.out.video.width << ", height: " << params.out.video.height << ", format: " << params.out.video.format << ", minDimension: " << params.out.video.minDimension << ", crop: " << params.out.video.cropImage; return false; } scaleFormat_.format = params.out.video.format; Util::setFormatDimensions( scaleFormat_.width, scaleFormat_.height, params.out.video.width, params.out.video.height, params.in.video.width, params.in.video.height, 0, 0, 1); if (!(scaleFormat_ == params_.out.video)) { // crop required cropContext_ = sws_getContext( params.out.video.width, params.out.video.height, (AVPixelFormat)params.out.video.format, params.out.video.width, params.out.video.height, (AVPixelFormat)params.out.video.format, swsFlags_, nullptr, nullptr, nullptr); if (!cropContext_) { LOG(ERROR) << "sws_getContext failed for crop context"; return false; } const auto scaleImageSize = av_image_get_buffer_size( (AVPixelFormat)scaleFormat_.format, scaleFormat_.width, scaleFormat_.height, 1); scaleBuffer_.resize(scaleImageSize); } } else { scaleFormat_ = params.out.video; } VLOG(1) << "Input format #" << loggingUuid_ << ", width " << params.in.video.width << ", height " << params.in.video.height << ", format " << params.in.video.format << ", minDimension " << params.in.video.minDimension << ", cropImage " << params.in.video.cropImage; VLOG(1) << "Scale format #" << loggingUuid_ << ", width " << scaleFormat_.width << ", height " << scaleFormat_.height << ", format " << scaleFormat_.format << ", minDimension " << scaleFormat_.minDimension << ", cropImage " << scaleFormat_.cropImage; VLOG(1) << "Crop format #" << loggingUuid_ << ", width " << params.out.video.width << ", height " << params.out.video.height << ", format " << params.out.video.format << ", minDimension " << params.out.video.minDimension << ", cropImage " << params.out.video.cropImage; // set output format params_ = params; scaleContext_ = sws_getContext( params.in.video.width, params.in.video.height, (AVPixelFormat)params.in.video.format, scaleFormat_.width, scaleFormat_.height, (AVPixelFormat)scaleFormat_.format, swsFlags_, nullptr, nullptr, nullptr); // sws_getContext might fail if in/out format == AV_PIX_FMT_PAL8 (png format) // Return true if input and output formats/width/height are identical // Check scaleContext_ for nullptr in transformImage to copy planes directly if (params.in.video.width == scaleFormat_.width && params.in.video.height == scaleFormat_.height && params.in.video.format == scaleFormat_.format) { return true; } return scaleContext_ != nullptr; } // Main body of the sample function called from one of the overloads below // // Args: // srcSlice: decoded AVFrame->data perpared buffer // srcStride: linesize (usually obtained from AVFrame->linesize) // out: return buffer (ByteStorage*) int VideoSampler::sample( const uint8_t* const srcSlice[], int srcStride[], ByteStorage* out) { int result; // scaled and cropped image int outImageSize = av_image_get_buffer_size( (AVPixelFormat)params_.out.video.format, params_.out.video.width, params_.out.video.height, 1); out->ensure(outImageSize); uint8_t* scalePlanes[4] = {nullptr}; int scaleLines[4] = {0}; // perform scale first if ((result = transformImage( scaleContext_, srcSlice, srcStride, params_.in.video, scaleFormat_, // for crop use internal buffer cropContext_ ? scaleBuffer_.data() : out->writableTail(), scalePlanes, scaleLines))) { return result; } // is crop required? if (cropContext_) { uint8_t* cropPlanes[4] = {nullptr}; int cropLines[4] = {0}; if (params_.out.video.height < scaleFormat_.height) { // Destination image is wider of source image: cut top and bottom for (size_t i = 0; i < 4 && scalePlanes[i] != nullptr; ++i) { scalePlanes[i] += scaleLines[i] * (scaleFormat_.height - params_.out.video.height) / 2; } } else { // Source image is wider of destination image: cut sides for (size_t i = 0; i < 4 && scalePlanes[i] != nullptr; ++i) { scalePlanes[i] += scaleLines[i] * (scaleFormat_.width - params_.out.video.width) / 2 / scaleFormat_.width; } } // crop image if ((result = transformImage( cropContext_, scalePlanes, scaleLines, params_.out.video, params_.out.video, out->writableTail(), cropPlanes, cropLines))) { return result; } } out->append(outImageSize); return outImageSize; } // Call from `video_stream.cpp::114` - occurs during file reads int VideoSampler::sample(AVFrame* frame, ByteStorage* out) { if (!frame) { return 0; // no flush for videos } return sample(frame->data, frame->linesize, out); } // Call from `video_stream.cpp::114` - not sure when this occurs int VideoSampler::sample(const ByteStorage* in, ByteStorage* out) { if (!in) { return 0; // no flush for videos } int result; uint8_t* inPlanes[4] = {nullptr}; int inLineSize[4] = {0}; if ((result = preparePlanes( params_.in.video, in->data(), inPlanes, inLineSize)) < 0) { return result; } return sample(inPlanes, inLineSize, out); } void VideoSampler::cleanUp() { if (scaleContext_) { sws_freeContext(scaleContext_); scaleContext_ = nullptr; } if (cropContext_) { sws_freeContext(cropContext_); cropContext_ = nullptr; scaleBuffer_.clear(); } } } // namespace ffmpeg <|endoftext|>
<commit_before>#include <StdAfx.h> #include <UI/Controls/PaneHeader/PaneHeader.h> #include <UI/UIFunctions.h> #include <core/utility/strings.h> #include <core/utility/output.h> namespace controls { void PaneHeader::Initialize(_In_ CWnd* pParent, _In_opt_ HDC hdc, _In_ UINT nid) { if (pParent) m_hWndParent = pParent->m_hWnd; // Assign a nID to the collapse button that is IDD_COLLAPSE more than the control's nID m_nIDCollapse = nid + IDD_COLLAPSE; // TODO: We don't save our header's nID here, but we could if we wanted // If we need an action button, go ahead and create it if (m_nIDAction) { EC_B_S(m_actionButton.Create( strings::wstringTotstring(m_szActionButton).c_str(), WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, m_nIDAction)); StyleButton(m_actionButton.m_hWnd, ui::uiButtonStyle::Unstyled); } EC_B_S(m_rightLabel.Create( WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, IDD_COUNTLABEL)); ui::SubclassLabel(m_rightLabel.m_hWnd); StyleLabel(m_rightLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderText); EC_B_S(Create(WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, nid)); ::SetWindowTextW(m_hWnd, m_szLabel.c_str()); ui::SubclassLabel(m_hWnd); if (m_bCollapsible) { StyleLabel(m_hWnd, ui::uiLabelStyle::PaneHeaderLabel); EC_B_S(m_CollapseButton.Create( nullptr, WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, m_nIDCollapse)); StyleButton( m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow); } const auto sizeText = ui::GetTextExtentPoint32(hdc, m_szLabel); m_iLabelWidth = sizeText.cx; output::DebugPrint( output::dbgLevel::Draw, L"PaneHeader::Initialize m_iLabelWidth:%d \"%ws\"\n", m_iLabelWidth, m_szLabel.c_str()); } // Draw our collapse button and label, if needed. // Draws everything to GetFixedHeight() void PaneHeader::DeferWindowPos(_In_ HDWP hWinPosInfo, const _In_ int x, const _In_ int y, const _In_ int width) { const auto height = GetFixedHeight(); auto curX = x; const auto actionButtonWidth = m_actionButtonWidth ? m_actionButtonWidth + 2 * m_iMargin : 0; const auto actionButtonAndGutterWidth = actionButtonWidth ? actionButtonWidth + m_iSideMargin : 0; if (m_bCollapsible) { ::DeferWindowPos( hWinPosInfo, m_CollapseButton.GetSafeHwnd(), nullptr, curX, y, width - actionButtonAndGutterWidth, height, SWP_NOZORDER); curX += m_iButtonHeight; } output::DebugPrint( output::dbgLevel::Draw, L"PaneHeader::DeferWindowPos x:%d width:%d labelpos:%d labelwidth:%d \n", x, width, curX, m_iLabelWidth); ::DeferWindowPos(hWinPosInfo, GetSafeHwnd(), nullptr, curX, y, m_iLabelWidth, height, SWP_NOZORDER); if (!m_bCollapsed) { // Drop the count on top of the label we drew above EC_B_S(::DeferWindowPos( hWinPosInfo, m_rightLabel.GetSafeHwnd(), nullptr, x + width - m_rightLabelWidth - actionButtonAndGutterWidth, y, m_rightLabelWidth, height, SWP_NOZORDER)); } if (m_nIDAction) { // Drop the action button next to the label we drew above EC_B_S(::DeferWindowPos( hWinPosInfo, m_actionButton.GetSafeHwnd(), nullptr, x + width - actionButtonWidth, y, actionButtonWidth, height, SWP_NOZORDER)); } } int PaneHeader::GetMinWidth() { auto cx = m_iLabelWidth; if (m_bCollapsible) cx += m_iButtonHeight; if (m_rightLabelWidth) { cx += m_iSideMargin; cx += m_rightLabelWidth; } if (m_actionButtonWidth) { cx += m_iSideMargin; cx += m_actionButtonWidth + 2 * m_iMargin; } return cx; } void PaneHeader::SetRightLabel(const std::wstring szLabel) { EC_B_S(::SetWindowTextW(m_rightLabel.m_hWnd, szLabel.c_str())); const auto hdc = ::GetDC(m_rightLabel.GetSafeHwnd()); const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont()); const auto sizeText = ui::GetTextExtentPoint32(hdc, szLabel); static_cast<void>(SelectObject(hdc, hfontOld)); ::ReleaseDC(m_rightLabel.GetSafeHwnd(), hdc); m_rightLabelWidth = sizeText.cx; } void PaneHeader::SetActionButton(const std::wstring szActionButton) { // Don't bother if we never enabled the button if (m_nIDAction == 0) return; EC_B_S(::SetWindowTextW(m_actionButton.GetSafeHwnd(), szActionButton.c_str())); m_szActionButton = szActionButton; const auto hdc = ::GetDC(m_actionButton.GetSafeHwnd()); const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont()); const auto sizeText = ui::GetTextExtentPoint32(hdc, szActionButton); static_cast<void>(SelectObject(hdc, hfontOld)); ::ReleaseDC(m_actionButton.GetSafeHwnd(), hdc); m_actionButtonWidth = sizeText.cx; } bool PaneHeader::HandleChange(UINT nID) { // Collapse buttons have a nID IDD_COLLAPSE higher than nID of the pane they toggle. // So if we get asked about one that matches, we can assume it's time to toggle our collapse. if (m_nIDCollapse == nID) { OnToggleCollapse(); return true; } return false; } void PaneHeader::OnToggleCollapse() { m_bCollapsed = !m_bCollapsed; StyleButton(m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow); WC_B_S(m_rightLabel.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW)); // Trigger a redraw ::PostMessage(m_hWndParent, WM_COMMAND, IDD_RECALCLAYOUT, NULL); } void PaneHeader::SetMargins( int iMargin, int iSideMargin, int iLabelHeight, // Height of the label int iButtonHeight) // Height of button { m_iMargin = iMargin; m_iSideMargin = iSideMargin; m_iLabelHeight = iLabelHeight; m_iButtonHeight = iButtonHeight; } } // namespace controls<commit_msg>Ignore SetRightLabel calls before initialize<commit_after>#include <StdAfx.h> #include <UI/Controls/PaneHeader/PaneHeader.h> #include <UI/UIFunctions.h> #include <core/utility/strings.h> #include <core/utility/output.h> namespace controls { void PaneHeader::Initialize(_In_ CWnd* pParent, _In_opt_ HDC hdc, _In_ UINT nid) { if (pParent) m_hWndParent = pParent->m_hWnd; // Assign a nID to the collapse button that is IDD_COLLAPSE more than the control's nID m_nIDCollapse = nid + IDD_COLLAPSE; // TODO: We don't save our header's nID here, but we could if we wanted // If we need an action button, go ahead and create it if (m_nIDAction) { EC_B_S(m_actionButton.Create( strings::wstringTotstring(m_szActionButton).c_str(), WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, m_nIDAction)); StyleButton(m_actionButton.m_hWnd, ui::uiButtonStyle::Unstyled); } EC_B_S(m_rightLabel.Create( WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, IDD_COUNTLABEL)); ui::SubclassLabel(m_rightLabel.m_hWnd); StyleLabel(m_rightLabel.m_hWnd, ui::uiLabelStyle::PaneHeaderText); EC_B_S(Create(WS_CHILD | WS_CLIPSIBLINGS | ES_READONLY | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, nid)); ::SetWindowTextW(m_hWnd, m_szLabel.c_str()); ui::SubclassLabel(m_hWnd); if (m_bCollapsible) { StyleLabel(m_hWnd, ui::uiLabelStyle::PaneHeaderLabel); EC_B_S(m_CollapseButton.Create( nullptr, WS_TABSTOP | WS_CHILD | WS_CLIPSIBLINGS | WS_VISIBLE, CRect(0, 0, 0, 0), pParent, m_nIDCollapse)); StyleButton( m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow); } const auto sizeText = ui::GetTextExtentPoint32(hdc, m_szLabel); m_iLabelWidth = sizeText.cx; output::DebugPrint( output::dbgLevel::Draw, L"PaneHeader::Initialize m_iLabelWidth:%d \"%ws\"\n", m_iLabelWidth, m_szLabel.c_str()); m_bInitialized = true; } // Draw our collapse button and label, if needed. // Draws everything to GetFixedHeight() void PaneHeader::DeferWindowPos(_In_ HDWP hWinPosInfo, const _In_ int x, const _In_ int y, const _In_ int width) { const auto height = GetFixedHeight(); auto curX = x; const auto actionButtonWidth = m_actionButtonWidth ? m_actionButtonWidth + 2 * m_iMargin : 0; const auto actionButtonAndGutterWidth = actionButtonWidth ? actionButtonWidth + m_iSideMargin : 0; if (m_bCollapsible) { ::DeferWindowPos( hWinPosInfo, m_CollapseButton.GetSafeHwnd(), nullptr, curX, y, width - actionButtonAndGutterWidth, height, SWP_NOZORDER); curX += m_iButtonHeight; } output::DebugPrint( output::dbgLevel::Draw, L"PaneHeader::DeferWindowPos x:%d width:%d labelpos:%d labelwidth:%d \n", x, width, curX, m_iLabelWidth); ::DeferWindowPos(hWinPosInfo, GetSafeHwnd(), nullptr, curX, y, m_iLabelWidth, height, SWP_NOZORDER); if (!m_bCollapsed) { // Drop the count on top of the label we drew above EC_B_S(::DeferWindowPos( hWinPosInfo, m_rightLabel.GetSafeHwnd(), nullptr, x + width - m_rightLabelWidth - actionButtonAndGutterWidth, y, m_rightLabelWidth, height, SWP_NOZORDER)); } if (m_nIDAction) { // Drop the action button next to the label we drew above EC_B_S(::DeferWindowPos( hWinPosInfo, m_actionButton.GetSafeHwnd(), nullptr, x + width - actionButtonWidth, y, actionButtonWidth, height, SWP_NOZORDER)); } } int PaneHeader::GetMinWidth() { auto cx = m_iLabelWidth; if (m_bCollapsible) cx += m_iButtonHeight; if (m_rightLabelWidth) { cx += m_iSideMargin; cx += m_rightLabelWidth; } if (m_actionButtonWidth) { cx += m_iSideMargin; cx += m_actionButtonWidth + 2 * m_iMargin; } return cx; } void PaneHeader::SetRightLabel(const std::wstring szLabel) { if (!m_bInitialized) return; EC_B_S(::SetWindowTextW(m_rightLabel.m_hWnd, szLabel.c_str())); const auto hdc = ::GetDC(m_rightLabel.GetSafeHwnd()); const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont()); const auto sizeText = ui::GetTextExtentPoint32(hdc, szLabel); static_cast<void>(SelectObject(hdc, hfontOld)); ::ReleaseDC(m_rightLabel.GetSafeHwnd(), hdc); m_rightLabelWidth = sizeText.cx; } void PaneHeader::SetActionButton(const std::wstring szActionButton) { // Don't bother if we never enabled the button if (m_nIDAction == 0) return; EC_B_S(::SetWindowTextW(m_actionButton.GetSafeHwnd(), szActionButton.c_str())); m_szActionButton = szActionButton; const auto hdc = ::GetDC(m_actionButton.GetSafeHwnd()); const auto hfontOld = SelectObject(hdc, ui::GetSegoeFont()); const auto sizeText = ui::GetTextExtentPoint32(hdc, szActionButton); static_cast<void>(SelectObject(hdc, hfontOld)); ::ReleaseDC(m_actionButton.GetSafeHwnd(), hdc); m_actionButtonWidth = sizeText.cx; } bool PaneHeader::HandleChange(UINT nID) { // Collapse buttons have a nID IDD_COLLAPSE higher than nID of the pane they toggle. // So if we get asked about one that matches, we can assume it's time to toggle our collapse. if (m_nIDCollapse == nID) { OnToggleCollapse(); return true; } return false; } void PaneHeader::OnToggleCollapse() { m_bCollapsed = !m_bCollapsed; StyleButton(m_CollapseButton.m_hWnd, m_bCollapsed ? ui::uiButtonStyle::UpArrow : ui::uiButtonStyle::DownArrow); WC_B_S(m_rightLabel.ShowWindow(m_bCollapsed ? SW_HIDE : SW_SHOW)); // Trigger a redraw ::PostMessage(m_hWndParent, WM_COMMAND, IDD_RECALCLAYOUT, NULL); } void PaneHeader::SetMargins( int iMargin, int iSideMargin, int iLabelHeight, // Height of the label int iButtonHeight) // Height of button { m_iMargin = iMargin; m_iSideMargin = iSideMargin; m_iLabelHeight = iLabelHeight; m_iButtonHeight = iButtonHeight; } } // namespace controls<|endoftext|>
<commit_before>/// \file /// \ingroup tutorial_tdataframe /// \notebook /// This tutorial shows how to write out datasets in ROOT formatusing the TDataFrame /// \macro_code /// /// \date April 2017 /// \author Danilo Piparo #include "TFile.h" #include "TH1F.h" #include "TTree.h" #include "ROOT/TDataFrame.hxx" // A simple helper function to fill a test tree: this makes the example // stand-alone. void fill_tree(const char *filename, const char *treeName) { TFile f(filename, "RECREATE"); TTree t(treeName, treeName); int b1; float b2; t.Branch("b1", &b1); t.Branch("b2", &b2); for (int i = 0; i < 100; ++i) { b1 = i; b2 = i * i; t.Fill(); } t.Write(); f.Close(); return; } int tdf007_snapshot() { // We prepare an input tree to run on auto fileName = "tdf007_snapshot.root"; auto outFileName = "tdf007_snapshot_output.root"; auto treeName = "myTree"; fill_tree(fileName, treeName); // We read the tree from the file and create a TDataFrame. ROOT::Experimental::TDataFrame d(treeName, fileName); // ## Select entries // We now select some entries in the dataset auto d_cut = d.Filter("b1 % 2 == 0"); // ## Enrich the dataset // Build some temporary branches: we'll write them out auto d2 = d_cut.Define("b1_square", "b1 * b1") .Define("b2_vector", [](float b2) { std::vector<float> v; for (int i = 0; i < 3; i++) v.push_back(i); return v; }, {"b2"}); // ## Write it to disk in ROOT format // We now write to disk a new dataset with one of the variables originally present in the tree and the new variables. d2.Snapshot<int, int, std::vector<float>>(treeName, outFileName, {"b1", "b1_square", "b2_vector"}); // Open the new file and list the branches of the tree TFile f(outFileName); TTree *t; f.GetObject(treeName, t); for (auto branch : *t->GetListOfBranches()) { std::cout << "Branch: " << branch->GetName() << std::endl; } f.Close(); // We can also get a fresh TDataFrame out of the snapshot and restart the // analysis chain from it. The default branches are the one selected. auto snapshot_tdf = d2.Snapshot<int>(treeName, outFileName, {"b1_square"}); auto h = snapshot_tdf.Histo1D(); auto c = new TCanvas(); h->DrawClone(); return 0; } <commit_msg>[TDF] Use lambda input variable<commit_after>/// \file /// \ingroup tutorial_tdataframe /// \notebook /// This tutorial shows how to write out datasets in ROOT formatusing the TDataFrame /// \macro_code /// /// \date April 2017 /// \author Danilo Piparo #include "TFile.h" #include "TH1F.h" #include "TTree.h" #include "ROOT/TDataFrame.hxx" // A simple helper function to fill a test tree: this makes the example // stand-alone. void fill_tree(const char *filename, const char *treeName) { TFile f(filename, "RECREATE"); TTree t(treeName, treeName); int b1; float b2; t.Branch("b1", &b1); t.Branch("b2", &b2); for (int i = 0; i < 100; ++i) { b1 = i; b2 = i * i; t.Fill(); } t.Write(); f.Close(); return; } int tdf007_snapshot() { // We prepare an input tree to run on auto fileName = "tdf007_snapshot.root"; auto outFileName = "tdf007_snapshot_output.root"; auto treeName = "myTree"; fill_tree(fileName, treeName); // We read the tree from the file and create a TDataFrame. ROOT::Experimental::TDataFrame d(treeName, fileName); // ## Select entries // We now select some entries in the dataset auto d_cut = d.Filter("b1 % 2 == 0"); // ## Enrich the dataset // Build some temporary branches: we'll write them out auto d2 = d_cut.Define("b1_square", "b1 * b1") .Define("b2_vector", [](float b2) { std::vector<float> v; for (int i = 0; i < 3; i++) v.push_back(b2*i); return v; }, {"b2"}); // ## Write it to disk in ROOT format // We now write to disk a new dataset with one of the variables originally present in the tree and the new variables. d2.Snapshot<int, int, std::vector<float>>(treeName, outFileName, {"b1", "b1_square", "b2_vector"}); // Open the new file and list the branches of the tree TFile f(outFileName); TTree *t; f.GetObject(treeName, t); for (auto branch : *t->GetListOfBranches()) { std::cout << "Branch: " << branch->GetName() << std::endl; } f.Close(); // We can also get a fresh TDataFrame out of the snapshot and restart the // analysis chain from it. The default branches are the one selected. auto snapshot_tdf = d2.Snapshot<int>(treeName, outFileName, {"b1_square"}); auto h = snapshot_tdf.Histo1D(); auto c = new TCanvas(); h->DrawClone(); return 0; } <|endoftext|>
<commit_before>/* * This file is part of the leaf3d project. * * Copyright 2014-2015 Emanuele Bertoldi. All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * You should have received a copy of the modified BSD License along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license.php> */ #include <stdio.h> #include <leaf3d/leaf3d.h> #include <leaf3d/leaf3dut.h> #include <glad/glad.h> #include <GLFW/glfw3.h> #define WINDOW_WIDTH 1024 #define WINDOW_HEIGHT 768 #define GRASS_DENSITY 300 #define GRASS_COLOR L3DVec3(0.67f,0.68f,0.41f) #define GRASS_COLOR_VAR L3DVec3(0.1f,0.08f,0.15f) #define GRASS_HEIGHT 1.0f #define GRASS_HEIGHT_VAR 4.0f #define GRASS_FIELD_SIZE 800.0f #define GRASS_DISTANCE_LOD3 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 1.0f #define GRASS_DISTANCE_LOD2 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 0.4f #define GRASS_DISTANCE_LOD1 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 0.3f using namespace l3d; int main() { // -------------------------------- INIT ------------------------------- // // Init GLFW. if (glfwInit() != GL_TRUE) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } // Create a rendering window with OpenGL 3.2 context. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "leaf3d", L3D_NULLPTR, L3D_NULLPTR); glfwMakeContextCurrent(window); // Init leaf3d. if (l3dInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3d\n"); return -2; } // Init leaf3dut. if (l3dutInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3dut\n"); return -3; } // ----------------------------- RESOURCES ----------------------------- // // Load a shader program with support for lighting (Blinn-Phong). L3DHandle blinnPhongShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/blinnphong.frag"); // Load a shader program for sky box. L3DHandle skyBoxShaderProgram = l3dutLoadShaderProgram("Shaders/skyBox.vert", "Shaders/skyBox.frag"); // Load a shader program for grass plane rendering. L3DHandle grassPlaneShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/grassPlane.frag"); // Load a shader program for realistic grass blades rendering. L3DHandle grassBladesShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/grassBlades.frag", "Shaders/grassBlades.geom"); // Load a sky box. L3DHandle skyBoxCubeMap = l3dutLoadTextureCube( "Textures/SkyBox2/right.jpg", "Textures/SkyBox2/left.jpg", "Textures/SkyBox2/top.jpg", "Textures/SkyBox2/bottom.jpg", "Textures/SkyBox2/back.jpg", "Textures/SkyBox2/front.jpg" ); L3DHandle skyBoxMaterial = l3dLoadMaterial("skyBoxMaterial", skyBoxShaderProgram); l3dAddTextureToMaterial(skyBoxMaterial, "cubeMap", skyBoxCubeMap); L3DHandle skyBox = l3dLoadSkyBox(skyBoxMaterial); // Load a grass plane. L3DHandle grassTexture = l3dutLoadTexture2D("Textures/Grass/grass_diffuse.jpg"); L3DHandle grassPlaneMaterial = l3dLoadMaterial("grassPlaneMaterial", grassPlaneShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassPlaneMaterial, "diffuseMap", grassTexture); L3DHandle grassPlane = l3dLoadGrid(1, grassPlaneMaterial, L3DVec2(40, 40), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassPlane, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassPlane, L3DVec3(GRASS_FIELD_SIZE, GRASS_FIELD_SIZE, 1)); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1); // Load grass blades. L3DHandle grassBladesTexture = l3dutLoadTexture2D("Textures/Grass/grass_blade_diffuse.png"); L3DHandle grassBladesMaterial = l3dLoadMaterial("grassBladeMaterial", grassBladesShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassBladesMaterial, "diffuseMap", grassBladesTexture); L3DHandle grassBlades = l3dLoadGrid(GRASS_DENSITY, grassBladesMaterial, L3DVec2(1, 1), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassBlades, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassBlades, L3DVec3(GRASS_FIELD_SIZE, GRASS_FIELD_SIZE, 1)); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeight", GRASS_HEIGHT); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeightVariation", GRASS_HEIGHT_VAR); l3dSetShaderProgramUniformVec3(grassBladesShaderProgram, "u_grassColorVariation", GRASS_COLOR_VAR); // Load a crate. L3DHandle crateTexture = l3dutLoadTexture2D("Textures/Crate/crate.png"); L3DHandle crateSpecTexture = l3dutLoadTexture2D("Textures/Crate/crate_spec.png"); L3DHandle crateNormTexture = l3dutLoadTexture2D("Textures/Crate/crate_norm.png"); L3DHandle crateMaterial = l3dLoadMaterial("crateMaterial", blinnPhongShaderProgram); l3dAddTextureToMaterial(crateMaterial, "diffuseMap", crateTexture); l3dAddTextureToMaterial(crateMaterial, "specularMap", crateSpecTexture); l3dAddTextureToMaterial(crateMaterial, "normalMap", crateNormTexture); L3DHandle cube1 = l3dLoadCube(crateMaterial); l3dRotateMesh(cube1, 0.75f); l3dTranslateMesh(cube1, L3DVec3(10, 3, -20)); l3dScaleMesh(cube1, L3DVec3(6, 6, 6)); // Load a tree. unsigned int meshCount = 0; L3DHandle* tree = l3dutLoadMeshes("Models/tree1.obj", blinnPhongShaderProgram, &meshCount); for (int i=0; i<meshCount; ++i) { l3dRotateMesh(tree[i], 0.75f); l3dTranslateMesh(tree[i], L3DVec3(-45, 0, 20)); l3dScaleMesh(tree[i], L3DVec3(10, 10, 10)); } // Load a directional light. L3DVec4 sunLightColor = L3DVec4(0.8f, 0.7f, 0.6f, 1); L3DHandle sunLight = l3dLoadDirectionalLight(L3DVec3(-2, -1, 5), sunLightColor); // Set the global ambient light color. l3dSetShaderProgramUniformVec4(blinnPhongShaderProgram, "u_ambientColor", L3DVec4(0.8f, 0.8f, 1, 0.6f)); // Create a camera. L3DHandle camera = l3dLoadCamera( "Default", glm::lookAt( glm::vec3(0.0f, 15.0f, 40.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) ), glm::perspective(45.0f, (GLfloat)WINDOW_WIDTH/(GLfloat)WINDOW_HEIGHT, 10.0f, GRASS_FIELD_SIZE) ); // Create a forward rendering pipeline. L3DHandle renderQueue = l3dLoadForwardRenderQueue(WINDOW_WIDTH, WINDOW_HEIGHT, L3DVec4(0, 0, 0.05f, 1)); // ---------------------------- RENDERING ------------------------------ // while(!glfwWindowShouldClose(window)) { // Poll window events. glfwPollEvents(); // Render current frame. l3dRenderFrame(camera, renderQueue); // Apply a rotation to the camera. float sinOfTime = sin(glfwGetTime()); l3dRotateCamera(camera, (0.5f + sinOfTime * 0.5f) * 0.01f, L3DVec3(0.0f, 1.0f, 0.0f)); // Swap buffers. glfwSwapBuffers(window); } // ---------------------------- TERMINATE ----------------------------- // // Terminate leaf3dut. l3dutTerminate(); // Terminate leaf3d. l3dTerminate(); // Terminate GLFW. glfwTerminate(); return 0; } <commit_msg>Improve performances<commit_after>/* * This file is part of the leaf3d project. * * Copyright 2014-2015 Emanuele Bertoldi. All rights reserved. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * You should have received a copy of the modified BSD License along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license.php> */ #include <stdio.h> #include <leaf3d/leaf3d.h> #include <leaf3d/leaf3dut.h> #include <glad/glad.h> #include <GLFW/glfw3.h> #define WINDOW_WIDTH 1024 #define WINDOW_HEIGHT 768 #define GRASS_DENSITY 200 #define GRASS_COLOR L3DVec3(0.67f,0.68f,0.41f) #define GRASS_COLOR_VAR L3DVec3(0.1f,0.08f,0.15f) #define GRASS_HEIGHT 1.0f #define GRASS_HEIGHT_VAR 4.0f #define GRASS_FIELD_SIZE 1000.0f #define GRASS_DISTANCE_LOD3 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 1.0f #define GRASS_DISTANCE_LOD2 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 0.4f #define GRASS_DISTANCE_LOD1 GRASS_FIELD_SIZE * GRASS_HEIGHT * 0.5 * 0.3f using namespace l3d; int main() { // -------------------------------- INIT ------------------------------- // // Init GLFW. if (glfwInit() != GL_TRUE) { fprintf(stderr, "Failed to initialize GLFW\n"); return -1; } // Create a rendering window with OpenGL 3.2 context. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "leaf3d", L3D_NULLPTR, L3D_NULLPTR); glfwMakeContextCurrent(window); // Init leaf3d. if (l3dInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3d\n"); return -2; } // Init leaf3dut. if (l3dutInit() != L3D_TRUE) { fprintf(stderr, "Failed to initialize leaf3dut\n"); return -3; } // ----------------------------- RESOURCES ----------------------------- // // Load a shader program with support for lighting (Blinn-Phong). L3DHandle blinnPhongShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/blinnphong.frag"); // Load a shader program for sky box. L3DHandle skyBoxShaderProgram = l3dutLoadShaderProgram("Shaders/skyBox.vert", "Shaders/skyBox.frag"); // Load a shader program for grass plane rendering. L3DHandle grassPlaneShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/grassPlane.frag"); // Load a shader program for realistic grass blades rendering. L3DHandle grassBladesShaderProgram = l3dutLoadShaderProgram("Shaders/basic.vert", "Shaders/grassBlades.frag", "Shaders/grassBlades.geom"); // Load a sky box. L3DHandle skyBoxCubeMap = l3dutLoadTextureCube( "Textures/SkyBox2/right.jpg", "Textures/SkyBox2/left.jpg", "Textures/SkyBox2/top.jpg", "Textures/SkyBox2/bottom.jpg", "Textures/SkyBox2/back.jpg", "Textures/SkyBox2/front.jpg" ); L3DHandle skyBoxMaterial = l3dLoadMaterial("skyBoxMaterial", skyBoxShaderProgram); l3dAddTextureToMaterial(skyBoxMaterial, "cubeMap", skyBoxCubeMap); L3DHandle skyBox = l3dLoadSkyBox(skyBoxMaterial); // Load a grass plane. L3DHandle grassTexture = l3dutLoadTexture2D("Textures/Grass/grass_diffuse.jpg"); L3DHandle grassPlaneMaterial = l3dLoadMaterial("grassPlaneMaterial", grassPlaneShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassPlaneMaterial, "diffuseMap", grassTexture); L3DHandle grassPlane = l3dLoadGrid(1, grassPlaneMaterial, L3DVec2(40, 40), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassPlane, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassPlane, L3DVec3(GRASS_FIELD_SIZE, GRASS_FIELD_SIZE, 1)); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2); l3dSetShaderProgramUniformF(grassPlaneShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1); // Load grass blades. L3DHandle grassBladesTexture = l3dutLoadTexture2D("Textures/Grass/grass_blade_diffuse.png"); L3DHandle grassBladesMaterial = l3dLoadMaterial("grassBladeMaterial", grassBladesShaderProgram, GRASS_COLOR); l3dAddTextureToMaterial(grassBladesMaterial, "diffuseMap", grassBladesTexture); L3DHandle grassBlades = l3dLoadGrid(GRASS_DENSITY, grassBladesMaterial, L3DVec2(1, 1), L3D_ALPHA_BLEND_MESH_RENDERLAYER); l3dRotateMesh(grassBlades, 1.57f, L3DVec3(-1, 0, 0)); l3dScaleMesh(grassBlades, L3DVec3(GRASS_FIELD_SIZE * 0.5, GRASS_FIELD_SIZE * 0.5, 1)); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD3", GRASS_DISTANCE_LOD3 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD2", GRASS_DISTANCE_LOD2 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassDistanceLOD1", GRASS_DISTANCE_LOD1 * 0.75f); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeight", GRASS_HEIGHT); l3dSetShaderProgramUniformF(grassBladesShaderProgram, "u_grassHeightVariation", GRASS_HEIGHT_VAR); l3dSetShaderProgramUniformVec3(grassBladesShaderProgram, "u_grassColorVariation", GRASS_COLOR_VAR); // Load a crate. L3DHandle crateTexture = l3dutLoadTexture2D("Textures/Crate/crate.png"); L3DHandle crateSpecTexture = l3dutLoadTexture2D("Textures/Crate/crate_spec.png"); L3DHandle crateNormTexture = l3dutLoadTexture2D("Textures/Crate/crate_norm.png"); L3DHandle crateMaterial = l3dLoadMaterial("crateMaterial", blinnPhongShaderProgram); l3dAddTextureToMaterial(crateMaterial, "diffuseMap", crateTexture); l3dAddTextureToMaterial(crateMaterial, "specularMap", crateSpecTexture); l3dAddTextureToMaterial(crateMaterial, "normalMap", crateNormTexture); L3DHandle cube1 = l3dLoadCube(crateMaterial); l3dRotateMesh(cube1, 0.75f); l3dTranslateMesh(cube1, L3DVec3(10, 3, -20)); l3dScaleMesh(cube1, L3DVec3(6, 6, 6)); // Load a tree. unsigned int meshCount = 0; L3DHandle* tree = l3dutLoadMeshes("Models/tree1.obj", blinnPhongShaderProgram, &meshCount); for (int i=0; i<meshCount; ++i) { l3dRotateMesh(tree[i], 0.75f); l3dTranslateMesh(tree[i], L3DVec3(-45, 0, 20)); l3dScaleMesh(tree[i], L3DVec3(10, 10, 10)); } // Load a directional light. L3DVec4 sunLightColor = L3DVec4(0.8f, 0.7f, 0.6f, 1); L3DHandle sunLight = l3dLoadDirectionalLight(L3DVec3(-2, -1, 5), sunLightColor); // Set the global ambient light color. l3dSetShaderProgramUniformVec4(blinnPhongShaderProgram, "u_ambientColor", L3DVec4(0.8f, 0.8f, 1, 0.6f)); // Create a camera. L3DHandle camera = l3dLoadCamera( "Default", glm::lookAt( glm::vec3(0.0f, 15.0f, 40.0f), glm::vec3(0.0f, 5.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f) ), glm::perspective(45.0f, (GLfloat)WINDOW_WIDTH/(GLfloat)WINDOW_HEIGHT, 10.0f, GRASS_FIELD_SIZE) ); // Create a forward rendering pipeline. L3DHandle renderQueue = l3dLoadForwardRenderQueue(WINDOW_WIDTH, WINDOW_HEIGHT, L3DVec4(0, 0, 0.05f, 1)); // ---------------------------- RENDERING ------------------------------ // while(!glfwWindowShouldClose(window)) { // Poll window events. glfwPollEvents(); // Render current frame. l3dRenderFrame(camera, renderQueue); // Apply a rotation to the camera. float sinOfTime = sin(glfwGetTime()); l3dRotateCamera(camera, (0.5f + sinOfTime * 0.5f) * 0.01f, L3DVec3(0.0f, 1.0f, 0.0f)); // Swap buffers. glfwSwapBuffers(window); } // ---------------------------- TERMINATE ----------------------------- // // Terminate leaf3dut. l3dutTerminate(); // Terminate leaf3d. l3dTerminate(); // Terminate GLFW. glfwTerminate(); return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rootitemcontainer.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 00:46:29 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ #define __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_HELPER_SHAREABLEMUTEX_HXX_ #include <helper/shareablemutex.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_ #include <com/sun/star/lang/XSingleComponentFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_OUSTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vector> namespace framework { class ConstItemContainer; class ItemContainer; class RootItemContainer : public ::com::sun::star::lang::XTypeProvider , public ::com::sun::star::container::XIndexContainer , public ::com::sun::star::lang::XSingleComponentFactory , public ::com::sun::star::lang::XUnoTunnel , protected ThreadHelpBase , public ::cppu::OBroadcastHelper , public ::cppu::OPropertySetHelper , public ::cppu::OWeakObject { friend class ConstItemContainer; public: RootItemContainer(); RootItemContainer( const ConstItemContainer& rConstItemContainer ); RootItemContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rItemAccessContainer ); virtual ~RootItemContainer(); //--------------------------------------------------------------------------------------------------------- // XInterface, XTypeProvider //--------------------------------------------------------------------------------------------------------- DECLARE_XINTERFACE DECLARE_XTYPEPROVIDER // XUnoTunnel static const ::com::sun::star::uno::Sequence< sal_Int8 >& GetUnoTunnelId() throw(); static RootItemContainer* GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw(); sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException); // XIndexContainer virtual void SAL_CALL insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByIndex( sal_Int32 Index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XIndexReplace virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XIndexAccess virtual sal_Int32 SAL_CALL getCount() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException) { return ::getCppuType((com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >*)0); } virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException); // XSingleComponentFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); protected: // OPropertySetHelper virtual sal_Bool SAL_CALL convertFastPropertyValue ( com::sun::star::uno::Any& aConvertedValue , com::sun::star::uno::Any& aOldValue , sal_Int32 nHandle , const com::sun::star::uno::Any& aValue ) throw( com::sun::star::lang::IllegalArgumentException ); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle , const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ); virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue , sal_Int32 nHandle ) const; virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > impl_getStaticPropertyDescriptor(); private: RootItemContainer& operator=( const RootItemContainer& ); RootItemContainer( const RootItemContainer& ); void copyItemContainer( const std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rSourceVector ); com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > deepCopyContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSubContainer ); mutable ShareableMutex m_aShareMutex; std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > m_aItemVector; rtl::OUString m_aUIName; }; } #endif // #ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ <commit_msg>INTEGRATION: CWS warnings01 (1.5.32); FILE MERGED 2005/11/16 15:20:13 pl 1.5.32.2: #i55991# removed warnings 2005/10/28 14:48:21 cd 1.5.32.1: #i55991# Warning free code changes for gcc<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rootitemcontainer.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2006-06-19 11:05:23 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ #define __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_THREADHELP_THREADHELPBASE_HXX_ #include <threadhelp/threadhelpbase.hxx> #endif #ifndef __FRAMEWORK_MACROS_GENERIC_HXX_ #include <macros/generic.hxx> #endif #ifndef __FRAMEWORK_MACROS_XINTERFACE_HXX_ #include <macros/xinterface.hxx> #endif #ifndef __FRAMEWORK_MACROS_XTYPEPROVIDER_HXX_ #include <macros/xtypeprovider.hxx> #endif #ifndef __FRAMEWORK_HELPER_SHAREABLEMUTEX_HXX_ #include <helper/shareablemutex.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_CONTAINER_XINDEXCONTAINER_HPP_ #include <com/sun/star/container/XIndexContainer.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XINDEXACCESS_HPP_ #include <com/sun/star/container/XIndexAccess.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSINGLECOMPONENTFACTORY_HPP_ #include <com/sun/star/lang/XSingleComponentFactory.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif //_________________________________________________________________________________________________________________ // other includes //_________________________________________________________________________________________________________________ #ifndef _RTL_OUSTRING_HXX_ #include <rtl/ustring.hxx> #endif #ifndef _CPPUHELPER_WEAK_HXX_ #include <cppuhelper/weak.hxx> #endif #ifndef _CPPUHELPER_PROPSHLP_HXX #include <cppuhelper/propshlp.hxx> #endif #ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_ #include <cppuhelper/interfacecontainer.hxx> #endif #include <vector> namespace framework { class ConstItemContainer; class ItemContainer; class RootItemContainer : public ::com::sun::star::lang::XTypeProvider , public ::com::sun::star::container::XIndexContainer , public ::com::sun::star::lang::XSingleComponentFactory , public ::com::sun::star::lang::XUnoTunnel , protected ThreadHelpBase , public ::cppu::OBroadcastHelper , public ::cppu::OPropertySetHelper , public ::cppu::OWeakObject { friend class ConstItemContainer; public: RootItemContainer(); RootItemContainer( const ConstItemContainer& rConstItemContainer ); RootItemContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rItemAccessContainer ); virtual ~RootItemContainer(); //--------------------------------------------------------------------------------------------------------- // XInterface, XTypeProvider //--------------------------------------------------------------------------------------------------------- FWK_DECLARE_XINTERFACE FWK_DECLARE_XTYPEPROVIDER // XUnoTunnel static const ::com::sun::star::uno::Sequence< sal_Int8 >& GetUnoTunnelId() throw(); static RootItemContainer* GetImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw(); sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rIdentifier ) throw(::com::sun::star::uno::RuntimeException); // XIndexContainer virtual void SAL_CALL insertByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL removeByIndex( sal_Int32 Index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XIndexReplace virtual void SAL_CALL replaceByIndex( sal_Int32 Index, const ::com::sun::star::uno::Any& Element ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XIndexAccess virtual sal_Int32 SAL_CALL getCount() throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getByIndex( sal_Int32 Index ) throw (::com::sun::star::lang::IndexOutOfBoundsException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XElementAccess virtual ::com::sun::star::uno::Type SAL_CALL getElementType() throw (::com::sun::star::uno::RuntimeException) { return ::getCppuType((com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue >*)0); } virtual sal_Bool SAL_CALL hasElements() throw (::com::sun::star::uno::RuntimeException); // XSingleComponentFactory virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithContext( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createInstanceWithArgumentsAndContext( const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >& Arguments, const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XComponentContext >& Context ) throw (::com::sun::star::uno::Exception, ::com::sun::star::uno::RuntimeException); protected: // OPropertySetHelper virtual sal_Bool SAL_CALL convertFastPropertyValue ( com::sun::star::uno::Any& aConvertedValue , com::sun::star::uno::Any& aOldValue , sal_Int32 nHandle , const com::sun::star::uno::Any& aValue ) throw( com::sun::star::lang::IllegalArgumentException ); virtual void SAL_CALL setFastPropertyValue_NoBroadcast( sal_Int32 nHandle , const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception ); using cppu::OPropertySetHelper::getFastPropertyValue; virtual void SAL_CALL getFastPropertyValue( com::sun::star::uno::Any& aValue , sal_Int32 nHandle ) const; virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper(); virtual ::com::sun::star::uno::Reference< com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo() throw (::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property > impl_getStaticPropertyDescriptor(); private: RootItemContainer& operator=( const RootItemContainer& ); RootItemContainer( const RootItemContainer& ); void copyItemContainer( const std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > >& rSourceVector ); com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess > deepCopyContainer( const com::sun::star::uno::Reference< com::sun::star::container::XIndexAccess >& rSubContainer ); mutable ShareableMutex m_aShareMutex; std::vector< com::sun::star::uno::Sequence< com::sun::star::beans::PropertyValue > > m_aItemVector; rtl::OUString m_aUIName; }; } #endif // #ifndef __FRAMEWORK_UIELEMENT_ROOTITEMCONTAINER_HXX_ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: toolboxfactory.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2005-03-01 19:47:18 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UIELEMENT_TOOLBARWRAPPER_HXX_ #include <uielement/toolbarwrapper.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPLLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace ::com::sun::star::ui; namespace framework { //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3 ( ToolBoxFactory , OWeakObject , DIRECT_INTERFACE( css::lang::XTypeProvider ), DIRECT_INTERFACE( css::lang::XServiceInfo ), DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementFactory ) ) DEFINE_XTYPEPROVIDER_3 ( ToolBoxFactory , css::lang::XTypeProvider , css::lang::XServiceInfo , ::com::sun::star::ui::XUIElementFactory ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( ToolBoxFactory , ::cppu::OWeakObject , SERVICENAME_TOOLBARFACTORY , IMPLEMENTATIONNAME_TOOLBARFACTORY ) DEFINE_INIT_SERVICE ( ToolBoxFactory, {} ) ToolBoxFactory::ToolBoxFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : ThreadHelpBase( &Application::GetSolarMutex() ) , m_xServiceManager( xServiceManager ) , m_xModuleManager( xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.ModuleManager" ))), UNO_QUERY ) { } ToolBoxFactory::~ToolBoxFactory() { } // XUIElementFactory Reference< XUIElement > SAL_CALL ToolBoxFactory::createUIElement( const ::rtl::OUString& ResourceURL, const Sequence< PropertyValue >& Args ) throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ) { // SAFE ResetableGuard aLock( m_aLock ); Reference< XUIConfigurationManager > xConfigSource; Reference< XFrame > xFrame; rtl::OUString aResourceURL( ResourceURL ); sal_Bool bPersistent( sal_True ); sal_Bool bMenuOnly( sal_False ); for ( sal_Int32 n = 0; n < Args.getLength(); n++ ) { if ( Args[n].Name.equalsAscii( "ConfigurationSource" )) Args[n].Value >>= xConfigSource; else if ( Args[n].Name.equalsAscii( "Frame" )) Args[n].Value >>= xFrame; else if ( Args[n].Name.equalsAscii( "ResourceURL" )) Args[n].Value >>= aResourceURL; else if ( Args[n].Name.equalsAscii( "Persistent" )) Args[n].Value >>= bPersistent; } Reference< XUIConfigurationManager > xCfgMgr; if ( aResourceURL.indexOf( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/" ))) != 0 ) throw IllegalArgumentException(); else { // Identify frame and determine document based ui configuration manager/module ui configuration manager if ( xFrame.is() && !xConfigSource.is() ) { bool bHasSettings( false ); Reference< XModel > xModel; Reference< XController > xController = xFrame->getController(); if ( xController.is() ) xModel = xController->getModel(); if ( xModel.is() ) { Reference< XUIConfigurationManagerSupplier > xUIConfigurationManagerSupplier( xModel, UNO_QUERY ); if ( xUIConfigurationManagerSupplier.is() ) { xCfgMgr = xUIConfigurationManagerSupplier->getUIConfigurationManager(); bHasSettings = xCfgMgr->hasSettings( aResourceURL ); } } if ( !bHasSettings ) { rtl::OUString aModuleIdentifier = m_xModuleManager->identify( Reference< XInterface >( xFrame, UNO_QUERY )); if ( aModuleIdentifier.getLength() ) { Reference< ::com::sun::star::ui::XModuleUIConfigurationManagerSupplier > xModuleCfgSupplier( m_xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))), UNO_QUERY ); xCfgMgr = xModuleCfgSupplier->getUIConfigurationManager( aModuleIdentifier ); bHasSettings = xCfgMgr->hasSettings( aResourceURL ); } } } } PropertyValue aPropValue; Sequence< Any > aPropSeq( 4 ); aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Frame" )); aPropValue.Value <<= xFrame; aPropSeq[0] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ConfigurationSource" )); aPropValue.Value <<= xCfgMgr; aPropSeq[1] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" )); aPropValue.Value <<= aResourceURL; aPropSeq[2] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" )); aPropValue.Value <<= bPersistent; aPropSeq[3] <<= aPropValue; vos::OGuard aGuard( Application::GetSolarMutex() ); ToolBarWrapper* pToolBarWrapper = new ToolBarWrapper( m_xServiceManager ); Reference< ::com::sun::star::ui::XUIElement > xToolBar( (OWeakObject *)pToolBarWrapper, UNO_QUERY ); Reference< XInitialization > xInit( xToolBar, UNO_QUERY ); xInit->initialize( aPropSeq ); return xToolBar; } } <commit_msg>INTEGRATION: CWS ooo19126 (1.3.128); FILE MERGED 2005/09/05 13:07:20 rt 1.3.128.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: toolboxfactory.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 02:01:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef __FRAMEWORK_UIFACTORY_TOOLBOXFACTORY_HXX_ #include <uifactory/toolboxfactory.hxx> #endif //_________________________________________________________________________________________________________________ // my own includes //_________________________________________________________________________________________________________________ #ifndef __FRAMEWORK_UIELEMENT_TOOLBARWRAPPER_HXX_ #include <uielement/toolbarwrapper.hxx> #endif #ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_ #include <threadhelp/resetableguard.hxx> #endif //_________________________________________________________________________________________________________________ // interface includes //_________________________________________________________________________________________________________________ #ifndef _COM_SUN_STAR_UTIL_XURLTRANSFORMER_HPP_ #include <com/sun/star/util/XURLTransformer.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XFRAME_HPP_ #include <com/sun/star/frame/XFrame.hpp> #endif #ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_ #include <com/sun/star/frame/XModel.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XINITIALIZATION_HPP_ #include <com/sun/star/lang/XInitialization.hpp> #endif #ifndef _COM_SUN_STAR_UI_XMODULEUICONFIGURATIONMANAGERSUPPLIER_HPP_ #include <com/sun/star/ui/XModuleUIConfigurationManagerSupplier.hpp> #endif #ifndef _COM_SUN_STAR_UI_XUICONFIGURATIONMANAGERSUPLLIER_HPP_ #include <com/sun/star/ui/XUIConfigurationManagerSupplier.hpp> #endif //_________________________________________________________________________________________________________________ // includes of other projects //_________________________________________________________________________________________________________________ #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _URLOBJ_HXX #include <tools/urlobj.hxx> #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif //_________________________________________________________________________________________________________________ // Defines //_________________________________________________________________________________________________________________ // using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace ::com::sun::star::ui; namespace framework { //***************************************************************************************************************** // XInterface, XTypeProvider, XServiceInfo //***************************************************************************************************************** DEFINE_XINTERFACE_3 ( ToolBoxFactory , OWeakObject , DIRECT_INTERFACE( css::lang::XTypeProvider ), DIRECT_INTERFACE( css::lang::XServiceInfo ), DIRECT_INTERFACE( ::com::sun::star::ui::XUIElementFactory ) ) DEFINE_XTYPEPROVIDER_3 ( ToolBoxFactory , css::lang::XTypeProvider , css::lang::XServiceInfo , ::com::sun::star::ui::XUIElementFactory ) DEFINE_XSERVICEINFO_ONEINSTANCESERVICE ( ToolBoxFactory , ::cppu::OWeakObject , SERVICENAME_TOOLBARFACTORY , IMPLEMENTATIONNAME_TOOLBARFACTORY ) DEFINE_INIT_SERVICE ( ToolBoxFactory, {} ) ToolBoxFactory::ToolBoxFactory( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : ThreadHelpBase( &Application::GetSolarMutex() ) , m_xServiceManager( xServiceManager ) , m_xModuleManager( xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.frame.ModuleManager" ))), UNO_QUERY ) { } ToolBoxFactory::~ToolBoxFactory() { } // XUIElementFactory Reference< XUIElement > SAL_CALL ToolBoxFactory::createUIElement( const ::rtl::OUString& ResourceURL, const Sequence< PropertyValue >& Args ) throw ( ::com::sun::star::container::NoSuchElementException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException ) { // SAFE ResetableGuard aLock( m_aLock ); Reference< XUIConfigurationManager > xConfigSource; Reference< XFrame > xFrame; rtl::OUString aResourceURL( ResourceURL ); sal_Bool bPersistent( sal_True ); sal_Bool bMenuOnly( sal_False ); for ( sal_Int32 n = 0; n < Args.getLength(); n++ ) { if ( Args[n].Name.equalsAscii( "ConfigurationSource" )) Args[n].Value >>= xConfigSource; else if ( Args[n].Name.equalsAscii( "Frame" )) Args[n].Value >>= xFrame; else if ( Args[n].Name.equalsAscii( "ResourceURL" )) Args[n].Value >>= aResourceURL; else if ( Args[n].Name.equalsAscii( "Persistent" )) Args[n].Value >>= bPersistent; } Reference< XUIConfigurationManager > xCfgMgr; if ( aResourceURL.indexOf( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "private:resource/toolbar/" ))) != 0 ) throw IllegalArgumentException(); else { // Identify frame and determine document based ui configuration manager/module ui configuration manager if ( xFrame.is() && !xConfigSource.is() ) { bool bHasSettings( false ); Reference< XModel > xModel; Reference< XController > xController = xFrame->getController(); if ( xController.is() ) xModel = xController->getModel(); if ( xModel.is() ) { Reference< XUIConfigurationManagerSupplier > xUIConfigurationManagerSupplier( xModel, UNO_QUERY ); if ( xUIConfigurationManagerSupplier.is() ) { xCfgMgr = xUIConfigurationManagerSupplier->getUIConfigurationManager(); bHasSettings = xCfgMgr->hasSettings( aResourceURL ); } } if ( !bHasSettings ) { rtl::OUString aModuleIdentifier = m_xModuleManager->identify( Reference< XInterface >( xFrame, UNO_QUERY )); if ( aModuleIdentifier.getLength() ) { Reference< ::com::sun::star::ui::XModuleUIConfigurationManagerSupplier > xModuleCfgSupplier( m_xServiceManager->createInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.ui.ModuleUIConfigurationManagerSupplier" ))), UNO_QUERY ); xCfgMgr = xModuleCfgSupplier->getUIConfigurationManager( aModuleIdentifier ); bHasSettings = xCfgMgr->hasSettings( aResourceURL ); } } } } PropertyValue aPropValue; Sequence< Any > aPropSeq( 4 ); aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Frame" )); aPropValue.Value <<= xFrame; aPropSeq[0] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ConfigurationSource" )); aPropValue.Value <<= xCfgMgr; aPropSeq[1] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "ResourceURL" )); aPropValue.Value <<= aResourceURL; aPropSeq[2] <<= aPropValue; aPropValue.Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "Persistent" )); aPropValue.Value <<= bPersistent; aPropSeq[3] <<= aPropValue; vos::OGuard aGuard( Application::GetSolarMutex() ); ToolBarWrapper* pToolBarWrapper = new ToolBarWrapper( m_xServiceManager ); Reference< ::com::sun::star::ui::XUIElement > xToolBar( (OWeakObject *)pToolBarWrapper, UNO_QUERY ); Reference< XInitialization > xInit( xToolBar, UNO_QUERY ); xInit->initialize( aPropSeq ); return xToolBar; } } <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ComputeElemAuxVarsThread.h" #include "AuxiliarySystem.h" #include "AuxKernel.h" #include "FEProblem.h" // libmesh includes #include "libmesh/threads.h" ComputeElemAuxVarsThread::ComputeElemAuxVarsThread(FEProblem & problem, AuxiliarySystem & sys, std::vector<AuxWarehouse> & auxs) : ThreadedElementLoop<ConstElemRange>(problem, sys), _aux_sys(sys), _auxs(auxs) { } // Splitting Constructor ComputeElemAuxVarsThread::ComputeElemAuxVarsThread(ComputeElemAuxVarsThread & x, Threads::split /*split*/) : ThreadedElementLoop<ConstElemRange>(x._fe_problem, x._system), _aux_sys(x._aux_sys), _auxs(x._auxs) { } ComputeElemAuxVarsThread::~ComputeElemAuxVarsThread() { } void ComputeElemAuxVarsThread::subdomainChanged() { // prepare variables for (std::map<std::string, MooseVariable *>::iterator it = _aux_sys._elem_vars[_tid].begin(); it != _aux_sys._elem_vars[_tid].end(); ++it) { MooseVariable * var = it->second; var->prepareAux(); } // TODO: No subdomain setup for block elemental aux-kernels? for(std::vector<AuxKernel *>::const_iterator aux_it=_auxs[_tid].activeElementKernels().begin(); aux_it != _auxs[_tid].activeElementKernels().end(); aux_it++) (*aux_it)->subdomainSetup(); std::set<MooseVariable *> needed_moose_vars; // block for(std::vector<AuxKernel*>::const_iterator block_element_aux_it = _auxs[_tid].activeBlockElementKernels(_subdomain).begin(); block_element_aux_it != _auxs[_tid].activeBlockElementKernels(_subdomain).end(); ++block_element_aux_it) { const std::set<MooseVariable *> & mv_deps = (*block_element_aux_it)->getMooseVariableDependencies(); needed_moose_vars.insert(mv_deps.begin(), mv_deps.end()); } // global for(std::vector<AuxKernel *>::const_iterator aux_it = _auxs[_tid].activeElementKernels().begin(); aux_it!=_auxs[_tid].activeElementKernels().end(); aux_it++) { const std::set<MooseVariable *> & mv_deps = (*aux_it)->getMooseVariableDependencies(); needed_moose_vars.insert(mv_deps.begin(), mv_deps.end()); } _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid); _fe_problem.prepareMaterials(_subdomain, _tid); } void ComputeElemAuxVarsThread::onElement(const Elem * elem) { if(_auxs[_tid].activeBlockElementKernels(_subdomain).size() > 0 || _auxs[_tid].activeElementKernels().size() > 0) { _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); _fe_problem.reinitMaterials(elem->subdomain_id(), _tid); // block for(std::vector<AuxKernel*>::const_iterator block_element_aux_it = _auxs[_tid].activeBlockElementKernels(_subdomain).begin(); block_element_aux_it != _auxs[_tid].activeBlockElementKernels(_subdomain).end(); ++block_element_aux_it) (*block_element_aux_it)->compute(); // global for(std::vector<AuxKernel *>::const_iterator aux_it = _auxs[_tid].activeElementKernels().begin(); aux_it!=_auxs[_tid].activeElementKernels().end(); aux_it++) (*aux_it)->compute(); _fe_problem.swapBackMaterials(_tid); // update the solution vector { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (std::map<std::string, MooseVariable *>::iterator it = _aux_sys._elem_vars[_tid].begin(); it != _aux_sys._elem_vars[_tid].end(); ++it) { MooseVariable * var = it->second; var->insert(_system.solution()); } } } } void ComputeElemAuxVarsThread::post() { _fe_problem.clearActiveElementalMooseVariables(_tid); } void ComputeElemAuxVarsThread::join(const ComputeElemAuxVarsThread & /*y*/) { } <commit_msg>Call subdomain setup on block restricted element aux kernels - closes #2391<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "ComputeElemAuxVarsThread.h" #include "AuxiliarySystem.h" #include "AuxKernel.h" #include "FEProblem.h" // libmesh includes #include "libmesh/threads.h" ComputeElemAuxVarsThread::ComputeElemAuxVarsThread(FEProblem & problem, AuxiliarySystem & sys, std::vector<AuxWarehouse> & auxs) : ThreadedElementLoop<ConstElemRange>(problem, sys), _aux_sys(sys), _auxs(auxs) { } // Splitting Constructor ComputeElemAuxVarsThread::ComputeElemAuxVarsThread(ComputeElemAuxVarsThread & x, Threads::split /*split*/) : ThreadedElementLoop<ConstElemRange>(x._fe_problem, x._system), _aux_sys(x._aux_sys), _auxs(x._auxs) { } ComputeElemAuxVarsThread::~ComputeElemAuxVarsThread() { } void ComputeElemAuxVarsThread::subdomainChanged() { // prepare variables for (std::map<std::string, MooseVariable *>::iterator it = _aux_sys._elem_vars[_tid].begin(); it != _aux_sys._elem_vars[_tid].end(); ++it) { MooseVariable * var = it->second; var->prepareAux(); } // block setup for(std::vector<AuxKernel *>::const_iterator aux_it=_auxs[_tid].activeBlockElementKernels(_subdomain).begin(); aux_it != _auxs[_tid].activeBlockElementKernels(_subdomain).end(); aux_it++) (*aux_it)->subdomainSetup(); // global setup for(std::vector<AuxKernel *>::const_iterator aux_it=_auxs[_tid].activeElementKernels().begin(); aux_it != _auxs[_tid].activeElementKernels().end(); aux_it++) (*aux_it)->subdomainSetup(); std::set<MooseVariable *> needed_moose_vars; // block for(std::vector<AuxKernel*>::const_iterator block_element_aux_it = _auxs[_tid].activeBlockElementKernels(_subdomain).begin(); block_element_aux_it != _auxs[_tid].activeBlockElementKernels(_subdomain).end(); ++block_element_aux_it) { const std::set<MooseVariable *> & mv_deps = (*block_element_aux_it)->getMooseVariableDependencies(); needed_moose_vars.insert(mv_deps.begin(), mv_deps.end()); } // global for(std::vector<AuxKernel *>::const_iterator aux_it = _auxs[_tid].activeElementKernels().begin(); aux_it!=_auxs[_tid].activeElementKernels().end(); aux_it++) { const std::set<MooseVariable *> & mv_deps = (*aux_it)->getMooseVariableDependencies(); needed_moose_vars.insert(mv_deps.begin(), mv_deps.end()); } _fe_problem.setActiveElementalMooseVariables(needed_moose_vars, _tid); _fe_problem.prepareMaterials(_subdomain, _tid); } void ComputeElemAuxVarsThread::onElement(const Elem * elem) { if(_auxs[_tid].activeBlockElementKernels(_subdomain).size() > 0 || _auxs[_tid].activeElementKernels().size() > 0) { _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); _fe_problem.reinitMaterials(elem->subdomain_id(), _tid); // block for(std::vector<AuxKernel*>::const_iterator block_element_aux_it = _auxs[_tid].activeBlockElementKernels(_subdomain).begin(); block_element_aux_it != _auxs[_tid].activeBlockElementKernels(_subdomain).end(); ++block_element_aux_it) (*block_element_aux_it)->compute(); // global for(std::vector<AuxKernel *>::const_iterator aux_it = _auxs[_tid].activeElementKernels().begin(); aux_it!=_auxs[_tid].activeElementKernels().end(); aux_it++) (*aux_it)->compute(); _fe_problem.swapBackMaterials(_tid); // update the solution vector { Threads::spin_mutex::scoped_lock lock(Threads::spin_mtx); for (std::map<std::string, MooseVariable *>::iterator it = _aux_sys._elem_vars[_tid].begin(); it != _aux_sys._elem_vars[_tid].end(); ++it) { MooseVariable * var = it->second; var->insert(_system.solution()); } } } } void ComputeElemAuxVarsThread::post() { _fe_problem.clearActiveElementalMooseVariables(_tid); } void ComputeElemAuxVarsThread::join(const ComputeElemAuxVarsThread & /*y*/) { } <|endoftext|>
<commit_before>#pragma once // We use ostream for logging purposes. #include <iostream> // NOLINT(readability/streams) #include <limits> #include <string> #include <type_traits> #include "base/not_null.hpp" #include "serialization/quantities.pb.h" namespace principia { using base::not_null; namespace quantities { template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent, int64_t CurrentExponent, int64_t TemperatureExponent, int64_t AmountExponent, int64_t LuminousIntensityExponent, int64_t WindingExponent, int64_t AngleExponent, int64_t SolidAngleExponent> struct Dimensions; template<typename D> class Quantity; using NoDimensions = Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 0>; // Base quantities using Length = Quantity<Dimensions<1, 0, 0, 0, 0, 0, 0, 0, 0, 0>>; using Mass = Quantity<Dimensions<0, 1, 0, 0, 0, 0, 0, 0, 0, 0>>; using Time = Quantity<Dimensions<0, 0, 1, 0, 0, 0, 0, 0, 0, 0>>; using Current = Quantity<Dimensions<0, 0, 0, 1, 0, 0, 0, 0, 0, 0>>; using Temperature = Quantity<Dimensions<0, 0, 0, 0, 1, 0, 0, 0, 0, 0>>; using Amount = Quantity<Dimensions<0, 0, 0, 0, 0, 1, 0, 0, 0, 0>>; using LuminousIntensity = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 1, 0, 0, 0>>; // Nonstandard; winding is a dimensionless quantity counting cycles, in order to // strongly type the distinction between Frequency = Winding/Time and // AngularFrequency = Angle/Time. We also strongly type angles. using Winding = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 1, 0, 0>>; using Angle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 1, 0>>; using SolidAngle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>; namespace internal { template<typename Left, typename Right> struct ProductGenerator; template<typename Left, typename Right> struct QuotientGenerator; template<int n, typename Q, typename = void> struct NthRootGenerator; template<typename T, int exponent, typename = void> struct ExponentiationGenerator; template<typename Left, typename Right> using Product = typename ProductGenerator<Left, Right>::Type; template<typename Left, typename Right> using Quotient = typename QuotientGenerator<Left, Right>::Type; } // namespace internal // The result type of +, -, * and / on arguments of types |Left| and |Right|. template<typename Left, typename Right> using Sum = decltype(std::declval<Left>() = std::declval<Right>()); template<typename Left, typename Right = Left> using Difference = decltype(std::declval<Left>() - std::declval<Right>()); template<typename Left, typename Right> using Product = decltype(std::declval<Left>() * std::declval<Right>()); template<typename Left, typename Right> using Quotient = decltype(std::declval<Left>() / std::declval<Right>()); // |Exponentiation<T, n>| is an alias for the following, where t is a value of // type |T|: // The type of ( ... (t * t) * ... * t), with n factors, if n >= 1; // The type of t / ( ... (t * t) * ... * t), with n + 1 factors in the // denominator, if n < 1. template<typename T, int exponent> using Exponentiation = typename internal::ExponentiationGenerator<T, exponent>::Type; // |SquareRoot<T>| is only defined if |T| is an instance of |Quantity| with only // even dimensions. In that case, it is the unique instance |S| of |Quantity| // such that |Product<S, S>| is |T|. template<int n, typename Q> using NthRoot = typename internal::NthRootGenerator<n, Q>::Type; template<typename Q> using SquareRoot = NthRoot<2, Q>; template<typename Q> using CubeRoot = NthRoot<3, Q>; // Returns the base or derived SI Unit of |Q|. // For instance, |SIUnit<Action>() == Joule * Second|. template<typename Q> constexpr Q SIUnit(); // Returns 1. template<> constexpr double SIUnit<double>(); template<typename LDimensions, typename RDimensions> constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*(Quantity<LDimensions> const&, Quantity<RDimensions> const&); template<typename LDimensions, typename RDimensions> constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/(Quantity<LDimensions> const&, Quantity<RDimensions> const&); template<typename RDimensions> constexpr Quantity<RDimensions> operator*(double const, Quantity<RDimensions> const&); template<typename RDimensions> constexpr typename Quantity<RDimensions>::Inverse operator/(double const, Quantity<RDimensions> const&); // Equivalent to |std::pow(x, exponent)| unless -3 ≤ x ≤ 3, in which case // explicit specialization yields multiplications statically. template<int exponent> constexpr double Pow(double x); template<int exponent, typename D> constexpr Exponentiation<Quantity<D>, exponent> Pow(Quantity<D> const& x); template<typename D> std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity); // Equivalent to |std::abs(x)|. double Abs(double const x); template<typename D> Quantity<D> Abs(Quantity<D> const& x); template<typename D> SquareRoot<Quantity<D>> Sqrt(Quantity<D> const& x); template<typename D> Angle ArcTan(Quantity<D> const& y, Quantity<D> const& x); std::string DebugString( double const number, int const precision = std::numeric_limits<double>::max_digits10); template<typename D> std::string DebugString( Quantity<D> const& quantity, int const precision = std::numeric_limits<double>::max_digits10); template<typename D> class Quantity { public: using Dimensions = D; using Inverse = internal::Quotient<double, Quantity>; constexpr Quantity(); ~Quantity() = default; constexpr Quantity operator+() const; constexpr Quantity operator-() const; constexpr Quantity operator+(Quantity const& right) const; constexpr Quantity operator-(Quantity const& right) const; constexpr Quantity operator*(double const right) const; constexpr Quantity operator/(double const right) const; Quantity& operator+=(Quantity const&); Quantity& operator-=(Quantity const&); Quantity& operator*=(double const); Quantity& operator/=(double const); constexpr bool operator>(Quantity const& right) const; constexpr bool operator<(Quantity const& right) const; constexpr bool operator>=(Quantity const& right) const; constexpr bool operator<=(Quantity const& right) const; constexpr bool operator==(Quantity const& right) const; constexpr bool operator!=(Quantity const& right) const; void WriteToMessage(not_null<serialization::Quantity*> const message) const; static Quantity ReadFromMessage(serialization::Quantity const& message); private: explicit constexpr Quantity(double const magnitude); double magnitude_; template<typename LDimensions, typename RDimensions> friend constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right); template<typename LDimensions, typename RDimensions> friend constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right); template<typename RDimensions> friend constexpr Quantity<RDimensions> operator*( double const left, Quantity<RDimensions> const& right); template<typename RDimensions> friend constexpr typename Quantity<RDimensions>::Inverse operator/( double const left, Quantity<RDimensions> const& right); template<typename Q> friend constexpr Q SIUnit(); template<int exponent, typename BaseDimensions> friend constexpr Exponentiation<Quantity<BaseDimensions>, exponent> Pow( Quantity<BaseDimensions> const& x); template<typename E> friend Quantity<E> Abs(Quantity<E> const&); template<typename ArgumentDimensions> friend SquareRoot<Quantity<ArgumentDimensions>> Sqrt( Quantity<ArgumentDimensions> const& x); template<typename ArgumentDimensions> friend CubeRoot<Quantity<ArgumentDimensions>> Cbrt( Quantity<ArgumentDimensions> const& x); friend Angle ArcTan<>(Quantity<D> const& y, Quantity<D> const& x); friend std::string DebugString<>(Quantity<D> const&, int const); }; // A type trait for testing if a type is a quantity. template<typename T> struct is_quantity : std::is_floating_point<T> {}; template<typename D> struct is_quantity<Quantity<D>> : std::true_type {}; } // namespace quantities } // namespace principia #include "quantities/quantities_body.hpp" <commit_msg>define types that have a default template parameters, don't just declare and specialize.<commit_after>#pragma once // We use ostream for logging purposes. #include <iostream> // NOLINT(readability/streams) #include <limits> #include <string> #include <type_traits> #include "base/not_null.hpp" #include "serialization/quantities.pb.h" namespace principia { using base::not_null; namespace quantities { template<int64_t LengthExponent, int64_t MassExponent, int64_t TimeExponent, int64_t CurrentExponent, int64_t TemperatureExponent, int64_t AmountExponent, int64_t LuminousIntensityExponent, int64_t WindingExponent, int64_t AngleExponent, int64_t SolidAngleExponent> struct Dimensions; template<typename D> class Quantity; using NoDimensions = Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 0>; // Base quantities using Length = Quantity<Dimensions<1, 0, 0, 0, 0, 0, 0, 0, 0, 0>>; using Mass = Quantity<Dimensions<0, 1, 0, 0, 0, 0, 0, 0, 0, 0>>; using Time = Quantity<Dimensions<0, 0, 1, 0, 0, 0, 0, 0, 0, 0>>; using Current = Quantity<Dimensions<0, 0, 0, 1, 0, 0, 0, 0, 0, 0>>; using Temperature = Quantity<Dimensions<0, 0, 0, 0, 1, 0, 0, 0, 0, 0>>; using Amount = Quantity<Dimensions<0, 0, 0, 0, 0, 1, 0, 0, 0, 0>>; using LuminousIntensity = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 1, 0, 0, 0>>; // Nonstandard; winding is a dimensionless quantity counting cycles, in order to // strongly type the distinction between Frequency = Winding/Time and // AngularFrequency = Angle/Time. We also strongly type angles. using Winding = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 1, 0, 0>>; using Angle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 1, 0>>; using SolidAngle = Quantity<Dimensions<0, 0, 0, 0, 0, 0, 0, 0, 0, 1>>; namespace internal { template<typename Left, typename Right> struct ProductGenerator; template<typename Left, typename Right> struct QuotientGenerator; template <int n, typename Q, typename = void> struct NthRootGenerator {}; template <typename T, int exponent, typename = void> struct ExponentiationGenerator {}; template<typename Left, typename Right> using Product = typename ProductGenerator<Left, Right>::Type; template<typename Left, typename Right> using Quotient = typename QuotientGenerator<Left, Right>::Type; } // namespace internal // The result type of +, -, * and / on arguments of types |Left| and |Right|. template<typename Left, typename Right> using Sum = decltype(std::declval<Left>() = std::declval<Right>()); template<typename Left, typename Right = Left> using Difference = decltype(std::declval<Left>() - std::declval<Right>()); template<typename Left, typename Right> using Product = decltype(std::declval<Left>() * std::declval<Right>()); template<typename Left, typename Right> using Quotient = decltype(std::declval<Left>() / std::declval<Right>()); // |Exponentiation<T, n>| is an alias for the following, where t is a value of // type |T|: // The type of ( ... (t * t) * ... * t), with n factors, if n >= 1; // The type of t / ( ... (t * t) * ... * t), with n + 1 factors in the // denominator, if n < 1. template<typename T, int exponent> using Exponentiation = typename internal::ExponentiationGenerator<T, exponent>::Type; // |SquareRoot<T>| is only defined if |T| is an instance of |Quantity| with only // even dimensions. In that case, it is the unique instance |S| of |Quantity| // such that |Product<S, S>| is |T|. template<int n, typename Q> using NthRoot = typename internal::NthRootGenerator<n, Q>::Type; template<typename Q> using SquareRoot = NthRoot<2, Q>; template<typename Q> using CubeRoot = NthRoot<3, Q>; // Returns the base or derived SI Unit of |Q|. // For instance, |SIUnit<Action>() == Joule * Second|. template<typename Q> constexpr Q SIUnit(); // Returns 1. template<> constexpr double SIUnit<double>(); template<typename LDimensions, typename RDimensions> constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*(Quantity<LDimensions> const&, Quantity<RDimensions> const&); template<typename LDimensions, typename RDimensions> constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/(Quantity<LDimensions> const&, Quantity<RDimensions> const&); template<typename RDimensions> constexpr Quantity<RDimensions> operator*(double const, Quantity<RDimensions> const&); template<typename RDimensions> constexpr typename Quantity<RDimensions>::Inverse operator/(double const, Quantity<RDimensions> const&); // Equivalent to |std::pow(x, exponent)| unless -3 ≤ x ≤ 3, in which case // explicit specialization yields multiplications statically. template<int exponent> constexpr double Pow(double x); template<int exponent, typename D> constexpr Exponentiation<Quantity<D>, exponent> Pow(Quantity<D> const& x); template<typename D> std::ostream& operator<<(std::ostream& out, Quantity<D> const& quantity); // Equivalent to |std::abs(x)|. double Abs(double const x); template<typename D> Quantity<D> Abs(Quantity<D> const& x); template<typename D> SquareRoot<Quantity<D>> Sqrt(Quantity<D> const& x); template<typename D> Angle ArcTan(Quantity<D> const& y, Quantity<D> const& x); std::string DebugString( double const number, int const precision = std::numeric_limits<double>::max_digits10); template<typename D> std::string DebugString( Quantity<D> const& quantity, int const precision = std::numeric_limits<double>::max_digits10); template<typename D> class Quantity { public: using Dimensions = D; using Inverse = internal::Quotient<double, Quantity>; constexpr Quantity(); ~Quantity() = default; constexpr Quantity operator+() const; constexpr Quantity operator-() const; constexpr Quantity operator+(Quantity const& right) const; constexpr Quantity operator-(Quantity const& right) const; constexpr Quantity operator*(double const right) const; constexpr Quantity operator/(double const right) const; Quantity& operator+=(Quantity const&); Quantity& operator-=(Quantity const&); Quantity& operator*=(double const); Quantity& operator/=(double const); constexpr bool operator>(Quantity const& right) const; constexpr bool operator<(Quantity const& right) const; constexpr bool operator>=(Quantity const& right) const; constexpr bool operator<=(Quantity const& right) const; constexpr bool operator==(Quantity const& right) const; constexpr bool operator!=(Quantity const& right) const; void WriteToMessage(not_null<serialization::Quantity*> const message) const; static Quantity ReadFromMessage(serialization::Quantity const& message); private: explicit constexpr Quantity(double const magnitude); double magnitude_; template<typename LDimensions, typename RDimensions> friend constexpr internal::Product<Quantity<LDimensions>, Quantity<RDimensions>> operator*( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right); template<typename LDimensions, typename RDimensions> friend constexpr internal::Quotient<Quantity<LDimensions>, Quantity<RDimensions>> operator/( Quantity<LDimensions> const& left, Quantity<RDimensions> const& right); template<typename RDimensions> friend constexpr Quantity<RDimensions> operator*( double const left, Quantity<RDimensions> const& right); template<typename RDimensions> friend constexpr typename Quantity<RDimensions>::Inverse operator/( double const left, Quantity<RDimensions> const& right); template<typename Q> friend constexpr Q SIUnit(); template<int exponent, typename BaseDimensions> friend constexpr Exponentiation<Quantity<BaseDimensions>, exponent> Pow( Quantity<BaseDimensions> const& x); template<typename E> friend Quantity<E> Abs(Quantity<E> const&); template<typename ArgumentDimensions> friend SquareRoot<Quantity<ArgumentDimensions>> Sqrt( Quantity<ArgumentDimensions> const& x); template<typename ArgumentDimensions> friend CubeRoot<Quantity<ArgumentDimensions>> Cbrt( Quantity<ArgumentDimensions> const& x); friend Angle ArcTan<>(Quantity<D> const& y, Quantity<D> const& x); friend std::string DebugString<>(Quantity<D> const&, int const); }; // A type trait for testing if a type is a quantity. template<typename T> struct is_quantity : std::is_floating_point<T> {}; template<typename D> struct is_quantity<Quantity<D>> : std::true_type {}; } // namespace quantities } // namespace principia #include "quantities/quantities_body.hpp" <|endoftext|>
<commit_before>//===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); /// FindStringInBuffer - This is basically just a strstr wrapper that differs in /// two ways: first it handles 'nul' characters in memory buffers, second, it /// returns the end of the memory buffer on match failure. static const char *FindStringInBuffer(const char *Str, const char *CurPtr, const MemoryBuffer &MB) { // Check to see if we have a match. If so, just return it. if (const char *Res = strstr(CurPtr, Str)) return Res; // If not, check to make sure we didn't just find an embedded nul in the // memory buffer. const char *Ptr = CurPtr + strlen(CurPtr); // If we really reached the end of the file, return it. if (Ptr == MB.getBufferEnd()) return Ptr; // Otherwise, just skip this section of the file, including the nul. return FindStringInBuffer(Str, Ptr+1, MB); } /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. static bool ReadCheckFile(SourceMgr &SM, std::vector<std::pair<std::string, SMLoc> > &CheckStrings) { // Open the check file, and tell SourceMgr about it. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open check file '" << CheckFilename << "': " << ErrorStr << '\n'; return true; } SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. The // MemoryBuffer is guaranteed to be nul terminated, but may have nul's // embedded into it. We don't support check strings with embedded nuls. std::string Prefix = CheckPrefix + ":"; const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); while (1) { // See if Prefix occurs in the memory buffer. const char *Ptr = FindStringInBuffer(Prefix.c_str(), CurPtr, *F); // If we didn't find a match, we're done. if (Ptr == BufferEnd) break; // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. Ptr += Prefix.size(); while (*Ptr == ' ' || *Ptr == '\t') ++Ptr; // Scan ahead to the end of line. CurPtr = Ptr; while (CurPtr != BufferEnd && *CurPtr != '\n' && *CurPtr != '\r') ++CurPtr; // Ignore trailing whitespace. while (CurPtr[-1] == ' ' || CurPtr[-1] == '\t') --CurPtr; // Check that there is something on the line. if (Ptr >= CurPtr) { SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "found empty check string with prefix '"+Prefix+"'", "error"); return true; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(std::make_pair(std::string(Ptr, CurPtr), SMLoc::getFromPointer(Ptr))); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << Prefix << "'\n"; return true; } return false; } // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in // the check strings with a single space. static void CanonicalizeCheckStrings(std::vector<std::pair<std::string, SMLoc> > &CheckStrings) { for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) { std::string &Str = CheckStrings[i].first; for (unsigned C = 0; C != Str.size(); ++C) { // If C is not a horizontal whitespace, skip it. if (Str[C] != ' ' && Str[C] != '\t') continue; // Replace the character with space, then remove any other space // characters after it. Str[C] = ' '; while (C+1 != Str.size() && (Str[C+1] == ' ' || Str[C+1] == '\t')) Str.erase(Str.begin()+C+1); } } } /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified /// memory buffer, free it, and return a new one. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) { std::vector<char> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // If C is not a horizontal whitespace, skip it. if (*Ptr != ' ' && *Ptr != '\t') { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(&NewFile[0], &NewFile[0]+NewFile.size(), MB->getBufferIdentifier()); delete MB; return MB2; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<std::pair<std::string, SMLoc> > CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Remove duplicate spaces in the check strings if requested. if (!NoCanonicalizeWhiteSpace) CanonicalizeCheckStrings(CheckStrings); // Open the file to check and add it to SourceMgr. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open input file '" << InputFilename << "': " << ErrorStr << '\n'; return true; } // Remove duplicate spaces in the input file if requested. if (!NoCanonicalizeWhiteSpace) F = CanonicalizeInputFile(F); SM.AddNewSourceBuffer(F, SMLoc()); // Check that we have all of the expected strings, in order, in the input // file. const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const std::pair<std::string, SMLoc> &CheckStr = CheckStrings[StrNo]; // Find StrNo in the file. const char *Ptr = FindStringInBuffer(CheckStr.first.c_str(), CurPtr, *F); // If we found a match, we're done, move on. if (Ptr != BufferEnd) { CurPtr = Ptr + CheckStr.first.size(); continue; } // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.second, "expected string not found in input", "error"); SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "scanning from here", "note"); return 1; } return 0; } <commit_msg>improve filecheck's "scanning from here" caret position.<commit_after>//===- FileCheck.cpp - Check that File's Contents match what is expected --===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // FileCheck does a line-by line check of a file that validates whether it // contains the expected content. This is useful for regression tests etc. // // This program exits with an error status of 2 on error, exit status of 0 if // the file matched the expected contents, and exit status of 1 if it did not // contain the expected contents. // //===----------------------------------------------------------------------===// #include "llvm/Support/CommandLine.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" using namespace llvm; static cl::opt<std::string> CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required); static cl::opt<std::string> InputFilename("input-file", cl::desc("File to check (defaults to stdin)"), cl::init("-"), cl::value_desc("filename")); static cl::opt<std::string> CheckPrefix("check-prefix", cl::init("CHECK"), cl::desc("Prefix to use from check file (defaults to 'CHECK')")); static cl::opt<bool> NoCanonicalizeWhiteSpace("strict-whitespace", cl::desc("Do not treat all horizontal whitespace as equivalent")); /// FindStringInBuffer - This is basically just a strstr wrapper that differs in /// two ways: first it handles 'nul' characters in memory buffers, second, it /// returns the end of the memory buffer on match failure. static const char *FindStringInBuffer(const char *Str, const char *CurPtr, const MemoryBuffer &MB) { // Check to see if we have a match. If so, just return it. if (const char *Res = strstr(CurPtr, Str)) return Res; // If not, check to make sure we didn't just find an embedded nul in the // memory buffer. const char *Ptr = CurPtr + strlen(CurPtr); // If we really reached the end of the file, return it. if (Ptr == MB.getBufferEnd()) return Ptr; // Otherwise, just skip this section of the file, including the nul. return FindStringInBuffer(Str, Ptr+1, MB); } /// ReadCheckFile - Read the check file, which specifies the sequence of /// expected strings. The strings are added to the CheckStrings vector. static bool ReadCheckFile(SourceMgr &SM, std::vector<std::pair<std::string, SMLoc> > &CheckStrings) { // Open the check file, and tell SourceMgr about it. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open check file '" << CheckFilename << "': " << ErrorStr << '\n'; return true; } SM.AddNewSourceBuffer(F, SMLoc()); // Find all instances of CheckPrefix followed by : in the file. The // MemoryBuffer is guaranteed to be nul terminated, but may have nul's // embedded into it. We don't support check strings with embedded nuls. std::string Prefix = CheckPrefix + ":"; const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); while (1) { // See if Prefix occurs in the memory buffer. const char *Ptr = FindStringInBuffer(Prefix.c_str(), CurPtr, *F); // If we didn't find a match, we're done. if (Ptr == BufferEnd) break; // Okay, we found the prefix, yay. Remember the rest of the line, but // ignore leading and trailing whitespace. Ptr += Prefix.size(); while (*Ptr == ' ' || *Ptr == '\t') ++Ptr; // Scan ahead to the end of line. CurPtr = Ptr; while (CurPtr != BufferEnd && *CurPtr != '\n' && *CurPtr != '\r') ++CurPtr; // Ignore trailing whitespace. while (CurPtr[-1] == ' ' || CurPtr[-1] == '\t') --CurPtr; // Check that there is something on the line. if (Ptr >= CurPtr) { SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "found empty check string with prefix '"+Prefix+"'", "error"); return true; } // Okay, add the string we captured to the output vector and move on. CheckStrings.push_back(std::make_pair(std::string(Ptr, CurPtr), SMLoc::getFromPointer(Ptr))); } if (CheckStrings.empty()) { errs() << "error: no check strings found with prefix '" << Prefix << "'\n"; return true; } return false; } // CanonicalizeCheckStrings - Replace all sequences of horizontal whitespace in // the check strings with a single space. static void CanonicalizeCheckStrings(std::vector<std::pair<std::string, SMLoc> > &CheckStrings) { for (unsigned i = 0, e = CheckStrings.size(); i != e; ++i) { std::string &Str = CheckStrings[i].first; for (unsigned C = 0; C != Str.size(); ++C) { // If C is not a horizontal whitespace, skip it. if (Str[C] != ' ' && Str[C] != '\t') continue; // Replace the character with space, then remove any other space // characters after it. Str[C] = ' '; while (C+1 != Str.size() && (Str[C+1] == ' ' || Str[C+1] == '\t')) Str.erase(Str.begin()+C+1); } } } /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified /// memory buffer, free it, and return a new one. static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) { std::vector<char> NewFile; NewFile.reserve(MB->getBufferSize()); for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd(); Ptr != End; ++Ptr) { // If C is not a horizontal whitespace, skip it. if (*Ptr != ' ' && *Ptr != '\t') { NewFile.push_back(*Ptr); continue; } // Otherwise, add one space and advance over neighboring space. NewFile.push_back(' '); while (Ptr+1 != End && (Ptr[1] == ' ' || Ptr[1] == '\t')) ++Ptr; } // Free the old buffer and return a new one. MemoryBuffer *MB2 = MemoryBuffer::getMemBufferCopy(&NewFile[0], &NewFile[0]+NewFile.size(), MB->getBufferIdentifier()); delete MB; return MB2; } int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); cl::ParseCommandLineOptions(argc, argv); SourceMgr SM; // Read the expected strings from the check file. std::vector<std::pair<std::string, SMLoc> > CheckStrings; if (ReadCheckFile(SM, CheckStrings)) return 2; // Remove duplicate spaces in the check strings if requested. if (!NoCanonicalizeWhiteSpace) CanonicalizeCheckStrings(CheckStrings); // Open the file to check and add it to SourceMgr. std::string ErrorStr; MemoryBuffer *F = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr); if (F == 0) { errs() << "Could not open input file '" << InputFilename << "': " << ErrorStr << '\n'; return true; } // Remove duplicate spaces in the input file if requested. if (!NoCanonicalizeWhiteSpace) F = CanonicalizeInputFile(F); SM.AddNewSourceBuffer(F, SMLoc()); // Check that we have all of the expected strings, in order, in the input // file. const char *CurPtr = F->getBufferStart(), *BufferEnd = F->getBufferEnd(); for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) { const std::pair<std::string, SMLoc> &CheckStr = CheckStrings[StrNo]; // Find StrNo in the file. const char *Ptr = FindStringInBuffer(CheckStr.first.c_str(), CurPtr, *F); // If we found a match, we're done, move on. if (Ptr != BufferEnd) { CurPtr = Ptr + CheckStr.first.size(); continue; } // Otherwise, we have an error, emit an error message. SM.PrintMessage(CheckStr.second, "expected string not found in input", "error"); // Print the scanning from here line. If the current position is at the end // of a line, advance to the start of the next line. const char *Scan = CurPtr; while (Scan != BufferEnd && (*Scan == ' ' || *Scan == '\t')) ++Scan; if (*Scan == '\n' || *Scan == '\r') CurPtr = Scan+1; SM.PrintMessage(SMLoc::getFromPointer(CurPtr), "scanning from here", "note"); return 1; } return 0; } <|endoftext|>
<commit_before>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Intel Corporation. All Rights Reserved. //#cmake:add-file ../../../src/dispatcher.cpp #include <unit-tests/test.h> #include <common/utilities/time/timer.h> #include <src/concurrency.h> #include <algorithm> #include <vector> using namespace utilities::time; TEST_CASE( "dequeue doesn't wait after stop" ) { single_consumer_queue< std::function< void( void ) > > scq; std::function< void( void ) > f; std::function< void( void ) > * f_ptr = &f; scq.enqueue( []() {} ); REQUIRE( scq.size() == 1 ); REQUIRE( scq.peek( &f_ptr ) ); REQUIRE( scq.started() ); REQUIRE_FALSE( scq.stopped() ); scq.stop(); REQUIRE_FALSE( scq.peek( &f_ptr ) ); REQUIRE( scq.stopped() ); REQUIRE_FALSE( scq.started() ); REQUIRE( scq.empty() ); timer t( std::chrono::seconds( 1 ) ); t.start(); scq.dequeue( &f, 2000 ); REQUIRE_FALSE( t.has_expired() ); // Verify no timeout, dequeue return in less than 10 seconds } TEST_CASE( "dequeue doesn't wait when queue is not empty" ) { single_consumer_queue< std::function< void( void ) > > scq; timer t( std::chrono::seconds( 1 ) ); std::function< void( void ) > f; scq.enqueue( []() {} ); t.start(); scq.dequeue( &f, 3000 ); REQUIRE_FALSE( t.has_expired() ); // Verify no timeout, dequeue return in less than 1 seconds REQUIRE( scq.empty() ); } TEST_CASE( "dequeue wait when queue is empty" ) { single_consumer_queue< std::function< void( void ) > > scq; timer t( std::chrono::milliseconds( 2900 ) ); std::function< void( void ) > f; t.start(); REQUIRE_FALSE( scq.dequeue( &f, 3000 ) ); REQUIRE( t.has_expired() ); // Verify timeout, dequeue return after >= 3 seconds } TEST_CASE( "try dequeue" ) { single_consumer_queue< std::function< void( void ) > > scq; std::function< void( void ) > f; REQUIRE_FALSE( scq.try_dequeue( &f ) ); // nothing on queue scq.enqueue( []() {} ); REQUIRE( scq.try_dequeue( &f ) ); // 1 item on queue REQUIRE_FALSE( scq.try_dequeue( &f ) ); // 0 items on queue } TEST_CASE( "blocking enqueue" ) { single_consumer_queue< std::function< void( void ) > > scq; std::function< void( void ) > f; stopwatch sw; sw.reset(); // dequeue an item after 5 seconds, we wait for the blocking call and verify we return after this dequeue call ~ 5 seconds std::thread dequeue_thread( [&]() { std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); scq.dequeue( &f, 1000 ); } ); REQUIRE( sw.get_elapsed_ms() < 1000 ); for( int i = 0; i < 10; ++i ) { scq.blocking_enqueue( []() {} ); } REQUIRE( sw.get_elapsed_ms() < 1000 ); REQUIRE( scq.size() == 10 ); // verify queue is full (default capacity is 10) scq.blocking_enqueue( []() {} ); // add a blocking call (item 11) REQUIRE( sw.get_elapsed_ms() > 5000 ); // verify the blocking call return on dequeue time REQUIRE( sw.get_elapsed_ms() < 6000 ); // verify the blocking call return on dequeue time dequeue_thread.join(); // verify clean exit with no threads alive. } TEST_CASE("verify mutex protection") { single_consumer_queue< int > scq; stopwatch sw; const int MAX_SIZE_FOR_THREAD = 20; std::thread enqueue_thread1( [&]() { for( int i = 0; i < MAX_SIZE_FOR_THREAD; ++i ) { std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); scq.blocking_enqueue(std::move(i)); } } ); std::thread enqueue_thread2( [&]() { for( int i = 0; i < MAX_SIZE_FOR_THREAD; ++i ) { std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); scq.blocking_enqueue(std::move(20 + i)); } } ); std::vector<int> all_values; for( int i = 0; i < MAX_SIZE_FOR_THREAD * 2; ++i ) { int val; scq.dequeue( &val, 1000 ); all_values.push_back(val); } REQUIRE(all_values.size() == MAX_SIZE_FOR_THREAD * 2); std::sort(all_values.begin(), all_values.end()); for (int i = 0; i < all_values.size(); ++i) { REQUIRE(all_values[i] == i); } enqueue_thread1.join(); enqueue_thread2.join(); } <commit_msg>fix test-scq<commit_after>// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2021 Intel Corporation. All Rights Reserved. //#cmake:add-file ../../../src/dispatcher.cpp #include <unit-tests/test.h> #include <common/utilities/time/timer.h> #include <src/concurrency.h> #include <algorithm> #include <vector> using namespace utilities::time; TEST_CASE( "dequeue doesn't wait after stop" ) { typedef std::function< void( void ) > scq_value_t; single_consumer_queue< scq_value_t > scq; scq_value_t f; scq_value_t * f_ptr = &f; scq.enqueue( []() {} ); REQUIRE( scq.size() == 1 ); REQUIRE( scq.peek( [&]( scq_value_t const & ) {} )); REQUIRE( scq.started() ); REQUIRE_FALSE( scq.stopped() ); scq.stop(); REQUIRE_FALSE( scq.peek( [&]( scq_value_t const& ) {} ) ); REQUIRE( scq.stopped() ); REQUIRE_FALSE( scq.started() ); REQUIRE( scq.empty() ); timer t( std::chrono::seconds( 1 ) ); t.start(); scq.dequeue( &f, 2000 ); REQUIRE_FALSE( t.has_expired() ); // Verify no timeout, dequeue return in less than 10 seconds } TEST_CASE( "dequeue doesn't wait when queue is not empty" ) { single_consumer_queue< std::function< void( void ) > > scq; timer t( std::chrono::seconds( 1 ) ); std::function< void( void ) > f; scq.enqueue( []() {} ); t.start(); scq.dequeue( &f, 3000 ); REQUIRE_FALSE( t.has_expired() ); // Verify no timeout, dequeue return in less than 1 seconds REQUIRE( scq.empty() ); } TEST_CASE( "dequeue wait when queue is empty" ) { single_consumer_queue< std::function< void( void ) > > scq; timer t( std::chrono::milliseconds( 2900 ) ); std::function< void( void ) > f; t.start(); REQUIRE_FALSE( scq.dequeue( &f, 3000 ) ); REQUIRE( t.has_expired() ); // Verify timeout, dequeue return after >= 3 seconds } TEST_CASE( "try dequeue" ) { single_consumer_queue< std::function< void( void ) > > scq; std::function< void( void ) > f; REQUIRE_FALSE( scq.try_dequeue( &f ) ); // nothing on queue scq.enqueue( []() {} ); REQUIRE( scq.try_dequeue( &f ) ); // 1 item on queue REQUIRE_FALSE( scq.try_dequeue( &f ) ); // 0 items on queue } TEST_CASE( "blocking enqueue" ) { single_consumer_queue< std::function< void( void ) > > scq; std::function< void( void ) > f; stopwatch sw; sw.reset(); // dequeue an item after 5 seconds, we wait for the blocking call and verify we return after this dequeue call ~ 5 seconds std::thread dequeue_thread( [&]() { std::this_thread::sleep_for( std::chrono::seconds( 5 ) ); scq.dequeue( &f, 1000 ); } ); REQUIRE( sw.get_elapsed_ms() < 1000 ); for( int i = 0; i < 10; ++i ) { scq.blocking_enqueue( []() {} ); } REQUIRE( sw.get_elapsed_ms() < 1000 ); REQUIRE( scq.size() == 10 ); // verify queue is full (default capacity is 10) scq.blocking_enqueue( []() {} ); // add a blocking call (item 11) REQUIRE( sw.get_elapsed_ms() > 5000 ); // verify the blocking call return on dequeue time REQUIRE( sw.get_elapsed_ms() < 6000 ); // verify the blocking call return on dequeue time dequeue_thread.join(); // verify clean exit with no threads alive. } TEST_CASE("verify mutex protection") { single_consumer_queue< int > scq; stopwatch sw; const int MAX_SIZE_FOR_THREAD = 20; std::thread enqueue_thread1( [&]() { for( int i = 0; i < MAX_SIZE_FOR_THREAD; ++i ) { std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); scq.blocking_enqueue(std::move(i)); } } ); std::thread enqueue_thread2( [&]() { for( int i = 0; i < MAX_SIZE_FOR_THREAD; ++i ) { std::this_thread::sleep_for( std::chrono::milliseconds( 100 ) ); scq.blocking_enqueue(std::move(20 + i)); } } ); std::vector<int> all_values; for( int i = 0; i < MAX_SIZE_FOR_THREAD * 2; ++i ) { int val; scq.dequeue( &val, 1000 ); all_values.push_back(val); } REQUIRE(all_values.size() == MAX_SIZE_FOR_THREAD * 2); std::sort(all_values.begin(), all_values.end()); for (int i = 0; i < all_values.size(); ++i) { REQUIRE(all_values[i] == i); } enqueue_thread1.join(); enqueue_thread2.join(); } <|endoftext|>
<commit_before>/* * * Copyright (c) 2016 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include "assert-macros.h" #include <syslog.h> #include <errno.h> #include "SpinelNCPTask.h" #include "SpinelNCPInstance.h" using namespace nl; using namespace nl::wpantund; SpinelNCPTask::SpinelNCPTask(SpinelNCPInstance* _instance, CallbackWithStatusArg1 cb): mInstance(_instance), mCB(cb), mNextCommandTimeout(NCP_DEFAULT_COMMAND_RESPONSE_TIMEOUT) { } SpinelNCPTask::~SpinelNCPTask() { finish(kWPANTUNDStatus_Canceled); } void SpinelNCPTask::finish(int status, const boost::any& value) { if (!mCB.empty()) { mCB(status, value); mCB = CallbackWithStatusArg1(); } } static bool spinel_callback_is_reset(int event, va_list args) { int status = peek_ncp_callback_status(event, args); return (status >= SPINEL_STATUS_RESET__BEGIN) && (status < SPINEL_STATUS_RESET__END); } int SpinelNCPTask::vprocess_send_command(int event, va_list args) { EH_BEGIN_SUB(&mSubPT); require(mNextCommand.size() < sizeof(GetInstance(this)->mOutboundBuffer), on_error); CONTROL_REQUIRE_PREP_TO_SEND_COMMAND_WITHIN(NCP_DEFAULT_COMMAND_SEND_TIMEOUT, on_error); memcpy(GetInstance(this)->mOutboundBuffer, mNextCommand.data(), mNextCommand.size()); GetInstance(this)->mOutboundBufferLen = static_cast<spinel_ssize_t>(mNextCommand.size()); CONTROL_REQUIRE_OUTBOUND_BUFFER_FLUSHED_WITHIN(NCP_DEFAULT_COMMAND_SEND_TIMEOUT, on_error); if (mNextCommand[1] == SPINEL_CMD_RESET) { mInstance->mResetIsExpected = true; EH_REQUIRE_WITHIN( mNextCommandTimeout, IS_EVENT_FROM_NCP(event) && ( (GetInstance(this)->mInboundHeader == mLastHeader) || spinel_callback_is_reset(event, args) ), on_error ); mInstance->mResetIsExpected = false; } else { CONTROL_REQUIRE_COMMAND_RESPONSE_WITHIN(mNextCommandTimeout, on_error); } mNextCommandRet = peek_ncp_callback_status(event, args); if (mNextCommandRet) { mNextCommandRet = spinel_status_to_wpantund_status(mNextCommandRet); } EH_EXIT(); on_error: mNextCommandRet = kWPANTUNDStatus_Timeout; EH_END(); } nl::Data nl::wpantund::SpinelPackData(const char* pack_format, ...) { Data ret(64); va_list args; va_start(args, pack_format); do { spinel_ssize_t packed_size = spinel_datatype_vpack(ret.data(), (spinel_size_t)ret.size(), pack_format, args); if (packed_size < 0) { ret.clear(); break; } else if (packed_size > ret.size()) { ret.resize(packed_size); continue; } else { ret.resize(packed_size); } } while(false); va_end(args); return ret; } <commit_msg>Fixed unused while statement in SpinelPackData<commit_after>/* * * Copyright (c) 2016 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #if HAVE_CONFIG_H #include <config.h> #endif #include "assert-macros.h" #include <syslog.h> #include <errno.h> #include "SpinelNCPTask.h" #include "SpinelNCPInstance.h" using namespace nl; using namespace nl::wpantund; SpinelNCPTask::SpinelNCPTask(SpinelNCPInstance* _instance, CallbackWithStatusArg1 cb): mInstance(_instance), mCB(cb), mNextCommandTimeout(NCP_DEFAULT_COMMAND_RESPONSE_TIMEOUT) { } SpinelNCPTask::~SpinelNCPTask() { finish(kWPANTUNDStatus_Canceled); } void SpinelNCPTask::finish(int status, const boost::any& value) { if (!mCB.empty()) { mCB(status, value); mCB = CallbackWithStatusArg1(); } } static bool spinel_callback_is_reset(int event, va_list args) { int status = peek_ncp_callback_status(event, args); return (status >= SPINEL_STATUS_RESET__BEGIN) && (status < SPINEL_STATUS_RESET__END); } int SpinelNCPTask::vprocess_send_command(int event, va_list args) { EH_BEGIN_SUB(&mSubPT); require(mNextCommand.size() < sizeof(GetInstance(this)->mOutboundBuffer), on_error); CONTROL_REQUIRE_PREP_TO_SEND_COMMAND_WITHIN(NCP_DEFAULT_COMMAND_SEND_TIMEOUT, on_error); memcpy(GetInstance(this)->mOutboundBuffer, mNextCommand.data(), mNextCommand.size()); GetInstance(this)->mOutboundBufferLen = static_cast<spinel_ssize_t>(mNextCommand.size()); CONTROL_REQUIRE_OUTBOUND_BUFFER_FLUSHED_WITHIN(NCP_DEFAULT_COMMAND_SEND_TIMEOUT, on_error); if (mNextCommand[1] == SPINEL_CMD_RESET) { mInstance->mResetIsExpected = true; EH_REQUIRE_WITHIN( mNextCommandTimeout, IS_EVENT_FROM_NCP(event) && ( (GetInstance(this)->mInboundHeader == mLastHeader) || spinel_callback_is_reset(event, args) ), on_error ); mInstance->mResetIsExpected = false; } else { CONTROL_REQUIRE_COMMAND_RESPONSE_WITHIN(mNextCommandTimeout, on_error); } mNextCommandRet = peek_ncp_callback_status(event, args); if (mNextCommandRet) { mNextCommandRet = spinel_status_to_wpantund_status(mNextCommandRet); } EH_EXIT(); on_error: mNextCommandRet = kWPANTUNDStatus_Timeout; EH_END(); } nl::Data nl::wpantund::SpinelPackData(const char* pack_format, ...) { Data ret(64); va_list args; va_start(args, pack_format); do { spinel_ssize_t packed_size = spinel_datatype_vpack(ret.data(), (spinel_size_t)ret.size(), pack_format, args); if (packed_size < 0) { ret.clear(); break; } else if (packed_size > ret.size()) { ret.resize(packed_size); continue; } else { ret.resize(packed_size); } break; } while(true); va_end(args); return ret; } <|endoftext|>
<commit_before>#include <iostream> #include <cstdio> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> #include <random> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::string host; std::string cur; std::string classpath; std::stringstream out; std::ostream& dump_out = std::cerr; std::istream& in = std::cin; // std::ostream& out = buf; //std::cout; std::ostream& err = std::cerr; bool shuffle_flag = true; bool dump_flag = false; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::deque<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(int, int); void dump(); void dump(std::deque<Position>&); void dump(std::deque<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); int dfs(int, int, int, int, Position, Field, std::deque<Position>); int put_stone(Field&, int, int, Position, std::deque<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::deque<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; int max_score; void solve() { if (shuffle_flag) { std::shuffle(initial_empties.begin(), initial_empties.end(), std::mt19937{std::random_device{}()}); } std::deque<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { if (dfs(1, 0, s.i, s.j, s.p, initial_field, empty_list) != 0) { break; } } } } int bfs(int c, int nowscore, int n, int m, Position p, Field f, std::deque<Position> candidates) { } int dfs(int c, int nowscore, int n, int m, Position p, Field f, std::deque<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return 1; } if (dump_flag) { f.dump(candidates); } f.answer[n] = answer_format(p, m); score += nowscore; if (max_score < score) { max_score = score; f.print_answer(score, c); } err << "score:" << initial_empties.size() - score << ", "; for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { if (dfs(c+1, score, s.i, s.j, s.p, f, candidates) != 0) { break; } } } } return 0; } int put_stone(Field& f, int n, int m, Position p1, std::deque<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main(int argc, char**argv) { if (argc < 3) { err << "Usage <path of SubmitClient.class> <ipv4 address>\n"; return 1; } cur = argv[0]; classpath = argv[1]; host = argv[2]; parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) dump_out.put('.'); else if (raw[i][j] < stone_number) dump_out.put('@'); else dump_out.put('#'); } dump_out.put('\n'); } } void Field::dump(std::deque<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) dump_out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) dump_out.put('_'); else if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('#'); } dump_out.put('\n'); } } void Field::dump(std::deque<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) dump_out.put('*'); else if (raw[i][j] < stone_number) dump_out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) dump_out.put('_'); else if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('#'); } dump_out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('@'); } dump_out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) initial_empties.emplace_back(Position{i, j}); } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { for (auto s_p : stones[i][j].zks) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{f_p.y - s_p.y, f_p.x - s_p.x}}); } } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(WIN64) || defined(_WIN64) #include <windows.h> void WinSubmit(); void Field::print_answer(int score, int c) { out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } WinSubmit(); } std::string getPath(std::string s) { auto p = s.rfind('\\'); return s.substr(0, p); } void WinSubmit() { HANDLE readPipe = NULL, writePipe = NULL; HANDLE readTemp; HANDLE childProcess = NULL; CreatePipe(&readTemp, &writePipe, NULL, 0); DuplicateHandle(GetCurrentProcess(), readTemp, GetCurrentProcess(), &readPipe, 0, true, DUPLICATE_SAME_ACCESS); CloseHandle(readTemp); bool bInheritHandles = true; DWORD creationFlags = 0; STARTUPINFO si = {}; si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = readPipe; si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); SetCurrentDirectory(getPath(cur).c_str()); PROCESS_INFORMATION pi = {}; CreateProcess(NULL, LPTSTR(("java " + classpath + " " + host).c_str()), NULL, NULL,bInheritHandles, creationFlags, NULL, NULL, &si, &pi); childProcess = pi.hProcess; CloseHandle(pi.hThread); CloseHandle(readPipe); readPipe = NULL; WriteFile(writePipe, out.str().c_str(), out.str().size(), NULL, NULL); CloseHandle(writePipe); writePipe = NULL; WaitForSingleObject(childProcess, INFINITE); } #else void Field::print_answer(int score, int c) { FILE* client = popen(("java " + classpath + " " + host).c_str(), "w"); if (client == NULL) return; out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } fprintf(client, "%s\r\n", out.str().c_str()); pclose(client); } #endif <commit_msg>bfs書きたさ<commit_after>#include <iostream> #include <cstdio> #include <map> #include <vector> #include <deque> #include <list> #include <array> #include <string> #include <sstream> #include <algorithm> #include <random> const int field_size = 32; const int stone_size = 8; const int empty_val = 256; const int filled_val = 257; const int normal = 0, rot90 = 1, rot180 = 2, rot270 = 3, fliped = 4; std::string host; std::string cur; std::string classpath; std::stringstream out; std::ostream& dump_out = std::cerr; std::istream& in = std::cin; // std::ostream& out = buf; //std::cout; std::ostream& err = std::cerr; bool shuffle_flag = true; bool dump_flag = false; struct Position { int y, x; bool operator==(const Position& obj) const { return y == obj.y && x == obj.x; } bool operator<(const Position& obj) const { if (y == obj.y) return x < obj.x; return y < obj.y; } }; struct OperatedStone { int i, j; Position p; }; struct Field { std::array<std::array<int, field_size>, field_size> raw; std::map<Position, std::deque<OperatedStone>> candidates; std::vector<std::string> answer; void print_answer(int, int); void dump(); void dump(std::deque<Position>&); void dump(std::deque<Position>&, Position p); }; struct Stone { std::array<std::array<int, stone_size>, stone_size> raw; std::deque<Position> zks; void dump(); }; int get(); void br(); void parse_input(); void parse_field(); void parse_stones(); void parse_stone(int); void get_candidates(); void solve(); int dfs(int, int, int, int, Position, Field, std::deque<Position>); int put_stone(Field&, int, int, Position, std::deque<Position>&); bool check_pos(int y, int x); std::string answer_format(Position, int); std::string to_s(int); void operate(int); int stone_number; Field initial_field; std::deque<Position> initial_empties; std::array<std::array<Stone, 8>, 256> stones; int max_score; void solve() { if (shuffle_flag) { std::shuffle(initial_empties.begin(), initial_empties.end(), std::mt19937{std::random_device{}()}); } std::deque<Position> empty_list; empty_list.clear(); for (auto p : initial_empties) { for (auto s : initial_field.candidates[p]) { if (dfs(1, 0, s.i, s.j, s.p, initial_field, empty_list) != 0) { break; } } } } // struct Arg{ // int c, // nowscore, // n, m; // Position p; // Field f; // std::deque<Position> candidates; // }; // int bfs() { // std::deque<Arg> args; // if (shuffle_flag) { // std::shuffle(initial_empties.begin(), initial_empties.end(), std::mt19937{std::random_device{}()}); // } // std::deque<Position> empty_list; empty_list.clear(); // for (auto p : initial_empties) { // for (auto s : initial_field.candidates[p]) { // args.emplace_back(Arg{}); // } // } // // } int dfs(int c, int nowscore, int n, int m, Position p, Field f, std::deque<Position> candidates) { int score = 0; if ((score = put_stone(f, n, m, p, candidates)) == 0) { return 1; } if (dump_flag) { f.dump(candidates); } f.answer[n] = answer_format(p, m); score += nowscore; if (max_score < score) { max_score = score; f.print_answer(score, c); } err << "score:" << initial_empties.size() - score << ", "; for (auto np : candidates) { for (auto s : initial_field.candidates[np]) { if (s.i > n) { if (dfs(c+1, score, s.i, s.j, s.p, f, candidates) != 0) { break; } } } } return 0; } int put_stone(Field& f, int n, int m, Position p1, std::deque<Position>& next) { Field backup = f; int score = 0; for (auto p2 : stones[n][m].zks) { int y = p1.y + p2.y, x = p1.x + p2.x; if (f.raw[y][x] != empty_val) { f = backup; next.clear(); return 0; } f.raw[y][x] = n; score += 1; auto exist = std::find(next.begin(), next.end(), Position{y, x}); if (exist != next.end()) { next.erase(exist); } int dy[] = {-1, 0, 0, 1}, dx[] = {0, -1, 1, 0}; for (int i = 0; i < 4; ++i) { int ny = y+dy[i], nx = x+dx[i]; if (check_pos(ny, nx) && f.raw[ny][nx] == empty_val) { next.emplace_back(Position{ny, nx}); } } } return score; } bool check_pos(int y, int x) { return (0<= y && y < field_size) && (0 <= x && x < field_size); } int main(int argc, char**argv) { if (argc < 3) { err << "Usage <path of SubmitClient.class> <ipv4 address>\n"; return 1; } cur = argv[0]; classpath = argv[1]; host = argv[2]; parse_input(); get_candidates(); solve(); return 0; } // ------- void Field::dump() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] == empty_val) dump_out.put('.'); else if (raw[i][j] < stone_number) dump_out.put('@'); else dump_out.put('#'); } dump_out.put('\n'); } } void Field::dump(std::deque<Position>& ps) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (raw[i][j] < stone_number) dump_out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) dump_out.put('_'); else if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('#'); } dump_out.put('\n'); } } void Field::dump(std::deque<Position>& ps, Position p) { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if (Position{i, j} == p) dump_out.put('*'); else if (raw[i][j] < stone_number) dump_out.put('@'); else if (std::find(ps.begin(), ps.end(), Position{i, j}) != ps.end()) dump_out.put('_'); else if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('#'); } dump_out.put('\n'); } } void Stone::dump() { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if (raw[i][j] == empty_val) dump_out.put('.'); else dump_out.put('@'); } dump_out.put('\n'); } } int get() { int c = in.get() - '0'; if (c == 0) return empty_val; return filled_val; } void br() { in.get(), in.get(); } void parse_input() { parse_field(); in >> stone_number; br(); parse_stones(); initial_field.answer.resize(stone_number); } void parse_field() { for (int i = 0; i < field_size; ++i) { for (int j = 0; j < field_size; ++j) { if ((initial_field.raw[i][j] = get()) == empty_val) { initial_empties.emplace_back(Position{i, j}); } } br(); } } void parse_stones() { for (int i = 0; i < stone_number; ++i) { parse_stone(i); br(); operate(i); } } void parse_stone(int n) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { if ((stones[n][normal].raw[i][j] = get()) != empty_val) stones[n][normal].zks.emplace_back(Position{i, j}); } br(); } } void operate(int n) { auto rotate_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+1].raw[j][7-i] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+1].zks.push_back(Position{p.x, 7-p.y}); } }; auto flip_impl = [](int n, int m) { for (int i = 0; i < stone_size; ++i) { for (int j = 0; j < stone_size; ++j) { stones[n][m+4].raw[i][7-j] = stones[n][m].raw[i][j]; } } for (auto p : stones[n][m].zks) { stones[n][m+4].zks.push_back(Position{p.y, 7-p.x}); } }; rotate_impl(n, 0); rotate_impl(n, 1); rotate_impl(n, 2); flip_impl(n, 0); flip_impl(n, 1); flip_impl(n, 2); flip_impl(n, 3); } void get_candidates() { for (auto f_p : initial_empties) { for (int i = 0; i < stone_number; ++i) { for (int j = 0; j < 8; ++j) { int y = f_p.y - stones[i][j].zks[0].y, x = f_p.x - stones[i][j].zks[0].x; bool flag = true; for (auto s_p : stones[i][j].zks) { if (initial_field.raw[y + s_p.y][x + s_p.x] != empty_val) { flag = false; break; } } if (flag) { for (auto s_p : stones[i][j].zks) { initial_field.candidates[Position{f_p.y, f_p.x}].push_back(OperatedStone{i, j, Position{f_p.y - s_p.y, f_p.x - s_p.x}}); } } } } } } std::string to_s(int n) { std::stringstream ss; ss << n; return ss.str(); } std::string answer_format(Position p, int n) { std::string base = to_s(p.x) + " " + to_s(p.y)+ " "; base += (n & fliped) ? "H " : "T "; base += to_s((3 & fliped)*90); return base; } #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(WIN64) || defined(_WIN64) #include <windows.h> void WinSubmit(); void Field::print_answer(int score, int c) { out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } WinSubmit(); } std::string getPath(std::string s) { auto p = s.rfind('\\'); return s.substr(0, p); } void WinSubmit() { HANDLE readPipe = NULL, writePipe = NULL; HANDLE readTemp; HANDLE childProcess = NULL; CreatePipe(&readTemp, &writePipe, NULL, 0); DuplicateHandle(GetCurrentProcess(), readTemp, GetCurrentProcess(), &readPipe, 0, true, DUPLICATE_SAME_ACCESS); CloseHandle(readTemp); bool bInheritHandles = true; DWORD creationFlags = 0; STARTUPINFO si = {}; si.cb = sizeof(STARTUPINFO); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = readPipe; si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE); si.hStdError = GetStdHandle(STD_ERROR_HANDLE); SetCurrentDirectory(getPath(cur).c_str()); PROCESS_INFORMATION pi = {}; CreateProcess(NULL, LPTSTR(("java " + classpath + " " + host).c_str()), NULL, NULL,bInheritHandles, creationFlags, NULL, NULL, &si, &pi); childProcess = pi.hProcess; CloseHandle(pi.hThread); CloseHandle(readPipe); readPipe = NULL; WriteFile(writePipe, out.str().c_str(), out.str().size(), NULL, NULL); CloseHandle(writePipe); writePipe = NULL; WaitForSingleObject(childProcess, INFINITE); } #else void Field::print_answer(int score, int c) { FILE* client = popen(("java " + classpath + " " + host).c_str(), "w"); if (client == NULL) return; out << initial_empties.size() - score << " " << c << " " << stone_number << "\r\n"; for (int i = 0; i < stone_number; ++i) { out << answer[i] << "\r\n"; } fprintf(client, "%s\r\n", out.str().c_str()); pclose(client); } #endif <|endoftext|>
<commit_before>#include "util/bitmap.h" #include "network_character.h" #include "object.h" #include "object_messages.h" #include "animation.h" #include "util/font.h" #include "util/funcs.h" #include "factory/font_render.h" #include "nameplacer.h" #include "globals.h" #include "world.h" #include <vector> #include <math.h> using namespace std; NetworkCharacter::NetworkCharacter( int alliance ): Character( alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const char * filename, int alliance ) throw( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const string & filename, int alliance ) throw ( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const Character & chr ) throw( LoadException ): Character( chr ), name_id(-1), show_name_time(0){ } NetworkCharacter::~NetworkCharacter(){ } Object * NetworkCharacter::copy(){ return new NetworkCharacter( *this ); } /* player will send a grab message, network character should send a bogus message */ Network::Message NetworkCharacter::grabMessage( unsigned int from, unsigned int who ){ Network::Message message; message.id = 0; message << World::IGNORE_MESSAGE; return message; } void NetworkCharacter::interpretMessage( Network::Message & message ){ int type; message >> type; switch ( type ){ case CharacterMessages::ShowName : { int amount; message >> amount; setNameTime( amount ); break; } default : { message.reset(); Character::interpretMessage( message ); break; } } } void NetworkCharacter::setNameTime( int d ){ show_name_time = d; } void NetworkCharacter::alwaysShowName(){ setNameTime( -1 ); Global::debug( 1 ) << getId() << " name time is " << show_name_time << endl; } void NetworkCharacter::drawFront(Bitmap * work, int rel_x){ if ( show_name_time > 0 || show_name_time == -1 ){ int x1, y1; NamePlacer::getPlacement( x1, y1, name_id ); if ( icon ) icon->draw( x1, y1, *work ); int hasIcon = icon ? icon->getWidth() : 0; const Font & player_font = Font::getFont( Util::getDataPath() + Global::DEFAULT_FONT, 20, 20 ); const string & name = getName(); int nameHeight = player_font.getHeight( name ) / 2; nameHeight = 20 / 2; FontRender * render = FontRender::getInstance(); render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name ); drawLifeBar( hasIcon + x1, y1 + nameHeight, work ); if ( show_name_time > 0 ){ show_name_time -= 1; } } else { Global::debug( 2 ) << "Show name time for " << getId() << " is " << show_name_time << endl; } } /* void NetworkCharacter::draw( Bitmap * work, int rel_x ){ Character::draw( work, rel_x ); } */ /* just performs the current animation */ void NetworkCharacter::act( vector< Object * > * others, World * world, vector< Object * > * add ){ Global::debug( 2 ) << getId() << " status is " << getStatus() << endl; Character::act( others, world, add ); if ( (getStatus() == Status_Ground || getStatus() == Status_Jumping) && animation_current->Act() ){ // Global::debug( 0 ) << "Reset animation" << endl; if ( animation_current->getName() != "idle" && animation_current->getName() != "walk" ){ animation_current = getMovement( "idle" ); } animation_current->reset(); } } void NetworkCharacter::landed( World * world ){ setThrown( false ); switch( getStatus() ){ case Status_Falling : { if ( landed_sound ){ landed_sound->play(); } world->Quake( (int)fabs(getYVelocity()) ); break; } case Status_Fell : { world->Quake( (int)fabs(getYVelocity()) ); break; } } } void NetworkCharacter::deathReset(){ setY( 200 ); setMoving( true ); setStatus( Status_Falling ); setHealth( getMaxHealth() ); setInvincibility( 400 ); setDeath( 0 ); animation_current = getMovement( "idle" ); } <commit_msg>fix white space<commit_after>#include "util/bitmap.h" #include "network_character.h" #include "object.h" #include "object_messages.h" #include "animation.h" #include "util/font.h" #include "util/funcs.h" #include "factory/font_render.h" #include "nameplacer.h" #include "globals.h" #include "world.h" #include <vector> #include <math.h> using namespace std; NetworkCharacter::NetworkCharacter( int alliance ): Character( alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const char * filename, int alliance ) throw( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const string & filename, int alliance ) throw ( LoadException ): Character( filename, alliance ), name_id(-1), show_name_time(0){ } NetworkCharacter::NetworkCharacter( const Character & chr ) throw( LoadException ): Character( chr ), name_id(-1), show_name_time(0){ } NetworkCharacter::~NetworkCharacter(){ } Object * NetworkCharacter::copy(){ return new NetworkCharacter( *this ); } /* player will send a grab message, network character should send a bogus message */ Network::Message NetworkCharacter::grabMessage( unsigned int from, unsigned int who ){ Network::Message message; message.id = 0; message << World::IGNORE_MESSAGE; return message; } void NetworkCharacter::interpretMessage( Network::Message & message ){ int type; message >> type; switch ( type ){ case CharacterMessages::ShowName : { int amount; message >> amount; setNameTime( amount ); break; } default : { message.reset(); Character::interpretMessage( message ); break; } } } void NetworkCharacter::setNameTime( int d ){ show_name_time = d; } void NetworkCharacter::alwaysShowName(){ setNameTime( -1 ); Global::debug( 1 ) << getId() << " name time is " << show_name_time << endl; } void NetworkCharacter::drawFront(Bitmap * work, int rel_x){ if ( show_name_time > 0 || show_name_time == -1 ){ int x1, y1; NamePlacer::getPlacement( x1, y1, name_id ); if ( icon ) icon->draw( x1, y1, *work ); int hasIcon = icon ? icon->getWidth() : 0; const Font & player_font = Font::getFont( Util::getDataPath() + Global::DEFAULT_FONT, 20, 20 ); const string & name = getName(); int nameHeight = player_font.getHeight( name ) / 2; nameHeight = 20 / 2; FontRender * render = FontRender::getInstance(); render->addMessage( player_font, (hasIcon + x1) * 2, y1 * 2, Bitmap::makeColor(255,255,255), -1, name ); drawLifeBar( hasIcon + x1, y1 + nameHeight, work ); if ( show_name_time > 0 ){ show_name_time -= 1; } } else { Global::debug( 2 ) << "Show name time for " << getId() << " is " << show_name_time << endl; } } /* void NetworkCharacter::draw( Bitmap * work, int rel_x ){ Character::draw( work, rel_x ); } */ /* just performs the current animation */ void NetworkCharacter::act( vector< Object * > * others, World * world, vector< Object * > * add ){ Global::debug( 2 ) << getId() << " status is " << getStatus() << endl; Character::act( others, world, add ); if ( (getStatus() == Status_Ground || getStatus() == Status_Jumping) && animation_current->Act() ){ // Global::debug( 0 ) << "Reset animation" << endl; if ( animation_current->getName() != "idle" && animation_current->getName() != "walk" ){ animation_current = getMovement( "idle" ); } animation_current->reset(); } } void NetworkCharacter::landed( World * world ){ setThrown( false ); switch( getStatus() ){ case Status_Falling : { if ( landed_sound ){ landed_sound->play(); } world->Quake( (int)fabs(getYVelocity()) ); break; } case Status_Fell : { world->Quake( (int)fabs(getYVelocity()) ); break; } } } void NetworkCharacter::deathReset(){ setY( 200 ); setMoving( true ); setStatus( Status_Falling ); setHealth( getMaxHealth() ); setInvincibility( 400 ); setDeath( 0 ); animation_current = getMovement( "idle" ); } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // This is a test file for the function decomposeHomography contributed to OpenCV // by Samson Yilma. // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Samson Yilma¸ (samson_yilma@yahoo.com), all rights reserved. // // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "test_precomp.hpp" #include "opencv2/calib3d.hpp" #include <vector> using namespace cv; using namespace std; class CV_HomographyDecompTest: public cvtest::BaseTest { public: CV_HomographyDecompTest() { buildTestDataSet(); } protected: void run(int) { vector<Mat> rotations; vector<Mat> translations; vector<Mat> normals; decomposeHomographyMat(_H, _K, rotations, translations, normals); //there should be at least 1 solution ASSERT_GT(static_cast<int>(rotations.size()), 0); ASSERT_GT(static_cast<int>(translations.size()), 0); ASSERT_GT(static_cast<int>(normals.size()), 0); ASSERT_EQ(rotations.size(), normals.size()); ASSERT_EQ(translations.size(), normals.size()); ASSERT_TRUE(containsValidMotion(rotations, translations, normals)); decomposeHomographyMat(_H, _K, rotations, noArray(), noArray()); ASSERT_GT(static_cast<int>(rotations.size()), 0); } private: void buildTestDataSet() { _K = Matx33d(640, 0.0, 320, 0, 640, 240, 0, 0, 1); _H = Matx33d(2.649157564634028, 4.583875997496426, 70.694447785121326, -1.072756858861583, 3.533262150437228, 1513.656999614321649, 0.001303887589576, 0.003042206876298, 1.000000000000000 ); //expected solution for the given homography and intrinsic matrices _R = Matx33d(0.43307983549125, 0.545749113549648, -0.717356090899523, -0.85630229674426, 0.497582023798831, -0.138414255706431, 0.281404038139784, 0.67421809131173, 0.682818960388909); _t = Vec3d(1.826751712278038, 1.264718492450820, 0.195080809998819); _n = Vec3d(0.244875830334816, 0.480857890778889, 0.841909446789566); } bool containsValidMotion(std::vector<Mat>& rotations, std::vector<Mat>& translations, std::vector<Mat>& normals ) { double max_error = 1.0e-3; vector<Mat>::iterator riter = rotations.begin(); vector<Mat>::iterator titer = translations.begin(); vector<Mat>::iterator niter = normals.begin(); for (; riter != rotations.end() && titer != translations.end() && niter != normals.end(); ++riter, ++titer, ++niter) { double rdist = norm(*riter, _R, NORM_INF); double tdist = norm(*titer, _t, NORM_INF); double ndist = norm(*niter, _n, NORM_INF); if ( rdist < max_error && tdist < max_error && ndist < max_error ) return true; } return false; } Matx33d _R, _K, _H; Vec3d _t, _n; }; TEST(Calib3d_DecomposeHomography, regression) { CV_HomographyDecompTest test; test.safe_run(); } <commit_msg>moving comment from the copyright message<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2014, Samson Yilma¸ (samson_yilma@yahoo.com), all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ // This is a test file for the function decomposeHomography contributed to OpenCV // by Samson Yilma. #include "test_precomp.hpp" #include "opencv2/calib3d.hpp" #include <vector> using namespace cv; using namespace std; class CV_HomographyDecompTest: public cvtest::BaseTest { public: CV_HomographyDecompTest() { buildTestDataSet(); } protected: void run(int) { vector<Mat> rotations; vector<Mat> translations; vector<Mat> normals; decomposeHomographyMat(_H, _K, rotations, translations, normals); //there should be at least 1 solution ASSERT_GT(static_cast<int>(rotations.size()), 0); ASSERT_GT(static_cast<int>(translations.size()), 0); ASSERT_GT(static_cast<int>(normals.size()), 0); ASSERT_EQ(rotations.size(), normals.size()); ASSERT_EQ(translations.size(), normals.size()); ASSERT_TRUE(containsValidMotion(rotations, translations, normals)); decomposeHomographyMat(_H, _K, rotations, noArray(), noArray()); ASSERT_GT(static_cast<int>(rotations.size()), 0); } private: void buildTestDataSet() { _K = Matx33d(640, 0.0, 320, 0, 640, 240, 0, 0, 1); _H = Matx33d(2.649157564634028, 4.583875997496426, 70.694447785121326, -1.072756858861583, 3.533262150437228, 1513.656999614321649, 0.001303887589576, 0.003042206876298, 1.000000000000000 ); //expected solution for the given homography and intrinsic matrices _R = Matx33d(0.43307983549125, 0.545749113549648, -0.717356090899523, -0.85630229674426, 0.497582023798831, -0.138414255706431, 0.281404038139784, 0.67421809131173, 0.682818960388909); _t = Vec3d(1.826751712278038, 1.264718492450820, 0.195080809998819); _n = Vec3d(0.244875830334816, 0.480857890778889, 0.841909446789566); } bool containsValidMotion(std::vector<Mat>& rotations, std::vector<Mat>& translations, std::vector<Mat>& normals ) { double max_error = 1.0e-3; vector<Mat>::iterator riter = rotations.begin(); vector<Mat>::iterator titer = translations.begin(); vector<Mat>::iterator niter = normals.begin(); for (; riter != rotations.end() && titer != translations.end() && niter != normals.end(); ++riter, ++titer, ++niter) { double rdist = norm(*riter, _R, NORM_INF); double tdist = norm(*titer, _t, NORM_INF); double ndist = norm(*niter, _n, NORM_INF); if ( rdist < max_error && tdist < max_error && ndist < max_error ) return true; } return false; } Matx33d _R, _K, _H; Vec3d _t, _n; }; TEST(Calib3d_DecomposeHomography, regression) { CV_HomographyDecompTest test; test.safe_run(); } <|endoftext|>
<commit_before>/* * start.hpp * ChessPlusPlus * * Created by Ronak Gajrawala on 12/01/13. * Copyright (c) 2013 Ronak Gajrawala. All rights reserved. */ #ifndef ChessPlusPlus_start_hpp #define ChessPlusPlus_start_hpp /** * The StartPage class. * The main starting page or menu is created and handled here. */ class StartPage { sf::RenderWindow Window; /**< The window of the menu. */ sf::Font Font; /**< The font that the text on the menu will use (sansation.ttf). */ sf::Event Event; /**< Any window events. */ sf::Vector2u Mouse; /**< Mouse coordinates. */ sf::Image Icon; /**< The icon for the window */ sf::Text Title; /**< The menu's title. Will say: "Chess++". */ sf::Text WhoWonText; /**< Shows who won. */ sf::RectangleShape NewGameButton; /**< The button for New Game. */ sf::Text NewGameText; /**< Will say: "New Game". */ sf::RectangleShape ReaderButton; /**< The button for the reader. */ sf::Text ReaderText; /**< Will say: "Reader". */ short WhoWon = 0; /**< Who won the game. 1 if white won. 2 if black won. 0 if game is still playing or tie. */ bool Go; /**< True if to go to game, otherwise false if to go to reader. */ public: /** * Creates the menu and other important parts of the start page. */ void Initialize(void); /** * Closes the window. */ void CleanUp(void); /** * Main loop for the start page. * Initializes, runs / loops, and cleans up. * @return True if to go to game, false if to go to reader. */ bool Main(void); /** * Event handler for window events. */ void OnEvent(void); /** * Event handler for mouse moves. * @see OnEvent */ void OnMouseMove(void); /** * Event handler for key presses. * @see OnEvent */ void OnKeyPressed(void); /** * Handler for mouse button releases. * @see OnEvent */ void OnMouseButtonReleased(void); /** * Sets WhoWon. * @see WhoWon */ void SetWhoWon(short); } StartPage; ////////// SOURCE ////////// void StartPage::Initialize(void) { this->Window.create(sf::VideoMode(600, 600), "ChessPlusPlus - Start Page", sf::Style::Close); this->Window.setFramerateLimit(10); if (!this->Icon.loadFromFile(GetResource("white_knight.png"))) { exit(EXIT_FAILURE); } this->Window.setIcon(this->Icon.getSize().x, this->Icon.getSize().y, this->Icon.getPixelsPtr()); if(!this->Font.loadFromFile(GetResource("sansation.ttf"))) { exit(EXIT_FAILURE); } this->Title.setFont(this->Font); this->Title.setString("Chess++"); this->Title.setPosition(110.0, 50.0); this->Title.setCharacterSize(100); this->NewGameText.setColor(sf::Color::Blue); this->NewGameButton.setFillColor(sf::Color::Yellow); this->NewGameButton.setSize(sf::Vector2f(300.0, 50.0)); this->NewGameButton.setPosition(150.0, 200.0); this->ReaderButton.setFillColor(sf::Color::Yellow); this->ReaderButton.setSize(sf::Vector2f(300.0, 50.0)); this->ReaderButton.setPosition(150.0, 275.0); this->NewGameText.setFont(this->Font); this->NewGameText.setColor(sf::Color::Blue); this->NewGameText.setPosition(200.0, 200.0); this->NewGameText.setCharacterSize(40); this->NewGameText.setString("New Game"); this->ReaderText.setFont(this->Font); this->ReaderText.setColor(sf::Color::Blue); this->ReaderText.setPosition(230.0, 275.0); this->ReaderText.setCharacterSize(40); this->ReaderText.setString("Reader"); this->WhoWonText.setFont(this->Font); if(this->WhoWon == 1) { this->WhoWonText.setString("White (Player 1) Won!"); } else if(this->WhoWon == 2) { this->WhoWonText.setString("Black (Player 2) Won!"); } else { this->WhoWonText.setString(""); } this->WhoWonText.setPosition(80.0, 310.0); this->WhoWonText.setCharacterSize(25); this->WhoWon = 0; } void StartPage::CleanUp(void) { this->Window.close(); } void StartPage::OnMouseMove(void) { this->Mouse.x = Event.mouseMove.x; this->Mouse.y = Event.mouseMove.y; } void StartPage::OnKeyPressed(void) { if(((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.control) or ((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.alt)) { this->CleanUp(); exit(EXIT_SUCCESS); } } void StartPage::OnMouseButtonReleased(void) { if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->NewGameButton.getPosition().x, this->NewGameButton.getPosition().y, this->NewGameButton.getSize().x, this->NewGameButton.getSize().y)) { Sounds.Music3.play(); this->Go = true; this->CleanUp(); } else if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->ReaderButton.getPosition().x, this->ReaderButton.getPosition().y, this->ReaderButton.getSize().x, this->ReaderButton.getSize().y)) { Sounds.Music3.play(); this->Go = false; this->CleanUp(); } } void StartPage::OnEvent(void) { switch(this->Event.type) { case sf::Event::Closed: exit(EXIT_SUCCESS); case sf::Event::KeyPressed: this->OnKeyPressed(); break; case sf::Event::MouseMoved: this->OnMouseMove(); break; case sf::Event::MouseButtonReleased: this->OnMouseButtonReleased(); break; default: break; } } bool StartPage::Main(void) { this->Initialize(); while(this->Window.isOpen()) { this->Window.clear(sf::Color::Black); while(this->Window.pollEvent(this->Event)) { this->OnEvent(); } this->Window.draw(this->Title); this->Window.draw(this->NewGameButton); this->Window.draw(this->NewGameText); this->Window.draw(this->ReaderButton); this->Window.draw(this->ReaderText); this->Window.draw(this->WhoWonText); this->Window.display(); } return this->Go; } void StartPage::SetWhoWon(short whowon) { if(whowon > 2 or whowon < 0) { return; } this->WhoWon = whowon; } #endif <commit_msg>Update start.hpp<commit_after>/* * start.hpp * SimpleChess * * Created by Ronak Gajrawala on 12/01/13. * Copyright (c) 2013 Ronak Gajrawala. All rights reserved. */ #ifndef SimpleChess_start_hpp #define SimpleChess_start_hpp /** * The StartPage class. * The main starting page or menu is created and handled here. */ class StartPage { sf::RenderWindow Window; /**< The window of the menu. */ sf::Font Font; /**< The font that the text on the menu will use (sansation.ttf). */ sf::Event Event; /**< Any window events. */ sf::Vector2u Mouse; /**< Mouse coordinates. */ sf::Image Icon; /**< The icon for the window */ sf::Text Title; /**< The menu's title. Will say: "Simple Chess". */ sf::Text WhoWonText; /**< Shows who won. */ sf::RectangleShape NewGameButton; /**< The button for New Game. */ sf::Text NewGameText; /**< Will say: "New Game". */ sf::RectangleShape ReaderButton; /**< The button for the reader. */ sf::Text ReaderText; /**< Will say: "Reader". */ short WhoWon = 0; /**< Who won the game. 1 if white won. 2 if black won. 0 if game is still playing or tie. */ bool Go; /**< True if to go to game, otherwise false if to go to reader. */ public: /** * Creates the menu and other important parts of the start page. */ void Initialize(void); /** * Closes the window. */ void CleanUp(void); /** * Main loop for the start page. * Initializes, runs / loops, and cleans up. * @return True if to go to game, false if to go to reader. */ bool Main(void); /** * Event handler for window events. */ void OnEvent(void); /** * Event handler for mouse moves. * @see OnEvent */ void OnMouseMove(void); /** * Event handler for key presses. * @see OnEvent */ void OnKeyPressed(void); /** * Handler for mouse button releases. * @see OnEvent */ void OnMouseButtonReleased(void); /** * Sets WhoWon. * @see WhoWon */ void SetWhoWon(short); } StartPage; ////////// SOURCE ////////// void StartPage::Initialize(void) { this->Window.create(sf::VideoMode(600, 600), "SimpleChess - Start Page", sf::Style::Close); this->Window.setFramerateLimit(10); if (!this->Icon.loadFromFile(GetResource("white_knight.png"))) { exit(EXIT_FAILURE); } this->Window.setIcon(this->Icon.getSize().x, this->Icon.getSize().y, this->Icon.getPixelsPtr()); if(!this->Font.loadFromFile(GetResource("sansation.ttf"))) { exit(EXIT_FAILURE); } this->Title.setFont(this->Font); this->Title.setString("SimpleChess"); this->Title.setPosition(20.0, 50.0); this->Title.setCharacterSize(100); this->NewGameText.setColor(sf::Color::Blue); this->NewGameButton.setFillColor(sf::Color::Yellow); this->NewGameButton.setSize(sf::Vector2f(300.0, 50.0)); this->NewGameButton.setPosition(150.0, 200.0); this->ReaderButton.setFillColor(sf::Color::Yellow); this->ReaderButton.setSize(sf::Vector2f(300.0, 50.0)); this->ReaderButton.setPosition(150.0, 275.0); this->NewGameText.setFont(this->Font); this->NewGameText.setColor(sf::Color::Blue); this->NewGameText.setPosition(200.0, 200.0); this->NewGameText.setCharacterSize(40); this->NewGameText.setString("New Game"); this->ReaderText.setFont(this->Font); this->ReaderText.setColor(sf::Color::Blue); this->ReaderText.setPosition(230.0, 275.0); this->ReaderText.setCharacterSize(40); this->ReaderText.setString("Reader"); this->WhoWonText.setFont(this->Font); if(this->WhoWon == 1) { this->WhoWonText.setString("White (Player 1) Won!"); } else if(this->WhoWon == 2) { this->WhoWonText.setString("Black (Player 2) Won!"); } else { this->WhoWonText.setString(""); } this->WhoWonText.setPosition(80.0, 310.0); this->WhoWonText.setCharacterSize(25); this->WhoWon = 0; } void StartPage::CleanUp(void) { this->Window.close(); } void StartPage::OnMouseMove(void) { this->Mouse.x = Event.mouseMove.x; this->Mouse.y = Event.mouseMove.y; } void StartPage::OnKeyPressed(void) { if(((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.control) or ((this->Event.key.code is sf::Keyboard::W or this->Event.key.code is sf::Keyboard::C) and this->Event.key.alt)) { this->CleanUp(); exit(EXIT_SUCCESS); } } void StartPage::OnMouseButtonReleased(void) { if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->NewGameButton.getPosition().x, this->NewGameButton.getPosition().y, this->NewGameButton.getSize().x, this->NewGameButton.getSize().y)) { Sounds.Music3.play(); this->Go = true; this->CleanUp(); } else if(Utils.Contains(this->Mouse.x, this->Mouse.y, this->ReaderButton.getPosition().x, this->ReaderButton.getPosition().y, this->ReaderButton.getSize().x, this->ReaderButton.getSize().y)) { Sounds.Music3.play(); this->Go = false; this->CleanUp(); } } void StartPage::OnEvent(void) { switch(this->Event.type) { case sf::Event::Closed: exit(EXIT_SUCCESS); case sf::Event::KeyPressed: this->OnKeyPressed(); break; case sf::Event::MouseMoved: this->OnMouseMove(); break; case sf::Event::MouseButtonReleased: this->OnMouseButtonReleased(); break; default: break; } } bool StartPage::Main(void) { this->Initialize(); while(this->Window.isOpen()) { this->Window.clear(sf::Color::Black); while(this->Window.pollEvent(this->Event)) { this->OnEvent(); } this->Window.draw(this->Title); this->Window.draw(this->NewGameButton); this->Window.draw(this->NewGameText); this->Window.draw(this->ReaderButton); this->Window.draw(this->ReaderText); this->Window.draw(this->WhoWonText); this->Window.display(); } return this->Go; } void StartPage::SetWhoWon(short whowon) { if(whowon > 2 or whowon < 0) { return; } this->WhoWon = whowon; } #endif <|endoftext|>
<commit_before>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/prctl.h> #include <vpr/Thread/Thread.h> #include <vpr/Thread/ThreadManager.h> #include <vpr/Util/Assert.h> #include <vpr/md/SPROC/Thread/ThreadSGI.h> namespace vpr { // Non-spawning constructor. This will not start a thread. ThreadSGI::ThreadSGI(BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { } /** * Spawning constructor. This will actually start a new thread that will * execute the specified function. */ ThreadSGI::ThreadSGI(thread_func_t func, void* arg, BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { // Create the thread functor to start. // XXX: Memory leak. setFunctor(new ThreadNonMemberFunctor(func, arg)); start(); } /** * Spawning constructor with arguments (functor version). This will start a * new thread that will execute the specified function. */ ThreadSGI::ThreadSGI(BaseThreadFunctor* functorPtr, BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { setFunctor(functorPtr); } void ThreadSGI::setFunctor(BaseThreadFunctor* functorPtr) { vprASSERT(! mRunning && "Thread already running"); vprASSERT(functorPtr->isValid()); mUserThreadFunctor = functorPtr; } vpr::ReturnStatus ThreadSGI::start() { vpr::ReturnStatus status; if ( mRunning ) { vprASSERT(false && "Thread already running"); status.setCode(vpr::ReturnStatus::Fail); } else if ( NULL == mUserThreadFunctor ) { vprASSERT(false && "No functor set"); status.setCode(vpr::ReturnStatus::Fail); } else { // XXX: Memory leak. ThreadMemberFunctor<ThreadSGI>* start_functor = new ThreadMemberFunctor<ThreadSGI>(this, &ThreadSGI::startThread, NULL); // START THREAD // NOTE: Automagically registers UNLESS failure status = spawn(start_functor); if ( status.success() ) { mRunning = true; } else { ThreadManager::instance()->lock(); { registerThread(false); // Failed to create } ThreadManager::instance()->unlock(); } } return status; } vpr::ReturnStatus ThreadSGI::spawn(BaseThreadFunctor* functorPtr) { vpr::ReturnStatus status; mThreadPID = sproc(thread_func_t(&vprThreadFunctorFunction), PR_SADDR | PR_SFDS, functorPtr); if ( mThreadPID == -1 ) { status.setCode(vpr::ReturnStatus::Fail); } return status; } /** * Called by the spawn routine to start the user thread function. */ void ThreadSGI::startThread(void* null_param) { // WE are a new thread... yeah!!!! // TELL EVERYONE THAT WE LIVE!!!! ThreadManager::instance()->lock(); // Lock manager { setLocalThreadPtr(this); // Store the pointer to me registerThread(true); } ThreadManager::instance()->unlock(); // Tell this thread to die when its parent dies prctl(PR_SETEXITSIG, 0); prctl(PR_TERMCHILD); // --- CALL USER FUNCTOR --- // (*mUserThreadFunctor)(); } /** * Makes the calling thread wait for the termination of the specified * thread. */ int ThreadSGI::join (void** arg) { int status, retval; pid_t pid; do { pid = ::waitpid(mThreadPID, &status, 0); } while ( WIFSTOPPED(status) != 0 ); if ( pid > -1 ) { vprASSERT(pid == mThreadPID); if ( WIFEXITED(status) != 0 && arg != NULL ) { **((int**) arg) = WEXITSTATUS(status); } else if ( WIFSIGNALED(status) != 0 && arg != NULL ) { **((int**) arg) = WTERMSIG(status); } retval = 0; } else { retval = -1; } return retval; } }; // End of vpr namespace <commit_msg>Added a missing call to start() in the functor auto-spawn constructor.<commit_after>/****************** <VPR heading BEGIN do not edit this line> ***************** * * VR Juggler Portable Runtime * * Original Authors: * Allen Bierbaum, Patrick Hartling, Kevin Meinert, Carolina Cruz-Neira * * ----------------------------------------------------------------- * File: $RCSfile$ * Date modified: $Date$ * Version: $Revision$ * ----------------------------------------------------------------- * ****************** <VPR heading END do not edit this line> ******************/ /*************** <auto-copyright.pl BEGIN do not edit this line> ************** * * VR Juggler is (C) Copyright 1998-2002 by Iowa State University * * Original Authors: * Allen Bierbaum, Christopher Just, * Patrick Hartling, Kevin Meinert, * Carolina Cruz-Neira, Albert Baker * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., 59 Temple Place - Suite 330, * Boston, MA 02111-1307, USA. * *************** <auto-copyright.pl END do not edit this line> ***************/ #include <vpr/vprConfig.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/prctl.h> #include <vpr/Thread/Thread.h> #include <vpr/Thread/ThreadManager.h> #include <vpr/Util/Assert.h> #include <vpr/md/SPROC/Thread/ThreadSGI.h> namespace vpr { // Non-spawning constructor. This will not start a thread. ThreadSGI::ThreadSGI(BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { } /** * Spawning constructor. This will actually start a new thread that will * execute the specified function. */ ThreadSGI::ThreadSGI(thread_func_t func, void* arg, BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { // Create the thread functor to start. // XXX: Memory leak. setFunctor(new ThreadNonMemberFunctor(func, arg)); start(); } /** * Spawning constructor with arguments (functor version). This will start a * new thread that will execute the specified function. */ ThreadSGI::ThreadSGI(BaseThreadFunctor* functorPtr, BaseThread::VPRThreadPriority priority, BaseThread::VPRThreadScope scope, BaseThread::VPRThreadState state, size_t stackSize) : mUserThreadFunctor(NULL), mRunning(false) { setFunctor(functorPtr); start(); } void ThreadSGI::setFunctor(BaseThreadFunctor* functorPtr) { vprASSERT(! mRunning && "Thread already running"); vprASSERT(functorPtr->isValid()); mUserThreadFunctor = functorPtr; } vpr::ReturnStatus ThreadSGI::start() { vpr::ReturnStatus status; if ( mRunning ) { vprASSERT(false && "Thread already running"); status.setCode(vpr::ReturnStatus::Fail); } else if ( NULL == mUserThreadFunctor ) { vprASSERT(false && "No functor set"); status.setCode(vpr::ReturnStatus::Fail); } else { // XXX: Memory leak. ThreadMemberFunctor<ThreadSGI>* start_functor = new ThreadMemberFunctor<ThreadSGI>(this, &ThreadSGI::startThread, NULL); // START THREAD // NOTE: Automagically registers UNLESS failure status = spawn(start_functor); if ( status.success() ) { mRunning = true; } else { ThreadManager::instance()->lock(); { registerThread(false); // Failed to create } ThreadManager::instance()->unlock(); } } return status; } vpr::ReturnStatus ThreadSGI::spawn(BaseThreadFunctor* functorPtr) { vpr::ReturnStatus status; mThreadPID = sproc(thread_func_t(&vprThreadFunctorFunction), PR_SADDR | PR_SFDS, functorPtr); if ( mThreadPID == -1 ) { status.setCode(vpr::ReturnStatus::Fail); } return status; } /** * Called by the spawn routine to start the user thread function. */ void ThreadSGI::startThread(void* null_param) { // WE are a new thread... yeah!!!! // TELL EVERYONE THAT WE LIVE!!!! ThreadManager::instance()->lock(); // Lock manager { setLocalThreadPtr(this); // Store the pointer to me registerThread(true); } ThreadManager::instance()->unlock(); // Tell this thread to die when its parent dies prctl(PR_SETEXITSIG, 0); prctl(PR_TERMCHILD); // --- CALL USER FUNCTOR --- // (*mUserThreadFunctor)(); } /** * Makes the calling thread wait for the termination of the specified * thread. */ int ThreadSGI::join (void** arg) { int status, retval; pid_t pid; do { pid = ::waitpid(mThreadPID, &status, 0); } while ( WIFSTOPPED(status) != 0 ); if ( pid > -1 ) { vprASSERT(pid == mThreadPID); if ( WIFEXITED(status) != 0 && arg != NULL ) { **((int**) arg) = WEXITSTATUS(status); } else if ( WIFSIGNALED(status) != 0 && arg != NULL ) { **((int**) arg) = WTERMSIG(status); } retval = 0; } else { retval = -1; } return retval; } }; // End of vpr namespace <|endoftext|>
<commit_before>#ifndef JOINT_DEVKIT_STACKSTORAGE_HPP #define JOINT_DEVKIT_STACKSTORAGE_HPP #include <joint/devkit/Holder.hpp> #include <array> namespace joint { namespace devkit { template < typename T_ > T_ AlignUp(T_ value, T_ alignment) { return alignment * ((value + alignment - 1) / alignment); } template < typename T_ > T_ AlignDown(T_ value, T_ alignment) { return alignment * (value / alignment); } template < typename T_, size_t BytesSize_ > class StackStorage { using ElementStorage = typename std::aligned_storage<sizeof(T_), alignof(T_)>::type; using BufArray = std::array<ElementStorage, BytesSize_ / sizeof(T_)>; struct BlockDescriptor { size_t Count; ElementStorage* Pointer; }; using BlocksVector = std::vector<BlockDescriptor>; private: BufArray _buf; size_t _freeOfs; BlocksVector _fallbackBlocks; public: StackStorage() : _freeOfs() { } StackStorage(const StackStorage&) = delete; StackStorage* operator = (const StackStorage&) = delete; ~StackStorage() { while (_freeOfs--) reinterpret_cast<T_&>(_buf[_freeOfs]).~T_(); for (auto block : _fallbackBlocks) { auto count = block.Count; auto ptr = block.Pointer; for (size_t i = 0; i < count; ++i) reinterpret_cast<T_&>(ptr[i]).~T_(); delete[] ptr; } } T_* Make(size_t count) { return AllocateAndConstruct(count, [&](T_* p) { size_t i = 0; auto sg(ScopeExit([&]() { while (i--) p[i].~T_(); })); for (; i < count; ++i) new(p + i) T_; sg.Cancel(); }); } template < typename... Args_ > T_& MakeSingle(Args_&&... args) { return *AllocateAndConstruct(1, [&](T_* p) { new(p) T_(std::forward<Args_>(args)...); }); } private: template < typename ConstructFunc_ > T_* AllocateAndConstruct(size_t count, ConstructFunc_&& constructFunc) { T_* result; if (_buf.size() >= _freeOfs + count) { auto ptr = &_buf[_freeOfs]; _freeOfs += count; auto sg(ScopeExit([&]{ _freeOfs -= count; })); result = reinterpret_cast<T_*>(ptr); constructFunc(result); sg.Cancel(); } else { static_assert(sizeof(ElementStorage) >= sizeof(T_), "sdfsdfgsdfg"); auto ptr = new ElementStorage[count]; _fallbackBlocks.push_back({ count, ptr }); auto sg(ScopeExit([&]{ _fallbackBlocks.pop_back(); delete[] ptr; })); result = reinterpret_cast<T_*>(ptr); constructFunc(result); sg.Cancel(); } return result; } }; }} #endif <commit_msg>Fixed gcc-4.8 build<commit_after>#ifndef JOINT_DEVKIT_STACKSTORAGE_HPP #define JOINT_DEVKIT_STACKSTORAGE_HPP #include <joint/devkit/Holder.hpp> #include <array> namespace joint { namespace devkit { template < typename T_ > T_ AlignUp(T_ value, T_ alignment) { return alignment * ((value + alignment - 1) / alignment); } template < typename T_ > T_ AlignDown(T_ value, T_ alignment) { return alignment * (value / alignment); } template < typename T_, size_t BytesSize_ > class StackStorage { using ElementStorage = typename std::aligned_storage<sizeof(T_), alignof(T_)>::type; using BufArray = std::array<ElementStorage, BytesSize_ / sizeof(T_)>; struct BlockDescriptor { size_t Count; ElementStorage* Pointer; }; using BlocksVector = std::vector<BlockDescriptor>; private: BufArray _buf; size_t _freeOfs; BlocksVector _fallbackBlocks; public: StackStorage() : _freeOfs() { } StackStorage(const StackStorage&) = delete; StackStorage* operator = (const StackStorage&) = delete; ~StackStorage() { while (_freeOfs--) reinterpret_cast<T_&>(_buf[_freeOfs]).~T_(); for (auto block : _fallbackBlocks) { auto count = block.Count; auto ptr = block.Pointer; for (size_t i = 0; i < count; ++i) reinterpret_cast<T_&>(ptr[i]).~T_(); delete[] ptr; } } T_* Make(size_t count) { return AllocateAndConstruct(count, [&](T_* p) { size_t i = 0; auto sg(ScopeExit([&]() { while (i--) p[i].~T_(); })); for (; i < count; ++i) new(p + i) T_; sg.Cancel(); }); } template < typename... Args_ > T_& MakeSingle(Args_&&... args) { return *AllocateAndConstruct(1, [&](T_* p, Args_&&... a) { new(p) T_(std::forward<Args_>(a)...); }, std::forward<Args_>(args)...); } private: template < typename ConstructFunc_, typename... Args_ > T_* AllocateAndConstruct(size_t count, ConstructFunc_&& constructFunc, Args_&&... args) { T_* result; if (_buf.size() >= _freeOfs + count) { auto ptr = &_buf[_freeOfs]; _freeOfs += count; auto sg(ScopeExit([&]{ _freeOfs -= count; })); result = reinterpret_cast<T_*>(ptr); constructFunc(result, std::forward<Args_>(args)...); sg.Cancel(); } else { static_assert(sizeof(ElementStorage) >= sizeof(T_), "sdfsdfgsdfg"); auto ptr = new ElementStorage[count]; _fallbackBlocks.push_back({ count, ptr }); auto sg(ScopeExit([&]{ _fallbackBlocks.pop_back(); delete[] ptr; })); result = reinterpret_cast<T_*>(ptr); constructFunc(result, std::forward<Args_>(args)...); sg.Cancel(); } return result; } }; }} #endif <|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS ooo19126 (1.1.1.1.110); FILE MERGED 2005/09/05 18:43:19 rt 1.1.1.1.110.1: #i54170# Change license header: remove SISSL<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "config.h" #include "ThreadGlobalData.h" #include "EventNames.h" #include "StringImpl.h" #include "ThreadTimers.h" #include <wtf/UnusedParam.h> #include <wtf/WTFThreadData.h> #if USE(ICU_UNICODE) #include "TextCodecICU.h" #endif #if PLATFORM(MAC) #include "TextCodecMac.h" #endif #if ENABLE(WORKERS) #include <wtf/Threading.h> #include <wtf/ThreadSpecific.h> using namespace WTF; #endif namespace WebCore { #if ENABLE(WORKERS) ThreadSpecific<ThreadGlobalData>* ThreadGlobalData::staticData; #else ThreadGlobalData* ThreadGlobalData::staticData; #endif ThreadGlobalData::ThreadGlobalData() : m_eventNames(new EventNames) , m_threadTimers(new ThreadTimers) #ifndef NDEBUG , m_isMainThread(isMainThread()) #endif #if USE(ICU_UNICODE) , m_cachedConverterICU(new ICUConverterWrapper) #endif #if PLATFORM(MAC) , m_cachedConverterTEC(new TECConverterWrapper) #endif { // This constructor will have been called on the main thread before being called on // any other thread, and is only called once per thread – this makes this a convenient // point to call methods that internally perform a one-time initialization that is not // threadsafe. wtfThreadData(); StringImpl::empty(); } ThreadGlobalData::~ThreadGlobalData() { #if PLATFORM(MAC) delete m_cachedConverterTEC; #endif #if USE(ICU_UNICODE) delete m_cachedConverterICU; #endif delete m_eventNames; delete m_threadTimers; } } // namespace WebCore <commit_msg>Unreviewed. Build fix on Japanese Windows. Replace a non-ASCII character in a comment with an ASCII character.<commit_after>/* * Copyright (C) 2008 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "config.h" #include "ThreadGlobalData.h" #include "EventNames.h" #include "StringImpl.h" #include "ThreadTimers.h" #include <wtf/UnusedParam.h> #include <wtf/WTFThreadData.h> #if USE(ICU_UNICODE) #include "TextCodecICU.h" #endif #if PLATFORM(MAC) #include "TextCodecMac.h" #endif #if ENABLE(WORKERS) #include <wtf/Threading.h> #include <wtf/ThreadSpecific.h> using namespace WTF; #endif namespace WebCore { #if ENABLE(WORKERS) ThreadSpecific<ThreadGlobalData>* ThreadGlobalData::staticData; #else ThreadGlobalData* ThreadGlobalData::staticData; #endif ThreadGlobalData::ThreadGlobalData() : m_eventNames(new EventNames) , m_threadTimers(new ThreadTimers) #ifndef NDEBUG , m_isMainThread(isMainThread()) #endif #if USE(ICU_UNICODE) , m_cachedConverterICU(new ICUConverterWrapper) #endif #if PLATFORM(MAC) , m_cachedConverterTEC(new TECConverterWrapper) #endif { // This constructor will have been called on the main thread before being called on // any other thread, and is only called once per thread - this makes this a convenient // point to call methods that internally perform a one-time initialization that is not // threadsafe. wtfThreadData(); StringImpl::empty(); } ThreadGlobalData::~ThreadGlobalData() { #if PLATFORM(MAC) delete m_cachedConverterTEC; #endif #if USE(ICU_UNICODE) delete m_cachedConverterICU; #endif delete m_eventNames; delete m_threadTimers; } } // namespace WebCore <|endoftext|>
<commit_before>/* * Copyright 2014 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PipelineManager.h" #include "img/fcc_to_string.h" #include "internal.h" #include <algorithm> #include <cstring> #include <ctime> #include <utils.h> using namespace tcam; PipelineManager::PipelineManager() : status(TCAM_PIPELINE_UNDEFINED), current_ppl_buffer(0) {} PipelineManager::~PipelineManager() { if (status == TCAM_PIPELINE_PLAYING) { stop_playing(); } if (m_pipeline_thread.joinable()) { m_pipeline_thread.join(); } available_filter.clear(); filter_pipeline.clear(); } std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats() const { return available_output_formats; } bool PipelineManager::setVideoFormat(const VideoFormat& f) { this->output_format = f; return true; } VideoFormat PipelineManager::getVideoFormat() const { return this->output_format; } bool PipelineManager::set_status(TCAM_PIPELINE_STATUS s) { if (status == s) return true; this->status = s; if (status == TCAM_PIPELINE_PLAYING) { if (create_pipeline()) { start_playing(); SPDLOG_INFO("All pipeline elements set to PLAYING."); } else { status = TCAM_PIPELINE_ERROR; return false; } } else if (status == TCAM_PIPELINE_STOPPED) { stop_playing(); } return true; } TCAM_PIPELINE_STATUS PipelineManager::get_status() const { return status; } bool PipelineManager::destroyPipeline() { set_status(TCAM_PIPELINE_STOPPED); source = nullptr; sink = nullptr; return true; } bool PipelineManager::setSource(std::shared_ptr<DeviceInterface> device) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } available_input_formats = device->get_available_video_formats(); SPDLOG_DEBUG("Received {} formats.", available_input_formats.size()); distributeProperties(); this->source = std::make_shared<ImageSource>(); source->setSink(shared_from_this()); source->setDevice(device); property_filter = std::make_shared<tcam::stream::filter::PropertyFilter>(device->get_properties()); available_output_formats = available_input_formats; if (available_output_formats.empty()) { SPDLOG_ERROR("No output formats available."); return false; } return true; } std::shared_ptr<ImageSource> PipelineManager::getSource() { return source; } bool PipelineManager::setSink(std::shared_ptr<SinkInterface> s) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } this->sink = s; this->sink->set_source(shared_from_this()); return true; } std::shared_ptr<SinkInterface> PipelineManager::getSink() { return sink; } void PipelineManager::distributeProperties() { //for (auto& f : available_filter) { f->setDeviceProperties(device_properties); } } static bool isFilterApplicable(uint32_t fourcc, const std::vector<uint32_t>& vec) { if (std::find(vec.begin(), vec.end(), fourcc) == vec.end()) { return false; } return true; } void PipelineManager::create_input_format(uint32_t fourcc) { input_format = output_format; input_format.set_fourcc(fourcc); } std::vector<uint32_t> PipelineManager::getDeviceFourcc() { // for easy usage we create a vector<fourcc> for avail. inputs std::vector<uint32_t> device_fourcc; for (const auto& v : available_input_formats) { SPDLOG_DEBUG( "Found device fourcc '{}' - {:x}", img::fcc_to_string(v.get_fourcc()), v.get_fourcc()); device_fourcc.push_back(v.get_fourcc()); } return device_fourcc; } bool PipelineManager::set_source_status(TCAM_PIPELINE_STATUS _status) { if (source == nullptr) { SPDLOG_ERROR("Source is not defined"); return false; } if (!source->set_status(_status)) { SPDLOG_ERROR("Source did not accept status change"); return false; } return true; } bool PipelineManager::set_sink_status(TCAM_PIPELINE_STATUS _status) { if (sink == nullptr) { if (_status != TCAM_PIPELINE_STOPPED) // additional check to prevent warning when pipeline comes up { SPDLOG_WARN("Sink is not defined."); } return false; } if (!sink->set_status(_status)) { SPDLOG_ERROR("Sink spewed error"); return false; } return true; } bool PipelineManager::validate_pipeline() { // check if pipeline is valid if (source.get() == nullptr || sink.get() == nullptr) { return false; } // check source format auto in_format = source->getVideoFormat(); if (in_format != this->input_format) { SPDLOG_DEBUG("Video format in source does not match pipeline: '{}' != '{}'", in_format.to_string().c_str(), input_format.to_string().c_str()); return false; } else { SPDLOG_DEBUG("Starting pipeline with format: '{}'", in_format.to_string().c_str()); } VideoFormat in; VideoFormat out; for (auto f : filter_pipeline) { f->getVideoFormat(in, out); if (in != in_format) { SPDLOG_ERROR("Ingoing video format for filter {} is not compatible with previous " "element. '{}' != '{}'", f->getDescription().name.c_str(), in_format.to_string().c_str(), in.to_string().c_str()); return false; } else { SPDLOG_DEBUG("Filter {} connected to pipeline -- {}", f->getDescription().name.c_str(), out.to_string().c_str()); // save output for next comparison in_format = out; } } if (in_format != this->output_format) { SPDLOG_ERROR("Video format in sink does not match pipeline '{}' != '{}'", in_format.to_string().c_str(), output_format.to_string().c_str()); return false; } return true; } bool PipelineManager::create_conversion_pipeline() { if (source.get() == nullptr || sink.get() == nullptr) { return false; } auto device_fourcc = getDeviceFourcc(); create_input_format(output_format.get_fourcc()); for (auto f : available_filter) { std::string s = f->getDescription().name; if (f->getDescription().type == FILTER_TYPE_CONVERSION) { if (isFilterApplicable(output_format.get_fourcc(), f->getDescription().output_fourcc)) { bool filter_valid = false; uint32_t fourcc_to_use = 0; for (const auto& cc : device_fourcc) { if (isFilterApplicable(cc, f->getDescription().input_fourcc)) { filter_valid = true; fourcc_to_use = cc; break; } } // set device format to use correct fourcc create_input_format(fourcc_to_use); if (filter_valid) { if (f->setVideoFormat(input_format, output_format)) { SPDLOG_DEBUG("Added filter \"{}\" to pipeline", s.c_str()); filter_pipeline.push_back(f); } else { SPDLOG_DEBUG("Filter {} did not accept format settings", s.c_str()); } } else { SPDLOG_DEBUG("Filter {} does not use the device output formats.", s.c_str()); } } else { SPDLOG_DEBUG("Filter {} is not applicable", s.c_str()); } } } return true; } bool PipelineManager::add_interpretation_filter() { // if a valid pipeline can be created insert additional filter (e.g. autoexposure) // interpretations should be done as early as possible in the pipeline for (auto& f : available_filter) { if (f->getDescription().type == FILTER_TYPE_INTERPRET) { std::string s = f->getDescription().name; // applicable to sink bool all_formats = false; if (f->getDescription().input_fourcc.size() == 1) { if (f->getDescription().input_fourcc.at(0) == 0) { all_formats = true; } } if (all_formats || isFilterApplicable(input_format.get_fourcc(), f->getDescription().input_fourcc)) { SPDLOG_DEBUG("Adding filter '{}' after source", s.c_str()); f->setVideoFormat(input_format, input_format); filter_pipeline.insert(filter_pipeline.begin(), f); continue; } else { SPDLOG_DEBUG("Filter '{}' not usable after source", s.c_str()); } if (f->setVideoFormat(input_format, input_format)) { continue; } } } return true; } bool PipelineManager::create_pipeline() { if (source.get() == nullptr || sink.get() == nullptr) { return false; } // assure everything is in a defined state filter_pipeline.clear(); if (!create_conversion_pipeline()) { SPDLOG_ERROR("Unable to determine conversion pipeline."); return false; } if (!source->setVideoFormat(input_format)) { SPDLOG_ERROR("Unable to set video format in source."); return false; } if (!sink->setVideoFormat(output_format)) { SPDLOG_ERROR("Unable to set video format in sink."); return false; } if (!source->set_buffer_collection(sink->get_buffer_collection())) { SPDLOG_ERROR("Unable to set buffer collection."); return false; } SPDLOG_INFO("Pipeline creation successful."); std::string ppl = "source -> "; property_filter->setVideoFormat(output_format, output_format); for (const auto& f : filter_pipeline) { ppl += f->getDescription().name; ppl += " -> "; } ppl += " sink"; SPDLOG_INFO("{}", ppl.c_str()); return true; } bool PipelineManager::start_playing() { if (!set_sink_status(TCAM_PIPELINE_PLAYING)) { SPDLOG_ERROR("Sink refused to change to state PLAYING"); goto error; } if (!set_source_status(TCAM_PIPELINE_PLAYING)) { SPDLOG_ERROR("Source refused to change to state PLAYING"); goto error; } property_filter->setStatus(TCAM_PIPELINE_PLAYING); status = TCAM_PIPELINE_PLAYING; m_pipeline_thread = std::thread(&PipelineManager::run_pipeline, this); return true; error: stop_playing(); return false; } bool PipelineManager::stop_playing() { status = TCAM_PIPELINE_STOPPED; m_cv.notify_all(); if (!set_source_status(TCAM_PIPELINE_STOPPED)) { SPDLOG_ERROR("Source refused to change to state STOP"); return false; } for (auto& f : filter_pipeline) { if (!f->setStatus(TCAM_PIPELINE_STOPPED)) { SPDLOG_ERROR("Filter {} refused to change to state STOP", f->getDescription().name.c_str()); return false; } } set_sink_status(TCAM_PIPELINE_STOPPED); property_filter->setStatus(TCAM_PIPELINE_STOPPED); //destroyPipeline(); return true; } void PipelineManager::push_image(std::shared_ptr<ImageBuffer> buffer) { if (status == TCAM_PIPELINE_STOPPED) { return; } std::scoped_lock lock (m_mtx); m_entry_queue.push(buffer); m_cv.notify_all(); } void PipelineManager::requeue_buffer(std::shared_ptr<ImageBuffer> buffer) { if (source) { source->requeue_buffer(buffer); } } std::vector<std::shared_ptr<ImageBuffer>> PipelineManager::get_buffer_collection() { return std::vector<std::shared_ptr<ImageBuffer>>(); } void PipelineManager::drop_incomplete_frames(bool drop_them) { if (source) { source->drop_incomplete_frames(drop_them); } } bool PipelineManager::should_incomplete_frames_be_dropped() const { if (source) { return source->should_incomplete_frames_be_dropped(); } SPDLOG_ERROR("No shource to ask if incomplete frames should be dropped."); return true; } std::vector<std::shared_ptr<tcam::property::IPropertyBase>> PipelineManager::get_properties() { return property_filter->getProperties(); } void PipelineManager::run_pipeline() { while (status == TCAM_PIPELINE_PLAYING) { std::unique_lock lock(m_mtx); pl_wait_again: while (status == TCAM_PIPELINE_PLAYING && m_entry_queue.empty()) { m_cv.wait(lock); } if (status != TCAM_PIPELINE_PLAYING) { SPDLOG_INFO("Pipeline not in playing. Stopping pipeline thread."); return; } if (m_entry_queue.empty()) { SPDLOG_ERROR("Buffer queue is empty. Returning to waiting position."); goto pl_wait_again; } // SPDLOG_DEBUG("Working on new image"); auto& current_buffer = m_entry_queue.front(); m_entry_queue.pop(); // remove buffer from queue property_filter->apply(current_buffer); if (sink != nullptr) { sink->push_image(current_buffer); } else { SPDLOG_ERROR("Sink is NULL"); } } } <commit_msg>srcs: Add periodic state checks<commit_after>/* * Copyright 2014 The Imaging Source Europe GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "PipelineManager.h" #include "img/fcc_to_string.h" #include "internal.h" #include <algorithm> #include <chrono> #include <cstring> #include <ctime> #include <utils.h> using namespace tcam; PipelineManager::PipelineManager() : status(TCAM_PIPELINE_UNDEFINED), current_ppl_buffer(0) {} PipelineManager::~PipelineManager() { if (status == TCAM_PIPELINE_PLAYING) { stop_playing(); } if (m_pipeline_thread.joinable()) { m_pipeline_thread.join(); } available_filter.clear(); filter_pipeline.clear(); } std::vector<VideoFormatDescription> PipelineManager::getAvailableVideoFormats() const { return available_output_formats; } bool PipelineManager::setVideoFormat(const VideoFormat& f) { this->output_format = f; return true; } VideoFormat PipelineManager::getVideoFormat() const { return this->output_format; } bool PipelineManager::set_status(TCAM_PIPELINE_STATUS s) { if (status == s) return true; this->status = s; if (status == TCAM_PIPELINE_PLAYING) { if (create_pipeline()) { start_playing(); SPDLOG_INFO("All pipeline elements set to PLAYING."); } else { status = TCAM_PIPELINE_ERROR; return false; } } else if (status == TCAM_PIPELINE_STOPPED) { stop_playing(); } return true; } TCAM_PIPELINE_STATUS PipelineManager::get_status() const { return status; } bool PipelineManager::destroyPipeline() { set_status(TCAM_PIPELINE_STOPPED); source = nullptr; sink = nullptr; return true; } bool PipelineManager::setSource(std::shared_ptr<DeviceInterface> device) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } available_input_formats = device->get_available_video_formats(); SPDLOG_DEBUG("Received {} formats.", available_input_formats.size()); distributeProperties(); this->source = std::make_shared<ImageSource>(); source->setSink(shared_from_this()); source->setDevice(device); property_filter = std::make_shared<tcam::stream::filter::PropertyFilter>(device->get_properties()); available_output_formats = available_input_formats; if (available_output_formats.empty()) { SPDLOG_ERROR("No output formats available."); return false; } return true; } std::shared_ptr<ImageSource> PipelineManager::getSource() { return source; } bool PipelineManager::setSink(std::shared_ptr<SinkInterface> s) { if (status == TCAM_PIPELINE_PLAYING || status == TCAM_PIPELINE_PAUSED) { return false; } this->sink = s; this->sink->set_source(shared_from_this()); return true; } std::shared_ptr<SinkInterface> PipelineManager::getSink() { return sink; } void PipelineManager::distributeProperties() { //for (auto& f : available_filter) { f->setDeviceProperties(device_properties); } } static bool isFilterApplicable(uint32_t fourcc, const std::vector<uint32_t>& vec) { if (std::find(vec.begin(), vec.end(), fourcc) == vec.end()) { return false; } return true; } void PipelineManager::create_input_format(uint32_t fourcc) { input_format = output_format; input_format.set_fourcc(fourcc); } std::vector<uint32_t> PipelineManager::getDeviceFourcc() { // for easy usage we create a vector<fourcc> for avail. inputs std::vector<uint32_t> device_fourcc; for (const auto& v : available_input_formats) { SPDLOG_DEBUG( "Found device fourcc '{}' - {:x}", img::fcc_to_string(v.get_fourcc()), v.get_fourcc()); device_fourcc.push_back(v.get_fourcc()); } return device_fourcc; } bool PipelineManager::set_source_status(TCAM_PIPELINE_STATUS _status) { if (source == nullptr) { SPDLOG_ERROR("Source is not defined"); return false; } if (!source->set_status(_status)) { SPDLOG_ERROR("Source did not accept status change"); return false; } return true; } bool PipelineManager::set_sink_status(TCAM_PIPELINE_STATUS _status) { if (sink == nullptr) { if (_status != TCAM_PIPELINE_STOPPED) // additional check to prevent warning when pipeline comes up { SPDLOG_WARN("Sink is not defined."); } return false; } if (!sink->set_status(_status)) { SPDLOG_ERROR("Sink spewed error"); return false; } return true; } bool PipelineManager::validate_pipeline() { // check if pipeline is valid if (source.get() == nullptr || sink.get() == nullptr) { return false; } // check source format auto in_format = source->getVideoFormat(); if (in_format != this->input_format) { SPDLOG_DEBUG("Video format in source does not match pipeline: '{}' != '{}'", in_format.to_string().c_str(), input_format.to_string().c_str()); return false; } else { SPDLOG_DEBUG("Starting pipeline with format: '{}'", in_format.to_string().c_str()); } VideoFormat in; VideoFormat out; for (auto f : filter_pipeline) { f->getVideoFormat(in, out); if (in != in_format) { SPDLOG_ERROR("Ingoing video format for filter {} is not compatible with previous " "element. '{}' != '{}'", f->getDescription().name.c_str(), in_format.to_string().c_str(), in.to_string().c_str()); return false; } else { SPDLOG_DEBUG("Filter {} connected to pipeline -- {}", f->getDescription().name.c_str(), out.to_string().c_str()); // save output for next comparison in_format = out; } } if (in_format != this->output_format) { SPDLOG_ERROR("Video format in sink does not match pipeline '{}' != '{}'", in_format.to_string().c_str(), output_format.to_string().c_str()); return false; } return true; } bool PipelineManager::create_conversion_pipeline() { if (source.get() == nullptr || sink.get() == nullptr) { return false; } auto device_fourcc = getDeviceFourcc(); create_input_format(output_format.get_fourcc()); for (auto f : available_filter) { std::string s = f->getDescription().name; if (f->getDescription().type == FILTER_TYPE_CONVERSION) { if (isFilterApplicable(output_format.get_fourcc(), f->getDescription().output_fourcc)) { bool filter_valid = false; uint32_t fourcc_to_use = 0; for (const auto& cc : device_fourcc) { if (isFilterApplicable(cc, f->getDescription().input_fourcc)) { filter_valid = true; fourcc_to_use = cc; break; } } // set device format to use correct fourcc create_input_format(fourcc_to_use); if (filter_valid) { if (f->setVideoFormat(input_format, output_format)) { SPDLOG_DEBUG("Added filter \"{}\" to pipeline", s.c_str()); filter_pipeline.push_back(f); } else { SPDLOG_DEBUG("Filter {} did not accept format settings", s.c_str()); } } else { SPDLOG_DEBUG("Filter {} does not use the device output formats.", s.c_str()); } } else { SPDLOG_DEBUG("Filter {} is not applicable", s.c_str()); } } } return true; } bool PipelineManager::add_interpretation_filter() { // if a valid pipeline can be created insert additional filter (e.g. autoexposure) // interpretations should be done as early as possible in the pipeline for (auto& f : available_filter) { if (f->getDescription().type == FILTER_TYPE_INTERPRET) { std::string s = f->getDescription().name; // applicable to sink bool all_formats = false; if (f->getDescription().input_fourcc.size() == 1) { if (f->getDescription().input_fourcc.at(0) == 0) { all_formats = true; } } if (all_formats || isFilterApplicable(input_format.get_fourcc(), f->getDescription().input_fourcc)) { SPDLOG_DEBUG("Adding filter '{}' after source", s.c_str()); f->setVideoFormat(input_format, input_format); filter_pipeline.insert(filter_pipeline.begin(), f); continue; } else { SPDLOG_DEBUG("Filter '{}' not usable after source", s.c_str()); } if (f->setVideoFormat(input_format, input_format)) { continue; } } } return true; } bool PipelineManager::create_pipeline() { if (source.get() == nullptr || sink.get() == nullptr) { return false; } // assure everything is in a defined state filter_pipeline.clear(); if (!create_conversion_pipeline()) { SPDLOG_ERROR("Unable to determine conversion pipeline."); return false; } if (!source->setVideoFormat(input_format)) { SPDLOG_ERROR("Unable to set video format in source."); return false; } if (!sink->setVideoFormat(output_format)) { SPDLOG_ERROR("Unable to set video format in sink."); return false; } if (!source->set_buffer_collection(sink->get_buffer_collection())) { SPDLOG_ERROR("Unable to set buffer collection."); return false; } SPDLOG_INFO("Pipeline creation successful."); std::string ppl = "source -> "; property_filter->setVideoFormat(output_format, output_format); for (const auto& f : filter_pipeline) { ppl += f->getDescription().name; ppl += " -> "; } ppl += " sink"; SPDLOG_INFO("{}", ppl.c_str()); return true; } bool PipelineManager::start_playing() { if (!set_sink_status(TCAM_PIPELINE_PLAYING)) { SPDLOG_ERROR("Sink refused to change to state PLAYING"); goto error; } if (!set_source_status(TCAM_PIPELINE_PLAYING)) { SPDLOG_ERROR("Source refused to change to state PLAYING"); goto error; } property_filter->setStatus(TCAM_PIPELINE_PLAYING); status = TCAM_PIPELINE_PLAYING; m_pipeline_thread = std::thread(&PipelineManager::run_pipeline, this); return true; error: stop_playing(); return false; } bool PipelineManager::stop_playing() { status = TCAM_PIPELINE_STOPPED; m_cv.notify_all(); if (!set_source_status(TCAM_PIPELINE_STOPPED)) { SPDLOG_ERROR("Source refused to change to state STOP"); return false; } for (auto& f : filter_pipeline) { if (!f->setStatus(TCAM_PIPELINE_STOPPED)) { SPDLOG_ERROR("Filter {} refused to change to state STOP", f->getDescription().name.c_str()); return false; } } set_sink_status(TCAM_PIPELINE_STOPPED); property_filter->setStatus(TCAM_PIPELINE_STOPPED); //destroyPipeline(); return true; } void PipelineManager::push_image(std::shared_ptr<ImageBuffer> buffer) { if (status == TCAM_PIPELINE_STOPPED) { return; } std::scoped_lock lock (m_mtx); m_entry_queue.push(buffer); m_cv.notify_all(); } void PipelineManager::requeue_buffer(std::shared_ptr<ImageBuffer> buffer) { if (source) { source->requeue_buffer(buffer); } } std::vector<std::shared_ptr<ImageBuffer>> PipelineManager::get_buffer_collection() { return std::vector<std::shared_ptr<ImageBuffer>>(); } void PipelineManager::drop_incomplete_frames(bool drop_them) { if (source) { source->drop_incomplete_frames(drop_them); } } bool PipelineManager::should_incomplete_frames_be_dropped() const { if (source) { return source->should_incomplete_frames_be_dropped(); } SPDLOG_ERROR("No shource to ask if incomplete frames should be dropped."); return true; } std::vector<std::shared_ptr<tcam::property::IPropertyBase>> PipelineManager::get_properties() { return property_filter->getProperties(); } void PipelineManager::run_pipeline() { while (status == TCAM_PIPELINE_PLAYING) { std::unique_lock lock(m_mtx); pl_wait_again: while (status == TCAM_PIPELINE_PLAYING && m_entry_queue.empty()) { m_cv.wait_for(lock, std::chrono::milliseconds(500)); } if (status != TCAM_PIPELINE_PLAYING) { SPDLOG_INFO("Pipeline not in playing. Stopping pipeline thread."); return; } if (m_entry_queue.empty()) { SPDLOG_ERROR("Buffer queue is empty. Returning to waiting position."); goto pl_wait_again; } // SPDLOG_DEBUG("Working on new image"); auto& current_buffer = m_entry_queue.front(); m_entry_queue.pop(); // remove buffer from queue property_filter->apply(current_buffer); if (sink != nullptr) { sink->push_image(current_buffer); } else { SPDLOG_ERROR("Sink is NULL"); } } } <|endoftext|>
<commit_before>/*! \file RendererApi.cpp * \author Jared Hoberock * \brief Implementation of RendererApi class. */ #include "RendererApi.h" #include "PathDebugRenderer.h" #include "EnergyRedistributionRenderer.h" #include "MetropolisRenderer.h" #include "DebugRenderer.h" #include "MultiStageMetropolisRenderer.h" #include "VarianceRenderer.h" #include "BatchMeansRenderer.h" #include "NoiseAwareMetropolisRenderer.h" #include "../path/PathApi.h" #include "../mutators/MutatorApi.h" #include "../importance/ImportanceApi.h" #include "../importance/LuminanceImportance.h" #include "HaltCriterion.h" using namespace boost; void RendererApi ::getDefaultAttributes(Gotham::AttributeMap &attr) { // call HaltCriterion first HaltCriterion::getDefaultAttributes(attr); attr["renderer:algorithm"] = "montecarlo"; attr["renderer:energyredistribution:mutationspersample"] = "1"; attr["renderer:energyredistribution:chainlength"] = "100"; attr["renderer:batchmeans:batches"] = "2"; attr["renderer:noiseawaremetropolis:varianceexponent"] = "0.5"; } // end RendererApi::getDefaultAttributes() Renderer *RendererApi ::renderer(Gotham::AttributeMap &attr) { // create a RandomSequence shared_ptr<RandomSequence> z(new RandomSequence()); // create a new Renderer Renderer *result = 0; // fish out the parameters std::string rendererName = attr["renderer:algorithm"]; float k = lexical_cast<float>(attr["renderer:energyredistribution:mutationspersample"]); size_t m = lexical_cast<size_t>(attr["renderer:energyredistribution:chainlength"]); size_t numBatches = lexical_cast<size_t>(attr["renderer:batchmeans:batches"]); Gotham::AttributeMap::const_iterator a = attr.find("renderer:targetrays"); if(a != attr.end()) { std::cerr << "Warning: attribute \"renderer::targetrays\" is deprecated." << std::endl; std::cerr << "Please use \"renderer::target::function\" and \"renderer::target::count\" instead." << std::endl; attr["renderer::target::function"] = std::string("rays"); attr["renderer::target::count"] = a->second; } // end if float varianceExponent = lexical_cast<float>(attr["renderer:noiseawaremetropolis:varianceexponent"]); std::string acceptanceFilename = attr["record:acceptance:outfile"]; std::string proposalFilename = attr["record:proposals:outfile"]; std::string targetFilename = attr["record:target:outfile"]; // create the renderer if(rendererName == "montecarlo") { // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); result = new PathDebugRenderer(z, sampler); } // end if else if(rendererName == "energyredistribution") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new EnergyRedistributionRenderer(k, m, z, mutator, importance); } // end else if else if(rendererName == "metropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new MetropolisRenderer(z, mutator, importance); } // end else if else if(rendererName == "multistagemetropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new MultiStageMetropolisRenderer(z, mutator, importance); } // end else if else if(rendererName == "noiseawaremetropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new NoiseAwareMetropolisRenderer(z, mutator, importance, varianceExponent); static_cast<NoiseAwareMetropolisRenderer*>(result)->setTargetFilename(targetFilename); } // end else if else if(rendererName == "altnoiseawaremetropolis") { std::cerr << "Warning: rendering algorithm \"altnoiseawaremetropolis\" is deprecated. Please use \"noiseawaremetropolis\" instead." << std::endl; // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new NoiseAwareMetropolisRenderer(z, mutator, importance, varianceExponent); static_cast<NoiseAwareMetropolisRenderer*>(result)->setTargetFilename(targetFilename); } // end else if else if(rendererName == "variance") { // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); VarianceRenderer *vr = new VarianceRenderer(z, sampler); result = vr; boost::shared_ptr<Record> v(new RenderFilm(512, 512, "variance.exr")); vr->setVarianceRecord(v); } // end else if else if(rendererName == "batchmeans") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new BatchMeansRenderer(z, mutator, importance, numBatches); } // end else if else if(rendererName == "debug") { result = new DebugRenderer(); } // end else if else { std::cerr << "Warning: unknown rendering algorithm \"" << rendererName << "\"." << std::endl; // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); result = new PathDebugRenderer(z, sampler); } // end else // XXX Remove this when we have successfully generalized target counts // get spp unsigned int spp = 4; a = attr.find("renderer:spp"); if(a != attr.end()) { any val = a->second; spp = atoi(any_cast<std::string>(val).c_str()); } // end if result->setSamplesPerPixel(spp); // create a HaltCriterion for MonteCarloRenderers if(dynamic_cast<MonteCarloRenderer*>(result)) { shared_ptr<HaltCriterion> halt(HaltCriterion::createCriterion(attr)); dynamic_cast<MonteCarloRenderer*>(result)->setHaltCriterion(halt); } // end if // set the acceptance filename for MetropolisRenderers // XXX this is all so shitty // i guess we need a MetropolisRecord which can also integrate acceptance and proposals? if(dynamic_cast<MetropolisRenderer*>(result)) { MetropolisRenderer *r = dynamic_cast<MetropolisRenderer*>(result); r->setAcceptanceFilename(acceptanceFilename); r->setProposalFilename(proposalFilename); } // end try return result; } // end RendererApi::renderer() <commit_msg>Respect how the new attributes work.<commit_after>/*! \file RendererApi.cpp * \author Jared Hoberock * \brief Implementation of RendererApi class. */ #include "RendererApi.h" #include "PathDebugRenderer.h" #include "EnergyRedistributionRenderer.h" #include "MetropolisRenderer.h" #include "DebugRenderer.h" #include "MultiStageMetropolisRenderer.h" #include "VarianceRenderer.h" #include "BatchMeansRenderer.h" #include "NoiseAwareMetropolisRenderer.h" #include "../path/PathApi.h" #include "../mutators/MutatorApi.h" #include "../importance/ImportanceApi.h" #include "../importance/LuminanceImportance.h" #include "HaltCriterion.h" #include "ExperimentalMetropolisRenderer.h" using namespace boost; void RendererApi ::getDefaultAttributes(Gotham::AttributeMap &attr) { // call HaltCriterion first HaltCriterion::getDefaultAttributes(attr); attr["renderer:algorithm"] = "montecarlo"; attr["renderer:energyredistribution:mutationspersample"] = "1"; attr["renderer:energyredistribution:chainlength"] = "100"; attr["renderer:batchmeans:batches"] = "2"; attr["renderer:noiseawaremetropolis:varianceexponent"] = "0.5"; } // end RendererApi::getDefaultAttributes() Renderer *RendererApi ::renderer(Gotham::AttributeMap &attr) { // create a RandomSequence shared_ptr<RandomSequence> z(new RandomSequence()); // create a new Renderer Renderer *result = 0; // fish out the parameters std::string rendererName = attr["renderer:algorithm"]; float k = lexical_cast<float>(attr["renderer:energyredistribution:mutationspersample"]); size_t m = lexical_cast<size_t>(attr["renderer:energyredistribution:chainlength"]); size_t numBatches = lexical_cast<size_t>(attr["renderer:batchmeans:batches"]); Gotham::AttributeMap::const_iterator a = attr.find("renderer:targetrays"); if(a != attr.end()) { std::cerr << "Warning: attribute \"renderer::targetrays\" is deprecated." << std::endl; std::cerr << "Please use \"renderer::target::function\" and \"renderer::target::count\" instead." << std::endl; attr["renderer:target:function"] = std::string("rays"); attr["renderer:target:count"] = a->second; } // end if float varianceExponent = lexical_cast<float>(attr["renderer:noiseawaremetropolis:varianceexponent"]); std::string acceptanceFilename = attr["record:acceptance:outfile"]; std::string proposalFilename = attr["record:proposals:outfile"]; std::string targetFilename = attr["record:target:outfile"]; // create the renderer if(rendererName == "montecarlo") { // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); result = new PathDebugRenderer(z, sampler); } // end if else if(rendererName == "energyredistribution") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new EnergyRedistributionRenderer(k, m, z, mutator, importance); } // end else if else if(rendererName == "metropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new MetropolisRenderer(z, mutator, importance); } // end else if else if(rendererName == "multistagemetropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new MultiStageMetropolisRenderer(z, mutator, importance); } // end else if else if(rendererName == "noiseawaremetropolis") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new NoiseAwareMetropolisRenderer(z, mutator, importance, varianceExponent); static_cast<NoiseAwareMetropolisRenderer*>(result)->setTargetFilename(targetFilename); } // end else if else if(rendererName == "altnoiseawaremetropolis") { std::cerr << "Warning: rendering algorithm \"altnoiseawaremetropolis\" is deprecated. Please use \"noiseawaremetropolis\" instead." << std::endl; // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new NoiseAwareMetropolisRenderer(z, mutator, importance, varianceExponent); static_cast<NoiseAwareMetropolisRenderer*>(result)->setTargetFilename(targetFilename); } // end else if else if(rendererName == "variance") { // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); VarianceRenderer *vr = new VarianceRenderer(z, sampler); result = vr; boost::shared_ptr<Record> v(new RenderFilm(512, 512, "variance.exr")); vr->setVarianceRecord(v); } // end else if else if(rendererName == "batchmeans") { // create a PathMutator shared_ptr<PathMutator> mutator(MutatorApi::mutator(attr)); // create a ScalarImportance shared_ptr<ScalarImportance> importance(ImportanceApi::importance(attr)); result = new BatchMeansRenderer(z, mutator, importance, numBatches); } // end else if else if(rendererName == "debug") { result = new DebugRenderer(); } // end else if else { std::cerr << "Warning: unknown rendering algorithm \"" << rendererName << "\"." << std::endl; // create a PathSampler shared_ptr<PathSampler> sampler(PathApi::sampler(attr)); result = new PathDebugRenderer(z, sampler); } // end else // XXX Remove this when we have successfully generalized target counts // get spp size_t spp = 4; a = attr.find("renderer:spp"); if(a != attr.end()) { spp = lexical_cast<size_t>(a->second); } // end if result->setSamplesPerPixel(spp); // create a HaltCriterion for MonteCarloRenderers if(dynamic_cast<MonteCarloRenderer*>(result)) { shared_ptr<HaltCriterion> halt(HaltCriterion::createCriterion(attr)); dynamic_cast<MonteCarloRenderer*>(result)->setHaltCriterion(halt); } // end if // set the acceptance filename for MetropolisRenderers // XXX this is all so shitty // i guess we need a MetropolisRecord which can also integrate acceptance and proposals? if(dynamic_cast<MetropolisRenderer*>(result)) { MetropolisRenderer *r = dynamic_cast<MetropolisRenderer*>(result); r->setAcceptanceFilename(acceptanceFilename); r->setProposalFilename(proposalFilename); } // end try return result; } // end RendererApi::renderer() <|endoftext|>
<commit_before>#include "PlayerAnimation.hpp" PlayerAnimation::PlayerAnimation(Ogre::SceneManager *sceneMgr, Ogre::Entity *entity) : mSceneMgr(sceneMgr) { // Controle bones individualy Ogre::Bone* bHead = entity->getSkeleton()->getBone("HEAD"); bHead->setManuallyControlled(true); // Setup the animation Ogre::Real duration=4.0; Ogre::Real step=duration/4.0; Ogre::Animation* animation = mSceneMgr->createAnimation("HeadRotate",duration); animation->setInterpolationMode(Ogre::Animation::IM_SPLINE); Ogre::NodeAnimationTrack* track = animation->createNodeTrack(0,entity->getSkeleton()->getBone("HEAD")); // Then make the animation Ogre::TransformKeyFrame* key; key = track->createNodeKeyFrame(0.0f); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(step); key->setRotation(Ogre::Quaternion(Ogre::Radian(3.14/2), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(2.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(3.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(-3.14/2), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(4.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); // Implement the animation mPlayerAnimationState = mSceneMgr->createAnimationState("HeadRotate"); mPlayerAnimationState->setEnabled(true); mPlayerAnimationState->setLoop(true); } Ogre::AnimationState* PlayerAnimation::getPlayerAnimationState() {return mPlayerAnimationState;} <commit_msg>renamed the animation to make the name unique for each player<commit_after>#include "PlayerAnimation.hpp" PlayerAnimation::PlayerAnimation(Ogre::SceneManager *sceneMgr, Ogre::Entity *entity) : mSceneMgr(sceneMgr) { // Controle bones individualy Ogre::Bone* bHead = entity->getSkeleton()->getBone("HEAD"); bHead->setManuallyControlled(true); // Setup the animation Ogre::Real duration=4.0; Ogre::Real step=duration/4.0; Ogre::Animation* animation = mSceneMgr->createAnimation(entity->getName() + "HeadRotate",duration); animation->setInterpolationMode(Ogre::Animation::IM_SPLINE); Ogre::NodeAnimationTrack* track = animation->createNodeTrack(0,entity->getSkeleton()->getBone("HEAD")); // Then make the animation Ogre::TransformKeyFrame* key; key = track->createNodeKeyFrame(0.0f); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(step); key->setRotation(Ogre::Quaternion(Ogre::Radian(3.14/2), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(2.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(3.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(-3.14/2), Ogre::Vector3::UNIT_Y)); key = track->createNodeKeyFrame(4.0*step); key->setRotation(Ogre::Quaternion(Ogre::Radian(0), Ogre::Vector3::UNIT_Y)); // Implement the animation mPlayerAnimationState = mSceneMgr->createAnimationState(entity->getName() + "HeadRotate"); mPlayerAnimationState->setEnabled(true); mPlayerAnimationState->setLoop(true); } Ogre::AnimationState* PlayerAnimation::getPlayerAnimationState() {return mPlayerAnimationState;} <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLargeImageWriteReadTest.cxx Language: C++ Date: $Date$xgoto-l Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkImageFileReader.h" #include "itkImageRegionIterator.h" int itkLargeImageWriteReadTest(int ac, char* av[]) { if (ac < 3) { std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl; return EXIT_FAILURE; } typedef unsigned short PixelType; typedef itk::Image<PixelType,2> ImageType; typedef itk::ImageFileWriter< ImageType > WriterType; typedef itk::ImageFileReader< ImageType > ReaderType; ImageType::Pointer image = ImageType::New(); ImageType::RegionType region; ImageType::IndexType index; ImageType::SizeType size; const unsigned long numberOfPixelsInOneDimension = atol( av[2] ); size.Fill( numberOfPixelsInOneDimension ); index.Fill(0); region.SetSize(size); region.SetIndex(index); image->SetRegions(region); const unsigned long sizeInMegaBytes = ( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) / ( 1024.0 * 1024.0 ); std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl; image->Allocate(); std::cout << "Initializing pixel values " << std::endl; typedef itk::ImageRegionIterator< ImageType > IteratorType; typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; IteratorType itr( image, region ); itr.GoToBegin(); PixelType pixelValue = itk::NumericTraits< PixelType >::Zero; while( itr.IsAtEnd() ) { itr.Set( pixelValue ); ++pixelValue; ++itr; } std::cout << "Trying to write the image to disk" << std::endl; try { WriterType::Pointer writer = WriterType::New(); writer->SetInput(image); writer->SetFileName(av[1]); writer->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } std::cout << "Trying to read the image back from disk" << std::endl; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(av[1]); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } ImageType::ConstPointer readImage = reader->GetOutput(); ConstIteratorType ritr( readImage, region ); IteratorType oitr( image, region ); ritr.GoToBegin(); oitr.GoToBegin(); while( itr.IsAtEnd() ) { if( oitr.Get() != ritr.Get() ) { std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl; return EXIT_FAILURE; } ++oitr; ++ritr; } std::cout << "Comparing the pixel values.. :" << std::endl; return EXIT_SUCCESS; } <commit_msg>BUG: The iterator while loops were missing the negation of IsAtEnd().<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkLargeImageWriteReadTest.cxx Language: C++ Date: $Date$xgoto-l Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkImageFileWriter.h" #include "itkImageFileReader.h" #include "itkImageRegionIterator.h" int itkLargeImageWriteReadTest(int ac, char* av[]) { if (ac < 3) { std::cout << "usage: itkIOTests itkLargeImageWriteReadTest outputFileName numberOfPixelsInOneDimension" << std::endl; return EXIT_FAILURE; } typedef unsigned short PixelType; typedef itk::Image<PixelType,2> ImageType; typedef itk::ImageFileWriter< ImageType > WriterType; typedef itk::ImageFileReader< ImageType > ReaderType; ImageType::Pointer image = ImageType::New(); ImageType::RegionType region; ImageType::IndexType index; ImageType::SizeType size; const unsigned long numberOfPixelsInOneDimension = atol( av[2] ); size.Fill( numberOfPixelsInOneDimension ); index.Fill(0); region.SetSize(size); region.SetIndex(index); image->SetRegions(region); const unsigned long sizeInMegaBytes = ( sizeof(PixelType) * numberOfPixelsInOneDimension * numberOfPixelsInOneDimension ) / ( 1024.0 * 1024.0 ); std::cout << "Trying to allocate an image of size " << sizeInMegaBytes << " Mb " << std::endl; image->Allocate(); std::cout << "Initializing pixel values " << std::endl; typedef itk::ImageRegionIterator< ImageType > IteratorType; typedef itk::ImageRegionConstIterator< ImageType > ConstIteratorType; IteratorType itr( image, region ); itr.GoToBegin(); PixelType pixelValue = itk::NumericTraits< PixelType >::Zero; while( !itr.IsAtEnd() ) { itr.Set( pixelValue ); ++pixelValue; ++itr; } std::cout << "Trying to write the image to disk" << std::endl; try { WriterType::Pointer writer = WriterType::New(); writer->SetInput(image); writer->SetFileName(av[1]); writer->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } std::cout << "Trying to read the image back from disk" << std::endl; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(av[1]); try { reader->Update(); } catch (itk::ExceptionObject &ex) { std::cout << ex << std::endl; return EXIT_FAILURE; } ImageType::ConstPointer readImage = reader->GetOutput(); ConstIteratorType ritr( readImage, region ); IteratorType oitr( image, region ); ritr.GoToBegin(); oitr.GoToBegin(); while( !ritr.IsAtEnd() ) { if( oitr.Get() != ritr.Get() ) { std::cerr << "Pixel comparison failed at index = " << oitr.GetIndex() << std::endl; return EXIT_FAILURE; } ++oitr; ++ritr; } std::cout << "Comparing the pixel values.. :" << std::endl; return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <osgProducer/EventAdapter> using namespace osgProducer; // default to no mouse buttons being pressed. unsigned int EventAdapter::_s_accumulatedButtonMask = 0; int EventAdapter::_s_button = 0; int EventAdapter::_s_modKeyMask = 0; float EventAdapter::_s_Xmin = 0; float EventAdapter::_s_Xmax = 1280; float EventAdapter::_s_Ymin = 0; float EventAdapter::_s_Ymax = 1024; float EventAdapter::_s_mx = 0; float EventAdapter::_s_my = 0; static float s_xOffset=1.0f; static float s_xScale=0.5f; static float s_yOffset=1.0f; static float s_yScale=0.5f; EventAdapter::EventAdapter() { _eventType = NONE; // adaptor does not encapsulate any events. _key = -1; // set to 'invalid' key value. _button = -1; // set to 'invalid' button value. _mx = -1; // set to 'invalid' position value. _my = -1; // set to 'invalid' position value. _buttonMask = 0; // default to no mouse buttons being pressed. _modKeyMask = 0; // default to no mouse buttons being pressed. _time = 0.0f; // default to no time has been set. copyStaticVariables(); } void EventAdapter::copyStaticVariables() { _buttonMask = _s_accumulatedButtonMask; _modKeyMask = _s_modKeyMask; _button = _s_button; _Xmin = _s_Xmin; _Xmax = _s_Xmax; _Ymin = _s_Ymin; _Ymax = _s_Ymax; _mx = _s_mx; _my = _s_my; } void EventAdapter::setWindowSize(float Xmin, float Ymin, float Xmax, float Ymax) { _s_Xmin = Xmin; _s_Xmax = Xmax; _s_Ymin = Ymin; _s_Ymax = Ymax; } void EventAdapter::setButtonMask(unsigned int buttonMask) { _s_accumulatedButtonMask = buttonMask; } void EventAdapter::adaptResize(double time, float Xmin, float Ymin, float Xmax, float Ymax) { setWindowSize(Xmin,Ymin,Xmax,Ymax); _eventType = RESIZE; _time = time; copyStaticVariables(); } void EventAdapter::adaptButtonPress(double time,float x, float y, unsigned int button) { _time = time; _eventType = PUSH; _button = button-1; switch(_button) { case(0): _s_accumulatedButtonMask = _s_accumulatedButtonMask | LEFT_MOUSE_BUTTON; _s_button = LEFT_MOUSE_BUTTON; break; case(1): _s_accumulatedButtonMask = _s_accumulatedButtonMask | MIDDLE_MOUSE_BUTTON; _s_button = MIDDLE_MOUSE_BUTTON; break; case(2): _s_accumulatedButtonMask = _s_accumulatedButtonMask | RIGHT_MOUSE_BUTTON; _s_button = RIGHT_MOUSE_BUTTON; break; } _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } void EventAdapter::adaptButtonRelease(double time,float x, float y, unsigned int button) { _time = time; _eventType = RELEASE; _button = button-1; switch(_button) { case(0): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~LEFT_MOUSE_BUTTON; _s_button = LEFT_MOUSE_BUTTON; break; case(1): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~MIDDLE_MOUSE_BUTTON; _s_button = MIDDLE_MOUSE_BUTTON; break; case(2): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~RIGHT_MOUSE_BUTTON; _s_button = RIGHT_MOUSE_BUTTON; break; } _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } /** method for adapting mouse motion events whilst mouse buttons are pressed.*/ void EventAdapter::adaptMouseMotion(double time, float x, float y) { _eventType = (_s_accumulatedButtonMask) ? DRAG : MOVE; _time = time; _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } /** method for adapting keyboard events.*/ void EventAdapter::adaptKeyPress( double time, Producer::KeySymbol key) { _eventType = KEYDOWN; _time = time; _key = key; copyStaticVariables(); } void EventAdapter::adaptKeyRelease( double time, Producer::KeySymbol key) { // we won't handle this correctly right now.. GUIEventAdapter isn't up to it _eventType = KEYUP; _time = time; _key = key; copyStaticVariables(); } /** method for adapting frame events, i.e. iddle/display callback.*/ void EventAdapter::adaptFrame(double time) { _eventType = FRAME; _time = time; copyStaticVariables(); } <commit_msg>Added support for key modifiers to osgProducer::EventAdapter.<commit_after>#include <osgProducer/EventAdapter> using namespace osgProducer; // default to no mouse buttons being pressed. unsigned int EventAdapter::_s_accumulatedButtonMask = 0; int EventAdapter::_s_button = 0; int EventAdapter::_s_modKeyMask = 0; float EventAdapter::_s_Xmin = 0; float EventAdapter::_s_Xmax = 1280; float EventAdapter::_s_Ymin = 0; float EventAdapter::_s_Ymax = 1024; float EventAdapter::_s_mx = 0; float EventAdapter::_s_my = 0; static float s_xOffset=1.0f; static float s_xScale=0.5f; static float s_yOffset=1.0f; static float s_yScale=0.5f; EventAdapter::EventAdapter() { _eventType = NONE; // adaptor does not encapsulate any events. _key = -1; // set to 'invalid' key value. _button = -1; // set to 'invalid' button value. _mx = -1; // set to 'invalid' position value. _my = -1; // set to 'invalid' position value. _buttonMask = 0; // default to no mouse buttons being pressed. _modKeyMask = 0; // default to no mouse buttons being pressed. _time = 0.0f; // default to no time has been set. copyStaticVariables(); } void EventAdapter::copyStaticVariables() { _buttonMask = _s_accumulatedButtonMask; _modKeyMask = _s_modKeyMask; _button = _s_button; _Xmin = _s_Xmin; _Xmax = _s_Xmax; _Ymin = _s_Ymin; _Ymax = _s_Ymax; _mx = _s_mx; _my = _s_my; } void EventAdapter::setWindowSize(float Xmin, float Ymin, float Xmax, float Ymax) { _s_Xmin = Xmin; _s_Xmax = Xmax; _s_Ymin = Ymin; _s_Ymax = Ymax; } void EventAdapter::setButtonMask(unsigned int buttonMask) { _s_accumulatedButtonMask = buttonMask; } void EventAdapter::adaptResize(double time, float Xmin, float Ymin, float Xmax, float Ymax) { setWindowSize(Xmin,Ymin,Xmax,Ymax); _eventType = RESIZE; _time = time; copyStaticVariables(); } void EventAdapter::adaptButtonPress(double time,float x, float y, unsigned int button) { _time = time; _eventType = PUSH; _button = button-1; switch(_button) { case(0): _s_accumulatedButtonMask = _s_accumulatedButtonMask | LEFT_MOUSE_BUTTON; _s_button = LEFT_MOUSE_BUTTON; break; case(1): _s_accumulatedButtonMask = _s_accumulatedButtonMask | MIDDLE_MOUSE_BUTTON; _s_button = MIDDLE_MOUSE_BUTTON; break; case(2): _s_accumulatedButtonMask = _s_accumulatedButtonMask | RIGHT_MOUSE_BUTTON; _s_button = RIGHT_MOUSE_BUTTON; break; } _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } void EventAdapter::adaptButtonRelease(double time,float x, float y, unsigned int button) { _time = time; _eventType = RELEASE; _button = button-1; switch(_button) { case(0): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~LEFT_MOUSE_BUTTON; _s_button = LEFT_MOUSE_BUTTON; break; case(1): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~MIDDLE_MOUSE_BUTTON; _s_button = MIDDLE_MOUSE_BUTTON; break; case(2): _s_accumulatedButtonMask = _s_accumulatedButtonMask & ~RIGHT_MOUSE_BUTTON; _s_button = RIGHT_MOUSE_BUTTON; break; } _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } /** method for adapting mouse motion events whilst mouse buttons are pressed.*/ void EventAdapter::adaptMouseMotion(double time, float x, float y) { _eventType = (_s_accumulatedButtonMask) ? DRAG : MOVE; _time = time; _s_mx = (float)((x+s_xOffset)*s_xScale*(float)(_s_Xmax-_s_Xmin))+_s_Xmin; _s_my = (float)((y+s_yOffset)*s_yScale*(float)(_s_Ymin-_s_Ymax))+_s_Ymax; copyStaticVariables(); } /** method for adapting keyboard events.*/ void EventAdapter::adaptKeyPress( double time, Producer::KeySymbol key) { _eventType = KEYDOWN; _time = time; _key = key; switch(key) { case(KEY_Shift_L): _s_modKeyMask = MODKEY_LEFT_SHIFT | _s_modKeyMask; break; case(KEY_Shift_R): _s_modKeyMask = MODKEY_RIGHT_SHIFT | _s_modKeyMask; break; case(KEY_Control_L): _s_modKeyMask = MODKEY_LEFT_CTRL | _s_modKeyMask; break; case(KEY_Control_R): _s_modKeyMask = MODKEY_RIGHT_CTRL | _s_modKeyMask; break; case(KEY_Meta_L): _s_modKeyMask = MODKEY_LEFT_META | _s_modKeyMask; break; case(KEY_Meta_R): _s_modKeyMask = MODKEY_RIGHT_META | _s_modKeyMask; break; case(KEY_Alt_L): _s_modKeyMask = MODKEY_LEFT_ALT | _s_modKeyMask; break; case(KEY_Alt_R): _s_modKeyMask = MODKEY_LEFT_ALT | _s_modKeyMask; break; case(KEY_Caps_Lock): { if ((_s_modKeyMask & MODKEY_CAPS_LOCK)!=0) _s_modKeyMask = ~MODKEY_CAPS_LOCK & _s_modKeyMask; else _s_modKeyMask = MODKEY_CAPS_LOCK | _s_modKeyMask; break; } case(KEY_Num_Lock): { if ((_s_modKeyMask & MODKEY_NUM_LOCK)!=0) _s_modKeyMask = ~MODKEY_NUM_LOCK & _s_modKeyMask; else _s_modKeyMask = MODKEY_NUM_LOCK | _s_modKeyMask; break; } } copyStaticVariables(); } void EventAdapter::adaptKeyRelease( double time, Producer::KeySymbol key) { // we won't handle this correctly right now.. GUIEventAdapter isn't up to it _eventType = KEYUP; _time = time; _key = key; switch(key) { case(KEY_Shift_L): _s_modKeyMask = ~MODKEY_LEFT_SHIFT & _s_modKeyMask; break; case(KEY_Shift_R): _s_modKeyMask = ~MODKEY_RIGHT_SHIFT & _s_modKeyMask; break; case(KEY_Control_L): _s_modKeyMask = ~MODKEY_LEFT_CTRL & _s_modKeyMask; break; case(KEY_Control_R): _s_modKeyMask = ~MODKEY_RIGHT_CTRL & _s_modKeyMask; break; case(KEY_Meta_L): _s_modKeyMask = ~MODKEY_LEFT_META & _s_modKeyMask; break; case(KEY_Meta_R): _s_modKeyMask = ~MODKEY_RIGHT_META & _s_modKeyMask; break; case(KEY_Alt_L): _s_modKeyMask = ~MODKEY_LEFT_ALT & _s_modKeyMask; break; case(KEY_Alt_R): _s_modKeyMask = ~MODKEY_LEFT_ALT & _s_modKeyMask; break; } copyStaticVariables(); } /** method for adapting frame events, i.e. iddle/display callback.*/ void EventAdapter::adaptFrame(double time) { _eventType = FRAME; _time = time; copyStaticVariables(); } <|endoftext|>
<commit_before>#include "PoiActionRunner.h" PoiActionRunner::PoiActionRunner(PoiTimer& ptimer, LogLevel logLevel) : _currentAction(NO_ACTION), _currentSyncId(0), _currentScene(0), _imageCache(_flashMemory.getSizeOfImageSection(), logLevel), _playHandler(_imageCache), _fadeHandler(_imageCache), _progHandler(_playHandler, _flashMemory, logLevel), _animationHandler(_imageCache), _staticRgbHandler(_imageCache), _currentHandler(&_playHandler), _ptimer(ptimer), _logLevel(logLevel) {} void PoiActionRunner::clearImageMap(){ _imageCache.clearImageMap(); } void PoiActionRunner::setup(){ // Create semaphore to inform us when the timer has fired _timerSemaphore = xSemaphoreCreateBinary(); _imageCache.clearImageMap(); _flashMemory.setup(_logLevel, _imageCache.getRawImageData()); _progHandler.setup(); // load program _updateSceneFromFlash(0); // load scene 0 into flash } /********************** * Utility functions * *********************/ void PoiActionRunner::_display(rgbVal* frame){ ws2812_setColors(N_PIXELS, frame); } void PoiActionRunner::_displayRegister(uint8_t registerId){ ws2812_setColors(N_PIXELS, _imageCache.getRegister(registerId)); } /**************************** * External action methods * ***************************/ void PoiActionRunner::initializeFlash(){ _imageCache.clearImageMap(); _flashMemory.initializeFlash(_logLevel, _imageCache.getRawImageData()); } void PoiActionRunner::setPixel(uint8_t scene_idx, uint8_t frame_idx, uint8_t pixel_idx, uint8_t r, uint8_t g, uint8_t b){ // TODO: possibly handle cases in which scene_idx changes _currentScene = scene_idx; _imageCache.setPixel(frame_idx, pixel_idx, r, g, b); } void PoiActionRunner::saveScene(uint8_t scene){ if (_logLevel != MUTE) printf("Saving image of scene %d to flash.\n", _currentScene); if (_flashMemory.saveImage(scene, _imageCache.getRawImageData())){ _currentScene = scene; if (_logLevel != MUTE) printf("Image of scene %d saved to flash.\n", _currentScene); } else { printf("Error saving scene %d to flash.", _currentScene); } } // load scene from flash into memory void PoiActionRunner::_updateSceneFromFlash(uint8_t scene){ if (_flashMemory.loadImage(scene, _imageCache.getRawImageData())){ _currentScene = scene; if (_logLevel != MUTE) printf("Scene %d loaded from Flash.\n", _currentScene); } else{ printf("Error. Cannot load scene %d\n", scene); } } /******************************** * Actions operated by handler * *******************************/ void PoiActionRunner::showStaticFrame(uint8_t scene, uint8_t frame, uint8_t timeOutMSB, uint8_t timeOutLSB){ _currentAction = SHOW_STATIC_FRAME; _updateSceneFromFlash(scene); uint8_t timeout = (uint16_t)timeOutMSB *256 + timeOutLSB; if (_logLevel != MUTE) printf("Play static frame: %d timeout: %d \n", frame, timeout); _imageCache.copyFrameToRegister(0, frame); // play initial frame right away _ptimer.disable(); _displayRegister(0); _ptimer.setIntervalAndEnable( timeout ); } void PoiActionRunner::playScene(uint8_t scene, uint8_t startFrame, uint8_t endFrame, uint8_t speed, uint8_t loops){ // init of play action if (scene != _currentScene){ _updateSceneFromFlash(scene); _currentScene = scene; } _playHandler.init(startFrame, endFrame, speed, loops); _currentHandlerStart(&_playHandler, PLAY_DIRECT); } void PoiActionRunner::fadeToBlack(uint8_t fadeMSB, uint8_t fadeLSB){ uint16_t fadeTime = (uint16_t)fadeMSB * 256 + fadeLSB; if (fadeTime < MIN_FADE_TIME){ displayOff(); return; } _fadeHandler.init(fadeTime); _currentHandlerStart(&_fadeHandler, FADE_TO_BLACK); } void PoiActionRunner::playWorm(Color color, uint8_t registerLength, uint8_t numLoops, bool synchronous){ uint16_t delayMs = 25; _animationHandler.init(ANIMATIONTYPE_WORM, registerLength, numLoops, color, delayMs); if (_logLevel != MUTE) { printf("Play Worm Animation: Color %d Len: %d delay: %d \n", color, registerLength, delayMs); } if (synchronous){ _ptimer.disable(); _display(_animationHandler.getDisplayFrame()); while (true){ _animationHandler.next(); if (!_animationHandler.isActive()){ break; } _display(_animationHandler.getDisplayFrame()); delay(delayMs); } displayOff(); _currentAction = NO_ACTION; } else { _currentHandlerStart(&_animationHandler, ANIMATION_WORM); } } // set current handler to passed in handler, display and start timer void PoiActionRunner::_currentHandlerStart(AbstractHandler* handler, PoiAction action){ _currentAction = action; _currentHandler = handler; printf("Starting action %s.\n", _currentHandler->getActionName()); if (_logLevel != MUTE) _currentHandler->printInfo(); // play initial frame right away _ptimer.disable(); _display(_currentHandler->getDisplayFrame()); _ptimer.setIntervalAndEnable( _currentHandler->getDelayMs() ); } void PoiActionRunner::showStaticRgb(uint8_t r, uint8_t g, uint8_t b, uint8_t nLeds) { _staticRgbHandler.init(r,g,b,nLeds); _currentAction = SHOW_STATIC_RGB; _currentHandler = &_staticRgbHandler; _ptimer.disable(); _display(_currentHandler->getDisplayFrame()); } void PoiActionRunner::displayOff() { showStaticRgb(0,0,0); } void PoiActionRunner::displayIp(uint8_t ipIncrement, bool withStaticBackground){ // set back the ip led to black _imageCache.clearRegister(0); if (withStaticBackground){ rgbVal paleWhite = makeRGBVal(8,8,8); _imageCache.fillRegister(0, paleWhite, N_POIS); } rgbVal* reg0 = _imageCache.getRegister(0); // display colored led (first one less bright for each) uint8_t b = 64; if (ipIncrement %2 == 0){ b=8; } rgbVal color = makeRGBValue(RED, b); switch(ipIncrement/2){ case 1: color = makeRGBValue(GREEN, b); break; case 2: color = makeRGBValue(BLUE, b); break; case 3: color = makeRGBValue(YELLOW, b); break; case 4: color = makeRGBValue(LILA, b); break; } reg0[ipIncrement]= color; _displayRegister(0); } /**************************** * Program related methods * ***************************/ void PoiActionRunner::addCmdToProgram(unsigned char cmd[7]){ _progHandler.addCmdToProgram(cmd); } void PoiActionRunner::startProg(){ _currentAction = PLAY_PROG; _progHandler.init(); if (!_progHandler.isActive()){ return; // if check was negative } if (_logLevel != MUTE) _progHandler.printInfo(); // play initial frame right away _ptimer.disable(); _display(_progHandler.getDisplayFrame()); _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); } void PoiActionRunner::pauseProg(){ _currentAction = PAUSE_PROG; if (_logLevel != MUTE) printf("Program paused.\n" ); } void PoiActionRunner::pauseAction(){ _currentAction = PAUSE_PROG; if (_logLevel != MUTE) printf("Action paused.\n" ); } void PoiActionRunner::jumptoSync(uint8_t syncId){ if (syncId == 0){ _currentSyncId++; _progHandler.syncNow(_currentSyncId); } else { _progHandler.syncNow(syncId); } } void PoiActionRunner::continueProg() { _currentAction = PLAY_PROG; if (_logLevel != MUTE) printf("Program continuing.\n" ); } bool PoiActionRunner::isProgramActive(){ return _progHandler.isActive(); } uint8_t PoiActionRunner::getIpIncrement(){ uint8_t ipIncrement = 0; _flashMemory.loadIpIncrement(&ipIncrement); return ipIncrement; } void PoiActionRunner::saveIpIncrement(uint8_t ipIncrement){ _flashMemory.saveIpIncrement(ipIncrement); } /******************************* * Interrupt & State handling * ******************************/ // no printf in interrupt! void IRAM_ATTR PoiActionRunner::onInterrupt(){ if (_currentAction != NO_ACTION){ //Serial.println("play next frame"); // Give a semaphore that we can check in the loop xSemaphoreGiveFromISR(_timerSemaphore, NULL); } } void PoiActionRunner::loop(){ float factor = 1; if (xSemaphoreTake(_timerSemaphore, 0) == pdTRUE){ switch(_currentAction){ // all action that are using handlers based on AbastractHandler case PLAY_DIRECT: case FADE_TO_BLACK: case ANIMATION_WORM: _currentHandler->next(); if (_logLevel == CHATTY) _currentHandler->printState(); _display(_currentHandler->getDisplayFrame()); if (!_currentHandler->isActive()) { _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("End of action %s.\n", _currentHandler->getActionName()); } break; case PLAY_PROG: _progHandler.next(); if (_progHandler.isActive()){ // check and update scene and interval if changed if (_progHandler.hasDelayChanged()) { _ptimer.disable(); } uint8_t scene = _progHandler.getCurrentScene(); if (scene != _currentScene){ _updateSceneFromFlash(scene); _currentScene = scene; } // finally display the frame _display(_progHandler.getDisplayFrame()); if (_progHandler.hasDelayChanged()) { _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); } } else { _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("End of program PLAY_PROG.\n"); } break; case SHOW_STATIC_FRAME: // reached timeout _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("Timeout of SHOW_STATIC_FRAME reached.\n"); break; case NO_ACTION: case PAUSE_PROG: // do nothing break; default: break; } } } <commit_msg>switch showStaticFrame to player<commit_after>#include "PoiActionRunner.h" PoiActionRunner::PoiActionRunner(PoiTimer& ptimer, LogLevel logLevel) : _currentAction(NO_ACTION), _currentSyncId(0), _currentScene(0), _imageCache(_flashMemory.getSizeOfImageSection(), logLevel), _playHandler(_imageCache), _fadeHandler(_imageCache), _progHandler(_playHandler, _flashMemory, logLevel), _animationHandler(_imageCache), _staticRgbHandler(_imageCache), _currentHandler(&_playHandler), _ptimer(ptimer), _logLevel(logLevel) {} void PoiActionRunner::clearImageMap(){ _imageCache.clearImageMap(); } void PoiActionRunner::setup(){ // Create semaphore to inform us when the timer has fired _timerSemaphore = xSemaphoreCreateBinary(); _imageCache.clearImageMap(); _flashMemory.setup(_logLevel, _imageCache.getRawImageData()); _progHandler.setup(); // load program _updateSceneFromFlash(0); // load scene 0 into flash } /********************** * Utility functions * *********************/ void PoiActionRunner::_display(rgbVal* frame){ ws2812_setColors(N_PIXELS, frame); } void PoiActionRunner::_displayRegister(uint8_t registerId){ ws2812_setColors(N_PIXELS, _imageCache.getRegister(registerId)); } /**************************** * External action methods * ***************************/ void PoiActionRunner::initializeFlash(){ _imageCache.clearImageMap(); _flashMemory.initializeFlash(_logLevel, _imageCache.getRawImageData()); } void PoiActionRunner::setPixel(uint8_t scene_idx, uint8_t frame_idx, uint8_t pixel_idx, uint8_t r, uint8_t g, uint8_t b){ // TODO: possibly handle cases in which scene_idx changes _currentScene = scene_idx; _imageCache.setPixel(frame_idx, pixel_idx, r, g, b); } void PoiActionRunner::saveScene(uint8_t scene){ if (_logLevel != MUTE) printf("Saving image of scene %d to flash.\n", _currentScene); if (_flashMemory.saveImage(scene, _imageCache.getRawImageData())){ _currentScene = scene; if (_logLevel != MUTE) printf("Image of scene %d saved to flash.\n", _currentScene); } else { printf("Error saving scene %d to flash.", _currentScene); } } // load scene from flash into memory void PoiActionRunner::_updateSceneFromFlash(uint8_t scene){ if (_flashMemory.loadImage(scene, _imageCache.getRawImageData())){ _currentScene = scene; if (_logLevel != MUTE) printf("Scene %d loaded from Flash.\n", _currentScene); } else{ printf("Error. Cannot load scene %d\n", scene); } } /******************************** * Actions operated by handler * *******************************/ void PoiActionRunner::showStaticFrame(uint8_t scene, uint8_t frame, uint8_t timeOutMSB, uint8_t timeOutLSB){ if (scene != _currentScene){ _updateSceneFromFlash(scene); _currentScene = scene; } uint8_t timeout = (uint16_t)timeOutMSB *256 + timeOutLSB; if (_logLevel != MUTE) printf("Play static frame: %d timeout: %d \n", frame, timeout); // use frame player but with same start and end frame and timeout as speed _playHandler.init(frame, frame, timeout, 1); _currentHandlerStart(&_playHandler, SHOW_STATIC_FRAME); } void PoiActionRunner::playScene(uint8_t scene, uint8_t startFrame, uint8_t endFrame, uint8_t speed, uint8_t loops){ // init of play action if (scene != _currentScene){ _updateSceneFromFlash(scene); _currentScene = scene; } _playHandler.init(startFrame, endFrame, speed, loops); _currentHandlerStart(&_playHandler, PLAY_DIRECT); } void PoiActionRunner::fadeToBlack(uint8_t fadeMSB, uint8_t fadeLSB){ uint16_t fadeTime = (uint16_t)fadeMSB * 256 + fadeLSB; if (fadeTime < MIN_FADE_TIME){ displayOff(); return; } _fadeHandler.init(fadeTime); _currentHandlerStart(&_fadeHandler, FADE_TO_BLACK); } void PoiActionRunner::playWorm(Color color, uint8_t registerLength, uint8_t numLoops, bool synchronous){ uint16_t delayMs = 25; _animationHandler.init(ANIMATIONTYPE_WORM, registerLength, numLoops, color, delayMs); if (_logLevel != MUTE) { printf("Play Worm Animation: Color %d Len: %d delay: %d \n", color, registerLength, delayMs); } if (synchronous){ _ptimer.disable(); _display(_animationHandler.getDisplayFrame()); while (true){ _animationHandler.next(); if (!_animationHandler.isActive()){ break; } _display(_animationHandler.getDisplayFrame()); delay(delayMs); } displayOff(); _currentAction = NO_ACTION; } else { _currentHandlerStart(&_animationHandler, ANIMATION_WORM); } } // set current handler to passed in handler, display and start timer void PoiActionRunner::_currentHandlerStart(AbstractHandler* handler, PoiAction action){ _currentAction = action; _currentHandler = handler; printf("Starting action %s.\n", _currentHandler->getActionName()); if (_logLevel != MUTE) _currentHandler->printInfo(); // play initial frame right away _ptimer.disable(); _display(_currentHandler->getDisplayFrame()); _ptimer.setIntervalAndEnable( _currentHandler->getDelayMs() ); } void PoiActionRunner::showStaticRgb(uint8_t r, uint8_t g, uint8_t b, uint8_t nLeds) { _staticRgbHandler.init(r,g,b,nLeds); _currentAction = SHOW_STATIC_RGB; _currentHandler = &_staticRgbHandler; _ptimer.disable(); _display(_currentHandler->getDisplayFrame()); } void PoiActionRunner::displayOff() { showStaticRgb(0,0,0); } void PoiActionRunner::displayIp(uint8_t ipIncrement, bool withStaticBackground){ // set back the ip led to black _imageCache.clearRegister(0); if (withStaticBackground){ rgbVal paleWhite = makeRGBVal(8,8,8); _imageCache.fillRegister(0, paleWhite, N_POIS); } rgbVal* reg0 = _imageCache.getRegister(0); // display colored led (first one less bright for each) uint8_t b = 64; if (ipIncrement %2 == 0){ b=8; } rgbVal color = makeRGBValue(RED, b); switch(ipIncrement/2){ case 1: color = makeRGBValue(GREEN, b); break; case 2: color = makeRGBValue(BLUE, b); break; case 3: color = makeRGBValue(YELLOW, b); break; case 4: color = makeRGBValue(LILA, b); break; } reg0[ipIncrement]= color; _displayRegister(0); } /**************************** * Program related methods * ***************************/ void PoiActionRunner::addCmdToProgram(unsigned char cmd[7]){ _progHandler.addCmdToProgram(cmd); } void PoiActionRunner::startProg(){ _currentAction = PLAY_PROG; _progHandler.init(); if (!_progHandler.isActive()){ return; // if check was negative } if (_logLevel != MUTE) _progHandler.printInfo(); // play initial frame right away _ptimer.disable(); _display(_progHandler.getDisplayFrame()); _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); } void PoiActionRunner::pauseProg(){ _currentAction = PAUSE_PROG; if (_logLevel != MUTE) printf("Program paused.\n" ); } void PoiActionRunner::pauseAction(){ _currentAction = PAUSE_PROG; if (_logLevel != MUTE) printf("Action paused.\n" ); } void PoiActionRunner::jumptoSync(uint8_t syncId){ if (syncId == 0){ _currentSyncId++; _progHandler.syncNow(_currentSyncId); } else { _progHandler.syncNow(syncId); } } void PoiActionRunner::continueProg() { _currentAction = PLAY_PROG; if (_logLevel != MUTE) printf("Program continuing.\n" ); } bool PoiActionRunner::isProgramActive(){ return _progHandler.isActive(); } uint8_t PoiActionRunner::getIpIncrement(){ uint8_t ipIncrement = 0; _flashMemory.loadIpIncrement(&ipIncrement); return ipIncrement; } void PoiActionRunner::saveIpIncrement(uint8_t ipIncrement){ _flashMemory.saveIpIncrement(ipIncrement); } /******************************* * Interrupt & State handling * ******************************/ // no printf in interrupt! void IRAM_ATTR PoiActionRunner::onInterrupt(){ if (_currentAction != NO_ACTION){ //Serial.println("play next frame"); // Give a semaphore that we can check in the loop xSemaphoreGiveFromISR(_timerSemaphore, NULL); } } void PoiActionRunner::loop(){ float factor = 1; if (xSemaphoreTake(_timerSemaphore, 0) == pdTRUE){ switch(_currentAction){ // all action that are using handlers based on AbastractHandler case PLAY_DIRECT: case FADE_TO_BLACK: case ANIMATION_WORM: _currentHandler->next(); if (_logLevel == CHATTY) _currentHandler->printState(); _display(_currentHandler->getDisplayFrame()); if (!_currentHandler->isActive()) { _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("End of action %s.\n", _currentHandler->getActionName()); } break; case PLAY_PROG: _progHandler.next(); if (_progHandler.isActive()){ // check and update scene and interval if changed if (_progHandler.hasDelayChanged()) { _ptimer.disable(); } uint8_t scene = _progHandler.getCurrentScene(); if (scene != _currentScene){ _updateSceneFromFlash(scene); _currentScene = scene; } // finally display the frame _display(_progHandler.getDisplayFrame()); if (_progHandler.hasDelayChanged()) { _ptimer.setIntervalAndEnable( _progHandler.getDelayMs() ); } } else { _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("End of program PLAY_PROG.\n"); } break; case SHOW_STATIC_FRAME: // reached timeout _currentAction = NO_ACTION; if (_logLevel != MUTE) printf("Timeout of SHOW_STATIC_FRAME reached.\n"); break; case NO_ACTION: case PAUSE_PROG: case SHOW_STATIC_RGB: // do nothing break; default: break; } } } <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/GLObjectsVisitor> #include <osg/Drawable> #include <osg/Notify> #include <osg/Timer> namespace osgUtil { ///////////////////////////////////////////////////////////////// // // GLObjectsVisitor // GLObjectsVisitor::GLObjectsVisitor(Mode mode) { setTraversalMode(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN); _mode = mode; } void GLObjectsVisitor::apply(osg::Node& node) { if (node.getStateSet()) { apply(*(node.getStateSet())); } traverse(node); } void GLObjectsVisitor::apply(osg::Geode& node) { if (node.getStateSet()) { apply(*(node.getStateSet())); } for(unsigned int i=0;i<node.getNumDrawables();++i) { osg::Drawable* drawable = node.getDrawable(i); if (drawable) { apply(*drawable); if (drawable->getStateSet()) { apply(*(drawable->getStateSet())); } } } } void GLObjectsVisitor::apply(osg::Drawable& drawable) { if (_drawablesAppliedSet.count(&drawable)!=0) return; _drawablesAppliedSet.insert(&drawable); if (_mode&SWITCH_OFF_DISPLAY_LISTS) { drawable.setUseDisplayList(false); } if (_mode&SWITCH_ON_DISPLAY_LISTS) { drawable.setUseDisplayList(true); } if (_mode&COMPILE_DISPLAY_LISTS && _renderInfo.getState()) { drawable.compileGLObjects(_renderInfo); } if (_mode&RELEASE_DISPLAY_LISTS) { drawable.releaseGLObjects(_renderInfo.getState()); } if (_mode&SWITCH_ON_VERTEX_BUFFER_OBJECTS) { drawable.setUseVertexBufferObjects(true); } if (_mode&SWITCH_OFF_VERTEX_BUFFER_OBJECTS) { drawable.setUseVertexBufferObjects(false); } } void GLObjectsVisitor::apply(osg::StateSet& stateset) { if (_stateSetAppliedSet.count(&stateset)!=0) return; _stateSetAppliedSet.insert(&stateset); if (_mode & COMPILE_STATE_ATTRIBUTES && _renderInfo.getState()) { stateset.compileGLObjects(*_renderInfo.getState()); osg::Program* program = dynamic_cast<osg::Program*>(stateset.getAttribute(osg::StateAttribute::PROGRAM)); if (program) _lastCompiledProgram = program; if (_lastCompiledProgram.valid() && !stateset.getUniformList().empty()) { osg::Program::PerContextProgram* pcp = _lastCompiledProgram->getPCP(_renderInfo.getState()->getContextID()); if (pcp) { pcp->useProgram(); _renderInfo.getState()->setLastAppliedProgramObject(pcp); osg::StateSet::UniformList& ul = stateset.getUniformList(); for(osg::StateSet::UniformList::iterator itr = ul.begin(); itr != ul.end(); ++itr) { pcp->apply(*(itr->second.first)); } } } else if(_renderInfo.getState()->getLastAppliedProgramObject()){ osg::GL2Extensions* extensions = osg::GL2Extensions::Get(_renderInfo.getState()->getContextID(), true); extensions->glUseProgram(0); _renderInfo.getState()->setLastAppliedProgramObject(0); } } if (_mode & RELEASE_STATE_ATTRIBUTES) { stateset.releaseGLObjects(_renderInfo.getState()); } if (_mode & CHECK_BLACK_LISTED_MODES) { stateset.checkValidityOfAssociatedModes(*_renderInfo.getState()); } } ///////////////////////////////////////////////////////////////// // // GLObjectsVisitor // GLObjectsOperation::GLObjectsOperation(GLObjectsVisitor::Mode mode): osg::GraphicsOperation("GLObjectOperation",false), _mode(mode) { } GLObjectsOperation::GLObjectsOperation(osg::Node* subgraph, GLObjectsVisitor::Mode mode): osg::GraphicsOperation("GLObjectOperation",false), _subgraph(subgraph), _mode(mode) { } void GLObjectsOperation::operator () (osg::GraphicsContext* context) { GLObjectsVisitor glObjectsVisitor(_mode); context->getState()->initializeExtensionProcs(); glObjectsVisitor.setState(context->getState()); // osg::notify(osg::NOTICE)<<"GLObjectsOperation::before <<<<<<<<<<<"<<std::endl; if (_subgraph.valid()) { _subgraph->accept(glObjectsVisitor); } else { for(osg::GraphicsContext::Cameras::iterator itr = context->getCameras().begin(); itr != context->getCameras().end(); ++itr) { (*itr)->accept(glObjectsVisitor); } } // osg::notify(osg::NOTICE)<<"GLObjectsOperation::after >>>>>>>>>>> "<<std::endl; } } // end of namespace osgUtil <commit_msg>From Wojciech Lewandowski, Fixed handling of empty Program.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osgUtil/GLObjectsVisitor> #include <osg/Drawable> #include <osg/Notify> #include <osg/Timer> namespace osgUtil { ///////////////////////////////////////////////////////////////// // // GLObjectsVisitor // GLObjectsVisitor::GLObjectsVisitor(Mode mode) { setTraversalMode(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN); _mode = mode; } void GLObjectsVisitor::apply(osg::Node& node) { if (node.getStateSet()) { apply(*(node.getStateSet())); } traverse(node); } void GLObjectsVisitor::apply(osg::Geode& node) { if (node.getStateSet()) { apply(*(node.getStateSet())); } for(unsigned int i=0;i<node.getNumDrawables();++i) { osg::Drawable* drawable = node.getDrawable(i); if (drawable) { apply(*drawable); if (drawable->getStateSet()) { apply(*(drawable->getStateSet())); } } } } void GLObjectsVisitor::apply(osg::Drawable& drawable) { if (_drawablesAppliedSet.count(&drawable)!=0) return; _drawablesAppliedSet.insert(&drawable); if (_mode&SWITCH_OFF_DISPLAY_LISTS) { drawable.setUseDisplayList(false); } if (_mode&SWITCH_ON_DISPLAY_LISTS) { drawable.setUseDisplayList(true); } if (_mode&COMPILE_DISPLAY_LISTS && _renderInfo.getState()) { drawable.compileGLObjects(_renderInfo); } if (_mode&RELEASE_DISPLAY_LISTS) { drawable.releaseGLObjects(_renderInfo.getState()); } if (_mode&SWITCH_ON_VERTEX_BUFFER_OBJECTS) { drawable.setUseVertexBufferObjects(true); } if (_mode&SWITCH_OFF_VERTEX_BUFFER_OBJECTS) { drawable.setUseVertexBufferObjects(false); } } void GLObjectsVisitor::apply(osg::StateSet& stateset) { if (_stateSetAppliedSet.count(&stateset)!=0) return; _stateSetAppliedSet.insert(&stateset); if (_mode & COMPILE_STATE_ATTRIBUTES && _renderInfo.getState()) { stateset.compileGLObjects(*_renderInfo.getState()); osg::Program* program = dynamic_cast<osg::Program*>(stateset.getAttribute(osg::StateAttribute::PROGRAM)); if (program) { if( program->isFixedFunction() ) _lastCompiledProgram = NULL; // It does not make sense to apply uniforms on fixed pipe else _lastCompiledProgram = program; } if (_lastCompiledProgram.valid() && !stateset.getUniformList().empty()) { osg::Program::PerContextProgram* pcp = _lastCompiledProgram->getPCP(_renderInfo.getState()->getContextID()); if (pcp) { pcp->useProgram(); _renderInfo.getState()->setLastAppliedProgramObject(pcp); osg::StateSet::UniformList& ul = stateset.getUniformList(); for(osg::StateSet::UniformList::iterator itr = ul.begin(); itr != ul.end(); ++itr) { pcp->apply(*(itr->second.first)); } } } else if(_renderInfo.getState()->getLastAppliedProgramObject()){ osg::GL2Extensions* extensions = osg::GL2Extensions::Get(_renderInfo.getState()->getContextID(), true); extensions->glUseProgram(0); _renderInfo.getState()->setLastAppliedProgramObject(0); } } if (_mode & RELEASE_STATE_ATTRIBUTES) { stateset.releaseGLObjects(_renderInfo.getState()); } if (_mode & CHECK_BLACK_LISTED_MODES) { stateset.checkValidityOfAssociatedModes(*_renderInfo.getState()); } } ///////////////////////////////////////////////////////////////// // // GLObjectsVisitor // GLObjectsOperation::GLObjectsOperation(GLObjectsVisitor::Mode mode): osg::GraphicsOperation("GLObjectOperation",false), _mode(mode) { } GLObjectsOperation::GLObjectsOperation(osg::Node* subgraph, GLObjectsVisitor::Mode mode): osg::GraphicsOperation("GLObjectOperation",false), _subgraph(subgraph), _mode(mode) { } void GLObjectsOperation::operator () (osg::GraphicsContext* context) { GLObjectsVisitor glObjectsVisitor(_mode); context->getState()->initializeExtensionProcs(); glObjectsVisitor.setState(context->getState()); // osg::notify(osg::NOTICE)<<"GLObjectsOperation::before <<<<<<<<<<<"<<std::endl; if (_subgraph.valid()) { _subgraph->accept(glObjectsVisitor); } else { for(osg::GraphicsContext::Cameras::iterator itr = context->getCameras().begin(); itr != context->getCameras().end(); ++itr) { (*itr)->accept(glObjectsVisitor); } } // osg::notify(osg::NOTICE)<<"GLObjectsOperation::after >>>>>>>>>>> "<<std::endl; } } // end of namespace osgUtil <|endoftext|>
<commit_before>#include "ActivityWidget.h" #include "ValidatorAdapter.h" #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> #include <QHBoxLayout> #include <QSplitter> #include <QFontMetrics> #include <QVector> #include <Calculator.h> #include <Representer.h> #include <QDebug> ActivityWidget::ActivityWidget (QWidget * parent) : QWidget (parent) , editCodeId (nullptr) , editLength (nullptr) , editHexView (nullptr) , editStringView (nullptr) , editPsl (nullptr) , checkLengthAuto (nullptr) , plot (nullptr) , isLengthAutoDetect(true) { createWidgets (); createLayouts (); createConnections (); } void ActivityWidget::createWidgets () { editCodeId = new QLineEdit (this); editLength = new QLineEdit (this); editHexView = new QLineEdit (this); editStringView = new QLineEdit (this); editPsl = new QLineEdit (this); editHexView->setValidator (new ValidatorHexViewAdapter); editStringView->setValidator (new ValidatorStringViewAdapter); checkLengthAuto = new QCheckBox (this); checkLengthAuto->setCheckState (isLengthAutoDetect ? Qt::Checked : Qt::Unchecked); plot = new QCustomPlot (this); } void ActivityWidget::createLayouts () { QHBoxLayout * layoutCodeId = new QHBoxLayout (); QLabel * labelCodeId = new QLabel (tr ("Code ID") ); layoutCodeId->addWidget (labelCodeId); layoutCodeId->addWidget (editCodeId); QHBoxLayout * layoutLength = new QHBoxLayout (); QLabel * labelLength = new QLabel (tr ("Length") ); layoutLength->addWidget (labelLength); layoutLength->addWidget (editLength); QLabel * labelLengthAuto = new QLabel (tr ("Auto detect") ); layoutLength->addWidget (labelLengthAuto); layoutLength->addWidget (checkLengthAuto); QHBoxLayout * layoutHexView = new QHBoxLayout (); QLabel * labelHexView = new QLabel (tr ("Hex View") ); layoutHexView->addWidget (labelHexView); layoutHexView->addWidget (editHexView); QHBoxLayout * layoutStringView = new QHBoxLayout (); QLabel * labelStringView = new QLabel (tr ("String View") ); layoutStringView->addWidget (labelStringView); layoutStringView->addWidget (editStringView); QHBoxLayout * layoutPsl = new QHBoxLayout (); QLabel * labelPsl = new QLabel (tr ("PSL") ); layoutPsl->addWidget (labelPsl); layoutPsl->addWidget (editPsl); int width {0}; width = std::max (labelCodeId->fontMetrics ().width (labelCodeId->text () ), width); width = std::max (labelLength->fontMetrics ().width (labelLength->text () ), width); width = std::max (labelHexView->fontMetrics ().width (labelHexView->text () ), width); width = std::max (labelStringView->fontMetrics ().width (labelStringView->text () ), width); width = std::max (labelPsl->fontMetrics ().width (labelPsl->text () ), width); labelCodeId->setFixedWidth (width); labelLength->setFixedWidth (width); labelHexView->setFixedWidth (width); labelStringView->setFixedWidth (width); labelPsl->setFixedWidth (width); QWidget * widgetCode = new QWidget (); QVBoxLayout * layoutCode = new QVBoxLayout (); layoutCode->addLayout (layoutCodeId); layoutCode->addLayout (layoutLength); layoutCode->addLayout (layoutHexView); layoutCode->addLayout (layoutStringView); layoutCode->addLayout (layoutPsl); layoutCode->addStretch (); widgetCode->setLayout (layoutCode); QWidget * widgetChart = new QWidget (); QVBoxLayout * layoutChart = new QVBoxLayout (); layoutChart->addWidget (plot); widgetChart->setLayout (layoutChart); QSplitter * splitterTop = new QSplitter (Qt::Vertical, this); QVBoxLayout * layoutTop = new QVBoxLayout (); splitterTop->addWidget (widgetCode); splitterTop->addWidget (widgetChart); splitterTop->setStretchFactor (0, 0); splitterTop->setStretchFactor (1, 1); layoutTop->addWidget (splitterTop); this->setLayout (layoutTop); } void ActivityWidget::createConnections () { connect (editHexView, SIGNAL (textEdited (const QString &) ), this, SLOT (onHexViewEdited (const QString &) ) ); connect (editStringView, SIGNAL (textEdited (const QString &) ), this, SLOT (onStringViewEdited (const QString &) ) ); connect (checkLengthAuto, SIGNAL (stateChanged (int) ), this, SLOT (onLengthAutoDetectChanged (const int) ) ); } void ActivityWidget::onLengthAutoDetectChanged (const int state) { isLengthAutoDetect = (state == Qt::Checked ? true : false); } void ActivityWidget::onHexViewEdited (const QString & view) { std::string stringView; if (isLengthAutoDetect) { stringView = Pslrk::Core::Representer::HexViewToStringView (view.toStdString () ); } else { stringView = Pslrk::Core::Representer::HexViewToStringView (view.toStdString (), editLength->text ().toInt () ); } onViewChanged (stringView); editStringView->setText (QString::fromStdString (stringView) ); } void ActivityWidget::onStringViewEdited (const QString & view) { onViewChanged (view.toStdString () ); editHexView->setText (QString::fromStdString (Pslrk::Core::Representer::StringViewToHexView(view.toStdString () ) ) ); } void ActivityWidget::onViewChanged (const std::string & view) { editCodeId->setText (QString::fromStdString (Pslrk::Core::Representer::DetectCodeId (view) ) ); editPsl->setText (QString ("%1").arg (Pslrk::Core::Calculator::CalculatePsl (view) ) ); if (isLengthAutoDetect) { editLength->setText (QString ("%1").arg (view.size () ) ); } const double range = view.size (); QVector <double> y; for (auto i : Pslrk::Core::Calculator::CalculateAcf (view) ) { y.push_back (i); } QVector <double> x; for (int i = 0; i < y.size (); ++i) { x.push_back (i - range + 1); } double min {0.0}; for (auto i : y) { min = std::min (min, i); } double max {0.0}; for (auto i : y) { max = std::max (max, i); } plot->addGraph (); plot->graph (0)->setData (x, y); plot->graph (0)->setPen (QPen (Qt::blue) ); plot->xAxis->setRange (-range, range); plot->yAxis->setRange ( min, max); plot->xAxis->setVisible (true); plot->yAxis->setVisible (true); plot->replot (); }<commit_msg>Prohibit input for string view with explicit settings of code length.<commit_after>#include "ActivityWidget.h" #include "ValidatorAdapter.h" #include <QLabel> #include <QLineEdit> #include <QVBoxLayout> #include <QHBoxLayout> #include <QSplitter> #include <QFontMetrics> #include <QVector> #include <Calculator.h> #include <Representer.h> #include <QDebug> ActivityWidget::ActivityWidget (QWidget * parent) : QWidget (parent) , editCodeId (nullptr) , editLength (nullptr) , editHexView (nullptr) , editStringView (nullptr) , editPsl (nullptr) , checkLengthAuto (nullptr) , plot (nullptr) , isLengthAutoDetect(true) { createWidgets (); createLayouts (); createConnections (); } void ActivityWidget::createWidgets () { editCodeId = new QLineEdit (this); editLength = new QLineEdit (this); editHexView = new QLineEdit (this); editStringView = new QLineEdit (this); editPsl = new QLineEdit (this); editHexView->setValidator (new ValidatorHexViewAdapter); editStringView->setValidator (new ValidatorStringViewAdapter); editStringView->setReadOnly (!isLengthAutoDetect); checkLengthAuto = new QCheckBox (this); checkLengthAuto->setCheckState (isLengthAutoDetect ? Qt::Checked : Qt::Unchecked); plot = new QCustomPlot (this); } void ActivityWidget::createLayouts () { QHBoxLayout * layoutCodeId = new QHBoxLayout (); QLabel * labelCodeId = new QLabel (tr ("Code ID") ); layoutCodeId->addWidget (labelCodeId); layoutCodeId->addWidget (editCodeId); QHBoxLayout * layoutLength = new QHBoxLayout (); QLabel * labelLength = new QLabel (tr ("Length") ); layoutLength->addWidget (labelLength); layoutLength->addWidget (editLength); QLabel * labelLengthAuto = new QLabel (tr ("Auto detect") ); layoutLength->addWidget (labelLengthAuto); layoutLength->addWidget (checkLengthAuto); QHBoxLayout * layoutHexView = new QHBoxLayout (); QLabel * labelHexView = new QLabel (tr ("Hex View") ); layoutHexView->addWidget (labelHexView); layoutHexView->addWidget (editHexView); QHBoxLayout * layoutStringView = new QHBoxLayout (); QLabel * labelStringView = new QLabel (tr ("String View") ); layoutStringView->addWidget (labelStringView); layoutStringView->addWidget (editStringView); QHBoxLayout * layoutPsl = new QHBoxLayout (); QLabel * labelPsl = new QLabel (tr ("PSL") ); layoutPsl->addWidget (labelPsl); layoutPsl->addWidget (editPsl); int width {0}; width = std::max (labelCodeId->fontMetrics ().width (labelCodeId->text () ), width); width = std::max (labelLength->fontMetrics ().width (labelLength->text () ), width); width = std::max (labelHexView->fontMetrics ().width (labelHexView->text () ), width); width = std::max (labelStringView->fontMetrics ().width (labelStringView->text () ), width); width = std::max (labelPsl->fontMetrics ().width (labelPsl->text () ), width); labelCodeId->setFixedWidth (width); labelLength->setFixedWidth (width); labelHexView->setFixedWidth (width); labelStringView->setFixedWidth (width); labelPsl->setFixedWidth (width); QWidget * widgetCode = new QWidget (); QVBoxLayout * layoutCode = new QVBoxLayout (); layoutCode->addLayout (layoutCodeId); layoutCode->addLayout (layoutLength); layoutCode->addLayout (layoutHexView); layoutCode->addLayout (layoutStringView); layoutCode->addLayout (layoutPsl); layoutCode->addStretch (); widgetCode->setLayout (layoutCode); QWidget * widgetChart = new QWidget (); QVBoxLayout * layoutChart = new QVBoxLayout (); layoutChart->addWidget (plot); widgetChart->setLayout (layoutChart); QSplitter * splitterTop = new QSplitter (Qt::Vertical, this); QVBoxLayout * layoutTop = new QVBoxLayout (); splitterTop->addWidget (widgetCode); splitterTop->addWidget (widgetChart); splitterTop->setStretchFactor (0, 0); splitterTop->setStretchFactor (1, 1); layoutTop->addWidget (splitterTop); this->setLayout (layoutTop); } void ActivityWidget::createConnections () { connect (editHexView, SIGNAL (textEdited (const QString &) ), this, SLOT (onHexViewEdited (const QString &) ) ); connect (editStringView, SIGNAL (textEdited (const QString &) ), this, SLOT (onStringViewEdited (const QString &) ) ); connect (checkLengthAuto, SIGNAL (stateChanged (int) ), this, SLOT (onLengthAutoDetectChanged (const int) ) ); } void ActivityWidget::onLengthAutoDetectChanged (const int state) { isLengthAutoDetect = (state == Qt::Checked ? true : false); // Explicit setting of code length has sense only for manipulating with hex views. editStringView->setReadOnly (!isLengthAutoDetect); } void ActivityWidget::onHexViewEdited (const QString & view) { std::string stringView; if (isLengthAutoDetect) { stringView = Pslrk::Core::Representer::HexViewToStringView (view.toStdString () ); } else { stringView = Pslrk::Core::Representer::HexViewToStringView (view.toStdString (), editLength->text ().toInt () ); } onViewChanged (stringView); editStringView->setText (QString::fromStdString (stringView) ); } void ActivityWidget::onStringViewEdited (const QString & view) { onViewChanged (view.toStdString () ); editHexView->setText (QString::fromStdString (Pslrk::Core::Representer::StringViewToHexView(view.toStdString () ) ) ); } void ActivityWidget::onViewChanged (const std::string & view) { editCodeId->setText (QString::fromStdString (Pslrk::Core::Representer::DetectCodeId (view) ) ); editPsl->setText (QString ("%1").arg (Pslrk::Core::Calculator::CalculatePsl (view) ) ); if (isLengthAutoDetect) { editLength->setText (QString ("%1").arg (view.size () ) ); } const double range = view.size (); QVector <double> y; for (auto i : Pslrk::Core::Calculator::CalculateAcf (view) ) { y.push_back (i); } QVector <double> x; for (int i = 0; i < y.size (); ++i) { x.push_back (i - range + 1); } double min {0.0}; for (auto i : y) { min = std::min (min, i); } double max {0.0}; for (auto i : y) { max = std::max (max, i); } plot->addGraph (); plot->graph (0)->setData (x, y); plot->graph (0)->setPen (QPen (Qt::blue) ); plot->xAxis->setRange (-range, range); plot->yAxis->setRange ( min, max); plot->xAxis->setVisible (true); plot->yAxis->setVisible (true); plot->replot (); }<|endoftext|>
<commit_before>// -*- mode: c++; indent-tabs-mode: nil; tab-width:2 -*- #include "ug_sampling_bias.h" #include <iostream> #include <boost/foreach.hpp> #include "moses/Util.h" #ifndef NO_MOSES #include "moses/Timer.h" #endif // #ifdef WITH_MMT_BIAS_CLIENT #include "ug_http_client.h" // #endif namespace sapt { using tpt::id_type; std::string query_bias_server(std::string const& server, std::string const& context, std::ostream* log) { std::string query = server + Moses::uri_encode(context); boost::asio::io_service io_service; Moses::http_client c(io_service, query, log); io_service.run(); if (log) { std::string response = c.content(); *log << "SERVER RESPONSE: " << response << std::endl; } if (c.content().size() == 0) { if (log) *log << "BIAS SERVER ERROR: " << c.error_msg() << std::endl; } return c.content(); } SamplingBias:: SamplingBias(std::vector<id_type> const* sid2doc) : m_sid2docid(sid2doc) { } int SamplingBias:: GetClass(id_type const idx) const { return m_sid2docid ? m_sid2docid->at(idx) : -1; } DocumentBias:: DocumentBias(std::vector<id_type> const& sid2doc, std::map<std::string,id_type> const& docname2docid, std::string const& server_url, std::string const& text, std::ostream* _log) : SamplingBias(&sid2doc) { this->log = _log; #ifndef NO_MOSES Moses::Timer timer; if (_log) timer.start(NULL); #endif std::string json = query_bias_server(server_url, text, _log); init_from_json(json, docname2docid, log); #ifndef NO_MOSES if (_log) *_log << "Bias query took " << timer << " seconds." << std::endl; #endif } DocumentBias:: DocumentBias(std::vector<id_type> const& sid2doc, std::map<std::string,id_type> const& docname2docid, std::map<std::string, float> const& context_weights, std::ostream* _log) : SamplingBias(&sid2doc) { this->log = _log; init(context_weights, docname2docid); } SPTR<std::map<std::string, float> const> SamplingBias:: getBiasMap() { return m_bias_map; } const std::map<id_type, float>& DocumentBias:: GetDocumentBiasMap() const { return m_bias; } void DocumentBias:: init_from_json ( std::string const& json, std::map<std::string,id_type> const& docname2docid, std::ostream* log) { // poor man's special purpose json parser for responses from the // MMT bias server std::string d; float total = 0; std::map<std::string,float> bias; size_t i = 0; while (i < json.size() && json[i] != '"') ++i; while (++i < json.size()) { size_t k = i; while (i < json.size() && json[i] != '"') ++i; if (i >= json.size()) break; float& f = bias[json.substr(k,i-k)]; while (++i < json.size() && json[i] != ':'); k = ++i; while (++i < json.size() && json[i] != ',' && json[i] != '}'); total += (f = atof(json.substr(k, i-k).c_str())); k = ++i; while (i < json.size() && json[i] != '"') ++i; } typedef std::pair<std::string const,float> item; if (total) { BOOST_FOREACH(item& x, bias) { x.second /= total; } } init(bias, docname2docid); } void DocumentBias:: init(std::map<std::string,float> const& biasmap, std::map<std::string,id_type> const& docname2docid) { typedef std::map<std::string, float>::value_type bias_record; float total = 0; m_bias_map.reset(new std::map<std::string,float>(biasmap)); BOOST_FOREACH(bias_record const& b, biasmap) { std::map<std::string, id_type>::const_iterator m; m = docname2docid.find(b.first); if (m != docname2docid.end()) total += (m_bias[m->second] = b.second); } if (total) { typedef std::map<id_type, float>::value_type item; BOOST_FOREACH(item& i, m_bias) i.second /= total; } if (log) { BOOST_FOREACH(bias_record const& b, biasmap) { std::map<std::string, id_type>::const_iterator m; m = = docname2docid.find(b.first); if (m != docname2docid.end()) *log << "BIAS " << b.first << " " << m_bias[m->second] << std::endl; else *log << "WARNING: bias reported for unknown document " << b.first << std::endl; } } } float DocumentBias:: operator[](id_type const idx) const { std::map<id_type, float>::const_iterator m; m = m_bias.find((*m_sid2docid)[idx]); return m != m_bias.end() ? m->second : 0; } size_t DocumentBias:: size() const { return m_sid2docid->size(); } SentenceBias:: SentenceBias(std::vector<float> const& bias, std::vector<id_type> const* sid2doc) : SamplingBias(sid2doc) , m_bias(bias) { } SentenceBias:: SentenceBias(size_t const s, float const f, std::vector<id_type> const* sid2doc) : SamplingBias(sid2doc) , m_bias(s,f) { } float& SentenceBias:: operator[](id_type const idx) { UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds"); return m_bias[idx]; } float SentenceBias:: operator[](id_type const idx) const { UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds"); return m_bias[idx]; } size_t SentenceBias:: size() const { return m_bias.size(); } } <commit_msg>Bug fix.<commit_after>// -*- mode: c++; indent-tabs-mode: nil; tab-width:2 -*- #include "ug_sampling_bias.h" #include <iostream> #include <boost/foreach.hpp> #include "moses/Util.h" #ifndef NO_MOSES #include "moses/Timer.h" #endif // #ifdef WITH_MMT_BIAS_CLIENT #include "ug_http_client.h" // #endif namespace sapt { using tpt::id_type; std::string query_bias_server(std::string const& server, std::string const& context, std::ostream* log) { std::string query = server + Moses::uri_encode(context); boost::asio::io_service io_service; Moses::http_client c(io_service, query, log); io_service.run(); if (log) { std::string response = c.content(); *log << "SERVER RESPONSE: " << response << std::endl; } if (c.content().size() == 0) { if (log) *log << "BIAS SERVER ERROR: " << c.error_msg() << std::endl; } return c.content(); } SamplingBias:: SamplingBias(std::vector<id_type> const* sid2doc) : m_sid2docid(sid2doc) { } int SamplingBias:: GetClass(id_type const idx) const { return m_sid2docid ? m_sid2docid->at(idx) : -1; } DocumentBias:: DocumentBias(std::vector<id_type> const& sid2doc, std::map<std::string,id_type> const& docname2docid, std::string const& server_url, std::string const& text, std::ostream* _log) : SamplingBias(&sid2doc) { this->log = _log; #ifndef NO_MOSES Moses::Timer timer; if (_log) timer.start(NULL); #endif std::string json = query_bias_server(server_url, text, _log); init_from_json(json, docname2docid, log); #ifndef NO_MOSES if (_log) *_log << "Bias query took " << timer << " seconds." << std::endl; #endif } DocumentBias:: DocumentBias(std::vector<id_type> const& sid2doc, std::map<std::string,id_type> const& docname2docid, std::map<std::string, float> const& context_weights, std::ostream* _log) : SamplingBias(&sid2doc) { this->log = _log; init(context_weights, docname2docid); } SPTR<std::map<std::string, float> const> SamplingBias:: getBiasMap() { return m_bias_map; } const std::map<id_type, float>& DocumentBias:: GetDocumentBiasMap() const { return m_bias; } void DocumentBias:: init_from_json ( std::string const& json, std::map<std::string,id_type> const& docname2docid, std::ostream* log) { // poor man's special purpose json parser for responses from the // MMT bias server std::string d; float total = 0; std::map<std::string,float> bias; size_t i = 0; while (i < json.size() && json[i] != '"') ++i; while (++i < json.size()) { size_t k = i; while (i < json.size() && json[i] != '"') ++i; if (i >= json.size()) break; float& f = bias[json.substr(k,i-k)]; while (++i < json.size() && json[i] != ':'); k = ++i; while (++i < json.size() && json[i] != ',' && json[i] != '}'); total += (f = atof(json.substr(k, i-k).c_str())); k = ++i; while (i < json.size() && json[i] != '"') ++i; } typedef std::pair<std::string const,float> item; if (total) { BOOST_FOREACH(item& x, bias) { x.second /= total; } } init(bias, docname2docid); } void DocumentBias:: init(std::map<std::string,float> const& biasmap, std::map<std::string,id_type> const& docname2docid) { typedef std::map<std::string, float>::value_type bias_record; float total = 0; m_bias_map.reset(new std::map<std::string,float>(biasmap)); BOOST_FOREACH(bias_record const& b, biasmap) { std::map<std::string, id_type>::const_iterator m; m = docname2docid.find(b.first); if (m != docname2docid.end()) total += (m_bias[m->second] = b.second); } if (total) { typedef std::map<id_type, float>::value_type item; BOOST_FOREACH(item& i, m_bias) i.second /= total; } if (log) { BOOST_FOREACH(bias_record const& b, biasmap) { std::map<std::string, id_type>::const_iterator m; m = docname2docid.find(b.first); if (m != docname2docid.end()) *log << "BIAS " << b.first << " " << m_bias[m->second] << std::endl; else *log << "WARNING: bias reported for unknown document " << b.first << std::endl; } } } float DocumentBias:: operator[](id_type const idx) const { std::map<id_type, float>::const_iterator m; m = m_bias.find((*m_sid2docid)[idx]); return m != m_bias.end() ? m->second : 0; } size_t DocumentBias:: size() const { return m_sid2docid->size(); } SentenceBias:: SentenceBias(std::vector<float> const& bias, std::vector<id_type> const* sid2doc) : SamplingBias(sid2doc) , m_bias(bias) { } SentenceBias:: SentenceBias(size_t const s, float const f, std::vector<id_type> const* sid2doc) : SamplingBias(sid2doc) , m_bias(s,f) { } float& SentenceBias:: operator[](id_type const idx) { UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds"); return m_bias[idx]; } float SentenceBias:: operator[](id_type const idx) const { UTIL_THROW_IF2(idx >= m_bias.size(), "Out of bounds"); return m_bias[idx]; } size_t SentenceBias:: size() const { return m_bias.size(); } } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/pick_place/pick_place.h> #include <moveit/pick_place/reachable_valid_pose_filter.h> #include <moveit/pick_place/approach_and_translate_stage.h> #include <moveit/pick_place/plan_stage.h> #include <moveit/robot_state/conversions.h> #include <eigen_conversions/eigen_msg.h> #include <ros/console.h> namespace pick_place { PlacePlan::PlacePlan(const PickPlaceConstPtr &pick_place) : PickPlacePlanBase(pick_place, "place") { } namespace { bool transformToEndEffectorGoal(const geometry_msgs::PoseStamped &goal_pose, const robot_state::AttachedBody* attached_body, geometry_msgs::PoseStamped &place_pose) { const EigenSTL::vector_Affine3d& fixed_transforms = attached_body->getFixedTransforms(); if (fixed_transforms.empty()) return false; Eigen::Affine3d end_effector_transform; tf::poseMsgToEigen(goal_pose.pose, end_effector_transform); end_effector_transform = end_effector_transform * fixed_transforms[0].inverse(); place_pose.header = goal_pose.header; tf::poseEigenToMsg(end_effector_transform, place_pose.pose); return true; } } bool PlacePlan::plan(const planning_scene::PlanningSceneConstPtr &planning_scene, const moveit_msgs::PlaceGoal &goal) { double timeout = goal.allowed_planning_time; ros::WallTime endtime = ros::WallTime::now() + ros::WallDuration(timeout); std::string attached_object_name = goal.attached_object_name; const robot_model::JointModelGroup *jmg = NULL; const robot_model::JointModelGroup *eef = NULL; if (planning_scene->getRobotModel()->hasEndEffector(goal.group_name)) { eef = planning_scene->getRobotModel()->getEndEffector(goal.group_name); if (eef) { const std::string &eef_parent = eef->getEndEffectorParentGroup().first; jmg = planning_scene->getRobotModel()->getJointModelGroup(eef_parent); } } else { jmg = planning_scene->getRobotModel()->getJointModelGroup(goal.group_name); if (jmg) { const std::vector<std::string> &eef_names = jmg->getAttachedEndEffectorNames(); if (eef_names.size() == 1) { eef = planning_scene->getRobotModel()->getEndEffector(eef_names[0]); } } } if (!jmg) { error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME; return false; } // try to infer attached body name if possible int loop_count = 0; while (attached_object_name.empty() && loop_count < 2) { // in the first try, look for objects attached to the eef, if the eef is known; // otherwise, look for attached bodies in the planning group itself std::vector<const robot_state::AttachedBody*> attached_bodies; planning_scene->getCurrentState().getAttachedBodies(attached_bodies, loop_count == 0 ? (eef ? eef : jmg) : jmg); // if we had no eef, there is no more looping to do, so we bump the loop count if (loop_count == 0 && !eef) loop_count++; loop_count++; if (attached_bodies.size() > 1) { ROS_ERROR("Multiple attached bodies for group '%s' but no explicit attached object to place was specified", goal.group_name.c_str()); error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_OBJECT_NAME; return false; } else attached_object_name = attached_bodies[0]->getName(); } const robot_state::AttachedBody *attached_body = planning_scene->getCurrentState().getAttachedBody(attached_object_name); if (!attached_body) { ROS_ERROR("There is no object to detach"); error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_OBJECT_NAME; return false; } ros::WallTime start_time = ros::WallTime::now(); // construct common data for possible manipulation plans ManipulationPlanSharedDataPtr plan_data(new ManipulationPlanSharedData()); ManipulationPlanSharedDataConstPtr const_plan_data = plan_data; plan_data->planning_group_ = jmg; plan_data->end_effector_group_ = eef; if (eef) plan_data->ik_link_ = planning_scene->getRobotModel()->getLinkModel(eef->getEndEffectorParentGroup().second); plan_data->timeout_ = endtime; plan_data->path_constraints_ = goal.path_constraints; plan_data->planner_id_ = goal.planner_id; plan_data->minimize_object_distance_ = false; plan_data->max_goal_sampling_attempts_ = std::max(2u, jmg->getDefaultIKAttempts()); moveit_msgs::AttachedCollisionObject &detach_object_msg = plan_data->diff_attached_object_; // construct the attached object message that will change the world to what it would become after a placement detach_object_msg.link_name = attached_body->getAttachedLinkName(); detach_object_msg.object.id = attached_object_name; detach_object_msg.object.operation = moveit_msgs::CollisionObject::REMOVE; collision_detection::AllowedCollisionMatrixPtr approach_place_acm(new collision_detection::AllowedCollisionMatrix(planning_scene->getAllowedCollisionMatrix())); // we are allowed to touch certain other objects with the gripper approach_place_acm->setEntry(eef->getLinkModelNames(), goal.allowed_touch_objects, true); // we are allowed to touch the target object slightly while retreating the end effector std::vector<std::string> touch_links(attached_body->getTouchLinks().begin(), attached_body->getTouchLinks().end()); approach_place_acm->setEntry(attached_object_name, touch_links, true); if (!goal.support_surface_name.empty()) { // we are allowed to have contact between the target object and the support surface before the place approach_place_acm->setEntry(goal.support_surface_name, attached_object_name, true); // optionally, it may be allowed to touch the support surface with the gripper if (goal.allow_gripper_support_collision && eef) approach_place_acm->setEntry(goal.support_surface_name, eef->getLinkModelNames(), true); } // configure the manipulation pipeline pipeline_.reset(); ManipulationStagePtr stage1(new ReachableAndValidPoseFilter(planning_scene, approach_place_acm, pick_place_->getConstraintsSamplerManager())); ManipulationStagePtr stage2(new ApproachAndTranslateStage(planning_scene, approach_place_acm)); ManipulationStagePtr stage3(new PlanStage(planning_scene, pick_place_->getPlanningPipeline())); pipeline_.addStage(stage1).addStage(stage2).addStage(stage3); initialize(); pipeline_.start(); // add possible place locations for (std::size_t i = 0 ; i < goal.place_locations.size() ; ++i) { ManipulationPlanPtr p(new ManipulationPlan(const_plan_data)); const moveit_msgs::PlaceLocation &pl = goal.place_locations[i]; if (goal.place_eef) p->goal_pose_ = pl.place_pose; else // The goals are specified for the attached body // but we want to transform them into goals for the end-effector instead if (!transformToEndEffectorGoal(pl.place_pose, attached_body, p->goal_pose_)) { p->goal_pose_ = pl.place_pose; logError("Unable to transform the desired pose of the object to the pose of the end-effector"); } p->approach_ = pl.pre_place_approach; p->retreat_ = pl.post_place_retreat; p->retreat_posture_ = pl.post_place_posture; p->id_ = i; if (p->retreat_posture_.joint_names.empty()) p->retreat_posture_ = attached_body->getDetachPosture(); pipeline_.push(p); } ROS_INFO("Added %d place locations", (int) goal.place_locations.size()); // wait till we're done waitForPipeline(endtime); pipeline_.stop(); last_plan_time_ = (ros::WallTime::now() - start_time).toSec(); if (!getSuccessfulManipulationPlans().empty()) error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS; else { if (last_plan_time_ > timeout) error_code_.val = moveit_msgs::MoveItErrorCodes::TIMED_OUT; else { error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; if (goal.place_locations.size() > 0) { ROS_WARN("All supplied place locations failed. Retrying last location in verbose mode."); // everything failed. we now start the pipeline again in verbose mode for one grasp initialize(); pipeline_.setVerbose(true); pipeline_.start(); pipeline_.reprocessLastFailure(); waitForPipeline(ros::WallTime::now() + ros::WallDuration(1.0)); pipeline_.stop(); pipeline_.setVerbose(false); } } } ROS_INFO("Place planning completed after %lf seconds", last_plan_time_); return error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS; } PlacePlanPtr PickPlace::planPlace(const planning_scene::PlanningSceneConstPtr &planning_scene, const moveit_msgs::PlaceGoal &goal) const { PlacePlanPtr p(new PlacePlan(shared_from_this())); if (planning_scene::PlanningScene::isEmpty(goal.planning_options.planning_scene_diff)) p->plan(planning_scene, goal); else p->plan(planning_scene->diff(goal.planning_options.planning_scene_diff), goal); if (display_computed_motion_plans_) { const std::vector<pick_place::ManipulationPlanPtr> &success = p->getSuccessfulManipulationPlans(); if (!success.empty()) visualizePlan(success.back()); } if (display_grasps_) { const std::vector<pick_place::ManipulationPlanPtr> &success = p->getSuccessfulManipulationPlans(); visualizeGrasps(success); const std::vector<pick_place::ManipulationPlanPtr> &failed = p->getFailedManipulationPlans(); visualizeGrasps(failed); } return p; } } <commit_msg>abort place if eef cannot be determined, fixes #325<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/pick_place/pick_place.h> #include <moveit/pick_place/reachable_valid_pose_filter.h> #include <moveit/pick_place/approach_and_translate_stage.h> #include <moveit/pick_place/plan_stage.h> #include <moveit/robot_state/conversions.h> #include <eigen_conversions/eigen_msg.h> #include <ros/console.h> namespace pick_place { PlacePlan::PlacePlan(const PickPlaceConstPtr &pick_place) : PickPlacePlanBase(pick_place, "place") { } namespace { bool transformToEndEffectorGoal(const geometry_msgs::PoseStamped &goal_pose, const robot_state::AttachedBody* attached_body, geometry_msgs::PoseStamped &place_pose) { const EigenSTL::vector_Affine3d& fixed_transforms = attached_body->getFixedTransforms(); if (fixed_transforms.empty()) return false; Eigen::Affine3d end_effector_transform; tf::poseMsgToEigen(goal_pose.pose, end_effector_transform); end_effector_transform = end_effector_transform * fixed_transforms[0].inverse(); place_pose.header = goal_pose.header; tf::poseEigenToMsg(end_effector_transform, place_pose.pose); return true; } } bool PlacePlan::plan(const planning_scene::PlanningSceneConstPtr &planning_scene, const moveit_msgs::PlaceGoal &goal) { double timeout = goal.allowed_planning_time; ros::WallTime endtime = ros::WallTime::now() + ros::WallDuration(timeout); std::string attached_object_name = goal.attached_object_name; const robot_model::JointModelGroup *jmg = NULL; const robot_model::JointModelGroup *eef = NULL; if (planning_scene->getRobotModel()->hasEndEffector(goal.group_name)) { eef = planning_scene->getRobotModel()->getEndEffector(goal.group_name); if (eef) { const std::string &eef_parent = eef->getEndEffectorParentGroup().first; jmg = planning_scene->getRobotModel()->getJointModelGroup(eef_parent); } } else { jmg = planning_scene->getRobotModel()->getJointModelGroup(goal.group_name); if (jmg) { const std::vector<std::string> &eef_names = jmg->getAttachedEndEffectorNames(); if (eef_names.size() == 1) { eef = planning_scene->getRobotModel()->getEndEffector(eef_names[0]); } } } if (!jmg || !eef) { error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_GROUP_NAME; return false; } // try to infer attached body name if possible int loop_count = 0; while (attached_object_name.empty() && loop_count < 2) { // in the first try, look for objects attached to the eef, if the eef is known; // otherwise, look for attached bodies in the planning group itself std::vector<const robot_state::AttachedBody*> attached_bodies; planning_scene->getCurrentState().getAttachedBodies(attached_bodies, loop_count == 0 ? (eef ? eef : jmg) : jmg); // if we had no eef, there is no more looping to do, so we bump the loop count if (loop_count == 0 && !eef) loop_count++; loop_count++; if (attached_bodies.size() > 1) { ROS_ERROR("Multiple attached bodies for group '%s' but no explicit attached object to place was specified", goal.group_name.c_str()); error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_OBJECT_NAME; return false; } else attached_object_name = attached_bodies[0]->getName(); } const robot_state::AttachedBody *attached_body = planning_scene->getCurrentState().getAttachedBody(attached_object_name); if (!attached_body) { ROS_ERROR("There is no object to detach"); error_code_.val = moveit_msgs::MoveItErrorCodes::INVALID_OBJECT_NAME; return false; } ros::WallTime start_time = ros::WallTime::now(); // construct common data for possible manipulation plans ManipulationPlanSharedDataPtr plan_data(new ManipulationPlanSharedData()); ManipulationPlanSharedDataConstPtr const_plan_data = plan_data; plan_data->planning_group_ = jmg; plan_data->end_effector_group_ = eef; if (eef) plan_data->ik_link_ = planning_scene->getRobotModel()->getLinkModel(eef->getEndEffectorParentGroup().second); plan_data->timeout_ = endtime; plan_data->path_constraints_ = goal.path_constraints; plan_data->planner_id_ = goal.planner_id; plan_data->minimize_object_distance_ = false; plan_data->max_goal_sampling_attempts_ = std::max(2u, jmg->getDefaultIKAttempts()); moveit_msgs::AttachedCollisionObject &detach_object_msg = plan_data->diff_attached_object_; // construct the attached object message that will change the world to what it would become after a placement detach_object_msg.link_name = attached_body->getAttachedLinkName(); detach_object_msg.object.id = attached_object_name; detach_object_msg.object.operation = moveit_msgs::CollisionObject::REMOVE; collision_detection::AllowedCollisionMatrixPtr approach_place_acm(new collision_detection::AllowedCollisionMatrix(planning_scene->getAllowedCollisionMatrix())); // we are allowed to touch certain other objects with the gripper approach_place_acm->setEntry(eef->getLinkModelNames(), goal.allowed_touch_objects, true); // we are allowed to touch the target object slightly while retreating the end effector std::vector<std::string> touch_links(attached_body->getTouchLinks().begin(), attached_body->getTouchLinks().end()); approach_place_acm->setEntry(attached_object_name, touch_links, true); if (!goal.support_surface_name.empty()) { // we are allowed to have contact between the target object and the support surface before the place approach_place_acm->setEntry(goal.support_surface_name, attached_object_name, true); // optionally, it may be allowed to touch the support surface with the gripper if (goal.allow_gripper_support_collision && eef) approach_place_acm->setEntry(goal.support_surface_name, eef->getLinkModelNames(), true); } // configure the manipulation pipeline pipeline_.reset(); ManipulationStagePtr stage1(new ReachableAndValidPoseFilter(planning_scene, approach_place_acm, pick_place_->getConstraintsSamplerManager())); ManipulationStagePtr stage2(new ApproachAndTranslateStage(planning_scene, approach_place_acm)); ManipulationStagePtr stage3(new PlanStage(planning_scene, pick_place_->getPlanningPipeline())); pipeline_.addStage(stage1).addStage(stage2).addStage(stage3); initialize(); pipeline_.start(); // add possible place locations for (std::size_t i = 0 ; i < goal.place_locations.size() ; ++i) { ManipulationPlanPtr p(new ManipulationPlan(const_plan_data)); const moveit_msgs::PlaceLocation &pl = goal.place_locations[i]; if (goal.place_eef) p->goal_pose_ = pl.place_pose; else // The goals are specified for the attached body // but we want to transform them into goals for the end-effector instead if (!transformToEndEffectorGoal(pl.place_pose, attached_body, p->goal_pose_)) { p->goal_pose_ = pl.place_pose; logError("Unable to transform the desired pose of the object to the pose of the end-effector"); } p->approach_ = pl.pre_place_approach; p->retreat_ = pl.post_place_retreat; p->retreat_posture_ = pl.post_place_posture; p->id_ = i; if (p->retreat_posture_.joint_names.empty()) p->retreat_posture_ = attached_body->getDetachPosture(); pipeline_.push(p); } ROS_INFO("Added %d place locations", (int) goal.place_locations.size()); // wait till we're done waitForPipeline(endtime); pipeline_.stop(); last_plan_time_ = (ros::WallTime::now() - start_time).toSec(); if (!getSuccessfulManipulationPlans().empty()) error_code_.val = moveit_msgs::MoveItErrorCodes::SUCCESS; else { if (last_plan_time_ > timeout) error_code_.val = moveit_msgs::MoveItErrorCodes::TIMED_OUT; else { error_code_.val = moveit_msgs::MoveItErrorCodes::PLANNING_FAILED; if (goal.place_locations.size() > 0) { ROS_WARN("All supplied place locations failed. Retrying last location in verbose mode."); // everything failed. we now start the pipeline again in verbose mode for one grasp initialize(); pipeline_.setVerbose(true); pipeline_.start(); pipeline_.reprocessLastFailure(); waitForPipeline(ros::WallTime::now() + ros::WallDuration(1.0)); pipeline_.stop(); pipeline_.setVerbose(false); } } } ROS_INFO("Place planning completed after %lf seconds", last_plan_time_); return error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS; } PlacePlanPtr PickPlace::planPlace(const planning_scene::PlanningSceneConstPtr &planning_scene, const moveit_msgs::PlaceGoal &goal) const { PlacePlanPtr p(new PlacePlan(shared_from_this())); if (planning_scene::PlanningScene::isEmpty(goal.planning_options.planning_scene_diff)) p->plan(planning_scene, goal); else p->plan(planning_scene->diff(goal.planning_options.planning_scene_diff), goal); if (display_computed_motion_plans_) { const std::vector<pick_place::ManipulationPlanPtr> &success = p->getSuccessfulManipulationPlans(); if (!success.empty()) visualizePlan(success.back()); } if (display_grasps_) { const std::vector<pick_place::ManipulationPlanPtr> &success = p->getSuccessfulManipulationPlans(); visualizeGrasps(success); const std::vector<pick_place::ManipulationPlanPtr> &failed = p->getFailedManipulationPlans(); visualizeGrasps(failed); } return p; } } <|endoftext|>
<commit_before>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include "multi-dgemm-type.hpp" #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstdlib> #include <cstring> #include <cstdio> #include <vector> #include <cmath> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> //#define MULTI_DGEMM_CHECK #define MULTI_DGEMM_SYNC 3 #define DGEMM dgemm_ LIBXSTREAM_EXTERN_C LIBXSTREAM_TARGET(mic) void DGEMM( const char*, const char*, const int*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*); LIBXSTREAM_TARGET(mic) void process(LIBXSTREAM_INVAL(size_t) size, LIBXSTREAM_INVAL(size_t) nn, const size_t* idata, const double* adata, const double* bdata, double* cdata) { if (0 < LIBXSTREAM_GETVAL(size)) { static const double alpha = 1, beta = 1; static const char trans = 'N'; const int isize = static_cast<int>(size); const size_t base = idata[0]; for (int i = 0; i < isize; ++i) { LIBXSTREAM_ASSERT(base <= idata[i]); const size_t i0 = idata[i], i1 = (i + 1) < isize ? idata[i+1] : (i0 + LIBXSTREAM_GETVAL(nn)), n2 = i1 - i0, offset = i0 - base; const int n = static_cast<int>(std::sqrt(static_cast<double>(n2)) + 0.5); DGEMM(&trans, &trans, &n, &n, &n, &alpha, adata + offset, &n, bdata + offset, &n, &beta, cdata + offset, &n); } } } int main(int argc, char* argv[]) { try { const int nitems = std::max(1 < argc ? std::atoi(argv[1]) : 60, 0); const int nbatch = std::max(2 < argc ? std::atoi(argv[2]) : 5, 1); const int mstreams = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS); #if defined(_OPENMP) const int nthreads = std::max(4 < argc ? std::atoi(argv[4]) : 2, 1); // not limited to test oversubscription #else LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); #endif size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { LIBXSTREAM_PRINT0(2, "No device found or device not ready!"); } fprintf(stdout, "Initializing %i device%s and host data...", static_cast<int>(ndevices), 1 == ndevices ? "" : "s"); const size_t split[] = { size_t(nitems * 18.0 / 250.0 + 0.5), size_t(nitems * 74.0 / 250.0 + 0.5) }; multi_dgemm_type::host_data_type host_data(reinterpret_cast<libxstream_function>(&process), nitems, split); fprintf(stdout, " %.1f MB\n", host_data.bytes() * 1E-6); fprintf(stdout, "Initializing %i stream%s per device...", mstreams, 1 < mstreams ? "s" : ""); const size_t nstreams = LIBXSTREAM_MAX(mstreams, 1) * LIBXSTREAM_MAX(ndevices, 1); multi_dgemm_type multi_dgemm[LIBXSTREAM_MAX_NSTREAMS]; for (size_t i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", static_cast<int>(i + 1)); LIBXSTREAM_CHECK_CALL_THROW(multi_dgemm[i].init(name, host_data, 0 < ndevices ? static_cast<int>(i % ndevices) : -1, static_cast<size_t>(nbatch))); } if (0 < nstreams) { fprintf(stdout, " %.1f MB\n", mstreams * multi_dgemm[0].bytes() * 1E-6); } // start benchmark with no pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); const int nbatches = (nitems + nbatch - 1) / nbatch; fprintf(stdout, "Running %i batch%s of %i item%s...\n", nbatches, 1 < nbatches ? "es" : "", std::min(nbatch, nitems), 1 < nbatch ? "s" : ""); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nitems; i += nbatch) { const size_t ibatch = i / nbatch, j = ibatch % nstreams; multi_dgemm_type& call = multi_dgemm[j]; LIBXSTREAM_CHECK_CALL_ASSERT(call(i, std::min(nbatch, nitems - i))); // enqueue batch #if defined(MULTI_DGEMM_SYNC) # if (2 <= MULTI_DGEMM_SYNC) // record event LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_record(call.event(), call.stream())); # endif const size_t k = (j + nstreams - 1) % nstreams; # if (3 <= (MULTI_DGEMM_SYNC)) // wait for an event within a stream LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_wait_event(multi_dgemm[k].stream(), call.event())); # elif (2 <= (MULTI_DGEMM_SYNC)) // wait for an event on the host LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_wait(multi_dgemm[k].event())); # else LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(multi_dgemm[k].stream())); # endif #endif } // wait for all streams to complete pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "Performance: %.1f GFLOPS/s\n", host_data.flops() * 1E-9 / duration); } fprintf(stdout, "Duration: %.1f s\n", duration); #endif #if !defined(MULTI_DGEMM_CHECK) const char *const check_env = getenv("CHECK"); if (check_env && *check_env && 0 != atoi(check_env)) #endif { std::vector<double> expected(host_data.max_matrix_size()); const size_t testbatchsize = 1; double max_error = 0; size_t i0 = 0; for (int i = 0; i < nitems; ++i) { const size_t i1 = host_data.idata()[i+1]; const int nn = static_cast<int>(i1 - i0); std::fill_n(&expected[0], nn, 0.0); process(LIBXSTREAM_SETVAL(testbatchsize), LIBXSTREAM_SETVAL(nn), host_data.idata() + i, host_data.adata() + i0, host_data.bdata() + i0, &expected[0]); for (int n = 0; n < nn; ++n) max_error = std::max(max_error, std::abs(expected[n] - host_data.cdata()[i0+n])); i0 = i1; } fprintf(stdout, "Error: %g\n", max_error); } fprintf(stdout, "Finished\n"); } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <commit_msg>Enabled stream-based synchronization (MULTI_DGEMM_SYNC).<commit_after>/****************************************************************************** ** Copyright (c) 2014-2015, Intel Corporation ** ** All rights reserved. ** ** ** ** Redistribution and use in source and binary forms, with or without ** ** modification, are permitted provided that the following conditions ** ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** ** notice, this list of conditions and the following disclaimer. ** ** 2. Redistributions in binary form must reproduce the above copyright ** ** notice, this list of conditions and the following disclaimer in the ** ** documentation and/or other materials provided with the distribution. ** ** 3. Neither the name of the copyright holder nor the names of its ** ** contributors may be used to endorse or promote products derived ** ** from this software without specific prior written permission. ** ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** ** HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED ** ** TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ** ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF ** ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING ** ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ /* Hans Pabst (Intel Corp.) ******************************************************************************/ #include "multi-dgemm-type.hpp" #include <libxstream_begin.h> #include <stdexcept> #include <algorithm> #include <cstdlib> #include <cstring> #include <cstdio> #include <vector> #include <cmath> #if defined(_OPENMP) # include <omp.h> #endif #include <libxstream_end.h> //#define MULTI_DGEMM_CHECK #define MULTI_DGEMM_SYNC 1 #define DGEMM dgemm_ LIBXSTREAM_EXTERN_C LIBXSTREAM_TARGET(mic) void DGEMM( const char*, const char*, const int*, const int*, const int*, const double*, const double*, const int*, const double*, const int*, const double*, double*, const int*); LIBXSTREAM_TARGET(mic) void process(LIBXSTREAM_INVAL(size_t) size, LIBXSTREAM_INVAL(size_t) nn, const size_t* idata, const double* adata, const double* bdata, double* cdata) { if (0 < LIBXSTREAM_GETVAL(size)) { static const double alpha = 1, beta = 1; static const char trans = 'N'; const int isize = static_cast<int>(size); const size_t base = idata[0]; for (int i = 0; i < isize; ++i) { LIBXSTREAM_ASSERT(base <= idata[i]); const size_t i0 = idata[i], i1 = (i + 1) < isize ? idata[i+1] : (i0 + LIBXSTREAM_GETVAL(nn)), n2 = i1 - i0, offset = i0 - base; const int n = static_cast<int>(std::sqrt(static_cast<double>(n2)) + 0.5); DGEMM(&trans, &trans, &n, &n, &n, &alpha, adata + offset, &n, bdata + offset, &n, &beta, cdata + offset, &n); } } } int main(int argc, char* argv[]) { try { const int nitems = std::max(1 < argc ? std::atoi(argv[1]) : 60, 0); const int nbatch = std::max(2 < argc ? std::atoi(argv[2]) : 5, 1); const int mstreams = std::min(std::max(3 < argc ? std::atoi(argv[3]) : 2, 1), LIBXSTREAM_MAX_NSTREAMS); #if defined(_OPENMP) const int nthreads = std::max(4 < argc ? std::atoi(argv[4]) : 2, 1); // not limited to test oversubscription #else LIBXSTREAM_PRINT0(1, "OpenMP support needed for performance results!"); #endif size_t ndevices = 0; if (LIBXSTREAM_ERROR_NONE != libxstream_get_ndevices(&ndevices) || 0 == ndevices) { LIBXSTREAM_PRINT0(2, "No device found or device not ready!"); } fprintf(stdout, "Initializing %i device%s and host data...", static_cast<int>(ndevices), 1 == ndevices ? "" : "s"); const size_t split[] = { size_t(nitems * 18.0 / 250.0 + 0.5), size_t(nitems * 74.0 / 250.0 + 0.5) }; multi_dgemm_type::host_data_type host_data(reinterpret_cast<libxstream_function>(&process), nitems, split); fprintf(stdout, " %.1f MB\n", host_data.bytes() * 1E-6); fprintf(stdout, "Initializing %i stream%s per device...", mstreams, 1 < mstreams ? "s" : ""); const size_t nstreams = LIBXSTREAM_MAX(mstreams, 1) * LIBXSTREAM_MAX(ndevices, 1); multi_dgemm_type multi_dgemm[LIBXSTREAM_MAX_NSTREAMS]; for (size_t i = 0; i < nstreams; ++i) { char name[128]; LIBXSTREAM_SNPRINTF(name, sizeof(name), "Stream %i", static_cast<int>(i + 1)); LIBXSTREAM_CHECK_CALL_THROW(multi_dgemm[i].init(name, host_data, 0 < ndevices ? static_cast<int>(i % ndevices) : -1, static_cast<size_t>(nbatch))); } if (0 < nstreams) { fprintf(stdout, " %.1f MB\n", mstreams * multi_dgemm[0].bytes() * 1E-6); } // start benchmark with no pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); const int nbatches = (nitems + nbatch - 1) / nbatch; fprintf(stdout, "Running %i batch%s of %i item%s...\n", nbatches, 1 < nbatches ? "es" : "", std::min(nbatch, nitems), 1 < nbatch ? "s" : ""); #if defined(_OPENMP) const double start = omp_get_wtime(); # pragma omp parallel for num_threads(nthreads) schedule(dynamic) #endif for (int i = 0; i < nitems; i += nbatch) { const size_t ibatch = i / nbatch, j = ibatch % nstreams; multi_dgemm_type& call = multi_dgemm[j]; LIBXSTREAM_CHECK_CALL_ASSERT(call(i, std::min(nbatch, nitems - i))); // enqueue batch #if defined(MULTI_DGEMM_SYNC) # if (2 <= MULTI_DGEMM_SYNC) // record event LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_record(call.event(), call.stream())); # endif const size_t k = (j + nstreams - 1) % nstreams; # if (3 <= (MULTI_DGEMM_SYNC)) // wait for an event within a stream LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_wait_event(multi_dgemm[k].stream(), call.event())); # elif (2 <= (MULTI_DGEMM_SYNC)) // wait for an event on the host LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_event_wait(multi_dgemm[k].event())); # else LIBXSTREAM_CHECK_CALL_ASSERT(libxstream_stream_sync(multi_dgemm[k].stream())); # endif #endif } // wait for all streams to complete pending work LIBXSTREAM_CHECK_CALL_THROW(libxstream_stream_wait(0)); #if defined(_OPENMP) const double duration = omp_get_wtime() - start; if (0 < duration) { fprintf(stdout, "Performance: %.1f GFLOPS/s\n", host_data.flops() * 1E-9 / duration); } fprintf(stdout, "Duration: %.1f s\n", duration); #endif #if !defined(MULTI_DGEMM_CHECK) const char *const check_env = getenv("CHECK"); if (check_env && *check_env && 0 != atoi(check_env)) #endif { std::vector<double> expected(host_data.max_matrix_size()); const size_t testbatchsize = 1; double max_error = 0; size_t i0 = 0; for (int i = 0; i < nitems; ++i) { const size_t i1 = host_data.idata()[i+1]; const int nn = static_cast<int>(i1 - i0); std::fill_n(&expected[0], nn, 0.0); process(LIBXSTREAM_SETVAL(testbatchsize), LIBXSTREAM_SETVAL(nn), host_data.idata() + i, host_data.adata() + i0, host_data.bdata() + i0, &expected[0]); for (int n = 0; n < nn; ++n) max_error = std::max(max_error, std::abs(expected[n] - host_data.cdata()[i0+n])); i0 = i1; } fprintf(stdout, "Error: %g\n", max_error); } fprintf(stdout, "Finished\n"); } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } catch(...) { fprintf(stderr, "Error: unknown exception caught!\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pkgcontent.hxx,v $ * * $Revision: 1.30 $ * * last change: $Author: ihi $ $Date: 2007-06-05 18:13:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _PKGCONTENT_HXX #define _PKGCONTENT_HXX #include <list> #ifndef _RTL_REF_HXX_ #include <rtl/ref.hxx> #endif #ifndef _COM_SUN_STAR_UCB_INTERACTIVEBADTRANSFRERURLEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveBadTransferURLException.hpp> #endif #ifndef _COM_SUN_STAR_UCB_XCONTENTCREATOR_HPP_ #include <com/sun/star/ucb/XContentCreator.hpp> #endif #ifndef _UCBHELPER_CONTENTHELPER_HXX #include <ucbhelper/contenthelper.hxx> #endif #ifndef _PKGURI_HXX #include "pkguri.hxx" #endif namespace com { namespace sun { namespace star { namespace beans { struct Property; struct PropertyValue; } namespace container { class XHierarchicalNameAccess; class XEnumeration; } namespace io { class XInputStream; } namespace sdbc { class XRow; } namespace ucb { struct OpenCommandArgument2; struct TransferInfo; } } } } namespace package_ucp { //========================================================================= // UNO service name for the content. #define PACKAGE_FOLDER_CONTENT_SERVICE_NAME \ "com.sun.star.ucb.PackageFolderContent" #define PACKAGE_STREAM_CONTENT_SERVICE_NAME \ "com.sun.star.ucb.PackageStreamContent" //========================================================================= struct ContentProperties { ::rtl::OUString aTitle; // Title ::rtl::OUString aContentType; // ContentType sal_Bool bIsDocument; // IsDocument sal_Bool bIsFolder; // IsFolder ::rtl::OUString aMediaType; // MediaType com::sun::star::uno::Sequence < sal_Int8 > aEncryptionKey; // EncryptionKey sal_Int64 nSize; // Size sal_Bool bCompressed; // Compressed sal_Bool bEncrypted; // Encrypted sal_Bool bHasEncryptedEntries; // HasEncryptedEntries ContentProperties() : bIsDocument( sal_True ), bIsFolder( sal_False ), nSize( 0 ), bCompressed( sal_True ), bEncrypted( sal_False ), bHasEncryptedEntries( sal_False ) {} ContentProperties( const ::rtl::OUString& rContentType ); }; //========================================================================= class ContentProvider; class Content : public ::ucbhelper::ContentImplHelper, public com::sun::star::ucb::XContentCreator { enum ContentState { TRANSIENT, // created via CreateNewContent, // but did not process "insert" yet PERSISTENT, // processed "insert" DEAD // processed "delete" }; PackageUri m_aUri; ContentProperties m_aProps; ContentState m_eState; com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > m_xPackage; ContentProvider* m_pProvider; sal_uInt32 m_nModifiedProps; private: Content( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const ::com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess >& Package, const PackageUri& rUri, const ContentProperties& rProps ); Content( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess >& Package, const PackageUri& rUri, const com::sun::star::ucb::ContentInfo& Info ); virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property > getProperties( const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > & xEnv ); virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo > getCommands( const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > & xEnv ); virtual ::rtl::OUString getParentURL(); static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties, const ContentProperties& rData, const rtl::Reference< ::ucbhelper::ContentProviderImplHelper >& rProvider, const ::rtl::OUString& rContentId ); ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rValues, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getPackage( const PackageUri& rURI ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getPackage(); static sal_Bool loadData( ContentProvider* pProvider, const PackageUri& rURI, ContentProperties& rProps, com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > & rxPackage ); static sal_Bool hasData( ContentProvider* pProvider, const PackageUri& rURI, com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > & rxPackage ); static ::rtl::OUString GetContentType( const ::rtl::OUString& aScheme, sal_Bool bFolder ); sal_Bool hasData( const PackageUri& rURI ); sal_Bool renameData( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& xOldId, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& xNewId ); sal_Bool storeData( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xStream ); sal_Bool removeData(); sal_Bool flushData(); typedef rtl::Reference< Content > ContentRef; typedef std::list< ContentRef > ContentRefList; void queryChildren( ContentRefList& rChildren ); sal_Bool exchangeIdentity( const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentIdentifier >& xNewId ); ::com::sun::star::uno::Any open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void insert( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xStream, sal_Int32 nNameClashResolve, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void destroy( sal_Bool bDeletePhysical, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > getInputStream(); sal_Bool isFolder() const { return m_aProps.bIsFolder; } public: // Create existing content. Fail, if not already exists. static Content* create( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ); // Create new content. Fail, if already exists. static Content* create( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const com::sun::star::ucb::ContentInfo& Info ); virtual ~Content(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); // XContent virtual rtl::OUString SAL_CALL getContentType() throw( com::sun::star::uno::RuntimeException ); // XCommandProcessor virtual com::sun::star::uno::Any SAL_CALL execute( const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( com::sun::star::uno::Exception, com::sun::star::ucb::CommandAbortedException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL abort( sal_Int32 CommandId ) throw( com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Additional interfaces ////////////////////////////////////////////////////////////////////// // XContentCreator virtual com::sun::star::uno::Sequence< com::sun::star::ucb::ContentInfo > SAL_CALL queryCreatableContentsInfo() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL createNewContent( const com::sun::star::ucb::ContentInfo& Info ) throw( com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Non-interface methods. ////////////////////////////////////////////////////////////////////// // Called from resultset data supplier. static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties, ContentProvider* pProvider, const ::rtl::OUString& rContentId ); // Called from resultset data supplier. ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > getIterator(); }; } #endif <commit_msg>INTEGRATION: CWS changefileheader (1.30.72); FILE MERGED 2008/04/01 16:02:22 thb 1.30.72.3: #i85898# Stripping all external header guards 2008/04/01 12:58:22 thb 1.30.72.2: #i85898# Stripping all external header guards 2008/03/31 15:30:26 rt 1.30.72.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pkgcontent.hxx,v $ * $Revision: 1.31 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _PKGCONTENT_HXX #define _PKGCONTENT_HXX #include <list> #include <rtl/ref.hxx> #ifndef _COM_SUN_STAR_UCB_INTERACTIVEBADTRANSFRERURLEXCEPTION_HPP_ #include <com/sun/star/ucb/InteractiveBadTransferURLException.hpp> #endif #include <com/sun/star/ucb/XContentCreator.hpp> #include <ucbhelper/contenthelper.hxx> #include "pkguri.hxx" namespace com { namespace sun { namespace star { namespace beans { struct Property; struct PropertyValue; } namespace container { class XHierarchicalNameAccess; class XEnumeration; } namespace io { class XInputStream; } namespace sdbc { class XRow; } namespace ucb { struct OpenCommandArgument2; struct TransferInfo; } } } } namespace package_ucp { //========================================================================= // UNO service name for the content. #define PACKAGE_FOLDER_CONTENT_SERVICE_NAME \ "com.sun.star.ucb.PackageFolderContent" #define PACKAGE_STREAM_CONTENT_SERVICE_NAME \ "com.sun.star.ucb.PackageStreamContent" //========================================================================= struct ContentProperties { ::rtl::OUString aTitle; // Title ::rtl::OUString aContentType; // ContentType sal_Bool bIsDocument; // IsDocument sal_Bool bIsFolder; // IsFolder ::rtl::OUString aMediaType; // MediaType com::sun::star::uno::Sequence < sal_Int8 > aEncryptionKey; // EncryptionKey sal_Int64 nSize; // Size sal_Bool bCompressed; // Compressed sal_Bool bEncrypted; // Encrypted sal_Bool bHasEncryptedEntries; // HasEncryptedEntries ContentProperties() : bIsDocument( sal_True ), bIsFolder( sal_False ), nSize( 0 ), bCompressed( sal_True ), bEncrypted( sal_False ), bHasEncryptedEntries( sal_False ) {} ContentProperties( const ::rtl::OUString& rContentType ); }; //========================================================================= class ContentProvider; class Content : public ::ucbhelper::ContentImplHelper, public com::sun::star::ucb::XContentCreator { enum ContentState { TRANSIENT, // created via CreateNewContent, // but did not process "insert" yet PERSISTENT, // processed "insert" DEAD // processed "delete" }; PackageUri m_aUri; ContentProperties m_aProps; ContentState m_eState; com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > m_xPackage; ContentProvider* m_pProvider; sal_uInt32 m_nModifiedProps; private: Content( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const ::com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess >& Package, const PackageUri& rUri, const ContentProperties& rProps ); Content( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess >& Package, const PackageUri& rUri, const com::sun::star::ucb::ContentInfo& Info ); virtual com::sun::star::uno::Sequence< com::sun::star::beans::Property > getProperties( const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > & xEnv ); virtual com::sun::star::uno::Sequence< com::sun::star::ucb::CommandInfo > getCommands( const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment > & xEnv ); virtual ::rtl::OUString getParentURL(); static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties, const ContentProperties& rData, const rtl::Reference< ::ucbhelper::ContentProviderImplHelper >& rProvider, const ::rtl::OUString& rContentId ); ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties ); ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > setPropertyValues( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rValues, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getPackage( const PackageUri& rURI ); com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > getPackage(); static sal_Bool loadData( ContentProvider* pProvider, const PackageUri& rURI, ContentProperties& rProps, com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > & rxPackage ); static sal_Bool hasData( ContentProvider* pProvider, const PackageUri& rURI, com::sun::star::uno::Reference< com::sun::star::container::XHierarchicalNameAccess > & rxPackage ); static ::rtl::OUString GetContentType( const ::rtl::OUString& aScheme, sal_Bool bFolder ); sal_Bool hasData( const PackageUri& rURI ); sal_Bool renameData( const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& xOldId, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& xNewId ); sal_Bool storeData( const com::sun::star::uno::Reference< com::sun::star::io::XInputStream >& xStream ); sal_Bool removeData(); sal_Bool flushData(); typedef rtl::Reference< Content > ContentRef; typedef std::list< ContentRef > ContentRefList; void queryChildren( ContentRefList& rChildren ); sal_Bool exchangeIdentity( const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XContentIdentifier >& xNewId ); ::com::sun::star::uno::Any open( const ::com::sun::star::ucb::OpenCommandArgument2& rArg, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void insert( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& xStream, sal_Int32 nNameClashResolve, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void destroy( sal_Bool bDeletePhysical, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); void transfer( const ::com::sun::star::ucb::TransferInfo& rInfo, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment > & xEnv ) throw( ::com::sun::star::uno::Exception ); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > getInputStream(); sal_Bool isFolder() const { return m_aProps.bIsFolder; } public: // Create existing content. Fail, if not already exists. static Content* create( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier ); // Create new content. Fail, if already exists. static Content* create( const com::sun::star::uno::Reference< com::sun::star::lang::XMultiServiceFactory >& rxSMgr, ContentProvider* pProvider, const com::sun::star::uno::Reference< com::sun::star::ucb::XContentIdentifier >& Identifier, const com::sun::star::ucb::ContentInfo& Info ); virtual ~Content(); // XInterface XINTERFACE_DECL() // XTypeProvider XTYPEPROVIDER_DECL() // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException ); // XContent virtual rtl::OUString SAL_CALL getContentType() throw( com::sun::star::uno::RuntimeException ); // XCommandProcessor virtual com::sun::star::uno::Any SAL_CALL execute( const com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const com::sun::star::uno::Reference< com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( com::sun::star::uno::Exception, com::sun::star::ucb::CommandAbortedException, com::sun::star::uno::RuntimeException ); virtual void SAL_CALL abort( sal_Int32 CommandId ) throw( com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Additional interfaces ////////////////////////////////////////////////////////////////////// // XContentCreator virtual com::sun::star::uno::Sequence< com::sun::star::ucb::ContentInfo > SAL_CALL queryCreatableContentsInfo() throw( com::sun::star::uno::RuntimeException ); virtual com::sun::star::uno::Reference< com::sun::star::ucb::XContent > SAL_CALL createNewContent( const com::sun::star::ucb::ContentInfo& Info ) throw( com::sun::star::uno::RuntimeException ); ////////////////////////////////////////////////////////////////////// // Non-interface methods. ////////////////////////////////////////////////////////////////////// // Called from resultset data supplier. static ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRow > getPropertyValues( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& rSMgr, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& rProperties, ContentProvider* pProvider, const ::rtl::OUString& rContentId ); // Called from resultset data supplier. ::com::sun::star::uno::Reference< ::com::sun::star::container::XEnumeration > getIterator(); }; } #endif <|endoftext|>
<commit_before>//===- llvm/unittest/VMCore/InstructionsTest.cpp - Instructions unit tests ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Instructions.h" #include "llvm/BasicBlock.h" #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "llvm/ADT/STLExtras.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(InstructionsTest, ReturnInst) { LLVMContext &C(getGlobalContext()); // test for PR6589 const ReturnInst* r0 = ReturnInst::Create(C); EXPECT_EQ(r0->getNumOperands(), 0U); EXPECT_EQ(r0->op_begin(), r0->op_end()); const IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); const ReturnInst* r1 = ReturnInst::Create(C, One); EXPECT_EQ(r1->getNumOperands(), 1U); User::const_op_iterator b(r1->op_begin()); EXPECT_NE(b, r1->op_end()); EXPECT_EQ(*b, One); EXPECT_EQ(r1->getOperand(0), One); ++b; EXPECT_EQ(b, r1->op_end()); // clean up delete r0; delete r1; } TEST(InstructionsTest, BranchInst) { LLVMContext &C(getGlobalContext()); // Make a BasicBlocks BasicBlock* bb0 = BasicBlock::Create(C); BasicBlock* bb1 = BasicBlock::Create(C); // Mandatory BranchInst const BranchInst* b0 = BranchInst::Create(bb0); EXPECT_TRUE(b0->isUnconditional()); EXPECT_FALSE(b0->isConditional()); EXPECT_EQ(b0->getNumSuccessors(), 1U); // check num operands EXPECT_EQ(b0->getNumOperands(), 1U); EXPECT_NE(b0->op_begin(), b0->op_end()); EXPECT_EQ(b0->op_begin() + 1, b0->op_end()); EXPECT_EQ(next(b0->op_begin()), b0->op_end()); const IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); // Conditional BranchInst BranchInst* b1 = BranchInst::Create(bb0, bb1, One); EXPECT_FALSE(b1->isUnconditional()); EXPECT_TRUE(b1->isConditional()); EXPECT_EQ(b1->getNumSuccessors(), 2U); // check num operands EXPECT_EQ(b1->getNumOperands(), 3U); User::const_op_iterator b(b1->op_begin()); // check COND EXPECT_NE(b, b1->op_end()); EXPECT_EQ(*b, One); EXPECT_EQ(b1->getOperand(0), One); EXPECT_EQ(b1->getCondition(), One); ++b; // check ELSE EXPECT_EQ(*b, bb1); EXPECT_EQ(b1->getOperand(1), bb1); EXPECT_EQ(b1->getSuccessor(1), bb1); ++b; // check THEN EXPECT_EQ(*b, bb0); EXPECT_EQ(b1->getOperand(2), bb0); EXPECT_EQ(b1->getSuccessor(0), bb0); ++b; EXPECT_EQ(b, b1->op_end()); // shrink it b1->setUnconditionalDest(bb1); // check num operands EXPECT_EQ(b1->getNumOperands(), 1U); User::const_op_iterator c(b1->op_begin()); EXPECT_NE(c, b1->op_end()); // check THEN EXPECT_EQ(*c, bb1); EXPECT_EQ(b1->getOperand(0), bb1); EXPECT_EQ(b1->getSuccessor(0), bb1); ++c; EXPECT_EQ(c, b1->op_end()); // clean up delete b0; delete b1; delete bb0; delete bb1; } } // end anonymous namespace } // end namespace llvm <commit_msg>another one<commit_after>//===- llvm/unittest/VMCore/InstructionsTest.cpp - Instructions unit tests ===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Instructions.h" #include "llvm/BasicBlock.h" #include "llvm/DerivedTypes.h" #include "llvm/LLVMContext.h" #include "llvm/ADT/STLExtras.h" #include "gtest/gtest.h" namespace llvm { namespace { TEST(InstructionsTest, ReturnInst) { LLVMContext &C(getGlobalContext()); // test for PR6589 const ReturnInst* r0 = ReturnInst::Create(C); EXPECT_EQ(r0->getNumOperands(), 0U); EXPECT_EQ(r0->op_begin(), r0->op_end()); const IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); const ReturnInst* r1 = ReturnInst::Create(C, One); EXPECT_EQ(r1->getNumOperands(), 1U); User::const_op_iterator b(r1->op_begin()); EXPECT_NE(b, r1->op_end()); EXPECT_EQ(*b, One); EXPECT_EQ(r1->getOperand(0), One); ++b; EXPECT_EQ(b, r1->op_end()); // clean up delete r0; delete r1; } TEST(InstructionsTest, BranchInst) { LLVMContext &C(getGlobalContext()); // Make a BasicBlocks BasicBlock* bb0 = BasicBlock::Create(C); BasicBlock* bb1 = BasicBlock::Create(C); // Mandatory BranchInst const BranchInst* b0 = BranchInst::Create(bb0); EXPECT_TRUE(b0->isUnconditional()); EXPECT_FALSE(b0->isConditional()); EXPECT_EQ(b0->getNumSuccessors(), 1U); // check num operands EXPECT_EQ(b0->getNumOperands(), 1U); EXPECT_NE(b0->op_begin(), b0->op_end()); EXPECT_EQ(next(b0->op_begin()), b0->op_end()); EXPECT_EQ(next(b0->op_begin()), b0->op_end()); const IntegerType* Int1 = IntegerType::get(C, 1); Constant* One = ConstantInt::get(Int1, 1, true); // Conditional BranchInst BranchInst* b1 = BranchInst::Create(bb0, bb1, One); EXPECT_FALSE(b1->isUnconditional()); EXPECT_TRUE(b1->isConditional()); EXPECT_EQ(b1->getNumSuccessors(), 2U); // check num operands EXPECT_EQ(b1->getNumOperands(), 3U); User::const_op_iterator b(b1->op_begin()); // check COND EXPECT_NE(b, b1->op_end()); EXPECT_EQ(*b, One); EXPECT_EQ(b1->getOperand(0), One); EXPECT_EQ(b1->getCondition(), One); ++b; // check ELSE EXPECT_EQ(*b, bb1); EXPECT_EQ(b1->getOperand(1), bb1); EXPECT_EQ(b1->getSuccessor(1), bb1); ++b; // check THEN EXPECT_EQ(*b, bb0); EXPECT_EQ(b1->getOperand(2), bb0); EXPECT_EQ(b1->getSuccessor(0), bb0); ++b; EXPECT_EQ(b, b1->op_end()); // shrink it b1->setUnconditionalDest(bb1); // check num operands EXPECT_EQ(b1->getNumOperands(), 1U); User::const_op_iterator c(b1->op_begin()); EXPECT_NE(c, b1->op_end()); // check THEN EXPECT_EQ(*c, bb1); EXPECT_EQ(b1->getOperand(0), bb1); EXPECT_EQ(b1->getSuccessor(0), bb1); ++c; EXPECT_EQ(c, b1->op_end()); // clean up delete b0; delete b1; delete bb0; delete bb1; } } // end anonymous namespace } // end namespace llvm <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "../Interface/Database.h" #include "../Interface/Server.h" #include "../Interface/DatabaseCursor.h" #include "../Interface/File.h" #include "database.h" #include "server_settings.h" #include "LMDBFileIndex.h" #include "../stringtools.h" #include "../urbackupcommon/os_functions.h" #include "serverinterface/helper.h" #include "dao/ServerBackupDao.h" namespace { const size_t sqlite_data_allocation_chunk_size = 50 * 1024 * 1024; //50MB struct SCallbackData { IDatabaseCursor* cur; int64 pos; int64 max_pos; SStartupStatus* status; }; db_results create_callback(size_t n_done, size_t n_rows, void *userdata) { SCallbackData *data=(SCallbackData*)userdata; data->status->processed_file_entries=n_done; int last_pc = static_cast<int>(data->status->pc_done*1000 + 0.5); if(data->max_pos>0) { data->status->pc_done = static_cast<double>(n_rows)/data->max_pos; } int curr_pc = static_cast<int>(data->status->pc_done*1000 + 0.5); if(curr_pc!=last_pc) { Server->Log("Creating files index: "+convert((double)curr_pc/10)+"% finished", LL_INFO); } db_results ret; db_single_result res; if(data->cur->next(res)) { ret.push_back(res); } return ret; } bool create_files_index_common(FileIndex& fileindex, SStartupStatus& status) { IDatabase* db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); IDatabase* db_files_new = NULL; if(db->getEngineName()=="sqlite") { Server->Log("Deleting database journal...", LL_INFO); db->Write("PRAGMA journal_mode = DELETE"); if (FileExists("urbackup/backup_server_files.db-journal") || FileExists("urbackup/backup_server_files.db-wal")) { Server->Log("Deleting database journal failed. Aborting.", LL_ERROR); return false; } Server->destroyAllDatabases(); Server->deleteFile("urbackup/backup_server_files_new.db"); Server->Log("Copying/reflinking database...", LL_INFO); if (!os_create_hardlink("urbackup/backup_server_files_new.db", "urbackup/backup_server_files.db", true, NULL)) { Server->Log("Reflinking failed. Falling back to copying...", LL_DEBUG); if (!copy_file("urbackup/backup_server_files.db", "urbackup/backup_server_files_new.db")) { Server->Log("Copying file failed. " + os_last_error_str(), LL_ERROR); return false; } } str_map params; if (!Server->openDatabase("urbackup/backup_server_files_new.db", URBACKUPDB_SERVER_FILES_NEW, params)) { Server->Log("Couldn't open Database backup_server_files_new.db. Exiting. Expecting database at \"" + Server->getServerWorkingDir() + os_file_sep() + "urbackup" + os_file_sep() + "backup_server_files_new.db\"", LL_ERROR); return false; } Server->setDatabaseAllocationChunkSize(URBACKUPDB_SERVER_FILES_NEW, sqlite_data_allocation_chunk_size); db_files_new = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES_NEW); if (db_files_new ==NULL) { Server->Log("Couldn't open backup server database. Exiting. Expecting database at \"" + Server->getServerWorkingDir() + os_file_sep() + "urbackup" + os_file_sep() + "backup_server_files_new.db\"", LL_ERROR); return false; } db_files_new->Write("PRAGMA journal_mode = OFF"); db_files_new->Write("PRAGMA synchronous = OFF"); db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); if (db == NULL) { Server->Log("Error opening database. -1", LL_ERROR); return false; } } status.creating_filesindex=true; Server->Log("Creating file entry index. This might take a while...", LL_WARNING); Server->Log("Getting number of files...", LL_INFO); db_results res = db->Read("SELECT COUNT(*) AS c FROM files"); int64 n_files = 0; if(!res.empty()) { n_files=watoi64(res[0]["c"]); } Server->Log("Dropping index...", LL_INFO); db_files_new->Write("DROP INDEX IF EXISTS files_backupid"); Server->Log("Starting creating files index...", LL_INFO); IQuery *q_read=db->Prepare("SELECT id, shahash, filesize, clientid, next_entry, prev_entry, pointed_to FROM files ORDER BY shahash ASC, filesize ASC, clientid ASC, created DESC"); SCallbackData data; data.cur=q_read->Cursor(); data.pos=0; data.max_pos=n_files; data.status=&status; { DBScopedWriteTransaction write_transaction(db_files_new); fileindex.create(create_callback, &data); } if(fileindex.has_error()) { return false; } else { if (data.cur->has_error()) { return false; } Server->Log("Creating backupid index...", LL_INFO); db_files_new->Write("CREATE INDEX files_backupid ON files (backupid)"); Server->Log("Syncing...", LL_INFO); Server->destroyAllDatabases(); std::auto_ptr<IFile> db_file(Server->openFile("urbackup/backup_server_files_new.db", MODE_RW)); if (db_file.get() == NULL) { Server->Log("Error opening new database file", LL_ERROR); return false; } db_file->Sync(); db_file.reset(); Server->Log("Renaming back result...", LL_INFO); if (!os_rename_file("urbackup/backup_server_files_new.db", "urbackup/backup_server_files.db")) { Server->Log("Renaming database file failed. " + os_last_error_str(), LL_ERROR); return false; } db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); if (db == NULL) { Server->Log("Error opening database after file index creation.", LL_ERROR); return false; } db->Write("PRAGMA journal_mode = WAL"); } status.creating_filesindex=false; return true; } bool setup_lmdb_file_index(SStartupStatus& status) { LMDBFileIndex fileindex(true);; if(fileindex.has_error()) { Server->Log("Error creating file index", LL_ERROR); return false; } return create_files_index_common(fileindex, status); } } void delete_file_index(void) { Server->deleteFile("urbackup/fileindex/backup_server_files_index.lmdb"); Server->deleteFile("urbackup/fileindex/backup_server_files_index.lmdb-lock"); } bool create_files_index(SStartupStatus& status) { IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); bool creating_index; { ServerBackupDao backupdao(db); creating_index = backupdao.getMiscValue("creating_file_entry_index").value == "true"; } if(!FileExists("urbackup/fileindex/backup_server_files_index.lmdb") || creating_index) { delete_file_index(); { DBScopedSynchronous synchronous_db(db); ServerBackupDao backupdao(db); backupdao.delMiscValue("creating_file_entry_index"); backupdao.addMiscValue("creating_file_entry_index", "true"); } status.upgrading_database=false; status.creating_filesindex=true; if(!setup_lmdb_file_index(status)) { Server->Log("Setting up file index failed", LL_ERROR); return false; } else { db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); ServerBackupDao backupdao(db); backupdao.delMiscValue("creating_file_entry_index"); } } LMDBFileIndex::initFileIndex(); return true; } FileIndex* create_lmdb_files_index(void) { if(!FileExists("urbackup/fileindex/backup_server_files_index.lmdb")) { return NULL; } return new LMDBFileIndex(); }<commit_msg>Clear all database connections before starting index creation<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011-2016 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "../Interface/Database.h" #include "../Interface/Server.h" #include "../Interface/DatabaseCursor.h" #include "../Interface/File.h" #include "database.h" #include "server_settings.h" #include "LMDBFileIndex.h" #include "../stringtools.h" #include "../urbackupcommon/os_functions.h" #include "serverinterface/helper.h" #include "dao/ServerBackupDao.h" namespace { const size_t sqlite_data_allocation_chunk_size = 50 * 1024 * 1024; //50MB struct SCallbackData { IDatabaseCursor* cur; int64 pos; int64 max_pos; SStartupStatus* status; }; db_results create_callback(size_t n_done, size_t n_rows, void *userdata) { SCallbackData *data=(SCallbackData*)userdata; data->status->processed_file_entries=n_done; int last_pc = static_cast<int>(data->status->pc_done*1000 + 0.5); if(data->max_pos>0) { data->status->pc_done = static_cast<double>(n_rows)/data->max_pos; } int curr_pc = static_cast<int>(data->status->pc_done*1000 + 0.5); if(curr_pc!=last_pc) { Server->Log("Creating files index: "+convert((double)curr_pc/10)+"% finished", LL_INFO); } db_results ret; db_single_result res; if(data->cur->next(res)) { ret.push_back(res); } return ret; } bool create_files_index_common(FileIndex& fileindex, SStartupStatus& status) { Server->destroyAllDatabases(); IDatabase* db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); IDatabase* db_files_new = NULL; if(db->getEngineName()=="sqlite") { Server->Log("Deleting database journal...", LL_INFO); db->Write("PRAGMA journal_mode = DELETE"); if (FileExists("urbackup/backup_server_files.db-journal") || FileExists("urbackup/backup_server_files.db-wal")) { Server->Log("Deleting database journal failed. Aborting.", LL_ERROR); return false; } Server->destroyAllDatabases(); Server->deleteFile("urbackup/backup_server_files_new.db"); Server->Log("Copying/reflinking database...", LL_INFO); if (!os_create_hardlink("urbackup/backup_server_files_new.db", "urbackup/backup_server_files.db", true, NULL)) { Server->Log("Reflinking failed. Falling back to copying...", LL_DEBUG); if (!copy_file("urbackup/backup_server_files.db", "urbackup/backup_server_files_new.db")) { Server->Log("Copying file failed. " + os_last_error_str(), LL_ERROR); return false; } } str_map params; if (!Server->openDatabase("urbackup/backup_server_files_new.db", URBACKUPDB_SERVER_FILES_NEW, params)) { Server->Log("Couldn't open Database backup_server_files_new.db. Exiting. Expecting database at \"" + Server->getServerWorkingDir() + os_file_sep() + "urbackup" + os_file_sep() + "backup_server_files_new.db\"", LL_ERROR); return false; } Server->setDatabaseAllocationChunkSize(URBACKUPDB_SERVER_FILES_NEW, sqlite_data_allocation_chunk_size); db_files_new = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES_NEW); if (db_files_new ==NULL) { Server->Log("Couldn't open backup server database. Exiting. Expecting database at \"" + Server->getServerWorkingDir() + os_file_sep() + "urbackup" + os_file_sep() + "backup_server_files_new.db\"", LL_ERROR); return false; } db_files_new->Write("PRAGMA journal_mode = OFF"); db_files_new->Write("PRAGMA synchronous = OFF"); db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); if (db == NULL) { Server->Log("Error opening database. -1", LL_ERROR); return false; } } status.creating_filesindex=true; Server->Log("Creating file entry index. This might take a while...", LL_WARNING); Server->Log("Getting number of files...", LL_INFO); db_results res = db->Read("SELECT COUNT(*) AS c FROM files"); int64 n_files = 0; if(!res.empty()) { n_files=watoi64(res[0]["c"]); } Server->Log("Dropping index...", LL_INFO); db_files_new->Write("DROP INDEX IF EXISTS files_backupid"); Server->Log("Starting creating files index...", LL_INFO); IQuery *q_read=db->Prepare("SELECT id, shahash, filesize, clientid, next_entry, prev_entry, pointed_to FROM files ORDER BY shahash ASC, filesize ASC, clientid ASC, created DESC"); SCallbackData data; data.cur=q_read->Cursor(); data.pos=0; data.max_pos=n_files; data.status=&status; { DBScopedWriteTransaction write_transaction(db_files_new); fileindex.create(create_callback, &data); } if(fileindex.has_error()) { return false; } else { if (data.cur->has_error()) { return false; } Server->Log("Creating backupid index...", LL_INFO); db_files_new->Write("CREATE INDEX files_backupid ON files (backupid)"); Server->Log("Syncing...", LL_INFO); Server->destroyAllDatabases(); std::auto_ptr<IFile> db_file(Server->openFile("urbackup/backup_server_files_new.db", MODE_RW)); if (db_file.get() == NULL) { Server->Log("Error opening new database file", LL_ERROR); return false; } db_file->Sync(); db_file.reset(); Server->Log("Renaming back result...", LL_INFO); if (!os_rename_file("urbackup/backup_server_files_new.db", "urbackup/backup_server_files.db")) { Server->Log("Renaming database file failed. " + os_last_error_str(), LL_ERROR); return false; } db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER_FILES); if (db == NULL) { Server->Log("Error opening database after file index creation.", LL_ERROR); return false; } db->Write("PRAGMA journal_mode = WAL"); } status.creating_filesindex=false; return true; } bool setup_lmdb_file_index(SStartupStatus& status) { LMDBFileIndex fileindex(true);; if(fileindex.has_error()) { Server->Log("Error creating file index", LL_ERROR); return false; } return create_files_index_common(fileindex, status); } } void delete_file_index(void) { Server->deleteFile("urbackup/fileindex/backup_server_files_index.lmdb"); Server->deleteFile("urbackup/fileindex/backup_server_files_index.lmdb-lock"); } bool create_files_index(SStartupStatus& status) { IDatabase *db=Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); bool creating_index; { ServerBackupDao backupdao(db); creating_index = backupdao.getMiscValue("creating_file_entry_index").value == "true"; } if(!FileExists("urbackup/fileindex/backup_server_files_index.lmdb") || creating_index) { delete_file_index(); { DBScopedSynchronous synchronous_db(db); ServerBackupDao backupdao(db); backupdao.delMiscValue("creating_file_entry_index"); backupdao.addMiscValue("creating_file_entry_index", "true"); } status.upgrading_database=false; status.creating_filesindex=true; if(!setup_lmdb_file_index(status)) { Server->Log("Setting up file index failed", LL_ERROR); return false; } else { db = Server->getDatabase(Server->getThreadID(), URBACKUPDB_SERVER); ServerBackupDao backupdao(db); backupdao.delMiscValue("creating_file_entry_index"); } } LMDBFileIndex::initFileIndex(); return true; } FileIndex* create_lmdb_files_index(void) { if(!FileExists("urbackup/fileindex/backup_server_files_index.lmdb")) { return NULL; } return new LMDBFileIndex(); }<|endoftext|>
<commit_before>// Copyright Paul Dardeau, SwampBits LLC 2014 // BSD License #include <cstdio> #include <cstdlib> #include "ThreadPoolQueue.h" #include "ThreadingFactory.h" #include "ConditionVariable.h" #include "MutexLock.h" #include "Logger.h" #include "BasicException.h" using namespace chaudiere; //****************************************************************************** ThreadPoolQueue::ThreadPoolQueue(ThreadingFactory* threadingFactory) : m_threadingFactory(threadingFactory), m_mutex(NULL), m_condQueueNotEmpty(NULL), m_isInitialized(false), m_isRunning(false) { Logger::logInstanceCreate("ThreadPoolQueue"); try { m_mutex = m_threadingFactory->createMutex("ThreadPoolQueue"); m_condQueueNotEmpty = m_threadingFactory->createConditionVariable("queue-not-empty"); if ((m_mutex != NULL) && (m_condQueueNotEmpty != NULL)) { m_isInitialized = true; m_isRunning = true; } else { Logger::error("unable to initialize ThreadPoolQueue"); if (NULL == m_mutex) { Logger::error("unable to create mutex"); } if (NULL == m_condQueueNotEmpty) { Logger::error("unable to create queue not empty condition variable"); } printf("error: unable to initialize thread pool queue, aborting\n"); exit(1); } } catch (const BasicException& be) { Logger::error("exception setting up thread pool queue: " + be.whatString()); } catch (const std::exception& e) { Logger::error("exception setting up thread pool queue: " + std::string(e.what())); } catch (...) { Logger::error("unknown exception setting up thread pool queue"); } } //****************************************************************************** ThreadPoolQueue::~ThreadPoolQueue() { Logger::logInstanceDestroy("ThreadPoolQueue"); m_isRunning = false; if (NULL != m_mutex) { delete m_mutex; } if (NULL != m_condQueueNotEmpty) { delete m_condQueueNotEmpty; } } //****************************************************************************** bool ThreadPoolQueue::addRequest(Runnable* runnableRequest) { if (!m_isInitialized) { Logger::log(Warning, "ThreadPoolQueue::addRequest queue not initialized"); return false; } if (!runnableRequest) { Logger::log(Warning, "ThreadPoolQueue::addRequest rejecting NULL request"); return false; } MutexLock lock(*m_mutex, "ThreadPoolQueue::addRequest"); if (!m_isRunning) { Logger::log(Warning, "ThreadPoolQueue::addRequest rejecting request, queue is shutting down"); return false; } //if (!m_mutex->haveValidMutex()) { // Logger::error("don't have valid mutex in addRequest"); // ::exit(1); //} Logger::log(Debug, "ThreadPoolQueue::addRequest accepting request"); const bool wasEmpty = m_queue.empty(); // add new request to the queue m_queue.push_back(runnableRequest); // did we just transition from QUEUE_EMPTY to QUEUE_NOT_EMPTY? if (wasEmpty) { // signal QUEUE_NOT_EMPTY (wake up a worker thread) Logger::log(Debug, "signalling queue_not_empty"); m_condQueueNotEmpty->notifyAll(); } return true; } //****************************************************************************** Runnable* ThreadPoolQueue::takeRequest() { if (!m_isInitialized) { Logger::log(Warning, "ThreadPoolQueue::takeRequest queue not initialized"); return NULL; } MutexLock lock(*m_mutex, "ThreadPoolQueue::takeRequest"); // is the queue shut down? if (!m_isRunning) { return NULL; } //if (!m_mutex->haveValidMutex()) { // Logger::error("don't have valid mutex in takeRequest"); // exit(1); //} Runnable* request = NULL; // is the queue empty? while (m_queue.empty()) { // && m_isRunning) { // empty queue -- wait for QUEUE_NOT_EMPTY event m_condQueueNotEmpty->wait(m_mutex); } if (!m_queue.empty()) { // take a request from the queue request = m_queue.front(); m_queue.pop_front(); } return request; } //****************************************************************************** bool ThreadPoolQueue::startUp() { bool wasStarted = true; printf("ThreadPoolQueue::startUp\n"); if (m_isInitialized && !m_isRunning) { MutexLock lock(*m_mutex, "ThreadPoolQueue::startUp"); m_isRunning = true; wasStarted = true; } return wasStarted; } //****************************************************************************** bool ThreadPoolQueue::shutDown() { bool wasShutDown = false; printf("ThreadPoolQueue::shutDown\n"); if (m_isInitialized && m_isRunning) { MutexLock lock(*m_mutex, "ThreadPoolQueue::shutDown"); m_isRunning = false; wasShutDown = true; } return wasShutDown; } //****************************************************************************** bool ThreadPoolQueue::isRunning() const { return m_isRunning; } //****************************************************************************** bool ThreadPoolQueue::isEmpty() const { return m_queue.empty(); } //****************************************************************************** bool ThreadPoolQueue::isInitialized() const { return m_isInitialized; } //****************************************************************************** <commit_msg>fix return type of startUp<commit_after>// Copyright Paul Dardeau, SwampBits LLC 2014 // BSD License #include <cstdio> #include <cstdlib> #include "ThreadPoolQueue.h" #include "ThreadingFactory.h" #include "ConditionVariable.h" #include "MutexLock.h" #include "Logger.h" #include "BasicException.h" using namespace chaudiere; //****************************************************************************** ThreadPoolQueue::ThreadPoolQueue(ThreadingFactory* threadingFactory) : m_threadingFactory(threadingFactory), m_mutex(NULL), m_condQueueNotEmpty(NULL), m_isInitialized(false), m_isRunning(false) { Logger::logInstanceCreate("ThreadPoolQueue"); try { m_mutex = m_threadingFactory->createMutex("ThreadPoolQueue"); m_condQueueNotEmpty = m_threadingFactory->createConditionVariable("queue-not-empty"); if ((m_mutex != NULL) && (m_condQueueNotEmpty != NULL)) { m_isInitialized = true; m_isRunning = true; } else { Logger::error("unable to initialize ThreadPoolQueue"); if (NULL == m_mutex) { Logger::error("unable to create mutex"); } if (NULL == m_condQueueNotEmpty) { Logger::error("unable to create queue not empty condition variable"); } printf("error: unable to initialize thread pool queue, aborting\n"); exit(1); } } catch (const BasicException& be) { Logger::error("exception setting up thread pool queue: " + be.whatString()); } catch (const std::exception& e) { Logger::error("exception setting up thread pool queue: " + std::string(e.what())); } catch (...) { Logger::error("unknown exception setting up thread pool queue"); } } //****************************************************************************** ThreadPoolQueue::~ThreadPoolQueue() { Logger::logInstanceDestroy("ThreadPoolQueue"); m_isRunning = false; if (NULL != m_mutex) { delete m_mutex; } if (NULL != m_condQueueNotEmpty) { delete m_condQueueNotEmpty; } } //****************************************************************************** bool ThreadPoolQueue::addRequest(Runnable* runnableRequest) { if (!m_isInitialized) { Logger::log(Warning, "ThreadPoolQueue::addRequest queue not initialized"); return false; } if (!runnableRequest) { Logger::log(Warning, "ThreadPoolQueue::addRequest rejecting NULL request"); return false; } MutexLock lock(*m_mutex, "ThreadPoolQueue::addRequest"); if (!m_isRunning) { Logger::log(Warning, "ThreadPoolQueue::addRequest rejecting request, queue is shutting down"); return false; } //if (!m_mutex->haveValidMutex()) { // Logger::error("don't have valid mutex in addRequest"); // ::exit(1); //} Logger::log(Debug, "ThreadPoolQueue::addRequest accepting request"); const bool wasEmpty = m_queue.empty(); // add new request to the queue m_queue.push_back(runnableRequest); // did we just transition from QUEUE_EMPTY to QUEUE_NOT_EMPTY? if (wasEmpty) { // signal QUEUE_NOT_EMPTY (wake up a worker thread) Logger::log(Debug, "signalling queue_not_empty"); m_condQueueNotEmpty->notifyAll(); } return true; } //****************************************************************************** Runnable* ThreadPoolQueue::takeRequest() { if (!m_isInitialized) { Logger::log(Warning, "ThreadPoolQueue::takeRequest queue not initialized"); return NULL; } MutexLock lock(*m_mutex, "ThreadPoolQueue::takeRequest"); // is the queue shut down? if (!m_isRunning) { return NULL; } //if (!m_mutex->haveValidMutex()) { // Logger::error("don't have valid mutex in takeRequest"); // exit(1); //} Runnable* request = NULL; // is the queue empty? while (m_queue.empty()) { // && m_isRunning) { // empty queue -- wait for QUEUE_NOT_EMPTY event m_condQueueNotEmpty->wait(m_mutex); } if (!m_queue.empty()) { // take a request from the queue request = m_queue.front(); m_queue.pop_front(); } return request; } //****************************************************************************** bool ThreadPoolQueue::startUp() { bool wasStarted = false; printf("ThreadPoolQueue::startUp\n"); if (m_isInitialized && !m_isRunning) { MutexLock lock(*m_mutex, "ThreadPoolQueue::startUp"); m_isRunning = true; wasStarted = true; } return wasStarted; } //****************************************************************************** bool ThreadPoolQueue::shutDown() { bool wasShutDown = false; printf("ThreadPoolQueue::shutDown\n"); if (m_isInitialized && m_isRunning) { MutexLock lock(*m_mutex, "ThreadPoolQueue::shutDown"); m_isRunning = false; wasShutDown = true; } return wasShutDown; } //****************************************************************************** bool ThreadPoolQueue::isRunning() const { return m_isRunning; } //****************************************************************************** bool ThreadPoolQueue::isEmpty() const { return m_queue.empty(); } //****************************************************************************** bool ThreadPoolQueue::isInitialized() const { return m_isInitialized; } //****************************************************************************** <|endoftext|>
<commit_before>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for wxExGetWord using namespace std; const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { wxString keywords; for ( set<wxString>::const_iterator it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->Upper().StartsWith(word.Upper())) { return true; } } return false; } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <commit_msg>fixed comment<commit_after>/******************************************************************************\ * File: lexer.cpp * Purpose: Implementation of lexer classes * Author: Anton van Wezenbeek * RCS-ID: $Id$ * * Copyright (c) 1998-2009 Anton van Wezenbeek * All rights are reserved. Reproduction in whole or part is prohibited * without the written consent of the copyright owner. \******************************************************************************/ #include <wx/stc/stc.h> // for wxSTC_KEYWORDSET_MAX #include <wx/tokenzr.h> #include <wx/extension/lexer.h> #include <wx/extension/util.h> // for wxExAlignText using namespace std; const wxString wxExLexer::GetFormattedText( const wxString& lines, const wxString& header, bool fill_out_with_space, bool fill_out) const { wxString text = lines, header_to_use = header; size_t nCharIndex; wxString out; // Process text between the carriage return line feeds. while ((nCharIndex = text.find("\n")) != wxString::npos) { out << wxExAlignText( text.substr(0, nCharIndex), header_to_use, fill_out_with_space, fill_out, *this); text = text.substr(nCharIndex + 1); header_to_use = wxString(' ', header.size()); } if (!text.empty()) { out << wxExAlignText( text, header_to_use, fill_out_with_space, fill_out, *this); } return out; } const wxString wxExLexer::GetKeywordsString(int keyword_set) const { if (keyword_set == -1) { return GetKeywordsStringSet(m_Keywords); } else { std::map< int, std::set<wxString> >::const_iterator it = m_KeywordsSet.find(keyword_set); if (it != m_KeywordsSet.end()) { return GetKeywordsStringSet(it->second); } } return wxEmptyString; } const wxString wxExLexer::GetKeywordsStringSet( const std::set<wxString>& kset) const { wxString keywords; for ( set<wxString>::const_iterator it = kset.begin(); it != kset.end(); ++it) { keywords += *it + " "; } return keywords.Trim(); // remove the ending space } bool wxExLexer::IsKeyword(const wxString& word) const { set<wxString>::const_iterator it = m_Keywords.find(word); return (it != m_Keywords.end()); } bool wxExLexer::KeywordStartsWith(const wxString& word) const { for ( set<wxString>::const_iterator it = m_Keywords.begin(); it != m_Keywords.end(); ++it) { if (it->Upper().StartsWith(word.Upper())) { return true; } } return false; } const wxString wxExLexer::MakeComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, wxEmptyString, fill_out_with_space, fill_out): out << wxExAlignText(text, wxEmptyString, fill_out_with_space, fill_out, *this); return out; } const wxString wxExLexer::MakeComment( const wxString& prefix, const wxString& text) const { wxString out; text.find("\n") != wxString::npos ? out << GetFormattedText(text, prefix, true, true): out << wxExAlignText(text, prefix, true, true, *this); return out; } const wxString wxExLexer::MakeSingleLineComment( const wxString& text, bool fill_out_with_space, bool fill_out) const { if (m_CommentBegin.empty() && m_CommentEnd.empty()) { return text; } // First set the fill_out_character. wxChar fill_out_character; if (fill_out_with_space || m_ScintillaLexer == "hypertext") { fill_out_character = ' '; } else { if (text.empty()) { if (m_CommentBegin == m_CommentEnd) fill_out_character = '-'; else fill_out_character = m_CommentBegin[m_CommentBegin.size() - 1]; } else fill_out_character = ' '; } wxString out = m_CommentBegin + fill_out_character + text; // Fill out characters. if (fill_out) { // To prevent filling out spaces if (fill_out_character != ' ' || !m_CommentEnd.empty()) { const int fill_chars = UsableCharactersPerLine() - text.size(); if (fill_chars > 0) { const wxString fill_out(fill_out_character, fill_chars); out += fill_out; } } } if (!m_CommentEnd.empty()) out += fill_out_character + m_CommentEnd; return out; } bool wxExLexer::SetKeywords(const wxString& value) { if (!m_Keywords.empty()) { m_Keywords.clear(); } if (!m_KeywordsSet.empty()) { m_KeywordsSet.clear(); } set<wxString> keywords_set; wxStringTokenizer tkz(value, "\r\n "); int setno = 0; while (tkz.HasMoreTokens()) { const wxString line = tkz.GetNextToken(); wxStringTokenizer fields(line, ":"); wxString keyword; if (fields.CountTokens() > 1) { keyword = fields.GetNextToken(); const int new_setno = atoi(fields.GetNextToken().c_str()); if (new_setno >= wxSTC_KEYWORDSET_MAX) { return false; } if (new_setno != setno) { if (!keywords_set.empty()) { m_KeywordsSet.insert(make_pair(setno, keywords_set)); keywords_set.clear(); } setno = new_setno; } keywords_set.insert(keyword); } else { keyword = line; keywords_set.insert(line); } m_Keywords.insert(keyword); } m_KeywordsSet.insert(make_pair(setno, keywords_set)); return true; } int wxExLexer::UsableCharactersPerLine() const { // We always use lines with 80 characters. We adjust this here for // the space the beginning and end of the comment characters occupy. return 80 - ((m_CommentBegin.size() != 0) ? m_CommentBegin.size() + 1 : 0) - ((m_CommentEnd.size() != 0) ? m_CommentEnd.size() + 1 : 0); } <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::text::str_base namespace abc { namespace io { namespace text { str_base::str_base(abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/) : base(lterm), m_ichOffset(0) { } /*virtual*/ str_base::~str_base() { } /*virtual*/ abc::text::encoding str_base::encoding() const { return abc::text::encoding::host; } /*virtual*/ abc::text::line_terminator str_base::line_terminator() const { ABC_TRACE_FN((this)); return m_lterm; } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::text::str_reader namespace abc { namespace io { namespace text { str_reader::str_reader( istr const & s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(s) { } str_reader::str_reader( istr && s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(std::move(s)) { } str_reader::str_reader( mstr && s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(std::move(s)) { } /*virtual*/ bool str_reader::read_while(mstr * ps, std::function< char_t const * (char_t const * pchBegin, char_t const * pchLastReadBegin, char_t const * pchEnd) > fnGetConsumeEnd) { ABC_TRACE_FN((this, ps/*, fnGetConsumeEnd*/)); ABC_UNUSED_ARG(fnGetConsumeEnd); // TODO: implement this. return false; } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::str_writer namespace abc { namespace io { namespace text { str_writer::str_writer( mstr * psBuf /*= nullptr*/, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), writer(lterm), m_psWriteBuf(psBuf ? psBuf : &m_sDefaultWriteBuf) { } void str_writer::clear() { ABC_TRACE_FN((this)); m_psWriteBuf->set_size(0); m_ichOffset = 0; } dmstr str_writer::release_content() { ABC_TRACE_FN((this)); m_ichOffset = 0; return std::move(*m_psWriteBuf); } /*virtual*/ void str_writer::write_binary(void const * p, size_t cb, abc::text::encoding enc) { ABC_TRACE_FN((this, p, cb, enc)); if (!cb) { // Nothing to do. return; } ABC_ASSERT(enc != abc::text::encoding::unknown, SL("cannot write data with unknown encoding")); if (enc == abc::text::encoding::host) { // Optimal case: no transcoding necessary. size_t cch(cb / sizeof(char_t)); // Enlarge the string as necessary, then overwrite any character in the affected range. m_psWriteBuf->set_capacity(m_ichOffset + cch, true); memory::copy(m_psWriteBuf->begin().base() + m_ichOffset, static_cast<char_t const *>(p), cch); m_ichOffset += cch; } else { do { // Calculate the additional size required, ceiling it to sizeof(char_t). size_t cchDstEst((abc::text::estimate_transcoded_size( enc, p, cb, abc::text::encoding::host ) + sizeof(char_t) - 1) / sizeof(char_t)); m_psWriteBuf->set_capacity(m_ichOffset + cchDstEst, true); // Get the resulting buffer and its actual size. void * pBuf(m_psWriteBuf->begin().base() + m_ichOffset); size_t cbBuf(sizeof(char_t) * (m_psWriteBuf->capacity() - m_ichOffset)); // Fill as much of the buffer as possible, and advance m_ichOffset accordingly. m_ichOffset += abc::text::transcode( std::nothrow, enc, &p, &cb, abc::text::encoding::host, &pBuf, &cbBuf ); } while (cb); } // Truncate the string. m_psWriteBuf->set_size(m_ichOffset); } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <commit_msg>Fix incorrect mix of byte count and char_t count<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*- Copyright 2010, 2011, 2012, 2013, 2014 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #include <abc.hxx> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::text::str_base namespace abc { namespace io { namespace text { str_base::str_base(abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/) : base(lterm), m_ichOffset(0) { } /*virtual*/ str_base::~str_base() { } /*virtual*/ abc::text::encoding str_base::encoding() const { return abc::text::encoding::host; } /*virtual*/ abc::text::line_terminator str_base::line_terminator() const { ABC_TRACE_FN((this)); return m_lterm; } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::text::str_reader namespace abc { namespace io { namespace text { str_reader::str_reader( istr const & s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(s) { } str_reader::str_reader( istr && s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(std::move(s)) { } str_reader::str_reader( mstr && s, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), reader(lterm), m_psReadBuf(&m_sReadBuf), m_sReadBuf(std::move(s)) { } /*virtual*/ bool str_reader::read_while(mstr * ps, std::function< char_t const * (char_t const * pchBegin, char_t const * pchLastReadBegin, char_t const * pchEnd) > fnGetConsumeEnd) { ABC_TRACE_FN((this, ps/*, fnGetConsumeEnd*/)); ABC_UNUSED_ARG(fnGetConsumeEnd); // TODO: implement this. return false; } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::io::str_writer namespace abc { namespace io { namespace text { str_writer::str_writer( mstr * psBuf /*= nullptr*/, abc::text::line_terminator lterm /*= abc::text::line_terminator::host*/ ) : base(lterm), str_base(lterm), writer(lterm), m_psWriteBuf(psBuf ? psBuf : &m_sDefaultWriteBuf) { } void str_writer::clear() { ABC_TRACE_FN((this)); m_psWriteBuf->set_size(0); m_ichOffset = 0; } dmstr str_writer::release_content() { ABC_TRACE_FN((this)); m_ichOffset = 0; return std::move(*m_psWriteBuf); } /*virtual*/ void str_writer::write_binary(void const * p, size_t cb, abc::text::encoding enc) { ABC_TRACE_FN((this, p, cb, enc)); if (!cb) { // Nothing to do. return; } ABC_ASSERT(enc != abc::text::encoding::unknown, SL("cannot write data with unknown encoding")); if (enc == abc::text::encoding::host) { // Optimal case: no transcoding necessary. size_t cch(cb / sizeof(char_t)); // Enlarge the string as necessary, then overwrite any character in the affected range. m_psWriteBuf->set_capacity(m_ichOffset + cch, true); memory::copy(m_psWriteBuf->begin().base() + m_ichOffset, static_cast<char_t const *>(p), cch); m_ichOffset += cch; } else { do { // Calculate the additional size required, ceiling it to sizeof(char_t). size_t cchDstEst((abc::text::estimate_transcoded_size( enc, p, cb, abc::text::encoding::host ) + sizeof(char_t) - 1) / sizeof(char_t)); m_psWriteBuf->set_capacity(m_ichOffset + cchDstEst, true); // Get the resulting buffer and its actual size. void * pBuf(m_psWriteBuf->begin().base() + m_ichOffset); size_t cbBuf(sizeof(char_t) * (m_psWriteBuf->capacity() - m_ichOffset)); // Fill as much of the buffer as possible, and advance m_ichOffset accordingly. m_ichOffset += abc::text::transcode( std::nothrow, enc, &p, &cb, abc::text::encoding::host, &pBuf, &cbBuf ) / sizeof(char_t); } while (cb); } // Truncate the string. m_psWriteBuf->set_size(m_ichOffset); } } //namespace text } //namespace io } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Log$ Revision 1.24 2002/10/21 09:20:51 alibrary Introduce Riostream.h and remove unused variables Revision 1.23 2002/10/14 14:55:35 hristov Merging the VirtualMC branch to the main development branch (HEAD) Revision 1.20.4.1 2002/06/10 14:57:41 hristov Merged with v3-08-02 Revision 1.22 2002/05/15 11:59:49 morsch CdEventFile() method added. Revision 1.21 2002/04/26 10:39:31 morsch AliGenExtFile derives from AliGenMC. Generate() uses methods from AliGenMC (N. Carrer) Revision 1.20 2002/03/22 09:43:28 morsch Don't delete the TParticle. Revision 1.19 2002/02/08 16:50:50 morsch Add name and title in constructor. Revision 1.18 2001/11/12 14:31:00 morsch Memory leaks fixed. (M. Bondila) Revision 1.17 2001/11/09 09:12:58 morsch Generalization by using AliGenReader object to read particles from file. Revision 1.16 2001/07/27 17:09:35 morsch Use local SetTrack, KeepTrack and SetHighWaterMark methods to delegate either to local stack or to stack owned by AliRun. (Piotr Skowronski, A.M.) Revision 1.15 2001/01/23 13:29:37 morsch Add method SetParticleCode and enum type Code_t to handle both PDG (new ntuples) and GEANT3 codes (old ntuples) in input file. Revision 1.14 2000/12/21 16:24:06 morsch Coding convention clean-up Revision 1.13 2000/11/30 07:12:50 alibrary Introducing new Rndm and QA classes Revision 1.12 2000/10/27 13:54:45 morsch Remove explicite reference to input file from constuctor. Revision 1.11 2000/10/02 21:28:06 fca Removal of useless dependecies via forward declarations Revision 1.10 2000/07/11 18:24:55 fca Coding convention corrections + few minor bug fixes Revision 1.9 2000/06/14 15:20:09 morsch Include clean-up (IH) Revision 1.8 2000/06/09 20:36:44 morsch All coding rule violations except RS3 corrected Revision 1.7 2000/02/16 14:56:27 morsch Convert geant particle code into pdg code before putting particle on the stack. Revision 1.6 1999/11/09 07:38:48 fca Changes for compatibility with version 2.23 of ROOT Revision 1.5 1999/09/29 09:24:12 fca Introduction of the Copyright and cvs Log */ // Event generator that using an instance of type AliGenReader // reads particles from a file and applies cuts. #include <Riostream.h> #include "AliGenExtFile.h" #include "AliRun.h" #include <TParticle.h> #include <TFile.h> #include <TTree.h> ClassImp(AliGenExtFile) AliGenExtFile::AliGenExtFile() :AliGenMC() { // Constructor // // Read all particles fNpart =- 1; fReader = 0; } AliGenExtFile::AliGenExtFile(Int_t npart) :AliGenMC(npart) { // Constructor fName = "ExtFile"; fTitle = "Primaries from ext. File"; fReader = 0; } AliGenExtFile::AliGenExtFile(const AliGenExtFile & ExtFile) { // copy constructor } //____________________________________________________________ AliGenExtFile::~AliGenExtFile() { // Destructor delete fReader; } //___________________________________________________________ void AliGenExtFile::Init() { // Initialize if (fReader) fReader->Init(); } void AliGenExtFile::Generate() { // Generate particles Float_t polar[3] = {0,0,0}; // Float_t origin[3] = {0,0,0}; Float_t p[3]; Float_t random[6]; Int_t i, j, nt; // for (j=0;j<3;j++) origin[j]=fOrigin[j]; if(fVertexSmear == kPerTrack) { Rndm(random,6); for (j = 0; j < 3; j++) { origin[j] += fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())* TMath::Sqrt(-2*TMath::Log(random[2*j+1])); } } while(1) { Int_t nTracks = fReader->NextEvent(); if (nTracks == 0) { // printf("\n No more events !!! !\n"); Warning("AliGenExtFile::Generate","\nNo more events in external file!!!\nLast event may be empty or incomplete.\n"); return; } // // Particle selection loop // // The selction criterium for the external file generator is as follows: // // 1) All tracs are subjects to the cuts defined by AliGenerator, i.e. // fThetaMin, fThetaMax, fPhiMin, fPhiMax, fPMin, fPMax, fPtMin, fPtMax, // fYMin, fYMax. // If the particle does not satisfy these cuts, it is not put on the // stack. // 2) If fCutOnChild and some specific child is selected (e.g. if // fForceDecay==kSemiElectronic) the event is rejected if NOT EVEN ONE // child falls into the child-cuts. if(fCutOnChild) { // Count the selected children Int_t nSelected = 0; for (i = 0; i < nTracks; i++) { TParticle* iparticle = fReader->NextParticle(); Int_t kf = CheckPDGCode(iparticle->GetPdgCode()); kf = TMath::Abs(kf); if (ChildSelected(kf) && KinematicSelection(iparticle, 1)) { nSelected++; } } if (!nSelected) continue; // No particle selected: Go to next event fReader->RewindEvent(); } // // Stack filling loop // for (i = 0; i < nTracks; i++) { TParticle* iparticle = fReader->NextParticle(); if (!KinematicSelection(iparticle,0)) { Double_t pz = iparticle->Pz(); Double_t e = iparticle->Energy(); Double_t y; if ((e-pz) == 0) { y = 20.; } else if ((e+pz) == 0.) { y = -20.; } else { y = 0.5*TMath::Log((e+pz)/(e-pz)); } printf("\n Not selected %d %f %f %f %f %f", i, iparticle->Theta(), iparticle->Phi(), iparticle->P(), iparticle->Pt(), y); //PH delete iparticle; continue; } p[0] = iparticle->Px(); p[1] = iparticle->Py(); p[2] = iparticle->Pz(); Int_t idpart = iparticle->GetPdgCode(); if(fVertexSmear==kPerTrack) { Rndm(random,6); for (j = 0; j < 3; j++) { origin[j]=fOrigin[j] +fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())* TMath::Sqrt(-2*TMath::Log(random[2*j+1])); } } Int_t decayed = iparticle->GetFirstDaughter(); Int_t doTracking = fTrackIt && (decayed < 0) && (TMath::Abs(idpart) > 10); // printf("*** pdg, first daughter, trk = %d, %d, %d\n", // idpart,decayed, doTracking); SetTrack(doTracking,-1,idpart,p,origin,polar,0,kPPrimary,nt); KeepTrack(nt); } // track loop break; } // event loop SetHighWaterMark(nt); CdEventFile(); } void AliGenExtFile::CdEventFile() { // CD back to the event file TFile *pFile=0; if (!gAlice) { gAlice = (AliRun*)pFile->Get("gAlice"); if (gAlice) printf("AliRun object found on file\n"); if (!gAlice) gAlice = new AliRun("gAlice","Alice test program"); } TTree *fAli=gAlice->TreeK(); if (fAli) pFile =fAli->GetCurrentFile(); pFile->cd(); } AliGenExtFile& AliGenExtFile::operator=(const AliGenExtFile& rhs) { // Assignment operator return *this; } <commit_msg>Keeping the information about the particle's parent. Additional comments, Log replaced by Id<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ // Event generator that using an instance of type AliGenReader // reads particles from a file and applies cuts. // Example: In your Config.C you can include the following lines // AliGenExtFile *gener = new AliGenExtFile(-1); // gener->SetMomentumRange(0,999); // gener->SetPhiRange(-180.,180.); // gener->SetThetaRange(0,180); // gener->SetYRange(-999,999); // AliGenReaderTreeK * reader = new AliGenReaderTreeK(); // reader->SetFileName("myFileWithTreeK.root"); // gener->SetReader(reader); // gener->Init(); #include <Riostream.h> #include "AliGenExtFile.h" #include "AliRun.h" #include <TParticle.h> #include <TFile.h> #include <TTree.h> ClassImp(AliGenExtFile) AliGenExtFile::AliGenExtFile() :AliGenMC() { // Constructor // // Read all particles fNpart =- 1; fReader = 0; } AliGenExtFile::AliGenExtFile(Int_t npart) :AliGenMC(npart) { // Constructor fName = "ExtFile"; fTitle = "Primaries from ext. File"; fReader = 0; } AliGenExtFile::AliGenExtFile(const AliGenExtFile & ExtFile) { // copy constructor } //____________________________________________________________ AliGenExtFile::~AliGenExtFile() { // Destructor delete fReader; } //___________________________________________________________ void AliGenExtFile::Init() { // Initialize if (fReader) fReader->Init(); } void AliGenExtFile::Generate() { // Generate particles Float_t polar[3] = {0,0,0}; // Float_t origin[3] = {0,0,0}; Float_t p[3]; Float_t random[6]; Int_t i, j, nt; // for (j=0;j<3;j++) origin[j]=fOrigin[j]; if(fVertexSmear == kPerTrack) { Rndm(random,6); for (j = 0; j < 3; j++) { origin[j] += fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())* TMath::Sqrt(-2*TMath::Log(random[2*j+1])); } } while(1) { Int_t nTracks = fReader->NextEvent(); if (nTracks == 0) { // printf("\n No more events !!! !\n"); Warning("AliGenExtFile::Generate","\nNo more events in external file!!!\nLast event may be empty or incomplete.\n"); return; } // // Particle selection loop // // The selction criterium for the external file generator is as follows: // // 1) All tracs are subjects to the cuts defined by AliGenerator, i.e. // fThetaMin, fThetaMax, fPhiMin, fPhiMax, fPMin, fPMax, fPtMin, fPtMax, // fYMin, fYMax. // If the particle does not satisfy these cuts, it is not put on the // stack. // 2) If fCutOnChild and some specific child is selected (e.g. if // fForceDecay==kSemiElectronic) the event is rejected if NOT EVEN ONE // child falls into the child-cuts. if(fCutOnChild) { // Count the selected children Int_t nSelected = 0; for (i = 0; i < nTracks; i++) { TParticle* iparticle = fReader->NextParticle(); Int_t kf = CheckPDGCode(iparticle->GetPdgCode()); kf = TMath::Abs(kf); if (ChildSelected(kf) && KinematicSelection(iparticle, 1)) { nSelected++; } } if (!nSelected) continue; // No particle selected: Go to next event fReader->RewindEvent(); } // // Stack filling loop // for (i = 0; i < nTracks; i++) { TParticle* iparticle = fReader->NextParticle(); if (!KinematicSelection(iparticle,0)) { Double_t pz = iparticle->Pz(); Double_t e = iparticle->Energy(); Double_t y; if ((e-pz) == 0) { y = 20.; } else if ((e+pz) == 0.) { y = -20.; } else { y = 0.5*TMath::Log((e+pz)/(e-pz)); } printf("\n Not selected %d %f %f %f %f %f", i, iparticle->Theta(), iparticle->Phi(), iparticle->P(), iparticle->Pt(), y); //PH delete iparticle; continue; } p[0] = iparticle->Px(); p[1] = iparticle->Py(); p[2] = iparticle->Pz(); Int_t idpart = iparticle->GetPdgCode(); if(fVertexSmear==kPerTrack) { Rndm(random,6); for (j = 0; j < 3; j++) { origin[j]=fOrigin[j] +fOsigma[j]*TMath::Cos(2*random[2*j]*TMath::Pi())* TMath::Sqrt(-2*TMath::Log(random[2*j+1])); } } Int_t decayed = iparticle->GetFirstDaughter(); Int_t doTracking = fTrackIt && (decayed < 0) && (TMath::Abs(idpart) > 10); // printf("*** pdg, first daughter, trk = %d, %d, %d\n", // idpart,decayed, doTracking); //PH SetTrack(doTracking,-1,idpart,p,origin,polar,0,kPPrimary,nt); Int_t parent = iparticle->GetFirstMother(); SetTrack(doTracking,parent,idpart,p,origin,polar,0,kPPrimary,nt); KeepTrack(nt); } // track loop break; } // event loop SetHighWaterMark(nt); CdEventFile(); } void AliGenExtFile::CdEventFile() { // CD back to the event file TFile *pFile=0; if (!gAlice) { gAlice = (AliRun*)pFile->Get("gAlice"); if (gAlice) printf("AliRun object found on file\n"); if (!gAlice) gAlice = new AliRun("gAlice","Alice test program"); } TTree *fAli=gAlice->TreeK(); if (fAli) pFile =fAli->GetCurrentFile(); pFile->cd(); } AliGenExtFile& AliGenExtFile::operator=(const AliGenExtFile& rhs) { // Assignment operator return *this; } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked for this. TEST_F(VoEAudioProcessingTest, DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <commit_msg>Trivial fix for memcheck error.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { base_->Terminate(); audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked for this. TEST_F(VoEAudioProcessingTest, DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { base_->Terminate(); audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked for this. TEST_F(VoEAudioProcessingTest, DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <commit_msg>Disable test causing race conditions.<commit_after>/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "voice_engine/include/voe_audio_processing.h" #include "gtest/gtest.h" #include "voice_engine/include/voe_base.h" namespace webrtc { namespace voe { namespace { class VoEAudioProcessingTest : public ::testing::Test { protected: VoEAudioProcessingTest() : voe_(VoiceEngine::Create()), base_(VoEBase::GetInterface(voe_)), audioproc_(VoEAudioProcessing::GetInterface(voe_)) { } virtual ~VoEAudioProcessingTest() { base_->Terminate(); audioproc_->Release(); base_->Release(); VoiceEngine::Delete(voe_); } VoiceEngine* voe_; VoEBase* base_; VoEAudioProcessing* audioproc_; }; TEST_F(VoEAudioProcessingTest, FailureIfNotInitialized) { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } // TODO(andrew): Investigate race conditions triggered by this test: // https://code.google.com/p/webrtc/issues/detail?id=788 TEST_F(VoEAudioProcessingTest, DISABLED_DriftCompensationIsEnabledIfSupported) { ASSERT_EQ(0, base_->Init()); // TODO(andrew): Ideally, DriftCompensationSupported() would be mocked. bool supported = VoEAudioProcessing::DriftCompensationSupported(); if (supported) { EXPECT_EQ(0, audioproc_->EnableDriftCompensation(true)); EXPECT_TRUE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(0, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } else { EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(true)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); EXPECT_EQ(-1, audioproc_->EnableDriftCompensation(false)); EXPECT_FALSE(audioproc_->DriftCompensationEnabled()); } } } // namespace } // namespace voe } // namespace webrtc <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Korey Sewell * Jaidev Patwardhan */ #ifndef __MIPS_FAULTS_HH__ #define __MIPS_FAULTS_HH__ #include "sim/faults.hh" namespace MipsISA { typedef const Addr FaultVect; class MipsFaultBase : public FaultBase { protected: virtual bool skipFaultingInstruction() {return false;} virtual bool setRestartAddress() {return true;} public: struct FaultVals { const FaultName name; const FaultVect vect; FaultStat count; }; Addr badVAddr; Addr entryHiAsid; Addr entryHiVPN2; Addr entryHiVPN2X; Addr contextBadVPN2; #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = StaticInst::nullStaticInstPtr) {} void setExceptionState(ThreadContext *, uint8_t); void setHandlerPC(Addr, ThreadContext *); #endif }; template <typename T> class MipsFault : public MipsFaultBase { protected: static FaultVals vals; public: FaultName name() const { return vals.name; } FaultVect vect() const { return vals.vect; } FaultStat & countStat() { return vals.count; } }; class MachineCheckFault : public MipsFault<MachineCheckFault> { public: bool isMachineCheckFault() {return true;} }; static inline Fault genMachineCheckFault() { return new MachineCheckFault; } class NonMaskableInterrupt : public MipsFault<NonMaskableInterrupt> { public: bool isNonMaskableInterrupt() {return true;} }; class AddressErrorFault : public MipsFault<AddressErrorFault> { protected: Addr vaddr; bool store; public: AddressErrorFault(Addr _vaddr, bool _store) : vaddr(_vaddr), store(_store) {} #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ResetFault : public MipsFault<ResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class SystemCallFault : public MipsFault<SystemCallFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class SoftResetFault : public MipsFault<SoftResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class CoprocessorUnusableFault : public MipsFault<CoprocessorUnusableFault> { protected: int coProcID; public: CoprocessorUnusableFault(int _procid) : coProcID(_procid) {} void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ReservedInstructionFault : public MipsFault<ReservedInstructionFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ThreadFault : public MipsFault<ThreadFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class IntegerOverflowFault : public MipsFault<IntegerOverflowFault> { protected: bool skipFaultingInstruction() {return true;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class InterruptFault : public MipsFault<InterruptFault> { protected: bool setRestartAddress() {return false;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TrapFault : public MipsFault<TrapFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class BreakpointFault : public MipsFault<BreakpointFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbRefillFault : public MipsFault<ItbRefillFault> { public: ItbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbRefillFault : public MipsFault<DtbRefillFault> { public: DtbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbInvalidFault : public MipsFault<ItbInvalidFault> { public: ItbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TLBModifiedFault : public MipsFault<TLBModifiedFault> { public: TLBModifiedFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbInvalidFault : public MipsFault<DtbInvalidFault> { public: DtbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = nullStaticInstPtr); #endif }; class DspStateDisabledFault : public MipsFault<DspStateDisabledFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; } // namespace MipsISA #endif // __MIPS_FAULTS_HH__ <commit_msg>MIPS: Get rid of the unused "count" field in FaultVals.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * Copyright (c) 2007 MIPS Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black * Korey Sewell * Jaidev Patwardhan */ #ifndef __MIPS_FAULTS_HH__ #define __MIPS_FAULTS_HH__ #include "sim/faults.hh" namespace MipsISA { typedef const Addr FaultVect; class MipsFaultBase : public FaultBase { protected: virtual bool skipFaultingInstruction() {return false;} virtual bool setRestartAddress() {return true;} public: struct FaultVals { const FaultName name; const FaultVect vect; }; Addr badVAddr; Addr entryHiAsid; Addr entryHiVPN2; Addr entryHiVPN2X; Addr contextBadVPN2; #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = StaticInst::nullStaticInstPtr) {} void setExceptionState(ThreadContext *, uint8_t); void setHandlerPC(Addr, ThreadContext *); #endif }; template <typename T> class MipsFault : public MipsFaultBase { protected: static FaultVals vals; public: FaultName name() const { return vals.name; } FaultVect vect() const { return vals.vect; } }; class MachineCheckFault : public MipsFault<MachineCheckFault> { public: bool isMachineCheckFault() {return true;} }; static inline Fault genMachineCheckFault() { return new MachineCheckFault; } class NonMaskableInterrupt : public MipsFault<NonMaskableInterrupt> { public: bool isNonMaskableInterrupt() {return true;} }; class AddressErrorFault : public MipsFault<AddressErrorFault> { protected: Addr vaddr; bool store; public: AddressErrorFault(Addr _vaddr, bool _store) : vaddr(_vaddr), store(_store) {} #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ResetFault : public MipsFault<ResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class SystemCallFault : public MipsFault<SystemCallFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class SoftResetFault : public MipsFault<SoftResetFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class CoprocessorUnusableFault : public MipsFault<CoprocessorUnusableFault> { protected: int coProcID; public: CoprocessorUnusableFault(int _procid) : coProcID(_procid) {} void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ReservedInstructionFault : public MipsFault<ReservedInstructionFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class ThreadFault : public MipsFault<ThreadFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; class IntegerOverflowFault : public MipsFault<IntegerOverflowFault> { protected: bool skipFaultingInstruction() {return true;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class InterruptFault : public MipsFault<InterruptFault> { protected: bool setRestartAddress() {return false;} public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TrapFault : public MipsFault<TrapFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class BreakpointFault : public MipsFault<BreakpointFault> { public: #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbRefillFault : public MipsFault<ItbRefillFault> { public: ItbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbRefillFault : public MipsFault<DtbRefillFault> { public: DtbRefillFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class ItbInvalidFault : public MipsFault<ItbInvalidFault> { public: ItbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class TLBModifiedFault : public MipsFault<TLBModifiedFault> { public: TLBModifiedFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); #endif }; class DtbInvalidFault : public MipsFault<DtbInvalidFault> { public: DtbInvalidFault(Addr asid, Addr vaddr, Addr vpn) { entryHiAsid = asid; entryHiVPN2 = vpn >> 2; entryHiVPN2X = vpn & 0x3; badVAddr = vaddr; contextBadVPN2 = vpn >> 2; } #if FULL_SYSTEM void invoke(ThreadContext * tc, StaticInst::StaticInstPtr inst = nullStaticInstPtr); #endif }; class DspStateDisabledFault : public MipsFault<DspStateDisabledFault> { public: void invoke(ThreadContext * tc, StaticInstPtr inst = StaticInst::nullStaticInstPtr); }; } // namespace MipsISA #endif // __MIPS_FAULTS_HH__ <|endoftext|>
<commit_before>/* ---------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2019, David McDougall * The following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * ---------------------------------------------------------------------- */ #include <bindings/suppress_register.hpp> //include before pybind11.h #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <nupic/ntypes/Sdr.hpp> #include <nupic/utils/StringUtils.hpp> // trim namespace py = pybind11; using namespace nupic; namespace nupic_ext { void init_SDR(py::module& m) { py::class_<SDR> py_SDR(m, "SDR", R"(Sparse Distributed Representation This class manages the specification and momentary value of a Sparse Distributed Representation (SDR). An SDR is a group of boolean values which represent the state of a group of neurons or their associated processes. SDR's have three commonly used data formats which are: * dense * sparse * flatSparse The SDR class has three magic properties, one for each of these data formats. These properties are the primary way of accessing the SDR's data. When these properties are read from, the data is automatically converted to the requested format and is cached so getting a value in one format many times incurs no extra performance cost. Assigning to the SDR via any one of these properties clears the cached values and causes them to be recomputed as needed. Example usage: # Make an SDR with 9 values, arranged in a (3 x 3) grid. X = SDR(dimensions = (3, 3)) # These three statements are equivalent. X.dense = [0, 1, 0, 0, 1, 0, 0, 0, 1] X.sparse = [[0, 1, 2], [1, 1, 2]] X.flatSparse = [ 1, 4, 8 ] # Access data in any format, SDR will automatically convert data formats, # even if it was not the format used by the most recent assignment to the # SDR. X.dense -> [[ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ]] X.sparse -> [[ 0, 1, 2 ], [1, 1, 2 ]] x.flatSparse -> [ 1, 4, 8 ] # Data format conversions are cached, and when an SDR value changes the # cache is cleared. X.flatSparse = [1, 2, 3] # Assign new data to the SDR, clearing the cache. X.dense # This line will convert formats. X.dense # This line will resuse the result of the previous line Assigning a value to the SDR requires copying the data from Python into C++. To avoid this copy operation: modify sdr.dense inplace, and call method sdr.setDenseInplace() when done to notify the SDR that it's data has changed. Example Usage: X = SDR((1000, 1000)) data = X.dense data[ 0, 4] = 1 data[444, 444] = 1 X.setDenseInplace() X.flatSparse -> [ 4, 444444 ] )"); py_SDR.def( py::init<vector<UInt>>(), R"(Create an SDR object. Initially SDRs value is all zeros. Argument dimensions is a list of dimension sizes, defining the shape of the SDR. The product of the dimensions must be greater than zero.)", py::arg("dimensions") ); py_SDR.def( py::init<SDR>(), R"(Initialize this SDR as a deep copy of the given SDR. This SDR and the given SDR will have no shared data and they can be modified without affecting each other.)", py::arg("sdr") ); py_SDR.def_property_readonly("dimensions", [](const SDR &self) { return self.dimensions; }, "A list of dimensions of the SDR."); py_SDR.def_property_readonly("size", [](const SDR &self) { return self.size; }, "The total number of boolean values in the SDR."); py_SDR.def("zero", &SDR::zero, R"(Set all of the values in the SDR to false. This method overwrites the SDRs current value.)"); py_SDR.def_property("dense", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); vector<UInt> strides( self.dimensions.size(), 0u ); uint z = sizeof(Byte); for(int i = self.dimensions.size() - 1; i >= 0; --i) { strides[i] = z; z *= self.dimensions[i]; } return py::array(self.dimensions, strides, self.getDense().data(), capsule); }, [](SDR &self, SDR_dense_t data) { self.setDense( data ); }, R"(A numpy array of boolean values, representing all of the bits in the SDR. This format allows random-access queries of the SDRs values. After modifying the dense array you MUST call sdr.setDenseInplace() in order to notify the SDR that its dense array has changed and its cached data is out of date.)"); py_SDR.def("setDenseInplace", [](SDR &self) { self.setDense( self.getDense() ); }, R"(Notify the SDR that its dense formatted data has been changed, and that it needs to update the other data formats.)"); py_SDR.def_property("flatSparse", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); return py::array(self.getSum(), self.getFlatSparse().data(), capsule); }, [](SDR &self, SDR_flatSparse_t data) { self.setFlatSparse( data ); }, R"(A numpy array containing the indices of only the true values in the SDR. These are indices into the flattened SDR. This format allows for quickly accessing all of the true bits in the SDR.)"); py_SDR.def_property("sparse", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); auto outer = py::list(); auto sparse = self.getSparse().data(); for(auto dim = 0u; dim < self.dimensions.size(); dim++) { auto vec = py::array(sparse[dim].size(), sparse[dim].data(), capsule); outer.append(vec); } return outer; }, [](SDR &self, SDR_sparse_t data) { self.setSparse( data ); }, R"(List of numpy arrays, containing the indices of only the true values in the SDR. This is a list of lists: the outter list contains an entry for each dimension in the SDR. The inner lists contain the coordinates of each true bit. The inner lists run in parallel. This format is useful because it contains the location of each true bit inside of the SDR's dimensional space.)"); py_SDR.def("setSDR", &SDR::setSDR, R"(Deep Copy the given SDR to this SDR. This overwrites the current value of this SDR. This SDR and the given SDR will have no shared data and they can be modified without affecting each other.)"); py_SDR.def("getSum", &SDR::getSum, "Calculates the number of true values in the SDR."); py_SDR.def("getSparsity", &SDR::getSparsity, R"(Calculates the sparsity of the SDR, which is the fraction of bits which are true out of the total number of bits in the SDR. I.E. sparsity = sdr.getSum() / sdr.size)"); py_SDR.def("getOverlap", &SDR::getOverlap, "Calculates the number of true bits which both SDRs have in common."); py_SDR.def("randomize", [](SDR &self, Real sparsity, UInt seed){ Random rng( seed ); self.randomize( sparsity, rng ); }, R"(Make a random SDR, overwriting the current value of the SDR. The result has uniformly random activations. Argument sparsity is the fraction of bits to set to true. After calling this method sdr.getSparsity() will return this sparsity, rounded to the nearest fraction of self.size. Optional argument seed is used for the random number generator. Seed 0 is special, it is replaced with the system time The default seed is 0.)", py::arg("sparsity"), py::arg("seed") = 0u); py_SDR.def("addNoise", [](SDR &self, Real fractionNoise, UInt seed = 0){ Random rng( seed ); self.addNoise( fractionNoise, rng ); }, R"(Modify the SDR by moving a fraction of the active bits to different locations. This method does not change the sparsity of the SDR, it moves the locations of the true values. The resulting SDR has a controlled amount of overlap with the original. Argument fractionNoise is the fraction of active bits to swap out. The original and resulting SDRs have the following relationship: originalSDR.getOverlap( newSDR ) / sparsity == 1 - fractionNoise Optional argument seed is used for the random number generator. Seed 0 is special, it is replaced with the system time. The default seed is 0.)", py::arg("fractionNoise"), py::arg("seed") = 0u); py_SDR.def("__str__", [](SDR &self){ stringstream buf; buf << self; return StringUtils::trim( buf.str() ); }); py_SDR.def("__eq__", [](SDR &self, SDR &other){ return self == other; }); py_SDR.def("__ne__", [](SDR &self, SDR &other){ return self != other; }); py_SDR.def(py::pickle( [](const SDR& self) { std::stringstream ss; self.save(ss); return py::bytes(ss.str()); }, [](py::bytes& s) { std::istringstream ss(s); SDR self; self.load(ss); return self; })); } } <commit_msg>SDR_Proxy python bindings: implemented, needs docs & unit-tests.<commit_after>/* ---------------------------------------------------------------------- * Numenta Platform for Intelligent Computing (NuPIC) * Copyright (C) 2019, David McDougall * The following terms and conditions apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero Public License version 3 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Affero Public License for more details. * * You should have received a copy of the GNU Affero Public License * along with this program. If not, see http://www.gnu.org/licenses. * * http://numenta.org/licenses/ * ---------------------------------------------------------------------- */ #include <bindings/suppress_register.hpp> //include before pybind11.h #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <nupic/ntypes/Sdr.hpp> #include <nupic/ntypes/SdrProxy.hpp> #include <nupic/utils/StringUtils.hpp> // trim namespace py = pybind11; using namespace nupic; namespace nupic_ext { void init_SDR(py::module& m) { py::class_<SDR> py_SDR(m, "SDR", R"(Sparse Distributed Representation This class manages the specification and momentary value of a Sparse Distributed Representation (SDR). An SDR is a group of boolean values which represent the state of a group of neurons or their associated processes. SDR's have three commonly used data formats which are: * dense * sparse * flatSparse The SDR class has three magic properties, one for each of these data formats. These properties are the primary way of accessing the SDR's data. When these properties are read from, the data is automatically converted to the requested format and is cached so getting a value in one format many times incurs no extra performance cost. Assigning to the SDR via any one of these properties clears the cached values and causes them to be recomputed as needed. Example usage: # Make an SDR with 9 values, arranged in a (3 x 3) grid. X = SDR(dimensions = (3, 3)) # These three statements are equivalent. X.dense = [0, 1, 0, 0, 1, 0, 0, 0, 1] X.sparse = [[0, 1, 2], [1, 1, 2]] X.flatSparse = [ 1, 4, 8 ] # Access data in any format, SDR will automatically convert data formats, # even if it was not the format used by the most recent assignment to the # SDR. X.dense -> [[ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ]] X.sparse -> [[ 0, 1, 2 ], [1, 1, 2 ]] x.flatSparse -> [ 1, 4, 8 ] # Data format conversions are cached, and when an SDR value changes the # cache is cleared. X.flatSparse = [1, 2, 3] # Assign new data to the SDR, clearing the cache. X.dense # This line will convert formats. X.dense # This line will resuse the result of the previous line Assigning a value to the SDR requires copying the data from Python into C++. To avoid this copy operation: modify sdr.dense inplace, and call method sdr.setDenseInplace() when done to notify the SDR that it's data has changed. Example Usage: X = SDR((1000, 1000)) data = X.dense data[ 0, 4] = 1 data[444, 444] = 1 X.setDenseInplace() X.flatSparse -> [ 4, 444444 ] )"); py_SDR.def( py::init<vector<UInt>>(), R"(Create an SDR object. Initially SDRs value is all zeros. Argument dimensions is a list of dimension sizes, defining the shape of the SDR. The product of the dimensions must be greater than zero.)", py::arg("dimensions") ); py_SDR.def( py::init<SDR>(), R"(Initialize this SDR as a deep copy of the given SDR. This SDR and the given SDR will have no shared data and they can be modified without affecting each other.)", py::arg("sdr") ); py_SDR.def_property_readonly("dimensions", [](const SDR &self) { return self.dimensions; }, "A list of dimensions of the SDR."); py_SDR.def_property_readonly("size", [](const SDR &self) { return self.size; }, "The total number of boolean values in the SDR."); py_SDR.def("zero", &SDR::zero, R"(Set all of the values in the SDR to false. This method overwrites the SDRs current value.)"); py_SDR.def_property("dense", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); vector<UInt> strides( self.dimensions.size(), 0u ); uint z = sizeof(Byte); for(int i = self.dimensions.size() - 1; i >= 0; --i) { strides[i] = z; z *= self.dimensions[i]; } return py::array(self.dimensions, strides, self.getDense().data(), capsule); }, [](SDR &self, SDR_dense_t data) { self.setDense( data ); }, R"(A numpy array of boolean values, representing all of the bits in the SDR. This format allows random-access queries of the SDRs values. After modifying the dense array you MUST call sdr.setDenseInplace() in order to notify the SDR that its dense array has changed and its cached data is out of date.)"); py_SDR.def("setDenseInplace", [](SDR &self) { self.setDense( self.getDense() ); }, R"(Notify the SDR that its dense formatted data has been changed, and that it needs to update the other data formats.)"); py_SDR.def_property("flatSparse", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); return py::array(self.getSum(), self.getFlatSparse().data(), capsule); }, [](SDR &self, SDR_flatSparse_t data) { self.setFlatSparse( data ); }, R"(A numpy array containing the indices of only the true values in the SDR. These are indices into the flattened SDR. This format allows for quickly accessing all of the true bits in the SDR.)"); py_SDR.def_property("sparse", [](SDR &self) { auto capsule = py::capsule(&self, [](void *self) {}); auto outer = py::list(); auto sparse = self.getSparse().data(); for(auto dim = 0u; dim < self.dimensions.size(); dim++) { auto vec = py::array(sparse[dim].size(), sparse[dim].data(), capsule); outer.append(vec); } return outer; }, [](SDR &self, SDR_sparse_t data) { self.setSparse( data ); }, R"(List of numpy arrays, containing the indices of only the true values in the SDR. This is a list of lists: the outter list contains an entry for each dimension in the SDR. The inner lists contain the coordinates of each true bit. The inner lists run in parallel. This format is useful because it contains the location of each true bit inside of the SDR's dimensional space.)"); py_SDR.def("setSDR", &SDR::setSDR, R"(Deep Copy the given SDR to this SDR. This overwrites the current value of this SDR. This SDR and the given SDR will have no shared data and they can be modified without affecting each other.)"); py_SDR.def("getSum", &SDR::getSum, "Calculates the number of true values in the SDR."); py_SDR.def("getSparsity", &SDR::getSparsity, R"(Calculates the sparsity of the SDR, which is the fraction of bits which are true out of the total number of bits in the SDR. I.E. sparsity = sdr.getSum() / sdr.size)"); py_SDR.def("getOverlap", &SDR::getOverlap, "Calculates the number of true bits which both SDRs have in common."); py_SDR.def("randomize", [](SDR &self, Real sparsity, UInt seed){ Random rng( seed ); self.randomize( sparsity, rng ); }, R"(Make a random SDR, overwriting the current value of the SDR. The result has uniformly random activations. Argument sparsity is the fraction of bits to set to true. After calling this method sdr.getSparsity() will return this sparsity, rounded to the nearest fraction of self.size. Optional argument seed is used for the random number generator. Seed 0 is special, it is replaced with the system time The default seed is 0.)", py::arg("sparsity"), py::arg("seed") = 0u); py_SDR.def("addNoise", [](SDR &self, Real fractionNoise, UInt seed = 0){ Random rng( seed ); self.addNoise( fractionNoise, rng ); }, R"(Modify the SDR by moving a fraction of the active bits to different locations. This method does not change the sparsity of the SDR, it moves the locations of the true values. The resulting SDR has a controlled amount of overlap with the original. Argument fractionNoise is the fraction of active bits to swap out. The original and resulting SDRs have the following relationship: originalSDR.getOverlap( newSDR ) / sparsity == 1 - fractionNoise Optional argument seed is used for the random number generator. Seed 0 is special, it is replaced with the system time. The default seed is 0.)", py::arg("fractionNoise"), py::arg("seed") = 0u); py_SDR.def("__str__", [](SDR &self){ stringstream buf; buf << self; return StringUtils::trim( buf.str() ); }); py_SDR.def("__eq__", [](SDR &self, SDR &other){ return self == other; }); py_SDR.def("__ne__", [](SDR &self, SDR &other){ return self != other; }); py_SDR.def(py::pickle( [](const SDR& self) { std::stringstream ss; self.save(ss); return py::bytes(ss.str()); }, [](const py::bytes& s) { std::istringstream ss(s); SDR self; self.load(ss); return self; })); py::class_<SDR_Proxy, SDR> py_Proxy(m, "SDR_Proxy"); py_Proxy.def( py::init<SDR&>() ); py_Proxy.def( py::init<SDR&, vector<UInt>>() ); } } <|endoftext|>
<commit_before>// simple server #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifdef __cplusplus #define __STDC_FORMAT_MACROS #endif #include "sgp_server.h" #include <fcntl.h> #include <getopt.h> #include <limits.h> #include <unistd.h> #include "sgp_protocol.h" // for SGPProtocol, etc #ifndef GEP_LITE #include "sgp.pb.h" // for Command1, etc #else #include "sgp_lite.pb.h" // for Command1, etc #endif class MyServer: public SGPServer { public: MyServer(int port) : SGPServer(16, port) { cnt1_ = 0; cnt2_ = 0; cnt3_ = 0; cnt4_ = 0; seen_client_ = false; } virtual ~MyServer() {}; // protocol callbacks bool Recv(const Command1 &msg, int id) override; bool Recv(const Command2 &msg, int id) override; bool Recv(const Command3 &msg, int id) override; bool Recv(const Command4 &msg, int id) override; int cnt1_; int cnt2_; int cnt3_; int cnt4_; bool seen_client_; }; bool MyServer::Recv(const Command1 &msg, int id) { cnt1_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command2 &msg, int id) { cnt2_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command3 &msg, int id) { cnt3_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command4 &msg, int id) { cnt4_++; seen_client_ = true; return true; } typedef struct arg_values { char *fifo; int cnt1; int cnt2; int cnt3; int cnt4; int nrem; char** rem; } arg_values; // default values #define DEFAULT_CNT1 1 #define DEFAULT_CNT2 2 #define DEFAULT_CNT3 3 #define DEFAULT_CNT4 4 void usage(char *name) { fprintf(stderr, "usage: %s [options]\n", name); fprintf(stderr, "where options are:\n"); fprintf(stderr, "\t--fifo <fifo>:\tUse <fifo> for client-server " "communications\n"); fprintf(stderr, "\t--cnt1 <cnt>:\tSend <cnt> Command1 messages [%i]\n", DEFAULT_CNT1); fprintf(stderr, "\t--cnt2 <cnt>:\tSend <cnt> Command2 messages [%i]\n", DEFAULT_CNT2); fprintf(stderr, "\t--cnt3 <cnt>:\tSend <cnt> Command3 messages [%i]\n", DEFAULT_CNT3); fprintf(stderr, "\t--cnt4 <cnt>:\tSend <cnt> Command4 messages [%i]\n", DEFAULT_CNT4); fprintf(stderr, "\t-h:\t\tHelp\n"); } // For long options that have no equivalent short option, use a // non-character as a pseudo short option, starting with CHAR_MAX + 1. enum { CNT1OPTION = CHAR_MAX + 1, CNT2OPTION, CNT3OPTION, CNT4OPTION, }; arg_values *parse_args(int argc, char** argv) { int c; // getopt_long stores the option index here int optindex = 0; static arg_values values; // set default values values.cnt1 = DEFAULT_CNT1; values.cnt2 = DEFAULT_CNT2; values.cnt3 = DEFAULT_CNT3; values.cnt4 = DEFAULT_CNT4; // long options static struct option longopts[] = { // matching options to short options {"help", no_argument, NULL, 'h'}, {"fifo", required_argument, NULL, 'f'}, // options without a short option match {"cnt1", required_argument, NULL, CNT1OPTION}, {"cnt2", required_argument, NULL, CNT2OPTION}, {"cnt3", required_argument, NULL, CNT3OPTION}, {"cnt4", required_argument, NULL, CNT4OPTION}, {NULL, 0, NULL, 0} }; char *endptr; while ((c = getopt_long(argc, argv, "", longopts, &optindex)) != -1) { switch (c) { case 'f': values.fifo = optarg; break; case CNT1OPTION: values.cnt1 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT2OPTION: values.cnt2 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT3OPTION: values.cnt3 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT4OPTION: values.cnt4 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case '?': case 'h': // getopt_long already printed an error message usage(argv[0]); exit(0); break; default: printf("Unsupported option: %c\n", c); usage(argv[0]); } } // store remaining arguments values.nrem = argc - optind; values.rem = argv + optind; return &values; } #define MAX_BUF 1024 int main(int argc, char **argv) { arg_values *values; // parse args values = parse_args(argc, argv); // create the server std::unique_ptr<MyServer> my_server; my_server.reset(new MyServer(0)); // start the server if (my_server->Start() < 0) { fprintf(stderr, "error: cannot start server\n"); return -1; } // get the port number int port = my_server->GetProto()->GetPort(); fprintf(stdout, "server listing in port %i\n", port); // tell the client about the port char wbuf[MAX_BUF]; sprintf(wbuf, "%i", port); int fd = open(values->fifo, O_WRONLY); write(fd, wbuf, strlen(wbuf)); close(fd); // wait until we see a client message while (!my_server->seen_client_) std::this_thread::yield(); // send some messages Command1 cmd1; for (int i = 0; i < values->cnt1; ++i) my_server->Send(cmd1); Command2 cmd2; for (int i = 0; i < values->cnt2; ++i) my_server->Send(cmd2); Command3 cmd3; for (int i = 0; i < values->cnt3; ++i) my_server->Send(cmd3); Command4 cmd4; for (int i = 0; i < values->cnt4; ++i) my_server->Send(cmd4); // give some time for all both sides to finish usleep(3000000); printf("results: %i %i %i %i\n", my_server->cnt1_, my_server->cnt2_, my_server->cnt3_, my_server->cnt4_); my_server->Stop(); return 0; } <commit_msg>libgep/test: minor typo<commit_after>// simple server #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifdef __cplusplus #define __STDC_FORMAT_MACROS #endif #include "sgp_server.h" #include <fcntl.h> #include <getopt.h> #include <limits.h> #include <unistd.h> #include "sgp_protocol.h" // for SGPProtocol, etc #ifndef GEP_LITE #include "sgp.pb.h" // for Command1, etc #else #include "sgp_lite.pb.h" // for Command1, etc #endif class MyServer: public SGPServer { public: MyServer(int port) : SGPServer(16, port) { cnt1_ = 0; cnt2_ = 0; cnt3_ = 0; cnt4_ = 0; seen_client_ = false; } virtual ~MyServer() {}; // protocol callbacks bool Recv(const Command1 &msg, int id) override; bool Recv(const Command2 &msg, int id) override; bool Recv(const Command3 &msg, int id) override; bool Recv(const Command4 &msg, int id) override; int cnt1_; int cnt2_; int cnt3_; int cnt4_; bool seen_client_; }; bool MyServer::Recv(const Command1 &msg, int id) { cnt1_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command2 &msg, int id) { cnt2_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command3 &msg, int id) { cnt3_++; seen_client_ = true; return true; } bool MyServer::Recv(const Command4 &msg, int id) { cnt4_++; seen_client_ = true; return true; } typedef struct arg_values { char *fifo; int cnt1; int cnt2; int cnt3; int cnt4; int nrem; char** rem; } arg_values; // default values #define DEFAULT_CNT1 1 #define DEFAULT_CNT2 2 #define DEFAULT_CNT3 3 #define DEFAULT_CNT4 4 void usage(char *name) { fprintf(stderr, "usage: %s [options]\n", name); fprintf(stderr, "where options are:\n"); fprintf(stderr, "\t--fifo <fifo>:\tUse <fifo> for client-server " "communications\n"); fprintf(stderr, "\t--cnt1 <cnt>:\tSend <cnt> Command1 messages [%i]\n", DEFAULT_CNT1); fprintf(stderr, "\t--cnt2 <cnt>:\tSend <cnt> Command2 messages [%i]\n", DEFAULT_CNT2); fprintf(stderr, "\t--cnt3 <cnt>:\tSend <cnt> Command3 messages [%i]\n", DEFAULT_CNT3); fprintf(stderr, "\t--cnt4 <cnt>:\tSend <cnt> Command4 messages [%i]\n", DEFAULT_CNT4); fprintf(stderr, "\t-h:\t\tHelp\n"); } // For long options that have no equivalent short option, use a // non-character as a pseudo short option, starting with CHAR_MAX + 1. enum { CNT1OPTION = CHAR_MAX + 1, CNT2OPTION, CNT3OPTION, CNT4OPTION, }; arg_values *parse_args(int argc, char** argv) { int c; // getopt_long stores the option index here int optindex = 0; static arg_values values; // set default values values.cnt1 = DEFAULT_CNT1; values.cnt2 = DEFAULT_CNT2; values.cnt3 = DEFAULT_CNT3; values.cnt4 = DEFAULT_CNT4; // long options static struct option longopts[] = { // matching options to short options {"help", no_argument, NULL, 'h'}, {"fifo", required_argument, NULL, 'f'}, // options without a short option match {"cnt1", required_argument, NULL, CNT1OPTION}, {"cnt2", required_argument, NULL, CNT2OPTION}, {"cnt3", required_argument, NULL, CNT3OPTION}, {"cnt4", required_argument, NULL, CNT4OPTION}, {NULL, 0, NULL, 0} }; char *endptr; while ((c = getopt_long(argc, argv, "", longopts, &optindex)) != -1) { switch (c) { case 'f': values.fifo = optarg; break; case CNT1OPTION: values.cnt1 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT2OPTION: values.cnt2 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT3OPTION: values.cnt3 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case CNT4OPTION: values.cnt4 = strtol(optarg, &endptr, 0); if (*endptr != '\0') { usage(argv[0]); exit(-1); } break; case '?': case 'h': // getopt_long already printed an error message usage(argv[0]); exit(0); break; default: printf("Unsupported option: %c\n", c); usage(argv[0]); } } // store remaining arguments values.nrem = argc - optind; values.rem = argv + optind; return &values; } #define MAX_BUF 1024 int main(int argc, char **argv) { arg_values *values; // parse args values = parse_args(argc, argv); // create the server std::unique_ptr<MyServer> my_server; my_server.reset(new MyServer(0)); // start the server if (my_server->Start() < 0) { fprintf(stderr, "error: cannot start server\n"); return -1; } // get the port number int port = my_server->GetProto()->GetPort(); fprintf(stdout, "server listening in port %i\n", port); // tell the client about the port char wbuf[MAX_BUF]; sprintf(wbuf, "%i", port); int fd = open(values->fifo, O_WRONLY); write(fd, wbuf, strlen(wbuf)); close(fd); // wait until we see a client message while (!my_server->seen_client_) std::this_thread::yield(); // send some messages Command1 cmd1; for (int i = 0; i < values->cnt1; ++i) my_server->Send(cmd1); Command2 cmd2; for (int i = 0; i < values->cnt2; ++i) my_server->Send(cmd2); Command3 cmd3; for (int i = 0; i < values->cnt3; ++i) my_server->Send(cmd3); Command4 cmd4; for (int i = 0; i < values->cnt4; ++i) my_server->Send(cmd4); // give some time for all both sides to finish usleep(3000000); printf("results: %i %i %i %i\n", my_server->cnt1_, my_server->cnt2_, my_server->cnt3_, my_server->cnt4_); my_server->Stop(); return 0; } <|endoftext|>
<commit_before>#include <ValueElement.h> #include <IO.h> #include <iostream> using V = Value<float, 3>; int main(){ V a({{1.1,1.5}, {2.2,2.8}, {3.9}}); V b({{3,2}, {1,2} ,{3,3}}); std::cout << "a : " << a << std::endl; std::cout << "b : " << b << std::endl; std::cout << "a+1: " << (a+1) << std::endl; std::cout << "2a : " << (a*2) << std::endl; std::cout << "a+b: " << (a+b) << std::endl; std::cout << "a*b: " << (a*b) << std::endl; return 0; } <commit_msg>Fixed silly test in value example<commit_after>#include <ValueElement.h> #include <IO.h> #include <iostream> using V = Value<float, 3>; int main(){ V a({{1.1,1.5}, {2.2,2.8}, {3.9}}); V b({{3,2}, {1,2} ,{3,3}}); std::cout << "a : " << a << std::endl; std::cout << "b : " << b << std::endl; std::cout << "a+1: " << (a+V::Ones()) << std::endl; std::cout << "2a : " << (a*2) << std::endl; std::cout << "a+b: " << (a+b) << std::endl; //std::cout << "a*b: " << (a*b) << std::endl; return 0; } <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <iostream> #include <gtest/gtest.h> #include <protobuf/message.h> #include <protobuf/dynamic_message.h> #include <protobuf/descriptor.h> // // Same as the last block, but do it dynamically via the Message // // reflection interface. // Message* foo = new Foo; // Descriptor* descriptor = foo->GetDescriptor(); // // // Get the descriptors for the fields we're interested in and verify // // their types. // FieldDescriptor* text_field = descriptor->FindFieldByName("text"); // assert(text_field != NULL); // assert(text_field->type() == FieldDescriptor::TYPE_STRING); // assert(text_field->label() == FieldDescriptor::TYPE_OPTIONAL); // FieldDescriptor* numbers_field = descriptor->FindFieldByName("numbers"); // assert(numbers_field != NULL); // assert(numbers_field->type() == FieldDescriptor::TYPE_INT32); // assert(numbers_field->label() == FieldDescriptor::TYPE_REPEATED); // // // Parse the message. // foo->ParseFromString(data); // // // Use the reflection interface to examine the contents. // const Reflection* reflection = foo->GetReflection(); // assert(reflection->GetString(foo, text_field) == "Hello World!"); // assert(reflection->FieldSize(foo, numbers_field) == 3); // assert(reflection->GetRepeatedInt32(foo, numbers_field, 0) == 1); // assert(reflection->GetRepeatedInt32(foo, numbers_field, 1) == 5); // assert(reflection->GetRepeatedInt32(foo, numbers_field, 2) == 42); // // delete foo; using namespace google::protobuf; TEST(TestProtoSerialization, Basic) { //Descriptor *desc = new Descriptor(); //DynamicMessageFactory().GetPrototype( Message *foo; //Message *prototype = factory_.GetPrototype(descriptor_); //protobuf::Descriptor *foo.desc; std::cout << "ProtoTest" << std::endl; } <commit_msg>protobuf: more test<commit_after>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <iostream> #include <gtest/gtest.h> #include <protobuf/message.h> #include <protobuf/dynamic_message.h> #include <protobuf/descriptor.h> #include "myproto.pb.h" using namespace google::protobuf; TEST(TestProtoSerialization, Basic) { testproto::Person p; p.set_name("toto"); testproto::Person_PhoneNumber *phone = p.add_phone(); phone->set_number("0642"); std::cout << p.phone(0).number() << std::endl; std::cout << p.name() << std::endl; std::cout << "ProtoTest" << std::endl; } <|endoftext|>
<commit_before>#include <stan/math/prim.hpp> #include <gtest/gtest.h> #include <cmath> #include <limits> #include <stdexcept> template <typename T> void test_quantile_double() { using stan::math::index_type_t; using stan::math::quantile; T c(1); c[0] = 1.7; EXPECT_EQ(quantile(c, 0), 1.7); EXPECT_EQ(quantile(c, 1), 1.7); EXPECT_EQ(quantile(c, 0.33), 1.7); EXPECT_EQ(quantile(c, 0.68), 1.7); T v(5); v[0] = -0.07; v[1] = 0.35; v[2] = 2.65; v[3] = -0.28; v[4] = 1.23; EXPECT_FLOAT_EQ(quantile(v, 0), -0.28); EXPECT_FLOAT_EQ(quantile(v, 0.1), -0.196); EXPECT_FLOAT_EQ(quantile(v, 0.2), -0.112); EXPECT_FLOAT_EQ(quantile(v, 0.3), 0.014); EXPECT_FLOAT_EQ(quantile(v, 0.4), 0.182); EXPECT_FLOAT_EQ(quantile(v, 0.5), 0.350); EXPECT_FLOAT_EQ(quantile(v, 0.6), 0.702); EXPECT_FLOAT_EQ(quantile(v, 0.7), 1.054); EXPECT_FLOAT_EQ(quantile(v, 0.8), 1.514); EXPECT_FLOAT_EQ(quantile(v, 0.9), 2.082); EXPECT_FLOAT_EQ(quantile(v, 1), 2.65); } TEST(MathFunctions, quantileStdVecDouble) { test_quantile_double<std::vector<double> >(); } TEST(MathFunctions, quantileEigenVectorXd) { test_quantile_double<Eigen::VectorXd>(); } TEST(MathFunctions, quantileEigenRowVectorXd) { test_quantile_double<Eigen::RowVectorXd>(); }<commit_msg>add int tests<commit_after>#include <stan/math/prim.hpp> #include <gtest/gtest.h> #include <cmath> #include <limits> #include <stdexcept> template <typename T> void test_quantile_double() { using stan::math::index_type_t; using stan::math::quantile; T c(1); c[0] = 1.7; EXPECT_EQ(quantile(c, 0), 1.7); EXPECT_EQ(quantile(c, 1), 1.7); EXPECT_EQ(quantile(c, 0.33), 1.7); EXPECT_EQ(quantile(c, 0.68), 1.7); T v(5); v[0] = -0.07; v[1] = 0.35; v[2] = 2.65; v[3] = -0.28; v[4] = 1.23; EXPECT_FLOAT_EQ(quantile(v, 0), -0.28); EXPECT_FLOAT_EQ(quantile(v, 0.1), -0.196); EXPECT_FLOAT_EQ(quantile(v, 0.2), -0.112); EXPECT_FLOAT_EQ(quantile(v, 0.3), 0.014); EXPECT_FLOAT_EQ(quantile(v, 0.4), 0.182); EXPECT_FLOAT_EQ(quantile(v, 0.5), 0.350); EXPECT_FLOAT_EQ(quantile(v, 0.6), 0.702); EXPECT_FLOAT_EQ(quantile(v, 0.7), 1.054); EXPECT_FLOAT_EQ(quantile(v, 0.8), 1.514); EXPECT_FLOAT_EQ(quantile(v, 0.9), 2.082); EXPECT_FLOAT_EQ(quantile(v, 1), 2.65); } TEST(MathFunctions, quantileStdVecDouble) { test_quantile_double<std::vector<double> >(); } TEST(MathFunctions, quantileEigenVectorXd) { test_quantile_double<Eigen::VectorXd>(); } TEST(MathFunctions, quantileEigenRowVectorXd) { test_quantile_double<Eigen::RowVectorXd>(); } TEST(MathFunctions, quantileStdVecInt) { using stan::math::quantile; std::vector<int> v{-1, 3, 5, -10}; EXPECT_FLOAT_EQ(quantile(v, 0), -10.0); EXPECT_FLOAT_EQ(quantile(v, 0.1), -7.3); EXPECT_FLOAT_EQ(quantile(v, 0.2), -4.6); EXPECT_FLOAT_EQ(quantile(v, 0.3), -1.9); EXPECT_FLOAT_EQ(quantile(v, 0.4), -0.2); EXPECT_FLOAT_EQ(quantile(v, 0.5), 1.0); EXPECT_FLOAT_EQ(quantile(v, 0.6), 2.2); EXPECT_FLOAT_EQ(quantile(v, 0.7), 3.2); EXPECT_FLOAT_EQ(quantile(v, 0.8), 3.8); EXPECT_FLOAT_EQ(quantile(v, 0.9), 4.4); EXPECT_FLOAT_EQ(quantile(v, 1), 5.0); }<|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief R8C MFRC522・メイン @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/delay.hpp" #include "common/intr_utils.hpp" #include "common/port_map.hpp" #include "common/format.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/adc_io.hpp" #include "common/trb_io.hpp" #include "common/spi_io.hpp" #include "chip/MFRC522.hpp" namespace { typedef device::trb_io<utils::null_task, uint8_t> timer_b; timer_b timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; typedef device::adc_io<utils::null_task> adc; adc adc_; // P1_0(20): typedef device::PORT<device::PORT1, device::bitpos::B0> MFRC_CS; // P1_1(19): typedef device::PORT<device::PORT1, device::bitpos::B1> SPI_SCK; // P1_2(18): typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_MOSI; // P1_3(17): typedef device::PORT<device::PORT1, device::bitpos::B3> SPI_MISO; // P1_4(16): typedef device::PORT<device::PORT1, device::bitpos::B4> MFRC_RES; typedef device::spi_io<SPI_SCK, SPI_MOSI, SPI_MISO> SPI; SPI spi_; typedef chip::MFRC522<SPI, MFRC_CS, MFRC_RES> MFRC522; MFRC522 mfrc522_(spi_); } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t intr_level = 1; uart_.start(57600, intr_level); } uart_.puts("Start R8C MFRC522 sample\n"); // SPI 開始 spi_.start(); // MFRC522 開始 mfrc522_.start(); using namespace utils; while(1) { timer_b_.sync(); if(uart_.length()) { // UART のレシーブデータがあるか? auto ch = uart_.getch(); uart_.putch(ch); } } } <commit_msg>update self-test<commit_after>//=====================================================================// /*! @file @brief R8C MFRC522・メイン @n @n ***** 電源は必ず3.3Vで使う事! ***** @n @n MFRC522(SDA) ---> MFRC_CS (P0_0) @n MFRC522(SCK) ---> SPI_SCK (P0_1) @n MFRC522(MOSI) ---> SPI_MOSI(P0_2) @n MFRC522(MISO) ---> SPI_MISO(P0_3) @n MFRC522(IRQ) N.C @n MFRC522(GND) ---> GND @n MFRC522(RES) ---> MFRC_RES(P4_2) @n MFRC522(3.3V) ---> 3.3V @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2017 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "system.hpp" #include "clock.hpp" #include "port.hpp" #include "common/delay.hpp" #include "common/intr_utils.hpp" #include "common/port_map.hpp" #include "common/format.hpp" #include "common/fifo.hpp" #include "common/uart_io.hpp" #include "common/adc_io.hpp" #include "common/trb_io.hpp" #include "common/spi_io.hpp" #include "chip/MFRC522.hpp" namespace { typedef device::trb_io<utils::null_task, uint8_t> timer_b; timer_b timer_b_; typedef utils::fifo<uint8_t, 16> buffer; typedef device::uart_io<device::UART0, buffer, buffer> uart; uart uart_; typedef device::adc_io<utils::null_task> adc; adc adc_; // ポートの定義と接続 // P1_0(20): typedef device::PORT<device::PORT1, device::bitpos::B0> MFRC_CS; // P1_1(19): typedef device::PORT<device::PORT1, device::bitpos::B1> SPI_SCK; // P1_2(18): typedef device::PORT<device::PORT1, device::bitpos::B2> SPI_MOSI; // P1_3(17): typedef device::PORT<device::PORT1, device::bitpos::B3> SPI_MISO; // P4_2(1): typedef device::PORT<device::PORT4, device::bitpos::B2> MFRC_RES; typedef device::spi_io<SPI_SCK, SPI_MOSI, SPI_MISO> SPI; SPI spi_; typedef chip::MFRC522<SPI, MFRC_CS, MFRC_RES> MFRC522; MFRC522 mfrc522_(spi_); } extern "C" { void sci_putch(char ch) { uart_.putch(ch); } char sci_getch(void) { return uart_.getch(); } uint16_t sci_length() { return uart_.length(); } void sci_puts(const char* str) { uart_.puts(str); } void TIMER_RB_intr(void) { timer_b_.itask(); } void UART0_TX_intr(void) { uart_.isend(); } void UART0_RX_intr(void) { uart_.irecv(); } } // __attribute__ ((section (".exttext"))) int main(int argc, char *argv[]) { using namespace device; // クロック関係レジスタ・プロテクト解除 PRCR.PRC0 = 1; // 高速オンチップオシレーターへ切り替え(20MHz) // ※ F_CLK を設定する事(Makefile内) OCOCR.HOCOE = 1; utils::delay::micro_second(1); // >=30us(125KHz) SCKCR.HSCKSEL = 1; CKSTPR.SCKSEL = 1; // タイマーB初期化 { uint8_t ir_level = 2; timer_b_.start_timer(60, ir_level); } // UART の設定 (P1_4: TXD0[out], P1_5: RXD0[in]) // ※シリアルライターでは、RXD 端子は、P1_6 となっているので注意! { utils::PORT_MAP(utils::port_map::P14::TXD0); utils::PORT_MAP(utils::port_map::P15::RXD0); uint8_t intr_level = 1; uart_.start(57600, intr_level); } uart_.puts("Start R8C MFRC522 sample\n"); // SPI 開始 { uint8_t speed = 10; spi_.start(speed); } // MFRC522 開始 mfrc522_.start(); // バージョンの表示 char tmp[64]; mfrc522_.list_version(tmp, sizeof(tmp)); utils::format("%s") % tmp; #if 0 // セルフ・テスト if(mfrc522_.self_test()) { utils::format("MFRC522 Self test: OK\n"); } else { utils::format("MFRC522 Self test: NG\n"); } #endif using namespace utils; while(1) { timer_b_.sync(); // Look for new cards if(mfrc522_.detect_card()) { utils::format("Card Detect !\n"); #if 0 // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { return; } // Dump debug info about the card; PICC_HaltA() is automatically called mfrc522.PICC_DumpToSerial(&(mfrc522.uid)); #endif } if(uart_.length()) { // UART のレシーブデータがあるか? auto ch = uart_.getch(); uart_.putch(ch); } } } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OOXMLPropertySetImpl.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hbrinkm $ $Date: 2007-03-06 09:51:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "OOXMLPropertySetImpl.hxx" #include <stdio.h> namespace ooxml { using namespace doctok; OOXMLPropertyImpl::OOXMLPropertyImpl(Id id, OOXMLValue::Pointer_t pValue, OOXMLPropertyImpl::Type_t eType) : mId(id), mpValue(pValue), meType(eType) { } OOXMLPropertyImpl::OOXMLPropertyImpl(const OOXMLPropertyImpl & rSprm) : OOXMLProperty(), mId(rSprm.mId), mpValue(rSprm.mpValue), meType(rSprm.meType) { } OOXMLPropertyImpl::~OOXMLPropertyImpl() { } sal_uInt32 OOXMLPropertyImpl::getId() const { return mId; } Value::Pointer_t OOXMLPropertyImpl::getValue() { Value::Pointer_t pResult; if (mpValue.get() != NULL) pResult = Value::Pointer_t(mpValue->clone()); return pResult; } doctok::Reference<BinaryObj>::Pointer_t OOXMLPropertyImpl::getBinary() { doctok::Reference<BinaryObj>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getBinary(); return pResult; } doctok::Reference<Stream>::Pointer_t OOXMLPropertyImpl::getStream() { doctok::Reference<Stream>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getStream(); return pResult; } doctok::Reference<Properties>::Pointer_t OOXMLPropertyImpl::getProps() { doctok::Reference<Properties>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getProperties(); return pResult; } string OOXMLPropertyImpl::getName() const { return "??"; } string OOXMLPropertyImpl::toString() const { string sResult = "("; static char buffer[256]; snprintf(buffer, sizeof(buffer), "0x%x", mId); sResult += buffer; sResult += ", "; if (mpValue.get() != NULL) sResult += mpValue->toString(); else sResult +="(null)"; sResult +=")"; return sResult; } Sprm * OOXMLPropertyImpl::clone() { return new OOXMLPropertyImpl(*this); } void OOXMLPropertyImpl::resolve(doctok::Properties & rProperties) { switch (meType) { case SPRM: rProperties.sprm(*this); break; case ATTRIBUTE: rProperties.attribute(mId, *getValue()); break; } } /* class OOXMLValue */ OOXMLValue::OOXMLValue() { } OOXMLValue::~OOXMLValue() { } int OOXMLValue::getInt() const { return 0; } ::rtl::OUString OOXMLValue::getString() const { return ::rtl::OUString(); } uno::Any OOXMLValue::getAny() const { return uno::Any(); } doctok::Reference<Properties>::Pointer_t OOXMLValue::getProperties() { return doctok::Reference<Properties>::Pointer_t(); } doctok::Reference<Stream>::Pointer_t OOXMLValue::getStream() { return doctok::Reference<Stream>::Pointer_t(); } doctok::Reference<BinaryObj>::Pointer_t OOXMLValue::getBinary() { return doctok::Reference<BinaryObj>::Pointer_t(); } string OOXMLValue::toString() const { return "OOXMLValue"; } OOXMLValue * OOXMLValue::clone() const { return new OOXMLValue(*this); } /* class OOXMLBooleanValue */ OOXMLBooleanValue::OOXMLBooleanValue(bool bValue) : mbValue(bValue) { } OOXMLBooleanValue::~OOXMLBooleanValue() { } int OOXMLBooleanValue::getInt() const { return mbValue ? 1 : 0; } uno::Any OOXMLBooleanValue::getAny() const { uno::Any aResult(mbValue); return aResult; } string OOXMLBooleanValue::toString() const { return mbValue ? "true" : "false"; } OOXMLValue * OOXMLBooleanValue::clone() const { return new OOXMLBooleanValue(*this); } /* class OOXMLStringValue */ OOXMLStringValue::OOXMLStringValue(const rtl::OUString & rStr) : mStr(rStr) { } OOXMLStringValue::~OOXMLStringValue() { } uno::Any OOXMLStringValue::getAny() const { uno::Any aAny(mStr); return aAny; } rtl::OUString OOXMLStringValue::getString() const { return mStr; } string OOXMLStringValue::toString() const { return OUStringToOString(mStr, RTL_TEXTENCODING_ASCII_US).getStr(); } OOXMLValue * OOXMLStringValue::clone() const { return new OOXMLStringValue(*this); } /** class OOXMLPropertySetImpl */ OOXMLPropertySetImpl::OOXMLPropertySetImpl() { } OOXMLPropertySetImpl::~OOXMLPropertySetImpl() { } void OOXMLPropertySetImpl::resolve(Properties & rHandler) { OOXMLProperties_t::iterator aIt = mProperties.begin(); while (aIt != mProperties.end()) { OOXMLProperty::Pointer_t pProp = *aIt; pProp->resolve(rHandler); aIt++; } } string OOXMLPropertySetImpl::getType() const { return "OOXMLPropertySetImpl"; } void OOXMLPropertySetImpl::add(OOXMLProperty::Pointer_t pProperty) { mProperties.push_back(pProperty); } OOXMLPropertySet * OOXMLPropertySetImpl::clone() const { return new OOXMLPropertySetImpl(*this); } /* class OOXMLPropertySetValue */ OOXMLPropertySetValue::OOXMLPropertySetValue (OOXMLPropertySet::Pointer_t pPropertySet) : mpPropertySet(pPropertySet) { } OOXMLPropertySetValue::~OOXMLPropertySetValue() { } doctok::Reference<Properties>::Pointer_t OOXMLPropertySetValue::getProperties() { return doctok::Reference<Properties>::Pointer_t (mpPropertySet->clone()); } string OOXMLPropertySetValue::toString() const { return "OOXMLPropertySetValue"; } OOXMLValue * OOXMLPropertySetValue::clone() const { return new OOXMLPropertySetValue(*this); } } <commit_msg>do not propagate sprm with id 0x0<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: OOXMLPropertySetImpl.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hbrinkm $ $Date: 2007-03-06 13:42:54 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "OOXMLPropertySetImpl.hxx" #include <stdio.h> namespace ooxml { using namespace doctok; OOXMLPropertyImpl::OOXMLPropertyImpl(Id id, OOXMLValue::Pointer_t pValue, OOXMLPropertyImpl::Type_t eType) : mId(id), mpValue(pValue), meType(eType) { } OOXMLPropertyImpl::OOXMLPropertyImpl(const OOXMLPropertyImpl & rSprm) : OOXMLProperty(), mId(rSprm.mId), mpValue(rSprm.mpValue), meType(rSprm.meType) { } OOXMLPropertyImpl::~OOXMLPropertyImpl() { } sal_uInt32 OOXMLPropertyImpl::getId() const { return mId; } Value::Pointer_t OOXMLPropertyImpl::getValue() { Value::Pointer_t pResult; if (mpValue.get() != NULL) pResult = Value::Pointer_t(mpValue->clone()); return pResult; } doctok::Reference<BinaryObj>::Pointer_t OOXMLPropertyImpl::getBinary() { doctok::Reference<BinaryObj>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getBinary(); return pResult; } doctok::Reference<Stream>::Pointer_t OOXMLPropertyImpl::getStream() { doctok::Reference<Stream>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getStream(); return pResult; } doctok::Reference<Properties>::Pointer_t OOXMLPropertyImpl::getProps() { doctok::Reference<Properties>::Pointer_t pResult; if (mpValue.get() != NULL) pResult = mpValue->getProperties(); return pResult; } string OOXMLPropertyImpl::getName() const { return "??"; } string OOXMLPropertyImpl::toString() const { string sResult = "("; static char buffer[256]; snprintf(buffer, sizeof(buffer), "0x%x", mId); sResult += buffer; sResult += ", "; if (mpValue.get() != NULL) sResult += mpValue->toString(); else sResult +="(null)"; sResult +=")"; return sResult; } Sprm * OOXMLPropertyImpl::clone() { return new OOXMLPropertyImpl(*this); } void OOXMLPropertyImpl::resolve(doctok::Properties & rProperties) { switch (meType) { case SPRM: if (mId != 0x0) rProperties.sprm(*this); break; case ATTRIBUTE: rProperties.attribute(mId, *getValue()); break; } } /* class OOXMLValue */ OOXMLValue::OOXMLValue() { } OOXMLValue::~OOXMLValue() { } int OOXMLValue::getInt() const { return 0; } ::rtl::OUString OOXMLValue::getString() const { return ::rtl::OUString(); } uno::Any OOXMLValue::getAny() const { return uno::Any(); } doctok::Reference<Properties>::Pointer_t OOXMLValue::getProperties() { return doctok::Reference<Properties>::Pointer_t(); } doctok::Reference<Stream>::Pointer_t OOXMLValue::getStream() { return doctok::Reference<Stream>::Pointer_t(); } doctok::Reference<BinaryObj>::Pointer_t OOXMLValue::getBinary() { return doctok::Reference<BinaryObj>::Pointer_t(); } string OOXMLValue::toString() const { return "OOXMLValue"; } OOXMLValue * OOXMLValue::clone() const { return new OOXMLValue(*this); } /* class OOXMLBooleanValue */ OOXMLBooleanValue::OOXMLBooleanValue(bool bValue) : mbValue(bValue) { } OOXMLBooleanValue::~OOXMLBooleanValue() { } int OOXMLBooleanValue::getInt() const { return mbValue ? 1 : 0; } uno::Any OOXMLBooleanValue::getAny() const { uno::Any aResult(mbValue); return aResult; } string OOXMLBooleanValue::toString() const { return mbValue ? "true" : "false"; } OOXMLValue * OOXMLBooleanValue::clone() const { return new OOXMLBooleanValue(*this); } /* class OOXMLStringValue */ OOXMLStringValue::OOXMLStringValue(const rtl::OUString & rStr) : mStr(rStr) { } OOXMLStringValue::~OOXMLStringValue() { } uno::Any OOXMLStringValue::getAny() const { uno::Any aAny(mStr); return aAny; } rtl::OUString OOXMLStringValue::getString() const { return mStr; } string OOXMLStringValue::toString() const { return OUStringToOString(mStr, RTL_TEXTENCODING_ASCII_US).getStr(); } OOXMLValue * OOXMLStringValue::clone() const { return new OOXMLStringValue(*this); } /** class OOXMLPropertySetImpl */ OOXMLPropertySetImpl::OOXMLPropertySetImpl() { } OOXMLPropertySetImpl::~OOXMLPropertySetImpl() { } void OOXMLPropertySetImpl::resolve(Properties & rHandler) { OOXMLProperties_t::iterator aIt = mProperties.begin(); while (aIt != mProperties.end()) { OOXMLProperty::Pointer_t pProp = *aIt; pProp->resolve(rHandler); aIt++; } } string OOXMLPropertySetImpl::getType() const { return "OOXMLPropertySetImpl"; } void OOXMLPropertySetImpl::add(OOXMLProperty::Pointer_t pProperty) { mProperties.push_back(pProperty); } OOXMLPropertySet * OOXMLPropertySetImpl::clone() const { return new OOXMLPropertySetImpl(*this); } /* class OOXMLPropertySetValue */ OOXMLPropertySetValue::OOXMLPropertySetValue (OOXMLPropertySet::Pointer_t pPropertySet) : mpPropertySet(pPropertySet) { } OOXMLPropertySetValue::~OOXMLPropertySetValue() { } doctok::Reference<Properties>::Pointer_t OOXMLPropertySetValue::getProperties() { return doctok::Reference<Properties>::Pointer_t (mpPropertySet->clone()); } string OOXMLPropertySetValue::toString() const { return "OOXMLPropertySetValue"; } OOXMLValue * OOXMLPropertySetValue::clone() const { return new OOXMLPropertySetValue(*this); } } <|endoftext|>
<commit_before>//=====================================================================// /*! @file @brief RX65N/RX72N 計算機サンプル @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/format.hpp" #include "graphics/font8x16.hpp" #include "graphics/kfont.hpp" #include "graphics/graphics.hpp" #include "graphics/simple_dialog.hpp" #include "graphics/widget_director.hpp" #include "graphics/scaling.hpp" #include "common/basic_arith.hpp" #include "common/fixed_string.hpp" namespace { // LCD 定義 static const int16_t LCD_X = 480; static const int16_t LCD_Y = 272; // static const auto PIX = graphics::pixel::TYPE::RGB565; // GLCDC 関係リソース // typedef device::glcdc_mgr<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC; template <uint32_t LCDX, uint32_t LCDY> class glcdc_emu { public: static const uint32_t width = LCDX; static const uint32_t height = LCDY; private: uint16_t fb_[LCDX * LCDY]; public: void sync_vpos() { } void* get_fbp() { return fb_; } }; typedef glcdc_emu<LCD_X, LCD_Y> GLCDC; // フォントの定義 typedef graphics::font8x16 AFONT; typedef graphics::kfont<16, 16> KFONT; typedef graphics::font<AFONT, KFONT> FONT; // ソフトウェアーレンダラー typedef graphics::render<GLCDC, FONT> RENDER; // 標準カラーインスタンス typedef graphics::def_color DEF_COLOR; GLCDC glcdc_; AFONT afont_; KFONT kfont_; FONT font_(afont_, kfont_); RENDER render_(glcdc_, font_); // typedef chip::FT5206<FT5206_I2C> TOUCH; class touch_emu { public: struct touch_t { vtx::spos pos; }; private: touch_t touch_[4]; uint32_t num_; public: touch_emu() : num_(0) { } uint32_t get_touch_num() const { return num_; } const auto& get_touch_pos(uint32_t idx) const { if(idx >= 4) idx = 0; return touch_[idx]; } void update() { } void set_pos(const vtx::spos& pos) { touch_[0].pos = pos; num_ = 1; } void reset() { num_ = 0; } }; typedef touch_emu TOUCH; TOUCH touch_; typedef gui::simple_dialog<RENDER, TOUCH> DIALOG; DIALOG dialog_(render_, touch_); // 最大32個の Widget 管理 typedef gui::widget_director<RENDER, TOUCH, 40> WIDD; WIDD widd_(render_, touch_); static const int16_t BTN_W = 38; static const int16_t BTN_H = 38; static const int16_t ORG_X = 10; static const int16_t ORG_Y = 94; static const int16_t SPC_X = 44; static const int16_t SPC_Y = 44; constexpr int16_t LOC_X(int16_t x) { return ORG_X + SPC_X * x; } constexpr int16_t LOC_Y(int16_t y) { return ORG_Y + SPC_Y * y; } typedef gui::button BUTTON; BUTTON no0_ (vtx::srect(LOC_X(0), LOC_Y(3), BTN_W, BTN_H), "0"); BUTTON no1_ (vtx::srect(LOC_X(0), LOC_Y(2), BTN_W, BTN_H), "1"); BUTTON no2_ (vtx::srect(LOC_X(1), LOC_Y(2), BTN_W, BTN_H), "2"); BUTTON no3_ (vtx::srect(LOC_X(2), LOC_Y(2), BTN_W, BTN_H), "3"); BUTTON no4_ (vtx::srect(LOC_X(0), LOC_Y(1), BTN_W, BTN_H), "4"); BUTTON no5_ (vtx::srect(LOC_X(1), LOC_Y(1), BTN_W, BTN_H), "5"); BUTTON no6_ (vtx::srect(LOC_X(2), LOC_Y(1), BTN_W, BTN_H), "6"); BUTTON no7_ (vtx::srect(LOC_X(0), LOC_Y(0), BTN_W, BTN_H), "7"); BUTTON no8_ (vtx::srect(LOC_X(1), LOC_Y(0), BTN_W, BTN_H), "8"); BUTTON no9_ (vtx::srect(LOC_X(2), LOC_Y(0), BTN_W, BTN_H), "9"); BUTTON del_ (vtx::srect(LOC_X(3), LOC_Y(0), BTN_W, BTN_H), "DEL"); BUTTON ac_ (vtx::srect(LOC_X(4), LOC_Y(0), BTN_W, BTN_H), "AC"); BUTTON mul_ (vtx::srect(LOC_X(3), LOC_Y(1), BTN_W, BTN_H), "×"); BUTTON div_ (vtx::srect(LOC_X(4), LOC_Y(1), BTN_W, BTN_H), "÷"); BUTTON add_ (vtx::srect(LOC_X(3), LOC_Y(2), BTN_W, BTN_H), "+"); BUTTON sub_ (vtx::srect(LOC_X(4), LOC_Y(2), BTN_W, BTN_H), "-"); BUTTON poi_ (vtx::srect(LOC_X(1), LOC_Y(3), BTN_W, BTN_H), "・"); BUTTON pin_ (vtx::srect(LOC_X(2), LOC_Y(3), BTN_W, BTN_H), "("); BUTTON pot_ (vtx::srect(LOC_X(3), LOC_Y(3), BTN_W, BTN_H), ")"); BUTTON equ_ (vtx::srect(LOC_X(4), LOC_Y(3), BTN_W, BTN_H), "="); typedef utils::basic_arith<float> ARITH; ARITH arith_; typedef utils::fixed_string<128> STR; STR cbuff_; static const int16_t limit_ = 3; vtx::spos cur_pos_; void clear_win_() { cbuff_.clear(); cur_pos_.set(0); render_.set_fore_color(DEF_COLOR::Darkgray); render_.round_box(vtx::srect(0, 0, 480, 16 * 5 + 6), 8); } typedef utils::fixed_string<512> OUTSTR; OUTSTR conv_cha_(const STR& inp) { OUTSTR tmp; for(uint32_t i = 0; i < inp.size(); ++i) { auto ch = inp[i]; switch(ch) { case '0': tmp += "0"; break; case '1': tmp += "1"; break; case '2': tmp += "2"; break; case '3': tmp += "3"; break; case '4': tmp += "4"; break; case '5': tmp += "5"; break; case '6': tmp += "6"; break; case '7': tmp += "7"; break; case '8': tmp += "8"; break; case '9': tmp += "9"; break; case '+': tmp += "+"; break; case '-': tmp += "-"; break; case '/': tmp += "÷"; break; case '*': tmp += "×"; break; default: tmp += ch; break; } } return tmp; } void update_calc_() { if(cur_pos_.x != cbuff_.size()) { if(cur_pos_.x > cbuff_.size()) { render_.set_fore_color(DEF_COLOR::Darkgray); auto x = cur_pos_.x; if(x > 0) --x; render_.fill_box(vtx::srect(6 + x * 16, 6 + cur_pos_.y * 20, 16, 16)); cur_pos_.x = cbuff_.size(); return; } cur_pos_.x = cbuff_.size(); auto tmp = conv_cha_(cbuff_); render_.set_fore_color(DEF_COLOR::White); render_.draw_text(vtx::spos(6, 6 + cur_pos_.y * 20), tmp.c_str()); } } void update_ans_() { arith_.analize(cbuff_.c_str()); auto ans = arith_.get(); char tmp[20]; utils::sformat("%7.6f\n", tmp, sizeof(tmp)) % ans; auto out = conv_cha_(tmp); render_.set_back_color(DEF_COLOR::Darkgray); render_.set_fore_color(DEF_COLOR::White); render_.draw_text(vtx::spos(6, 6 + 20 * 3), out.c_str(), false, true); cbuff_.clear(); cur_pos_.y++; if(cur_pos_.y >= limit_) { render_.move(vtx::srect(6, 6 + 20, 480 - 12, 20 * 2), vtx::spos(6, 6)); render_.set_fore_color(DEF_COLOR::Darkgray); render_.fill_box(vtx::srect(6, 6 + 20 * 2, 480 - 12, 20)); cur_pos_.y = limit_ - 1; } } } /// widget の登録・グローバル関数 bool insert_widget(gui::widget* w) { return widd_.insert(w); } /// widget の解除・グローバル関数 void remove_widget(gui::widget* w) { widd_.remove(w); } namespace gui_emu { const void* get_fbp() { return glcdc_.get_fbp(); } void set_pos(const vtx::spos& pos) { touch_.set_pos(pos); } void setup_gui() { no0_.enable(); no0_.at_select_func() = [=](uint32_t id) { cbuff_ += '0'; }; no1_.enable(); no1_.at_select_func() = [=](uint32_t id) { cbuff_ += '1'; }; no2_.enable(); no2_.at_select_func() = [=](uint32_t id) { cbuff_ += '2'; }; no3_.enable(); no3_.at_select_func() = [=](uint32_t id) { cbuff_ += '3'; }; no4_.enable(); no4_.at_select_func() = [=](uint32_t id) { cbuff_ += '4'; }; no5_.enable(); no5_.at_select_func() = [=](uint32_t id) { cbuff_ += '5'; }; no6_.enable(); no6_.at_select_func() = [=](uint32_t id) { cbuff_ += '6'; }; no7_.enable(); no7_.at_select_func() = [=](uint32_t id) { cbuff_ += '7'; }; no8_.enable(); no8_.at_select_func() = [=](uint32_t id) { cbuff_ += '8'; }; no9_.enable(); no9_.at_select_func() = [=](uint32_t id) { cbuff_ += '9'; }; del_.enable(); del_.at_select_func() = [=](uint32_t id) { cbuff_.pop_back(); }; ac_.enable(); ac_.at_select_func() = [=](uint32_t id) { clear_win_(); }; mul_.enable(); mul_.at_select_func() = [=](uint32_t id) { cbuff_ += '*'; }; div_.enable(); div_.at_select_func() = [=](uint32_t id) { cbuff_ += '/'; }; add_.enable(); add_.at_select_func() = [=](uint32_t id) { cbuff_ += '+'; }; sub_.enable(); sub_.at_select_func() = [=](uint32_t id) { cbuff_ += '-'; }; poi_.enable(); poi_.at_select_func() = [=](uint32_t id) { cbuff_ += '.'; }; pin_.enable(); pin_.at_select_func() = [=](uint32_t id) { cbuff_ += '('; }; pot_.enable(); pot_.at_select_func() = [=](uint32_t id) { cbuff_ += ')'; }; equ_.enable(); equ_.at_select_func() = [=](uint32_t id) { update_ans_(); }; clear_win_(); } void update_gui() { render_.sync_frame(); touch_.update(); widd_.update(); touch_.reset(); update_calc_(); } } <commit_msg>Update: cleanup<commit_after>//=====================================================================// /*! @file @brief RX65N/RX72N 計算機サンプル @author 平松邦仁 (hira@rvf-rc45.net) @copyright Copyright (C) 2020 Kunihito Hiramatsu @n Released under the MIT license @n https://github.com/hirakuni45/RX/blob/master/LICENSE */ //=====================================================================// #include "common/format.hpp" #include "graphics/font8x16.hpp" #include "graphics/kfont.hpp" #include "graphics/graphics.hpp" #include "graphics/simple_dialog.hpp" #include "graphics/widget_director.hpp" #include "graphics/scaling.hpp" #include "common/basic_arith.hpp" #include "common/fixed_string.hpp" namespace { // LCD 定義 static const int16_t LCD_X = 480; static const int16_t LCD_Y = 272; // static const auto PIX = graphics::pixel::TYPE::RGB565; // GLCDC 関係リソース // typedef device::glcdc_mgr<device::GLCDC, LCD_X, LCD_Y, PIX> GLCDC; template <uint32_t LCDX, uint32_t LCDY> class glcdc_emu { public: static const uint32_t width = LCDX; static const uint32_t height = LCDY; private: uint16_t fb_[LCDX * LCDY]; public: void sync_vpos() { } void* get_fbp() { return fb_; } }; typedef glcdc_emu<LCD_X, LCD_Y> GLCDC; // フォントの定義 typedef graphics::font8x16 AFONT; typedef graphics::kfont<16, 16> KFONT; typedef graphics::font<AFONT, KFONT> FONT; // ソフトウェアーレンダラー typedef graphics::render<GLCDC, FONT> RENDER; // 標準カラーインスタンス typedef graphics::def_color DEF_COLOR; GLCDC glcdc_; AFONT afont_; KFONT kfont_; FONT font_(afont_, kfont_); RENDER render_(glcdc_, font_); // typedef chip::FT5206<FT5206_I2C> TOUCH; class touch_emu { public: struct touch_t { vtx::spos pos; }; private: touch_t touch_[4]; uint32_t num_; public: touch_emu() : num_(0) { } uint32_t get_touch_num() const { return num_; } const auto& get_touch_pos(uint32_t idx) const { if(idx >= 4) idx = 0; return touch_[idx]; } void update() { } void set_pos(const vtx::spos& pos) { touch_[0].pos = pos; num_ = 1; } void reset() { num_ = 0; } }; typedef touch_emu TOUCH; TOUCH touch_; typedef gui::simple_dialog<RENDER, TOUCH> DIALOG; DIALOG dialog_(render_, touch_); // 最大32個の Widget 管理 typedef gui::widget_director<RENDER, TOUCH, 40> WIDD; WIDD widd_(render_, touch_); static const int16_t BTN_W = 38; static const int16_t BTN_H = 38; static const int16_t ORG_X = 10; static const int16_t ORG_Y = 94; static const int16_t SPC_X = 44; static const int16_t SPC_Y = 44; constexpr int16_t LOC_X(int16_t x) { return ORG_X + SPC_X * x; } constexpr int16_t LOC_Y(int16_t y) { return ORG_Y + SPC_Y * y; } typedef gui::button BUTTON; BUTTON no0_ (vtx::srect(LOC_X(0), LOC_Y(3), BTN_W, BTN_H), "0"); BUTTON no1_ (vtx::srect(LOC_X(0), LOC_Y(2), BTN_W, BTN_H), "1"); BUTTON no2_ (vtx::srect(LOC_X(1), LOC_Y(2), BTN_W, BTN_H), "2"); BUTTON no3_ (vtx::srect(LOC_X(2), LOC_Y(2), BTN_W, BTN_H), "3"); BUTTON no4_ (vtx::srect(LOC_X(0), LOC_Y(1), BTN_W, BTN_H), "4"); BUTTON no5_ (vtx::srect(LOC_X(1), LOC_Y(1), BTN_W, BTN_H), "5"); BUTTON no6_ (vtx::srect(LOC_X(2), LOC_Y(1), BTN_W, BTN_H), "6"); BUTTON no7_ (vtx::srect(LOC_X(0), LOC_Y(0), BTN_W, BTN_H), "7"); BUTTON no8_ (vtx::srect(LOC_X(1), LOC_Y(0), BTN_W, BTN_H), "8"); BUTTON no9_ (vtx::srect(LOC_X(2), LOC_Y(0), BTN_W, BTN_H), "9"); BUTTON del_ (vtx::srect(LOC_X(3), LOC_Y(0), BTN_W, BTN_H), "DEL"); BUTTON ac_ (vtx::srect(LOC_X(4), LOC_Y(0), BTN_W, BTN_H), "AC"); BUTTON mul_ (vtx::srect(LOC_X(3), LOC_Y(1), BTN_W, BTN_H), "×"); BUTTON div_ (vtx::srect(LOC_X(4), LOC_Y(1), BTN_W, BTN_H), "÷"); BUTTON add_ (vtx::srect(LOC_X(3), LOC_Y(2), BTN_W, BTN_H), "+"); BUTTON sub_ (vtx::srect(LOC_X(4), LOC_Y(2), BTN_W, BTN_H), "-"); BUTTON poi_ (vtx::srect(LOC_X(1), LOC_Y(3), BTN_W, BTN_H), "・"); BUTTON pin_ (vtx::srect(LOC_X(2), LOC_Y(3), BTN_W, BTN_H), "("); BUTTON pot_ (vtx::srect(LOC_X(3), LOC_Y(3), BTN_W, BTN_H), ")"); BUTTON equ_ (vtx::srect(LOC_X(4), LOC_Y(3), BTN_W, BTN_H), "="); typedef utils::basic_arith<float> ARITH; ARITH arith_; typedef utils::fixed_string<128> STR; STR cbuff_; static const int16_t limit_ = 3; vtx::spos cur_pos_; void clear_win_() { cbuff_.clear(); cur_pos_.set(0); render_.set_fore_color(DEF_COLOR::Darkgray); render_.round_box(vtx::srect(0, 0, 480, 16 * 5 + 6), 8); } typedef utils::fixed_string<512> OUTSTR; void conv_cha_(char ch, OUTSTR& out) { switch(ch) { case '0': out += "0"; break; case '1': out += "1"; break; case '2': out += "2"; break; case '3': out += "3"; break; case '4': out += "4"; break; case '5': out += "5"; break; case '6': out += "6"; break; case '7': out += "7"; break; case '8': out += "8"; break; case '9': out += "9"; break; case '+': out += "+"; break; case '-': out += "-"; break; case '/': out += "÷"; break; case '*': out += "×"; break; default: out += ch; break; } } OUTSTR conv_str_(const char* str) { OUTSTR out; char ch; while((ch = *str++) != 0) { conv_cha_(ch, out); } return out; } void update_calc_() { if(cur_pos_.x != cbuff_.size()) { if(cur_pos_.x > cbuff_.size()) { render_.set_fore_color(DEF_COLOR::Darkgray); auto x = cur_pos_.x; if(x > 0) --x; render_.fill_box(vtx::srect(6 + x * 16, 6 + cur_pos_.y * 20, 16, 16)); } else { OUTSTR tmp; conv_cha_(cbuff_.back(), tmp); render_.set_fore_color(DEF_COLOR::White); render_.draw_text(vtx::spos(6 + cur_pos_.x * 16, 6 + cur_pos_.y * 20), tmp.c_str()); } cur_pos_.x = cbuff_.size(); } } void update_ans_() { arith_.analize(cbuff_.c_str()); auto ans = arith_.get(); char tmp[20]; utils::sformat("%7.6f\n", tmp, sizeof(tmp)) % ans; auto out = conv_str_(tmp); render_.set_back_color(DEF_COLOR::Darkgray); render_.set_fore_color(DEF_COLOR::White); render_.draw_text(vtx::spos(6, 6 + 20 * 3), out.c_str(), false, true); cbuff_.clear(); cur_pos_.y++; if(cur_pos_.y >= limit_) { render_.move(vtx::srect(6, 6 + 20, 480 - 12, 20 * 2), vtx::spos(6, 6)); render_.set_fore_color(DEF_COLOR::Darkgray); render_.fill_box(vtx::srect(6, 6 + 20 * 2, 480 - 12, 20)); cur_pos_.y = limit_ - 1; } } } /// widget の登録・グローバル関数 bool insert_widget(gui::widget* w) { return widd_.insert(w); } /// widget の解除・グローバル関数 void remove_widget(gui::widget* w) { widd_.remove(w); } namespace gui_emu { const void* get_fbp() { return glcdc_.get_fbp(); } void set_pos(const vtx::spos& pos) { touch_.set_pos(pos); } void setup_gui() { no0_.enable(); no0_.at_select_func() = [=](uint32_t id) { cbuff_ += '0'; }; no1_.enable(); no1_.at_select_func() = [=](uint32_t id) { cbuff_ += '1'; }; no2_.enable(); no2_.at_select_func() = [=](uint32_t id) { cbuff_ += '2'; }; no3_.enable(); no3_.at_select_func() = [=](uint32_t id) { cbuff_ += '3'; }; no4_.enable(); no4_.at_select_func() = [=](uint32_t id) { cbuff_ += '4'; }; no5_.enable(); no5_.at_select_func() = [=](uint32_t id) { cbuff_ += '5'; }; no6_.enable(); no6_.at_select_func() = [=](uint32_t id) { cbuff_ += '6'; }; no7_.enable(); no7_.at_select_func() = [=](uint32_t id) { cbuff_ += '7'; }; no8_.enable(); no8_.at_select_func() = [=](uint32_t id) { cbuff_ += '8'; }; no9_.enable(); no9_.at_select_func() = [=](uint32_t id) { cbuff_ += '9'; }; del_.enable(); del_.at_select_func() = [=](uint32_t id) { cbuff_.pop_back(); }; ac_.enable(); ac_.at_select_func() = [=](uint32_t id) { clear_win_(); }; mul_.enable(); mul_.at_select_func() = [=](uint32_t id) { cbuff_ += '*'; }; div_.enable(); div_.at_select_func() = [=](uint32_t id) { cbuff_ += '/'; }; add_.enable(); add_.at_select_func() = [=](uint32_t id) { cbuff_ += '+'; }; sub_.enable(); sub_.at_select_func() = [=](uint32_t id) { cbuff_ += '-'; }; poi_.enable(); poi_.at_select_func() = [=](uint32_t id) { cbuff_ += '.'; }; pin_.enable(); pin_.at_select_func() = [=](uint32_t id) { cbuff_ += '('; }; pot_.enable(); pot_.at_select_func() = [=](uint32_t id) { cbuff_ += ')'; }; equ_.enable(); equ_.at_select_func() = [=](uint32_t id) { update_ans_(); }; clear_win_(); } void update_gui() { render_.sync_frame(); touch_.update(); widd_.update(); touch_.reset(); update_calc_(); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: XMLRectangleMembersHandler.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2004-09-08 14:59:48 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_AWT_RECTANGLE_HDL_ #include <com/sun/star/awt/Rectangle.hdl> #endif #ifndef _XMLOFF_XMLRECTANGLEMEMBERSHANDLER_HXX #include "XMLRectangleMembersHandler.hxx" #endif #ifndef _XMLOFF_XMLTYPES_HXX #include "xmltypes.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::rtl; XMLRectangleMembersHdl::XMLRectangleMembersHdl( sal_Int32 nType ) : mnType( nType ) { } sal_Int32 X; sal_Int32 Y; sal_Int32 Width; sal_Int32 Height; XMLRectangleMembersHdl::~XMLRectangleMembersHdl() { } sal_Bool XMLRectangleMembersHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { awt::Rectangle aRect( 0, 0, 0, 0 ); if( rValue.hasValue() ) rValue >>= aRect; sal_Int32 nValue; if( rUnitConverter.convertMeasure( nValue, rStrImpValue ) ) { switch( mnType ) { case XML_TYPE_RECTANGLE_LEFT : aRect.X = nValue; break; case XML_TYPE_RECTANGLE_TOP : aRect.Y = nValue; break; case XML_TYPE_RECTANGLE_WIDTH : aRect.Width = nValue; break; case XML_TYPE_RECTANGLE_HEIGHT : aRect.Height = nValue; break; } rValue <<= aRect; return sal_True; } return sal_False; } sal_Bool XMLRectangleMembersHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { awt::Rectangle aRect( 0, 0, 0, 0 ); rValue >>= aRect; sal_Int32 nValue; switch( mnType ) { case XML_TYPE_RECTANGLE_LEFT : nValue = aRect.X; break; case XML_TYPE_RECTANGLE_TOP : nValue = aRect.Y; break; case XML_TYPE_RECTANGLE_WIDTH : nValue = aRect.Width; break; case XML_TYPE_RECTANGLE_HEIGHT : nValue = aRect.Height; break; default: nValue = 0; // TODO What value should this be? break; } rtl::OUStringBuffer sBuffer; rUnitConverter.convertMeasure( sBuffer, nValue ); rStrExpValue = sBuffer.makeStringAndClear(); return sal_True; } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.264); FILE MERGED 2005/09/05 14:39:20 rt 1.4.264.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: XMLRectangleMembersHandler.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 14:35:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _XMLOFF_XMLUCONV_HXX #include "xmluconv.hxx" #endif #ifndef _RTL_USTRBUF_HXX_ #include <rtl/ustrbuf.hxx> #endif #ifndef _COM_SUN_STAR_UNO_ANY_HXX_ #include <com/sun/star/uno/Any.hxx> #endif #ifndef _COM_SUN_STAR_AWT_RECTANGLE_HDL_ #include <com/sun/star/awt/Rectangle.hdl> #endif #ifndef _XMLOFF_XMLRECTANGLEMEMBERSHANDLER_HXX #include "XMLRectangleMembersHandler.hxx" #endif #ifndef _XMLOFF_XMLTYPES_HXX #include "xmltypes.hxx" #endif using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::rtl; XMLRectangleMembersHdl::XMLRectangleMembersHdl( sal_Int32 nType ) : mnType( nType ) { } sal_Int32 X; sal_Int32 Y; sal_Int32 Width; sal_Int32 Height; XMLRectangleMembersHdl::~XMLRectangleMembersHdl() { } sal_Bool XMLRectangleMembersHdl::importXML( const OUString& rStrImpValue, Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { awt::Rectangle aRect( 0, 0, 0, 0 ); if( rValue.hasValue() ) rValue >>= aRect; sal_Int32 nValue; if( rUnitConverter.convertMeasure( nValue, rStrImpValue ) ) { switch( mnType ) { case XML_TYPE_RECTANGLE_LEFT : aRect.X = nValue; break; case XML_TYPE_RECTANGLE_TOP : aRect.Y = nValue; break; case XML_TYPE_RECTANGLE_WIDTH : aRect.Width = nValue; break; case XML_TYPE_RECTANGLE_HEIGHT : aRect.Height = nValue; break; } rValue <<= aRect; return sal_True; } return sal_False; } sal_Bool XMLRectangleMembersHdl::exportXML( OUString& rStrExpValue, const Any& rValue, const SvXMLUnitConverter& rUnitConverter ) const { awt::Rectangle aRect( 0, 0, 0, 0 ); rValue >>= aRect; sal_Int32 nValue; switch( mnType ) { case XML_TYPE_RECTANGLE_LEFT : nValue = aRect.X; break; case XML_TYPE_RECTANGLE_TOP : nValue = aRect.Y; break; case XML_TYPE_RECTANGLE_WIDTH : nValue = aRect.Width; break; case XML_TYPE_RECTANGLE_HEIGHT : nValue = aRect.Height; break; default: nValue = 0; // TODO What value should this be? break; } rtl::OUStringBuffer sBuffer; rUnitConverter.convertMeasure( sBuffer, nValue ); rStrExpValue = sBuffer.makeStringAndClear(); return sal_True; } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/browser/url_fixer_upper.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_process_filter.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "chrome/test/perf/mem_usage.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #ifndef NDEBUG #define TEST_ITERATIONS "2" #else #define TEST_ITERATIONS "10" #endif // URL at which data files may be found for HTTP tests. The document root of // this URL's server should point to data/page_cycler/. #define BASE_URL L"http://localhost:8000" namespace { class PageCyclerTest : public UITest { public: PageCyclerTest() { show_window_ = true; // Expose garbage collection for the page cycler tests. CommandLine::AppendSwitchWithValue(&launch_arguments_, switches::kJavaScriptFlags, L"--expose_gc"); } // For HTTP tests, the name must be safe for use in a URL without escaping. void RunPageCycler(const wchar_t* name, std::wstring* pages, std::wstring* timings, bool use_http) { GURL test_url; if (use_http) { std::wstring test_path(BASE_URL); file_util::AppendToPath(&test_path, name); file_util::AppendToPath(&test_path, L"start.html"); test_url = GURL(test_path); } else { std::wstring test_path; PathService::Get(base::DIR_EXE, &test_path); file_util::UpOneDirectory(&test_path); file_util::UpOneDirectory(&test_path); file_util::AppendToPath(&test_path, L"data"); file_util::AppendToPath(&test_path, L"page_cycler"); file_util::AppendToPath(&test_path, name); file_util::AppendToPath(&test_path, L"start.html"); test_url = net::FilePathToFileURL(test_path); } // run N iterations GURL::Replacements replacements; const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1"; replacements.SetQuery( query_string, url_parse::Component(0, arraysize(query_string) - 1)); test_url = test_url.ReplaceComponents(replacements); scoped_ptr<TabProxy> tab(GetActiveTab()); tab->NavigateToURL(test_url); // Wait for the test to finish. ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done", 3000, UITest::test_timeout_ms(), "1")); std::string cookie; ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie)); pages->swap(UTF8ToWide(cookie)); ASSERT_FALSE(pages->empty()); ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie)); timings->swap(UTF8ToWide(cookie)); ASSERT_FALSE(timings->empty()); } void PrintIOPerfInfo(const wchar_t* test_name) { BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while(chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid); scoped_ptr<process_util::ProcessMetrics> process_metrics; IO_COUNTERS io_counters; process_metrics.reset( process_util::ProcessMetrics::CreateProcessMetrics(process_handle)); ZeroMemory(&io_counters, sizeof(io_counters)); if (process_metrics.get()->GetIOCounters(&io_counters)) { // Print out IO performance. We assume that the values can be // converted to size_t (they're reported as ULONGLONG, 64-bit numbers). std::wstring chrome_name = (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r"; PrintResult(L"read_op", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.ReadOperationCount), L"", false /* not important */); PrintResult(L"write_op", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.WriteOperationCount), L"", false /* not important */); PrintResult(L"other_op", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.OtherOperationCount), L"", false /* not important */); size_t total = static_cast<size_t>(io_counters.ReadOperationCount + io_counters.WriteOperationCount + io_counters.OtherOperationCount); PrintResult(L"total_op", chrome_name, chrome_name + test_name, total, L"", true /* important */); PrintResult(L"read_byte", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.ReadTransferCount / 1024), L"kb", false /* not important */); PrintResult(L"write_byte", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.WriteTransferCount / 1024), L"kb", false /* not important */); PrintResult(L"other_byte", chrome_name, chrome_name + test_name, static_cast<size_t>(io_counters.OtherTransferCount / 1024), L"kb", false /* not important */); total = static_cast<size_t>((io_counters.ReadTransferCount + io_counters.WriteTransferCount + io_counters.OtherTransferCount) / 1024); PrintResult(L"total_byte", chrome_name, chrome_name + test_name, total, L"kb", true /* important */); } } } void PrintMemoryUsageInfo(const wchar_t* test_name) { BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while(chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; size_t peak_virtual_size; size_t current_virtual_size; size_t peak_working_set_size; size_t current_working_set_size; if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size, &peak_working_set_size, &current_working_set_size)) { std::wstring chrome_name = (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r"; std::wstring trace_name(test_name); PrintResult(L"vm_peak", chrome_name, L"vm_pk" + chrome_name + trace_name, peak_virtual_size, L"bytes", true /* important */); PrintResult(L"vm_final", chrome_name, L"vm_f" + chrome_name + trace_name, current_virtual_size, L"bytes", false /* not important */); PrintResult(L"ws_peak", chrome_name, L"ws_pk" + chrome_name + trace_name, peak_working_set_size, L"bytes", true /* important */); PrintResult(L"ws_final", chrome_name, L"ws_pk" + chrome_name + trace_name, current_working_set_size, L"bytes", false /* not important */); } } } // When use_http is true, the test name passed here will be used directly in // the path to the test data, so it must be safe for use in a URL without // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or // other funny stuff.) void RunTest(const wchar_t* name, bool use_http) { std::wstring pages, timings; RunPageCycler(name, &pages, &timings, use_http); if (timings.empty()) return; PrintMemoryUsageInfo(L""); PrintIOPerfInfo(L""); wprintf(L"\nPages: [%ls]\n", pages.c_str()); PrintResultList(L"times", L"", L"t", timings, L"ms", true /* important */); } }; class PageCyclerReferenceTest : public PageCyclerTest { public: // override the browser directory that is used by UITest::SetUp to cause it // to use the reference build instead. void SetUp() { std::wstring dir; PathService::Get(chrome::DIR_TEST_TOOLS, &dir); file_util::AppendToPath(&dir, L"reference_build"); file_util::AppendToPath(&dir, L"chrome"); browser_directory_ = dir; UITest::SetUp(); } void RunTest(const wchar_t* name, bool use_http) { std::wstring pages, timings; RunPageCycler(name, &pages, &timings, use_http); if (timings.empty()) return; PrintMemoryUsageInfo(L"_ref"); PrintIOPerfInfo(L"_ref"); PrintResultList(L"times", L"", L"t_ref", timings, L"ms", true /* important */); } }; } // namespace // file-URL tests TEST_F(PageCyclerTest, MozFile) { RunTest(L"moz", false); } TEST_F(PageCyclerReferenceTest, MozFile) { RunTest(L"moz", false); } TEST_F(PageCyclerTest, Intl1File) { RunTest(L"intl1", false); } TEST_F(PageCyclerReferenceTest, Intl1File) { RunTest(L"intl1", false); } TEST_F(PageCyclerTest, Intl2File) { RunTest(L"intl2", false); } TEST_F(PageCyclerReferenceTest, Intl2File) { RunTest(L"intl2", false); } TEST_F(PageCyclerTest, DomFile) { RunTest(L"dom", false); } TEST_F(PageCyclerReferenceTest, DomFile) { RunTest(L"dom", false); } TEST_F(PageCyclerTest, DhtmlFile) { RunTest(L"dhtml", false); } TEST_F(PageCyclerReferenceTest, DhtmlFile) { RunTest(L"dhtml", false); } // http (localhost) tests TEST_F(PageCyclerTest, MozHttp) { RunTest(L"moz", true); } TEST_F(PageCyclerReferenceTest, MozHttp) { RunTest(L"moz", true); } TEST_F(PageCyclerTest, Intl1Http) { RunTest(L"intl1", true); } TEST_F(PageCyclerReferenceTest, Intl1Http) { RunTest(L"intl1", true); } TEST_F(PageCyclerTest, Intl2Http) { RunTest(L"intl2", true); } TEST_F(PageCyclerReferenceTest, Intl2Http) { RunTest(L"intl2", true); } TEST_F(PageCyclerTest, DomHttp) { RunTest(L"dom", true); } TEST_F(PageCyclerReferenceTest, DomHttp) { RunTest(L"dom", true); } TEST_F(PageCyclerTest, BloatHttp) { RunTest(L"bloat", true); } TEST_F(PageCyclerReferenceTest, BloatHttp) { RunTest(L"bloat", true); } <commit_msg>Add prefixes to I/O data trace names so they can be distinguished on the waterfall.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/basictypes.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/path_service.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/browser/url_fixer_upper.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_process_filter.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/automation/tab_proxy.h" #include "chrome/test/automation/window_proxy.h" #include "chrome/test/ui/ui_test.h" #include "chrome/test/perf/mem_usage.h" #include "googleurl/src/gurl.h" #include "net/base/net_util.h" #ifndef NDEBUG #define TEST_ITERATIONS "2" #else #define TEST_ITERATIONS "10" #endif // URL at which data files may be found for HTTP tests. The document root of // this URL's server should point to data/page_cycler/. #define BASE_URL L"http://localhost:8000" namespace { class PageCyclerTest : public UITest { public: PageCyclerTest() { show_window_ = true; // Expose garbage collection for the page cycler tests. CommandLine::AppendSwitchWithValue(&launch_arguments_, switches::kJavaScriptFlags, L"--expose_gc"); } // For HTTP tests, the name must be safe for use in a URL without escaping. void RunPageCycler(const wchar_t* name, std::wstring* pages, std::wstring* timings, bool use_http) { GURL test_url; if (use_http) { std::wstring test_path(BASE_URL); file_util::AppendToPath(&test_path, name); file_util::AppendToPath(&test_path, L"start.html"); test_url = GURL(test_path); } else { std::wstring test_path; PathService::Get(base::DIR_EXE, &test_path); file_util::UpOneDirectory(&test_path); file_util::UpOneDirectory(&test_path); file_util::AppendToPath(&test_path, L"data"); file_util::AppendToPath(&test_path, L"page_cycler"); file_util::AppendToPath(&test_path, name); file_util::AppendToPath(&test_path, L"start.html"); test_url = net::FilePathToFileURL(test_path); } // run N iterations GURL::Replacements replacements; const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1"; replacements.SetQuery( query_string, url_parse::Component(0, arraysize(query_string) - 1)); test_url = test_url.ReplaceComponents(replacements); scoped_ptr<TabProxy> tab(GetActiveTab()); tab->NavigateToURL(test_url); // Wait for the test to finish. ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done", 3000, UITest::test_timeout_ms(), "1")); std::string cookie; ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie)); pages->swap(UTF8ToWide(cookie)); ASSERT_FALSE(pages->empty()); ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie)); timings->swap(UTF8ToWide(cookie)); ASSERT_FALSE(timings->empty()); } void PrintIOPerfInfo(const wchar_t* test_name) { BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while(chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; HANDLE process_handle = OpenProcess(PROCESS_QUERY_INFORMATION, false, pid); scoped_ptr<process_util::ProcessMetrics> process_metrics; IO_COUNTERS io_counters; process_metrics.reset( process_util::ProcessMetrics::CreateProcessMetrics(process_handle)); ZeroMemory(&io_counters, sizeof(io_counters)); if (process_metrics.get()->GetIOCounters(&io_counters)) { // Print out IO performance. We assume that the values can be // converted to size_t (they're reported as ULONGLONG, 64-bit numbers). std::wstring chrome_name = (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r"; PrintResult(L"read_op", chrome_name, L"r_op" + chrome_name + test_name, static_cast<size_t>(io_counters.ReadOperationCount), L"", false /* not important */); PrintResult(L"write_op", chrome_name, L"w_op" + chrome_name + test_name, static_cast<size_t>(io_counters.WriteOperationCount), L"", false /* not important */); PrintResult(L"other_op", chrome_name, L"o_op" + chrome_name + test_name, static_cast<size_t>(io_counters.OtherOperationCount), L"", false /* not important */); size_t total = static_cast<size_t>(io_counters.ReadOperationCount + io_counters.WriteOperationCount + io_counters.OtherOperationCount); PrintResult(L"total_op", chrome_name, L"IO_op" + chrome_name + test_name, total, L"", true /* important */); PrintResult(L"read_byte", chrome_name, L"r_b" + chrome_name + test_name, static_cast<size_t>(io_counters.ReadTransferCount / 1024), L"kb", false /* not important */); PrintResult(L"write_byte", chrome_name, L"w_b" + chrome_name + test_name, static_cast<size_t>(io_counters.WriteTransferCount / 1024), L"kb", false /* not important */); PrintResult(L"other_byte", chrome_name, L"o_b" + chrome_name + test_name, static_cast<size_t>(io_counters.OtherTransferCount / 1024), L"kb", false /* not important */); total = static_cast<size_t>((io_counters.ReadTransferCount + io_counters.WriteTransferCount + io_counters.OtherTransferCount) / 1024); PrintResult(L"total_byte", chrome_name, L"IO_b" + chrome_name + test_name, total, L"kb", true /* important */); } } } void PrintMemoryUsageInfo(const wchar_t* test_name) { BrowserProcessFilter chrome_filter(L""); process_util::NamedProcessIterator chrome_process_itr(chrome::kBrowserProcessExecutableName, &chrome_filter); const PROCESSENTRY32* chrome_entry; while(chrome_entry = chrome_process_itr.NextProcessEntry()) { uint32 pid = chrome_entry->th32ProcessID; size_t peak_virtual_size; size_t current_virtual_size; size_t peak_working_set_size; size_t current_working_set_size; if (GetMemoryInfo(pid, &peak_virtual_size, &current_virtual_size, &peak_working_set_size, &current_working_set_size)) { std::wstring chrome_name = (pid == chrome_filter.browser_process_id()) ? L"_b" : L"_r"; std::wstring trace_name(test_name); PrintResult(L"vm_peak", chrome_name, L"vm_pk" + chrome_name + trace_name, peak_virtual_size, L"bytes", true /* important */); PrintResult(L"vm_final", chrome_name, L"vm_f" + chrome_name + trace_name, current_virtual_size, L"bytes", false /* not important */); PrintResult(L"ws_peak", chrome_name, L"ws_pk" + chrome_name + trace_name, peak_working_set_size, L"bytes", true /* important */); PrintResult(L"ws_final", chrome_name, L"ws_pk" + chrome_name + trace_name, current_working_set_size, L"bytes", false /* not important */); } } } // When use_http is true, the test name passed here will be used directly in // the path to the test data, so it must be safe for use in a URL without // escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or // other funny stuff.) void RunTest(const wchar_t* name, bool use_http) { std::wstring pages, timings; RunPageCycler(name, &pages, &timings, use_http); if (timings.empty()) return; PrintMemoryUsageInfo(L""); PrintIOPerfInfo(L""); wprintf(L"\nPages: [%ls]\n", pages.c_str()); PrintResultList(L"times", L"", L"t", timings, L"ms", true /* important */); } }; class PageCyclerReferenceTest : public PageCyclerTest { public: // override the browser directory that is used by UITest::SetUp to cause it // to use the reference build instead. void SetUp() { std::wstring dir; PathService::Get(chrome::DIR_TEST_TOOLS, &dir); file_util::AppendToPath(&dir, L"reference_build"); file_util::AppendToPath(&dir, L"chrome"); browser_directory_ = dir; UITest::SetUp(); } void RunTest(const wchar_t* name, bool use_http) { std::wstring pages, timings; RunPageCycler(name, &pages, &timings, use_http); if (timings.empty()) return; PrintMemoryUsageInfo(L"_ref"); PrintIOPerfInfo(L"_ref"); PrintResultList(L"times", L"", L"t_ref", timings, L"ms", true /* important */); } }; } // namespace // file-URL tests TEST_F(PageCyclerTest, MozFile) { RunTest(L"moz", false); } TEST_F(PageCyclerReferenceTest, MozFile) { RunTest(L"moz", false); } TEST_F(PageCyclerTest, Intl1File) { RunTest(L"intl1", false); } TEST_F(PageCyclerReferenceTest, Intl1File) { RunTest(L"intl1", false); } TEST_F(PageCyclerTest, Intl2File) { RunTest(L"intl2", false); } TEST_F(PageCyclerReferenceTest, Intl2File) { RunTest(L"intl2", false); } TEST_F(PageCyclerTest, DomFile) { RunTest(L"dom", false); } TEST_F(PageCyclerReferenceTest, DomFile) { RunTest(L"dom", false); } TEST_F(PageCyclerTest, DhtmlFile) { RunTest(L"dhtml", false); } TEST_F(PageCyclerReferenceTest, DhtmlFile) { RunTest(L"dhtml", false); } // http (localhost) tests TEST_F(PageCyclerTest, MozHttp) { RunTest(L"moz", true); } TEST_F(PageCyclerReferenceTest, MozHttp) { RunTest(L"moz", true); } TEST_F(PageCyclerTest, Intl1Http) { RunTest(L"intl1", true); } TEST_F(PageCyclerReferenceTest, Intl1Http) { RunTest(L"intl1", true); } TEST_F(PageCyclerTest, Intl2Http) { RunTest(L"intl2", true); } TEST_F(PageCyclerReferenceTest, Intl2Http) { RunTest(L"intl2", true); } TEST_F(PageCyclerTest, DomHttp) { RunTest(L"dom", true); } TEST_F(PageCyclerReferenceTest, DomHttp) { RunTest(L"dom", true); } TEST_F(PageCyclerTest, BloatHttp) { RunTest(L"bloat", true); } TEST_F(PageCyclerReferenceTest, BloatHttp) { RunTest(L"bloat", true); } <|endoftext|>
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/perftimer.h" #include "base/time.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { // Returns the directory name where the "typical" user data is that we use for // testing. FilePath ComputeTypicalUserDataSource() { FilePath source_history_file; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &source_history_file)); source_history_file = source_history_file.AppendASCII("profiles") .AppendASCII("typical_history"); return source_history_file; } class NewTabUIStartupTest : public UITest { public: NewTabUIStartupTest() { show_window_ = true; } void SetUp() {} void TearDown() {} static const int kNumCycles = 5; void PrintTimings(const char* label, TimeDelta timings[kNumCycles], bool important) { std::string times; for (int i = 0; i < kNumCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList("new_tab", "", label, times, "ms", important); } // Run the test, by bringing up a browser and timing the new tab startup. // |want_warm| is true if we should output warm-disk timings, false if // we should report cold timings. void RunStartupTest(const char* label, bool want_warm, bool important) { // Install the location of the test profile file. set_template_user_data(ComputeTypicalUserDataSource().ToWStringHack()); TimeDelta timings[kNumCycles]; for (int i = 0; i < kNumCycles; ++i) { UITest::SetUp(); // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). BrowserProxy* window = automation()->GetBrowserWindow(0); ASSERT_TRUE(window); int tab_count = -1; ASSERT_TRUE(window->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Hit ctl-t and wait for the tab to load. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000)); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); if (want_warm) { // Bring up a second tab, now that we've already shown one tab. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000)); ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); } delete window; UITest::TearDown(); } PrintTimings(label, timings, important); } }; } // namespace // TODO(pamg): run these tests with a reference build? TEST_F(NewTabUIStartupTest, PerfCold) { RunStartupTest("tab_cold", false /* not cold */, true /* important */); } TEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) { RunStartupTest("tab_warm", true /* cold */, false /* not important */); } <commit_msg>Fix mac build by disabling tests.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/file_util.h" #include "base/path_service.h" #include "base/perftimer.h" #include "base/time.h" #include "build/build_config.h" #include "chrome/app/chrome_dll_resource.h" #include "chrome/common/chrome_paths.h" #include "chrome/test/automation/browser_proxy.h" #include "chrome/test/ui/ui_test.h" #include "net/base/net_util.h" using base::TimeDelta; namespace { // Returns the directory name where the "typical" user data is that we use for // testing. FilePath ComputeTypicalUserDataSource() { FilePath source_history_file; EXPECT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &source_history_file)); source_history_file = source_history_file.AppendASCII("profiles") .AppendASCII("typical_history"); return source_history_file; } class NewTabUIStartupTest : public UITest { public: NewTabUIStartupTest() { show_window_ = true; } void SetUp() {} void TearDown() {} static const int kNumCycles = 5; void PrintTimings(const char* label, TimeDelta timings[kNumCycles], bool important) { std::string times; for (int i = 0; i < kNumCycles; ++i) StringAppendF(&times, "%.2f,", timings[i].InMillisecondsF()); PrintResultList("new_tab", "", label, times, "ms", important); } // Run the test, by bringing up a browser and timing the new tab startup. // |want_warm| is true if we should output warm-disk timings, false if // we should report cold timings. void RunStartupTest(const char* label, bool want_warm, bool important) { // Install the location of the test profile file. set_template_user_data(ComputeTypicalUserDataSource().ToWStringHack()); TimeDelta timings[kNumCycles]; for (int i = 0; i < kNumCycles; ++i) { UITest::SetUp(); // Switch to the "new tab" tab, which should be any new tab after the // first (the first is about:blank). BrowserProxy* window = automation()->GetBrowserWindow(0); ASSERT_TRUE(window); int tab_count = -1; ASSERT_TRUE(window->GetTabCount(&tab_count)); ASSERT_EQ(1, tab_count); // Hit ctl-t and wait for the tab to load. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(2, 5000)); int load_time; ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); if (want_warm) { // Bring up a second tab, now that we've already shown one tab. window->ApplyAccelerator(IDC_NEW_TAB); ASSERT_TRUE(window->WaitForTabCountToBecome(3, 5000)); ASSERT_TRUE(automation()->WaitForInitialNewTabUILoad(&load_time)); timings[i] = TimeDelta::FromMilliseconds(load_time); } delete window; UITest::TearDown(); } PrintTimings(label, timings, important); } }; } // namespace // TODO(pamg): run these tests with a reference build? // TODO(tc): Fix this. #if !defined(OS_MACOSX) TEST_F(NewTabUIStartupTest, PerfCold) { RunStartupTest("tab_cold", false /* not cold */, true /* important */); } TEST_F(NewTabUIStartupTest, DISABLED_PerfWarm) { RunStartupTest("tab_warm", true /* cold */, false /* not important */); } #endif <|endoftext|>
<commit_before>//#include "NFComm/NFCore/NFPlatform.h" /* int main() { NFIDataNoSqlModule* pModule = new NFCDataNoSqlModule(); pModule->Init(); int nRet = -1; //ķʺ nRet = pModule->AddAccountInfo("test1", "123456"); //ȥķȷʺ nRet = pModule->ConfirmAccountInfo("test1", "123456"); //Ϸȷʺ nRet = pModule->HasAccount("test1"); //Ϸʺ nRet = pModule->CreateAccount("test1", "Password"); ////////////////////////////////////////////////////////////////////////// //Ϸʺ NFCDataList valueAccountPropertyList; NFCDataList valueAccountPropertyValueList; for (int i = 0; i < 10; i++) { char szProperty[MAX_PATH] = { 0 }; char szValue[MAX_PATH] = { 0 }; sprintf(szProperty, "Property_%d", i); sprintf(szValue, "Value_%d", i); valueAccountPropertyList.Add(szProperty); valueAccountPropertyValueList.Add(szValue); } nRet = pModule->SetAccountProperty("test1", valueAccountPropertyList, valueAccountPropertyValueList); //ϷʺԻȡ valueAccountPropertyList.Clear(); valueAccountPropertyValueList.Clear(); nRet = pModule->QueryAccountProperty("test1", valueAccountPropertyList, valueAccountPropertyValueList); for (int i = 0; i < valueAccountPropertyList.GetCount(); i++) { std::cout << valueAccountPropertyList.String(i) << " " << valueAccountPropertyValueList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //ϷΪijʺŴɫ nRet = pModule->CreateRole("test1", "Role1"); nRet = pModule->CreateRole("test1", "Role2"); //Ϸôʺ½ɫб NFCDataList valueRoleList; nRet = pModule->QueryAccountRoleList("test1", valueRoleList); for (int i = 0; i < valueRoleList.GetCount(); i++) { std::cout << valueRoleList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //Ϸýɫ NFCDataList valueRolePropertyList; NFCDataList valueRolePropertyValueList; for (int i = 0; i < 10; i++) { char szProperty[MAX_PATH] = { 0 }; char szValue[MAX_PATH] = { 0 }; sprintf(szProperty, "Property_%d", i); sprintf(szValue, "Value_%d", i); valueRolePropertyList.Add(szProperty); valueRolePropertyValueList.Add(szValue); } nRet = pModule->SetRoleProperty("Role1", valueRolePropertyList, valueRolePropertyValueList); //Ϸȡɫб valueRolePropertyList.Clear(); valueRolePropertyValueList.Clear(); nRet = pModule->QueryRoleProperty("Role1", valueRolePropertyList, valueRolePropertyValueList); for (int i = 0; i < valueRolePropertyList.GetCount(); i++) { std::cout << valueRolePropertyList.String(i) << " " << valueRolePropertyValueList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //Ϸýɫ NFCDataList valueRoleRecordValueList; for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { valueRoleRecordValueList.Add(i*j); } } nRet = pModule->SetRoleRecord("Role1", "record1", 4, 7, valueRoleRecordValueList); //Ϸȡɫ valueRoleRecordValueList.Clear(); int nRow = 0; int nCol = 0; nRet = pModule->QueryRoleRecord("Role1", "record1", nRow, nCol, valueRoleRecordValueList); for (int i = 0; i < valueRoleRecordValueList.GetCount(); i++) { std::cout << valueRoleRecordValueList.String(i) << std::endl; } return 0; } */ #ifdef _DEBUG #if NF_PLATFORM == NF_PLATFORM_WIN #pragma comment( lib, "ws2_32" ) #pragma comment( lib, "NFCore_d.lib" ) #pragma comment( lib, "anet_win64_d.lib" ) #elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID #pragma comment( lib, "NFCore_d.a" ) #elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS #endif #else #if NF_PLATFORM == NF_PLATFORM_WIN #pragma comment( lib, "NFCore.lib" ) #pragma comment( lib, "anet_win64.lib" ) #elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID #pragma comment( lib, "NFCore.a" ) #elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS #endif #endif <commit_msg>remove lib<commit_after>//#include "NFComm/NFCore/NFPlatform.h" /* int main() { NFIDataNoSqlModule* pModule = new NFCDataNoSqlModule(); pModule->Init(); int nRet = -1; //ķʺ nRet = pModule->AddAccountInfo("test1", "123456"); //ȥķȷʺ nRet = pModule->ConfirmAccountInfo("test1", "123456"); //Ϸȷʺ nRet = pModule->HasAccount("test1"); //Ϸʺ nRet = pModule->CreateAccount("test1", "Password"); ////////////////////////////////////////////////////////////////////////// //Ϸʺ NFCDataList valueAccountPropertyList; NFCDataList valueAccountPropertyValueList; for (int i = 0; i < 10; i++) { char szProperty[MAX_PATH] = { 0 }; char szValue[MAX_PATH] = { 0 }; sprintf(szProperty, "Property_%d", i); sprintf(szValue, "Value_%d", i); valueAccountPropertyList.Add(szProperty); valueAccountPropertyValueList.Add(szValue); } nRet = pModule->SetAccountProperty("test1", valueAccountPropertyList, valueAccountPropertyValueList); //ϷʺԻȡ valueAccountPropertyList.Clear(); valueAccountPropertyValueList.Clear(); nRet = pModule->QueryAccountProperty("test1", valueAccountPropertyList, valueAccountPropertyValueList); for (int i = 0; i < valueAccountPropertyList.GetCount(); i++) { std::cout << valueAccountPropertyList.String(i) << " " << valueAccountPropertyValueList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //ϷΪijʺŴɫ nRet = pModule->CreateRole("test1", "Role1"); nRet = pModule->CreateRole("test1", "Role2"); //Ϸôʺ½ɫб NFCDataList valueRoleList; nRet = pModule->QueryAccountRoleList("test1", valueRoleList); for (int i = 0; i < valueRoleList.GetCount(); i++) { std::cout << valueRoleList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //Ϸýɫ NFCDataList valueRolePropertyList; NFCDataList valueRolePropertyValueList; for (int i = 0; i < 10; i++) { char szProperty[MAX_PATH] = { 0 }; char szValue[MAX_PATH] = { 0 }; sprintf(szProperty, "Property_%d", i); sprintf(szValue, "Value_%d", i); valueRolePropertyList.Add(szProperty); valueRolePropertyValueList.Add(szValue); } nRet = pModule->SetRoleProperty("Role1", valueRolePropertyList, valueRolePropertyValueList); //Ϸȡɫб valueRolePropertyList.Clear(); valueRolePropertyValueList.Clear(); nRet = pModule->QueryRoleProperty("Role1", valueRolePropertyList, valueRolePropertyValueList); for (int i = 0; i < valueRolePropertyList.GetCount(); i++) { std::cout << valueRolePropertyList.String(i) << " " << valueRolePropertyValueList.String(i) << std::endl; } ////////////////////////////////////////////////////////////////////////// //Ϸýɫ NFCDataList valueRoleRecordValueList; for (int i = 0; i < 4; i++) { for (int j = 0; j < 7; j++) { valueRoleRecordValueList.Add(i*j); } } nRet = pModule->SetRoleRecord("Role1", "record1", 4, 7, valueRoleRecordValueList); //Ϸȡɫ valueRoleRecordValueList.Clear(); int nRow = 0; int nCol = 0; nRet = pModule->QueryRoleRecord("Role1", "record1", nRow, nCol, valueRoleRecordValueList); for (int i = 0; i < valueRoleRecordValueList.GetCount(); i++) { std::cout << valueRoleRecordValueList.String(i) << std::endl; } return 0; } */ #ifdef _DEBUG #if NF_PLATFORM == NF_PLATFORM_WIN #pragma comment( lib, "ws2_32" ) //#pragma comment( lib, "NFCore_d.lib" ) #pragma comment( lib, "anet_win64_d.lib" ) #elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID //#pragma comment( lib, "NFCore_d.a" ) #elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS #endif #else #if NF_PLATFORM == NF_PLATFORM_WIN //#pragma comment( lib, "NFCore.lib" ) #pragma comment( lib, "anet_win64.lib" ) #elif NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_ANDROID //#pragma comment( lib, "NFCore.a" ) #elif NF_PLATFORM == NF_PLATFORM_APPLE || NF_PLATFORM == NF_PLATFORM_APPLE_IOS #endif #endif <|endoftext|>
<commit_before>/* Copyright 2019 Andrei Khodko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "utilities.h" #include "QsLog.h" QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ auto fmt = QImage::Format_RGB32; auto *rawData = static_cast<const uchar *>(static_cast<const void *>(array.data())); // Reserve maximum possible size to avoid reallocation QVector<uchar> formattedData( (width + 3) * (height + 3) * 3 + 3); // QImage requires 32-bit aligned scan lines // Helper function to convert data auto copyAligned = [&](int perLine){ auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); formattedData.resize(scanLineSize * height); auto dst = formattedData.begin(); for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } rawData = formattedData.constData(); }; if (!format.compare("rgb32", Qt::CaseInsensitive)) { /* do nothing */ } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(width); } else { QLOG_ERROR() << "Unsupported format " << format; return QImage(); } return QImage(rawData, width, height, fmt); } <commit_msg>Fix show image (#516)<commit_after>/* Copyright 2019 Andrei Khodko * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "utilities.h" #include "QsLog.h" QImage Utilities::imageFromBytes(const QVector<int32_t> &array, int width, int height, const QString &format){ auto fmt = QImage::Format_RGB32; auto *rawData = static_cast<const uchar *>(static_cast<const void *>(array.data())); // Reserve maximum possible size to avoid reallocation auto formattedData = new uchar[(width + 3) * (height + 3) * 3 + 3]; static auto cleanUp = [](void *p) { if (p) delete [](static_cast<decltype (formattedData)>(p)); }; void *cleanUpInfo = nullptr; // QImage requires 32-bit aligned scan lines // Helper function to convert data auto copyAligned = [&](int perLine){ auto scanLineSize = static_cast<int>((static_cast<unsigned>(perLine + 3)) & 0xFFFFFFFC); auto dst = formattedData; for (auto src = array.begin(); src < array.end(); src += perLine) { dst = std::copy(src, src + perLine, dst); dst += scanLineSize - perLine; } rawData = formattedData; cleanUpInfo = formattedData; }; if (!format.compare("rgb32", Qt::CaseInsensitive)) { /* do nothing */ } else if (!format.compare("rgb888", Qt::CaseInsensitive)) { fmt = QImage::Format_RGB888; copyAligned(3 * width); } else if (format == "grayscale8") { fmt = QImage::Format_Grayscale8; copyAligned(width); } else { QLOG_ERROR() << "Unsupported format " << format; return QImage(); } return QImage(rawData, width, height, fmt, cleanUp, cleanUpInfo); } <|endoftext|>
<commit_before>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "primitive.h" #include "bezier1v.h" #include "bezier1i.h" #include "triangle.h" #include "trianglev.h" #include "trianglei.h" #include "trianglev_mb.h" #include "trianglepairsv.h" #include "quadv.h" #include "quadi.h" #include "subdivpatch1cached.h" #include "object.h" namespace embree { /********************** Bezier1v **************************/ #if !defined(__AVX__) Bezier1v::Type::Type () : PrimitiveType("bezier1v",sizeof(Bezier1v),1) {} size_t Bezier1v::Type::size(const char* This) const { return 1; } Bezier1v::Type Bezier1v::type; #endif /********************** Bezier1i **************************/ #if !defined(__AVX__) Bezier1i::Type::Type () : PrimitiveType("bezier1i",sizeof(Bezier1i),1) {} size_t Bezier1i::Type::size(const char* This) const { return 1; } Bezier1i::Type Bezier1i::type; #endif /********************** Triangle4 **************************/ #if !defined(__AVX__) template<> Triangle4::Type::Type () : PrimitiveType("triangle4",sizeof(Triangle4),4) {} template<> size_t Triangle4::Type::size(const char* This) const { return ((Triangle4*)This)->size(); } #endif /********************** Triangle4v **************************/ #if !defined(__AVX__) template<> Triangle4v::Type::Type () : PrimitiveType("triangle4v",sizeof(Triangle4v),4) {} template<> size_t Triangle4v::Type::size(const char* This) const { return ((Triangle4v*)This)->size(); } #endif /********************** Triangle4i **************************/ #if !defined(__AVX__) template<> Triangle4i::Type::Type () : PrimitiveType("triangle4i",sizeof(Triangle4i),4) {} template<> size_t Triangle4i::Type::size(const char* This) const { return ((Triangle4i*)This)->size(); } #endif /********************** Triangle4vMB **************************/ #if !defined(__AVX__) template<> Triangle4vMB::Type::Type () : PrimitiveType("triangle4vmb",sizeof(Triangle4vMB),4) {} template<> size_t Triangle4vMB::Type::size(const char* This) const { return ((Triangle4vMB*)This)->size(); } #endif /********************** Triangle8 **************************/ #if defined(__TARGET_AVX__) #if !defined(__AVX__) template<> Triangle8::Type::Type () : PrimitiveType("triangle8",2*sizeof(Triangle4),8) {} #else template<> size_t Triangle8::Type::size(const char* This) const { return ((Triangle8*)This)->size(); } #endif #endif /********************** TrianglePairs4 **************************/ #if !defined(__AVX__) template<> TrianglePairs4v::Type::Type () : PrimitiveType("trianglepairs4v",sizeof(TrianglePairs4v),4) {} template<> size_t TrianglePairs4v::Type::size(const char* This) const { return ((TrianglePairs4v*)This)->size(); } #endif /********************** Quad4v **************************/ #if !defined(__AVX__) template<> Quad4v::Type::Type () : PrimitiveType("quad4v",sizeof(Quad4v),4) {} template<> size_t Quad4v::Type::size(const char* This) const { return ((Quad4v*)This)->size(); } #endif /********************** Quad4i **************************/ #if !defined(__AVX__) template<> Quad4i::Type::Type () : PrimitiveType("quad4i",sizeof(Quad4i),4) {} template<> size_t Quad4i::Type::size(const char* This) const { return ((Quad4i*)This)->size(); } #endif /********************** SubdivPatch1Cached **************************/ #if !defined(__AVX__) SubdivPatch1Cached::Type::Type () : PrimitiveType("subdivpatch1cached",sizeof(SubdivPatch1Cached),1) {} size_t SubdivPatch1Cached::Type::size(const char* This) const { return 1; } SubdivPatch1Cached::Type SubdivPatch1Cached::type; #endif /********************** SubdivPatch1Eager **************************/ #if !defined(__AVX__) SubdivPatch1Eager::Type::Type () : PrimitiveType("subdivpatch1eager",sizeof(SubdivPatch1Eager),1) {} size_t SubdivPatch1Eager::Type::size(const char* This) const { return 1; } SubdivPatch1Eager::Type SubdivPatch1Eager::type; #endif /********************** Virtual Object **************************/ #if !defined(__AVX__) Object::Type::Type () : PrimitiveType("object",sizeof(Object),1) {} size_t Object::Type::size(const char* This) const { return 1; } Object::Type Object::type; #endif } <commit_msg>added quadi_mb primitive type<commit_after>// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "primitive.h" #include "bezier1v.h" #include "bezier1i.h" #include "triangle.h" #include "trianglev.h" #include "trianglei.h" #include "trianglev_mb.h" #include "trianglepairsv.h" #include "quadv.h" #include "quadi.h" #include "quadi_mb.h" #include "subdivpatch1cached.h" #include "object.h" namespace embree { /********************** Bezier1v **************************/ #if !defined(__AVX__) Bezier1v::Type::Type () : PrimitiveType("bezier1v",sizeof(Bezier1v),1) {} size_t Bezier1v::Type::size(const char* This) const { return 1; } Bezier1v::Type Bezier1v::type; #endif /********************** Bezier1i **************************/ #if !defined(__AVX__) Bezier1i::Type::Type () : PrimitiveType("bezier1i",sizeof(Bezier1i),1) {} size_t Bezier1i::Type::size(const char* This) const { return 1; } Bezier1i::Type Bezier1i::type; #endif /********************** Triangle4 **************************/ #if !defined(__AVX__) template<> Triangle4::Type::Type () : PrimitiveType("triangle4",sizeof(Triangle4),4) {} template<> size_t Triangle4::Type::size(const char* This) const { return ((Triangle4*)This)->size(); } #endif /********************** Triangle4v **************************/ #if !defined(__AVX__) template<> Triangle4v::Type::Type () : PrimitiveType("triangle4v",sizeof(Triangle4v),4) {} template<> size_t Triangle4v::Type::size(const char* This) const { return ((Triangle4v*)This)->size(); } #endif /********************** Triangle4i **************************/ #if !defined(__AVX__) template<> Triangle4i::Type::Type () : PrimitiveType("triangle4i",sizeof(Triangle4i),4) {} template<> size_t Triangle4i::Type::size(const char* This) const { return ((Triangle4i*)This)->size(); } #endif /********************** Triangle4vMB **************************/ #if !defined(__AVX__) template<> Triangle4vMB::Type::Type () : PrimitiveType("triangle4vmb",sizeof(Triangle4vMB),4) {} template<> size_t Triangle4vMB::Type::size(const char* This) const { return ((Triangle4vMB*)This)->size(); } #endif /********************** Triangle8 **************************/ #if defined(__TARGET_AVX__) #if !defined(__AVX__) template<> Triangle8::Type::Type () : PrimitiveType("triangle8",2*sizeof(Triangle4),8) {} #else template<> size_t Triangle8::Type::size(const char* This) const { return ((Triangle8*)This)->size(); } #endif #endif /********************** TrianglePairs4 **************************/ #if !defined(__AVX__) template<> TrianglePairs4v::Type::Type () : PrimitiveType("trianglepairs4v",sizeof(TrianglePairs4v),4) {} template<> size_t TrianglePairs4v::Type::size(const char* This) const { return ((TrianglePairs4v*)This)->size(); } #endif /********************** Quad4v **************************/ #if !defined(__AVX__) template<> Quad4v::Type::Type () : PrimitiveType("quad4v",sizeof(Quad4v),4) {} template<> size_t Quad4v::Type::size(const char* This) const { return ((Quad4v*)This)->size(); } #endif /********************** Quad4i **************************/ #if !defined(__AVX__) template<> Quad4i::Type::Type () : PrimitiveType("quad4i",sizeof(Quad4i),4) {} template<> size_t Quad4i::Type::size(const char* This) const { return ((Quad4i*)This)->size(); } #endif /********************** Quad4iMB **************************/ #if !defined(__AVX__) template<> Quad4iMB::Type::Type () : PrimitiveType("quad4imb",sizeof(Quad4iMB),4) {} template<> size_t Quad4iMB::Type::size(const char* This) const { return ((Quad4iMB*)This)->size(); } #endif /********************** SubdivPatch1Cached **************************/ #if !defined(__AVX__) SubdivPatch1Cached::Type::Type () : PrimitiveType("subdivpatch1cached",sizeof(SubdivPatch1Cached),1) {} size_t SubdivPatch1Cached::Type::size(const char* This) const { return 1; } SubdivPatch1Cached::Type SubdivPatch1Cached::type; #endif /********************** SubdivPatch1Eager **************************/ #if !defined(__AVX__) SubdivPatch1Eager::Type::Type () : PrimitiveType("subdivpatch1eager",sizeof(SubdivPatch1Eager),1) {} size_t SubdivPatch1Eager::Type::size(const char* This) const { return 1; } SubdivPatch1Eager::Type SubdivPatch1Eager::type; #endif /********************** Virtual Object **************************/ #if !defined(__AVX__) Object::Type::Type () : PrimitiveType("object",sizeof(Object),1) {} size_t Object::Type::size(const char* This) const { return 1; } Object::Type Object::type; #endif } <|endoftext|>
<commit_before>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Interface for a StrongMPC which uses a preconditioner in which the block-diagonal cell-local matrix is dense. If the system looks something like: A( y1, y2, x, t ) = 0 B( y1, y2, x, t ) = 0 where y1,y2 are spatially varying unknowns that are discretized using the MFD method (and therefore have both cell and face unknowns), an approximation to the Jacobian is written as [ dA_c/dy1_c dA_c/dy1_f dA_c/dy2_c 0 ] [ dA_f/dy1_c dA_f/dy1_f 0 0 ] [ dB_c/dy1_c 0 dB_c/dy2_c dB_c/dy2_f ] [ 0 0 dB_f/dy2_c dB_f/dy2_f ] Note that the upper left block is the standard preconditioner for the A system, and the lower right block is the standard precon for the B system, and we have simply added cell-based couplings, dA_c/dy2_c and dB_c/dy1_c. In the temperature/pressure system, these correspond to d_water_content / d_temperature and d_energy / d_pressure. ------------------------------------------------------------------------- */ #include <fstream> #include "EpetraExt_RowMatrixOut.h" #include "LinearOperatorFactory.hh" #include "FieldEvaluator.hh" #include "Operator.hh" #include "TreeOperator.hh" #include "PDE_Accumulation.hh" #include "mpc_coupled_cells.hh" namespace Amanzi { void MPCCoupledCells::Setup(const Teuchos::Ptr<State>& S) { StrongMPC<PK_PhysicalBDF_Default>::Setup(S); A_key_ = plist_->get<std::string>("conserved quantity A"); B_key_ = plist_->get<std::string>("conserved quantity B"); y1_key_ = plist_->get<std::string>("primary variable A"); y2_key_ = plist_->get<std::string>("primary variable B"); dA_dy2_key_ = std::string("d")+A_key_+std::string("_d")+y2_key_; dB_dy1_key_ = std::string("d")+B_key_+std::string("_d")+y1_key_; Key mesh_key = plist_->get<std::string>("domain name"); mesh_ = S->GetMesh(mesh_key); // set up debugger db_ = sub_pks_[0]->debugger(); // Get the sub-blocks from the sub-PK's preconditioners. Teuchos::RCP<Operators::Operator> pcA = sub_pks_[0]->preconditioner(); Teuchos::RCP<Operators::Operator> pcB = sub_pks_[1]->preconditioner(); // Create the combined operator Teuchos::RCP<TreeVectorSpace> tvs = Teuchos::rcp(new TreeVectorSpace()); tvs->PushBack(Teuchos::rcp(new TreeVectorSpace(Teuchos::rcpFromRef(pcA->DomainMap())))); tvs->PushBack(Teuchos::rcp(new TreeVectorSpace(Teuchos::rcpFromRef(pcB->DomainMap())))); preconditioner_ = Teuchos::rcp(new Operators::TreeOperator(tvs)); preconditioner_->SetOperatorBlock(0, 0, pcA); preconditioner_->SetOperatorBlock(1, 1, pcB); // create coupling blocks and push them into the preconditioner... S->RequireField(A_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireField(y2_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireFieldEvaluator(A_key_); S->RequireFieldEvaluator(y2_key_); if (!plist_->get<bool>("no dA/dy2 block", false)) { Teuchos::ParameterList& acc_pc_plist = plist_->sublist("dA_dy2 accumulation preconditioner"); acc_pc_plist.set("entity kind", "cell"); dA_dy2_ = Teuchos::rcp(new Operators::PDE_Accumulation(acc_pc_plist, mesh_)); preconditioner_->SetOperatorBlock(0, 1, dA_dy2_->global_operator()); } S->RequireField(B_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireField(y1_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireFieldEvaluator(B_key_); S->RequireFieldEvaluator(y1_key_); if (!plist_->get<bool>("no dB/dy1 block", false)) { Teuchos::ParameterList& acc_pc_plist = plist_->sublist("dB_dy1 accumulation preconditioner"); acc_pc_plist.set("entity kind", "cell"); dB_dy1_ = Teuchos::rcp(new Operators::PDE_Accumulation(acc_pc_plist, mesh_)); preconditioner_->SetOperatorBlock(1, 0, dB_dy1_->global_operator()); } // setup and initialize the preconditioner precon_used_ = plist_->isSublist("preconditioner"); if (precon_used_) { preconditioner_->SymbolicAssembleMatrix(); Teuchos::ParameterList& pc_sublist = plist_->sublist("preconditioner"); preconditioner_->InitializePreconditioner(pc_sublist); } // setup and initialize the linear solver for the preconditioner if (plist_->isSublist("linear solver")) { Teuchos::ParameterList linsolve_sublist = plist_->sublist("linear solver"); AmanziSolvers::LinearOperatorFactory<Operators::TreeOperator,TreeVector,TreeVectorSpace> fac; linsolve_preconditioner_ = fac.Create(linsolve_sublist, preconditioner_); } else { linsolve_preconditioner_ = preconditioner_; } } // updates the preconditioner void MPCCoupledCells::UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) { StrongMPC<PK_PhysicalBDF_Default>::UpdatePreconditioner(t,up,h); if (dA_dy2_ != Teuchos::null && S_next_->GetFieldEvaluator(A_key_)->IsDependency(S_next_.ptr(), y2_key_)) { dA_dy2_->global_operator()->Init(); S_next_->GetFieldEvaluator(A_key_) ->HasFieldDerivativeChanged(S_next_.ptr(), name_, y2_key_); Teuchos::RCP<const CompositeVector> dA_dy2_v = S_next_->GetFieldData(dA_dy2_key_); db_->WriteVector(" dwc_dT", dA_dy2_v.ptr()); // -- update the cell-cell block dA_dy2_->AddAccumulationTerm(*dA_dy2_v, h, "cell", false); } if (dB_dy1_ != Teuchos::null && S_next_->GetFieldEvaluator(B_key_)->IsDependency(S_next_.ptr(), y1_key_)) { dB_dy1_->global_operator()->Init(); S_next_->GetFieldEvaluator(B_key_) ->HasFieldDerivativeChanged(S_next_.ptr(), name_, y1_key_); Teuchos::RCP<const CompositeVector> dB_dy1_v = S_next_->GetFieldData(dB_dy1_key_); db_->WriteVector(" dE_dp", dB_dy1_v.ptr()); // -- update the cell-cell block dB_dy1_->AddAccumulationTerm(*dB_dy1_v, h, "cell", false); } if (precon_used_) { preconditioner_->AssembleMatrix(); preconditioner_->UpdatePreconditioner(); } } // applies preconditioner to u and returns the result in Pu int MPCCoupledCells::ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) { // write residuals if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << "Residuals:" << std::endl; std::vector<std::string> vnames; vnames.push_back(" r_p"); vnames.push_back(" r_T"); std::vector< Teuchos::Ptr<const CompositeVector> > vecs; vecs.push_back(u->SubVector(0)->Data().ptr()); vecs.push_back(u->SubVector(1)->Data().ptr()); db_->WriteVectors(vnames, vecs, true); } int ierr = linsolve_preconditioner_->ApplyInverse(*u, *Pu); if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << "PC * residuals:" << std::endl; std::vector<std::string> vnames; vnames.push_back(" PC*r_p"); vnames.push_back(" PC*r_T"); std::vector< Teuchos::Ptr<const CompositeVector> > vecs; vecs.push_back(Pu->SubVector(0)->Data().ptr()); vecs.push_back(Pu->SubVector(1)->Data().ptr()); db_->WriteVectors(vnames, vecs, true); } return (ierr > 0) ? 0 : 1; } } // namespace <commit_msg>pushes verbose object list to linear solver in coupled cells MPC for column runs<commit_after>/* -*- mode: c++; indent-tabs-mode: nil -*- */ /* ------------------------------------------------------------------------- ATS License: see $ATS_DIR/COPYRIGHT Author: Ethan Coon Interface for a StrongMPC which uses a preconditioner in which the block-diagonal cell-local matrix is dense. If the system looks something like: A( y1, y2, x, t ) = 0 B( y1, y2, x, t ) = 0 where y1,y2 are spatially varying unknowns that are discretized using the MFD method (and therefore have both cell and face unknowns), an approximation to the Jacobian is written as [ dA_c/dy1_c dA_c/dy1_f dA_c/dy2_c 0 ] [ dA_f/dy1_c dA_f/dy1_f 0 0 ] [ dB_c/dy1_c 0 dB_c/dy2_c dB_c/dy2_f ] [ 0 0 dB_f/dy2_c dB_f/dy2_f ] Note that the upper left block is the standard preconditioner for the A system, and the lower right block is the standard precon for the B system, and we have simply added cell-based couplings, dA_c/dy2_c and dB_c/dy1_c. In the temperature/pressure system, these correspond to d_water_content / d_temperature and d_energy / d_pressure. ------------------------------------------------------------------------- */ #include <fstream> #include "EpetraExt_RowMatrixOut.h" #include "LinearOperatorFactory.hh" #include "FieldEvaluator.hh" #include "Operator.hh" #include "TreeOperator.hh" #include "PDE_Accumulation.hh" #include "mpc_coupled_cells.hh" namespace Amanzi { void MPCCoupledCells::Setup(const Teuchos::Ptr<State>& S) { StrongMPC<PK_PhysicalBDF_Default>::Setup(S); A_key_ = plist_->get<std::string>("conserved quantity A"); B_key_ = plist_->get<std::string>("conserved quantity B"); y1_key_ = plist_->get<std::string>("primary variable A"); y2_key_ = plist_->get<std::string>("primary variable B"); dA_dy2_key_ = std::string("d")+A_key_+std::string("_d")+y2_key_; dB_dy1_key_ = std::string("d")+B_key_+std::string("_d")+y1_key_; Key mesh_key = plist_->get<std::string>("domain name"); mesh_ = S->GetMesh(mesh_key); // set up debugger db_ = sub_pks_[0]->debugger(); // Get the sub-blocks from the sub-PK's preconditioners. Teuchos::RCP<Operators::Operator> pcA = sub_pks_[0]->preconditioner(); Teuchos::RCP<Operators::Operator> pcB = sub_pks_[1]->preconditioner(); // Create the combined operator Teuchos::RCP<TreeVectorSpace> tvs = Teuchos::rcp(new TreeVectorSpace()); tvs->PushBack(Teuchos::rcp(new TreeVectorSpace(Teuchos::rcpFromRef(pcA->DomainMap())))); tvs->PushBack(Teuchos::rcp(new TreeVectorSpace(Teuchos::rcpFromRef(pcB->DomainMap())))); preconditioner_ = Teuchos::rcp(new Operators::TreeOperator(tvs)); preconditioner_->SetOperatorBlock(0, 0, pcA); preconditioner_->SetOperatorBlock(1, 1, pcB); // create coupling blocks and push them into the preconditioner... S->RequireField(A_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireField(y2_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireFieldEvaluator(A_key_); S->RequireFieldEvaluator(y2_key_); if (!plist_->get<bool>("no dA/dy2 block", false)) { Teuchos::ParameterList& acc_pc_plist = plist_->sublist("dA_dy2 accumulation preconditioner"); acc_pc_plist.set("entity kind", "cell"); dA_dy2_ = Teuchos::rcp(new Operators::PDE_Accumulation(acc_pc_plist, mesh_)); preconditioner_->SetOperatorBlock(0, 1, dA_dy2_->global_operator()); } S->RequireField(B_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireField(y1_key_)->SetMesh(mesh_)->AddComponent("cell", AmanziMesh::CELL, 1); S->RequireFieldEvaluator(B_key_); S->RequireFieldEvaluator(y1_key_); if (!plist_->get<bool>("no dB/dy1 block", false)) { Teuchos::ParameterList& acc_pc_plist = plist_->sublist("dB_dy1 accumulation preconditioner"); acc_pc_plist.set("entity kind", "cell"); dB_dy1_ = Teuchos::rcp(new Operators::PDE_Accumulation(acc_pc_plist, mesh_)); preconditioner_->SetOperatorBlock(1, 0, dB_dy1_->global_operator()); } // setup and initialize the preconditioner precon_used_ = plist_->isSublist("preconditioner"); if (precon_used_) { preconditioner_->SymbolicAssembleMatrix(); Teuchos::ParameterList& pc_sublist = plist_->sublist("preconditioner"); preconditioner_->InitializePreconditioner(pc_sublist); } // setup and initialize the linear solver for the preconditioner if (plist_->isSublist("linear solver")) { Teuchos::ParameterList linsolve_sublist = plist_->sublist("linear solver"); if (!linsolve_sublist.isSublist("verbose object")) linsolve_sublist.set("verbose object", plist_->sublist("verbose object")); AmanziSolvers::LinearOperatorFactory<Operators::TreeOperator,TreeVector,TreeVectorSpace> fac; linsolve_preconditioner_ = fac.Create(linsolve_sublist, preconditioner_); } else { linsolve_preconditioner_ = preconditioner_; } } // updates the preconditioner void MPCCoupledCells::UpdatePreconditioner(double t, Teuchos::RCP<const TreeVector> up, double h) { StrongMPC<PK_PhysicalBDF_Default>::UpdatePreconditioner(t,up,h); if (dA_dy2_ != Teuchos::null && S_next_->GetFieldEvaluator(A_key_)->IsDependency(S_next_.ptr(), y2_key_)) { dA_dy2_->global_operator()->Init(); S_next_->GetFieldEvaluator(A_key_) ->HasFieldDerivativeChanged(S_next_.ptr(), name_, y2_key_); Teuchos::RCP<const CompositeVector> dA_dy2_v = S_next_->GetFieldData(dA_dy2_key_); db_->WriteVector(" dwc_dT", dA_dy2_v.ptr()); // -- update the cell-cell block dA_dy2_->AddAccumulationTerm(*dA_dy2_v, h, "cell", false); } if (dB_dy1_ != Teuchos::null && S_next_->GetFieldEvaluator(B_key_)->IsDependency(S_next_.ptr(), y1_key_)) { dB_dy1_->global_operator()->Init(); S_next_->GetFieldEvaluator(B_key_) ->HasFieldDerivativeChanged(S_next_.ptr(), name_, y1_key_); Teuchos::RCP<const CompositeVector> dB_dy1_v = S_next_->GetFieldData(dB_dy1_key_); db_->WriteVector(" dE_dp", dB_dy1_v.ptr()); // -- update the cell-cell block dB_dy1_->AddAccumulationTerm(*dB_dy1_v, h, "cell", false); } if (precon_used_) { preconditioner_->AssembleMatrix(); preconditioner_->UpdatePreconditioner(); } } // applies preconditioner to u and returns the result in Pu int MPCCoupledCells::ApplyPreconditioner(Teuchos::RCP<const TreeVector> u, Teuchos::RCP<TreeVector> Pu) { // write residuals if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << "Residuals:" << std::endl; std::vector<std::string> vnames; vnames.push_back(" r_p"); vnames.push_back(" r_T"); std::vector< Teuchos::Ptr<const CompositeVector> > vecs; vecs.push_back(u->SubVector(0)->Data().ptr()); vecs.push_back(u->SubVector(1)->Data().ptr()); db_->WriteVectors(vnames, vecs, true); } int ierr = linsolve_preconditioner_->ApplyInverse(*u, *Pu); if (vo_->os_OK(Teuchos::VERB_HIGH)) { *vo_->os() << "PC * residuals:" << std::endl; std::vector<std::string> vnames; vnames.push_back(" PC*r_p"); vnames.push_back(" PC*r_T"); std::vector< Teuchos::Ptr<const CompositeVector> > vecs; vecs.push_back(Pu->SubVector(0)->Data().ptr()); vecs.push_back(Pu->SubVector(1)->Data().ptr()); db_->WriteVectors(vnames, vecs, true); } return (ierr > 0) ? 0 : 1; } } // namespace <|endoftext|>