text
stringlengths
54
60.6k
<commit_before>ab5185f8-327f-11e5-a128-9cf387a8033e<commit_msg>ab57d7c7-327f-11e5-b92f-9cf387a8033e<commit_after>ab57d7c7-327f-11e5-b92f-9cf387a8033e<|endoftext|>
<commit_before>6cba3d7a-2d3d-11e5-8550-c82a142b6f9b<commit_msg>6d17fc6e-2d3d-11e5-8d5a-c82a142b6f9b<commit_after>6d17fc6e-2d3d-11e5-8d5a-c82a142b6f9b<|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <map> #include <fstream> #include <string> #include <iterator> #include <functional> #include <algorithm> #include <deque> #include <sstream> std::string trim_begin(const std::string& str) { auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace); return str.substr(std::distance(str.begin(), alpha)); } std::string trim_end(const std::string& str) { auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base(); return str.substr(0, std::distance(str.begin(), alpha)); } std::string str_to_lower(const std::string& str) { std::string lowercase; std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower); return lowercase; } std::vector<std::string> str_split_whitespace(const std::string& str) { std::vector<std::string> words; std::istringstream is(str); std::copy( std::istream_iterator<std::string>(is), std::istream_iterator<std::string>(), std::back_inserter(words)); return words; } std::vector<std::string> str_split(const std::string& str, const char *delims) { size_t found = std::string::npos, prev = 0; std::vector<std::string> out; out.reserve(log(str.size())); found = str.find_first_of(delims); while (found != std::string::npos) { if (prev < found) { auto sub = str.substr(prev, found - prev); if (!sub.empty()) out.push_back(sub); } prev = found + 1; found = str.find_first_of(delims, prev); } auto sub = str.substr(prev, std::string::npos); if (!sub.empty()) out.push_back(sub); return out; } std::vector<std::string> extract_sentences(const std::string& str) { return str_split(str, ".?!\""); } std::vector<std::string> extract_words(const std::string& str) { return str_split(str, " .,;\"?!\n\r\""); } class sentence_file_reader { std::ifstream ifs; std::deque<std::string> sentence_buffer; static const size_t BUFFER_SIZE = 16 * 1024; char char_buffer[BUFFER_SIZE]; public: sentence_file_reader(const char *filename) : ifs(filename, std::ios::in) {} ~sentence_file_reader() { ifs.close(); } std::string get_next_sentence() { std::string sn; if (!sentence_buffer.empty()) { sn = sentence_buffer.front(); sentence_buffer.pop_front(); } else { ifs.getline(char_buffer, BUFFER_SIZE); auto sentences = extract_sentences(char_buffer); sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences)); sn = get_next_sentence(); } return trim_begin(trim_end(sn)); } bool has_more() { return ifs.good() || !sentence_buffer.empty(); } }; struct word_node { word_node(const std::string& name) : normalized_name(str_to_lower(name)), visited(false) {} void add_original_name(const std::string& original) { auto found = std::find( std::begin(original_names), std::end(original_names), original); if (found == original_names.end()) { original_names.push_back(original); } } std::vector<std::string> original_names; std::string normalized_name; std::map<word_node*, size_t> lefts; std::map<word_node*, size_t> rights; bool visited; }; struct word_graph { std::map<std::string, word_node*> word_nodes; word_node *head; word_node *get_or_create(std::string name) { auto word = str_to_lower(name); auto name_exists = word_nodes.equal_range(word); auto found_node = name_exists.first; if (name_exists.first == name_exists.second) { word_node *name_node = new word_node(name); found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node)); } found_node->second->add_original_name(name); return found_node->second; } void make_link(const std::string& a, const std::string& b) { word_node *a_node = get_or_create(a); word_node *b_node = get_or_create(b); a_node->rights[b_node]++; b_node->lefts[a_node]++; } }; void printSentences(word_node& node, const std::string& name, int superthreshold, int depth) { bool wasVisites = node.visited; node.visited = true; for (auto &w_node_cnt : node.rights) { if (w_node_cnt.second >= superthreshold && !wasVisites) { printSentences(*w_node_cnt.first, name + " " + w_node_cnt.first->normalized_name, superthreshold, depth+1); } else if (depth > 1) { std::cout << name + " " + w_node_cnt.first->normalized_name << "\n"; } } } int main(int argc, char *argv[]) { std::ios::ios_base::sync_with_stdio(false); const char *in_filename = "test.txt"; if (argc > 1) { in_filename = argv[1]; } sentence_file_reader cfr(in_filename); word_graph graph; std::string str; while (cfr.has_more()) { std::string sentence = cfr.get_next_sentence(); std::vector<std::string> words = extract_words(sentence); if (words.size() > 1) { graph.make_link(words[0], words[1]); for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) { graph.make_link(words[i], words[j]); } } else if (words.size() == 1 && !words[0].empty()) { graph.get_or_create(words[0]); } } const int threshold = 5; for (auto &kv : graph.word_nodes) { bool wordprinted = false; for (auto &w_node_cnt : kv.second->lefts) { if (w_node_cnt.second >= threshold) { if (!wordprinted) { std::cout << kv.first << "\n- left: "; wordprinted = true; } std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " "; } } if (wordprinted) std::cout << "\n- right: "; for (auto &w_node_cnt : kv.second->rights) { if (w_node_cnt.second >= threshold) { if (!wordprinted) { std::cout << kv.first << "\n- right: "; wordprinted = true; } std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " "; } } if (wordprinted) std::cout << "\n\n"; } const int superthreshold = 10; for (auto &kv : graph.word_nodes) { printSentences(*kv.second, kv.first, superthreshold,0); } return 0; } <commit_msg>Proper sentence printing<commit_after>#include <iostream> #include <vector> #include <map> #include <fstream> #include <string> #include <iterator> #include <functional> #include <algorithm> #include <deque> #include <sstream> std::string trim_begin(const std::string& str) { auto alpha = std::find_if_not(str.begin(), str.end(), ::isspace); return str.substr(std::distance(str.begin(), alpha)); } std::string trim_end(const std::string& str) { auto alpha = std::find_if_not(str.rbegin(), str.rend(), ::isspace).base(); return str.substr(0, std::distance(str.begin(), alpha)); } std::string str_to_lower(const std::string& str) { std::string lowercase; std::transform(std::begin(str), std::end(str), std::back_inserter(lowercase), ::tolower); return lowercase; } std::vector<std::string> str_split_whitespace(const std::string& str) { std::vector<std::string> words; std::istringstream is(str); std::copy( std::istream_iterator<std::string>(is), std::istream_iterator<std::string>(), std::back_inserter(words)); return words; } std::vector<std::string> str_split(const std::string& str, const char *delims) { size_t found = std::string::npos, prev = 0; std::vector<std::string> out; out.reserve(log(str.size())); found = str.find_first_of(delims); while (found != std::string::npos) { if (prev < found) { auto sub = str.substr(prev, found - prev); if (!sub.empty()) out.push_back(sub); } prev = found + 1; found = str.find_first_of(delims, prev); } auto sub = str.substr(prev, std::string::npos); if (!sub.empty()) out.push_back(sub); return out; } std::vector<std::string> extract_sentences(const std::string& str) { return str_split(str, ".?!\""); } std::vector<std::string> extract_words(const std::string& str) { return str_split(str, " .,;\"?!\n\r\""); } class sentence_file_reader { std::ifstream ifs; std::deque<std::string> sentence_buffer; static const size_t BUFFER_SIZE = 16 * 1024; char char_buffer[BUFFER_SIZE]; public: sentence_file_reader(const char *filename) : ifs(filename, std::ios::in) {} ~sentence_file_reader() { ifs.close(); } std::string get_next_sentence() { std::string sn; if (!sentence_buffer.empty()) { sn = sentence_buffer.front(); sentence_buffer.pop_front(); } else { ifs.getline(char_buffer, BUFFER_SIZE); auto sentences = extract_sentences(char_buffer); sentence_buffer = std::deque<std::string>(std::begin(sentences), std::end(sentences)); sn = get_next_sentence(); } return trim_begin(trim_end(sn)); } bool has_more() { return ifs.good() || !sentence_buffer.empty(); } }; struct word_node { word_node(const std::string& name) : normalized_name(str_to_lower(name)) {} void add_original_name(const std::string& original) { auto found = std::find( std::begin(original_names), std::end(original_names), original); if (found == original_names.end()) { original_names.push_back(original); } } std::vector<std::string> original_names; std::string normalized_name; std::map<word_node*, size_t> lefts; std::map<word_node*, size_t> rights; bool visited; }; struct word_graph { std::map<std::string, word_node*> word_nodes; word_node *head; word_node *get_or_create(std::string name) { auto word = str_to_lower(name); auto name_exists = word_nodes.equal_range(word); auto found_node = name_exists.first; if (name_exists.first == name_exists.second) { word_node *name_node = new word_node(name); found_node = word_nodes.insert(name_exists.second, std::make_pair(word, name_node)); } found_node->second->add_original_name(name); return found_node->second; } void make_link(const std::string& a, const std::string& b) { word_node *a_node = get_or_create(a); word_node *b_node = get_or_create(b); a_node->rights[b_node]++; b_node->lefts[a_node]++; } }; class sentence_printer { public: void print(word_node *node, int superthreshold, int depth) { node_visited.clear(); printSentences(node, node->normalized_name, superthreshold, depth); } private: void printSentences(word_node *node, const std::string& name, int superthreshold, int depth) { bool wasVisites = node_visited[node]; node_visited[node] = true; for (auto &w_node_cnt : node->rights) { if (w_node_cnt.second >= superthreshold && !wasVisites) { printSentences(w_node_cnt.first, name + " " + w_node_cnt.first->normalized_name, superthreshold, depth + 1); } else if (depth > 1) { std::cout << name + " " + w_node_cnt.first->normalized_name << "\n"; } } } private: std::map<word_node*, bool> node_visited; }; int main(int argc, char *argv[]) { std::ios::ios_base::sync_with_stdio(false); const char *in_filename = "test.txt"; if (argc > 1) { in_filename = argv[1]; } sentence_file_reader cfr(in_filename); word_graph graph; std::string str; while (cfr.has_more()) { std::string sentence = cfr.get_next_sentence(); std::vector<std::string> words = extract_words(sentence); if (words.size() > 1) { graph.make_link(words[0], words[1]); for (size_t i = 1, j = 2; j < words.size(); ++i, ++j) { graph.make_link(words[i], words[j]); } } else if (words.size() == 1 && !words[0].empty()) { graph.get_or_create(words[0]); } } const int threshold = 5; for (auto &kv : graph.word_nodes) { bool wordprinted = false; for (auto &w_node_cnt : kv.second->lefts) { if (w_node_cnt.second >= threshold) { if (!wordprinted) { std::cout << kv.first << "\n- left: "; wordprinted = true; } std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " "; } } if (wordprinted) std::cout << "\n- right: "; for (auto &w_node_cnt : kv.second->rights) { if (w_node_cnt.second >= threshold) { if (!wordprinted) { std::cout << kv.first << "\n- right: "; wordprinted = true; } std::cout << w_node_cnt.first->normalized_name << ":" << w_node_cnt.second << " "; } } if (wordprinted) std::cout << "\n\n"; } const int superthreshold = 100; sentence_printer printer; for (auto &kv : graph.word_nodes) { printer.print(kv.second, superthreshold, 0); } return 0; } <|endoftext|>
<commit_before>1d75799c-2d3e-11e5-af27-c82a142b6f9b<commit_msg>1e0308c0-2d3e-11e5-bfb3-c82a142b6f9b<commit_after>1e0308c0-2d3e-11e5-bfb3-c82a142b6f9b<|endoftext|>
<commit_before>231ba5b8-585b-11e5-beda-6c40088e03e4<commit_msg>23224878-585b-11e5-80d0-6c40088e03e4<commit_after>23224878-585b-11e5-80d0-6c40088e03e4<|endoftext|>
<commit_before>b90808b8-35ca-11e5-96f6-6c40088e03e4<commit_msg>b90eb076-35ca-11e5-954f-6c40088e03e4<commit_after>b90eb076-35ca-11e5-954f-6c40088e03e4<|endoftext|>
<commit_before>1f9c42c8-585b-11e5-81e0-6c40088e03e4<commit_msg>1fa46ed8-585b-11e5-a32f-6c40088e03e4<commit_after>1fa46ed8-585b-11e5-a32f-6c40088e03e4<|endoftext|>
<commit_before>891be399-4b02-11e5-a396-28cfe9171a43<commit_msg>For bobby to integrate at some point<commit_after>892ab59e-4b02-11e5-8855-28cfe9171a43<|endoftext|>
<commit_before>#include <iostream> #include <unistd.h> #include <getopt.h> #include <cstring> #include <cstdlib> #include "util.h" #include "sniffer.h" using namespace std; static int verbose_flag = 0; static int debug_flag = 0; static int help_flag = 0; static char * interface = 0; int main(int argc, char ** argv) { // Make sure that only root can run this program if ( geteuid() ) { help_flag = true; } if ( argc == 1 ) { help_flag = true; } // Option parsing loop while (1) { int c; static struct option long_options[] = { {"macstat" , no_argument , &macstat_flag , 1}, {"time" , required_argument, NULL ,'t'}, {"verbose" , no_argument , &verbose_flag , 1}, {"debug" , no_argument , &debug_flag , 1}, {"help" , no_argument , &help_flag , 1}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long_only (argc, argv, "", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 't': max_time = atoi(optarg); break; default: cerr << "Invalid option. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } } if (help_flag) { cerr << "Usage: " << argv[0] << " [options] interface\n" " -m, --macstat : Show number of detections of each MAC and timestamps\n" " -t, --time : Set time to run sniffer in seconds (default: 60)\n" " -v, --verbose : Output more information\n" " -d, --debug : Show debugging information\n" " -h, --help : Show this help text\n" "\n" "Note: This program needs to be run as root\n" ; return 0; } while (optind < argc) { if ( ! interface ) { interface = strdup(argv[optind++]); } else { cerr << "Too many interfaces. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } } if ( ! interface ) { cerr << "No interface specified. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } if ( verbose_flag ) { set_verbose_on(); } if ( debug_flag ) { set_debug_on(); } // Do actual work (from sniffer.* files) initialize(interface); capture_packets(); print_info(); return 0; } <commit_msg>Add useful header<commit_after>#include <iostream> #include <unistd.h> #include <getopt.h> #include <cstring> #include <cstdlib> #include "util.h" #include "sniffer.h" using namespace std; static int verbose_flag = 0; static int debug_flag = 0; static int help_flag = 0; static char * interface = 0; int main(int argc, char ** argv) { cout << "WiFi Sniffer\n" "------------\tBy Jay H. Bosamiya\n" " \t------------------\n\n"; // Make sure that only root can run this program if ( geteuid() ) { help_flag = true; } if ( argc == 1 ) { help_flag = true; } // Option parsing loop while (1) { int c; static struct option long_options[] = { {"macstat" , no_argument , &macstat_flag , 1}, {"time" , required_argument, NULL ,'t'}, {"verbose" , no_argument , &verbose_flag , 1}, {"debug" , no_argument , &debug_flag , 1}, {"help" , no_argument , &help_flag , 1}, {0, 0, 0, 0} }; int option_index = 0; c = getopt_long_only (argc, argv, "", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; switch (c) { case 0: break; case 't': max_time = atoi(optarg); break; default: cerr << "Invalid option. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } } if (help_flag) { cerr << "Usage: " << argv[0] << " [options] interface\n" " -m, --macstat : Show number of detections of each MAC and timestamps\n" " -t, --time : Set time to run sniffer in seconds (default: 60)\n" " -v, --verbose : Output more information\n" " -d, --debug : Show debugging information\n" " -h, --help : Show this help text\n" "\n" "Note: This program needs to be run as root\n" ; return 0; } while (optind < argc) { if ( ! interface ) { interface = strdup(argv[optind++]); } else { cerr << "Too many interfaces. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } } if ( ! interface ) { cerr << "No interface specified. Try " << argv[0] << " -h for help. Quitting.\n"; return -1; } if ( verbose_flag ) { set_verbose_on(); } if ( debug_flag ) { set_debug_on(); } // Do actual work (from sniffer.* files) initialize(interface); capture_packets(); print_info(); return 0; } <|endoftext|>
<commit_before>2f757e88-5216-11e5-bcfc-6c40088e03e4<commit_msg>2f7d1882-5216-11e5-986c-6c40088e03e4<commit_after>2f7d1882-5216-11e5-986c-6c40088e03e4<|endoftext|>
<commit_before>c2bbd808-35ca-11e5-b3bc-6c40088e03e4<commit_msg>c2c28a4a-35ca-11e5-a207-6c40088e03e4<commit_after>c2c28a4a-35ca-11e5-a207-6c40088e03e4<|endoftext|>
<commit_before>d4f6a65e-313a-11e5-b0d7-3c15c2e10482<commit_msg>d4fca9a1-313a-11e5-a09a-3c15c2e10482<commit_after>d4fca9a1-313a-11e5-a09a-3c15c2e10482<|endoftext|>
<commit_before>0930d1d4-2f67-11e5-a078-6c40088e03e4<commit_msg>0937c0b8-2f67-11e5-8f4a-6c40088e03e4<commit_after>0937c0b8-2f67-11e5-8f4a-6c40088e03e4<|endoftext|>
<commit_before>81cf0e5f-2d15-11e5-af21-0401358ea401<commit_msg>81cf0e60-2d15-11e5-af21-0401358ea401<commit_after>81cf0e60-2d15-11e5-af21-0401358ea401<|endoftext|>
<commit_before>7d3665e3-4b02-11e5-8256-28cfe9171a43<commit_msg>Did ANOTHER thing<commit_after>7d43ef97-4b02-11e5-bdf2-28cfe9171a43<|endoftext|>
<commit_before>#include <iostream> #include "named_param_map.hpp" constexpr bool constexpr_strequal(char const *one, char const *two) { return (*one && *two) ? (*one == *two && constexpr_strequal(one + 1, two + 1)) : (!*one && !*two); } template<typename NP0> auto collect(NP0&& first) -> named_param_map<NP0,void> { return named_param_map<NP0, void>(std::forward<NP0>(first)); } template<typename NP0, typename... Args> auto collect(NP0&& first, Args... args) -> named_param_map<NP0, decltype(collect(std::forward<Args>(args)...)) > { typedef decltype(collect(std::forward<Args>(args)...)) other_map_type; return named_param_map<NP0, other_map_type>(std::forward<NP0>(first), collect(std::forward<Args>(args)...)); } class basic_class { }; std::ostream& operator<<(std::ostream& os, const basic_class&) { os << "basic instance"; return os; } class move_only_class { public: move_only_class() {} move_only_class(move_only_class&&) {} move_only_class(const move_only_class& v) = delete; }; std::ostream& operator<<(std::ostream& os, const move_only_class&) { os << "move-only instance"; return os; } int main(const int argn, const char* argv[]) { auto numX = named<typestring_is("num")>(5); static_assert(constexpr_strequal(numX.name(),"num"), "the name of num is wrong!"); auto param_map = collect( named<typestring_is("f0")>(3.0f), named<typestring_is("other_param")>(2), named<typestring_is("class-type")>(basic_class()) ); std::cout << param_map.at<typestring_is("f0")>() << std::endl; std::cout << param_map.at<typestring_is("other_param")>() << std::endl; std::cout << param_map.at<typestring_is("class-type")>() << std::endl; // currently doesn't support move-only types, which I'd like it to return 1; } <commit_msg>Add comment about move-only-types which should probably be supported.<commit_after>#include <iostream> #include "named_param_map.hpp" constexpr bool constexpr_strequal(char const *one, char const *two) { return (*one && *two) ? (*one == *two && constexpr_strequal(one + 1, two + 1)) : (!*one && !*two); } template<typename NP0> auto collect(NP0&& first) -> named_param_map<NP0,void> { return named_param_map<NP0, void>(std::forward<NP0>(first)); } template<typename NP0, typename... Args> auto collect(NP0&& first, Args... args) -> named_param_map<NP0, decltype(collect(std::forward<Args>(args)...)) > { typedef decltype(collect(std::forward<Args>(args)...)) other_map_type; return named_param_map<NP0, other_map_type>(std::forward<NP0>(first), collect(std::forward<Args>(args)...)); } class basic_class { }; std::ostream& operator<<(std::ostream& os, const basic_class&) { os << "basic instance"; return os; } class move_only_class { public: move_only_class() {} move_only_class(move_only_class&&) {} move_only_class(const move_only_class& v) = delete; }; std::ostream& operator<<(std::ostream& os, const move_only_class&) { os << "move-only instance"; return os; } int main(const int argn, const char* argv[]) { auto numX = named<typestring_is("num")>(5); static_assert(constexpr_strequal(numX.name(),"num"), "the name of num is wrong!"); auto param_map = collect( named<typestring_is("f0")>(3.0f), named<typestring_is("other_param")>(2), named<typestring_is("class-type")>(basic_class()) ); std::cout << param_map.at<typestring_is("f0")>() << std::endl; std::cout << param_map.at<typestring_is("other_param")>() << std::endl; std::cout << param_map.at<typestring_is("class-type")>() << std::endl; //FIXME: doesn't support move-only types currently, which is desirable // std::cout << param_map.at<typestring_is("move-only-type")>() << std::endl; return 1; } <|endoftext|>
<commit_before>4296d9a1-2748-11e6-bbc5-e0f84713e7b8<commit_msg>Now it no longer crashes if X<commit_after>42c747fd-2748-11e6-bfd9-e0f84713e7b8<|endoftext|>
<commit_before>d3ded98c-585a-11e5-ba73-6c40088e03e4<commit_msg>d3e891fe-585a-11e5-b491-6c40088e03e4<commit_after>d3e891fe-585a-11e5-b491-6c40088e03e4<|endoftext|>
<commit_before>#include "Observador.h" Observador::Observador() { m_enviados=0; m_recibidos=0; m_perdidos=0; m_QoS=0; m_usuarios=0; } Observador::~Observador() { } void Observador::PktEnviado(Pkt<Const Packet>paquete); { t_enviado=Simulator::Now(); m_enviados=m_enviados++ uint64_t id = paquete->GetUid(); array[id]=t_enviados } void Observador::PktRecibido(Pkt<const Packet>paquete, const Address & dir) { std::map<uint64_t,Time>::iterator aux=array.find(paquete->GetUid()); if (array.end() == aux) { NS_LOG_INFO("NO ESTA EN LA ESTRUCTURA"); } else { NS_LOG_INFO("SI ESTA EN LA ESTRUCTURA"); Time Taux =array[paquete->GetUid()]; Jitter.Update((Simulator::Now()-Taux).GetMilliSeconds()); m_recibidos=m_recibidos+1; array.erase(aux); } } float Observador::QoSActual(); { m_perdidos=array.Size(); m_QoS=((m_recibidos)/m_enviados)*100; //referente a paquetes perdidos return m_QoS; } float Observador::ActualizaJitter() { return Jitter.Mean(); } Void Observador:Reset() { Jitter.Reset(); } <commit_msg>Jitter y Retardo diferenciado <commit_after>#include "Observador.h" Observador::Observador() { m_enviados=0; m_recibidos=0; m_perdidos=0; m_QoS=0; m_usuarios=0; } Observador::~Observador() { } void Observador::PktEncolado(Pkt<Const Packet>paquete) { t_encolado=Simulator::Now(); uint64_t id = paquete->GetUid(); array[id]=t_encolado } void Observador::PktEnviado(Pkt<Const Packet>paquete) { /*suponemos que el paquete está en la estructura*/ std::map<uint64_t,Time>::iterator aux=array.find(paquete->GetUid()); Time Taux =array[paquete->GetUid()]; Jitter.Update((Simulator::Now()-Taux).GetMilliSeconds()); m_enviados=m_enviados++ } void Observador::PktRecibido(Pkt<const Packet>paquete, const Address & dir) { std::map<uint64_t,Time>::iterator aux=array.find(paquete->GetUid()); if (array.end() == aux) { NS_LOG_INFO("NO ESTA EN LA ESTRUCTURA"); } else { NS_LOG_INFO("SI ESTA EN LA ESTRUCTURA"); Time Taux =array[paquete->GetUid()]; Retardo.Update((Simulator::Now()-Taux).GetMilliSeconds()); m_recibidos=m_recibidos+1; array.erase(aux); } } float Observador::QoSActual(); { /* modelo E QoS= (Ro − Is) − Id − Ie-eff + A jitter >= 100ms retardo >= 150ms % >=1 */ m_perdidos=array.Size(); /* debe ser menor a un 0.01 o un 1%*/ m_porcentaje=((m_perdidos)/m_enviados)*100; //referente a paquetes perdidos m_QoS= return m_QoS; } float Observador::ActualizaJitter() { /* el jitter debe se menor de 100 ms */ return Jitter.Mean(); } float Observador::ActualizaRetardo() { /* el retardo debe ser menor de 150ms */ return Retardo.Mean(); } Void Observador:Reset() { Jitter.Reset(); Retardo.Reset(); } <|endoftext|>
<commit_before>#pragma once #include <vector> #include "timing_graph_fwd.hpp" #include "timing_constraints_fwd.hpp" #include "analysis_types.hpp" class TimingTags; struct ta_runtime; /* * TimingAnalyzer represents a interface class for all timing analyzers */ template<class AnalysisType, class DelayCalcType> class TimingAnalyzer : public AnalysisType { public: typedef DelayCalcType delay_calculator_type; typedef AnalysisType analysis_type; virtual ~TimingAnalyzer() {}; virtual void calculate_timing() = 0; virtual void reset_timing() = 0; virtual const DelayCalcType& delay_calculator() = 0; virtual std::map<std::string, double> profiling_data() = 0; }; struct ta_runtime { float pre_traversal; float fwd_traversal; float bck_traversal; }; <commit_msg>Add high-level comments on the motivation and techniques of STA.<commit_after>#pragma once /* * TIMING ANALYSIS: Overview * =========================== * Timing analysis involves determining at what point in time (relative to some reference, * usually a clock) signals arrive at every point in a circuit. This is used to verify * that none of these signals will violate any constraints, ensuring the circuit will operate * correctly and reliably. * * The circuit is typically modelled as a directed graph (called a timing graph) where nodes * represent the 'pins' of elements in the circuit and edges the connectivity between them. * Delays through the circuit (e.g. along wires, or through combinational logic) are associated * with the edges. * * We are generally interested in whether signals arrive late (causing a setup * constraint violation) or arrive to early (causing a hold violation). Typically long/slow * paths cause setup violations, and short/fast paths hold violations. Violating a setup or * hold constraint can cause meta-stability in Flip-Flops putting the circuit into an * undetermined state for an indeterminate period of time (this is not good). * * To perform a completely accurate, non-pessemistic timing analysis would involve determining * exactly which set of state/inputs to the circuit trigger the worst case path. This requires * a dynamic analysis of the circuits behaviour and is prohibitively expensive to compute in * practice. * * * Static Timing Analysis (STA) * ============================== * Static Timing Analysis (STA), which this library implements, simplifies the problem somewhat * by ignoring the dynamic behaviour the circuit. That is, we assume all paths could be sensitized, * even if in practice they may be extremely rare or impossible to sensitize in practice. This * makes the result of our analysis pessemistic, but also makes the problem tractable. * * There are two approaches to performing STA: 'path-based' and 'block-based'. * * Under Path-Based Analysis (PBA) all paths in the circuit are analyzed. This provides * a more accurate (less-pessimistic) analysis than block-based approaches but can require * an exponential amount of time. In particular, circuit structures with re-convergent fanout * can exponentiallly increase the number of paths through the circuit which must be evaluated. * * To avoid this unpleasent behaviour, we implement 'block-based' STA. Under this formulation, * only the worst case values are kept at each node in the circuit. While this is more * pessimistic (any path passing through a node is now viewed as having the worst case delay * of any path through that node), it greatly reduces the computational complexity, allowing * STA to be perfomed in linear time. * * Arrival Time, Required Time & Slack * ======================================= * When a Timing Analyzer performs timing analysis it is primarily calculating the following: * * - Arrival Time: The time a signal actually arrived at a particular point in the circuit. * * - Required Time: The time a signal should have arrived (was required) at a particular * to avoid violating a timing constraint. * * - Slack: The difference between required and arrival times. This indicates how close * a particular path/node is to violating its timing constraint. A positive * value indicates there is no violation, a negative value indicates there is * a violation. The magnitude of the slack indicates by how much the constraint * is passing/failing. A value of zero indicates that the constraint is met * exactly. * * * Calculating Arrival & Required Times * ====================================== * It is also useful to define the following collections of timing graph nodes: * - Primary Inputs (PIs): circuit external input pins, Flip-Flop Q pins * - Primary Outputs (POs): circuit external output pins, Flip-Flop D pins * Note that in the timing graph PIs have no fan-in, and POs have no fan-out. * * The arrival and required times are calculated at every node in the timing graph by walking * the timing graph in either a 'forward' or 'backward' direction. The following provide a * high-level description of the process. * * On the initial (forward) traversal, the graph is walked from PIs to POs to calculate arrival * time, performing the following: * 1) Initialize the arrival time of all PIs based on constraints (typically zero in the * simplest case) * 2) Add the delay of each edge to the arrival time of the edge's driving node to * to calculate the edge arrival time. * 3) At each downstream node calculate the max (setup) or min (hold) of all input * edge arrival times, and store it as the node arrival time. * 4) Repeat (2)-(3) until all nodes have valid arrival times. * * On the second (backward) traversal, the graph is walked in reverse from POs to PIs, performing * the following: * 1) Initialize the required times of all POs based on constraints (typically target * clock period for setup analysis) * 2) Subtract the delay of each edge to the required time of the edge's sink node to * to calculate the edge required time. * 3) At each upstream node calculate the min (setup) or max (hold) of all input * edge required times, and store it as the node required time. * 4) Repeat (2)-(3) until all nodes have valid required times. * * Clock Skew * ============ * In a real system the clocks which launch signals at the PIs and capture them at POs may not * all arrive at the same instance in time. This difference is known as 'skew'. * * Skew can be modled by adjusting the initialized PI arrival times to reflect when the clock * signal actually reaches the node. Similarily the PO required times can also be adjusted. * * Multi-clock Analysis * ====================== * The previous discussion has focused primarily on single-clock STA. In a multi-clock analysis * transfers between clock domains need to be handled (e.g. if the launch and capture clocks are * different). This is typically handled by identifying the worst-case alignment between all pairs * of clocks. This worst case value then becomes the constraint between the two clocks. * * To perform a multi-clock analysis the paths between different clocks need to be considered with * the identified constraint applied. This can be handled in two ways either: * a) Performing multiple single-clock analysis passes (one for each pair of clocks), or * b) Perform a single analysis but track multiple arrival/required times (a unique one for * each clock). * * Approach (b) turns out to be more efficient in practice, since it only requires a single traversal * of the timing graph. The combined values {clock, arrival time, required time} (and potentially other * info) are typically combined into a single 'Tag'. As a result there may be multiple tags stored * at each node in the timing graph. * */ /* * XXX TODO: these features haven't yet been implemented! * * Derating & Pesimism Reduction Techniques * ========================================== * * Unlike the previous discussion (which assumed constant delay values), in reality circuit delays * varry based on a variety of different parameters. To generate a correct (i.e. pessimistic and not * optimistic) analysis this means we must often choose a highly pessemistic value for this single * delay. In order to recovering some of this pessimism requires modeling more details of the system. * * Slew & Rise/Fall * ------------------ * Two of the key parameters that the single delay model does not account for are the impact of: * - Signals 'slew rate' (e.g. signal transition time from low to high), which can effect * the delay through a logic gate * - Signal direction (i.e. is a logic gate's output rising or falling). In CMOS * technologies different transitors of different types are activated depending on the * direction of the output signal (e.g. NMOS pull-down vs PMOS pull-up) * * Derating * ---------- * Another challenge in modern CMOS technologies is the presence of On-Chip Variation (OCV), * identically design structures (e.g. transistors, wires) may have different performance * due to manufacturing variation. To capture this behaviour one approach is to apply a * derate to delays on different paths in the circuit. * * In the typical approach applies incrementally more advanced derating, focusing firstly * on the most significant sources of variation. A typical progressing is to apply derating to: * 1) Clock Path * Since clocks often span large portions of the chip they can be subject to large * variation. To ensure a pessemistic analysis an late (early) derate is applied to * clock launch paths, and a early (launch) derate to clock capture paths for a setup * (hold) analysis. * * 2) Data Path * Early (late) derates can also be applied to data paths to account for their variation * during setup (hold) analysis. * Note that data paths tend to be more localized to clock networks so the impact of * OCV tends to be smaller. * * The simplest form of derating is a fixed derate applied to every delay, this can be extended * to different delays for different types of circuit elements (wires vs cells, individual cells * etc.). * * It turns out that fixed derates are overly pessemistic, since it is unlikely (particularliy on * long paths) that random variation will always go in one direction. Improved forms of derating * take into account the length (depth) of a path, often using a (user specified) table of derates * which falls off (derates less) along deeper paths. It is also possible for the derate to take * into account the physical locality/spread of a path. * * Common Clock Pessimism Removal (CCPR) * --------------------------------------- * Note: Names for this vary, including: Clock Reconvergence Pessimism Removal (CRPR), * Common Path Pessimism Removal (CPPR), and likely others. * * Derating can also introduce pessimism when applied to clock networks if the launch and * capture paths share some common portion of the clock network. Specifically, using * early/late derates on the launch/capture paths of a clock network may model a scenario * which is physically impossible to occur: the shared portion of the clock path cannot * be both early and late at the same time. * * CCPR does not directly remove this effect, but instead calculates a 'credit' which is * added back to the final path to counter-act this extra pessimism. */ #include <vector> #include "timing_graph_fwd.hpp" #include "timing_constraints_fwd.hpp" #include "analysis_types.hpp" /* * TimingAnalyzer represents a interface class for all timing analyzers * * NOTE: Mix-in Classes * ==================== * The TimingAnalyzer class hierarchy uses 'mix-in classes' to separate * the mechanics of performing a traversal of a timing graph (implemented by * TimingAnalyzer sub-classes) from the detailed operations required by * the different types of analysis (e.g. Setup, Hold) which could be performed. * * In a mix-in heirarchy, the mix-in type (in this scenario the AnalysisType * template parameter) is inherited from; mixing it into the current class. * [This particular pattern is the Curriosly Recurring Template Pattern, or CRTP]. * This gives us static (i.e. resolved at compile time) polymorphism, allowing * the compiler to fully inline (and optimize) the operations defined in the * mixin class. This yeilds a noticable (~17%) run-time improvement, compared * to no inlining. */ template<class AnalysisType, class DelayCalcType> class TimingAnalyzer : public AnalysisType { public: //The type of the delay calculator this analyzer uses typedef DelayCalcType delay_calculator_type; //The type of analysis this analyzer performs typedef AnalysisType analysis_type; virtual ~TimingAnalyzer() {}; //Calculate timing information (i.e. arrival & required times) virtual void calculate_timing() = 0; //Clear any old timing values calculated virtual void reset_timing() = 0; //Return the current delay calculator virtual const DelayCalcType& delay_calculator() = 0; //Return performance profiling data virtual std::map<std::string, double> profiling_data() = 0; }; <|endoftext|>
<commit_before>/* * 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 * * 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. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <vector> #include "cql3/query_options.hh" #include "cql3/statements/bound.hh" #include "cql3/restrictions/restrictions.hh" #include "cql3/restrictions/restriction.hh" #include "cql3/restrictions/abstract_restriction.hh" #include "types.hh" #include "query-request.hh" #include "core/shared_ptr.hh" namespace cql3 { namespace restrictions { /** * A set of restrictions on a primary key part (partition key or clustering key). * * What was in AbstractPrimaryKeyRestrictions was moved here (In pre 1.8 Java interfaces could not have default * implementations of methods). */ template<typename ValueType> struct range_type_for; template<> struct range_type_for<partition_key> : public std::remove_reference<dht::partition_range> {}; template<> struct range_type_for<clustering_key_prefix> : public std::remove_reference<query::clustering_range> {}; template<typename ValueType> class primary_key_restrictions: public abstract_restriction, public restrictions, public enable_shared_from_this<primary_key_restrictions<ValueType>> { public: typedef typename range_type_for<ValueType>::type bounds_range_type; virtual ::shared_ptr<primary_key_restrictions<ValueType>> merge_to(schema_ptr, ::shared_ptr<restriction> restriction) { merge_with(restriction); return this->shared_from_this(); } virtual std::vector<ValueType> values_as_keys(const query_options& options) const = 0; virtual std::vector<bounds_range_type> bounds_ranges(const query_options& options) const = 0; using restrictions::uses_function; using restrictions::has_supporting_index; bool empty() const override { return get_column_defs().empty(); } uint32_t size() const override { return uint32_t(get_column_defs().size()); } bool has_unrestricted_components(const schema& schema) const; virtual bool needs_filtering(const schema& schema) const; }; template<> inline bool primary_key_restrictions<partition_key>::has_unrestricted_components(const schema& schema) const { return size() < schema.partition_key_size(); } template<> inline bool primary_key_restrictions<clustering_key>::has_unrestricted_components(const schema& schema) const { return size() < schema.clustering_key_size(); } template<> inline bool primary_key_restrictions<partition_key>::needs_filtering(const schema& schema) const { return !empty() && !is_on_token() && (has_unrestricted_components(schema) || is_contains() || is_slice()); } template<> inline bool primary_key_restrictions<clustering_key>::needs_filtering(const schema& schema) const { // Currently only overloaded single_column_primary_key_restrictions will require ALLOW FILTERING return false; } } } <commit_msg>cql3: make primary key restrictions' values unambiguous<commit_after>/* * 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 * * 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. */ /* * Copyright (C) 2015 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla 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. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include <vector> #include "cql3/query_options.hh" #include "cql3/statements/bound.hh" #include "cql3/restrictions/restrictions.hh" #include "cql3/restrictions/restriction.hh" #include "cql3/restrictions/abstract_restriction.hh" #include "types.hh" #include "query-request.hh" #include "core/shared_ptr.hh" namespace cql3 { namespace restrictions { /** * A set of restrictions on a primary key part (partition key or clustering key). * * What was in AbstractPrimaryKeyRestrictions was moved here (In pre 1.8 Java interfaces could not have default * implementations of methods). */ template<typename ValueType> struct range_type_for; template<> struct range_type_for<partition_key> : public std::remove_reference<dht::partition_range> {}; template<> struct range_type_for<clustering_key_prefix> : public std::remove_reference<query::clustering_range> {}; template<typename ValueType> class primary_key_restrictions: public abstract_restriction, public restrictions, public enable_shared_from_this<primary_key_restrictions<ValueType>> { public: typedef typename range_type_for<ValueType>::type bounds_range_type; virtual ::shared_ptr<primary_key_restrictions<ValueType>> merge_to(schema_ptr, ::shared_ptr<restriction> restriction) { merge_with(restriction); return this->shared_from_this(); } virtual std::vector<ValueType> values_as_keys(const query_options& options) const = 0; virtual std::vector<bounds_range_type> bounds_ranges(const query_options& options) const = 0; using restrictions::uses_function; using restrictions::has_supporting_index; using restrictions::values; bool empty() const override { return get_column_defs().empty(); } uint32_t size() const override { return uint32_t(get_column_defs().size()); } bool has_unrestricted_components(const schema& schema) const; virtual bool needs_filtering(const schema& schema) const; }; template<> inline bool primary_key_restrictions<partition_key>::has_unrestricted_components(const schema& schema) const { return size() < schema.partition_key_size(); } template<> inline bool primary_key_restrictions<clustering_key>::has_unrestricted_components(const schema& schema) const { return size() < schema.clustering_key_size(); } template<> inline bool primary_key_restrictions<partition_key>::needs_filtering(const schema& schema) const { return !empty() && !is_on_token() && (has_unrestricted_components(schema) || is_contains() || is_slice()); } template<> inline bool primary_key_restrictions<clustering_key>::needs_filtering(const schema& schema) const { // Currently only overloaded single_column_primary_key_restrictions will require ALLOW FILTERING return false; } } } <|endoftext|>
<commit_before>/* * CPatcher.cpp * * Created on: 19.07.2009 * Author: gerstrong */ #include "CPatcher.h" #include <dirent.h> #include <string.h> #include <fstream> #include "../FindFile.h" #include "../StringUtils.h" CPatcher::CPatcher(int episode, int version,unsigned char *data, const std::string& datadir) { m_episode = episode; m_version = version; m_data = data; m_datadirectory = datadir; } CPatcher::~CPatcher() {} void CPatcher::patchMemory() { if(!loadPatchfile()) return; // If the file was found and read into the m_TextList, // then read out of the list the patch commands and apply them to the // Exe-file data m_data // TODO: Extend this part further with more commands while(!m_TextList.empty()) { std::string line = *m_TextList.begin(); if(strCaseStartsWith(line,"\%version")) { std::string verstring = line.substr(strlen("\%version")); if((stringcaseequal(verstring,"1.31") && m_version == 131 ) || (stringcaseequal(verstring,"1.1") && m_version == 110 ) || stringcaseequal(verstring,"ALL")) { while(!m_TextList.empty()) { // Get the next line line = *m_TextList.begin(); // Now we really start to process the commands if( strCaseStartsWith(line,"\%patchfile") ) { size_t offset = 0; std::string patch_file_name; std::string newbuf = line.substr(strlen("\%patchfile")); size_t p = newbuf.find(' '); if(p != std::string::npos) { sscanf(newbuf.substr(0,p).c_str(), "%lx", &offset); // Only hexadecimal numbers supported patch_file_name = newbuf.substr(p+1); patchMemfromFile("data/" + m_datadirectory + "/" + patch_file_name,offset); } } if(!m_TextList.empty()) { m_TextList.pop_front(); } } } } if(!m_TextList.empty()) { m_TextList.pop_front(); } } } bool CPatcher::loadPatchfile() { std::string fullfname = GetFullFileName("data/" + m_datadirectory); if(fullfname.size() == 0) return false; // Detect the patchfile DIR *dir = opendir(Utf8ToSystemNative(fullfname).c_str()); bool ret = false; if(dir) { struct dirent *dp; while( ( dp = readdir(dir) ) ) { if(strstr(dp->d_name,".pat")) { // The file was found! now read it into the memory! std::ifstream Patchfile; OpenGameFileR(Patchfile, dp->d_name); while(!Patchfile.eof()) { char buf[256]; Patchfile.getline(buf,sizeof(buf)); fix_markend(buf); m_TextList.push_back(buf); } Patchfile.close(); ret = true; break; } } } closedir(dir); return ret; } void CPatcher::patchMemfromFile(const std::string& patch_file_name, int offset) { unsigned char *buf_to_patch; unsigned char byte; std::ifstream Patchfile; OpenGameFileR(Patchfile, patch_file_name, std::ios::binary); if(!Patchfile) return; buf_to_patch = m_data + offset; // TODO: Add a routine which checks the sizes of the file. long counter = 0; while(!Patchfile.eof()) { byte = (unsigned char) Patchfile.get(); memcpy(buf_to_patch+counter,&byte,1); // one byte every time ;-) counter++; } Patchfile.close(); } <commit_msg>Bug fix CPatcher Class for Mods, especially.<commit_after>/* * CPatcher.cpp * * Created on: 19.07.2009 * Author: gerstrong */ #include "CPatcher.h" #include <dirent.h> #include <string.h> #include <fstream> #include "../FindFile.h" #include "../StringUtils.h" #include "../CLogFile.h" CPatcher::CPatcher(int episode, int version,unsigned char *data, const std::string& datadir) { m_episode = episode; m_version = version; m_data = data; m_datadirectory = datadir; } CPatcher::~CPatcher() {} void CPatcher::patchMemory() { if(!loadPatchfile()) return; // If the file was found and read into the m_TextList, // then read out of the list the patch commands and apply them to the // Exe-file data m_data // TODO: Extend this part further with more commands while(!m_TextList.empty()) { std::string line = *m_TextList.begin(); if(strCaseStartsWith(line,"\%version")) { std::string verstring = line.substr(strlen("\%version ")); if((strCaseStartsWith(verstring,"1.31") && m_version == 131 ) || (strCaseStartsWith(verstring,"1.1") && m_version == 110 ) || strCaseStartsWith(verstring,"ALL")) { while(!m_TextList.empty()) { // Get the next line line = *m_TextList.begin(); // Now we really start to process the commands if( strCaseStartsWith(line,"\%patchfile") ) { size_t offset = 0; std::string patch_file_name; std::string newbuf = line.substr(strlen("\%patchfile")); size_t p = newbuf.find(' '); if(p != std::string::npos) { char temp[256]; sscanf(newbuf.c_str(), "%lx %s", &offset, temp); // Only hexadecimal numbers supported patch_file_name.append(temp); patchMemfromFile("data/" + m_datadirectory + "/" + patch_file_name,offset); } } if(!m_TextList.empty()) { m_TextList.pop_front(); } } } } if(!m_TextList.empty()) { m_TextList.pop_front(); } } } struct PatchListFiller { std::set<std::string> list; bool operator() (const std::string& filename) { std::string ext = GetFileExtension(filename); if (stringcaseequal(ext, "pat")) list.insert(filename); return true; } }; bool CPatcher::loadPatchfile() { std::string path = "data/" + m_datadirectory; //Get the list of ".pat" files PatchListFiller patchlist; FindFiles(patchlist, path, false, FM_REG); // Nothing to play, just quit if (!patchlist.list.size()) return false; if (patchlist.list.size() > 1) g_pLogFile->textOut(PURPLE,"Multiple Patch are not yet supported! Please remove a file. Taking one File.<br>"); while(!patchlist.list.empty()) { std::string buf = *patchlist.list.begin(); std::ifstream Patchfile; OpenGameFileR(Patchfile, buf); while(!Patchfile.eof()) { char buf[256]; Patchfile.getline(buf, sizeof(buf)); fix_markend(buf); m_TextList.push_back(buf); } Patchfile.close(); patchlist.list.clear(); } return true; } void CPatcher::patchMemfromFile(const std::string& patch_file_name, int offset) { unsigned char *buf_to_patch; unsigned char byte; std::ifstream Patchfile; OpenGameFileR(Patchfile, patch_file_name, std::ios::binary); if(!Patchfile) return; buf_to_patch = m_data + offset; // TODO: Add a routine which checks the sizes of the file. long counter = 0; while(!Patchfile.eof()) { byte = (unsigned char) Patchfile.get(); memcpy(buf_to_patch+counter,&byte,1); // one byte every time ;-) counter++; } Patchfile.close(); } <|endoftext|>
<commit_before><commit_msg>Fix NULL_RETURN defect found by Coverity.<commit_after><|endoftext|>
<commit_before>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/event/rendering/shader-impl.h> // Dali::Internal::Shader // INTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> #include <dali/public-api/shader-effects/shader-effect.h> // Dali::ShaderEffect::GeometryHints // TODO: MESH_REWORK REMOVE #include <dali/devel-api/rendering/shader.h> // Dali::Shader #include <dali/devel-api/scripting/scripting.h> #include <dali/internal/event/common/object-impl-helper.h> // Dali::Internal::ObjectHelper #include <dali/internal/event/common/property-helper.h> // DALI_PROPERTY_TABLE_BEGIN, DALI_PROPERTY, DALI_PROPERTY_TABLE_END #include <dali/internal/event/common/thread-local-storage.h> #include <dali/internal/event/effects/shader-factory.h> #include <dali/internal/event/resources/resource-ticket.h> #include <dali/internal/update/manager/update-manager.h> namespace Dali { namespace Internal { namespace { /** * |name |type |writable|animatable|constraint-input|enum for index-checking| */ DALI_PROPERTY_TABLE_BEGIN DALI_PROPERTY( "program", MAP, true, false, false, Dali::Shader::Property::PROGRAM ) DALI_PROPERTY_TABLE_END( DEFAULT_ACTOR_PROPERTY_START_INDEX ) const ObjectImplHelper<DEFAULT_PROPERTY_COUNT> SHADER_IMPL = { DEFAULT_PROPERTY_DETAILS }; Dali::Scripting::StringEnum ShaderHintsTable[] = { { "HINT_NONE", Dali::Shader::HINT_NONE}, { "HINT_OUTPUT_IS_TRANSPARENT", Dali::Shader::HINT_OUTPUT_IS_TRANSPARENT}, { "HINT_MODIFIES_GEOMETRY", Dali::Shader::HINT_MODIFIES_GEOMETRY} }; const unsigned int ShaderHintsTableSize = sizeof( ShaderHintsTable ) / sizeof( ShaderHintsTable[0] ); BaseHandle Create() { return Dali::BaseHandle(); } TypeRegistration mType( typeid( Dali::Shader ), typeid( Dali::Handle ), Create ); #define TOKEN_STRING(x) (#x) void AppendString(std::string& to, const std::string& append) { if(to.size()) { to += ","; } to += append; } Property::Value HintString(const Dali::Shader::ShaderHints& hints) { std::string s; if(hints == Dali::Shader::HINT_NONE) { s = "HINT_NONE"; } if(hints & Dali::Shader::HINT_OUTPUT_IS_TRANSPARENT) { AppendString(s, "HINT_OUTPUT_IS_TRANSPARENT"); } if(hints & Dali::Shader::HINT_MODIFIES_GEOMETRY) { AppendString(s, "HINT_MODIFIES_GEOMETRY"); } return Property::Value(s); } } // unnamed namespace ShaderPtr Shader::New( const std::string& vertexShader, const std::string& fragmentShader, Dali::Shader::ShaderHints hints ) { ShaderPtr shader( new Shader() ); shader->Initialize( vertexShader, fragmentShader, hints ); return shader; } const SceneGraph::Shader* Shader::GetShaderSceneObject() const { return mSceneObject; } SceneGraph::Shader* Shader::GetShaderSceneObject() { return mSceneObject; } unsigned int Shader::GetDefaultPropertyCount() const { return SHADER_IMPL.GetDefaultPropertyCount(); } void Shader::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const { SHADER_IMPL.GetDefaultPropertyIndices( indices ); } const char* Shader::GetDefaultPropertyName(Property::Index index) const { return SHADER_IMPL.GetDefaultPropertyName( index ); } Property::Index Shader::GetDefaultPropertyIndex( const std::string& name ) const { return SHADER_IMPL.GetDefaultPropertyIndex( name ); } bool Shader::IsDefaultPropertyWritable( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyWritable( index ); } bool Shader::IsDefaultPropertyAnimatable( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyAnimatable( index ); } bool Shader::IsDefaultPropertyAConstraintInput( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyAConstraintInput( index ); } Property::Type Shader::GetDefaultPropertyType( Property::Index index ) const { return SHADER_IMPL.GetDefaultPropertyType( index ); } void Shader::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue ) { switch(index) { case Dali::Shader::Property::PROGRAM: { if( propertyValue.GetType() == Property::MAP ) { Dali::Property::Map* map = propertyValue.GetMap(); std::string vertex; std::string fragment; Dali::Shader::ShaderHints hints(Dali::Shader::HINT_NONE); if( Property::Value* value = map->Find("vertex") ) { vertex = value->Get<std::string>(); } if( Property::Value* value = map->Find("fragment") ) { fragment = value->Get<std::string>(); } if( Property::Value* value = map->Find("hints") ) { static_cast<void>( // ignore return Scripting::GetEnumeration< Dali::Shader::ShaderHints >(value->Get<std::string>().c_str(), ShaderHintsTable, ShaderHintsTableSize, hints) ); } Initialize(vertex, fragment, hints ); } else { DALI_LOG_WARNING( "Shader program property should be a map\n" ); } break; } } } void Shader::SetSceneGraphProperty( Property::Index index, const PropertyMetadata& entry, const Property::Value& value ) { SHADER_IMPL.SetSceneGraphProperty( GetEventThreadServices(), this, index, entry, value ); OnPropertySet(index, value); } Property::Value Shader::GetDefaultProperty( Property::Index index ) const { Property::Value value; switch(index) { case Dali::Shader::Property::PROGRAM: { Dali::Property::Map map; if( mShaderData ) { map["vertex"] = Property::Value(mShaderData->GetVertexShader()); map["fragment"] = Property::Value(mShaderData->GetFragmentShader()); map["hints"] = HintString(mShaderData->GetHints()); } value = map; break; } } return value; } const SceneGraph::PropertyOwner* Shader::GetPropertyOwner() const { return mSceneObject; } const SceneGraph::PropertyOwner* Shader::GetSceneObject() const { return mSceneObject; } const SceneGraph::PropertyBase* Shader::GetSceneObjectAnimatableProperty( Property::Index index ) const { DALI_ASSERT_ALWAYS( IsPropertyAnimatable( index ) && "Property is not animatable" ); const SceneGraph::PropertyBase* property = NULL; property = SHADER_IMPL.GetRegisteredSceneGraphProperty( this, &Shader::FindAnimatableProperty, &Shader::FindCustomProperty, index ); if( property == NULL && index < DEFAULT_PROPERTY_MAX_COUNT ) { DALI_ASSERT_ALWAYS( 0 && "Property is not animatable" ); } return property; } const PropertyInputImpl* Shader::GetSceneObjectInputProperty( Property::Index index ) const { PropertyMetadata* property = NULL; if(index >= PROPERTY_CUSTOM_START_INDEX ) { property = FindCustomProperty( index ); } else { property = FindAnimatableProperty( index ); } DALI_ASSERT_ALWAYS( property && "property index is invalid" ); return property->GetSceneGraphProperty(); } int Shader::GetPropertyComponentIndex( Property::Index index ) const { return Property::INVALID_COMPONENT_INDEX; } Shader::Shader() : mSceneObject( NULL ), mShaderData( NULL ) { } void Shader::Initialize( const std::string& vertexSource, const std::string& fragmentSource, Dali::Shader::ShaderHints hints ) { EventThreadServices& eventThreadServices = GetEventThreadServices(); SceneGraph::UpdateManager& updateManager = eventThreadServices.GetUpdateManager(); mSceneObject = new SceneGraph::Shader( hints ); // Add to update manager AddShaderMessage( updateManager, *mSceneObject ); // Try to load a precompiled shader binary for the source pair: ThreadLocalStorage& tls = ThreadLocalStorage::Get(); ShaderFactory& shaderFactory = tls.GetShaderFactory(); size_t shaderHash; mShaderData = shaderFactory.Load( vertexSource, fragmentSource, hints, shaderHash ); // Add shader program to scene-object using a message to the UpdateManager SetShaderProgramMessage( updateManager, *mSceneObject, mShaderData, (hints & Dali::Shader::HINT_MODIFIES_GEOMETRY) != 0x0 ); eventThreadServices.RegisterObject( this ); } Shader::~Shader() { if( EventThreadServices::IsCoreRunning() ) { EventThreadServices& eventThreadServices = GetEventThreadServices(); SceneGraph::UpdateManager& updateManager = eventThreadServices.GetUpdateManager(); RemoveShaderMessage( updateManager, *mSceneObject); eventThreadServices.UnregisterObject( this ); } } } // namespace Internal } // namespace Dali <commit_msg>Fix Svace issue<commit_after>/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/event/rendering/shader-impl.h> // Dali::Internal::Shader // INTERNAL INCLUDES #include <dali/public-api/object/type-registry.h> #include <dali/public-api/shader-effects/shader-effect.h> // Dali::ShaderEffect::GeometryHints // TODO: MESH_REWORK REMOVE #include <dali/devel-api/rendering/shader.h> // Dali::Shader #include <dali/devel-api/scripting/scripting.h> #include <dali/internal/event/common/object-impl-helper.h> // Dali::Internal::ObjectHelper #include <dali/internal/event/common/property-helper.h> // DALI_PROPERTY_TABLE_BEGIN, DALI_PROPERTY, DALI_PROPERTY_TABLE_END #include <dali/internal/event/common/thread-local-storage.h> #include <dali/internal/event/effects/shader-factory.h> #include <dali/internal/event/resources/resource-ticket.h> #include <dali/internal/update/manager/update-manager.h> namespace Dali { namespace Internal { namespace { /** * |name |type |writable|animatable|constraint-input|enum for index-checking| */ DALI_PROPERTY_TABLE_BEGIN DALI_PROPERTY( "program", MAP, true, false, false, Dali::Shader::Property::PROGRAM ) DALI_PROPERTY_TABLE_END( DEFAULT_ACTOR_PROPERTY_START_INDEX ) const ObjectImplHelper<DEFAULT_PROPERTY_COUNT> SHADER_IMPL = { DEFAULT_PROPERTY_DETAILS }; Dali::Scripting::StringEnum ShaderHintsTable[] = { { "HINT_NONE", Dali::Shader::HINT_NONE}, { "HINT_OUTPUT_IS_TRANSPARENT", Dali::Shader::HINT_OUTPUT_IS_TRANSPARENT}, { "HINT_MODIFIES_GEOMETRY", Dali::Shader::HINT_MODIFIES_GEOMETRY} }; const unsigned int ShaderHintsTableSize = sizeof( ShaderHintsTable ) / sizeof( ShaderHintsTable[0] ); BaseHandle Create() { return Dali::BaseHandle(); } TypeRegistration mType( typeid( Dali::Shader ), typeid( Dali::Handle ), Create ); #define TOKEN_STRING(x) (#x) void AppendString(std::string& to, const std::string& append) { if(to.size()) { to += ","; } to += append; } Property::Value HintString(const Dali::Shader::ShaderHints& hints) { std::string s; if(hints == Dali::Shader::HINT_NONE) { s = "HINT_NONE"; } if(hints & Dali::Shader::HINT_OUTPUT_IS_TRANSPARENT) { AppendString(s, "HINT_OUTPUT_IS_TRANSPARENT"); } if(hints & Dali::Shader::HINT_MODIFIES_GEOMETRY) { AppendString(s, "HINT_MODIFIES_GEOMETRY"); } return Property::Value(s); } } // unnamed namespace ShaderPtr Shader::New( const std::string& vertexShader, const std::string& fragmentShader, Dali::Shader::ShaderHints hints ) { ShaderPtr shader( new Shader() ); shader->Initialize( vertexShader, fragmentShader, hints ); return shader; } const SceneGraph::Shader* Shader::GetShaderSceneObject() const { return mSceneObject; } SceneGraph::Shader* Shader::GetShaderSceneObject() { return mSceneObject; } unsigned int Shader::GetDefaultPropertyCount() const { return SHADER_IMPL.GetDefaultPropertyCount(); } void Shader::GetDefaultPropertyIndices( Property::IndexContainer& indices ) const { SHADER_IMPL.GetDefaultPropertyIndices( indices ); } const char* Shader::GetDefaultPropertyName(Property::Index index) const { return SHADER_IMPL.GetDefaultPropertyName( index ); } Property::Index Shader::GetDefaultPropertyIndex( const std::string& name ) const { return SHADER_IMPL.GetDefaultPropertyIndex( name ); } bool Shader::IsDefaultPropertyWritable( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyWritable( index ); } bool Shader::IsDefaultPropertyAnimatable( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyAnimatable( index ); } bool Shader::IsDefaultPropertyAConstraintInput( Property::Index index ) const { return SHADER_IMPL.IsDefaultPropertyAConstraintInput( index ); } Property::Type Shader::GetDefaultPropertyType( Property::Index index ) const { return SHADER_IMPL.GetDefaultPropertyType( index ); } void Shader::SetDefaultProperty( Property::Index index, const Property::Value& propertyValue ) { switch(index) { case Dali::Shader::Property::PROGRAM: { if( propertyValue.GetType() == Property::MAP ) { Dali::Property::Map* map = propertyValue.GetMap(); if( map ) { std::string vertex; std::string fragment; Dali::Shader::ShaderHints hints(Dali::Shader::HINT_NONE); if( Property::Value* value = map->Find("vertex") ) { vertex = value->Get<std::string>(); } if( Property::Value* value = map->Find("fragment") ) { fragment = value->Get<std::string>(); } if( Property::Value* value = map->Find("hints") ) { static_cast<void>( // ignore return Scripting::GetEnumeration< Dali::Shader::ShaderHints >(value->Get<std::string>().c_str(), ShaderHintsTable, ShaderHintsTableSize, hints) ); } Initialize(vertex, fragment, hints ); } } else { DALI_LOG_WARNING( "Shader program property should be a map\n" ); } break; } } } void Shader::SetSceneGraphProperty( Property::Index index, const PropertyMetadata& entry, const Property::Value& value ) { SHADER_IMPL.SetSceneGraphProperty( GetEventThreadServices(), this, index, entry, value ); OnPropertySet(index, value); } Property::Value Shader::GetDefaultProperty( Property::Index index ) const { Property::Value value; switch(index) { case Dali::Shader::Property::PROGRAM: { Dali::Property::Map map; if( mShaderData ) { map["vertex"] = Property::Value(mShaderData->GetVertexShader()); map["fragment"] = Property::Value(mShaderData->GetFragmentShader()); map["hints"] = HintString(mShaderData->GetHints()); } value = map; break; } } return value; } const SceneGraph::PropertyOwner* Shader::GetPropertyOwner() const { return mSceneObject; } const SceneGraph::PropertyOwner* Shader::GetSceneObject() const { return mSceneObject; } const SceneGraph::PropertyBase* Shader::GetSceneObjectAnimatableProperty( Property::Index index ) const { DALI_ASSERT_ALWAYS( IsPropertyAnimatable( index ) && "Property is not animatable" ); const SceneGraph::PropertyBase* property = NULL; property = SHADER_IMPL.GetRegisteredSceneGraphProperty( this, &Shader::FindAnimatableProperty, &Shader::FindCustomProperty, index ); if( property == NULL && index < DEFAULT_PROPERTY_MAX_COUNT ) { DALI_ASSERT_ALWAYS( 0 && "Property is not animatable" ); } return property; } const PropertyInputImpl* Shader::GetSceneObjectInputProperty( Property::Index index ) const { PropertyMetadata* property = NULL; if(index >= PROPERTY_CUSTOM_START_INDEX ) { property = FindCustomProperty( index ); } else { property = FindAnimatableProperty( index ); } DALI_ASSERT_ALWAYS( property && "property index is invalid" ); return property->GetSceneGraphProperty(); } int Shader::GetPropertyComponentIndex( Property::Index index ) const { return Property::INVALID_COMPONENT_INDEX; } Shader::Shader() : mSceneObject( NULL ), mShaderData( NULL ) { } void Shader::Initialize( const std::string& vertexSource, const std::string& fragmentSource, Dali::Shader::ShaderHints hints ) { EventThreadServices& eventThreadServices = GetEventThreadServices(); SceneGraph::UpdateManager& updateManager = eventThreadServices.GetUpdateManager(); mSceneObject = new SceneGraph::Shader( hints ); // Add to update manager AddShaderMessage( updateManager, *mSceneObject ); // Try to load a precompiled shader binary for the source pair: ThreadLocalStorage& tls = ThreadLocalStorage::Get(); ShaderFactory& shaderFactory = tls.GetShaderFactory(); size_t shaderHash; mShaderData = shaderFactory.Load( vertexSource, fragmentSource, hints, shaderHash ); // Add shader program to scene-object using a message to the UpdateManager SetShaderProgramMessage( updateManager, *mSceneObject, mShaderData, (hints & Dali::Shader::HINT_MODIFIES_GEOMETRY) != 0x0 ); eventThreadServices.RegisterObject( this ); } Shader::~Shader() { if( EventThreadServices::IsCoreRunning() ) { EventThreadServices& eventThreadServices = GetEventThreadServices(); SceneGraph::UpdateManager& updateManager = eventThreadServices.GetUpdateManager(); RemoveShaderMessage( updateManager, *mSceneObject); eventThreadServices.UnregisterObject( this ); } } } // namespace Internal } // namespace Dali <|endoftext|>
<commit_before>#include "Application.h" #include "Module.h" #include "ModuleScripting.h" #include "ModuleAudio.h" #include "ModuleCamera3D.h" #include "ModuleFileSystem.h" #include "ModuleGOManager.h" #include "ModuleInput.h" #include "ModuleSceneIntro.h" #include "ModuleLighting.h" #include "ModulePhysics3D.h" #include "ModuleRenderer3D.h" #include "ModuleResourceManager.h" #include "ModuleEditor.h" #include "ModuleWindow.h" #include "Time.h" #include "Random.h" #include "EventQueue.h" #include "Data.h" #include "Brofiler/include/Brofiler.h" #include "ComponentCar.h" using namespace std; Application::Application() { // Time controller time = new Time(); // Random rnd = new Random(); // EventQueue event_queue = new EventQueue(); // Modules window = new ModuleWindow("window"); resource_manager = new ModuleResourceManager("resource_manager"); input = new ModuleInput("input"); audio = new ModuleAudio("audio"); scene_intro = new ModuleSceneIntro("scene_intro"); renderer3D = new ModuleRenderer3D("renderer"); camera = new ModuleCamera3D("camera"); physics = new ModulePhysics3D("physics"); scripting = new ModuleScripting("scripting"); editor = new ModuleEditor("editor"); file_system = new ModuleFileSystem("file_system"); go_manager = new ModuleGOManager("go_manager"); lighting = new ModuleLighting("lighting"); //Globals g_Debug = new DebugDraw("debug_draw"); // Modules will Init() Start() and Update in this order // They will CleanUp() in reverse order // Main Modules AddModule(file_system); AddModule(resource_manager); AddModule(window); AddModule(input); AddModule(g_Debug); AddModule(scripting); AddModule(physics); AddModule(go_manager); AddModule(camera); AddModule(audio); AddModule(lighting); // Scenes AddModule(scene_intro); //Editor AddModule(editor); // Renderer last! AddModule(renderer3D); } Application::~Application() { delete rnd; delete event_queue; vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { delete (*i); ++i; } delete time; } bool Application::Init() { bool ret = true; //Load Configuration char* buffer = nullptr; if (App->file_system->Load("Configuration.json", &buffer) == 0) { LOG("Error while loading Configuration file"); //Create a new Configuration file if (buffer) delete[] buffer; Data root_node; root_node.AppendBool("start_in_game", false); vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { root_node.AppendJObject((*i)->GetName()); ++i; } size_t size = root_node.Serialize(&buffer); App->file_system->Save("Configuration.json", buffer, size); } Data config(buffer); delete[] buffer; // Game is initialized in PlayMode? if (config.GetBool("start_in_game")) { start_in_game = true; game_state = GAME_RUNNING; } // Call Init() in all modules vector<Module*>::iterator i = list_modules.begin(); while (i != list_modules.end() && ret == true) { ret = (*i)->Init(config.GetJObject((*i)->GetName())); ++i; } // After all Init calls we call Start() in all modules LOG("Application Start --------------"); i = list_modules.begin(); while(i != list_modules.end() && ret == true) { ret = (*i)->Start(); ++i; } capped_ms = 1000 / max_fps; //// Play all Components of every GameObject on the scene if (start_in_game) { time->Play(); for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) (*it)->OnPlay(); } return ret; } // --------------------------------------------- void Application::PrepareUpdate() { time->UpdateFrame(); } // --------------------------------------------- void Application::FinishUpdate() { event_queue->ProcessEvents(); if (want_to_load == true) { want_to_load = false; resource_manager->LoadSceneFromAssets(scene_to_load); } } void Application::LoadScene(const char* path) { if (want_to_load == false) { scene_to_load = (char*)path; want_to_load = true; } } void Application::OnStop() { for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) { (*it)->OnStop(); } } void Application::OnPlay() { for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) (*it)->OnPlay(); } void Application::RunGame() { //Save current scene only if the game was stopped if (game_state == GAME_STOP) go_manager->SaveSceneBeforeRunning(); game_state = GAME_RUNNING; time->Play(); OnPlay(); } void Application::PauseGame() { game_state = GAME_PAUSED; time->Pause(); for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) { (*it)->OnPause(); } } void Application::StopGame() { game_state = GAME_STOP; go_manager->LoadSceneBeforeRunning(); time->Stop(); OnStop(); } // Call PreUpdate, Update and PostUpdate on all modules update_status Application::Update() { BROFILER_FRAME("GameLoop") update_status ret = UPDATE_CONTINUE; PrepareUpdate(); vector<Module*>::iterator i = list_modules.begin(); while (i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->PreUpdate(); ++i; } i = list_modules.begin(); while(i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->Update(); ++i; } i = list_modules.begin(); while (i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->PostUpdate(); i++; } FinishUpdate(); return ret; } bool Application::CleanUp() { bool ret = true; vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend() && ret == true) { ret = (*i)->CleanUp(); ++i; } return ret; } void Application::SaveBeforeClosing() { Data root_node; char* buf; root_node.AppendBool("start_in_game", start_in_game); vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { (*i)->SaveBeforeClosing(root_node.AppendJObject((*i)->GetName())); ++i; } size_t size = root_node.Serialize(&buf); uint success = App->file_system->Save("Configuration.json", buf, size); if (success == 0) LOG("Configuration could not be saved before closing"); delete[] buf; } void Application::AddModule(Module* mod) { list_modules.push_back(mod); } void Application::OpenURL(const char* url) { ShellExecuteA(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); } void Application::SetMaxFPS(int max_fps) { this->max_fps = max_fps; if (max_fps == 0) this->max_fps = -1; capped_ms = 1000 / max_fps; } int Application::GetFPS() { return 60; //TODO: Update time with fps limit. } bool Application::ChangeGameState(GameStates new_state) { bool success = false; switch (new_state) { case GAME_STOP: if (game_state == GAME_RUNNING || game_state == GAME_PAUSED) { StopGame(); success = true; } break; case GAME_RUNNING: if (game_state == GAME_STOP || game_state == GAME_PAUSED) { RunGame(); success = true; } break; case GAME_PAUSED: if (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME) { PauseGame(); success = true; } break; case GAME_NEXT_FRAME: if(game_state == GAME_RUNNING || game_state == GAME_PAUSED) //TODO: Now this features is not available yet. Nothing happens in the game now. //NextFrameGame(); break; } return success; } ///Returns true if the game simulation has started. If the game is paused also returns true. bool Application::IsGameRunning() const { return (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME || game_state == GAME_PAUSED) ? true : false; } ///Returns true if the game is paused or in next frame mode. If the game is stop returns false. bool Application::IsGamePaused() const { return (game_state == GAME_PAUSED || game_state == GAME_NEXT_FRAME) ? true : false; } bool Application::StartInGame() const { return start_in_game; } <commit_msg>Scene load on Game Mode without Starting Audio Module<commit_after>#include "Application.h" #include "Module.h" #include "ModuleScripting.h" #include "ModuleAudio.h" #include "ModuleCamera3D.h" #include "ModuleFileSystem.h" #include "ModuleGOManager.h" #include "ModuleInput.h" #include "ModuleSceneIntro.h" #include "ModuleLighting.h" #include "ModulePhysics3D.h" #include "ModuleRenderer3D.h" #include "ModuleResourceManager.h" #include "ModuleEditor.h" #include "ModuleWindow.h" #include "Time.h" #include "Random.h" #include "EventQueue.h" #include "Data.h" #include "Brofiler/include/Brofiler.h" #include "ComponentCar.h" using namespace std; Application::Application() { // Time controller time = new Time(); // Random rnd = new Random(); // EventQueue event_queue = new EventQueue(); // Modules window = new ModuleWindow("window"); resource_manager = new ModuleResourceManager("resource_manager"); input = new ModuleInput("input"); audio = new ModuleAudio("audio"); scene_intro = new ModuleSceneIntro("scene_intro"); renderer3D = new ModuleRenderer3D("renderer"); camera = new ModuleCamera3D("camera"); physics = new ModulePhysics3D("physics"); scripting = new ModuleScripting("scripting"); editor = new ModuleEditor("editor"); file_system = new ModuleFileSystem("file_system"); go_manager = new ModuleGOManager("go_manager"); lighting = new ModuleLighting("lighting"); //Globals g_Debug = new DebugDraw("debug_draw"); // Modules will Init() Start() and Update in this order // They will CleanUp() in reverse order // Main Modules AddModule(file_system); AddModule(resource_manager); AddModule(window); AddModule(input); AddModule(g_Debug); AddModule(scripting); AddModule(physics); AddModule(audio); AddModule(go_manager); AddModule(camera); AddModule(lighting); // Scenes AddModule(scene_intro); //Editor AddModule(editor); // Renderer last! AddModule(renderer3D); } Application::~Application() { delete rnd; delete event_queue; vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { delete (*i); ++i; } delete time; } bool Application::Init() { bool ret = true; //Load Configuration char* buffer = nullptr; if (App->file_system->Load("Configuration.json", &buffer) == 0) { LOG("Error while loading Configuration file"); //Create a new Configuration file if (buffer) delete[] buffer; Data root_node; root_node.AppendBool("start_in_game", false); vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { root_node.AppendJObject((*i)->GetName()); ++i; } size_t size = root_node.Serialize(&buffer); App->file_system->Save("Configuration.json", buffer, size); } Data config(buffer); delete[] buffer; // Game is initialized in PlayMode? if (config.GetBool("start_in_game")) { start_in_game = true; game_state = GAME_RUNNING; } // Call Init() in all modules vector<Module*>::iterator i = list_modules.begin(); while (i != list_modules.end() && ret == true) { ret = (*i)->Init(config.GetJObject((*i)->GetName())); ++i; } // After all Init calls we call Start() in all modules LOG("Application Start --------------"); i = list_modules.begin(); while(i != list_modules.end() && ret == true) { ret = (*i)->Start(); ++i; } capped_ms = 1000 / max_fps; //// Play all Components of every GameObject on the scene if (start_in_game) { time->Play(); for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) (*it)->OnPlay(); } return ret; } // --------------------------------------------- void Application::PrepareUpdate() { time->UpdateFrame(); } // --------------------------------------------- void Application::FinishUpdate() { event_queue->ProcessEvents(); if (want_to_load == true) { want_to_load = false; resource_manager->LoadSceneFromAssets(scene_to_load); } } void Application::LoadScene(const char* path) { if (want_to_load == false) { scene_to_load = (char*)path; want_to_load = true; } } void Application::OnStop() { for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) { (*it)->OnStop(); } } void Application::OnPlay() { for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) (*it)->OnPlay(); } void Application::RunGame() { //Save current scene only if the game was stopped if (game_state == GAME_STOP) go_manager->SaveSceneBeforeRunning(); game_state = GAME_RUNNING; time->Play(); OnPlay(); } void Application::PauseGame() { game_state = GAME_PAUSED; time->Pause(); for (std::vector<Module*>::iterator it = list_modules.begin(); it != list_modules.end(); it++) { (*it)->OnPause(); } } void Application::StopGame() { game_state = GAME_STOP; go_manager->LoadSceneBeforeRunning(); time->Stop(); OnStop(); } // Call PreUpdate, Update and PostUpdate on all modules update_status Application::Update() { BROFILER_FRAME("GameLoop") update_status ret = UPDATE_CONTINUE; PrepareUpdate(); vector<Module*>::iterator i = list_modules.begin(); while (i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->PreUpdate(); ++i; } i = list_modules.begin(); while(i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->Update(); ++i; } i = list_modules.begin(); while (i != list_modules.end() && ret == UPDATE_CONTINUE) { ret = (*i)->PostUpdate(); i++; } FinishUpdate(); return ret; } bool Application::CleanUp() { bool ret = true; vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend() && ret == true) { ret = (*i)->CleanUp(); ++i; } return ret; } void Application::SaveBeforeClosing() { Data root_node; char* buf; root_node.AppendBool("start_in_game", start_in_game); vector<Module*>::reverse_iterator i = list_modules.rbegin(); while (i != list_modules.rend()) { (*i)->SaveBeforeClosing(root_node.AppendJObject((*i)->GetName())); ++i; } size_t size = root_node.Serialize(&buf); uint success = App->file_system->Save("Configuration.json", buf, size); if (success == 0) LOG("Configuration could not be saved before closing"); delete[] buf; } void Application::AddModule(Module* mod) { list_modules.push_back(mod); } void Application::OpenURL(const char* url) { ShellExecuteA(NULL, "open", url, NULL, NULL, SW_SHOWNORMAL); } void Application::SetMaxFPS(int max_fps) { this->max_fps = max_fps; if (max_fps == 0) this->max_fps = -1; capped_ms = 1000 / max_fps; } int Application::GetFPS() { return 60; //TODO: Update time with fps limit. } bool Application::ChangeGameState(GameStates new_state) { bool success = false; switch (new_state) { case GAME_STOP: if (game_state == GAME_RUNNING || game_state == GAME_PAUSED) { StopGame(); success = true; } break; case GAME_RUNNING: if (game_state == GAME_STOP || game_state == GAME_PAUSED) { RunGame(); success = true; } break; case GAME_PAUSED: if (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME) { PauseGame(); success = true; } break; case GAME_NEXT_FRAME: if(game_state == GAME_RUNNING || game_state == GAME_PAUSED) //TODO: Now this features is not available yet. Nothing happens in the game now. //NextFrameGame(); break; } return success; } ///Returns true if the game simulation has started. If the game is paused also returns true. bool Application::IsGameRunning() const { return (game_state == GAME_RUNNING || game_state == GAME_NEXT_FRAME || game_state == GAME_PAUSED) ? true : false; } ///Returns true if the game is paused or in next frame mode. If the game is stop returns false. bool Application::IsGamePaused() const { return (game_state == GAME_PAUSED || game_state == GAME_NEXT_FRAME) ? true : false; } bool Application::StartInGame() const { return start_in_game; } <|endoftext|>
<commit_before>#include <QPainter> #include <QTimer> #include "CommentLib.h" #include "AssassinWar.h" #include "MapLoader.h" AssassinWar::AssassinWar(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags), m_pRepaintTimer(NULL) { ui.setupUi(this); MapLoader mapLoader; QWidget* pMapWidget = mapLoader.LoadMap("./map/map1.ui"); mapLoader.LoadMapTerrain(*pMapWidget); m_pRepaintTimer = new QTimer(this); connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint())); m_pRepaintTimer->start(100); } AssassinWar::~AssassinWar() { m_pRepaintTimer->stop(); } void AssassinWar::paintEvent(QPaintEvent *PaintEvent) { static float a = 0.0f; if(60 < a) { a = 0.0f; } QPainter painter(this); painter.drawLine(++a, 0.0, 15.0, 25.0);// drawing code }<commit_msg>Signed-off-by: flymianmian <flymianmian@163.com><commit_after>#include <QPainter> #include <QTimer> #include "CommentLib.h" #include "AssassinWar.h" #include "MapLoader.h" AssassinWar::AssassinWar(QWidget *parent, Qt::WFlags flags) : QMainWindow(parent, flags), m_pRepaintTimer(NULL) { ui.setupUi(this); MapLoader mapLoader; QWidget* pMapWidget = mapLoader.LoadMap("./map/map1.ui"); mapLoader.LoadMapTerrain(*pMapWidget); m_pRepaintTimer = new QTimer(this); connect(m_pRepaintTimer, SIGNAL(timeout()), this, SLOT(repaint())); m_pRepaintTimer->start(250); } AssassinWar::~AssassinWar() { m_pRepaintTimer->stop(); } void AssassinWar::paintEvent(QPaintEvent *PaintEvent) { static float a = 0.0f; if(60 < a) { a = 0.0f; } QPainter painter(this); painter.drawLine(++a, 0.0, 15.0, 25.0);// drawing code }<|endoftext|>
<commit_before>#include<iostream> #include <vector> using namespace std; class Floor { protected: string name; int sizeSqFt; vector<string> features; public: }; <commit_msg>Updated room class<commit_after>#include<iostream> #include <vector> using namespace std; class Room { protected: string name; int sizeSqFt; vector<string> features; public: }; <|endoftext|>
<commit_before>// $Id$ // Category: geometry // // See the class description in the header file. #include "AliModulesCompositionMessenger.h" #include "AliModulesComposition.h" #include "AliGlobals.h" #include <G4UIdirectory.hh> #include <G4UIcmdWithAString.hh> #include <G4UIcmdWithoutParameter.hh> #include <G4UIcmdWithABool.hh> #include <G4UIcmdWithADoubleAndUnit.hh> AliModulesCompositionMessenger::AliModulesCompositionMessenger( AliModulesComposition* modulesComposition) : fModulesComposition(modulesComposition) { // fDirectory = new G4UIdirectory("/aliDet/"); fDirectory->SetGuidance("Detector construction control commands."); fSwitchOnCmd = new G4UIcmdWithAString("/aliDet/switchOn", this); fSwitchOnCmd->SetGuidance("Define the module to be built."); fSwitchOnCmd->SetGuidance("Available modules:"); G4String listAvailableDets = "NONE, ALL, "; listAvailableDets = listAvailableDets + modulesComposition->GetAvailableDetsListWithCommas(); fSwitchOnCmd->SetGuidance(listAvailableDets); fSwitchOnCmd->SetParameterName("module", false); fSwitchOnCmd->AvailableForStates(PreInit);; fSwitchOffCmd = new G4UIcmdWithAString("/aliDet/switchOff", this); fSwitchOffCmd->SetGuidance("Define the module not to be built."); fSwitchOffCmd->SetGuidance("Available modules:"); G4String listDetsNames = "ALL, "; listDetsNames = listDetsNames + modulesComposition->GetDetNamesListWithCommas(); fSwitchOffCmd->SetGuidance(listDetsNames); fSwitchOffCmd->SetParameterName("module", false); fSwitchOffCmd->AvailableForStates(PreInit);; fListCmd = new G4UIcmdWithoutParameter("/aliDet/list", this); fListCmd->SetGuidance("List the currently switched modules."); fListCmd ->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc); fListAvailableCmd = new G4UIcmdWithoutParameter("/aliDet/listAvailable", this); fListAvailableCmd->SetGuidance("List all available modules."); fListAvailableCmd ->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc); fFieldValueCmd = new G4UIcmdWithADoubleAndUnit("/aliDet/fieldValue", this); fFieldValueCmd->SetGuidance("Define magnetic field in Z direction."); fFieldValueCmd->SetParameterName("fieldValue", false, false); fFieldValueCmd->SetDefaultUnit("tesla"); fFieldValueCmd->SetUnitCategory("Magnetic flux density"); fFieldValueCmd->AvailableForStates(PreInit,Idle); fSetAllSensitiveCmd = new G4UIcmdWithABool("/aliDet/setAllSensitive", this); fSetAllSensitiveCmd ->SetGuidance("If true: set all logical volumes sensitive."); fSetAllSensitiveCmd ->SetGuidance(" (Each logical is volume associated with a sensitive"); fSetAllSensitiveCmd ->SetGuidance(" detector.)"); fSetAllSensitiveCmd ->SetGuidance("If false: only volumes defined with a sensitive tracking"); fSetAllSensitiveCmd ->SetGuidance(" medium are associated with a sensitive detector."); fSetAllSensitiveCmd->SetParameterName("sensitivity", false); fSetAllSensitiveCmd->AvailableForStates(PreInit); fSetReadGeometryCmd = new G4UIcmdWithABool("/aliDet/readGeometry", this); fSetReadGeometryCmd->SetGuidance("Read geometry from g3calls.dat files"); fSetReadGeometryCmd->SetParameterName("readGeometry", false); fSetReadGeometryCmd->AvailableForStates(PreInit); fSetWriteGeometryCmd = new G4UIcmdWithABool("/aliDet/writeGeometry", this); fSetWriteGeometryCmd->SetGuidance("Write geometry to g3calls.dat file"); fSetWriteGeometryCmd->SetParameterName("writeGeometry", false); fSetWriteGeometryCmd->AvailableForStates(PreInit); fPrintMaterialsCmd = new G4UIcmdWithoutParameter("/aliDet/printMaterials", this); fPrintMaterialsCmd->SetGuidance("Prints all materials."); fPrintMaterialsCmd->AvailableForStates(PreInit, Init, Idle); fGenerateXMLCmd = new G4UIcmdWithoutParameter("/aliDet/generateXML", this); fGenerateXMLCmd->SetGuidance("Generate geometry XML file."); fGenerateXMLCmd->AvailableForStates(Idle); // set candidates list SetCandidates(); // set default values to a detector fModulesComposition->SwitchDetOn("NONE"); } AliModulesCompositionMessenger::AliModulesCompositionMessenger() { // } AliModulesCompositionMessenger::AliModulesCompositionMessenger( const AliModulesCompositionMessenger& right) { // AliGlobals::Exception( "AliModulesCompositionMessenger is protected from copying."); } AliModulesCompositionMessenger::~AliModulesCompositionMessenger() { // delete fDirectory; delete fSwitchOnCmd; delete fSwitchOffCmd; delete fListCmd; delete fListAvailableCmd; delete fFieldValueCmd; delete fSetAllSensitiveCmd; delete fSetReadGeometryCmd; delete fSetWriteGeometryCmd; delete fPrintMaterialsCmd; delete fGenerateXMLCmd; } // operators AliModulesCompositionMessenger& AliModulesCompositionMessenger::operator=( const AliModulesCompositionMessenger& right) { // check assignement to self if (this == &right) return *this; AliGlobals::Exception( "AliModulesCompositionMessenger is protected from assigning."); return *this; } // public methods void AliModulesCompositionMessenger::SetNewValue(G4UIcommand* command, G4String newValues) { // Applies command to the associated object. // --- if (command == fSwitchOnCmd) { fModulesComposition->SwitchDetOn(newValues); } else if (command == fSwitchOffCmd) { fModulesComposition->SwitchDetOff(newValues); } else if (command == fListCmd) { fModulesComposition->PrintSwitchedDets(); } else if (command == fListAvailableCmd) { fModulesComposition->PrintAvailableDets(); } else if (command == fFieldValueCmd) { fModulesComposition ->SetMagField(fFieldValueCmd->GetNewDoubleValue(newValues)); } else if (command == fSetAllSensitiveCmd) { fModulesComposition->SetAllLVSensitive( fSetAllSensitiveCmd->GetNewBoolValue(newValues)); } else if (command == fSetReadGeometryCmd) { fModulesComposition->SetReadGeometry( fSetReadGeometryCmd->GetNewBoolValue(newValues)); } else if (command == fSetWriteGeometryCmd) { fModulesComposition->SetWriteGeometry( fSetWriteGeometryCmd->GetNewBoolValue(newValues)); } else if (command == fPrintMaterialsCmd) { fModulesComposition->PrintMaterials(); } else if (command == fGenerateXMLCmd) { fModulesComposition->GenerateXMLGeometry(); } } void AliModulesCompositionMessenger::SetCandidates() { // Builds candidates list. // --- G4String candidatesList = "NONE ALL "; candidatesList += fModulesComposition->GetDetNamesList();; candidatesList += fModulesComposition->GetAvailableDetsList(); fSwitchOnCmd->SetCandidates(candidatesList); candidatesList = "ALL "; candidatesList += fModulesComposition->GetDetNamesList();; fSwitchOffCmd->SetCandidates(candidatesList); } <commit_msg>command: forceAllSensitive added<commit_after>// $Id$ // Category: geometry // // See the class description in the header file. #include "AliModulesCompositionMessenger.h" #include "AliModulesComposition.h" #include "AliGlobals.h" #include <G4UIdirectory.hh> #include <G4UIcmdWithAString.hh> #include <G4UIcmdWithoutParameter.hh> #include <G4UIcmdWithABool.hh> #include <G4UIcmdWithADoubleAndUnit.hh> AliModulesCompositionMessenger::AliModulesCompositionMessenger( AliModulesComposition* modulesComposition) : fModulesComposition(modulesComposition) { // fDirectory = new G4UIdirectory("/aliDet/"); fDirectory->SetGuidance("Detector construction control commands."); fSwitchOnCmd = new G4UIcmdWithAString("/aliDet/switchOn", this); fSwitchOnCmd->SetGuidance("Define the module to be built."); fSwitchOnCmd->SetGuidance("Available modules:"); G4String listAvailableDets = "NONE, ALL, "; listAvailableDets = listAvailableDets + modulesComposition->GetAvailableDetsListWithCommas(); fSwitchOnCmd->SetGuidance(listAvailableDets); fSwitchOnCmd->SetParameterName("module", false); fSwitchOnCmd->AvailableForStates(PreInit);; fSwitchOffCmd = new G4UIcmdWithAString("/aliDet/switchOff", this); fSwitchOffCmd->SetGuidance("Define the module not to be built."); fSwitchOffCmd->SetGuidance("Available modules:"); G4String listDetsNames = "ALL, "; listDetsNames = listDetsNames + modulesComposition->GetDetNamesListWithCommas(); fSwitchOffCmd->SetGuidance(listDetsNames); fSwitchOffCmd->SetParameterName("module", false); fSwitchOffCmd->AvailableForStates(PreInit);; fListCmd = new G4UIcmdWithoutParameter("/aliDet/list", this); fListCmd->SetGuidance("List the currently switched modules."); fListCmd ->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc); fListAvailableCmd = new G4UIcmdWithoutParameter("/aliDet/listAvailable", this); fListAvailableCmd->SetGuidance("List all available modules."); fListAvailableCmd ->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc); fFieldValueCmd = new G4UIcmdWithADoubleAndUnit("/aliDet/fieldValue", this); fFieldValueCmd->SetGuidance("Define magnetic field in Z direction."); fFieldValueCmd->SetParameterName("fieldValue", false, false); fFieldValueCmd->SetDefaultUnit("tesla"); fFieldValueCmd->SetUnitCategory("Magnetic flux density"); fFieldValueCmd->AvailableForStates(PreInit,Idle); fSetAllSensitiveCmd = new G4UIcmdWithABool("/aliDet/setAllSensitive", this); fSetAllSensitiveCmd ->SetGuidance("If true: set all logical volumes sensitive."); fSetAllSensitiveCmd ->SetGuidance(" (Each logical is volume associated with a sensitive"); fSetAllSensitiveCmd ->SetGuidance(" detector.)"); fSetAllSensitiveCmd ->SetGuidance("If false: only volumes defined with a sensitive tracking"); fSetAllSensitiveCmd ->SetGuidance(" medium are associated with a sensitive detector."); fSetAllSensitiveCmd ->SetGuidance("It has lower priority than individual module setting"); fSetAllSensitiveCmd->SetParameterName("sensitivity", false); fSetAllSensitiveCmd->AvailableForStates(PreInit); fForceAllSensitiveCmd = new G4UIcmdWithABool("/aliDet/forceAllSensitive", this); fForceAllSensitiveCmd ->SetGuidance("If true: force to set all logical volumes sensitive."); fForceAllSensitiveCmd ->SetGuidance(" (Each logical is volume associated with a sensitive"); fForceAllSensitiveCmd ->SetGuidance(" detector.)"); fForceAllSensitiveCmd ->SetGuidance("It has higher priority than individual module setting"); fForceAllSensitiveCmd->SetParameterName("forceSensitivity", false); fForceAllSensitiveCmd->AvailableForStates(PreInit); fSetReadGeometryCmd = new G4UIcmdWithABool("/aliDet/readGeometry", this); fSetReadGeometryCmd->SetGuidance("Read geometry from g3calls.dat files"); fSetReadGeometryCmd->SetParameterName("readGeometry", false); fSetReadGeometryCmd->AvailableForStates(PreInit); fSetWriteGeometryCmd = new G4UIcmdWithABool("/aliDet/writeGeometry", this); fSetWriteGeometryCmd->SetGuidance("Write geometry to g3calls.dat file"); fSetWriteGeometryCmd->SetParameterName("writeGeometry", false); fSetWriteGeometryCmd->AvailableForStates(PreInit); fPrintMaterialsCmd = new G4UIcmdWithoutParameter("/aliDet/printMaterials", this); fPrintMaterialsCmd->SetGuidance("Prints all materials."); fPrintMaterialsCmd->AvailableForStates(PreInit, Init, Idle); fGenerateXMLCmd = new G4UIcmdWithoutParameter("/aliDet/generateXML", this); fGenerateXMLCmd->SetGuidance("Generate geometry XML file."); fGenerateXMLCmd->AvailableForStates(Idle); // set candidates list SetCandidates(); // set default values to a detector fModulesComposition->SwitchDetOn("NONE"); } AliModulesCompositionMessenger::AliModulesCompositionMessenger() { // } AliModulesCompositionMessenger::AliModulesCompositionMessenger( const AliModulesCompositionMessenger& right) { // AliGlobals::Exception( "AliModulesCompositionMessenger is protected from copying."); } AliModulesCompositionMessenger::~AliModulesCompositionMessenger() { // delete fDirectory; delete fSwitchOnCmd; delete fSwitchOffCmd; delete fListCmd; delete fListAvailableCmd; delete fFieldValueCmd; delete fSetAllSensitiveCmd; delete fForceAllSensitiveCmd; delete fSetReadGeometryCmd; delete fSetWriteGeometryCmd; delete fPrintMaterialsCmd; delete fGenerateXMLCmd; } // operators AliModulesCompositionMessenger& AliModulesCompositionMessenger::operator=( const AliModulesCompositionMessenger& right) { // check assignement to self if (this == &right) return *this; AliGlobals::Exception( "AliModulesCompositionMessenger is protected from assigning."); return *this; } // public methods void AliModulesCompositionMessenger::SetNewValue(G4UIcommand* command, G4String newValues) { // Applies command to the associated object. // --- if (command == fSwitchOnCmd) { fModulesComposition->SwitchDetOn(newValues); } else if (command == fSwitchOffCmd) { fModulesComposition->SwitchDetOff(newValues); } else if (command == fListCmd) { fModulesComposition->PrintSwitchedDets(); } else if (command == fListAvailableCmd) { fModulesComposition->PrintAvailableDets(); } else if (command == fFieldValueCmd) { fModulesComposition ->SetMagField(fFieldValueCmd->GetNewDoubleValue(newValues)); } else if (command == fSetAllSensitiveCmd) { fModulesComposition->SetAllLVSensitive( fSetAllSensitiveCmd->GetNewBoolValue(newValues)); } else if (command == fForceAllSensitiveCmd) { fModulesComposition->SetForceAllLVSensitive( fForceAllSensitiveCmd->GetNewBoolValue(newValues)); } else if (command == fSetReadGeometryCmd) { fModulesComposition->SetReadGeometry( fSetReadGeometryCmd->GetNewBoolValue(newValues)); } else if (command == fSetWriteGeometryCmd) { fModulesComposition->SetWriteGeometry( fSetWriteGeometryCmd->GetNewBoolValue(newValues)); } else if (command == fPrintMaterialsCmd) { fModulesComposition->PrintMaterials(); } else if (command == fGenerateXMLCmd) { fModulesComposition->GenerateXMLGeometry(); } } void AliModulesCompositionMessenger::SetCandidates() { // Builds candidates list. // --- G4String candidatesList = "NONE ALL "; candidatesList += fModulesComposition->GetDetNamesList();; candidatesList += fModulesComposition->GetAvailableDetsList(); fSwitchOnCmd->SetCandidates(candidatesList); candidatesList = "ALL "; candidatesList += fModulesComposition->GetDetNamesList();; fSwitchOffCmd->SetCandidates(candidatesList); } <|endoftext|>
<commit_before>#include "Iop_SubSystem.h" #include "../MemoryStateFile.h" #include "../Ps2Const.h" #include "../Log.h" #include "placeholder_def.h" using namespace Iop; using namespace PS2; #define LOG_NAME ("iop_subsystem") #define STATE_CPU ("iop_cpu") #define STATE_RAM ("iop_ram") #define STATE_SCRATCH ("iop_scratch") CSubSystem::CSubSystem() : m_cpu(MEMORYMAP_ENDIAN_LSBF) , m_executor(m_cpu, (IOP_RAM_SIZE * 4)) , m_ram(new uint8[IOP_RAM_SIZE]) , m_scratchPad(new uint8[IOP_SCRATCH_SIZE]) , m_spuRam(new uint8[SPU_RAM_SIZE]) , m_dmac(m_ram, m_intc) , m_counters(IOP_CLOCK_FREQ, m_intc) , m_spuCore0(m_spuRam, SPU_RAM_SIZE) , m_spuCore1(m_spuRam, SPU_RAM_SIZE) , m_spu(m_spuCore0) , m_spu2(m_spuCore0, m_spuCore1) , m_cpuArch(MIPS_REGSIZE_32) , m_copScu(MIPS_REGSIZE_32) { //Read memory map m_cpu.m_pMemoryMap->InsertReadMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertReadMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertReadMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertReadMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pMemoryMap->InsertReadMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05); m_cpu.m_pMemoryMap->InsertReadMap(HW_REG_BEGIN, HW_REG_END, std::bind(&CSubSystem::ReadIoRegister, this, std::placeholders::_1), 0x06); //Write memory map m_cpu.m_pMemoryMap->InsertWriteMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertWriteMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertWriteMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertWriteMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pMemoryMap->InsertWriteMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05); m_cpu.m_pMemoryMap->InsertWriteMap(HW_REG_BEGIN, HW_REG_END, std::bind(&CSubSystem::WriteIoRegister, this, std::placeholders::_1, std::placeholders::_2), 0x06); //Instruction memory map m_cpu.m_pMemoryMap->InsertInstructionMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertInstructionMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertInstructionMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertInstructionMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pArch = &m_cpuArch; m_cpu.m_pCOP[0] = &m_copScu; m_cpu.m_pAddrTranslator = &CMIPS::TranslateAddress64; m_dmac.SetReceiveFunction(4, bind(&CSpuBase::ReceiveDma, &m_spuCore0, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3)); m_dmac.SetReceiveFunction(8, bind(&CSpuBase::ReceiveDma, &m_spuCore1, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3)); } CSubSystem::~CSubSystem() { delete [] m_ram; delete [] m_scratchPad; delete [] m_spuRam; } void CSubSystem::SetBios(const BiosPtr& bios) { m_bios = bios; } void CSubSystem::NotifyVBlankStart() { m_bios->NotifyVBlankStart(); m_intc.AssertLine(Iop::CIntc::LINE_VBLANK); } void CSubSystem::NotifyVBlankEnd() { m_bios->NotifyVBlankEnd(); m_intc.AssertLine(Iop::CIntc::LINE_EVBLANK); } void CSubSystem::SaveState(Framework::CZipArchiveWriter& archive) { archive.InsertFile(new CMemoryStateFile(STATE_CPU, &m_cpu.m_State, sizeof(MIPSSTATE))); archive.InsertFile(new CMemoryStateFile(STATE_RAM, m_ram, IOP_RAM_SIZE)); archive.InsertFile(new CMemoryStateFile(STATE_SCRATCH, m_scratchPad, IOP_SCRATCH_SIZE)); m_bios->SaveState(archive); } void CSubSystem::LoadState(Framework::CZipArchiveReader& archive) { archive.BeginReadFile(STATE_CPU )->Read(&m_cpu.m_State, sizeof(MIPSSTATE)); archive.BeginReadFile(STATE_RAM )->Read(m_ram, IOP_RAM_SIZE); archive.BeginReadFile(STATE_SCRATCH )->Read(m_scratchPad, IOP_SCRATCH_SIZE); m_bios->LoadState(archive); } void CSubSystem::Reset() { memset(m_ram, 0, IOP_RAM_SIZE); memset(m_scratchPad, 0, IOP_SCRATCH_SIZE); memset(m_spuRam, 0, SPU_RAM_SIZE); m_executor.Reset(); m_cpu.Reset(); m_spuCore0.Reset(); m_spuCore1.Reset(); m_spu.Reset(); m_spu2.Reset(); m_counters.Reset(); m_dmac.Reset(); m_intc.Reset(); m_bios.reset(); m_cpu.m_Comments.RemoveTags(); m_cpu.m_Functions.RemoveTags(); } uint32 CSubSystem::ReadIoRegister(uint32 address) { if(address == 0x1F801814) { return 0x14802000; } else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END) { return m_spu.ReadRegister(address); } else if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END) { return m_dmac.ReadRegister(address); } else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END) { return m_dmac.ReadRegister(address); } else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END) { return m_intc.ReadRegister(address); } else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END) { return m_counters.ReadRegister(address); } else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END) { return m_spu2.ReadRegister(address); } else if(address >= 0x1F808400 && address <= 0x1F808500) { //iLink (aka Firewire) stuff return 0x08; } else { CLog::GetInstance().Print(LOG_NAME, "Reading an unknown hardware register (0x%0.8X).\r\n", address); } return 0; } uint32 CSubSystem::WriteIoRegister(uint32 address, uint32 value) { if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END) { m_dmac.WriteRegister(address, value); } else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END) { m_spu.WriteRegister(address, static_cast<uint16>(value)); } else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END) { m_dmac.WriteRegister(address, value); } else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END) { m_intc.WriteRegister(address, value); } else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END) { m_counters.WriteRegister(address, value); } else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END) { return m_spu2.WriteRegister(address, value); } else { CLog::GetInstance().Print(LOG_NAME, "Writing to an unknown hardware register (0x%0.8X, 0x%0.8X).\r\n", address, value); } return 0; } unsigned int CSubSystem::ExecuteCpu(bool singleStep) { int ticks = 0; if(!m_cpu.m_State.nHasException) { if(m_intc.HasPendingInterrupt()) { m_bios->HandleInterrupt(); } } if(!m_cpu.m_State.nHasException) { bool isIdle = false; int quota = singleStep ? 1 : 500; { if(m_bios->IsIdle()) { isIdle = true; ticks += (quota * 2); } else { uint32 physicalPc = m_cpu.m_pAddrTranslator(&m_cpu, m_cpu.m_State.nPC); CBasicBlock* nextBlock = m_executor.FindBlockAt(physicalPc); if(nextBlock && nextBlock->GetSelfLoopCount() > 5000) { //Go a little bit faster if we're "stuck" isIdle = true; ticks += (quota * 2); } } } if(isIdle && !singleStep) { quota /= 50; } ticks += (quota - m_executor.Execute(quota)); assert(ticks >= 0); if(ticks > 0) { m_counters.Update(ticks); m_bios->CountTicks(ticks); } } if(m_cpu.m_State.nHasException) { m_bios->HandleException(); } return ticks; } <commit_msg>Clear IOP analysis when resetting.<commit_after>#include "Iop_SubSystem.h" #include "../MemoryStateFile.h" #include "../Ps2Const.h" #include "../Log.h" #include "placeholder_def.h" using namespace Iop; using namespace PS2; #define LOG_NAME ("iop_subsystem") #define STATE_CPU ("iop_cpu") #define STATE_RAM ("iop_ram") #define STATE_SCRATCH ("iop_scratch") CSubSystem::CSubSystem() : m_cpu(MEMORYMAP_ENDIAN_LSBF) , m_executor(m_cpu, (IOP_RAM_SIZE * 4)) , m_ram(new uint8[IOP_RAM_SIZE]) , m_scratchPad(new uint8[IOP_SCRATCH_SIZE]) , m_spuRam(new uint8[SPU_RAM_SIZE]) , m_dmac(m_ram, m_intc) , m_counters(IOP_CLOCK_FREQ, m_intc) , m_spuCore0(m_spuRam, SPU_RAM_SIZE) , m_spuCore1(m_spuRam, SPU_RAM_SIZE) , m_spu(m_spuCore0) , m_spu2(m_spuCore0, m_spuCore1) , m_cpuArch(MIPS_REGSIZE_32) , m_copScu(MIPS_REGSIZE_32) { //Read memory map m_cpu.m_pMemoryMap->InsertReadMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertReadMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertReadMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertReadMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pMemoryMap->InsertReadMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05); m_cpu.m_pMemoryMap->InsertReadMap(HW_REG_BEGIN, HW_REG_END, std::bind(&CSubSystem::ReadIoRegister, this, std::placeholders::_1), 0x06); //Write memory map m_cpu.m_pMemoryMap->InsertWriteMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertWriteMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertWriteMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertWriteMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pMemoryMap->InsertWriteMap(0x1F800000, 0x1F8003FF, m_scratchPad, 0x05); m_cpu.m_pMemoryMap->InsertWriteMap(HW_REG_BEGIN, HW_REG_END, std::bind(&CSubSystem::WriteIoRegister, this, std::placeholders::_1, std::placeholders::_2), 0x06); //Instruction memory map m_cpu.m_pMemoryMap->InsertInstructionMap((0 * IOP_RAM_SIZE), (0 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x01); m_cpu.m_pMemoryMap->InsertInstructionMap((1 * IOP_RAM_SIZE), (1 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x02); m_cpu.m_pMemoryMap->InsertInstructionMap((2 * IOP_RAM_SIZE), (2 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x03); m_cpu.m_pMemoryMap->InsertInstructionMap((3 * IOP_RAM_SIZE), (3 * IOP_RAM_SIZE) + IOP_RAM_SIZE - 1, m_ram, 0x04); m_cpu.m_pArch = &m_cpuArch; m_cpu.m_pCOP[0] = &m_copScu; m_cpu.m_pAddrTranslator = &CMIPS::TranslateAddress64; m_dmac.SetReceiveFunction(4, bind(&CSpuBase::ReceiveDma, &m_spuCore0, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3)); m_dmac.SetReceiveFunction(8, bind(&CSpuBase::ReceiveDma, &m_spuCore1, PLACEHOLDER_1, PLACEHOLDER_2, PLACEHOLDER_3)); } CSubSystem::~CSubSystem() { delete [] m_ram; delete [] m_scratchPad; delete [] m_spuRam; } void CSubSystem::SetBios(const BiosPtr& bios) { m_bios = bios; } void CSubSystem::NotifyVBlankStart() { m_bios->NotifyVBlankStart(); m_intc.AssertLine(Iop::CIntc::LINE_VBLANK); } void CSubSystem::NotifyVBlankEnd() { m_bios->NotifyVBlankEnd(); m_intc.AssertLine(Iop::CIntc::LINE_EVBLANK); } void CSubSystem::SaveState(Framework::CZipArchiveWriter& archive) { archive.InsertFile(new CMemoryStateFile(STATE_CPU, &m_cpu.m_State, sizeof(MIPSSTATE))); archive.InsertFile(new CMemoryStateFile(STATE_RAM, m_ram, IOP_RAM_SIZE)); archive.InsertFile(new CMemoryStateFile(STATE_SCRATCH, m_scratchPad, IOP_SCRATCH_SIZE)); m_bios->SaveState(archive); } void CSubSystem::LoadState(Framework::CZipArchiveReader& archive) { archive.BeginReadFile(STATE_CPU )->Read(&m_cpu.m_State, sizeof(MIPSSTATE)); archive.BeginReadFile(STATE_RAM )->Read(m_ram, IOP_RAM_SIZE); archive.BeginReadFile(STATE_SCRATCH )->Read(m_scratchPad, IOP_SCRATCH_SIZE); m_bios->LoadState(archive); } void CSubSystem::Reset() { memset(m_ram, 0, IOP_RAM_SIZE); memset(m_scratchPad, 0, IOP_SCRATCH_SIZE); memset(m_spuRam, 0, SPU_RAM_SIZE); m_executor.Reset(); m_cpu.Reset(); m_cpu.m_pAnalysis->Clear(); m_spuCore0.Reset(); m_spuCore1.Reset(); m_spu.Reset(); m_spu2.Reset(); m_counters.Reset(); m_dmac.Reset(); m_intc.Reset(); m_bios.reset(); m_cpu.m_Comments.RemoveTags(); m_cpu.m_Functions.RemoveTags(); } uint32 CSubSystem::ReadIoRegister(uint32 address) { if(address == 0x1F801814) { return 0x14802000; } else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END) { return m_spu.ReadRegister(address); } else if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END) { return m_dmac.ReadRegister(address); } else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END) { return m_dmac.ReadRegister(address); } else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END) { return m_intc.ReadRegister(address); } else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END) { return m_counters.ReadRegister(address); } else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END) { return m_spu2.ReadRegister(address); } else if(address >= 0x1F808400 && address <= 0x1F808500) { //iLink (aka Firewire) stuff return 0x08; } else { CLog::GetInstance().Print(LOG_NAME, "Reading an unknown hardware register (0x%0.8X).\r\n", address); } return 0; } uint32 CSubSystem::WriteIoRegister(uint32 address, uint32 value) { if(address >= CDmac::DMAC_ZONE1_START && address <= CDmac::DMAC_ZONE1_END) { m_dmac.WriteRegister(address, value); } else if(address >= CSpu::SPU_BEGIN && address <= CSpu::SPU_END) { m_spu.WriteRegister(address, static_cast<uint16>(value)); } else if(address >= CDmac::DMAC_ZONE2_START && address <= CDmac::DMAC_ZONE2_END) { m_dmac.WriteRegister(address, value); } else if(address >= CIntc::ADDR_BEGIN && address <= CIntc::ADDR_END) { m_intc.WriteRegister(address, value); } else if(address >= CRootCounters::ADDR_BEGIN && address <= CRootCounters::ADDR_END) { m_counters.WriteRegister(address, value); } else if(address >= CSpu2::REGS_BEGIN && address <= CSpu2::REGS_END) { return m_spu2.WriteRegister(address, value); } else { CLog::GetInstance().Print(LOG_NAME, "Writing to an unknown hardware register (0x%0.8X, 0x%0.8X).\r\n", address, value); } return 0; } unsigned int CSubSystem::ExecuteCpu(bool singleStep) { int ticks = 0; if(!m_cpu.m_State.nHasException) { if(m_intc.HasPendingInterrupt()) { m_bios->HandleInterrupt(); } } if(!m_cpu.m_State.nHasException) { bool isIdle = false; int quota = singleStep ? 1 : 500; { if(m_bios->IsIdle()) { isIdle = true; ticks += (quota * 2); } else { uint32 physicalPc = m_cpu.m_pAddrTranslator(&m_cpu, m_cpu.m_State.nPC); CBasicBlock* nextBlock = m_executor.FindBlockAt(physicalPc); if(nextBlock && nextBlock->GetSelfLoopCount() > 5000) { //Go a little bit faster if we're "stuck" isIdle = true; ticks += (quota * 2); } } } if(isIdle && !singleStep) { quota /= 50; } ticks += (quota - m_executor.Execute(quota)); assert(ticks >= 0); if(ticks > 0) { m_counters.Update(ticks); m_bios->CountTicks(ticks); } } if(m_cpu.m_State.nHasException) { m_bios->HandleException(); } return ticks; } <|endoftext|>
<commit_before>#include "queuemanager.h" #include "rdkafka.h" QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk) { } QueueManager::~QueueManager() { ASSERT(queues_.empty()); } void QueueManager::add(rd_kafka_queue_t* queue) { CritScope ss(&crt_); ASSERT(queues_.find(queue) == queues_.end()); //remove the queue forwarding on the main queue. rd_kafka_queue_forward(queue, NULL); queues_.insert(queue); } bool QueueManager::remove(rd_kafka_queue_t* queue) { CritScope ss(&crt_); auto it = queues_.find(queue); if(it == queues_.end()) return false; //forward the queue back to the main queue rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); queues_.erase(it); return true; } void QueueManager::clear_all() { CritScope ss(&crt_); //forwards all queues back on the main queue for(auto it = queues_.begin(); it != queues_.end(); ++ it) { rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); } queues_.clear(); } <commit_msg>Fix another memory leak found with instruments.<commit_after>#include "queuemanager.h" #include "rdkafka.h" QueueManager::QueueManager(rd_kafka_t *rk) : rk_(rk) { } QueueManager::~QueueManager() { ASSERT(queues_.empty()); } void QueueManager::add(rd_kafka_queue_t* queue) { CritScope ss(&crt_); ASSERT(queues_.find(queue) == queues_.end()); //remove the queue forwarding on the main queue. rd_kafka_queue_forward(queue, NULL); queues_.insert(queue); } bool QueueManager::remove(rd_kafka_queue_t* queue) { CritScope ss(&crt_); auto it = queues_.find(queue); if(it == queues_.end()) return false; //forward the queue back to the main queue rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); rd_kafka_queue_destroy(*it); queues_.erase(it); return true; } void QueueManager::clear_all() { CritScope ss(&crt_); //forwards all queues back on the main queue for(auto it = queues_.begin(); it != queues_.end(); ++ it) { rd_kafka_queue_t* main_queue = rd_kafka_queue_get_consumer(rk_); rd_kafka_queue_forward(*it, main_queue); rd_kafka_queue_destroy(main_queue); } queues_.clear(); } <|endoftext|>
<commit_before>#include "FileSystem.h" #ifdef _WIN32 #include "windows.h" #endif #ifdef __unix__ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #endif #include <iostream> namespace StiGame { namespace FS { FileSystem::FileSystem() { } #ifdef __unix__ //POSIX implementation std::vector<Entry*> FileSystem::ListDirectory(std::string m_path) { std::string unix_path; if(m_path.length() == 0) { //current_dir unix_path = "."; } else { unix_path = m_path; } std::vector<Entry*> root; DIR *dir = opendir(unix_path.c_str()); if(dir) { dirent *ent; while(ent) { std::string name (ent->d_name); if(name != "." && name != ".." && name.size() > 0) { if(ent->d_type == DT_DIR) { //directory Directory *_dir = new Directory(name, m_path); root.push_back(_dir); } else { //file File *_file = new File(name, m_path); root.push_back(_file); } } ent = readdir(dir); } closedir(dir); } return root; } void FileSystem::CreateDir(std::string d_path) { struct stat st = {0}; if (stat(d_path.c_str(), &st) == -1) { mkdir(d_path.c_str(), 0755) } } #endif #ifdef _WIN32 //windows implementation std::vector<Entry*> FileSystem::ListDirectory(std::string m_path) { std::string win32_path; if(m_path.length() == 0) { //current_dir win32_path = "./*"; } else { //need to add a wildcard for win32 win32_path = m_path + "*"; } std::vector<Entry*> root; WIN32_FIND_DATA f; HANDLE h = FindFirstFile(win32_path.c_str(), &f); if(h != INVALID_HANDLE_VALUE) { do { if(f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //dir std::string name(f.cFileName); if(name != "." && name != "..") { Directory *dir = new Directory(name, m_path); root.push_back(dir); } } else { //file File *file = new File(f.cFileName, m_path); root.push_back(file); } } while(FindNextFile(h, &f)); } return root; } void FileSystem::CreateDir(std::string d_path) { if (CreateDirectory(d_path.c_str(), NULL)) { } else if (ERROR_ALREADY_EXISTS == GetLastError()) { } else { //todo //error message } } #endif } } <commit_msg>unix mkdir fix<commit_after>#include "FileSystem.h" #ifdef _WIN32 #include "windows.h" #endif #ifdef __unix__ #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <dirent.h> #endif #include <iostream> namespace StiGame { namespace FS { FileSystem::FileSystem() { } #ifdef __unix__ //POSIX implementation std::vector<Entry*> FileSystem::ListDirectory(std::string m_path) { std::string unix_path; if(m_path.length() == 0) { //current_dir unix_path = "."; } else { unix_path = m_path; } std::vector<Entry*> root; DIR *dir = opendir(unix_path.c_str()); if(dir) { dirent *ent; while(ent) { std::string name (ent->d_name); if(name != "." && name != ".." && name.size() > 0) { if(ent->d_type == DT_DIR) { //directory Directory *_dir = new Directory(name, m_path); root.push_back(_dir); } else { //file File *_file = new File(name, m_path); root.push_back(_file); } } ent = readdir(dir); } closedir(dir); } return root; } void FileSystem::CreateDir(std::string d_path) { struct stat st = {0}; if (stat(d_path.c_str(), &st) == -1) { mkdir(d_path.c_str(), 0755); } } #endif #ifdef _WIN32 //windows implementation std::vector<Entry*> FileSystem::ListDirectory(std::string m_path) { std::string win32_path; if(m_path.length() == 0) { //current_dir win32_path = "./*"; } else { //need to add a wildcard for win32 win32_path = m_path + "*"; } std::vector<Entry*> root; WIN32_FIND_DATA f; HANDLE h = FindFirstFile(win32_path.c_str(), &f); if(h != INVALID_HANDLE_VALUE) { do { if(f.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //dir std::string name(f.cFileName); if(name != "." && name != "..") { Directory *dir = new Directory(name, m_path); root.push_back(dir); } } else { //file File *file = new File(f.cFileName, m_path); root.push_back(file); } } while(FindNextFile(h, &f)); } return root; } void FileSystem::CreateDir(std::string d_path) { if (CreateDirectory(d_path.c_str(), NULL)) { } else if (ERROR_ALREADY_EXISTS == GetLastError()) { } else { //todo //error message } } #endif } } <|endoftext|>
<commit_before>/* * Copyright (c) 2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_CONF_APP_CONNECT_STATEMENT #error [NOT_SUPPORTED] No network configuration found for this target. #endif #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "nsapi_dns.h" #include "EventQueue.h" #include "dns_tests.h" #include MBED_CONF_APP_HEADER_FILE using namespace utest::v1; namespace { NetworkInterface *net; } const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS; const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND; // Callback used for asynchronous DNS result void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address) { dns_application_data *app_data = static_cast<dns_application_data *>(data); app_data->result = result; if (address) { app_data->addr = *address; } app_data->semaphore->release(); app_data->value_set = true; } // General function to do asynchronous DNS host name resolution void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; // Create callback semaphore and data rtos::Semaphore semaphore; dns_application_data *data = new dns_application_data[op_count]; unsigned int count = 0; for (unsigned int i = 0; i < op_count; i++) { data[i].semaphore = &semaphore; nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i])); TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY); if (err >= 0) { // Callback will be called count++; } else { // No memory to initiate DNS query, callback will not be called data[i].result = NSAPI_ERROR_NO_MEMORY; } } // Wait for callback(s) to complete for (unsigned int i = 0; i < count; i++) { semaphore.wait(); } // Print result for (unsigned int i = 0; i < op_count; i++) { TEST_ASSERT(data[i].result == NSAPI_ERROR_OK || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT); if (data[i].result == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], data[i].addr.get_ip_address()); } else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } } delete[] data; } NetworkInterface *get_interface() { return net; } static void net_bringup() { MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1); net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); printf("MBED: Connected to network\n"); printf("MBED: IP Address: %s\n", net->get_ip_address()); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(120, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE), Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE), Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC), Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL), Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE), Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST), Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT), }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } <commit_msg>Moved ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT under mbed extended tests<commit_after>/* * Copyright (c) 2018, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBED_CONF_APP_CONNECT_STATEMENT #error [NOT_SUPPORTED] No network configuration found for this target. #endif #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "nsapi_dns.h" #include "EventQueue.h" #include "dns_tests.h" #include MBED_CONF_APP_HEADER_FILE using namespace utest::v1; namespace { NetworkInterface *net; } const char dns_test_hosts[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS; const char dns_test_hosts_second[MBED_CONF_APP_DNS_TEST_HOSTS_NUM][DNS_TEST_HOST_LEN] = MBED_CONF_APP_DNS_TEST_HOSTS_SECOND; // Callback used for asynchronous DNS result void hostbyname_cb(void *data, nsapi_error_t result, SocketAddress *address) { dns_application_data *app_data = static_cast<dns_application_data *>(data); app_data->result = result; if (address) { app_data->addr = *address; } app_data->semaphore->release(); app_data->value_set = true; } // General function to do asynchronous DNS host name resolution void do_asynchronous_gethostbyname(const char hosts[][DNS_TEST_HOST_LEN], unsigned int op_count, int *exp_ok, int *exp_no_mem, int *exp_dns_failure, int *exp_timeout) { // Verify that there is enough hosts in the host list TEST_ASSERT(op_count <= MBED_CONF_APP_DNS_TEST_HOSTS_NUM) // Reset counters (*exp_ok) = 0; (*exp_no_mem) = 0; (*exp_dns_failure) = 0; (*exp_timeout) = 0; // Create callback semaphore and data rtos::Semaphore semaphore; dns_application_data *data = new dns_application_data[op_count]; unsigned int count = 0; for (unsigned int i = 0; i < op_count; i++) { data[i].semaphore = &semaphore; nsapi_error_t err = net->gethostbyname_async(hosts[i], mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data[i])); TEST_ASSERT(err >= 0 || err == NSAPI_ERROR_NO_MEMORY); if (err >= 0) { // Callback will be called count++; } else { // No memory to initiate DNS query, callback will not be called data[i].result = NSAPI_ERROR_NO_MEMORY; } } // Wait for callback(s) to complete for (unsigned int i = 0; i < count; i++) { semaphore.wait(); } // Print result for (unsigned int i = 0; i < op_count; i++) { TEST_ASSERT(data[i].result == NSAPI_ERROR_OK || data[i].result == NSAPI_ERROR_NO_MEMORY || data[i].result == NSAPI_ERROR_DNS_FAILURE || data[i].result == NSAPI_ERROR_TIMEOUT); if (data[i].result == NSAPI_ERROR_OK) { (*exp_ok)++; printf("DNS: query \"%s\" => \"%s\"\n", hosts[i], data[i].addr.get_ip_address()); } else if (data[i].result == NSAPI_ERROR_DNS_FAILURE) { (*exp_dns_failure)++; printf("DNS: query \"%s\" => DNS failure\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_TIMEOUT) { (*exp_timeout)++; printf("DNS: query \"%s\" => timeout\n", hosts[i]); } else if (data[i].result == NSAPI_ERROR_NO_MEMORY) { (*exp_no_mem)++; printf("DNS: query \"%s\" => no memory\n", hosts[i]); } } delete[] data; } NetworkInterface *get_interface() { return net; } static void net_bringup() { MBED_ASSERT(MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_NSAPI_DNS_CACHE_SIZE && MBED_CONF_APP_DNS_TEST_HOSTS_NUM >= MBED_CONF_APP_DNS_SIMULT_QUERIES + 1); net = MBED_CONF_APP_OBJECT_CONSTRUCTION; int err = MBED_CONF_APP_CONNECT_STATEMENT; TEST_ASSERT_EQUAL(0, err); printf("MBED: Connected to network\n"); printf("MBED: IP Address: %s\n", net->get_ip_address()); } // Test setup utest::v1::status_t test_setup(const size_t number_of_cases) { GREENTEA_SETUP(120, "default_auto"); net_bringup(); return verbose_test_setup_handler(number_of_cases); } Case cases[] = { Case("ASYNCHRONOUS_DNS", ASYNCHRONOUS_DNS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS", ASYNCHRONOUS_DNS_SIMULTANEOUS), Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE", ASYNCHRONOUS_DNS_SIMULTANEOUS_CACHE), Case("ASYNCHRONOUS_DNS_CACHE", ASYNCHRONOUS_DNS_CACHE), Case("ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC", ASYNCHRONOUS_DNS_NON_ASYNC_AND_ASYNC), Case("ASYNCHRONOUS_DNS_CANCEL", ASYNCHRONOUS_DNS_CANCEL), Case("ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE", ASYNCHRONOUS_DNS_EXTERNAL_EVENT_QUEUE), Case("ASYNCHRONOUS_DNS_INVALID_HOST", ASYNCHRONOUS_DNS_INVALID_HOST), Case("ASYNCHRONOUS_DNS_TIMEOUTS", ASYNCHRONOUS_DNS_TIMEOUTS), #ifdef MBED_EXTENDED_TESTS Case("ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT", ASYNCHRONOUS_DNS_SIMULTANEOUS_REPEAT), #endif }; Specification specification(test_setup, cases); int main() { return !Harness::run(specification); } <|endoftext|>
<commit_before>/* This file is part of the Rendering library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "Helper.h" #include "GLHeader.h" #include <iostream> #include <iomanip> #if defined(ANDROID) #include <android/log.h> #endif /* defined(ANDROID) */ namespace Rendering { static bool GLErrorChecking = false; void enableGLErrorChecking() { GLErrorChecking = true; } void disableGLErrorChecking() { GLErrorChecking = false; } static const char * getGLErrorString(GLenum errorFlag) { switch (errorFlag) { case GL_NO_ERROR: return "GL_NO_ERROR"; case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; #ifdef LIB_GL case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW"; case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW"; case GL_TABLE_TOO_LARGE: return "GL_TABLE_TOO_LARGE"; #endif /* LIB_GL */ #ifdef LIB_GLESv2 case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION"; #endif /* LIB_GLESv2 */ default: return "Unknown error"; } } void checkGLError(const char * file, int line) { if(!GLErrorChecking) { return; } // Call glGetError() in a loop, because there might be multiple recorded errors. GLenum errorFlag = glGetError(); while (errorFlag != GL_NO_ERROR) { #if defined(ANDROID) __android_log_print(ANDROID_LOG_WARN, "RenderingMobile", "GL ERROR (%i):%s at %s:%i", errorFlag, getGLErrorString(errorFlag), file, line); #else std::cerr << "GL ERROR (0x" << std::hex << errorFlag << "):" << getGLErrorString(errorFlag) << " at " << file << ":" << std::dec << line << std::endl; #endif errorFlag = glGetError(); } } const char * getGLTypeString(uint32_t type) { switch (static_cast<GLenum>(type)) { case GL_BOOL: return "bool"; case GL_UNSIGNED_BYTE: return "uchar"; case GL_BYTE: return "char"; case GL_UNSIGNED_SHORT: return "ushort"; case GL_SHORT: return "short"; case GL_UNSIGNED_INT: return "uint"; case GL_INT: return "int"; case GL_FLOAT: return "float"; #ifdef LIB_GL case GL_DOUBLE: return "double"; case GL_UNSIGNED_INT_24_8_EXT: return "uint_24_8_EXT"; #endif default: return ""; } } unsigned int getGLTypeSize(uint32_t type) { switch (static_cast<GLenum>(type)) { case GL_BOOL: return sizeof(GLboolean); case GL_UNSIGNED_BYTE: return sizeof(GLubyte); case GL_BYTE: return sizeof(GLbyte); case GL_UNSIGNED_SHORT: return sizeof(GLushort); case GL_SHORT: return sizeof(GLshort); case GL_UNSIGNED_INT: return sizeof(GLuint); case GL_INT: return sizeof(GLint); case GL_FLOAT: return sizeof(GLfloat); #ifdef LIB_GL case GL_DOUBLE: return sizeof(GLdouble); case GL_UNSIGNED_INT_24_8_EXT: return sizeof(GLuint); #endif /* LIB_GL */ default: return 0; } } void outputGLInformation(std::ostream & output) { output << "OpenGL vendor: " << glGetString(GL_VENDOR) << '\n'; output << "OpenGL renderer: " << glGetString(GL_RENDERER) << '\n'; output << "OpenGL version: " << glGetString(GL_VERSION) << '\n'; output << "OpenGL shading language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << '\n'; } const char * getGraphicsLanguageVersion() { return reinterpret_cast<const char *>(glGetString(GL_VERSION)); } const char * getShadingLanguageVersion() { return reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); } bool isExtensionSupported(const char * extension) { #if defined(LIB_GLEW) return glewIsSupported(extension); #else return false; #endif } float readDepthValue(int32_t x, int32_t y) { GLfloat z; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); return z; } #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) #if defined(_WIN32) static void debugCallback(GLenum, GLenum, GLuint, GLenum, GLsizei , const char *, const void * ) __attribute__((__stdcall__)); // the following alias function is required as different versions of glew define GLDEBUGPROCARB differently: // with void*userParam OR const void*userParam static void debugCallback(GLenum, GLenum, GLuint, GLenum, GLsizei , const char *, void * ) __attribute__((__stdcall__)); #endif static void debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char *message, void *userParam ){ debugCallback(source,type,id,severity,length,message,static_cast<const void*>(userParam)); } static void debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*length*/, const char * message, const void * /*userParam*/) { std::cerr << "GL DEBUG source="; switch(source) { case GL_DEBUG_SOURCE_API_ARB: std::cerr << "GL"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: std::cerr << "GLSL"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: std::cerr << "GLX/WGL"; break; case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: std::cerr << "ThirdParty"; break; case GL_DEBUG_SOURCE_APPLICATION_ARB: std::cerr << "Application"; break; case GL_DEBUG_SOURCE_OTHER_ARB: default: std::cerr << "Other"; break; } std::cerr << " type="; switch(type) { case GL_DEBUG_TYPE_ERROR_ARB: std::cerr << "Error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: std::cerr << "DeprecatedBehaviour"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: std::cerr << "UndefinedBehaviour"; break; case GL_DEBUG_TYPE_PERFORMANCE_ARB: std::cerr << "Performance"; break; case GL_DEBUG_TYPE_PORTABILITY_ARB: std::cerr << "Portability"; break; case GL_DEBUG_TYPE_OTHER_ARB: default: std::cerr << "Other"; break; } std::cerr << " id=" << id << " severity="; switch(severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: std::cerr << "High"; break; case GL_DEBUG_SEVERITY_MEDIUM_ARB: std::cerr << "Medium"; break; case GL_DEBUG_SEVERITY_LOW_ARB: default: std::cerr << "Low"; break; } std::cerr << " message=" << message << std::endl; } #endif void enableDebugOutput() { #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) if(!glewIsSupported("GL_ARB_debug_output")) { std::cerr << "GL_ARB_debug_output is not supported" << std::endl; return; } glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); glDebugMessageCallbackARB(&debugCallback, nullptr); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageInsertARB(GL_DEBUG_SOURCE_THIRD_PARTY_ARB, GL_DEBUG_TYPE_OTHER_ARB, 1, GL_DEBUG_SEVERITY_LOW_ARB, -1, "Rendering: Debugging enabled"); #else std::cerr << "GL_ARB_debug_output is not supported" << std::endl; #endif } void disableDebugOutput() { #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) if(!glewIsSupported("GL_ARB_debug_output")) { std::cerr << "GL_ARB_debug_output is not supported" << std::endl; return; } glDebugMessageInsertARB(GL_DEBUG_SOURCE_THIRD_PARTY_ARB, GL_DEBUG_TYPE_OTHER_ARB, 2, GL_DEBUG_SEVERITY_LOW_ARB, -1, "Rendering: Debugging disabled"); glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); glDebugMessageCallbackARB(nullptr, nullptr); glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); #else std::cerr << "GL_ARB_debug_output is not supported" << std::endl; #endif } } <commit_msg>Helper: Compile fix -- another try. Use alternative callback definition only on windows.<commit_after>/* This file is part of the Rendering library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "Helper.h" #include "GLHeader.h" #include <iostream> #include <iomanip> #if defined(ANDROID) #include <android/log.h> #endif /* defined(ANDROID) */ namespace Rendering { static bool GLErrorChecking = false; void enableGLErrorChecking() { GLErrorChecking = true; } void disableGLErrorChecking() { GLErrorChecking = false; } static const char * getGLErrorString(GLenum errorFlag) { switch (errorFlag) { case GL_NO_ERROR: return "GL_NO_ERROR"; case GL_INVALID_ENUM: return "GL_INVALID_ENUM"; case GL_INVALID_VALUE: return "GL_INVALID_VALUE"; case GL_INVALID_OPERATION: return "GL_INVALID_OPERATION"; case GL_OUT_OF_MEMORY: return "GL_OUT_OF_MEMORY"; #ifdef LIB_GL case GL_STACK_OVERFLOW: return "GL_STACK_OVERFLOW"; case GL_STACK_UNDERFLOW: return "GL_STACK_UNDERFLOW"; case GL_TABLE_TOO_LARGE: return "GL_TABLE_TOO_LARGE"; #endif /* LIB_GL */ #ifdef LIB_GLESv2 case GL_INVALID_FRAMEBUFFER_OPERATION: return "GL_INVALID_FRAMEBUFFER_OPERATION"; #endif /* LIB_GLESv2 */ default: return "Unknown error"; } } void checkGLError(const char * file, int line) { if(!GLErrorChecking) { return; } // Call glGetError() in a loop, because there might be multiple recorded errors. GLenum errorFlag = glGetError(); while (errorFlag != GL_NO_ERROR) { #if defined(ANDROID) __android_log_print(ANDROID_LOG_WARN, "RenderingMobile", "GL ERROR (%i):%s at %s:%i", errorFlag, getGLErrorString(errorFlag), file, line); #else std::cerr << "GL ERROR (0x" << std::hex << errorFlag << "):" << getGLErrorString(errorFlag) << " at " << file << ":" << std::dec << line << std::endl; #endif errorFlag = glGetError(); } } const char * getGLTypeString(uint32_t type) { switch (static_cast<GLenum>(type)) { case GL_BOOL: return "bool"; case GL_UNSIGNED_BYTE: return "uchar"; case GL_BYTE: return "char"; case GL_UNSIGNED_SHORT: return "ushort"; case GL_SHORT: return "short"; case GL_UNSIGNED_INT: return "uint"; case GL_INT: return "int"; case GL_FLOAT: return "float"; #ifdef LIB_GL case GL_DOUBLE: return "double"; case GL_UNSIGNED_INT_24_8_EXT: return "uint_24_8_EXT"; #endif default: return ""; } } unsigned int getGLTypeSize(uint32_t type) { switch (static_cast<GLenum>(type)) { case GL_BOOL: return sizeof(GLboolean); case GL_UNSIGNED_BYTE: return sizeof(GLubyte); case GL_BYTE: return sizeof(GLbyte); case GL_UNSIGNED_SHORT: return sizeof(GLushort); case GL_SHORT: return sizeof(GLshort); case GL_UNSIGNED_INT: return sizeof(GLuint); case GL_INT: return sizeof(GLint); case GL_FLOAT: return sizeof(GLfloat); #ifdef LIB_GL case GL_DOUBLE: return sizeof(GLdouble); case GL_UNSIGNED_INT_24_8_EXT: return sizeof(GLuint); #endif /* LIB_GL */ default: return 0; } } void outputGLInformation(std::ostream & output) { output << "OpenGL vendor: " << glGetString(GL_VENDOR) << '\n'; output << "OpenGL renderer: " << glGetString(GL_RENDERER) << '\n'; output << "OpenGL version: " << glGetString(GL_VERSION) << '\n'; output << "OpenGL shading language version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << '\n'; } const char * getGraphicsLanguageVersion() { return reinterpret_cast<const char *>(glGetString(GL_VERSION)); } const char * getShadingLanguageVersion() { return reinterpret_cast<const char *>(glGetString(GL_SHADING_LANGUAGE_VERSION)); } bool isExtensionSupported(const char * extension) { #if defined(LIB_GLEW) return glewIsSupported(extension); #else return false; #endif } float readDepthValue(int32_t x, int32_t y) { GLfloat z; glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, &z); return z; } #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) #if defined(_WIN32) static void debugCallback(GLenum, GLenum, GLuint, GLenum, GLsizei , const char *, const void * ) __attribute__((__stdcall__)); // the following alias function is required as different versions of glew define GLDEBUGPROCARB differently: // with void*userParam OR const void*userParam static void debugCallback(GLenum, GLenum, GLuint, GLenum, GLsizei , const char *, void * ) __attribute__((__stdcall__)); static void debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const char *message, void *userParam ){ debugCallback(source,type,id,severity,length,message,static_cast<const void*>(userParam)); } #endif static void debugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei /*length*/, const char * message, const void * /*userParam*/) { std::cerr << "GL DEBUG source="; switch(source) { case GL_DEBUG_SOURCE_API_ARB: std::cerr << "GL"; break; case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: std::cerr << "GLSL"; break; case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: std::cerr << "GLX/WGL"; break; case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: std::cerr << "ThirdParty"; break; case GL_DEBUG_SOURCE_APPLICATION_ARB: std::cerr << "Application"; break; case GL_DEBUG_SOURCE_OTHER_ARB: default: std::cerr << "Other"; break; } std::cerr << " type="; switch(type) { case GL_DEBUG_TYPE_ERROR_ARB: std::cerr << "Error"; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: std::cerr << "DeprecatedBehaviour"; break; case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: std::cerr << "UndefinedBehaviour"; break; case GL_DEBUG_TYPE_PERFORMANCE_ARB: std::cerr << "Performance"; break; case GL_DEBUG_TYPE_PORTABILITY_ARB: std::cerr << "Portability"; break; case GL_DEBUG_TYPE_OTHER_ARB: default: std::cerr << "Other"; break; } std::cerr << " id=" << id << " severity="; switch(severity) { case GL_DEBUG_SEVERITY_HIGH_ARB: std::cerr << "High"; break; case GL_DEBUG_SEVERITY_MEDIUM_ARB: std::cerr << "Medium"; break; case GL_DEBUG_SEVERITY_LOW_ARB: default: std::cerr << "Low"; break; } std::cerr << " message=" << message << std::endl; } #endif void enableDebugOutput() { #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) if(!glewIsSupported("GL_ARB_debug_output")) { std::cerr << "GL_ARB_debug_output is not supported" << std::endl; return; } glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE); glDebugMessageCallbackARB(&debugCallback, nullptr); glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); glDebugMessageInsertARB(GL_DEBUG_SOURCE_THIRD_PARTY_ARB, GL_DEBUG_TYPE_OTHER_ARB, 1, GL_DEBUG_SEVERITY_LOW_ARB, -1, "Rendering: Debugging enabled"); #else std::cerr << "GL_ARB_debug_output is not supported" << std::endl; #endif } void disableDebugOutput() { #if defined(LIB_GLEW) && defined(LIB_GL) && defined(GL_ARB_debug_output) if(!glewIsSupported("GL_ARB_debug_output")) { std::cerr << "GL_ARB_debug_output is not supported" << std::endl; return; } glDebugMessageInsertARB(GL_DEBUG_SOURCE_THIRD_PARTY_ARB, GL_DEBUG_TYPE_OTHER_ARB, 2, GL_DEBUG_SEVERITY_LOW_ARB, -1, "Rendering: Debugging disabled"); glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE); glDebugMessageCallbackARB(nullptr, nullptr); glDisable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); #else std::cerr << "GL_ARB_debug_output is not supported" << std::endl; #endif } } <|endoftext|>
<commit_before><commit_msg>re-fix example<commit_after><|endoftext|>
<commit_before>/*********************************************************************** OpenSync Plugin for KDE 3.x Copyright (C) 2004 Stewart Heitmann <sheitmann@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /* * 03 Nov 2004 - Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * - Ported to OpenSync plugin interface */ extern "C" { #include <opensync/opensync.h> #include "kaddrbook.h" } #include <kabc/stdaddressbook.h> #include <kabc/vcardconverter.h> #include <kabc/resource.h> #include <kcmdlineargs.h> #include <kapplication.h> #include <klocale.h> #include <qsignal.h> #include <qfile.h> static void unfold_vcard(char *vcard, size_t *size) { char* in = vcard; char* out = vcard; char *end = vcard + *size; while ( in < end) { /* remove any occurrences of "=[CR][LF]" */ /* these denote folded line markers in VCARD format. */ /* Dont know why, but Evolution uses the leading "=" */ /* character to (presumably) denote a control sequence. */ /* This is not quite how I interpret the VCARD RFC2426 */ /* spec (section 2.6 line delimiting and folding). */ /* This seems to work though, so thats the main thing! */ if (in[0]=='=' && in[1]==13 && in[2]==10) in+=3; else *out++ = *in++; } *size = out - vcard; } class kaddrbook { private: KABC::AddressBook* addressbookptr; KABC::Ticket* addressbookticket; QDateTime syncdate, newsyncdate; OSyncMember *member; OSyncHashTable *hashtable; public: kaddrbook(OSyncMember *memb) :member(memb) { //osync_debug("kde", 3, "kdepim_plugin: %s(%s)", __FUNCTION__); //get a handle to the standard KDE addressbook addressbookptr = KABC::StdAddressBook::self(); //ensure a NULL Ticket ptr addressbookticket=NULL; hashtable = osync_hashtable_new(); osync_hashtable_load(hashtable, member); } int connect() { //Lock the addressbook addressbookticket = addressbookptr->requestSaveTicket(); if (!addressbookticket) { osync_debug("kde", 3, "kdepim_plugin: couldnt lock KDE addressbook, aborting sync."); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook locked OK."); return 0; } int disconnect() { //Unlock the addressbook addressbookptr->save(addressbookticket); addressbookticket = NULL; return 0; } int get_changes(OSyncContext *ctx) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(newdbs=%d)", __FUNCTION__, newdbs); osync_bool slow_sync = osync_member_get_slow_sync(member, "contact"); //remember when we started this current sync newsyncdate = QDateTime::currentDateTime(); // We must reload the KDE addressbook in order to retrieve the latest changes. if (!addressbookptr->load()) { osync_debug("kde", 3, "kdepim_plugin: couldnt reload KDE addressbook, aborting sync."); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook reloaded OK."); //osync_debug("kde", 3, "%s: %s : plugin UID list has %d entries", __FILE__, __FUNCTION__, uidlist.count()); //Check the entries of the KDE addressbook against the last entries seen by the sync-engine for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) { //Get the revision date of the KDE addressbook entry. //Regard entries with invalid revision dates as having just been changed. osync_debug("kde", 3, "new entry, uid: %s", it->uid().latin1()); QDateTime revdate = it->revision(); if (!revdate.isValid()) { revdate = newsyncdate; //use date of this sync as the revision date. it->setRevision(revdate); //update the Addressbook entry for future reference. } // gmalloc a changed_object for this phonebook entry //FIXME: deallocate it somewhere OSyncChange *chg= osync_change_new(); osync_change_set_member(chg, member); QCString hash(revdate.toString()); osync_change_set_hash(chg, hash); osync_change_set_uid(chg, it->uid().latin1()); // Convert the VCARD data into a string KABC::VCardConverter converter; QString card = converter.createVCard(*it); QString data(card.latin1()); //FIXME: deallocate data somewhere osync_change_set_data(chg, strdup(data), data.length(), 1); // set the remaining fields osync_change_set_objtype_string(chg, "contact"); osync_change_set_objformat_string(chg, "vcard"); osync_change_set_hash(chg, hash.data()); /*FIXME: slowsync */ if (osync_hashtable_detect_change(hashtable, chg, slow_sync)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } osync_hashtable_report_deleted(hashtable, ctx, slow_sync); return 0; } int access(OSyncChange *chg) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s()",__FUNCTION__); int result = 0; // Ensure we still have a lock on the KDE addressbook (we ought to) if (addressbookticket==NULL) { //This should never happen, but just in case.... osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync."); return -1; } KABC::VCardConverter converter; OSyncChangeType chtype = osync_change_get_changetype(chg); char *uid = osync_change_get_uid(chg); /* treat modified objects without UIDs as if they were newly added objects */ if (chtype == CHANGE_MODIFIED && !uid) chtype = CHANGE_ADDED; // convert VCARD string from obj->comp into an Addresse object. char *data; size_t data_size; data = (char*)osync_change_get_data(chg); data_size = osync_change_get_datasize(chg); switch(chtype) { case CHANGE_MODIFIED: { unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has the correct UID addressee.setUid(QString(uid)); // replace the current addressbook entry (if any) with the new one addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)", uid); result = 0; break; } case CHANGE_ADDED: { // convert VCARD string from obj->comp into an Addresse object // KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first. unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has a NULL UID //addressee.setUid(QString(NULL)); if (!addressee.uid()) { osync_debug("kde", 1, "New addresse has null uid!"); addressee.setUid(KApplication::randomString( 10 )); } // add the new address to the addressbook addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)", addressee.uid().latin1()); // return the UID of the new entry along with the result osync_change_set_uid(chg, addressee.uid().latin1()); result = 0; break; } case CHANGE_DELETED: { if (uid==NULL) { result = 1; break; } //find addressbook entry with matching UID and delete it KABC::Addressee addressee = addressbookptr->findByUid(QString(uid)); if(!addressee.isEmpty()) addressbookptr->removeAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)", uid); result = 0; break; } default: result = 0; } //Save the changes without dropping the lock addressbookticket->resource()->save(addressbookticket); return result; } int commit_change(OSyncChange *chg) { int ret; if ( (ret = access(chg)) < 0) return ret; osync_hashtable_update_hash(hashtable, chg); return 0; } }; static KApplication *applicationptr=NULL; static char name[] = "kde-opensync-plugin"; static char *argv[] = {name,0}; static kaddrbook *addrbook_for_context(OSyncContext *ctx) { return (kaddrbook *)osync_context_get_plugin_data(ctx); } static void *kde_initialize(OSyncMember *member) { kaddrbook *addrbook; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); osync_debug("kde", 3, "kdepim_plugin: %s", __FUNCTION__); KCmdLineArgs::init(1, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false); applicationptr = new KApplication(); /* Allocate and initialise a kaddrbook object. */ addrbook = new kaddrbook(member); if (!addrbook) //FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case return NULL; /* Return kaddrbook object to the sync engine */ return (void*)addrbook; } static void kde_finalize(void *data) { osync_debug("kde", 3, "kdepim_plugin: %s()", __FUNCTION__); kaddrbook *addrbook = (kaddrbook *)data; delete addrbook; if (applicationptr) { delete applicationptr; applicationptr = 0; } } static void kde_connect(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); if (addrbook->connect() < 0) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook"); return; } osync_context_report_success(ctx); } static void kde_disconnect(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); if (addrbook->disconnect() < 0) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook"); return; } osync_context_report_success(ctx); } static void kde_get_changeinfo(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); osync_debug("kde", 3, "kdepim_plugin: %s",__FUNCTION__); int err = addrbook->get_changes(ctx); if (err) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't access KDE addressbook"); return; } osync_context_report_success(ctx); return; } static osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); err = addrbook->commit_change(change); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } static osync_bool kde_access(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); err = addrbook->access(change); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } extern "C" { void get_info(OSyncPluginInfo *info) { info->version = 1; info->name = "kde-sync"; info->description = i18n("Plugin for the KDE 3.x Addressbook"); info->functions.initialize = kde_initialize; info->functions.connect = kde_connect; info->functions.disconnect = kde_disconnect; info->functions.finalize = kde_finalize; info->functions.get_changeinfo = kde_get_changeinfo; osync_plugin_accept_objtype(info, "contact"); osync_plugin_accept_objformat(info, "contact", "vcard"); osync_plugin_set_commit_objformat(info, "contact", "vcard", kde_commit_change); osync_plugin_set_access_objformat(info, "contact", "vcard", kde_access); } }// extern "C" <commit_msg>Set the hash values correctly<commit_after>/*********************************************************************** OpenSync Plugin for KDE 3.x Copyright (C) 2004 Stewart Heitmann <sheitmann@users.sourceforge.net> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. *************************************************************************/ /* * 03 Nov 2004 - Eduardo Pereira Habkost <ehabkost@conectiva.com.br> * - Ported to OpenSync plugin interface */ extern "C" { #include <opensync/opensync.h> #include "kaddrbook.h" } #include <kabc/stdaddressbook.h> #include <kabc/vcardconverter.h> #include <kabc/resource.h> #include <kcmdlineargs.h> #include <kapplication.h> #include <klocale.h> #include <qsignal.h> #include <qfile.h> static void unfold_vcard(char *vcard, size_t *size) { char* in = vcard; char* out = vcard; char *end = vcard + *size; while ( in < end) { /* remove any occurrences of "=[CR][LF]" */ /* these denote folded line markers in VCARD format. */ /* Dont know why, but Evolution uses the leading "=" */ /* character to (presumably) denote a control sequence. */ /* This is not quite how I interpret the VCARD RFC2426 */ /* spec (section 2.6 line delimiting and folding). */ /* This seems to work though, so thats the main thing! */ if (in[0]=='=' && in[1]==13 && in[2]==10) in+=3; else *out++ = *in++; } *size = out - vcard; } class kaddrbook { private: KABC::AddressBook* addressbookptr; KABC::Ticket* addressbookticket; QDateTime syncdate, newsyncdate; OSyncMember *member; OSyncHashTable *hashtable; public: kaddrbook(OSyncMember *memb) :member(memb) { //osync_debug("kde", 3, "kdepim_plugin: %s(%s)", __FUNCTION__); //get a handle to the standard KDE addressbook addressbookptr = KABC::StdAddressBook::self(); //ensure a NULL Ticket ptr addressbookticket=NULL; hashtable = osync_hashtable_new(); osync_hashtable_load(hashtable, member); } /** Calculate the hash value for an Addressee. * Should be called before returning/writing the * data, because the revision of the Addressee * can be changed. */ QString calc_hash(KABC::Addressee &e) { QDateTime revdate = e.revision(); if (!revdate.isValid()) { revdate = newsyncdate; //use date of this sync as the revision date. e.setRevision(revdate); //update the Addressbook entry for future reference. } return revdate.toString(); } int connect() { //Lock the addressbook addressbookticket = addressbookptr->requestSaveTicket(); if (!addressbookticket) { osync_debug("kde", 3, "kdepim_plugin: couldnt lock KDE addressbook, aborting sync."); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook locked OK."); return 0; } int disconnect() { //Unlock the addressbook addressbookptr->save(addressbookticket); addressbookticket = NULL; return 0; } int get_changes(OSyncContext *ctx) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s(newdbs=%d)", __FUNCTION__, newdbs); osync_bool slow_sync = osync_member_get_slow_sync(member, "contact"); //remember when we started this current sync newsyncdate = QDateTime::currentDateTime(); // We must reload the KDE addressbook in order to retrieve the latest changes. if (!addressbookptr->load()) { osync_debug("kde", 3, "kdepim_plugin: couldnt reload KDE addressbook, aborting sync."); return -1; } osync_debug("kde", 3, "kdepim_plugin: KDE addressbook reloaded OK."); //osync_debug("kde", 3, "%s: %s : plugin UID list has %d entries", __FILE__, __FUNCTION__, uidlist.count()); //Check the entries of the KDE addressbook against the last entries seen by the sync-engine for (KABC::AddressBook::Iterator it=addressbookptr->begin(); it!=addressbookptr->end(); it++ ) { //Get the revision date of the KDE addressbook entry. //Regard entries with invalid revision dates as having just been changed. osync_debug("kde", 3, "new entry, uid: %s", it->uid().latin1()); QString hash = calc_hash(*it); // gmalloc a changed_object for this phonebook entry //FIXME: deallocate it somewhere OSyncChange *chg= osync_change_new(); osync_change_set_member(chg, member); osync_change_set_hash(chg, hash); osync_change_set_uid(chg, it->uid().latin1()); // Convert the VCARD data into a string KABC::VCardConverter converter; QString card = converter.createVCard(*it); QString data(card.latin1()); //FIXME: deallocate data somewhere osync_change_set_data(chg, strdup(data), data.length(), 1); // set the remaining fields osync_change_set_objtype_string(chg, "contact"); osync_change_set_objformat_string(chg, "vcard"); osync_change_set_hash(chg, hash.data()); /*FIXME: slowsync */ if (osync_hashtable_detect_change(hashtable, chg, slow_sync)) { osync_context_report_change(ctx, chg); osync_hashtable_update_hash(hashtable, chg); } } osync_hashtable_report_deleted(hashtable, ctx, slow_sync); return 0; } int access(OSyncChange *chg) { //osync_debug("kde", 3, "kdepim_plugin: kaddrbook::%s()",__FUNCTION__); int result = 0; // Ensure we still have a lock on the KDE addressbook (we ought to) if (addressbookticket==NULL) { //This should never happen, but just in case.... osync_debug("kde", 3, "kdepim_plugin: lock on KDE addressbook was lost, aborting sync."); return -1; } KABC::VCardConverter converter; OSyncChangeType chtype = osync_change_get_changetype(chg); char *uid = osync_change_get_uid(chg); /* treat modified objects without UIDs as if they were newly added objects */ if (chtype == CHANGE_MODIFIED && !uid) chtype = CHANGE_ADDED; // convert VCARD string from obj->comp into an Addresse object. char *data; size_t data_size; data = (char*)osync_change_get_data(chg); data_size = osync_change_get_datasize(chg); switch(chtype) { case CHANGE_MODIFIED: { unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); // ensure it has the correct UID addressee.setUid(QString(uid)); // replace the current addressbook entry (if any) with the new one addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY UPDATED (UID=%s)", uid); result = 0; break; } case CHANGE_ADDED: { // convert VCARD string from obj->comp into an Addresse object // KABC::VCardConverter doesnt do VCARD unfolding so we must do it ourselves first. unfold_vcard(data, &data_size); KABC::Addressee addressee = converter.parseVCard(QString::fromLatin1(data, data_size)); QString hash = calc_hash(addressee); // ensure it has a NULL UID //addressee.setUid(QString(NULL)); if (!addressee.uid()) { osync_debug("kde", 1, "New addresse has null uid!"); addressee.setUid(KApplication::randomString( 10 )); } // add the new address to the addressbook addressbookptr->insertAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY ADDED (UID=%s)", addressee.uid().latin1()); // return the UID of the new entry along with the result osync_change_set_uid(chg, addressee.uid().latin1()); osync_change_set_hash(chg, hash); result = 0; break; } case CHANGE_DELETED: { if (uid==NULL) { result = 1; break; } //find addressbook entry with matching UID and delete it KABC::Addressee addressee = addressbookptr->findByUid(QString(uid)); if(!addressee.isEmpty()) addressbookptr->removeAddressee(addressee); osync_debug("kde", 3, "kdepim_plugin: KDE ADDRESSBOOK ENTRY DELETED (UID=%s)", uid); result = 0; break; } default: result = 0; } //Save the changes without dropping the lock addressbookticket->resource()->save(addressbookticket); return result; } int commit_change(OSyncChange *chg) { int ret; if ( (ret = access(chg)) < 0) return ret; osync_hashtable_update_hash(hashtable, chg); return 0; } }; static KApplication *applicationptr=NULL; static char name[] = "kde-opensync-plugin"; static char *argv[] = {name,0}; static kaddrbook *addrbook_for_context(OSyncContext *ctx) { return (kaddrbook *)osync_context_get_plugin_data(ctx); } static void *kde_initialize(OSyncMember *member) { kaddrbook *addrbook; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); osync_debug("kde", 3, "kdepim_plugin: %s", __FUNCTION__); KCmdLineArgs::init(1, argv, "kde-opensync-plugin", i18n("KOpenSync"), "KDE OpenSync plugin", "0.1", false); applicationptr = new KApplication(); /* Allocate and initialise a kaddrbook object. */ addrbook = new kaddrbook(member); if (!addrbook) //FIXME: Check if OSYNC_ERROR_GENERIC is the righ error code in this case return NULL; /* Return kaddrbook object to the sync engine */ return (void*)addrbook; } static void kde_finalize(void *data) { osync_debug("kde", 3, "kdepim_plugin: %s()", __FUNCTION__); kaddrbook *addrbook = (kaddrbook *)data; delete addrbook; if (applicationptr) { delete applicationptr; applicationptr = 0; } } static void kde_connect(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); if (addrbook->connect() < 0) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook"); return; } osync_context_report_success(ctx); } static void kde_disconnect(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); if (addrbook->disconnect() < 0) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't lock KDE addressbook"); return; } osync_context_report_success(ctx); } static void kde_get_changeinfo(OSyncContext *ctx) { kaddrbook *addrbook = addrbook_for_context(ctx); osync_debug("kde", 3, "kdepim_plugin: %s",__FUNCTION__); int err = addrbook->get_changes(ctx); if (err) { osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't access KDE addressbook"); return; } osync_context_report_success(ctx); return; } static osync_bool kde_commit_change(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); err = addrbook->commit_change(change); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } static osync_bool kde_access(OSyncContext *ctx, OSyncChange *change) { kaddrbook *addrbook = addrbook_for_context(ctx); int err; osync_debug("kde", 3, "kdepim_plugin: %s()",__FUNCTION__); err = addrbook->access(change); if (err) osync_context_report_error(ctx, OSYNC_ERROR_GENERIC, "Couldn't update KDE addressbook"); else osync_context_report_success(ctx); /*FIXME: What should be returned? */ return true; } extern "C" { void get_info(OSyncPluginInfo *info) { info->version = 1; info->name = "kde-sync"; info->description = i18n("Plugin for the KDE 3.x Addressbook"); info->functions.initialize = kde_initialize; info->functions.connect = kde_connect; info->functions.disconnect = kde_disconnect; info->functions.finalize = kde_finalize; info->functions.get_changeinfo = kde_get_changeinfo; osync_plugin_accept_objtype(info, "contact"); osync_plugin_accept_objformat(info, "contact", "vcard"); osync_plugin_set_commit_objformat(info, "contact", "vcard", kde_commit_change); osync_plugin_set_access_objformat(info, "contact", "vcard", kde_access); } }// extern "C" <|endoftext|>
<commit_before>#pragma once #include <exception> #include <string> class SensorBuildException : public std::exception { public: SensorBuildException(const std::string& message) : message(message) { } virtual const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; class ControllerBuildException : public std::exception { public: ControllerBuildException(const std::string& message) : message(message) { } virtual const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; <commit_msg>errors: add configuration exception<commit_after>#pragma once #include <exception> #include <string> class SensorBuildException : public std::exception { public: SensorBuildException(const std::string& message) : message(message) { } virtual const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; class ControllerBuildException : public std::exception { public: ControllerBuildException(const std::string& message) : message(message) { } virtual const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; class ConfigurationException : public std::exception { public: ConfigurationException(const std::string& message) : message(message) { } virtual const char* what() const noexcept override { return message.c_str(); } private: std::string message; }; <|endoftext|>
<commit_before>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <stdexcept> #include <thrift/lib/cpp2/server/ResourcePool.h> namespace apache::thrift { // ResourcePool ResourcePool::ResourcePool( std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController, std::string_view name) : requestPile_(std::move(requestPile)), executor_(executor), concurrencyController_(std::move(concurrencyController)), name_(name) { // Current preconditions - either we have all three of these or none of them if (requestPile_ && concurrencyController_ && executor_) { // This is an async pool - that's allowed. } else { // This is a sync/eb pool. DCHECK(!requestPile_ && !concurrencyController && !executor_); } } ResourcePool::~ResourcePool() { if (concurrencyController_) { concurrencyController_->stop(); } } std::optional<ServerRequestRejection> ResourcePool::accept( ServerRequest&& request) { if (requestPile_) { // This pool is async, enqueue it on the requestPile auto result = requestPile_->enqueue(std::move(request)); if (result) { return result; } concurrencyController_->onEnqueued(); return std::optional<ServerRequestRejection>(std::nullopt); } else { // This pool is sync, just now we execute the request inline. AsyncProcessorHelper::executeRequest(std::move(request)); return std::optional<ServerRequestRejection>(std::nullopt); } } // ResourcePoolSet void ResourcePoolSet::setResourcePool( ResourcePoolHandle const& handle, std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController) { if (resourcePoolsLock_) { throw std::logic_error("Cannot setResourcePool() after lock()"); } auto rp = resourcePools_.wlock(); rp->resize(std::max(rp->size(), handle.index() + 1)); if (rp->at(handle.index())) { LOG(ERROR) << "Cannot overwrite resourcePool:" << handle.name(); throw std::invalid_argument("Cannot overwrite resourcePool"); } std::unique_ptr<ResourcePool> pool{new ResourcePool{ std::move(requestPile), executor, std::move(concurrencyController), handle.name()}}; rp->at(handle.index()) = std::move(pool); } ResourcePoolHandle ResourcePoolSet::addResourcePool( std::string_view poolName, std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController) { if (resourcePoolsLock_) { throw std::logic_error("Cannot addResourcePool() after lock()"); } auto rp = resourcePools_.wlock(); std::unique_ptr<ResourcePool> pool{new ResourcePool{ std::move(requestPile), executor, std::move(concurrencyController), poolName}}; // Ensure that any default slots have been initialized (with empty unique_ptr // if necessary). rp->resize(std::max(rp->size(), ResourcePoolHandle::kMaxReservedHandle + 1)); rp->emplace_back(std::move(pool)); return ResourcePoolHandle::makeHandle(poolName, rp->size() - 1); } void ResourcePoolSet::lock() const { auto lock = resourcePools_.rlock(); resourcePoolsLock_ = std::move(lock); } std::optional<ResourcePoolHandle> ResourcePoolSet::findResourcePool( std::string_view poolName) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); for (std::size_t i = 0; i < lock->size(); ++i) { if (lock->at(i) && lock->at(i)->name() == poolName) { return ResourcePoolHandle::makeHandle(poolName, i); } } return std::nullopt; } bool ResourcePoolSet::hasResourcePool(const ResourcePoolHandle& handle) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); if (handle.index() >= lock->size()) { return false; } return static_cast<bool>((*lock)[handle.index()]); } ResourcePool& ResourcePoolSet::resourcePool( const ResourcePoolHandle& handle) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); DCHECK_LT(handle.index(), lock->size()); DCHECK((*lock)[handle.index()]); return *(*lock)[handle.index()].get(); } bool ResourcePoolSet::empty() const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); return lock->empty(); } void ResourcePoolSet::stopAndJoin() { resourcePoolsLock_.unlock(); auto rp = resourcePools_.wlock(); for (auto& resourcePool : *rp) { if (resourcePool && resourcePool->concurrencyController()) { resourcePool->concurrencyController().value()->stop(); } } for (auto& resourcePool : *rp) { if (resourcePool && resourcePool->executor()) { resourcePool->executor().value()->join(); } } } } // namespace apache::thrift <commit_msg>Fix queue timeouts firing when using async_eb + ResourcePools<commit_after>/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <stdexcept> #include <thrift/lib/cpp2/server/ResourcePool.h> namespace apache::thrift { // ResourcePool ResourcePool::ResourcePool( std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController, std::string_view name) : requestPile_(std::move(requestPile)), executor_(executor), concurrencyController_(std::move(concurrencyController)), name_(name) { // Current preconditions - either we have all three of these or none of them if (requestPile_ && concurrencyController_ && executor_) { // This is an async pool - that's allowed. } else { // This is a sync/eb pool. DCHECK(!requestPile_ && !concurrencyController && !executor_); } } ResourcePool::~ResourcePool() { if (concurrencyController_) { concurrencyController_->stop(); } } std::optional<ServerRequestRejection> ResourcePool::accept( ServerRequest&& request) { if (requestPile_) { // This pool is async, enqueue it on the requestPile auto result = requestPile_->enqueue(std::move(request)); if (result) { return result; } concurrencyController_->onEnqueued(); return std::optional<ServerRequestRejection>(std::nullopt); } else { // Trigger processing of request and check for queue timeouts. if (!request.request()->getShouldStartProcessing()) { auto eb = detail::ServerRequestHelper::eventBase(request); HandlerCallbackBase::releaseRequest( detail::ServerRequestHelper::request(std::move(request)), eb); return std::optional<ServerRequestRejection>(std::nullopt); } // This pool is sync, just now we execute the request inline. AsyncProcessorHelper::executeRequest(std::move(request)); return std::optional<ServerRequestRejection>(std::nullopt); } } // ResourcePoolSet void ResourcePoolSet::setResourcePool( ResourcePoolHandle const& handle, std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController) { if (resourcePoolsLock_) { throw std::logic_error("Cannot setResourcePool() after lock()"); } auto rp = resourcePools_.wlock(); rp->resize(std::max(rp->size(), handle.index() + 1)); if (rp->at(handle.index())) { LOG(ERROR) << "Cannot overwrite resourcePool:" << handle.name(); throw std::invalid_argument("Cannot overwrite resourcePool"); } std::unique_ptr<ResourcePool> pool{new ResourcePool{ std::move(requestPile), executor, std::move(concurrencyController), handle.name()}}; rp->at(handle.index()) = std::move(pool); } ResourcePoolHandle ResourcePoolSet::addResourcePool( std::string_view poolName, std::unique_ptr<RequestPileInterface>&& requestPile, std::shared_ptr<folly::ThreadPoolExecutor> executor, std::unique_ptr<ConcurrencyControllerInterface>&& concurrencyController) { if (resourcePoolsLock_) { throw std::logic_error("Cannot addResourcePool() after lock()"); } auto rp = resourcePools_.wlock(); std::unique_ptr<ResourcePool> pool{new ResourcePool{ std::move(requestPile), executor, std::move(concurrencyController), poolName}}; // Ensure that any default slots have been initialized (with empty unique_ptr // if necessary). rp->resize(std::max(rp->size(), ResourcePoolHandle::kMaxReservedHandle + 1)); rp->emplace_back(std::move(pool)); return ResourcePoolHandle::makeHandle(poolName, rp->size() - 1); } void ResourcePoolSet::lock() const { auto lock = resourcePools_.rlock(); resourcePoolsLock_ = std::move(lock); } std::optional<ResourcePoolHandle> ResourcePoolSet::findResourcePool( std::string_view poolName) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); for (std::size_t i = 0; i < lock->size(); ++i) { if (lock->at(i) && lock->at(i)->name() == poolName) { return ResourcePoolHandle::makeHandle(poolName, i); } } return std::nullopt; } bool ResourcePoolSet::hasResourcePool(const ResourcePoolHandle& handle) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); if (handle.index() >= lock->size()) { return false; } return static_cast<bool>((*lock)[handle.index()]); } ResourcePool& ResourcePoolSet::resourcePool( const ResourcePoolHandle& handle) const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); DCHECK_LT(handle.index(), lock->size()); DCHECK((*lock)[handle.index()]); return *(*lock)[handle.index()].get(); } bool ResourcePoolSet::empty() const { ResourcePools::ConstLockedPtr localLock; auto& lock = resourcePoolsLock_ ? resourcePoolsLock_ : localLock = resourcePools_.rlock(); return lock->empty(); } void ResourcePoolSet::stopAndJoin() { resourcePoolsLock_.unlock(); auto rp = resourcePools_.wlock(); for (auto& resourcePool : *rp) { if (resourcePool && resourcePool->concurrencyController()) { resourcePool->concurrencyController().value()->stop(); } } for (auto& resourcePool : *rp) { if (resourcePool && resourcePool->executor()) { resourcePool->executor().value()->join(); } } } } // namespace apache::thrift <|endoftext|>
<commit_before>// @(#)root/tmva $Id$ // Author: Kim Albertsson /************************************************************************* * Copyright (C) 2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /*! \class TMVA::MethodCrossValidation \ingroup TMVA */ #include "TMVA/MethodCrossValidation.h" #include "TMVA/ClassifierFactory.h" #include "TMVA/Config.h" #include "TMVA/CvSplit.h" #include "TMVA/MethodCategory.h" #include "TMVA/Tools.h" #include "TMVA/Types.h" #include "TSystem.h" REGISTER_METHOD(CrossValidation) ClassImp(TMVA::MethodCrossValidation); //////////////////////////////////////////////////////////////////////////////// /// TMVA::MethodCrossValidation::MethodCrossValidation(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption) : TMVA::MethodBase(jobName, Types::kCrossValidation, methodTitle, theData, theOption) { } //////////////////////////////////////////////////////////////////////////////// TMVA::MethodCrossValidation::MethodCrossValidation(DataSetInfo &theData, const TString &theWeightFile) : TMVA::MethodBase(Types::kCrossValidation, theData, theWeightFile) { } //////////////////////////////////////////////////////////////////////////////// /// Destructor. /// TMVA::MethodCrossValidation::~MethodCrossValidation(void) {} //////////////////////////////////////////////////////////////////////////////// void TMVA::MethodCrossValidation::DeclareOptions() { DeclareOptionRef(fEncapsulatedMethodName, "EncapsulatedMethodName", ""); DeclareOptionRef(fEncapsulatedMethodTypeName, "EncapsulatedMethodTypeName", ""); DeclareOptionRef(fNumFolds, "NumFolds", "Number of folds to generate"); DeclareOptionRef(fOutputEnsembling = TString("None"), "OutputEnsembling", "Combines output from contained methods. If None, no combination is performed. (default None)"); AddPreDefVal(TString("None")); AddPreDefVal(TString("Avg")); DeclareOptionRef(fSplitExprString, "SplitExpr", "The expression used to assign events to folds"); } //////////////////////////////////////////////////////////////////////////////// /// Options that are used ONLY for the READER to ensure backward compatibility. void TMVA::MethodCrossValidation::DeclareCompatibilityOptions() { MethodBase::DeclareCompatibilityOptions(); } //////////////////////////////////////////////////////////////////////////////// /// The option string is decoded, for available options see "DeclareOptions". void TMVA::MethodCrossValidation::ProcessOptions() { Log() << kDEBUG << "ProcessOptions -- fNumFolds: " << fNumFolds << Endl; Log() << kDEBUG << "ProcessOptions -- fEncapsulatedMethodName: " << fEncapsulatedMethodName << Endl; Log() << kDEBUG << "ProcessOptions -- fEncapsulatedMethodTypeName: " << fEncapsulatedMethodTypeName << Endl; fSplitExpr = std::unique_ptr<CvSplitCrossValidationExpr>(new CvSplitCrossValidationExpr(DataInfo(), fSplitExprString)); for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); Log() << kINFO << "Reading weightfile: " << weightfile << Endl; MethodBase *fold_method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); fEncapsulatedMethods.push_back(fold_method); } } //////////////////////////////////////////////////////////////////////////////// /// Common initialisation with defaults for the Method. void TMVA::MethodCrossValidation::Init(void) { fMulticlassValues = std::vector<Float_t>(DataInfo().GetNClasses()); fRegressionValues = std::vector<Float_t>(DataInfo().GetNTargets()); } //////////////////////////////////////////////////////////////////////////////// /// Reset the method, as if it had just been instantiated (forget all training etc.). void TMVA::MethodCrossValidation::Reset(void) {} //////////////////////////////////////////////////////////////////////////////// /// \brief Returns filename of weight file for a given fold. /// \param[in] iFold Ordinal of the fold. Range: 0 to NumFolds exclusive. /// TString TMVA::MethodCrossValidation::GetWeightFileNameForFold(UInt_t iFold) const { if (iFold >= fNumFolds) { Log() << kFATAL << iFold << " out of range. " << "Should be < " << fNumFolds << "." << Endl; } TString foldStr = Form("fold%i", iFold + 1); TString fileDir = gSystem->DirName(GetWeightFileName()); TString weightfile = fileDir + "/" + fJobName + "_" + fEncapsulatedMethodName + "_" + foldStr + ".weights.xml"; return weightfile; } //////////////////////////////////////////////////////////////////////////////// /// Call the Optimizer with the set of parameters and ranges that /// are meant to be tuned. // std::map<TString,Double_t> TMVA::MethodCrossValidation::OptimizeTuningParameters(TString fomType, TString fitType) // { // } //////////////////////////////////////////////////////////////////////////////// /// Set the tuning parameters according to the argument. // void TMVA::MethodCrossValidation::SetTuneParameters(std::map<TString,Double_t> tuneParameters) // { // } //////////////////////////////////////////////////////////////////////////////// /// training. void TMVA::MethodCrossValidation::Train() {} //////////////////////////////////////////////////////////////////////////////// /// \brief Reads in a weight file an instantiates the corresponding method /// \param[in] methodTypeName Canonical name of the method type. E.g. `"BDT"` /// for Boosted Decision Trees. /// \param[in] weightfile File to read method parameters from TMVA::MethodBase * TMVA::MethodCrossValidation::InstantiateMethodFromXML(TString methodTypeName, TString weightfile) const { TMVA::MethodBase *m = dynamic_cast<MethodBase *>( ClassifierFactory::Instance().Create(std::string(methodTypeName), DataInfo(), weightfile)); if (m->GetMethodType() == Types::kCategory) { Log() << kFATAL << "MethodCategory not supported for the moment." << Endl; } TString fileDir = TString(DataInfo().GetName()) + "/" + gConfig().GetIONames().fWeightFileDir; m->SetWeightFileDir(fileDir); // m->SetModelPersistence(fModelPersistence); // m->SetSilentFile(IsSilentFile()); m->SetAnalysisType(fAnalysisType); m->SetupMethod(); m->ReadStateFromFile(); // m->SetTestvarName(testvarName); return m; } //////////////////////////////////////////////////////////////////////////////// /// Write weights to XML. void TMVA::MethodCrossValidation::AddWeightsXMLTo(void *parent) const { void *wght = gTools().AddChild(parent, "Weights"); gTools().AddAttr(wght, "JobName", fJobName); gTools().AddAttr(wght, "SplitExpr", fSplitExprString); gTools().AddAttr(wght, "NumFolds", fNumFolds); gTools().AddAttr(wght, "EncapsulatedMethodName", fEncapsulatedMethodName); gTools().AddAttr(wght, "EncapsulatedMethodTypeName", fEncapsulatedMethodTypeName); gTools().AddAttr(wght, "OutputEnsembling", fOutputEnsembling); for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); // TODO: Add a swithch in options for using either split files or only one. // TODO: This would store the method inside MethodCrossValidation // Another option is to store the folds as separate files. // // Retrieve encap. method for fold n // MethodBase * method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); // // // Serialise encapsulated method for fold n // void* foldNode = gTools().AddChild(parent, foldStr); // method->WriteStateToXML(foldNode); } } //////////////////////////////////////////////////////////////////////////////// /// Reads from the xml file. /// void TMVA::MethodCrossValidation::ReadWeightsFromXML(void *parent) { gTools().ReadAttr(parent, "JobName", fJobName); gTools().ReadAttr(parent, "SplitExpr", fSplitExprString); gTools().ReadAttr(parent, "NumFolds", fNumFolds); gTools().ReadAttr(parent, "EncapsulatedMethodName", fEncapsulatedMethodName); gTools().ReadAttr(parent, "EncapsulatedMethodTypeName", fEncapsulatedMethodTypeName); gTools().ReadAttr(parent, "OutputEnsembling", fOutputEnsembling); // Read in methods for all folds for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); Log() << kINFO << "Reading weightfile: " << weightfile << Endl; MethodBase *fold_method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); fEncapsulatedMethods.push_back(fold_method); } // SplitExpr fSplitExpr = std::unique_ptr<CvSplitCrossValidationExpr>(new CvSplitCrossValidationExpr(DataInfo(), fSplitExprString)); } //////////////////////////////////////////////////////////////////////////////// /// Read the weights /// void TMVA::MethodCrossValidation::ReadWeightsFromStream(std::istream & /*istr*/) { Log() << kFATAL << "CrossValidation currently supports only reading from XML." << Endl; } //////////////////////////////////////////////////////////////////////////////// /// Double_t TMVA::MethodCrossValidation::GetMvaValue(Double_t *err, Double_t *errUpper) { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetMvaValue(err, errUpper); } else if (fOutputEnsembling == "Avg") { Double_t val = 0.0; for (auto &m : fEncapsulatedMethods) { val += m->GetMvaValue(err, errUpper); } return val / fEncapsulatedMethods.size(); } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return 0; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// Get the multiclass MVA response. const std::vector<Float_t> &TMVA::MethodCrossValidation::GetMulticlassValues() { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetMulticlassValues(); } else if (fOutputEnsembling == "Avg") { for (auto &m : fEncapsulatedMethods) { auto methodValues = m->GetMulticlassValues(); for (size_t i = 0; i < methodValues.size(); ++i) { fMulticlassValues[i] += methodValues[i]; } } for (auto &e : fMulticlassValues) { e /= fEncapsulatedMethods.size(); } return fMulticlassValues; } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return fMulticlassValues; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// Get the regression value generated by the containing methods. const std::vector<Float_t> &TMVA::MethodCrossValidation::GetRegressionValues() { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetRegressionValues(); } else if (fOutputEnsembling == "Avg") { for (auto &e : fRegressionValues) { e = 0; } for (auto &m : fEncapsulatedMethods) { auto methodValues = m->GetRegressionValues(); for (size_t i = 0; i < methodValues.size(); ++i) { fRegressionValues[i] += methodValues[i]; } } for (auto &e : fRegressionValues) { e /= fEncapsulatedMethods.size(); } return fRegressionValues; } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return fRegressionValues; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::MethodCrossValidation::WriteMonitoringHistosToFile(void) const { // // Used for evaluation, which is outside the life time of MethodCrossEval. // Log() << kFATAL << "Method CrossValidation should not be created manually," // " only as part of using TMVA::Reader." << Endl; // return; } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::MethodCrossValidation::GetHelpMessage() const { Log() << kWARNING << "Method CrossValidation should not be created manually," " only as part of using TMVA::Reader." << Endl; } //////////////////////////////////////////////////////////////////////////////// /// const TMVA::Ranking *TMVA::MethodCrossValidation::CreateRanking() { return nullptr; } //////////////////////////////////////////////////////////////////////////////// Bool_t TMVA::MethodCrossValidation::HasAnalysisType(Types::EAnalysisType /*type*/, UInt_t /*numberClasses*/, UInt_t /*numberTargets*/) { return kTRUE; // if (fEncapsulatedMethods.size() == 0) {return kFALSE;} // if (fEncapsulatedMethods.at(0) == nullptr) {return kFALSE;} // return fEncapsulatedMethods.at(0)->HasAnalysisType(type, numberClasses, numberTargets); } //////////////////////////////////////////////////////////////////////////////// /// Make ROOT-independent C++ class for classifier response (classifier-specific implementation). void TMVA::MethodCrossValidation::MakeClassSpecific(std::ostream & /*fout*/, const TString & /*className*/) const { Log() << kWARNING << "MakeClassSpecific not implemented for CrossValidation" << Endl; } //////////////////////////////////////////////////////////////////////////////// /// Specific class header. void TMVA::MethodCrossValidation::MakeClassSpecificHeader(std::ostream & /*fout*/, const TString & /*className*/) const { Log() << kWARNING << "MakeClassSpecificHeader not implemented for CrossValidation" << Endl; } <commit_msg>[TMVA] CV - Fix output avg MethodCrossValidation init<commit_after>// @(#)root/tmva $Id$ // Author: Kim Albertsson /************************************************************************* * Copyright (C) 2018, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ /*! \class TMVA::MethodCrossValidation \ingroup TMVA */ #include "TMVA/MethodCrossValidation.h" #include "TMVA/ClassifierFactory.h" #include "TMVA/Config.h" #include "TMVA/CvSplit.h" #include "TMVA/MethodCategory.h" #include "TMVA/Tools.h" #include "TMVA/Types.h" #include "TSystem.h" REGISTER_METHOD(CrossValidation) ClassImp(TMVA::MethodCrossValidation); //////////////////////////////////////////////////////////////////////////////// /// TMVA::MethodCrossValidation::MethodCrossValidation(const TString &jobName, const TString &methodTitle, DataSetInfo &theData, const TString &theOption) : TMVA::MethodBase(jobName, Types::kCrossValidation, methodTitle, theData, theOption) { } //////////////////////////////////////////////////////////////////////////////// TMVA::MethodCrossValidation::MethodCrossValidation(DataSetInfo &theData, const TString &theWeightFile) : TMVA::MethodBase(Types::kCrossValidation, theData, theWeightFile) { } //////////////////////////////////////////////////////////////////////////////// /// Destructor. /// TMVA::MethodCrossValidation::~MethodCrossValidation(void) {} //////////////////////////////////////////////////////////////////////////////// void TMVA::MethodCrossValidation::DeclareOptions() { DeclareOptionRef(fEncapsulatedMethodName, "EncapsulatedMethodName", ""); DeclareOptionRef(fEncapsulatedMethodTypeName, "EncapsulatedMethodTypeName", ""); DeclareOptionRef(fNumFolds, "NumFolds", "Number of folds to generate"); DeclareOptionRef(fOutputEnsembling = TString("None"), "OutputEnsembling", "Combines output from contained methods. If None, no combination is performed. (default None)"); AddPreDefVal(TString("None")); AddPreDefVal(TString("Avg")); DeclareOptionRef(fSplitExprString, "SplitExpr", "The expression used to assign events to folds"); } //////////////////////////////////////////////////////////////////////////////// /// Options that are used ONLY for the READER to ensure backward compatibility. void TMVA::MethodCrossValidation::DeclareCompatibilityOptions() { MethodBase::DeclareCompatibilityOptions(); } //////////////////////////////////////////////////////////////////////////////// /// The option string is decoded, for available options see "DeclareOptions". void TMVA::MethodCrossValidation::ProcessOptions() { Log() << kDEBUG << "ProcessOptions -- fNumFolds: " << fNumFolds << Endl; Log() << kDEBUG << "ProcessOptions -- fEncapsulatedMethodName: " << fEncapsulatedMethodName << Endl; Log() << kDEBUG << "ProcessOptions -- fEncapsulatedMethodTypeName: " << fEncapsulatedMethodTypeName << Endl; fSplitExpr = std::unique_ptr<CvSplitCrossValidationExpr>(new CvSplitCrossValidationExpr(DataInfo(), fSplitExprString)); for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); Log() << kINFO << "Reading weightfile: " << weightfile << Endl; MethodBase *fold_method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); fEncapsulatedMethods.push_back(fold_method); } } //////////////////////////////////////////////////////////////////////////////// /// Common initialisation with defaults for the Method. void TMVA::MethodCrossValidation::Init(void) { fMulticlassValues = std::vector<Float_t>(DataInfo().GetNClasses()); fRegressionValues = std::vector<Float_t>(DataInfo().GetNTargets()); } //////////////////////////////////////////////////////////////////////////////// /// Reset the method, as if it had just been instantiated (forget all training etc.). void TMVA::MethodCrossValidation::Reset(void) {} //////////////////////////////////////////////////////////////////////////////// /// \brief Returns filename of weight file for a given fold. /// \param[in] iFold Ordinal of the fold. Range: 0 to NumFolds exclusive. /// TString TMVA::MethodCrossValidation::GetWeightFileNameForFold(UInt_t iFold) const { if (iFold >= fNumFolds) { Log() << kFATAL << iFold << " out of range. " << "Should be < " << fNumFolds << "." << Endl; } TString foldStr = Form("fold%i", iFold + 1); TString fileDir = gSystem->DirName(GetWeightFileName()); TString weightfile = fileDir + "/" + fJobName + "_" + fEncapsulatedMethodName + "_" + foldStr + ".weights.xml"; return weightfile; } //////////////////////////////////////////////////////////////////////////////// /// Call the Optimizer with the set of parameters and ranges that /// are meant to be tuned. // std::map<TString,Double_t> TMVA::MethodCrossValidation::OptimizeTuningParameters(TString fomType, TString fitType) // { // } //////////////////////////////////////////////////////////////////////////////// /// Set the tuning parameters according to the argument. // void TMVA::MethodCrossValidation::SetTuneParameters(std::map<TString,Double_t> tuneParameters) // { // } //////////////////////////////////////////////////////////////////////////////// /// training. void TMVA::MethodCrossValidation::Train() {} //////////////////////////////////////////////////////////////////////////////// /// \brief Reads in a weight file an instantiates the corresponding method /// \param[in] methodTypeName Canonical name of the method type. E.g. `"BDT"` /// for Boosted Decision Trees. /// \param[in] weightfile File to read method parameters from TMVA::MethodBase * TMVA::MethodCrossValidation::InstantiateMethodFromXML(TString methodTypeName, TString weightfile) const { TMVA::MethodBase *m = dynamic_cast<MethodBase *>( ClassifierFactory::Instance().Create(std::string(methodTypeName), DataInfo(), weightfile)); if (m->GetMethodType() == Types::kCategory) { Log() << kFATAL << "MethodCategory not supported for the moment." << Endl; } TString fileDir = TString(DataInfo().GetName()) + "/" + gConfig().GetIONames().fWeightFileDir; m->SetWeightFileDir(fileDir); // m->SetModelPersistence(fModelPersistence); // m->SetSilentFile(IsSilentFile()); m->SetAnalysisType(fAnalysisType); m->SetupMethod(); m->ReadStateFromFile(); // m->SetTestvarName(testvarName); return m; } //////////////////////////////////////////////////////////////////////////////// /// Write weights to XML. void TMVA::MethodCrossValidation::AddWeightsXMLTo(void *parent) const { void *wght = gTools().AddChild(parent, "Weights"); gTools().AddAttr(wght, "JobName", fJobName); gTools().AddAttr(wght, "SplitExpr", fSplitExprString); gTools().AddAttr(wght, "NumFolds", fNumFolds); gTools().AddAttr(wght, "EncapsulatedMethodName", fEncapsulatedMethodName); gTools().AddAttr(wght, "EncapsulatedMethodTypeName", fEncapsulatedMethodTypeName); gTools().AddAttr(wght, "OutputEnsembling", fOutputEnsembling); for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); // TODO: Add a swithch in options for using either split files or only one. // TODO: This would store the method inside MethodCrossValidation // Another option is to store the folds as separate files. // // Retrieve encap. method for fold n // MethodBase * method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); // // // Serialise encapsulated method for fold n // void* foldNode = gTools().AddChild(parent, foldStr); // method->WriteStateToXML(foldNode); } } //////////////////////////////////////////////////////////////////////////////// /// Reads from the xml file. /// void TMVA::MethodCrossValidation::ReadWeightsFromXML(void *parent) { gTools().ReadAttr(parent, "JobName", fJobName); gTools().ReadAttr(parent, "SplitExpr", fSplitExprString); gTools().ReadAttr(parent, "NumFolds", fNumFolds); gTools().ReadAttr(parent, "EncapsulatedMethodName", fEncapsulatedMethodName); gTools().ReadAttr(parent, "EncapsulatedMethodTypeName", fEncapsulatedMethodTypeName); gTools().ReadAttr(parent, "OutputEnsembling", fOutputEnsembling); // Read in methods for all folds for (UInt_t iFold = 0; iFold < fNumFolds; ++iFold) { TString weightfile = GetWeightFileNameForFold(iFold); Log() << kINFO << "Reading weightfile: " << weightfile << Endl; MethodBase *fold_method = InstantiateMethodFromXML(fEncapsulatedMethodTypeName, weightfile); fEncapsulatedMethods.push_back(fold_method); } // SplitExpr fSplitExpr = std::unique_ptr<CvSplitCrossValidationExpr>(new CvSplitCrossValidationExpr(DataInfo(), fSplitExprString)); } //////////////////////////////////////////////////////////////////////////////// /// Read the weights /// void TMVA::MethodCrossValidation::ReadWeightsFromStream(std::istream & /*istr*/) { Log() << kFATAL << "CrossValidation currently supports only reading from XML." << Endl; } //////////////////////////////////////////////////////////////////////////////// /// Double_t TMVA::MethodCrossValidation::GetMvaValue(Double_t *err, Double_t *errUpper) { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetMvaValue(err, errUpper); } else if (fOutputEnsembling == "Avg") { Double_t val = 0.0; for (auto &m : fEncapsulatedMethods) { val += m->GetMvaValue(err, errUpper); } return val / fEncapsulatedMethods.size(); } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return 0; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// Get the multiclass MVA response. const std::vector<Float_t> &TMVA::MethodCrossValidation::GetMulticlassValues() { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetMulticlassValues(); } else if (fOutputEnsembling == "Avg") { for (auto &e : fMulticlassValues) { e = 0; } for (auto &m : fEncapsulatedMethods) { auto methodValues = m->GetMulticlassValues(); for (size_t i = 0; i < methodValues.size(); ++i) { fMulticlassValues[i] += methodValues[i]; } } for (auto &e : fMulticlassValues) { e /= fEncapsulatedMethods.size(); } return fMulticlassValues; } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return fMulticlassValues; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// Get the regression value generated by the containing methods. const std::vector<Float_t> &TMVA::MethodCrossValidation::GetRegressionValues() { const Event *ev = GetEvent(); if (fOutputEnsembling == "None") { UInt_t iFold = fSplitExpr->Eval(fNumFolds, ev); return fEncapsulatedMethods.at(iFold)->GetRegressionValues(); } else if (fOutputEnsembling == "Avg") { for (auto &e : fRegressionValues) { e = 0; } for (auto &m : fEncapsulatedMethods) { auto methodValues = m->GetRegressionValues(); for (size_t i = 0; i < methodValues.size(); ++i) { fRegressionValues[i] += methodValues[i]; } } for (auto &e : fRegressionValues) { e /= fEncapsulatedMethods.size(); } return fRegressionValues; } else { Log() << kFATAL << "Ensembling type " << fOutputEnsembling << " unknown" << Endl; return fRegressionValues; // Cannot happen } } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::MethodCrossValidation::WriteMonitoringHistosToFile(void) const { // // Used for evaluation, which is outside the life time of MethodCrossEval. // Log() << kFATAL << "Method CrossValidation should not be created manually," // " only as part of using TMVA::Reader." << Endl; // return; } //////////////////////////////////////////////////////////////////////////////// /// void TMVA::MethodCrossValidation::GetHelpMessage() const { Log() << kWARNING << "Method CrossValidation should not be created manually," " only as part of using TMVA::Reader." << Endl; } //////////////////////////////////////////////////////////////////////////////// /// const TMVA::Ranking *TMVA::MethodCrossValidation::CreateRanking() { return nullptr; } //////////////////////////////////////////////////////////////////////////////// Bool_t TMVA::MethodCrossValidation::HasAnalysisType(Types::EAnalysisType /*type*/, UInt_t /*numberClasses*/, UInt_t /*numberTargets*/) { return kTRUE; // if (fEncapsulatedMethods.size() == 0) {return kFALSE;} // if (fEncapsulatedMethods.at(0) == nullptr) {return kFALSE;} // return fEncapsulatedMethods.at(0)->HasAnalysisType(type, numberClasses, numberTargets); } //////////////////////////////////////////////////////////////////////////////// /// Make ROOT-independent C++ class for classifier response (classifier-specific implementation). void TMVA::MethodCrossValidation::MakeClassSpecific(std::ostream & /*fout*/, const TString & /*className*/) const { Log() << kWARNING << "MakeClassSpecific not implemented for CrossValidation" << Endl; } //////////////////////////////////////////////////////////////////////////////// /// Specific class header. void TMVA::MethodCrossValidation::MakeClassSpecificHeader(std::ostream & /*fout*/, const TString & /*className*/) const { Log() << kWARNING << "MakeClassSpecificHeader not implemented for CrossValidation" << Endl; } <|endoftext|>
<commit_before>/* httprequest.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (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 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/httprequest.h> #include <tnt/httpparser.h> #include <sstream> #include <cxxtools/log.h> #include <cxxtools/thread.h> #include <sys/socket.h> #include <arpa/inet.h> #include <tnt/sessionscope.h> #include <errno.h> #include <string.h> #include "config.h" namespace tnt { log_define("tntnet.httprequest") //////////////////////////////////////////////////////////////////////// // HttpRequest // unsigned HttpRequest::serial_ = 0; HttpRequest::HttpRequest(const std::string& url) : ssl(false), locale_init(false), requestScope(0), applicationScope(0), threadScope(0), sessionScope(0), applicationScopeLocked(false), sessionScopeLocked(false) { std::istringstream s("GET " + url + " HTTP/1.1\r\n\r\n"); parse(s); } HttpRequest::HttpRequest(const HttpRequest& r) : pathinfo(r.pathinfo), args(r.args), qparam(r.qparam), peerAddr(r.peerAddr), serverAddr(r.serverAddr), ct(r.ct), mp(r.mp), ssl(r.ssl), serial(r.serial), locale_init(r.locale_init), locale(r.locale), requestScope(r.requestScope), applicationScope(r.applicationScope), threadScope(r.threadScope), sessionScope(r.sessionScope), applicationScopeLocked(false), sessionScopeLocked(false) { if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (threadScope) threadScope->addRef(); if (sessionScope) sessionScope->addRef(); } HttpRequest::~HttpRequest() { releaseLocks(); if (requestScope) requestScope->release(); if (applicationScope) applicationScope->release(); if (threadScope) threadScope->release(); if (sessionScope) sessionScope->release(); } HttpRequest& HttpRequest::operator= (const HttpRequest& r) { pathinfo = r.pathinfo; args = r.args; qparam = r.qparam; peerAddr = r.peerAddr; serverAddr = r.serverAddr; ct = r.ct; mp = r.mp; ssl = r.ssl; serial = r.serial; locale_init = r.locale_init; locale = r.locale; requestScope = r.requestScope; applicationScope = r.applicationScope; threadScope = r.threadScope; sessionScope = r.sessionScope; applicationScopeLocked = false; sessionScopeLocked = false; if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (threadScope) threadScope->addRef(); if (sessionScope) sessionScope->addRef(); return *this; } void HttpRequest::clear() { HttpMessage::clear(); pathinfo.clear(); args.clear(); qparam.clear(); ct = Contenttype(); mp = Multipart(); locale_init = false; if (requestScope) { requestScope->release(); requestScope = 0; } httpcookies.clear(); encodingRead = false; releaseLocks(); if (applicationScope) { applicationScope->release(); applicationScope = 0; } if (threadScope) { threadScope->release(); threadScope = 0; } if (sessionScope) { sessionScope->release(); sessionScope = 0; } } void HttpRequest::parse(std::istream& in) { Parser p(*this); p.parse(in); if (!p.failed()) doPostParse(); } void HttpRequest::doPostParse() { qparam.parse_url(getQueryString()); if (getMethod() == "POST") { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; if (in) { log_debug(httpheader::contentType << ' ' << in.str()); log_debug("type=" << ct.getType() << " subtype=" << ct.getSubtype()); if (ct.isMultipart()) { log_debug("multipart-boundary=" << ct.getBoundary()); mp.set(ct.getBoundary(), getBody()); for (Multipart::const_iterator it = mp.begin(); it != mp.end(); ++it) { // don't copy uploaded files into qparam to prevent unnecessery // copies of large chunks if (it->getFilename().empty()) { std::string multipartBody(it->getBodyBegin(), it->getBodyEnd()); log_debug("multipart-item name=" << it->getName() << " body=" << multipartBody); qparam.add(it->getName(), multipartBody); } } } else { qparam.parse_url(getBody()); } } else if (ct.getType() == "application" && ct.getSubtype() == "x-www-form-urlencoded") qparam.parse_url(getBody()); } { static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); serial = ++serial_; } } namespace { void formatIp(const sockaddr_storage& addr, std::string& str) { #ifdef HAVE_INET_NTOP const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr); char strbuf[INET6_ADDRSTRLEN]; inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf)); str = strbuf; #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); char* p = inet_ntoa(peerAddr.sin_addr); str = p; #endif } } std::string HttpRequest::getPeerIp() const { if (peerAddrStr.empty()) formatIp(peerAddr, peerAddrStr); return peerAddrStr; } std::string HttpRequest::getServerIp() const { if (serverAddrStr.empty()) formatIp(serverAddr, serverAddrStr); return serverAddrStr; } const std::locale& HttpRequest::getLocale() const { if (!locale_init) { static const std::string LANG = "LANG"; static const std::locale stdlocale(""); typedef std::map<std::string, std::locale> locale_map_type; static locale_map_type locale_map; static cxxtools::Mutex locale_monitor; locale_init = true; log_debug("HttpRequest::getLocale() " << qparam.dump()); std::string lang = qparam[LANG]; if (lang.empty() || lang == stdlocale.name()) locale = stdlocale; else { log_debug("LANG from query-parameter (" << lang << ')'); try { cxxtools::MutexLock lock(locale_monitor); locale_map_type::const_iterator it = locale_map.find(lang); if (it == locale_map.end()) { locale = std::locale(lang.c_str()); locale_map.insert(locale_map_type::value_type(lang, locale)); } else locale = it->second; } catch (const std::exception& e) { log_warn("unknown locale " << lang << ": " << e.what()); locale = stdlocale; locale_map.insert(locale_map_type::value_type(lang, locale)); } } log_debug("LANG=" << locale.name()); } return locale; } const Cookies& HttpRequest::getCookies() const { log_debug("HttpRequest::getCookies()"); if (!httpcookies.hasCookies()) { header_type::const_iterator it = header.find(httpheader::cookie); if (it != header.end()) { log_debug("parse cookie-header " << it->second); const_cast<HttpRequest*>(this)->httpcookies.set(it->second); } } return httpcookies; } const Encoding& HttpRequest::getEncoding() const { if (!encodingRead) { encoding.parse(getHeader(httpheader::acceptEncoding)); encodingRead = true; } return encoding; } namespace { class CompareNoCase { public: bool operator() (char c1, char c2) const { return tolower(c1) == tolower(c2); } }; } bool HttpRequest::keepAlive() const { header_type::const_iterator it = header.find(httpheader::connection); return it == header.end() ? getMajorVersion() == 1 && getMinorVersion() == 1 : it->second.size() >= httpheader::connectionKeepAlive.size() && std::equal(it->second.begin(), it->second.end(), httpheader::connectionKeepAlive.begin(), CompareNoCase()); } void HttpRequest::setApplicationScope(Scope* s) { if (applicationScope == s) return; if (applicationScope) { releaseApplicationScopeLock(); applicationScope->release(); } if (s) s->addRef(); applicationScope = s; } void HttpRequest::setThreadScope(Scope* s) { if (threadScope == s) return; if (threadScope) threadScope->release(); if (s) s->addRef(); threadScope = s; } void HttpRequest::setSessionScope(Sessionscope* s) { if (sessionScope == s) return; if (sessionScope) { releaseSessionScopeLock(); sessionScope->release(); } if (s) s->addRef(); sessionScope = s; } void HttpRequest::clearSession() { if (sessionScope) { log_info("end session"); releaseSessionScopeLock(); sessionScope->release(); sessionScope = 0; } } void HttpRequest::ensureApplicationScopeLock() { log_trace("ensureApplicationScopeLock; thread " << pthread_self()); ensureSessionScopeLock(); if (applicationScope && !applicationScopeLocked) { log_debug("lock application scope; thread" << pthread_self()); applicationScope->lock(); applicationScopeLocked = true; } else log_debug("applicationscope locked already"); } void HttpRequest::ensureSessionScopeLock() { log_trace("ensureSessionScopeLock; thread " << pthread_self()); if (sessionScope && !sessionScopeLocked) { log_debug("lock sessionscope; thread " << pthread_self()); sessionScope->lock(); sessionScopeLocked = true; } else log_debug("sessionscope locked already"); } void HttpRequest::releaseApplicationScopeLock() { log_trace("releaseApplicationScopeLock; thread " << pthread_self()); if (applicationScope && applicationScopeLocked) { log_debug("unlock applicationscope"); applicationScopeLocked = false; applicationScope->unlock(); } else log_debug("applicationscope not locked"); } void HttpRequest::releaseSessionScopeLock() { log_trace("releaseSessionScopeLock; thread " << pthread_self()); releaseApplicationScopeLock(); if (sessionScope && sessionScopeLocked) { log_debug("unlock sessionscope"); sessionScopeLocked = false; sessionScope->unlock(); } else log_debug("sessionscope not locked"); } Scope& HttpRequest::getRequestScope() { if (requestScope == 0) requestScope = new Scope(); return *requestScope; } Scope& HttpRequest::getThreadScope() { if (threadScope == 0) throw std::runtime_error("threadscope not set"); return *threadScope; } Scope& HttpRequest::getApplicationScope() { ensureApplicationScopeLock(); return *applicationScope; } Sessionscope& HttpRequest::getSessionScope() { if (!sessionScope) sessionScope = new Sessionscope(); ensureSessionScopeLock(); return *sessionScope; } bool HttpRequest::hasSessionScope() const { return sessionScope != 0 && !sessionScope->empty(); } } <commit_msg>don't release thread-scope - thread handles the lifetime<commit_after>/* httprequest.cpp * Copyright (C) 2003-2005 Tommi Maekitalo * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (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 * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include <tnt/httprequest.h> #include <tnt/httpparser.h> #include <sstream> #include <cxxtools/log.h> #include <cxxtools/thread.h> #include <sys/socket.h> #include <arpa/inet.h> #include <tnt/sessionscope.h> #include <errno.h> #include <string.h> #include "config.h" namespace tnt { log_define("tntnet.httprequest") //////////////////////////////////////////////////////////////////////// // HttpRequest // unsigned HttpRequest::serial_ = 0; HttpRequest::HttpRequest(const std::string& url) : ssl(false), locale_init(false), requestScope(0), applicationScope(0), threadScope(0), sessionScope(0), applicationScopeLocked(false), sessionScopeLocked(false) { std::istringstream s("GET " + url + " HTTP/1.1\r\n\r\n"); parse(s); } HttpRequest::HttpRequest(const HttpRequest& r) : pathinfo(r.pathinfo), args(r.args), qparam(r.qparam), peerAddr(r.peerAddr), serverAddr(r.serverAddr), ct(r.ct), mp(r.mp), ssl(r.ssl), serial(r.serial), locale_init(r.locale_init), locale(r.locale), requestScope(r.requestScope), applicationScope(r.applicationScope), threadScope(r.threadScope), sessionScope(r.sessionScope), applicationScopeLocked(false), sessionScopeLocked(false) { if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); } HttpRequest::~HttpRequest() { releaseLocks(); if (requestScope) requestScope->release(); if (applicationScope) applicationScope->release(); if (sessionScope) sessionScope->release(); } HttpRequest& HttpRequest::operator= (const HttpRequest& r) { pathinfo = r.pathinfo; args = r.args; qparam = r.qparam; peerAddr = r.peerAddr; serverAddr = r.serverAddr; ct = r.ct; mp = r.mp; ssl = r.ssl; serial = r.serial; locale_init = r.locale_init; locale = r.locale; requestScope = r.requestScope; applicationScope = r.applicationScope; threadScope = r.threadScope; sessionScope = r.sessionScope; applicationScopeLocked = false; sessionScopeLocked = false; if (requestScope) requestScope->addRef(); if (applicationScope) applicationScope->addRef(); if (sessionScope) sessionScope->addRef(); return *this; } void HttpRequest::clear() { HttpMessage::clear(); pathinfo.clear(); args.clear(); qparam.clear(); ct = Contenttype(); mp = Multipart(); locale_init = false; if (requestScope) { requestScope->release(); requestScope = 0; } httpcookies.clear(); encodingRead = false; releaseLocks(); if (applicationScope) { applicationScope->release(); applicationScope = 0; } threadScope = 0; if (sessionScope) { sessionScope->release(); sessionScope = 0; } } void HttpRequest::parse(std::istream& in) { Parser p(*this); p.parse(in); if (!p.failed()) doPostParse(); } void HttpRequest::doPostParse() { qparam.parse_url(getQueryString()); if (getMethod() == "POST") { std::istringstream in(getHeader(httpheader::contentType)); in >> ct; if (in) { log_debug(httpheader::contentType << ' ' << in.str()); log_debug("type=" << ct.getType() << " subtype=" << ct.getSubtype()); if (ct.isMultipart()) { log_debug("multipart-boundary=" << ct.getBoundary()); mp.set(ct.getBoundary(), getBody()); for (Multipart::const_iterator it = mp.begin(); it != mp.end(); ++it) { // don't copy uploaded files into qparam to prevent unnecessery // copies of large chunks if (it->getFilename().empty()) { std::string multipartBody(it->getBodyBegin(), it->getBodyEnd()); log_debug("multipart-item name=" << it->getName() << " body=" << multipartBody); qparam.add(it->getName(), multipartBody); } } } else { qparam.parse_url(getBody()); } } else if (ct.getType() == "application" && ct.getSubtype() == "x-www-form-urlencoded") qparam.parse_url(getBody()); } { static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); serial = ++serial_; } } namespace { void formatIp(const sockaddr_storage& addr, std::string& str) { #ifdef HAVE_INET_NTOP const sockaddr_in* sa = reinterpret_cast<const sockaddr_in*>(&addr); char strbuf[INET6_ADDRSTRLEN]; inet_ntop(sa->sin_family, &sa->sin_addr, strbuf, sizeof(strbuf)); str = strbuf; #else static cxxtools::Mutex monitor; cxxtools::MutexLock lock(monitor); char* p = inet_ntoa(peerAddr.sin_addr); str = p; #endif } } std::string HttpRequest::getPeerIp() const { if (peerAddrStr.empty()) formatIp(peerAddr, peerAddrStr); return peerAddrStr; } std::string HttpRequest::getServerIp() const { if (serverAddrStr.empty()) formatIp(serverAddr, serverAddrStr); return serverAddrStr; } const std::locale& HttpRequest::getLocale() const { if (!locale_init) { static const std::string LANG = "LANG"; static const std::locale stdlocale(""); typedef std::map<std::string, std::locale> locale_map_type; static locale_map_type locale_map; static cxxtools::Mutex locale_monitor; locale_init = true; log_debug("HttpRequest::getLocale() " << qparam.dump()); std::string lang = qparam[LANG]; if (lang.empty() || lang == stdlocale.name()) locale = stdlocale; else { log_debug("LANG from query-parameter (" << lang << ')'); try { cxxtools::MutexLock lock(locale_monitor); locale_map_type::const_iterator it = locale_map.find(lang); if (it == locale_map.end()) { locale = std::locale(lang.c_str()); locale_map.insert(locale_map_type::value_type(lang, locale)); } else locale = it->second; } catch (const std::exception& e) { log_warn("unknown locale " << lang << ": " << e.what()); locale = stdlocale; locale_map.insert(locale_map_type::value_type(lang, locale)); } } log_debug("LANG=" << locale.name()); } return locale; } const Cookies& HttpRequest::getCookies() const { log_debug("HttpRequest::getCookies()"); if (!httpcookies.hasCookies()) { header_type::const_iterator it = header.find(httpheader::cookie); if (it != header.end()) { log_debug("parse cookie-header " << it->second); const_cast<HttpRequest*>(this)->httpcookies.set(it->second); } } return httpcookies; } const Encoding& HttpRequest::getEncoding() const { if (!encodingRead) { encoding.parse(getHeader(httpheader::acceptEncoding)); encodingRead = true; } return encoding; } namespace { class CompareNoCase { public: bool operator() (char c1, char c2) const { return tolower(c1) == tolower(c2); } }; } bool HttpRequest::keepAlive() const { header_type::const_iterator it = header.find(httpheader::connection); return it == header.end() ? getMajorVersion() == 1 && getMinorVersion() == 1 : it->second.size() >= httpheader::connectionKeepAlive.size() && std::equal(it->second.begin(), it->second.end(), httpheader::connectionKeepAlive.begin(), CompareNoCase()); } void HttpRequest::setApplicationScope(Scope* s) { if (applicationScope == s) return; if (applicationScope) { releaseApplicationScopeLock(); applicationScope->release(); } if (s) s->addRef(); applicationScope = s; } void HttpRequest::setThreadScope(Scope* s) { threadScope = s; } void HttpRequest::setSessionScope(Sessionscope* s) { if (sessionScope == s) return; if (sessionScope) { releaseSessionScopeLock(); sessionScope->release(); } if (s) s->addRef(); sessionScope = s; } void HttpRequest::clearSession() { if (sessionScope) { log_info("end session"); releaseSessionScopeLock(); sessionScope->release(); sessionScope = 0; } } void HttpRequest::ensureApplicationScopeLock() { log_trace("ensureApplicationScopeLock; thread " << pthread_self()); ensureSessionScopeLock(); if (applicationScope && !applicationScopeLocked) { log_debug("lock application scope; thread" << pthread_self()); applicationScope->lock(); applicationScopeLocked = true; } else log_debug("applicationscope locked already"); } void HttpRequest::ensureSessionScopeLock() { log_trace("ensureSessionScopeLock; thread " << pthread_self()); if (sessionScope && !sessionScopeLocked) { log_debug("lock sessionscope; thread " << pthread_self()); sessionScope->lock(); sessionScopeLocked = true; } else log_debug("sessionscope locked already"); } void HttpRequest::releaseApplicationScopeLock() { log_trace("releaseApplicationScopeLock; thread " << pthread_self()); if (applicationScope && applicationScopeLocked) { log_debug("unlock applicationscope"); applicationScopeLocked = false; applicationScope->unlock(); } else log_debug("applicationscope not locked"); } void HttpRequest::releaseSessionScopeLock() { log_trace("releaseSessionScopeLock; thread " << pthread_self()); releaseApplicationScopeLock(); if (sessionScope && sessionScopeLocked) { log_debug("unlock sessionscope"); sessionScopeLocked = false; sessionScope->unlock(); } else log_debug("sessionscope not locked"); } Scope& HttpRequest::getRequestScope() { if (requestScope == 0) requestScope = new Scope(); return *requestScope; } Scope& HttpRequest::getThreadScope() { if (threadScope == 0) throw std::runtime_error("threadscope not set"); return *threadScope; } Scope& HttpRequest::getApplicationScope() { ensureApplicationScopeLock(); return *applicationScope; } Sessionscope& HttpRequest::getSessionScope() { if (!sessionScope) sessionScope = new Sessionscope(); ensureSessionScopeLock(); return *sessionScope; } bool HttpRequest::hasSessionScope() const { return sessionScope != 0 && !sessionScope->empty(); } } <|endoftext|>
<commit_before>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/observable.h> #include <set> #include <unordered_set> class ObservableTest: public testing::Test {}; TEST_F(ObservableTest, SimpleAssignmentCheck) { autowiring::observable<int> ob; bool hit = false; ob.onChanged += [&hit] { hit = true; }; ob = 2; ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified"; ASSERT_EQ(2, *ob) << "operator * gives an incorrect value"; } TEST_F(ObservableTest, BeforeAndAfter) { autowiring::observable<int> ob; ob = 8; bool hit = false; ob.onChanged += [&hit] { hit = true; }; int obBefore = 0; int obAfter = 0; ob.onBeforeChanged += [&] (const int& before, const int& after) { obBefore = before; obAfter = after; }; ob = 9; ASSERT_TRUE(hit) << "Change notification not raised"; ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct"; ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct"; } TEST_F(ObservableTest, SetOfObservable) { std::unordered_set<autowiring::observable<int>> a; a.insert(4449); a.insert(44410); a.insert(44411); ASSERT_EQ(1, a.count(4449)); ASSERT_EQ(1, a.count(44410)); ASSERT_EQ(1, a.count(44411)); std::set<autowiring::observable<int>> b; b.insert(9); b.insert(12); b.insert(44); ASSERT_EQ(1, b.count(9)); ASSERT_EQ(1, b.count(12)); ASSERT_EQ(1, b.count(44)); } TEST_F(ObservableTest, MathOperators) { autowiring::observable<int> one(1); autowiring::observable<int> two(2); // plus, minus, multiply, divide ASSERT_EQ(3, one + 2); ASSERT_EQ(1, two - 1); ASSERT_EQ(2.0, one * 2.0); ASSERT_EQ(two, two / one); // all comparison operators ASSERT_TRUE(one == 1); ASSERT_TRUE(one != 2); ASSERT_TRUE(one < 2); ASSERT_TRUE(one >= 1); ASSERT_FALSE(one > two); ASSERT_FALSE(two <= one); }<commit_msg>Use const<commit_after>// Copyright (C) 2012-2015 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include <autowiring/observable.h> #include <set> #include <unordered_set> class ObservableTest: public testing::Test {}; TEST_F(ObservableTest, SimpleAssignmentCheck) { autowiring::observable<int> ob; bool hit = false; ob.onChanged += [&hit] { hit = true; }; ob = 2; ASSERT_TRUE(hit) << "OnChanged handler not hit when the observable value was modified"; ASSERT_EQ(2, *ob) << "operator * gives an incorrect value"; } TEST_F(ObservableTest, BeforeAndAfter) { autowiring::observable<int> ob; ob = 8; bool hit = false; ob.onChanged += [&hit] { hit = true; }; int obBefore = 0; int obAfter = 0; ob.onBeforeChanged += [&] (const int& before, const int& after) { obBefore = before; obAfter = after; }; ob = 9; ASSERT_TRUE(hit) << "Change notification not raised"; ASSERT_EQ(8, obBefore) << "\"Before\" value in onBeforeChanged was not correct"; ASSERT_EQ(9, obAfter) << "\"AfFter\" value in onBeforeChanged was not correct"; } TEST_F(ObservableTest, SetOfObservable) { std::unordered_set<autowiring::observable<int>> a; a.insert(4449); a.insert(44410); a.insert(44411); ASSERT_EQ(1, a.count(4449)); ASSERT_EQ(1, a.count(44410)); ASSERT_EQ(1, a.count(44411)); std::set<autowiring::observable<int>> b; b.insert(9); b.insert(12); b.insert(44); ASSERT_EQ(1, b.count(9)); ASSERT_EQ(1, b.count(12)); ASSERT_EQ(1, b.count(44)); } TEST_F(ObservableTest, MathOperators) { const autowiring::observable<int> one(1); const autowiring::observable<int> two(2); // plus, minus, multiply, divide ASSERT_EQ(3, one + 2); ASSERT_EQ(1, two - 1); ASSERT_EQ(2.0, one * 2.0); ASSERT_EQ(two, two / one); // all comparison operators ASSERT_TRUE(one == 1); ASSERT_TRUE(one != 2); ASSERT_TRUE(one < 2); ASSERT_TRUE(one >= 1); ASSERT_FALSE(one > two); ASSERT_FALSE(two <= one); }<|endoftext|>
<commit_before>/* * mmvtkmDataRenderer.cpp * * Copyright (C) 2018 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmvtkm/mmvtkmRenderer.h" #include "mmvtkm/mmvtkmDataCall.h" #include "vtkm/io/reader/VTKDataSetReader.h" //#define VTKM_DEVICE_ADAPTER VTKM_DEVICE_ADAPTER_CUDA //#include "vtkm/cont/DeviceAdapter.h" using namespace megamol; using namespace megamol::mmvtkm; mmvtkmDataRenderer::mmvtkmDataRenderer(void) : Renderer3DModule_2() , vtkmDataCallerSlot("getData", "Connects the vtkm renderer with a vtkm data source") , oldHash(0) , scene() , mapper() , canvas() , camera() , colorArray(nullptr) , dataHasChanged(true) { this->vtkmDataCallerSlot.SetCompatibleCall<megamol::mmvtkm::mmvtkmDataCallDescription>(); this->MakeSlotAvailable(&this->vtkmDataCallerSlot); } mmvtkmDataRenderer::~mmvtkmDataRenderer(void) { this->Release(); } bool mmvtkmDataRenderer::create() { return true; } void mmvtkmDataRenderer::release() { // Renderer3DModule::release(); } bool mmvtkmDataRenderer::GetCapabilities(core::view::CallRender3D_2& call) { return true; } bool mmvtkmDataRenderer::GetExtents(core::view::CallRender3D_2& call) { mmvtkmDataCall* cd = this->vtkmDataCallerSlot.CallAs<mmvtkmDataCall>(); if (cd == NULL) return false; if (!(*cd)(1)) { return false; } else { //cd->FrameID(); } return true; } bool mmvtkmDataRenderer::GetData(core::view::CallRender3D_2& call) { mmvtkmDataCall* cd = this->vtkmDataCallerSlot.CallAs<mmvtkmDataCall>(); if (cd == NULL) { return false; } this->GetExtents(call); if (!(*cd)(0)) { return false; } else { if (cd->DataHash() == this->oldHash) { return false; } else { this->oldHash = cd->DataHash(); vtkmDataSet = cd->GetDataSet(); dataHasChanged = true; // compute the bounds and extends of the input data vtkm::cont::ColorTable colorTable("inferno"); vtkm::rendering::Actor actor(vtkmDataSet->GetCellSet(), vtkmDataSet->GetCoordinateSystem(), vtkmDataSet->GetPointField("pointvar"), colorTable); // depending on dataset change to getCellField with according FrameID scene = vtkm::rendering::Scene(); scene.AddActor(actor); // makeScene(...) } } return true; } bool mmvtkmDataRenderer::Render(core::view::CallRender3D_2& call) { this->GetData(call); // camera setup core::view::Camera_2 cam; call.GetCamera(cam); cam_type::snapshot_type snapshot; cam_type::matrix_type viewTemp, projTemp; // Generate complete snapshot cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all); glm::vec4 viewport = glm::vec4(0, 0, cam.resolution_gate().width(), cam.resolution_gate().height()); if (viewport.z < 1.0f) viewport.z = 1.0f; if (viewport.w < 1.0f) viewport.w = 1.0f; float shaderPointSize = vislib::math::Max(viewport.z, viewport.w); viewport = glm::vec4(0, 0, 2.f / viewport.z, 2.f / viewport.w); glm::vec4 camView = snapshot.view_vector; glm::vec4 camRight = snapshot.right_vector; glm::vec4 camUp = snapshot.up_vector; glm::vec4 camPos = snapshot.position; canvasWidth = cam.resolution_gate().width(); canvasHeight = cam.resolution_gate().height(); canvas = vtkm::rendering::CanvasRayTracer(canvasWidth, canvasHeight); vtkm::Vec<vtkm::Float64, 3> lookat(camView.x + 1.f, camView.y + 1.f, camView.z + 1.f); vtkm::Vec<vtkm::Float32, 3> up(camUp.x, camUp.y, camUp.z); vtkm::Vec<vtkm::Float32, 3> position(camPos.x + 1.f, camPos.y + 1.f, camPos.z + 1.f); vtkm::Float32 nearPlane = snapshot.frustum_near; vtkm::Float32 farPlane = snapshot.frustum_far; vtkm::Float32 fovY = cam.aperture_angle(); vtkm::Bounds coordsBounds = vtkmDataSet->GetCoordinateSystem().GetBounds(); vtkm::Vec<vtkm::Float64, 3> totalExtent(coordsBounds.X.Length(), coordsBounds.Y.Length(), coordsBounds.Z.Length()); vtkm::Float64 mag = vtkm::Magnitude(totalExtent); vtkm::Normalize(totalExtent); // setup a camera and point it to towards the center of the input data camera.ResetToBounds(coordsBounds); camera.SetLookAt(lookat /*totalExtent * (mag * .5f)*/); camera.SetViewUp(up); camera.SetClippingRange(nearPlane, farPlane); camera.SetFieldOfView(fovY); camera.SetPosition(position); //vislib::math::Cuboid<float> bbox(coordsBounds.X.Min, coordsBounds.Y.Min, coordsBounds.Z.Min, //coordsBounds.X.Max, coordsBounds.Y.Max, coordsBounds.Z.Max); vislib::math::Cuboid<float> bbox(-1.f, -1.f, -1.f, 1.f, 1.f, 1.f); call.AccessBoundingBoxes().SetBoundingBox(bbox); call.AccessBoundingBoxes().SetClipBox(bbox); // default coordinatesystem name = "coordinates" // default fieldname = "pointvar" // default cellname = "cells" // update actor, acutally just the field, each frame // store dynamiccellset and coordinatesystem after reading them in GetExtents if (true) { vtkm::rendering::View3D view(scene, mapper, canvas, camera); view.Initialize(); // required view.Paint(); // the canvas holds the buffer of the offscreen rendered image vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>> colorBuffer = view.GetCanvas().GetColorBuffer(); // pulling out the c array from the buffer // which can just be rendered colorArray = colorBuffer.GetStorage().GetBasePointer(); dataHasChanged = false; } // Write the C array to an OpenGL buffer glDrawPixels((GLint)canvasWidth, (GLint)canvasHeight, GL_RGBA, GL_FLOAT, colorArray); // SwapBuffers(); return true; } <commit_msg>minor changes<commit_after>/* * mmvtkmDataRenderer.cpp * * Copyright (C) 2018 by VISUS (Universitaet Stuttgart) * Alle Rechte vorbehalten. */ #include "stdafx.h" #include "mmvtkm/mmvtkmRenderer.h" #include "mmvtkm/mmvtkmDataCall.h" #include "vtkm/io/reader/VTKDataSetReader.h" //#define VTKM_DEVICE_ADAPTER VTKM_DEVICE_ADAPTER_CUDA //#include "vtkm/cont/DeviceAdapter.h" using namespace megamol; using namespace megamol::mmvtkm; mmvtkmDataRenderer::mmvtkmDataRenderer(void) : Renderer3DModule_2() , vtkmDataCallerSlot("getData", "Connects the vtkm renderer with a vtkm data source") , oldHash(0) , scene() , mapper() , canvas() , camera() , colorArray(nullptr) , dataHasChanged(true) { this->vtkmDataCallerSlot.SetCompatibleCall<megamol::mmvtkm::mmvtkmDataCallDescription>(); this->MakeSlotAvailable(&this->vtkmDataCallerSlot); } mmvtkmDataRenderer::~mmvtkmDataRenderer(void) { this->Release(); } bool mmvtkmDataRenderer::create() { return true; } void mmvtkmDataRenderer::release() { // Renderer3DModule::release(); } bool mmvtkmDataRenderer::GetCapabilities(core::view::CallRender3D_2& call) { return true; } bool mmvtkmDataRenderer::GetExtents(core::view::CallRender3D_2& call) { mmvtkmDataCall* cd = this->vtkmDataCallerSlot.CallAs<mmvtkmDataCall>(); if (cd == NULL) return false; if (!(*cd)(1)) { return false; } else { //cd->FrameID(); } return true; } bool mmvtkmDataRenderer::GetData(core::view::CallRender3D_2& call) { mmvtkmDataCall* cd = this->vtkmDataCallerSlot.CallAs<mmvtkmDataCall>(); if (cd == NULL) { return false; } this->GetExtents(call); if (!(*cd)(0)) { return false; } else { if (cd->DataHash() == this->oldHash) { return false; } else { this->oldHash = cd->DataHash(); vtkmDataSet = cd->GetDataSet(); dataHasChanged = true; // compute the bounds and extends of the input data vtkm::cont::ColorTable colorTable("inferno"); vtkm::rendering::Actor actor(vtkmDataSet->GetCellSet(), vtkmDataSet->GetCoordinateSystem(), vtkmDataSet->GetPointField("pointvar"), colorTable); // depending on dataset change to getCellField with according FrameID scene = vtkm::rendering::Scene(); scene.AddActor(actor); // makeScene(...) } } return true; } bool mmvtkmDataRenderer::Render(core::view::CallRender3D_2& call) { this->GetData(call); // camera setup core::view::Camera_2 cam; call.GetCamera(cam); cam_type::snapshot_type snapshot; cam_type::matrix_type viewTemp, projTemp; // Generate complete snapshot cam.calc_matrices(snapshot, viewTemp, projTemp, core::thecam::snapshot_content::all); glm::vec4 viewport = glm::vec4(0, 0, cam.resolution_gate().width(), cam.resolution_gate().height()); if (viewport.z < 1.0f) viewport.z = 1.0f; if (viewport.w < 1.0f) viewport.w = 1.0f; float shaderPointSize = vislib::math::Max(viewport.z, viewport.w); viewport = glm::vec4(0, 0, 2.f / viewport.z, 2.f / viewport.w); glm::vec4 camView = snapshot.view_vector; glm::vec4 camRight = snapshot.right_vector; glm::vec4 camUp = snapshot.up_vector; glm::vec4 camPos = snapshot.position; // set camera setting for vtkm canvasWidth = cam.resolution_gate().width(); canvasHeight = cam.resolution_gate().height(); canvas = vtkm::rendering::CanvasRayTracer(canvasWidth, canvasHeight); vtkm::Vec<vtkm::Float64, 3> lookat(camView.x + 1.f, camView.y + 1.f, camView.z + 1.f); vtkm::Vec<vtkm::Float32, 3> up(camUp.x, camUp.y, camUp.z); vtkm::Vec<vtkm::Float32, 3> position(camPos.x + 1.f, camPos.y + 1.f, camPos.z + 1.f); vtkm::Float32 nearPlane = snapshot.frustum_near; vtkm::Float32 farPlane = snapshot.frustum_far; vtkm::Float32 fovY = cam.aperture_angle(); vtkm::Bounds coordsBounds = vtkmDataSet->GetCoordinateSystem().GetBounds(); vtkm::Vec<vtkm::Float64, 3> totalExtent(coordsBounds.X.Length(), coordsBounds.Y.Length(), coordsBounds.Z.Length()); vtkm::Float64 mag = vtkm::Magnitude(totalExtent); vtkm::Normalize(totalExtent); // setup a camera and point it to towards the center of the input data camera.ResetToBounds(coordsBounds); camera.SetLookAt(lookat /*totalExtent * (mag * .5f)*/); camera.SetViewUp(up); camera.SetClippingRange(nearPlane, farPlane); camera.SetFieldOfView(fovY); camera.SetPosition(position); //vislib::math::Cuboid<float> bbox(coordsBounds.X.Min, coordsBounds.Y.Min, coordsBounds.Z.Min, //coordsBounds.X.Max, coordsBounds.Y.Max, coordsBounds.Z.Max); vislib::math::Cuboid<float> bbox(-1.f, -1.f, -1.f, 1.f, 1.f, 1.f); call.AccessBoundingBoxes().SetBoundingBox(bbox); call.AccessBoundingBoxes().SetClipBox(bbox); // default coordinatesystem name = "coordinates" // default fieldname = "pointvar" // default cellname = "cells" // update actor, acutally just the field, each frame // store dynamiccellset and coordinatesystem after reading them in GetExtents vtkm::rendering::View3D view(scene, mapper, canvas, camera); view.Initialize(); // required view.Paint(); // the canvas holds the buffer of the offscreen rendered image vtkm::cont::ArrayHandle<vtkm::Vec<vtkm::Float32, 4>> colorBuffer = view.GetCanvas().GetColorBuffer(); // pulling out the c array from the buffer // which can just be rendered colorArray = colorBuffer.GetStorage().GetBasePointer(); dataHasChanged = false; // Write the C array to an OpenGL buffer glDrawPixels((GLint)canvasWidth, (GLint)canvasHeight, GL_RGBA, GL_FLOAT, colorArray); // SwapBuffers(); return true; } <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993-2015 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // thiefControl.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" class ThiefControl : public bz_Plugin { public: virtual const char* Name() { return "Thief Control"; } virtual void Init(const char* config); virtual void Event(bz_EventData *eventData); }; BZ_PLUGIN(ThiefControl) void ThiefControl::Init(const char* /*config*/ ) { bz_debugMessage(4, "thiefControl plugin loaded"); Register(bz_eFlagTransferredEvent); } void ThiefControl::Event (bz_EventData * eventData) { bz_FlagTransferredEventData_V1 *data = (bz_FlagTransferredEventData_V1 *) eventData; const std::string noStealMsg = "Flag dropped. Don't steal from teammates!"; if (!data) return; if (data->eventType != bz_eFlagTransferredEvent) return; bz_BasePlayerRecord *playerFrom = bz_getPlayerByIndex(data->fromPlayerID); if (!playerFrom) return; bz_BasePlayerRecord *playerTo = bz_getPlayerByIndex(data->toPlayerID); if (!playerTo) { bz_freePlayerRecord(playerFrom); return; } switch (bz_getGameType()) { case eFFAGame: if (playerTo->team == playerFrom->team && playerTo->team != eRogueTeam) { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } break; case eCTFGame: { // Allow teammates to steal team flags // This will allow someone to steal a team flag in order // to possibly capture it faster. bool allowTransfer = false; if (playerTo->team == playerFrom->team && playerTo->team != eRogueTeam) { bz_ApiString flagT = bz_ApiString(data->flagType); // Allow theft of team flags only allowTransfer = (flagT == "R*" || flagT == "G*" || flagT == "B*" || flagT == "P*"); if (!allowTransfer) { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } } } break; case eRabbitGame: if (playerTo->team == playerFrom->team) { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } break; default: break; } bz_freePlayerRecord(playerTo); bz_freePlayerRecord(playerFrom); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Eliminate unnecessary variable creation.<commit_after>/* bzflag * Copyright (c) 1993-2015 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named COPYING that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // thiefControl.cpp : Defines the entry point for the DLL application. // #include "bzfsAPI.h" class ThiefControl : public bz_Plugin { public: virtual const char* Name() { return "Thief Control"; } virtual void Init(const char* config); virtual void Event(bz_EventData *eventData); }; BZ_PLUGIN(ThiefControl) void ThiefControl::Init(const char* /*config*/ ) { bz_debugMessage(4, "thiefControl plugin loaded"); Register(bz_eFlagTransferredEvent); } void ThiefControl::Event (bz_EventData * eventData) { bz_FlagTransferredEventData_V1 *data = (bz_FlagTransferredEventData_V1 *) eventData; const std::string noStealMsg = "Flag dropped. Don't steal from teammates!"; if (!data) return; if (data->eventType != bz_eFlagTransferredEvent) return; bz_BasePlayerRecord *playerFrom = bz_getPlayerByIndex(data->fromPlayerID); if (!playerFrom) return; bz_BasePlayerRecord *playerTo = bz_getPlayerByIndex(data->toPlayerID); if (!playerTo) { bz_freePlayerRecord(playerFrom); return; } switch (bz_getGameType()) { case eFFAGame: if (playerTo->team == playerFrom->team && playerTo->team != eRogueTeam) { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } break; case eCTFGame: { if (playerTo->team == playerFrom->team && playerTo->team != eRogueTeam) { bz_ApiString flagT = bz_ApiString(data->flagType); // Allow teammates to steal team flags // This will allow someone to steal a team flag in order // to possibly capture it faster. if (flagT != "R*" && flagT != "G*" && flagT != "B*" && flagT != "P*") { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } } } break; case eRabbitGame: if (playerTo->team == playerFrom->team) { data->action = data->DropThief; bz_sendTextMessage(BZ_SERVER, data->toPlayerID, noStealMsg.c_str()); } break; default: break; } bz_freePlayerRecord(playerTo); bz_freePlayerRecord(playerFrom); } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>#include <stdlib.h> #include <unistd.h> #include <string> #include <cmath> #include <iostream> #include <wiringSerial.h> #include "Hardware.h" #define LENGTH_ONE 11.5 #define LENGTH_TWO 16.0 #define I_MIN_VAL 0 #define I_MAX_VAL 1023 #define I_MIN_ANG -65 #define I_MAX_ANG 65 #define J_MIN_VAL 230 #define J_MAX_VAL 850 #define J_MIN_ANG 35 #define J_MAX_ANG 180 #define K_MIN_VAL 950 #define K_MAX_VAL 20 #define K_MIN_ANG 0 #define K_MAX_ANG 270 #define SPHERE_CENTER_Z -5 #define SPHERE_RADIUS 7 Hardware::Hardware() { fd = serialOpen("/dev/ttyAMA0", 57600); } void Hardware::good() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0xFF0000 1 &"); } void Hardware::bad() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0x00FF00 1 &"); } void Hardware::neutral() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0x0000FF 1 &"); } void Hardware::poise() { moveJoint(1, 512); moveJoint(2, 860); moveJoint(3, 960); } void Hardware::clap(int claps) { for (int i=0; i<1+claps*2; i++) { gripper(i%2); usleep(500000); } } int Hardware::getServoError(int id) { return readDxl(id,'e'); } void Hardware::getSonars(int *sonarOne, int *sonarTwo) { writeCommand('R','v',128); usleep(100000); std::string val; while (serialDataAvail(fd) > 0) val += serialGetchar(fd); std::string one = val.substr(0, val.find("\n")); std::string two = val.substr(val.find("\n")); *sonarOne = atoi(one.c_str()); *sonarTwo = atoi(two.c_str()); } int Hardware::readDxl(int id, char cmd) { writeCommand('R',cmd,id); std::string val; while (serialDataAvail(fd) > 0) val += serialGetchar(fd); return atoi(val.c_str()); } void Hardware::writeInt(int inInt) { serialPutchar(fd,inInt%256); serialPutchar(fd,inInt>>8); } void Hardware::writeCommand(char readWrite, char command, int id) { std::string s; s += readWrite; s += command; s += static_cast<char>(id); serialPuts(fd,s.c_str()); } void Hardware::setTorque(int id, int torque) { writeCommand('W','t',id); writeInt(torque); } void Hardware::setSpeed(int id, int speed) { writeCommand('W','s',id); writeInt(speed); } void Hardware::gripper(bool open) { if (open) { writeCommand('W','o',128); writeInt(500); } else { writeCommand('W','c',128); writeInt(500); } } bool Hardware::setJoints(double i, double j, double k, bool override = false) { double x, y, z; forwardKinematicsXY(i, j, k, &x, &y, &z); if (!override && !safetyCheck(x,y,z)) return false; int iVal, jVal, kVal; scaleServos(i, j, k, &iVal, &jVal, &kVal); moveJoint(1,iVal); moveJoint(2,jVal); moveJoint(3,kVal); return true; } bool Hardware::safetyCheck(double x, double y, double z) { double radius = sqrt(x*x + y*y + pow(z-SPHERE_CENTER_Z,2)); if (radius < SPHERE_RADIUS) return false; else if (z < -5 || z > 24) return false; else if (y < -1) return false; else return true; } bool Hardware::setEffectorPosition(double theta, double x, double y) { double theta1, theta2; inverseKinematicsXY(x, y, &theta1, &theta2); return setJoints(theta,theta1,theta2); } void Hardware::moveJoint(int id, int position) { writeCommand('W','p',id); writeInt(position); } void Hardware::scaleServos(double iAng, double jAng, double kAng, int *iVal, int *jVal, int *kVal) { *iVal = round(map(iAng,I_MIN_ANG,I_MAX_ANG,I_MIN_VAL,I_MAX_VAL)); *jVal = round(map(jAng,J_MIN_ANG,J_MAX_ANG,J_MIN_VAL,J_MAX_VAL)); *kVal = round(map(kAng,K_MIN_ANG,K_MAX_ANG,K_MIN_VAL,K_MAX_VAL)); } void Hardware::forwardKinematicsXY(double theta0, double theta1, double theta2, double *x, double *y, double *z) { double theta3 = theta2 - (180 - theta1); *y = LENGTH_ONE*cos(theta1*0.0174533) + LENGTH_TWO*cos(theta3*0.0174533); *z = LENGTH_ONE*sin(theta1*0.0174533) + LENGTH_TWO*sin(theta3*0.0174533); *x = -*y*sin(theta0*0.0174532925); *y *= cos(theta0*0.0174532925); //std::cout << "Thetas: (" << theta0 << "," << theta1 << "," << theta2 << "), Position: (" << *x << "," << *y << "," << *z << ")\n"; } void Hardware::inverseKinematicsXY(double x, double y, double *theta1, double *theta2) { double hypo = sqrt(pow(x,2) + pow(y,2)); double q1 = atan2(y,x); double q2 = acos((pow(LENGTH_ONE,2) - pow(LENGTH_TWO,2) + pow(hypo,2)) /(2.0*LENGTH_ONE*hypo)); *theta1 = q1 + q2; *theta2 = acos((pow(LENGTH_ONE,2) + pow(LENGTH_TWO,2) - pow(hypo,2)) /(2.0*LENGTH_ONE*LENGTH_TWO)); *theta1 *= 180.0/3.14159265; *theta2 *= 180.0/3.14159265; } Hardware::~Hardware() { serialClose(fd); } <commit_msg>fix default param<commit_after>#include <stdlib.h> #include <unistd.h> #include <string> #include <cmath> #include <iostream> #include <wiringSerial.h> #include "Hardware.h" #define LENGTH_ONE 11.5 #define LENGTH_TWO 16.0 #define I_MIN_VAL 0 #define I_MAX_VAL 1023 #define I_MIN_ANG -65 #define I_MAX_ANG 65 #define J_MIN_VAL 230 #define J_MAX_VAL 850 #define J_MIN_ANG 35 #define J_MAX_ANG 180 #define K_MIN_VAL 950 #define K_MAX_VAL 20 #define K_MIN_ANG 0 #define K_MAX_ANG 270 #define SPHERE_CENTER_Z -5 #define SPHERE_RADIUS 7 Hardware::Hardware() { fd = serialOpen("/dev/ttyAMA0", 57600); } void Hardware::good() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0xFF0000 1 &"); } void Hardware::bad() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0x00FF00 1 &"); } void Hardware::neutral() { system("sudo python ~/Hardware/ThingThree/Code/Dotstar/strandtest.py 0x0000FF 1 &"); } void Hardware::poise() { moveJoint(1, 512); moveJoint(2, 860); moveJoint(3, 960); } void Hardware::clap(int claps) { for (int i=0; i<1+claps*2; i++) { gripper(i%2); usleep(500000); } } int Hardware::getServoError(int id) { return readDxl(id,'e'); } void Hardware::getSonars(int *sonarOne, int *sonarTwo) { writeCommand('R','v',128); usleep(100000); std::string val; while (serialDataAvail(fd) > 0) val += serialGetchar(fd); std::string one = val.substr(0, val.find("\n")); std::string two = val.substr(val.find("\n")); *sonarOne = atoi(one.c_str()); *sonarTwo = atoi(two.c_str()); } int Hardware::readDxl(int id, char cmd) { writeCommand('R',cmd,id); std::string val; while (serialDataAvail(fd) > 0) val += serialGetchar(fd); return atoi(val.c_str()); } void Hardware::writeInt(int inInt) { serialPutchar(fd,inInt%256); serialPutchar(fd,inInt>>8); } void Hardware::writeCommand(char readWrite, char command, int id) { std::string s; s += readWrite; s += command; s += static_cast<char>(id); serialPuts(fd,s.c_str()); } void Hardware::setTorque(int id, int torque) { writeCommand('W','t',id); writeInt(torque); } void Hardware::setSpeed(int id, int speed) { writeCommand('W','s',id); writeInt(speed); } void Hardware::gripper(bool open) { if (open) { writeCommand('W','o',128); writeInt(500); } else { writeCommand('W','c',128); writeInt(500); } } bool Hardware::setJoints(double i, double j, double k, bool override /* = false */) { double x, y, z; forwardKinematicsXY(i, j, k, &x, &y, &z); if (!override && !safetyCheck(x,y,z)) return false; int iVal, jVal, kVal; scaleServos(i, j, k, &iVal, &jVal, &kVal); moveJoint(1,iVal); moveJoint(2,jVal); moveJoint(3,kVal); return true; } bool Hardware::safetyCheck(double x, double y, double z) { double radius = sqrt(x*x + y*y + pow(z-SPHERE_CENTER_Z,2)); if (radius < SPHERE_RADIUS) return false; else if (z < -5 || z > 24) return false; else if (y < -1) return false; else return true; } bool Hardware::setEffectorPosition(double theta, double x, double y) { double theta1, theta2; inverseKinematicsXY(x, y, &theta1, &theta2); return setJoints(theta,theta1,theta2); } void Hardware::moveJoint(int id, int position) { writeCommand('W','p',id); writeInt(position); } void Hardware::scaleServos(double iAng, double jAng, double kAng, int *iVal, int *jVal, int *kVal) { *iVal = round(map(iAng,I_MIN_ANG,I_MAX_ANG,I_MIN_VAL,I_MAX_VAL)); *jVal = round(map(jAng,J_MIN_ANG,J_MAX_ANG,J_MIN_VAL,J_MAX_VAL)); *kVal = round(map(kAng,K_MIN_ANG,K_MAX_ANG,K_MIN_VAL,K_MAX_VAL)); } void Hardware::forwardKinematicsXY(double theta0, double theta1, double theta2, double *x, double *y, double *z) { double theta3 = theta2 - (180 - theta1); *y = LENGTH_ONE*cos(theta1*0.0174533) + LENGTH_TWO*cos(theta3*0.0174533); *z = LENGTH_ONE*sin(theta1*0.0174533) + LENGTH_TWO*sin(theta3*0.0174533); *x = -*y*sin(theta0*0.0174532925); *y *= cos(theta0*0.0174532925); //std::cout << "Thetas: (" << theta0 << "," << theta1 << "," << theta2 << "), Position: (" << *x << "," << *y << "," << *z << ")\n"; } void Hardware::inverseKinematicsXY(double x, double y, double *theta1, double *theta2) { double hypo = sqrt(pow(x,2) + pow(y,2)); double q1 = atan2(y,x); double q2 = acos((pow(LENGTH_ONE,2) - pow(LENGTH_TWO,2) + pow(hypo,2)) /(2.0*LENGTH_ONE*hypo)); *theta1 = q1 + q2; *theta2 = acos((pow(LENGTH_ONE,2) + pow(LENGTH_TWO,2) - pow(hypo,2)) /(2.0*LENGTH_ONE*LENGTH_TWO)); *theta1 *= 180.0/3.14159265; *theta2 *= 180.0/3.14159265; } Hardware::~Hardware() { serialClose(fd); } <|endoftext|>
<commit_before>/* * main.cpp * * Copyright (C) ST-Ericsson SA 2011 * Authors: Srimanta Panda <srimanta.panda@stericsson.com>, * Ola Borgelin <ola.borgelin@stericsson.com>, * Karin Hedlund <karin.hedlund@stericsson.com>, * Markus Andersson <markus.m.andersson@stericsson.com> for ST-Ericsson. * License terms: 3-clause BSD license * */ /* * @addtogroup main * @{ */ #include "main.h" #include "CDAL.h" #include "DutManager.h" #include <iostream> #include <string> #include <vector> #include <utility> #include <cstring> #include <cstdlib> #include <cstdio> using namespace std; volatile bool isDone = false; const string info = \ "\n \ ----------------------- riff - Raw Image File Flasher -------------------------\n \ Version: 0.5.1\n \ " "Flash a device. Try `riff --help' for more information. \n \ " "-------------------------------------------------------------------------------"; const string cmdHelpString = " \n \ Usage: riff [OPTION]...[FILE]...\n\n \ Available command line arguments are:\n\n \ -h, --help\t Display this help message.\n \ -m, --mode ACTION\t Select the mode.\n \ ACTION is `flash`, `erase` or `dump`\n \ -c, --config PATH\t Give path to configuration file.\n \ -f, --flashimage IMAGEPATH\t Give path to flashimage.\n \ -a, --address FLASHADDR\t Give a start address in hex.\n \ -l, --length HEXLENGTH Length of the dump [Byte] in hex.\n \ -d, --dumppath DUMPPATH File path on PC where to store dump.\n \ -v, --verbose\t Shows more detailed information.\n \ --version\t Shows version information.\n \ "; int main(int argc, char* argv[]) { signal(SIGINT, interrupt); cout << info << endl; handleCmdLineInput(argc, argv); logger_ = new Logger("Application"); logger_->log(Logger::INFO, "Using config file %s", configFile); //Parse the config file. config_ = new Config(configFile); // if flashimage path has not been set from commandline //then use the path in the config file if it is set there. if (!strlen(flashimage)) { if (config_->valueExists("FLASH_IMG_PATH")) { strcpy(flashimage, config_->getValue("FLASH_IMG_PATH")); } } // Set the LCM path from ConfigFile, init the USB driver and set the callback function SetLCMLibPath(config_->getValue("LCMLIBPATH")); usb_init_driver(config_->getValue("VENDORID"), config_->getValue("PRODUCTID")); usb_set_listen_callback(UsbDeviceEventCallback); logger_->log(Logger::PROGRESS, "Listening on USB for device connection..."); while (!isDone) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } usb_deinit_driver(); _exit(exitstatus); } void interrupt(int param) { logger_->log(Logger::PROGRESS, "Program interrupted..."); exitstatus = 1; isDone = true; } void UsbDeviceEventCallback(DeviceStatus_t status, DeviceEvent_t event, Device_t device) { if (COMM_DEVICE_SUCCESS == status) { const DUT* dut; switch (event) { case LIBUSB_DEVICE_CONNECTED: logger_->log(Logger::INFO, "Device detected on USB@%u", comm_get_physical_address(device)); dut = DutManager::createDut(device); if (0 != dut) { logger_->log(Logger::PROGRESS, "Connected %s", dut->getId()); } break; case LIBUSB_DEVICE_DISCONNECTED: logger_->log(Logger::INFO, "Disconnect detected on USB@%u", comm_get_physical_address(device)); dut = DutManager::getDut(device); if (0 != dut) { exitstatus = dut->getErrorCode(); logger_->log(Logger::PROGRESS, "Disconnected %s", dut->getId()); DutManager::destroyDut(device); } isDone = true; break; default: logger_->log(Logger::ERR, "Unknown USB event %d", event); break; } } else if (COMM_DEVICE_LIBUSB_FAILED_TO_OPEN_PORT == status) { logger_->log(Logger::ERR, "Cannot open USB device. Are you root?", status); isDone = true; exitstatus = 1; } else { logger_->log(Logger::ERR, "USB device error %d", status); } } void handleCmdLineInput(int argc, char* argv[]) { string input; bool configPathSet = false; for (int i = 1; i != argc; ++i) { input = argv[i]; if ("-h" == input || "--help" == input) { cout << cmdHelpString << endl; _exit(0); } else if ("-v" == input || "--verbose" == input) { Logger::verbose_ = true; } else if ("--version" == input) { _exit(0); } else if ("-m" == input || "--mode" == input) { i = checkCmdLineArgument(argc, i, argv, mode); } else if ("-c" == input || "--config" == input) { configPathSet = true; i = checkCmdLineArgument(argc, i, argv, configFile); } else if ("-f" == input || "--flashimage" == input) { i = checkCmdLineArgument(argc, i, argv, flashimage); } else if ("-a" == input || "--address" == input) { i = checkCmdLineArgument(argc, i, argv, address); } else if ("-l" == input || "--length" == input) { i = checkCmdLineArgument(argc, i, argv, length); } else if ("-d" == input || "--dumppath" == input) { i = checkCmdLineArgument(argc, i, argv, dumpPath); } else { cout << "Unknown option: " << input << endl; } } if (!configPathSet) { FILE* userConfig; #ifdef _WIN32 char* home = getenv("USERPROFILE"); #else char* home = getenv("HOME"); #endif char homeConfigPath[50]; strcpy(homeConfigPath, home); strcat(homeConfigPath, "/.riff/config"); userConfig = fopen(homeConfigPath, "rb"); if (userConfig != NULL) { strcpy(configFile, homeConfigPath); fclose(userConfig); } else { // It will check the default config in /usr/share folder otherwise // or /<current directory>/riff/config userConfig = fopen(configFile, "r"); if(userConfig == NULL) { cout << cmdHelpString << endl; _exit(0); } } } if (*dumpPath == '\0') { //Sets default dump path if not provided #ifdef _WIN32 char* home = "."; #else char* home = getenv("HOME"); #endif strcpy(dumpPath, home); strcat(dumpPath, "/flashdump.bin"); } SequenceFactory::setArguments(configFile, mode, flashimage, address, length, dumpPath); } int checkCmdLineArgument(int argc, int counter, char* argv[], char* var) { counter++; if (counter < argc) { strcpy(var, argv[counter]); } else { cout << "Please give a parameter to the option" << endl; counter--; } return counter; } /* @} */ <commit_msg>Missing include.<commit_after>/* * main.cpp * * Copyright (C) ST-Ericsson SA 2011 * Authors: Srimanta Panda <srimanta.panda@stericsson.com>, * Ola Borgelin <ola.borgelin@stericsson.com>, * Karin Hedlund <karin.hedlund@stericsson.com>, * Markus Andersson <markus.m.andersson@stericsson.com> for ST-Ericsson. * License terms: 3-clause BSD license * */ /* * @addtogroup main * @{ */ #include "main.h" #include "CDAL.h" #include "DutManager.h" #include <iostream> #include <string> #include <vector> #include <utility> #include <cstring> #include <cstdlib> #include <cstdio> #include <unistd.h> using namespace std; volatile bool isDone = false; const string info = \ "\n \ ----------------------- riff - Raw Image File Flasher -------------------------\n \ Version: 0.5.1\n \ " "Flash a device. Try `riff --help' for more information. \n \ " "-------------------------------------------------------------------------------"; const string cmdHelpString = " \n \ Usage: riff [OPTION]...[FILE]...\n\n \ Available command line arguments are:\n\n \ -h, --help\t Display this help message.\n \ -m, --mode ACTION\t Select the mode.\n \ ACTION is `flash`, `erase` or `dump`\n \ -c, --config PATH\t Give path to configuration file.\n \ -f, --flashimage IMAGEPATH\t Give path to flashimage.\n \ -a, --address FLASHADDR\t Give a start address in hex.\n \ -l, --length HEXLENGTH Length of the dump [Byte] in hex.\n \ -d, --dumppath DUMPPATH File path on PC where to store dump.\n \ -v, --verbose\t Shows more detailed information.\n \ --version\t Shows version information.\n \ "; int main(int argc, char* argv[]) { signal(SIGINT, interrupt); cout << info << endl; handleCmdLineInput(argc, argv); logger_ = new Logger("Application"); logger_->log(Logger::INFO, "Using config file %s", configFile); //Parse the config file. config_ = new Config(configFile); // if flashimage path has not been set from commandline //then use the path in the config file if it is set there. if (!strlen(flashimage)) { if (config_->valueExists("FLASH_IMG_PATH")) { strcpy(flashimage, config_->getValue("FLASH_IMG_PATH")); } } // Set the LCM path from ConfigFile, init the USB driver and set the callback function SetLCMLibPath(config_->getValue("LCMLIBPATH")); usb_init_driver(config_->getValue("VENDORID"), config_->getValue("PRODUCTID")); usb_set_listen_callback(UsbDeviceEventCallback); logger_->log(Logger::PROGRESS, "Listening on USB for device connection..."); while (!isDone) { #ifdef _WIN32 Sleep(1000); #else sleep(1); #endif } usb_deinit_driver(); _exit(exitstatus); } void interrupt(int param) { logger_->log(Logger::PROGRESS, "Program interrupted..."); exitstatus = 1; isDone = true; } void UsbDeviceEventCallback(DeviceStatus_t status, DeviceEvent_t event, Device_t device) { if (COMM_DEVICE_SUCCESS == status) { const DUT* dut; switch (event) { case LIBUSB_DEVICE_CONNECTED: logger_->log(Logger::INFO, "Device detected on USB@%u", comm_get_physical_address(device)); dut = DutManager::createDut(device); if (0 != dut) { logger_->log(Logger::PROGRESS, "Connected %s", dut->getId()); } break; case LIBUSB_DEVICE_DISCONNECTED: logger_->log(Logger::INFO, "Disconnect detected on USB@%u", comm_get_physical_address(device)); dut = DutManager::getDut(device); if (0 != dut) { exitstatus = dut->getErrorCode(); logger_->log(Logger::PROGRESS, "Disconnected %s", dut->getId()); DutManager::destroyDut(device); } isDone = true; break; default: logger_->log(Logger::ERR, "Unknown USB event %d", event); break; } } else if (COMM_DEVICE_LIBUSB_FAILED_TO_OPEN_PORT == status) { logger_->log(Logger::ERR, "Cannot open USB device. Are you root?", status); isDone = true; exitstatus = 1; } else { logger_->log(Logger::ERR, "USB device error %d", status); } } void handleCmdLineInput(int argc, char* argv[]) { string input; bool configPathSet = false; for (int i = 1; i != argc; ++i) { input = argv[i]; if ("-h" == input || "--help" == input) { cout << cmdHelpString << endl; _exit(0); } else if ("-v" == input || "--verbose" == input) { Logger::verbose_ = true; } else if ("--version" == input) { _exit(0); } else if ("-m" == input || "--mode" == input) { i = checkCmdLineArgument(argc, i, argv, mode); } else if ("-c" == input || "--config" == input) { configPathSet = true; i = checkCmdLineArgument(argc, i, argv, configFile); } else if ("-f" == input || "--flashimage" == input) { i = checkCmdLineArgument(argc, i, argv, flashimage); } else if ("-a" == input || "--address" == input) { i = checkCmdLineArgument(argc, i, argv, address); } else if ("-l" == input || "--length" == input) { i = checkCmdLineArgument(argc, i, argv, length); } else if ("-d" == input || "--dumppath" == input) { i = checkCmdLineArgument(argc, i, argv, dumpPath); } else { cout << "Unknown option: " << input << endl; } } if (!configPathSet) { FILE* userConfig; #ifdef _WIN32 char* home = getenv("USERPROFILE"); #else char* home = getenv("HOME"); #endif char homeConfigPath[50]; strcpy(homeConfigPath, home); strcat(homeConfigPath, "/.riff/config"); userConfig = fopen(homeConfigPath, "rb"); if (userConfig != NULL) { strcpy(configFile, homeConfigPath); fclose(userConfig); } else { // It will check the default config in /usr/share folder otherwise // or /<current directory>/riff/config userConfig = fopen(configFile, "r"); if(userConfig == NULL) { cout << cmdHelpString << endl; _exit(0); } } } if (*dumpPath == '\0') { //Sets default dump path if not provided #ifdef _WIN32 char* home = "."; #else char* home = getenv("HOME"); #endif strcpy(dumpPath, home); strcat(dumpPath, "/flashdump.bin"); } SequenceFactory::setArguments(configFile, mode, flashimage, address, length, dumpPath); } int checkCmdLineArgument(int argc, int counter, char* argv[], char* var) { counter++; if (counter < argc) { strcpy(var, argv[counter]); } else { cout << "Please give a parameter to the option" << endl; counter--; } return counter; } /* @} */ <|endoftext|>
<commit_before>#include <tuple> #include "acmacs-base/enumerate.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-base/quicklook.hh" #include "seqdb-3/compare.hh" #include "acmacs-map-draw/mod-amino-acids.hh" #include "acmacs-map-draw/draw.hh" #include "acmacs-map-draw/report-antigens.hh" #include "acmacs-map-draw/select.hh" // ---------------------------------------------------------------------- void ModAminoAcids::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/) { const auto verbose = rjson::get_or(args(), "report", false); const auto report_names_threshold = rjson::get_or(args(), "report_names_threshold", 10UL); if (const auto& pos = args()["pos"]; !pos.is_null()) { aa_pos(aChartDraw, pos, verbose, report_names_threshold); } else if (const auto& groups = args()["groups"]; !groups.is_null()) { rjson::for_each(groups, [this,&aChartDraw,verbose,report_names_threshold](const rjson::value& group) { aa_group(aChartDraw, group, verbose, report_names_threshold); }); } else { std::cerr << "No pos no groups" << '\n'; throw unrecognized_mod{"expected either \"pos\":[] or \"groups\":[] mod: " + rjson::to_string(args())}; } } // ModAminoAcids::apply // ---------------------------------------------------------------------- void ModAminoAcids::aa_pos(ChartDraw& aChartDraw, const rjson::value& aPos, bool aVerbose, size_t report_names_threshold) { std::vector<size_t> positions; rjson::copy(aPos, positions); const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions); // aa_indices is std::map<std::string, std::vector<size_t>> std::vector<std::string> aa_sorted(aa_indices.size()); // most frequent aa first std::transform(std::begin(aa_indices), std::end(aa_indices), std::begin(aa_sorted), [](const auto& entry) -> std::string { return entry.first; }); std::sort(std::begin(aa_sorted), std::end(aa_sorted), [&aa_indices](const auto& n1, const auto& n2) -> bool { return aa_indices.find(n1)->second.size() > aa_indices.find(n2)->second.size(); }); std::map<std::string, Color> color_for_aa; make_color_for_aa(color_for_aa, aa_sorted); for (auto [index, aa] : acmacs::enumerate(aa_sorted)) { const auto& indices_for_aa = aa_indices.find(aa)->second; auto styl = style(); if (auto ca = color_for_aa.find(aa); ca == color_for_aa.end()) throw unrecognized_mod{"cannot find color for AA: " + aa + ", \"colors\" in the settings is not complete?"}; else styl.fill = ca->second; aChartDraw.modify(indices_for_aa, styl, drawing_order()); if (const auto& legend = args()["legend"]; !legend.is_null()) add_legend(aChartDraw, indices_for_aa, styl, aa, legend); if (aVerbose) { fmt::print(stderr, "INFO: amino-acids at {}: {} {}\n", aPos, aa, indices_for_aa.size()); report_antigens(std::begin(indices_for_aa), std::end(indices_for_aa), aChartDraw, report_names_threshold); } } if (auto make_centroid = rjson::get_or(args(), "centroid", false); make_centroid) { auto layout = aChartDraw.projection().transformed_layout(); for (auto [aa, indexes] : aa_indices) { if (indexes.size() > 1) { const auto sum_vectors = [](acmacs::PointCoordinates sum, const auto& point) { for (auto dim : acmacs::range(std::get<0>(point).number_of_dimensions())) sum[dim] += std::get<0>(point)[dim]; return sum; }; // coordinates, distance to centroid of all points, distance to centroid of 90% closest points using element_t = std::tuple<acmacs::PointCoordinates, double, double>; std::vector<element_t> points(indexes.size(), {acmacs::PointCoordinates(layout->number_of_dimensions()), 0.0, 0.0}); std::transform(indexes.begin(), indexes.end(), points.begin(), [layout](auto index) -> element_t { return {layout->get(index), -1, -1}; }); acmacs::PointCoordinates centroid = std::accumulate(points.begin(), points.end(), acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors); centroid /= points.size(); std::for_each(points.begin(), points.end(), [&centroid](auto& point) { std::get<1>(point) = acmacs::distance(std::get<0>(point), centroid); }); std::sort(points.begin(), points.end(), [](const auto& p1, const auto& p2) { return std::get<1>(p1) < std::get<1>(p2); }); const auto radius = std::get<1>(points.back()); // std::cerr << "DEBUG: min dist:" << std::get<1>(points.front()) << " max:" << radius << '\n'; const auto num_points_90 = static_cast<long>(points.size() * 0.9); acmacs::PointCoordinates centroid_90 = std::accumulate(points.begin(), points.begin() + num_points_90, acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors); centroid_90 /= num_points_90; std::for_each(points.begin(), points.begin() + num_points_90, [&centroid_90](auto& point) { std::get<2>(point) = acmacs::distance(std::get<0>(point), centroid_90); }); std::sort(points.begin(), points.begin() + num_points_90, [](const auto& p1, const auto& p2) { return std::get<2>(p1) < std::get<2>(p2); }); const auto radius_90 = std::get<2>(*(points.begin() + num_points_90 - 1)); // aChartDraw.point(centroid, Pixels{10}).color(color_for_aa.find(aa)->second, GREEN); aChartDraw.circle(centroid, Scaled{radius * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second); aChartDraw.circle(centroid, Scaled{radius_90 * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second); } } } } // ModAminoAcids::aa_pos // ---------------------------------------------------------------------- void ModAminoAcids::make_color_for_aa(std::map<std::string, Color>& color_for_aa, const std::vector<std::string>& aa_sorted) { if (const auto& colors = args()["colors"]; !colors.is_null()) { std::vector<std::string> aa_without_colors; for (const auto& aa : aa_sorted) { if (const auto& color = colors[aa]; !color.is_null()) { color_for_aa[aa] = Color(static_cast<std::string_view>(color)); } else aa_without_colors.push_back(aa); } if (!aa_without_colors.empty()) throw unrecognized_mod{"the following AAs has no colors defined in settings \"colors\": " + acmacs::to_string(aa_without_colors)}; } else { for (auto [index, aa]: acmacs::enumerate(aa_sorted)) { color_for_aa[aa] = fill_color_default(index, aa); } } } // ModAminoAcids::make_color_for_aa // ---------------------------------------------------------------------- void ModAminoAcids::aa_group(ChartDraw& aChartDraw, const rjson::value& aGroup, bool aVerbose, size_t report_names_threshold) { const auto& pos_aa = aGroup["pos_aa"]; std::vector<size_t> positions(pos_aa.size()); rjson::transform(pos_aa, std::begin(positions), [](const rjson::value& src) -> size_t { return std::stoul(static_cast<std::string>(src)); }); std::string target_aas(pos_aa.size(), ' '); rjson::transform(pos_aa, std::begin(target_aas), [](const rjson::value& src) { return static_cast<std::string_view>(src).back(); }); const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions); if (const auto aap = aa_indices.find(target_aas); aap != aa_indices.end()) { auto styl = style(); styl = point_style_from_json(aGroup); aChartDraw.modify(aap->second, styl, drawing_order()); if (const auto& legend = args()["legend"]; !legend.is_null()) add_legend(aChartDraw, aap->second, styl, string::join(" ", positions), legend); if (aVerbose) { fmt::print(stderr, "INFO: amino-acids group {}: {}\n", pos_aa, aap->second.size()); report_antigens(std::begin(aap->second), std::end(aap->second), aChartDraw, report_names_threshold); } } else { std::cerr << "WARNING: no \"" << target_aas << "\" in " << aa_indices << '\n'; } } // ModAminoAcids::aa_group // ---------------------------------------------------------------------- Color ModAminoAcids::fill_color_default(size_t aIndex, std::string aAA) { if (aAA == "X") { ++mIndexDiff; return Color(rjson::get_or(args(), "X_color", "grey25")); } if (mColors.empty()) { const auto ct = rjson::get_or(args(), "color_set", "ana"); mColors = Color::distinct(ct == "google" ? Color::distinct_t::GoogleMaps : Color::distinct_t::Ana); } const auto index = aIndex - mIndexDiff; if (index < mColors.size()) return mColors[index]; else return mColors.back(); // throw unrecognized_mod{fmt::format("too few distinct colors in mod ({}): {}", mColors.size(), rjson::to_string(args()))}; } // ModAminoAcids::fill_color_default // ---------------------------------------------------------------------- void ModCompareSequences::apply(ChartDraw& aChartDraw, const rjson::value& aModData) { acmacs::chart::Indexes indexes1, indexes2; if (const auto& select1 = args()["select1"]; !select1.is_null()) indexes1 = SelectAntigens(false, 10).select(aChartDraw, select1); else throw unrecognized_mod{fmt::format("no select1 in mod: {}", rjson::to_string(args()))}; if (const auto& select2 = args()["select2"]; !select2.is_null()) indexes2 = SelectAntigens(false, 10).select(aChartDraw, select2); else throw unrecognized_mod{fmt::format("no select2 in mod: {}", rjson::to_string(args()))}; const auto& matched = aChartDraw.match_seqdb(); auto set1 = matched.filter_by_indexes(indexes1); auto set2 = matched.filter_by_indexes(indexes2); if (const auto& format = args()["format"]; !format.is_null() && static_cast<std::string>(format) == "html") { const auto html = acmacs::seqdb::compare_report_html(set1, set2); std::string filename{"-"}; if (const auto& output1 = args()["output"]; !output1.is_null()) { filename = output1; } else if (const auto& output2 = aModData["output_pdf"]; !output2.is_null()) { filename = fs::path(static_cast<std::string>(output2)).replace_extension(".html"); } else { filename = "/d/a.html"; } acmacs::file::write(filename, html); if (const auto& open = args()["open"]; open.is_null() || open) acmacs::open_or_quicklook(true, false, filename, 0, 0); } else fmt::print("{}\n\n", acmacs::seqdb::compare_report_text(set1, set2)); } // ModCompareSequences::apply // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>ModCompareSequences<commit_after>#include <tuple> #include "acmacs-base/enumerate.hh" #include "acmacs-base/fmt.hh" #include "acmacs-base/read-file.hh" #include "acmacs-base/filesystem.hh" #include "acmacs-base/quicklook.hh" #include "seqdb-3/compare.hh" #include "acmacs-map-draw/mod-amino-acids.hh" #include "acmacs-map-draw/draw.hh" #include "acmacs-map-draw/report-antigens.hh" #include "acmacs-map-draw/select.hh" // ---------------------------------------------------------------------- void ModAminoAcids::apply(ChartDraw& aChartDraw, const rjson::value& /*aModData*/) { const auto verbose = rjson::get_or(args(), "report", false); const auto report_names_threshold = rjson::get_or(args(), "report_names_threshold", 10UL); if (const auto& pos = args()["pos"]; !pos.is_null()) { aa_pos(aChartDraw, pos, verbose, report_names_threshold); } else if (const auto& groups = args()["groups"]; !groups.is_null()) { rjson::for_each(groups, [this,&aChartDraw,verbose,report_names_threshold](const rjson::value& group) { aa_group(aChartDraw, group, verbose, report_names_threshold); }); } else { std::cerr << "No pos no groups" << '\n'; throw unrecognized_mod{"expected either \"pos\":[] or \"groups\":[] mod: " + rjson::to_string(args())}; } } // ModAminoAcids::apply // ---------------------------------------------------------------------- void ModAminoAcids::aa_pos(ChartDraw& aChartDraw, const rjson::value& aPos, bool aVerbose, size_t report_names_threshold) { std::vector<size_t> positions; rjson::copy(aPos, positions); const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions); // aa_indices is std::map<std::string, std::vector<size_t>> std::vector<std::string> aa_sorted(aa_indices.size()); // most frequent aa first std::transform(std::begin(aa_indices), std::end(aa_indices), std::begin(aa_sorted), [](const auto& entry) -> std::string { return entry.first; }); std::sort(std::begin(aa_sorted), std::end(aa_sorted), [&aa_indices](const auto& n1, const auto& n2) -> bool { return aa_indices.find(n1)->second.size() > aa_indices.find(n2)->second.size(); }); std::map<std::string, Color> color_for_aa; make_color_for_aa(color_for_aa, aa_sorted); for (auto [index, aa] : acmacs::enumerate(aa_sorted)) { const auto& indices_for_aa = aa_indices.find(aa)->second; auto styl = style(); if (auto ca = color_for_aa.find(aa); ca == color_for_aa.end()) throw unrecognized_mod{"cannot find color for AA: " + aa + ", \"colors\" in the settings is not complete?"}; else styl.fill = ca->second; aChartDraw.modify(indices_for_aa, styl, drawing_order()); if (const auto& legend = args()["legend"]; !legend.is_null()) add_legend(aChartDraw, indices_for_aa, styl, aa, legend); if (aVerbose) { fmt::print(stderr, "INFO: amino-acids at {}: {} {}\n", aPos, aa, indices_for_aa.size()); report_antigens(std::begin(indices_for_aa), std::end(indices_for_aa), aChartDraw, report_names_threshold); } } if (auto make_centroid = rjson::get_or(args(), "centroid", false); make_centroid) { auto layout = aChartDraw.projection().transformed_layout(); for (auto [aa, indexes] : aa_indices) { if (indexes.size() > 1) { const auto sum_vectors = [](acmacs::PointCoordinates sum, const auto& point) { for (auto dim : acmacs::range(std::get<0>(point).number_of_dimensions())) sum[dim] += std::get<0>(point)[dim]; return sum; }; // coordinates, distance to centroid of all points, distance to centroid of 90% closest points using element_t = std::tuple<acmacs::PointCoordinates, double, double>; std::vector<element_t> points(indexes.size(), {acmacs::PointCoordinates(layout->number_of_dimensions()), 0.0, 0.0}); std::transform(indexes.begin(), indexes.end(), points.begin(), [layout](auto index) -> element_t { return {layout->get(index), -1, -1}; }); acmacs::PointCoordinates centroid = std::accumulate(points.begin(), points.end(), acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors); centroid /= points.size(); std::for_each(points.begin(), points.end(), [&centroid](auto& point) { std::get<1>(point) = acmacs::distance(std::get<0>(point), centroid); }); std::sort(points.begin(), points.end(), [](const auto& p1, const auto& p2) { return std::get<1>(p1) < std::get<1>(p2); }); const auto radius = std::get<1>(points.back()); // std::cerr << "DEBUG: min dist:" << std::get<1>(points.front()) << " max:" << radius << '\n'; const auto num_points_90 = static_cast<long>(points.size() * 0.9); acmacs::PointCoordinates centroid_90 = std::accumulate(points.begin(), points.begin() + num_points_90, acmacs::PointCoordinates(layout->number_of_dimensions(), 0.0), sum_vectors); centroid_90 /= num_points_90; std::for_each(points.begin(), points.begin() + num_points_90, [&centroid_90](auto& point) { std::get<2>(point) = acmacs::distance(std::get<0>(point), centroid_90); }); std::sort(points.begin(), points.begin() + num_points_90, [](const auto& p1, const auto& p2) { return std::get<2>(p1) < std::get<2>(p2); }); const auto radius_90 = std::get<2>(*(points.begin() + num_points_90 - 1)); // aChartDraw.point(centroid, Pixels{10}).color(color_for_aa.find(aa)->second, GREEN); aChartDraw.circle(centroid, Scaled{radius * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second); aChartDraw.circle(centroid, Scaled{radius_90 * 2}).color(TRANSPARENT, color_for_aa.find(aa)->second); } } } } // ModAminoAcids::aa_pos // ---------------------------------------------------------------------- void ModAminoAcids::make_color_for_aa(std::map<std::string, Color>& color_for_aa, const std::vector<std::string>& aa_sorted) { if (const auto& colors = args()["colors"]; !colors.is_null()) { std::vector<std::string> aa_without_colors; for (const auto& aa : aa_sorted) { if (const auto& color = colors[aa]; !color.is_null()) { color_for_aa[aa] = Color(static_cast<std::string_view>(color)); } else aa_without_colors.push_back(aa); } if (!aa_without_colors.empty()) throw unrecognized_mod{"the following AAs has no colors defined in settings \"colors\": " + acmacs::to_string(aa_without_colors)}; } else { for (auto [index, aa]: acmacs::enumerate(aa_sorted)) { color_for_aa[aa] = fill_color_default(index, aa); } } } // ModAminoAcids::make_color_for_aa // ---------------------------------------------------------------------- void ModAminoAcids::aa_group(ChartDraw& aChartDraw, const rjson::value& aGroup, bool aVerbose, size_t report_names_threshold) { const auto& pos_aa = aGroup["pos_aa"]; std::vector<size_t> positions(pos_aa.size()); rjson::transform(pos_aa, std::begin(positions), [](const rjson::value& src) -> size_t { return std::stoul(static_cast<std::string>(src)); }); std::string target_aas(pos_aa.size(), ' '); rjson::transform(pos_aa, std::begin(target_aas), [](const rjson::value& src) { return static_cast<std::string_view>(src).back(); }); const auto aa_indices = aChartDraw.aa_at_pos1_for_antigens(positions); if (const auto aap = aa_indices.find(target_aas); aap != aa_indices.end()) { auto styl = style(); styl = point_style_from_json(aGroup); aChartDraw.modify(aap->second, styl, drawing_order()); if (const auto& legend = args()["legend"]; !legend.is_null()) add_legend(aChartDraw, aap->second, styl, string::join(" ", positions), legend); if (aVerbose) { fmt::print(stderr, "INFO: amino-acids group {}: {}\n", pos_aa, aap->second.size()); report_antigens(std::begin(aap->second), std::end(aap->second), aChartDraw, report_names_threshold); } } else { std::cerr << "WARNING: no \"" << target_aas << "\" in " << aa_indices << '\n'; } } // ModAminoAcids::aa_group // ---------------------------------------------------------------------- Color ModAminoAcids::fill_color_default(size_t aIndex, std::string aAA) { if (aAA == "X") { ++mIndexDiff; return Color(rjson::get_or(args(), "X_color", "grey25")); } if (mColors.empty()) { const auto ct = rjson::get_or(args(), "color_set", "ana"); mColors = Color::distinct(ct == "google" ? Color::distinct_t::GoogleMaps : Color::distinct_t::Ana); } const auto index = aIndex - mIndexDiff; if (index < mColors.size()) return mColors[index]; else return mColors.back(); // throw unrecognized_mod{fmt::format("too few distinct colors in mod ({}): {}", mColors.size(), rjson::to_string(args()))}; } // ModAminoAcids::fill_color_default // ---------------------------------------------------------------------- void ModCompareSequences::apply(ChartDraw& aChartDraw, const rjson::value& aModData) { acmacs::chart::Indexes indexes1, indexes2; if (const auto& select1 = args()["select1"]; !select1.is_null()) indexes1 = SelectAntigens(false, 10).select(aChartDraw, select1); else throw unrecognized_mod{fmt::format("no select1 in mod: {}", rjson::to_string(args()))}; if (const auto& select2 = args()["select2"]; !select2.is_null()) indexes2 = SelectAntigens(false, 10).select(aChartDraw, select2); else throw unrecognized_mod{fmt::format("no select2 in mod: {}", rjson::to_string(args()))}; const auto& matched = aChartDraw.match_seqdb(); auto set1 = matched.filter_by_indexes(indexes1); auto set2 = matched.filter_by_indexes(indexes2); if (const auto& format = args()["format"]; !format.is_null() && static_cast<std::string>(format) == "html") { std::string filename{"-"}; if (const auto& output1 = args()["output"]; !output1.is_null()) { filename = output1; } else if (const auto& output2 = aModData["output_pdf"]; !output2.is_null()) { filename = fs::path(static_cast<std::string>(output2)).replace_extension(".html"); } else { filename = "/d/a.html"; } acmacs::file::write(filename, acmacs::seqdb::compare_report_html(filename, set1, set2)); if (const auto& open = args()["open"]; open.is_null() || open) acmacs::open_or_quicklook(true, false, filename, 0, 0); } else fmt::print("{}\n\n", acmacs::seqdb::compare_report_text(set1, set2)); } // ModCompareSequences::apply // ---------------------------------------------------------------------- // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#include <chrono> #include <iostream> #include <stdio.h> #include "uvpp_udp.hpp" int main(int argc, char *argv[]) { struct sockaddr_in saddr; uv_ip4_addr("239.255.255.1", 12345, &saddr); uvpp::Loop uvloop; uvpp::Signal sigint(uvloop); sigint.set_callback([&uvloop](){ uvloop.stop(); }); sigint.start(SIGINT); uvpp::Udp mcast(uvloop); int sndbufsize = mcast.send_buffer_size(1048576); printf("send_buffer_size: %d\n", sndbufsize); auto period = std::chrono::milliseconds{125}; using clk = std::chrono::system_clock; auto start_time = clk::now(); uint32_t intcnt = 0; uint32_t buf[15360]; uvpp::Timer timer(uvloop); timer.set_callback([&](){ for (int blkcnt=0; blkcnt < 9; blkcnt++) { buf[0] = intcnt; buf[1] = blkcnt; mcast.send((char*)buf, sizeof(buf), saddr); } intcnt++; auto elapsed = clk::now() - start_time; auto delay = (intcnt+1)*period - elapsed; auto delay_ms = std::chrono::duration_cast<std::chrono::milliseconds>(delay); timer.start(delay_ms.count(), 0); if (intcnt % 8==0) { std::chrono::duration<double> elapsed_sec = elapsed; printf("%.3f\n", elapsed_sec.count()); } }); timer.start(period.count(), 0); uvloop.run(); printf("loop exit\n"); } <commit_msg>switch to steady_clock<commit_after>#include <chrono> #include <iostream> #include <stdio.h> #include "uvpp_udp.hpp" int main(int argc, char *argv[]) { struct sockaddr_in saddr; uv_ip4_addr("239.255.255.1", 12345, &saddr); uvpp::Loop uvloop; uvpp::Signal sigint(uvloop); sigint.set_callback([&uvloop](){ uvloop.stop(); }); sigint.start(SIGINT); uvpp::Udp mcast(uvloop); int sndbufsize = mcast.send_buffer_size(1048576); printf("send_buffer_size: %d\n", sndbufsize); auto period = std::chrono::milliseconds{125}; using clk = std::chrono::steady_clock; auto start_time = clk::now(); uint32_t intcnt = 0; uint32_t buf[15360]; uvpp::Timer timer(uvloop); timer.set_callback([&](){ for (int blkcnt=0; blkcnt < 9; blkcnt++) { buf[0] = intcnt; buf[1] = blkcnt; mcast.send((char*)buf, sizeof(buf), saddr); } intcnt++; auto elapsed = clk::now() - start_time; auto delay = (intcnt+1)*period - elapsed; auto delay_ms = std::chrono::duration_cast<std::chrono::milliseconds>(delay); timer.start(delay_ms.count(), 0); if (intcnt % 8==0) { std::chrono::duration<double> elapsed_sec = elapsed; printf("%.3f\n", elapsed_sec.count()); } }); timer.start(period.count(), 0); uvloop.run(); printf("loop exit\n"); } <|endoftext|>
<commit_before>#ifndef ELEKTRA_KDBTHREAD_HPP #define ELEKTRA_KDBTHREAD_HPP #include <kdbcontext.hpp> #include <kdb.hpp> #include <mutex> #include <thread> #include <vector> #include <cassert> #include <algorithm> #include <functional> #include <unordered_map> namespace kdb { /// Subject from Observer pattern for ThreadContext class ThreadSubject { public: virtual void notify(KeySet &ks) = 0; virtual void syncLayers() = 0; }; struct LayerAction { LayerAction(bool activate_, std::shared_ptr<Layer> layer_) : activate(activate_), layer(layer_) { } bool activate; // false if deactivate std::shared_ptr<Layer> layer; }; /// A vector of layers typedef std::vector<LayerAction> LayerVector; typedef std::unordered_map<std::string, std::vector<std::function<void()>>> FunctionMap; /// A data structure that is stored by context inside the Coordinator struct PerContext { KeySet toUpdate; LayerVector toActivate; }; class ThreadNoContext { public: /** * @brief attach a new value * * NoContext will never update anything */ void attachByName(ELEKTRA_UNUSED std::string const & key_name,ELEKTRA_UNUSED ValueObserver & ValueObserver) {} /** * @brief The evaluated equals the non-evaluated name! * * @return NoContext always returns the same string */ std::string evaluate(std::string const & key_name) const { return key_name; } /** * @brief (Re)attaches a ValueSubject to a thread or simply * execute code in a locked section. * * NoContext just executes the function but does so in a * thread-safe way * * @param c the command to apply */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); c(); } private: std::mutex m_mutex; }; /** * @brief Thread safe coordination of ThreadContext per Threads. */ class Coordinator { public: template <typename T> void onLayerActivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onActivate[layer->id()].push_back(f); } template <typename T> void onLayerDeactivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onDeactivate[layer->id()].push_back(f); } void onLayerActivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].push_back(f); } void onLayerDeactivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].push_back(f); } void clearOnLayerActivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].clear(); } void clearOnLayerDeactivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].clear(); } std::unique_lock<std::mutex> requireLock() { std::unique_lock<std::mutex> lock(m_mutex); return std::move(lock); } ~Coordinator() { #if DEBUG for (auto & i: m_updates) { std::cout << "coordinator " << this << "left over : " << i.first << " with updates: " << i.second.toUpdate.size() << " activations: " << i.second.toActivate.size() << std::endl; } #endif } private: friend class ThreadContext; void attach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.insert(std::make_pair(c, PerContext())); } void detach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.erase(c); } /** * @brief Update the given ThreadContext with newly assigned * values. */ void updateNewlyAssignedValues(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); KeySet & toUpdate = m_updates[c].toUpdate; if (toUpdate.size() == 0) return; c->notify(toUpdate); toUpdate.clear(); } /** * @brief Receive a function to be executed and remember * which keys need a update in the other ThreadContexts. */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); Command::Pair ret = c(); c.oldKey = ret.first; c.newKey = ret.second; if (c.hasChanged) { for (auto & i: m_updates) { i.second.toUpdate.append(Key(c.newKey, KEY_CASCADING_NAME, KEY_END)); } } } void runOnActivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); for (auto && f: m_onActivate[layer->id()]) { f(); } } /** * @brief Request that some layer needs to be globally * activated. * * @param cc requests it and already has it updated itself * @param layer to activate for all threads */ void globalActivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnActivate(layer); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already activated if (cc == c.first) continue; c.second.toActivate.push_back(LayerAction(true, layer)); } } void runOnDeactivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); for (auto && f: m_onDeactivate[layer->id()]) { f(); } } void globalDeactivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnDeactivate(layer); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already deactivated if (cc == c.first) continue; c.second.toActivate.push_back(LayerAction(false, layer)); } } /** * @param cc requester of its updates * * @see globalActivate * @return all layers for that subject */ LayerVector fetchGlobalActivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toActivate); return std::move(ret); } /// stores per context updates not yet delievered std::unordered_map<ThreadSubject *, PerContext> m_updates; /// mutex protecting m_updates std::mutex m_mutex; FunctionMap m_onActivate; std::mutex m_mutexOnActivate; FunctionMap m_onDeactivate; std::mutex m_mutexOnDeactivate; }; class ThreadContext : public ThreadSubject, public Context { public: typedef std::reference_wrapper<ValueSubject> ValueRef ; explicit ThreadContext(Coordinator & gc) : m_gc(gc) { m_gc.attach(this); } ~ThreadContext() { m_gc.detach(this); #if DEBUG for (auto & i: m_keys) { std::cout << "threadcontext " << this << " left over: " << i.first << std::endl; } #endif } Coordinator & global() { return m_gc; } Coordinator & g() { return m_gc; } template <typename T, typename... Args> std::shared_ptr<Layer> activate(Args&&... args) { syncLayers(); std::shared_ptr<Layer>layer = Context::activate<T>(std::forward<Args>(args)...); m_gc.globalActivate(this, layer); return layer; } template <typename T, typename... Args> std::shared_ptr<Layer> deactivate(Args&&... args) { syncLayers(); std::shared_ptr<Layer>layer = Context::deactivate<T>(std::forward<Args>(args)...); m_gc.globalDeactivate(this, layer); return layer; } void syncLayers() { // now activate/deactive layers Events e; for(auto const & l: m_gc.fetchGlobalActivation(this)) { if (l.activate) { activateLayer(l.layer); } else { deactivateLayer(l.layer); } e.push_back(l.layer->id()); } notifyByEvents(e); // pull in assignments from other threads m_gc.updateNewlyAssignedValues(this); } /** * @brief Command dispatching * * @param c the command to execute */ void execute(Command & c) { m_gc.execute(c); if (c.oldKey != c.newKey) { if (!c.oldKey.empty()) { m_keys.erase(c.oldKey); } if (!c.newKey.empty()) { m_keys.insert(std::make_pair(c.newKey, ValueRef(c.v))); } } } /** * @brief notify all keys * * Locked during execution, safe to use ks * * @param ks */ void notify(KeySet & ks) { for(auto const & k: ks) { auto const& f = m_keys.find(k.getName()); if (f == m_keys.end()) continue; // key already had context change f->second.get().notifyInThread(); } } private: Coordinator & m_gc; /** * @brief A map of values this ThreadContext is responsible for. */ std::unordered_map<std::string, ValueRef> m_keys; }; template<typename T, typename PolicySetter1 = DefaultPolicyArgs, typename PolicySetter2 = DefaultPolicyArgs, typename PolicySetter3 = DefaultPolicyArgs, typename PolicySetter4 = DefaultPolicyArgs, typename PolicySetter5 = DefaultPolicyArgs > using ThreadValue = Value <T, ContextPolicyIs<ThreadContext>, PolicySetter1, PolicySetter2, PolicySetter3, PolicySetter4, PolicySetter5 >; typedef ThreadValue<uint32_t>ThreadInteger; typedef ThreadValue<bool>ThreadBoolean; typedef ThreadValue<std::string>ThreadString; } #endif <commit_msg>give new ThreadContext history up to now<commit_after>#ifndef ELEKTRA_KDBTHREAD_HPP #define ELEKTRA_KDBTHREAD_HPP #include <kdbcontext.hpp> #include <kdb.hpp> #include <mutex> #include <thread> #include <vector> #include <cassert> #include <algorithm> #include <functional> #include <unordered_map> namespace kdb { /// Subject from Observer pattern for ThreadContext class ThreadSubject { public: virtual void notify(KeySet &ks) = 0; virtual void syncLayers() = 0; }; struct LayerAction { LayerAction(bool activate_, std::shared_ptr<Layer> layer_) : activate(activate_), layer(layer_) { } bool activate; // false if deactivate std::shared_ptr<Layer> layer; }; /// A vector of layers typedef std::vector<LayerAction> LayerVector; typedef std::unordered_map<std::string, std::vector<std::function<void()>>> FunctionMap; /// A data structure that is stored by context inside the Coordinator struct PerContext { KeySet toUpdate; LayerVector toActivate; }; class ThreadNoContext { public: /** * @brief attach a new value * * NoContext will never update anything */ void attachByName(ELEKTRA_UNUSED std::string const & key_name,ELEKTRA_UNUSED ValueObserver & ValueObserver) {} /** * @brief The evaluated equals the non-evaluated name! * * @return NoContext always returns the same string */ std::string evaluate(std::string const & key_name) const { return key_name; } /** * @brief (Re)attaches a ValueSubject to a thread or simply * execute code in a locked section. * * NoContext just executes the function but does so in a * thread-safe way * * @param c the command to apply */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); c(); } private: std::mutex m_mutex; }; /** * @brief Thread safe coordination of ThreadContext per Threads. */ class Coordinator { public: template <typename T> void onLayerActivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onActivate[layer->id()].push_back(f); } template <typename T> void onLayerDeactivation(std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); std::shared_ptr<Layer>layer = std::make_shared<T>(); m_onDeactivate[layer->id()].push_back(f); } void onLayerActivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].push_back(f); } void onLayerDeactivation(std::string layerid, std::function <void()> f) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].push_back(f); } void clearOnLayerActivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); m_onActivate[layerid].clear(); } void clearOnLayerDeactivation(std::string layerid) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); m_onDeactivate[layerid].clear(); } std::unique_lock<std::mutex> requireLock() { std::unique_lock<std::mutex> lock(m_mutex); return std::move(lock); } Coordinator() { std::lock_guard<std::mutex> lock (m_mutex); m_updates.insert(std::make_pair(nullptr, PerContext())); } ~Coordinator() { #if DEBUG for (auto & i: m_updates) { std::cout << "coordinator " << this << " left over: " << i.first << " with updates: " << i.second.toUpdate.size() << " activations: " << i.second.toActivate.size() << std::endl; } #endif } private: friend class ThreadContext; void attach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.insert(std::make_pair(c, m_updates[nullptr])); } void detach(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); m_updates.erase(c); } /** * @brief Update the given ThreadContext with newly assigned * values. */ void updateNewlyAssignedValues(ThreadSubject *c) { std::lock_guard<std::mutex> lock (m_mutex); KeySet & toUpdate = m_updates[c].toUpdate; if (toUpdate.size() == 0) return; c->notify(toUpdate); toUpdate.clear(); } /** * @brief Receive a function to be executed and remember * which keys need a update in the other ThreadContexts. */ void execute(Command & c) { std::lock_guard<std::mutex> lock (m_mutex); Command::Pair ret = c(); c.oldKey = ret.first; c.newKey = ret.second; if (c.hasChanged) { for (auto & i: m_updates) { i.second.toUpdate.append(Key(c.newKey, KEY_CASCADING_NAME, KEY_END)); } } } void runOnActivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnActivate); for (auto && f: m_onActivate[layer->id()]) { f(); } } /** * @brief Request that some layer needs to be globally * activated. * * @param cc requests it and already has it updated itself * @param layer to activate for all threads */ void globalActivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnActivate(layer); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already activated if (cc == c.first) continue; c.second.toActivate.push_back(LayerAction(true, layer)); } } void runOnDeactivate(std::shared_ptr<Layer> layer) { std::lock_guard<std::mutex> lock (m_mutexOnDeactivate); for (auto && f: m_onDeactivate[layer->id()]) { f(); } } void globalDeactivate(ThreadSubject *cc, std::shared_ptr<Layer> layer) { runOnDeactivate(layer); std::lock_guard<std::mutex> lock (m_mutex); for (auto & c: m_updates) { // caller itself has it already deactivated if (cc == c.first) continue; c.second.toActivate.push_back(LayerAction(false, layer)); } } /** * @param cc requester of its updates * * @see globalActivate * @return all layers for that subject */ LayerVector fetchGlobalActivation(ThreadSubject *cc) { std::lock_guard<std::mutex> lock (m_mutex); LayerVector ret; ret.swap(m_updates[cc].toActivate); return std::move(ret); } /// stores per context updates not yet delievered /// nullptr is for full history to be copied to new contexts std::unordered_map<ThreadSubject *, PerContext> m_updates; /// mutex protecting m_updates std::mutex m_mutex; FunctionMap m_onActivate; std::mutex m_mutexOnActivate; FunctionMap m_onDeactivate; std::mutex m_mutexOnDeactivate; }; class ThreadContext : public ThreadSubject, public Context { public: typedef std::reference_wrapper<ValueSubject> ValueRef ; explicit ThreadContext(Coordinator & gc) : m_gc(gc) { m_gc.attach(this); } ~ThreadContext() { m_gc.detach(this); #if DEBUG for (auto & i: m_keys) { std::cout << "threadcontext " << this << " left over: " << i.first << std::endl; } #endif } Coordinator & global() { return m_gc; } Coordinator & g() { return m_gc; } template <typename T, typename... Args> std::shared_ptr<Layer> activate(Args&&... args) { syncLayers(); std::shared_ptr<Layer>layer = Context::activate<T>(std::forward<Args>(args)...); m_gc.globalActivate(this, layer); return layer; } template <typename T, typename... Args> std::shared_ptr<Layer> deactivate(Args&&... args) { syncLayers(); std::shared_ptr<Layer>layer = Context::deactivate<T>(std::forward<Args>(args)...); m_gc.globalDeactivate(this, layer); return layer; } void syncLayers() { // now activate/deactive layers Events e; for(auto const & l: m_gc.fetchGlobalActivation(this)) { if (l.activate) { activateLayer(l.layer); } else { deactivateLayer(l.layer); } e.push_back(l.layer->id()); } notifyByEvents(e); // pull in assignments from other threads m_gc.updateNewlyAssignedValues(this); } /** * @brief Command dispatching * * @param c the command to execute */ void execute(Command & c) { m_gc.execute(c); if (c.oldKey != c.newKey) { if (!c.oldKey.empty()) { m_keys.erase(c.oldKey); } if (!c.newKey.empty()) { m_keys.insert(std::make_pair(c.newKey, ValueRef(c.v))); } } } /** * @brief notify all keys * * Locked during execution, safe to use ks * * @param ks */ void notify(KeySet & ks) { for(auto const & k: ks) { auto const& f = m_keys.find(k.getName()); if (f == m_keys.end()) continue; // key already had context change f->second.get().notifyInThread(); } } private: Coordinator & m_gc; /** * @brief A map of values this ThreadContext is responsible for. */ std::unordered_map<std::string, ValueRef> m_keys; }; template<typename T, typename PolicySetter1 = DefaultPolicyArgs, typename PolicySetter2 = DefaultPolicyArgs, typename PolicySetter3 = DefaultPolicyArgs, typename PolicySetter4 = DefaultPolicyArgs, typename PolicySetter5 = DefaultPolicyArgs > using ThreadValue = Value <T, ContextPolicyIs<ThreadContext>, PolicySetter1, PolicySetter2, PolicySetter3, PolicySetter4, PolicySetter5 >; typedef ThreadValue<uint32_t>ThreadInteger; typedef ThreadValue<bool>ThreadBoolean; typedef ThreadValue<std::string>ThreadString; } #endif <|endoftext|>
<commit_before>// // ConfigImpl.cpp #include "common/RhoStd.h" #include "common/AutoPointer.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "generated/cpp/ConfigBase.h" #include "logging/RhoLog.h" namespace rho { using namespace apiGenerator; using namespace common; class CConfigSingletonImpl: public CConfigSingletonBase { public: CConfigSingletonImpl() : CConfigSingletonBase(){} virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getAppConfFilePath()); } virtual void setConfigPath(const rho::String& configPath, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setAppConfFilePath(configPath.c_str()); } virtual void getPropertyString(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getString(name.c_str())); } virtual void setPropertyString(const rho::String& name, const rho::String& value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setString(name.c_str(), value, saveToFile); } virtual void getPropertyInt(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getInt(name.c_str())); } virtual void setPropertyInt(const rho::String& name, int value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setInt(name.c_str(), value, saveToFile); } virtual void getPropertyBool(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getBool(name.c_str())); } virtual void setPropertyBool(const rho::String& name, bool value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setBool(name.c_str(), value, saveToFile); } virtual void isPropertyExists(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().isExist(name.c_str())); } virtual void removeProperty( const rho::String& name, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().removeProperty(name.c_str(), saveToFile); } virtual void loadFromFile(rho::apiGenerator::CMethodResult& oResult) { RHOCONF().loadFromFile(); } virtual void getConflicts(rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getConflicts()); } }; class CConfigImpl : public CConfigBase { public: virtual ~CConfigImpl() {} }; //////////////////////////////////////////////////////////////////////// class CConfigFactory: public CConfigFactoryBase { public: CConfigFactory(){} IConfigSingleton* createModuleSingleton() { return new CConfigSingletonImpl(); } virtual IConfig* createModuleByID(const rho::String& strID){ return new CConfigImpl(); }; }; } extern "C" void Init_Config_extension() { rho::CConfigFactory::setInstance( new rho::CConfigFactory() ); rho::Init_Config_API(); }<commit_msg>revert implementtaion of getConflicts<commit_after>// // ConfigImpl.cpp #include "common/RhoStd.h" #include "common/AutoPointer.h" #include "common/RhodesApp.h" #include "common/RhoConf.h" #include "generated/cpp/ConfigBase.h" #include "logging/RhoLog.h" namespace rho { using namespace apiGenerator; using namespace common; class CConfigSingletonImpl: public CConfigSingletonBase { public: CConfigSingletonImpl() : CConfigSingletonBase(){} virtual void getConfigPath(rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getAppConfFilePath()); } virtual void setConfigPath(const rho::String& configPath, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setAppConfFilePath(configPath.c_str()); } virtual void getPropertyString(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getString(name.c_str())); } virtual void setPropertyString(const rho::String& name, const rho::String& value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setString(name.c_str(), value, saveToFile); } virtual void getPropertyInt(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getInt(name.c_str())); } virtual void setPropertyInt(const rho::String& name, int value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setInt(name.c_str(), value, saveToFile); } virtual void getPropertyBool(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().getBool(name.c_str())); } virtual void setPropertyBool(const rho::String& name, bool value, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().setBool(name.c_str(), value, saveToFile); } virtual void isPropertyExists(const rho::String& name, rho::apiGenerator::CMethodResult& oResult) { oResult.set(RHOCONF().isExist(name.c_str())); } virtual void removeProperty( const rho::String& name, bool saveToFile, rho::apiGenerator::CMethodResult& oResult) { RHOCONF().removeProperty(name.c_str(), saveToFile); } virtual void loadFromFile(rho::apiGenerator::CMethodResult& oResult) { RHOCONF().loadFromFile(); } virtual void getConflicts(rho::apiGenerator::CMethodResult& oResult) { //oResult.set(RHOCONF().getConflicts()); } }; class CConfigImpl : public CConfigBase { public: virtual ~CConfigImpl() {} }; //////////////////////////////////////////////////////////////////////// class CConfigFactory: public CConfigFactoryBase { public: CConfigFactory(){} IConfigSingleton* createModuleSingleton() { return new CConfigSingletonImpl(); } virtual IConfig* createModuleByID(const rho::String& strID){ return new CConfigImpl(); }; }; } extern "C" void Init_Config_extension() { rho::CConfigFactory::setInstance( new rho::CConfigFactory() ); rho::Init_Config_API(); }<|endoftext|>
<commit_before>// // oexpand.cpp // // Created by Edmund Kapusniak on 29/10/2014. // Copyright (c) 2014 Edmund Kapusniak. All rights reserved. // #include "oexpand.h" ometatype oexpand::metatype = { &mark_expand, "object" }; oexpand* oexpand::alloc() { void* p = malloc( sizeof( oexpand ) ); return new ( p ) oexpand( &metatype, ocontext::context->empty ); } oexpand* oexpand::alloc( oexpand* prototype ) { void* p = malloc( sizeof( oexpand ) ); return new ( p ) oexpand( &metatype, prototype->empty() ); } oexpand::oexpand( ometatype* metatype, oclass* klass ) : obase( metatype ) , klass( klass ) { } void oexpand::delkey( osymbol key ) { auto lookup = klass->lookup.lookup( key ); if ( lookup ) { #if OEXPANDSLOTS oslotindex index = lookup->value; slots->store( index.slot, ovalue::undefined ); if ( index.dual >= 2 ) slots->store( index.dual - 2, ovalue::undefined ); #else slots->at( lookup->value ) = ovalue::undefined; #endif } } oclass* oexpand::empty() { if ( klass->is_prototype ) { #if OEXPANDSLOTS return slots->load( 0 ).as< oclass >(); #else return slots->at( 0 ).load().as< oclass >(); #endif } else { // Create empty. oclass* empty = oclass::alloc(); empty->prototype = this; // Assign to appropriate slot. The class we expand to will // have is_prototype set and empty will be assigned slot 0. expandkey( osymbol(), empty ); // Return the created empty. return empty; } } #if OEXPANDSLOTS void oexpand::dualkey( osymbol key, oslotindex index, ovalue value ) { if ( index.dual >= oslotindex::DUALSLOT ) { // Dual property write. Remember, slot is the _number_ slot, and // dual is the reference. This is because any value can safely be // stored in 'number' slots, while references can't hold numbers. size_t dualslot = index.dual - oslotindex::DUALSLOT; if ( value.is_number() ) { // Write number to number slot, and undefined to reference slot. slots->store( index.slot, value ); slots->store( dualslot, ovalue::undefined ); } else { // Write reference to both slots. slots->store( index.slot, value ); slots->store( dualslot, value ); } } else { // Otherwise, we need to promote the slot to a dual slot and // construct a new class. expanddual( key, index, value ); } } void oexpand::expandkey( osymbol key, ovalue value ) { // Expand a new slot. expanddual( key, oslotindex(), value ); } void oexpand::expanddual( osymbol key, oslotindex index, ovalue value ) { oclass* klass = this->klass; oslotlist* slots = this->slots; // If key is null then we're allocating slot 0 for the prototype. size_t offset = key ? 0 : 1; // If the new class resizes the slotlist then number slots (which // are allocated from the bottom up) will end up in different locations. size_t size = slots->size(); size_t watermark = slots->watermark(); size_t expand_size = klass->expandref.size() + klass->expandnum.size() + 1; expand_size = std::max( ceil_pow2( expand_size ), (size_t)8 ); // Where we would place the new value (assuming it's not slot 0). size_t reference_slot = watermark; size_t number_slot = expand_size - 1 - klass->numbercount; assert( number_slot >= reference_slot ); // Find class describing expanded object. oclass* expand = nullptr; bool is_number = value.is_number(); auto& expandtable = is_number ? klass->expandnum : klass->expandref; auto lookup = expandtable.lookup( key ); if ( lookup ) { // Expand class already exists, use it. expand = lookup->value; } else { // Build new class. expand = oclass::alloc(); expand->prototype = klass->prototype; bool made_dual = false; for ( auto i = klass->lookup.iter(); i != nullptr; i = klass->lookup.next( i ) ) { oslotindex index = i->value; // Numbers, or the number part of dual slots, may end up moving. // References may be pushed downwards due to addition of slot 0. if ( index.dual == oslotindex::REFERENCE ) { index.slot += offset; } else if ( index.dual == oslotindex::NUMBER ) { index.slot += expand_size - size; } else if ( index.dual >= oslotindex::DUALSLOT ) { index.slot += expand_size - size; index.dual += offset; } // If this is the key that is expanding, then it needs to become // a dual slot. if ( i->key == key ) { assert( key ); if ( is_number ) { index.dual = oslotindex::DUALSLOT + index.slot; index.slot = number_slot; } else { index.dual = oslotindex::DUALSLOT + reference_slot; } made_dual = true; } expand->lookup.insert( i->key, index ); } expand->numbercount = klass->numbercount + ( is_number ? 1 : 0 ); if ( key ) { // Add key, if it wasn't a key that expanded. if ( ! made_dual ) { oslotindex index; if ( is_number ) { index.slot = number_slot; index.dual = oslotindex::NUMBER; } else { index.slot = reference_slot; index.dual = oslotindex::REFERENCE; } expand->lookup.insert( key, index ); } expand->is_prototype = klass->prototype; } else { // Add prototype reference at slot 0. assert( ! is_number ); assert( ! klass->is_prototype ); oslotindex index( 0, oslotindex::REFERENCE ); expand->lookup.insert( key, index ); expand->is_prototype = true; } // Remember new class. expandtable.insert( key, expand ); } // Update class. this->klass = expand; if ( size != expand_size ) { // Slots require reallocation. oslotlist* newslots = oslotlist::alloc( expand_size ); for ( size_t i = 0; i < watermark; ++i ) { newslots->store( offset + i, slots->load( i ) ); } for ( size_t i = size - klass->numbercount; i < size; ++i ) { newslots->store( i + expand_size - size, slots->load( i ) ); } if ( key ) { size_t slot = is_number ? number_slot : reference_slot; storedual( index, slot, value ); newslots->set_watermark( watermark + ( is_number ? 0 : 1 ) ); } else { assert( ! is_number ); slots->store( 0, value ); slots->set_watermark( watermark + 1 ); } this->slots = slots; } else if ( key ) { // Store new slot. size_t slot = is_number ? number_slot : reference_slot; storedual( index, slot, value ); if ( ! is_number ) { slots->set_watermark( watermark + 1 ); } } else { // Shuffle slots and add at slot 0. for ( size_t i = watermark; i > 0; --i ) { slots->store( i, slots->load( i - 1 ) ); } assert( ! is_number ); slots->store( 0, value ); slots->set_watermark( watermark + 1 ); } } void oexpand::storedual( oslotindex index, size_t newslot, ovalue value ) { bool is_number = value.is_number(); if ( index.slot != oslotindex::INVALID ) { // Slot existed before the expand, this is now a dual slot. if ( is_number ) { assert( index.dual == oslotindex::REFERENCE ); slots->store( index.slot, ovalue::undefined ); slots->store( newslot, value ); } else { assert( index.dual == oslotindex::NUMBER ); slots->store( index.slot, value ); slots->store( newslot, value ); } } else { // Single slot. if ( is_number ) { slots->store( newslot, value ); } else { slots->store( newslot, value ); } } } #else void oexpand::expandkey( osymbol key, ovalue value ) { oclass* klass = this->klass; otuple< ovalue >* slots = this->slots; // If key is null then we're allocating slot 0 for the prototype. size_t offset = key ? 0 : 1; // Find class describing expanded object. oclass* expand = nullptr; auto lookup = klass->expand.lookup( key ); if ( lookup ) { // Expand class already exists, use it. expand = lookup->value; } else { // Build new class. expand = oclass::alloc(); expand->prototype = klass->prototype; for ( auto i = klass->lookup.iter(); i != nullptr; i = klass->lookup.next( i ) ) { expand->lookup.insert( i->key, offset + i->value ); } if ( key ) { expand->lookup.insert( key, klass->lookup.size() ); expand->is_prototype = klass->is_prototype; } else { assert( ! klass->is_prototype ); expand->lookup.insert( key, 0 ); expand->is_prototype = true; } // Link it in so it gets reused. klass->expand.insert( key, expand ); } // Update class. this->klass = expand; if ( ! slots || slots->size() < expand->lookup.size() ) { // Slots require reallocation. size_t size = ceil_pow2( expand->lookup.size() ); size = std::max( size, (size_t)8 ); otuple< ovalue >* newslots = otuple< ovalue >::alloc( size ); for ( size_t i = 0; i < klass->lookup.size(); ++i ) { newslots->at( i + offset ) = slots->at( i ); } if ( key ) newslots->at( klass->lookup.size() ) = value; else newslots->at( 0 ) = value; this->slots = slots; } else if ( key ) { // Add new value in its position. slots->at( klass->lookup.size() ) = value; } else { // Shuffle slots downwards to make room for slot 0. for ( size_t i = klass->lookup.size(); i > 0; --i ) { slots->at( i ) = slots->at( i - 1 ); } slots->at( 0 ) = value; } } #endif void oexpand::mark_expand( oworklist* work, obase* object, ocolour colour ) { oexpand* expand = (oexpand*)object; omark< oclass* >::mark( expand->klass, work, colour ); #if OEXPANDSLOTS omark< oslotlist* >::mark( expand->slots, work, colour ); #else omark< otuple< ovalue >* >::mark( expand->slots, work, colour ); #endif } ometatype oclass::metatype = { &mark_class, "class" }; oclass* oclass::alloc() { void* p = malloc( sizeof( oclass ) ); return new ( p ) oclass( &metatype ); } oclass::oclass( ometatype* metatype ) : obase( metatype ) #if OEXPANDCLASS , numbercount( 0 ) #endif , is_prototype( false ) { } void oclass::mark_class( oworklist* work, obase* object, ocolour colour ) { oclass* klass = (oclass*)object; omark< oexpand* >::mark( klass->prototype, work, colour ); #if OEXPANDSLOTS omark< okeytable< osymbol, oslotindex > >::mark( klass->lookup, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expandref, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expandnum, work, colour ); #else omark< okeytable< osymbol, size_t > >::mark( klass->lookup, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expand, work, colour ); #endif } <commit_msg>number of slots is watermark + numbercount, not that other rubbish<commit_after>// // oexpand.cpp // // Created by Edmund Kapusniak on 29/10/2014. // Copyright (c) 2014 Edmund Kapusniak. All rights reserved. // #include "oexpand.h" ometatype oexpand::metatype = { &mark_expand, "object" }; oexpand* oexpand::alloc() { void* p = malloc( sizeof( oexpand ) ); return new ( p ) oexpand( &metatype, ocontext::context->empty ); } oexpand* oexpand::alloc( oexpand* prototype ) { void* p = malloc( sizeof( oexpand ) ); return new ( p ) oexpand( &metatype, prototype->empty() ); } oexpand::oexpand( ometatype* metatype, oclass* klass ) : obase( metatype ) , klass( klass ) { } void oexpand::delkey( osymbol key ) { auto lookup = klass->lookup.lookup( key ); if ( lookup ) { #if OEXPANDSLOTS oslotindex index = lookup->value; slots->store( index.slot, ovalue::undefined ); if ( index.dual >= 2 ) slots->store( index.dual - 2, ovalue::undefined ); #else slots->at( lookup->value ) = ovalue::undefined; #endif } } oclass* oexpand::empty() { if ( klass->is_prototype ) { #if OEXPANDSLOTS return slots->load( 0 ).as< oclass >(); #else return slots->at( 0 ).load().as< oclass >(); #endif } else { // Create empty. oclass* empty = oclass::alloc(); empty->prototype = this; // Assign to appropriate slot. The class we expand to will // have is_prototype set and empty will be assigned slot 0. expandkey( osymbol(), empty ); // Return the created empty. return empty; } } #if OEXPANDSLOTS void oexpand::dualkey( osymbol key, oslotindex index, ovalue value ) { if ( index.dual >= oslotindex::DUALSLOT ) { // Dual property write. Remember, slot is the _number_ slot, and // dual is the reference. This is because any value can safely be // stored in 'number' slots, while references can't hold numbers. size_t dualslot = index.dual - oslotindex::DUALSLOT; if ( value.is_number() ) { // Write number to number slot, and undefined to reference slot. slots->store( index.slot, value ); slots->store( dualslot, ovalue::undefined ); } else { // Write reference to both slots. slots->store( index.slot, value ); slots->store( dualslot, value ); } } else { // Otherwise, we need to promote the slot to a dual slot and // construct a new class. expanddual( key, index, value ); } } void oexpand::expandkey( osymbol key, ovalue value ) { // Expand a new slot. expanddual( key, oslotindex(), value ); } void oexpand::expanddual( osymbol key, oslotindex index, ovalue value ) { oclass* klass = this->klass; oslotlist* slots = this->slots; // If key is null then we're allocating slot 0 for the prototype. size_t offset = key ? 0 : 1; // If the new class resizes the slotlist then number slots (which // are allocated from the bottom up) will end up in different locations. size_t size = slots->size(); size_t watermark = slots->watermark(); size_t expand_size = watermark + klass->numbercount + 1; expand_size = std::max( ceil_pow2( expand_size ), (size_t)8 ); // Where we would place the new value (assuming it's not slot 0). size_t reference_slot = watermark; size_t number_slot = expand_size - 1 - klass->numbercount; assert( number_slot >= reference_slot ); // Find class describing expanded object. oclass* expand = nullptr; bool is_number = value.is_number(); auto& expandtable = is_number ? klass->expandnum : klass->expandref; auto lookup = expandtable.lookup( key ); if ( lookup ) { // Expand class already exists, use it. expand = lookup->value; } else { // Build new class. expand = oclass::alloc(); expand->prototype = klass->prototype; bool made_dual = false; for ( auto i = klass->lookup.iter(); i != nullptr; i = klass->lookup.next( i ) ) { oslotindex index = i->value; // Numbers, or the number part of dual slots, may end up moving. // References may be pushed downwards due to addition of slot 0. if ( index.dual == oslotindex::REFERENCE ) { index.slot += offset; } else if ( index.dual == oslotindex::NUMBER ) { index.slot += expand_size - size; } else if ( index.dual >= oslotindex::DUALSLOT ) { index.slot += expand_size - size; index.dual += offset; } // If this is the key that is expanding, then it needs to become // a dual slot. if ( i->key == key ) { assert( key ); if ( is_number ) { index.dual = oslotindex::DUALSLOT + index.slot; index.slot = number_slot; } else { index.dual = oslotindex::DUALSLOT + reference_slot; } made_dual = true; } expand->lookup.insert( i->key, index ); } expand->numbercount = klass->numbercount + ( is_number ? 1 : 0 ); if ( key ) { // Add key, if it wasn't a key that expanded. if ( ! made_dual ) { oslotindex index; if ( is_number ) { index.slot = number_slot; index.dual = oslotindex::NUMBER; } else { index.slot = reference_slot; index.dual = oslotindex::REFERENCE; } expand->lookup.insert( key, index ); } expand->is_prototype = klass->prototype; } else { // Add prototype reference at slot 0. assert( ! is_number ); assert( ! klass->is_prototype ); oslotindex index( 0, oslotindex::REFERENCE ); expand->lookup.insert( key, index ); expand->is_prototype = true; } // Remember new class. expandtable.insert( key, expand ); } // Update class. this->klass = expand; if ( size != expand_size ) { // Slots require reallocation. oslotlist* newslots = oslotlist::alloc( expand_size ); for ( size_t i = 0; i < watermark; ++i ) { newslots->store( offset + i, slots->load( i ) ); } for ( size_t i = size - klass->numbercount; i < size; ++i ) { newslots->store( i + expand_size - size, slots->load( i ) ); } if ( key ) { size_t slot = is_number ? number_slot : reference_slot; storedual( index, slot, value ); newslots->set_watermark( watermark + ( is_number ? 0 : 1 ) ); } else { assert( ! is_number ); slots->store( 0, value ); slots->set_watermark( watermark + 1 ); } this->slots = slots; } else if ( key ) { // Store new slot. size_t slot = is_number ? number_slot : reference_slot; storedual( index, slot, value ); if ( ! is_number ) { slots->set_watermark( watermark + 1 ); } } else { // Shuffle slots and add at slot 0. for ( size_t i = watermark; i > 0; --i ) { slots->store( i, slots->load( i - 1 ) ); } assert( ! is_number ); slots->store( 0, value ); slots->set_watermark( watermark + 1 ); } } void oexpand::storedual( oslotindex index, size_t newslot, ovalue value ) { bool is_number = value.is_number(); if ( index.slot != oslotindex::INVALID ) { // Slot existed before the expand, this is now a dual slot. if ( is_number ) { assert( index.dual == oslotindex::REFERENCE ); slots->store( index.slot, ovalue::undefined ); slots->store( newslot, value ); } else { assert( index.dual == oslotindex::NUMBER ); slots->store( index.slot, value ); slots->store( newslot, value ); } } else { // Single slot. if ( is_number ) { slots->store( newslot, value ); } else { slots->store( newslot, value ); } } } #else void oexpand::expandkey( osymbol key, ovalue value ) { oclass* klass = this->klass; otuple< ovalue >* slots = this->slots; // If key is null then we're allocating slot 0 for the prototype. size_t offset = key ? 0 : 1; // Find class describing expanded object. oclass* expand = nullptr; auto lookup = klass->expand.lookup( key ); if ( lookup ) { // Expand class already exists, use it. expand = lookup->value; } else { // Build new class. expand = oclass::alloc(); expand->prototype = klass->prototype; for ( auto i = klass->lookup.iter(); i != nullptr; i = klass->lookup.next( i ) ) { expand->lookup.insert( i->key, offset + i->value ); } if ( key ) { expand->lookup.insert( key, klass->lookup.size() ); expand->is_prototype = klass->is_prototype; } else { assert( ! klass->is_prototype ); expand->lookup.insert( key, 0 ); expand->is_prototype = true; } // Link it in so it gets reused. klass->expand.insert( key, expand ); } // Update class. this->klass = expand; if ( ! slots || slots->size() < expand->lookup.size() ) { // Slots require reallocation. size_t size = ceil_pow2( expand->lookup.size() ); size = std::max( size, (size_t)8 ); otuple< ovalue >* newslots = otuple< ovalue >::alloc( size ); for ( size_t i = 0; i < klass->lookup.size(); ++i ) { newslots->at( i + offset ) = slots->at( i ); } if ( key ) newslots->at( klass->lookup.size() ) = value; else newslots->at( 0 ) = value; this->slots = slots; } else if ( key ) { // Add new value in its position. slots->at( klass->lookup.size() ) = value; } else { // Shuffle slots downwards to make room for slot 0. for ( size_t i = klass->lookup.size(); i > 0; --i ) { slots->at( i ) = slots->at( i - 1 ); } slots->at( 0 ) = value; } } #endif void oexpand::mark_expand( oworklist* work, obase* object, ocolour colour ) { oexpand* expand = (oexpand*)object; omark< oclass* >::mark( expand->klass, work, colour ); #if OEXPANDSLOTS omark< oslotlist* >::mark( expand->slots, work, colour ); #else omark< otuple< ovalue >* >::mark( expand->slots, work, colour ); #endif } ometatype oclass::metatype = { &mark_class, "class" }; oclass* oclass::alloc() { void* p = malloc( sizeof( oclass ) ); return new ( p ) oclass( &metatype ); } oclass::oclass( ometatype* metatype ) : obase( metatype ) #if OEXPANDCLASS , numbercount( 0 ) #endif , is_prototype( false ) { } void oclass::mark_class( oworklist* work, obase* object, ocolour colour ) { oclass* klass = (oclass*)object; omark< oexpand* >::mark( klass->prototype, work, colour ); #if OEXPANDSLOTS omark< okeytable< osymbol, oslotindex > >::mark( klass->lookup, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expandref, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expandnum, work, colour ); #else omark< okeytable< osymbol, size_t > >::mark( klass->lookup, work, colour ); omark< okeytable< osymbol, oclass* > >::mark( klass->expand, work, colour ); #endif } <|endoftext|>
<commit_before>/* Copyright 2015-2020 Igor Petrovic 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 "stm32f4xx_hal.h" #include "board/Internal.h" #include "core/src/general/ADC.h" namespace core { namespace adc { void startConversion() { /* Clear regular group conversion flag and overrun flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ ADC1->SR = ~(ADC_FLAG_EOC | ADC_FLAG_OVR); /* Enable end of conversion interrupt for regular group */ ADC1->CR1 |= (ADC_IT_EOC | ADC_IT_OVR); /* Enable the selected ADC software conversion for regular group */ ADC1->CR2 |= (uint32_t)ADC_CR2_SWSTART; } void setChannel(uint32_t adcChannel) { /* Clear the old SQx bits for the selected rank */ ADC1->SQR3 &= ~ADC_SQR3_RK(ADC_SQR3_SQ1, 1); /* Set the SQx bits for the selected rank */ ADC1->SQR3 |= ADC_SQR3_RK(adcChannel, 1); } } // namespace adc } // namespace core void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { if (hadc->Instance == ADC1) { __HAL_RCC_ADC1_CLK_ENABLE(); } else if (hadc->Instance == ADC2) { __HAL_RCC_ADC2_CLK_ENABLE(); } else if (hadc->Instance == ADC3) { __HAL_RCC_ADC3_CLK_ENABLE(); } else { return; } HAL_NVIC_SetPriority(ADC_IRQn, 0, 0); HAL_NVIC_EnableIRQ(ADC_IRQn); } void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base) { if (htim_base->Instance == TIM2) { __HAL_RCC_TIM2_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM2_IRQn); } else if (htim_base->Instance == TIM3) { __HAL_RCC_TIM3_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM3_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM3_IRQn); } else if (htim_base->Instance == TIM4) { __HAL_RCC_TIM4_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM4_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM4_IRQn); } else if (htim_base->Instance == TIM5) { __HAL_RCC_TIM5_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM5_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM5_IRQn); } else if (htim_base->Instance == TIM6) { __HAL_RCC_TIM6_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM6_DAC_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn); } else if (htim_base->Instance == TIM7) { __HAL_RCC_TIM7_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM7_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM7_IRQn); } else if (htim_base->Instance == TIM12) { __HAL_RCC_TIM12_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_BRK_TIM12_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_BRK_TIM12_IRQn); } else if (htim_base->Instance == TIM13) { __HAL_RCC_TIM13_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_UP_TIM13_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_UP_TIM13_IRQn); } else if (htim_base->Instance == TIM14) { __HAL_RCC_TIM14_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_TRG_COM_TIM14_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_TRG_COM_TIM14_IRQn); } } void HAL_UART_MspInit(UART_HandleTypeDef* huart) { uint8_t channel = 0; if (Board::detail::map::uartChannel(huart->Instance, channel)) { auto uartDescriptor = Board::detail::map::uartDescriptor(channel); uartDescriptor->enableClock(); for (size_t i = 0; i < uartDescriptor->pins().size(); i++) CORE_IO_CONFIG(uartDescriptor->pins().at(i)); HAL_NVIC_SetPriority(uartDescriptor->irqn(), 0, 0); HAL_NVIC_EnableIRQ(uartDescriptor->irqn()); } } void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) { uint8_t channel = 0; if (Board::detail::map::uartChannel(huart->Instance, channel)) { auto uartDescriptor = Board::detail::map::uartDescriptor(channel); uartDescriptor->disableClock(); for (size_t i = 0; i < uartDescriptor->pins().size(); i++) HAL_GPIO_DeInit(uartDescriptor->pins().at(i).port, uartDescriptor->pins().at(i).index); HAL_NVIC_DisableIRQ(uartDescriptor->irqn()); } }<commit_msg>stm32: add missing extern C for uart msp init<commit_after>/* Copyright 2015-2020 Igor Petrovic 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 "stm32f4xx_hal.h" #include "board/Internal.h" #include "core/src/general/ADC.h" namespace core { namespace adc { void startConversion() { /* Clear regular group conversion flag and overrun flag */ /* (To ensure of no unknown state from potential previous ADC operations) */ ADC1->SR = ~(ADC_FLAG_EOC | ADC_FLAG_OVR); /* Enable end of conversion interrupt for regular group */ ADC1->CR1 |= (ADC_IT_EOC | ADC_IT_OVR); /* Enable the selected ADC software conversion for regular group */ ADC1->CR2 |= (uint32_t)ADC_CR2_SWSTART; } void setChannel(uint32_t adcChannel) { /* Clear the old SQx bits for the selected rank */ ADC1->SQR3 &= ~ADC_SQR3_RK(ADC_SQR3_SQ1, 1); /* Set the SQx bits for the selected rank */ ADC1->SQR3 |= ADC_SQR3_RK(adcChannel, 1); } } // namespace adc } // namespace core void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { if (hadc->Instance == ADC1) { __HAL_RCC_ADC1_CLK_ENABLE(); } else if (hadc->Instance == ADC2) { __HAL_RCC_ADC2_CLK_ENABLE(); } else if (hadc->Instance == ADC3) { __HAL_RCC_ADC3_CLK_ENABLE(); } else { return; } HAL_NVIC_SetPriority(ADC_IRQn, 0, 0); HAL_NVIC_EnableIRQ(ADC_IRQn); } void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* htim_base) { if (htim_base->Instance == TIM2) { __HAL_RCC_TIM2_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM2_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM2_IRQn); } else if (htim_base->Instance == TIM3) { __HAL_RCC_TIM3_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM3_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM3_IRQn); } else if (htim_base->Instance == TIM4) { __HAL_RCC_TIM4_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM4_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM4_IRQn); } else if (htim_base->Instance == TIM5) { __HAL_RCC_TIM5_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM5_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM5_IRQn); } else if (htim_base->Instance == TIM6) { __HAL_RCC_TIM6_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM6_DAC_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM6_DAC_IRQn); } else if (htim_base->Instance == TIM7) { __HAL_RCC_TIM7_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM7_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM7_IRQn); } else if (htim_base->Instance == TIM12) { __HAL_RCC_TIM12_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_BRK_TIM12_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_BRK_TIM12_IRQn); } else if (htim_base->Instance == TIM13) { __HAL_RCC_TIM13_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_UP_TIM13_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_UP_TIM13_IRQn); } else if (htim_base->Instance == TIM14) { __HAL_RCC_TIM14_CLK_ENABLE(); HAL_NVIC_SetPriority(TIM8_TRG_COM_TIM14_IRQn, 0, 0); HAL_NVIC_EnableIRQ(TIM8_TRG_COM_TIM14_IRQn); } } extern "C" void HAL_UART_MspInit(UART_HandleTypeDef* huart) { uint8_t channel = 0; if (Board::detail::map::uartChannel(huart->Instance, channel)) { auto uartDescriptor = Board::detail::map::uartDescriptor(channel); uartDescriptor->enableClock(); for (size_t i = 0; i < uartDescriptor->pins().size(); i++) CORE_IO_CONFIG(uartDescriptor->pins().at(i)); HAL_NVIC_SetPriority(uartDescriptor->irqn(), 0, 0); HAL_NVIC_EnableIRQ(uartDescriptor->irqn()); } } extern "C" void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) { uint8_t channel = 0; if (Board::detail::map::uartChannel(huart->Instance, channel)) { auto uartDescriptor = Board::detail::map::uartDescriptor(channel); uartDescriptor->disableClock(); for (size_t i = 0; i < uartDescriptor->pins().size(); i++) HAL_GPIO_DeInit(uartDescriptor->pins().at(i).port, uartDescriptor->pins().at(i).index); HAL_NVIC_DisableIRQ(uartDescriptor->irqn()); } }<|endoftext|>
<commit_before>#include <cstdint> #include <kernel/definitions.hpp> #include <kernel/cpu/common.hpp> #include <kernel/vfs/vfs.hpp> #include <kernel/vfs/file.hpp> #include <kernel/vfs/ramfs.hpp> #include <kernel/vfs/cache.hpp> #include <yatf.h> TEST(cache, new_cache_is_empty) { vfs::cache c; REQUIRE(c.empty()); REQUIRE_FALSE(c.find("/", nullptr)); } TEST(cache, can_add_root_element) { vfs::cache c; auto root_node = utils::make_shared<vfs::vnode>(1u, 0u, 0u, nullptr, vfs::vnode::type::dir); c.add("/", root_node, nullptr); auto cached_node = c.find("/")->node; REQUIRE(cached_node); REQUIRE(cached_node == root_node); REQUIRE_EQ(cached_node->id, 1u); REQUIRE_EQ(cached_node->mount_point, nullptr); REQUIRE_EQ(cached_node->data, nullptr); } namespace vfs { extern null_block_device null_bd_; } TEST(vfs, can_create_root) { ramfs::ramfs ramfs; vfs::vfs fs(ramfs, vfs::null_bd_); auto node = fs.lookup("/"); REQUIRE(node); REQUIRE_EQ(node->id, 1u); REQUIRE(node->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node->size, 0u); } TEST(vfs, can_create_files) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node = vfs.create("/some_file", vfs::vnode::type::file); REQUIRE(node); REQUIRE_EQ(node->id, 2u); REQUIRE(node->node_type == vfs::vnode::type::file); REQUIRE_EQ(node->size, 0u); { auto node2 = vfs.lookup("/some_file"); REQUIRE_EQ(node2->id, 2u); REQUIRE_EQ(node2->size, 0u); REQUIRE(node2->node_type == vfs::vnode::type::file); } node = vfs.create("/some_file2", vfs::vnode::type::file); REQUIRE(node); REQUIRE_EQ(node->id, 3u); REQUIRE_EQ(node->size, 0u); REQUIRE(node->node_type == vfs::vnode::type::file); { auto node2 = vfs.lookup("/some_file2"); REQUIRE_EQ(node2->id, 3u); REQUIRE_EQ(node2->size, 0u); REQUIRE(node2->node_type == vfs::vnode::type::file); } } TEST(vfs, can_create_dirs) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node = vfs.create("/some_dir", vfs::vnode::type::dir); REQUIRE(node); REQUIRE_EQ(node->id, 2u); REQUIRE(node->node_type == vfs::vnode::type::dir); { auto node2 = vfs.lookup("/some_dir"); REQUIRE_EQ(node2->id, 2u); REQUIRE(node2->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node2->size, 0u); } node = vfs.create("/some_dir2", vfs::vnode::type::dir); REQUIRE(node); REQUIRE_EQ(node->id, 3u); REQUIRE(node->node_type == vfs::vnode::type::dir); { auto node2 = vfs.lookup("/some_dir2"); REQUIRE_EQ(node2->id, 3u); REQUIRE(node2->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node2->size, 0u); } } TEST(vfs, cannot_lookup_for_nonexistent_path) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); REQUIRE_FALSE(vfs.lookup("/a")); REQUIRE_FALSE(vfs.lookup("/dir1")); REQUIRE_FALSE(vfs.lookup("/dir2")); REQUIRE_FALSE(vfs.lookup("/file")); REQUIRE_FALSE(vfs.lookup("/file/dir")); REQUIRE_FALSE(vfs.lookup("/file/dir/a/b")); } TEST(vfs, can_create_tree) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node2 = vfs.create("/some_dir", vfs::vnode::type::dir); REQUIRE(node2); auto node3 = vfs.create("/file", vfs::vnode::type::file); REQUIRE(node3); auto node4 = vfs.create("/some_dir/file1", vfs::vnode::type::file); REQUIRE(node4); auto node5 = vfs.create("/some_dir/file2", vfs::vnode::type::file); REQUIRE(node5); auto node6 = vfs.create("/some_dir/dir1", vfs::vnode::type::dir); REQUIRE(node6); auto node7 = vfs.create("/some_dir/dir1/file", vfs::vnode::type::file); REQUIRE(node7); { auto node = vfs.lookup("/file"); REQUIRE(node); REQUIRE(node == node3); REQUIRE_EQ(node->id, 3u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/file1"); REQUIRE(node); REQUIRE(node == node4); REQUIRE_EQ(node->id, 4u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/dir1/file"); REQUIRE(node); REQUIRE(node == node7); REQUIRE_EQ(node->id, 7u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/dir1"); REQUIRE(node); REQUIRE(node == node6); REQUIRE_EQ(node->id, 6u); REQUIRE(node->node_type == vfs::vnode::type::dir); } { auto node = vfs.lookup("/some_dir/file2"); REQUIRE(node); REQUIRE(node == node5); REQUIRE_EQ(node->id, 5u); REQUIRE(node->node_type == vfs::vnode::type::file); } } TEST(vfs, can_cache_nodes) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); { auto orig_node = vfs.create("/some_file", vfs::vnode::type::file); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_file"); } { auto orig_node = vfs.create("/some_dir", vfs::vnode::type::dir); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_dir"); REQUIRE(cache_entry->node->node_type == vfs::vnode::type::dir); } { auto orig_node = vfs.create("/some_dir/some_other_file", vfs::vnode::type::file); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_other_file"); } { auto orig_node = vfs.create("/some_dir/other_file", vfs::vnode::type::file); auto node = vfs.lookup("/some_dir"); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(node->node_type == vfs::vnode::type::dir); } { auto node = vfs.lookup("/some_dir"); REQUIRE(node); } } TEST(vfs, open_can_create_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::write); REQUIRE(file); REQUIRE(file->operator bool()); REQUIRE_EQ(file->size(), 0u); auto node = vfs.lookup("/file"); REQUIRE(node); REQUIRE_EQ(node->size, 0u); REQUIRE_EQ(node->id, 2u); } TEST(vfs, cannot_open_directory) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); vfs.create("/some_dir", vfs::vnode::type::dir); auto file = vfs.open("/some_dir", vfs::file::mode::read); REQUIRE_FALSE(file); file = vfs.open("/some_dir", vfs::file::mode::write); REQUIRE_FALSE(file); file = vfs.open("/some_dir", vfs::file::mode::read_write); REQUIRE_FALSE(file); } TEST(vfs, can_read_write_to_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::read_write); REQUIRE(file); REQUIRE_EQ(file->position(), 0u); file->write("some text", 10); REQUIRE_EQ(file->size(), 10u); REQUIRE_EQ(file->position(), 10u); file->seek(0u); REQUIRE_EQ(file->position(), 0u); char buffer[32]; file->read(buffer, 10); REQUIRE_EQ(file->position(), 10u); REQUIRE_EQ((const char *)buffer, "some text"); file->seek(5); REQUIRE_EQ(file->position(), 5u); file->read(buffer, 5); REQUIRE_EQ(file->position(), 10u); REQUIRE_EQ((const char *)buffer, "text"); file->seek(5); file->write("testing", 8); REQUIRE_EQ(file->size(), 13u); file->seek(0); REQUIRE_EQ(file->position(), 0u); file->read(buffer, 13); REQUIRE_EQ((const char *)buffer, "some testing"); REQUIRE_EQ(file->position(), 13u); file->seek(12u); file->write(" for kernel", 12u); file->seek(0); file->read(buffer, 24u); REQUIRE_EQ((const char *)buffer, "some testing for kernel"); REQUIRE_EQ(file->size(), 24u); } TEST(vfs, cannot_write_to_read_open_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::read); REQUIRE(file); REQUIRE(file->mode_ == vfs::file::mode::read); REQUIRE_EQ(file->position(), 0u); auto res = file->write("some text", 10); REQUIRE(res < 0); REQUIRE_EQ(file->position(), 0u); } TEST(vfs, cannot_read_from_write_open_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::write); REQUIRE(file); REQUIRE(file->mode_ == vfs::file::mode::write); REQUIRE_EQ(file->position(), 0u); auto res = file->write("some text", 10); REQUIRE(res == 10); REQUIRE_EQ(file->position(), 10u); char buffer[32]; utils::fill(buffer, 32, 0); res = file->read(buffer, 10); REQUIRE(res < 0); REQUIRE_EQ(buffer[0], 0); } TEST(vfs, cannot_create_file_under_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file_node = vfs.create("/some_file", vfs::vnode::type::file); { auto bad_node = vfs.create("/some_file/file", vfs::vnode::type::file); REQUIRE_FALSE(bad_node); } { auto bad_node = vfs.create("/some_file/dir", vfs::vnode::type::dir); REQUIRE_FALSE(bad_node); } { auto bad_node = vfs.create("/some_file/dir/dir", vfs::vnode::type::dir); REQUIRE_FALSE(bad_node); } } TEST(vfs, cannot_create_files_with_the_same_name) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file_node = vfs.create("/some_file", vfs::vnode::type::file); for (auto i = 0; i < 32; ++i) { auto bad_node = vfs.create("/some_file", vfs::vnode::type::file); REQUIRE_FALSE(bad_node); } } <commit_msg>Add dummy test for null_bd<commit_after>#include <cstdint> #include <kernel/definitions.hpp> #include <kernel/cpu/common.hpp> #include <kernel/vfs/vfs.hpp> #include <kernel/vfs/file.hpp> #include <kernel/vfs/ramfs.hpp> #include <kernel/vfs/cache.hpp> #include <yatf.h> TEST(cache, new_cache_is_empty) { vfs::cache c; REQUIRE(c.empty()); REQUIRE_FALSE(c.find("/", nullptr)); } TEST(cache, can_add_root_element) { vfs::cache c; auto root_node = utils::make_shared<vfs::vnode>(1u, 0u, 0u, nullptr, vfs::vnode::type::dir); c.add("/", root_node, nullptr); auto cached_node = c.find("/")->node; REQUIRE(cached_node); REQUIRE(cached_node == root_node); REQUIRE_EQ(cached_node->id, 1u); REQUIRE_EQ(cached_node->mount_point, nullptr); REQUIRE_EQ(cached_node->data, nullptr); } namespace vfs { extern null_block_device null_bd_; } TEST(vfs, null_bd_works) { REQUIRE(vfs::null_bd_.name()); // FIXME: check something vfs::null_bd_.handle_request({}); } TEST(vfs, can_create_root) { ramfs::ramfs ramfs; vfs::vfs fs(ramfs, vfs::null_bd_); auto node = fs.lookup("/"); REQUIRE(node); REQUIRE_EQ(node->id, 1u); REQUIRE(node->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node->size, 0u); } TEST(vfs, can_create_files) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node = vfs.create("/some_file", vfs::vnode::type::file); REQUIRE(node); REQUIRE_EQ(node->id, 2u); REQUIRE(node->node_type == vfs::vnode::type::file); REQUIRE_EQ(node->size, 0u); { auto node2 = vfs.lookup("/some_file"); REQUIRE_EQ(node2->id, 2u); REQUIRE_EQ(node2->size, 0u); REQUIRE(node2->node_type == vfs::vnode::type::file); } node = vfs.create("/some_file2", vfs::vnode::type::file); REQUIRE(node); REQUIRE_EQ(node->id, 3u); REQUIRE_EQ(node->size, 0u); REQUIRE(node->node_type == vfs::vnode::type::file); { auto node2 = vfs.lookup("/some_file2"); REQUIRE_EQ(node2->id, 3u); REQUIRE_EQ(node2->size, 0u); REQUIRE(node2->node_type == vfs::vnode::type::file); } } TEST(vfs, can_create_dirs) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node = vfs.create("/some_dir", vfs::vnode::type::dir); REQUIRE(node); REQUIRE_EQ(node->id, 2u); REQUIRE(node->node_type == vfs::vnode::type::dir); { auto node2 = vfs.lookup("/some_dir"); REQUIRE_EQ(node2->id, 2u); REQUIRE(node2->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node2->size, 0u); } node = vfs.create("/some_dir2", vfs::vnode::type::dir); REQUIRE(node); REQUIRE_EQ(node->id, 3u); REQUIRE(node->node_type == vfs::vnode::type::dir); { auto node2 = vfs.lookup("/some_dir2"); REQUIRE_EQ(node2->id, 3u); REQUIRE(node2->node_type == vfs::vnode::type::dir); REQUIRE_EQ(node2->size, 0u); } } TEST(vfs, cannot_lookup_for_nonexistent_path) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); REQUIRE_FALSE(vfs.lookup("/a")); REQUIRE_FALSE(vfs.lookup("/dir1")); REQUIRE_FALSE(vfs.lookup("/dir2")); REQUIRE_FALSE(vfs.lookup("/file")); REQUIRE_FALSE(vfs.lookup("/file/dir")); REQUIRE_FALSE(vfs.lookup("/file/dir/a/b")); } TEST(vfs, can_create_tree) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto node2 = vfs.create("/some_dir", vfs::vnode::type::dir); REQUIRE(node2); auto node3 = vfs.create("/file", vfs::vnode::type::file); REQUIRE(node3); auto node4 = vfs.create("/some_dir/file1", vfs::vnode::type::file); REQUIRE(node4); auto node5 = vfs.create("/some_dir/file2", vfs::vnode::type::file); REQUIRE(node5); auto node6 = vfs.create("/some_dir/dir1", vfs::vnode::type::dir); REQUIRE(node6); auto node7 = vfs.create("/some_dir/dir1/file", vfs::vnode::type::file); REQUIRE(node7); { auto node = vfs.lookup("/file"); REQUIRE(node); REQUIRE(node == node3); REQUIRE_EQ(node->id, 3u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/file1"); REQUIRE(node); REQUIRE(node == node4); REQUIRE_EQ(node->id, 4u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/dir1/file"); REQUIRE(node); REQUIRE(node == node7); REQUIRE_EQ(node->id, 7u); REQUIRE(node->node_type == vfs::vnode::type::file); } { auto node = vfs.lookup("/some_dir/dir1"); REQUIRE(node); REQUIRE(node == node6); REQUIRE_EQ(node->id, 6u); REQUIRE(node->node_type == vfs::vnode::type::dir); } { auto node = vfs.lookup("/some_dir/file2"); REQUIRE(node); REQUIRE(node == node5); REQUIRE_EQ(node->id, 5u); REQUIRE(node->node_type == vfs::vnode::type::file); } } TEST(vfs, can_cache_nodes) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); { auto orig_node = vfs.create("/some_file", vfs::vnode::type::file); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_file"); } { auto orig_node = vfs.create("/some_dir", vfs::vnode::type::dir); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_dir"); REQUIRE(cache_entry->node->node_type == vfs::vnode::type::dir); } { auto orig_node = vfs.create("/some_dir/some_other_file", vfs::vnode::type::file); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(cache_entry->node == orig_node); REQUIRE(cache_entry->name == "some_other_file"); } { auto orig_node = vfs.create("/some_dir/other_file", vfs::vnode::type::file); auto node = vfs.lookup("/some_dir"); auto cache_entry = vfs.get_cache().find(*orig_node); REQUIRE(cache_entry != nullptr); REQUIRE(node->node_type == vfs::vnode::type::dir); } { auto node = vfs.lookup("/some_dir"); REQUIRE(node); } } TEST(vfs, open_can_create_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::write); REQUIRE(file); REQUIRE(file->operator bool()); REQUIRE_EQ(file->size(), 0u); auto node = vfs.lookup("/file"); REQUIRE(node); REQUIRE_EQ(node->size, 0u); REQUIRE_EQ(node->id, 2u); } TEST(vfs, cannot_open_directory) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); vfs.create("/some_dir", vfs::vnode::type::dir); auto file = vfs.open("/some_dir", vfs::file::mode::read); REQUIRE_FALSE(file); file = vfs.open("/some_dir", vfs::file::mode::write); REQUIRE_FALSE(file); file = vfs.open("/some_dir", vfs::file::mode::read_write); REQUIRE_FALSE(file); } TEST(vfs, can_read_write_to_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::read_write); REQUIRE(file); REQUIRE_EQ(file->position(), 0u); file->write("some text", 10); REQUIRE_EQ(file->size(), 10u); REQUIRE_EQ(file->position(), 10u); file->seek(0u); REQUIRE_EQ(file->position(), 0u); char buffer[32]; file->read(buffer, 10); REQUIRE_EQ(file->position(), 10u); REQUIRE_EQ((const char *)buffer, "some text"); file->seek(5); REQUIRE_EQ(file->position(), 5u); file->read(buffer, 5); REQUIRE_EQ(file->position(), 10u); REQUIRE_EQ((const char *)buffer, "text"); file->seek(5); file->write("testing", 8); REQUIRE_EQ(file->size(), 13u); file->seek(0); REQUIRE_EQ(file->position(), 0u); file->read(buffer, 13); REQUIRE_EQ((const char *)buffer, "some testing"); REQUIRE_EQ(file->position(), 13u); file->seek(12u); file->write(" for kernel", 12u); file->seek(0); file->read(buffer, 24u); REQUIRE_EQ((const char *)buffer, "some testing for kernel"); REQUIRE_EQ(file->size(), 24u); } TEST(vfs, cannot_write_to_read_open_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::read); REQUIRE(file); REQUIRE(file->mode_ == vfs::file::mode::read); REQUIRE_EQ(file->position(), 0u); auto res = file->write("some text", 10); REQUIRE(res < 0); REQUIRE_EQ(file->position(), 0u); } TEST(vfs, cannot_read_from_write_open_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file = vfs.open("/file", vfs::file::mode::write); REQUIRE(file); REQUIRE(file->mode_ == vfs::file::mode::write); REQUIRE_EQ(file->position(), 0u); auto res = file->write("some text", 10); REQUIRE(res == 10); REQUIRE_EQ(file->position(), 10u); char buffer[32]; utils::fill(buffer, 32, 0); res = file->read(buffer, 10); REQUIRE(res < 0); REQUIRE_EQ(buffer[0], 0); } TEST(vfs, cannot_create_file_under_file) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file_node = vfs.create("/some_file", vfs::vnode::type::file); { auto bad_node = vfs.create("/some_file/file", vfs::vnode::type::file); REQUIRE_FALSE(bad_node); } { auto bad_node = vfs.create("/some_file/dir", vfs::vnode::type::dir); REQUIRE_FALSE(bad_node); } { auto bad_node = vfs.create("/some_file/dir/dir", vfs::vnode::type::dir); REQUIRE_FALSE(bad_node); } } TEST(vfs, cannot_create_files_with_the_same_name) { ramfs::ramfs ramfs; vfs::vfs vfs(ramfs, vfs::null_bd_); auto file_node = vfs.create("/some_file", vfs::vnode::type::file); for (auto i = 0; i < 32; ++i) { auto bad_node = vfs.create("/some_file", vfs::vnode::type::file); REQUIRE_FALSE(bad_node); } } <|endoftext|>
<commit_before>#ifndef __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ #define __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ #include "buffer_cache/types.hpp" #include "utils.hpp" #include <boost/crc.hpp> #include "containers/two_level_array.hpp" #include "buffer_cache/buf_patch.hpp" #include "serializer/serializer.hpp" // TODO: Have the semantic checking cache make sure that the // repli_timestamps are correct. /* The semantic-checking cache (scc_cache_t) is a wrapper around another cache that will make sure that the inner cache obeys the proper semantics. */ template<class inner_cache_t> class scc_buf_t; template<class inner_cache_t> class scc_transaction_t; template<class inner_cache_t> class scc_cache_t; typedef uint32_t crc_t; /* Buf */ template<class inner_cache_t> class scc_buf_t { public: block_id_t get_block_id(); bool is_dirty(); const void *get_data_read() const; // Use this only for writes which affect a large part of the block, as it bypasses the diff system void *get_data_major_write(); // Convenience function to set some address in the buffer acquired through get_data_read. (similar to memcpy) void set_data(void* dest, const void* src, const size_t n); // Convenience function to move data within the buffer acquired through get_data_read. (similar to memmove) void move_data(void* dest, const void* src, const size_t n); void apply_patch(buf_patch_t *patch); // This might delete the supplied patch, do not use patch after its application patch_counter_t get_next_patch_counter(); void mark_deleted(bool write_null = true); void touch_recency(repli_timestamp timestamp); void release(); private: friend class scc_transaction_t<inner_cache_t>; bool snapshotted; bool should_load; bool has_been_changed; typename inner_cache_t::buf_t *inner_buf; explicit scc_buf_t(scc_cache_t<inner_cache_t> *, bool snapshotted, bool should_load); scc_cache_t<inner_cache_t> *cache; private: crc_t compute_crc() { boost::crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true> crc_computer; crc_computer.process_bytes((void *) inner_buf->get_data_read(), cache->get_block_size().value()); return crc_computer.checksum(); } }; /* Transaction */ template<class inner_cache_t> class scc_transaction_t : public home_thread_mixin_t { typedef scc_buf_t<inner_cache_t> buf_t; public: scc_transaction_t(scc_cache_t<inner_cache_t> *cache, access_t access, int expected_change_count, repli_timestamp recency_timestamp); scc_transaction_t(scc_cache_t<inner_cache_t> *cache, access_t access); ~scc_transaction_t(); // TODO: Implement semantic checking for snapshots! void snapshot() { snapshotted = true; inner_transaction.snapshot(); } void set_account(boost::shared_ptr<typename inner_cache_t::cache_account_t> cache_account); buf_t *acquire(block_id_t block_id, access_t mode, boost::function<void()> call_when_in_line = 0, bool should_load = true); buf_t *allocate(); void get_subtree_recencies(block_id_t *block_ids, size_t num_block_ids, repli_timestamp *recencies_out, get_subtree_recencies_callback_t *cb); scc_cache_t<inner_cache_t> *cache; order_token_t order_token; void set_token(order_token_t token) { order_token = token; } private: bool snapshotted; // Disables CRC checks friend class scc_cache_t<inner_cache_t>; access_t access; typename inner_cache_t::transaction_t inner_transaction; }; /* Cache */ template<class inner_cache_t> class scc_cache_t : public home_thread_mixin_t, public serializer_t::read_ahead_callback_t { public: typedef scc_buf_t<inner_cache_t> buf_t; typedef scc_transaction_t<inner_cache_t> transaction_t; typedef typename inner_cache_t::cache_account_t cache_account_t; static void create( serializer_t *serializer, mirrored_cache_static_config_t *static_config); scc_cache_t( serializer_t *serializer, mirrored_cache_config_t *dynamic_config); block_size_t get_block_size(); boost::shared_ptr<cache_account_t> create_account(int priority); bool offer_read_ahead_buf(block_id_t block_id, void *buf, repli_timestamp recency_timestamp); bool contains_block(block_id_t block_id); coro_fifo_t& co_begin_coro_fifo() { return inner_cache.co_begin_coro_fifo(); } private: inner_cache_t inner_cache; private: friend class scc_transaction_t<inner_cache_t>; friend class scc_buf_t<inner_cache_t>; /* CRC checking stuff */ two_level_array_t<crc_t, MAX_BLOCK_ID> crc_map; /* order checking stuff */ two_level_array_t<plain_sink_t, MAX_BLOCK_ID> sink_map; }; #include "buffer_cache/semantic_checking.tcc" #endif /* __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ */ <commit_msg>Added get_cache to scc_transaction_t, to match the mc_transaction_t interface.<commit_after>#ifndef __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ #define __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ #include "buffer_cache/types.hpp" #include "utils.hpp" #include <boost/crc.hpp> #include "containers/two_level_array.hpp" #include "buffer_cache/buf_patch.hpp" #include "serializer/serializer.hpp" // TODO: Have the semantic checking cache make sure that the // repli_timestamps are correct. /* The semantic-checking cache (scc_cache_t) is a wrapper around another cache that will make sure that the inner cache obeys the proper semantics. */ template<class inner_cache_t> class scc_buf_t; template<class inner_cache_t> class scc_transaction_t; template<class inner_cache_t> class scc_cache_t; typedef uint32_t crc_t; /* Buf */ template<class inner_cache_t> class scc_buf_t { public: block_id_t get_block_id(); bool is_dirty(); const void *get_data_read() const; // Use this only for writes which affect a large part of the block, as it bypasses the diff system void *get_data_major_write(); // Convenience function to set some address in the buffer acquired through get_data_read. (similar to memcpy) void set_data(void* dest, const void* src, const size_t n); // Convenience function to move data within the buffer acquired through get_data_read. (similar to memmove) void move_data(void* dest, const void* src, const size_t n); void apply_patch(buf_patch_t *patch); // This might delete the supplied patch, do not use patch after its application patch_counter_t get_next_patch_counter(); void mark_deleted(bool write_null = true); void touch_recency(repli_timestamp timestamp); void release(); private: friend class scc_transaction_t<inner_cache_t>; bool snapshotted; bool should_load; bool has_been_changed; typename inner_cache_t::buf_t *inner_buf; explicit scc_buf_t(scc_cache_t<inner_cache_t> *, bool snapshotted, bool should_load); scc_cache_t<inner_cache_t> *cache; private: crc_t compute_crc() { boost::crc_optimal<32, 0x04C11DB7, 0xFFFFFFFF, 0xFFFFFFFF, true, true> crc_computer; crc_computer.process_bytes((void *) inner_buf->get_data_read(), cache->get_block_size().value()); return crc_computer.checksum(); } }; /* Transaction */ template<class inner_cache_t> class scc_transaction_t : public home_thread_mixin_t { typedef scc_buf_t<inner_cache_t> buf_t; public: scc_transaction_t(scc_cache_t<inner_cache_t> *cache, access_t access, int expected_change_count, repli_timestamp recency_timestamp); scc_transaction_t(scc_cache_t<inner_cache_t> *cache, access_t access); ~scc_transaction_t(); // TODO: Implement semantic checking for snapshots! void snapshot() { snapshotted = true; inner_transaction.snapshot(); } void set_account(boost::shared_ptr<typename inner_cache_t::cache_account_t> cache_account); buf_t *acquire(block_id_t block_id, access_t mode, boost::function<void()> call_when_in_line = 0, bool should_load = true); buf_t *allocate(); void get_subtree_recencies(block_id_t *block_ids, size_t num_block_ids, repli_timestamp *recencies_out, get_subtree_recencies_callback_t *cb); scc_cache_t<inner_cache_t> *get_cache() const { return cache; } scc_cache_t<inner_cache_t> *cache; order_token_t order_token; void set_token(order_token_t token) { order_token = token; } private: bool snapshotted; // Disables CRC checks friend class scc_cache_t<inner_cache_t>; access_t access; typename inner_cache_t::transaction_t inner_transaction; }; /* Cache */ template<class inner_cache_t> class scc_cache_t : public home_thread_mixin_t, public serializer_t::read_ahead_callback_t { public: typedef scc_buf_t<inner_cache_t> buf_t; typedef scc_transaction_t<inner_cache_t> transaction_t; typedef typename inner_cache_t::cache_account_t cache_account_t; static void create( serializer_t *serializer, mirrored_cache_static_config_t *static_config); scc_cache_t( serializer_t *serializer, mirrored_cache_config_t *dynamic_config); block_size_t get_block_size(); boost::shared_ptr<cache_account_t> create_account(int priority); bool offer_read_ahead_buf(block_id_t block_id, void *buf, repli_timestamp recency_timestamp); bool contains_block(block_id_t block_id); coro_fifo_t& co_begin_coro_fifo() { return inner_cache.co_begin_coro_fifo(); } private: inner_cache_t inner_cache; private: friend class scc_transaction_t<inner_cache_t>; friend class scc_buf_t<inner_cache_t>; /* CRC checking stuff */ two_level_array_t<crc_t, MAX_BLOCK_ID> crc_map; /* order checking stuff */ two_level_array_t<plain_sink_t, MAX_BLOCK_ID> sink_map; }; #include "buffer_cache/semantic_checking.tcc" #endif /* __BUFFER_CACHE_SEMANTIC_CHECKING_HPP__ */ <|endoftext|>
<commit_before>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <getopt.h> #include <errno.h> #include <limits.h> #include <math.h> #include "geopm_agent.h" #include "geopm_version.h" #include "geopm_error.h" #include "config.h" enum geopmagent_const { GEOPMAGENT_STRING_LENGTH = 512, GEOPMAGENT_DOUBLE_LENGTH = 100, }; int main(int argc, char **argv) { int opt; int err = 0; int output_num; double policy_vals[GEOPMAGENT_DOUBLE_LENGTH] = {0}; char error_str[GEOPMAGENT_STRING_LENGTH] = {0}; char agent_str[GEOPMAGENT_STRING_LENGTH] = {0}; char policy_vals_str[GEOPMAGENT_STRING_LENGTH] = {0}; char output_str[NAME_MAX * GEOPMAGENT_DOUBLE_LENGTH]; char *agent_ptr = NULL; char *policy_vals_ptr = NULL; char *arg_ptr = NULL; const char *usage = "\nUsage: geopmagent\n" " geopmagent [-a AGENT] [-p POLICY0,POLICY1,...]\n" " geopmagent [--help] [--version]\n" "\n" "Mandatory arguments to long options are mandatory for short options too.\n" "\n" " -a, --agent=AGENT specify the name of the agent\n" " -p, --policy=POLICY0,... values to be set for each policy in a\n" " comma-seperated list\n" " -h, --help print brief summary of the command line\n" " usage information, then exit\n" " -v, --version print version of GEOPM to standard output,\n" " then exit\n" "\n" "Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation. All rights reserved.\n" "\n"; static struct option long_options[] = { {"agent", required_argument, NULL, 'a'}, {"policy", required_argument, NULL, 'p'}, {"help", no_argument, NULL, 'h'}, {"version", no_argument, NULL, 'v'}, {NULL, 0, NULL, 0} }; while (!err && (opt = getopt_long(argc, argv, "a:p:hv", long_options, NULL)) != -1) { arg_ptr = NULL; switch (opt) { case 'a': arg_ptr = agent_str; break; case 'p': arg_ptr = policy_vals_str; break; case 'h': printf("%s", usage); return 0; case 'v': printf("%s\n", geopm_version()); printf("\n\nCopyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation. All rights reserved.\n\n"); return 0; case '?': // opt is ? when an option required an arg but it was missing fprintf(stderr, usage, argv[0]); err = EINVAL; break; default: fprintf(stderr, "Error: getopt returned character code \"0%o\"\n", opt); err = EINVAL; break; } if (!err) { strncpy(arg_ptr, optarg, GEOPMAGENT_STRING_LENGTH); if (arg_ptr[GEOPMAGENT_STRING_LENGTH - 1] != '\0') { fprintf(stderr, "Error: config_file name too long\n"); err = EINVAL; } } } if (!err && optind != argc) { fprintf(stderr, "Error: The following positional argument(s) are in error:\n"); while (optind < argc) { fprintf(stderr, "%s\n", argv[optind++]); } err = EINVAL; } if (!err) { if (strnlen(agent_str, GEOPMAGENT_STRING_LENGTH)) { agent_ptr = agent_str; } if (strnlen(policy_vals_str, GEOPMAGENT_STRING_LENGTH)) { policy_vals_ptr = policy_vals_str; } } if (!err && argc == 1) { err = geopm_agent_num_avail(&output_num); if (!err) { for(int i = 0; !err && i < output_num; ++i) { err = geopm_agent_name(i, sizeof(output_str), output_str); if (!err) { printf("%s\n", output_str); } } } } else if (!err && agent_ptr != NULL && policy_vals_ptr == NULL) { err = geopm_agent_supported(agent_ptr); // Policies if (!err) { err = geopm_agent_num_policy(agent_ptr, &output_num); } if (!err) { printf("Policy: "); for (int i = 0; !err && i < output_num; ++i) { err = geopm_agent_policy_name(agent_ptr, i, sizeof(output_str), output_str); if (!err) { if (i > 0) { printf(","); } printf("%s", output_str); } } if (!err && output_num == 0) { printf("(none)\n"); } else { printf("\n"); } } // Samples if (!err) { err = geopm_agent_num_sample(agent_ptr, &output_num); } if (!err) { printf("Sample: "); for (int i = 0; !err && i < output_num; ++i) { err = geopm_agent_sample_name(agent_ptr, i, sizeof(output_str), output_str); if (!err) { if (i > 0) { printf(","); } printf("%s", output_str); } } if (!err && output_num == 0) { printf("(none)\n"); } else { printf("\n"); } } } else if (!err) { if (agent_ptr == NULL) { fprintf(stderr, "Error: Agent (-a) must be specified to create a policy.\n"); err = EINVAL; } int num_policy = 0; if (!err) { err = geopm_agent_num_policy(agent_ptr, &num_policy); } int policy_count = 0; if (!err) { if (num_policy) { char *tok = strtok(policy_vals_ptr, ","); char *endptr = NULL; while (!err && tok != NULL) { policy_vals[policy_count++] = strtod(tok, &endptr); if (tok == endptr) { fprintf(stderr, "Error: %s is not a valid floating-point number; " "use \"NAN\" to indicate default.\n", tok); err = EINVAL; } if (policy_count > GEOPMAGENT_DOUBLE_LENGTH) { err = E2BIG; } tok = strtok(NULL, ","); } if (!err && policy_count > num_policy) { fprintf(stderr, "Error: Number of policies read from command line is greater than expected for agent.\n"); err = EINVAL; } } else if (strncmp(policy_vals_ptr, "none", 4) != 0 && strncmp(policy_vals_ptr, "None", 4) != 0) { fprintf(stderr, "Error: Must specify \"None\" for the parameter option if agent takes no parameters.\n"); err = EINVAL; } } if (!err) { err = geopm_agent_policy_json_partial(agent_ptr, policy_count, policy_vals, sizeof(output_str), output_str); printf("%s\n", output_str); } } if (err) { geopm_error_message(err, error_str, GEOPMAGENT_STRING_LENGTH); fprintf(stderr, "Error: %s\n", error_str); } return err; } <commit_msg>Update geopmagent to use OptionParser for CLI<commit_after>/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <limits.h> #include <math.h> #include <iostream> #include "geopm_agent.h" #include "geopm_error.h" #include "OptionParser.hpp" #include "config.h" enum geopmagent_const { GEOPMAGENT_STRING_LENGTH = 512, GEOPMAGENT_DOUBLE_LENGTH = 100, }; int main(int argc, char **argv) { geopm::OptionParser parser{"geopmagent", std::cout, std::cerr, ""}; parser.add_option("agent", 'a', "agent", "", "specify the name of the agent"); parser.add_option("policy", 'p', "policy", "", "values to be set for each policy in a comma-separated list"); parser.add_example_usage(""); parser.add_example_usage("[-a AGENT] [-p POLICY0,POLICY1,...]"); bool early_exit = parser.parse(argc, argv); if (early_exit) { return 0; } int err = 0; auto pos_args = parser.get_positional_args(); if (pos_args.size() > 0) { std::cerr << "Error: The following positional argument(s) are in error:" << std::endl; for (const std::string &arg : pos_args) { std::cerr << arg << std::endl; } err = EINVAL; } int output_num; double policy_vals[GEOPMAGENT_DOUBLE_LENGTH] = {0}; char error_str[GEOPMAGENT_STRING_LENGTH] = {0}; char policy_vals_str[GEOPMAGENT_STRING_LENGTH] = {0}; char output_str[NAME_MAX * GEOPMAGENT_DOUBLE_LENGTH]; const char *agent_ptr = NULL; char *policy_vals_ptr = NULL; try { std::string agent = parser.get_value("agent"); if (agent != "") { agent_ptr = agent.c_str(); } std::string policy = parser.get_value("policy"); if (parser.get_value("policy") != "") { strncpy(policy_vals_str, policy.c_str(), GEOPMAGENT_STRING_LENGTH); policy_vals_ptr = policy_vals_str; } } catch (...) { err = geopm::exception_handler(std::current_exception(), false); } if (!err && argc == 1) { err = geopm_agent_num_avail(&output_num); if (!err) { for(int i = 0; !err && i < output_num; ++i) { err = geopm_agent_name(i, sizeof(output_str), output_str); if (!err) { printf("%s\n", output_str); } } } } else if (!err && agent_ptr != NULL && policy_vals_ptr == NULL) { err = geopm_agent_supported(agent_ptr); // Policies if (!err) { err = geopm_agent_num_policy(agent_ptr, &output_num); } if (!err) { printf("Policy: "); for (int i = 0; !err && i < output_num; ++i) { err = geopm_agent_policy_name(agent_ptr, i, sizeof(output_str), output_str); if (!err) { if (i > 0) { printf(","); } printf("%s", output_str); } } if (!err && output_num == 0) { printf("(none)\n"); } else { printf("\n"); } } // Samples if (!err) { err = geopm_agent_num_sample(agent_ptr, &output_num); } if (!err) { printf("Sample: "); for (int i = 0; !err && i < output_num; ++i) { err = geopm_agent_sample_name(agent_ptr, i, sizeof(output_str), output_str); if (!err) { if (i > 0) { printf(","); } printf("%s", output_str); } } if (!err && output_num == 0) { printf("(none)\n"); } else { printf("\n"); } } } else if (!err) { if (agent_ptr == NULL) { fprintf(stderr, "Error: Agent (-a) must be specified to create a policy.\n"); err = EINVAL; } int num_policy = 0; if (!err) { err = geopm_agent_num_policy(agent_ptr, &num_policy); } int policy_count = 0; if (!err) { if (num_policy) { char *tok = strtok(policy_vals_ptr, ","); char *endptr = NULL; while (!err && tok != NULL) { policy_vals[policy_count++] = strtod(tok, &endptr); if (tok == endptr) { fprintf(stderr, "Error: %s is not a valid floating-point number; " "use \"NAN\" to indicate default.\n", tok); err = EINVAL; } if (policy_count > GEOPMAGENT_DOUBLE_LENGTH) { err = E2BIG; } tok = strtok(NULL, ","); } if (!err && policy_count > num_policy) { fprintf(stderr, "Error: Number of policies read from command line is greater than expected for agent.\n"); err = EINVAL; } } else if (strncmp(policy_vals_ptr, "none", 4) != 0 && strncmp(policy_vals_ptr, "None", 4) != 0) { fprintf(stderr, "Error: Must specify \"None\" for the parameter option if agent takes no parameters.\n"); err = EINVAL; } } if (!err) { err = geopm_agent_policy_json_partial(agent_ptr, policy_count, policy_vals, sizeof(output_str), output_str); printf("%s\n", output_str); } } if (err) { geopm_error_message(err, error_str, GEOPMAGENT_STRING_LENGTH); fprintf(stderr, "Error: %s\n", error_str); } return err; } <|endoftext|>
<commit_before>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * adp.cpp * * AVDECC Discovery Protocol implementation */ #include <cstdint> #include "net_interface_imp.h" #include "enumeration.h" #include "log_imp.h" #include "util_imp.h" #include "adp.h" namespace avdecc_lib { adp::adp(const uint8_t *frame, size_t frame_len) { adp_frame = (uint8_t *)malloc(frame_len * sizeof(uint8_t)); memcpy(adp_frame, frame, frame_len); frame_read_returned = jdksavdecc_frame_read(&cmd_frame, adp_frame, 0, frame_len); if(frame_read_returned < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "frame_read error"); assert(frame_read_returned >= 0); } adpdu_read_returned = jdksavdecc_adpdu_read(&adpdu, adp_frame, ETHER_HDR_SIZE, frame_len); if(adpdu_read_returned < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "adpdu_read error"); assert(adpdu_read_returned >= 0); } } adp::~adp() { free(adp_frame); // Free allocated memory for frame from the heap } struct jdksavdecc_eui64 adp::get_controller_guid() { uint64_t mac_guid; mac_guid = ((net_interface_ref->mac_addr() & UINT64_C(0xFFFFFF000000)) << 16) | UINT64_C(0x000000FFFF000000) | (net_interface_ref->mac_addr() & UINT64_C(0xFFFFFF)); return jdksavdecc_eui64_get(&mac_guid, 0); } } <commit_msg>Fixes byte order of Controller entity ID<commit_after>/* * Licensed under the MIT License (MIT) * * Copyright (c) 2013 AudioScience Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * adp.cpp * * AVDECC Discovery Protocol implementation */ #include <cstdint> #include "net_interface_imp.h" #include "enumeration.h" #include "log_imp.h" #include "util_imp.h" #include "adp.h" namespace avdecc_lib { adp::adp(const uint8_t *frame, size_t frame_len) { adp_frame = (uint8_t *)malloc(frame_len * sizeof(uint8_t)); memcpy(adp_frame, frame, frame_len); frame_read_returned = jdksavdecc_frame_read(&cmd_frame, adp_frame, 0, frame_len); if(frame_read_returned < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "frame_read error"); assert(frame_read_returned >= 0); } adpdu_read_returned = jdksavdecc_adpdu_read(&adpdu, adp_frame, ETHER_HDR_SIZE, frame_len); if(adpdu_read_returned < 0) { log_imp_ref->post_log_msg(LOGGING_LEVEL_ERROR, "adpdu_read error"); assert(adpdu_read_returned >= 0); } } adp::~adp() { free(adp_frame); // Free allocated memory for frame from the heap } struct jdksavdecc_eui64 adp::get_controller_guid() { uint64_t mac_guid = ((net_interface_ref->mac_addr() & UINT64_C(0xFFFFFF000000)) << 16) | UINT64_C(0x000000FFFF000000) | (net_interface_ref->mac_addr() & UINT64_C(0xFFFFFF)); struct jdksavdecc_eui64 guid; jdksavdecc_eui64_init_from_uint64(&guid, mac_guid); return guid; } } <|endoftext|>
<commit_before>#include "SocketSession.h" #include "fxtimer.h" #include "fxdb.h" #include "fxmeta.h" #include "PlayerSession.h" #include "ServerSession.h" #include "GameServer.h" #include <signal.h> #include "gflags/gflags.h" unsigned int g_dwPort = 20000; bool g_bRun = true; DEFINE_uint32(server_id, 30001, "server id"); DEFINE_string(server_ip, "127.0.0.1", "server ip"); DEFINE_uint32(server_port, 31001, "server port"); DEFINE_uint32(player_port, 31002, "player port"); DEFINE_string(center_ip, "127.0.0.1", "center ip"); DEFINE_uint32(center_port, 40000, "center port"); DEFINE_string(redis_ip, "127.0.0.1", "redis ip"); DEFINE_string(redis_pw, "1", "redis password"); DEFINE_uint32(redis_port, 16379, "redis port"); void EndFun(int n) { if (n == SIGINT || n == SIGTERM) { g_bRun = false; } else { printf("unknown signal : %d !!!!!!!!!!!!!!!!!!!!!!!\n", n); } } int main(int argc, char **argv) { //----------------------order can't change begin-----------------------// gflags::SetUsageMessage("WebGameManager"); gflags::ParseCommandLineFlags(&argc, &argv, false); signal(SIGINT, EndFun); signal(SIGTERM, EndFun); // must define before goto IFxNet* pNet = NULL; if (!GetTimeHandler()->Init()) { g_bRun = false; goto STOP; } GetTimeHandler()->Run(); if (!GameServer::CreateInstance()) { g_bRun = false; goto STOP; } pNet = FxNetGetModule(); if (!pNet) { g_bRun = false; goto STOP; } //----------------------order can't change end-----------------------// if (!GameServer::Instance()->Init(FLAGS_server_id, FLAGS_server_ip, FLAGS_center_ip, FLAGS_center_port, FLAGS_server_port, FLAGS_player_port)) { g_bRun = false; goto STOP; } while (g_bRun) { GetTimeHandler()->Run(); pNet->Run(0xffffffff); FxSleep(1); } GameServer::Instance()->Stop(); FxSleep(10); pNet->Release(); STOP: printf("error!!!!!!!!\n");false;} <commit_msg>fix linux下 僵尸进程<commit_after>#include "SocketSession.h" #include "fxtimer.h" #include "fxdb.h" #include "fxmeta.h" #include "PlayerSession.h" #include "ServerSession.h" #include "GameServer.h" #include <signal.h> #include "gflags/gflags.h" unsigned int g_dwPort = 20000; bool g_bRun = true; DEFINE_uint32(server_id, 30001, "server id"); DEFINE_string(server_ip, "127.0.0.1", "server ip"); DEFINE_uint32(server_port, 31001, "server port"); DEFINE_uint32(player_port, 31002, "player port"); DEFINE_string(center_ip, "127.0.0.1", "center ip"); DEFINE_uint32(center_port, 40000, "center port"); DEFINE_string(redis_ip, "127.0.0.1", "redis ip"); DEFINE_string(redis_pw, "1", "redis password"); DEFINE_uint32(redis_port, 16379, "redis port"); void EndFun(int n) { if (n == SIGINT || n == SIGTERM) { g_bRun = false; } else { printf("unknown signal : %d !!!!!!!!!!!!!!!!!!!!!!!\n", n); } } #ifndef WIN32 void SigChld(int signo) { pid_t pid; int stat; pid = wait(&stat); printf("child %d exit\n", pid); return; } #endif // !WIN32 int main(int argc, char **argv) { //----------------------order can't change begin-----------------------// gflags::SetUsageMessage("WebGameManager"); gflags::ParseCommandLineFlags(&argc, &argv, false); signal(SIGINT, EndFun); signal(SIGTERM, EndFun); #ifndef WIN32 signal(SIGCHLD, &SigChld); #endif // !WIN32 // must define before goto IFxNet* pNet = NULL; if (!GetTimeHandler()->Init()) { g_bRun = false; goto STOP; } GetTimeHandler()->Run(); if (!GameServer::CreateInstance()) { g_bRun = false; goto STOP; } pNet = FxNetGetModule(); if (!pNet) { g_bRun = false; goto STOP; } //----------------------order can't change end-----------------------// if (!GameServer::Instance()->Init(FLAGS_server_id, FLAGS_server_ip, FLAGS_center_ip, FLAGS_center_port, FLAGS_server_port, FLAGS_player_port)) { g_bRun = false; goto STOP; } while (g_bRun) { GetTimeHandler()->Run(); pNet->Run(0xffffffff); FxSleep(1); } GameServer::Instance()->Stop(); FxSleep(10); pNet->Release(); STOP: printf("error!!!!!!!!\n");false;} <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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, Inc. 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. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_BOUNDARY_H_ #define PCL_FEATURES_IMPL_BOUNDARY_H_ #include "pcl/features/boundary.h" #include <cfloat> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint ( const pcl::PointCloud<PointInT> &cloud, int q_idx, const std::vector<int> &indices, const Eigen::Vector4f &u, const Eigen::Vector4f &v, const float angle_threshold) { return (isBoundaryPoint (cloud, cloud.points[q_idx], indices, u, v, angle_threshold)); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint ( const pcl::PointCloud<PointInT> &cloud, const PointInT &q_point, const std::vector<int> &indices, const Eigen::Vector4f &u, const Eigen::Vector4f &v, const float angle_threshold) { if (indices.size () < 3) return (false); if (!pcl_isfinite (q_point.x) || !pcl_isfinite (q_point.y) || !pcl_isfinite (q_point.z)) return (false); // Compute the angles between each neighboring point and the query point itself std::vector<float> angles (indices.size ()); float max_dif = FLT_MIN, dif; int cp = 0; for (size_t i = 0; i < indices.size (); ++i) { if (!pcl_isfinite (cloud.points[indices[i]].x) || !pcl_isfinite (cloud.points[indices[i]].y) || !pcl_isfinite (cloud.points[indices[i]].z)) continue; Eigen::Vector4f delta = cloud.points[indices[i]].getVector4fMap () - q_point.getVector4fMap (); angles[cp++] = atan2f (v.dot (delta), u.dot (delta)); // the angles are fine between -PI and PI too } if (cp == 0) return (false); angles.resize (cp); std::sort (angles.begin (), angles.end ()); // Compute the maximal angle difference between two consecutive angles for (size_t i = 0; i < angles.size () - 1; ++i) { dif = angles[i + 1] - angles[i]; if (max_dif < dif) max_dif = dif; } // Get the angle difference between the last and the first dif = 2 * M_PI - angles[angles.size () - 1] + angles[0]; if (max_dif < dif) max_dif = dif; // Check results if (max_dif > angle_threshold) return (true); else return (false); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero (); output.is_dense = true; // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense if (input_->is_dense) { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points[idx].boundary_point = std::numeric_limits<uint8_t>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } else { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points[idx].boundary_point = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT> void pcl::BoundaryEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero (); output.is_dense = true; output.points.resize (indices_->size (), 1); // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense if (input_->is_dense) { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } else { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } } #define PCL_INSTANTIATE_BoundaryEstimation(PointInT,PointNT,PointOutT) template class PCL_EXPORTS pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>; #endif // PCL_FEATURES_IMPL_BOUNDARY_H_ <commit_msg>Changed float to uint8_t to prevent overflow warning.<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, 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, Inc. 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. * * $Id$ * */ #ifndef PCL_FEATURES_IMPL_BOUNDARY_H_ #define PCL_FEATURES_IMPL_BOUNDARY_H_ #include "pcl/features/boundary.h" #include <cfloat> ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint ( const pcl::PointCloud<PointInT> &cloud, int q_idx, const std::vector<int> &indices, const Eigen::Vector4f &u, const Eigen::Vector4f &v, const float angle_threshold) { return (isBoundaryPoint (cloud, cloud.points[q_idx], indices, u, v, angle_threshold)); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> bool pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::isBoundaryPoint ( const pcl::PointCloud<PointInT> &cloud, const PointInT &q_point, const std::vector<int> &indices, const Eigen::Vector4f &u, const Eigen::Vector4f &v, const float angle_threshold) { if (indices.size () < 3) return (false); if (!pcl_isfinite (q_point.x) || !pcl_isfinite (q_point.y) || !pcl_isfinite (q_point.z)) return (false); // Compute the angles between each neighboring point and the query point itself std::vector<float> angles (indices.size ()); float max_dif = FLT_MIN, dif; int cp = 0; for (size_t i = 0; i < indices.size (); ++i) { if (!pcl_isfinite (cloud.points[indices[i]].x) || !pcl_isfinite (cloud.points[indices[i]].y) || !pcl_isfinite (cloud.points[indices[i]].z)) continue; Eigen::Vector4f delta = cloud.points[indices[i]].getVector4fMap () - q_point.getVector4fMap (); angles[cp++] = atan2f (v.dot (delta), u.dot (delta)); // the angles are fine between -PI and PI too } if (cp == 0) return (false); angles.resize (cp); std::sort (angles.begin (), angles.end ()); // Compute the maximal angle difference between two consecutive angles for (size_t i = 0; i < angles.size () - 1; ++i) { dif = angles[i + 1] - angles[i]; if (max_dif < dif) max_dif = dif; } // Get the angle difference between the last and the first dif = 2 * M_PI - angles[angles.size () - 1] + angles[0]; if (max_dif < dif) max_dif = dif; // Check results if (max_dif > angle_threshold) return (true); else return (false); } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT, typename PointOutT> void pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>::computeFeature (PointCloudOut &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero (); output.is_dense = true; // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense if (input_->is_dense) { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points[idx].boundary_point = std::numeric_limits<uint8_t>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } else { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points[idx].boundary_point = std::numeric_limits<uint8_t>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points[idx].boundary_point = isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } } ////////////////////////////////////////////////////////////////////////////////////////////// template <typename PointInT, typename PointNT> void pcl::BoundaryEstimation<PointInT, PointNT, Eigen::MatrixXf>::computeFeatureEigen (pcl::PointCloud<Eigen::MatrixXf> &output) { // Allocate enough space to hold the results // \note This resize is irrelevant for a radiusSearch (). std::vector<int> nn_indices (k_); std::vector<float> nn_dists (k_); Eigen::Vector4f u = Eigen::Vector4f::Zero (), v = Eigen::Vector4f::Zero (); output.is_dense = true; output.points.resize (indices_->size (), 1); // Save a few cycles by not checking every point for NaN/Inf values if the cloud is set to dense if (input_->is_dense) { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } else { // Iterating over the entire index vector for (size_t idx = 0; idx < indices_->size (); ++idx) { if (!isFinite ((*input_)[(*indices_)[idx]]) || this->searchForNeighbors ((*indices_)[idx], search_parameter_, nn_indices, nn_dists) == 0) { output.points (idx, 0) = std::numeric_limits<float>::quiet_NaN (); output.is_dense = false; continue; } // Obtain a coordinate system on the least-squares plane //v = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().unitOrthogonal (); //u = normals_->points[(*indices_)[idx]].getNormalVector4fMap ().cross3 (v); this->getCoordinateSystemOnPlane (normals_->points[(*indices_)[idx]], u, v); // Estimate whether the point is lying on a boundary surface or not output.points (idx, 0) = this->isBoundaryPoint (*surface_, input_->points[(*indices_)[idx]], nn_indices, u, v, angle_threshold_); } } } #define PCL_INSTANTIATE_BoundaryEstimation(PointInT,PointNT,PointOutT) template class PCL_EXPORTS pcl::BoundaryEstimation<PointInT, PointNT, PointOutT>; #endif // PCL_FEATURES_IMPL_BOUNDARY_H_ <|endoftext|>
<commit_before>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.1 2003/04/17 21:58:49 neilg * Adding a new property, * http://apache.org/xml/properties/security-manager, with * appropriate getSecurityManager/setSecurityManager methods on DOM * and SAX parsers. Also adding a new SecurityManager class. * * The purpose of these modifications is to permit applications a * means to have the parser reject documents whose processing would * otherwise consume large amounts of system resources. Malicious * use of such documents could be used to launch a denial-of-service * attack against a system running the parser. Initially, the * SecurityManager only knows about attacks that can result from * exponential entity expansion; this is the only known attack that * involves processing a single XML document. Other, simlar attacks * can be launched if arbitrary schemas may be parsed; there already * exist means (via use of the EntityResolver interface) by which * applications can deny processing of untrusted schemas. In future, * the SecurityManager will be expanded to take these other exploits * into account. * * Initial checkin of SecurityManager * * $Id$ * */ #ifndef SECURITYMANAGER_HPP #define SECURITYMANAGER_HPP #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * Allow application to force the parser to behave in a security-conscious * way. * * <p> There are cases in which an XML- or XmL-schema- * conformant processor can be presented with documents the * processing of which can involve the consumption of * prohibitive amounts of system resources. Applications can * attach instances of this class to parsers that they've * created, via the * http://apache.org/xml/properties/security-manager property. * </p> * * <p> Defaults will be provided for all known security holes. * Setter methods will be provided on this class to ensure that * an application can customize each limit as it chooses. * Components that are vulnerable to any given hole need to be * written to act appropriately when an instance of this class * has been set on the calling parser. * </p> */ class XMLUTIL_EXPORT SecurityManager { public: static const unsigned int ENTITY_EXPANSION_LIMIT = 50000; /** @name default Constructors */ //@{ /** Default constructor */ SecurityManager() { fEntityExpansionLimit = ENTITY_EXPANSION_LIMIT; } /** Destructor */ virtual ~SecurityManager(){}; //@} /** @name The Security Manager */ //@{ /** * An application should call this method when it wishes to specify a particular * limit to the number of entity expansions the parser will permit in a * particular document. The default behaviour should allow the parser * to validate nearly all XML non-malicious XML documents; if an * application knows that it is operating in a domain where entities are * uncommon, for instance, it may wish to provide a limit lower than the * parser's default. * * @param newLimit the new entity expansion limit * */ virtual void setEntityExpansionLimit(unsigned int newLimit) { fEntityExpansionLimit = newLimit; } /** * Permits the application or a parser component to query the current * limit for entity expansions. * * @return the current setting of the entity expansion limit * */ virtual unsigned int getEntityExpansionLimit() const { return fEntityExpansionLimit; } //@} protected: unsigned int fEntityExpansionLimit; private: /* Unimplemented Constructors and operators */ /* Copy constructor */ SecurityManager(const SecurityManager&); /** Assignment operator */ SecurityManager& operator=(const SecurityManager&); }; XERCES_CPP_NAMESPACE_END #endif <commit_msg>change const static member to an enum to make MSVC happy<commit_after>/* * The Apache Software License, Version 1.1 * * Copyright (c) 2003 The Apache Software Foundation. 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. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xerces" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact apache\@apache.org. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation, and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com . For more information * on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /* * $Log$ * Revision 1.2 2003/04/22 12:53:38 neilg * change const static member to an enum to make MSVC happy * * change ENTITY_EXPANSION_LIMIT from a static const data member to an enum * * Revision 1.1 2003/04/17 21:58:49 neilg * Adding a new property, * http://apache.org/xml/properties/security-manager, with * appropriate getSecurityManager/setSecurityManager methods on DOM * and SAX parsers. Also adding a new SecurityManager class. * * The purpose of these modifications is to permit applications a * means to have the parser reject documents whose processing would * otherwise consume large amounts of system resources. Malicious * use of such documents could be used to launch a denial-of-service * attack against a system running the parser. Initially, the * SecurityManager only knows about attacks that can result from * exponential entity expansion; this is the only known attack that * involves processing a single XML document. Other, simlar attacks * can be launched if arbitrary schemas may be parsed; there already * exist means (via use of the EntityResolver interface) by which * applications can deny processing of untrusted schemas. In future, * the SecurityManager will be expanded to take these other exploits * into account. * * Initial checkin of SecurityManager * * $Id$ * */ #ifndef SECURITYMANAGER_HPP #define SECURITYMANAGER_HPP #include <xercesc/util/XercesDefs.hpp> XERCES_CPP_NAMESPACE_BEGIN /** * Allow application to force the parser to behave in a security-conscious * way. * * <p> There are cases in which an XML- or XmL-schema- * conformant processor can be presented with documents the * processing of which can involve the consumption of * prohibitive amounts of system resources. Applications can * attach instances of this class to parsers that they've * created, via the * http://apache.org/xml/properties/security-manager property. * </p> * * <p> Defaults will be provided for all known security holes. * Setter methods will be provided on this class to ensure that * an application can customize each limit as it chooses. * Components that are vulnerable to any given hole need to be * written to act appropriately when an instance of this class * has been set on the calling parser. * </p> */ class XMLUTIL_EXPORT SecurityManager { public: enum { ENTITY_EXPANSION_LIMIT = 50000}; /** @name default Constructors */ //@{ /** Default constructor */ SecurityManager() { fEntityExpansionLimit = ENTITY_EXPANSION_LIMIT; } /** Destructor */ virtual ~SecurityManager(){}; //@} /** @name The Security Manager */ //@{ /** * An application should call this method when it wishes to specify a particular * limit to the number of entity expansions the parser will permit in a * particular document. The default behaviour should allow the parser * to validate nearly all XML non-malicious XML documents; if an * application knows that it is operating in a domain where entities are * uncommon, for instance, it may wish to provide a limit lower than the * parser's default. * * @param newLimit the new entity expansion limit * */ virtual void setEntityExpansionLimit(unsigned int newLimit) { fEntityExpansionLimit = newLimit; } /** * Permits the application or a parser component to query the current * limit for entity expansions. * * @return the current setting of the entity expansion limit * */ virtual unsigned int getEntityExpansionLimit() const { return fEntityExpansionLimit; } //@} protected: unsigned int fEntityExpansionLimit; private: /* Unimplemented Constructors and operators */ /* Copy constructor */ SecurityManager(const SecurityManager&); /** Assignment operator */ SecurityManager& operator=(const SecurityManager&); }; XERCES_CPP_NAMESPACE_END #endif <|endoftext|>
<commit_before>#include <drivers/mpu6000.hpp> #include <hal.h> #include <hal_config.hpp> MPU6000::MPU6000(SPIDriver *spid, const SPIConfig *spicfg) : spid(spid), spicfg(spicfg) { } void MPU6000::init() { uint8_t txbuf[8], rxbuf[8]; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); spiStart(spid, spicfg); spiSelect(spid); // Reset device. txbuf[0] = MPU6000_PWR_MGMT_1; txbuf[1] = 0x80; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. chThdSleepMilliseconds(100); // Set sample rate to 1 kHz. txbuf[0] = MPU6000_SMPLRT_DIV; txbuf[1] = 0x00; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set DLPF to 4 (20 Hz gyro bandwidth1 Hz accelerometer bandwidth) txbuf[0] = MPU6000_CONFIG; txbuf[1] = 0x04; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Wake up device and set clock source to Gyro Z. txbuf[0] = MPU6000_PWR_MGMT_1; txbuf[1] = 0x03; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set gyro full range to 2000 dps. We first read in the current register // value so we can change what we need and leave everything else alone. txbuf[0] = MPU6000_GYRO_CONFIG | (1<<7); spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. txbuf[0] = MPU6000_GYRO_CONFIG; txbuf[1] = (rxbuf[1] & ~0x18) | 0x18; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set accelerometer full range to 2 g. txbuf[0] = MPU6000_ACCEL_CONFIG | (1<<7); spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. txbuf[0] = MPU6000_ACCEL_CONFIG; txbuf[1] = (rxbuf[1] & ~0x18) | 0x00; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Stop bus spiUnselect(spid); spiReleaseBus(spid); chMtxUnlock(); // Read once to clear out bad data? readGyro(); readAccel(); } gyroscope_reading_t MPU6000::readGyro() { uint8_t txbuf[8], rxbuf[8]; gyroscope_reading_t reading; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); spiStart(spid, spicfg); spiSelect(spid); // Get data txbuf[0] = MPU6000_GYRO_XOUT_H | (1<<7); spiExchange(spid, 7, txbuf, rxbuf); reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16.384 * 3.1415926535 / 180.0 + GYR_X_OFFSET; reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16.384 * 3.1415926535 / 180.0 + GYR_Y_OFFSET; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16.384 * 3.1415926535 / 180.0 + GYR_Z_OFFSET; // TODO(yoos): correct for thermal bias. txbuf[0] = MPU6000_TEMP_OUT_H | (1<<7); spiExchange(spid, 3, txbuf, rxbuf); float temp = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 340 + 36.53; // Stop bus spiUnselect(spid); spiReleaseBus(spid); chMtxUnlock(); return reading; } accelerometer_reading_t MPU6000::readAccel() { uint8_t txbuf[8], rxbuf[8]; accelerometer_reading_t reading; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); spiStart(spid, spicfg); spiSelect(spid); // Get data txbuf[0] = MPU6000_ACCEL_XOUT_H | (1<<7); spiExchange(spid, 7, txbuf, rxbuf); reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16384.0 + ACC_X_OFFSET; reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16384.0 + ACC_Y_OFFSET; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16384.0 + ACC_Z_OFFSET; // Stop bus spiUnselect(spid); spiReleaseBus(spid); chMtxUnlock(); return reading; } //uint8_t MPU6000::readRegister(uint8_t reg) { // uint8_t txbuf[8]; // uint8_t rxbuf[8]; // // txbuf[0] = reg; // txbuf[1] = 0xFF; // // spiSelect(this->spid); // spiExchange(this->spid, 2, txbuf, rxbuf); // spiUnselect(this->spid); // // return rxbuf[1]; //} // //void MPU6000::writeRegister(uint8_t reg, uint8_t val) { // uint8_t txbuf[8]; // uint8_t rxbuf[8]; // // txbuf[0] = reg; // txbuf[1] = val; // // spiSelect(this->spid); // spiExchange(this->spid, 2, txbuf, rxbuf); // spiUnselect(this->spid); //} <commit_msg>Add comments on SPI exchange setup/teardown.<commit_after>#include <drivers/mpu6000.hpp> #include <hal.h> #include <hal_config.hpp> MPU6000::MPU6000(SPIDriver *spid, const SPIConfig *spicfg) : spid(spid), spicfg(spicfg) { } void MPU6000::init() { uint8_t txbuf[8], rxbuf[8]; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); // Acquire bus ownership spiStart(spid, spicfg); // Set up transfer parameters spiSelect(spid); // Assert slave select // Reset device. txbuf[0] = MPU6000_PWR_MGMT_1; txbuf[1] = 0x80; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. chThdSleepMilliseconds(100); // Set sample rate to 1 kHz. txbuf[0] = MPU6000_SMPLRT_DIV; txbuf[1] = 0x00; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set DLPF to 4 (20 Hz gyro bandwidth1 Hz accelerometer bandwidth) txbuf[0] = MPU6000_CONFIG; txbuf[1] = 0x04; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Wake up device and set clock source to Gyro Z. txbuf[0] = MPU6000_PWR_MGMT_1; txbuf[1] = 0x03; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set gyro full range to 2000 dps. We first read in the current register // value so we can change what we need and leave everything else alone. txbuf[0] = MPU6000_GYRO_CONFIG | (1<<7); spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. txbuf[0] = MPU6000_GYRO_CONFIG; txbuf[1] = (rxbuf[1] & ~0x18) | 0x18; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Set accelerometer full range to 2 g. txbuf[0] = MPU6000_ACCEL_CONFIG | (1<<7); spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. txbuf[0] = MPU6000_ACCEL_CONFIG; txbuf[1] = (rxbuf[1] & ~0x18) | 0x00; spiExchange(spid, 2, txbuf, rxbuf); // Exchange data. // Stop bus spiUnselect(spid); // Deassert slave select spiReleaseBus(spid); // Release bus ownership chMtxUnlock(); // Read once to clear out bad data? readGyro(); readAccel(); } gyroscope_reading_t MPU6000::readGyro() { uint8_t txbuf[8], rxbuf[8]; gyroscope_reading_t reading; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); // Acquire bus ownership spiStart(spid, spicfg); // Set up transfer parameters spiSelect(spid); // Assert slave select // Get data txbuf[0] = MPU6000_GYRO_XOUT_H | (1<<7); spiExchange(spid, 7, txbuf, rxbuf); // Atomic transfer operations reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16.384 * 3.1415926535 / 180.0 + GYR_X_OFFSET; reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16.384 * 3.1415926535 / 180.0 + GYR_Y_OFFSET; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16.384 * 3.1415926535 / 180.0 + GYR_Z_OFFSET; // TODO(yoos): correct for thermal bias. txbuf[0] = MPU6000_TEMP_OUT_H | (1<<7); spiExchange(spid, 3, txbuf, rxbuf); float temp = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 340 + 36.53; // Stop bus spiUnselect(spid); // Deassert slave select spiReleaseBus(spid); // Release bus ownership chMtxUnlock(); return reading; } accelerometer_reading_t MPU6000::readAccel() { uint8_t txbuf[8], rxbuf[8]; accelerometer_reading_t reading; // Start bus chMtxLock(&spi_mtx); spiAcquireBus(spid); // Acquire bus ownership spiStart(spid, spicfg); // Set up transfer parameters spiSelect(spid); // Assert slave select // Get data txbuf[0] = MPU6000_ACCEL_XOUT_H | (1<<7); spiExchange(spid, 7, txbuf, rxbuf); // Atomic transfer operations reading.axes[0] = ((int16_t) ((rxbuf[1]<<8) | rxbuf[2])) / 16384.0 + ACC_X_OFFSET; reading.axes[1] = ((int16_t) ((rxbuf[3]<<8) | rxbuf[4])) / 16384.0 + ACC_Y_OFFSET; reading.axes[2] = ((int16_t) ((rxbuf[5]<<8) | rxbuf[6])) / 16384.0 + ACC_Z_OFFSET; // Stop bus spiUnselect(spid); // Deassert slave select spiReleaseBus(spid); // Release bus ownership chMtxUnlock(); return reading; } //uint8_t MPU6000::readRegister(uint8_t reg) { // uint8_t txbuf[8]; // uint8_t rxbuf[8]; // // txbuf[0] = reg; // txbuf[1] = 0xFF; // // spiSelect(this->spid); // spiExchange(this->spid, 2, txbuf, rxbuf); // spiUnselect(this->spid); // // return rxbuf[1]; //} // //void MPU6000::writeRegister(uint8_t reg, uint8_t val) { // uint8_t txbuf[8]; // uint8_t rxbuf[8]; // // txbuf[0] = reg; // txbuf[1] = val; // // spiSelect(this->spid); // spiExchange(this->spid, 2, txbuf, rxbuf); // spiUnselect(this->spid); //} <|endoftext|>
<commit_before>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2015, Cauldron Development LLC Copyright (c) 2003-2015, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "AsyncCopyStreamToLog.h" #include "Logger.h" #include <cbang/util/DefaultCatch.h> #include <string.h> using namespace std; using namespace cb; void AsyncCopyStreamToLog::run() { try { Logger::LogStream log = Logger::instance().createStream (CBANG_LOG_DOMAIN, CBANG_LOG_INFO_LEVEL(1), prefix); const unsigned bufferSize = 4096; char buffer[bufferSize]; int fill = 0; while (!in->fail() && !log->fail() && !shouldShutdown()) { int c = in->get(); if (c == char_traits<char>::eof()) break; buffer[fill++] = c; if (c == '\n' || fill == bufferSize) { log->write(buffer, fill); fill = 0; } } if (fill) log->write(buffer, fill); } CATCH_ERROR; } <commit_msg>signed/unsigned compare<commit_after>/******************************************************************************\ This file is part of the C! library. A.K.A the cbang library. Copyright (c) 2003-2015, Cauldron Development LLC Copyright (c) 2003-2015, Stanford University All rights reserved. The C! library is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 2.1 of the License, or (at your option) any later version. The C! 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 the C! library. If not, see <http://www.gnu.org/licenses/>. In addition, BSD licensing may be granted on a case by case basis by written permission from at least one of the copyright holders. You may request written permission by emailing the authors. For information regarding this software email: Joseph Coffland joseph@cauldrondevelopment.com \******************************************************************************/ #include "AsyncCopyStreamToLog.h" #include "Logger.h" #include <cbang/util/DefaultCatch.h> #include <string.h> using namespace std; using namespace cb; void AsyncCopyStreamToLog::run() { try { Logger::LogStream log = Logger::instance().createStream (CBANG_LOG_DOMAIN, CBANG_LOG_INFO_LEVEL(1), prefix); const unsigned bufferSize = 4096; char buffer[bufferSize]; unsigned fill = 0; while (!in->fail() && !log->fail() && !shouldShutdown()) { int c = in->get(); if (c == char_traits<char>::eof()) break; buffer[fill++] = c; if (c == '\n' || fill == bufferSize) { log->write(buffer, fill); fill = 0; } } if (fill) log->write(buffer, fill); } CATCH_ERROR; } <|endoftext|>
<commit_before><commit_msg>fdo#74595 Make HTML detection to follow specs<commit_after><|endoftext|>
<commit_before>/*********************************************************************** custom1.cpp - Example very similar to simple1, except that it accesses the query results through a Specialized SQL Structure instead of through Row objects. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "util.h" #include <mysql++.h> #include <custom.h> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace mysqlpp; // The following is calling a very complex macro which will create // "struct stock", which has the member variables: // string item // int num // ... // Date sdate // plus methods to help populate the class from a MySQL row // among other things that I'll get too in a later example. sql_create_5(stock, 1, 5, // explained in the user manual string, item, longlong, num, double, weight, double, price, Date, sdate) int main(int argc, char *argv[]) { try { Connection con(use_exceptions); if (!connect_to_db(argc, argv, con)) { return 1; } Query query = con.query(); query << "select * from stock"; vector < stock > res; query.storein(res); // this is storing the results into a vector of the custom struct // "stock" which was created my the macro above. cout.setf(ios::left); cout << setw(17) << "Item" << setw(4) << "Num" << setw(7) << "Weight" << setw(7) << "Price" << "Date" << endl << endl; // Now we we iterate through the vector using an iterator and // produce output similar to that using Row // Notice how we call the actual variables in i and not an index // offset. This is because the macro at the begging of the file // set up an *actual* struct of type stock which contains the // variables item, num, weight, price, and data. cout.precision(3); vector<stock>::iterator i; for (i = res.begin(); i != res.end(); i++) { cout << setw(17) << i->item.c_str() // unfortunally the gnu string class does not respond to format // modifers so I have to convert it to a conat char *. << setw(4) << i->num << setw(7) << i->weight << setw(7) << i->price << i->sdate << endl; } return 0; } catch (BadQuery& er) { // handle any connection or query errors that may come up cerr << "Error: " << er.what() << endl; return -1; } catch (BadConversion& er) { // handle bad conversions cerr << "Error: " << er.what() << "\"." << endl << "retrieved data size: " << er.retrieved << " actual data size: " << er.actual_size << endl; return -1; } catch (exception & er) { cerr << "Error: " << er.what() << endl; return -1; } } <commit_msg>Comment tweak<commit_after>/*********************************************************************** custom1.cpp - Example very similar to simple1, except that it accesses the query results through a Specialized SQL Structure instead of through Row objects. Copyright (c) 1998 by Kevin Atkinson, (c) 1999, 2000 and 2001 by MySQL AB, and (c) 2004, 2005 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ 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 MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "util.h" #include <mysql++.h> #include <custom.h> #include <iostream> #include <iomanip> #include <vector> using namespace std; using namespace mysqlpp; // The following is calling a very complex macro which will create // "struct stock", which has the member variables: // string item // ... // Date sdate // plus methods to help populate the class from a MySQL row // among other things that I'll get too in a later example. sql_create_5(stock, 1, 5, // explained in the user manual string, item, longlong, num, double, weight, double, price, Date, sdate) int main(int argc, char *argv[]) { try { Connection con(use_exceptions); if (!connect_to_db(argc, argv, con)) { return 1; } Query query = con.query(); query << "select * from stock"; vector < stock > res; query.storein(res); // this is storing the results into a vector of the custom struct // "stock" which was created my the macro above. cout.setf(ios::left); cout << setw(17) << "Item" << setw(4) << "Num" << setw(7) << "Weight" << setw(7) << "Price" << "Date" << endl << endl; // Now we we iterate through the vector using an iterator and // produce output similar to that using Row // Notice how we call the actual variables in i and not an index // offset. This is because the macro at the begging of the file // set up an *actual* struct of type stock which contains the // variables item, num, weight, price, and data. cout.precision(3); vector<stock>::iterator i; for (i = res.begin(); i != res.end(); i++) { cout << setw(17) << i->item.c_str() // unfortunally the gnu string class does not respond to format // modifers so I have to convert it to a conat char *. << setw(4) << i->num << setw(7) << i->weight << setw(7) << i->price << i->sdate << endl; } return 0; } catch (BadQuery& er) { // handle any connection or query errors that may come up cerr << "Error: " << er.what() << endl; return -1; } catch (BadConversion& er) { // handle bad conversions cerr << "Error: " << er.what() << "\"." << endl << "retrieved data size: " << er.retrieved << " actual data size: " << er.actual_size << endl; return -1; } catch (exception & er) { cerr << "Error: " << er.what() << endl; return -1; } } <|endoftext|>
<commit_before>#include <libtorrent/enum_net.hpp> #include <libtorrent/socket.hpp> #include <libtorrent/broadcast_socket.hpp> #include <vector> using namespace libtorrent; int main() { io_service ios; asio::error_code ec; std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { std::cout << "address: " << i->interface_address << std::endl << " mask: " << i->netmask << std::endl << " flags: "; if (is_multicast(i->interface_address)) std::cout << "multicast "; if (is_local(i->interface_address)) std::cout << "local "; if (is_loopback(i->interface_address)) std::cout << "loopback "; std::cout << std::endl; } address local = guess_local_address(ios); std::cout << "Local address: " << local << std::endl; } <commit_msg>prints out default gateway in example<commit_after>#include <libtorrent/enum_net.hpp> #include <libtorrent/socket.hpp> #include <libtorrent/broadcast_socket.hpp> #include <vector> using namespace libtorrent; int main() { io_service ios; asio::error_code ec; std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec); for (std::vector<ip_interface>::const_iterator i = net.begin() , end(net.end()); i != end; ++i) { std::cout << "address: " << i->interface_address << std::endl << " mask: " << i->netmask << std::endl << " flags: "; if (is_multicast(i->interface_address)) std::cout << "multicast "; if (is_local(i->interface_address)) std::cout << "local "; if (is_loopback(i->interface_address)) std::cout << "loopback "; std::cout << std::endl; } address local = guess_local_address(ios); std::cout << "Local address: " << local << std::endl; address gateway = get_default_gateway(ios, local, ec); std::cout << "Default gateway: " << gateway << std::endl; } <|endoftext|>
<commit_before>#include "State.h" #include <fstream> #include "Configuration.h" #include "utils/BencodeWriter.h" #include "utils/BencodeParser.h" mtt::TorrentState::TorrentState(std::vector<uint8_t>& p) : pieces(p) { } void mtt::TorrentState::save(const std::string& name) { auto folderPath = mtt::config::getInternal().stateFolder + "\\" + name + ".state"; std::ofstream file(folderPath, std::ios::binary); if (!file) return; BencodeWriter writer; writer.startArray(); writer.addRawItem("12:downloadPath", downloadPath); writer.addRawItemFromBuffer("6:pieces", (const char*)pieces.data(), pieces.size()); writer.addRawItem("13:lastStateTime", lastStateTime); writer.addRawItem("7:started", started); writer.startRawArrayItem("9:selection"); for (auto& f : files) { writer.startArray(); writer.addNumber(f.selected); writer.addNumber((size_t)f.priority); writer.endArray(); } writer.endArray(); writer.endArray(); file << writer.data; } bool mtt::TorrentState::load(const std::string& name) { std::ifstream file(mtt::config::getInternal().stateFolder + "\\" + name + ".state", std::ios::binary); if (!file) return false; std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); BencodeParser parser; if (!parser.parse((uint8_t*)data.data(), data.length())) return false; if (auto root = parser.getRoot()) { downloadPath = root->getTxt("downloadPath"); lastStateTime = (int64_t)root->getBigInt("lastStateTime"); started = root->getInt("started"); if (auto pItem = root->getTxtItem("pieces")) { pieces.assign(pItem->data, pItem->data + pItem->size); } if (auto fList = root->getListItem("selection")) { files.clear(); for (auto& f : *fList) { if (f.isList()) { auto params = f.getFirstItem(); files.push_back({ params->getInt() != 0, (Priority)params->getNextSibling()->getInt() }); } else files.push_back({ false, Priority::Normal }); } } } return true; } void mtt::TorrentState::remove(const std::string& name) { auto fullName = mtt::config::getInternal().stateFolder + "\\" + name + ".state"; std::remove(fullName.data()); } void mtt::TorrentsList::save() { auto folderPath = mtt::config::getInternal().stateFolder + "\\list"; std::ofstream file(folderPath, std::ios::binary); if (!file) return; BencodeWriter writer; writer.startArray(); for (auto& t : torrents) { writer.startMap(); writer.addRawItem("4:name", t.name); writer.endMap(); } writer.endArray(); file << writer.data; } bool mtt::TorrentsList::load() { std::ifstream file(mtt::config::getInternal().stateFolder + "\\list", std::ios::binary); if (!file) return false; std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); BencodeParser parser; if (!parser.parse((uint8_t*)data.data(), data.length())) return false; torrents.clear(); if (auto root = parser.getRoot()) { for (auto& it : *root) { TorrentInfo info; info.name = it.getTxt("name"); torrents.push_back(info); } } return true; } <commit_msg>dont assign pieces state from invalid saved state<commit_after>#include "State.h" #include <fstream> #include "Configuration.h" #include "utils/BencodeWriter.h" #include "utils/BencodeParser.h" mtt::TorrentState::TorrentState(std::vector<uint8_t>& p) : pieces(p) { } void mtt::TorrentState::save(const std::string& name) { auto folderPath = mtt::config::getInternal().stateFolder + "\\" + name + ".state"; std::ofstream file(folderPath, std::ios::binary); if (!file) return; BencodeWriter writer; writer.startArray(); writer.addRawItem("12:downloadPath", downloadPath); writer.addRawItemFromBuffer("6:pieces", (const char*)pieces.data(), pieces.size()); writer.addRawItem("13:lastStateTime", lastStateTime); writer.addRawItem("7:started", started); writer.startRawArrayItem("9:selection"); for (auto& f : files) { writer.startArray(); writer.addNumber(f.selected); writer.addNumber((size_t)f.priority); writer.endArray(); } writer.endArray(); writer.endArray(); file << writer.data; } bool mtt::TorrentState::load(const std::string& name) { std::ifstream file(mtt::config::getInternal().stateFolder + "\\" + name + ".state", std::ios::binary); if (!file) return false; std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); BencodeParser parser; if (!parser.parse((uint8_t*)data.data(), data.length())) return false; if (auto root = parser.getRoot()) { downloadPath = root->getTxt("downloadPath"); lastStateTime = (int64_t)root->getBigInt("lastStateTime"); started = root->getInt("started"); if (auto pItem = root->getTxtItem("pieces")) { if(pieces.size() == pItem->size) pieces.assign(pItem->data, pItem->data + pItem->size); } if (auto fList = root->getListItem("selection")) { files.clear(); for (auto& f : *fList) { if (f.isList()) { auto params = f.getFirstItem(); files.push_back({ params->getInt() != 0, (Priority)params->getNextSibling()->getInt() }); } else files.push_back({ false, Priority::Normal }); } } } return true; } void mtt::TorrentState::remove(const std::string& name) { auto fullName = mtt::config::getInternal().stateFolder + "\\" + name + ".state"; std::remove(fullName.data()); } void mtt::TorrentsList::save() { auto folderPath = mtt::config::getInternal().stateFolder + "\\list"; std::ofstream file(folderPath, std::ios::binary); if (!file) return; BencodeWriter writer; writer.startArray(); for (auto& t : torrents) { writer.startMap(); writer.addRawItem("4:name", t.name); writer.endMap(); } writer.endArray(); file << writer.data; } bool mtt::TorrentsList::load() { std::ifstream file(mtt::config::getInternal().stateFolder + "\\list", std::ios::binary); if (!file) return false; std::string data((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); BencodeParser parser; if (!parser.parse((uint8_t*)data.data(), data.length())) return false; torrents.clear(); if (auto root = parser.getRoot()) { for (auto& it : *root) { TorrentInfo info; info.name = it.getTxt("name"); torrents.push_back(info); } } return true; } <|endoftext|>
<commit_before>#include <iostream> #include <vpp/vpp.hh> int main() { using vpp::image2d; using vpp::vint2; using vpp::make_box2d; image2d<int> img1(make_box2d(100, 200)); image2d<int> img2({100, 200}); assert(img1.domain() == img2.domain()); assert(img1.nrows() == 100); assert(img1.ncols() == 200); } <commit_msg>Test operator[][]<commit_after>#include <iostream> #include <vpp/vpp.hh> int main() { using namespace vpp; image2d<int> img1(make_box2d(100, 200), _border = 3); image2d<int> img2({100, 200}); assert(img1.domain() == img2.domain()); assert(img1.nrows() == 100); assert(img1.ncols() == 200); { image2d<int> img(make_box2d(5, 5), _border = 3); auto s1 = img.subimage(img.domain()); for (auto p : img.domain()) assert(img(p) == img[p[0]][p[1]]); for (auto p : img.domain()) assert(img(p) == s1[p[0]][p[1]]); } } <|endoftext|>
<commit_before>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <python/helpers/pystream.h> #include <python/helpers/python_convert_optional.h> #include <vistk/pipeline_util/load_pipe.h> #include <vistk/pipeline_util/load_pipe_exception.h> #include <vistk/pipeline_util/pipe_declaration_types.h> #include <vistk/pipeline/process.h> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <string> /** * \file load.cxx * * \brief Python bindings for loading pipe blocks. */ using namespace boost::python; static object pipe_block_config(vistk::pipe_block const& block); static void pipe_block_config_set(vistk::pipe_block& block, vistk::config_pipe_block const& config); static object pipe_block_process(vistk::pipe_block const& block); static void pipe_block_process_set(vistk::pipe_block& block, vistk::process_pipe_block const& process); static object pipe_block_connect(vistk::pipe_block const& block); static void pipe_block_connect_set(vistk::pipe_block& block, vistk::connect_pipe_block const& connect); static object pipe_block_group(vistk::pipe_block const& block); static void pipe_block_group_set(vistk::pipe_block& block, vistk::group_pipe_block const& group); static vistk::pipe_blocks load_pipe_file(std::string const& path); static vistk::pipe_blocks load_pipe(object const& stream, std::string const& inc_root); static void translator(vistk::load_pipe_exception const& e); class block_visitor : public boost::static_visitor<object> { public: typedef enum { BLOCK_CONFIG, BLOCK_PROCESS, BLOCK_CONNECT, BLOCK_GROUP } block_t; block_visitor(block_t type); ~block_visitor(); block_t const block_type; object operator () (vistk::config_pipe_block const& config_block) const; object operator () (vistk::process_pipe_block const& process_block) const; object operator () (vistk::connect_pipe_block const& connect_block) const; object operator () (vistk::group_pipe_block const& group_block) const; }; BOOST_PYTHON_MODULE(load) { register_exception_translator< vistk::load_pipe_exception>(translator); REGISTER_OPTIONAL_CONVERTER(vistk::config_flags_t); REGISTER_OPTIONAL_CONVERTER(vistk::config_provider_t); REGISTER_OPTIONAL_CONVERTER(vistk::process::port_flags_t); class_<vistk::token_t>("Token" , "A token in the pipeline description."); class_<vistk::config_flag_t>("ConfigFlag" , "A flag on a configuration setting."); class_<vistk::config_flags_t>("ConfigFlags" , "A collection of flags on a configuration setting.") .def(vector_indexing_suite<vistk::config_flags_t>()) ; class_<vistk::config_provider_t>("ConfigProvider" , "A provider key for a configuration setting."); class_<vistk::config_key_options_t>("ConfigKeyOptions" , "A collection of options on a configuration setting.") .def_readwrite("flags", &vistk::config_key_options_t::flags) .def_readwrite("provider", &vistk::config_key_options_t::provider) ; class_<vistk::config_key_t>("ConfigKey" , "A configuration key with its settings.") .def_readwrite("key_path", &vistk::config_key_t::key_path) .def_readwrite("options", &vistk::config_key_t::options) ; class_<vistk::config_value_t>("ConfigValue" , "A complete configuration setting.") .def_readwrite("key", &vistk::config_value_t::key) .def_readwrite("value", &vistk::config_value_t::value) ; class_<vistk::config_values_t>("ConfigValues" , "A collection of configuration settings.") /// \todo Need operator == on config_value_t //.def(vector_indexing_suite<vistk::config_values_t>()) ; class_<vistk::map_options_t>("MapOptions" , "A collection of options for a mapping.") .def_readwrite("flags", &vistk::map_options_t::flags) ; class_<vistk::input_map_t>("InputMap" , "An input mapping for a group.") .def_readwrite("options", &vistk::input_map_t::options) .def_readwrite("from_", &vistk::input_map_t::from) .def_readwrite("to", &vistk::input_map_t::to) ; class_<vistk::input_maps_t>("InputMaps" , "A collection of input mappings.") /// \todo Need operator == on input_map_t. //.def(vector_indexing_suite<vistk::input_maps_t>()) ; class_<vistk::output_map_t>("OutputMap" , "An output mapping for a group.") .def_readwrite("options", &vistk::output_map_t::options) .def_readwrite("from_", &vistk::output_map_t::from) .def_readwrite("to", &vistk::output_map_t::to) ; class_<vistk::output_maps_t>("OutputMaps" , "A collection of output mappings.") /// \todo Need operator == on output_map_t. //.def(vector_indexing_suite<vistk::output_maps_t>()) ; class_<vistk::config_pipe_block>("ConfigBlock" , "A block of configuration settings.") .def_readwrite("key", &vistk::config_pipe_block::key) .def_readwrite("values", &vistk::config_pipe_block::values) ; class_<vistk::process_pipe_block>("ProcessBlock" , "A block which declares a process.") .def_readwrite("name", &vistk::process_pipe_block::name) .def_readwrite("type", &vistk::process_pipe_block::type) .def_readwrite("config_values", &vistk::process_pipe_block::config_values) ; class_<vistk::connect_pipe_block>("ConnectBlock" , "A block which connects two ports together.") .def_readwrite("from_", &vistk::connect_pipe_block::from) .def_readwrite("to", &vistk::connect_pipe_block::to) ; class_<vistk::group_pipe_block>("GroupBlock" , "A block which declares a group within the pipeline.") .def_readwrite("name", &vistk::group_pipe_block::name) .def_readwrite("config_values", &vistk::group_pipe_block::config_values) .def_readwrite("input_mappings", &vistk::group_pipe_block::input_mappings) .def_readwrite("output_mappings", &vistk::group_pipe_block::output_mappings) ; class_<vistk::pipe_block>("PipeBlock" , "A block in a pipeline declaration file.") .add_property("config", &pipe_block_config, &pipe_block_config_set) .add_property("process", &pipe_block_process, &pipe_block_process_set) .add_property("connect", &pipe_block_connect, &pipe_block_connect_set) .add_property("group", &pipe_block_group, &pipe_block_group_set) ; class_<vistk::pipe_blocks>("PipeBlocks" , "A collection of pipeline blocks.") /// \todo Need operator == on pipe_block. //.def(vector_indexing_suite<vistk::pipe_blocks>()) ; def("load_pipe_file", &load_pipe_file , (arg("path")) , "Load pipe blocks from a file."); def("load_pipe", &load_pipe , (arg("stream"), arg("inc_root") = std::string()) , "Load pipe blocks from a stream."); } void translator(vistk::load_pipe_exception const& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } object pipe_block_config(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_CONFIG), block); } void pipe_block_config_set(vistk::pipe_block& block, vistk::config_pipe_block const& config) { block = config; } object pipe_block_process(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_PROCESS), block); } void pipe_block_process_set(vistk::pipe_block& block, vistk::process_pipe_block const& process) { block = process; } object pipe_block_connect(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_CONNECT), block); } void pipe_block_connect_set(vistk::pipe_block& block, vistk::connect_pipe_block const& connect) { block = connect; } object pipe_block_group(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_GROUP), block); } void pipe_block_group_set(vistk::pipe_block& block, vistk::group_pipe_block const& group) { block = group; } vistk::pipe_blocks load_pipe_file(std::string const& path) { return vistk::load_pipe_blocks_from_file(boost::filesystem::path(path)); } vistk::pipe_blocks load_pipe(object const& stream, std::string const& inc_root) { pyistream istr(stream); return vistk::load_pipe_blocks(istr, boost::filesystem::path(inc_root)); } block_visitor ::block_visitor(block_t type) : block_type(type) { } block_visitor ::~block_visitor() { } object block_visitor ::operator () (vistk::config_pipe_block const& config_block) const { if (block_type == BLOCK_CONFIG) { return object(config_block); } return object(); } object block_visitor ::operator () (vistk::process_pipe_block const& process_block) const { if (block_type == BLOCK_PROCESS) { return object(process_block); } return object(); } object block_visitor ::operator () (vistk::connect_pipe_block const& connect_block) const { if (block_type == BLOCK_CONNECT) { return object(connect_block); } return object(); } object block_visitor ::operator () (vistk::group_pipe_block const& group_block) const { if (block_type == BLOCK_GROUP) { return object(group_block); } return object(); } <commit_msg>Use boost::optional binding function over macro<commit_after>/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include <python/helpers/pystream.h> #include <python/helpers/python_convert_optional.h> #include <vistk/pipeline_util/load_pipe.h> #include <vistk/pipeline_util/load_pipe_exception.h> #include <vistk/pipeline_util/pipe_declaration_types.h> #include <vistk/pipeline/process.h> #include <boost/python.hpp> #include <boost/python/suite/indexing/vector_indexing_suite.hpp> #include <string> /** * \file load.cxx * * \brief Python bindings for loading pipe blocks. */ using namespace boost::python; static object pipe_block_config(vistk::pipe_block const& block); static void pipe_block_config_set(vistk::pipe_block& block, vistk::config_pipe_block const& config); static object pipe_block_process(vistk::pipe_block const& block); static void pipe_block_process_set(vistk::pipe_block& block, vistk::process_pipe_block const& process); static object pipe_block_connect(vistk::pipe_block const& block); static void pipe_block_connect_set(vistk::pipe_block& block, vistk::connect_pipe_block const& connect); static object pipe_block_group(vistk::pipe_block const& block); static void pipe_block_group_set(vistk::pipe_block& block, vistk::group_pipe_block const& group); static vistk::pipe_blocks load_pipe_file(std::string const& path); static vistk::pipe_blocks load_pipe(object const& stream, std::string const& inc_root); static void translator(vistk::load_pipe_exception const& e); class block_visitor : public boost::static_visitor<object> { public: typedef enum { BLOCK_CONFIG, BLOCK_PROCESS, BLOCK_CONNECT, BLOCK_GROUP } block_t; block_visitor(block_t type); ~block_visitor(); block_t const block_type; object operator () (vistk::config_pipe_block const& config_block) const; object operator () (vistk::process_pipe_block const& process_block) const; object operator () (vistk::connect_pipe_block const& connect_block) const; object operator () (vistk::group_pipe_block const& group_block) const; }; BOOST_PYTHON_MODULE(load) { register_exception_translator< vistk::load_pipe_exception>(translator); register_optional_converter<vistk::config_flags_t>("ConfigFlagsOpt", "An optional config flags."); register_optional_converter<vistk::config_provider_t>("ConfigProviderOpt", "An optional config provider."); register_optional_converter<vistk::process::port_flags_t>("PortFlagsOpt", "An optional port flags."); class_<vistk::token_t>("Token" , "A token in the pipeline description."); class_<vistk::config_flag_t>("ConfigFlag" , "A flag on a configuration setting."); class_<vistk::config_flags_t>("ConfigFlags" , "A collection of flags on a configuration setting.") .def(vector_indexing_suite<vistk::config_flags_t>()) ; class_<vistk::config_provider_t>("ConfigProvider" , "A provider key for a configuration setting."); class_<vistk::config_key_options_t>("ConfigKeyOptions" , "A collection of options on a configuration setting.") .def_readwrite("flags", &vistk::config_key_options_t::flags) .def_readwrite("provider", &vistk::config_key_options_t::provider) ; class_<vistk::config_key_t>("ConfigKey" , "A configuration key with its settings.") .def_readwrite("key_path", &vistk::config_key_t::key_path) .def_readwrite("options", &vistk::config_key_t::options) ; class_<vistk::config_value_t>("ConfigValue" , "A complete configuration setting.") .def_readwrite("key", &vistk::config_value_t::key) .def_readwrite("value", &vistk::config_value_t::value) ; class_<vistk::config_values_t>("ConfigValues" , "A collection of configuration settings.") /// \todo Need operator == on config_value_t //.def(vector_indexing_suite<vistk::config_values_t>()) ; class_<vistk::map_options_t>("MapOptions" , "A collection of options for a mapping.") .def_readwrite("flags", &vistk::map_options_t::flags) ; class_<vistk::input_map_t>("InputMap" , "An input mapping for a group.") .def_readwrite("options", &vistk::input_map_t::options) .def_readwrite("from_", &vistk::input_map_t::from) .def_readwrite("to", &vistk::input_map_t::to) ; class_<vistk::input_maps_t>("InputMaps" , "A collection of input mappings.") /// \todo Need operator == on input_map_t. //.def(vector_indexing_suite<vistk::input_maps_t>()) ; class_<vistk::output_map_t>("OutputMap" , "An output mapping for a group.") .def_readwrite("options", &vistk::output_map_t::options) .def_readwrite("from_", &vistk::output_map_t::from) .def_readwrite("to", &vistk::output_map_t::to) ; class_<vistk::output_maps_t>("OutputMaps" , "A collection of output mappings.") /// \todo Need operator == on output_map_t. //.def(vector_indexing_suite<vistk::output_maps_t>()) ; class_<vistk::config_pipe_block>("ConfigBlock" , "A block of configuration settings.") .def_readwrite("key", &vistk::config_pipe_block::key) .def_readwrite("values", &vistk::config_pipe_block::values) ; class_<vistk::process_pipe_block>("ProcessBlock" , "A block which declares a process.") .def_readwrite("name", &vistk::process_pipe_block::name) .def_readwrite("type", &vistk::process_pipe_block::type) .def_readwrite("config_values", &vistk::process_pipe_block::config_values) ; class_<vistk::connect_pipe_block>("ConnectBlock" , "A block which connects two ports together.") .def_readwrite("from_", &vistk::connect_pipe_block::from) .def_readwrite("to", &vistk::connect_pipe_block::to) ; class_<vistk::group_pipe_block>("GroupBlock" , "A block which declares a group within the pipeline.") .def_readwrite("name", &vistk::group_pipe_block::name) .def_readwrite("config_values", &vistk::group_pipe_block::config_values) .def_readwrite("input_mappings", &vistk::group_pipe_block::input_mappings) .def_readwrite("output_mappings", &vistk::group_pipe_block::output_mappings) ; class_<vistk::pipe_block>("PipeBlock" , "A block in a pipeline declaration file.") .add_property("config", &pipe_block_config, &pipe_block_config_set) .add_property("process", &pipe_block_process, &pipe_block_process_set) .add_property("connect", &pipe_block_connect, &pipe_block_connect_set) .add_property("group", &pipe_block_group, &pipe_block_group_set) ; class_<vistk::pipe_blocks>("PipeBlocks" , "A collection of pipeline blocks.") /// \todo Need operator == on pipe_block. //.def(vector_indexing_suite<vistk::pipe_blocks>()) ; def("load_pipe_file", &load_pipe_file , (arg("path")) , "Load pipe blocks from a file."); def("load_pipe", &load_pipe , (arg("stream"), arg("inc_root") = std::string()) , "Load pipe blocks from a stream."); } void translator(vistk::load_pipe_exception const& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } object pipe_block_config(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_CONFIG), block); } void pipe_block_config_set(vistk::pipe_block& block, vistk::config_pipe_block const& config) { block = config; } object pipe_block_process(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_PROCESS), block); } void pipe_block_process_set(vistk::pipe_block& block, vistk::process_pipe_block const& process) { block = process; } object pipe_block_connect(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_CONNECT), block); } void pipe_block_connect_set(vistk::pipe_block& block, vistk::connect_pipe_block const& connect) { block = connect; } object pipe_block_group(vistk::pipe_block const& block) { return boost::apply_visitor(block_visitor(block_visitor::BLOCK_GROUP), block); } void pipe_block_group_set(vistk::pipe_block& block, vistk::group_pipe_block const& group) { block = group; } vistk::pipe_blocks load_pipe_file(std::string const& path) { return vistk::load_pipe_blocks_from_file(boost::filesystem::path(path)); } vistk::pipe_blocks load_pipe(object const& stream, std::string const& inc_root) { pyistream istr(stream); return vistk::load_pipe_blocks(istr, boost::filesystem::path(inc_root)); } block_visitor ::block_visitor(block_t type) : block_type(type) { } block_visitor ::~block_visitor() { } object block_visitor ::operator () (vistk::config_pipe_block const& config_block) const { if (block_type == BLOCK_CONFIG) { return object(config_block); } return object(); } object block_visitor ::operator () (vistk::process_pipe_block const& process_block) const { if (block_type == BLOCK_PROCESS) { return object(process_block); } return object(); } object block_visitor ::operator () (vistk::connect_pipe_block const& connect_block) const { if (block_type == BLOCK_CONNECT) { return object(connect_block); } return object(); } object block_visitor ::operator () (vistk::group_pipe_block const& group_block) const { if (block_type == BLOCK_GROUP) { return object(group_block); } return object(); } <|endoftext|>
<commit_before>//===-- BuildDB-C-API.cpp ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include <llbuild/llbuild.h> #include "llbuild/BuildSystem/BuildKey.h" #include "llbuild/Core/BuildDB.h" #include "BuildKey-C-API-Private.h" #include <mutex> using namespace llbuild; using namespace llbuild::core; using namespace llbuild::buildsystem; namespace { class CAPIBuildDB: public BuildDBDelegate { private: /// The key table, for memory caching of key to key id mapping. llvm::StringMap<KeyID> keyTable; /// The mutex that protects the key table. std::mutex keyTableMutex; std::unique_ptr<BuildDB> _db; /// The mutex that protects the key cache. std::mutex keyCacheMutex; std::unordered_map<KeyID, CAPIBuildKey *> keyCache; bool keyCacheInitialized = false; CAPIBuildDB(StringRef path, uint32_t clientSchemaVersion, std::string *error_out) { _db = createSQLiteBuildDB(path, clientSchemaVersion, /* recreateUnmatchedVersion = */ false, error_out); } bool fetchKeysIfNecessary(std::string *error) { if (keyCacheInitialized) { return true; } std::vector<KeyType> keys; auto success = getKeys(keys, error); if (!error->empty()) { return success; } return success; } /// This method needs keyCacheMutex to be locked to ensure thread safety. void buildUpKeyCache(std::vector<KeyType> &allKeys) { if (keyCache.size() == allKeys.size()) { // There's not need to build up the cache multiple times return; } // Since we're holding the lock already, we don't lock in the destroy method destroyKeyCache(); keyCache = std::unordered_map<KeyID, CAPIBuildKey *>(); keyCache.reserve(allKeys.size()); for (auto rawKey: allKeys) { const KeyID engineID = getKeyID(rawKey); keyCache[engineID] = new CAPIBuildKey(BuildKey::fromData(rawKey), engineID); } keyCacheInitialized = true; } /// This method needs keyCacheMutex to be locked to ensure thread safety. void destroyKeyCache() { // every key in the keyCache is owned by the database, so we need to destroy them for (std::pair<KeyID, CAPIBuildKey *>element: keyCache) { llb_build_key_destroy((llb_build_key_t *)element.second); } } public: static CAPIBuildDB *create(StringRef path, uint32_t clientSchemaVersion, std::string *error_out) { auto databaseObject = new CAPIBuildDB(path, clientSchemaVersion, error_out); if (databaseObject->_db == nullptr || !error_out->empty() || !databaseObject->buildStarted(error_out)) { delete databaseObject; return nullptr; } // The delegate caches keys for key ids databaseObject->_db.get()->attachDelegate(databaseObject); return databaseObject; } ~CAPIBuildDB() { std::lock_guard<std::mutex> guard(keyCacheMutex); destroyKeyCache(); } CAPIBuildKey *buildKeyForIdentifier(KeyID keyIdentifier, std::string *error) { if (!fetchKeysIfNecessary(error)) { return nullptr; } std::lock_guard<std::mutex> guard(keyCacheMutex); auto buildKey = keyCache[keyIdentifier]; if (buildKey == nullptr) { *error = "Unable to get build key for identifier " + std::to_string(keyIdentifier); } return buildKey; } virtual const KeyID getKeyID(const KeyType& key) override { std::lock_guard<std::mutex> guard(keyTableMutex); // The RHS of the mapping is actually ignored, we use the StringMap's ptr // identity because it allows us to efficiently map back to the key string // in `getRuleInfoForKey`. auto it = keyTable.insert(std::make_pair(key.str(), KeyID::novalue())).first; return KeyID(it->getKey().data()); } virtual KeyType getKeyForID(const KeyID key) override { // Note that we don't need to lock `keyTable` here because the key entries // themselves don't change once created. return llvm::StringMapEntry<KeyID>::GetStringMapEntryFromKeyData( (const char*)(uintptr_t)key).getKey(); } bool lookupRuleResult(const KeyType &key, Result *result_out, std::string *error_out) { return _db.get()->lookupRuleResult(this->getKeyID(key), key, result_out, error_out); } bool buildStarted(std::string *error_out) { return _db.get()->buildStarted(error_out); } void buildComplete() { _db.get()->buildComplete(); } bool getKeys(std::vector<KeyType>& keys_out, std::string *error_out) { auto success = _db.get()->getKeys(keys_out, error_out); std::lock_guard<std::mutex> guard(keyCacheMutex); buildUpKeyCache(keys_out); return success; } bool getKeysWithResult(std::vector<KeyType> &keys_out, std::vector<Result> &results_out, std::string *error_out) { auto success = _db.get()->getKeysWithResult(keys_out, results_out, error_out); std::lock_guard<std::mutex> guard(keyCacheMutex); buildUpKeyCache(keys_out); return success; } }; const llb_data_t mapData(std::vector<uint8_t> input) { const auto data = input.data(); const auto size = sizeof(data) * input.size(); const auto newData = (uint8_t *)malloc(size); memcpy(newData, data, size); return llb_data_t { input.size(), newData }; } const llb_database_result_t mapResult(CAPIBuildDB &db, Result result) { auto count = result.dependencies.size(); auto size = sizeof(llb_build_key_t*) * count; llb_build_key_t **deps = (llb_build_key_t **)malloc(size); int index = 0; for (auto keyIDAndFlag: result.dependencies) { std::string error; auto buildKey = db.buildKeyForIdentifier(keyIDAndFlag.keyID, &error); if (!error.empty() || buildKey == nullptr) { assert(0 && "Got dependency from database and don't know this identifier."); continue; } deps[index] = (llb_build_key_t *)buildKey; index++; } return llb_database_result_t { mapData(result.value), result.signature.value, result.computedAt, result.builtAt, result.start, result.end, deps, static_cast<uint32_t>(count) }; } class CAPIBuildDBFetchResult { private: const std::vector<KeyID> keys; std::vector<llb_database_result_t> results; CAPIBuildDB &db; public: const bool hasResults; CAPIBuildDBFetchResult(const std::vector<KeyID>& keys, CAPIBuildDB& db): keys(keys), results({}), db(db), hasResults(false) {} CAPIBuildDBFetchResult(const std::vector<KeyID>& keys, const std::vector<llb_database_result_t> results, CAPIBuildDB &db): keys(keys), results(results), db(db), hasResults(true) { assert(keys.size() == results.size() && "The size of keys and results should be the same when initializing a database fetch result."); } CAPIBuildDBFetchResult(const CAPIBuildDBFetchResult&) LLBUILD_DELETED_FUNCTION; CAPIBuildDBFetchResult& operator=(const CAPIBuildDBFetchResult&) LLBUILD_DELETED_FUNCTION; size_t size() { return keys.size(); } llb_build_key_t *keyAtIndex(int32_t index) { std::string error; auto buildKey = db.buildKeyForIdentifier(keys[index], &error); if (!error.empty() || buildKey == nullptr) { assert(0 && "Couldn't find build key for unknown identifier"); } return (llb_build_key_t *)buildKey; } llb_database_result_t *resultAtIndex(int32_t index) { return &results[index]; } }; } void llb_database_destroy_result(llb_database_result_t *result) {\ llb_data_destroy(&result->value); delete result->dependencies; } const llb_database_t* llb_database_open( char *path, uint32_t clientSchemaVersion, llb_data_t *error_out) { std::string error; auto database = CAPIBuildDB::create(StringRef(path), clientSchemaVersion, &error); if (!error.empty()) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); delete database; return nullptr; } return (llb_database_t *)database; } void llb_database_destroy(llb_database_t *database) { auto db = (CAPIBuildDB *)database; db->buildComplete(); delete db; } bool llb_database_lookup_rule_result(llb_database_t *database, llb_build_key_t *key, llb_database_result_t *result_out, llb_data_t *error_out) { auto db = (CAPIBuildDB *)database; std::string error; Result result; auto stored = db->lookupRuleResult(((CAPIBuildKey *)key)->getInternalBuildKey().toData(), &result, &error); if (result_out) { *result_out = mapResult(*db, result); } if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); } return stored; } llb_database_key_id llb_database_fetch_result_get_count(llb_database_fetch_result_t *result) { auto resultKeys = (CAPIBuildDBFetchResult *)result; return resultKeys->size(); } llb_build_key_t * llb_database_fetch_result_get_key_at_index(llb_database_fetch_result_t *result, int32_t index) { auto resultKeys = (CAPIBuildDBFetchResult *)result; return resultKeys->keyAtIndex(index); } bool llb_database_fetch_result_contains_rule_results(llb_database_fetch_result_t *result) { return ((CAPIBuildDBFetchResult *)result)->hasResults; } llb_database_result_t *llb_database_fetch_result_get_result_at_index(llb_database_fetch_result_t *result, int32_t index) { auto resultKeys = (CAPIBuildDBFetchResult *)result; // TODO: Check if results were fetched return resultKeys->resultAtIndex(index); } void llb_database_destroy_fetch_result(llb_database_fetch_result_t *result) { delete (CAPIBuildDBFetchResult *)result; } bool llb_database_get_keys(llb_database_t *database, llb_database_fetch_result_t **keysResult_out, llb_data_t *error_out) { auto db = (CAPIBuildDB *)database; std::vector<KeyType> keys; std::string error; auto success = db->getKeys(keys, &error); if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); return success; } std::vector<KeyID> buildKeys; buildKeys.reserve(keys.size()); for (auto rawKey: keys) { buildKeys.emplace_back(db->getKeyID(rawKey)); } auto resultKeys = new CAPIBuildDBFetchResult(buildKeys, *db); *keysResult_out = (llb_database_fetch_result_t *)resultKeys; return success; } bool llb_database_get_keys_and_results(llb_database_t *database, llb_database_fetch_result_t *_Nullable *_Nonnull keysAndResults_out, llb_data_t *_Nullable error_out) { auto db = (CAPIBuildDB *)database; std::vector<KeyType> keys; std::vector<Result> results; std::string error; auto success = db->getKeysWithResult(keys, results, &error); if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t *)strdup(error.c_str()); return success; } assert(keys.size() == results.size()); std::vector<KeyID> keyIDs; keyIDs.reserve(keys.size()); std::vector<llb_database_result_t> databaseResults; databaseResults.reserve(results.size()); for (size_t index = 0; index < keys.size(); index++) { keyIDs.emplace_back(db->getKeyID(keys[index])); databaseResults.emplace_back(mapResult(*db, results[index])); } auto keysAndResults = new CAPIBuildDBFetchResult(keyIDs, databaseResults, *db); *keysAndResults_out = (llb_database_fetch_result_t *)keysAndResults; return success; } <commit_msg>[BuildDB-C-API] Fix buffer read overflow<commit_after>//===-- BuildDB-C-API.cpp ---------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2019 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include <llbuild/llbuild.h> #include "llbuild/BuildSystem/BuildKey.h" #include "llbuild/Core/BuildDB.h" #include "BuildKey-C-API-Private.h" #include <mutex> using namespace llbuild; using namespace llbuild::core; using namespace llbuild::buildsystem; namespace { class CAPIBuildDB: public BuildDBDelegate { private: /// The key table, for memory caching of key to key id mapping. llvm::StringMap<KeyID> keyTable; /// The mutex that protects the key table. std::mutex keyTableMutex; std::unique_ptr<BuildDB> _db; /// The mutex that protects the key cache. std::mutex keyCacheMutex; std::unordered_map<KeyID, CAPIBuildKey *> keyCache; bool keyCacheInitialized = false; CAPIBuildDB(StringRef path, uint32_t clientSchemaVersion, std::string *error_out) { _db = createSQLiteBuildDB(path, clientSchemaVersion, /* recreateUnmatchedVersion = */ false, error_out); } bool fetchKeysIfNecessary(std::string *error) { if (keyCacheInitialized) { return true; } std::vector<KeyType> keys; auto success = getKeys(keys, error); if (!error->empty()) { return success; } return success; } /// This method needs keyCacheMutex to be locked to ensure thread safety. void buildUpKeyCache(std::vector<KeyType> &allKeys) { if (keyCache.size() == allKeys.size()) { // There's not need to build up the cache multiple times return; } // Since we're holding the lock already, we don't lock in the destroy method destroyKeyCache(); keyCache = std::unordered_map<KeyID, CAPIBuildKey *>(); keyCache.reserve(allKeys.size()); for (auto rawKey: allKeys) { const KeyID engineID = getKeyID(rawKey); keyCache[engineID] = new CAPIBuildKey(BuildKey::fromData(rawKey), engineID); } keyCacheInitialized = true; } /// This method needs keyCacheMutex to be locked to ensure thread safety. void destroyKeyCache() { // every key in the keyCache is owned by the database, so we need to destroy them for (std::pair<KeyID, CAPIBuildKey *>element: keyCache) { llb_build_key_destroy((llb_build_key_t *)element.second); } } public: static CAPIBuildDB *create(StringRef path, uint32_t clientSchemaVersion, std::string *error_out) { auto databaseObject = new CAPIBuildDB(path, clientSchemaVersion, error_out); if (databaseObject->_db == nullptr || !error_out->empty() || !databaseObject->buildStarted(error_out)) { delete databaseObject; return nullptr; } // The delegate caches keys for key ids databaseObject->_db.get()->attachDelegate(databaseObject); return databaseObject; } ~CAPIBuildDB() { std::lock_guard<std::mutex> guard(keyCacheMutex); destroyKeyCache(); } CAPIBuildKey *buildKeyForIdentifier(KeyID keyIdentifier, std::string *error) { if (!fetchKeysIfNecessary(error)) { return nullptr; } std::lock_guard<std::mutex> guard(keyCacheMutex); auto buildKey = keyCache[keyIdentifier]; if (buildKey == nullptr) { *error = "Unable to get build key for identifier " + std::to_string(keyIdentifier); } return buildKey; } virtual const KeyID getKeyID(const KeyType& key) override { std::lock_guard<std::mutex> guard(keyTableMutex); // The RHS of the mapping is actually ignored, we use the StringMap's ptr // identity because it allows us to efficiently map back to the key string // in `getRuleInfoForKey`. auto it = keyTable.insert(std::make_pair(key.str(), KeyID::novalue())).first; return KeyID(it->getKey().data()); } virtual KeyType getKeyForID(const KeyID key) override { // Note that we don't need to lock `keyTable` here because the key entries // themselves don't change once created. return llvm::StringMapEntry<KeyID>::GetStringMapEntryFromKeyData( (const char*)(uintptr_t)key).getKey(); } bool lookupRuleResult(const KeyType &key, Result *result_out, std::string *error_out) { return _db.get()->lookupRuleResult(this->getKeyID(key), key, result_out, error_out); } bool buildStarted(std::string *error_out) { return _db.get()->buildStarted(error_out); } void buildComplete() { _db.get()->buildComplete(); } bool getKeys(std::vector<KeyType>& keys_out, std::string *error_out) { auto success = _db.get()->getKeys(keys_out, error_out); std::lock_guard<std::mutex> guard(keyCacheMutex); buildUpKeyCache(keys_out); return success; } bool getKeysWithResult(std::vector<KeyType> &keys_out, std::vector<Result> &results_out, std::string *error_out) { auto success = _db.get()->getKeysWithResult(keys_out, results_out, error_out); std::lock_guard<std::mutex> guard(keyCacheMutex); buildUpKeyCache(keys_out); return success; } }; const llb_data_t mapData(std::vector<uint8_t> input) { const auto size = sizeof(input.front()) * input.size(); const auto newData = (uint8_t *)malloc(size); memcpy(newData, input.data(), size); return llb_data_t { input.size(), newData }; } const llb_database_result_t mapResult(CAPIBuildDB &db, Result result) { auto count = result.dependencies.size(); auto size = sizeof(llb_build_key_t*) * count; llb_build_key_t **deps = (llb_build_key_t **)malloc(size); int index = 0; for (auto keyIDAndFlag: result.dependencies) { std::string error; auto buildKey = db.buildKeyForIdentifier(keyIDAndFlag.keyID, &error); if (!error.empty() || buildKey == nullptr) { assert(0 && "Got dependency from database and don't know this identifier."); continue; } deps[index] = (llb_build_key_t *)buildKey; index++; } return llb_database_result_t { mapData(result.value), result.signature.value, result.computedAt, result.builtAt, result.start, result.end, deps, static_cast<uint32_t>(count) }; } class CAPIBuildDBFetchResult { private: const std::vector<KeyID> keys; std::vector<llb_database_result_t> results; CAPIBuildDB &db; public: const bool hasResults; CAPIBuildDBFetchResult(const std::vector<KeyID>& keys, CAPIBuildDB& db): keys(keys), results({}), db(db), hasResults(false) {} CAPIBuildDBFetchResult(const std::vector<KeyID>& keys, const std::vector<llb_database_result_t> results, CAPIBuildDB &db): keys(keys), results(results), db(db), hasResults(true) { assert(keys.size() == results.size() && "The size of keys and results should be the same when initializing a database fetch result."); } CAPIBuildDBFetchResult(const CAPIBuildDBFetchResult&) LLBUILD_DELETED_FUNCTION; CAPIBuildDBFetchResult& operator=(const CAPIBuildDBFetchResult&) LLBUILD_DELETED_FUNCTION; size_t size() { return keys.size(); } llb_build_key_t *keyAtIndex(int32_t index) { std::string error; auto buildKey = db.buildKeyForIdentifier(keys[index], &error); if (!error.empty() || buildKey == nullptr) { assert(0 && "Couldn't find build key for unknown identifier"); } return (llb_build_key_t *)buildKey; } llb_database_result_t *resultAtIndex(int32_t index) { return &results[index]; } }; } void llb_database_destroy_result(llb_database_result_t *result) {\ llb_data_destroy(&result->value); delete result->dependencies; } const llb_database_t* llb_database_open( char *path, uint32_t clientSchemaVersion, llb_data_t *error_out) { std::string error; auto database = CAPIBuildDB::create(StringRef(path), clientSchemaVersion, &error); if (!error.empty()) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); delete database; return nullptr; } return (llb_database_t *)database; } void llb_database_destroy(llb_database_t *database) { auto db = (CAPIBuildDB *)database; db->buildComplete(); delete db; } bool llb_database_lookup_rule_result(llb_database_t *database, llb_build_key_t *key, llb_database_result_t *result_out, llb_data_t *error_out) { auto db = (CAPIBuildDB *)database; std::string error; Result result; auto stored = db->lookupRuleResult(((CAPIBuildKey *)key)->getInternalBuildKey().toData(), &result, &error); if (result_out) { *result_out = mapResult(*db, result); } if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); } return stored; } llb_database_key_id llb_database_fetch_result_get_count(llb_database_fetch_result_t *result) { auto resultKeys = (CAPIBuildDBFetchResult *)result; return resultKeys->size(); } llb_build_key_t * llb_database_fetch_result_get_key_at_index(llb_database_fetch_result_t *result, int32_t index) { auto resultKeys = (CAPIBuildDBFetchResult *)result; return resultKeys->keyAtIndex(index); } bool llb_database_fetch_result_contains_rule_results(llb_database_fetch_result_t *result) { return ((CAPIBuildDBFetchResult *)result)->hasResults; } llb_database_result_t *llb_database_fetch_result_get_result_at_index(llb_database_fetch_result_t *result, int32_t index) { auto resultKeys = (CAPIBuildDBFetchResult *)result; // TODO: Check if results were fetched return resultKeys->resultAtIndex(index); } void llb_database_destroy_fetch_result(llb_database_fetch_result_t *result) { delete (CAPIBuildDBFetchResult *)result; } bool llb_database_get_keys(llb_database_t *database, llb_database_fetch_result_t **keysResult_out, llb_data_t *error_out) { auto db = (CAPIBuildDB *)database; std::vector<KeyType> keys; std::string error; auto success = db->getKeys(keys, &error); if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t*)strdup(error.c_str()); return success; } std::vector<KeyID> buildKeys; buildKeys.reserve(keys.size()); for (auto rawKey: keys) { buildKeys.emplace_back(db->getKeyID(rawKey)); } auto resultKeys = new CAPIBuildDBFetchResult(buildKeys, *db); *keysResult_out = (llb_database_fetch_result_t *)resultKeys; return success; } bool llb_database_get_keys_and_results(llb_database_t *database, llb_database_fetch_result_t *_Nullable *_Nonnull keysAndResults_out, llb_data_t *_Nullable error_out) { auto db = (CAPIBuildDB *)database; std::vector<KeyType> keys; std::vector<Result> results; std::string error; auto success = db->getKeysWithResult(keys, results, &error); if (!error.empty() && error_out) { error_out->length = error.size(); error_out->data = (const uint8_t *)strdup(error.c_str()); return success; } assert(keys.size() == results.size()); std::vector<KeyID> keyIDs; keyIDs.reserve(keys.size()); std::vector<llb_database_result_t> databaseResults; databaseResults.reserve(results.size()); for (size_t index = 0; index < keys.size(); index++) { keyIDs.emplace_back(db->getKeyID(keys[index])); databaseResults.emplace_back(mapResult(*db, results[index])); } auto keysAndResults = new CAPIBuildDBFetchResult(keyIDs, databaseResults, *db); *keysAndResults_out = (llb_database_fetch_result_t *)keysAndResults; return success; } <|endoftext|>
<commit_before>#include "stm32f4xx_hal.h" #include "stm32f4xx.h" #include "stm32f4xx_it.h" #include "dcf77.h" #include "cRCSwitch.h" #include "cBsp.h" #include "cMaster.h" extern volatile uint8_t UART_buffer_pointer; extern volatile uint8_t UART_cmdBuffer[100]; static uint64_t lastReceivedUARTChar=0; static bool binaryMode=false; static uint8_t binaryMessageSize; extern uint64_t epochtimer; //extern ADC_HandleTypeDef AdcHandle; //extern __IO uint16_t uhADCxConvertedValue; extern "C" void SysTick_Handler(void) { HAL_IncTick(); HAL_SYSTICK_IRQHandler(); #ifdef DCF77 sensact::cDCF77::CallEveryMillisecond(HAL_GetTick()); #endif if(HAL_GetTick()%1000 ==0) { epochtimer++; } } void ADC_IRQHandler(void) { //HAL_ADC_IRQHandler(&AdcHandle); } /* void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* AdcHandle) { // Get the converted value of regular channel uhADCxConvertedValue = HAL_ADC_GetValue(AdcHandle); } */ void DMA2_Stream0_IRQHandler(void) { //HAL_DMA_IRQHandler(AdcHandle.DMA_Handle); } void EXTI9_5_IRQHandler(void) { if(__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_5) != RESET) { __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_5); drivers::cRCSwitch::handleInterrupt(); } } void USART3_IRQHandler(void) { if(READ_BIT(USART3->SR, USART_SR_RXNE)) { volatile uint8_t chartoreceive = (uint8_t)(USART3->DR); /* Receive data, clear flag */ if(binaryMode && epochtimer-lastReceivedUARTChar > 1000) { //reset binary mode after some time without data binaryMode=false; UART_buffer_pointer=0; } if(chartoreceive==0x01) { binaryMode=true; UART_buffer_pointer=0; } if(binaryMode) { if(UART_buffer_pointer==0) { UART_buffer_pointer++; } else if(UART_buffer_pointer==1) { binaryMessageSize=chartoreceive; UART_buffer_pointer++; } else { UART_cmdBuffer[UART_buffer_pointer-2]=chartoreceive; UART_buffer_pointer++; if(UART_buffer_pointer>=binaryMessageSize) { uint16_t appId = *((uint16_t*)UART_cmdBuffer); uint8_t commandId = UART_cmdBuffer[2]; sensact::cMaster::SendCommandToMessageBus(epochtimer, (sensact::eApplicationID)appId, (sensact::eCommandType)commandId, (uint8_t*)&UART_cmdBuffer[3], (uint8_t)(binaryMessageSize-3)); binaryMode=false; UART_buffer_pointer=0; } } } else { if(chartoreceive == '\r') { return; } else if(chartoreceive == '\n') { UART_buffer_pointer = UART_BUFFER_SIZE; } else if(UART_buffer_pointer<UART_BUFFER_SIZE) { UART_cmdBuffer[UART_buffer_pointer]=chartoreceive; UART_buffer_pointer++; } } } //USART1->ICR = UINT32_MAX;//clear all flags } <commit_msg>Fixed Binary command parser<commit_after>#include "stm32f4xx_hal.h" #include "stm32f4xx.h" #include "stm32f4xx_it.h" #include "dcf77.h" #include "cRCSwitch.h" #include "cBsp.h" #include "cMaster.h" extern volatile uint8_t UART_buffer_pointer; extern volatile uint8_t UART_cmdBuffer[100]; static uint64_t lastReceivedUARTChar=0; static bool binaryMode=false; static uint8_t binaryMessageSize; extern uint64_t epochtimer; //extern ADC_HandleTypeDef AdcHandle; //extern __IO uint16_t uhADCxConvertedValue; extern "C" void SysTick_Handler(void) { HAL_IncTick(); HAL_SYSTICK_IRQHandler(); #ifdef DCF77 sensact::cDCF77::CallEveryMillisecond(HAL_GetTick()); #endif if(HAL_GetTick()%1000 ==0) { epochtimer++; } } void ADC_IRQHandler(void) { //HAL_ADC_IRQHandler(&AdcHandle); } /* void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* AdcHandle) { // Get the converted value of regular channel uhADCxConvertedValue = HAL_ADC_GetValue(AdcHandle); } */ void DMA2_Stream0_IRQHandler(void) { //HAL_DMA_IRQHandler(AdcHandle.DMA_Handle); } void EXTI9_5_IRQHandler(void) { if(__HAL_GPIO_EXTI_GET_IT(GPIO_PIN_5) != RESET) { __HAL_GPIO_EXTI_CLEAR_IT(GPIO_PIN_5); drivers::cRCSwitch::handleInterrupt(); } } void USART3_IRQHandler(void) { if(READ_BIT(USART3->SR, USART_SR_RXNE)) { volatile uint8_t chartoreceive = (uint8_t)(USART3->DR); /* Receive data, clear flag */ if(binaryMode && epochtimer-lastReceivedUARTChar > 1000) { //reset binary mode after some time without data binaryMode=false; UART_buffer_pointer=0; } if(chartoreceive==0x01) { binaryMode=true; UART_buffer_pointer=0; } if(binaryMode) { if(UART_buffer_pointer==0) { UART_buffer_pointer++; } else if(UART_buffer_pointer==1) { binaryMessageSize=chartoreceive; UART_buffer_pointer++; } else { UART_cmdBuffer[UART_buffer_pointer-2]=chartoreceive; UART_buffer_pointer++; if(UART_buffer_pointer>=binaryMessageSize) { uint16_t appId = *((uint16_t*)UART_cmdBuffer); uint8_t commandId = UART_cmdBuffer[2]; sensact::cMaster::SendCommandToMessageBus(epochtimer, (sensact::eApplicationID)appId, (sensact::eCommandType)commandId, (uint8_t*)&UART_cmdBuffer[3], (uint8_t)(binaryMessageSize-5)); binaryMode=false; UART_buffer_pointer=0; } } } else { if(chartoreceive == '\r') { return; } else if(chartoreceive == '\n') { UART_buffer_pointer = UART_BUFFER_SIZE; } else if(UART_buffer_pointer<UART_BUFFER_SIZE) { UART_cmdBuffer[UART_buffer_pointer]=chartoreceive; UART_buffer_pointer++; } } } //USART1->ICR = UINT32_MAX;//clear all flags } <|endoftext|>
<commit_before>#include "SCTPSocket.h" #include "TempFailure.h" #include "SocketUtils.h" #include <netinet/in.h> #include <poll.h> #include <cstring> using namespace NET; SCTPSocket::SCTPSocket( unsigned numOutStreams /* = 10 */, unsigned maxInStreams /* = 65535 */, unsigned maxAttempts /* = 4 */, unsigned maxInitTimeout /* = 0 */) : InternetSocket( STREAM, IPPROTO_SCTP) { setInitValues( numOutStreams, maxInStreams, maxAttempts, maxInitTimeout); } SCTPSocket::SCTPSocket( Handle handle) : InternetSocket( handle.release() ) {} int SCTPSocket::bind( const std::vector<std::string>& localAddresses, unsigned short localPort /* = 0 */) { sockaddr_in *dest = new sockaddr_in[localAddresses.size()]; std::vector<std::string>::const_iterator it; std::vector<std::string>::const_iterator end; int i = 0; for( it = localAddresses.begin(), end = localAddresses.end(); it != end; ++it) { fillAddress( *it, localPort, dest[i++]); } int ret = sctp_bindx( m_socket, reinterpret_cast<sockaddr*>(dest), localAddresses.size(), SCTP_BINDX_ADD_ADDR); delete[] dest; if(ret < 0) throw SocketException("SCTPSocket::bind bindx failed"); return ret; } int SCTPSocket::connect( const std::vector<std::string>& foreignAddresses, unsigned short foreignPort /* = 0 */) { sockaddr_in *dest = new sockaddr_in[foreignAddresses.size()]; std::vector<std::string>::const_iterator it; std::vector<std::string>::const_iterator end; int i = 0; for( it = foreignAddresses.begin(), end = foreignAddresses.end(); it != end; ++it) { fillAddress( *it, foreignPort, dest[i++]); } int ret = sctp_connectx( m_socket, reinterpret_cast<sockaddr*>(dest), foreignAddresses.size()); delete[] dest; if(ret < 0) throw SocketException("SCTPSocket::SCTPSocket connect failed"); } int SCTPSocket::state() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::state failed"); return status.sstat_state; } int SCTPSocket::notAckedData() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::notAckedData failed"); return status.sstat_unackdata; } int SCTPSocket::pendingData() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::pendingData failed"); return status.sstat_penddata; } unsigned SCTPSocket::inStreams() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::inStreams failed"); return status.sstat_instrms; } unsigned SCTPSocket::outStreams() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::outStreams failed"); return status.sstat_outstrms; } unsigned SCTPSocket::fragmentationPoint() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::fragmentationPoint failed"); return status.sstat_fragmentation_point; } std::string SCTPSocket::primaryAddress() const { } int SCTPSocket::send( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */, unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */) { int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr, stream, ttl, context); if( ret < 0) throw SocketException("SCTPSocket::send failed"); else if (ret < length) throw SocketException("Interpreted SCTP false, sent a packet fragement"); return ret; } int SCTPSocket::sendUnordered( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */, unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */) { int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr + SCTP_UNORDERED, stream, ttl, context); if( ret < 0) throw SocketException("SCTPSocket::send failed"); else if (ret < length) throw SocketException("Interpreted SCTP false, sent a packet fragement"); return ret; } int SCTPSocket::receive( void* data, int maxLen, unsigned& stream) { struct sctp_sndrcvinfo info; int ret; if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0) throw SocketException("SCTPSocket::receive failed"); stream = info.sinfo_stream; return ret; } int SCTPSocket::receive( void* data, int maxLen, unsigned& stream, receiveFlag& flag) { struct sctp_sndrcvinfo info; int ret; if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0) throw SocketException("SCTPSocket::receive failed"); stream = info.sinfo_stream; // flag = info.sinfo_flags; return ret; } int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, unsigned timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return 0; if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)"); if( poll.revents & POLLRDHUP) m_peerDisconnected = true; if( poll.revents & POLLIN || poll.revents & POLLPRI) return receive( data, maxLen, stream); return 0; } int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, receiveFlag& flag, unsigned timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return 0; if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)"); if( poll.revents & POLLRDHUP) m_peerDisconnected = true; if( poll.revents & POLLIN || poll.revents & POLLPRI) return receive( data, maxLen, stream, flag); return 0; } void SCTPSocket::listen( int backlog /* = 5 */) { int ret = ::listen( m_socket, backlog); if( ret < 0) throw SocketException("listen failed, most likely another socket is already listening on the same port"); } SCTPSocket::Handle SCTPSocket::accept() const { int ret = ::accept( m_socket, 0, 0); if( ret <= 0) throw SocketException("SCTPSocket::accept failed"); return Handle(ret); } SCTPSocket::Handle SCTPSocket::timedAccept( unsigned timeout) const { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return Handle(0); if( ret < 0) throw SocketException("SCTPSocket::timedAccept failed (poll)"); ret = ::accept( m_socket, 0, 0); if( ret <= 0) throw SocketException("SCTPSocket::timedAccept failed (accept)"); return Handle(ret); } void SCTPSocket::setInitValues( unsigned numOutStreams, unsigned maxInStreams, unsigned maxAttempts, unsigned maxInitTimeout) { struct sctp_initmsg init; std::memset( &init, 0, sizeof(init)); init.sinit_num_ostreams = numOutStreams; init.sinit_max_instreams = maxInStreams; init.sinit_max_attempts = maxAttempts; init.sinit_max_init_timeo = maxInitTimeout; setsockopt( m_socket, IPPROTO_SCTP, SCTP_INITMSG, &init, sizeof(init)); } <commit_msg>simplify SCTP::connect and bind for multiple addresses<commit_after>#include "SCTPSocket.h" #include "TempFailure.h" #include "SocketUtils.h" #include <netinet/in.h> #include <poll.h> #include <cstring> using namespace NET; SCTPSocket::SCTPSocket( unsigned numOutStreams /* = 10 */, unsigned maxInStreams /* = 65535 */, unsigned maxAttempts /* = 4 */, unsigned maxInitTimeout /* = 0 */) : InternetSocket( STREAM, IPPROTO_SCTP) { setInitValues( numOutStreams, maxInStreams, maxAttempts, maxInitTimeout); } SCTPSocket::SCTPSocket( Handle handle) : InternetSocket( handle.release() ) {} int SCTPSocket::bind( const std::vector<std::string>& localAddresses, unsigned short localPort /* = 0 */) { size_t size = localAddresses.size(); sockaddr_in *dest = new sockaddr_in[size]; for( int i = 0; i < size; ++i) fillAddress( localAddresses[i], localPort, dest[i]); int ret = sctp_bindx( m_socket, reinterpret_cast<sockaddr*>(dest), size, SCTP_BINDX_ADD_ADDR); delete[] dest; if(ret < 0) throw SocketException("SCTPSocket::bind bindx failed"); return ret; } int SCTPSocket::connect( const std::vector<std::string>& foreignAddresses, unsigned short foreignPort /* = 0 */) { size_t size = foreignAddresses.size(); sockaddr_in *dest = new sockaddr_in[size]; for( int i = 0; i < size; ++i) fillAddress( foreignAddresses[i], foreignPort, dest[i]); int ret = sctp_connectx( m_socket, reinterpret_cast<sockaddr*>(dest), size); delete[] dest; if(ret < 0) throw SocketException("SCTPSocket::SCTPSocket connect failed"); } int SCTPSocket::state() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::state failed"); return status.sstat_state; } int SCTPSocket::notAckedData() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::notAckedData failed"); return status.sstat_unackdata; } int SCTPSocket::pendingData() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::pendingData failed"); return status.sstat_penddata; } unsigned SCTPSocket::inStreams() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::inStreams failed"); return status.sstat_instrms; } unsigned SCTPSocket::outStreams() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::outStreams failed"); return status.sstat_outstrms; } unsigned SCTPSocket::fragmentationPoint() const { struct sctp_status status; socklen_t size = sizeof(status); if( getsockopt( m_socket, IPPROTO_SCTP, SCTP_STATUS, &status, &size) < 0) throw SocketException("SCTPSocket::fragmentationPoint failed"); return status.sstat_fragmentation_point; } std::string SCTPSocket::primaryAddress() const { } int SCTPSocket::send( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */, unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */) { int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr, stream, ttl, context); if( ret < 0) throw SocketException("SCTPSocket::send failed"); else if (ret < length) throw SocketException("Interpreted SCTP false, sent a packet fragement"); return ret; } int SCTPSocket::sendUnordered( const void* data, int length, unsigned stream, unsigned ttl /* = 0 */, unsigned context /* = 0 */, unsigned ppid /* = 0 */, abortFlag abort /* = KEEPALIVE */, switchAddressFlag switchAddr /* = KEEP_PRIMARY */) { int ret = sctp_sendmsg( m_socket, data, length, NULL, 0, ppid, abort + switchAddr + SCTP_UNORDERED, stream, ttl, context); if( ret < 0) throw SocketException("SCTPSocket::send failed"); else if (ret < length) throw SocketException("Interpreted SCTP false, sent a packet fragement"); return ret; } int SCTPSocket::receive( void* data, int maxLen, unsigned& stream) { struct sctp_sndrcvinfo info; int ret; if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0) throw SocketException("SCTPSocket::receive failed"); stream = info.sinfo_stream; return ret; } int SCTPSocket::receive( void* data, int maxLen, unsigned& stream, receiveFlag& flag) { struct sctp_sndrcvinfo info; int ret; if( (ret = sctp_recvmsg( m_socket, data, maxLen, 0, 0, &info, 0)) <= 0) throw SocketException("SCTPSocket::receive failed"); stream = info.sinfo_stream; // flag = info.sinfo_flags; return ret; } int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, unsigned timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return 0; if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)"); if( poll.revents & POLLRDHUP) m_peerDisconnected = true; if( poll.revents & POLLIN || poll.revents & POLLPRI) return receive( data, maxLen, stream); return 0; } int SCTPSocket::timedReceive( void* data, int maxLen, unsigned& stream, receiveFlag& flag, unsigned timeout) { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN | POLLPRI | POLLRDHUP; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return 0; if( ret < 0) throw SocketException("SCTPSocket::receive failed (poll)"); if( poll.revents & POLLRDHUP) m_peerDisconnected = true; if( poll.revents & POLLIN || poll.revents & POLLPRI) return receive( data, maxLen, stream, flag); return 0; } void SCTPSocket::listen( int backlog /* = 5 */) { int ret = ::listen( m_socket, backlog); if( ret < 0) throw SocketException("listen failed, most likely another socket is already listening on the same port"); } SCTPSocket::Handle SCTPSocket::accept() const { int ret = ::accept( m_socket, 0, 0); if( ret <= 0) throw SocketException("SCTPSocket::accept failed"); return Handle(ret); } SCTPSocket::Handle SCTPSocket::timedAccept( unsigned timeout) const { struct pollfd poll; poll.fd = m_socket; poll.events = POLLIN; int ret = TEMP_FAILURE_RETRY (::poll( &poll, 1, timeout)); if( ret == 0) return Handle(0); if( ret < 0) throw SocketException("SCTPSocket::timedAccept failed (poll)"); ret = ::accept( m_socket, 0, 0); if( ret <= 0) throw SocketException("SCTPSocket::timedAccept failed (accept)"); return Handle(ret); } void SCTPSocket::setInitValues( unsigned numOutStreams, unsigned maxInStreams, unsigned maxAttempts, unsigned maxInitTimeout) { struct sctp_initmsg init; std::memset( &init, 0, sizeof(init)); init.sinit_num_ostreams = numOutStreams; init.sinit_max_instreams = maxInStreams; init.sinit_max_attempts = maxAttempts; init.sinit_max_init_timeo = maxInitTimeout; setsockopt( m_socket, IPPROTO_SCTP, SCTP_INITMSG, &init, sizeof(init)); } <|endoftext|>
<commit_before>#include "aquila/global.h" #include "aquila/functions.h" #include "aquila/ml/Dtw.h" #include <unittestpp.h> #include <vector> SUITE(Dtw) { TEST(DistanceToItself) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 1, 2}, arr2[SIZE] = {1, 2, 3}; std::vector<double> v1(arr1, arr1 + SIZE), v2(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(v1); from.push_back(v2); to.push_back(v1); to.push_back(v2); Aquila::Dtw dtw; double distance = dtw.getDistance(from, to); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(ZeroDiagonalDistance) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(zeros); from.push_back(ones); from.push_back(ones); to.push_back(zeros); to.push_back(ones); to.push_back(ones); /** * this will give the following local Manhattan distances: * * 3 0 0 * 3 0 0 * 0 3 3 * * and the lowest-cost path will be on the diagonal. */ Aquila::Dtw dtw(Aquila::manhattanDistance); double distance = dtw.getDistance(from, to); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(NonZeroDiagonalDistance) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to.push_back(ones); to.push_back(ones); to.push_back(ones); /** * this will give the following distances (using Manhattan for local): * * local accumulated * * 3 3 3 3 6 9 * 3 3 3 3 6 6 * 3 3 3 3 3 3 * * and the lowest-cost path will still be on the diagonal, but this time * the distance is a non-zero value. */ Aquila::Dtw dtw(Aquila::manhattanDistance); double distance = dtw.getDistance(from, to); CHECK_CLOSE(9.0, distance, 0.000001); } TEST(Similarity) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to1, to2; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to1.push_back(zeros); to1.push_back(zeros); to1.push_back(ones); to2.push_back(zeros); to2.push_back(ones); to2.push_back(ones); /** * 000 is more "similar" to 001 than 011, therefore distance between * from and to1 should be smaller */ Aquila::Dtw dtw; double distance1 = dtw.getDistance(from, to1); double distance2 = dtw.getDistance(from, to2); CHECK(distance1 < distance2); } TEST(RectangularSimilarity) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to1, to2; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to1.push_back(zeros); to1.push_back(ones); to2.push_back(ones); to2.push_back(ones); /** * 000 is more "similar" to 01 than 11, therefore distance between * from and to1 should be smaller */ Aquila::Dtw dtw; double distance1 = dtw.getDistance(from, to1); double distance2 = dtw.getDistance(from, to2); CHECK(distance1 < distance2); } } <commit_msg>Test for path in DTW of size 1x1.<commit_after>#include "aquila/global.h" #include "aquila/functions.h" #include "aquila/ml/Dtw.h" #include <unittestpp.h> #include <vector> SUITE(Dtw) { TEST(DistanceToItself) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 1, 2}, arr2[SIZE] = {1, 2, 3}; std::vector<double> v1(arr1, arr1 + SIZE), v2(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(v1); from.push_back(v2); to.push_back(v1); to.push_back(v2); Aquila::Dtw dtw; double distance = dtw.getDistance(from, to); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(ZeroDiagonalDistance) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(zeros); from.push_back(ones); from.push_back(ones); to.push_back(zeros); to.push_back(ones); to.push_back(ones); /** * this will give the following local Manhattan distances: * * 3 0 0 * 3 0 0 * 0 3 3 * * and the lowest-cost path will be on the diagonal. */ Aquila::Dtw dtw(Aquila::manhattanDistance); double distance = dtw.getDistance(from, to); CHECK_CLOSE(0.0, distance, 0.000001); } TEST(NonZeroDiagonalDistance) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to.push_back(ones); to.push_back(ones); to.push_back(ones); /** * this will give the following distances (using Manhattan for local): * * local accumulated * * 3 3 3 3 6 9 * 3 3 3 3 6 6 * 3 3 3 3 3 3 * * and the lowest-cost path will still be on the diagonal, but this time * the distance is a non-zero value. */ Aquila::Dtw dtw(Aquila::manhattanDistance); double distance = dtw.getDistance(from, to); CHECK_CLOSE(9.0, distance, 0.000001); } TEST(Similarity) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to1, to2; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to1.push_back(zeros); to1.push_back(zeros); to1.push_back(ones); to2.push_back(zeros); to2.push_back(ones); to2.push_back(ones); /** * 000 is more "similar" to 001 than 011, therefore distance between * from and to1 should be smaller */ Aquila::Dtw dtw; double distance1 = dtw.getDistance(from, to1); double distance2 = dtw.getDistance(from, to2); CHECK(distance1 < distance2); } TEST(RectangularSimilarity) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to1, to2; from.push_back(zeros); from.push_back(zeros); from.push_back(zeros); to1.push_back(zeros); to1.push_back(ones); to2.push_back(ones); to2.push_back(ones); /** * 000 is more "similar" to 01 than 11, therefore distance between * from and to1 should be smaller */ Aquila::Dtw dtw; double distance1 = dtw.getDistance(from, to1); double distance2 = dtw.getDistance(from, to2); CHECK(distance1 < distance2); } TEST(TrivialPath) { const std::size_t SIZE = 3; double arr1[SIZE] = {0, 0, 0}, arr2[SIZE] = {1, 1, 1}; std::vector<double> zeros(arr1, arr1 + SIZE), ones(arr2, arr2 + SIZE); Aquila::DtwDataType from, to; from.push_back(zeros); to.push_back(ones); Aquila::Dtw dtw; dtw.getDistance(from, to); auto path = dtw.getPath(); CHECK_EQUAL(1ul, path.size()); } } <|endoftext|>
<commit_before> // $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: Oystein Djuvsland * * * * 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. * **************************************************************************/ #include "AliHLTEMCALDigitMakerComponent.h" #include "AliHLTCaloDigitMaker.h" #include "AliHLTCaloDigitDataStruct.h" #include "AliHLTCaloChannelDataHeaderStruct.h" #include "AliHLTCaloChannelDataStruct.h" #include "AliHLTEMCALMapper.h" #include "AliHLTEMCALDefinitions.h" #include "AliCaloCalibPedestal.h" #include "AliEMCALCalibData.h" #include "AliCDBEntry.h" #include "AliCDBPath.h" #include "AliCDBManager.h" #include "TFile.h" #include <sys/stat.h> #include <sys/types.h> //#include "AliHLTEMCALConstant.h" #include "AliHLTCaloConstants.h" using EMCAL::NZROWSMOD; using EMCAL::NXCOLUMNSMOD; using CALO::HGLGFACTOR; /** * @file AliHLTEMCALDigitMakerComponent.cxx * @author Oystein Djuvsland * @date * @brief A digit maker component for EMCAL HLT */ // see below for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt ClassImp(AliHLTEMCALDigitMakerComponent) AliHLTEMCALDigitMakerComponent gAliHLTEMCALDigitMakerComponent; AliHLTEMCALDigitMakerComponent::AliHLTEMCALDigitMakerComponent() : AliHLTCaloProcessor(), // AliHLTCaloConstantsHandler("EMCAL"), fDigitMakerPtr(0), fDigitContainerPtr(0), fPedestalData(0), fCalibData(0), fBCMInitialised(true), fGainsInitialised(true) { //see header file for documentation } AliHLTEMCALDigitMakerComponent::~AliHLTEMCALDigitMakerComponent() { //see header file for documentation } int AliHLTEMCALDigitMakerComponent::Deinit() { //see header file for documentation if(fDigitMakerPtr) { delete fDigitMakerPtr; fDigitMakerPtr = 0; } return 0; } const char* AliHLTEMCALDigitMakerComponent::GetComponentID() { //see header file for documentation return "EmcalDigitMaker"; } void AliHLTEMCALDigitMakerComponent::GetInputDataTypes(vector<AliHLTComponentDataType>& list) { //see header file for documentation list.clear(); list.push_back(AliHLTEMCALDefinitions::fgkChannelDataType); } AliHLTComponentDataType AliHLTEMCALDigitMakerComponent::GetOutputDataType() { //see header file for documentation // return AliHLTCaloDefinitions::fgkDigitDataType|kAliHLTDataOriginEMCAL; return AliHLTEMCALDefinitions::fgkDigitDataType; } void AliHLTEMCALDigitMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier) { //see header file for documentation constBase = 0; inputMultiplier = (float)sizeof(AliHLTCaloDigitDataStruct)/sizeof(AliHLTCaloChannelDataStruct) + 1; } int AliHLTEMCALDigitMakerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks) { //see header file for documentation UInt_t offset = 0; UInt_t mysize = 0; Int_t digitCount = 0; Int_t ret = 0; const AliHLTComponentBlockData* iter = 0; unsigned long ndx; UInt_t specification = 0; AliHLTCaloChannelDataHeaderStruct* tmpChannelData = 0; // fDigitMakerPtr->SetDigitHeaderPtr(reinterpret_cast<AliHLTCaloDigitHeaderStruct*>(outputPtr)); fDigitMakerPtr->SetDigitDataPtr(reinterpret_cast<AliHLTCaloDigitDataStruct*>(outputPtr)); for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ ) { iter = blocks+ndx; if(iter->fDataType != AliHLTEMCALDefinitions::fgkChannelDataType) { continue; } Int_t module = 0; if(!fBCMInitialised) { AliHLTEMCALMapper mapper(iter->fSpecification); module = mapper.GetModuleFromSpec(iter->fSpecification); for(Int_t x = 0; x < NXCOLUMNSMOD ; x++) // PTH { for(Int_t z = 0; z < NZROWSMOD ; z++) // PTH { fDigitMakerPtr->SetBadChannel(x, z, fPedestalData->IsBadChannel(module, z+1, x+1)); } } //delete fBadChannelMap; fBCMInitialised = true; } if(!fGainsInitialised) { AliHLTEMCALMapper mapper(iter->fSpecification);; module = mapper.GetModuleFromSpec(iter->fSpecification); for(Int_t x = 0; x < NXCOLUMNSMOD; x++) //PTH { for(Int_t z = 0; z < NZROWSMOD; z++) //PTH { // FR setting gains fDigitMakerPtr->SetGain(x, z, HGLGFACTOR, fCalibData->GetADCchannel(module, z+1, x+1)); } } fGainsInitialised = true; } specification |= iter->fSpecification; tmpChannelData = reinterpret_cast<AliHLTCaloChannelDataHeaderStruct*>(iter->fPtr); ret = fDigitMakerPtr->MakeDigits(tmpChannelData, size-(digitCount*sizeof(AliHLTCaloDigitDataStruct))); if(ret == -1) { HLTError("Trying to write over buffer size"); return -ENOBUFS; } digitCount += ret; } mysize += digitCount*sizeof(AliHLTCaloDigitDataStruct); HLTDebug("# of digits: %d, used memory size: %d, available size: %d", digitCount, mysize, size); if(mysize > 0) { AliHLTComponentBlockData bd; FillBlockData( bd ); bd.fOffset = offset; bd.fSize = mysize; bd.fDataType = AliHLTEMCALDefinitions::fgkDigitDataType; bd.fSpecification = specification; outputBlocks.push_back(bd); } fDigitMakerPtr->Reset(); size = mysize; return 0; } int AliHLTEMCALDigitMakerComponent::DoInit(int argc, const char** argv ) { //see header file for documentation fDigitMakerPtr = new AliHLTCaloDigitMaker("EMCAL"); AliHLTCaloMapper *mapper = new AliHLTEMCALMapper(2); fDigitMakerPtr->SetMapper(mapper); for(int i = 0; i < argc; i++) { if(!strcmp("-lowgainfactor", argv[i])) { fDigitMakerPtr->SetGlobalLowGainFactor(atof(argv[i+1])); } if(!strcmp("-highgainfactor", argv[i])) { fDigitMakerPtr->SetGlobalHighGainFactor(atof(argv[i+1])); } } if (GetBCMFromCDB()) return -1; if (GetGainsFromCDB()) return -1; //GetBCMFromCDB(); //fDigitMakerPtr->SetDigitThreshold(2); return 0; } int AliHLTEMCALDigitMakerComponent::GetBCMFromCDB() { // See header file for class documentation fBCMInitialised = false; // HLTInfo("Getting bad channel map..."); AliCDBPath path("EMCAL","Calib","Pedestals"); if(path.GetPath()) { // HLTInfo("configure from entry %s", path.GetPath()); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { fPedestalData = (AliCaloCalibPedestal*)pEntry->GetObject(); } else { // HLTError("can not fetch object \"%s\" from CDB", path); return -1; } } if(!fPedestalData) { return -1; } return 0; } int AliHLTEMCALDigitMakerComponent::GetGainsFromCDB() { // See header file for class documentation fGainsInitialised = false; // HLTInfo("Getting bad channel map..."); AliCDBPath path("EMCAL","Calib","Data"); if(path.GetPath()) { // HLTInfo("configure from entry %s", path.GetPath()); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { fCalibData = (AliEMCALCalibData*)pEntry->GetObject(); } else { // HLTError("can not fetch object \"%s\" from CDB", path); return -1; } } if(!fCalibData) return -1; return 0; } AliHLTComponent* AliHLTEMCALDigitMakerComponent::Spawn() { //see header file for documentation return new AliHLTEMCALDigitMakerComponent(); } <commit_msg>fixing coverity (index out of bounds)<commit_after> // $Id$ /************************************************************************** * This file is property of and copyright by the ALICE HLT Project * * All rights reserved. * * * * Primary Authors: Oystein Djuvsland * * * * 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. * **************************************************************************/ #include "AliHLTEMCALDigitMakerComponent.h" #include "AliHLTCaloDigitMaker.h" #include "AliHLTCaloDigitDataStruct.h" #include "AliHLTCaloChannelDataHeaderStruct.h" #include "AliHLTCaloChannelDataStruct.h" #include "AliHLTEMCALMapper.h" #include "AliHLTEMCALDefinitions.h" #include "AliCaloCalibPedestal.h" #include "AliEMCALCalibData.h" #include "AliCDBEntry.h" #include "AliCDBPath.h" #include "AliCDBManager.h" #include "TFile.h" #include <sys/stat.h> #include <sys/types.h> //#include "AliHLTEMCALConstant.h" #include "AliHLTCaloConstants.h" using EMCAL::NZROWSMOD; using EMCAL::NXCOLUMNSMOD; using CALO::HGLGFACTOR; /** * @file AliHLTEMCALDigitMakerComponent.cxx * @author Oystein Djuvsland * @date * @brief A digit maker component for EMCAL HLT */ // see below for class documentation // or // refer to README to build package // or // visit http://web.ift.uib.no/~kjeks/doc/alice-hlt ClassImp(AliHLTEMCALDigitMakerComponent) AliHLTEMCALDigitMakerComponent gAliHLTEMCALDigitMakerComponent; AliHLTEMCALDigitMakerComponent::AliHLTEMCALDigitMakerComponent() : AliHLTCaloProcessor(), // AliHLTCaloConstantsHandler("EMCAL"), fDigitMakerPtr(0), fDigitContainerPtr(0), fPedestalData(0), fCalibData(0), fBCMInitialised(true), fGainsInitialised(true) { //see header file for documentation } AliHLTEMCALDigitMakerComponent::~AliHLTEMCALDigitMakerComponent() { //see header file for documentation } int AliHLTEMCALDigitMakerComponent::Deinit() { //see header file for documentation if(fDigitMakerPtr) { delete fDigitMakerPtr; fDigitMakerPtr = 0; } return 0; } const char* AliHLTEMCALDigitMakerComponent::GetComponentID() { //see header file for documentation return "EmcalDigitMaker"; } void AliHLTEMCALDigitMakerComponent::GetInputDataTypes(vector<AliHLTComponentDataType>& list) { //see header file for documentation list.clear(); list.push_back(AliHLTEMCALDefinitions::fgkChannelDataType); } AliHLTComponentDataType AliHLTEMCALDigitMakerComponent::GetOutputDataType() { //see header file for documentation // return AliHLTCaloDefinitions::fgkDigitDataType|kAliHLTDataOriginEMCAL; return AliHLTEMCALDefinitions::fgkDigitDataType; } void AliHLTEMCALDigitMakerComponent::GetOutputDataSize(unsigned long& constBase, double& inputMultiplier) { //see header file for documentation constBase = 0; inputMultiplier = (float)sizeof(AliHLTCaloDigitDataStruct)/sizeof(AliHLTCaloChannelDataStruct) + 1; } int AliHLTEMCALDigitMakerComponent::DoEvent(const AliHLTComponentEventData& evtData, const AliHLTComponentBlockData* blocks, AliHLTComponentTriggerData& /*trigData*/, AliHLTUInt8_t* outputPtr, AliHLTUInt32_t& size, std::vector<AliHLTComponentBlockData>& outputBlocks) { //see header file for documentation UInt_t offset = 0; UInt_t mysize = 0; Int_t digitCount = 0; Int_t ret = 0; const AliHLTComponentBlockData* iter = 0; unsigned long ndx; UInt_t specification = 0; AliHLTCaloChannelDataHeaderStruct* tmpChannelData = 0; // fDigitMakerPtr->SetDigitHeaderPtr(reinterpret_cast<AliHLTCaloDigitHeaderStruct*>(outputPtr)); fDigitMakerPtr->SetDigitDataPtr(reinterpret_cast<AliHLTCaloDigitDataStruct*>(outputPtr)); for( ndx = 0; ndx < evtData.fBlockCnt; ndx++ ) { iter = blocks+ndx; if(iter->fDataType != AliHLTEMCALDefinitions::fgkChannelDataType) { continue; } Int_t module = 0; if(!fBCMInitialised) { AliHLTEMCALMapper mapper(iter->fSpecification); module = mapper.GetModuleFromSpec(iter->fSpecification); for(Int_t x = 0; x < NXCOLUMNSMOD ; x++) // PTH { for(Int_t z = 0; z < NZROWSMOD ; z++) // PTH { fDigitMakerPtr->SetBadChannel(x, z, fPedestalData->IsBadChannel(module, z+1, x+1)); } } //delete fBadChannelMap; fBCMInitialised = true; } if(!fGainsInitialised) { AliHLTEMCALMapper mapper(iter->fSpecification);; module = mapper.GetModuleFromSpec(iter->fSpecification); for(Int_t x = 0; x < NXCOLUMNSMOD; x++) //PTH { for(Int_t z = 0; z < NZROWSMOD; z++) //PTH { // FR setting gains fDigitMakerPtr->SetGain(x, z, HGLGFACTOR, fCalibData->GetADCchannel(module, z, x)); } } fGainsInitialised = true; } specification |= iter->fSpecification; tmpChannelData = reinterpret_cast<AliHLTCaloChannelDataHeaderStruct*>(iter->fPtr); ret = fDigitMakerPtr->MakeDigits(tmpChannelData, size-(digitCount*sizeof(AliHLTCaloDigitDataStruct))); if(ret == -1) { HLTError("Trying to write over buffer size"); return -ENOBUFS; } digitCount += ret; } mysize += digitCount*sizeof(AliHLTCaloDigitDataStruct); HLTDebug("# of digits: %d, used memory size: %d, available size: %d", digitCount, mysize, size); if(mysize > 0) { AliHLTComponentBlockData bd; FillBlockData( bd ); bd.fOffset = offset; bd.fSize = mysize; bd.fDataType = AliHLTEMCALDefinitions::fgkDigitDataType; bd.fSpecification = specification; outputBlocks.push_back(bd); } fDigitMakerPtr->Reset(); size = mysize; return 0; } int AliHLTEMCALDigitMakerComponent::DoInit(int argc, const char** argv ) { //see header file for documentation fDigitMakerPtr = new AliHLTCaloDigitMaker("EMCAL"); AliHLTCaloMapper *mapper = new AliHLTEMCALMapper(2); fDigitMakerPtr->SetMapper(mapper); for(int i = 0; i < argc; i++) { if(!strcmp("-lowgainfactor", argv[i])) { fDigitMakerPtr->SetGlobalLowGainFactor(atof(argv[i+1])); } if(!strcmp("-highgainfactor", argv[i])) { fDigitMakerPtr->SetGlobalHighGainFactor(atof(argv[i+1])); } } if (GetBCMFromCDB()) return -1; if (GetGainsFromCDB()) return -1; //GetBCMFromCDB(); //fDigitMakerPtr->SetDigitThreshold(2); return 0; } int AliHLTEMCALDigitMakerComponent::GetBCMFromCDB() { // See header file for class documentation fBCMInitialised = false; // HLTInfo("Getting bad channel map..."); AliCDBPath path("EMCAL","Calib","Pedestals"); if(path.GetPath()) { // HLTInfo("configure from entry %s", path.GetPath()); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { fPedestalData = (AliCaloCalibPedestal*)pEntry->GetObject(); } else { // HLTError("can not fetch object \"%s\" from CDB", path); return -1; } } if(!fPedestalData) { return -1; } return 0; } int AliHLTEMCALDigitMakerComponent::GetGainsFromCDB() { // See header file for class documentation fGainsInitialised = false; // HLTInfo("Getting bad channel map..."); AliCDBPath path("EMCAL","Calib","Data"); if(path.GetPath()) { // HLTInfo("configure from entry %s", path.GetPath()); AliCDBEntry *pEntry = AliCDBManager::Instance()->Get(path/*,GetRunNo()*/); if (pEntry) { fCalibData = (AliEMCALCalibData*)pEntry->GetObject(); } else { // HLTError("can not fetch object \"%s\" from CDB", path); return -1; } } if(!fCalibData) return -1; return 0; } AliHLTComponent* AliHLTEMCALDigitMakerComponent::Spawn() { //see header file for documentation return new AliHLTEMCALDigitMakerComponent(); } <|endoftext|>
<commit_before>#include "binson.hpp" #include <binson_light.h> #include <string.h> #include <stdexcept> using namespace std; Binson & Binson::put(const std::string &key, const BinsonValue &v) { m_items[key] = move(v); return *this; } Binson & Binson::put(const std::string &key, Binson o) { m_items[key] = BinsonValue(move(o)); return *this; } Binson & Binson::put(const string &key, const uint8_t *data, size_t size) { vector<uint8_t> v(data, data + size); m_items[key] = move(BinsonValue(move(v))); return *this; } BinsonValue Binson::get(const string &key) { if (!hasKey(key)) throw std::out_of_range("Key '" + key + "' does not exist"); else return m_items.at(key); } bool Binson::hasKey(const string &key) { return m_items.find(key) != m_items.end(); } void Binson::clear() { m_items.clear(); } bool Binson::seralizeItem(binson_writer *w, BinsonValue &val) { bool result = true; switch(val.myType()) { case BinsonValue::Types::noneType: break; case BinsonValue::Types::boolType: result = result && binson_write_boolean(w, val.getBool()); break; case BinsonValue::Types::intType: result = result && binson_write_integer(w, val.getInt()); break; case BinsonValue::Types::doubleType: result = result && binson_write_double(w, val.getDouble()); break; case BinsonValue::Types::stringType: result = result && binson_write_string_with_len(w, val.getString().data(), val.getString().size()); break; case BinsonValue::Types::binaryType: result = result && binson_write_bytes(w, val.getBin().data(), val.getBin().size()); break; case BinsonValue::Types::objectType: result = result && binson_write_object_begin(w); result = result && val.getObject().seralizeItems(w); result = result && binson_write_object_end(w); break; case BinsonValue::Types::arrayType: result = result && binson_write_array_begin(w); for (auto &arrayValue : val.getArray()) { result = result && seralizeItem(w, arrayValue); } result = result && binson_write_array_end(w); break; default: throw runtime_error("Unknown binson type"); } return result; } bool Binson::seralizeItems(binson_writer *w) { bool result = true; for (auto &item: m_items) { result = result && binson_write_name(w, item.first.c_str()); result = result && seralizeItem(w, item.second); } return result; } std::vector<uint8_t> Binson::serialize() { vector<uint8_t> data; data.resize(10000); binson_writer w; int trys = 5; bool result = false; do { if (!binson_writer_init(&w, data.data(), data.size())) break; result = serialize(&w); if (!result) data.resize(data.size() * 2); } while(!result && trys-- > 0 && w.error_flags == BINSON_ERROR_RANGE); if (result) data.resize(binson_writer_get_counter(&w)); else data.clear(); return data; } bool Binson::serialize(binson_writer *w) { bool result = true; result = result && binson_write_object_begin(w); result = result && seralizeItems(w); result = result && binson_write_object_end(w); return result; } BinsonValue Binson::deseralizeItem(binson_parser *p) { uint8_t t = binson_parser_get_type(p); switch(t) { case BINSON_ID_BOOLEAN: return BinsonValue(binson_parser_get_boolean(p) == 0 ? false : true); break; case BINSON_ID_INTEGER: return BinsonValue(binson_parser_get_integer(p)); break; case BINSON_ID_DOUBLE: return BinsonValue(binson_parser_get_double(p)); break; case BINSON_ID_STRING: { bbuf *buf; buf = binson_parser_get_string_bbuf(p); if (buf) return BinsonValue(string(reinterpret_cast<const char*>(buf->bptr), buf->bsize)); else throw runtime_error("Parse error, missing string"); } break; case BINSON_ID_BYTES: { bbuf *buf; buf = binson_parser_get_bytes_bbuf(p); return BinsonValue(vector<uint8_t>(buf->bptr, buf->bptr + buf->bsize)); } break; case BINSON_ID_OBJECT: { binson_parser_go_into_object(p); Binson b; b.deseralizeItems(p); binson_parser_leave_object(p); return BinsonValue(b); } break; case BINSON_ID_ARRAY: { binson_parser_go_into_array(p); vector<BinsonValue> array; while(binson_parser_next(p)) { array.push_back(deseralizeItem(p)); } binson_parser_leave_array(p); return array; } break; default: throw runtime_error("Unknown type"); } return BinsonValue(); } void Binson::deseralizeItems(binson_parser *p) { while(binson_parser_next(p)) { bbuf *buf; buf = binson_parser_get_name(p); string name(reinterpret_cast<const char*>(buf->bptr), buf->bsize); put(name, deseralizeItem(p)); } } bool Binson::deserialize(const std::vector<uint8_t> &data) { binson_parser p; clear(); binson_parser_init(&p, const_cast<uint8_t*>(data.data()), data.size()); binson_parser_go_into_object(&p); deseralizeItems(&p); binson_parser_leave_object(&p); return true; } bool Binson::deserialize(const uint8_t *data, size_t size) { binson_parser p; clear(); binson_parser_init(&p, const_cast<uint8_t*>(data), size); deserialize(&p); return true; } bool Binson::deserialize(binson_parser *p) { clear(); binson_parser_reset(p); binson_parser_go_into_object(p); deseralizeItems(p); binson_parser_leave_object(p); return true; } string Binson::toStr() { binson_parser p; string str; str.resize(10000); vector<uint8_t> stream = serialize(); if (stream.empty()) return string(); int trys = 5; bool result = false; size_t size = 0; do { if (!binson_parser_init(&p, stream.data(), stream.size())) break; size = str.size(); result = binson_parser_to_string(&p, (char*)str.data(), &size, true); if (!result) str.resize(size * 2); } while(!result && trys-- > 0 && p.error_flags == 0); if (!result) str.clear(); else str.resize(size); return str; } BinsonValue::BinsonValue() { } BinsonValue::BinsonValue(bool val) { m_val.b = val; m_val.setType(Types::boolType); } BinsonValue::BinsonValue(int64_t val) { m_val.i = val; m_val.setType(Types::intType); } BinsonValue::BinsonValue(int val) { m_val.i = val; m_val.setType(Types::intType); } BinsonValue::BinsonValue(double val) { m_val.d = val; m_val.setType(Types::doubleType); } BinsonValue::BinsonValue(string &&val) { m_val.str = move(val); m_val.setType(Types::stringType); } BinsonValue::BinsonValue(const string &val) { m_val.str = val; m_val.setType(Types::stringType); } BinsonValue::BinsonValue(const char *str) { m_val.str = string(str); m_val.setType(Types::stringType); } BinsonValue::BinsonValue(std::vector<uint8_t> &&val) { m_val.bin = move(val); m_val.setType(Types::binaryType); } BinsonValue::BinsonValue(const std::vector<uint8_t> &val) { m_val.bin = val; m_val.setType(Types::binaryType); } BinsonValue::BinsonValue(Binson &&val) { m_val.o = move(val); m_val.setType(Types::objectType); } BinsonValue::BinsonValue(const Binson &val) { m_val.o = val; m_val.setType(Types::objectType); } BinsonValue::BinsonValue(std::vector<BinsonValue> &&val) { m_val.a = move(val); m_val.setType(Types::arrayType); } BinsonValue::BinsonValue(const std::vector<BinsonValue> &val) { m_val.a = val; m_val.setType(Types::arrayType); } BinsonValue BinsonValue::operator=(bool &&val) { m_val.b = move(val); m_val.setType(Types::boolType); return *this; } BinsonValue BinsonValue::operator=(int64_t &&val) { m_val.i = move(val); m_val.setType(Types::intType); return *this; } BinsonValue BinsonValue::operator=(int &&val) { m_val.i = val; m_val.setType(Types::intType); return *this; } BinsonValue BinsonValue::operator=(double &&val) { m_val.d = move(val); m_val.setType(Types::doubleType); return *this; } BinsonValue BinsonValue::operator=(string &&val) { m_val.str = move(val); m_val.setType(Types::stringType); return *this; } BinsonValue BinsonValue::operator=(std::vector<uint8_t> &&val) { m_val.bin = move(val); m_val.setType(Types::binaryType); return *this; } BinsonValue BinsonValue::operator=(Binson &&val) { m_val.o = move(val); m_val.setType(Types::objectType); return *this; } BinsonValue BinsonValue::operator=(std::vector<BinsonValue> &&val) { m_val.a = move(val); m_val.setType(Types::arrayType); return *this; } <commit_msg>Check data ptr<commit_after>#include "binson.hpp" #include <binson_light.h> #include <string.h> #include <stdexcept> using namespace std; Binson & Binson::put(const std::string &key, const BinsonValue &v) { m_items[key] = move(v); return *this; } Binson & Binson::put(const std::string &key, Binson o) { m_items[key] = BinsonValue(move(o)); return *this; } Binson & Binson::put(const string &key, const uint8_t *data, size_t size) { vector<uint8_t> v(data, data + size); m_items[key] = move(BinsonValue(move(v))); return *this; } BinsonValue Binson::get(const string &key) { if (!hasKey(key)) throw std::out_of_range("Key '" + key + "' does not exist"); else return m_items.at(key); } bool Binson::hasKey(const string &key) { return m_items.find(key) != m_items.end(); } void Binson::clear() { m_items.clear(); } bool Binson::seralizeItem(binson_writer *w, BinsonValue &val) { bool result = true; switch(val.myType()) { case BinsonValue::Types::noneType: break; case BinsonValue::Types::boolType: result = result && binson_write_boolean(w, val.getBool()); break; case BinsonValue::Types::intType: result = result && binson_write_integer(w, val.getInt()); break; case BinsonValue::Types::doubleType: result = result && binson_write_double(w, val.getDouble()); break; case BinsonValue::Types::stringType: result = result && binson_write_string_with_len(w, val.getString().data(), val.getString().size()); break; case BinsonValue::Types::binaryType: result = result && binson_write_bytes(w, val.getBin().data(), val.getBin().size()); break; case BinsonValue::Types::objectType: result = result && binson_write_object_begin(w); result = result && val.getObject().seralizeItems(w); result = result && binson_write_object_end(w); break; case BinsonValue::Types::arrayType: result = result && binson_write_array_begin(w); for (auto &arrayValue : val.getArray()) { result = result && seralizeItem(w, arrayValue); } result = result && binson_write_array_end(w); break; default: throw runtime_error("Unknown binson type"); } return result; } bool Binson::seralizeItems(binson_writer *w) { bool result = true; for (auto &item: m_items) { result = result && binson_write_name(w, item.first.c_str()); result = result && seralizeItem(w, item.second); } return result; } std::vector<uint8_t> Binson::serialize() { vector<uint8_t> data; data.resize(10000); binson_writer w; int trys = 5; bool result = false; do { if (!binson_writer_init(&w, data.data(), data.size())) break; result = serialize(&w); if (!result) data.resize(data.size() * 2); } while(!result && trys-- > 0 && w.error_flags == BINSON_ERROR_RANGE); if (result) data.resize(binson_writer_get_counter(&w)); else data.clear(); return data; } bool Binson::serialize(binson_writer *w) { bool result = true; result = result && binson_write_object_begin(w); result = result && seralizeItems(w); result = result && binson_write_object_end(w); return result; } BinsonValue Binson::deseralizeItem(binson_parser *p) { uint8_t t = binson_parser_get_type(p); switch(t) { case BINSON_ID_BOOLEAN: return BinsonValue(binson_parser_get_boolean(p) == 0 ? false : true); break; case BINSON_ID_INTEGER: return BinsonValue(binson_parser_get_integer(p)); break; case BINSON_ID_DOUBLE: return BinsonValue(binson_parser_get_double(p)); break; case BINSON_ID_STRING: { bbuf *buf; buf = binson_parser_get_string_bbuf(p); if (buf) return BinsonValue(string(reinterpret_cast<const char*>(buf->bptr), buf->bsize)); else throw runtime_error("Parse error, missing string"); } break; case BINSON_ID_BYTES: { bbuf *buf; buf = binson_parser_get_bytes_bbuf(p); if (buf) return BinsonValue(vector<uint8_t>(buf->bptr, buf->bptr + buf->bsize)); else throw runtime_error("Parse error, missing data"); } break; case BINSON_ID_OBJECT: { binson_parser_go_into_object(p); Binson b; b.deseralizeItems(p); binson_parser_leave_object(p); return BinsonValue(b); } break; case BINSON_ID_ARRAY: { binson_parser_go_into_array(p); vector<BinsonValue> array; while(binson_parser_next(p)) { array.push_back(deseralizeItem(p)); } binson_parser_leave_array(p); return array; } break; default: throw runtime_error("Unknown type"); } return BinsonValue(); } void Binson::deseralizeItems(binson_parser *p) { while(binson_parser_next(p)) { bbuf *buf; buf = binson_parser_get_name(p); string name(reinterpret_cast<const char*>(buf->bptr), buf->bsize); put(name, deseralizeItem(p)); } } bool Binson::deserialize(const std::vector<uint8_t> &data) { binson_parser p; clear(); binson_parser_init(&p, const_cast<uint8_t*>(data.data()), data.size()); binson_parser_go_into_object(&p); deseralizeItems(&p); binson_parser_leave_object(&p); return true; } bool Binson::deserialize(const uint8_t *data, size_t size) { binson_parser p; clear(); binson_parser_init(&p, const_cast<uint8_t*>(data), size); deserialize(&p); return true; } bool Binson::deserialize(binson_parser *p) { clear(); binson_parser_reset(p); binson_parser_go_into_object(p); deseralizeItems(p); binson_parser_leave_object(p); return true; } string Binson::toStr() { binson_parser p; string str; str.resize(10000); vector<uint8_t> stream = serialize(); if (stream.empty()) return string(); int trys = 5; bool result = false; size_t size = 0; do { if (!binson_parser_init(&p, stream.data(), stream.size())) break; size = str.size(); result = binson_parser_to_string(&p, (char*)str.data(), &size, true); if (!result) str.resize(size * 2); } while(!result && trys-- > 0 && p.error_flags == 0); if (!result) str.clear(); else str.resize(size); return str; } BinsonValue::BinsonValue() { } BinsonValue::BinsonValue(bool val) { m_val.b = val; m_val.setType(Types::boolType); } BinsonValue::BinsonValue(int64_t val) { m_val.i = val; m_val.setType(Types::intType); } BinsonValue::BinsonValue(int val) { m_val.i = val; m_val.setType(Types::intType); } BinsonValue::BinsonValue(double val) { m_val.d = val; m_val.setType(Types::doubleType); } BinsonValue::BinsonValue(string &&val) { m_val.str = move(val); m_val.setType(Types::stringType); } BinsonValue::BinsonValue(const string &val) { m_val.str = val; m_val.setType(Types::stringType); } BinsonValue::BinsonValue(const char *str) { m_val.str = string(str); m_val.setType(Types::stringType); } BinsonValue::BinsonValue(std::vector<uint8_t> &&val) { m_val.bin = move(val); m_val.setType(Types::binaryType); } BinsonValue::BinsonValue(const std::vector<uint8_t> &val) { m_val.bin = val; m_val.setType(Types::binaryType); } BinsonValue::BinsonValue(Binson &&val) { m_val.o = move(val); m_val.setType(Types::objectType); } BinsonValue::BinsonValue(const Binson &val) { m_val.o = val; m_val.setType(Types::objectType); } BinsonValue::BinsonValue(std::vector<BinsonValue> &&val) { m_val.a = move(val); m_val.setType(Types::arrayType); } BinsonValue::BinsonValue(const std::vector<BinsonValue> &val) { m_val.a = val; m_val.setType(Types::arrayType); } BinsonValue BinsonValue::operator=(bool &&val) { m_val.b = move(val); m_val.setType(Types::boolType); return *this; } BinsonValue BinsonValue::operator=(int64_t &&val) { m_val.i = move(val); m_val.setType(Types::intType); return *this; } BinsonValue BinsonValue::operator=(int &&val) { m_val.i = val; m_val.setType(Types::intType); return *this; } BinsonValue BinsonValue::operator=(double &&val) { m_val.d = move(val); m_val.setType(Types::doubleType); return *this; } BinsonValue BinsonValue::operator=(string &&val) { m_val.str = move(val); m_val.setType(Types::stringType); return *this; } BinsonValue BinsonValue::operator=(std::vector<uint8_t> &&val) { m_val.bin = move(val); m_val.setType(Types::binaryType); return *this; } BinsonValue BinsonValue::operator=(Binson &&val) { m_val.o = move(val); m_val.setType(Types::objectType); return *this; } BinsonValue BinsonValue::operator=(std::vector<BinsonValue> &&val) { m_val.a = move(val); m_val.setType(Types::arrayType); return *this; } <|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <zmq.hpp> #if defined(ZMQ_CPP11) && defined(ZMQ_BUILD_DRAFT_API) #include <array> TEST(poller, create_destroy) { zmq::poller_t poller; ASSERT_EQ(0u, poller.size ()); } static_assert(!std::is_copy_constructible<zmq::poller_t>::value, "poller_t should not be copy-constructible"); static_assert(!std::is_copy_assignable<zmq::poller_t>::value, "poller_t should not be copy-assignable"); TEST(poller, move_construct_empty) { std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; zmq::poller_t b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(0u, b.size ()); } TEST(poller, move_assign_empty) { std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; zmq::poller_t b; b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(0u, b.size ()); } TEST(poller, move_construct_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; a->add(socket, ZMQ_POLLIN, [](short) {}); zmq::poller_t b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(1u, b.size ()); } TEST(poller, move_assign_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; a->add(socket, ZMQ_POLLIN, [](short) {}); zmq::poller_t b; b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(1u, b.size ()); } TEST(poller, add_handler) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; ASSERT_NO_THROW(poller.add(socket, ZMQ_POLLIN, handler)); } TEST(poller, add_handler_invalid_events_type) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; short invalid_events_type = 2 << 10; ASSERT_NO_THROW(poller.add(socket, invalid_events_type, handler)); } TEST(poller, add_handler_twice_throws) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; poller.add(socket, ZMQ_POLLIN, handler); /// \todo the actual error code should be checked ASSERT_THROW(poller.add(socket, ZMQ_POLLIN, handler), zmq::error_t); } TEST(poller, wait_with_no_handlers_throws) { zmq::poller_t poller; /// \todo the actual error code should be checked ASSERT_THROW(poller.wait(std::chrono::milliseconds{10}), zmq::error_t); } TEST(poller, remove_unregistered_throws) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; /// \todo the actual error code should be checked ASSERT_THROW(poller.remove(socket), zmq::error_t); } /// \todo this should lead to an exception instead TEST(poller, remove_registered_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; poller.add(socket, ZMQ_POLLIN, zmq::poller_t::handler_t{}); ASSERT_NO_THROW(poller.remove(socket)); } TEST(poller, remove_registered_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; poller.add(socket, ZMQ_POLLIN, [](short) {}); ASSERT_NO_THROW(poller.remove(socket)); } namespace { class loopback_ip4_binder { public: loopback_ip4_binder(zmq::socket_t &socket) { bind(socket); } std::string endpoint() { return endpoint_; } private: // Helper function used in constructor // as Gtest allows ASSERT_* only in void returning functions // and constructor/destructor are not. void bind(zmq::socket_t &socket) { ASSERT_NO_THROW(socket.bind("tcp://127.0.0.1:*")); std::array<char, 100> endpoint{}; size_t endpoint_size = endpoint.size(); ASSERT_NO_THROW(socket.getsockopt(ZMQ_LAST_ENDPOINT, endpoint.data(), &endpoint_size)); ASSERT_TRUE(endpoint_size < endpoint.size()); endpoint_ = std::string{endpoint.data()}; } std::string endpoint_; }; } //namespace TEST(poller, poll_basic) { zmq::context_t context; zmq::socket_t vent{context, zmq::socket_type::push}; auto endpoint = loopback_ip4_binder(vent).endpoint(); zmq::socket_t sink{context, zmq::socket_type::pull}; ASSERT_NO_THROW(sink.connect(endpoint)); const std::string message = "H"; // TODO: send overload for string would be handy. ASSERT_NO_THROW(vent.send(std::begin(message), std::end(message))); zmq::poller_t poller; bool message_received = false; zmq::poller_t::handler_t handler = [&message_received](short events) { ASSERT_TRUE(0 != (events & ZMQ_POLLIN)); message_received = true; }; ASSERT_NO_THROW(poller.add(sink, ZMQ_POLLIN, handler)); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(message_received); } /// \todo this contains multiple test cases that should be split up TEST(poller, client_server) { zmq::context_t context; const std::string send_msg = "Hi"; // Setup server zmq::socket_t server{context, zmq::socket_type::router}; auto endpoint = loopback_ip4_binder(server).endpoint(); // Setup poller zmq::poller_t poller; bool got_pollin = false; bool got_pollout = false; zmq::poller_t::handler_t handler = [&](short events) { if (0 != (events & ZMQ_POLLIN)) { zmq::message_t zmq_msg; ASSERT_NO_THROW(server.recv(&zmq_msg)); // skip msg id ASSERT_NO_THROW(server.recv(&zmq_msg)); // get message std::string recv_msg(zmq_msg.data<char>(), zmq_msg.size()); ASSERT_EQ(send_msg, recv_msg); got_pollin = true; } else if (0 != (events & ZMQ_POLLOUT)) { got_pollout = true; } else { ASSERT_TRUE(false) << "Unexpected event type " << events; } }; ASSERT_NO_THROW(poller.add(server, ZMQ_POLLIN, handler)); // Setup client and send message zmq::socket_t client{context, zmq::socket_type::dealer}; ASSERT_NO_THROW(client.connect(endpoint)); ASSERT_NO_THROW(client.send(std::begin(send_msg), std::end(send_msg))); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(got_pollin); ASSERT_FALSE(got_pollout); // Re-add server socket with pollout flag ASSERT_NO_THROW(poller.remove(server)); ASSERT_NO_THROW(poller.add(server, ZMQ_POLLIN | ZMQ_POLLOUT, handler)); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(got_pollout); } #endif <commit_msg>Problem: create_destroy test not assigned properly<commit_after>#include <gtest/gtest.h> #include <zmq.hpp> #if defined(ZMQ_CPP11) && defined(ZMQ_BUILD_DRAFT_API) #include <array> TEST(poller, create_destroy) { zmq::poller_t poller; ASSERT_EQ(0u, poller.size ()); } static_assert(!std::is_copy_constructible<zmq::poller_t>::value, "poller_t should not be copy-constructible"); static_assert(!std::is_copy_assignable<zmq::poller_t>::value, "poller_t should not be copy-assignable"); TEST(poller, move_construct_empty) { std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; zmq::poller_t b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(0u, b.size ()); } TEST(poller, move_assign_empty) { std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; zmq::poller_t b; b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(0u, b.size ()); } TEST(poller, move_construct_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; a->add(socket, ZMQ_POLLIN, [](short) {}); zmq::poller_t b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(1u, b.size ()); } TEST(poller, move_assign_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; std::unique_ptr<zmq::poller_t> a{new zmq::poller_t}; a->add(socket, ZMQ_POLLIN, [](short) {}); zmq::poller_t b; b = std::move(*a); ASSERT_EQ(0u, a->size ()); a.reset (); ASSERT_EQ(1u, b.size ()); } TEST(poller, add_handler) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; ASSERT_NO_THROW(poller.add(socket, ZMQ_POLLIN, handler)); } TEST(poller, add_handler_invalid_events_type) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; short invalid_events_type = 2 << 10; ASSERT_NO_THROW(poller.add(socket, invalid_events_type, handler)); } TEST(poller, add_handler_twice_throws) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; zmq::poller_t::handler_t handler; poller.add(socket, ZMQ_POLLIN, handler); /// \todo the actual error code should be checked ASSERT_THROW(poller.add(socket, ZMQ_POLLIN, handler), zmq::error_t); } TEST(poller, wait_with_no_handlers_throws) { zmq::poller_t poller; /// \todo the actual error code should be checked ASSERT_THROW(poller.wait(std::chrono::milliseconds{10}), zmq::error_t); } TEST(poller, remove_unregistered_throws) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; /// \todo the actual error code should be checked ASSERT_THROW(poller.remove(socket), zmq::error_t); } /// \todo this should lead to an exception instead TEST(poller, remove_registered_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; poller.add(socket, ZMQ_POLLIN, zmq::poller_t::handler_t{}); ASSERT_NO_THROW(poller.remove(socket)); } TEST(poller, remove_registered_non_empty) { zmq::context_t context; zmq::socket_t socket{context, zmq::socket_type::router}; zmq::poller_t poller; poller.add(socket, ZMQ_POLLIN, [](short) {}); ASSERT_NO_THROW(poller.remove(socket)); } namespace { class loopback_ip4_binder { public: loopback_ip4_binder(zmq::socket_t &socket) { bind(socket); } std::string endpoint() { return endpoint_; } private: // Helper function used in constructor // as Gtest allows ASSERT_* only in void returning functions // and constructor/destructor are not. void bind(zmq::socket_t &socket) { ASSERT_NO_THROW(socket.bind("tcp://127.0.0.1:*")); std::array<char, 100> endpoint{}; size_t endpoint_size = endpoint.size(); ASSERT_NO_THROW(socket.getsockopt(ZMQ_LAST_ENDPOINT, endpoint.data(), &endpoint_size)); ASSERT_TRUE(endpoint_size < endpoint.size()); endpoint_ = std::string{endpoint.data()}; } std::string endpoint_; }; } //namespace TEST(poller, poll_basic) { zmq::context_t context; zmq::socket_t vent{context, zmq::socket_type::push}; auto endpoint = loopback_ip4_binder(vent).endpoint(); zmq::socket_t sink{context, zmq::socket_type::pull}; ASSERT_NO_THROW(sink.connect(endpoint)); const std::string message = "H"; // TODO: send overload for string would be handy. ASSERT_NO_THROW(vent.send(std::begin(message), std::end(message))); zmq::poller_t poller; bool message_received = false; zmq::poller_t::handler_t handler = [&message_received](short events) { ASSERT_TRUE(0 != (events & ZMQ_POLLIN)); message_received = true; }; ASSERT_NO_THROW(poller.add(sink, ZMQ_POLLIN, handler)); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(message_received); } /// \todo this contains multiple test cases that should be split up TEST(poller, client_server) { zmq::context_t context; const std::string send_msg = "Hi"; // Setup server zmq::socket_t server{context, zmq::socket_type::router}; auto endpoint = loopback_ip4_binder(server).endpoint(); // Setup poller zmq::poller_t poller; bool got_pollin = false; bool got_pollout = false; zmq::poller_t::handler_t handler = [&](short events) { if (0 != (events & ZMQ_POLLIN)) { zmq::message_t zmq_msg; ASSERT_NO_THROW(server.recv(&zmq_msg)); // skip msg id ASSERT_NO_THROW(server.recv(&zmq_msg)); // get message std::string recv_msg(zmq_msg.data<char>(), zmq_msg.size()); ASSERT_EQ(send_msg, recv_msg); got_pollin = true; } else if (0 != (events & ZMQ_POLLOUT)) { got_pollout = true; } else { ASSERT_TRUE(false) << "Unexpected event type " << events; } }; ASSERT_NO_THROW(poller.add(server, ZMQ_POLLIN, handler)); // Setup client and send message zmq::socket_t client{context, zmq::socket_type::dealer}; ASSERT_NO_THROW(client.connect(endpoint)); ASSERT_NO_THROW(client.send(std::begin(send_msg), std::end(send_msg))); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(got_pollin); ASSERT_FALSE(got_pollout); // Re-add server socket with pollout flag ASSERT_NO_THROW(poller.remove(server)); ASSERT_NO_THROW(poller.add(server, ZMQ_POLLIN | ZMQ_POLLOUT, handler)); ASSERT_NO_THROW(poller.wait(std::chrono::milliseconds{-1})); ASSERT_TRUE(got_pollout); } #endif <|endoftext|>
<commit_before>// Source : https://leetcode.com/problems/maximum-gap/ // Author : Yijing Bai // Date : 2016-04-03 /********************************************************************************** * * Given an unsorted array, find the maximum difference between the successive elements * in its sorted form. * * Try to solve it in linear time/space. * * Return 0 if the array contains less than 2 elements. * * You may assume all elements in the array are non-negative integers and fit in the * 32-bit signed integer range. * * Credits:Special thanks to @porker2008 for adding this problem and creating all test * cases. * * * * **********************************************************************************/ <commit_msg>Finished MaximumGap<commit_after>// Source : https://leetcode.com/problems/maximum-gap/ // Author : Yijing Bai // Date : 2016-04-03 /********************************************************************************** * * Given an unsorted array, find the maximum difference between the successive elements * in its sorted form. * * Try to solve it in linear time/space. * * Return 0 if the array contains less than 2 elements. * * You may assume all elements in the array are non-negative integers and fit in the * 32-bit signed integer range. * * Credits:Special thanks to @porker2008 for adding this problem and creating all test * cases. * * * * **********************************************************************************/ class Solution { public: int maximumGap(vector<int>& num) { int sSize = num.size(); int i, res = 0; int minV, maxV; int bucket_size, bucket_num, bucket_id; int maxGap = INT_MIN; int last_max; if(sSize>1) { minV = maxV = num[0]; for(i=1; i<sSize; i++) { if(minV > num[i]) minV = num[i]; else if(maxV < num[i]) maxV = num[i]; } bucket_size = max(1, (maxV - minV )/ (sSize - 1)); bucket_num = (maxV - minV)/bucket_size + 1; if(bucket_num <=1) return (maxV - minV); vector<int> bucket_max(bucket_num, INT_MIN); vector<int> bucket_min(bucket_num, INT_MAX); vector<int> bucket_count(bucket_num, 0); for(i=0; i<sSize; i++) { bucket_id = (num[i] - minV)/bucket_size; bucket_count[bucket_id]++; bucket_min[bucket_id] = bucket_min[bucket_id] > num[i]? num[i]:bucket_min[bucket_id]; bucket_max[bucket_id] = bucket_max[bucket_id] < num[i]? num[i]:bucket_max[bucket_id]; } last_max = minV; for(i=0; i<bucket_num; i++) { if(bucket_count[i]>0) { maxGap = max(maxGap, bucket_min[i]- last_max); last_max = bucket_max[i]; } } return maxGap; } return 0; } }; <|endoftext|>
<commit_before>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include <cmath> #include "error.h" #include "bpmf.h" #include "io.h" static const bool measure_perf = false; std::ostream *Sys::os; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err num_predict = 0; // number of predictions int lo = from(); int hi = to(); if (all) { #ifdef BPMF_REDUCE Sys::cout() << "WARNING: predict all items in test set not available in BPMF_REDUCE mode" << std::endl; #else lo = 0; hi = num(); #endif } #pragma omp parallel for reduction(+:se,se_avg,num_predict) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { #ifdef BPMF_REDUCE if (it.row() >= other.to() || it.row() < other.from()) continue; #endif auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); num_predict++; } } rmse = sqrt( se / num_predict ); rmse_avg = sqrt( se_avg / num_predict ); } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum_map().setZero(); cov_map().setZero(); norm_map().setZero(); col_permutation.setIdentity(num()); #ifdef BPMF_REDUCE precMu = MatrixNXd::Zero(num_latent, num()); precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); #endif if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } int count_larger_bp1 = 0; int count_larger_bp2 = 0; int count_sum = 0; for(int k = 0; k<M.cols(); k++) { int count = M.col(k).nonZeros(); count_sum += count; if (count > breakpoint1) count_larger_bp1++; if (count > breakpoint2) count_larger_bp2++; } Sys::cout() << "mean rating: " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl; Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; void Sys::preComputeMuLambda(const Sys &other) { BPMF_COUNTER("preComputeMuLambda"); #pragma omp parallel for schedule(guided) for (int i = 0; i < num(); ++i) { VectorNd mu = VectorNd::Zero(); MatrixNNd Lambda = MatrixNNd::Zero(); computeMuLambda(i, other, mu, Lambda, true); precLambdaMatrix(i) = Lambda; precMu.col(i) = mu; } } void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM, bool local_only) const { BPMF_COUNTER("computeMuLambda"); for (SparseMatrixD::InnerIterator it(M, idx); it; ++it) { if (local_only && (it.row() < other.from() || it.row() >= other.to())) continue; auto col = other.items().col(it.row()); MM.triangularView<Eigen::Upper>() += col * col.transpose(); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } } // // Update ONE movie or one user // VectorNd Sys::sample(long idx, Sys &other) { auto start = tick(); VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper MatrixNNd MM(MatrixNNd::Zero()); PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) #ifdef BPMF_REDUCE rr += precMu.col(idx); MM += precLambdaMatrix(idx); #else computeMuLambda(idx, other, rr, MM, false); #endif // copy upper -> lower part, matrix is symmetric. MM.triangularView<Eigen::Lower>() = MM.transpose(); chol.compute(hp_LambdaF + alpha * MM); if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &other) { iter++; thread_vector<VectorNd> sums(VectorNd::Zero()); // sum thread_vector<double> norms(0.0); // squared norm thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod #pragma omp parallel for schedule(guided) for (int i = from(); i < to(); ++i) { #pragma omp task { auto r = sample(i, other); MatrixNNd cov = (r * r.transpose()); prods.local() += cov; sums.local() += r; norms.local() += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_item(i); } } #pragma omp taskwait #ifdef BPMF_REDUCE other.preComputeMuLambda(*this); #endif VectorNd sum = sums.combine(); MatrixNNd prod = prods.combine(); double norm = norms.combine(); const int N = num(); local_sum() = sum; local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1); local_norm() = norm; } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; }<commit_msg>FIX: do not use class member in OpenMP reduction (for old compilers)<commit_after>/* * Copyright (c) 2014-2016, imec * All rights reserved. */ #include <random> #include <memory> #include <cstdio> #include <iostream> #include <climits> #include <stdexcept> #include <cmath> #include "error.h" #include "bpmf.h" #include "io.h" static const bool measure_perf = false; std::ostream *Sys::os; int Sys::procid = -1; int Sys::nprocs = -1; int Sys::nsims; int Sys::burnin; int Sys::update_freq; double Sys::alpha = 2.0; std::string Sys::odirname = ""; bool Sys::permute = true; bool Sys::verbose = false; // verifies that A has the same non-zero structure as B void assert_same_struct(SparseMatrixD &A, SparseMatrixD &B) { assert(A.cols() == B.cols()); assert(A.rows() == B.rows()); for(int i=0; i<A.cols(); ++i) assert(A.col(i).nonZeros() == B.col(i).nonZeros()); } // // Does predictions for prediction matrix T // Computes RMSE (Root Means Square Error) // void Sys::predict(Sys& other, bool all) { int n = (iter < burnin) ? 0 : (iter - burnin); double se(0.0); // squared err double se_avg(0.0); // squared avg err int nump = 0; // number of predictions int lo = from(); int hi = to(); if (all) { #ifdef BPMF_REDUCE Sys::cout() << "WARNING: predict all items in test set not available in BPMF_REDUCE mode" << std::endl; #else lo = 0; hi = num(); #endif } #pragma omp parallel for reduction(+:se,se_avg,nump) for(int k = lo; k<hi; k++) { for (Eigen::SparseMatrix<double>::InnerIterator it(T,k); it; ++it) { #ifdef BPMF_REDUCE if (it.row() >= other.to() || it.row() < other.from()) continue; #endif auto m = items().col(it.col()); auto u = other.items().col(it.row()); assert(m.norm() > 0.0); assert(u.norm() > 0.0); const double pred = m.dot(u) + mean_rating; se += sqr(it.value() - pred); // update average prediction double &avg = Pavg.coeffRef(it.row(), it.col()); double delta = pred - avg; avg = (n == 0) ? pred : (avg + delta/n); double &m2 = Pm2.coeffRef(it.row(), it.col()); m2 = (n == 0) ? 0 : m2 + delta * (pred - avg); se_avg += sqr(it.value() - avg); nump++; } } rmse = sqrt( se / num_predict ); rmse_avg = sqrt( se_avg / num_predict ); num_predict = nump; } // // Prints sampling progress // void Sys::print(double items_per_sec, double ratings_per_sec, double norm_u, double norm_m) { char buf[1024]; std::string phase = (iter < Sys::burnin) ? "Burnin" : "Sampling"; sprintf(buf, "%d: %s iteration %d:\t RMSE: %3.4f\tavg RMSE: %3.4f\tFU(%6.2f)\tFM(%6.2f)\titems/sec: %6.2f\tratings/sec: %6.2fM\n", Sys::procid, phase.c_str(), iter, rmse, rmse_avg, norm_u, norm_m, items_per_sec, ratings_per_sec / 1e6); Sys::cout() << buf; } // // Constructor with that reads MTX files // Sys::Sys(std::string name, std::string fname, std::string probename) : name(name), iter(-1), assigned(false), dom(nprocs+1) { read_matrix(fname, M); read_matrix(probename, T); auto rows = std::max(M.rows(), T.rows()); auto cols = std::max(M.cols(), T.cols()); M.conservativeResize(rows,cols); T.conservativeResize(rows,cols); Pm2 = Pavg = Torig = T; // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); assert(Sys::nprocs <= (int)Sys::max_procs); } // // Constructs Sys as transpose of existing Sys // Sys::Sys(std::string name, const SparseMatrixD &Mt, const SparseMatrixD &Pt) : name(name), iter(-1), assigned(false), dom(nprocs+1) { M = Mt.transpose(); Pm2 = Pavg = T = Torig = Pt.transpose(); // reference ratings and predicted ratings assert(M.rows() == Pavg.rows()); assert(M.cols() == Pavg.cols()); } Sys::~Sys() { if (measure_perf) { Sys::cout() << " --------------------\n"; Sys::cout() << name << ": sampling times on " << procid << "\n"; for(int i = from(); i<to(); ++i) { Sys::cout() << "\t" << nnz(i) << "\t" << sample_time.at(i) / nsims << "\n"; } Sys::cout() << " --------------------\n\n"; } } bool Sys::has_prop_posterior() const { return propMu.nonZeros() > 0; } void Sys::add_prop_posterior(std::string fnames) { if (fnames.empty()) return; std::size_t pos = fnames.find_first_of(","); std::string mu_name = fnames.substr(0, pos); std::string lambda_name = fnames.substr(pos+1); read_matrix(mu_name, propMu); read_matrix(lambda_name, propLambda); assert(propMu.cols() == num()); assert(propLambda.cols() == num()); assert(propMu.rows() == num_latent); assert(propLambda.rows() == num_latent * num_latent); } // // Intializes internal Matrices and Vectors // void Sys::init() { //-- M assert(M.rows() > 0 && M.cols() > 0); mean_rating = M.sum() / M.nonZeros(); items().setZero(); sum_map().setZero(); cov_map().setZero(); norm_map().setZero(); col_permutation.setIdentity(num()); #ifdef BPMF_REDUCE precMu = MatrixNXd::Zero(num_latent, num()); precLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); #endif if (Sys::odirname.size()) { aggrMu = Eigen::MatrixXd::Zero(num_latent, num()); aggrLambda = Eigen::MatrixXd::Zero(num_latent * num_latent, num()); } int count_larger_bp1 = 0; int count_larger_bp2 = 0; int count_sum = 0; for(int k = 0; k<M.cols(); k++) { int count = M.col(k).nonZeros(); count_sum += count; if (count > breakpoint1) count_larger_bp1++; if (count > breakpoint2) count_larger_bp2++; } Sys::cout() << "mean rating: " << mean_rating << std::endl; Sys::cout() << "total number of ratings in train: " << M.nonZeros() << std::endl; Sys::cout() << "total number of ratings in test: " << T.nonZeros() << std::endl; Sys::cout() << "average ratings per row: " << (double)count_sum / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point1: " << 100. * (double)count_larger_bp1 / (double)M.cols() << std::endl; Sys::cout() << "rows > break_point2: " << 100. * (double)count_larger_bp2 / (double)M.cols() << std::endl; Sys::cout() << "num " << name << ": " << num() << std::endl; if (has_prop_posterior()) { Sys::cout() << "with propagated posterior" << std::endl; } if (measure_perf) sample_time.resize(num(), .0); } class PrecomputedLLT : public Eigen::LLT<MatrixNNd> { public: void operator=(const MatrixNNd &m) { m_matrix = m; m_isInitialized = true; m_info = Eigen::Success; } }; void Sys::preComputeMuLambda(const Sys &other) { BPMF_COUNTER("preComputeMuLambda"); #pragma omp parallel for schedule(guided) for (int i = 0; i < num(); ++i) { VectorNd mu = VectorNd::Zero(); MatrixNNd Lambda = MatrixNNd::Zero(); computeMuLambda(i, other, mu, Lambda, true); precLambdaMatrix(i) = Lambda; precMu.col(i) = mu; } } void Sys::computeMuLambda(long idx, const Sys &other, VectorNd &rr, MatrixNNd &MM, bool local_only) const { BPMF_COUNTER("computeMuLambda"); for (SparseMatrixD::InnerIterator it(M, idx); it; ++it) { if (local_only && (it.row() < other.from() || it.row() >= other.to())) continue; auto col = other.items().col(it.row()); MM.triangularView<Eigen::Upper>() += col * col.transpose(); rr.noalias() += col * ((it.value() - mean_rating) * alpha); } } // // Update ONE movie or one user // VectorNd Sys::sample(long idx, Sys &other) { auto start = tick(); VectorNd hp_mu; MatrixNNd hp_LambdaF; MatrixNNd hp_LambdaL; if (has_prop_posterior()) { hp_mu = propMu.col(idx); hp_LambdaF = Eigen::Map<MatrixNNd>(propLambda.col(idx).data()); hp_LambdaL = hp_LambdaF.llt().matrixL(); } else { hp_mu = hp.mu; hp_LambdaF = hp.LambdaF; hp_LambdaL = hp.LambdaL; } VectorNd rr = hp_LambdaF * hp.mu; // vector num_latent x 1, we will use it in formula (14) from the paper MatrixNNd MM(MatrixNNd::Zero()); PrecomputedLLT chol; // matrix num_latent x num_latent, chol="lambda_i with *" from formula (14) #ifdef BPMF_REDUCE rr += precMu.col(idx); MM += precLambdaMatrix(idx); #else computeMuLambda(idx, other, rr, MM, false); #endif // copy upper -> lower part, matrix is symmetric. MM.triangularView<Eigen::Lower>() = MM.transpose(); chol.compute(hp_LambdaF + alpha * MM); if(chol.info() != Eigen::Success) THROWERROR("Cholesky failed"); // now we should calculate formula (14) from the paper // u_i for k-th iteration = Gaussian distribution N(u_i | mu_i with *, [lambda_i with *]^-1) = // = mu_i with * + s * [U]^-1, // where // s is a random vector with N(0, I), // mu_i with * is a vector num_latent x 1, // mu_i with * = [lambda_i with *]^-1 * rr, // lambda_i with * = L * U // Expression u_i = U \ (s + (L \ rr)) in Matlab looks for Eigen library like: chol.matrixL().solveInPlace(rr); // L*Y=rr => Y=L\rr, we store Y result again in rr vector rr += nrandn(num_latent); // rr=s+(L\rr), we store result again in rr vector chol.matrixU().solveInPlace(rr); // u_i=U\rr items().col(idx) = rr; // we save rr vector in items matrix (it is user features matrix) auto stop = tick(); register_time(idx, 1e6 * (stop - start)); //Sys::cout() << " " << count << ": " << 1e6*(stop - start) << std::endl; assert(rr.norm() > .0); return rr; } // // update ALL movies / users in parallel // void Sys::sample(Sys &other) { iter++; thread_vector<VectorNd> sums(VectorNd::Zero()); // sum thread_vector<double> norms(0.0); // squared norm thread_vector<MatrixNNd> prods(MatrixNNd::Zero()); // outer prod #pragma omp parallel for schedule(guided) for (int i = from(); i < to(); ++i) { #pragma omp task { auto r = sample(i, other); MatrixNNd cov = (r * r.transpose()); prods.local() += cov; sums.local() += r; norms.local() += r.squaredNorm(); if (iter >= burnin && Sys::odirname.size()) { aggrMu.col(i) += r; aggrLambda.col(i) += Eigen::Map<Eigen::VectorXd>(cov.data(), num_latent * num_latent); } send_item(i); } } #pragma omp taskwait #ifdef BPMF_REDUCE other.preComputeMuLambda(*this); #endif VectorNd sum = sums.combine(); MatrixNNd prod = prods.combine(); double norm = norms.combine(); const int N = num(); local_sum() = sum; local_cov() = (prod - (sum * sum.transpose() / N)) / (N-1); local_norm() = norm; } void Sys::register_time(int i, double t) { if (measure_perf) sample_time.at(i) += t; }<|endoftext|>
<commit_before>#include "Model.h" #include <tiny_obj_loader.h> #include <vector> static const char* g_vertexShaderSource = R"(#version 150 in vec3 Position; in vec3 Normal; in vec2 TexCoord0; uniform mat4 uWorldMatrix; uniform mat4 uViewProjMatrix; out vec3 vWorldNormal; out vec2 vTexCoord0; out vec3 vWorldPosition; void main() { vec3 worldPosition = vec3(uWorldMatrix * vec4(Position, 1)); vec3 worldNormal = normalize(vec3(mat3(uWorldMatrix) * Normal)); gl_Position = uViewProjMatrix * vec4(worldPosition, 1); vWorldPosition = worldPosition; vWorldNormal = worldNormal; vTexCoord0 = TexCoord0; } )"; static const char* g_pixelShaderSource = R"(#version 150 out vec4 Target; in vec2 vTexCoord0; in vec3 vWorldNormal; in vec3 vWorldPosition; uniform sampler2D Texture0; #define PI 3.14159265358979323846 vec2 cartesianToLatLongTexcoord(vec3 p) { float u = (1.0 + atan(p.x, -p.z) / PI); float v = acos(p.y) / PI; return vec2(u * 0.5, v); } void main() { vec3 albedo = vec3(1.0); vec3 normal = normalize(vWorldNormal); vec2 texCoord = cartesianToLatLongTexcoord(normal); vec3 irradiance = texture(Texture0, texCoord).xyz; vec3 color = albedo * irradiance; Target = vec4(color, 1.0); } )"; Model::Model(const char* objFilename) { auto vertexShader = createShaderFromSource(GL_VERTEX_SHADER, g_vertexShaderSource); auto pixelShaderTexture2D = createShaderFromSource(GL_FRAGMENT_SHADER, g_pixelShaderSource); m_shaderProgram = createShaderProgram( *vertexShader, *pixelShaderTexture2D, m_vertexDeclaration); const bool forceGenerateNormals = true; readObj(objFilename, forceGenerateNormals); } Model::~Model() { glDeleteBuffers(1, &m_vertexBuffer); glDeleteBuffers(1, &m_indexBuffer); } bool Model::readObj(const char* objFilename, bool forceGenerateNormals) { std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string errors; m_valid = tinyobj::LoadObj(shapes, materials, errors, objFilename); if (!m_valid) { printf("ERROR: Could not load model from '%s'\n%s\n", objFilename, errors.c_str()); return m_valid; } std::vector<Vertex> vertices; std::vector<u32> indices; m_boundsMin = vec3(FLT_MAX); m_boundsMax = vec3(-FLT_MAX); for (const auto& shape : shapes) { u32 firstVertex = (u32)vertices.size(); const auto& mesh = shape.mesh; const u32 vertexCount = (u32)mesh.positions.size() / 3; const bool haveNormals = mesh.positions.size() == mesh.normals.size(); const bool haveTexCoords = mesh.positions.size() == mesh.texcoords.size(); for (u32 i = 0; i < vertexCount; ++i) { Vertex v = {}; v.position.x = mesh.positions[i * 3 + 0]; v.position.y = mesh.positions[i * 3 + 1]; v.position.z = mesh.positions[i * 3 + 2]; if (haveTexCoords) { v.texCoord.x = mesh.texcoords[i * 2 + 0]; v.texCoord.y = mesh.texcoords[i * 2 + 1]; } if (haveNormals) { v.normal.x = mesh.normals[i * 3 + 0]; v.normal.y = mesh.normals[i * 3 + 1]; v.normal.y = mesh.normals[i * 3 + 2]; } vertices.push_back(v); m_boundsMin = min(m_boundsMin, v.position); m_boundsMax = max(m_boundsMax, v.position); } if (!haveNormals || forceGenerateNormals) { const u32 triangleCount = (u32)mesh.indices.size() / 3; for (u32 i = 0; i < triangleCount; ++i) { u32 idxA = firstVertex + mesh.indices[i * 3 + 0]; u32 idxB = firstVertex + mesh.indices[i * 3 + 1]; u32 idxC = firstVertex + mesh.indices[i * 3 + 2]; vec3 a = vertices[idxA].position; vec3 b = vertices[idxB].position; vec3 c = vertices[idxC].position; vec3 normal = cross(b - a, c - b); normal = normalize(normal); vertices[idxA].normal += normal; vertices[idxB].normal += normal; vertices[idxC].normal += normal; } for (u32 i = firstVertex; i < (u32)vertices.size(); ++i) { vertices[i].normal = normalize(vertices[i].normal); } } for (u32 index : mesh.indices) { indices.push_back(index + firstVertex); } m_indexCount = (u32)indices.size(); } m_dimensions = m_boundsMax - m_boundsMin; m_center = (m_boundsMax + m_boundsMin) / 2.0f; glGenBuffers(1, &m_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW); glGenBuffers(1, &m_indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(u32), indices.data(), GL_STATIC_DRAW); return m_valid; } void Model::draw( const Texture& irradianceTexture, const mat4& worldMatrix, const mat4& viewProjMatrix) { if (!m_valid) return; glUseProgram(m_shaderProgram->m_native); setTexture(*m_shaderProgram, 0, irradianceTexture); setUniformByName(*m_shaderProgram, "uWorldMatrix", worldMatrix); setUniformByName(*m_shaderProgram, "uViewProjMatrix", viewProjMatrix); setVertexBuffer(*m_shaderProgram, m_vertexBuffer, sizeof(Vertex)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, nullptr); } <commit_msg>Fixed normals in loaded obj models<commit_after>#include "Model.h" #include <tiny_obj_loader.h> #include <vector> static const char* g_vertexShaderSource = R"(#version 150 in vec3 Position; in vec3 Normal; in vec2 TexCoord0; uniform mat4 uWorldMatrix; uniform mat4 uViewProjMatrix; out vec3 vWorldNormal; out vec2 vTexCoord0; out vec3 vWorldPosition; void main() { vec3 worldPosition = vec3(uWorldMatrix * vec4(Position, 1)); vec3 worldNormal = normalize(vec3(mat3(uWorldMatrix) * Normal)); gl_Position = uViewProjMatrix * vec4(worldPosition, 1); vWorldPosition = worldPosition; vWorldNormal = worldNormal; vTexCoord0 = TexCoord0; } )"; static const char* g_pixelShaderSource = R"(#version 150 out vec4 Target; in vec2 vTexCoord0; in vec3 vWorldNormal; in vec3 vWorldPosition; uniform sampler2D Texture0; #define PI 3.14159265358979323846 vec2 cartesianToLatLongTexcoord(vec3 p) { float u = (1.0 + atan(p.x, -p.z) / PI); float v = acos(p.y) / PI; return vec2(u * 0.5, v); } void main() { vec3 albedo = vec3(1.0); vec3 normal = normalize(vWorldNormal); vec2 texCoord = cartesianToLatLongTexcoord(normal); vec3 irradiance = texture(Texture0, texCoord).xyz; vec3 color = albedo * irradiance; Target = vec4(color, 1.0); } )"; Model::Model(const char* objFilename) { auto vertexShader = createShaderFromSource(GL_VERTEX_SHADER, g_vertexShaderSource); auto pixelShaderTexture2D = createShaderFromSource(GL_FRAGMENT_SHADER, g_pixelShaderSource); m_shaderProgram = createShaderProgram( *vertexShader, *pixelShaderTexture2D, m_vertexDeclaration); const bool forceGenerateNormals = false; readObj(objFilename, forceGenerateNormals); } Model::~Model() { glDeleteBuffers(1, &m_vertexBuffer); glDeleteBuffers(1, &m_indexBuffer); } bool Model::readObj(const char* objFilename, bool forceGenerateNormals) { std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string errors; m_valid = tinyobj::LoadObj(shapes, materials, errors, objFilename); if (!m_valid) { printf("ERROR: Could not load model from '%s'\n%s\n", objFilename, errors.c_str()); return m_valid; } std::vector<Vertex> vertices; std::vector<u32> indices; m_boundsMin = vec3(FLT_MAX); m_boundsMax = vec3(-FLT_MAX); for (const auto& shape : shapes) { u32 firstVertex = (u32)vertices.size(); const auto& mesh = shape.mesh; const u32 vertexCount = (u32)mesh.positions.size() / 3; const bool haveNormals = mesh.positions.size() == mesh.normals.size(); const bool haveTexCoords = mesh.positions.size() == mesh.texcoords.size(); for (u32 i = 0; i < vertexCount; ++i) { Vertex v = {}; v.position.x = mesh.positions[i * 3 + 0]; v.position.y = mesh.positions[i * 3 + 1]; v.position.z = mesh.positions[i * 3 + 2]; if (haveTexCoords) { v.texCoord.x = mesh.texcoords[i * 2 + 0]; v.texCoord.y = mesh.texcoords[i * 2 + 1]; } if (haveNormals) { v.normal.x = mesh.normals[i * 3 + 0]; v.normal.y = mesh.normals[i * 3 + 1]; v.normal.z = mesh.normals[i * 3 + 2]; } vertices.push_back(v); m_boundsMin = min(m_boundsMin, v.position); m_boundsMax = max(m_boundsMax, v.position); } if (!haveNormals || forceGenerateNormals) { const u32 triangleCount = (u32)mesh.indices.size() / 3; for (u32 i = 0; i < triangleCount; ++i) { u32 idxA = firstVertex + mesh.indices[i * 3 + 0]; u32 idxB = firstVertex + mesh.indices[i * 3 + 1]; u32 idxC = firstVertex + mesh.indices[i * 3 + 2]; vec3 a = vertices[idxA].position; vec3 b = vertices[idxB].position; vec3 c = vertices[idxC].position; vec3 normal = cross(b - a, c - b); normal = normalize(normal); vertices[idxA].normal += normal; vertices[idxB].normal += normal; vertices[idxC].normal += normal; } for (u32 i = firstVertex; i < (u32)vertices.size(); ++i) { vertices[i].normal = normalize(vertices[i].normal); } } for (u32 index : mesh.indices) { indices.push_back(index + firstVertex); } m_indexCount = (u32)indices.size(); } m_dimensions = m_boundsMax - m_boundsMin; m_center = (m_boundsMax + m_boundsMin) / 2.0f; glGenBuffers(1, &m_vertexBuffer); glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(Vertex), vertices.data(), GL_STATIC_DRAW); glGenBuffers(1, &m_indexBuffer); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(u32), indices.data(), GL_STATIC_DRAW); return m_valid; } void Model::draw( const Texture& irradianceTexture, const mat4& worldMatrix, const mat4& viewProjMatrix) { if (!m_valid) return; glUseProgram(m_shaderProgram->m_native); setTexture(*m_shaderProgram, 0, irradianceTexture); setUniformByName(*m_shaderProgram, "uWorldMatrix", worldMatrix); setUniformByName(*m_shaderProgram, "uViewProjMatrix", viewProjMatrix); setVertexBuffer(*m_shaderProgram, m_vertexBuffer, sizeof(Vertex)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_indexBuffer); glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glDepthFunc(GL_LEQUAL); glDrawElements(GL_TRIANGLES, m_indexCount, GL_UNSIGNED_INT, nullptr); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nbdll.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 16:33:14 $ * * 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 * ************************************************************************/ #ifdef WIN #ifndef _SVWIN_H #include <svwin.h> #endif #ifndef _SYSDEP_HXX #include <sysdep.hxx> #endif // Statische DLL-Verwaltungs-Variablen static HINSTANCE hDLLInst = 0; // HANDLE der DLL /*************************************************************************** |* |* LibMain() |* |* Beschreibung Initialisierungsfunktion der DLL |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR ) { #ifndef WNT if ( nHeap ) UnlockData( 0 ); #endif hDLLInst = hDLL; return TRUE; } /*************************************************************************** |* |* WEP() |* |* Beschreibung DLL-Deinitialisierung |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK WEP( int ) { return 1; } #endif <commit_msg>INTEGRATION: CWS pchfix02 (1.2.326); FILE MERGED 2006/09/01 17:43:26 kaib 1.2.326.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: nbdll.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: obo $ $Date: 2006-09-17 15:20:14 $ * * 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_svtools.hxx" #ifdef WIN #ifndef _SVWIN_H #include <svwin.h> #endif #ifndef _SYSDEP_HXX #include <sysdep.hxx> #endif // Statische DLL-Verwaltungs-Variablen static HINSTANCE hDLLInst = 0; // HANDLE der DLL /*************************************************************************** |* |* LibMain() |* |* Beschreibung Initialisierungsfunktion der DLL |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK LibMain( HINSTANCE hDLL, WORD, WORD nHeap, LPSTR ) { #ifndef WNT if ( nHeap ) UnlockData( 0 ); #endif hDLLInst = hDLL; return TRUE; } /*************************************************************************** |* |* WEP() |* |* Beschreibung DLL-Deinitialisierung |* Ersterstellung TH 05.05.93 |* Letzte Aenderung TH 05.05.93 |* ***************************************************************************/ extern "C" int CALLBACK WEP( int ) { return 1; } #endif <|endoftext|>
<commit_before>#include <ORM/backends/Sqlite3.hpp> orm::Sqlite3Bdd def("./salamandre.db"); orm::Bdd& orm::Bdd::Default = def; #include <Salamandre-stats/stats.hpp> float Stats::default_robustesse = 99.9f; void Stats::init() { orm::Bdd::Default.connect(); orm::Tables::create(); } void Stats::close() { orm::Bdd::Default.disconnect(); } void Stats::add_node(std::string host, int port) { orm::Cache<Node>::type_ptr node; std::list<orm::Cache<Node>::type_ptr> results; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(results); if (results.size() > 0) { node = results.front(); } else { node = orm::Cache<Node>::type_ptr(new Node()); node->host = host; node->port = port; } node->last_seen_time = time(NULL); node->save(); } void Stats::delete_node(std::string host, int port) { Node node; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(node); node.del(); } std::list<std::shared_ptr<Node>> Stats::get_nodes(unsigned int number) { std::list<std::shared_ptr<Node>> list; Node::query()\ //.filter(...) //.orderBy(...) .limit(number)\ .get(list); const unsigned int _size = list.size(); if(_size > 0) { //ajout du nombre de node qu'il manque unsigned int diff = number - _size; std::list<std::shared_ptr<Node>>::iterator current = list.begin(); while(diff > 0) { list.push_back(*current); ++current; --diff; } } return list; } unsigned int Stats::get_duplication_number_for(float robustesse) { //\todo TODO return 4; } <commit_msg>add romdom ordering for get nodes<commit_after>#include <ORM/backends/Sqlite3.hpp> orm::Sqlite3Bdd def("./salamandre.db"); orm::Bdd& orm::Bdd::Default = def; #include <Salamandre-stats/stats.hpp> float Stats::default_robustesse = 99.9f; void Stats::init() { orm::Bdd::Default.connect(); orm::Tables::create(); } void Stats::close() { orm::Bdd::Default.disconnect(); } void Stats::add_node(std::string host, int port) { orm::Cache<Node>::type_ptr node; std::list<orm::Cache<Node>::type_ptr> results; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(results); if (results.size() > 0) { node = results.front(); } else { node = orm::Cache<Node>::type_ptr(new Node()); node->host = host; node->port = port; } node->last_seen_time = time(NULL); node->save(); } void Stats::delete_node(std::string host, int port) { Node node; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(node); node.del(); } std::list<std::shared_ptr<Node>> Stats::get_nodes(unsigned int number) { std::list<std::shared_ptr<Node>> list; Node::query()\ //.filter(...) .orderBy("?") .limit(number)\ .get(list); const unsigned int _size = list.size(); if(_size > 0) { //ajout du nombre de node qu'il manque unsigned int diff = number - _size; std::list<std::shared_ptr<Node>>::iterator current = list.begin(); while(diff > 0) { list.push_back(*current); ++current; --diff; } } return list; } unsigned int Stats::get_duplication_number_for(float robustesse) { //\todo TODO return 4; } <|endoftext|>
<commit_before>#include <ORM/backends/Sqlite3.hpp> orm::Sqlite3Bdd def("./salamandre.db"); orm::Bdd& orm::Bdd::Default = def; #include <Salamandre-stats/stats.hpp> using namespace salamandre::stats; float Stats::default_robustesse = 99.9f; void Stats::init() { orm::Bdd::Default.connect(); orm::Tables::create(); } void Stats::close() { orm::Bdd::Default.disconnect(); } void Stats::add_node(std::string host, int port) { orm::Cache<Node>::type_ptr node; std::list<orm::Cache<Node>::type_ptr> results; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(results); if (results.size() > 0) { node = results.front(); } else { node = orm::Cache<Node>::type_ptr(new Node()); node->host = host; node->port = port; } node->last_seen_time = time(NULL); node->save(); } void Stats::delete_node(std::string host, int port) { Node node; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(node); node.del(); } std::list<std::shared_ptr<Node>> Stats::get_nodes(unsigned int number) { std::list<std::shared_ptr<Node>> list; Node::query()\ //.filter(...) .orderBy("?") .limit(number)\ .get(list); const unsigned int _size = list.size(); if(_size > 0) { //ajout du nombre de node qu'il manque unsigned int diff = number - _size; std::list<std::shared_ptr<Node>>::iterator current = list.begin(); while(diff > 0) { list.push_back(*current); ++current; --diff; } } return list; } unsigned int Stats::get_duplication_number_for(float robustesse) { //\todo TODO return 4; } <commit_msg>[stats] Get only most recent nodes<commit_after>#include <ORM/backends/Sqlite3.hpp> orm::Sqlite3Bdd def("./salamandre.db"); orm::Bdd& orm::Bdd::Default = def; #include <Salamandre-stats/stats.hpp> using namespace salamandre::stats; float Stats::default_robustesse = 99.9f; void Stats::init() { orm::Bdd::Default.connect(); orm::Tables::create(); } void Stats::close() { orm::Bdd::Default.disconnect(); } void Stats::add_node(std::string host, int port) { orm::Cache<Node>::type_ptr node; std::list<orm::Cache<Node>::type_ptr> results; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(results); if (results.size() > 0) { node = results.front(); } else { node = orm::Cache<Node>::type_ptr(new Node()); node->host = host; node->port = port; } node->last_seen_time = time(NULL); node->save(); } void Stats::delete_node(std::string host, int port) { Node node; Node::query().filter(host, "exact", Node::_host).filter(port, "exact", Node::_port).get(node); node.del(); } std::list<std::shared_ptr<Node>> Stats::get_nodes(unsigned int number) { std::list<std::shared_ptr<Node>> list; Node::query()\ //.filter(...) .orderBy("last_seen_time", '-') .limit(number)\ .get(list); const unsigned int _size = list.size(); if(_size > 0) { //ajout du nombre de node qu'il manque unsigned int diff = number - _size; std::list<std::shared_ptr<Node>>::iterator current = list.begin(); while(diff > 0) { list.push_back(*current); ++current; --diff; } } return list; } unsigned int Stats::get_duplication_number_for(float robustesse) { //\todo TODO return 4; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ParseContext.cxx,v $ * * $Revision: 1.9 $ * * last change: $Author: obo $ $Date: 2006-10-12 12:44: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 * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef SVX_QUERYDESIGNCONTEXT_HXX #include "ParseContext.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include <svtools/syslocale.hxx> #endif #ifndef _SVX_FMRESIDS_HRC #include "fmresids.hrc" #endif #include "dialmgr.hxx" #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif using namespace svxform; using namespace ::connectivity; //========================================================================== //= OSystemParseContext //========================================================================== DBG_NAME(OSystemParseContext) //----------------------------------------------------------------------------- OSystemParseContext::OSystemParseContext() : IParseContext() { DBG_CTOR(OSystemParseContext,NULL); vos::OGuard aGuard( Application::GetSolarMutex() ); m_aSQLInternationals = ByteString(SVX_RES(RID_STR_SVT_SQL_INTERNATIONAL),RTL_TEXTENCODING_UTF8); } //----------------------------------------------------------------------------- OSystemParseContext::~OSystemParseContext() { DBG_DTOR(OSystemParseContext,NULL); } //----------------------------------------------------------------------------- ::com::sun::star::lang::Locale OSystemParseContext::getPreferredLocale( ) const { return SvtSysLocale().GetLocaleData().getLocale(); } //----------------------------------------------------------------------------- ::rtl::OUString OSystemParseContext::getErrorMessage(ErrorCode _eCode) const { String aMsg; vos::OGuard aGuard( Application::GetSolarMutex() ); switch (_eCode) { case ERROR_GENERAL: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_ERROR); break; case ERROR_VALUE_NO_LIKE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_VALUE_NO_LIKE); break; case ERROR_FIELD_NO_LIKE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_FIELD_NO_LIKE); break; case ERROR_INVALID_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_CRIT_NO_COMPARE); break; case ERROR_INVALID_INT_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_INT_NO_VALID); break; case ERROR_INVALID_DATE_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_ACCESS_DAT_NO_VALID); break; case ERROR_INVALID_REAL_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_REAL_NO_VALID); break; case ERROR_INVALID_TABLE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE); break; case ERROR_INVALID_TABLE_OR_QUERY: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE_OR_QUERY); break; case ERROR_INVALID_COLUMN: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_COLUMN); break; case ERROR_INVALID_TABLE_EXIST: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE_EXISTS); break; case ERROR_INVALID_QUERY_EXIST: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_QUERY_EXISTS); break; case ERROR_CYCLIC_SUB_QUERIES: aMsg = SVX_RES(RID_STR_SVT_SQL_CYCLIC_SUB_QUERIES); break; case ERROR_NONE: break; } return aMsg; } //----------------------------------------------------------------------------- ::rtl::OString OSystemParseContext::getIntlKeywordAscii(InternationalKeyCode _eKey) const { ByteString aKeyword; switch (_eKey) { case KEY_LIKE: aKeyword = m_aSQLInternationals.GetToken(0); break; case KEY_NOT: aKeyword = m_aSQLInternationals.GetToken(1); break; case KEY_NULL: aKeyword = m_aSQLInternationals.GetToken(2); break; case KEY_TRUE: aKeyword = m_aSQLInternationals.GetToken(3); break; case KEY_FALSE: aKeyword = m_aSQLInternationals.GetToken(4); break; case KEY_IS: aKeyword = m_aSQLInternationals.GetToken(5); break; case KEY_BETWEEN: aKeyword = m_aSQLInternationals.GetToken(6); break; case KEY_OR: aKeyword = m_aSQLInternationals.GetToken(7); break; case KEY_AND: aKeyword = m_aSQLInternationals.GetToken(8); break; case KEY_AVG: aKeyword = m_aSQLInternationals.GetToken(9); break; case KEY_COUNT: aKeyword = m_aSQLInternationals.GetToken(10); break; case KEY_MAX: aKeyword = m_aSQLInternationals.GetToken(11); break; case KEY_MIN: aKeyword = m_aSQLInternationals.GetToken(12); break; case KEY_SUM: aKeyword = m_aSQLInternationals.GetToken(13); break; case KEY_NONE: DBG_ERROR( "OSystemParseContext::getIntlKeywordAscii: illegal argument!" ); break; } return aKeyword; } //----------------------------------------------------------------------------- static sal_Unicode lcl_getSeparatorChar( const String& _rSeparator, sal_Unicode _nFallback ) { DBG_ASSERT( 0 < _rSeparator.Len(), "::lcl_getSeparatorChar: invalid decimal separator!" ); sal_Unicode nReturn( _nFallback ); if ( _rSeparator.Len() ) nReturn = static_cast< sal_Char >( _rSeparator.GetBuffer( )[0] ); return nReturn; } //----------------------------------------------------------------------------- sal_Unicode OSystemParseContext::getNumDecimalSep( ) const { return lcl_getSeparatorChar( SvtSysLocale().GetLocaleData().getNumDecimalSep(), '.' ); } //----------------------------------------------------------------------------- sal_Unicode OSystemParseContext::getNumThousandSep( ) const { return lcl_getSeparatorChar( SvtSysLocale().GetLocaleData().getNumThousandSep(), ',' ); } // ----------------------------------------------------------------------------- IParseContext::InternationalKeyCode OSystemParseContext::getIntlKeyCode(const ::rtl::OString& rToken) const { static IParseContext::InternationalKeyCode Intl_TokenID[] = { KEY_LIKE, KEY_NOT, KEY_NULL, KEY_TRUE, KEY_FALSE, KEY_IS, KEY_BETWEEN, KEY_OR, KEY_AND, KEY_AVG, KEY_COUNT, KEY_MAX, KEY_MIN, KEY_SUM }; sal_uInt32 nCount = sizeof Intl_TokenID / sizeof Intl_TokenID[0]; for (sal_uInt32 i = 0; i < nCount; i++) { ::rtl::OString aKey = getIntlKeywordAscii(Intl_TokenID[i]); if (rToken.equalsIgnoreAsciiCase(aKey)) return Intl_TokenID[i]; } return KEY_NONE; } // ============================================================================= // ============================================================================= namespace { // ----------------------------------------------------------------------------- ::osl::Mutex& getSafteyMutex() { static ::osl::Mutex s_aSafety; return s_aSafety; } // ----------------------------------------------------------------------------- oslInterlockedCount& getCounter() { static oslInterlockedCount s_nCounter; return s_nCounter; } // ----------------------------------------------------------------------------- OSystemParseContext* getSharedContext(OSystemParseContext* _pContext = NULL,sal_Bool _bSet = sal_False) { static OSystemParseContext* s_pSharedContext = NULL; if ( _pContext && !s_pSharedContext || _bSet ) s_pSharedContext = _pContext; return s_pSharedContext; } // ----------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- OParseContextClient::OParseContextClient() { ::osl::MutexGuard aGuard( getSafteyMutex() ); if ( 1 == osl_incrementInterlockedCount( &getCounter() ) ) { // first instance getSharedContext( new OSystemParseContext ); } } // ----------------------------------------------------------------------------- OParseContextClient::~OParseContextClient() { { ::osl::MutexGuard aGuard( getSafteyMutex() ); if ( 0 == osl_decrementInterlockedCount( &getCounter() ) ) delete getSharedContext(NULL,sal_True); } } // ----------------------------------------------------------------------------- const OSystemParseContext* OParseContextClient::getParseContext() const { return getSharedContext(); } // ----------------------------------------------------------------------------- <commit_msg>INTEGRATION: CWS dba23a (1.9.232); FILE MERGED 2007/03/01 12:40:38 fs 1.9.232.1: #i73819#<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: ParseContext.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: kz $ $Date: 2007-05-10 10:05:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #ifndef SVX_QUERYDESIGNCONTEXT_HXX #include "ParseContext.hxx" #endif #ifndef _TOOLS_DEBUG_HXX #include <tools/debug.hxx> #endif #ifndef INCLUDED_SVTOOLS_SYSLOCALE_HXX #include <svtools/syslocale.hxx> #endif #ifndef _SVX_FMRESIDS_HRC #include "fmresids.hrc" #endif #include "dialmgr.hxx" #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif #ifndef _VOS_MUTEX_HXX_ #include <vos/mutex.hxx> #endif using namespace svxform; using namespace ::connectivity; //========================================================================== //= OSystemParseContext //========================================================================== DBG_NAME(OSystemParseContext) //----------------------------------------------------------------------------- OSystemParseContext::OSystemParseContext() : IParseContext() { DBG_CTOR(OSystemParseContext,NULL); vos::OGuard aGuard( Application::GetSolarMutex() ); m_aSQLInternationals = ByteString(SVX_RES(RID_STR_SVT_SQL_INTERNATIONAL),RTL_TEXTENCODING_UTF8); } //----------------------------------------------------------------------------- OSystemParseContext::~OSystemParseContext() { DBG_DTOR(OSystemParseContext,NULL); } //----------------------------------------------------------------------------- ::com::sun::star::lang::Locale OSystemParseContext::getPreferredLocale( ) const { return SvtSysLocale().GetLocaleData().getLocale(); } //----------------------------------------------------------------------------- ::rtl::OUString OSystemParseContext::getErrorMessage(ErrorCode _eCode) const { String aMsg; vos::OGuard aGuard( Application::GetSolarMutex() ); switch (_eCode) { case ERROR_GENERAL: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_ERROR); break; case ERROR_VALUE_NO_LIKE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_VALUE_NO_LIKE); break; case ERROR_FIELD_NO_LIKE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_FIELD_NO_LIKE); break; case ERROR_INVALID_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_CRIT_NO_COMPARE); break; case ERROR_INVALID_INT_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_INT_NO_VALID); break; case ERROR_INVALID_DATE_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_ACCESS_DAT_NO_VALID); break; case ERROR_INVALID_REAL_COMPARE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_REAL_NO_VALID); break; case ERROR_INVALID_TABLE: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE); break; case ERROR_INVALID_TABLE_OR_QUERY: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE_OR_QUERY); break; case ERROR_INVALID_COLUMN: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_COLUMN); break; case ERROR_INVALID_TABLE_EXIST: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_TABLE_EXISTS); break; case ERROR_INVALID_QUERY_EXIST: aMsg = SVX_RES(RID_STR_SVT_SQL_SYNTAX_QUERY_EXISTS); break; case ERROR_CYCLIC_SUB_QUERIES: aMsg = SVX_RES(RID_STR_SVT_SQL_CYCLIC_SUB_QUERIES); break; case ERROR_NONE: break; } return aMsg; } //----------------------------------------------------------------------------- ::rtl::OString OSystemParseContext::getIntlKeywordAscii(InternationalKeyCode _eKey) const { ByteString aKeyword; switch (_eKey) { case KEY_LIKE: aKeyword = m_aSQLInternationals.GetToken(0); break; case KEY_NOT: aKeyword = m_aSQLInternationals.GetToken(1); break; case KEY_NULL: aKeyword = m_aSQLInternationals.GetToken(2); break; case KEY_TRUE: aKeyword = m_aSQLInternationals.GetToken(3); break; case KEY_FALSE: aKeyword = m_aSQLInternationals.GetToken(4); break; case KEY_IS: aKeyword = m_aSQLInternationals.GetToken(5); break; case KEY_BETWEEN: aKeyword = m_aSQLInternationals.GetToken(6); break; case KEY_OR: aKeyword = m_aSQLInternationals.GetToken(7); break; case KEY_AND: aKeyword = m_aSQLInternationals.GetToken(8); break; case KEY_AVG: aKeyword = m_aSQLInternationals.GetToken(9); break; case KEY_COUNT: aKeyword = m_aSQLInternationals.GetToken(10); break; case KEY_MAX: aKeyword = m_aSQLInternationals.GetToken(11); break; case KEY_MIN: aKeyword = m_aSQLInternationals.GetToken(12); break; case KEY_SUM: aKeyword = m_aSQLInternationals.GetToken(13); break; case KEY_NONE: DBG_ERROR( "OSystemParseContext::getIntlKeywordAscii: illegal argument!" ); break; } return aKeyword; } //----------------------------------------------------------------------------- static sal_Unicode lcl_getSeparatorChar( const String& _rSeparator, sal_Unicode _nFallback ) { DBG_ASSERT( 0 < _rSeparator.Len(), "::lcl_getSeparatorChar: invalid decimal separator!" ); sal_Unicode nReturn( _nFallback ); if ( _rSeparator.Len() ) nReturn = static_cast< sal_Char >( _rSeparator.GetBuffer( )[0] ); return nReturn; } //----------------------------------------------------------------------------- sal_Unicode OSystemParseContext::getNumDecimalSep( ) const { return lcl_getSeparatorChar( SvtSysLocale().GetLocaleData().getNumDecimalSep(), '.' ); } //----------------------------------------------------------------------------- sal_Unicode OSystemParseContext::getNumThousandSep( ) const { return lcl_getSeparatorChar( SvtSysLocale().GetLocaleData().getNumThousandSep(), ',' ); } // ----------------------------------------------------------------------------- IParseContext::InternationalKeyCode OSystemParseContext::getIntlKeyCode(const ::rtl::OString& rToken) const { static IParseContext::InternationalKeyCode Intl_TokenID[] = { KEY_LIKE, KEY_NOT, KEY_NULL, KEY_TRUE, KEY_FALSE, KEY_IS, KEY_BETWEEN, KEY_OR, KEY_AND, KEY_AVG, KEY_COUNT, KEY_MAX, KEY_MIN, KEY_SUM }; sal_uInt32 nCount = sizeof Intl_TokenID / sizeof Intl_TokenID[0]; for (sal_uInt32 i = 0; i < nCount; i++) { ::rtl::OString aKey = getIntlKeywordAscii(Intl_TokenID[i]); if (rToken.equalsIgnoreAsciiCase(aKey)) return Intl_TokenID[i]; } return KEY_NONE; } // ============================================================================= // ============================================================================= namespace { // ----------------------------------------------------------------------------- ::osl::Mutex& getSafteyMutex() { static ::osl::Mutex s_aSafety; return s_aSafety; } // ----------------------------------------------------------------------------- oslInterlockedCount& getCounter() { static oslInterlockedCount s_nCounter; return s_nCounter; } // ----------------------------------------------------------------------------- OSystemParseContext* getSharedContext(OSystemParseContext* _pContext = NULL,sal_Bool _bSet = sal_False) { static OSystemParseContext* s_pSharedContext = NULL; if ( _pContext && !s_pSharedContext ) { s_pSharedContext = _pContext; return s_pSharedContext; } if ( _bSet ) { OSystemParseContext* pReturn = _pContext ? _pContext : s_pSharedContext; s_pSharedContext = _pContext; return pReturn; } return s_pSharedContext; } // ----------------------------------------------------------------------------- } // ----------------------------------------------------------------------------- OParseContextClient::OParseContextClient() { ::osl::MutexGuard aGuard( getSafteyMutex() ); if ( 1 == osl_incrementInterlockedCount( &getCounter() ) ) { // first instance getSharedContext( new OSystemParseContext ); } } // ----------------------------------------------------------------------------- OParseContextClient::~OParseContextClient() { { ::osl::MutexGuard aGuard( getSafteyMutex() ); if ( 0 == osl_decrementInterlockedCount( &getCounter() ) ) delete getSharedContext(NULL,sal_True); } } // ----------------------------------------------------------------------------- const OSystemParseContext* OParseContextClient::getParseContext() const { return getSharedContext(); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>#include <chrono> #include <exception> #include <stdexcept> // __gnu_cxx::__verbose_terminate_handler #include <fstream> #include <iostream> #include <thread> #include <libtorrent/add_torrent_params.hpp> #include <libtorrent/alert_types.hpp> #include <libtorrent/bencode.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/session.hpp> #include <libtorrent/storage_defs.hpp> // lt::disabled_storage_constructor #include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_info.hpp> namespace lt = libtorrent; int main(int argc, char *argv[]) { std::set_terminate(__gnu_cxx::__verbose_terminate_handler); if (argc != 2) { std::cerr << "usage: " << argv[0] << " <magnet-url>" << std::endl; return 1; } lt::session sess; lt::add_torrent_params atp; atp.url = argv[1]; atp.upload_mode = true; atp.auto_managed = false; atp.paused = false; // Start with "storage == disabled" to avoid pre-allocating any files // mentioned in the torrent file on disk: atp.storage = lt::disabled_storage_constructor; atp.save_path = "."; // save in current dir /* // .flags duplicate .upload_mode/auto_managed/paused // functionality: atp.flags = lt::add_torrent_params::flag_update_subscribe | lt::add_torrent_params::flag_upload_mode | lt::add_torrent_params::flag_apply_ip_filter; */ lt::torrent_handle torh = sess.add_torrent(atp); std::cout << atp.url << ":"; for (;;) { std::deque<lt::alert*> alerts; sess.pop_alerts(&alerts); for (lt::alert const* a : alerts) { std::cout << std::endl << a->message() << std::endl; // quit on error/finish: if (lt::alert_cast<lt::torrent_finished_alert>(a) || lt::alert_cast<lt::torrent_error_alert>(a)) { goto done1; }; } if (torh.status().has_metadata) { sess.pause(); lt::torrent_info tinf = torh.get_torrent_info(); std::cout << tinf.name() << std::endl; std::cout.flush(); std::ofstream ofs; ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit); ofs.open(tinf.name() + ".torrent", std::ofstream::binary); std::ostream_iterator<char> ofsi(ofs); lt::bencode(ofsi, lt::create_torrent(tinf) .generate()); ofs.close(); sess.remove_torrent(torh); goto done0; }; std::cout << "."; std::cout.flush(); std::this_thread::sleep_for( std::chrono::milliseconds(1000)); } done0: return 0; done1: return 1; } // vi: set sw=8 ts=8 noet tw=77: <commit_msg>Set prefer_udp_trackers=false by default.<commit_after>#include <chrono> #include <exception> #include <stdexcept> // __gnu_cxx::__verbose_terminate_handler #include <fstream> #include <iostream> #include <thread> #include <libtorrent/add_torrent_params.hpp> #include <libtorrent/alert_types.hpp> #include <libtorrent/bencode.hpp> #include <libtorrent/create_torrent.hpp> #include <libtorrent/session.hpp> #include <libtorrent/session_settings.hpp> #include <libtorrent/storage_defs.hpp> // lt::disabled_storage_constructor #include <libtorrent/torrent_handle.hpp> #include <libtorrent/torrent_info.hpp> namespace lt = libtorrent; int main(int argc, char *argv[]) { std::set_terminate(__gnu_cxx::__verbose_terminate_handler); lt::session_settings sset; sset.prefer_udp_trackers = false; if (argc != 2) { std::cerr << "usage: " << argv[0] << " <magnet-url>" << std::endl; return 1; } lt::session sess; sess.set_settings(sset); lt::add_torrent_params atp; atp.url = argv[1]; atp.upload_mode = true; atp.auto_managed = false; atp.paused = false; // Start with "storage == disabled" to avoid pre-allocating any files // mentioned in the torrent file on disk: atp.storage = lt::disabled_storage_constructor; atp.save_path = "."; // save in current dir /* // .flags duplicate .upload_mode/auto_managed/paused // functionality: atp.flags = lt::add_torrent_params::flag_update_subscribe | lt::add_torrent_params::flag_upload_mode | lt::add_torrent_params::flag_apply_ip_filter; */ lt::torrent_handle torh = sess.add_torrent(atp); std::cout << atp.url << ":"; for (;;) { std::deque<lt::alert*> alerts; sess.pop_alerts(&alerts); for (lt::alert const* a : alerts) { std::cout << std::endl << a->message() << std::endl; // quit on error/finish: if (lt::alert_cast<lt::torrent_finished_alert>(a) || lt::alert_cast<lt::torrent_error_alert>(a)) { goto done1; }; } if (torh.status().has_metadata) { sess.pause(); lt::torrent_info tinf = torh.get_torrent_info(); std::cout << tinf.name() << std::endl; std::cout.flush(); std::ofstream ofs; ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit); ofs.open(tinf.name() + ".torrent", std::ofstream::binary); std::ostream_iterator<char> ofsi(ofs); lt::bencode(ofsi, lt::create_torrent(tinf) .generate()); ofs.close(); sess.remove_torrent(torh); goto done0; }; std::cout << "."; std::cout.flush(); std::this_thread::sleep_for( std::chrono::milliseconds(1000)); } done0: return 0; done1: return 1; } // vi: set sw=8 ts=8 noet tw=77: <|endoftext|>
<commit_before>/* * Copyright 2009, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "plugin/cross/main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_util.h" #include "plugin/cross/config.h" #include "plugin/cross/out_of_memory.h" #include "plugin/cross/whitelist.h" #ifdef OS_WIN #include "breakpad/win/bluescreen_detector.h" #endif using glue::_o3d::PluginObject; using glue::StreamManager; #if !defined(O3D_INTERNAL_PLUGIN) #ifdef OS_WIN #define O3D_DEBUG_LOG_FILENAME L"debug.log" #else #define O3D_DEBUG_LOG_FILENAME "debug.log" #endif #if defined(OS_WIN) || defined(OS_MACOSX) o3d::PluginLogging *g_logger = NULL; static bool g_logging_initialized = false; #ifdef OS_WIN static o3d::BluescreenDetector *g_bluescreen_detector = NULL; #endif // OS_WIN #endif // OS_WIN || OS_MACOSX // We would normally make this a stack variable in main(), but in a // plugin, that's not possible, so we make it a global. When the DLL is loaded // this it gets constructed and when it is unlooaded it is destructed. Note // that this cannot be done in NP_Initialize and NP_Shutdown because those // calls do not necessarily signify the DLL being loaded and unloaded. If the // DLL is not unloaded then the values of global variables are preserved. static base::AtExitManager g_at_exit_manager; int BreakpadEnabler::scope_count_ = 0; #endif // O3D_INTERNAL_PLUGIN namespace o3d { NPError NP_GetValue(NPPVariable variable, void *value) { switch (variable) { case NPPVpluginNameString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME); break; case NPPVpluginDescriptionString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION); break; default: return NPERR_INVALID_PARAM; break; } return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void *event) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } return PlatformNPPHandleEvent(instance, obj, event); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->NewStream(stream, stype)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->DestroyStream(stream, reason)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } int32 NPP_WriteReady(NPP instance, NPStream *stream) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->Write(stream, offset, len, buffer); } void NPP_Print(NPP instance, NPPrint *platformPrint) { HANDLE_CRASHES; } void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); stream_manager->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } switch (variable) { case NPPVpluginScriptableNPObject: { void **v = static_cast<void **>(value); // Return value is expected to be retained GLUE_PROFILE_START(instance, "retainobject"); NPN_RetainObject(obj); GLUE_PROFILE_STOP(instance, "retainobject"); *v = obj; break; } default: { NPError ret = PlatformNPPGetValue(obj, variable, value); if (ret == NPERR_INVALID_PARAM) ret = o3d::NP_GetValue(variable, value); return ret; } } return NPERR_NO_ERROR; } NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { HANDLE_CRASHES; #if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX)) // TODO(tschmelcher): Support this on Linux? if (!g_logging_initialized) { // Get user config metrics. These won't be stored though unless the user // opts-in for usagestats logging GetUserAgentMetrics(instance); GetUserConfigMetrics(); // Create usage stats logs object g_logger = o3d::PluginLogging::InitializeUsageStatsLogging(); #ifdef OS_WIN if (g_logger) { // Setup blue-screen detection g_bluescreen_detector = new o3d::BluescreenDetector(); g_bluescreen_detector->Start(); } #endif g_logging_initialized = true; } #endif if (!IsDomainAuthorized(instance)) { return NPERR_INVALID_URL; } PluginObject *obj = glue::_o3d::PluginObject::Create(instance); instance->pdata = obj; glue::_o3d::InitializeGlue(instance); obj->Init(argc, argn, argv); return PlatformNPPNew(instance, obj); } NPError NPP_Destroy(NPP instance, NPSavedData **save) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } NPError err = PlatformNPPDestroy(instance, obj); NPN_ReleaseObject(obj); instance->pdata = NULL; return err; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { HANDLE_CRASHES; return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } return PlatformNPPSetWindow(instance, obj, window); } // Called when the browser has finished attempting to stream data to // a file as requested. If fname == NULL the attempt was not successful. void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); PlatformNPPStreamAsFile(stream_manager, stream, fname); } } // namespace o3d #if defined(O3D_INTERNAL_PLUGIN) namespace o3d { #else extern "C" { #endif NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs #ifdef OS_LINUX , NPPluginFuncs *pluginFuncs #endif ) { HANDLE_CRASHES; NPError err = InitializeNPNApi(browserFuncs); if (err != NPERR_NO_ERROR) { return err; } #ifdef OS_LINUX NP_GetEntryPoints(pluginFuncs); #endif // OS_LINUX #if !defined(O3D_INTERNAL_PLUGIN) if (!o3d::SetupOutOfMemoryHandler()) return NPERR_MODULE_LOAD_FAILED_ERROR; #endif // O3D_INTERNAL_PLUGIN err = o3d::PlatformPreNPInitialize(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) // Turn on the logging. CommandLine::Init(0, NULL); FilePath log; file_util::GetTempDir(&log); log.Append(O3D_DEBUG_LOG_FILENAME); InitLogging(log.value().c_str(), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE); #endif // O3D_INTERNAL_PLUGIN DLOG(INFO) << "NP_Initialize"; return o3d::PlatformPostNPInitialize(); } NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) { HANDLE_CRASHES; DLOG(INFO) << "NP_Shutdown"; NPError err = o3d::PlatformPreNPShutdown(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) #if defined(OS_WIN) || defined(OS_MACOSX) if (g_logger) { // Do a last sweep to aggregate metrics before we shut down g_logger->ProcessMetrics(true, false, false); delete g_logger; g_logger = NULL; g_logging_initialized = false; stats_report::g_global_metrics.Uninitialize(); } #endif // OS_WIN || OS_MACOSX CommandLine::Reset(); #ifdef OS_WIN // Strictly speaking, on windows, it's not really necessary to call // Stop(), but we do so for completeness if (g_bluescreen_detector) { g_bluescreen_detector->Stop(); delete g_bluescreen_detector; g_bluescreen_detector = NULL; } #endif // OS_WIN #endif // O3D_INTERNAL_PLUGIN return o3d::PlatformPostNPShutdown(); } NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) { HANDLE_CRASHES; pluginFuncs->version = 11; pluginFuncs->size = sizeof(*pluginFuncs); pluginFuncs->newp = o3d::NPP_New; pluginFuncs->destroy = o3d::NPP_Destroy; pluginFuncs->setwindow = o3d::NPP_SetWindow; pluginFuncs->newstream = o3d::NPP_NewStream; pluginFuncs->destroystream = o3d::NPP_DestroyStream; pluginFuncs->asfile = o3d::NPP_StreamAsFile; pluginFuncs->writeready = o3d::NPP_WriteReady; pluginFuncs->write = o3d::NPP_Write; pluginFuncs->print = o3d::NPP_Print; pluginFuncs->event = o3d::NPP_HandleEvent; pluginFuncs->urlnotify = o3d::NPP_URLNotify; pluginFuncs->getvalue = o3d::NPP_GetValue; pluginFuncs->setvalue = o3d::NPP_SetValue; return NPERR_NO_ERROR; } char* NP_GetMIMEDescription(void) { return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME"); } } // namespace o3d / extern "C" #if !defined(O3D_INTERNAL_PLUGIN) extern "C" { NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable, void *value) { return o3d::NP_GetValue(variable, value); } } #endif <commit_msg>Fix IE crash regression from r66344.<commit_after>/* * Copyright 2009, Google 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 Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "plugin/cross/main.h" #include "base/at_exit.h" #include "base/command_line.h" #include "base/file_util.h" #include "plugin/cross/config.h" #include "plugin/cross/out_of_memory.h" #include "plugin/cross/whitelist.h" #ifdef OS_WIN #include "breakpad/win/bluescreen_detector.h" #endif using glue::_o3d::PluginObject; using glue::StreamManager; #if !defined(O3D_INTERNAL_PLUGIN) #ifdef OS_WIN #define O3D_DEBUG_LOG_FILENAME L"debug.log" #else #define O3D_DEBUG_LOG_FILENAME "debug.log" #endif #if defined(OS_WIN) || defined(OS_MACOSX) o3d::PluginLogging *g_logger = NULL; static bool g_logging_initialized = false; #ifdef OS_WIN static o3d::BluescreenDetector *g_bluescreen_detector = NULL; #endif // OS_WIN #endif // OS_WIN || OS_MACOSX // We would normally make this a stack variable in main(), but in a // plugin, that's not possible, so we make it a global. When the DLL is loaded // this it gets constructed and when it is unlooaded it is destructed. Note // that this cannot be done in NP_Initialize and NP_Shutdown because those // calls do not necessarily signify the DLL being loaded and unloaded. If the // DLL is not unloaded then the values of global variables are preserved. static base::AtExitManager g_at_exit_manager; int BreakpadEnabler::scope_count_ = 0; #endif // O3D_INTERNAL_PLUGIN namespace o3d { NPError NP_GetValue(NPPVariable variable, void *value) { switch (variable) { case NPPVpluginNameString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME); break; case NPPVpluginDescriptionString: *static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION); break; default: return NPERR_INVALID_PARAM; break; } return NPERR_NO_ERROR; } int16 NPP_HandleEvent(NPP instance, void *event) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } return PlatformNPPHandleEvent(instance, obj, event); } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->NewStream(stream, stype)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } StreamManager *stream_manager = obj->stream_manager(); if (stream_manager->DestroyStream(stream, reason)) { return NPERR_NO_ERROR; } else { // TODO: find out which error we should return return NPERR_INVALID_PARAM; } } int32 NPP_WriteReady(NPP instance, NPStream *stream) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->WriteReady(stream); } int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return 0; } StreamManager *stream_manager = obj->stream_manager(); return stream_manager->Write(stream, offset, len, buffer); } void NPP_Print(NPP instance, NPPrint *platformPrint) { HANDLE_CRASHES; } void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); stream_manager->URLNotify(url, reason, notifyData); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { HANDLE_CRASHES; if (!instance) { // Our ActiveX wrapper calls us like this as a way of saying that what it // really wants to call is NP_GetValue(). :/ return o3d::NP_GetValue(variable, value); } PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_INVALID_PARAM; } switch (variable) { case NPPVpluginScriptableNPObject: { void **v = static_cast<void **>(value); // Return value is expected to be retained GLUE_PROFILE_START(instance, "retainobject"); NPN_RetainObject(obj); GLUE_PROFILE_STOP(instance, "retainobject"); *v = obj; break; } default: { NPError ret = PlatformNPPGetValue(obj, variable, value); if (ret == NPERR_INVALID_PARAM) // TODO(tschmelcher): Do we still need to fall back to this now that we // have the ActiveX special case above? ret = o3d::NP_GetValue(variable, value); return ret; } } return NPERR_NO_ERROR; } NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved) { HANDLE_CRASHES; #if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX)) // TODO(tschmelcher): Support this on Linux? if (!g_logging_initialized) { // Get user config metrics. These won't be stored though unless the user // opts-in for usagestats logging GetUserAgentMetrics(instance); GetUserConfigMetrics(); // Create usage stats logs object g_logger = o3d::PluginLogging::InitializeUsageStatsLogging(); #ifdef OS_WIN if (g_logger) { // Setup blue-screen detection g_bluescreen_detector = new o3d::BluescreenDetector(); g_bluescreen_detector->Start(); } #endif g_logging_initialized = true; } #endif if (!IsDomainAuthorized(instance)) { return NPERR_INVALID_URL; } PluginObject *obj = glue::_o3d::PluginObject::Create(instance); instance->pdata = obj; glue::_o3d::InitializeGlue(instance); obj->Init(argc, argn, argv); return PlatformNPPNew(instance, obj); } NPError NPP_Destroy(NPP instance, NPSavedData **save) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } NPError err = PlatformNPPDestroy(instance, obj); NPN_ReleaseObject(obj); instance->pdata = NULL; return err; } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { HANDLE_CRASHES; return NPERR_GENERIC_ERROR; } NPError NPP_SetWindow(NPP instance, NPWindow* window) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return NPERR_NO_ERROR; } return PlatformNPPSetWindow(instance, obj, window); } // Called when the browser has finished attempting to stream data to // a file as requested. If fname == NULL the attempt was not successful. void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) { HANDLE_CRASHES; PluginObject *obj = static_cast<PluginObject *>(instance->pdata); if (!obj) { return; } StreamManager *stream_manager = obj->stream_manager(); PlatformNPPStreamAsFile(stream_manager, stream, fname); } } // namespace o3d #if defined(O3D_INTERNAL_PLUGIN) namespace o3d { #else extern "C" { #endif NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs #ifdef OS_LINUX , NPPluginFuncs *pluginFuncs #endif ) { HANDLE_CRASHES; NPError err = InitializeNPNApi(browserFuncs); if (err != NPERR_NO_ERROR) { return err; } #ifdef OS_LINUX NP_GetEntryPoints(pluginFuncs); #endif // OS_LINUX #if !defined(O3D_INTERNAL_PLUGIN) if (!o3d::SetupOutOfMemoryHandler()) return NPERR_MODULE_LOAD_FAILED_ERROR; #endif // O3D_INTERNAL_PLUGIN err = o3d::PlatformPreNPInitialize(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) // Turn on the logging. CommandLine::Init(0, NULL); FilePath log; file_util::GetTempDir(&log); log.Append(O3D_DEBUG_LOG_FILENAME); InitLogging(log.value().c_str(), logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG, logging::DONT_LOCK_LOG_FILE, logging::APPEND_TO_OLD_LOG_FILE); #endif // O3D_INTERNAL_PLUGIN DLOG(INFO) << "NP_Initialize"; return o3d::PlatformPostNPInitialize(); } NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) { HANDLE_CRASHES; DLOG(INFO) << "NP_Shutdown"; NPError err = o3d::PlatformPreNPShutdown(); if (err != NPERR_NO_ERROR) { return err; } #if !defined(O3D_INTERNAL_PLUGIN) #if defined(OS_WIN) || defined(OS_MACOSX) if (g_logger) { // Do a last sweep to aggregate metrics before we shut down g_logger->ProcessMetrics(true, false, false); delete g_logger; g_logger = NULL; g_logging_initialized = false; stats_report::g_global_metrics.Uninitialize(); } #endif // OS_WIN || OS_MACOSX CommandLine::Reset(); #ifdef OS_WIN // Strictly speaking, on windows, it's not really necessary to call // Stop(), but we do so for completeness if (g_bluescreen_detector) { g_bluescreen_detector->Stop(); delete g_bluescreen_detector; g_bluescreen_detector = NULL; } #endif // OS_WIN #endif // O3D_INTERNAL_PLUGIN return o3d::PlatformPostNPShutdown(); } NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) { HANDLE_CRASHES; pluginFuncs->version = 11; pluginFuncs->size = sizeof(*pluginFuncs); pluginFuncs->newp = o3d::NPP_New; pluginFuncs->destroy = o3d::NPP_Destroy; pluginFuncs->setwindow = o3d::NPP_SetWindow; pluginFuncs->newstream = o3d::NPP_NewStream; pluginFuncs->destroystream = o3d::NPP_DestroyStream; pluginFuncs->asfile = o3d::NPP_StreamAsFile; pluginFuncs->writeready = o3d::NPP_WriteReady; pluginFuncs->write = o3d::NPP_Write; pluginFuncs->print = o3d::NPP_Print; pluginFuncs->event = o3d::NPP_HandleEvent; pluginFuncs->urlnotify = o3d::NPP_URLNotify; pluginFuncs->getvalue = o3d::NPP_GetValue; pluginFuncs->setvalue = o3d::NPP_SetValue; return NPERR_NO_ERROR; } char* NP_GetMIMEDescription(void) { return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME"); } } // namespace o3d / extern "C" #if !defined(O3D_INTERNAL_PLUGIN) extern "C" { NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable, void *value) { return o3d::NP_GetValue(variable, value); } } #endif <|endoftext|>
<commit_before>#include <bits/stdc++.h> #include<chrono> #include<random> typedef unsigned long long ui; using namespace std; int main() { /**************************************************************/ /* Generating Random Graph */ /* */ /**************************************************************/ ui n=500; cout<<"Enter no of nodes: "<<endl; cin>>n; ui d=2; cout<<"Enter minimum Degree of each Node: "<<endl; cin>>d; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_int_distribution<ui> distribution(1,n); vector<vector <ui> > G(n+1); for(ui i=1;i<=n;++i) { ui neighbour = distribution(generator); if(G[i].size()<2*d && G[neighbour].size()<2*d && (find(G[i].begin(), G[i].end(), neighbour)==G[i].end())) { G[i].push_back(neighbour); G[neighbour].push_back(i); } if(G[i].size()< d){ --i; } } for(ui i=1;i<=n;++i) { cout<<"Node "<<i<<": " ; for(auto it = G[i].begin(); it != G[i].end();++it) { cout<<" "<<*it; } cout<<endl; } /**************************************************************/ /* Testing Connectivity of Graph */ /* Using BFS */ /**************************************************************/ vector<bool> visited (n+1,false); visited[0] = true; visited[1] = true; queue<ui> q; q.push(1); while(!q.empty()){ ui temp = q.front(); for(ui i=0; i< G[temp].size(); ++i){ if(!visited[G[temp][i]]) q.push(G[temp][i]); visited[G[temp][i]] = true; } q.pop(); } if(find(visited.begin(),visited.end(),false) == visited.end()) cout<<"Connected"<<endl; else cout<<"Multiple Components"<<endl; /* for(int i=0; i<visited.size(); ++i){ cout<<"visited["<<i<<"]: "<<visited[i]<<" "<<endl; }*/ return 0; } <commit_msg>Generate RG with flexible degree <commit_after>#include <bits/stdc++.h> #include<chrono> #include<random> typedef unsigned long long ui; using namespace std; int main() { /**************************************************************/ /* Generating Random Graph */ /* */ /**************************************************************/ ui n=500; cout<<"Enter no of nodes: "<<endl; cin>>n; ui d=2; cout<<"Enter minimum Degree of each Node: "<<endl; cin>>d; unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); std::default_random_engine generator (seed); std::uniform_int_distribution<ui> distribution(1,n); vector<vector <ui> > G(n+1); for(ui i=1;i<=n;++i){ while(G[i].size()< d){ ui neighbour = distribution(generator); if(G[i].size()<2*d && G[neighbour].size()<2*d && (find(G[i].begin(), G[i].end(), neighbour)==G[i].end())) { G[i].push_back(neighbour); G[neighbour].push_back(i); } } } for(ui i=1;i<=n;++i) { cout<<"Node "<<i<<": " ; for(auto it = G[i].begin(); it != G[i].end();++it) { cout<<" "<<*it; } cout<<endl; } /**************************************************************/ /* Testing Connectivity of Graph */ /* Using BFS */ /**************************************************************/ vector<bool> visited (n+1,false); visited[0] = true; visited[1] = true; queue<ui> q; q.push(1); while(!q.empty()){ ui temp = q.front(); for(ui i=0; i< G[temp].size(); ++i){ if(!visited[G[temp][i]]) q.push(G[temp][i]); visited[G[temp][i]] = true; } q.pop(); } if(find(visited.begin(),visited.end(),false) == visited.end()) cout<<"Connected"<<endl; else cout<<"Multiple Components"<<endl; /* for(int i=0; i<visited.size(); ++i){ cout<<"visited["<<i<<"]: "<<visited[i]<<" "<<endl; }*/ return 0; } <|endoftext|>
<commit_before>// Copyright 2010-2014 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "ortools/base/basictypes.h" #include "ortools/base/join.h" #include "ortools/base/stringpiece.h" #include "ortools/base/stringprintf.h" namespace { // ----- StrCat ----- static char* Append1(char* out, const AlphaNum& x) { memcpy(out, x.data(), x.size()); return out + x.size(); } static char* Append2(char* out, const AlphaNum& x1, const AlphaNum& x2) { memcpy(out, x1.data(), x1.size()); out += x1.size(); memcpy(out, x2.data(), x2.size()); return out + x2.size(); } static char* Append4(char* out, const AlphaNum& x1, const AlphaNum& x2, const AlphaNum& x3, const AlphaNum& x4) { memcpy(out, x1.data(), x1.size()); out += x1.size(); memcpy(out, x2.data(), x2.size()); out += x2.size(); memcpy(out, x3.data(), x3.size()); out += x3.size(); memcpy(out, x4.data(), x4.size()); return out + x4.size(); } } // namespace void StrAppend(std::string* s, const AlphaNum& a) { s->append(a.data(), a.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b) { s->reserve(s->size() + a.size() + b.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { s->reserve(s->size() + a.size() + b.size() + c.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); s->append(c.data(), c.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { s->reserve(s->size() + a.size() + b.size() + c.size() + d.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); s->append(c.data(), c.size()); s->append(d.data(), d.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e) { StrAppend(s, a, b, c, d); StrAppend(s, e); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f) { StrAppend(s, a, b, c, d); StrAppend(s, e, f); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i, j); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j, const AlphaNum& k) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i, j, k); } std::string StrCat(const AlphaNum& a) { return std::string(a.data(), a.size()); } std::string StrCat(const AlphaNum& a, const AlphaNum& b) { std::string out; StrAppend(&out, a, b); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { std::string out; StrAppend(&out, a, b, c); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { std::string out; StrAppend(&out, a, b, c, d); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e) { std::string out; StrAppend(&out, a, b, c, d, e); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f) { std::string out; StrAppend(&out, a, b, c, d, e, f); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g) { std::string out; StrAppend(&out, a, b, c, d, e, f, g); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i, j); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j, const AlphaNum& k) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i, j, k); return out; } <commit_msg>remove unused code<commit_after>// Copyright 2010-2014 Google // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <string> #include "ortools/base/basictypes.h" #include "ortools/base/join.h" #include "ortools/base/stringpiece.h" #include "ortools/base/stringprintf.h" void StrAppend(std::string* s, const AlphaNum& a) { s->append(a.data(), a.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b) { s->reserve(s->size() + a.size() + b.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { s->reserve(s->size() + a.size() + b.size() + c.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); s->append(c.data(), c.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { s->reserve(s->size() + a.size() + b.size() + c.size() + d.size()); s->append(a.data(), a.size()); s->append(b.data(), b.size()); s->append(c.data(), c.size()); s->append(d.data(), d.size()); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e) { StrAppend(s, a, b, c, d); StrAppend(s, e); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f) { StrAppend(s, a, b, c, d); StrAppend(s, e, f); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i, j); } void StrAppend(std::string* s, const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j, const AlphaNum& k) { StrAppend(s, a, b, c, d); StrAppend(s, e, f, g, h, i, j, k); } std::string StrCat(const AlphaNum& a) { return std::string(a.data(), a.size()); } std::string StrCat(const AlphaNum& a, const AlphaNum& b) { std::string out; StrAppend(&out, a, b); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c) { std::string out; StrAppend(&out, a, b, c); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d) { std::string out; StrAppend(&out, a, b, c, d); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e) { std::string out; StrAppend(&out, a, b, c, d, e); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f) { std::string out; StrAppend(&out, a, b, c, d, e, f); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g) { std::string out; StrAppend(&out, a, b, c, d, e, f, g); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i, j); return out; } std::string StrCat(const AlphaNum& a, const AlphaNum& b, const AlphaNum& c, const AlphaNum& d, const AlphaNum& e, const AlphaNum& f, const AlphaNum& g, const AlphaNum& h, const AlphaNum& i, const AlphaNum& j, const AlphaNum& k) { std::string out; StrAppend(&out, a, b, c, d, e, f, g, h, i, j, k); return out; } <|endoftext|>
<commit_before>// Copyright © 2014 Lénaïc Bagnères, hnc@singularity.fr // 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 <iostream> #include <hnc/random.hpp> #include <hnc/test.hpp> #include <hnc/to_string.hpp> int main() { int nb_test = 0; nb_test += 2; { int const n0 = hnc::random::uniform(-73, 42); int const n1 = hnc::random::uniform(100, 200); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= -73 && n0 <= 42, "hnc::random::uniform<int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<int> fails"); } std::cout << std::endl; nb_test += 2; { unsigned int const n0 = hnc::random::uniform(42u, 73u); unsigned int const n1 = hnc::random::uniform(100u, 200u); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 42 && n0 <= 73, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; nb_test += 2; { float const n0 = hnc::random::uniform(0.f, 1.f); float const n1 = hnc::random::uniform(-1.f, 0.f); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 0.f && n0 <= 1.f, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= -1.f && n1 <= 1.f, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; nb_test += 2; { double const n0 = hnc::random::uniform(0.0, 1.0); double const n1 = hnc::random::uniform(-1.0, 0.0); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 0.0 && n0 <= 1.0, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= -1.0 && n1 <= 1.0, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; { bool const n0 = hnc::random::true_false(0.5); bool const n1 = hnc::random::true_false(); std::cout << n0 << std::endl; std::cout << n1 << std::endl; } std::cout << std::endl; nb_test += 2; { auto random = hnc::random::make_uniform_t(-73, 42); int const n0 = random(); int const n1 = random(100, 200); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= -73 && n0 <= 42, "hnc::random::uniform<int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<int> fails"); } std::cout << std::endl; { auto random = hnc::random::make_true_false_t(); int const n0 = random(); int const n1 = random(0.1); std::cout << n0 << std::endl; std::cout << n1 << std::endl; } std::cout << std::endl; hnc::test::warning(nb_test == 0, "hnc::random: " + hnc::to_string(nb_test) + " test fail!\n"); return 0; } <commit_msg>Update test of hnc/random.hpp<commit_after>// Copyright © 2014 Lénaïc Bagnères, hnc@singularity.fr // 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 <iostream> #include <vector> #include <hnc/random.hpp> #include <hnc/test.hpp> #include <hnc/to_string.hpp> int main() { int nb_test = 0; nb_test += 2; { int const n0 = hnc::random::uniform(-73, 42); int const n1 = hnc::random::uniform(100, 200); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= -73 && n0 <= 42, "hnc::random::uniform<int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<int> fails"); } std::cout << std::endl; nb_test += 2; { unsigned int const n0 = hnc::random::uniform(42u, 73u); unsigned int const n1 = hnc::random::uniform(100u, 200u); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 42 && n0 <= 73, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; nb_test += 2; { float const n0 = hnc::random::uniform(0.f, 1.f); float const n1 = hnc::random::uniform(-1.f, 0.f); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 0.f && n0 <= 1.f, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= -1.f && n1 <= 1.f, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; nb_test += 2; { double const n0 = hnc::random::uniform(0.0, 1.0); double const n1 = hnc::random::uniform(-1.0, 0.0); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= 0.0 && n0 <= 1.0, "hnc::random::uniform<unsigned int> fails"); nb_test -= hnc::test::warning(n1 >= -1.0 && n1 <= 1.0, "hnc::random::uniform<unsigned int> fails"); } std::cout << std::endl; { bool const n0 = hnc::random::true_false(0.5); bool const n1 = hnc::random::true_false(); std::cout << n0 << std::endl; std::cout << n1 << std::endl; } std::cout << std::endl; nb_test += 2; { auto random = hnc::random::make_uniform_t(-73, 42); int const n0 = random(); int const n1 = random(100, 200); std::cout << n0 << std::endl; std::cout << n1 << std::endl; nb_test -= hnc::test::warning(n0 >= -73 && n0 <= 42, "hnc::random::uniform<int> fails"); nb_test -= hnc::test::warning(n1 >= 100 && n1 <= 200, "hnc::random::uniform<int> fails"); } std::cout << std::endl; { auto random = hnc::random::make_true_false_t(); int const n0 = random(); int const n1 = random(0.1); std::cout << n0 << std::endl; std::cout << n1 << std::endl; } std::cout << std::endl; { auto random = hnc::random::make_uniform_t(0, 9); std::vector<int> r(10, 0); for (unsigned int i = 0; i < 10000; ++i) { ++r.at(std::size_t(random())); } for (std::size_t i =0; i < r.size(); ++i) { std::cout << i << " - " << r[i] << std::endl; } } std::cout << std::endl; { auto random = hnc::random::make_true_false_t(); std::vector<int> r(2, 0); for (unsigned int i = 0; i < 1000; ++i) { if (random()) { ++r[1]; } if (random()) { ++r[0]; } } for (std::size_t i =0; i < r.size(); ++i) { std::cout << i << " - " << r[i] << std::endl; } } std::cout << std::endl; hnc::test::warning(nb_test == 0, "hnc::random: " + hnc::to_string(nb_test) + " test fail!\n"); return 0; } <|endoftext|>
<commit_before>// @(#)root/base:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TString Input/Output functions, put here so the linker will include // // them only if I/O is done. // // // ////////////////////////////////////////////////////////////////////////// #include <ctype.h> // Looking for isspace() #include "Riostream.h" #include "TString.h" //______________________________________________________________________________ istream& TString::ReadFile(istream& strm) { // Replace string with the contents of strm, stopping at an EOF. // any positive number of reasonable size for a file const Ssiz_t incr = 256; Clobber(incr); while(1) { Ssiz_t len = Length(); strm.read(GetPointer()+len, Capacity()-len); SetSize(len + strm.gcount()); if (!strm.good()) break; // EOF encountered // If we got here, the read must have stopped because // the buffer was going to overflow. Resize and keep // going. Capacity(Length() + incr); } GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& TString::ReadLine(istream& strm, Bool_t skipWhite) { // Read a line from stream upto newline skipping any whitespace. if (skipWhite) strm >> ws; return ReadToDelim(strm, '\n'); } //______________________________________________________________________________ istream& TString::ReadString(istream& strm) { // Read a line from stream upto \0, including any newline. return ReadToDelim(strm, '\0'); } //______________________________________________________________________________ istream& TString::ReadToDelim(istream& strm, char delim) { // Read up to an EOF, or a delimiting character, whichever comes // first. The delimiter is not stored in the string, // but is removed from the input stream. // Because we don't know how big a string to expect, we first read // as much as we can and then, if the EOF or null hasn't been // encountered, do a resize and keep reading. // any positive number of reasonable size for a string const Ssiz_t incr = 32; Clobber(incr); int p = strm.peek(); // Check if we are already at delim if (p == delim) { strm.get(); // eat the delimiter, and return \0. } else { while (1) { Ssiz_t len = Length(); strm.get(GetPointer()+len, // Address of next byte Capacity()-len+1, // Space available (+1 for terminator) delim); // Delimiter SetSize(len + strm.gcount()); if (!strm.good()) break; // Check for EOF or stream failure p = strm.peek(); if (p == delim) { // Check for delimiter strm.get(); // eat the delimiter. break; } // Delimiter not seen. Resize and keep going: Capacity(Length() + incr); } } GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& TString::ReadToken(istream& strm) { // Read a token, delimited by whitespace, from the input stream. // any positive number of reasonable size for a token const Ssiz_t incr = 16; Clobber(incr); strm >> ws; // Eat whitespace UInt_t wid = strm.width(0); char c; Int_t hitSpace = 0; while ((wid == 0 || Length() < (Int_t)wid) && strm.get(c).good() && (hitSpace = isspace((Int_t)c)) == 0) { // Check for overflow: Ssiz_t len = Length(); if (len == Capacity()) Capacity(len + incr); GetPointer()[len] = c; len++; SetSize(len); } if (hitSpace) strm.putback(c); GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& operator>>(istream& strm, TString& s) { // Read string from stream. return s.ReadToken(strm); } //______________________________________________________________________________ ostream& operator<<(ostream& os, const TString& s) { // Write string to stream. if (os.good()) { if (os.tie()) os.tie()->flush(); // instead of opfx UInt_t len = s.Length(); UInt_t wid = os.width(); wid = (len < wid) ? wid - len : 0; os.width(wid); long flags = os.flags(); if (wid && !(flags & ios::left)) os << ""; // let the ostream fill os.write((char*)s.Data(), s.Length()); if (wid && (flags & ios::left)) os << ""; // let the ostream fill } // instead of os.osfx(); if (os.flags() & ios::unitbuf) os.flush(); return os; } // ------------------- C I/O ------------------------------------ //______________________________________________________________________________ Bool_t TString::Gets(FILE *fp, Bool_t chop) { // Read one line from the stream, including the \n, or until EOF. // Remove the trailing \n if chop is true. Returns kTRUE if data was read. char buf[256]; Bool_t r = kFALSE; Clobber(256); do { if (fgets(buf, sizeof(buf), fp) == 0) break; *this += buf; r = kTRUE; } while (!ferror(fp) && !feof(fp) && strchr(buf,'\n') == 0); if (chop && EndsWith("\n")) Chop(); return r; } //______________________________________________________________________________ void TString::Puts(FILE *fp) { // Write string to the stream. fputs(GetPointer(), fp); } <commit_msg>optimize ReadFile() by trying to allocate directly a buffer for the entire file.<commit_after>// @(#)root/base:$Id$ // Author: Fons Rademakers 04/08/95 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // TString Input/Output functions, put here so the linker will include // // them only if I/O is done. // // // ////////////////////////////////////////////////////////////////////////// #include <ctype.h> // Looking for isspace() #include "Riostream.h" #include "TString.h" //______________________________________________________________________________ istream& TString::ReadFile(istream& strm) { // Replace string with the contents of strm, stopping at an EOF. // get file size Ssiz_t end, cur = strm.tellg(); strm.seekg(0, ios::end); end = strm.tellg(); strm.seekg(cur); // any positive number of reasonable size for a file const Ssiz_t incr = 256; Clobber(end-cur); while(1) { Ssiz_t len = Length(); strm.read(GetPointer()+len, Capacity()-len); SetSize(len + strm.gcount()); if (!strm.good()) break; // EOF encountered // If we got here, the read must have stopped because // the buffer was going to overflow. Resize and keep // going. Capacity(Length() + incr); } GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& TString::ReadLine(istream& strm, Bool_t skipWhite) { // Read a line from stream upto newline skipping any whitespace. if (skipWhite) strm >> ws; return ReadToDelim(strm, '\n'); } //______________________________________________________________________________ istream& TString::ReadString(istream& strm) { // Read a line from stream upto \0, including any newline. return ReadToDelim(strm, '\0'); } //______________________________________________________________________________ istream& TString::ReadToDelim(istream& strm, char delim) { // Read up to an EOF, or a delimiting character, whichever comes // first. The delimiter is not stored in the string, // but is removed from the input stream. // Because we don't know how big a string to expect, we first read // as much as we can and then, if the EOF or null hasn't been // encountered, do a resize and keep reading. // any positive number of reasonable size for a string const Ssiz_t incr = 32; Clobber(incr); int p = strm.peek(); // Check if we are already at delim if (p == delim) { strm.get(); // eat the delimiter, and return \0. } else { while (1) { Ssiz_t len = Length(); strm.get(GetPointer()+len, // Address of next byte Capacity()-len+1, // Space available (+1 for terminator) delim); // Delimiter SetSize(len + strm.gcount()); if (!strm.good()) break; // Check for EOF or stream failure p = strm.peek(); if (p == delim) { // Check for delimiter strm.get(); // eat the delimiter. break; } // Delimiter not seen. Resize and keep going: Capacity(Length() + incr); } } GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& TString::ReadToken(istream& strm) { // Read a token, delimited by whitespace, from the input stream. // any positive number of reasonable size for a token const Ssiz_t incr = 16; Clobber(incr); strm >> ws; // Eat whitespace UInt_t wid = strm.width(0); char c; Int_t hitSpace = 0; while ((wid == 0 || Length() < (Int_t)wid) && strm.get(c).good() && (hitSpace = isspace((Int_t)c)) == 0) { // Check for overflow: Ssiz_t len = Length(); if (len == Capacity()) Capacity(len + incr); GetPointer()[len] = c; len++; SetSize(len); } if (hitSpace) strm.putback(c); GetPointer()[Length()] = '\0'; // Add null terminator return strm; } //______________________________________________________________________________ istream& operator>>(istream& strm, TString& s) { // Read string from stream. return s.ReadToken(strm); } //______________________________________________________________________________ ostream& operator<<(ostream& os, const TString& s) { // Write string to stream. if (os.good()) { if (os.tie()) os.tie()->flush(); // instead of opfx UInt_t len = s.Length(); UInt_t wid = os.width(); wid = (len < wid) ? wid - len : 0; os.width(wid); long flags = os.flags(); if (wid && !(flags & ios::left)) os << ""; // let the ostream fill os.write((char*)s.Data(), s.Length()); if (wid && (flags & ios::left)) os << ""; // let the ostream fill } // instead of os.osfx(); if (os.flags() & ios::unitbuf) os.flush(); return os; } // ------------------- C I/O ------------------------------------ //______________________________________________________________________________ Bool_t TString::Gets(FILE *fp, Bool_t chop) { // Read one line from the stream, including the \n, or until EOF. // Remove the trailing \n if chop is true. Returns kTRUE if data was read. char buf[256]; Bool_t r = kFALSE; Clobber(256); do { if (fgets(buf, sizeof(buf), fp) == 0) break; *this += buf; r = kTRUE; } while (!ferror(fp) && !feof(fp) && strchr(buf,'\n') == 0); if (chop && EndsWith("\n")) Chop(); return r; } //______________________________________________________________________________ void TString::Puts(FILE *fp) { // Write string to the stream. fputs(GetPointer(), fp); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outlundo.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: obo $ $Date: 2006-10-12 13:02:41 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <outl_pch.hxx> #define _OUTLINER_CXX #include <outliner.hxx> #include <outlundo.hxx> OutlinerUndoBase::OutlinerUndoBase( USHORT _nId, Outliner* pOutliner ) : EditUndo( _nId, NULL ) { DBG_ASSERT( pOutliner, "Undo: Outliner?!" ); mpOutliner = pOutliner; } OutlinerUndoChangeDepth::OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth ) : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner ) { mnPara = nPara; mnOldDepth = nOldDepth; mnNewDepth = nNewDepth; } void OutlinerUndoChangeDepth::Undo() { GetOutliner()->ImplInitDepth( mnPara, mnOldDepth, FALSE ); } void OutlinerUndoChangeDepth::Redo() { GetOutliner()->ImplInitDepth( mnPara, mnNewDepth, FALSE ); } void OutlinerUndoChangeDepth::Repeat() { DBG_ERROR( "Repeat not implemented!" ); } OutlinerUndoCheckPara::OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara ) : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner ) { mnPara = nPara; } void OutlinerUndoCheckPara::Undo() { Paragraph* pPara = GetOutliner()->GetParagraph( mnPara ); pPara->Invalidate(); GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE ); } void OutlinerUndoCheckPara::Redo() { Paragraph* pPara = GetOutliner()->GetParagraph( mnPara ); pPara->Invalidate(); GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE ); } void OutlinerUndoCheckPara::Repeat() { DBG_ERROR( "Repeat not implemented!" ); } DBG_NAME(OLUndoExpand); OLUndoExpand::OLUndoExpand(Outliner* pOut, USHORT _nId ) : EditUndo( _nId, 0 ) { DBG_CTOR(OLUndoExpand,0); DBG_ASSERT(pOut,"Undo:No Outliner"); pOutliner = pOut; nCount = 0; pParas = 0; } OLUndoExpand::~OLUndoExpand() { DBG_DTOR(OLUndoExpand,0); delete pParas; } void OLUndoExpand::Restore( BOOL bUndo ) { DBG_CHKTHIS(OLUndoExpand,0); DBG_ASSERT(pOutliner,"Undo:No Outliner"); DBG_ASSERT(pOutliner->pEditEngine,"Outliner already deleted"); Paragraph* pPara; BOOL bExpand = FALSE; USHORT _nId = GetId(); if((_nId == OLUNDO_EXPAND && !bUndo) || (_nId == OLUNDO_COLLAPSE && bUndo)) bExpand = TRUE; if( !pParas ) { pPara = pOutliner->GetParagraph( (ULONG)nCount ); if( bExpand ) pOutliner->Expand( pPara ); else pOutliner->Collapse( pPara ); } else { for( USHORT nIdx = 0; nIdx < nCount; nIdx++ ) { pPara = pOutliner->GetParagraph( (ULONG)(pParas[nIdx]) ); if( bExpand ) pOutliner->Expand( pPara ); else pOutliner->Collapse( pPara ); } } } void OLUndoExpand::Undo() { DBG_CHKTHIS(OLUndoExpand,0); Restore( TRUE ); } void OLUndoExpand::Redo() { DBG_CHKTHIS(OLUndoExpand,0); Restore( FALSE ); } void OLUndoExpand::Repeat() { DBG_CHKTHIS(OLUndoExpand,0); DBG_ERROR("Not implemented"); } <commit_msg>INTEGRATION: CWS vgbugs07 (1.6.320); FILE MERGED 2007/06/04 13:27:14 vg 1.6.320.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: outlundo.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-06-27 18:42:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_svx.hxx" #include <outl_pch.hxx> #define _OUTLINER_CXX #include <svx/outliner.hxx> #include <outlundo.hxx> OutlinerUndoBase::OutlinerUndoBase( USHORT _nId, Outliner* pOutliner ) : EditUndo( _nId, NULL ) { DBG_ASSERT( pOutliner, "Undo: Outliner?!" ); mpOutliner = pOutliner; } OutlinerUndoChangeDepth::OutlinerUndoChangeDepth( Outliner* pOutliner, USHORT nPara, USHORT nOldDepth, USHORT nNewDepth ) : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner ) { mnPara = nPara; mnOldDepth = nOldDepth; mnNewDepth = nNewDepth; } void OutlinerUndoChangeDepth::Undo() { GetOutliner()->ImplInitDepth( mnPara, mnOldDepth, FALSE ); } void OutlinerUndoChangeDepth::Redo() { GetOutliner()->ImplInitDepth( mnPara, mnNewDepth, FALSE ); } void OutlinerUndoChangeDepth::Repeat() { DBG_ERROR( "Repeat not implemented!" ); } OutlinerUndoCheckPara::OutlinerUndoCheckPara( Outliner* pOutliner, USHORT nPara ) : OutlinerUndoBase( OLUNDO_DEPTH, pOutliner ) { mnPara = nPara; } void OutlinerUndoCheckPara::Undo() { Paragraph* pPara = GetOutliner()->GetParagraph( mnPara ); pPara->Invalidate(); GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE ); } void OutlinerUndoCheckPara::Redo() { Paragraph* pPara = GetOutliner()->GetParagraph( mnPara ); pPara->Invalidate(); GetOutliner()->ImplCalcBulletText( mnPara, FALSE, FALSE ); } void OutlinerUndoCheckPara::Repeat() { DBG_ERROR( "Repeat not implemented!" ); } DBG_NAME(OLUndoExpand); OLUndoExpand::OLUndoExpand(Outliner* pOut, USHORT _nId ) : EditUndo( _nId, 0 ) { DBG_CTOR(OLUndoExpand,0); DBG_ASSERT(pOut,"Undo:No Outliner"); pOutliner = pOut; nCount = 0; pParas = 0; } OLUndoExpand::~OLUndoExpand() { DBG_DTOR(OLUndoExpand,0); delete pParas; } void OLUndoExpand::Restore( BOOL bUndo ) { DBG_CHKTHIS(OLUndoExpand,0); DBG_ASSERT(pOutliner,"Undo:No Outliner"); DBG_ASSERT(pOutliner->pEditEngine,"Outliner already deleted"); Paragraph* pPara; BOOL bExpand = FALSE; USHORT _nId = GetId(); if((_nId == OLUNDO_EXPAND && !bUndo) || (_nId == OLUNDO_COLLAPSE && bUndo)) bExpand = TRUE; if( !pParas ) { pPara = pOutliner->GetParagraph( (ULONG)nCount ); if( bExpand ) pOutliner->Expand( pPara ); else pOutliner->Collapse( pPara ); } else { for( USHORT nIdx = 0; nIdx < nCount; nIdx++ ) { pPara = pOutliner->GetParagraph( (ULONG)(pParas[nIdx]) ); if( bExpand ) pOutliner->Expand( pPara ); else pOutliner->Collapse( pPara ); } } } void OLUndoExpand::Undo() { DBG_CHKTHIS(OLUndoExpand,0); Restore( TRUE ); } void OLUndoExpand::Redo() { DBG_CHKTHIS(OLUndoExpand,0); Restore( FALSE ); } void OLUndoExpand::Repeat() { DBG_CHKTHIS(OLUndoExpand,0); DBG_ERROR("Not implemented"); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03 // <future> // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(F&& f, Args&&... args); // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(launch policy, F&& f, Args&&... args); #include <future> #include <atomic> #include <memory> #include <cassert> #include "test_macros.h" int foo (int x) { return x; } int main () { std::async( foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} }<commit_msg>Add additional 'UNSUPPORTED' to the test case.<commit_after>//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: libcpp-has-no-threads // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // UNSUPPORTED: clang-3.3, clang-3.4, clang-3.5, clang-3.6, clang-3.7, clang-3.8 // <future> // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(F&& f, Args&&... args); // template <class F, class... Args> // future<typename result_of<F(Args...)>::type> // async(launch policy, F&& f, Args&&... args); #include <future> #include <atomic> #include <memory> #include <cassert> #include "test_macros.h" int foo (int x) { return x; } int main () { std::async( foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} std::async(std::launch::async, foo, 3); // expected-error {{ignoring return value of function declared with 'nodiscard' attribute}} }<|endoftext|>
<commit_before>#include <SFML/Graphics.hpp> #include <vector> #include <string> #include "gui.hpp" #include "message_box.hpp" #include "text.hpp" gui::MessageBox::MessageBox(const sf::Vector2u& dimensions, const std::string& text, const gui::Font& font, const sf::Color& backgroundCol, const sf::Color& textCol) : mDimensions(dimensions), mFont(&font), mCurrentPage(0), mBackgroundCol(backgroundCol), mTextCol(textCol) { createPages(gui::alignString(text, dimensions.x)); } void gui::MessageBox::createPages(const std::vector<std::string>& lines) { unsigned int borderWidth = mDimensions.x + 2; unsigned int& maxWidth = mDimensions.x; unsigned int& maxHeight = mDimensions.y; std::string page = gui::Border::genTop(borderWidth); // If the lines vector is empty, we'll just make a blank box if(lines.size() == 0) { for(size_t i = 0; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); return; } // Otherwise there are lines of text so we can add them for(size_t i = 0; i < lines.size(); ++i) { // There are maxHeight lines, so this is true on the last line if(i % maxHeight == maxHeight-1) { // Expand the line to the width of the box std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth - lines[i].size(), ' '); } // Surround the line with border to pieces and add it to the page page += gui::Border::surround(lines[i]+padding) + "\n"; // Add the bottom border of the page page += gui::Border::genBottom(borderWidth); // Add the page to the list of pages and reset mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); page = gui::Border::genTop(borderWidth); } else { std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth-lines[i].size(), ' '); } page += gui::Border::surround(lines[i] + padding) + "\n"; } } // We'll still have a partial page unless the number of // lines is divisible by the maximum height if(lines.size() % maxHeight != 0) { // Add padding lines to make the page the desired height for(size_t i = lines.size() % maxHeight; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); } } void gui::MessageBox::setPage(unsigned int page) { if(page >= mPages.size()) page = mPages.size() % page; mCurrentPage = page; } unsigned int gui::MessageBox::getPage() const { return mCurrentPage; } unsigned int gui::MessageBox::numPages() const { return mPages.size(); } void gui::MessageBox::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); mPages.at(mCurrentPage).draw(target, states); } sf::Vector2u gui::MessageBox::getSize() const { return mDimensions + sf::Vector2u(2, 2); } void gui::MessageBox::setText(const std::string& text) { mPages.clear(); createPages(gui::alignString(text, mDimensions.x)); } <commit_msg>Changing text of a gui::MessageBox now resets the page properly<commit_after>#include <SFML/Graphics.hpp> #include <vector> #include <string> #include "gui.hpp" #include "message_box.hpp" #include "text.hpp" gui::MessageBox::MessageBox(const sf::Vector2u& dimensions, const std::string& text, const gui::Font& font, const sf::Color& backgroundCol, const sf::Color& textCol) : mDimensions(dimensions), mFont(&font), mCurrentPage(0), mBackgroundCol(backgroundCol), mTextCol(textCol) { createPages(gui::alignString(text, dimensions.x)); } void gui::MessageBox::createPages(const std::vector<std::string>& lines) { unsigned int borderWidth = mDimensions.x + 2; unsigned int& maxWidth = mDimensions.x; unsigned int& maxHeight = mDimensions.y; std::string page = gui::Border::genTop(borderWidth); // If the lines vector is empty, we'll just make a blank box if(lines.size() == 0) { for(size_t i = 0; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); return; } // Otherwise there are lines of text so we can add them for(size_t i = 0; i < lines.size(); ++i) { // There are maxHeight lines, so this is true on the last line if(i % maxHeight == maxHeight-1) { // Expand the line to the width of the box std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth - lines[i].size(), ' '); } // Surround the line with border to pieces and add it to the page page += gui::Border::surround(lines[i]+padding) + "\n"; // Add the bottom border of the page page += gui::Border::genBottom(borderWidth); // Add the page to the list of pages and reset mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); page = gui::Border::genTop(borderWidth); } else { std::string padding; if(lines[i].size() < maxWidth) { padding = std::string(maxWidth-lines[i].size(), ' '); } page += gui::Border::surround(lines[i] + padding) + "\n"; } } // We'll still have a partial page unless the number of // lines is divisible by the maximum height if(lines.size() % maxHeight != 0) { // Add padding lines to make the page the desired height for(size_t i = lines.size() % maxHeight; i < maxHeight; ++i) { page += gui::Border::genRow(borderWidth); } page += gui::Border::genBottom(borderWidth); mPages.push_back(gui::Text(page, *mFont, mBackgroundCol, mTextCol)); } } void gui::MessageBox::setPage(unsigned int page) { if(page >= mPages.size()) page = mPages.size() % page; mCurrentPage = page; } unsigned int gui::MessageBox::getPage() const { return mCurrentPage; } unsigned int gui::MessageBox::numPages() const { return mPages.size(); } void gui::MessageBox::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); mPages.at(mCurrentPage).draw(target, states); } sf::Vector2u gui::MessageBox::getSize() const { return mDimensions + sf::Vector2u(2, 2); } void gui::MessageBox::setText(const std::string& text) { mPages.clear(); createPages(gui::alignString(text, mDimensions.x)); mCurrentPage = 0; } <|endoftext|>
<commit_before>#pragma once /* Manage communication between the two threads: - A Command thread, that manages add-actor/start/status/kill/... requests. This thread also keeps a list of open sockets, for clean termination. - A SimGrid thread, that runs the simulation. Communication is done via lockfree queues. This makes it robust and simple (performance is not critical here, inter-thread messages will be very rare). */ #include <boost/lockfree/queue.hpp> namespace rsg { enum class InterthreadMessageType { // From Command to SimGrid START_SIMULATION, // From SimGrid to Command SIMULATION_FINISHED }; // Abstract base class for message content. struct InterthreadMessageContent { virtual ~InterthreadMessageContent() = 0; }; struct InterthreadMessage { InterthreadMessageType type; InterthreadMessageContent * data = nullptr; }; // Convenient alias using message_queue = boost::lockfree::queue<rsg::InterthreadMessage>; } <commit_msg>[code] remove warning<commit_after>#pragma once /* Manage communication between the two threads: - A Command thread, that manages add-actor/start/status/kill/... requests. This thread also keeps a list of open sockets, for clean termination. - A SimGrid thread, that runs the simulation. Communication is done via lockfree queues. This makes it robust and simple (performance is not critical here, inter-thread messages will be very rare). */ #include <boost/lockfree/queue.hpp> namespace rsg { enum class InterthreadMessageType { UNDEFINED // From Command to SimGrid ,START_SIMULATION // From SimGrid to Command ,SIMULATION_FINISHED }; // Abstract base class for message content. struct InterthreadMessageContent { virtual ~InterthreadMessageContent() = 0; }; struct InterthreadMessage { InterthreadMessageType type = InterthreadMessageType::UNDEFINED; InterthreadMessageContent * data = nullptr; }; // Convenient alias using message_queue = boost::lockfree::queue<rsg::InterthreadMessage>; } <|endoftext|>
<commit_before>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef sw_MutexLock_hpp #define sw_MutexLock_hpp #include "Thread.hpp" #ifdef __ANDROID__ // Use an actual mutex on Android. Since many processes may use SwiftShader // at the same time it's best to just have the scheduler overhead. #include <pthread.h> namespace sw { class MutexLock { public: MutexLock() { pthread_mutex_init(&mutex, NULL); } ~MutexLock() { pthread_mutex_destroy(&mutex); } bool attemptLock() { return pthread_mutex_trylock(&mutex) == 0; } void lock() { pthread_mutex_lock(&mutex); } void unlock() { pthread_mutex_unlock(&mutex); } private: pthread_mutex_t mutex; }; } #else // !__ANDROID__ namespace sw { class BackoffLock { public: BackoffLock() { mutex = 0; } bool attemptLock() { if(!isLocked()) { if(atomicExchange(&mutex, 1) == 0) { return true; } } return false; } void lock() { int backoff = 1; while(!attemptLock()) { if(backoff <= 64) { for(int i = 0; i < backoff; i++) { nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); } backoff *= 2; } else { Thread::yield(); backoff = 1; } }; } void unlock() { mutex = 0; } bool isLocked() { return mutex != 0; } private: struct { // Ensure that the mutex variable is on its own 64-byte cache line to avoid false sharing // Padding must be public to avoid compiler warnings volatile int padding1[16]; volatile int mutex; volatile int padding2[15]; }; }; using MutexLock = BackoffLock; } #endif // !__ANDROID__ class LockGuard { public: explicit LockGuard(sw::MutexLock &mutex) : mutex(mutex) { mutex.lock(); } ~LockGuard() { mutex.unlock(); } protected: sw::MutexLock &mutex; }; #endif // sw_MutexLock_hpp <commit_msg>Fix potential data race in mutex lock implementation.<commit_after>// Copyright 2016 The SwiftShader Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef sw_MutexLock_hpp #define sw_MutexLock_hpp #include "Thread.hpp" #ifdef __ANDROID__ // Use an actual mutex on Android. Since many processes may use SwiftShader // at the same time it's best to just have the scheduler overhead. #include <pthread.h> namespace sw { class MutexLock { public: MutexLock() { pthread_mutex_init(&mutex, NULL); } ~MutexLock() { pthread_mutex_destroy(&mutex); } bool attemptLock() { return pthread_mutex_trylock(&mutex) == 0; } void lock() { pthread_mutex_lock(&mutex); } void unlock() { pthread_mutex_unlock(&mutex); } private: pthread_mutex_t mutex; }; } #else // !__ANDROID__ #include <atomic> namespace sw { class BackoffLock { public: BackoffLock() { mutex = 0; } bool attemptLock() { if(!isLocked()) { if(mutex.exchange(true) == false) { return true; } } return false; } void lock() { int backoff = 1; while(!attemptLock()) { if(backoff <= 64) { for(int i = 0; i < backoff; i++) { nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); nop(); } backoff *= 2; } else { Thread::yield(); backoff = 1; } }; } void unlock() { mutex.store(false, std::memory_order_release); } bool isLocked() { return mutex.load(std::memory_order_acquire); } private: struct { // Ensure that the mutex variable is on its own 64-byte cache line to avoid false sharing // Padding must be public to avoid compiler warnings volatile int padding1[16]; std::atomic<bool> mutex; volatile int padding2[15]; }; }; using MutexLock = BackoffLock; } #endif // !__ANDROID__ class LockGuard { public: explicit LockGuard(sw::MutexLock &mutex) : mutex(mutex) { mutex.lock(); } ~LockGuard() { mutex.unlock(); } protected: sw::MutexLock &mutex; }; #endif // sw_MutexLock_hpp <|endoftext|>
<commit_before>#include <variant> #include <catch2/catch.hpp> #include "dexode/EventBus.hpp" #include "dexode/eventbus/test/event.hpp" namespace dexode::eventbus::test { // class TestProducer //{ // public: // using Events = std::variant<event::T1, event::T2>; // // void onUpdate(TransactionEventBus& bus) // { // bus.postpone(event::T1{}); // } // // private: //}; // TEST_CASE("Should process events independently When postponed multiple event types", // "[EventBus]") //{ // EventBus bus; // // int event1CallCount = 0; // int event2CallCount = 0; // // auto listener = Listener::createNotOwning(bus); // listener.listen<event::T1>([&](const event::T1& event) { ++event1CallCount; }); // listener.listen2([&](const event::T2& event) { ++event2CallCount; }); // // bus.postpone(event::T1{}); // { // event::T2 localVariable; // bus.postpone(localVariable); // } // // REQUIRE(event1CallCount == 0); // REQUIRE(event2CallCount == 0); // REQUIRE(bus.process<event::T1>() == 1); // REQUIRE(event1CallCount == 1); // REQUIRE(event2CallCount == 0); // // REQUIRE(bus.process<event::T2>() == 1); // REQUIRE(event1CallCount == 1); // REQUIRE(event2CallCount == 1); //} TEST_CASE("Should deliver event with desired value When postpone event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); REQUIRE(callCount == 0); bus.postpone(event::Value{3}); REQUIRE(callCount == 0); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } TEST_CASE("Should be able to replace listener When we do listen -> unlisten -> listen", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; { // TODO validate other signatures is it possible to make mistake? (maybe fail to build tests // ?) listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } { listener.unlisten<event::Value>(); bus.postpone(event::Value{2}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } { listener.listen([&](const event::Value& event) { REQUIRE(event.value == 1); ++callCount; }); bus.postpone(event::Value{1}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 2); } } TEST_CASE("Should be able to replace listener When we do listen -> unlistenAll -> listen", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; { // TODO validate other signatures is it possible to make mistake? (maybe fail to build tests // ?) listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); listener.listen([&](const event::T1& event) { ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 2); } { listener.unlistenAll(); bus.postpone(event::Value{3}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 2); // no new calls } { listener.listen([&](const event::Value& event) { REQUIRE(event.value == 1); ++callCount; }); bus.postpone(event::Value{1}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 3); } } TEST_CASE("Should flush events When no one listens", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events } TEST_CASE("Should be able to unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { ++callCount; listener.unlisten<event::Value>(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 1); } TEST_CASE("Should not fail When unlisten multiple times during processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { REQUIRE_NOTHROW(listener.unlisten<event::Value>()); REQUIRE_NOTHROW(listener.unlisten<event::Value>()); REQUIRE_NOTHROW(listener.unlisten<event::Value>()); ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 1); } TEST_CASE("Should fail When try to add not unique listener", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); REQUIRE_NOTHROW(listener.listen([](const event::T1&) {})); REQUIRE_THROWS(listener.listen([](const event::T1&) {})); // We already added listener } TEST_CASE("Should be able to add listener When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callCountOther = 0; listener.listen([&](const event::Value& event) { ++callCount; if(callCount == 1) // remember that we can only add it once! { listenerOther.listen( [&callCountOther](const event::Value& event) { ++callCountOther; }); } }); { bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); REQUIRE(callCountOther == 0); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 2); REQUIRE(callCountOther == 1); } { listenerOther.unlistenAll(); callCount = 0; callCountOther = 0; bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 3); REQUIRE(callCountOther == 2); } } TEST_CASE("Should be able to add listener and unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callCountOther = 0; listener.listen([&](const event::Value& event) { ++callCount; if(callCount == 1) // remember that we can only add it once! { listenerOther.listen([&](const event::Value& event) { ++callCountOther; }); } listener.unlistenAll(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); REQUIRE(callCount == 1); REQUIRE(callCountOther == 2); } TEST_CASE( "Should be able to add listener and remove listener in Matryoshka style When processing event", "[EventBus]") { EventBus bus; auto listener1 = EventBus::Listener::createNotOwning(bus); auto listener2 = EventBus::Listener::createNotOwning(bus); auto listener3 = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener1.listen([&](const event::Value& event) { listener1.unlistenAll(); // Level 1 listener2.listen([&](const event::Value& event) { listener2.unlistenAll(); // Level 2 listener3.listen([&](const event::Value& event) { listener3.unlistenAll(); // Level 3 (final) ++callCount; }); ++callCount; }); ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 4); REQUIRE(callCount == 3); } TEST_CASE("Should be chain listen and unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callOtherOption = 0; listener.listen([&](const event::Value& event) { ++callCount; // remember that we can only add it once! listenerOther.listen([&](const event::Value& event) { callOtherOption = 1; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 2; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 3; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 4; }); listener.unlistenAll(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); REQUIRE(callCount == 1); REQUIRE(callOtherOption == 4); } TEST_CASE("Should not process events When no more events", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(bus.process() == 0); } TEST_CASE("Should distinguish event producer When", "[EventBus]") { // EventBus bus; // // // dexode::eventbus::WrapTag<event::T1, Tag, Tag::gui> e; // // int counterGui = 0; // int counterBackend = 0; // auto listener = EventBus::Listener::createNotOwning(bus); // // listener.listen([&](const event::Tag<event::T1>& event) { // if(event.tag == "gui") // { // ++counterGui; // } // else if(event.tag == "backend") // { // ++counterBackend; // } // else // { // FAIL(); // } // }); // // auto producerGui = [tag = Tag::gui](EventBus& bus) { // const event::T1 event; // bus.postpone(event); // }; // // auto producerBackend = [](EventBus& bus) { // const event::T1 event; // bus.postpone(Tag::backend, event); // }; // // auto producerNoTag = [](EventBus& bus) { // const event::T1 event; // bus.postpone(event); // }; // // auto producerGeneric = [](EventBus& bus, Tag tag) { // const event::T1 event; // if(tag == Tag::none) // { // bus.postpone(event); // } // else // { // bus.postpone(tag, event); // } // }; // // producerGui(bus); // producerGui(bus); // producerBackend(bus); // producerGui(bus); // producerNoTag(bus); // producerGeneric(bus, Tag::none); // producerGeneric(bus, Tag::backend); // // CHECK(bus.process() == 7); // // REQUIRE(counterGui == 3); // REQUIRE(counterBackend == 2); } } // namespace dexode::eventbus::test // TODO should listen work with bind'ing e.g. //_listener.listen<dashboard::back::events::LoadOrders>( // std::bind(&BackDashboard::onLoadOrders, this, std::placeholders::_1)); <commit_msg>Add unit test for processing events behavior<commit_after>#include <variant> #include <catch2/catch.hpp> #include "dexode/EventBus.hpp" #include "dexode/eventbus/test/event.hpp" namespace dexode::eventbus::test { // class TestProducer //{ // public: // using Events = std::variant<event::T1, event::T2>; // // void onUpdate(TransactionEventBus& bus) // { // bus.postpone(event::T1{}); // } // // private: //}; // TEST_CASE("Should process events independently When postponed multiple event types", // "[EventBus]") //{ // EventBus bus; // // int event1CallCount = 0; // int event2CallCount = 0; // // auto listener = Listener::createNotOwning(bus); // listener.listen<event::T1>([&](const event::T1& event) { ++event1CallCount; }); // listener.listen2([&](const event::T2& event) { ++event2CallCount; }); // // bus.postpone(event::T1{}); // { // event::T2 localVariable; // bus.postpone(localVariable); // } // // REQUIRE(event1CallCount == 0); // REQUIRE(event2CallCount == 0); // REQUIRE(bus.process<event::T1>() == 1); // REQUIRE(event1CallCount == 1); // REQUIRE(event2CallCount == 0); // // REQUIRE(bus.process<event::T2>() == 1); // REQUIRE(event1CallCount == 1); // REQUIRE(event2CallCount == 1); //} TEST_CASE("Should deliver event with desired value When postpone event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); REQUIRE(callCount == 0); bus.postpone(event::Value{3}); REQUIRE(callCount == 0); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } TEST_CASE("Should be able to replace listener When we do listen -> unlisten -> listen", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; { // TODO validate other signatures is it possible to make mistake? (maybe fail to build tests // ?) listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } { listener.unlisten<event::Value>(); bus.postpone(event::Value{2}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); } { listener.listen([&](const event::Value& event) { REQUIRE(event.value == 1); ++callCount; }); bus.postpone(event::Value{1}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 2); } } TEST_CASE("Should be able to replace listener When we do listen -> unlistenAll -> listen", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; { // TODO validate other signatures is it possible to make mistake? (maybe fail to build tests // ?) listener.listen([&](const event::Value& event) { REQUIRE(event.value == 3); ++callCount; }); listener.listen([&](const event::T1& event) { ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 2); } { listener.unlistenAll(); bus.postpone(event::Value{3}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 2); // no new calls } { listener.listen([&](const event::Value& event) { REQUIRE(event.value == 1); ++callCount; }); bus.postpone(event::Value{1}); bus.postpone(event::T1{}); REQUIRE(bus.process() == 2); REQUIRE(callCount == 3); } } TEST_CASE("Should flush events When no one listens", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events } TEST_CASE("Should be able to unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { ++callCount; listener.unlisten<event::Value>(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 1); } TEST_CASE("Should not fail When unlisten multiple times during processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener.listen([&](const event::Value& event) { REQUIRE_NOTHROW(listener.unlisten<event::Value>()); REQUIRE_NOTHROW(listener.unlisten<event::Value>()); REQUIRE_NOTHROW(listener.unlisten<event::Value>()); ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 1); } TEST_CASE("Should fail When try to add not unique listener", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); REQUIRE_NOTHROW(listener.listen([](const event::T1&) {})); REQUIRE_THROWS(listener.listen([](const event::T1&) {})); // We already added listener } TEST_CASE("Should be able to add listener When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callCountOther = 0; listener.listen([&](const event::Value& event) { ++callCount; if(callCount == 1) // remember that we can only add it once! { listenerOther.listen( [&callCountOther](const event::Value& event) { ++callCountOther; }); } }); { bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 1); REQUIRE(callCountOther == 0); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 1); REQUIRE(callCount == 2); REQUIRE(callCountOther == 1); } { listenerOther.unlistenAll(); callCount = 0; callCountOther = 0; bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(callCount == 3); REQUIRE(callCountOther == 2); } } TEST_CASE("Should be able to add listener and unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callCountOther = 0; listener.listen([&](const event::Value& event) { ++callCount; if(callCount == 1) // remember that we can only add it once! { listenerOther.listen([&](const event::Value& event) { ++callCountOther; }); } listener.unlistenAll(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); REQUIRE(callCount == 1); REQUIRE(callCountOther == 2); } TEST_CASE( "Should be able to add listener and remove listener in Matryoshka style When processing event", "[EventBus]") { EventBus bus; auto listener1 = EventBus::Listener::createNotOwning(bus); auto listener2 = EventBus::Listener::createNotOwning(bus); auto listener3 = EventBus::Listener::createNotOwning(bus); int callCount = 0; listener1.listen([&](const event::Value& event) { listener1.unlistenAll(); // Level 1 listener2.listen([&](const event::Value& event) { listener2.unlistenAll(); // Level 2 listener3.listen([&](const event::Value& event) { listener3.unlistenAll(); // Level 3 (final) ++callCount; }); ++callCount; }); ++callCount; }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 4); REQUIRE(callCount == 3); } TEST_CASE("Should be chain listen and unlisten When processing event", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); auto listenerOther = EventBus::Listener::createNotOwning(bus); int callCount = 0; int callOtherOption = 0; listener.listen([&](const event::Value& event) { ++callCount; // remember that we can only add it once! listenerOther.listen([&](const event::Value& event) { callOtherOption = 1; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 2; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 3; }); listenerOther.unlisten<event::Value>(); listenerOther.listen([&](const event::Value& event) { callOtherOption = 4; }); listener.unlistenAll(); }); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); REQUIRE(callCount == 1); REQUIRE(callOtherOption == 4); } TEST_CASE("Should not process events When no more events", "[EventBus]") { EventBus bus; auto listener = EventBus::Listener::createNotOwning(bus); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); bus.postpone(event::Value{3}); REQUIRE(bus.process() == 3); // it shouldn't accumulate events REQUIRE(bus.process() == 0); } TEST_CASE("Should process event When listener transit", "[EventBus]") { /** * This case may be usefull when we use EventBus for some kind of state machine and we are * during transit from one state to other. */ EventBus bus; auto listenerA = EventBus::Listener::createNotOwning(bus); auto listenerB = EventBus::Listener::createNotOwning(bus); int listenerAReceiveEvent = 0; int listenerBReceiveEvent = 0; listenerA.listen([&](const event::Value& event) { ++listenerAReceiveEvent; }); REQUIRE(bus.process() == 0); // All cases should be same because of deterministic way of processing SECTION("Post event before transit") { bus.postpone(event::Value{3}); // <-- before listenerA.unlistenAll(); listenerB.listen([&](const event::Value& event) { ++listenerBReceiveEvent; }); } SECTION("Post event in transit") { listenerA.unlistenAll(); bus.postpone(event::Value{3}); // <-- in listenerB.listen([&](const event::Value& event) { ++listenerBReceiveEvent; }); } SECTION("Post event after transit") { listenerA.unlistenAll(); listenerB.listen([&](const event::Value& event) { ++listenerBReceiveEvent; }); bus.postpone(event::Value{3}); // <-- after } REQUIRE(bus.process() == 1); CHECK(listenerAReceiveEvent == 0); CHECK(listenerBReceiveEvent == 1); } TEST_CASE("Should distinguish event producer When", "[EventBus]") { // EventBus bus; // // // dexode::eventbus::WrapTag<event::T1, Tag, Tag::gui> e; // // int counterGui = 0; // int counterBackend = 0; // auto listener = EventBus::Listener::createNotOwning(bus); // // listener.listen([&](const event::Tag<event::T1>& event) { // if(event.tag == "gui") // { // ++counterGui; // } // else if(event.tag == "backend") // { // ++counterBackend; // } // else // { // FAIL(); // } // }); // // auto producerGui = [tag = Tag::gui](EventBus& bus) { // const event::T1 event; // bus.postpone(event); // }; // // auto producerBackend = [](EventBus& bus) { // const event::T1 event; // bus.postpone(Tag::backend, event); // }; // // auto producerNoTag = [](EventBus& bus) { // const event::T1 event; // bus.postpone(event); // }; // // auto producerGeneric = [](EventBus& bus, Tag tag) { // const event::T1 event; // if(tag == Tag::none) // { // bus.postpone(event); // } // else // { // bus.postpone(tag, event); // } // }; // // producerGui(bus); // producerGui(bus); // producerBackend(bus); // producerGui(bus); // producerNoTag(bus); // producerGeneric(bus, Tag::none); // producerGeneric(bus, Tag::backend); // // CHECK(bus.process() == 7); // // REQUIRE(counterGui == 3); // REQUIRE(counterBackend == 2); } } // namespace dexode::eventbus::test // TODO should listen work with bind'ing e.g. //_listener.listen<dashboard::back::events::LoadOrders>( // std::bind(&BackDashboard::onLoadOrders, this, std::placeholders::_1)); <|endoftext|>
<commit_before><commit_msg>Fix logic inversion<commit_after><|endoftext|>
<commit_before><commit_msg>Remove some useless swapping call inside SwGrfNode<commit_after><|endoftext|>
<commit_before><commit_msg>WaE: private field 'doc' is not used<commit_after><|endoftext|>
<commit_before>/// /// @file calculator.hpp /// @brief calculator::eval(const std::string&) evaluates an integer /// arithmetic expression and returns the result. If an error /// occurs a calculator::error exception is thrown. /// <https://github.com/kimwalisch/calculator> /// @author Kim Walisch, <kim.walisch@gmail.com> /// @copyright Copyright (C) 2013-2018 Kim Walisch /// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause /// @version 1.2 /// /// == Supported operators == /// /// OPERATOR NAME ASSOCIATIVITY PRECEDENCE /// /// | Bitwise Inclusive OR Left 4 /// ^ Bitwise Exclusive OR Left 5 /// & Bitwise AND Left 6 /// << Shift Left Left 9 /// >> Shift Right Left 9 /// + Addition Left 10 /// - Subtraction Left 10 /// * Multiplication Left 20 /// / Division Left 20 /// % Modulo Left 20 /// ** Raise to power Right 30 /// e, E Scientific notation Right 40 /// ~ Unary complement Left 99 /// /// The operator precedence has been set according to (uses the C and /// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations /// Operators with higher precedence are evaluated before operators /// with relatively lower precedence. Unary operators are set to have /// the highest precedence, this is not strictly correct for the power /// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell, /// Microsoft Excel, GNU bc, ...) use the same convention. /// /// == Examples of valid expressions == /// /// "65536 >> 15" = 2 /// "2**16" = 65536 /// "(0 + 0xDf234 - 1000)*3/2%999" = 828 /// "-(2**2**2**2)" = -65536 /// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817 /// "(2**16) + (1 << 16) >> 0X5" = 4096 /// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221 /// /// == About the algorithm used == /// /// calculator::eval(std::string&) relies on the ExpressionParser /// class which is a simple C++ operator precedence parser with infix /// notation for integer arithmetic expressions. /// ExpressionParser has its roots in a JavaScript parser published /// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961 /// The same author has also published an article about his operator /// precedence algorithm at PerlMonks: /// http://www.perlmonks.org/?node_id=554516 /// #ifndef CALCULATOR_HPP #define CALCULATOR_HPP #include <stdexcept> #include <string> #include <sstream> #include <stack> #include <cstddef> #include <cctype> namespace calculator { /// calculator::eval() throws a calculator::error if it fails /// to evaluate the expression string. /// class error : public std::runtime_error { public: error(const std::string& expr, const std::string& message) : std::runtime_error(message), expr_(expr) { } #if __cplusplus >= 201103L ~error() { } #else ~error() throw() { } #endif std::string expression() const { return expr_; } private: std::string expr_; }; template <typename T> class ExpressionParser { public: /// Evaluate an integer arithmetic expression and return its result. /// @throw error if parsing fails. /// T eval(const std::string& expr) { T result = 0; index_ = 0; expr_ = expr; try { result = parseExpr(); if (!isEnd()) unexpected(); } catch (const calculator::error&) { while(!stack_.empty()) stack_.pop(); throw; } return result; } /// Get the integer value of a character. T eval(char c) { std::string expr(1, c); return eval(expr); } private: enum { OPERATOR_NULL, OPERATOR_BITWISE_OR, /// | OPERATOR_BITWISE_XOR, /// ^ OPERATOR_BITWISE_AND, /// & OPERATOR_BITWISE_SHL, /// << OPERATOR_BITWISE_SHR, /// >> OPERATOR_ADDITION, /// + OPERATOR_SUBTRACTION, /// - OPERATOR_MULTIPLICATION, /// * OPERATOR_DIVISION, /// / OPERATOR_MODULO, /// % OPERATOR_POWER, /// ** OPERATOR_EXPONENT /// e, E }; struct Operator { /// Operator, one of the OPERATOR_* enum definitions int op; int precedence; /// 'L' = left or 'R' = right int associativity; Operator(int opr, int prec, int assoc) : op(opr), precedence(prec), associativity(assoc) { } }; struct OperatorValue { Operator op; T value; OperatorValue(const Operator& opr, T val) : op(opr), value(val) { } int getPrecedence() const { return op.precedence; } bool isNull() const { return op.op == OPERATOR_NULL; } }; /// Expression string std::string expr_; /// Current expression index, incremented whilst parsing std::size_t index_; /// The current operator and its left value /// are pushed onto the stack if the operator on /// top of the stack has lower precedence. std::stack<OperatorValue> stack_; /// Exponentiation by squaring, x^n. static T pow(T x, T n) { if (n <= 0) return 0; T res = 1; while (n > 0) { if (n % 2 != 0) { res *= x; n -= 1; } n /= 2; if (n > 0) x *= x; } return res; } T checkZero(T value) const { if (value == 0) { std::string divOperators("/%"); std::size_t division = expr_.find_last_of(divOperators, index_ - 2); std::ostringstream msg; msg << "Parser error: division by 0"; if (division != std::string::npos) msg << " (error token is \"" << expr_.substr(division, expr_.size() - division) << "\")"; throw calculator::error(expr_, msg.str()); } return value; } T calculate(T v1, T v2, const Operator& op) const { switch (op.op) { case OPERATOR_BITWISE_OR: return v1 | v2; case OPERATOR_BITWISE_XOR: return v1 ^ v2; case OPERATOR_BITWISE_AND: return v1 & v2; case OPERATOR_BITWISE_SHL: return v1 << v2; case OPERATOR_BITWISE_SHR: return v1 >> v2; case OPERATOR_ADDITION: return v1 + v2; case OPERATOR_SUBTRACTION: return v1 - v2; case OPERATOR_MULTIPLICATION: return v1 * v2; case OPERATOR_DIVISION: return v1 / checkZero(v2); case OPERATOR_MODULO: return v1 % checkZero(v2); case OPERATOR_POWER: return pow(v1, v2); case OPERATOR_EXPONENT: return v1 * pow(10, v2); default: return 0; } } bool isEnd() const { return index_ >= expr_.size(); } /// Returns the character at the current expression index or /// 0 if the end of the expression is reached. /// char getCharacter() const { if (!isEnd()) return expr_[index_]; return 0; } /// Parse str at the current expression index. /// @throw error if parsing fails. /// void expect(const std::string& str) { if (expr_.compare(index_, str.size(), str) != 0) unexpected(); index_ += str.size(); } void unexpected() const { std::ostringstream msg; msg << "Syntax error: unexpected token \"" << expr_.substr(index_, expr_.size() - index_) << "\" at index " << index_; throw calculator::error(expr_, msg.str()); } /// Eat all white space characters at the /// current expression index. /// void eatSpaces() { while (std::isspace(getCharacter()) != 0) index_++; } /// Parse a binary operator at the current expression index. /// @return Operator with precedence and associativity. /// Operator parseOp() { eatSpaces(); switch (getCharacter()) { case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L'); case '^': index_++; return Operator(OPERATOR_BITWISE_XOR, 5, 'L'); case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L'); case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L'); case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L'); case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L'); case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L'); case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L'); case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L'); case '*': index_++; if (getCharacter() != '*') return Operator(OPERATOR_MULTIPLICATION, 20, 'L'); index_++; return Operator(OPERATOR_POWER, 30, 'R'); case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); default : return Operator(OPERATOR_NULL, 0, 'L'); } } static T toInteger(char c) { if (c >= '0' && c <= '9') return c -'0'; if (c >= 'a' && c <= 'f') return c -'a' + 0xa; if (c >= 'A' && c <= 'F') return c -'A' + 0xa; T noDigit = 0xf + 1; return noDigit; } T getInteger() const { return toInteger(getCharacter()); } T parseDecimal() { T value = 0; for (T d; (d = getInteger()) <= 9; index_++) value = value * 10 + d; return value; } T parseHex() { index_ = index_ + 2; T value = 0; for (T h; (h = getInteger()) <= 0xf; index_++) value = value * 0x10 + h; return value; } bool isHex() const { if (index_ + 2 < expr_.size()) { char x = expr_[index_ + 1]; char h = expr_[index_ + 2]; return (std::tolower(x) == 'x' && toInteger(h) <= 0xf); } return false; } /// Parse an integer value at the current expression index. /// The unary `+', `-' and `~' operators and opening /// parentheses `(' cause recursion. /// T parseValue() { T val = 0; eatSpaces(); switch (getCharacter()) { case '0': if (isHex()) val = parseHex(); else val = parseDecimal(); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': val = parseDecimal(); break; case '(': index_++; val = parseExpr(); eatSpaces(); if (getCharacter() != ')') { if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: `)' expected at end of expression"); } index_++; break; case '~': index_++; val = ~parseValue(); break; case '+': index_++; val = parseValue(); break; case '-': index_++; val = parseValue() * static_cast<T>(-1); break; default : if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: value expected at end of expression"); } return val; } /// Parse all operations of the current parenthesis /// level and the levels above, when done /// return the result (value). /// T parseExpr() { stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0)); // first parse value on the left T value = parseValue(); while (!stack_.empty()) { // parse an operator (+, -, *, ...) Operator op(parseOp()); while (op.precedence < stack_.top().getPrecedence() || ( op.precedence == stack_.top().getPrecedence() && op.associativity == 'L')) { // end reached if (stack_.top().isNull()) { stack_.pop(); return value; } // do the calculation ("reduce"), producing a new value value = calculate(stack_.top().value, value, stack_.top().op); stack_.pop(); } // store on stack_ and continue parsing ("shift") stack_.push(OperatorValue(op, value)); // parse value on the right value = parseValue(); } return 0; } }; template <typename T> inline T eval(const std::string& expression) { ExpressionParser<T> parser; return parser.eval(expression); } template <typename T> inline T eval(char c) { ExpressionParser<T> parser; return parser.eval(c); } inline int eval(const std::string& expression) { return eval<int>(expression); } inline int eval(char c) { return eval<int>(c); } } // namespace calculator #endif <commit_msg>pow(x, 0) = 1<commit_after>/// /// @file calculator.hpp /// @brief calculator::eval(const std::string&) evaluates an integer /// arithmetic expression and returns the result. If an error /// occurs a calculator::error exception is thrown. /// <https://github.com/kimwalisch/calculator> /// @author Kim Walisch, <kim.walisch@gmail.com> /// @copyright Copyright (C) 2013-2018 Kim Walisch /// @license BSD 2-Clause, http://opensource.org/licenses/BSD-2-Clause /// @version 1.2 /// /// == Supported operators == /// /// OPERATOR NAME ASSOCIATIVITY PRECEDENCE /// /// | Bitwise Inclusive OR Left 4 /// ^ Bitwise Exclusive OR Left 5 /// & Bitwise AND Left 6 /// << Shift Left Left 9 /// >> Shift Right Left 9 /// + Addition Left 10 /// - Subtraction Left 10 /// * Multiplication Left 20 /// / Division Left 20 /// % Modulo Left 20 /// ** Raise to power Right 30 /// e, E Scientific notation Right 40 /// ~ Unary complement Left 99 /// /// The operator precedence has been set according to (uses the C and /// C++ operator precedence): http://en.wikipedia.org/wiki/Order_of_operations /// Operators with higher precedence are evaluated before operators /// with relatively lower precedence. Unary operators are set to have /// the highest precedence, this is not strictly correct for the power /// operator e.g. "-3**2" = 9 but a lot of software tools (Bash shell, /// Microsoft Excel, GNU bc, ...) use the same convention. /// /// == Examples of valid expressions == /// /// "65536 >> 15" = 2 /// "2**16" = 65536 /// "(0 + 0xDf234 - 1000)*3/2%999" = 828 /// "-(2**2**2**2)" = -65536 /// "(0 + ~(0xDF234 & 1000) *3) /-2" = 817 /// "(2**16) + (1 << 16) >> 0X5" = 4096 /// "5*-(2**(9+7))/3+5*(1 & 0xFf123)" = -109221 /// /// == About the algorithm used == /// /// calculator::eval(std::string&) relies on the ExpressionParser /// class which is a simple C++ operator precedence parser with infix /// notation for integer arithmetic expressions. /// ExpressionParser has its roots in a JavaScript parser published /// at: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence/114961#114961 /// The same author has also published an article about his operator /// precedence algorithm at PerlMonks: /// http://www.perlmonks.org/?node_id=554516 /// #ifndef CALCULATOR_HPP #define CALCULATOR_HPP #include <stdexcept> #include <string> #include <sstream> #include <stack> #include <cstddef> #include <cctype> namespace calculator { /// calculator::eval() throws a calculator::error if it fails /// to evaluate the expression string. /// class error : public std::runtime_error { public: error(const std::string& expr, const std::string& message) : std::runtime_error(message), expr_(expr) { } #if __cplusplus >= 201103L ~error() { } #else ~error() throw() { } #endif std::string expression() const { return expr_; } private: std::string expr_; }; template <typename T> class ExpressionParser { public: /// Evaluate an integer arithmetic expression and return its result. /// @throw error if parsing fails. /// T eval(const std::string& expr) { T result = 0; index_ = 0; expr_ = expr; try { result = parseExpr(); if (!isEnd()) unexpected(); } catch (const calculator::error&) { while(!stack_.empty()) stack_.pop(); throw; } return result; } /// Get the integer value of a character. T eval(char c) { std::string expr(1, c); return eval(expr); } private: enum { OPERATOR_NULL, OPERATOR_BITWISE_OR, /// | OPERATOR_BITWISE_XOR, /// ^ OPERATOR_BITWISE_AND, /// & OPERATOR_BITWISE_SHL, /// << OPERATOR_BITWISE_SHR, /// >> OPERATOR_ADDITION, /// + OPERATOR_SUBTRACTION, /// - OPERATOR_MULTIPLICATION, /// * OPERATOR_DIVISION, /// / OPERATOR_MODULO, /// % OPERATOR_POWER, /// ** OPERATOR_EXPONENT /// e, E }; struct Operator { /// Operator, one of the OPERATOR_* enum definitions int op; int precedence; /// 'L' = left or 'R' = right int associativity; Operator(int opr, int prec, int assoc) : op(opr), precedence(prec), associativity(assoc) { } }; struct OperatorValue { Operator op; T value; OperatorValue(const Operator& opr, T val) : op(opr), value(val) { } int getPrecedence() const { return op.precedence; } bool isNull() const { return op.op == OPERATOR_NULL; } }; /// Expression string std::string expr_; /// Current expression index, incremented whilst parsing std::size_t index_; /// The current operator and its left value /// are pushed onto the stack if the operator on /// top of the stack has lower precedence. std::stack<OperatorValue> stack_; /// Exponentiation by squaring, x^n. static T pow(T x, T n) { T res = 1; while (n > 0) { if (n % 2 != 0) { res *= x; n -= 1; } n /= 2; if (n > 0) x *= x; } return res; } T checkZero(T value) const { if (value == 0) { std::string divOperators("/%"); std::size_t division = expr_.find_last_of(divOperators, index_ - 2); std::ostringstream msg; msg << "Parser error: division by 0"; if (division != std::string::npos) msg << " (error token is \"" << expr_.substr(division, expr_.size() - division) << "\")"; throw calculator::error(expr_, msg.str()); } return value; } T calculate(T v1, T v2, const Operator& op) const { switch (op.op) { case OPERATOR_BITWISE_OR: return v1 | v2; case OPERATOR_BITWISE_XOR: return v1 ^ v2; case OPERATOR_BITWISE_AND: return v1 & v2; case OPERATOR_BITWISE_SHL: return v1 << v2; case OPERATOR_BITWISE_SHR: return v1 >> v2; case OPERATOR_ADDITION: return v1 + v2; case OPERATOR_SUBTRACTION: return v1 - v2; case OPERATOR_MULTIPLICATION: return v1 * v2; case OPERATOR_DIVISION: return v1 / checkZero(v2); case OPERATOR_MODULO: return v1 % checkZero(v2); case OPERATOR_POWER: return pow(v1, v2); case OPERATOR_EXPONENT: return v1 * pow(10, v2); default: return 0; } } bool isEnd() const { return index_ >= expr_.size(); } /// Returns the character at the current expression index or /// 0 if the end of the expression is reached. /// char getCharacter() const { if (!isEnd()) return expr_[index_]; return 0; } /// Parse str at the current expression index. /// @throw error if parsing fails. /// void expect(const std::string& str) { if (expr_.compare(index_, str.size(), str) != 0) unexpected(); index_ += str.size(); } void unexpected() const { std::ostringstream msg; msg << "Syntax error: unexpected token \"" << expr_.substr(index_, expr_.size() - index_) << "\" at index " << index_; throw calculator::error(expr_, msg.str()); } /// Eat all white space characters at the /// current expression index. /// void eatSpaces() { while (std::isspace(getCharacter()) != 0) index_++; } /// Parse a binary operator at the current expression index. /// @return Operator with precedence and associativity. /// Operator parseOp() { eatSpaces(); switch (getCharacter()) { case '|': index_++; return Operator(OPERATOR_BITWISE_OR, 4, 'L'); case '^': index_++; return Operator(OPERATOR_BITWISE_XOR, 5, 'L'); case '&': index_++; return Operator(OPERATOR_BITWISE_AND, 6, 'L'); case '<': expect("<<"); return Operator(OPERATOR_BITWISE_SHL, 9, 'L'); case '>': expect(">>"); return Operator(OPERATOR_BITWISE_SHR, 9, 'L'); case '+': index_++; return Operator(OPERATOR_ADDITION, 10, 'L'); case '-': index_++; return Operator(OPERATOR_SUBTRACTION, 10, 'L'); case '/': index_++; return Operator(OPERATOR_DIVISION, 20, 'L'); case '%': index_++; return Operator(OPERATOR_MODULO, 20, 'L'); case '*': index_++; if (getCharacter() != '*') return Operator(OPERATOR_MULTIPLICATION, 20, 'L'); index_++; return Operator(OPERATOR_POWER, 30, 'R'); case 'e': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); case 'E': index_++; return Operator(OPERATOR_EXPONENT, 40, 'R'); default : return Operator(OPERATOR_NULL, 0, 'L'); } } static T toInteger(char c) { if (c >= '0' && c <= '9') return c -'0'; if (c >= 'a' && c <= 'f') return c -'a' + 0xa; if (c >= 'A' && c <= 'F') return c -'A' + 0xa; T noDigit = 0xf + 1; return noDigit; } T getInteger() const { return toInteger(getCharacter()); } T parseDecimal() { T value = 0; for (T d; (d = getInteger()) <= 9; index_++) value = value * 10 + d; return value; } T parseHex() { index_ = index_ + 2; T value = 0; for (T h; (h = getInteger()) <= 0xf; index_++) value = value * 0x10 + h; return value; } bool isHex() const { if (index_ + 2 < expr_.size()) { char x = expr_[index_ + 1]; char h = expr_[index_ + 2]; return (std::tolower(x) == 'x' && toInteger(h) <= 0xf); } return false; } /// Parse an integer value at the current expression index. /// The unary `+', `-' and `~' operators and opening /// parentheses `(' cause recursion. /// T parseValue() { T val = 0; eatSpaces(); switch (getCharacter()) { case '0': if (isHex()) val = parseHex(); else val = parseDecimal(); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': val = parseDecimal(); break; case '(': index_++; val = parseExpr(); eatSpaces(); if (getCharacter() != ')') { if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: `)' expected at end of expression"); } index_++; break; case '~': index_++; val = ~parseValue(); break; case '+': index_++; val = parseValue(); break; case '-': index_++; val = parseValue() * static_cast<T>(-1); break; default : if (!isEnd()) unexpected(); throw calculator::error(expr_, "Syntax error: value expected at end of expression"); } return val; } /// Parse all operations of the current parenthesis /// level and the levels above, when done /// return the result (value). /// T parseExpr() { stack_.push(OperatorValue(Operator(OPERATOR_NULL, 0, 'L'), 0)); // first parse value on the left T value = parseValue(); while (!stack_.empty()) { // parse an operator (+, -, *, ...) Operator op(parseOp()); while (op.precedence < stack_.top().getPrecedence() || ( op.precedence == stack_.top().getPrecedence() && op.associativity == 'L')) { // end reached if (stack_.top().isNull()) { stack_.pop(); return value; } // do the calculation ("reduce"), producing a new value value = calculate(stack_.top().value, value, stack_.top().op); stack_.pop(); } // store on stack_ and continue parsing ("shift") stack_.push(OperatorValue(op, value)); // parse value on the right value = parseValue(); } return 0; } }; template <typename T> inline T eval(const std::string& expression) { ExpressionParser<T> parser; return parser.eval(expression); } template <typename T> inline T eval(char c) { ExpressionParser<T> parser; return parser.eval(c); } inline int eval(const std::string& expression) { return eval<int>(expression); } inline int eval(char c) { return eval<int>(c); } } // namespace calculator #endif <|endoftext|>
<commit_before><commit_msg>coverity#1302687 Dereference null return value<commit_after><|endoftext|>
<commit_before>/* * cam_altair.cpp * PHD Guiding * * Created by Robin Glover. * Copyright (c) 2014 Robin Glover. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 "phd.h" #ifdef ALTAIR #include "cam_altair.h" #ifdef __WINDOWS__ #ifdef OS_WINDOWS // troubleshooting with the libusb definitions # undef OS_WINDOWS #endif # include <Shlwapi.h> # include <DelayImp.h> #endif class AltairCameraDlg : public wxDialog { public: wxCheckBox* m_reduceRes; AltairCameraDlg(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& title = _("Altair Camera Settings"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(268, 133), long style = wxDEFAULT_DIALOG_STYLE); ~AltairCameraDlg() { } }; AltairCameraDlg::AltairCameraDlg(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { SetSizeHints(wxDefaultSize, wxDefaultSize); wxBoxSizer *bSizer12 = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer *sbSizer3 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Settings")), wxHORIZONTAL); m_reduceRes = new wxCheckBox(this, wxID_ANY, wxT("Reduced Resolution (by ~20%)"), wxDefaultPosition, wxDefaultSize, 0); sbSizer3->Add(m_reduceRes, 0, wxALL, 5); bSizer12->Add(sbSizer3, 1, wxEXPAND, 5); wxStdDialogButtonSizer* sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); bSizer12->Add(sdbSizer2, 0, wxALL | wxEXPAND, 5); SetSizer(bSizer12); Layout(); Centre(wxBOTH); } Camera_Altair::Camera_Altair() : m_buffer(0), m_capturing(false) { PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; Name = _T("Altair Camera"); Connected = false; m_hasGuideOutput = true; HasSubframes = false; HasGainControl = true; // workaround: ok to set to false later, but brain dialog will frash if we start false then change to true later when the camera is connected } Camera_Altair::~Camera_Altair() { delete[] m_buffer; } wxByte Camera_Altair::BitsPerPixel() { return 8; } inline static int cam_gain(int minval, int maxval, int pct) { return minval + pct * (maxval - minval) / 100; } inline static int gain_pct(int minval, int maxval, int val) { return (val - minval) * 100 / (maxval - minval); } bool Camera_Altair::EnumCameras(wxArrayString& names, wxArrayString& ids) { AltaircamInstV2 ai[ALTAIRCAM_MAX]; unsigned numCameras = Altaircam_EnumV2(ai); for (int i = 0; i < numCameras; i++) { names.Add(ai[i].displayname); ids.Add(ai[i].id); } return false; } bool Camera_Altair::Connect(const wxString& camIdArg) { AltaircamInstV2 ai[ALTAIRCAM_MAX]; unsigned numCameras = Altaircam_EnumV2(ai); if (numCameras == 0) { return CamConnectFailed(_("No Altair cameras detected")); } wxString camId(camIdArg); if (camId == DEFAULT_CAMERA_ID || numCameras == 1) camId = ai[0].id; bool found = false; for (int i=0; i<numCameras; i++) { if (camId == ai[i].id) { found = true; break; } } if (!found) { return CamConnectFailed(_("Specified Altair Camera not found.")); } m_handle = Altaircam_Open(camId); if (m_handle == nullptr) { return CamConnectFailed(_("Failed to open Altair Camera.")); } Connected = true; bool hasROI = false; bool hasSkip = false; for (int i = 0; i < numCameras; i++) { if (ai[i].id == camId) { Name = ai[i].displayname; hasROI = (ai[i].model->flag & ALTAIRCAM_FLAG_ROI_HARDWARE) != 0; hasSkip = (ai[i].model->flag & ALTAIRCAM_FLAG_BINSKIP_SUPPORTED) != 0; break; } } int width, height; if (FAILED(Altaircam_get_Resolution(m_handle, 0, &width, &height))) { Disconnect(); return CamConnectFailed(_("Failed to get camera resolution for Altair Camera.")); } delete[] m_buffer; m_buffer = new unsigned char[width * height]; // new SDK has issues with some ROI functions needing full resolution buffer size ReduceResolution = pConfig->Profile.GetBoolean("/camera/Altair/ReduceResolution", false); if (hasROI && ReduceResolution) { width *= 0.8; height *= 0.8; } FullSize.x = width; FullSize.y = height; float xSize, ySize; m_devicePixelSize = 3.75; // for all cameras so far.... if (Altaircam_get_PixelSize(m_handle, 0, &xSize, &ySize) == 0) { m_devicePixelSize = xSize; } wxYield(); HasGainControl = false; unsigned short min, max, def; if (SUCCEEDED(Altaircam_get_ExpoAGainRange(m_handle, &min, &max, &def))) { m_minGain = min; m_maxGain = max; HasGainControl = max > min; } Altaircam_put_AutoExpoEnable(m_handle, FALSE); Altaircam_put_Speed(m_handle, 0); Altaircam_put_RealTime(m_handle, TRUE); wxYield(); m_frame = wxRect(FullSize); Debug.Write(wxString::Format("Altair: frame (%d,%d)+(%d,%d)\n", m_frame.x, m_frame.y, m_frame.width, m_frame.height)); if (hasROI && ReduceResolution) { Altaircam_put_Roi(m_handle, 0, 0, width, height); } if (hasSkip) Altaircam_put_Mode(m_handle, 0); Altaircam_put_Option(m_handle, ALTAIRCAM_OPTION_RAW, 0); Altaircam_put_Option(m_handle, ALTAIRCAM_OPTION_AGAIN, 0); return false; } bool Camera_Altair::StopCapture(void) { if (m_capturing) { Debug.AddLine("Altair: stopcapture"); Altaircam_Stop(m_handle); m_capturing = false; } return true; } void Camera_Altair::FrameReady(void) { m_frameReady = true; } bool Camera_Altair::GetDevicePixelSize(double *devPixelSize) { if (!Connected) return true; *devPixelSize = m_devicePixelSize; return false; // Pixel size is known in any case } void Camera_Altair::ShowPropertyDialog() { AltairCameraDlg dlg(wxGetApp().GetTopWindow()); bool value = pConfig->Profile.GetBoolean("/camera/Altair/ReduceResolution", false); dlg.m_reduceRes->SetValue(value); if (dlg.ShowModal() == wxID_OK) { ReduceResolution = dlg.m_reduceRes->GetValue(); pConfig->Profile.SetBoolean("/camera/Altair/ReduceResolution", ReduceResolution); } } bool Camera_Altair::Disconnect() { StopCapture(); Altaircam_Close(m_handle); Connected = false; delete[] m_buffer; m_buffer = 0; return false; } inline static int round_down(int v, int m) { return v & ~(m - 1); } inline static int round_up(int v, int m) { return round_down(v + m - 1, m); } void __stdcall CameraCallback(unsigned int event, void *pCallbackCtx) { if (event == ALTAIRCAM_EVENT_IMAGE) { Camera_Altair *pCam = (Camera_Altair *) pCallbackCtx; pCam->FrameReady(); } } //static void flush_buffered_image(int cameraId, usImage& img) //{ // enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers // // // clear buffered frames if any // // for (unsigned int num_cleared = 0; num_cleared < NUM_IMAGE_BUFFERS; num_cleared++) // { // ASI_ERROR_CODE status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned short), 0); // if (status != ASI_SUCCESS) // break; // no more buffered frames // // Debug.Write(wxString::Format("Altair: getimagedata clearbuf %u ret %d\n", num_cleared + 1, status)); // } //} bool Camera_Altair::Capture(int duration, usImage& img, int options, const wxRect& subframe) { if (img.Init(FullSize)) { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } wxRect frame; frame = wxRect(FullSize); long exposureUS = duration * 1000; unsigned int cur_exp; if (Altaircam_get_ExpoTime(m_handle, &cur_exp) == 0 && cur_exp != exposureUS) { Debug.Write(wxString::Format("Altair: set CONTROL_EXPOSURE %d\n", exposureUS)); Altaircam_put_ExpoTime(m_handle, exposureUS); } long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain); unsigned short cur_gain; if (Altaircam_get_ExpoAGain(m_handle, &cur_gain) == 0 && new_gain != cur_gain) { Debug.Write(wxString::Format("Altair: set CONTROL_GAIN %d%% %d\n", GuideCameraGain, new_gain)); Altaircam_put_ExpoAGain(m_handle, new_gain); } // the camera and/or driver will buffer frames and return the oldest frame, // which could be quite stale. read out all buffered frames so the frame we // get is current //flush_buffered_image(m_handle, img); unsigned int width, height; while (SUCCEEDED(Altaircam_PullImage(m_handle, m_buffer, 8, &width, &height))) { } if (!m_capturing) { Debug.AddLine("Altair: startcapture"); HRESULT result = Altaircam_StartPullModeWithCallback(m_handle, CameraCallback, this); if (result != 0) { Debug.Write(wxString::Format("Altaircam_StartPullModeWithCallback failed with code %d\n", result)); return true; } m_capturing = true; m_frameReady = false; } int frameSize = frame.GetWidth() * frame.GetHeight(); int poll = wxMin(duration, 100); CameraWatchdog watchdog(duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) // do not wait here, as we will miss a frame most likely, leading to poor flow of frames. /* if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && (WorkerThread::TerminateRequested() || StopCapture())) { return true; }*/ while (true) { if (m_frameReady) { m_frameReady = false; if (SUCCEEDED(Altaircam_PullImage(m_handle, m_buffer, 8, &width, &height))) break; } WorkerThread::MilliSleep(poll, WorkerThread::INT_ANY); if (WorkerThread::InterruptRequested()) { StopCapture(); return true; } if (watchdog.Expired()) { Debug.AddLine("Altair: getimagedata failed"); StopCapture(); DisconnectWithAlert(CAPT_FAIL_TIMEOUT); return true; } } for (unsigned int i = 0; i < img.NPixels; i++) img.ImageData[i] = m_buffer[i]; if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); return false; } inline static int GetAltairDirection(int direction) { switch (direction) { default: case NORTH: return 0; case EAST: return 2; case WEST: return 3; case SOUTH: return 1; } } bool Camera_Altair::ST4PulseGuideScope(int direction, int duration) { int d = GetAltairDirection(direction); Altaircam_ST4PlusGuide(m_handle, d, duration); return false; } void Camera_Altair::ClearGuidePort() { Altaircam_ST4PlusGuide(m_handle, 0,0); } #endif // Altaircam_ASI <commit_msg>Altair cameras: prevent connecting to the wrong camera when reconnecting after a disconnect<commit_after>/* * cam_altair.cpp * PHD Guiding * * Created by Robin Glover. * Copyright (c) 2014 Robin Glover. * All rights reserved. * * This source code is distributed under the following "BSD" license * 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 Craig Stark, Stark Labs 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 "phd.h" #ifdef ALTAIR #include "cam_altair.h" #ifdef __WINDOWS__ #ifdef OS_WINDOWS // troubleshooting with the libusb definitions # undef OS_WINDOWS #endif # include <Shlwapi.h> # include <DelayImp.h> #endif class AltairCameraDlg : public wxDialog { public: wxCheckBox* m_reduceRes; AltairCameraDlg(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& title = _("Altair Camera Settings"), const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxSize(268, 133), long style = wxDEFAULT_DIALOG_STYLE); ~AltairCameraDlg() { } }; AltairCameraDlg::AltairCameraDlg(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style) : wxDialog(parent, id, title, pos, size, style) { SetSizeHints(wxDefaultSize, wxDefaultSize); wxBoxSizer *bSizer12 = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer *sbSizer3 = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, _("Settings")), wxHORIZONTAL); m_reduceRes = new wxCheckBox(this, wxID_ANY, wxT("Reduced Resolution (by ~20%)"), wxDefaultPosition, wxDefaultSize, 0); sbSizer3->Add(m_reduceRes, 0, wxALL, 5); bSizer12->Add(sbSizer3, 1, wxEXPAND, 5); wxStdDialogButtonSizer* sdbSizer2 = new wxStdDialogButtonSizer(); wxButton *sdbSizer2OK = new wxButton(this, wxID_OK); wxButton* sdbSizer2Cancel = new wxButton(this, wxID_CANCEL); sdbSizer2->AddButton(sdbSizer2OK); sdbSizer2->AddButton(sdbSizer2Cancel); sdbSizer2->Realize(); bSizer12->Add(sdbSizer2, 0, wxALL | wxEXPAND, 5); SetSizer(bSizer12); Layout(); Centre(wxBOTH); } Camera_Altair::Camera_Altair() : m_buffer(0), m_capturing(false) { PropertyDialogType = PROPDLG_WHEN_DISCONNECTED; Name = _T("Altair Camera"); Connected = false; m_hasGuideOutput = true; HasSubframes = false; HasGainControl = true; // workaround: ok to set to false later, but brain dialog will frash if we start false then change to true later when the camera is connected } Camera_Altair::~Camera_Altair() { delete[] m_buffer; } wxByte Camera_Altair::BitsPerPixel() { return 8; } inline static int cam_gain(int minval, int maxval, int pct) { return minval + pct * (maxval - minval) / 100; } inline static int gain_pct(int minval, int maxval, int val) { return (val - minval) * 100 / (maxval - minval); } bool Camera_Altair::EnumCameras(wxArrayString& names, wxArrayString& ids) { AltaircamInstV2 ai[ALTAIRCAM_MAX]; unsigned numCameras = Altaircam_EnumV2(ai); for (int i = 0; i < numCameras; i++) { names.Add(ai[i].displayname); ids.Add(ai[i].id); } return false; } bool Camera_Altair::Connect(const wxString& camIdArg) { AltaircamInstV2 ai[ALTAIRCAM_MAX]; unsigned numCameras = Altaircam_EnumV2(ai); if (numCameras == 0) { return CamConnectFailed(_("No Altair cameras detected")); } wxString camId(camIdArg); if (camId == DEFAULT_CAMERA_ID) camId = ai[0].id; bool found = false; for (int i=0; i<numCameras; i++) { if (camId == ai[i].id) { found = true; break; } } if (!found) { return CamConnectFailed(_("Specified Altair Camera not found.")); } m_handle = Altaircam_Open(camId); if (m_handle == nullptr) { return CamConnectFailed(_("Failed to open Altair Camera.")); } Connected = true; bool hasROI = false; bool hasSkip = false; for (int i = 0; i < numCameras; i++) { if (ai[i].id == camId) { Name = ai[i].displayname; hasROI = (ai[i].model->flag & ALTAIRCAM_FLAG_ROI_HARDWARE) != 0; hasSkip = (ai[i].model->flag & ALTAIRCAM_FLAG_BINSKIP_SUPPORTED) != 0; break; } } int width, height; if (FAILED(Altaircam_get_Resolution(m_handle, 0, &width, &height))) { Disconnect(); return CamConnectFailed(_("Failed to get camera resolution for Altair Camera.")); } delete[] m_buffer; m_buffer = new unsigned char[width * height]; // new SDK has issues with some ROI functions needing full resolution buffer size ReduceResolution = pConfig->Profile.GetBoolean("/camera/Altair/ReduceResolution", false); if (hasROI && ReduceResolution) { width *= 0.8; height *= 0.8; } FullSize.x = width; FullSize.y = height; float xSize, ySize; m_devicePixelSize = 3.75; // for all cameras so far.... if (Altaircam_get_PixelSize(m_handle, 0, &xSize, &ySize) == 0) { m_devicePixelSize = xSize; } wxYield(); HasGainControl = false; unsigned short min, max, def; if (SUCCEEDED(Altaircam_get_ExpoAGainRange(m_handle, &min, &max, &def))) { m_minGain = min; m_maxGain = max; HasGainControl = max > min; } Altaircam_put_AutoExpoEnable(m_handle, FALSE); Altaircam_put_Speed(m_handle, 0); Altaircam_put_RealTime(m_handle, TRUE); wxYield(); m_frame = wxRect(FullSize); Debug.Write(wxString::Format("Altair: frame (%d,%d)+(%d,%d)\n", m_frame.x, m_frame.y, m_frame.width, m_frame.height)); if (hasROI && ReduceResolution) { Altaircam_put_Roi(m_handle, 0, 0, width, height); } if (hasSkip) Altaircam_put_Mode(m_handle, 0); Altaircam_put_Option(m_handle, ALTAIRCAM_OPTION_RAW, 0); Altaircam_put_Option(m_handle, ALTAIRCAM_OPTION_AGAIN, 0); return false; } bool Camera_Altair::StopCapture(void) { if (m_capturing) { Debug.AddLine("Altair: stopcapture"); Altaircam_Stop(m_handle); m_capturing = false; } return true; } void Camera_Altair::FrameReady(void) { m_frameReady = true; } bool Camera_Altair::GetDevicePixelSize(double *devPixelSize) { if (!Connected) return true; *devPixelSize = m_devicePixelSize; return false; // Pixel size is known in any case } void Camera_Altair::ShowPropertyDialog() { AltairCameraDlg dlg(wxGetApp().GetTopWindow()); bool value = pConfig->Profile.GetBoolean("/camera/Altair/ReduceResolution", false); dlg.m_reduceRes->SetValue(value); if (dlg.ShowModal() == wxID_OK) { ReduceResolution = dlg.m_reduceRes->GetValue(); pConfig->Profile.SetBoolean("/camera/Altair/ReduceResolution", ReduceResolution); } } bool Camera_Altair::Disconnect() { StopCapture(); Altaircam_Close(m_handle); Connected = false; delete[] m_buffer; m_buffer = 0; return false; } inline static int round_down(int v, int m) { return v & ~(m - 1); } inline static int round_up(int v, int m) { return round_down(v + m - 1, m); } void __stdcall CameraCallback(unsigned int event, void *pCallbackCtx) { if (event == ALTAIRCAM_EVENT_IMAGE) { Camera_Altair *pCam = (Camera_Altair *) pCallbackCtx; pCam->FrameReady(); } } //static void flush_buffered_image(int cameraId, usImage& img) //{ // enum { NUM_IMAGE_BUFFERS = 2 }; // camera has 2 internal frame buffers // // // clear buffered frames if any // // for (unsigned int num_cleared = 0; num_cleared < NUM_IMAGE_BUFFERS; num_cleared++) // { // ASI_ERROR_CODE status = ASIGetVideoData(cameraId, (unsigned char *) img.ImageData, img.NPixels * sizeof(unsigned short), 0); // if (status != ASI_SUCCESS) // break; // no more buffered frames // // Debug.Write(wxString::Format("Altair: getimagedata clearbuf %u ret %d\n", num_cleared + 1, status)); // } //} bool Camera_Altair::Capture(int duration, usImage& img, int options, const wxRect& subframe) { if (img.Init(FullSize)) { DisconnectWithAlert(CAPT_FAIL_MEMORY); return true; } wxRect frame; frame = wxRect(FullSize); long exposureUS = duration * 1000; unsigned int cur_exp; if (Altaircam_get_ExpoTime(m_handle, &cur_exp) == 0 && cur_exp != exposureUS) { Debug.Write(wxString::Format("Altair: set CONTROL_EXPOSURE %d\n", exposureUS)); Altaircam_put_ExpoTime(m_handle, exposureUS); } long new_gain = cam_gain(m_minGain, m_maxGain, GuideCameraGain); unsigned short cur_gain; if (Altaircam_get_ExpoAGain(m_handle, &cur_gain) == 0 && new_gain != cur_gain) { Debug.Write(wxString::Format("Altair: set CONTROL_GAIN %d%% %d\n", GuideCameraGain, new_gain)); Altaircam_put_ExpoAGain(m_handle, new_gain); } // the camera and/or driver will buffer frames and return the oldest frame, // which could be quite stale. read out all buffered frames so the frame we // get is current //flush_buffered_image(m_handle, img); unsigned int width, height; while (SUCCEEDED(Altaircam_PullImage(m_handle, m_buffer, 8, &width, &height))) { } if (!m_capturing) { Debug.AddLine("Altair: startcapture"); HRESULT result = Altaircam_StartPullModeWithCallback(m_handle, CameraCallback, this); if (result != 0) { Debug.Write(wxString::Format("Altaircam_StartPullModeWithCallback failed with code %d\n", result)); return true; } m_capturing = true; m_frameReady = false; } int frameSize = frame.GetWidth() * frame.GetHeight(); int poll = wxMin(duration, 100); CameraWatchdog watchdog(duration, duration + GetTimeoutMs() + 10000); // total timeout is 2 * duration + 15s (typically) // do not wait here, as we will miss a frame most likely, leading to poor flow of frames. /* if (WorkerThread::MilliSleep(duration, WorkerThread::INT_ANY) && (WorkerThread::TerminateRequested() || StopCapture())) { return true; }*/ while (true) { if (m_frameReady) { m_frameReady = false; if (SUCCEEDED(Altaircam_PullImage(m_handle, m_buffer, 8, &width, &height))) break; } WorkerThread::MilliSleep(poll, WorkerThread::INT_ANY); if (WorkerThread::InterruptRequested()) { StopCapture(); return true; } if (watchdog.Expired()) { Debug.AddLine("Altair: getimagedata failed"); StopCapture(); DisconnectWithAlert(CAPT_FAIL_TIMEOUT); return true; } } for (unsigned int i = 0; i < img.NPixels; i++) img.ImageData[i] = m_buffer[i]; if (options & CAPTURE_SUBTRACT_DARK) SubtractDark(img); return false; } inline static int GetAltairDirection(int direction) { switch (direction) { default: case NORTH: return 0; case EAST: return 2; case WEST: return 3; case SOUTH: return 1; } } bool Camera_Altair::ST4PulseGuideScope(int direction, int duration) { int d = GetAltairDirection(direction); Altaircam_ST4PlusGuide(m_handle, d, duration); return false; } void Camera_Altair::ClearGuidePort() { Altaircam_ST4PlusGuide(m_handle, 0,0); } #endif // Altaircam_ASI <|endoftext|>
<commit_before>#include "sprite.h" #include <fstream> #include <iostream> #include <sstream> #include <vector> namespace entities { Sprite::Sprite(const std::string& path, SpriteType type) : type_(type) { load(path); direction_ = util::Direction::RIGHT; visualDirection_ = util::Direction::RIGHT; } bool Sprite::load(const std::string& path) { std::ifstream spritefile(path); if (!spritefile.is_open()) { logger::error("Unable to load spritefile: " + path); return false; } std::stringstream fileData; fileData << spritefile.rdbuf(); spritefile.close(); auto spriteData = nlohmann::json::parse(fileData.str()); dimensions_.width = spriteData["width"].get<float>(); dimensions_.height = spriteData["height"].get<float>(); tile_ = spriteData["tile"].get<int>(); updateMs_ = sf::milliseconds(spriteData["update_ms"].get<int>()); multiFile_ = spriteData["multi_file"].get<bool>(); scale_ = spriteData["scale"].get<float>(); sprite_.setScale(scale_, scale_); frameSpacing_ = spriteData["frame_spacing"].get<int>(); columns_ = spriteData["columns"].get<int>(); std::vector<std::string> texturePaths; if (multiFile_) { texturePaths = spriteData["frames"].get<std::vector<std::string>>(); totalFrames_ = (int)texturePaths.size(); } else { texturePaths.push_back(spriteData["texture"].get<std::string>()); totalFrames_ = spriteData["total_frames"].get<int>(); } auto basePath = path.substr(0, path.find_last_of("/")); for (auto& path : texturePaths) { std::string fullPath = basePath + "/" + path; sf::Texture texture; texture.loadFromFile(fullPath); textures_.push_back(texture); } return true; } void Sprite::updateVelocity() { velocityY_ += GRAVITY; // Necessary to prevent jumping after initiating a fall jumping_ = true; } void Sprite::setVelocity(float velocity) { velocityY_ = velocity; } void Sprite::startJump(float magnitudePercent) { if (!jumping_ && canJump_) { velocityY_ = STARTING_JUMP_VELOCITY * magnitudePercent; jumping_ = true; } } void Sprite::zeroVelocity(bool stopJump) { velocityY_ = 0; jumping_ = !stopJump; } void Sprite::setFlag(const std::string& key, const bool flag) { flags_[key] = flag; } bool Sprite::getFlag(const std::string& key) { const auto iter = flags_.find(key); if (iter == flags_.end()) { return false; } return iter->second; } void Sprite::setValue(const std::string& key, const int value) { values_[key] = value; } int Sprite::getValue(const std::string& key) { const auto iter = values_.find(key); if (iter == values_.end()) { return 0; } return iter->second; } void Sprite::update(const sf::Time& time) { if (!active()) { return; } time_ += time; if (time_ >= updateMs_) { int limit = textures_.size(); if (limit == 1 && totalFrames_ == 1) { return; } int frameIncrease; if (multiFile_) { limit = totalFrames_; frameIncrease = 1; } else { limit = totalFrames_ * frameSpacing_; frameIncrease = frameSpacing_; } frame_ = (frame_ + frameIncrease) % limit; if (id > 2) { logger::info("changed frame to frame " + std::to_string(frame_)); } time_ = sf::seconds(0); } } void Sprite::render(sf::RenderTarget& window, sf::Vector2f cameraPos) { if (!active()) { return; } int tile = tile_; if (!multiFile_) { tile += frame_; } sf::IntRect source((tile % columns_) * (int)dimensions_.width, (tile / columns_) * (int)dimensions_.height, (int)dimensions_.width, (int)dimensions_.height); sf::Texture tex; if (multiFile_) { tex = textures_[frame_]; } else { tex = textures_[0]; } sprite_.setTexture(tex); if (visualDirection_ == util::Direction::RIGHT) { source.left += (int)dimensions_.width; source.width = (int)-dimensions_.width; } sprite_.setTextureRect(source); sprite_.setPosition(dimensions_.left - cameraPos.x, dimensions_.top - cameraPos.y); window.draw(sprite_); } } // namespace entities <commit_msg>Remove debug print<commit_after>#include "sprite.h" #include <fstream> #include <iostream> #include <sstream> #include <vector> namespace entities { Sprite::Sprite(const std::string& path, SpriteType type) : type_(type) { load(path); direction_ = util::Direction::RIGHT; visualDirection_ = util::Direction::RIGHT; } bool Sprite::load(const std::string& path) { std::ifstream spritefile(path); if (!spritefile.is_open()) { logger::error("Unable to load spritefile: " + path); return false; } std::stringstream fileData; fileData << spritefile.rdbuf(); spritefile.close(); auto spriteData = nlohmann::json::parse(fileData.str()); dimensions_.width = spriteData["width"].get<float>(); dimensions_.height = spriteData["height"].get<float>(); tile_ = spriteData["tile"].get<int>(); updateMs_ = sf::milliseconds(spriteData["update_ms"].get<int>()); multiFile_ = spriteData["multi_file"].get<bool>(); scale_ = spriteData["scale"].get<float>(); sprite_.setScale(scale_, scale_); frameSpacing_ = spriteData["frame_spacing"].get<int>(); columns_ = spriteData["columns"].get<int>(); std::vector<std::string> texturePaths; if (multiFile_) { texturePaths = spriteData["frames"].get<std::vector<std::string>>(); totalFrames_ = (int)texturePaths.size(); } else { texturePaths.push_back(spriteData["texture"].get<std::string>()); totalFrames_ = spriteData["total_frames"].get<int>(); } auto basePath = path.substr(0, path.find_last_of("/")); for (auto& path : texturePaths) { std::string fullPath = basePath + "/" + path; sf::Texture texture; texture.loadFromFile(fullPath); textures_.push_back(texture); } return true; } void Sprite::updateVelocity() { velocityY_ += GRAVITY; // Necessary to prevent jumping after initiating a fall jumping_ = true; } void Sprite::setVelocity(float velocity) { velocityY_ = velocity; } void Sprite::startJump(float magnitudePercent) { if (!jumping_ && canJump_) { velocityY_ = STARTING_JUMP_VELOCITY * magnitudePercent; jumping_ = true; } } void Sprite::zeroVelocity(bool stopJump) { velocityY_ = 0; jumping_ = !stopJump; } void Sprite::setFlag(const std::string& key, const bool flag) { flags_[key] = flag; } bool Sprite::getFlag(const std::string& key) { const auto iter = flags_.find(key); if (iter == flags_.end()) { return false; } return iter->second; } void Sprite::setValue(const std::string& key, const int value) { values_[key] = value; } int Sprite::getValue(const std::string& key) { const auto iter = values_.find(key); if (iter == values_.end()) { return 0; } return iter->second; } void Sprite::update(const sf::Time& time) { if (!active()) { return; } time_ += time; if (time_ >= updateMs_) { int limit = textures_.size(); if (limit == 1 && totalFrames_ == 1) { return; } int frameIncrease; if (multiFile_) { limit = totalFrames_; frameIncrease = 1; } else { limit = totalFrames_ * frameSpacing_; frameIncrease = frameSpacing_; } frame_ = (frame_ + frameIncrease) % limit; time_ = sf::seconds(0); } } void Sprite::render(sf::RenderTarget& window, sf::Vector2f cameraPos) { if (!active()) { return; } int tile = tile_; if (!multiFile_) { tile += frame_; } sf::IntRect source((tile % columns_) * (int)dimensions_.width, (tile / columns_) * (int)dimensions_.height, (int)dimensions_.width, (int)dimensions_.height); sf::Texture tex; if (multiFile_) { tex = textures_[frame_]; } else { tex = textures_[0]; } sprite_.setTexture(tex); if (visualDirection_ == util::Direction::RIGHT) { source.left += (int)dimensions_.width; source.width = (int)-dimensions_.width; } sprite_.setTextureRect(source); sprite_.setPosition(dimensions_.left - cameraPos.x, dimensions_.top - cameraPos.y); window.draw(sprite_); } } // namespace entities <|endoftext|>
<commit_before><commit_msg>fdo#43249: WW8: fix double border import:<commit_after><|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ /* * ActionPrompt.cpp * * Created on: Sep 27, 2012 * Author: Dimitar Asenov */ #include "ActionPrompt.h" #include "../vis/TextAndDescription.h" #include "Action.h" #include "VisualizationBase/src/Scene.h" #include "VisualizationBase/src/cursor/Cursor.h" //#include "VisualizationBase/src/cursor/TextCursor.h" //#include "VisualizationBase/src/items/SceneHandlerItem.h" using namespace Visualization; namespace Interaction { ITEM_COMMON_DEFINITIONS(ActionPrompt, "item") ActionPrompt::ActionPrompt(Item* actionReceiver, bool autoExecuteAction, const StyleType* style) : Item(nullptr, style), autoExecuteAction_(autoExecuteAction), originalActionReceiver_(actionReceiver), currentActionReceiver_(actionReceiver), layout_(new SequentialLayout(this, &style->layout())), actionsContainer_(new SequentialLayout(layout_, &style->actionsContainer())), actionText_( new Text(layout_, &style->shortcutText())) { setFlag(QGraphicsItem::ItemIsMovable); setFlag(ItemIgnoresTransformations); setZValue(LAYER_COMMAND); setItemCategory(Scene::MenuItemCategory); layout_->append(actionText_); layout_->append(actionsContainer_); computeCurrentActionReceiver(); originalActionReceiver_->scene()->addTopLevelItem(this); actionText_->setText(""); setPromptPosition(); acquireCursor(); } ActionPrompt::~ActionPrompt() { if(scene()) scene()->removeTopLevelItem(this); // These itemi are completely out of our control, we just know about them. currentActionReceiver_ = nullptr; originalActionReceiver_ = nullptr; SAFE_DELETE_ITEM(layout_); // These are deleted by layout's destructor actionText_ = nullptr; actionsContainer_ = nullptr; } void ActionPrompt::showPrompt() { parentActionsLevel_ = 0; computeCurrentActionReceiver(); actionText_->setText(""); setPromptPosition(); show(); acquireCursor(); setUpdateNeeded(StandardUpdate); } void ActionPrompt::hidePrompt() { hide(); originalActionReceiver_->moveCursor(Visualization::Item::MoveOnPosition, receiverCursorPosition_); } void ActionPrompt::determineChildren() { actionsContainer_->clear(); for(auto a : actions()) { if (a->shortcut().startsWith(actionText_->text())) actionsContainer_->append(new TextAndDescription(a->shortcut(), a->name(), &style()->actionStyle())); } } void ActionPrompt::updateGeometry(int availableWidth, int availableHeight) { Item::updateGeometry(layout_, availableWidth, availableHeight); } void ActionPrompt::acquireCursor() { // Save the current cursor receiverCursorPosition_ = QPoint(0,0); if (originalActionReceiver_->scene()->mainCursor()->owner() == originalActionReceiver_) receiverCursorPosition_ = originalActionReceiver_->scene()->mainCursor()->position(); actionText_->moveCursor(); } void ActionPrompt::setPromptPosition() { for( auto v : originalActionReceiver_->scene()->views()) { if (v->isActiveWindow()) { setPos(v->mapToScene(210, v->viewport()->height() - 40)); // Put it after the mini map on the bottom break; } } } void ActionPrompt::computeCurrentActionReceiver() { int level = parentActionsLevel_; if (level >= 0) { // Find a parent that has a node with actions auto item = originalActionReceiver_; QList<Model::Node*> nodesSeen; while (item) { // In some cases it happens that a single node is visualized multiple times in the hierarchy (e.g. RootItem // visualizes the same node as its child). We count only the first occurence. if (item->node() != nullptr && !nodesSeen.contains(item->node())) { nodesSeen.prepend(item->node()); auto actionList = Action::actions(item->node()); if (!actionList.isEmpty()) { if (level == 0) { currentActionReceiver_ = item; return; } else --level; } } item = item->parent(); } } else { // Get a linear order of children auto children = originalActionReceiver_->childItems(); int i = 0; while(i < children.size()) { // While exploring the children in a BFS manner, look out for reaching the desired child node auto child = static_cast<Visualization::Item*>(children.at(i)); if (child->node()) { auto actionList = Action::actions(child->node()); if (!actionList.isEmpty()) { ++level; if (level == 0) { currentActionReceiver_ = child; return; } } } children.append(child->childItems()); ++i; } } currentActionReceiver_ = nullptr; } QList<Action*> ActionPrompt::actions() { return Action::actions(currentActionReceiver_->node()); } void ActionPrompt::upParentActionsLevel() { ++parentActionsLevel_; computeCurrentActionReceiver(); // Only allow this if we can actually get to an item that contains a node with actions or if we end up at 0 if (parentActionsLevel_ > 0 && !currentActionReceiver_) { --parentActionsLevel_; computeCurrentActionReceiver(); } else setUpdateNeeded(StandardUpdate); } void ActionPrompt::downParentActionsLevel() { --parentActionsLevel_; computeCurrentActionReceiver(); // Only allow this if we can actually get to an item that contains a node with actions or if we end up at 0 if (parentActionsLevel_ < 0 && !currentActionReceiver_) { ++parentActionsLevel_; computeCurrentActionReceiver(); } else setUpdateNeeded(StandardUpdate); } } /* namespace Interaction */ <commit_msg>Cleanup unused headers<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2012 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ /* * ActionPrompt.cpp * * Created on: Sep 27, 2012 * Author: Dimitar Asenov */ #include "ActionPrompt.h" #include "../vis/TextAndDescription.h" #include "Action.h" #include "VisualizationBase/src/Scene.h" #include "VisualizationBase/src/cursor/Cursor.h" using namespace Visualization; namespace Interaction { ITEM_COMMON_DEFINITIONS(ActionPrompt, "item") ActionPrompt::ActionPrompt(Item* actionReceiver, bool autoExecuteAction, const StyleType* style) : Item(nullptr, style), autoExecuteAction_(autoExecuteAction), originalActionReceiver_(actionReceiver), currentActionReceiver_(actionReceiver), layout_(new SequentialLayout(this, &style->layout())), actionsContainer_(new SequentialLayout(layout_, &style->actionsContainer())), actionText_( new Text(layout_, &style->shortcutText())) { setFlag(QGraphicsItem::ItemIsMovable); setFlag(ItemIgnoresTransformations); setZValue(LAYER_COMMAND); setItemCategory(Scene::MenuItemCategory); layout_->append(actionText_); layout_->append(actionsContainer_); computeCurrentActionReceiver(); originalActionReceiver_->scene()->addTopLevelItem(this); actionText_->setText(""); setPromptPosition(); acquireCursor(); } ActionPrompt::~ActionPrompt() { if(scene()) scene()->removeTopLevelItem(this); // These items are completely out of our control, we just know about them. currentActionReceiver_ = nullptr; originalActionReceiver_ = nullptr; SAFE_DELETE_ITEM(layout_); // These are deleted by layout's destructor actionText_ = nullptr; actionsContainer_ = nullptr; } void ActionPrompt::showPrompt() { parentActionsLevel_ = 0; computeCurrentActionReceiver(); actionText_->setText(""); setPromptPosition(); show(); acquireCursor(); setUpdateNeeded(StandardUpdate); } void ActionPrompt::hidePrompt() { hide(); originalActionReceiver_->moveCursor(Visualization::Item::MoveOnPosition, receiverCursorPosition_); } void ActionPrompt::determineChildren() { actionsContainer_->clear(); for(auto a : actions()) { if (a->shortcut().startsWith(actionText_->text())) actionsContainer_->append(new TextAndDescription(a->shortcut(), a->name(), &style()->actionStyle())); } } void ActionPrompt::updateGeometry(int availableWidth, int availableHeight) { Item::updateGeometry(layout_, availableWidth, availableHeight); } void ActionPrompt::acquireCursor() { // Save the current cursor receiverCursorPosition_ = QPoint(0,0); if (originalActionReceiver_->scene()->mainCursor()->owner() == originalActionReceiver_) receiverCursorPosition_ = originalActionReceiver_->scene()->mainCursor()->position(); actionText_->moveCursor(); } void ActionPrompt::setPromptPosition() { for( auto v : originalActionReceiver_->scene()->views()) { if (v->isActiveWindow()) { setPos(v->mapToScene(210, v->viewport()->height() - 40)); // Put it after the mini map on the bottom break; } } } void ActionPrompt::computeCurrentActionReceiver() { int level = parentActionsLevel_; if (level >= 0) { // Find a parent that has a node with actions auto item = originalActionReceiver_; QList<Model::Node*> nodesSeen; while (item) { // In some cases it happens that a single node is visualized multiple times in the hierarchy (e.g. RootItem // visualizes the same node as its child). We count only the first occurence. if (item->node() != nullptr && !nodesSeen.contains(item->node())) { nodesSeen.prepend(item->node()); auto actionList = Action::actions(item->node()); if (!actionList.isEmpty()) { if (level == 0) { currentActionReceiver_ = item; return; } else --level; } } item = item->parent(); } } else { // Get a linear order of children auto children = originalActionReceiver_->childItems(); int i = 0; while(i < children.size()) { // While exploring the children in a BFS manner, look out for reaching the desired child node auto child = static_cast<Visualization::Item*>(children.at(i)); if (child->node()) { auto actionList = Action::actions(child->node()); if (!actionList.isEmpty()) { ++level; if (level == 0) { currentActionReceiver_ = child; return; } } } children.append(child->childItems()); ++i; } } currentActionReceiver_ = nullptr; } QList<Action*> ActionPrompt::actions() { return Action::actions(currentActionReceiver_->node()); } void ActionPrompt::upParentActionsLevel() { ++parentActionsLevel_; computeCurrentActionReceiver(); // Only allow this if we can actually get to an item that contains a node with actions or if we end up at 0 if (parentActionsLevel_ > 0 && !currentActionReceiver_) { --parentActionsLevel_; computeCurrentActionReceiver(); } else setUpdateNeeded(StandardUpdate); } void ActionPrompt::downParentActionsLevel() { --parentActionsLevel_; computeCurrentActionReceiver(); // Only allow this if we can actually get to an item that contains a node with actions or if we end up at 0 if (parentActionsLevel_ < 0 && !currentActionReceiver_) { ++parentActionsLevel_; computeCurrentActionReceiver(); } else setUpdateNeeded(StandardUpdate); } } /* namespace Interaction */ <|endoftext|>