text
stringlengths
54
60.6k
<commit_before>//======================================================================= // Copyright (c) 2013-2017 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "assets.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" using namespace budget; namespace { static data_handler<asset> assets; static data_handler<asset_value> asset_values; void show_assets(){ if (!assets.data.size()) { std::cout << "No assets" << std::endl; return; } std::vector<std::string> columns = {"ID", "Name", "Int. Stocks", "Dom. Stocks", "Bonds", "Cash", "Currency"}; std::vector<std::vector<std::string>> contents; // Display the assets for(auto& asset : assets.data){ contents.push_back({to_string(asset.id), asset.name, to_string(asset.int_stocks), to_string(asset.dom_stocks), to_string(asset.bonds), to_string(asset.cash), to_string(asset.currency)}); } display_table(columns, contents); } void show_asset_values(){ if (!asset_values.data.size()) { std::cout << "No asset values" << std::endl; return; } std::vector<std::string> columns = {"Name", "Int. Stocks", "Dom. Stocks", "Bonds", "Cash", "Total", "Currency"}; std::vector<std::vector<std::string>> contents; budget::money int_stocks; budget::money dom_stocks; budget::money bonds; budget::money cash; budget::money total; for(auto& asset : assets.data){ auto id = asset.id; size_t asset_value_id = 0; bool asset_value_found = false; for (auto& asset_value : asset_values.data) { if (asset_value.asset_id == id) { if(!asset_value_found){ asset_value_found = true; asset_value_id = asset_value.id; } else if(asset_value.set_date > get_asset_value(asset_value_id).set_date){ asset_value_id = asset_value.id; } } } if(asset_value_found){ auto& asset_value = get_asset_value(asset_value_id); auto amount = asset_value.amount; contents.push_back({asset.name, to_string(amount * (asset.int_stocks / 100.0)), to_string(amount * (asset.dom_stocks / 100.0)), to_string(amount * (asset.bonds / 100.0)), to_string(amount * (asset.cash / 100.0)), to_string(amount), asset.currency}); int_stocks += amount * (asset.int_stocks / 100.0); dom_stocks += amount * (asset.dom_stocks / 100.0); bonds += amount * (asset.bonds / 100.0); cash += amount * (asset.cash / 100.0); total += amount; } } contents.push_back({"Total", to_string(int_stocks), to_string(dom_stocks), to_string(bonds), to_string(cash), to_string(total), budget::get_default_currency()}); contents.push_back({"Distribution", to_string_precision(100 * int_stocks.dollars() / (double)total.dollars(), 2), to_string_precision(100 * dom_stocks.dollars() / (double)total.dollars(), 2), to_string_precision(100 * bonds.dollars() / (double)total.dollars(), 2), to_string_precision(100 * cash.dollars() / (double)total.dollars(), 2), to_string(100), ""}); display_table(columns, contents); } } //end of anonymous namespace void budget::assets_module::load(){ load_assets(); } void budget::assets_module::unload(){ save_assets(); } void budget::assets_module::handle(const std::vector<std::string>& args){ if(args.size() == 1){ show_assets(); } else { auto& subcommand = args[1]; if(subcommand == "show"){ show_assets(); } else if(subcommand == "add"){ asset asset; asset.guid = generate_guid(); edit_string(asset.name, "Name", not_empty_checker()); if(asset_exists(asset.name)){ throw budget_exception("An asset with this name already exists"); } asset.int_stocks = 0; asset.dom_stocks = 0; asset.bonds = 0; asset.cash = 0; do { edit_number(asset.int_stocks, "Int. Stocks"); edit_number(asset.dom_stocks, "Dom. Stocks"); edit_number(asset.bonds, "Bonds"); edit_number(asset.cash, "Cash"); if(asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100){ std::cout << "The distribution must account to 100%" << std::endl; } } while (asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100); asset.currency = "CHF"; edit_string(asset.currency, "Currency", not_empty_checker()); auto id = add_data(assets, std::move(asset)); std::cout << "Asset " << id << " has been created" << std::endl; } else if(subcommand == "delete"){ size_t id = 0; if(args.size() >= 3){ enough_args(args, 3); id = to_number<size_t>(args[2]); if (!exists(assets, id)) { throw budget_exception("There are no asset with id " + args[2]); } } else { std::string name; edit_string(name, "Asset", not_empty_checker(), asset_checker()); id = budget::get_asset(name).id; } // TODO Make sure there is no values to this asset remove(assets, id); std::cout << "Asset " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ size_t id = 0; if(args.size() >= 3){ enough_args(args, 3); id = to_number<size_t>(args[2]); if(!exists(assets, id)){ throw budget_exception("There are no asset with id " + args[2]); } } else { std::string name; edit_string(name, "Asset", not_empty_checker(), asset_checker()); id = get_asset(name).id; } auto& asset = get(assets, id); edit_string(asset.name, "Name", not_empty_checker()); //Verify that there are no OTHER asset with this name //in the current set of assets (taking archiving into asset) for(auto& other_asset : all_assets()){ if(other_asset.id != id){ if(other_asset.name == asset.name){ throw budget_exception("There is already an asset with the name " + asset.name); } } } do { edit_number(asset.int_stocks, "Int. Stocks"); edit_number(asset.dom_stocks, "Dom. Stocks"); edit_number(asset.bonds, "Bonds"); edit_number(asset.cash, "Cash"); if(asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100){ std::cout << "The distribution must asset to 100%" << std::endl; } } while (asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100); edit_string(asset.currency, "Currency", not_empty_checker()); std::cout << "Asset " << id << " has been modified" << std::endl; assets.changed = true; } else if(subcommand == "value"){ if(args.size() == 2){ show_asset_values(); } else { auto& subsubcommand = args[2]; if(subsubcommand == "set"){ asset_value asset_value; asset_value.guid = generate_guid(); std::string asset_name; edit_string(asset_name, "Asset", not_empty_checker(), asset_checker()); asset_value.asset_id = get_asset(asset_name).id; edit_money(asset_value.amount, "Amount", not_negative_checker()); asset_value.set_date = budget::local_day(); edit_date(asset_value.set_date, "Date"); auto id = add_data(asset_values, std::move(asset_value)); std::cout << "Asset Value " << id << " has been created" << std::endl; } else if(subsubcommand == "show"){ show_asset_values(); } else if(subsubcommand == "edit"){ } else if(subsubcommand == "delete"){ } } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_assets(){ load_data(assets, "assets.data"); load_data(asset_values, "asset_values.data"); } void budget::save_assets(){ save_data(assets, "assets.data"); save_data(asset_values, "asset_values.data"); } budget::asset& budget::get_asset(size_t id){ return get(assets, id); } budget::asset& budget::get_asset(std::string name){ for(auto& asset : assets.data){ if(asset.name == name){ return asset; } } cpp_unreachable("The asset does not exist"); } budget::asset_value& budget::get_asset_value(size_t id){ return get(asset_values, id); } std::ostream& budget::operator<<(std::ostream& stream, const asset& asset){ return stream << asset.id << ':' << asset.guid << ':' << asset.name << ':' << asset.int_stocks << ':' << asset.dom_stocks << ":" << asset.bonds << ":" << asset.cash << ":" << asset.currency; } void budget::operator>>(const std::vector<std::string>& parts, asset& asset){ asset.id = to_number<size_t>(parts[0]); asset.guid = parts[1]; asset.name = parts[2]; asset.int_stocks = to_number<size_t>(parts[3]); asset.dom_stocks = to_number<size_t>(parts[4]); asset.bonds = to_number<size_t>(parts[5]); asset.cash = to_number<size_t>(parts[6]); asset.currency = parts[7]; } std::ostream& budget::operator<<(std::ostream& stream, const asset_value& asset_value){ return stream << asset_value.id << ':' << asset_value.guid << ':' << asset_value.asset_id << ":" << asset_value.amount << ":" << to_string(asset_value.set_date); } void budget::operator>>(const std::vector<std::string>& parts, asset_value& asset_value){ asset_value.id = to_number<size_t>(parts[0]); asset_value.guid = parts[1]; asset_value.asset_id = to_number<size_t>(parts[2]); asset_value.amount = parse_money(parts[3]); asset_value.set_date = from_string(parts[4]); } bool budget::asset_exists(const std::string& name){ for (auto& asset : assets.data) { if (asset.name == name) { return true; } } return false; } std::vector<asset>& budget::all_assets(){ return assets.data; } std::vector<asset_value>& budget::all_asset_values(){ return asset_values.data; } void budget::set_assets_changed(){ assets.changed = true; } void budget::set_assets_next_id(size_t next_id){ assets.next_id = next_id; } void budget::set_asset_values_next_id(size_t next_id){ asset_values.next_id = next_id; } std::string budget::get_default_currency(){ if(budget::config_contains("default_currency")){ return budget::config_value("default_currency"); } return "CHF"; } <commit_msg>Correctly handle the invalid commands<commit_after>//======================================================================= // Copyright (c) 2013-2017 Baptiste Wicht. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include "assets.hpp" #include "budget_exception.hpp" #include "args.hpp" #include "data.hpp" #include "guid.hpp" #include "config.hpp" #include "utils.hpp" #include "console.hpp" #include "earnings.hpp" #include "expenses.hpp" using namespace budget; namespace { static data_handler<asset> assets; static data_handler<asset_value> asset_values; void show_assets(){ if (!assets.data.size()) { std::cout << "No assets" << std::endl; return; } std::vector<std::string> columns = {"ID", "Name", "Int. Stocks", "Dom. Stocks", "Bonds", "Cash", "Currency"}; std::vector<std::vector<std::string>> contents; // Display the assets for(auto& asset : assets.data){ contents.push_back({to_string(asset.id), asset.name, to_string(asset.int_stocks), to_string(asset.dom_stocks), to_string(asset.bonds), to_string(asset.cash), to_string(asset.currency)}); } display_table(columns, contents); } void show_asset_values(){ if (!asset_values.data.size()) { std::cout << "No asset values" << std::endl; return; } std::vector<std::string> columns = {"Name", "Int. Stocks", "Dom. Stocks", "Bonds", "Cash", "Total", "Currency"}; std::vector<std::vector<std::string>> contents; budget::money int_stocks; budget::money dom_stocks; budget::money bonds; budget::money cash; budget::money total; for(auto& asset : assets.data){ auto id = asset.id; size_t asset_value_id = 0; bool asset_value_found = false; for (auto& asset_value : asset_values.data) { if (asset_value.asset_id == id) { if(!asset_value_found){ asset_value_found = true; asset_value_id = asset_value.id; } else if(asset_value.set_date > get_asset_value(asset_value_id).set_date){ asset_value_id = asset_value.id; } } } if(asset_value_found){ auto& asset_value = get_asset_value(asset_value_id); auto amount = asset_value.amount; contents.push_back({asset.name, to_string(amount * (asset.int_stocks / 100.0)), to_string(amount * (asset.dom_stocks / 100.0)), to_string(amount * (asset.bonds / 100.0)), to_string(amount * (asset.cash / 100.0)), to_string(amount), asset.currency}); int_stocks += amount * (asset.int_stocks / 100.0); dom_stocks += amount * (asset.dom_stocks / 100.0); bonds += amount * (asset.bonds / 100.0); cash += amount * (asset.cash / 100.0); total += amount; } } contents.push_back({"Total", to_string(int_stocks), to_string(dom_stocks), to_string(bonds), to_string(cash), to_string(total), budget::get_default_currency()}); contents.push_back({"Distribution", to_string_precision(100 * int_stocks.dollars() / (double)total.dollars(), 2), to_string_precision(100 * dom_stocks.dollars() / (double)total.dollars(), 2), to_string_precision(100 * bonds.dollars() / (double)total.dollars(), 2), to_string_precision(100 * cash.dollars() / (double)total.dollars(), 2), to_string(100), ""}); display_table(columns, contents); std::cout << std::endl << " Net worth: " << total << get_default_currency() << std::endl; } } //end of anonymous namespace void budget::assets_module::load(){ load_assets(); } void budget::assets_module::unload(){ save_assets(); } void budget::assets_module::handle(const std::vector<std::string>& args){ if(args.size() == 1){ show_assets(); } else { auto& subcommand = args[1]; if(subcommand == "show"){ show_assets(); } else if(subcommand == "add"){ asset asset; asset.guid = generate_guid(); edit_string(asset.name, "Name", not_empty_checker()); if(asset_exists(asset.name)){ throw budget_exception("An asset with this name already exists"); } asset.int_stocks = 0; asset.dom_stocks = 0; asset.bonds = 0; asset.cash = 0; do { edit_number(asset.int_stocks, "Int. Stocks"); edit_number(asset.dom_stocks, "Dom. Stocks"); edit_number(asset.bonds, "Bonds"); edit_number(asset.cash, "Cash"); if(asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100){ std::cout << "The distribution must account to 100%" << std::endl; } } while (asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100); asset.currency = budget::get_default_currency(); edit_string(asset.currency, "Currency", not_empty_checker()); auto id = add_data(assets, std::move(asset)); std::cout << "Asset " << id << " has been created" << std::endl; } else if(subcommand == "delete"){ size_t id = 0; if(args.size() >= 3){ enough_args(args, 3); id = to_number<size_t>(args[2]); if (!exists(assets, id)) { throw budget_exception("There are no asset with id " + args[2]); } } else { std::string name; edit_string(name, "Asset", not_empty_checker(), asset_checker()); id = budget::get_asset(name).id; } // TODO Make sure there is no values to this asset remove(assets, id); std::cout << "Asset " << id << " has been deleted" << std::endl; } else if(subcommand == "edit"){ size_t id = 0; if(args.size() >= 3){ enough_args(args, 3); id = to_number<size_t>(args[2]); if(!exists(assets, id)){ throw budget_exception("There are no asset with id " + args[2]); } } else { std::string name; edit_string(name, "Asset", not_empty_checker(), asset_checker()); id = get_asset(name).id; } auto& asset = get(assets, id); edit_string(asset.name, "Name", not_empty_checker()); //Verify that there are no OTHER asset with this name //in the current set of assets (taking archiving into asset) for(auto& other_asset : all_assets()){ if(other_asset.id != id){ if(other_asset.name == asset.name){ throw budget_exception("There is already an asset with the name " + asset.name); } } } do { edit_number(asset.int_stocks, "Int. Stocks"); edit_number(asset.dom_stocks, "Dom. Stocks"); edit_number(asset.bonds, "Bonds"); edit_number(asset.cash, "Cash"); if(asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100){ std::cout << "The distribution must asset to 100%" << std::endl; } } while (asset.int_stocks + asset.dom_stocks + asset.bonds + asset.cash != 100); edit_string(asset.currency, "Currency", not_empty_checker()); std::cout << "Asset " << id << " has been modified" << std::endl; assets.changed = true; } else if(subcommand == "value"){ if(args.size() == 2){ show_asset_values(); } else { auto& subsubcommand = args[2]; if(subsubcommand == "set"){ asset_value asset_value; asset_value.guid = generate_guid(); std::string asset_name; edit_string(asset_name, "Asset", not_empty_checker(), asset_checker()); asset_value.asset_id = get_asset(asset_name).id; edit_money(asset_value.amount, "Amount", not_negative_checker()); asset_value.set_date = budget::local_day(); edit_date(asset_value.set_date, "Date"); auto id = add_data(asset_values, std::move(asset_value)); std::cout << "Asset Value " << id << " has been created" << std::endl; } else if(subsubcommand == "show"){ show_asset_values(); } else if(subsubcommand == "edit"){ } else if(subsubcommand == "delete"){ } else { throw budget_exception("Invalid subcommand value \"" + subsubcommand + "\""); } } } else { throw budget_exception("Invalid subcommand \"" + subcommand + "\""); } } } void budget::load_assets(){ load_data(assets, "assets.data"); load_data(asset_values, "asset_values.data"); } void budget::save_assets(){ save_data(assets, "assets.data"); save_data(asset_values, "asset_values.data"); } budget::asset& budget::get_asset(size_t id){ return get(assets, id); } budget::asset& budget::get_asset(std::string name){ for(auto& asset : assets.data){ if(asset.name == name){ return asset; } } cpp_unreachable("The asset does not exist"); } budget::asset_value& budget::get_asset_value(size_t id){ return get(asset_values, id); } std::ostream& budget::operator<<(std::ostream& stream, const asset& asset){ return stream << asset.id << ':' << asset.guid << ':' << asset.name << ':' << asset.int_stocks << ':' << asset.dom_stocks << ":" << asset.bonds << ":" << asset.cash << ":" << asset.currency; } void budget::operator>>(const std::vector<std::string>& parts, asset& asset){ asset.id = to_number<size_t>(parts[0]); asset.guid = parts[1]; asset.name = parts[2]; asset.int_stocks = to_number<size_t>(parts[3]); asset.dom_stocks = to_number<size_t>(parts[4]); asset.bonds = to_number<size_t>(parts[5]); asset.cash = to_number<size_t>(parts[6]); asset.currency = parts[7]; } std::ostream& budget::operator<<(std::ostream& stream, const asset_value& asset_value){ return stream << asset_value.id << ':' << asset_value.guid << ':' << asset_value.asset_id << ":" << asset_value.amount << ":" << to_string(asset_value.set_date); } void budget::operator>>(const std::vector<std::string>& parts, asset_value& asset_value){ asset_value.id = to_number<size_t>(parts[0]); asset_value.guid = parts[1]; asset_value.asset_id = to_number<size_t>(parts[2]); asset_value.amount = parse_money(parts[3]); asset_value.set_date = from_string(parts[4]); } bool budget::asset_exists(const std::string& name){ for (auto& asset : assets.data) { if (asset.name == name) { return true; } } return false; } std::vector<asset>& budget::all_assets(){ return assets.data; } std::vector<asset_value>& budget::all_asset_values(){ return asset_values.data; } void budget::set_assets_changed(){ assets.changed = true; } void budget::set_assets_next_id(size_t next_id){ assets.next_id = next_id; } void budget::set_asset_values_next_id(size_t next_id){ asset_values.next_id = next_id; } std::string budget::get_default_currency(){ if(budget::config_contains("default_currency")){ return budget::config_value("default_currency"); } return "CHF"; } <|endoftext|>
<commit_before>/** * @file MessageBuffers.hpp * @ingroup * @author tpan * @brief buffering data for MPI send/receive * @details MessageBuffers provides buffering for MPI Send/Receive messages. * Terminology: Message is an MPI compatible message, serialized from buffer, including the appropriate metadata. * Element is a single piece of data from the application code. * Buffer is a collection of elements. * * * provides functions for storing single and collection of elements into the buffer, and function to serialize * the buffer into a message. * * 2 modes: send: application code populates the buffer either 1 element at a time or multiple elements at a time * then application code will request the message * recv: application code gets a buffer region and receive from comm channel * application code will request the entire buffer. * * each element is destined for a particular mpi target rank, along with a tag that denotes its type. The add method uses a byte array along with size. * buffer has a limited size. * * This class contains a vector of buffers, each with a different id. The tag is set as template parameter, since we need to know type corresponding to the * tag at compile time anyways. * * The class allows sharing between thread but it can certainly be used within a single thread. * * send/recv have different semantics? single class would be nice - easier to support different patterns * buffer -> send = send * recv -> buffer = recv * recv -> send = forward * buffer -> buffer = local, same rank send. * * event driven with observer pattern on full/receive with CommLayer as handler? - avoids looping to check if full, before enqueue. * comm layer can do this work without being an observer since it has to have a send method - can check for full and send. * * * * * buffer's lifetime is from the first call to the buffer function to the completion of the MPI send, or * from the start of the MPI recv to the consumption of the buffer. * * QUESTIONS: reuse buffer? std::move or copy content? * MAY NEED A BUFFER OF THESE. Do that later. * * * * * Copyright (c) 2014 Georgia Institute of Technology. All Rights Reserved. * * TODO add License */ #ifndef MESSAGEBUFFERS_HPP_ #define MESSAGEBUFFERS_HPP_ #include <cassert> #include <mutex> #include <vector> #include <type_traits> #include <typeinfo> #include "config.hpp" #include "io/buffer.hpp" #include "io/buffer_pool.hpp" namespace bliss { namespace io { /** * @class bliss::io::MessageBuffers * @brief a data structure to buffering/batching messages for communication * @details THREAD_SAFE enables std::mutex for thread safety. this may introduce contention * this class uses Buffer class for the actual in memory storage. * this class also uses BufferPool to reuse memory. * * this class's purpose is to manage the actual buffering of the data for a set of message targets. * there is no need to have the MessageBuffers be aware of the tags - user can manage that. * when a Buffer is full, we swap in an empty Buffer from BufferPool. The full Buffer * is added to a processing queue by Buffer Id (used to get access the buffer from BufferPool). * * CommLayer manages the "inProgress" queues, although the actual memory used in the inProgress queues are * retrieved from the Buffers used here. * Inter-thread communication is handled by the ThreadSafeQueues * * * 2 potential subclasses: send and receive, because they have different flow of control. * RecvMessageBuffers is not needed at the moment so not implemented. * */ template<bliss::concurrent::ThreadSafety ThreadSafety> class MessageBuffers { protected: typedef typename bliss::io::BufferPool<ThreadSafety>::IdType BufferIdType; bliss::io::BufferPool<ThreadSafety> pool; const int bufferCapacity; const int getBufferCapacity() { return bufferCapacity; } /** * default, internal pool has unlimited capacity. * * @param numDests number of destinations. e.g. mpi comm size. * @param buffer_capacity individual buffer's size in bytes */ MessageBuffers(const int & numDests, const int & _buffer_capacity, const int & pool_capacity = std::numeric_limits<BufferIdType>::max()) : pool(pool_capacity, _buffer_capacity), bufferCapacity(_buffer_capacity) {}; MessageBuffers() = delete; public: virtual ~MessageBuffers() {}; // virtual bool acquireBuffer(size_t &id); /** * after the buffer has been consumed, release it back to the pool * @param id */ void releaseBuffer(const BufferIdType &id) throw (bliss::io::IOException) { pool.releaseBuffer(id); } virtual void reset() { pool.reset(); } private: }; /** * each SendMessageBuffers class contains an vector of Buffer Ids (reference buffers in BufferPool), one for each target id * * for ones that are full and are not in the vector, the user of this class will need to track the Id and use this class to * access the internal BufferPool by id. * */ template<bliss::concurrent::ThreadSafety ThreadSafety> class SendMessageBuffers : public MessageBuffers<ThreadSafety> { public: typedef typename bliss::io::BufferPool<ThreadSafety>::IdType BufferIdType; protected: typedef typename std::conditional<ThreadSafety, std::atomic<BufferIdType>, BufferIdType>::type IdType; std::vector< IdType > bufferIds; // mapping from process id (0 to vector size), to buffer Ids (from BufferPool) public: SendMessageBuffers(const int & numDests, const int & buffer_capacity, const int & pool_capacity) : MessageBuffers<ThreadSafety>(numDests, buffer_capacity, pool_capacity), bufferIds(numDests) { /// initialize the bufferIds by acquiring them from the pool. this->reset(); }; SendMessageBuffers(const int & numDests, const int & buffer_capacity) : MessageBuffers<ThreadSafety>(numDests, buffer_capacity, 3 * numDests) {}; SendMessageBuffers() = delete; SendMessageBuffers(const SendMessageBuffers<ThreadSafety> &other) = delete; SendMessageBuffers(SendMessageBuffers<ThreadSafety> && other) = default; SendMessageBuffers<ThreadSafety>& operator=(const SendMessageBuffers<ThreadSafety> &other) = delete; SendMessageBuffers<ThreadSafety>& operator=(SendMessageBuffers<ThreadSafety> && other) = default; virtual ~SendMessageBuffers() {}; size_t getSize() { return bufferIds.size(); } const Buffer<ThreadSafety> & getBackBuffer(const BufferIdType& id) { return this->pool[id]; } const std::vector< IdType >& getActiveIds() { return bufferIds; } virtual void reset() { MessageBuffers<ThreadSafety>::reset(); BufferIdType t = -1; for (int i = 0; i < this->bufferIds.size(); ++i) { t= -1; this->pool.tryAcquireBuffer(t); bufferIds[i] = t; } } /** * function appends data to the target message buffer. internally will try to swap in a new buffer when full, and notify the caller of the full buffer's id. * need to return 3 things: * status of current insert (in case the bufferpool is fixed size, and there is no available place to buffer) * indicator that there is a full buffer, and the full buffer's id. * * TODO: show a table for compare exchange values and behavior * * @param[in] data * @param[in] count * @param[in] dest * @param[out] fullBufferId id of the full buffer, if full. if not full, -1. * @return */ template<bliss::concurrent::ThreadSafety TS = ThreadSafety, typename std::enable_if<TS>::type* = nullptr > bool append(const void* data, const size_t &count, const int &dest, BufferIdType& oldBufferId) throw (bliss::io::IOException) { /// if there is not enough room for the new data in even a new buffer, LOGIC ERROR IN CODE: throw exception if (count > this->bufferCapacity) { std::stringstream ss; ss << "ERROR: MessageBuffer append with count " << count << " larger than buffer capacity " << this->bufferCapacity; throw (bliss::io::IOException(ss.str())); } /// default fullBufferId return value. BufferIdType fullBufferId = -1; /// get the current Buffer's Id BufferIdType targetBufferId = bufferIds[dest].load(std::memory_order_consume); /// need to replace bufferIds[dest], if it's -1, or if new data can't fit if ((targetBufferId == -1) || ((this->bufferCapacity - this->pool[targetBufferId].getSize()) < count)) { // at this point, targetBufferId may be -1 or some value, and the local variables may be out of date already. /// get a new buffer and try to replace the existing. BufferIdType newBufferId = -1; bool hasNewBuffer = this->pool.tryAcquireBuffer(newBufferId); // if acquire fails, we have -1 for newBufferId. /// now try to set the bufferIds[dest] to the new buffer id (valid, or -1 if can't get a new one) // again, targetBufferId is -1 or pointing to a full buffer. // use compare_exchange to ensure we only replace if targetBufferId hasn't changed. if (bufferIds[dest].compare_exchange_strong(targetBufferId, newBufferId, std::memory_order_acq_rel)) { // successful exchange. bufferIds[dest] now has newBufferId value. targetBufferId has old value. // only a success exchange should return targetBufferId as fullBufferId. fullBufferId = targetBufferId; // value could be full buffer, or could be -1. targetBufferId = newBufferId; // set targetBufferId to the new buffer, prep for append. } else { // failed exchange, then another thread had already updated bufferIds[dest]. // leave fullBufferId as -1. // targetBufferId on failed exchange will contain the up-to-date bufferIds[dest], which could be -1. // return the unused buffer id to pool. if (hasNewBuffer) this->pool.releaseBuffer(newBufferId); } } oldBufferId = fullBufferId; // now try insert using the new targetBufferId. if (targetBufferId == -1) // some other thread may have set this to -1 because it could not get a buffer from pool. try again. return false; else return this->pool[targetBufferId].append(data, count); } /** * function appends data to the target message buffer. internally will try to swap in a new buffer when full, and notify the caller of the full buffer's id. * need to return 3 things: * status of current insert (in case the bufferpool is fixed size, and there is no available place to buffer) * indicator that there is a full buffer, and the full buffer's id. * * @param[in] data * @param[in] count * @param[in] dest * @param[out] fullBufferId id of the full buffer, if full. if not full, -1. * @return */ template<bliss::concurrent::ThreadSafety TS = ThreadSafety, typename std::enable_if<!TS>::type* = nullptr > bool append(const void* data, const size_t &count, const int &dest, BufferIdType& oldBufferId) throw (bliss::io::IOException) { /// if there is not enough room for the new data in even a new buffer, throw exception if (count > this->bufferCapacity) { std::stringstream ss; ss << "ERROR: MessageBuffer append with count " << count << " larger than buffer capacity " << this->bufferCapacity; throw (bliss::io::IOException(ss.str())); } /// initialize fullBufferId to no buffer returned. BufferIdType fullBufferId = -1; /// save the current Buffer's Id BufferIdType targetBufferId = bufferIds[dest]; /// need to replace bufferIds[dest], if it's -1, or if new data can't fit if ((targetBufferId == -1) || ((this->bufferCapacity - this->pool[targetBufferId].getSize()) < count)) { // save the old buffer/full buffer to return fullBufferId = targetBufferId; /// get a new buffer and try to replace the existing. targetBufferId = -1; this->pool.tryAcquireBuffer(targetBufferId); /// now try to set the bufferIds[dest] to the new buffer id (valid, or -1 if can't get a new one) bufferIds[dest] = targetBufferId; } // now try insert using the new targetBufferId. oldBufferId = fullBufferId; if (targetBufferId == -1) return false; else return this->pool[targetBufferId].append(data, count); } }; /** * each RecvMessageBuffers contains a collection of Buffers, one for each received buffer to be processed. * * not implemented. */ // template<int TAG, bliss::concurrent::ThreadSafety ThreadSafety> // class RecvMessageBuffers; } /* namespace io */ } /* namespace bliss */ #endif /* MESSAGEBUFFERS_HPP_ */ <commit_msg>WIP: updating comm layer.<commit_after>/** * @file MessageBuffers.hpp * @ingroup * @author tpan * @brief buffering data for MPI send/receive * @details MessageBuffers provides buffering for MPI Send/Receive messages. * Terminology: Message is an MPI compatible message, serialized from buffer, including the appropriate metadata. * Element is a single piece of data from the application code. * Buffer is a collection of elements. * * * provides functions for storing single and collection of elements into the buffer, and function to serialize * the buffer into a message. * * 2 modes: send: application code populates the buffer either 1 element at a time or multiple elements at a time * then application code will request the message * recv: application code gets a buffer region and receive from comm channel * application code will request the entire buffer. * * each element is destined for a particular mpi target rank, along with a tag that denotes its type. The add method uses a byte array along with size. * buffer has a limited size. * * This class contains a vector of buffers, each with a different id. The tag is set as template parameter, since we need to know type corresponding to the * tag at compile time anyways. * * The class allows sharing between thread but it can certainly be used within a single thread. * * send/recv have different semantics? single class would be nice - easier to support different patterns * buffer -> send = send * recv -> buffer = recv * recv -> send = forward * buffer -> buffer = local, same rank send. * * event driven with observer pattern on full/receive with CommLayer as handler? - avoids looping to check if full, before enqueue. * comm layer can do this work without being an observer since it has to have a send method - can check for full and send. * * * * * buffer's lifetime is from the first call to the buffer function to the completion of the MPI send, or * from the start of the MPI recv to the consumption of the buffer. * * QUESTIONS: reuse buffer? std::move or copy content? * MAY NEED A BUFFER OF THESE. Do that later. * * * * * Copyright (c) 2014 Georgia Institute of Technology. All Rights Reserved. * * TODO add License */ #ifndef MESSAGEBUFFERS_HPP_ #define MESSAGEBUFFERS_HPP_ #include <cassert> #include <mutex> #include <vector> #include <type_traits> #include <typeinfo> #include "config.hpp" #include "io/buffer.hpp" #include "io/buffer_pool.hpp" namespace bliss { namespace io { /** * @class bliss::io::MessageBuffers * @brief a data structure to buffering/batching messages for communication * @details THREAD_SAFE enables std::mutex for thread safety. this may introduce contention * this class uses Buffer class for the actual in memory storage. * this class also uses BufferPool to reuse memory. * * this class's purpose is to manage the actual buffering of the data for a set of message targets. * there is no need to have the MessageBuffers be aware of the tags - user can manage that. * when a Buffer is full, we swap in an empty Buffer from BufferPool. The full Buffer * is added to a processing queue by Buffer Id (used to get access the buffer from BufferPool). * * CommLayer manages the "inProgress" queues, although the actual memory used in the inProgress queues are * retrieved from the Buffers used here. * Inter-thread communication is handled by the ThreadSafeQueues * * * 2 potential subclasses: send and receive, because they have different flow of control. * RecvMessageBuffers is not needed at the moment so not implemented. * */ template<bliss::concurrent::ThreadSafety ThreadSafety> class MessageBuffers { protected: typedef typename bliss::io::BufferPool<ThreadSafety>::IdType BufferIdType; bliss::io::BufferPool<ThreadSafety> pool; const int bufferCapacity; const int getBufferCapacity() { return bufferCapacity; } /** * default, internal pool has unlimited capacity. * * @param numDests number of destinations. e.g. mpi comm size. * @param buffer_capacity individual buffer's size in bytes */ MessageBuffers(const int & _buffer_capacity, const int & pool_capacity = std::numeric_limits<BufferIdType>::max()) : pool(pool_capacity, _buffer_capacity), bufferCapacity(_buffer_capacity) {}; MessageBuffers() = delete; public: virtual ~MessageBuffers() {}; // virtual bool acquireBuffer(size_t &id); /** * after the buffer has been consumed, release it back to the pool * @param id */ void releaseBuffer(const BufferIdType &id) throw (bliss::io::IOException) { pool.releaseBuffer(id); } virtual void reset() { pool.reset(); } private: }; /** * each SendMessageBuffers class contains an vector of Buffer Ids (reference buffers in BufferPool), one for each target id * * for ones that are full and are not in the vector, the user of this class will need to track the Id and use this class to * access the internal BufferPool by id. * */ template<bliss::concurrent::ThreadSafety ThreadSafety> class SendMessageBuffers : public MessageBuffers<ThreadSafety> { public: typedef typename bliss::io::BufferPool<ThreadSafety>::IdType BufferIdType; protected: typedef typename std::conditional<ThreadSafety, std::atomic<BufferIdType>, BufferIdType>::type IdType; std::vector< IdType > bufferIds; // mapping from process id (0 to vector size), to buffer Ids (from BufferPool) public: SendMessageBuffers(const int & numDests, const int & buffer_capacity, const int pool_capacity) : MessageBuffers<ThreadSafety>(buffer_capacity, pool_capacity), bufferIds(numDests) { /// initialize the bufferIds by acquiring them from the pool. this->reset(); }; SendMessageBuffers(const int & numDests, const int & buffer_capacity) : SendMessageBuffers<ThreadSafety>(numDests, buffer_capacity, 3 * numDests) {}; SendMessageBuffers() = delete; SendMessageBuffers(const SendMessageBuffers<ThreadSafety> &other) = delete; SendMessageBuffers(SendMessageBuffers<ThreadSafety> && other) = default; SendMessageBuffers<ThreadSafety>& operator=(const SendMessageBuffers<ThreadSafety> &other) = delete; SendMessageBuffers<ThreadSafety>& operator=(SendMessageBuffers<ThreadSafety> && other) = default; virtual ~SendMessageBuffers() {}; size_t getSize() { return bufferIds.size(); } const Buffer<ThreadSafety> & getBackBuffer(const BufferIdType& id) { return this->pool[id]; } const std::vector< IdType >& getActiveIds() { return bufferIds; } virtual void reset() { MessageBuffers<ThreadSafety>::reset(); BufferIdType t = -1; for (int i = 0; i < this->bufferIds.size(); ++i) { t= -1; this->pool.tryAcquireBuffer(t); bufferIds[i] = t; } } /** * function appends data to the target message buffer. internally will try to swap in a new buffer when full, and notify the caller of the full buffer's id. * need to return 3 things: * status of current insert (in case the bufferpool is fixed size, and there is no available place to buffer) * indicator that there is a full buffer, and the full buffer's id. * * TODO: show a table for compare exchange values and behavior * * @param[in] data * @param[in] count * @param[in] dest * @param[out] fullBufferId id of the full buffer, if full. if not full, -1. * @return */ template<bliss::concurrent::ThreadSafety TS = ThreadSafety, typename std::enable_if<TS>::type* = nullptr > bool append(const void* data, const size_t &count, const int &dest, BufferIdType& oldBufferId) throw (bliss::io::IOException) { /// if there is not enough room for the new data in even a new buffer, LOGIC ERROR IN CODE: throw exception if (count > this->bufferCapacity) { std::stringstream ss; ss << "ERROR: MessageBuffer append with count " << count << " larger than buffer capacity " << this->bufferCapacity; throw (bliss::io::IOException(ss.str())); } /// default fullBufferId return value. BufferIdType fullBufferId = -1; /// get the current Buffer's Id BufferIdType targetBufferId = bufferIds[dest].load(std::memory_order_consume); /// need to replace bufferIds[dest], if it's -1, or if new data can't fit if ((targetBufferId == -1) || ((this->bufferCapacity - this->pool[targetBufferId].getSize()) < count)) { // at this point, targetBufferId may be -1 or some value, and the local variables may be out of date already. /// get a new buffer and try to replace the existing. BufferIdType newBufferId = -1; bool hasNewBuffer = this->pool.tryAcquireBuffer(newBufferId); // if acquire fails, we have -1 for newBufferId. /// now try to set the bufferIds[dest] to the new buffer id (valid, or -1 if can't get a new one) // again, targetBufferId is -1 or pointing to a full buffer. // use compare_exchange to ensure we only replace if targetBufferId hasn't changed. if (bufferIds[dest].compare_exchange_strong(targetBufferId, newBufferId, std::memory_order_acq_rel)) { // successful exchange. bufferIds[dest] now has newBufferId value. targetBufferId has old value. // only a success exchange should return targetBufferId as fullBufferId. fullBufferId = targetBufferId; // value could be full buffer, or could be -1. targetBufferId = newBufferId; // set targetBufferId to the new buffer, prep for append. } else { // failed exchange, then another thread had already updated bufferIds[dest]. // leave fullBufferId as -1. // targetBufferId on failed exchange will contain the up-to-date bufferIds[dest], which could be -1. // return the unused buffer id to pool. if (hasNewBuffer) this->pool.releaseBuffer(newBufferId); } } oldBufferId = fullBufferId; // now try insert using the new targetBufferId. if (targetBufferId == -1) // some other thread may have set this to -1 because it could not get a buffer from pool. try again. return false; else return this->pool[targetBufferId].append(data, count); } /** * function appends data to the target message buffer. internally will try to swap in a new buffer when full, and notify the caller of the full buffer's id. * need to return 3 things: * status of current insert (in case the bufferpool is fixed size, and there is no available place to buffer) * indicator that there is a full buffer, and the full buffer's id. * * @param[in] data * @param[in] count * @param[in] dest * @param[out] fullBufferId id of the full buffer, if full. if not full, -1. * @return */ template<bliss::concurrent::ThreadSafety TS = ThreadSafety, typename std::enable_if<!TS>::type* = nullptr > bool append(const void* data, const size_t &count, const int &dest, BufferIdType& oldBufferId) throw (bliss::io::IOException) { /// if there is not enough room for the new data in even a new buffer, throw exception if (count > this->bufferCapacity) { std::stringstream ss; ss << "ERROR: MessageBuffer append with count " << count << " larger than buffer capacity " << this->bufferCapacity; throw (bliss::io::IOException(ss.str())); } /// initialize fullBufferId to no buffer returned. BufferIdType fullBufferId = -1; /// save the current Buffer's Id BufferIdType targetBufferId = bufferIds[dest]; /// need to replace bufferIds[dest], if it's -1, or if new data can't fit if ((targetBufferId == -1) || ((this->bufferCapacity - this->pool[targetBufferId].getSize()) < count)) { // save the old buffer/full buffer to return fullBufferId = targetBufferId; /// get a new buffer and try to replace the existing. targetBufferId = -1; this->pool.tryAcquireBuffer(targetBufferId); /// now try to set the bufferIds[dest] to the new buffer id (valid, or -1 if can't get a new one) bufferIds[dest] = targetBufferId; } // now try insert using the new targetBufferId. oldBufferId = fullBufferId; if (targetBufferId == -1) return false; else return this->pool[targetBufferId].append(data, count); } }; /** * each RecvMessageBuffers contains a collection of Buffers, one for each received buffer to be processed. * * not implemented. */ // template<int TAG, bliss::concurrent::ThreadSafety ThreadSafety> // class RecvMessageBuffers; } /* namespace io */ } /* namespace bliss */ #endif /* MESSAGEBUFFERS_HPP_ */ <|endoftext|>
<commit_before>#ifndef AURACLE_HH #define AURACLE_HH #include <iostream> #include <set> #include <string> #include <unordered_set> #include <vector> #include "aur/aur.hh" #include "inmemory_repo.hh" #include "pacman.hh" class PackageOrDependency : public std::variant<std::string, aur::Dependency> { public: using std::variant<std::string, aur::Dependency>::variant; operator std::string() const { auto pval = std::get_if<std::string>(this); if (pval != nullptr) { return *pval; } else { return std::get_if<aur::Dependency>(this)->name; } } bool operator==(const std::string& other) const { return std::string(*this) == other; } }; class Auracle { public: struct Options { Options& set_aur_baseurl(std::string aur_baseurl) { this->aur_baseurl = aur_baseurl; return *this; } Options& set_pacman(dlr::Pacman* pacman) { this->pacman = pacman; return *this; } Options& set_max_connections(int max_connections) { this->max_connections = max_connections; return *this; } Options& set_connection_timeout(int connection_timeout) { this->connection_timeout = connection_timeout; return *this; } Options& set_allow_regex(bool allow_regex) { this->allow_regex = allow_regex; return *this; } Options& set_quiet(bool quiet) { this->quiet = quiet; return *this; } std::string aur_baseurl; dlr::Pacman* pacman; bool allow_regex = true; bool quiet = false; int max_connections = 0; int connection_timeout = 0; }; explicit Auracle(Options options) : options_(std::move(options)), aur_(options_.aur_baseurl), allow_regex_(options_.allow_regex), pacman_(options_.pacman) { aur_.SetMaxConnections(options_.max_connections); aur_.SetConnectTimeout(options_.connection_timeout); } ~Auracle() = default; Auracle(const Auracle&) = delete; Auracle& operator=(const Auracle&) = delete; int Info(const std::vector<PackageOrDependency>& args); int Search(const std::vector<PackageOrDependency>& args, aur::SearchRequest::SearchBy by); int Download(const std::vector<PackageOrDependency>& args, bool recurse); int Sync(const std::vector<PackageOrDependency>& args); int BuildOrder(const std::vector<PackageOrDependency>& args); int Pkgbuild(const std::vector<PackageOrDependency>& args); private: struct PackageIterator { explicit PackageIterator(bool recurse, bool download) : recurse(recurse), download(download) {} bool recurse; bool download; dlr::InMemoryRepo package_repo; }; void IteratePackages(std::vector<PackageOrDependency> args, PackageIterator* state); const Options options_; aur::Aur aur_; bool allow_regex_; dlr::Pacman* const pacman_; }; #endif // AURACLE_HH <commit_msg>Drop unused includes<commit_after>#ifndef AURACLE_HH #define AURACLE_HH #include <string> #include <vector> #include "aur/aur.hh" #include "inmemory_repo.hh" #include "pacman.hh" class PackageOrDependency : public std::variant<std::string, aur::Dependency> { public: using std::variant<std::string, aur::Dependency>::variant; operator std::string() const { auto pval = std::get_if<std::string>(this); if (pval != nullptr) { return *pval; } else { return std::get_if<aur::Dependency>(this)->name; } } bool operator==(const std::string& other) const { return std::string(*this) == other; } }; class Auracle { public: struct Options { Options& set_aur_baseurl(std::string aur_baseurl) { this->aur_baseurl = aur_baseurl; return *this; } Options& set_pacman(dlr::Pacman* pacman) { this->pacman = pacman; return *this; } Options& set_max_connections(int max_connections) { this->max_connections = max_connections; return *this; } Options& set_connection_timeout(int connection_timeout) { this->connection_timeout = connection_timeout; return *this; } Options& set_allow_regex(bool allow_regex) { this->allow_regex = allow_regex; return *this; } Options& set_quiet(bool quiet) { this->quiet = quiet; return *this; } std::string aur_baseurl; dlr::Pacman* pacman; bool allow_regex = true; bool quiet = false; int max_connections = 0; int connection_timeout = 0; }; explicit Auracle(Options options) : options_(std::move(options)), aur_(options_.aur_baseurl), allow_regex_(options_.allow_regex), pacman_(options_.pacman) { aur_.SetMaxConnections(options_.max_connections); aur_.SetConnectTimeout(options_.connection_timeout); } ~Auracle() = default; Auracle(const Auracle&) = delete; Auracle& operator=(const Auracle&) = delete; int Info(const std::vector<PackageOrDependency>& args); int Search(const std::vector<PackageOrDependency>& args, aur::SearchRequest::SearchBy by); int Download(const std::vector<PackageOrDependency>& args, bool recurse); int Sync(const std::vector<PackageOrDependency>& args); int BuildOrder(const std::vector<PackageOrDependency>& args); int Pkgbuild(const std::vector<PackageOrDependency>& args); private: struct PackageIterator { explicit PackageIterator(bool recurse, bool download) : recurse(recurse), download(download) {} bool recurse; bool download; dlr::InMemoryRepo package_repo; }; void IteratePackages(std::vector<PackageOrDependency> args, PackageIterator* state); const Options options_; aur::Aur aur_; bool allow_regex_; dlr::Pacman* const pacman_; }; #endif // AURACLE_HH <|endoftext|>
<commit_before>//=-- SystemZHazardRecognizer.h - SystemZ Hazard Recognizer -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a hazard recognizer for the SystemZ scheduler. // // This class is used by the SystemZ scheduling strategy to maintain // the state during scheduling, and provide cost functions for // scheduling candidates. This includes: // // * Decoder grouping. A decoder group can maximally hold 3 uops, and // instructions that always begin a new group should be scheduled when // the current decoder group is empty. // * Processor resources usage. It is beneficial to balance the use of // resources. // // A goal is to consider all instructions, also those outside of any // scheduling region. Such instructions are "advanced" past and include // single instructions before a scheduling region, branches etc. // // A block that has only one predecessor continues scheduling with the state // of it (which may be updated by emitting branches). // // ===---------------------------------------------------------------------===// #include "SystemZHazardRecognizer.h" #include "llvm/ADT/Statistic.h" using namespace llvm; #define DEBUG_TYPE "machine-scheduler" // This is the limit of processor resource usage at which the // scheduler should try to look for other instructions (not using the // critical resource). static cl::opt<int> ProcResCostLim("procres-cost-lim", cl::Hidden, cl::desc("The OOO window for processor " "resources during scheduling."), cl::init(8)); unsigned SystemZHazardRecognizer:: getNumDecoderSlots(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // IMPLICIT_DEF / KILL -- will not make impact in output. if (SC->BeginGroup) { if (!SC->EndGroup) return 2; // Cracked instruction else return 3; // Expanded/group-alone instruction } return 1; // Normal instruction } unsigned SystemZHazardRecognizer::getCurrCycleIdx() const { unsigned Idx = CurrGroupSize; if (GrpCount % 2) Idx += 3; return Idx; } ScheduleHazardRecognizer::HazardType SystemZHazardRecognizer:: getHazardType(SUnit *m, int Stalls) { return (fitsIntoCurrentGroup(m) ? NoHazard : Hazard); } void SystemZHazardRecognizer::Reset() { CurrGroupSize = 0; clearProcResCounters(); GrpCount = 0; LastFPdOpCycleIdx = UINT_MAX; LastEmittedMI = nullptr; DEBUG(CurGroupDbg = "";); } bool SystemZHazardRecognizer::fitsIntoCurrentGroup(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return true; // A cracked instruction only fits into schedule if the current // group is empty. if (SC->BeginGroup) return (CurrGroupSize == 0); // Since a full group is handled immediately in EmitInstruction(), // SU should fit into current group. NumSlots should be 1 or 0, // since it is not a cracked or expanded instruction. assert ((getNumDecoderSlots(SU) <= 1) && (CurrGroupSize < 3) && "Expected normal instruction to fit in non-full group!"); return true; } void SystemZHazardRecognizer::nextGroup() { if (CurrGroupSize == 0) return; DEBUG(dumpCurrGroup("Completed decode group")); DEBUG(CurGroupDbg = "";); GrpCount++; // Reset counter for next group. CurrGroupSize = 0; // Decrease counters for execution units by one. for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) ProcResourceCounters[i]--; // Clear CriticalResourceIdx if it is now below the threshold. if (CriticalResourceIdx != UINT_MAX && (ProcResourceCounters[CriticalResourceIdx] <= ProcResCostLim)) CriticalResourceIdx = UINT_MAX; DEBUG(dumpState();); } #ifndef NDEBUG // Debug output void SystemZHazardRecognizer::dumpSU(SUnit *SU, raw_ostream &OS) const { OS << "SU(" << SU->NodeNum << "):"; OS << TII->getName(SU->getInstr()->getOpcode()); const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return; for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { const MCProcResourceDesc &PRD = *SchedModel->getProcResource(PI->ProcResourceIdx); std::string FU(PRD.Name); // trim e.g. Z13_FXaUnit -> FXa FU = FU.substr(FU.find("_") + 1); FU.resize(FU.find("Unit")); OS << "/" << FU; if (PI->Cycles > 1) OS << "(" << PI->Cycles << "cyc)"; } if (SC->NumMicroOps > 1) OS << "/" << SC->NumMicroOps << "uops"; if (SC->BeginGroup && SC->EndGroup) OS << "/GroupsAlone"; else if (SC->BeginGroup) OS << "/BeginsGroup"; else if (SC->EndGroup) OS << "/EndsGroup"; if (SU->isUnbuffered) OS << "/Unbuffered"; } void SystemZHazardRecognizer::dumpCurrGroup(std::string Msg) const { dbgs() << "++ " << Msg; dbgs() << ": "; if (CurGroupDbg.empty()) dbgs() << " <empty>\n"; else { dbgs() << "{ " << CurGroupDbg << " }"; dbgs() << " (" << CurrGroupSize << " decoder slot" << (CurrGroupSize > 1 ? "s":"") << ")\n"; } } void SystemZHazardRecognizer::dumpProcResourceCounters() const { bool any = false; for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) { any = true; break; } if (!any) return; dbgs() << "++ | Resource counters: "; for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) dbgs() << SchedModel->getProcResource(i)->Name << ":" << ProcResourceCounters[i] << " "; dbgs() << "\n"; if (CriticalResourceIdx != UINT_MAX) dbgs() << "++ | Critical resource: " << SchedModel->getProcResource(CriticalResourceIdx)->Name << "\n"; } void SystemZHazardRecognizer::dumpState() const { dumpCurrGroup("| Current decoder group"); dbgs() << "++ | Current cycle index: " << getCurrCycleIdx() << "\n"; dumpProcResourceCounters(); if (LastFPdOpCycleIdx != UINT_MAX) dbgs() << "++ | Last FPd cycle index: " << LastFPdOpCycleIdx << "\n"; } #endif //NDEBUG void SystemZHazardRecognizer::clearProcResCounters() { ProcResourceCounters.assign(SchedModel->getNumProcResourceKinds(), 0); CriticalResourceIdx = UINT_MAX; } static inline bool isBranchRetTrap(MachineInstr *MI) { return (MI->isBranch() || MI->isReturn() || MI->getOpcode() == SystemZ::CondTrap); } // Update state with SU as the next scheduled unit. void SystemZHazardRecognizer:: EmitInstruction(SUnit *SU) { const MCSchedClassDesc *SC = getSchedClass(SU); DEBUG(dbgs() << "++ HazardRecognizer emitting "; dumpSU(SU, dbgs()); dbgs() << "\n";); DEBUG(dumpCurrGroup("Decode group before emission");); // If scheduling an SU that must begin a new decoder group, move on // to next group. if (!fitsIntoCurrentGroup(SU)) nextGroup(); DEBUG(raw_string_ostream cgd(CurGroupDbg); if (CurGroupDbg.length()) cgd << ", "; dumpSU(SU, cgd);); LastEmittedMI = SU->getInstr(); // After returning from a call, we don't know much about the state. if (SU->isCall) { DEBUG(dbgs() << "++ Clearing state after call.\n";); clearProcResCounters(); LastFPdOpCycleIdx = UINT_MAX; CurrGroupSize += getNumDecoderSlots(SU); assert (CurrGroupSize <= 3); nextGroup(); return; } // Increase counter for execution unit(s). for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { // Don't handle FPd together with the other resources. if (SchedModel->getProcResource(PI->ProcResourceIdx)->BufferSize == 1) continue; int &CurrCounter = ProcResourceCounters[PI->ProcResourceIdx]; CurrCounter += PI->Cycles; // Check if this is now the new critical resource. if ((CurrCounter > ProcResCostLim) && (CriticalResourceIdx == UINT_MAX || (PI->ProcResourceIdx != CriticalResourceIdx && CurrCounter > ProcResourceCounters[CriticalResourceIdx]))) { DEBUG(dbgs() << "++ New critical resource: " << SchedModel->getProcResource(PI->ProcResourceIdx)->Name << "\n";); CriticalResourceIdx = PI->ProcResourceIdx; } } // Make note of an instruction that uses a blocking resource (FPd). if (SU->isUnbuffered) { LastFPdOpCycleIdx = getCurrCycleIdx(); DEBUG(dbgs() << "++ Last FPd cycle index: " << LastFPdOpCycleIdx << "\n";); } bool GroupEndingBranch = (CurrGroupSize >= 1 && isBranchRetTrap(SU->getInstr())); // Insert SU into current group by increasing number of slots used // in current group. CurrGroupSize += getNumDecoderSlots(SU); assert (CurrGroupSize <= 3); // Check if current group is now full/ended. If so, move on to next // group to be ready to evaluate more candidates. if (CurrGroupSize == 3 || SC->EndGroup || GroupEndingBranch) nextGroup(); } int SystemZHazardRecognizer::groupingCost(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // If SU begins new group, it can either break a current group early // or fit naturally if current group is empty (negative cost). if (SC->BeginGroup) { if (CurrGroupSize) return 3 - CurrGroupSize; return -1; } // Similarly, a group-ending SU may either fit well (last in group), or // end the group prematurely. if (SC->EndGroup) { unsigned resultingGroupSize = (CurrGroupSize + getNumDecoderSlots(SU)); if (resultingGroupSize < 3) return (3 - resultingGroupSize); return -1; } // Most instructions can be placed in any decoder slot. return 0; } bool SystemZHazardRecognizer::isFPdOpPreferred_distance(const SUnit *SU) { assert (SU->isUnbuffered); // If this is the first FPd op, it should be scheduled high. if (LastFPdOpCycleIdx == UINT_MAX) return true; // If this is not the first PFd op, it should go into the other side // of the processor to use the other FPd unit there. This should // generally happen if two FPd ops are placed with 2 other // instructions between them (modulo 6). if (LastFPdOpCycleIdx > getCurrCycleIdx()) return ((LastFPdOpCycleIdx - getCurrCycleIdx()) == 3); return ((getCurrCycleIdx() - LastFPdOpCycleIdx) == 3); } int SystemZHazardRecognizer:: resourcesCost(SUnit *SU) { int Cost = 0; const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // For a FPd op, either return min or max value as indicated by the // distance to any prior FPd op. if (SU->isUnbuffered) Cost = (isFPdOpPreferred_distance(SU) ? INT_MIN : INT_MAX); // For other instructions, give a cost to the use of the critical resource. else if (CriticalResourceIdx != UINT_MAX) { for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) if (PI->ProcResourceIdx == CriticalResourceIdx) Cost = PI->Cycles; } return Cost; } void SystemZHazardRecognizer::emitInstruction(MachineInstr *MI, bool TakenBranch) { // Make a temporary SUnit. SUnit SU(MI, 0); // Set interesting flags. SU.isCall = MI->isCall(); const MCSchedClassDesc *SC = SchedModel->resolveSchedClass(MI); for (const MCWriteProcResEntry &PRE : make_range(SchedModel->getWriteProcResBegin(SC), SchedModel->getWriteProcResEnd(SC))) { switch (SchedModel->getProcResource(PRE.ProcResourceIdx)->BufferSize) { case 0: SU.hasReservedResource = true; break; case 1: SU.isUnbuffered = true; break; default: break; } } EmitInstruction(&SU); if (TakenBranch && CurrGroupSize > 0) nextGroup(); assert ((!MI->isTerminator() || isBranchRetTrap(MI)) && "Scheduler: unhandled terminator!"); } void SystemZHazardRecognizer:: copyState(SystemZHazardRecognizer *Incoming) { // Current decoder group CurrGroupSize = Incoming->CurrGroupSize; DEBUG(CurGroupDbg = Incoming->CurGroupDbg;); // Processor resources ProcResourceCounters = Incoming->ProcResourceCounters; CriticalResourceIdx = Incoming->CriticalResourceIdx; // FPd LastFPdOpCycleIdx = Incoming->LastFPdOpCycleIdx; GrpCount = Incoming->GrpCount; } <commit_msg>[SystemZ] NFC refactoring in SystemZHazardRecognizer.<commit_after>//=-- SystemZHazardRecognizer.h - SystemZ Hazard Recognizer -----*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a hazard recognizer for the SystemZ scheduler. // // This class is used by the SystemZ scheduling strategy to maintain // the state during scheduling, and provide cost functions for // scheduling candidates. This includes: // // * Decoder grouping. A decoder group can maximally hold 3 uops, and // instructions that always begin a new group should be scheduled when // the current decoder group is empty. // * Processor resources usage. It is beneficial to balance the use of // resources. // // A goal is to consider all instructions, also those outside of any // scheduling region. Such instructions are "advanced" past and include // single instructions before a scheduling region, branches etc. // // A block that has only one predecessor continues scheduling with the state // of it (which may be updated by emitting branches). // // ===---------------------------------------------------------------------===// #include "SystemZHazardRecognizer.h" #include "llvm/ADT/Statistic.h" using namespace llvm; #define DEBUG_TYPE "machine-scheduler" // This is the limit of processor resource usage at which the // scheduler should try to look for other instructions (not using the // critical resource). static cl::opt<int> ProcResCostLim("procres-cost-lim", cl::Hidden, cl::desc("The OOO window for processor " "resources during scheduling."), cl::init(8)); unsigned SystemZHazardRecognizer:: getNumDecoderSlots(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // IMPLICIT_DEF / KILL -- will not make impact in output. if (SC->BeginGroup) { if (!SC->EndGroup) return 2; // Cracked instruction else return 3; // Expanded/group-alone instruction } return 1; // Normal instruction } unsigned SystemZHazardRecognizer::getCurrCycleIdx() const { unsigned Idx = CurrGroupSize; if (GrpCount % 2) Idx += 3; return Idx; } ScheduleHazardRecognizer::HazardType SystemZHazardRecognizer:: getHazardType(SUnit *m, int Stalls) { return (fitsIntoCurrentGroup(m) ? NoHazard : Hazard); } void SystemZHazardRecognizer::Reset() { CurrGroupSize = 0; clearProcResCounters(); GrpCount = 0; LastFPdOpCycleIdx = UINT_MAX; LastEmittedMI = nullptr; DEBUG(CurGroupDbg = "";); } bool SystemZHazardRecognizer::fitsIntoCurrentGroup(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return true; // A cracked instruction only fits into schedule if the current // group is empty. if (SC->BeginGroup) return (CurrGroupSize == 0); // Since a full group is handled immediately in EmitInstruction(), // SU should fit into current group. NumSlots should be 1 or 0, // since it is not a cracked or expanded instruction. assert ((getNumDecoderSlots(SU) <= 1) && (CurrGroupSize < 3) && "Expected normal instruction to fit in non-full group!"); return true; } void SystemZHazardRecognizer::nextGroup() { if (CurrGroupSize == 0) return; DEBUG(dumpCurrGroup("Completed decode group")); DEBUG(CurGroupDbg = "";); GrpCount++; // Reset counter for next group. CurrGroupSize = 0; // Decrease counters for execution units by one. for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) ProcResourceCounters[i]--; // Clear CriticalResourceIdx if it is now below the threshold. if (CriticalResourceIdx != UINT_MAX && (ProcResourceCounters[CriticalResourceIdx] <= ProcResCostLim)) CriticalResourceIdx = UINT_MAX; DEBUG(dumpState();); } #ifndef NDEBUG // Debug output void SystemZHazardRecognizer::dumpSU(SUnit *SU, raw_ostream &OS) const { OS << "SU(" << SU->NodeNum << "):"; OS << TII->getName(SU->getInstr()->getOpcode()); const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return; for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { const MCProcResourceDesc &PRD = *SchedModel->getProcResource(PI->ProcResourceIdx); std::string FU(PRD.Name); // trim e.g. Z13_FXaUnit -> FXa FU = FU.substr(FU.find("_") + 1); FU.resize(FU.find("Unit")); OS << "/" << FU; if (PI->Cycles > 1) OS << "(" << PI->Cycles << "cyc)"; } if (SC->NumMicroOps > 1) OS << "/" << SC->NumMicroOps << "uops"; if (SC->BeginGroup && SC->EndGroup) OS << "/GroupsAlone"; else if (SC->BeginGroup) OS << "/BeginsGroup"; else if (SC->EndGroup) OS << "/EndsGroup"; if (SU->isUnbuffered) OS << "/Unbuffered"; } void SystemZHazardRecognizer::dumpCurrGroup(std::string Msg) const { dbgs() << "++ " << Msg; dbgs() << ": "; if (CurGroupDbg.empty()) dbgs() << " <empty>\n"; else { dbgs() << "{ " << CurGroupDbg << " }"; dbgs() << " (" << CurrGroupSize << " decoder slot" << (CurrGroupSize > 1 ? "s":"") << ")\n"; } } void SystemZHazardRecognizer::dumpProcResourceCounters() const { bool any = false; for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) { any = true; break; } if (!any) return; dbgs() << "++ | Resource counters: "; for (unsigned i = 0; i < SchedModel->getNumProcResourceKinds(); ++i) if (ProcResourceCounters[i] > 0) dbgs() << SchedModel->getProcResource(i)->Name << ":" << ProcResourceCounters[i] << " "; dbgs() << "\n"; if (CriticalResourceIdx != UINT_MAX) dbgs() << "++ | Critical resource: " << SchedModel->getProcResource(CriticalResourceIdx)->Name << "\n"; } void SystemZHazardRecognizer::dumpState() const { dumpCurrGroup("| Current decoder group"); dbgs() << "++ | Current cycle index: " << getCurrCycleIdx() << "\n"; dumpProcResourceCounters(); if (LastFPdOpCycleIdx != UINT_MAX) dbgs() << "++ | Last FPd cycle index: " << LastFPdOpCycleIdx << "\n"; } #endif //NDEBUG void SystemZHazardRecognizer::clearProcResCounters() { ProcResourceCounters.assign(SchedModel->getNumProcResourceKinds(), 0); CriticalResourceIdx = UINT_MAX; } static inline bool isBranchRetTrap(MachineInstr *MI) { return (MI->isBranch() || MI->isReturn() || MI->getOpcode() == SystemZ::CondTrap); } // Update state with SU as the next scheduled unit. void SystemZHazardRecognizer:: EmitInstruction(SUnit *SU) { const MCSchedClassDesc *SC = getSchedClass(SU); DEBUG(dbgs() << "++ HazardRecognizer emitting "; dumpSU(SU, dbgs()); dbgs() << "\n";); DEBUG(dumpCurrGroup("Decode group before emission");); // If scheduling an SU that must begin a new decoder group, move on // to next group. if (!fitsIntoCurrentGroup(SU)) nextGroup(); DEBUG(raw_string_ostream cgd(CurGroupDbg); if (CurGroupDbg.length()) cgd << ", "; dumpSU(SU, cgd);); LastEmittedMI = SU->getInstr(); // After returning from a call, we don't know much about the state. if (SU->isCall) { DEBUG(dbgs() << "++ Clearing state after call.\n";); clearProcResCounters(); LastFPdOpCycleIdx = UINT_MAX; CurrGroupSize += getNumDecoderSlots(SU); assert (CurrGroupSize <= 3); nextGroup(); return; } // Increase counter for execution unit(s). for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) { // Don't handle FPd together with the other resources. if (SchedModel->getProcResource(PI->ProcResourceIdx)->BufferSize == 1) continue; int &CurrCounter = ProcResourceCounters[PI->ProcResourceIdx]; CurrCounter += PI->Cycles; // Check if this is now the new critical resource. if ((CurrCounter > ProcResCostLim) && (CriticalResourceIdx == UINT_MAX || (PI->ProcResourceIdx != CriticalResourceIdx && CurrCounter > ProcResourceCounters[CriticalResourceIdx]))) { DEBUG(dbgs() << "++ New critical resource: " << SchedModel->getProcResource(PI->ProcResourceIdx)->Name << "\n";); CriticalResourceIdx = PI->ProcResourceIdx; } } // Make note of an instruction that uses a blocking resource (FPd). if (SU->isUnbuffered) { LastFPdOpCycleIdx = getCurrCycleIdx(); DEBUG(dbgs() << "++ Last FPd cycle index: " << LastFPdOpCycleIdx << "\n";); } // Insert SU into current group by increasing number of slots used // in current group. CurrGroupSize += getNumDecoderSlots(SU); assert (CurrGroupSize <= 3); // Check if current group is now full/ended. If so, move on to next // group to be ready to evaluate more candidates. if (CurrGroupSize == 3 || SC->EndGroup) nextGroup(); } int SystemZHazardRecognizer::groupingCost(SUnit *SU) const { const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // If SU begins new group, it can either break a current group early // or fit naturally if current group is empty (negative cost). if (SC->BeginGroup) { if (CurrGroupSize) return 3 - CurrGroupSize; return -1; } // Similarly, a group-ending SU may either fit well (last in group), or // end the group prematurely. if (SC->EndGroup) { unsigned resultingGroupSize = (CurrGroupSize + getNumDecoderSlots(SU)); if (resultingGroupSize < 3) return (3 - resultingGroupSize); return -1; } // Most instructions can be placed in any decoder slot. return 0; } bool SystemZHazardRecognizer::isFPdOpPreferred_distance(const SUnit *SU) { assert (SU->isUnbuffered); // If this is the first FPd op, it should be scheduled high. if (LastFPdOpCycleIdx == UINT_MAX) return true; // If this is not the first PFd op, it should go into the other side // of the processor to use the other FPd unit there. This should // generally happen if two FPd ops are placed with 2 other // instructions between them (modulo 6). if (LastFPdOpCycleIdx > getCurrCycleIdx()) return ((LastFPdOpCycleIdx - getCurrCycleIdx()) == 3); return ((getCurrCycleIdx() - LastFPdOpCycleIdx) == 3); } int SystemZHazardRecognizer:: resourcesCost(SUnit *SU) { int Cost = 0; const MCSchedClassDesc *SC = getSchedClass(SU); if (!SC->isValid()) return 0; // For a FPd op, either return min or max value as indicated by the // distance to any prior FPd op. if (SU->isUnbuffered) Cost = (isFPdOpPreferred_distance(SU) ? INT_MIN : INT_MAX); // For other instructions, give a cost to the use of the critical resource. else if (CriticalResourceIdx != UINT_MAX) { for (TargetSchedModel::ProcResIter PI = SchedModel->getWriteProcResBegin(SC), PE = SchedModel->getWriteProcResEnd(SC); PI != PE; ++PI) if (PI->ProcResourceIdx == CriticalResourceIdx) Cost = PI->Cycles; } return Cost; } void SystemZHazardRecognizer::emitInstruction(MachineInstr *MI, bool TakenBranch) { // Make a temporary SUnit. SUnit SU(MI, 0); // Set interesting flags. SU.isCall = MI->isCall(); const MCSchedClassDesc *SC = SchedModel->resolveSchedClass(MI); for (const MCWriteProcResEntry &PRE : make_range(SchedModel->getWriteProcResBegin(SC), SchedModel->getWriteProcResEnd(SC))) { switch (SchedModel->getProcResource(PRE.ProcResourceIdx)->BufferSize) { case 0: SU.hasReservedResource = true; break; case 1: SU.isUnbuffered = true; break; default: break; } } unsigned GroupSizeBeforeEmit = CurrGroupSize; EmitInstruction(&SU); if (!TakenBranch && isBranchRetTrap(MI)) { // NT Branch on second slot ends group. if (GroupSizeBeforeEmit == 1) nextGroup(); } if (TakenBranch && CurrGroupSize > 0) nextGroup(); assert ((!MI->isTerminator() || isBranchRetTrap(MI)) && "Scheduler: unhandled terminator!"); } void SystemZHazardRecognizer:: copyState(SystemZHazardRecognizer *Incoming) { // Current decoder group CurrGroupSize = Incoming->CurrGroupSize; DEBUG(CurGroupDbg = Incoming->CurGroupDbg;); // Processor resources ProcResourceCounters = Incoming->ProcResourceCounters; CriticalResourceIdx = Incoming->CriticalResourceIdx; // FPd LastFPdOpCycleIdx = Incoming->LastFPdOpCycleIdx; GrpCount = Incoming->GrpCount; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 Vince Durham // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2017 Daniel Kraft // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <auxpow.h> #include <compat/endian.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <hash.h> #include <primitives/block.h> #include <script/script.h> #include <util.h> #include <utilstrencodings.h> #include <algorithm> #include <cassert> void CBaseMerkleTx::InitMerkleBranch(const CBlock& block, int posInBlock) { hashBlock = block.GetHash(); nIndex = posInBlock; vMerkleBranch = BlockMerkleBranch (block, nIndex); } bool CAuxPow::isAuxPowEquihash() const { return nVersion & AUXPOW_EQUIHASH_FLAG; } bool CAuxPow::isAuxPowPOS() const { return nVersion & AUXPOW_STAKE_FLAG; } bool CAuxPow::check (const uint256& hashAuxBlock, int nChainId, const Consensus::Params& params) const { bool fSameChainId = isAuxPowEquihash() ? (getEquihashParentBlock().GetChainId () == nChainId) : (getDefaultParentBlock().GetChainId () == nChainId); int nIndex = isAuxPowPOS() ? coinbasePOSTx.nIndex : coinbaseTx.nIndex; if (nIndex != 0) return error("AuxPow is not a generate"); if (params.fStrictChainId && fSameChainId) return error("Aux POW parent has our chain ID"); if (vChainMerkleBranch.size() > 30) return error("Aux POW chain merkle branch too long"); // Check that the chain merkle root is in the coinbase const uint256 nRootHash = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex); std::vector<unsigned char> vchRootHash(nRootHash.begin (), nRootHash.end ()); std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian const uint256 blockMerkleRoot = isAuxPowEquihash() ? getEquihashParentBlock().hashMerkleRoot : getDefaultParentBlock().hashMerkleRoot; const std::vector<uint256> vMerkleBranch = isAuxPowPOS() ? coinbasePOSTx.vMerkleBranch : coinbaseTx.vMerkleBranch; uint256 coinbaseTxHash = isAuxPowPOS() ? coinbasePOSTx.GetHash() : coinbaseTx.GetHash(); // Check that we are in the parent block merkle tree if (CheckMerkleBranch(coinbaseTxHash, vMerkleBranch, nIndex) != blockMerkleRoot) return error("Aux POW merkle root incorrect"); const CScript script = coinbaseTx.tx->vin[0].scriptSig; // Check that the same work is not submitted twice to our chain. // CScript::const_iterator pcHead = std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)); CScript::const_iterator pc = std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end()); if (pc == script.end()) return error("Aux POW missing chain merkle root in parent coinbase"); if (pcHead != script.end()) { // Enforce only one chain merkle root by checking that a single instance of the merged // mining header exists just before. if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader))) return error("Multiple merged mining headers in coinbase"); if (pcHead + sizeof(pchMergedMiningHeader) != pc) return error("Merged mining header is not just before chain merkle root"); } else { // For backward compatibility. // Enforce only one chain merkle root by checking that it starts early in the coinbase. // 8-12 bytes are enough to encode extraNonce and nBits. if (pc - script.begin() > 20) return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase"); } // Ensure we are at a deterministic point in the merkle leaves by hashing // a nonce and our chain ID and comparing to the index. pc += vchRootHash.size(); if (script.end() - pc < 8) return error("Aux POW missing chain merkle tree size and nonce in parent coinbase"); uint32_t nSize; memcpy(&nSize, &pc[0], 4); nSize = le32toh (nSize); const unsigned merkleHeight = vChainMerkleBranch.size (); if (nSize != (1u << merkleHeight)) return error("Aux POW merkle branch size does not match parent coinbase"); uint32_t nNonce; memcpy(&nNonce, &pc[4], 4); nNonce = le32toh (nNonce); if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight)) return error("Aux POW wrong index"); return true; } int CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h) { // Choose a pseudo-random slot in the chain merkle tree // but have it be fixed for a size/nonce/chain combination. // // This prevents the same work from being used twice for the // same chain while reducing the chance that two chains clash // for the same slot. /* This computation can overflow the uint32 used. This is not an issue, though, since we take the mod against a power-of-two in the end anyway. This also ensures that the computation is, actually, consistent even if done in 64 bits as it was in the past on some systems. Note that h is always <= 30 (enforced by the maximum allowed chain merkle branch length), so that 32 bits are enough for the computation. */ uint32_t rand = nNonce; rand = rand * 1103515245 + 12345; rand += nChainId; rand = rand * 1103515245 + 12345; return rand % (1u << h); } uint256 CAuxPow::CheckMerkleBranch (uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return uint256 (); for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ()); it != vMerkleBranch.end (); ++it) { if (nIndex & 1) hash = Hash (BEGIN (*it), END (*it), BEGIN (hash), END (hash)); else hash = Hash (BEGIN (hash), END (hash), BEGIN (*it), END (*it)); nIndex >>= 1; } return hash; } void CAuxPow::initAuxPow (CBlockHeader& header, uint32_t nAuxPowVersion) { /* Set auxpow flag right now, since we take the block hash below. */ header.SetAuxpowVersion(true); if((header.GetAlgo() == ALGO_EQUIHASH || header.GetAlgo() == ALGO_ZHASH) && (nAuxPowVersion & AUXPOW_EQUIHASH_FLAG)) { if(nAuxPowVersion & AUXPOW_STAKE_FLAG) { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutablePOSTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CPOSTransactionRef coinbaseRef = MakePOSTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CPOSEquihashBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = EquihashPOSBlockMerkleRoot (parent); /* Convert parent Block now into CDefaultBlock */ CEquihashBlockHeader equihashblock; equihashblock.nVersion = parent.nVersion; equihashblock.hashMerkleRoot = parent.hashMerkleRoot; /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbasePOSTx.vMerkleBranch.empty ()); header.auxpow->coinbasePOSTx.nIndex = 0; header.auxpow->equihashparentBlock = equihashblock; } else { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CEquihashBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = EquihashBlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbaseTx.vMerkleBranch.empty ()); header.auxpow->coinbaseTx.nIndex = 0; header.auxpow->equihashparentBlock = parent; } } else { if(nAuxPowVersion & AUXPOW_STAKE_FLAG) { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutablePOSTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CPOSTransactionRef coinbaseRef = MakePOSTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CPOSDefaultBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = DefaultPOSBlockMerkleRoot (parent); /* Convert parent Block now into CDefaultBlock */ CDefaultBlockHeader defaultblock; defaultblock.nVersion = parent.nVersion; defaultblock.hashMerkleRoot = parent.hashMerkleRoot; /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbasePOSTx.vMerkleBranch.empty ()); header.auxpow->coinbasePOSTx.nIndex = 0; header.auxpow->defaultparentBlock = defaultblock; } else { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CDefaultBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = DefaultBlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbaseTx.vMerkleBranch.empty ()); header.auxpow->coinbaseTx.nIndex = 0; header.auxpow->defaultparentBlock = parent; } } }<commit_msg>Fixed an Auxpow Bug<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2011 Vince Durham // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2017 Daniel Kraft // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <auxpow.h> #include <compat/endian.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <hash.h> #include <primitives/block.h> #include <script/script.h> #include <util.h> #include <utilstrencodings.h> #include <algorithm> #include <cassert> void CBaseMerkleTx::InitMerkleBranch(const CBlock& block, int posInBlock) { hashBlock = block.GetHash(); nIndex = posInBlock; vMerkleBranch = BlockMerkleBranch (block, nIndex); } bool CAuxPow::isAuxPowEquihash() const { return nVersion & AUXPOW_EQUIHASH_FLAG; } bool CAuxPow::isAuxPowPOS() const { return nVersion & AUXPOW_STAKE_FLAG; } bool CAuxPow::check (const uint256& hashAuxBlock, int nChainId, const Consensus::Params& params) const { bool fSameChainId = isAuxPowEquihash() ? (getEquihashParentBlock().GetChainId () == nChainId) : (getDefaultParentBlock().GetChainId () == nChainId); int nIndex = isAuxPowPOS() ? coinbasePOSTx.nIndex : coinbaseTx.nIndex; if (nIndex != 0) return error("AuxPow is not a generate"); if (params.fStrictChainId && fSameChainId) return error("Aux POW parent has our chain ID"); if (vChainMerkleBranch.size() > 30) return error("Aux POW chain merkle branch too long"); // Check that the chain merkle root is in the coinbase const uint256 nRootHash = CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch, nChainIndex); std::vector<unsigned char> vchRootHash(nRootHash.begin (), nRootHash.end ()); std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian const uint256 blockMerkleRoot = isAuxPowEquihash() ? getEquihashParentBlock().hashMerkleRoot : getDefaultParentBlock().hashMerkleRoot; const std::vector<uint256> vMerkleBranch = isAuxPowPOS() ? coinbasePOSTx.vMerkleBranch : coinbaseTx.vMerkleBranch; uint256 coinbaseTxHash = isAuxPowPOS() ? coinbasePOSTx.GetHash() : coinbaseTx.GetHash(); // Check that we are in the parent block merkle tree if (CheckMerkleBranch(coinbaseTxHash, vMerkleBranch, nIndex) != blockMerkleRoot) return error("Aux POW merkle root incorrect"); const CScript script = isAuxPowPOS() ? coinbasePOSTx.tx->vin[0].scriptSig : coinbaseTx.tx->vin[0].scriptSig; // Check that the same work is not submitted twice to our chain. // CScript::const_iterator pcHead = std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)); CScript::const_iterator pc = std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end()); if (pc == script.end()) return error("Aux POW missing chain merkle root in parent coinbase"); if (pcHead != script.end()) { // Enforce only one chain merkle root by checking that a single instance of the merged // mining header exists just before. if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader))) return error("Multiple merged mining headers in coinbase"); if (pcHead + sizeof(pchMergedMiningHeader) != pc) return error("Merged mining header is not just before chain merkle root"); } else { // For backward compatibility. // Enforce only one chain merkle root by checking that it starts early in the coinbase. // 8-12 bytes are enough to encode extraNonce and nBits. if (pc - script.begin() > 20) return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase"); } // Ensure we are at a deterministic point in the merkle leaves by hashing // a nonce and our chain ID and comparing to the index. pc += vchRootHash.size(); if (script.end() - pc < 8) return error("Aux POW missing chain merkle tree size and nonce in parent coinbase"); uint32_t nSize; memcpy(&nSize, &pc[0], 4); nSize = le32toh (nSize); const unsigned merkleHeight = vChainMerkleBranch.size (); if (nSize != (1u << merkleHeight)) return error("Aux POW merkle branch size does not match parent coinbase"); uint32_t nNonce; memcpy(&nNonce, &pc[4], 4); nNonce = le32toh (nNonce); if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight)) return error("Aux POW wrong index"); return true; } int CAuxPow::getExpectedIndex (uint32_t nNonce, int nChainId, unsigned h) { // Choose a pseudo-random slot in the chain merkle tree // but have it be fixed for a size/nonce/chain combination. // // This prevents the same work from being used twice for the // same chain while reducing the chance that two chains clash // for the same slot. /* This computation can overflow the uint32 used. This is not an issue, though, since we take the mod against a power-of-two in the end anyway. This also ensures that the computation is, actually, consistent even if done in 64 bits as it was in the past on some systems. Note that h is always <= 30 (enforced by the maximum allowed chain merkle branch length), so that 32 bits are enough for the computation. */ uint32_t rand = nNonce; rand = rand * 1103515245 + 12345; rand += nChainId; rand = rand * 1103515245 + 12345; return rand % (1u << h); } uint256 CAuxPow::CheckMerkleBranch (uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return uint256 (); for (std::vector<uint256>::const_iterator it(vMerkleBranch.begin ()); it != vMerkleBranch.end (); ++it) { if (nIndex & 1) hash = Hash (BEGIN (*it), END (*it), BEGIN (hash), END (hash)); else hash = Hash (BEGIN (hash), END (hash), BEGIN (*it), END (*it)); nIndex >>= 1; } return hash; } void CAuxPow::initAuxPow (CBlockHeader& header, uint32_t nAuxPowVersion) { /* Set auxpow flag right now, since we take the block hash below. */ header.SetAuxpowVersion(true); if((header.GetAlgo() == ALGO_EQUIHASH || header.GetAlgo() == ALGO_ZHASH) && (nAuxPowVersion & AUXPOW_EQUIHASH_FLAG)) { if(nAuxPowVersion & AUXPOW_STAKE_FLAG) { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutablePOSTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CPOSTransactionRef coinbaseRef = MakePOSTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CPOSEquihashBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = EquihashPOSBlockMerkleRoot (parent); /* Convert parent Block now into CDefaultBlock */ CEquihashBlockHeader equihashblock; equihashblock.nVersion = parent.nVersion; equihashblock.hashMerkleRoot = parent.hashMerkleRoot; /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbasePOSTx.vMerkleBranch.empty ()); header.auxpow->coinbasePOSTx.nIndex = 0; header.auxpow->equihashparentBlock = equihashblock; } else { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CEquihashBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = EquihashBlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbaseTx.vMerkleBranch.empty ()); header.auxpow->coinbaseTx.nIndex = 0; header.auxpow->equihashparentBlock = parent; } } else { if(nAuxPowVersion & AUXPOW_STAKE_FLAG) { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutablePOSTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CPOSTransactionRef coinbaseRef = MakePOSTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CPOSDefaultBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = DefaultPOSBlockMerkleRoot (parent); /* Convert parent Block now into CDefaultBlock */ CDefaultBlockHeader defaultblock; defaultblock.nVersion = parent.nVersion; defaultblock.hashMerkleRoot = parent.hashMerkleRoot; /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbasePOSTx.vMerkleBranch.empty ()); header.auxpow->coinbasePOSTx.nIndex = 0; header.auxpow->defaultparentBlock = defaultblock; } else { /* Build a minimal coinbase script input for merge-mining. */ const uint256 blockHash = header.GetHash (); std::vector<unsigned char> inputData(blockHash.begin (), blockHash.end ()); std::reverse (inputData.begin (), inputData.end ()); inputData.push_back (1); inputData.insert (inputData.end (), 7, 0); /* Fake a parent-block coinbase with just the required input script and no outputs. */ CMutableTransaction coinbase; coinbase.vin.resize (1); coinbase.vin[0].prevout.SetNull (); coinbase.vin[0].scriptSig = (CScript () << inputData); assert (coinbase.vout.empty ()); CTransactionRef coinbaseRef = MakeTransactionRef (coinbase); /* Build a fake parent block with the coinbase. */ CDefaultBlock parent; parent.nVersion = 1; parent.vtx.resize (1); parent.vtx[0] = coinbaseRef; parent.hashMerkleRoot = DefaultBlockMerkleRoot (parent); /* Construct the auxpow object. */ header.SetAuxpow (new CAuxPow (coinbaseRef)); header.auxpow->nVersion = nAuxPowVersion; assert (header.auxpow->vChainMerkleBranch.empty ()); header.auxpow->nChainIndex = 0; assert (header.auxpow->coinbaseTx.vMerkleBranch.empty ()); header.auxpow->coinbaseTx.nIndex = 0; header.auxpow->defaultparentBlock = parent; } } }<|endoftext|>
<commit_before>/* * * Copyright 2015, 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 <chrono> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include <gtest/gtest.h> #include "src/core/lib/profiling/timers.h" #include "src/proto/grpc/testing/services.grpc.pb.h" #include "test/cpp/qps/client.h" #include "test/cpp/qps/interarrival.h" #include "test/cpp/qps/usage_timer.h" namespace grpc { namespace testing { static std::unique_ptr<BenchmarkService::Stub> BenchmarkStubCreator( std::shared_ptr<Channel> ch) { return BenchmarkService::NewStub(ch); } class SynchronousClient : public ClientImpl<BenchmarkService::Stub, SimpleRequest> { public: SynchronousClient(const ClientConfig& config) : ClientImpl<BenchmarkService::Stub, SimpleRequest>( config, BenchmarkStubCreator) { num_threads_ = config.outstanding_rpcs_per_channel() * config.client_channels(); responses_.resize(num_threads_); SetupLoadTest(config, num_threads_); } virtual ~SynchronousClient(){}; protected: // WaitToIssue returns false if we realize that we need to break out bool WaitToIssue(int thread_idx) { if (!closed_loop_) { const gpr_timespec next_issue_time = NextIssueTime(thread_idx); // Avoid sleeping for too long continuously because we might // need to terminate before then. This is an issue since // exponential distribution can occasionally produce bad outliers while (true) { const gpr_timespec one_sec_delay = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), gpr_time_from_seconds(1, GPR_TIMESPAN)); if (gpr_time_cmp(next_issue_time, one_sec_delay) <= 0) { gpr_sleep_until(next_issue_time); return true; } else { gpr_sleep_until(one_sec_delay); if (gpr_atm_acq_load(&thread_pool_done_) != static_cast<gpr_atm>(0)) { return false; } } } } return true; } size_t num_threads_; std::vector<SimpleResponse> responses_; private: void DestroyMultithreading() GRPC_OVERRIDE GRPC_FINAL { EndThreads(); } }; class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient { public: SynchronousUnaryClient(const ClientConfig& config) : SynchronousClient(config) { StartThreads(num_threads_); } ~SynchronousUnaryClient() {} bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { if (!WaitToIssue(thread_idx)) { return true; } auto* stub = channels_[thread_idx % channels_.size()].get_stub(); double start = UsageTimer::Now(); GPR_TIMER_SCOPE("SynchronousUnaryClient::ThreadFunc", 0); grpc::ClientContext context; grpc::Status s = stub->UnaryCall(&context, request_, &responses_[thread_idx]); entry->set_value((UsageTimer::Now() - start) * 1e9); if (!s.ok()) { gpr_log(GPR_ERROR, "RPC error: %d: %s", s.error_code(), s.error_message().c_str()); } return s.ok(); } }; class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient { public: SynchronousStreamingClient(const ClientConfig& config) : SynchronousClient(config) { context_ = new grpc::ClientContext[num_threads_]; stream_ = new std::unique_ptr< grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>>[num_threads_]; for (size_t thread_idx = 0; thread_idx < num_threads_; thread_idx++) { auto* stub = channels_[thread_idx % channels_.size()].get_stub(); stream_[thread_idx] = stub->StreamingCall(&context_[thread_idx]); } StartThreads(num_threads_); } ~SynchronousStreamingClient() { for (size_t i = 0; i < num_threads_; i++) { auto stream = &stream_[i]; if (*stream) { (*stream)->WritesDone(); Status s = (*stream)->Finish(); EXPECT_TRUE(s.ok()); if (!s.ok()) { gpr_log(GPR_ERROR, "Stream %zu received an error %s", i, s.error_message().c_str()); } } } delete[] stream_; delete[] context_; } bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { if (!WaitToIssue(thread_idx)) { return true; } GPR_TIMER_SCOPE("SynchronousStreamingClient::ThreadFunc", 0); double start = UsageTimer::Now(); if (stream_[thread_idx]->Write(request_) && stream_[thread_idx]->Read(&responses_[thread_idx])) { entry->set_value((UsageTimer::Now() - start) * 1e9); return true; } return false; } private: // These are both conceptually std::vector but cannot be for old compilers // that expect contained classes to support copy constructors grpc::ClientContext* context_; std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>>* stream_; }; std::unique_ptr<Client> CreateSynchronousUnaryClient( const ClientConfig& config) { return std::unique_ptr<Client>(new SynchronousUnaryClient(config)); } std::unique_ptr<Client> CreateSynchronousStreamingClient( const ClientConfig& config) { return std::unique_ptr<Client>(new SynchronousStreamingClient(config)); } } // namespace testing } // namespace grpc <commit_msg>Handle failed calls in sync client<commit_after>/* * * Copyright 2015, 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 <chrono> #include <memory> #include <mutex> #include <sstream> #include <string> #include <thread> #include <vector> #include <grpc++/channel.h> #include <grpc++/client_context.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <grpc/grpc.h> #include <grpc/support/alloc.h> #include <grpc/support/host_port.h> #include <grpc/support/log.h> #include <grpc/support/time.h> #include <gtest/gtest.h> #include "src/core/lib/profiling/timers.h" #include "src/proto/grpc/testing/services.grpc.pb.h" #include "test/cpp/qps/client.h" #include "test/cpp/qps/interarrival.h" #include "test/cpp/qps/usage_timer.h" namespace grpc { namespace testing { static std::unique_ptr<BenchmarkService::Stub> BenchmarkStubCreator( std::shared_ptr<Channel> ch) { return BenchmarkService::NewStub(ch); } class SynchronousClient : public ClientImpl<BenchmarkService::Stub, SimpleRequest> { public: SynchronousClient(const ClientConfig& config) : ClientImpl<BenchmarkService::Stub, SimpleRequest>( config, BenchmarkStubCreator) { num_threads_ = config.outstanding_rpcs_per_channel() * config.client_channels(); responses_.resize(num_threads_); SetupLoadTest(config, num_threads_); } virtual ~SynchronousClient(){}; protected: // WaitToIssue returns false if we realize that we need to break out bool WaitToIssue(int thread_idx) { if (!closed_loop_) { const gpr_timespec next_issue_time = NextIssueTime(thread_idx); // Avoid sleeping for too long continuously because we might // need to terminate before then. This is an issue since // exponential distribution can occasionally produce bad outliers while (true) { const gpr_timespec one_sec_delay = gpr_time_add(gpr_now(GPR_CLOCK_MONOTONIC), gpr_time_from_seconds(1, GPR_TIMESPAN)); if (gpr_time_cmp(next_issue_time, one_sec_delay) <= 0) { gpr_sleep_until(next_issue_time); return true; } else { gpr_sleep_until(one_sec_delay); if (gpr_atm_acq_load(&thread_pool_done_) != static_cast<gpr_atm>(0)) { return false; } } } } return true; } size_t num_threads_; std::vector<SimpleResponse> responses_; private: void DestroyMultithreading() GRPC_OVERRIDE GRPC_FINAL { EndThreads(); } }; class SynchronousUnaryClient GRPC_FINAL : public SynchronousClient { public: SynchronousUnaryClient(const ClientConfig& config) : SynchronousClient(config) { StartThreads(num_threads_); } ~SynchronousUnaryClient() {} bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { if (!WaitToIssue(thread_idx)) { return true; } auto* stub = channels_[thread_idx % channels_.size()].get_stub(); double start = UsageTimer::Now(); GPR_TIMER_SCOPE("SynchronousUnaryClient::ThreadFunc", 0); grpc::ClientContext context; grpc::Status s = stub->UnaryCall(&context, request_, &responses_[thread_idx]); entry->set_value((UsageTimer::Now() - start) * 1e9); entry->set_status(s.error_code()); return true; } }; class SynchronousStreamingClient GRPC_FINAL : public SynchronousClient { public: SynchronousStreamingClient(const ClientConfig& config) : SynchronousClient(config) { context_ = new grpc::ClientContext[num_threads_]; stream_ = new std::unique_ptr< grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>>[num_threads_]; for (size_t thread_idx = 0; thread_idx < num_threads_; thread_idx++) { auto* stub = channels_[thread_idx % channels_.size()].get_stub(); stream_[thread_idx] = stub->StreamingCall(&context_[thread_idx]); } StartThreads(num_threads_); } ~SynchronousStreamingClient() { for (size_t i = 0; i < num_threads_; i++) { auto stream = &stream_[i]; if (*stream) { (*stream)->WritesDone(); Status s = (*stream)->Finish(); EXPECT_TRUE(s.ok()); if (!s.ok()) { gpr_log(GPR_ERROR, "Stream %zu received an error %s", i, s.error_message().c_str()); } } } delete[] stream_; delete[] context_; } bool ThreadFunc(HistogramEntry* entry, size_t thread_idx) GRPC_OVERRIDE { if (!WaitToIssue(thread_idx)) { return true; } GPR_TIMER_SCOPE("SynchronousStreamingClient::ThreadFunc", 0); double start = UsageTimer::Now(); if (stream_[thread_idx]->Write(request_) && stream_[thread_idx]->Read(&responses_[thread_idx])) { entry->set_value((UsageTimer::Now() - start) * 1e9); return true; } return false; } private: // These are both conceptually std::vector but cannot be for old compilers // that expect contained classes to support copy constructors grpc::ClientContext* context_; std::unique_ptr<grpc::ClientReaderWriter<SimpleRequest, SimpleResponse>>* stream_; }; std::unique_ptr<Client> CreateSynchronousUnaryClient( const ClientConfig& config) { return std::unique_ptr<Client>(new SynchronousUnaryClient(config)); } std::unique_ptr<Client> CreateSynchronousStreamingClient( const ClientConfig& config) { return std::unique_ptr<Client>(new SynchronousStreamingClient(config)); } } // namespace testing } // namespace grpc <|endoftext|>
<commit_before>#ifndef _BACKUP_H_ #define _BACKUP_H_ #include "cmdline.hpp" class Backup { public: Backup(); Backup(const string &filename); bool execute(const vector<string>); //virtual bool isValid() = 0; }; #endif <commit_msg>added backup<commit_after>#ifndef _BACKUP_H_ #define _BACKUP_H_ #include "cmdline.hpp" class Backup { public: Backup(); Backup(const string &filename); bool execute(const vector<string> &lhs, const vector<string &rhs); //virtual bool isValid() = 0; }; #endif <|endoftext|>
<commit_before>/* Kopete Contactlist Model Copyright (c) 2007 by Aleix Pol <aleixpol@gmail.com> Copyright (c) 2008 by Matt Rogers <mattr@kde.org> Copyright (c) 2009 by Gustavo Pichorim Boiko <gustavo.boiko@kdemail.net> Kopete (c) 2002-2008 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "contactlistmodel.h" #include <QStandardItem> #include <QList> #include <QUuid> #include <QImage> #include <qimageblitz.h> #include <KIcon> #include <KDebug> #include <KLocale> #include <KIconLoader> #include "kopetegroup.h" #include "kopetepicture.h" #include "kopetemetacontact.h" #include "kopetecontactlist.h" #include "kopeteitembase.h" #include "kopeteappearancesettings.h" namespace Kopete { namespace UI { ContactListModel::ContactListModel( QObject* parent ) : QAbstractItemModel( parent ) { Kopete::ContactList* kcl = Kopete::ContactList::self(); connect( kcl, SIGNAL( metaContactAdded( Kopete::MetaContact* ) ), this, SLOT( addMetaContact( Kopete::MetaContact* ) ) ); connect( kcl, SIGNAL( groupAdded( Kopete::Group* ) ), this, SLOT( addGroup( Kopete::Group* ) ) ); } ContactListModel::~ContactListModel() { } void ContactListModel::addMetaContact( Kopete::MetaContact* contact ) { foreach( Kopete::Group* g, contact->groups() ) { int pos = m_groups.indexOf( g ); int groupMemberCount = m_contacts[g].count(); QModelIndex groupIndex = index( pos, 0, QModelIndex() ); beginInsertRows( groupIndex, groupMemberCount, groupMemberCount ); m_contacts[g].append(contact); connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(handleContactDataChange(Kopete::MetaContact*))); endInsertRows(); } /*connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(resetModel()));*/ } void ContactListModel::removeMetaContact( Kopete::MetaContact* contact ) { /*disconnect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(resetModel()) );*/ disconnect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(handleContactDataChange(Kopete::MetaContact*))); } void ContactListModel::addGroup( Kopete::Group* group ) { kDebug(14001) << "addGroup" << group->displayName(); beginInsertRows( QModelIndex(), rowCount(), rowCount() ); m_groups.append( group ); m_contacts[group] = QList<Kopete::MetaContact*>(); endInsertRows(); } void ContactListModel::removeGroup( Kopete::Group* group ) { int pos = m_groups.indexOf( group ); beginRemoveRows( QModelIndex(), pos, pos ); m_groups.removeAt( m_groups.indexOf( group ) ); m_contacts.remove( group ); endRemoveRows(); } int ContactListModel::childCount( const QModelIndex& parent ) const { int cnt = 0; if ( !parent.isValid() ) { //Number of groups cnt = m_groups.count(); } else { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); if (g) cnt = m_contacts[g].count(); } return cnt; } int ContactListModel::rowCount( const QModelIndex& parent ) const { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); int cnt = 0; if ( !parent.isValid() ) { //Number of groups and contacts cnt = m_groups.count(); foreach( QList<Kopete::MetaContact*> l, m_contacts.values() ) cnt += l.count(); } else { if ( g ) cnt+= m_contacts[g].count(); } return cnt; } bool ContactListModel::hasChildren( const QModelIndex& parent ) const { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); bool res = false; if ( !parent.isValid() ) res=!m_groups.isEmpty(); else { if ( g ) { int row = parent.row(); Kopete::Group *g = m_groups[row]; res = !m_contacts[g].isEmpty(); } } return res; } QModelIndex ContactListModel::index( int row, int column, const QModelIndex & parent ) const { if ( row < 0 || row >= childCount( parent ) ) { return QModelIndex(); } Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>(cle); QModelIndex idx; Kopete::ContactListElement *itemPtr=0; if( !parent.isValid() ) itemPtr = m_groups[row]; else { if ( g ) itemPtr = m_contacts[g][row]; } idx = createIndex( row, column, itemPtr ); return idx; } int ContactListModel::countConnected(Kopete::Group* g) const { int onlineCount = 0; QList<Kopete::MetaContact*> metaContactList = m_contacts.value(g); QList<Kopete::MetaContact*>::const_iterator it, itEnd; itEnd = metaContactList.constEnd(); for (it = metaContactList.constBegin(); it != itEnd; ++it) { if ( (*it)->isOnline() ) onlineCount++; } return onlineCount; } QVariant ContactListModel::data ( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); using namespace Kopete; /* do all the casting up front. I need to profile to see how expensive this is though */ ContactListElement *cle = static_cast<ContactListElement*>( index.internalPointer() ); Group *g = qobject_cast<Group*>( cle ); MetaContact *mc = qobject_cast<MetaContact*>( cle ); QString display; QImage img; if ( g ) { switch ( role ) { case Qt::DisplayRole: display = i18n( "%1 (%2/%3)", g->displayName(), countConnected( g ), m_contacts[g].count() ); return display; break; case Qt::DecorationRole: if ( g->isExpanded() ) { if ( g->useCustomIcon() ) return g->icon(); else return KIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON ); } else { if ( g->useCustomIcon() ) return g->icon(); else return KIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON ); } break; case Kopete::Items::TypeRole: return Kopete::Items::Group; break; case Kopete::Items::UuidRole: return QUuid().toString(); break; case Kopete::Items::TotalCountRole: return g->members().count(); break; case Kopete::Items::ConnectedCountRole: return countConnected( g ); break; case Kopete::Items::OnlineStatusRole: return OnlineStatus::Unknown; break; } } if ( mc ) { switch ( role ) { case Qt::DisplayRole: display = mc->displayName(); return display; break; case Qt::DecorationRole: return metaContactImage( mc ); break; case Kopete::Items::TypeRole: return Kopete::Items::MetaContact; break; case Kopete::Items::UuidRole: return mc->metaContactId().toString(); break; case Kopete::Items::OnlineStatusRole: return mc->status(); break; } } return QVariant(); } Qt::ItemFlags ContactListModel::flags( const QModelIndex &index ) const { if ( !index.isValid() ) return 0; Qt::ItemFlags f(Qt::ItemIsEnabled); // if it is a contact item, add the selectable flag if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::MetaContact ) f |= Qt::ItemIsSelectable; return f; } QModelIndex ContactListModel::parent(const QModelIndex & index) const { QModelIndex parent; if(index.isValid()) { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( index.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); if ( !g ) { Kopete::MetaContact *mc = dynamic_cast<Kopete::MetaContact*>( cle ); parent = createIndex( 0, 0, mc->groups().last() ); } } return parent; } QModelIndexList ContactListModel::indexListFor(Kopete::ContactListElement *ce) const { QModelIndexList indexList; Kopete::MetaContact *mc = dynamic_cast<Kopete::MetaContact*>(ce); if (mc) { // metacontact handling // search for all the groups in which this contact is foreach( Kopete::Group *g, mc->groups() ) { int groupPos = m_groups.indexOf( g ); int mcPos = m_contacts[g].indexOf( mc ); // get the group index to be the parent for the contact search QModelIndex grpIndex = index(groupPos, 0); QModelIndex mcIndex = index(mcPos, 0, grpIndex); if (mcIndex.isValid()) indexList.append(mcIndex); } } else { // group handling Kopete::Group *g = dynamic_cast<Kopete::Group*>(ce); if (g) { int pos = m_groups.indexOf( g ); indexList.append(index(pos,0)); } } return indexList; } void ContactListModel::resetModel() { reset(); } void ContactListModel::handleContactDataChange(Kopete::MetaContact* mc) { QModelIndexList indexList; // we need to emit the dataChanged signal to the groups this metacontact belongs to // so that proxy filtering is aware of the changes foreach(Kopete::Group *g, mc->groups()) indexList += indexListFor(g); indexList += indexListFor(mc); // and now notify all the changes foreach(QModelIndex index, indexList) emit dataChanged(index, index); } QVariant ContactListModel::metaContactImage( Kopete::MetaContact* mc ) const { using namespace Kopete; QImage img; img = mc->picture().image(); int displayMode = AppearanceSettings::self()->contactListDisplayMode(); int iconMode = AppearanceSettings::self()->contactListIconMode(); int imageSize = IconSize( KIconLoader::Small ); bool usePhoto = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPhoto ); if ( displayMode == AppearanceSettings::EnumContactListDisplayMode::Detailed ) { imageSize = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPic ? KIconLoader::SizeMedium : KIconLoader::SizeLarge ); } else { imageSize = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPic ? IconSize( KIconLoader::Small ) : KIconLoader::SizeMedium ); } if ( usePhoto && !img.isNull() ) { img = img.scaled( imageSize, imageSize, Qt::KeepAspectRatio, Qt::SmoothTransformation ); if ( mc->status() == Kopete::OnlineStatus::Offline ) Blitz::grayscale(img); return img; } else { switch( mc->status() ) { case OnlineStatus::Online: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Online ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-online" ), imageSize ); break; case OnlineStatus::Away: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Away ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-away" ), imageSize ); break; case OnlineStatus::Unknown: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Unknown ), imageSize ); if ( mc->contacts().isEmpty() ) return SmallIcon( QString::fromUtf8( "metacontact_unknown" ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-offline" ), imageSize ); break; case OnlineStatus::Offline: default: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Offline ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-offline" ), imageSize ); break; } } return img; } } } #include "contactlistmodel.moc" //kate: tab-width 4 <commit_msg>For the root index rowCount should return just the toplevel items<commit_after>/* Kopete Contactlist Model Copyright (c) 2007 by Aleix Pol <aleixpol@gmail.com> Copyright (c) 2008 by Matt Rogers <mattr@kde.org> Copyright (c) 2009 by Gustavo Pichorim Boiko <gustavo.boiko@kdemail.net> Kopete (c) 2002-2008 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ************************************************************************* */ #include "contactlistmodel.h" #include <QStandardItem> #include <QList> #include <QUuid> #include <QImage> #include <qimageblitz.h> #include <KIcon> #include <KDebug> #include <KLocale> #include <KIconLoader> #include "kopetegroup.h" #include "kopetepicture.h" #include "kopetemetacontact.h" #include "kopetecontactlist.h" #include "kopeteitembase.h" #include "kopeteappearancesettings.h" namespace Kopete { namespace UI { ContactListModel::ContactListModel( QObject* parent ) : QAbstractItemModel( parent ) { Kopete::ContactList* kcl = Kopete::ContactList::self(); connect( kcl, SIGNAL( metaContactAdded( Kopete::MetaContact* ) ), this, SLOT( addMetaContact( Kopete::MetaContact* ) ) ); connect( kcl, SIGNAL( groupAdded( Kopete::Group* ) ), this, SLOT( addGroup( Kopete::Group* ) ) ); } ContactListModel::~ContactListModel() { } void ContactListModel::addMetaContact( Kopete::MetaContact* contact ) { foreach( Kopete::Group* g, contact->groups() ) { int pos = m_groups.indexOf( g ); int groupMemberCount = m_contacts[g].count(); QModelIndex groupIndex = index( pos, 0, QModelIndex() ); beginInsertRows( groupIndex, groupMemberCount, groupMemberCount ); m_contacts[g].append(contact); connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(handleContactDataChange(Kopete::MetaContact*))); endInsertRows(); } /*connect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(resetModel()));*/ } void ContactListModel::removeMetaContact( Kopete::MetaContact* contact ) { /*disconnect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(resetModel()) );*/ disconnect( contact, SIGNAL(onlineStatusChanged(Kopete::MetaContact*, Kopete::OnlineStatus::StatusType)), this, SLOT(handleContactDataChange(Kopete::MetaContact*))); } void ContactListModel::addGroup( Kopete::Group* group ) { kDebug(14001) << "addGroup" << group->displayName(); beginInsertRows( QModelIndex(), rowCount(), rowCount() ); m_groups.append( group ); m_contacts[group] = QList<Kopete::MetaContact*>(); endInsertRows(); } void ContactListModel::removeGroup( Kopete::Group* group ) { int pos = m_groups.indexOf( group ); beginRemoveRows( QModelIndex(), pos, pos ); m_groups.removeAt( m_groups.indexOf( group ) ); m_contacts.remove( group ); endRemoveRows(); } int ContactListModel::childCount( const QModelIndex& parent ) const { int cnt = 0; if ( !parent.isValid() ) { //Number of groups cnt = m_groups.count(); } else { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); if (g) cnt = m_contacts[g].count(); } return cnt; } int ContactListModel::rowCount( const QModelIndex& parent ) const { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); int cnt = 0; if ( !parent.isValid() ) cnt = m_groups.count(); else { if ( g ) cnt+= m_contacts[g].count(); } return cnt; } bool ContactListModel::hasChildren( const QModelIndex& parent ) const { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); bool res = false; if ( !parent.isValid() ) res=!m_groups.isEmpty(); else { if ( g ) { int row = parent.row(); Kopete::Group *g = m_groups[row]; res = !m_contacts[g].isEmpty(); } } return res; } QModelIndex ContactListModel::index( int row, int column, const QModelIndex & parent ) const { if ( row < 0 || row >= childCount( parent ) ) { return QModelIndex(); } Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( parent.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>(cle); QModelIndex idx; Kopete::ContactListElement *itemPtr=0; if( !parent.isValid() ) itemPtr = m_groups[row]; else { if ( g ) itemPtr = m_contacts[g][row]; } idx = createIndex( row, column, itemPtr ); return idx; } int ContactListModel::countConnected(Kopete::Group* g) const { int onlineCount = 0; QList<Kopete::MetaContact*> metaContactList = m_contacts.value(g); QList<Kopete::MetaContact*>::const_iterator it, itEnd; itEnd = metaContactList.constEnd(); for (it = metaContactList.constBegin(); it != itEnd; ++it) { if ( (*it)->isOnline() ) onlineCount++; } return onlineCount; } QVariant ContactListModel::data ( const QModelIndex & index, int role ) const { if ( !index.isValid() ) return QVariant(); using namespace Kopete; /* do all the casting up front. I need to profile to see how expensive this is though */ ContactListElement *cle = static_cast<ContactListElement*>( index.internalPointer() ); Group *g = qobject_cast<Group*>( cle ); MetaContact *mc = qobject_cast<MetaContact*>( cle ); QString display; QImage img; if ( g ) { switch ( role ) { case Qt::DisplayRole: display = i18n( "%1 (%2/%3)", g->displayName(), countConnected( g ), m_contacts[g].count() ); return display; break; case Qt::DecorationRole: if ( g->isExpanded() ) { if ( g->useCustomIcon() ) return g->icon(); else return KIcon( KOPETE_GROUP_DEFAULT_OPEN_ICON ); } else { if ( g->useCustomIcon() ) return g->icon(); else return KIcon( KOPETE_GROUP_DEFAULT_CLOSED_ICON ); } break; case Kopete::Items::TypeRole: return Kopete::Items::Group; break; case Kopete::Items::UuidRole: return QUuid().toString(); break; case Kopete::Items::TotalCountRole: return g->members().count(); break; case Kopete::Items::ConnectedCountRole: return countConnected( g ); break; case Kopete::Items::OnlineStatusRole: return OnlineStatus::Unknown; break; } } if ( mc ) { switch ( role ) { case Qt::DisplayRole: display = mc->displayName(); return display; break; case Qt::DecorationRole: return metaContactImage( mc ); break; case Kopete::Items::TypeRole: return Kopete::Items::MetaContact; break; case Kopete::Items::UuidRole: return mc->metaContactId().toString(); break; case Kopete::Items::OnlineStatusRole: return mc->status(); break; } } return QVariant(); } Qt::ItemFlags ContactListModel::flags( const QModelIndex &index ) const { if ( !index.isValid() ) return 0; Qt::ItemFlags f(Qt::ItemIsEnabled); // if it is a contact item, add the selectable flag if ( index.data( Kopete::Items::TypeRole ) == Kopete::Items::MetaContact ) f |= Qt::ItemIsSelectable; return f; } QModelIndex ContactListModel::parent(const QModelIndex & index) const { QModelIndex parent; if(index.isValid()) { Kopete::ContactListElement *cle = static_cast<Kopete::ContactListElement*>( index.internalPointer() ); Kopete::Group *g = dynamic_cast<Kopete::Group*>( cle ); if ( !g ) { Kopete::MetaContact *mc = dynamic_cast<Kopete::MetaContact*>( cle ); parent = createIndex( 0, 0, mc->groups().last() ); } } return parent; } QModelIndexList ContactListModel::indexListFor(Kopete::ContactListElement *ce) const { QModelIndexList indexList; Kopete::MetaContact *mc = dynamic_cast<Kopete::MetaContact*>(ce); if (mc) { // metacontact handling // search for all the groups in which this contact is foreach( Kopete::Group *g, mc->groups() ) { int groupPos = m_groups.indexOf( g ); int mcPos = m_contacts[g].indexOf( mc ); // get the group index to be the parent for the contact search QModelIndex grpIndex = index(groupPos, 0); QModelIndex mcIndex = index(mcPos, 0, grpIndex); if (mcIndex.isValid()) indexList.append(mcIndex); } } else { // group handling Kopete::Group *g = dynamic_cast<Kopete::Group*>(ce); if (g) { int pos = m_groups.indexOf( g ); indexList.append(index(pos,0)); } } return indexList; } void ContactListModel::resetModel() { reset(); } void ContactListModel::handleContactDataChange(Kopete::MetaContact* mc) { QModelIndexList indexList; // we need to emit the dataChanged signal to the groups this metacontact belongs to // so that proxy filtering is aware of the changes foreach(Kopete::Group *g, mc->groups()) indexList += indexListFor(g); indexList += indexListFor(mc); // and now notify all the changes foreach(QModelIndex index, indexList) emit dataChanged(index, index); } QVariant ContactListModel::metaContactImage( Kopete::MetaContact* mc ) const { using namespace Kopete; QImage img; img = mc->picture().image(); int displayMode = AppearanceSettings::self()->contactListDisplayMode(); int iconMode = AppearanceSettings::self()->contactListIconMode(); int imageSize = IconSize( KIconLoader::Small ); bool usePhoto = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPhoto ); if ( displayMode == AppearanceSettings::EnumContactListDisplayMode::Detailed ) { imageSize = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPic ? KIconLoader::SizeMedium : KIconLoader::SizeLarge ); } else { imageSize = ( iconMode == AppearanceSettings::EnumContactListIconMode::IconPic ? IconSize( KIconLoader::Small ) : KIconLoader::SizeMedium ); } if ( usePhoto && !img.isNull() ) { img = img.scaled( imageSize, imageSize, Qt::KeepAspectRatio, Qt::SmoothTransformation ); if ( mc->status() == Kopete::OnlineStatus::Offline ) Blitz::grayscale(img); return img; } else { switch( mc->status() ) { case OnlineStatus::Online: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Online ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-online" ), imageSize ); break; case OnlineStatus::Away: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Away ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-away" ), imageSize ); break; case OnlineStatus::Unknown: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Unknown ), imageSize ); if ( mc->contacts().isEmpty() ) return SmallIcon( QString::fromUtf8( "metacontact_unknown" ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-offline" ), imageSize ); break; case OnlineStatus::Offline: default: if( mc->useCustomIcon() ) return SmallIcon( mc->icon( ContactListElement::Offline ), imageSize ); else return SmallIcon( QString::fromUtf8( "user-offline" ), imageSize ); break; } } return img; } } } #include "contactlistmodel.moc" //kate: tab-width 4 <|endoftext|>
<commit_before>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <tuple> namespace gnr { template <typename F, typename ...A> constexpr auto invoke_all(F f, A&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } template <typename F, typename ...A> constexpr auto invoke_cond(F f, A&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } template <std::size_t M> constexpr void invoke_split(auto f, auto&& ...a) { constexpr auto split([]<std::size_t N>(auto&& t) noexcept requires (bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::make_tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } ); std::apply([&](auto&& ...t) noexcept(noexcept( (std::apply(f, std::forward<decltype(t)>(t)), ...))) { (std::apply(f, std::forward<decltype(t)>(t)), ...); }, split.template operator()<M>(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <commit_msg>some fixes<commit_after>#ifndef GNR_INVOKE_HPP # define GNR_INVOKE_HPP # pragma once #include <tuple> namespace gnr { template <typename F, typename ...A> constexpr auto invoke_all(F f, A&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { (f(std::forward<decltype(a)>(a)), ...); } template <typename F, typename ...A> constexpr auto invoke_cond(F f, A&& ...a) noexcept(noexcept( (f(std::forward<decltype(a)>(a)), ...))) { return (f(std::forward<decltype(a)>(a)) || ...); } template <std::size_t N> constexpr void invoke_split(auto f, auto&& ...a) { constexpr auto split([](auto&& t) noexcept requires (bool(N)) { constexpr auto n(std::tuple_size_v<std::remove_cvref_t<decltype(t)>>); static_assert(n && !(n % N)); return [&]<auto ...I>(std::index_sequence<I...>) noexcept { return std::make_tuple( [&]<auto ...J>(std::index_sequence<J...>) noexcept { constexpr auto K(N * I); return std::forward_as_tuple(std::get<K + J>(t)...); }(std::make_index_sequence<N + I - I>())... ); }(std::make_index_sequence<n / N>()); } ); std::apply([&](auto&& ...t) noexcept(noexcept( (std::apply(f, std::forward<decltype(t)>(t)), ...))) { (std::apply(f, std::forward<decltype(t)>(t)), ...); }, split(std::forward_as_tuple(a...)) ); } } #endif // GNR_INVOKE_HPP <|endoftext|>
<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef CROFBASE_HPP_ #define CROFBASE_HPP_ #define OF_DPA #include <sys/types.h> #include <sys/wait.h> #include <string> #include <iostream> #include <exception> #include <rofl/common/crofbase.h> #include "roflibs/netlink/cnetlink_observer.hpp" #include "roflibs/netlink/ofdpa_bridge.hpp" #include "roflibs/netlink/tap_manager.hpp" namespace basebox { class eBaseBoxBase : public std::runtime_error { public: eBaseBoxBase(const std::string &__arg) : std::runtime_error(__arg) {} }; static rofl::crofdpt invalid(NULL, rofl::cdptid(0)); class cbasebox : public rofl::crofbase, public virtual rofl::cthread_env, public rofcore::tap_callback, public rofcore::auto_reg_cnetlink_common_observer { enum ExperimenterMessageType { QUERY_FLOW_ENTRIES, ///< query flow entries from controller RECEIVED_FLOW_ENTRIES_QUERY }; enum ExperimenterId { BISDN = 0xFF0000B0 ///< should be registered as ONF-Managed Experimenter ID ///(OUI) }; static bool keep_on_running; rofl::cthread thread; /** * */ cbasebox(const rofl::openflow::cofhello_elem_versionbitmap &versionbitmap = rofl::openflow::cofhello_elem_versionbitmap()) : thread(this), fm_driver(), bridge(fm_driver) { rofl::crofbase::set_versionbitmap(versionbitmap); thread.start(); tap_man = new rofcore::tap_manager(); } /** * */ ~cbasebox() override { delete tap_man; } /** * */ cbasebox(const cbasebox &ethbase); public: /** * */ static cbasebox &get_instance( const rofl::openflow::cofhello_elem_versionbitmap &versionbitmap = rofl::openflow::cofhello_elem_versionbitmap()) { static cbasebox box(versionbitmap); return box; } static bool running() { return keep_on_running; } static void stop() { keep_on_running = false; }; protected: void handle_wakeup(rofl::cthread &thread) override; void handle_conn_established(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override { dpt.set_conn(auxid).set_trace(true); crofbase::add_ctl(rofl::cctlid(0)) .set_conn(rofl::cauxid(0)) .set_trace(true) .set_journal() .log_on_stderr(true) .set_max_entries(64); crofbase::set_ctl(rofl::cctlid(0)) .set_conn(rofl::cauxid(0)) .set_tcp_journal() .log_on_stderr(true) .set_max_entries(16); } void handle_dpt_open(rofl::crofdpt &dpt) override; void handle_dpt_close(const rofl::cdptid &dptid) override; void handle_conn_terminated(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_refused(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_failed(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_negotiation_failed(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_congestion_occured(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_congestion_solved(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_features_reply(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_features_reply &msg) override; void handle_desc_stats_reply( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_desc_stats_reply &msg) override; void handle_packet_in(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_packet_in &msg) override; void handle_flow_removed(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_flow_removed &msg) override; void handle_port_status(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_port_status &msg) override; void handle_error_message(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_error &msg) override; void handle_port_desc_stats_reply( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_port_desc_stats_reply &msg) override; void handle_port_desc_stats_reply_timeout(rofl::crofdpt &dpt, uint32_t xid) override; void handle_experimenter_message( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_experimenter &msg) override; public: friend std::ostream &operator<<(std::ostream &os, const cbasebox &box) { os << rofcore::indent(0) << "<cbasebox>" << std::endl; return os; } private: rofl::cdptid dptid; rofcore::tap_manager *tap_man; rofl::rofl_ofdpa_fm_driver fm_driver; ofdpa_bridge bridge; std::map<int, uint32_t> port_id_to_of_port; std::map<uint32_t, int> of_port_to_port_id; /* IO */ int enqueue(rofcore::ctapdev *netdev, rofl::cpacket *pkt) override; /* OF handler */ void handle_srcmac_table(rofl::crofdpt &dpt, rofl::openflow::cofmsg_packet_in &msg); void handle_acl_policy_table(rofl::crofdpt &dpt, rofl::openflow::cofmsg_packet_in &msg); void handle_bridging_table_rm(rofl::crofdpt &dpt, rofl::openflow::cofmsg_flow_removed &msg); void init(rofl::crofdpt &dpt); void send_full_state(rofl::crofdpt &dpt); /* netlink */ void link_created(unsigned int ifindex) noexcept override; void link_updated(const rofcore::crtlink &newlink) noexcept override; void link_deleted(unsigned int ifindex) noexcept override; void neigh_ll_created(unsigned int ifindex, uint16_t nbindex) noexcept override; void neigh_ll_updated(unsigned int ifindex, uint16_t nbindex) noexcept override; void neigh_ll_deleted(unsigned int ifindex, uint16_t nbindex) noexcept override; }; // class cbasebox } // end of namespace basebox #endif /* CROFBASE_HPP_ */ <commit_msg>cbasebox: cleanup header<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef CROFBASE_HPP_ #define CROFBASE_HPP_ #include <sys/types.h> #include <sys/wait.h> #include <string> #include <iostream> #include <exception> #include <rofl/common/crofbase.h> #include "roflibs/netlink/cnetlink_observer.hpp" #include "roflibs/netlink/ofdpa_bridge.hpp" #include "roflibs/netlink/tap_manager.hpp" namespace basebox { class eBaseBoxBase : public std::runtime_error { public: eBaseBoxBase(const std::string &__arg) : std::runtime_error(__arg) {} }; static rofl::crofdpt invalid(NULL, rofl::cdptid(0)); class cbasebox : public rofl::crofbase, public virtual rofl::cthread_env, public rofcore::tap_callback, public rofcore::auto_reg_cnetlink_common_observer { enum ExperimenterMessageType { QUERY_FLOW_ENTRIES, ///< query flow entries from controller RECEIVED_FLOW_ENTRIES_QUERY }; enum ExperimenterId { BISDN = 0xFF0000B0 ///< should be registered as ONF-Managed Experimenter ID ///(OUI) }; static bool keep_on_running; rofl::cthread thread; /** * */ cbasebox(const rofl::openflow::cofhello_elem_versionbitmap &versionbitmap = rofl::openflow::cofhello_elem_versionbitmap()) : thread(this), fm_driver(), bridge(fm_driver) { rofl::crofbase::set_versionbitmap(versionbitmap); thread.start(); tap_man = new rofcore::tap_manager(); } /** * */ ~cbasebox() override { delete tap_man; } /** * */ cbasebox(const cbasebox &ethbase); public: /** * */ static cbasebox &get_instance( const rofl::openflow::cofhello_elem_versionbitmap &versionbitmap = rofl::openflow::cofhello_elem_versionbitmap()) { static cbasebox box(versionbitmap); return box; } static bool running() { return keep_on_running; } static void stop() { keep_on_running = false; } protected: void handle_wakeup(rofl::cthread &thread) override; void handle_conn_established(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override { dpt.set_conn(auxid).set_trace(true); crofbase::add_ctl(rofl::cctlid(0)) .set_conn(rofl::cauxid(0)) .set_trace(true) .set_journal() .log_on_stderr(true) .set_max_entries(64); crofbase::set_ctl(rofl::cctlid(0)) .set_conn(rofl::cauxid(0)) .set_tcp_journal() .log_on_stderr(true) .set_max_entries(16); } void handle_dpt_open(rofl::crofdpt &dpt) override; void handle_dpt_close(const rofl::cdptid &dptid) override; void handle_conn_terminated(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_refused(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_failed(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_negotiation_failed(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_congestion_occured(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_conn_congestion_solved(rofl::crofdpt &dpt, const rofl::cauxid &auxid) override; void handle_features_reply(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_features_reply &msg) override; void handle_desc_stats_reply( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_desc_stats_reply &msg) override; void handle_packet_in(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_packet_in &msg) override; void handle_flow_removed(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_flow_removed &msg) override; void handle_port_status(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_port_status &msg) override; void handle_error_message(rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_error &msg) override; void handle_port_desc_stats_reply( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_port_desc_stats_reply &msg) override; void handle_port_desc_stats_reply_timeout(rofl::crofdpt &dpt, uint32_t xid) override; void handle_experimenter_message( rofl::crofdpt &dpt, const rofl::cauxid &auxid, rofl::openflow::cofmsg_experimenter &msg) override; public: friend std::ostream &operator<<(std::ostream &os, const cbasebox &box) { os << rofcore::indent(0) << "<cbasebox>" << std::endl; return os; } private: rofl::cdptid dptid; rofcore::tap_manager *tap_man; rofl::rofl_ofdpa_fm_driver fm_driver; ofdpa_bridge bridge; std::map<int, uint32_t> port_id_to_of_port; std::map<uint32_t, int> of_port_to_port_id; /* IO */ int enqueue(rofcore::ctapdev *netdev, rofl::cpacket *pkt) override; /* OF handler */ void handle_srcmac_table(rofl::crofdpt &dpt, rofl::openflow::cofmsg_packet_in &msg); void handle_acl_policy_table(rofl::crofdpt &dpt, rofl::openflow::cofmsg_packet_in &msg); void handle_bridging_table_rm(rofl::crofdpt &dpt, rofl::openflow::cofmsg_flow_removed &msg); void init(rofl::crofdpt &dpt); void send_full_state(rofl::crofdpt &dpt); /* netlink */ void link_created(unsigned int ifindex) noexcept override; void link_updated(const rofcore::crtlink &newlink) noexcept override; void link_deleted(unsigned int ifindex) noexcept override; void neigh_ll_created(unsigned int ifindex, uint16_t nbindex) noexcept override; void neigh_ll_updated(unsigned int ifindex, uint16_t nbindex) noexcept override; void neigh_ll_deleted(unsigned int ifindex, uint16_t nbindex) noexcept override; }; // class cbasebox } // end of namespace basebox #endif /* CROFBASE_HPP_ */ <|endoftext|>
<commit_before>/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "memoryleak.h" #include <QDebug> #include <QSettings> #include <QTimer> #include "feedfilter.h" #include "feedmodel.h" #include "actions.h" #include "settings.h" #include "feedrelevance.h" #include "actionsproxy.h" #include "memoryleak-defines.h" // // Overview of McaFeedFilter // - records ids of hidden rows and filters them out of the model // const int LookbackDaysDefault = 30; const int SaveDelayMS = 1 * 1000; // slight delay to batch rapid requests // // public methods // McaFeedFilter::McaFeedFilter(QAbstractItemModel *source, QString serviceId, QObject *parent): QSortFilterProxyModel(parent) { setSourceModel(source); m_source = source; m_feedRelevance = 0; m_serviceId = serviceId; m_numDays = LookbackDaysDefault; m_hiddenByDate = new QSet<QString>[m_numDays]; m_dirty = false; load(); } McaFeedFilter::~McaFeedFilter() { if(0 != m_feedRelevance) { m_feedRelevance->release(m_panelName, m_serviceId); m_feedRelevance = 0; } delete m_source; delete []m_hiddenByDate; } int McaFeedFilter::lookback() { return m_numDays; } void McaFeedFilter::hide(QString uniqueid) { // handle date change while we're running if (QDate::currentDate() != m_lastDate) update(); m_hiddenByDate[m_lastIndex].insert(uniqueid); m_hidden.insert(uniqueid); invalidateFilter(); save(); } bool McaFeedFilter::isHidden(QString uniqueid) const { return m_hidden.contains(uniqueid); } void McaFeedFilter::clearHistory(QDateTime datetime) { if (datetime < m_earliestTime) return; m_earliestTime = datetime; invalidateFilter(); save(); } bool McaFeedFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { Q_UNUSED(source_parent) // filter out hidden items QModelIndex sourceIndex = m_source->index(source_row, 0); QDateTime timestamp = m_source->data(sourceIndex, McaFeedModel::RequiredTimestampRole).toDateTime(); if (timestamp < m_earliestTime) { static bool first = true; if (first) { qDebug() << "Ignoring some items from service" << m_serviceId << "due to age"; first = false; } return false; } return !isHidden(m_source->data(sourceIndex, McaFeedModel::RequiredUniqueIdRole).toString()); } QVariant McaFeedFilter::data(const QModelIndex &index, int role) const { if (role == McaFeedModel::CommonActionsRole) { QVariant variantActions = m_source->data(index, McaFeedModel::CommonActionsRole); McaActions *actions = variantActions.value<McaActions*>(); if (!actions) return variantActions; // return our own McaActions to catch all actions McaActions *proxyActions = actions->findChild<McaActions*>("proxyAction"); if(0 == proxyActions) { // set parent to real actions object and let Qt delete this proxyActions = new McaActions(); proxyActions->moveToThread(actions->thread()); proxyActions->setParent(actions); proxyActions->setObjectName("proxyAction"); // copy any custom actions exist // TODO: what happens if more actions are added to the original object? QStringList actionNames = actions->customDisplayActions(); QStringList actionIds = actions->customActions(); for(int i=0; i < actionNames.length(); i++) { proxyActions->addCustomAction(actionIds.at(i), actionNames.at(i), actions->actionType(actionIds.at(i))); } connect(proxyActions, SIGNAL(standardAction(QString,QString)), this, SLOT(performStandardAction(QString,QString))); connect(proxyActions, SIGNAL(customAction(QString,QString)), this, SLOT(performCustomAction(QString,QString))); } return QVariant::fromValue<McaActions*>(proxyActions); } return QSortFilterProxyModel::data(index, role); } void McaFeedFilter::setPanelName(const QString &panelName) { if(m_panelName == panelName) return; if(0 != m_feedRelevance) { m_feedRelevance->release(m_panelName, m_serviceId); } m_panelName = panelName; m_feedRelevance = FeedRelevance::instance(m_panelName, m_serviceId); } // // protected methods // void McaFeedFilter::clear() { m_lastIndex = 0; m_lastDate = QDate::currentDate(); for (int i = 0; i < m_numDays; i++) m_hiddenByDate[i].clear(); m_hidden.clear(); } void McaFeedFilter::load() { // load hidden item data from QSettings file clear(); QSettings settings(McaSettings::Organization, McaSettings::ApplicationHide); settings.beginGroup(m_serviceId); QDateTime datetime = QDateTime::currentDateTime().addDays(-LookbackDaysDefault); QVariant variant = settings.value(McaSettings::KeyEarliestTime); if (variant.isValid()) { QDateTime dt = variant.toDateTime(); if (dt > datetime) datetime = dt; } m_earliestTime = datetime; QDate date = settings.value(McaSettings::KeyLastDate).toDate(); if (!date.isValid()) return; m_lastDate = date; m_lastIndex = 0; QString hidden = McaSettings::KeyHiddenPrefix; for (int i = 0; i < m_numDays; i++) { int index = (m_lastIndex + m_numDays - i) % m_numDays; QString str = settings.value(hidden + QString::number(i)).toString(); if (!str.isEmpty()) { foreach (QString uniqueid, str.split(",", QString::SkipEmptyParts)) { m_hiddenByDate[index].insert(uniqueid); m_hidden.insert(uniqueid); } } date = date.addDays(-1); } settings.endGroup(); update(); } void McaFeedFilter::save() { if (!m_dirty) { QTimer::singleShot(SaveDelayMS, this, SLOT(saveNow())); m_dirty = true; } } void McaFeedFilter::saveNow() { // save hidden item data to QSettings file m_dirty = false; QSettings settings(McaSettings::Organization, McaSettings::ApplicationHide); settings.beginGroup(m_serviceId); settings.setValue(McaSettings::KeyLastDate, m_lastDate); settings.setValue(McaSettings::KeyEarliestTime, m_earliestTime); // hidden0 contains today's items, hidden1 contains yesterday's, etc. QString hidden = McaSettings::KeyHiddenPrefix; for (int i=0; i<m_numDays; i++) { int index = (m_lastIndex + m_numDays - i) % m_numDays; // add the hidden lines QStringList list; foreach (QString uniqueid, m_hiddenByDate[index]) list << uniqueid; settings.setValue(hidden + QString::number(i), list.join(",")); } settings.endGroup(); } void McaFeedFilter::update() { // handle date rollover since the last change to hidden item data QDate current = QDate::currentDate(); int days = m_lastDate.daysTo(current); if (days == 0) return; if (days < 0) { qWarning("new date earlier than expected"); return; } if (days > m_numDays - 1) { clear(); save(); return; } QDate earliest = current.addDays(-m_numDays + 1); for (int i=0; i<days; i++) { m_lastIndex = (m_lastIndex + 1) % m_numDays; m_hiddenByDate[m_lastIndex].clear(); } m_lastDate = current; save(); } // // protected slots // void McaFeedFilter::performStandardAction(QString action, QString uniqueid) { if (action == "hide") { hide(uniqueid); m_feedRelevance->negativeFeedback(uniqueid); return; } if (action == "setViewed") { m_feedRelevance->recordSeen(uniqueid); return; } m_feedRelevance->positiveFeedback(uniqueid); if(sender()) { McaActions *realActions = qobject_cast<McaActions*>(sender()->parent()); if(0 != realActions) { realActions->performCustomAction(action, uniqueid); } } } void McaFeedFilter::performCustomAction(QString action, QString uniqueid) { if(sender()) { McaActions *realActions = qobject_cast<McaActions*>(sender()->parent()); if(0 != realActions) { if(realActions->actionType(action)) { m_feedRelevance->positiveFeedback(uniqueid); } else { m_feedRelevance->negativeFeedback(uniqueid); } realActions->performCustomAction(action, uniqueid); } } } <commit_msg>Call standard action instead of custom action in feedfilter performStandardAction Fixes BMC#19038 - Friends panel items are no longer tappable<commit_after>/* * Copyright 2011 Intel Corporation. * * This program is licensed under the terms and conditions of the * Apache License, version 2.0. The full text of the Apache License is at * http://www.apache.org/licenses/LICENSE-2.0 */ #include "memoryleak.h" #include <QDebug> #include <QSettings> #include <QTimer> #include "feedfilter.h" #include "feedmodel.h" #include "actions.h" #include "settings.h" #include "feedrelevance.h" #include "actionsproxy.h" #include "memoryleak-defines.h" // // Overview of McaFeedFilter // - records ids of hidden rows and filters them out of the model // const int LookbackDaysDefault = 30; const int SaveDelayMS = 1 * 1000; // slight delay to batch rapid requests // // public methods // McaFeedFilter::McaFeedFilter(QAbstractItemModel *source, QString serviceId, QObject *parent): QSortFilterProxyModel(parent) { setSourceModel(source); m_source = source; m_feedRelevance = 0; m_serviceId = serviceId; m_numDays = LookbackDaysDefault; m_hiddenByDate = new QSet<QString>[m_numDays]; m_dirty = false; load(); } McaFeedFilter::~McaFeedFilter() { if(0 != m_feedRelevance) { m_feedRelevance->release(m_panelName, m_serviceId); m_feedRelevance = 0; } delete m_source; delete []m_hiddenByDate; } int McaFeedFilter::lookback() { return m_numDays; } void McaFeedFilter::hide(QString uniqueid) { // handle date change while we're running if (QDate::currentDate() != m_lastDate) update(); m_hiddenByDate[m_lastIndex].insert(uniqueid); m_hidden.insert(uniqueid); invalidateFilter(); save(); } bool McaFeedFilter::isHidden(QString uniqueid) const { return m_hidden.contains(uniqueid); } void McaFeedFilter::clearHistory(QDateTime datetime) { if (datetime < m_earliestTime) return; m_earliestTime = datetime; invalidateFilter(); save(); } bool McaFeedFilter::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const { Q_UNUSED(source_parent) // filter out hidden items QModelIndex sourceIndex = m_source->index(source_row, 0); QDateTime timestamp = m_source->data(sourceIndex, McaFeedModel::RequiredTimestampRole).toDateTime(); if (timestamp < m_earliestTime) { static bool first = true; if (first) { qDebug() << "Ignoring some items from service" << m_serviceId << "due to age"; first = false; } return false; } return !isHidden(m_source->data(sourceIndex, McaFeedModel::RequiredUniqueIdRole).toString()); } QVariant McaFeedFilter::data(const QModelIndex &index, int role) const { if (role == McaFeedModel::CommonActionsRole) { QVariant variantActions = m_source->data(index, McaFeedModel::CommonActionsRole); McaActions *actions = variantActions.value<McaActions*>(); if (!actions) return variantActions; // return our own McaActions to catch all actions McaActions *proxyActions = actions->findChild<McaActions*>("proxyAction"); if(0 == proxyActions) { // set parent to real actions object and let Qt delete this proxyActions = new McaActions(); proxyActions->moveToThread(actions->thread()); proxyActions->setParent(actions); proxyActions->setObjectName("proxyAction"); // copy any custom actions exist // TODO: what happens if more actions are added to the original object? QStringList actionNames = actions->customDisplayActions(); QStringList actionIds = actions->customActions(); for(int i=0; i < actionNames.length(); i++) { proxyActions->addCustomAction(actionIds.at(i), actionNames.at(i), actions->actionType(actionIds.at(i))); } connect(proxyActions, SIGNAL(standardAction(QString,QString)), this, SLOT(performStandardAction(QString,QString))); connect(proxyActions, SIGNAL(customAction(QString,QString)), this, SLOT(performCustomAction(QString,QString))); } return QVariant::fromValue<McaActions*>(proxyActions); } return QSortFilterProxyModel::data(index, role); } void McaFeedFilter::setPanelName(const QString &panelName) { if(m_panelName == panelName) return; if(0 != m_feedRelevance) { m_feedRelevance->release(m_panelName, m_serviceId); } m_panelName = panelName; m_feedRelevance = FeedRelevance::instance(m_panelName, m_serviceId); } // // protected methods // void McaFeedFilter::clear() { m_lastIndex = 0; m_lastDate = QDate::currentDate(); for (int i = 0; i < m_numDays; i++) m_hiddenByDate[i].clear(); m_hidden.clear(); } void McaFeedFilter::load() { // load hidden item data from QSettings file clear(); QSettings settings(McaSettings::Organization, McaSettings::ApplicationHide); settings.beginGroup(m_serviceId); QDateTime datetime = QDateTime::currentDateTime().addDays(-LookbackDaysDefault); QVariant variant = settings.value(McaSettings::KeyEarliestTime); if (variant.isValid()) { QDateTime dt = variant.toDateTime(); if (dt > datetime) datetime = dt; } m_earliestTime = datetime; QDate date = settings.value(McaSettings::KeyLastDate).toDate(); if (!date.isValid()) return; m_lastDate = date; m_lastIndex = 0; QString hidden = McaSettings::KeyHiddenPrefix; for (int i = 0; i < m_numDays; i++) { int index = (m_lastIndex + m_numDays - i) % m_numDays; QString str = settings.value(hidden + QString::number(i)).toString(); if (!str.isEmpty()) { foreach (QString uniqueid, str.split(",", QString::SkipEmptyParts)) { m_hiddenByDate[index].insert(uniqueid); m_hidden.insert(uniqueid); } } date = date.addDays(-1); } settings.endGroup(); update(); } void McaFeedFilter::save() { if (!m_dirty) { QTimer::singleShot(SaveDelayMS, this, SLOT(saveNow())); m_dirty = true; } } void McaFeedFilter::saveNow() { // save hidden item data to QSettings file m_dirty = false; QSettings settings(McaSettings::Organization, McaSettings::ApplicationHide); settings.beginGroup(m_serviceId); settings.setValue(McaSettings::KeyLastDate, m_lastDate); settings.setValue(McaSettings::KeyEarliestTime, m_earliestTime); // hidden0 contains today's items, hidden1 contains yesterday's, etc. QString hidden = McaSettings::KeyHiddenPrefix; for (int i=0; i<m_numDays; i++) { int index = (m_lastIndex + m_numDays - i) % m_numDays; // add the hidden lines QStringList list; foreach (QString uniqueid, m_hiddenByDate[index]) list << uniqueid; settings.setValue(hidden + QString::number(i), list.join(",")); } settings.endGroup(); } void McaFeedFilter::update() { // handle date rollover since the last change to hidden item data QDate current = QDate::currentDate(); int days = m_lastDate.daysTo(current); if (days == 0) return; if (days < 0) { qWarning("new date earlier than expected"); return; } if (days > m_numDays - 1) { clear(); save(); return; } QDate earliest = current.addDays(-m_numDays + 1); for (int i=0; i<days; i++) { m_lastIndex = (m_lastIndex + 1) % m_numDays; m_hiddenByDate[m_lastIndex].clear(); } m_lastDate = current; save(); } // // protected slots // void McaFeedFilter::performStandardAction(QString action, QString uniqueid) { if (action == "hide") { hide(uniqueid); m_feedRelevance->negativeFeedback(uniqueid); return; } if (action == "setViewed") { m_feedRelevance->recordSeen(uniqueid); return; } m_feedRelevance->positiveFeedback(uniqueid); if(sender()) { McaActions *realActions = qobject_cast<McaActions*>(sender()->parent()); if(0 != realActions) { realActions->performStandardAction(action, uniqueid); } } } void McaFeedFilter::performCustomAction(QString action, QString uniqueid) { if(sender()) { McaActions *realActions = qobject_cast<McaActions*>(sender()->parent()); if(0 != realActions) { if(realActions->actionType(action)) { m_feedRelevance->positiveFeedback(uniqueid); } else { m_feedRelevance->negativeFeedback(uniqueid); } realActions->performCustomAction(action, uniqueid); } } } <|endoftext|>
<commit_before>/** * @file fractile.cpp * * @date June, 2016 * @author Tack **/ #include "fractile.h" #include <iostream> #include <algorithm> #include <string> #include <boost/thread.hpp> #include "logger_factory.h" #include "plugin_factory.h" #include "json_parser.h" #include "fetcher.h" #include "ensemble.h" #include "radon.h" namespace himan { namespace plugin { fractile::fractile() { itsClearTextFormula = "%"; itsCudaEnabledCalculation = false; itsLogger = logger_factory::Instance()->GetLog("fractile"); } fractile::~fractile() { } void fractile::Process(const std::shared_ptr<const plugin_configuration> conf) { Init(conf); if(!itsConfiguration->GetValue("param").empty()) { itsParamName = itsConfiguration->GetValue("param"); } else { throw std::runtime_error("Fractile_plugin: param not specified."); exit(1); } auto r = GET_PLUGIN(radon); params calculatedParams; std::vector<std::string> fractiles = {"F0-","F10-","F25-","F50-","F75-","F90-","F100-"}; for (const std::string& fractile : fractiles) { r->RadonDB().Query("select param_name, univ_id from param_newbase_v where param_name = '" + fractile + itsParamName + "' and producer_id = " + boost::lexical_cast<std::string>(conf->TargetProducer().Id())); auto answer = r->RadonDB().FetchRow(); calculatedParams.push_back(param(answer[0],std::stoi(answer[1]))); } SetParams(calculatedParams); Start(); } void fractile::Calculate(std::shared_ptr<info> myTargetInfo, uint16_t threadIndex) { const int numForecasts = 51; std::vector<int> fractile = {0,10,25,50,75,90,100}; const std::string deviceType = "CPU"; auto threadedLogger = logger_factory::Instance()->GetLog("fractileThread # " + boost::lexical_cast<std::string>(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); threadedLogger->Info("Calculating time " + static_cast<std::string>(forecastTime.ValidDateTime()) + " level " + static_cast<std::string>(forecastLevel)); ensemble ens(param(itsParamName), numForecasts); try { ens.Fetch(itsConfiguration, forecastTime, forecastLevel); } catch (const HPExceptionType& e) { if (e == kFileDataNotFound) { throw std::runtime_error(ClassName() + " failed to find ensemble data"); } } myTargetInfo->ResetLocation(); ens.ResetLocation(); while (myTargetInfo->NextLocation() && ens.NextLocation()) { auto sortedValues = ens.SortedValues(); size_t targetInfoIndex = 0; for (auto i : fractile) { myTargetInfo->ParamIndex(targetInfoIndex); myTargetInfo->Value(sortedValues[i*(numForecasts-1)/100]); ++targetInfoIndex; } } threadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<std::string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<std::string> (myTargetInfo->Data().Size())); } } // plugin } // namespace <commit_msg>Specification of univ_id for target params not needed. DB request of univ_id removed from code.<commit_after>/** * @file fractile.cpp * * @date June, 2016 * @author Tack **/ #include "fractile.h" #include <iostream> #include <algorithm> #include <string> #include <boost/thread.hpp> #include "logger_factory.h" #include "plugin_factory.h" #include "json_parser.h" #include "fetcher.h" #include "ensemble.h" namespace himan { namespace plugin { fractile::fractile() { itsClearTextFormula = "%"; itsCudaEnabledCalculation = false; itsLogger = logger_factory::Instance()->GetLog("fractile"); } fractile::~fractile() { } void fractile::Process(const std::shared_ptr<const plugin_configuration> conf) { Init(conf); if(!itsConfiguration->GetValue("param").empty()) { itsParamName = itsConfiguration->GetValue("param"); } else { throw std::runtime_error("Fractile_plugin: param not specified."); exit(1); } auto r = GET_PLUGIN(radon); params calculatedParams; std::vector<std::string> fractiles = {"F0-","F10-","F25-","F50-","F75-","F90-","F100-"}; for (const std::string& fractile : fractiles) { calculatedParams.push_back(param(fractile + itsParamName)); } SetParams(calculatedParams); Start(); } void fractile::Calculate(std::shared_ptr<info> myTargetInfo, uint16_t threadIndex) { const int numForecasts = 51; std::vector<int> fractile = {0,10,25,50,75,90,100}; const std::string deviceType = "CPU"; auto threadedLogger = logger_factory::Instance()->GetLog("fractileThread # " + boost::lexical_cast<std::string>(threadIndex)); forecast_time forecastTime = myTargetInfo->Time(); level forecastLevel = myTargetInfo->Level(); threadedLogger->Info("Calculating time " + static_cast<std::string>(forecastTime.ValidDateTime()) + " level " + static_cast<std::string>(forecastLevel)); ensemble ens(param(itsParamName), numForecasts); try { ens.Fetch(itsConfiguration, forecastTime, forecastLevel); } catch (const HPExceptionType& e) { if (e == kFileDataNotFound) { throw std::runtime_error(ClassName() + " failed to find ensemble data"); } } myTargetInfo->ResetLocation(); ens.ResetLocation(); while (myTargetInfo->NextLocation() && ens.NextLocation()) { auto sortedValues = ens.SortedValues(); size_t targetInfoIndex = 0; for (auto i : fractile) { myTargetInfo->ParamIndex(targetInfoIndex); myTargetInfo->Value(sortedValues[i*(numForecasts-1)/100]); ++targetInfoIndex; } } threadedLogger->Info("[" + deviceType + "] Missing values: " + boost::lexical_cast<std::string> (myTargetInfo->Data().MissingCount()) + "/" + boost::lexical_cast<std::string> (myTargetInfo->Data().Size())); } } // plugin } // namespace <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <boost/python.hpp> #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/markers_symbolizer.hpp> #include <mapnik/parse_path.hpp> #include "mapnik_svg.hpp" #include "mapnik_enumeration.hpp" using mapnik::markers_symbolizer; using mapnik::symbolizer_with_image; using mapnik::path_processor_type; using mapnik::parse_path; namespace { using namespace boost::python; std::string get_filename(mapnik::markers_symbolizer const& symbolizer) { return path_processor_type::to_string(*symbolizer.get_filename()); } void set_filename(mapnik::markers_symbolizer & symbolizer, std::string const& file_expr) { symbolizer.set_filename(parse_path(file_expr)); } } struct markers_symbolizer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(markers_symbolizer const& p) { std::string filename = path_processor_type::to_string(*p.get_filename()); return boost::python::make_tuple(filename,mapnik::guess_type(filename)); } static boost::python::tuple getstate(markers_symbolizer const& p) { return boost::python::make_tuple(p.get_allow_overlap(), p.get_ignore_placement());//,p.get_opacity()); } static void setstate (markers_symbolizer& p, boost::python::tuple state) { using namespace boost::python; if (len(state) != 2) { PyErr_SetObject(PyExc_ValueError, ("expected 2-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } p.set_allow_overlap(extract<bool>(state[0])); p.set_ignore_placement(extract<bool>(state[1])); //p.set_opacity(extract<float>(state[2])); } }; void export_markers_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement") .value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT) .value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT) ; class_<markers_symbolizer>("MarkersSymbolizer", init<>("Default Markers Symbolizer - blue arrow")) .def (init<mapnik::path_expression_ptr>("<path expression ptr>")) //.def_pickle(markers_symbolizer_pickle_suite()) .add_property("filename", &get_filename, &set_filename) .add_property("allow_overlap", &markers_symbolizer::get_allow_overlap, &markers_symbolizer::set_allow_overlap) .add_property("spacing", &markers_symbolizer::get_spacing, &markers_symbolizer::set_spacing) .add_property("max_error", &markers_symbolizer::get_max_error, &markers_symbolizer::set_max_error) .add_property("opacity", &markers_symbolizer::get_opacity, &markers_symbolizer::set_opacity, "Set/get the text opacity") .add_property("ignore_placement", &markers_symbolizer::get_ignore_placement, &markers_symbolizer::set_ignore_placement) .add_property("transform", &mapnik::get_svg_transform<markers_symbolizer>, &mapnik::set_svg_transform<markers_symbolizer>) .add_property("width", &markers_symbolizer::get_width, &markers_symbolizer::set_width, "Set/get the marker width") .add_property("height", &markers_symbolizer::get_height, &markers_symbolizer::set_height, "Set/get the marker height") .add_property("fill", make_function(&markers_symbolizer::get_fill, return_value_policy<copy_const_reference>()), &markers_symbolizer::set_fill, "Set/get the marker fill color") .add_property("stroke", make_function(&markers_symbolizer::get_stroke, return_value_policy<copy_const_reference>()), &markers_symbolizer::set_stroke, "Set/get the marker stroke (outline)") .add_property("placement", &markers_symbolizer::get_marker_placement, &markers_symbolizer::set_marker_placement, "Set/get the marker placement") ; } <commit_msg>+ update python bindings for markers_symbolizer<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2010 Artem Pavlenko * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #include <boost/python.hpp> #include <mapnik/graphics.hpp> #include <mapnik/image_util.hpp> #include <mapnik/markers_symbolizer.hpp> #include <mapnik/parse_path.hpp> #include "mapnik_svg.hpp" #include "mapnik_enumeration.hpp" using mapnik::markers_symbolizer; using mapnik::symbolizer_with_image; using mapnik::path_processor_type; using mapnik::parse_path; namespace { using namespace boost::python; std::string get_filename(mapnik::markers_symbolizer const& symbolizer) { return path_processor_type::to_string(*symbolizer.get_filename()); } void set_filename(mapnik::markers_symbolizer & symbolizer, std::string const& file_expr) { symbolizer.set_filename(parse_path(file_expr)); } } struct markers_symbolizer_pickle_suite : boost::python::pickle_suite { static boost::python::tuple getinitargs(markers_symbolizer const& p) { std::string filename = path_processor_type::to_string(*p.get_filename()); return boost::python::make_tuple(filename,mapnik::guess_type(filename)); } static boost::python::tuple getstate(markers_symbolizer const& p) { return boost::python::make_tuple(p.get_allow_overlap(), p.get_ignore_placement());//,p.get_opacity()); } static void setstate (markers_symbolizer& p, boost::python::tuple state) { using namespace boost::python; if (len(state) != 2) { PyErr_SetObject(PyExc_ValueError, ("expected 2-item tuple in call to __setstate__; got %s" % state).ptr() ); throw_error_already_set(); } p.set_allow_overlap(extract<bool>(state[0])); p.set_ignore_placement(extract<bool>(state[1])); //p.set_opacity(extract<float>(state[2])); } }; void export_markers_symbolizer() { using namespace boost::python; mapnik::enumeration_<mapnik::marker_placement_e>("marker_placement") .value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT) .value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT) ; class_<markers_symbolizer>("MarkersSymbolizer", init<>("Default Markers Symbolizer - blue arrow")) .def (init<mapnik::path_expression_ptr>("<path expression ptr>")) //.def_pickle(markers_symbolizer_pickle_suite()) .add_property("filename", &get_filename, &set_filename) .add_property("allow_overlap", &markers_symbolizer::get_allow_overlap, &markers_symbolizer::set_allow_overlap) .add_property("spacing", &markers_symbolizer::get_spacing, &markers_symbolizer::set_spacing) .add_property("max_error", &markers_symbolizer::get_max_error, &markers_symbolizer::set_max_error) .add_property("opacity", &markers_symbolizer::get_opacity, &markers_symbolizer::set_opacity, "Set/get the text opacity") .add_property("ignore_placement", &markers_symbolizer::get_ignore_placement, &markers_symbolizer::set_ignore_placement) .add_property("transform", &mapnik::get_svg_transform<markers_symbolizer>, &mapnik::set_svg_transform<markers_symbolizer>) .add_property("width", make_function(&markers_symbolizer::get_width, return_value_policy<copy_const_reference>()), &markers_symbolizer::set_width, "Set/get the marker width") .add_property("height", make_function(&markers_symbolizer::get_height, return_value_policy<copy_const_reference>()), &markers_symbolizer::set_height, "Set/get the marker height") .add_property("fill", &markers_symbolizer::get_fill, &markers_symbolizer::set_fill, "Set/get the marker fill color") .add_property("stroke", &markers_symbolizer::get_stroke, &markers_symbolizer::set_stroke, "Set/get the marker stroke (outline)") .add_property("placement", &markers_symbolizer::get_marker_placement, &markers_symbolizer::set_marker_placement, "Set/get the marker placement") ; } <|endoftext|>
<commit_before>// // Copyright 2013 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License // and the following modification to it: Section 6 Trademarks. // deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the // trade names, trademarks, service marks, or product names of the // Licensor and its affiliates, except as required for reproducing // the content of the NOTICE file. // // 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 "../osd/cudaGLVertexBuffer.h" #include "../osd/error.h" #include "../osd/opengl.h" #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include <cassert> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { OsdCudaGLVertexBuffer::OsdCudaGLVertexBuffer(int numElements, int numVertices) : _numElements(numElements), _numVertices(numVertices), _vbo(0), _devicePtr(0), _cudaResource(0) { } OsdCudaGLVertexBuffer::~OsdCudaGLVertexBuffer() { unmap(); cudaGraphicsUnregisterResource(_cudaResource); glDeleteBuffers(1, &_vbo); } OsdCudaGLVertexBuffer * OsdCudaGLVertexBuffer::Create(int numElements, int numVertices) { OsdCudaGLVertexBuffer *instance = new OsdCudaGLVertexBuffer(numElements, numVertices); if (instance->allocate()) return instance; OsdError(OSD_CUDA_GL_ERROR,"OsdCudaGLVertexBuffer::Create failed.\n"); delete instance; return NULL; } void OsdCudaGLVertexBuffer::UpdateData(const float *src, int startVertex, int numVertices) { map(); cudaMemcpy((float*)_devicePtr + _numElements * startVertex, src, _numElements * numVertices * sizeof(float), cudaMemcpyHostToDevice); } int OsdCudaGLVertexBuffer::GetNumElements() const { return _numElements; } int OsdCudaGLVertexBuffer::GetNumVertices() const { return _numVertices; } float * OsdCudaGLVertexBuffer::BindCudaBuffer() { map(); return static_cast<float*>(_devicePtr); } GLuint OsdCudaGLVertexBuffer::BindVBO() { unmap(); return _vbo; } bool OsdCudaGLVertexBuffer::allocate() { int size = _numElements * _numVertices * sizeof(float); glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // register vbo as cuda resource cudaError_t err = cudaGraphicsGLRegisterBuffer( &_cudaResource, _vbo, cudaGraphicsMapFlagsWriteDiscard); if (err != cudaSuccess) return false; return true; } void OsdCudaGLVertexBuffer::map() { if (_devicePtr) return; size_t num_bytes; void *ptr; cudaError_t err = cudaGraphicsMapResources(1, &_cudaResource, 0); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::map failed.\n%s\n", cudaGetErrorString(err)); err = cudaGraphicsResourceGetMappedPointer(&ptr, &num_bytes, _cudaResource); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::map failed.\n%s\n", cudaGetErrorString(err)); _devicePtr = ptr; } void OsdCudaGLVertexBuffer::unmap() { if (_devicePtr == NULL) return; cudaError_t err = cudaGraphicsUnmapResources(1, &_cudaResource, 0); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::unmap failed.\n%s\n", cudaGetErrorString(err)); _devicePtr = NULL; } } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <commit_msg>Add an error check on updating cuda buffer.<commit_after>// // Copyright 2013 Pixar // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License // and the following modification to it: Section 6 Trademarks. // deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the // trade names, trademarks, service marks, or product names of the // Licensor and its affiliates, except as required for reproducing // the content of the NOTICE file. // // 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 "../osd/cudaGLVertexBuffer.h" #include "../osd/error.h" #include "../osd/opengl.h" #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include <cassert> namespace OpenSubdiv { namespace OPENSUBDIV_VERSION { OsdCudaGLVertexBuffer::OsdCudaGLVertexBuffer(int numElements, int numVertices) : _numElements(numElements), _numVertices(numVertices), _vbo(0), _devicePtr(0), _cudaResource(0) { } OsdCudaGLVertexBuffer::~OsdCudaGLVertexBuffer() { unmap(); cudaGraphicsUnregisterResource(_cudaResource); glDeleteBuffers(1, &_vbo); } OsdCudaGLVertexBuffer * OsdCudaGLVertexBuffer::Create(int numElements, int numVertices) { OsdCudaGLVertexBuffer *instance = new OsdCudaGLVertexBuffer(numElements, numVertices); if (instance->allocate()) return instance; OsdError(OSD_CUDA_GL_ERROR,"OsdCudaGLVertexBuffer::Create failed.\n"); delete instance; return NULL; } void OsdCudaGLVertexBuffer::UpdateData(const float *src, int startVertex, int numVertices) { map(); cudaError_t err = cudaMemcpy((float*)_devicePtr + _numElements * startVertex, src, _numElements * numVertices * sizeof(float), cudaMemcpyHostToDevice); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::UpdateData failed. : %s\n", cudaGetErrorString(err)); } int OsdCudaGLVertexBuffer::GetNumElements() const { return _numElements; } int OsdCudaGLVertexBuffer::GetNumVertices() const { return _numVertices; } float * OsdCudaGLVertexBuffer::BindCudaBuffer() { map(); return static_cast<float*>(_devicePtr); } GLuint OsdCudaGLVertexBuffer::BindVBO() { unmap(); return _vbo; } bool OsdCudaGLVertexBuffer::allocate() { int size = _numElements * _numVertices * sizeof(float); glGenBuffers(1, &_vbo); glBindBuffer(GL_ARRAY_BUFFER, _vbo); glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); // register vbo as cuda resource cudaError_t err = cudaGraphicsGLRegisterBuffer( &_cudaResource, _vbo, cudaGraphicsMapFlagsWriteDiscard); if (err != cudaSuccess) return false; return true; } void OsdCudaGLVertexBuffer::map() { if (_devicePtr) return; size_t num_bytes; void *ptr; cudaError_t err = cudaGraphicsMapResources(1, &_cudaResource, 0); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::map failed.\n%s\n", cudaGetErrorString(err)); err = cudaGraphicsResourceGetMappedPointer(&ptr, &num_bytes, _cudaResource); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::map failed.\n%s\n", cudaGetErrorString(err)); _devicePtr = ptr; } void OsdCudaGLVertexBuffer::unmap() { if (_devicePtr == NULL) return; cudaError_t err = cudaGraphicsUnmapResources(1, &_cudaResource, 0); if (err != cudaSuccess) OsdError(OSD_CUDA_GL_ERROR, "OsdCudaGLVertexBuffer::unmap failed.\n%s\n", cudaGetErrorString(err)); _devicePtr = NULL; } } // end namespace OPENSUBDIV_VERSION } // end namespace OpenSubdiv <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ /* e.g. export CC=afl-clang-fast export CXX=afl-clang-fast++ make cp workdir/LinkTarget/Executable/fftester instdir/program LD_LIBRARY_PATH=`pwd`/instdir/program SAL_USE_VCLPLUGIN=svp AFL_PERSISTENT=1 afl-fuzz -t 50 -i ~/fuzz/in.png -o ~/fuzz/out.png -d -T png -m 50000000 instdir/program/fftester @@ png On slower file formats like .doc you can probably drop the -t and rely on the estimations, on faster file formats ironically not specifing a timeout will result in a hillarious dramatic falloff in performance from thousands per second to teens per second as tiny variations from the initial calculated timeout will trigger a shutdown of the fftester and a restart and the startup time is woeful (hence the AFL_PERSISTENT mode in the first place) */ #include <sal/main.h> #include <tools/extendapplicationenvironment.hxx> #include <cppuhelper/bootstrap.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <unotools/configmgr.hxx> #include <vcl/dibtools.hxx> #include <vcl/event.hxx> #include <vcl/graphicfilter.hxx> #include <vcl/pngread.hxx> #include <vcl/svapp.hxx> #include <vcl/wmf.hxx> #include <vcl/wrkwin.hxx> #include <vcl/fltcall.hxx> #include <osl/file.hxx> #include <signal.h> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace cppu; extern bool ImportJPEG( SvStream& rInputStream, Graphic& rGraphic, void* pCallerData, GraphicFilterImportFlags nImportFlags ); extern bool ImportGIF( SvStream & rStm, Graphic& rGraphic ); extern bool ImportXBM( SvStream& rStream, Graphic& rGraphic ); extern bool ImportXPM( SvStream& rStm, Graphic& rGraphic ); extern "C" { static void SAL_CALL thisModule() {} } typedef bool (*WFilterCall)(const OUString &rUrl); /* This constant specifies the number of inputs to process before restarting. * This is optional, but helps limit the impact of memory leaks and similar * hiccups. */ #define PERSIST_MAX 1000 unsigned int persist_cnt; SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { int ret = -1; if (argc < 3) { fprintf(stderr, "Usage: fftester <filename> <wmf|jpg>\n"); return -1; } OUString in(argv[1], strlen(argv[1]), RTL_TEXTENCODING_UTF8); OUString out; osl::File::getFileURLFromSystemPath(in, out); tools::extendApplicationEnvironment(); Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext(); Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY ); if( !xServiceManager.is() ) Application::Abort( "Failed to bootstrap" ); comphelper::setProcessServiceFactory( xServiceManager ); utl::ConfigManager::EnableAvoidConfig(); InitVCL(); try_again: { if (strcmp(argv[2], "wmf") == 0 || strcmp(argv[2], "emf") == 0) { GDIMetaFile aGDIMetaFile; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ReadWindowMetafile(aFileStream, aGDIMetaFile); } else if (strcmp(argv[2], "jpg") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportJPEG(aFileStream, aGraphic, NULL, GraphicFilterImportFlags::NONE); } else if (strcmp(argv[2], "gif") == 0) { SvFileStream aFileStream(out, StreamMode::READ); Graphic aGraphic; ret = (int) ImportGIF(aFileStream, aGraphic); } else if (strcmp(argv[2], "xbm") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportXBM(aFileStream, aGraphic); } else if (strcmp(argv[2], "xpm") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportXPM(aFileStream, aGraphic); } else if (strcmp(argv[2], "png") == 0) { SvFileStream aFileStream(out, StreamMode::READ); vcl::PNGReader aReader(aFileStream); aReader.Read(); } else if (strcmp(argv[2], "bmp") == 0) { Bitmap aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ReadDIB(aTarget, aFileStream, true); } else if (strcmp(argv[2], "svm") == 0) { GDIMetaFile aGDIMetaFile; SvFileStream aFileStream(out, StreamMode::READ); ReadGDIMetaFile(aFileStream, aGDIMetaFile); } else if (strcmp(argv[2], "pcd") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libicdlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "dxf") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libidxlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "met") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libimelo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if ((strcmp(argv[2], "pbm") == 0) || strcmp(argv[2], "ppm") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipblo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "psd") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipdlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "eps") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipslo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "pct") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libiptlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "pcx") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipxlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "ras") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libiralo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "tga") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libitglo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "tif") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libitilo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "doc") == 0) { static WFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libmswordlo.so", SAL_LOADMODULE_LAZY); pfnImport = reinterpret_cast<WFilterCall>( aLibrary.getFunctionSymbol("TestImportDOC")); aLibrary.release(); } ret = (int) (*pfnImport)(out); } } /* To signal successful completion of a run, we need to deliver SIGSTOP to our own process, then loop to the very beginning once we're resumed by the supervisor process. We do this only if AFL_PERSISTENT is set to retain normal behavior when the program is executed directly; and take note of PERSIST_MAX. */ if (getenv("AFL_PERSISTENT") && persist_cnt++ < PERSIST_MAX) { raise(SIGSTOP); goto try_again; } /* If AFL_PERSISTENT not set or PERSIST_MAX exceeded, exit normally. */ _exit(ret); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>loplugin:externandnotdefined<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ /* e.g. export CC=afl-clang-fast export CXX=afl-clang-fast++ make cp workdir/LinkTarget/Executable/fftester instdir/program LD_LIBRARY_PATH=`pwd`/instdir/program SAL_USE_VCLPLUGIN=svp AFL_PERSISTENT=1 afl-fuzz -t 50 -i ~/fuzz/in.png -o ~/fuzz/out.png -d -T png -m 50000000 instdir/program/fftester @@ png On slower file formats like .doc you can probably drop the -t and rely on the estimations, on faster file formats ironically not specifing a timeout will result in a hillarious dramatic falloff in performance from thousands per second to teens per second as tiny variations from the initial calculated timeout will trigger a shutdown of the fftester and a restart and the startup time is woeful (hence the AFL_PERSISTENT mode in the first place) */ #include <sal/main.h> #include <tools/extendapplicationenvironment.hxx> #include <cppuhelper/bootstrap.hxx> #include <comphelper/processfactory.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <com/sun/star/uno/XComponentContext.hpp> #include <unotools/configmgr.hxx> #include <vcl/dibtools.hxx> #include <vcl/event.hxx> #include <vcl/graphicfilter.hxx> #include <vcl/pngread.hxx> #include <vcl/svapp.hxx> #include <vcl/wmf.hxx> #include <vcl/wrkwin.hxx> #include <vcl/fltcall.hxx> #include <osl/file.hxx> #include <signal.h> #include <../source/filter/igif/gifread.hxx> #include <../source/filter/ixbm/xbmread.hxx> #include <../source/filter/ixpm/xpmread.hxx> #include <../source/filter/jpeg/jpeg.hxx> using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; using namespace cppu; extern "C" { static void SAL_CALL thisModule() {} } typedef bool (*WFilterCall)(const OUString &rUrl); /* This constant specifies the number of inputs to process before restarting. * This is optional, but helps limit the impact of memory leaks and similar * hiccups. */ #define PERSIST_MAX 1000 unsigned int persist_cnt; SAL_IMPLEMENT_MAIN_WITH_ARGS(argc, argv) { int ret = -1; if (argc < 3) { fprintf(stderr, "Usage: fftester <filename> <wmf|jpg>\n"); return -1; } OUString in(argv[1], strlen(argv[1]), RTL_TEXTENCODING_UTF8); OUString out; osl::File::getFileURLFromSystemPath(in, out); tools::extendApplicationEnvironment(); Reference< XComponentContext > xContext = defaultBootstrap_InitialComponentContext(); Reference< XMultiServiceFactory > xServiceManager( xContext->getServiceManager(), UNO_QUERY ); if( !xServiceManager.is() ) Application::Abort( "Failed to bootstrap" ); comphelper::setProcessServiceFactory( xServiceManager ); utl::ConfigManager::EnableAvoidConfig(); InitVCL(); try_again: { if (strcmp(argv[2], "wmf") == 0 || strcmp(argv[2], "emf") == 0) { GDIMetaFile aGDIMetaFile; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ReadWindowMetafile(aFileStream, aGDIMetaFile); } else if (strcmp(argv[2], "jpg") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportJPEG(aFileStream, aGraphic, NULL, GraphicFilterImportFlags::NONE); } else if (strcmp(argv[2], "gif") == 0) { SvFileStream aFileStream(out, StreamMode::READ); Graphic aGraphic; ret = (int) ImportGIF(aFileStream, aGraphic); } else if (strcmp(argv[2], "xbm") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportXBM(aFileStream, aGraphic); } else if (strcmp(argv[2], "xpm") == 0) { Graphic aGraphic; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ImportXPM(aFileStream, aGraphic); } else if (strcmp(argv[2], "png") == 0) { SvFileStream aFileStream(out, StreamMode::READ); vcl::PNGReader aReader(aFileStream); aReader.Read(); } else if (strcmp(argv[2], "bmp") == 0) { Bitmap aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) ReadDIB(aTarget, aFileStream, true); } else if (strcmp(argv[2], "svm") == 0) { GDIMetaFile aGDIMetaFile; SvFileStream aFileStream(out, StreamMode::READ); ReadGDIMetaFile(aFileStream, aGDIMetaFile); } else if (strcmp(argv[2], "pcd") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libicdlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "dxf") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libidxlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "met") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libimelo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if ((strcmp(argv[2], "pbm") == 0) || strcmp(argv[2], "ppm") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipblo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "psd") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipdlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "eps") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipslo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "pct") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libiptlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "pcx") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libipxlo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "ras") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libiralo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "tga") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libitglo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "tif") == 0) { static PFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libitilo.so"); pfnImport = reinterpret_cast<PFilterCall>( aLibrary.getFunctionSymbol("GraphicImport")); aLibrary.release(); } Graphic aTarget; SvFileStream aFileStream(out, StreamMode::READ); ret = (int) (*pfnImport)(aFileStream, aTarget, NULL); } else if (strcmp(argv[2], "doc") == 0) { static WFilterCall pfnImport(0); if (!pfnImport) { osl::Module aLibrary; aLibrary.loadRelative(&thisModule, "libmswordlo.so", SAL_LOADMODULE_LAZY); pfnImport = reinterpret_cast<WFilterCall>( aLibrary.getFunctionSymbol("TestImportDOC")); aLibrary.release(); } ret = (int) (*pfnImport)(out); } } /* To signal successful completion of a run, we need to deliver SIGSTOP to our own process, then loop to the very beginning once we're resumed by the supervisor process. We do this only if AFL_PERSISTENT is set to retain normal behavior when the program is executed directly; and take note of PERSIST_MAX. */ if (getenv("AFL_PERSISTENT") && persist_cnt++ < PERSIST_MAX) { raise(SIGSTOP); goto try_again; } /* If AFL_PERSISTENT not set or PERSIST_MAX exceeded, exit normally. */ _exit(ret); } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before><commit_msg>dump more udev info<commit_after><|endoftext|>
<commit_before>// g++ -std=c++11 problem2.cpp && ./a.exe // output: // sum = 4613731 #include <iostream> int problem2(int num) { int sum = 0; for (int f1 = 1, f2 = 1; f2 < num; f2 += f1, f1 = f2 - f1) { if (f2 % 2 != 0) sum += f2; } return sum; } int main(int argc, char const* argv[]) { std::cout << "sum = " << problem2(4000000) << std::endl; } <commit_msg>Update problem2.cpp<commit_after>// g++ -std=c++11 problem2.cpp && ./a.exe // output: // sum = 4613732 #include <iostream> int problem2(int num) { int sum = 0; for (int f1 = 1, f2 = 1; f2 < num; f2 += f1, f1 = f2 - f1) { if (f2 % 2 == 0) sum += f2; } return sum; } int main(int argc, char const* argv[]) { std::cout << "sum = " << problem2(4000000) << std::endl; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "translate.hxx" #include <list> #if TEST_LAYOUT #include <cstdio> #include "tools/getprocessworkingdir.hxx" #endif #include <unotools/bootstrap.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbhelper.hxx> #include <vcl/svapp.hxx> #include "proplist.hxx" namespace layoutimpl { namespace css = ::com::sun::star; using namespace css; using ::rtl::OUString; using ::utl::LocalFileHelper; using ::utl::UCBContentHelper; using ::utl::Bootstrap; static std::list<OUString> getLocaleSubdirList( lang::Locale const& rLocale ) { std::list<OUString> aSubdirs; aSubdirs.push_front( OUString(RTL_CONSTASCII_USTRINGPARAM(".")) ); aSubdirs.push_front( OUString(RTL_CONSTASCII_USTRINGPARAM("en-US")) ); if ( rLocale.Language.getLength() ) aSubdirs.push_front( rLocale.Language ); if ( rLocale.Country.getLength() ) { OUString aLocaleCountry = rLocale.Language + OUString(RTL_CONSTASCII_USTRINGPARAM("-")) + rLocale.Country; aSubdirs.push_front( aLocaleCountry ); if ( rLocale.Variant.getLength() ) aSubdirs.push_front( aLocaleCountry + OUString(RTL_CONSTASCII_USTRINGPARAM(".")) + rLocale.Variant ); } return aSubdirs; } static bool fileExists( String const& aFile ) { String aUrl; LocalFileHelper::ConvertPhysicalNameToURL( aFile, aUrl ); return UCBContentHelper::Exists( aUrl ); } static OUString getFirstExisting( OUString const& aDir, std::list<OUString> const& aSubDirs, OUString const& aXMLName ) { static OUString const aSlash(RTL_CONSTASCII_USTRINGPARAM("/")); String aResult; for ( std::list<OUString>::const_iterator i = aSubDirs.begin(); i != aSubDirs.end(); i++ ) { String aFile = aDir + aSlash + *i + aSlash + aXMLName; OSL_TRACE( "testing: %s", OUSTRING_CSTR( aFile ) ); if ( fileExists( aFile ) ) return aFile; } return OUString(); } /* FIXME: IWBN to share code with impimagetree.cxx, also for reading from zip files. */ OUString readRightTranslation( OUString const& aXMLName ) { String aXMLFile; std::list<OUString> aSubdirs = getLocaleSubdirList( Application::GetSettings().GetUILocale() ); #if TEST_LAYOUT // read from cwd first OUString aCurrentWorkingUrl; tools::getProcessWorkingDir( &aCurrentWorkingUrl ); String aCurrentWorkingDir; LocalFileHelper::ConvertURLToPhysicalName( aCurrentWorkingUrl, aCurrentWorkingDir ); aXMLFile = getFirstExisting( aCurrentWorkingDir, aSubdirs, aXMLName ); if ( aXMLFile.Len() ) ; else #endif /* TEST_LAYOUT */ { OUString aShareUrl; Bootstrap::locateSharedData( aShareUrl ); OUString aXMLUrl = aShareUrl + OUString(RTL_CONSTASCII_USTRINGPARAM("/layout")); String aXMLDir; LocalFileHelper::ConvertURLToPhysicalName( aXMLUrl, aXMLDir ); aXMLFile = getFirstExisting( aXMLDir, aSubdirs, aXMLName ); } OSL_TRACE( "FOUND:%s", OUSTRING_CSTR ( OUString (aXMLFile) ) ); return aXMLFile; } } // namespace layoutimpl /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>cppcheck: prefer prefix variant<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #include "translate.hxx" #include <list> #if TEST_LAYOUT #include <cstdio> #include "tools/getprocessworkingdir.hxx" #endif #include <unotools/bootstrap.hxx> #include <unotools/localfilehelper.hxx> #include <unotools/ucbhelper.hxx> #include <vcl/svapp.hxx> #include "proplist.hxx" namespace layoutimpl { namespace css = ::com::sun::star; using namespace css; using ::rtl::OUString; using ::utl::LocalFileHelper; using ::utl::UCBContentHelper; using ::utl::Bootstrap; static std::list<OUString> getLocaleSubdirList( lang::Locale const& rLocale ) { std::list<OUString> aSubdirs; aSubdirs.push_front( OUString(RTL_CONSTASCII_USTRINGPARAM(".")) ); aSubdirs.push_front( OUString(RTL_CONSTASCII_USTRINGPARAM("en-US")) ); if ( rLocale.Language.getLength() ) aSubdirs.push_front( rLocale.Language ); if ( rLocale.Country.getLength() ) { OUString aLocaleCountry = rLocale.Language + OUString(RTL_CONSTASCII_USTRINGPARAM("-")) + rLocale.Country; aSubdirs.push_front( aLocaleCountry ); if ( rLocale.Variant.getLength() ) aSubdirs.push_front( aLocaleCountry + OUString(RTL_CONSTASCII_USTRINGPARAM(".")) + rLocale.Variant ); } return aSubdirs; } static bool fileExists( String const& aFile ) { String aUrl; LocalFileHelper::ConvertPhysicalNameToURL( aFile, aUrl ); return UCBContentHelper::Exists( aUrl ); } static OUString getFirstExisting( OUString const& aDir, std::list<OUString> const& aSubDirs, OUString const& aXMLName ) { static OUString const aSlash(RTL_CONSTASCII_USTRINGPARAM("/")); String aResult; for ( std::list<OUString>::const_iterator i = aSubDirs.begin(); i != aSubDirs.end(); ++i ) { String aFile = aDir + aSlash + *i + aSlash + aXMLName; OSL_TRACE( "testing: %s", OUSTRING_CSTR( aFile ) ); if ( fileExists( aFile ) ) return aFile; } return OUString(); } /* FIXME: IWBN to share code with impimagetree.cxx, also for reading from zip files. */ OUString readRightTranslation( OUString const& aXMLName ) { String aXMLFile; std::list<OUString> aSubdirs = getLocaleSubdirList( Application::GetSettings().GetUILocale() ); #if TEST_LAYOUT // read from cwd first OUString aCurrentWorkingUrl; tools::getProcessWorkingDir( &aCurrentWorkingUrl ); String aCurrentWorkingDir; LocalFileHelper::ConvertURLToPhysicalName( aCurrentWorkingUrl, aCurrentWorkingDir ); aXMLFile = getFirstExisting( aCurrentWorkingDir, aSubdirs, aXMLName ); if ( aXMLFile.Len() ) ; else #endif /* TEST_LAYOUT */ { OUString aShareUrl; Bootstrap::locateSharedData( aShareUrl ); OUString aXMLUrl = aShareUrl + OUString(RTL_CONSTASCII_USTRINGPARAM("/layout")); String aXMLDir; LocalFileHelper::ConvertURLToPhysicalName( aXMLUrl, aXMLDir ); aXMLFile = getFirstExisting( aXMLDir, aSubdirs, aXMLName ); } OSL_TRACE( "FOUND:%s", OUSTRING_CSTR ( OUString (aXMLFile) ) ); return aXMLFile; } } // namespace layoutimpl /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "vld.h" #include "AcceptThread.h" #include "Server.h" #include "stringtools.h" #include "SelectThread.h" #include "Client.h" #include <memory.h> #ifndef _WIN32 #include <errno.h> #endif extern bool run; OutputCallback::OutputCallback(SOCKET fd_) { fd=fd_; } OutputCallback::~OutputCallback() { closesocket(fd); } void OutputCallback::operator() (const void* buf, size_t count) { int rc; rc = send(fd, (const char*)buf, (int)count, MSG_NOSIGNAL); if (rc < 0) Server->Log("Send failed in OutputCallback"); } CAcceptThread::CAcceptThread( unsigned int nWorkerThreadsPerMaster, unsigned short int uPort ) : error(false) { WorkerThreadsPerMaster=nWorkerThreadsPerMaster; Server->Log("Creating SOCKET...",LL_INFO); s=socket(AF_INET,SOCK_STREAM,0); if(s<1) { Server->Log("Creating SOCKET failed",LL_ERROR); error=true; return; } Server->Log("done.",LL_INFO); int optval=1; int rc=setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int)); if(rc==SOCKET_ERROR) { Server->Log("Failed setting SO_REUSEADDR for port "+nconvert(uPort),LL_ERROR); error=true; return; } sockaddr_in addr; memset(&addr, 0, sizeof(sockaddr_in)); addr.sin_family=AF_INET; addr.sin_port=htons(uPort); addr.sin_addr.s_addr=INADDR_ANY; rc=bind(s,(sockaddr*)&addr,sizeof(addr)); if(rc==SOCKET_ERROR) { Server->Log("Failed binding SOCKET to Port "+nconvert(uPort),LL_ERROR); error=true; return; } listen(s, 10000); Server->Log("Server started up sucessfully!",LL_INFO); } CAcceptThread::~CAcceptThread() { closesocket(s); Server->Log("Deleting SelectThreads.."); for(size_t i=0;i<SelectThreads.size();++i) { delete SelectThreads[i]; } } #ifndef _WIN32 void printLinError(void) { switch(errno) { case EWOULDBLOCK: Server->Log("Reason: EWOULDBLOCK", LL_ERROR); break; case EBADF: Server->Log("Reason: EBADF", LL_ERROR); break; case ECONNABORTED: Server->Log("Reason: ECONNABORTED", LL_ERROR); break; case EINTR: Server->Log("Reason: EINTR", LL_ERROR); break; case EINVAL: Server->Log("Reason: EINVAL", LL_ERROR); break; case EMFILE: Server->Log("Reason: EMFILE", LL_ERROR); break; case ENFILE: Server->Log("Reason: ENFILE", LL_ERROR); break; case ENOTSOCK: Server->Log("Reason: ENOTSOCK", LL_ERROR); break; case EFAULT: Server->Log("Reason: EFAULT", LL_ERROR); break; case ENOBUFS: Server->Log("Reason: ENOBUFS", LL_ERROR); break; case ENOMEM: Server->Log("Reason: ENOMEM", LL_ERROR); break; case EPROTO: Server->Log("Reason: EPROTO", LL_ERROR); break; case EPERM: Server->Log("Reason: EPERM", LL_ERROR); break; } } #endif void CAcceptThread::operator()(bool single) { do { socklen_t addrsize=sizeof(sockaddr_in); #ifdef _WIN32 fd_set fdset; FD_ZERO(&fdset); FD_SET(s, &fdset); timeval lon; lon.tv_sec=1; lon.tv_usec=0; _i32 rc=select((int)s+1, &fdset, 0, 0, &lon); if( rc<0 ) return; if( FD_ISSET(s,&fdset) ) { #else pollfd conn[1]; conn[0].fd=s; conn[0].events=POLLIN; conn[0].revents=0; int rc = poll(conn, 1, 1000); if(rc<0) return; if(rc>0) { #endif sockaddr_in naddr; SOCKET ns=accept(s, (sockaddr*)&naddr, &addrsize); if(ns!=SOCKET_ERROR) { //Server->Log("New Connection incomming", LL_INFO); OutputCallback *output=new OutputCallback(ns); FCGIProtocolDriver *driver=new FCGIProtocolDriver(*output ); CClient *client=new CClient(); client->set(ns, output, driver); AddToSelectThread(client); } else { Server->Log("Accepting client failed", LL_ERROR); #ifndef _WIN32 printLinError(); #endif Server->wait(1000); } } }while(single==false); } void CAcceptThread::AddToSelectThread(CClient *client) { for(size_t i=0;i<SelectThreads.size();++i) { if( SelectThreads[i]->FreeClients()>0 ) { SelectThreads[i]->AddClient( client ); return; } } CSelectThread *nt=new CSelectThread(WorkerThreadsPerMaster); nt->AddClient( client ); SelectThreads.push_back( nt ); Server->createThread(nt); } bool CAcceptThread::has_error(void) { return error; } <commit_msg>Throw exception if sending fails, interrupting transfer<commit_after>/************************************************************************* * UrBackup - Client/Server backup system * Copyright (C) 2011 Martin Raiber * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ #include "vld.h" #include "AcceptThread.h" #include "Server.h" #include "stringtools.h" #include "SelectThread.h" #include "Client.h" #include <memory.h> #ifndef _WIN32 #include <errno.h> #endif extern bool run; OutputCallback::OutputCallback(SOCKET fd_) { fd=fd_; } OutputCallback::~OutputCallback() { closesocket(fd); } void OutputCallback::operator() (const void* buf, size_t count) { int rc; rc = send(fd, (const char*)buf, (int)count, MSG_NOSIGNAL); if (rc < 0) { Server->Log("Send failed in OutputCallback"); throw std::runtime_error("Send failed in OutputCallback"); } } CAcceptThread::CAcceptThread( unsigned int nWorkerThreadsPerMaster, unsigned short int uPort ) : error(false) { WorkerThreadsPerMaster=nWorkerThreadsPerMaster; Server->Log("Creating SOCKET...",LL_INFO); s=socket(AF_INET,SOCK_STREAM,0); if(s<1) { Server->Log("Creating SOCKET failed",LL_ERROR); error=true; return; } Server->Log("done.",LL_INFO); int optval=1; int rc=setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (char*)&optval, sizeof(int)); if(rc==SOCKET_ERROR) { Server->Log("Failed setting SO_REUSEADDR for port "+nconvert(uPort),LL_ERROR); error=true; return; } sockaddr_in addr; memset(&addr, 0, sizeof(sockaddr_in)); addr.sin_family=AF_INET; addr.sin_port=htons(uPort); addr.sin_addr.s_addr=INADDR_ANY; rc=bind(s,(sockaddr*)&addr,sizeof(addr)); if(rc==SOCKET_ERROR) { Server->Log("Failed binding SOCKET to Port "+nconvert(uPort),LL_ERROR); error=true; return; } listen(s, 10000); Server->Log("Server started up sucessfully!",LL_INFO); } CAcceptThread::~CAcceptThread() { closesocket(s); Server->Log("Deleting SelectThreads.."); for(size_t i=0;i<SelectThreads.size();++i) { delete SelectThreads[i]; } } #ifndef _WIN32 void printLinError(void) { switch(errno) { case EWOULDBLOCK: Server->Log("Reason: EWOULDBLOCK", LL_ERROR); break; case EBADF: Server->Log("Reason: EBADF", LL_ERROR); break; case ECONNABORTED: Server->Log("Reason: ECONNABORTED", LL_ERROR); break; case EINTR: Server->Log("Reason: EINTR", LL_ERROR); break; case EINVAL: Server->Log("Reason: EINVAL", LL_ERROR); break; case EMFILE: Server->Log("Reason: EMFILE", LL_ERROR); break; case ENFILE: Server->Log("Reason: ENFILE", LL_ERROR); break; case ENOTSOCK: Server->Log("Reason: ENOTSOCK", LL_ERROR); break; case EFAULT: Server->Log("Reason: EFAULT", LL_ERROR); break; case ENOBUFS: Server->Log("Reason: ENOBUFS", LL_ERROR); break; case ENOMEM: Server->Log("Reason: ENOMEM", LL_ERROR); break; case EPROTO: Server->Log("Reason: EPROTO", LL_ERROR); break; case EPERM: Server->Log("Reason: EPERM", LL_ERROR); break; } } #endif void CAcceptThread::operator()(bool single) { do { socklen_t addrsize=sizeof(sockaddr_in); #ifdef _WIN32 fd_set fdset; FD_ZERO(&fdset); FD_SET(s, &fdset); timeval lon; lon.tv_sec=1; lon.tv_usec=0; _i32 rc=select((int)s+1, &fdset, 0, 0, &lon); if( rc<0 ) return; if( FD_ISSET(s,&fdset) ) { #else pollfd conn[1]; conn[0].fd=s; conn[0].events=POLLIN; conn[0].revents=0; int rc = poll(conn, 1, 1000); if(rc<0) return; if(rc>0) { #endif sockaddr_in naddr; SOCKET ns=accept(s, (sockaddr*)&naddr, &addrsize); if(ns!=SOCKET_ERROR) { //Server->Log("New Connection incomming", LL_INFO); OutputCallback *output=new OutputCallback(ns); FCGIProtocolDriver *driver=new FCGIProtocolDriver(*output ); CClient *client=new CClient(); client->set(ns, output, driver); AddToSelectThread(client); } else { Server->Log("Accepting client failed", LL_ERROR); #ifndef _WIN32 printLinError(); #endif Server->wait(1000); } } }while(single==false); } void CAcceptThread::AddToSelectThread(CClient *client) { for(size_t i=0;i<SelectThreads.size();++i) { if( SelectThreads[i]->FreeClients()>0 ) { SelectThreads[i]->AddClient( client ); return; } } CSelectThread *nt=new CSelectThread(WorkerThreadsPerMaster); nt->AddClient( client ); SelectThreads.push_back( nt ); Server->createThread(nt); } bool CAcceptThread::has_error(void) { return error; } <|endoftext|>
<commit_before>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "branch_iterators.hpp" namespace circa { Branch::~Branch() { // Dealloc_value on all non-types for (unsigned int i = 0; i < _terms.count(); i++) { Term *term = _terms[i]; if (term == NULL) continue; assert_good_pointer(term); if (term->type != TYPE_TYPE) dealloc_value(term); if (term->state != NULL) dealloc_value(term->state); } // Delete everybody for (unsigned int i = 0; i < _terms.count(); i++) { Term *term = _terms[i]; if (term == NULL) continue; assert_good_pointer(term); dealloc_value(term); term->owningBranch = NULL; delete_term(term); } } Branch& Branch::operator=(Branch const& b) { // Const hack because not everything is const-correct Branch& b_unconst = const_cast<Branch&>(b); clear(); duplicate_branch(b_unconst, *this); return *this; } void Branch::append(Term* term) { assert_good_pointer(term); assert(term->owningBranch == NULL); term->owningBranch = this; _terms.append(term); } void Branch::removeTerm(std::string const& name) { if (!names.contains(name)) return; Term* term = names[name]; names.remove(name); _terms.remove(term); delete_term(term); } Term* Branch::findFirstBinding(std::string const& name) const { for (unsigned int i = 0; i < _terms.count(); i++) { if (_terms[i] == NULL) continue; if (_terms[i]->name == name) return _terms[i]; } return NULL; } void Branch::bindName(Term* term, std::string name) { names.bind(term, name); if (term->name != "") { throw std::runtime_error(std::string("term already has name: ")+term->name); } term->name = name; } void Branch::remapPointers(ReferenceMap const& map) { names.remapPointers(map); for (unsigned int i = 0; i < _terms.count(); i++) { Term* term = _terms[i]; if (term != NULL) remap_pointers(term, map); } } void Branch::visitPointers(PointerVisitor& visitor) { struct VisitPointerIfOutsideBranch : PointerVisitor { Branch *branch; PointerVisitor &visitor; VisitPointerIfOutsideBranch(Branch *_branch, PointerVisitor &_visitor) : branch(_branch), visitor(_visitor) {} virtual void visitPointer(Term* term) { if (term == NULL) return; if (term->owningBranch != branch) visitor.visitPointer(term); } }; VisitPointerIfOutsideBranch myVisitor(this, visitor); for (unsigned int i = 0; i < _terms.count(); i++) { Term* term = _terms[i]; if (term == NULL) continue; visit_pointers(term, myVisitor); } } void Branch::_replaceTermObject(Term* existing, Term* replacement) { int existingIndex = _terms.findIndex(existing); assert(existingIndex >= 0); _terms[existingIndex] = replacement; ReferenceMap map; map[existing] = replacement; remapPointers(map); } void Branch::clear() { _terms.clear(); names.clear(); } void Branch::eval() { evaluate_branch(*this); } Term* Branch::eval(std::string const& statement) { //return newparser::evaluate_statement(*this, statement); return eval_statement(this, statement); } Term* Branch::compile(std::string const& statement) { return newparser::compile_statement(*this, statement); //return compile_statement(this, statement); } Branch& Branch::startBranch(std::string const& name) { Term* result = create_value(this, BRANCH_TYPE, name); as_branch(result).outerScope = this; return as_branch(result); } void Branch::copy(Term* source, Term* dest) { as_branch(dest).clear(); duplicate_branch(as_branch(source), as_branch(dest)); } void Branch::hosted_remap_pointers(Term* caller, ReferenceMap const& map) { as_branch(caller).remapPointers(map); } void Branch::hosted_visit_pointers(Term* caller, PointerVisitor& visitor) { as_branch(caller).visitPointers(visitor); } Branch& as_branch(Term* term) { assert_type(term, BRANCH_TYPE); assert(term->value != NULL); return *((Branch*) term->value); } std::string get_name_for_attribute(std::string attribute) { return "#attr:" + attribute; } void duplicate_branch_nested(ReferenceMap& newTermMap, Branch& source, Branch& dest) { // Duplicate every term for (int index=0; index < source.numTerms(); index++) { Term* source_term = source.get(index); Term* dest_term = create_duplicate(&dest, source_term, false); newTermMap[source_term] = dest_term; if (dest_term->state != NULL && dest_term->state->type == BRANCH_TYPE) { duplicate_branch_nested(newTermMap, as_branch(source_term->state), as_branch(dest_term->state)); } // Copy names if (source_term->name != "") dest.bindName(dest_term, source_term->name); } } void duplicate_branch(Branch& source, Branch& dest) { ReferenceMap newTermMap; duplicate_branch_nested(newTermMap, source, dest); // Remap pointers for (int index=0; index < dest.numTerms(); index++) { Term* term = dest.get(index); remap_pointers(term, newTermMap); } } // Returns whether the term was migrated bool migrate_term(Term* source, Term* dest) { // Branch migration if (dest->state != NULL && dest->state->type == BRANCH_TYPE) { migrate_branch(as_branch(source->state),as_branch(dest->state)); return true; } // Subroutine migration if (is_value(dest) && dest->type == FUNCTION_TYPE) { migrate_branch(get_subroutine_branch(source),get_subroutine_branch(dest)); return true; } // Value migration if (is_value(dest)) { // Don't overwrite value for state. But do migrate this term object if (!dest->isStateful()) { copy_value(source, dest); } return true; } return false; } void migrate_branch(Branch& replacement, Branch& target) { // The goal: // // Modify 'target' so that it is roughly equivalent to 'replacement', // but with as much state preserved as possible. // // The algorithm: // // 1. Copy 'target' to a temporary branch 'original' // 2. Overwrite 'target' with the contents of 'replacement' // 3. For every term in 'original', look for a match inside 'replacement'. // A 'match' is defined loosely on purpose, because we want to allow for // any amount of cleverness. But at a minimum, if two terms have the same // name, then they match. // 4. If a match is found, completely replace the relevant term inside // 'target' with the matching term from 'original'. // 5. Discard 'original'. // ReferenceList originalTerms = target._terms; TermNamespace originalNamespace = target.names; target.clear(); duplicate_branch(replacement, target); // Go through every one of original's names, see if we can migrate them. TermNamespace::iterator it; for (it = originalNamespace.begin(); it != originalNamespace.end(); ++it) { std::string name = it->first; Term* originalTerm = it->second; // Skip if name isn't in replacement if (!target.names.contains(name)) { continue; } Term* targetTerm = target[name]; // Skip if type doesn't match if (originalTerm->type != targetTerm->type) { continue; } bool migrated = migrate_term(targetTerm, originalTerm); if (migrated) { // Replace in list target._replaceTermObject(targetTerm, originalTerm); originalTerms.remove(originalTerm); } } } void evaluate_file(Branch& branch, std::string const& filename) { std::string fileContents = read_text_file(filename); TokenStream tokens(fileContents); ast::StatementList *statementList = parser::statementList(tokens); statementList->createTerms(branch); delete statementList; remove_compilation_attrs(branch); string_value(branch, filename, get_name_for_attribute("source-file")); } void reload_branch_from_file(Branch& branch) { std::string filename = as_string(branch[get_name_for_attribute("source-file")]); Branch replacement; evaluate_file(replacement, filename); migrate_branch(replacement, branch); } PointerIterator* Branch::start_pointer_iterator(Term* term) { return new BranchExternalPointerIterator((Branch*) term->value); } PointerIterator* start_branch_iterator(Branch* branch) { return new BranchIterator(branch); } PointerIterator* start_branch_pointer_iterator(Branch* branch) { return new BranchExternalPointerIterator(branch); } PointerIterator* start_branch_control_flow_iterator(Branch* branch) { return new BranchControlFlowIterator(branch); } Term* find_named(Branch* branch, std::string const& name) { if (branch != NULL) { if (branch->containsName(name)) return branch->getNamed(name); return find_named(branch->outerScope, name); } return get_global(name); } } // namespace circa <commit_msg>Branch.eval and compile are now switched over to newparser<commit_after>// Copyright 2008 Paul Hodge #include "common_headers.h" #include "circa.h" #include "branch_iterators.hpp" namespace circa { Branch::~Branch() { // Dealloc_value on all non-types for (unsigned int i = 0; i < _terms.count(); i++) { Term *term = _terms[i]; if (term == NULL) continue; assert_good_pointer(term); if (term->type != TYPE_TYPE) dealloc_value(term); if (term->state != NULL) dealloc_value(term->state); } // Delete everybody for (unsigned int i = 0; i < _terms.count(); i++) { Term *term = _terms[i]; if (term == NULL) continue; assert_good_pointer(term); dealloc_value(term); term->owningBranch = NULL; delete_term(term); } } Branch& Branch::operator=(Branch const& b) { // Const hack because not everything is const-correct Branch& b_unconst = const_cast<Branch&>(b); clear(); duplicate_branch(b_unconst, *this); return *this; } void Branch::append(Term* term) { assert_good_pointer(term); assert(term->owningBranch == NULL); term->owningBranch = this; _terms.append(term); } void Branch::removeTerm(std::string const& name) { if (!names.contains(name)) return; Term* term = names[name]; names.remove(name); _terms.remove(term); delete_term(term); } Term* Branch::findFirstBinding(std::string const& name) const { for (unsigned int i = 0; i < _terms.count(); i++) { if (_terms[i] == NULL) continue; if (_terms[i]->name == name) return _terms[i]; } return NULL; } void Branch::bindName(Term* term, std::string name) { names.bind(term, name); if (term->name != "") { throw std::runtime_error(std::string("term already has name: ")+term->name); } term->name = name; } void Branch::remapPointers(ReferenceMap const& map) { names.remapPointers(map); for (unsigned int i = 0; i < _terms.count(); i++) { Term* term = _terms[i]; if (term != NULL) remap_pointers(term, map); } } void Branch::visitPointers(PointerVisitor& visitor) { struct VisitPointerIfOutsideBranch : PointerVisitor { Branch *branch; PointerVisitor &visitor; VisitPointerIfOutsideBranch(Branch *_branch, PointerVisitor &_visitor) : branch(_branch), visitor(_visitor) {} virtual void visitPointer(Term* term) { if (term == NULL) return; if (term->owningBranch != branch) visitor.visitPointer(term); } }; VisitPointerIfOutsideBranch myVisitor(this, visitor); for (unsigned int i = 0; i < _terms.count(); i++) { Term* term = _terms[i]; if (term == NULL) continue; visit_pointers(term, myVisitor); } } void Branch::_replaceTermObject(Term* existing, Term* replacement) { int existingIndex = _terms.findIndex(existing); assert(existingIndex >= 0); _terms[existingIndex] = replacement; ReferenceMap map; map[existing] = replacement; remapPointers(map); } void Branch::clear() { _terms.clear(); names.clear(); } void Branch::eval() { evaluate_branch(*this); } Term* Branch::eval(std::string const& statement) { return newparser::evaluate_statement(*this, statement); } Term* Branch::compile(std::string const& statement) { return newparser::compile_statement(*this, statement); } Branch& Branch::startBranch(std::string const& name) { Term* result = create_value(this, BRANCH_TYPE, name); as_branch(result).outerScope = this; return as_branch(result); } void Branch::copy(Term* source, Term* dest) { as_branch(dest).clear(); duplicate_branch(as_branch(source), as_branch(dest)); } void Branch::hosted_remap_pointers(Term* caller, ReferenceMap const& map) { as_branch(caller).remapPointers(map); } void Branch::hosted_visit_pointers(Term* caller, PointerVisitor& visitor) { as_branch(caller).visitPointers(visitor); } Branch& as_branch(Term* term) { assert_type(term, BRANCH_TYPE); assert(term->value != NULL); return *((Branch*) term->value); } std::string get_name_for_attribute(std::string attribute) { return "#attr:" + attribute; } void duplicate_branch_nested(ReferenceMap& newTermMap, Branch& source, Branch& dest) { // Duplicate every term for (int index=0; index < source.numTerms(); index++) { Term* source_term = source.get(index); Term* dest_term = create_duplicate(&dest, source_term, false); newTermMap[source_term] = dest_term; if (dest_term->state != NULL && dest_term->state->type == BRANCH_TYPE) { duplicate_branch_nested(newTermMap, as_branch(source_term->state), as_branch(dest_term->state)); } // Copy names if (source_term->name != "") dest.bindName(dest_term, source_term->name); } } void duplicate_branch(Branch& source, Branch& dest) { ReferenceMap newTermMap; duplicate_branch_nested(newTermMap, source, dest); // Remap pointers for (int index=0; index < dest.numTerms(); index++) { Term* term = dest.get(index); remap_pointers(term, newTermMap); } } // Returns whether the term was migrated bool migrate_term(Term* source, Term* dest) { // Branch migration if (dest->state != NULL && dest->state->type == BRANCH_TYPE) { migrate_branch(as_branch(source->state),as_branch(dest->state)); return true; } // Subroutine migration if (is_value(dest) && dest->type == FUNCTION_TYPE) { migrate_branch(get_subroutine_branch(source),get_subroutine_branch(dest)); return true; } // Value migration if (is_value(dest)) { // Don't overwrite value for state. But do migrate this term object if (!dest->isStateful()) { copy_value(source, dest); } return true; } return false; } void migrate_branch(Branch& replacement, Branch& target) { // The goal: // // Modify 'target' so that it is roughly equivalent to 'replacement', // but with as much state preserved as possible. // // The algorithm: // // 1. Copy 'target' to a temporary branch 'original' // 2. Overwrite 'target' with the contents of 'replacement' // 3. For every term in 'original', look for a match inside 'replacement'. // A 'match' is defined loosely on purpose, because we want to allow for // any amount of cleverness. But at a minimum, if two terms have the same // name, then they match. // 4. If a match is found, completely replace the relevant term inside // 'target' with the matching term from 'original'. // 5. Discard 'original'. // ReferenceList originalTerms = target._terms; TermNamespace originalNamespace = target.names; target.clear(); duplicate_branch(replacement, target); // Go through every one of original's names, see if we can migrate them. TermNamespace::iterator it; for (it = originalNamespace.begin(); it != originalNamespace.end(); ++it) { std::string name = it->first; Term* originalTerm = it->second; // Skip if name isn't in replacement if (!target.names.contains(name)) { continue; } Term* targetTerm = target[name]; // Skip if type doesn't match if (originalTerm->type != targetTerm->type) { continue; } bool migrated = migrate_term(targetTerm, originalTerm); if (migrated) { // Replace in list target._replaceTermObject(targetTerm, originalTerm); originalTerms.remove(originalTerm); } } } void evaluate_file(Branch& branch, std::string const& filename) { std::string fileContents = read_text_file(filename); TokenStream tokens(fileContents); ast::StatementList *statementList = parser::statementList(tokens); statementList->createTerms(branch); delete statementList; remove_compilation_attrs(branch); string_value(branch, filename, get_name_for_attribute("source-file")); } void reload_branch_from_file(Branch& branch) { std::string filename = as_string(branch[get_name_for_attribute("source-file")]); Branch replacement; evaluate_file(replacement, filename); migrate_branch(replacement, branch); } PointerIterator* Branch::start_pointer_iterator(Term* term) { return new BranchExternalPointerIterator((Branch*) term->value); } PointerIterator* start_branch_iterator(Branch* branch) { return new BranchIterator(branch); } PointerIterator* start_branch_pointer_iterator(Branch* branch) { return new BranchExternalPointerIterator(branch); } PointerIterator* start_branch_control_flow_iterator(Branch* branch) { return new BranchControlFlowIterator(branch); } Term* find_named(Branch* branch, std::string const& name) { if (branch != NULL) { if (branch->containsName(name)) return branch->getNamed(name); return find_named(branch->outerScope, name); } return get_global(name); } } // namespace circa <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/core/error_reporter.h" #include <cstdarg> #include <cstdio> #include <cstring> #include "tensorflow/lite/minimal_logging.h" namespace tflite { namespace task { namespace core { int ErrorReporter::Report(const char* format, va_list args) { last_message_[0] = '\0'; int num_characters = vsnprintf(last_message_, kBufferSize, format, args); // To mimic tflite::StderrReporter. tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, last_message_); return num_characters; } std::string ErrorReporter::message() { return last_message_; } } // namespace core } // namespace task } // namespace tflite <commit_msg>Fix bug where it was assuming that error messages won't contain format strings.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/core/error_reporter.h" #include <cstdarg> #include <cstdio> #include <cstring> #include "tensorflow/lite/minimal_logging.h" namespace tflite { namespace task { namespace core { int ErrorReporter::Report(const char* format, va_list args) { last_message_[0] = '\0'; int num_characters = vsnprintf(last_message_, kBufferSize, format, args); // To mimic tflite::StderrReporter. tflite::logging_internal::MinimalLogger::Log(TFLITE_LOG_ERROR, "%s", last_message_); return num_characters; } std::string ErrorReporter::message() { return last_message_; } } // namespace core } // namespace task } // namespace tflite <|endoftext|>
<commit_before>/** * OpenColorIO conversion Iop. */ #include "ColorSpaceConversion.h" namespace OCIO = OCIO_NAMESPACE; #include <DDImage/PixelIop.h> #include <DDImage/NukeWrapper.h> #include <DDImage/Row.h> #include <DDImage/Knobs.h> #include <string> ColorSpaceConversion::ColorSpaceConversion(Node *n) : DD::Image::PixelIop(n) { hasColorSpaces = false; inputColorSpaceIndex = 0; outputColorSpaceIndex = 0; layersToProcess = DD::Image::Mask_RGB; // TODO (when to) re-grab the list of available colorspaces? How to save/load? try { OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig(); OCIO::ConstColorSpaceRcPtr defaultColorSpace = \ config->getColorSpaceForRole(OCIO::ROLE_SCENE_LINEAR); int nColorSpaces = config->getNumColorSpaces(); for(int i = 0; i < nColorSpaces; i++) { OCIO::ConstColorSpaceRcPtr colorSpace = config->getColorSpaceByIndex(i); bool usedAsInput = false; bool isDefault = colorSpace->equals(defaultColorSpace); //if (colorSpace->isTransformAllowed(OCIO::COLORSPACE_DIR_TO_REFERENCE)) { usedAsInput = true; colorSpaceNames.push_back(colorSpace->getName()); if (isDefault) { inputColorSpaceIndex = static_cast<int>(inputColorSpaceCstrNames.size()); } inputColorSpaceCstrNames.push_back(colorSpaceNames.back().c_str()); } //if (colorSpace->isTransformAllowed(OCIO::COLORSPACE_DIR_FROM_REFERENCE)) { if (!usedAsInput) { colorSpaceNames.push_back(colorSpace->getName()); } if (isDefault) { outputColorSpaceIndex = static_cast<int>(outputColorSpaceCstrNames.size()); } outputColorSpaceCstrNames.push_back(colorSpaceNames.back().c_str()); } } } catch (OCIO::OCIOException& e) { error(e.what()); } hasColorSpaces = !(inputColorSpaceCstrNames.empty() || outputColorSpaceCstrNames.empty()); inputColorSpaceCstrNames.push_back(NULL); outputColorSpaceCstrNames.push_back(NULL); if(!hasColorSpaces) { error("No ColorSpaces available for input and/or output."); } } ColorSpaceConversion::~ColorSpaceConversion() { } void ColorSpaceConversion::knobs(DD::Image::Knob_Callback f) { DD::Image::Enumeration_knob(f, &inputColorSpaceIndex, &inputColorSpaceCstrNames[0], "in_colorspace", "in"); DD::Image::Tooltip(f, "Input data is taken to be in this colorspace."); DD::Image::Enumeration_knob(f, &outputColorSpaceIndex, &outputColorSpaceCstrNames[0], "out_colorspace", "out"); DD::Image::Tooltip(f, "Image data is converted to this colorspace for output."); DD::Image::Divider(f); DD::Image::Input_ChannelSet_knob(f, &layersToProcess, 0, "layer", "layer"); DD::Image::SetFlags(f, DD::Image::Knob::NO_CHECKMARKS | DD::Image::Knob::NO_ALPHA_PULLDOWN); DD::Image::Tooltip(f, "Set which layer to process. This should be a layer with rgb data."); } void ColorSpaceConversion::_validate(bool for_real) { input0().validate(for_real); if(!hasColorSpaces) { error("No colorspaces available for input and/or output."); return; } if(inputColorSpaceIndex < 0 || inputColorSpaceIndex >= inputColorSpaceCstrNames.size() - 1) { std::ostringstream err; err << "Input colorspace index (" << inputColorSpaceIndex << ") out of range."; error(err.str().c_str()); return; } if(outputColorSpaceIndex < 0 || outputColorSpaceIndex >= outputColorSpaceCstrNames.size() - 1) { std::ostringstream err; err << "Output colorspace index (" << outputColorSpaceIndex << ") out of range."; error(err.str().c_str()); return; } try { const char * inputName = inputColorSpaceCstrNames[inputColorSpaceIndex]; const char * outputName = outputColorSpaceCstrNames[outputColorSpaceIndex]; OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig(); OCIO::ConstColorSpaceRcPtr csSrc = config->getColorSpaceByName( inputName ); OCIO::ConstColorSpaceRcPtr csDst = config->getColorSpaceByName( outputName ); processor = config->getProcessor(csSrc, csDst); } catch(OCIO::OCIOException &e) { error(e.what()); return; } if(processor->isNoOp()) { // TODO or call disable() ? set_out_channels(DD::Image::Mask_None); // prevents engine() from being called copy_info(); return; } set_out_channels(DD::Image::Mask_All); DD::Image::PixelIop::_validate(for_real); } void ColorSpaceConversion::in_channels(int /* n unused */, DD::Image::ChannelSet& mask) const { DD::Image::ChannelSet done; foreach(c, mask) { if ((layersToProcess & c) && DD::Image::colourIndex(c) < 3 && !(done & c)) { done.addBrothers(c, 3); } } mask += done; } // See Saturation::pixel_engine for a well-commented example. void ColorSpaceConversion::pixel_engine( const DD::Image::Row& in, int /* rowY unused */, int rowX, int rowXBound, const DD::Image::ChannelSet& outputChannels, DD::Image::Row& out) { int rowWidth = rowXBound - rowX; DD::Image::ChannelSet done; foreach (requestedChannel, outputChannels) { // Skip channels which had their trios processed already, if (done & requestedChannel) { continue; } // Pass through channels which are not selected for processing // and non-rgb channels. if (!(layersToProcess & requestedChannel) || colourIndex(requestedChannel) >= 3) { out.copy(in, requestedChannel, rowX, rowXBound); continue; } DD::Image::Channel rChannel = DD::Image::brother(requestedChannel, 0); DD::Image::Channel gChannel = DD::Image::brother(requestedChannel, 1); DD::Image::Channel bChannel = DD::Image::brother(requestedChannel, 2); done += rChannel; done += gChannel; done += bChannel; const float *rIn = in[rChannel] + rowX; const float *gIn = in[gChannel] + rowX; const float *bIn = in[bChannel] + rowX; float *rOut = out.writable(rChannel) + rowX; float *gOut = out.writable(gChannel) + rowX; float *bOut = out.writable(bChannel) + rowX; #if 0 for(int i = 0; i < rowWidth; i++) { float sum = rIn[i] + gIn[i] + bIn[i]; sum /= 3.0f; rOut[i] = gOut[i] = bOut[i] = sum; } #endif #if 1 // OCIO modifies in-place memcpy(rOut, rIn, sizeof(float)*rowWidth); memcpy(gOut, gIn, sizeof(float)*rowWidth); memcpy(bOut, bIn, sizeof(float)*rowWidth); try { OCIO::PlanarImageDesc img(rOut, gOut, bOut, rowWidth, /*height*/ 1); processor->apply(img); } catch(OCIO::OCIOException &e) { error(e.what()); } #endif } } const DD::Image::Op::Description ColorSpaceConversion::description("OCIOColorSpaceConversion", build); const char* ColorSpaceConversion::Class() const { return description.name; } const char* ColorSpaceConversion::displayName() const { return description.name; } const char* ColorSpaceConversion::node_help() const { // TODO more detailed help text return "Use OpenColorIO to convert from one ColorSpace to another."; } DD::Image::Op* build(Node *node) { DD::Image::NukeWrapper *op = new DD::Image::NukeWrapper(new ColorSpaceConversion(node)); op->noMix(); op->noMask(); op->noChannels(); // prefer our own channels control without checkboxes / alpha op->noUnpremult(); return op; } <commit_msg>Fix a signed/unsigned comparison warning.<commit_after>/** * OpenColorIO conversion Iop. */ #include "ColorSpaceConversion.h" namespace OCIO = OCIO_NAMESPACE; #include <DDImage/PixelIop.h> #include <DDImage/NukeWrapper.h> #include <DDImage/Row.h> #include <DDImage/Knobs.h> #include <string> ColorSpaceConversion::ColorSpaceConversion(Node *n) : DD::Image::PixelIop(n) { hasColorSpaces = false; inputColorSpaceIndex = 0; outputColorSpaceIndex = 0; layersToProcess = DD::Image::Mask_RGB; // TODO (when to) re-grab the list of available colorspaces? How to save/load? try { OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig(); OCIO::ConstColorSpaceRcPtr defaultColorSpace = \ config->getColorSpaceForRole(OCIO::ROLE_SCENE_LINEAR); int nColorSpaces = config->getNumColorSpaces(); for(int i = 0; i < nColorSpaces; i++) { OCIO::ConstColorSpaceRcPtr colorSpace = config->getColorSpaceByIndex(i); bool usedAsInput = false; bool isDefault = colorSpace->equals(defaultColorSpace); //if (colorSpace->isTransformAllowed(OCIO::COLORSPACE_DIR_TO_REFERENCE)) { usedAsInput = true; colorSpaceNames.push_back(colorSpace->getName()); if (isDefault) { inputColorSpaceIndex = static_cast<int>(inputColorSpaceCstrNames.size()); } inputColorSpaceCstrNames.push_back(colorSpaceNames.back().c_str()); } //if (colorSpace->isTransformAllowed(OCIO::COLORSPACE_DIR_FROM_REFERENCE)) { if (!usedAsInput) { colorSpaceNames.push_back(colorSpace->getName()); } if (isDefault) { outputColorSpaceIndex = static_cast<int>(outputColorSpaceCstrNames.size()); } outputColorSpaceCstrNames.push_back(colorSpaceNames.back().c_str()); } } } catch (OCIO::OCIOException& e) { error(e.what()); } hasColorSpaces = !(inputColorSpaceCstrNames.empty() || outputColorSpaceCstrNames.empty()); inputColorSpaceCstrNames.push_back(NULL); outputColorSpaceCstrNames.push_back(NULL); if(!hasColorSpaces) { error("No ColorSpaces available for input and/or output."); } } ColorSpaceConversion::~ColorSpaceConversion() { } void ColorSpaceConversion::knobs(DD::Image::Knob_Callback f) { DD::Image::Enumeration_knob(f, &inputColorSpaceIndex, &inputColorSpaceCstrNames[0], "in_colorspace", "in"); DD::Image::Tooltip(f, "Input data is taken to be in this colorspace."); DD::Image::Enumeration_knob(f, &outputColorSpaceIndex, &outputColorSpaceCstrNames[0], "out_colorspace", "out"); DD::Image::Tooltip(f, "Image data is converted to this colorspace for output."); DD::Image::Divider(f); DD::Image::Input_ChannelSet_knob(f, &layersToProcess, 0, "layer", "layer"); DD::Image::SetFlags(f, DD::Image::Knob::NO_CHECKMARKS | DD::Image::Knob::NO_ALPHA_PULLDOWN); DD::Image::Tooltip(f, "Set which layer to process. This should be a layer with rgb data."); } void ColorSpaceConversion::_validate(bool for_real) { input0().validate(for_real); if(!hasColorSpaces) { error("No colorspaces available for input and/or output."); return; } int inputColorSpaceCount = static_cast<int>(inputColorSpaceCstrNames.size()) - 1; if(inputColorSpaceIndex < 0 || inputColorSpaceIndex >= inputColorSpaceCount) { std::ostringstream err; err << "Input colorspace index (" << inputColorSpaceIndex << ") out of range."; error(err.str().c_str()); return; } int outputColorSpaceCount = static_cast<int>(outputColorSpaceCstrNames.size()) - 1; if(outputColorSpaceIndex < 0 || outputColorSpaceIndex >= outputColorSpaceCount) { std::ostringstream err; err << "Output colorspace index (" << outputColorSpaceIndex << ") out of range."; error(err.str().c_str()); return; } try { const char * inputName = inputColorSpaceCstrNames[inputColorSpaceIndex]; const char * outputName = outputColorSpaceCstrNames[outputColorSpaceIndex]; OCIO::ConstConfigRcPtr config = OCIO::GetCurrentConfig(); OCIO::ConstColorSpaceRcPtr csSrc = config->getColorSpaceByName( inputName ); OCIO::ConstColorSpaceRcPtr csDst = config->getColorSpaceByName( outputName ); processor = config->getProcessor(csSrc, csDst); } catch(OCIO::OCIOException &e) { error(e.what()); return; } if(processor->isNoOp()) { // TODO or call disable() ? set_out_channels(DD::Image::Mask_None); // prevents engine() from being called copy_info(); return; } set_out_channels(DD::Image::Mask_All); DD::Image::PixelIop::_validate(for_real); } void ColorSpaceConversion::in_channels(int /* n unused */, DD::Image::ChannelSet& mask) const { DD::Image::ChannelSet done; foreach(c, mask) { if ((layersToProcess & c) && DD::Image::colourIndex(c) < 3 && !(done & c)) { done.addBrothers(c, 3); } } mask += done; } // See Saturation::pixel_engine for a well-commented example. void ColorSpaceConversion::pixel_engine( const DD::Image::Row& in, int /* rowY unused */, int rowX, int rowXBound, const DD::Image::ChannelSet& outputChannels, DD::Image::Row& out) { int rowWidth = rowXBound - rowX; DD::Image::ChannelSet done; foreach (requestedChannel, outputChannels) { // Skip channels which had their trios processed already, if (done & requestedChannel) { continue; } // Pass through channels which are not selected for processing // and non-rgb channels. if (!(layersToProcess & requestedChannel) || colourIndex(requestedChannel) >= 3) { out.copy(in, requestedChannel, rowX, rowXBound); continue; } DD::Image::Channel rChannel = DD::Image::brother(requestedChannel, 0); DD::Image::Channel gChannel = DD::Image::brother(requestedChannel, 1); DD::Image::Channel bChannel = DD::Image::brother(requestedChannel, 2); done += rChannel; done += gChannel; done += bChannel; const float *rIn = in[rChannel] + rowX; const float *gIn = in[gChannel] + rowX; const float *bIn = in[bChannel] + rowX; float *rOut = out.writable(rChannel) + rowX; float *gOut = out.writable(gChannel) + rowX; float *bOut = out.writable(bChannel) + rowX; #if 0 for(int i = 0; i < rowWidth; i++) { float sum = rIn[i] + gIn[i] + bIn[i]; sum /= 3.0f; rOut[i] = gOut[i] = bOut[i] = sum; } #endif #if 1 // OCIO modifies in-place memcpy(rOut, rIn, sizeof(float)*rowWidth); memcpy(gOut, gIn, sizeof(float)*rowWidth); memcpy(bOut, bIn, sizeof(float)*rowWidth); try { OCIO::PlanarImageDesc img(rOut, gOut, bOut, rowWidth, /*height*/ 1); processor->apply(img); } catch(OCIO::OCIOException &e) { error(e.what()); } #endif } } const DD::Image::Op::Description ColorSpaceConversion::description("OCIOColorSpaceConversion", build); const char* ColorSpaceConversion::Class() const { return description.name; } const char* ColorSpaceConversion::displayName() const { return description.name; } const char* ColorSpaceConversion::node_help() const { // TODO more detailed help text return "Use OpenColorIO to convert from one ColorSpace to another."; } DD::Image::Op* build(Node *node) { DD::Image::NukeWrapper *op = new DD::Image::NukeWrapper(new ColorSpaceConversion(node)); op->noMix(); op->noMask(); op->noChannels(); // prefer our own channels control without checkboxes / alpha op->noUnpremult(); return op; } <|endoftext|>
<commit_before>#include "broker.hpp" #include "message.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <unordered_map> namespace { bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse if(str1.length() != str2.length()) return false; for(int i = str1.length() - 1; i >= 0; --i) if(str1[i] != str2[i]) return false; return true; } bool equalOrPlus(const std::string& pat, const std::string& top) { return pat == "+" || revStrEquals(pat, top); } } //anonymous namespace class Subscription { public: Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic, std::deque<std::string> topicParts): _subscriber(subscriber), _part(std::move(topicParts.back())), _topic(std::move(topic.topic)), _qos(topic.qos) { } void newMessage(std::string topic, std::vector<ubyte> payload) { _subscriber.newMessage(topic, payload); } bool isSubscriber(const MqttSubscriber& subscriber) const { return &_subscriber == &subscriber; } bool isSubscription(const MqttSubscriber& subscriber, std::vector<std::string> topics) const { return isSubscriber(subscriber) && isTopic(topics); } bool isTopic(std::vector<std::string> topics) const { return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend(); } private: MqttSubscriber& _subscriber; std::string _part; std::string _topic; ubyte _qos; }; struct SubscriptionTree { public: void addSubscription(Subscription* s, std::deque<std::string> parts) { assert(parts.size()); clearCache(); addSubscriptionImpl(s, parts, nullptr, _nodes); } // void removeSubscription(MqttSubscriber& subscriber, // std::unordered_map<std::string, Node*>& nodes) { // clearCache(); // decltype(nodes) newNodes; // std::copy(nodes.cbegin(), nodes.cend(), std::back_inserter(newNodes)); // for(auto n: newnodes) { // if(n->leaves) { // std::remove_if(n->leaves.begin(), n->leaves.end(), // [](Subscription* l) { return l.isSubscriber(subscriber); }); // if(!n->leaves.size() && !n->branches.size()) { // removeNode(n->parent, n); // } // } else { // removeSubscription(subscriber, n.branches); // } // } // } // void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) { // clearCache(); // auto newnodes = nodes.dup; // foreach(n; newnodes) { // if(n.leaves) { // n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves); // if(n.leaves.empty && !n.branches.length) { // removeNode(n.parent, n); // } // } else { // removeSubscription(subscriber, topic, n.branches); // } // } // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload) { // publish(topic, topParts, payload, _nodes); // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload, // Node*[string] nodes) { // //check the cache first // if(_useCache && topic in _cache) { // foreach(s; _cache[topic]) s.newMessage(topic, payload); // return; // } // //not in the cache or not using the cache, do it the hard way // foreach(part; [topParts[0], "#", "+"]) { // if(part in nodes) { // if(topParts.length == 1 && "#" in nodes[part].branches) { // //So that "finance/#" matches finance // publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves); // } // publishLeaves(topic, payload, topParts, nodes[part].leaves); // if(topParts.length > 1) { // publish(topic, topParts[1..$], payload, nodes[part].branches); // } // } // } // } // void publishLeaves(in string topic, in const(ubyte)[] payload, // in string[] topParts, // Subscription[] subscriptions) { // foreach(sub; subscriptions) { // if(topParts.length == 1 && // equalOrPlus(sub._part, topParts[0])) { // publishLeaf(sub, topic, payload); // } // else if(sub._part == "#") { // publishLeaf(sub, topic, payload); // } // } // } // void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) { // sub.newMessage(topic, payload); // if(_useCache) _cache[topic] ~= sub; // } void useCache(bool u) { _useCache = u; } private: struct Node { Node(std::string pt, Node* pr):part(pt), parent(pr) {} std::string part; Node* parent; std::unordered_map<std::string, Node*> branches; std::vector<Subscription*> leaves; }; bool _useCache; std::unordered_map<std::string, Subscription*> _cache; std::unordered_map<std::string, Node*> _nodes; void addSubscriptionImpl(Subscription* s, std::deque<std::string> parts, Node* parent, std::unordered_map<std::string, Node*> nodes) { auto part = parts.front(); parts.pop_front(); auto node = addOrFindNode(part, parent, nodes); if(!parts.size()) { node->leaves.emplace_back(s); } else { addSubscriptionImpl(s, parts, node, node->branches); } } Node* addOrFindNode(std::string part, Node* parent, std::unordered_map<std::string, Node*> nodes) { if(nodes.count(part) && part == nodes[part]->part) { return nodes[part]; } auto node = new Node(part, parent); nodes[part] = node; return node; } void clearCache() { if(_useCache) _cache.clear(); } void removeNode(Node* parent, Node* child) { if(parent) { parent->branches.erase(child->part); } else { _nodes.erase(child->part); } if(parent && !parent->branches.size() && !parent->leaves.size()) removeNode(parent->parent, parent); } }; class MqttBroker { public: void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { std::vector<MqttSubscribe::Topic> newTopics; std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics), [](std::string t) { return MqttSubscribe::Topic(t, 0); }); subscribe(subscriber, newTopics); } void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) { for(const auto& t: topics) { std::deque<std::string> parts; boost::split(parts, t.topic, boost::is_any_of("/")); _subscriptions.addSubscription(new Subscription(subscriber, t, parts), parts); } } // void unsubscribe(MqttSubscriber& subscriber) { // _subscriptions.removeSubscription(subscriber, _subscriptions._nodes); // } // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { // _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes); // } // void publish(std::string topic, std::vector<ubyte> payload) { // auto topParts = array(splitter(topic, "/")); // publish(topic, topParts, payload); // } void useCache(bool u) { _subscriptions.useCache(u); } private: SubscriptionTree _subscriptions; // void publish(std::string topic, std::vector<std::string> topParts, // std::vector<ubyte> payload) { // _subscriptions.publish(topic, topParts, payload); // } }; <commit_msg>Uncommented removeSubscription<commit_after>#include "broker.hpp" #include "message.hpp" #include <algorithm> #include <boost/algorithm/string.hpp> #include <unordered_map> namespace { bool revStrEquals(const std::string& str1, const std::string& str2) { //compare strings in reverse if(str1.length() != str2.length()) return false; for(int i = str1.length() - 1; i >= 0; --i) if(str1[i] != str2[i]) return false; return true; } bool equalOrPlus(const std::string& pat, const std::string& top) { return pat == "+" || revStrEquals(pat, top); } } //anonymous namespace class Subscription { public: Subscription(MqttSubscriber& subscriber, MqttSubscribe::Topic topic, std::deque<std::string> topicParts): _subscriber(subscriber), _part(std::move(topicParts.back())), _topic(std::move(topic.topic)), _qos(topic.qos) { } void newMessage(std::string topic, std::vector<ubyte> payload) { _subscriber.newMessage(topic, payload); } bool isSubscriber(const MqttSubscriber& subscriber) const { return &_subscriber == &subscriber; } bool isSubscription(const MqttSubscriber& subscriber, std::vector<std::string> topics) const { return isSubscriber(subscriber) && isTopic(topics); } bool isTopic(std::vector<std::string> topics) const { return std::find(topics.cbegin(), topics.cend(), _topic) == topics.cend(); } private: MqttSubscriber& _subscriber; std::string _part; std::string _topic; ubyte _qos; }; struct SubscriptionTree { private: struct Node { Node(std::string pt, Node* pr):part(pt), parent(pr) {} std::string part; Node* parent; std::unordered_map<std::string, Node*> branches; std::vector<Subscription*> leaves; }; public: void addSubscription(Subscription* s, std::deque<std::string> parts) { assert(parts.size()); clearCache(); addSubscriptionImpl(s, parts, nullptr, _nodes); } void removeSubscription(MqttSubscriber& subscriber, std::unordered_map<std::string, Node*>& nodes) { clearCache(); std::unordered_map<std::string, Node*> newNodes = nodes; for(auto n: newNodes) { if(n.second->leaves.size()) { std::remove_if(n.second->leaves.begin(), n.second->leaves.end(), [&subscriber](Subscription* l) { return l->isSubscriber(subscriber); }); if(!n.second->leaves.size() && !n.second->branches.size()) { removeNode(n.second->parent, n.second); } } else { removeSubscription(subscriber, n.second->branches); } } } // void removeSubscription(MqttSubscriber subscriber, in string[] topic, ref Node*[string] nodes) { // clearCache(); // auto newnodes = nodes.dup; // foreach(n; newnodes) { // if(n.leaves) { // n.leaves = std.algorithm.remove!(l => l.isSubscription(subscriber, topic))(n.leaves); // if(n.leaves.empty && !n.branches.length) { // removeNode(n.parent, n); // } // } else { // removeSubscription(subscriber, topic, n.branches); // } // } // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload) { // publish(topic, topParts, payload, _nodes); // } // void publish(in string topic, string[] topParts, in const(ubyte)[] payload, // Node*[string] nodes) { // //check the cache first // if(_useCache && topic in _cache) { // foreach(s; _cache[topic]) s.newMessage(topic, payload); // return; // } // //not in the cache or not using the cache, do it the hard way // foreach(part; [topParts[0], "#", "+"]) { // if(part in nodes) { // if(topParts.length == 1 && "#" in nodes[part].branches) { // //So that "finance/#" matches finance // publishLeaves(topic, payload, topParts, nodes[part].branches["#"].leaves); // } // publishLeaves(topic, payload, topParts, nodes[part].leaves); // if(topParts.length > 1) { // publish(topic, topParts[1..$], payload, nodes[part].branches); // } // } // } // } // void publishLeaves(in string topic, in const(ubyte)[] payload, // in string[] topParts, // Subscription[] subscriptions) { // foreach(sub; subscriptions) { // if(topParts.length == 1 && // equalOrPlus(sub._part, topParts[0])) { // publishLeaf(sub, topic, payload); // } // else if(sub._part == "#") { // publishLeaf(sub, topic, payload); // } // } // } // void publishLeaf(Subscription sub, in string topic, in const(ubyte)[] payload) { // sub.newMessage(topic, payload); // if(_useCache) _cache[topic] ~= sub; // } void useCache(bool u) { _useCache = u; } private: bool _useCache; std::unordered_map<std::string, Subscription*> _cache; std::unordered_map<std::string, Node*> _nodes; void addSubscriptionImpl(Subscription* s, std::deque<std::string> parts, Node* parent, std::unordered_map<std::string, Node*> nodes) { auto part = parts.front(); parts.pop_front(); auto node = addOrFindNode(part, parent, nodes); if(!parts.size()) { node->leaves.emplace_back(s); } else { addSubscriptionImpl(s, parts, node, node->branches); } } Node* addOrFindNode(std::string part, Node* parent, std::unordered_map<std::string, Node*> nodes) { if(nodes.count(part) && part == nodes[part]->part) { return nodes[part]; } auto node = new Node(part, parent); nodes[part] = node; return node; } void clearCache() { if(_useCache) _cache.clear(); } void removeNode(Node* parent, Node* child) { if(parent) { parent->branches.erase(child->part); } else { _nodes.erase(child->part); } if(parent && !parent->branches.size() && !parent->leaves.size()) removeNode(parent->parent, parent); } }; class MqttBroker { public: void subscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { std::vector<MqttSubscribe::Topic> newTopics; std::transform(topics.cbegin(), topics.cend(), std::back_inserter(newTopics), [](std::string t) { return MqttSubscribe::Topic(t, 0); }); subscribe(subscriber, newTopics); } void subscribe(MqttSubscriber& subscriber, std::vector<MqttSubscribe::Topic> topics) { for(const auto& t: topics) { std::deque<std::string> parts; boost::split(parts, t.topic, boost::is_any_of("/")); _subscriptions.addSubscription(new Subscription(subscriber, t, parts), parts); } } // void unsubscribe(MqttSubscriber& subscriber) { // _subscriptions.removeSubscription(subscriber, _subscriptions._nodes); // } // void unsubscribe(MqttSubscriber& subscriber, std::vector<std::string> topics) { // _subscriptions.removeSubscription(subscriber, topics, _subscriptions._nodes); // } // void publish(std::string topic, std::vector<ubyte> payload) { // auto topParts = array(splitter(topic, "/")); // publish(topic, topParts, payload); // } void useCache(bool u) { _subscriptions.useCache(u); } private: SubscriptionTree _subscriptions; // void publish(std::string topic, std::vector<std::string> topParts, // std::vector<ubyte> payload) { // _subscriptions.publish(topic, topParts, payload); // } }; <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include "impl/weak_realm_notifier.hpp" #include "shared_realm.hpp" using namespace realm; using namespace realm::_impl; WeakRealmNotifier::WeakRealmNotifier(const std::shared_ptr<Realm>& realm, bool cache) : WeakRealmNotifierBase(realm, cache) , m_handle(new uv_async_t) { m_handle->data = new std::weak_ptr<Realm>(realm); // This assumes that only one thread matters: the main thread (default loop). uv_async_init(uv_default_loop(), m_handle, [](uv_async_t* handle) { auto realm_weak_ptr = static_cast<std::weak_ptr<Realm>*>(handle->data); auto realm = realm_weak_ptr->lock(); if (realm) { realm->notify(); } }); } WeakRealmNotifier::WeakRealmNotifier(WeakRealmNotifier&& rgt) : WeakRealmNotifierBase(std::move(rgt)) { rgt.m_handle = nullptr; } WeakRealmNotifier& WeakRealmNotifier::operator=(WeakRealmNotifier&& rgt) { WeakRealmNotifierBase::operator=(std::move(rgt)); m_handle = rgt.m_handle; rgt.m_handle = nullptr; return *this; } WeakRealmNotifier::~WeakRealmNotifier() { if (m_handle) { uv_close((uv_handle_t*)m_handle, [](uv_handle_t* handle) { auto realm_weak_ptr = static_cast<std::weak_ptr<Realm>*>(handle->data); delete realm_weak_ptr; delete handle; }); } } void WeakRealmNotifier::notify() { if (m_handle) { uv_async_send(m_handle); } } <commit_msg>Create a HandleScope before calling callbacks<commit_after>//////////////////////////////////////////////////////////////////////////// // // Copyright 2016 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// #include <nan.h> #include "impl/weak_realm_notifier.hpp" #include "shared_realm.hpp" using namespace realm; using namespace realm::_impl; WeakRealmNotifier::WeakRealmNotifier(const std::shared_ptr<Realm>& realm, bool cache) : WeakRealmNotifierBase(realm, cache) , m_handle(new uv_async_t) { m_handle->data = new std::weak_ptr<Realm>(realm); // This assumes that only one thread matters: the main thread (default loop). uv_async_init(uv_default_loop(), m_handle, [](uv_async_t* handle) { auto realm_weak_ptr = static_cast<std::weak_ptr<Realm>*>(handle->data); auto realm = realm_weak_ptr->lock(); if (realm) { // The v8::Local handles need a "scope" to be present or will crash. Nan::HandleScope scope; realm->notify(); } }); } WeakRealmNotifier::WeakRealmNotifier(WeakRealmNotifier&& rgt) : WeakRealmNotifierBase(std::move(rgt)) { rgt.m_handle = nullptr; } WeakRealmNotifier& WeakRealmNotifier::operator=(WeakRealmNotifier&& rgt) { WeakRealmNotifierBase::operator=(std::move(rgt)); m_handle = rgt.m_handle; rgt.m_handle = nullptr; return *this; } WeakRealmNotifier::~WeakRealmNotifier() { if (m_handle) { uv_close((uv_handle_t*)m_handle, [](uv_handle_t* handle) { auto realm_weak_ptr = static_cast<std::weak_ptr<Realm>*>(handle->data); delete realm_weak_ptr; delete handle; }); } } void WeakRealmNotifier::notify() { if (m_handle) { uv_async_send(m_handle); } } <|endoftext|>
<commit_before>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace llvm; namespace cling { std::set<std::string> IncrementalExecutor::m_unresolvedSymbols; std::vector<IncrementalExecutor::LazyFunctionCreatorFunc_t> IncrementalExecutor::m_lazyFuncCreator; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine IncrementalExecutor::IncrementalExecutor(llvm::Module* m) : m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::IncrementalExecutor::IncrementalExecutor(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine IncrementalExecutor::~IncrementalExecutor() {} void IncrementalExecutor::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::remapCXAAtExit() { if (m_CxaAtExitRemapped) return; llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); if (!atExit) return; llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); assert(clingAtExit && "cling_cxa_atexit must exist."); void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg, const cling::Transaction* T) { // Register a CXAAtExit function m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, T)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "IncrementalExecutor: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } IncrementalExecutor::ExecutionResult IncrementalExecutor::executeFunction(llvm::StringRef funcname, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); remapCXAAtExit(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "IncrementalExecutor::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } assert (f->getFunctionType()->getNumParams() == 1 && (*f->getFunctionType()->param_begin())->isPtrOrPtrVectorTy() && "Wrong signature"); typedef void (*PromptWrapper_t)(void*); union { PromptWrapper_t wrapperFunction; void* address; } p2f; p2f.address = m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. if (ff) funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } // Run the function (*p2f.wrapperFunction)(returnValue); return kExeSuccess; } IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { remapCXAAtExit(); m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "IncrementalExecutor::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } //executeFunction(F->getName()); m_engine->runFunction(F, std::vector<llvm::GenericValue>()); // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. Function* GlobalVarInitF = cast<Function>(F->getEntryBlock().getFirstNonPHI()->getOperand(0)); F->eraseFromParent(); GlobalVarInitF->eraseFromParent(); } } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromT == T) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::Module* m, llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; remapCXAAtExit(); address = m_engine->getPointerToGlobal(gvar); } return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { remapCXAAtExit(); if (void* addr = m_engine->getPointerToGlobalIfAvailable(&GV)) return addr; // Function not yet codegened by the JIT, force this to happen now. return m_engine->getPointerToGlobal(&GV); } }// end namespace cling <commit_msg>Remove the functions after the loop is done.<commit_after>//--------------------------------------------------------------------*- C++ -*- // CLING - the C++ LLVM-based InterpreterG :) // author: Axel Naumann <axel@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "IncrementalExecutor.h" #include "llvm/IR/Constants.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/PassManager.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/ExecutionEngine/JIT.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/DynamicLibrary.h" using namespace llvm; namespace cling { std::set<std::string> IncrementalExecutor::m_unresolvedSymbols; std::vector<IncrementalExecutor::LazyFunctionCreatorFunc_t> IncrementalExecutor::m_lazyFuncCreator; // Keep in source: OwningPtr<ExecutionEngine> needs #include ExecutionEngine IncrementalExecutor::IncrementalExecutor(llvm::Module* m) : m_CxaAtExitRemapped(false) { assert(m && "llvm::Module must not be null!"); m_AtExitFuncs.reserve(256); // // Create an execution engine to use. // assert(m && "Module cannot be null"); // Note: Engine takes ownership of the module. llvm::EngineBuilder builder(m); std::string errMsg; builder.setErrorStr(&errMsg); builder.setOptLevel(llvm::CodeGenOpt::Less); builder.setEngineKind(llvm::EngineKind::JIT); builder.setAllocateGVsWithCode(false); // EngineBuilder uses default c'ted TargetOptions, too: llvm::TargetOptions TargetOpts; TargetOpts.NoFramePointerElim = 1; TargetOpts.JITEmitDebugInfo = 1; builder.setTargetOptions(TargetOpts); m_engine.reset(builder.create()); if (!m_engine) llvm::errs() << "cling::IncrementalExecutor::IncrementalExecutor(): " << errMsg; assert(m_engine && "Cannot create module!"); // install lazy function creators m_engine->InstallLazyFunctionCreator(NotifyLazyFunctionCreators); } // Keep in source: ~OwningPtr<ExecutionEngine> needs #include ExecutionEngine IncrementalExecutor::~IncrementalExecutor() {} void IncrementalExecutor::shuttingDown() { for (size_t I = 0, N = m_AtExitFuncs.size(); I < N; ++I) { const CXAAtExitElement& AEE = m_AtExitFuncs[N - I - 1]; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::remapCXAAtExit() { if (m_CxaAtExitRemapped) return; llvm::Function* atExit = m_engine->FindFunctionNamed("__cxa_atexit"); if (!atExit) return; llvm::Function* clingAtExit = m_engine->FindFunctionNamed("cling_cxa_atexit"); assert(clingAtExit && "cling_cxa_atexit must exist."); void* clingAtExitAddr = m_engine->getPointerToFunction(clingAtExit); assert(clingAtExitAddr && "cannot find cling_cxa_atexit"); m_engine->updateGlobalMapping(atExit, clingAtExitAddr); m_CxaAtExitRemapped = true; } void IncrementalExecutor::AddAtExitFunc(void (*func) (void*), void* arg, const cling::Transaction* T) { // Register a CXAAtExit function m_AtExitFuncs.push_back(CXAAtExitElement(func, arg, T)); } void unresolvedSymbol() { // throw exception? llvm::errs() << "IncrementalExecutor: calling unresolved symbol, " "see previous error message!\n"; } void* IncrementalExecutor::HandleMissingFunction(const std::string& mangled_name) { // Not found in the map, add the symbol in the list of unresolved symbols if (m_unresolvedSymbols.insert(mangled_name).second) { llvm::errs() << "IncrementalExecutor: use of undefined symbol '" << mangled_name << "'!\n"; } // Avoid "ISO C++ forbids casting between pointer-to-function and // pointer-to-object": return (void*)reinterpret_cast<size_t>(unresolvedSymbol); } void* IncrementalExecutor::NotifyLazyFunctionCreators(const std::string& mangled_name) { for (std::vector<LazyFunctionCreatorFunc_t>::iterator it = m_lazyFuncCreator.begin(), et = m_lazyFuncCreator.end(); it != et; ++it) { void* ret = (void*)((LazyFunctionCreatorFunc_t)*it)(mangled_name); if (ret) return ret; } return HandleMissingFunction(mangled_name); } static void freeCallersOfUnresolvedSymbols(llvm::SmallVectorImpl<llvm::Function*>& funcsToFree, llvm::ExecutionEngine* engine) { llvm::SmallPtrSet<llvm::Function*, 40> funcsToFreeUnique; for (size_t i = 0; i < funcsToFree.size(); ++i) { llvm::Function* func = funcsToFree[i]; assert(func && "Cannot free NULL function"); if (funcsToFreeUnique.insert(func)) { for (llvm::Value::use_iterator IU = func->use_begin(), EU = func->use_end(); IU != EU; ++IU) { llvm::Instruction* instUser = llvm::dyn_cast<llvm::Instruction>(*IU); if (!instUser) continue; if (!instUser->getParent()) continue; if (llvm::Function* userFunc = instUser->getParent()->getParent()) funcsToFree.push_back(userFunc); } } } for (llvm::SmallPtrSet<llvm::Function*, 40>::iterator I = funcsToFreeUnique.begin(), E = funcsToFreeUnique.end(); I != E; ++I) { // This should force the JIT to recompile the function. But the stubs stay, // and the JIT reuses the stubs now pointing nowhere, i.e. without updating // the machine code address. Fix the JIT, or hope that MCJIT helps. //engine->freeMachineCodeForFunction(*I); engine->updateGlobalMapping(*I, 0); } } IncrementalExecutor::ExecutionResult IncrementalExecutor::executeFunction(llvm::StringRef funcname, StoredValueRef* returnValue) { // Call a function without arguments, or with an SRet argument, see SRet below // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); remapCXAAtExit(); llvm::Function* f = m_engine->FindFunctionNamed(funcname.str().c_str()); if (!f) { llvm::errs() << "IncrementalExecutor::executeFunction: " "could not find function named " << funcname << '\n'; return kExeFunctionNotCompiled; } assert (f->getFunctionType()->getNumParams() == 1 && (*f->getFunctionType()->param_begin())->isPtrOrPtrVectorTy() && "Wrong signature"); typedef void (*PromptWrapper_t)(void*); union { PromptWrapper_t wrapperFunction; void* address; } p2f; p2f.address = m_engine->getPointerToFunction(f); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 128> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "IncrementalExecutor::executeFunction: symbol '" << *i << "' unresolved while linking function '" << funcname << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); // i could also reference a global variable, in which case ff == 0. if (ff) funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } // Run the function (*p2f.wrapperFunction)(returnValue); return kExeSuccess; } IncrementalExecutor::ExecutionResult IncrementalExecutor::runStaticInitializersOnce(llvm::Module* m) { assert(m && "Module must not be null"); assert(m_engine && "Code generation did not create an engine!"); llvm::GlobalVariable* GV = m->getGlobalVariable("llvm.global_ctors", true); // Nothing to do is good, too. if (!GV) return kExeSuccess; // Close similarity to // m_engine->runStaticConstructorsDestructors(false) aka // llvm::ExecutionEngine::runStaticConstructorsDestructors() // is intentional; we do an extra pass to check whether the JIT // managed to collect all the symbols needed by the niitializers. // Should be an array of '{ i32, void ()* }' structs. The first value is // the init priority, which we ignore. llvm::ConstantArray *InitList = llvm::dyn_cast<llvm::ConstantArray>(GV->getInitializer()); GV->eraseFromParent(); if (InitList == 0) return kExeSuccess; // We don't care whether something was unresolved before. m_unresolvedSymbols.clear(); SmallVector<Function*, 2> initFuncs; for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { llvm::ConstantStruct *CS = llvm::dyn_cast<llvm::ConstantStruct>(InitList->getOperand(i)); if (CS == 0) continue; llvm::Constant *FP = CS->getOperand(1); if (FP->isNullValue()) continue; // Found a sentinal value, ignore. // Strip off constant expression casts. if (llvm::ConstantExpr *CE = llvm::dyn_cast<llvm::ConstantExpr>(FP)) if (CE->isCast()) FP = CE->getOperand(0); // Execute the ctor/dtor function! if (llvm::Function *F = llvm::dyn_cast<llvm::Function>(FP)) { remapCXAAtExit(); m_engine->getPointerToFunction(F); // check if there is any unresolved symbol in the list if (!m_unresolvedSymbols.empty()) { llvm::SmallVector<llvm::Function*, 100> funcsToFree; for (std::set<std::string>::const_iterator i = m_unresolvedSymbols.begin(), e = m_unresolvedSymbols.end(); i != e; ++i) { llvm::errs() << "IncrementalExecutor::runStaticInitializersOnce: symbol '" << *i << "' unresolved while linking static initializer '" << F->getName() << "'!\n"; llvm::Function *ff = m_engine->FindFunctionNamed(i->c_str()); assert(ff && "cannot find function to free"); funcsToFree.push_back(ff); } freeCallersOfUnresolvedSymbols(funcsToFree, m_engine.get()); m_unresolvedSymbols.clear(); return kExeUnresolvedSymbols; } //executeFunction(F->getName()); m_engine->runFunction(F, std::vector<llvm::GenericValue>()); initFuncs.push_back(F); } } for (SmallVector<Function*,2>::iterator I = initFuncs.begin(), E = initFuncs.end(); I != E; ++I) { // Cleanup also the dangling init functions. They are in the form: // define internal void @_GLOBAL__I_aN() section "..."{ // entry: // call void @__cxx_global_var_init(N-1)() // ret void // } // // define internal void @__cxx_global_var_init(N-1)() section "..." { // entry: // call void @_ZN7MyClassC1Ev(%struct.MyClass* @n) // ret void // } // Erase __cxx_global_var_init(N-1)() first. Function* GlobalVarInitF = cast<Function>((*I)->getEntryBlock().getFirstNonPHI()->getOperand(0)); (*I)->eraseFromParent(); GlobalVarInitF->eraseFromParent(); } return kExeSuccess; } void IncrementalExecutor::runAndRemoveStaticDestructors(Transaction* T) { assert(T && "Must be set"); // Collect all the dtors bound to this transaction. AtExitFunctions boundToT; for (AtExitFunctions::iterator I = m_AtExitFuncs.begin(); I != m_AtExitFuncs.end();) if (I->m_FromT == T) { boundToT.push_back(*I); I = m_AtExitFuncs.erase(I); } else ++I; // 'Unload' the cxa_atexit entities. for (AtExitFunctions::reverse_iterator I = boundToT.rbegin(), E = boundToT.rend(); I != E; ++I) { const CXAAtExitElement& AEE = *I; (*AEE.m_Func)(AEE.m_Arg); } } void IncrementalExecutor::installLazyFunctionCreator(LazyFunctionCreatorFunc_t fp) { m_lazyFuncCreator.push_back(fp); } bool IncrementalExecutor::addSymbol(const char* symbolName, void* symbolAddress) { void* actualAddress = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (actualAddress) return false; llvm::sys::DynamicLibrary::AddSymbol(symbolName, symbolAddress); return true; } void* IncrementalExecutor::getAddressOfGlobal(llvm::Module* m, llvm::StringRef symbolName, bool* fromJIT /*=0*/) { // Return a symbol's address, and whether it was jitted. void* address = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(symbolName); if (address) { if (fromJIT) *fromJIT = false; } else { if (fromJIT) *fromJIT = true; llvm::GlobalVariable* gvar = m->getGlobalVariable(symbolName, true); if (!gvar) return 0; remapCXAAtExit(); address = m_engine->getPointerToGlobal(gvar); } return address; } void* IncrementalExecutor::getPointerToGlobalFromJIT(const llvm::GlobalValue& GV) { remapCXAAtExit(); if (void* addr = m_engine->getPointerToGlobalIfAvailable(&GV)) return addr; // Function not yet codegened by the JIT, force this to happen now. return m_engine->getPointerToGlobal(&GV); } }// end namespace cling <|endoftext|>
<commit_before>/********************************************************************************* * Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - initial code and implementation ********************************************************************************/ #ifndef polynomial_curve_test_suite_hpp #define polynomial_curve_test_suite_hpp #include <cmath> // std::pow, std::exp #include <typeinfo> // typeid #include <string> // std::string #include <sstream> // std::stringstream #include <iomanip> // std::setw #include <limits> // std::numeric_limits #include "eli/constants/math.hpp" #include "eli/geom/point/distance.hpp" #include "eli/geom/curve/length.hpp" #include "eli/geom/curve/curvature.hpp" #include "eli/geom/curve/pseudo/polynomial.hpp" #include "octave_helpers.hpp" template<typename data__> class polynomial_curve_test_suite : public Test::Suite { private: typedef eli::geom::curve::pseudo::polynomial<data__, 3> curve_type; typedef typename curve_type::point_type point_type; typedef typename curve_type::data_type data_type; typedef typename curve_type::index_type index_type; typedef typename curve_type::coefficient_type coefficient_type; protected: void AddTests(const float &) { // add the tests TEST_ADD(polynomial_curve_test_suite<float>::assignment_test); TEST_ADD(polynomial_curve_test_suite<float>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<float>::derivative_test); } void AddTests(const double &) { // add the tests TEST_ADD(polynomial_curve_test_suite<double>::assignment_test); TEST_ADD(polynomial_curve_test_suite<double>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<double>::derivative_test); } void AddTests(const long double &) { // add the tests TEST_ADD(polynomial_curve_test_suite<long double>::assignment_test); TEST_ADD(polynomial_curve_test_suite<long double>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<long double>::derivative_test); } public: polynomial_curve_test_suite() { AddTests(data__()); } ~polynomial_curve_test_suite() { } private: void octave_print(int figno, const std::vector<point_type, Eigen::aligned_allocator<point_type> > &pts, const curve_type &bez) const { size_t i; std::cout << "figure(" << figno << ");" << std::endl; std::cout << "xpts=[" << pts[0].x(); for (i=1; i<pts.size(); ++i) std::cout << ", " << pts[i].x(); std::cout << "];" << std::endl; std::cout << "ypts=[" << pts[0].y(); for (i=1; i<pts.size(); ++i) std::cout << ", " << pts[i].y(); std::cout << "];" << std::endl; std::vector<data_type> t(101); for (i=0; i<t.size(); ++i) t[i]=static_cast<data_type>(i)/(t.size()-1); std::cout << "xint=[" << bez.f(t[0])(0); for (i=1; i<t.size(); ++i) std::cout << ", " << bez.f(t[i])(0); std::cout << "];" << std::endl; std::cout << "yint=[" << bez.f(t[0])(1); for (i=1; i<t.size(); ++i) std::cout << ", " << bez.f(t[i])(1); std::cout << "];" << std::endl; std::cout << "plot(xpts, ypts, 'bo', xint, yint, 'k-');" << std::endl; } void assignment_test() { curve_type c1, c2; coefficient_type coef1(6), coef2(1), coef_out; // test setting coefficients coef1 << 2, 0, 1, 4, 1, 8; coef2 << 0; c1.set_coefficients(coef1, 0); c1.set_coefficients(coef2, 1); c1.set_coefficients(coef2, 2); c1.get_coefficients(coef_out, 0); TEST_ASSERT(coef1==coef_out); coef_out.setZero(); c1.get_coefficients(coef_out, 1); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); c1.get_coefficients(coef_out, 2); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); // test assignment operator c2=c1; c2.get_coefficients(coef_out, 0); TEST_ASSERT(coef1==coef_out); coef_out.setZero(); c2.get_coefficients(coef_out, 1); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); c2.get_coefficients(coef_out, 2); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); // test equivalence operator TEST_ASSERT(c1==c2); coef2 << 1; c2.set_coefficients(coef2, 2); TEST_ASSERT(c1!=c2); // test copy ctr curve_type c3(c1); TEST_ASSERT(c3==c1); } void evaluation_test() { curve_type c; coefficient_type coef1(5), coef2(2); point_type eval_out, eval_ref; data_type t; // set coefficients coef1 << 2, 4, 3, 1, 2; coef2 << 1, 1; c.set_coefficients(coef1, 0); c.set_coefficients(coef2, 1); // test evaluation at points t=0; eval_out=c.f(t); eval_ref << coef1(0), coef2(0), 0; TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=c.f(t); eval_ref << coef1.sum(), coef2.sum(), 0; TEST_ASSERT(eval_out==eval_ref); t=10; eval_out=c.f(t); eval_ref << 21342, 11, 0; TEST_ASSERT(eval_out==eval_ref); // if (typeid(data_type)==typeid(float)) // { // std::cout.flush(); // eli::test::octave_start(1); // eli::test::octave_print(1, c, "poly"); // eli::test::octave_finish(1); // } } void derivative_test() { #if 0 typedef eli::geom::curve::bezier<data__, 2> bezier_curve_type; data_type eps(std::numeric_limits<data__>::epsilon()); control_point_type cntrl_in[5]; typename bezier_curve_type::control_point_type bez_cntrl[5]; curve_type ebc; bezier_curve_type bc; typename curve_type::point_type eval_out, eval_ref; typename curve_type::data_type t; // set control points and create curves cntrl_in[0] << 2.0; cntrl_in[1] << 1.5; cntrl_in[2] << 0.0; cntrl_in[3] << 1.0; cntrl_in[4] << 0.5; bez_cntrl[0] << 0, 2; bez_cntrl[1] << 0.25, 1.5; bez_cntrl[2] << 0.5, 0; bez_cntrl[3] << 0.75, 1; bez_cntrl[4] << 1, 0.5; ebc.resize(4); bc.resize(4); for (index_type i=0; i<5; ++i) { ebc.set_control_point(cntrl_in[i], i); bc.set_control_point(bez_cntrl[i], i); } // test 1st derivative at end points t=0; eval_out=ebc.fp(t); eval_ref=bc.fp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fp(t); eval_ref=bc.fp(t); TEST_ASSERT(eval_out==eval_ref); // test 1st derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fp(t); eval_ref=bc.fp(t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<3*eps); } else { TEST_ASSERT(eval_out==eval_ref); } // test 2nd derivative at end points t=0; eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); TEST_ASSERT(eval_out==eval_ref); // test 2nd derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<17*eps); } else { TEST_ASSERT(eval_out==eval_ref); } // test 3rd derivative at end points t=0; eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); // test 3rd derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); // test curvature at end points data_type curv_out, curv_ref; t=0; eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); TEST_ASSERT(curv_out==curv_ref); t=1; eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); TEST_ASSERT(curv_out==curv_ref); // test curvature at interior point t=static_cast<data__>(0.45); eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<3*eps); } else { TEST_ASSERT(curv_out==curv_ref); } #endif } }; #endif <commit_msg>Removed unused method in test suite.<commit_after>/********************************************************************************* * Copyright (c) 2014 David D. Marshall <ddmarsha@calpoly.edu> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * David D. Marshall - initial code and implementation ********************************************************************************/ #ifndef polynomial_curve_test_suite_hpp #define polynomial_curve_test_suite_hpp #include <cmath> // std::pow, std::exp #include <typeinfo> // typeid #include <string> // std::string #include <sstream> // std::stringstream #include <iomanip> // std::setw #include <limits> // std::numeric_limits #include "eli/constants/math.hpp" #include "eli/geom/point/distance.hpp" #include "eli/geom/curve/length.hpp" #include "eli/geom/curve/curvature.hpp" #include "eli/geom/curve/pseudo/polynomial.hpp" #include "octave_helpers.hpp" template<typename data__> class polynomial_curve_test_suite : public Test::Suite { private: typedef eli::geom::curve::pseudo::polynomial<data__, 3> curve_type; typedef typename curve_type::point_type point_type; typedef typename curve_type::data_type data_type; typedef typename curve_type::index_type index_type; typedef typename curve_type::coefficient_type coefficient_type; protected: void AddTests(const float &) { // add the tests TEST_ADD(polynomial_curve_test_suite<float>::assignment_test); TEST_ADD(polynomial_curve_test_suite<float>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<float>::derivative_test); } void AddTests(const double &) { // add the tests TEST_ADD(polynomial_curve_test_suite<double>::assignment_test); TEST_ADD(polynomial_curve_test_suite<double>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<double>::derivative_test); } void AddTests(const long double &) { // add the tests TEST_ADD(polynomial_curve_test_suite<long double>::assignment_test); TEST_ADD(polynomial_curve_test_suite<long double>::evaluation_test); TEST_ADD(polynomial_curve_test_suite<long double>::derivative_test); } public: polynomial_curve_test_suite() { AddTests(data__()); } ~polynomial_curve_test_suite() { } private: void assignment_test() { curve_type c1, c2; coefficient_type coef1(6), coef2(1), coef_out; // test setting coefficients coef1 << 2, 0, 1, 4, 1, 8; coef2 << 0; c1.set_coefficients(coef1, 0); c1.set_coefficients(coef2, 1); c1.set_coefficients(coef2, 2); c1.get_coefficients(coef_out, 0); TEST_ASSERT(coef1==coef_out); coef_out.setZero(); c1.get_coefficients(coef_out, 1); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); c1.get_coefficients(coef_out, 2); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); // test assignment operator c2=c1; c2.get_coefficients(coef_out, 0); TEST_ASSERT(coef1==coef_out); coef_out.setZero(); c2.get_coefficients(coef_out, 1); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); c2.get_coefficients(coef_out, 2); TEST_ASSERT(coef2==coef_out); coef_out.setZero(); // test equivalence operator TEST_ASSERT(c1==c2); coef2 << 1; c2.set_coefficients(coef2, 2); TEST_ASSERT(c1!=c2); // test copy ctr curve_type c3(c1); TEST_ASSERT(c3==c1); } void evaluation_test() { curve_type c; coefficient_type coef1(5), coef2(2); point_type eval_out, eval_ref; data_type t; // set coefficients coef1 << 2, 4, 3, 1, 2; coef2 << 1, 1; c.set_coefficients(coef1, 0); c.set_coefficients(coef2, 1); // test evaluation at points t=0; eval_out=c.f(t); eval_ref << coef1(0), coef2(0), 0; TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=c.f(t); eval_ref << coef1.sum(), coef2.sum(), 0; TEST_ASSERT(eval_out==eval_ref); t=10; eval_out=c.f(t); eval_ref << 21342, 11, 0; TEST_ASSERT(eval_out==eval_ref); // if (typeid(data_type)==typeid(float)) // { // std::cout.flush(); // eli::test::octave_start(1); // eli::test::octave_print(1, c, "poly"); // eli::test::octave_finish(1); // } } void derivative_test() { #if 0 typedef eli::geom::curve::bezier<data__, 2> bezier_curve_type; data_type eps(std::numeric_limits<data__>::epsilon()); control_point_type cntrl_in[5]; typename bezier_curve_type::control_point_type bez_cntrl[5]; curve_type ebc; bezier_curve_type bc; typename curve_type::point_type eval_out, eval_ref; typename curve_type::data_type t; // set control points and create curves cntrl_in[0] << 2.0; cntrl_in[1] << 1.5; cntrl_in[2] << 0.0; cntrl_in[3] << 1.0; cntrl_in[4] << 0.5; bez_cntrl[0] << 0, 2; bez_cntrl[1] << 0.25, 1.5; bez_cntrl[2] << 0.5, 0; bez_cntrl[3] << 0.75, 1; bez_cntrl[4] << 1, 0.5; ebc.resize(4); bc.resize(4); for (index_type i=0; i<5; ++i) { ebc.set_control_point(cntrl_in[i], i); bc.set_control_point(bez_cntrl[i], i); } // test 1st derivative at end points t=0; eval_out=ebc.fp(t); eval_ref=bc.fp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fp(t); eval_ref=bc.fp(t); TEST_ASSERT(eval_out==eval_ref); // test 1st derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fp(t); eval_ref=bc.fp(t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<3*eps); } else { TEST_ASSERT(eval_out==eval_ref); } // test 2nd derivative at end points t=0; eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); TEST_ASSERT(eval_out==eval_ref); // test 2nd derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fpp(t); eval_ref=bc.fpp(t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<17*eps); } else { TEST_ASSERT(eval_out==eval_ref); } // test 3rd derivative at end points t=0; eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); t=1; eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); // test 3rd derivative at interior point t=static_cast<data__>(0.45); eval_out=ebc.fppp(t); eval_ref=bc.fppp(t); TEST_ASSERT(eval_out==eval_ref); // test curvature at end points data_type curv_out, curv_ref; t=0; eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); TEST_ASSERT(curv_out==curv_ref); t=1; eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); TEST_ASSERT(curv_out==curv_ref); // test curvature at interior point t=static_cast<data__>(0.45); eli::geom::curve::curvature(curv_out, ebc, t); eli::geom::curve::curvature(curv_ref, bc, t); if (typeid(data__)==typeid(float)) { TEST_ASSERT((eval_out-eval_ref).norm()<3*eps); } else { TEST_ASSERT(curv_out==curv_ref); } #endif } }; #endif <|endoftext|>
<commit_before>//===- PowerPCInstrInfo.cpp - PowerPC Instruction Information ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the PowerPC implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "PowerPCInstrInfo.h" #include "PowerPC.h" #include "PowerPCGenInstrInfo.inc" #include "llvm/CodeGen/MachineInstrBuilder.h" #include <iostream> using namespace llvm; PowerPCInstrInfo::PowerPCInstrInfo() : TargetInstrInfo(PowerPCInsts, sizeof(PowerPCInsts)/sizeof(PowerPCInsts[0])) { } bool PowerPCInstrInfo::isMoveInstr(const MachineInstr& MI, unsigned& sourceReg, unsigned& destReg) const { MachineOpCode oc = MI.getOpcode(); if (oc == PPC32::OR) { assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isRegister() && "invalid register-register int move instruction"); if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC32::FMR) { assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid register-register fp move instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } return false; } <commit_msg>* Recognize `addi r1, r2, 0' a move instruction * List formats of instructions currently recognized as moves<commit_after>//===- PowerPCInstrInfo.cpp - PowerPC Instruction Information ---*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains the PowerPC implementation of the TargetInstrInfo class. // //===----------------------------------------------------------------------===// #include "PowerPCInstrInfo.h" #include "PowerPC.h" #include "PowerPCGenInstrInfo.inc" #include "llvm/CodeGen/MachineInstrBuilder.h" #include <iostream> using namespace llvm; PowerPCInstrInfo::PowerPCInstrInfo() : TargetInstrInfo(PowerPCInsts, sizeof(PowerPCInsts)/sizeof(PowerPCInsts[0])) { } bool PowerPCInstrInfo::isMoveInstr(const MachineInstr& MI, unsigned& sourceReg, unsigned& destReg) const { MachineOpCode oc = MI.getOpcode(); if (oc == PPC32::OR) { // or r1, r2, r2 assert(MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isRegister() && "invalid register-register int move instruction"); if (MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC32::ADDI) { // addi r1, r2, 0 if (MI.getNumOperands() == 3 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && MI.getOperand(2).isImmediate() && MI.getOperand(2).getImmedValue() == 0) { sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } } else if (oc == PPC32::FMR) { // fmr r1, r2 assert(MI.getNumOperands() == 2 && MI.getOperand(0).isRegister() && MI.getOperand(1).isRegister() && "invalid register-register fp move instruction"); sourceReg = MI.getOperand(1).getReg(); destReg = MI.getOperand(0).getReg(); return true; } return false; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "documentmodel.h" #include "ieditor.h" #include <coreplugin/idocument.h> #include <utils/qtcassert.h> #include <QDir> #include <QIcon> namespace Core { struct DocumentModelPrivate { DocumentModelPrivate(); ~DocumentModelPrivate(); const QIcon m_lockedIcon; const QIcon m_unlockedIcon; QList<DocumentModel::Entry *> m_documents; QMap<IDocument *, QList<IEditor *> > m_editors; }; DocumentModelPrivate::DocumentModelPrivate() : m_lockedIcon(QLatin1String(":/core/images/locked.png")), m_unlockedIcon(QLatin1String(":/core/images/unlocked.png")) { } DocumentModelPrivate::~DocumentModelPrivate() { qDeleteAll(m_documents); } DocumentModel::Entry::Entry() : document(0) { } DocumentModel::DocumentModel(QObject *parent) : QAbstractItemModel(parent), d(new DocumentModelPrivate) { } DocumentModel::~DocumentModel() { delete d; } QIcon DocumentModel::lockedIcon() const { return d->m_lockedIcon; } QIcon DocumentModel::unlockedIcon() const { return d->m_unlockedIcon; } QString DocumentModel::Entry::fileName() const { return document ? document->filePath() : m_fileName; } QString DocumentModel::Entry::displayName() const { return document ? document->displayName() : m_displayName; } Id DocumentModel::Entry::id() const { return m_id; } int DocumentModel::columnCount(const QModelIndex &parent) const { if (!parent.isValid()) return 2; return 0; } int DocumentModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) return d->m_documents.count() + 1/*<no document>*/; return 0; } // TODO remove QList<IEditor *> DocumentModel::oneEditorForEachOpenedDocument() const { QList<IEditor *> result; QMapIterator<IDocument *, QList<IEditor *> > it(d->m_editors); while (it.hasNext()) result << it.next().value().first(); return result; } void DocumentModel::addEditor(IEditor *editor, bool *isNewDocument) { if (!editor) return; QList<IEditor *> &editorList = d->m_editors[editor->document()]; bool isNew = editorList.isEmpty(); if (isNewDocument) *isNewDocument = isNew; editorList << editor; if (isNew) { Entry *entry = new Entry; entry->document = editor->document(); entry->m_id = editor->id(); addEntry(entry); } } void DocumentModel::addRestoredDocument(const QString &fileName, const QString &displayName, const Id &id) { Entry *entry = new Entry; entry->m_fileName = fileName; entry->m_displayName = displayName; entry->m_id = id; addEntry(entry); } DocumentModel::Entry *DocumentModel::firstRestoredDocument() const { for (int i = 0; i < d->m_documents.count(); ++i) if (!d->m_documents.at(i)->document) return d->m_documents.at(i); return 0; } void DocumentModel::addEntry(Entry *entry) { QString fileName = entry->fileName(); // replace a non-loaded entry (aka 'restored') if possible int previousIndex = indexOfFilePath(fileName); if (previousIndex >= 0) { if (entry->document && d->m_documents.at(previousIndex)->document == 0) { Entry *previousEntry = d->m_documents.at(previousIndex); d->m_documents[previousIndex] = entry; delete previousEntry; connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged())); } else { delete entry; } return; } int index; QString displayName = entry->displayName(); for (index = 0; index < d->m_documents.count(); ++index) { if (displayName < d->m_documents.at(index)->displayName()) break; } int row = index + 1/*<no document>*/; beginInsertRows(QModelIndex(), row, row); d->m_documents.insert(index, entry); if (entry->document) connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged())); endInsertRows(); } int DocumentModel::indexOfFilePath(const QString &filePath) const { if (filePath.isEmpty()) return -1; for (int i = 0; i < d->m_documents.count(); ++i) { if (d->m_documents.at(i)->fileName() == filePath) return i; } return -1; } void DocumentModel::removeEntry(DocumentModel::Entry *entry) { QTC_ASSERT(!entry->document, return); // we wouldn't know what to do with the associated editors int index = d->m_documents.indexOf(entry); removeDocument(index); } void DocumentModel::removeEditor(IEditor *editor, bool *lastOneForDocument) { if (lastOneForDocument) *lastOneForDocument = false; QTC_ASSERT(editor, return); IDocument *document = editor->document(); QTC_ASSERT(d->m_editors.contains(document), return); d->m_editors[document].removeAll(editor); if (d->m_editors.value(document).isEmpty()) { if (lastOneForDocument) *lastOneForDocument = true; d->m_editors.remove(document); removeDocument(indexOfDocument(document)); } } void DocumentModel::removeDocument(const QString &fileName) { int index = indexOfFilePath(fileName); QTC_ASSERT(!d->m_documents.at(index)->document, return); // we wouldn't know what to do with the associated editors removeDocument(index); } void DocumentModel::removeDocument(int idx) { if (idx < 0) return; QTC_ASSERT(idx < d->m_documents.size(), return); IDocument *document = d->m_documents.at(idx)->document; int row = idx + 1/*<no document>*/; beginRemoveRows(QModelIndex(), row, row); delete d->m_documents.takeAt(idx); endRemoveRows(); if (document) disconnect(document, SIGNAL(changed()), this, SLOT(itemChanged())); } void DocumentModel::removeAllRestoredDocuments() { for (int i = d->m_documents.count()-1; i >= 0; --i) { if (!d->m_documents.at(i)->document) { int row = i + 1/*<no document>*/; beginRemoveRows(QModelIndex(), row, row); delete d->m_documents.takeAt(i); endRemoveRows(); } } } QList<IEditor *> DocumentModel::editorsForDocument(IDocument *document) const { return d->m_editors.value(document); } QList<IEditor *> DocumentModel::editorsForDocuments(const QList<IDocument *> &documents) const { QList<IEditor *> result; foreach (IDocument *document, documents) result += d->m_editors.value(document); return result; } int DocumentModel::indexOfDocument(IDocument *document) const { for (int i = 0; i < d->m_documents.count(); ++i) if (d->m_documents.at(i)->document == document) return i; return -1; } DocumentModel::Entry *DocumentModel::entryForDocument(IDocument *document) const { int index = indexOfDocument(document); if (index < 0) return 0; return d->m_documents.at(index); } QList<IDocument *> DocumentModel::openedDocuments() const { return d->m_editors.keys(); } IDocument *DocumentModel::documentForFilePath(const QString &filePath) const { int index = indexOfFilePath(filePath); if (index < 0) return 0; return d->m_documents.at(index)->document; } QList<IEditor *> DocumentModel::editorsForFilePath(const QString &filePath) const { IDocument *document = documentForFilePath(filePath); if (document) return editorsForDocument(document); return QList<IEditor *>(); } QModelIndex DocumentModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent) if (column < 0 || column > 1 || row < 0 || row >= d->m_documents.count() + 1/*<no document>*/) return QModelIndex(); return createIndex(row, column); } DocumentModel::Entry *DocumentModel::documentAtRow(int row) const { int entryIndex = row - 1/*<no document>*/; if (entryIndex < 0) return 0; return d->m_documents[entryIndex]; } int DocumentModel::documentCount() const { return d->m_documents.count(); } QVariant DocumentModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole)) return QVariant(); int entryIndex = index.row() - 1/*<no document>*/; if (entryIndex < 0) { // <no document> entry switch (role) { case Qt::DisplayRole: return tr("<no document>"); case Qt::ToolTipRole: return tr("No document is selected."); default: return QVariant(); } } const Entry *e = d->m_documents.at(entryIndex); switch (role) { case Qt::DisplayRole: return (e->document && e->document->isModified()) ? e->displayName() + QLatin1Char('*') : e->displayName(); case Qt::DecorationRole: { bool showLock = false; if (e->document) { showLock = e->document->filePath().isEmpty() ? false : e->document->isFileReadOnly(); } else { showLock = !QFileInfo(e->m_fileName).isWritable(); } return showLock ? d->m_lockedIcon : QIcon(); } case Qt::ToolTipRole: return e->fileName().isEmpty() ? e->displayName() : QDir::toNativeSeparators(e->fileName()); default: return QVariant(); } return QVariant(); } int DocumentModel::rowOfDocument(IDocument *document) const { if (!document) return 0 /*<no document>*/; return indexOfDocument(document) + 1/*<no document>*/; } void DocumentModel::itemChanged() { IDocument *document = qobject_cast<IDocument *>(sender()); int idx = indexOfDocument(document); if (idx < 0) return; QModelIndex mindex = index(idx + 1/*<no document>*/, 0); emit dataChanged(mindex, mindex); } QList<DocumentModel::Entry *> DocumentModel::documents() const { return d->m_documents; } } // namespace Core <commit_msg>Resolve links and normalize file names when opening editors again.<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "documentmodel.h" #include "ieditor.h" #include <coreplugin/documentmanager.h> #include <coreplugin/idocument.h> #include <utils/qtcassert.h> #include <QDir> #include <QIcon> namespace Core { struct DocumentModelPrivate { DocumentModelPrivate(); ~DocumentModelPrivate(); const QIcon m_lockedIcon; const QIcon m_unlockedIcon; QList<DocumentModel::Entry *> m_documents; QMap<IDocument *, QList<IEditor *> > m_editors; }; DocumentModelPrivate::DocumentModelPrivate() : m_lockedIcon(QLatin1String(":/core/images/locked.png")), m_unlockedIcon(QLatin1String(":/core/images/unlocked.png")) { } DocumentModelPrivate::~DocumentModelPrivate() { qDeleteAll(m_documents); } DocumentModel::Entry::Entry() : document(0) { } DocumentModel::DocumentModel(QObject *parent) : QAbstractItemModel(parent), d(new DocumentModelPrivate) { } DocumentModel::~DocumentModel() { delete d; } QIcon DocumentModel::lockedIcon() const { return d->m_lockedIcon; } QIcon DocumentModel::unlockedIcon() const { return d->m_unlockedIcon; } QString DocumentModel::Entry::fileName() const { return document ? document->filePath() : m_fileName; } QString DocumentModel::Entry::displayName() const { return document ? document->displayName() : m_displayName; } Id DocumentModel::Entry::id() const { return m_id; } int DocumentModel::columnCount(const QModelIndex &parent) const { if (!parent.isValid()) return 2; return 0; } int DocumentModel::rowCount(const QModelIndex &parent) const { if (!parent.isValid()) return d->m_documents.count() + 1/*<no document>*/; return 0; } // TODO remove QList<IEditor *> DocumentModel::oneEditorForEachOpenedDocument() const { QList<IEditor *> result; QMapIterator<IDocument *, QList<IEditor *> > it(d->m_editors); while (it.hasNext()) result << it.next().value().first(); return result; } void DocumentModel::addEditor(IEditor *editor, bool *isNewDocument) { if (!editor) return; QList<IEditor *> &editorList = d->m_editors[editor->document()]; bool isNew = editorList.isEmpty(); if (isNewDocument) *isNewDocument = isNew; editorList << editor; if (isNew) { Entry *entry = new Entry; entry->document = editor->document(); entry->m_id = editor->id(); addEntry(entry); } } void DocumentModel::addRestoredDocument(const QString &fileName, const QString &displayName, const Id &id) { Entry *entry = new Entry; entry->m_fileName = fileName; entry->m_displayName = displayName; entry->m_id = id; addEntry(entry); } DocumentModel::Entry *DocumentModel::firstRestoredDocument() const { for (int i = 0; i < d->m_documents.count(); ++i) if (!d->m_documents.at(i)->document) return d->m_documents.at(i); return 0; } void DocumentModel::addEntry(Entry *entry) { QString fileName = entry->fileName(); // replace a non-loaded entry (aka 'restored') if possible int previousIndex = indexOfFilePath(fileName); if (previousIndex >= 0) { if (entry->document && d->m_documents.at(previousIndex)->document == 0) { Entry *previousEntry = d->m_documents.at(previousIndex); d->m_documents[previousIndex] = entry; delete previousEntry; connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged())); } else { delete entry; } return; } int index; QString displayName = entry->displayName(); for (index = 0; index < d->m_documents.count(); ++index) { if (displayName < d->m_documents.at(index)->displayName()) break; } int row = index + 1/*<no document>*/; beginInsertRows(QModelIndex(), row, row); d->m_documents.insert(index, entry); if (entry->document) connect(entry->document, SIGNAL(changed()), this, SLOT(itemChanged())); endInsertRows(); } int DocumentModel::indexOfFilePath(const QString &filePath) const { if (filePath.isEmpty()) return -1; const QString fixedPath = DocumentManager::fixFileName(filePath, DocumentManager::KeepLinks); for (int i = 0; i < d->m_documents.count(); ++i) { if (DocumentManager::fixFileName(d->m_documents.at(i)->fileName(), DocumentManager::KeepLinks) == fixedPath) return i; } return -1; } void DocumentModel::removeEntry(DocumentModel::Entry *entry) { QTC_ASSERT(!entry->document, return); // we wouldn't know what to do with the associated editors int index = d->m_documents.indexOf(entry); removeDocument(index); } void DocumentModel::removeEditor(IEditor *editor, bool *lastOneForDocument) { if (lastOneForDocument) *lastOneForDocument = false; QTC_ASSERT(editor, return); IDocument *document = editor->document(); QTC_ASSERT(d->m_editors.contains(document), return); d->m_editors[document].removeAll(editor); if (d->m_editors.value(document).isEmpty()) { if (lastOneForDocument) *lastOneForDocument = true; d->m_editors.remove(document); removeDocument(indexOfDocument(document)); } } void DocumentModel::removeDocument(const QString &fileName) { int index = indexOfFilePath(fileName); QTC_ASSERT(!d->m_documents.at(index)->document, return); // we wouldn't know what to do with the associated editors removeDocument(index); } void DocumentModel::removeDocument(int idx) { if (idx < 0) return; QTC_ASSERT(idx < d->m_documents.size(), return); IDocument *document = d->m_documents.at(idx)->document; int row = idx + 1/*<no document>*/; beginRemoveRows(QModelIndex(), row, row); delete d->m_documents.takeAt(idx); endRemoveRows(); if (document) disconnect(document, SIGNAL(changed()), this, SLOT(itemChanged())); } void DocumentModel::removeAllRestoredDocuments() { for (int i = d->m_documents.count()-1; i >= 0; --i) { if (!d->m_documents.at(i)->document) { int row = i + 1/*<no document>*/; beginRemoveRows(QModelIndex(), row, row); delete d->m_documents.takeAt(i); endRemoveRows(); } } } QList<IEditor *> DocumentModel::editorsForDocument(IDocument *document) const { return d->m_editors.value(document); } QList<IEditor *> DocumentModel::editorsForDocuments(const QList<IDocument *> &documents) const { QList<IEditor *> result; foreach (IDocument *document, documents) result += d->m_editors.value(document); return result; } int DocumentModel::indexOfDocument(IDocument *document) const { for (int i = 0; i < d->m_documents.count(); ++i) if (d->m_documents.at(i)->document == document) return i; return -1; } DocumentModel::Entry *DocumentModel::entryForDocument(IDocument *document) const { int index = indexOfDocument(document); if (index < 0) return 0; return d->m_documents.at(index); } QList<IDocument *> DocumentModel::openedDocuments() const { return d->m_editors.keys(); } IDocument *DocumentModel::documentForFilePath(const QString &filePath) const { int index = indexOfFilePath(filePath); if (index < 0) return 0; return d->m_documents.at(index)->document; } QList<IEditor *> DocumentModel::editorsForFilePath(const QString &filePath) const { IDocument *document = documentForFilePath(filePath); if (document) return editorsForDocument(document); return QList<IEditor *>(); } QModelIndex DocumentModel::index(int row, int column, const QModelIndex &parent) const { Q_UNUSED(parent) if (column < 0 || column > 1 || row < 0 || row >= d->m_documents.count() + 1/*<no document>*/) return QModelIndex(); return createIndex(row, column); } DocumentModel::Entry *DocumentModel::documentAtRow(int row) const { int entryIndex = row - 1/*<no document>*/; if (entryIndex < 0) return 0; return d->m_documents[entryIndex]; } int DocumentModel::documentCount() const { return d->m_documents.count(); } QVariant DocumentModel::data(const QModelIndex &index, int role) const { if (!index.isValid() || (index.column() != 0 && role < Qt::UserRole)) return QVariant(); int entryIndex = index.row() - 1/*<no document>*/; if (entryIndex < 0) { // <no document> entry switch (role) { case Qt::DisplayRole: return tr("<no document>"); case Qt::ToolTipRole: return tr("No document is selected."); default: return QVariant(); } } const Entry *e = d->m_documents.at(entryIndex); switch (role) { case Qt::DisplayRole: return (e->document && e->document->isModified()) ? e->displayName() + QLatin1Char('*') : e->displayName(); case Qt::DecorationRole: { bool showLock = false; if (e->document) { showLock = e->document->filePath().isEmpty() ? false : e->document->isFileReadOnly(); } else { showLock = !QFileInfo(e->m_fileName).isWritable(); } return showLock ? d->m_lockedIcon : QIcon(); } case Qt::ToolTipRole: return e->fileName().isEmpty() ? e->displayName() : QDir::toNativeSeparators(e->fileName()); default: return QVariant(); } return QVariant(); } int DocumentModel::rowOfDocument(IDocument *document) const { if (!document) return 0 /*<no document>*/; return indexOfDocument(document) + 1/*<no document>*/; } void DocumentModel::itemChanged() { IDocument *document = qobject_cast<IDocument *>(sender()); int idx = indexOfDocument(document); if (idx < 0) return; QModelIndex mindex = index(idx + 1/*<no document>*/, 0); emit dataChanged(mindex, mindex); } QList<DocumentModel::Entry *> DocumentModel::documents() const { return d->m_documents; } } // namespace Core <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::fast_conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { tmp_result(batch) = h_s_padded(batch)(k) >> w_padded(channel)(k); tmp_result(batch).ifft2_inplace(); for (std::size_t i = 0; i < etl::size(tmp_result(batch)); ++i) { h_cv(batch)(1)[i] += tmp_result(batch)[i].real(); } } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::fast_conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif <commit_msg>Speed up batch_compute_hcv<commit_after>//======================================================================= // Copyright (c) 2014-2016 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef DLL_STANDARD_CONV_RBM_HPP #define DLL_STANDARD_CONV_RBM_HPP #include "base_conf.hpp" //The configuration helpers #include "rbm_base.hpp" //The base class #include "layer_traits.hpp" //layer_traits #include "util/checks.hpp" //nan_check #include "util/timers.hpp" //auto_timer namespace dll { /*! * \brief Standard version of Convolutional Restricted Boltzmann Machine * * This follows the definition of a CRBM by Honglak Lee. This is an "abstract" class, * using CRTP to inject features into its children. */ template <typename Parent, typename Desc> struct standard_conv_rbm : public rbm_base<Parent, Desc> { using desc = Desc; using parent_t = Parent; using this_type = standard_conv_rbm<parent_t, desc>; using base_type = rbm_base<parent_t, Desc>; using weight = typename desc::weight; static constexpr const unit_type visible_unit = desc::visible_unit; static constexpr const unit_type hidden_unit = desc::hidden_unit; static_assert(visible_unit == unit_type::BINARY || visible_unit == unit_type::GAUSSIAN, "Only binary and linear visible units are supported"); static_assert(hidden_unit == unit_type::BINARY || is_relu(hidden_unit), "Only binary hidden units are supported"); double std_gaussian = 0.2; double c_sigm = 1.0; //Constructors standard_conv_rbm() { //Note: Convolutional RBM needs lower learning rate than standard RBM //Better initialization of learning rate base_type::learning_rate = visible_unit == unit_type::GAUSSIAN ? 1e-5 : is_relu(hidden_unit) ? 1e-4 : /* Only Gaussian Units needs lower rate */ 1e-3; } parent_t& as_derived() { return *static_cast<parent_t*>(this); } const parent_t& as_derived() const { return *static_cast<const parent_t*>(this); } //Utility functions template <typename Sample> void reconstruct(const Sample& items) { reconstruct(items, as_derived()); } void display_visible_unit_activations() const { display_visible_unit_activations(as_derived()); } void display_visible_unit_samples() const { display_visible_unit_samples(as_derived()); } void display_hidden_unit_activations() const { display_hidden_unit_samples(as_derived()); } void display_hidden_unit_samples() const { display_hidden_unit_samples(as_derived()); } protected: template <typename W> static void deep_fflip(W&& w_f) { //flip all the kernels horizontally and vertically for (std::size_t channel = 0; channel < etl::dim<0>(w_f); ++channel) { for (size_t k = 0; k < etl::dim<1>(w_f); ++k) { w_f(channel)(k).fflip_inplace(); } } } template <typename L, typename V1, typename VCV, typename W> static void compute_vcv(const V1& v_a, VCV&& v_cv, W&& w) { dll::auto_timer timer("crbm:compute_vcv"); static constexpr const auto NC = L::NC; auto w_f = etl::force_temporary(w); deep_fflip(w_f); v_cv(1) = 0; for (std::size_t channel = 0; channel < NC; ++channel) { etl::conv_2d_valid_multi(v_a(channel), w_f(channel), v_cv(0)); v_cv(1) += v_cv(0); } nan_check_deep(v_cv); } template <typename L, typename H2, typename HCV, typename W, typename Functor> static void compute_hcv(const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:compute_hcv"); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(0) = etl::fast_conv_2d_full(h_s(k), w(channel)(k)); h_cv(1) += h_cv(0); } activate(channel); } } #ifdef ETL_MKL_MODE template <typename F1, typename F2> static void deep_pad(const F1& in, F2& out) { for (std::size_t outer1 = 0; outer1 < in.template dim<0>(); ++outer1) { for (std::size_t outer2 = 0; outer2 < in.template dim<1>(); ++outer2) { auto* out_m = out(outer1)(outer2).memory_start(); auto* in_m = in(outer1)(outer2).memory_start(); for (std::size_t i = 0; i < in.template dim<2>(); ++i) { for (std::size_t j = 0; j < in.template dim<3>(); ++j) { out_m[i * out.template dim<3>() + j] = in_m[i * in.template dim<3>() + j]; } } } } } template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:mkl"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; static constexpr const auto NV1 = L::NV1; static constexpr const auto NV2 = L::NV2; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> h_s_padded; etl::fast_dyn_matrix<std::complex<weight>, NC, K, NV1, NV2> w_padded; etl::fast_dyn_matrix<std::complex<weight>, Batch, K, NV1, NV2> tmp_result; deep_pad(h_s, h_s_padded); deep_pad(w, w_padded); h_s_padded.fft2_many_inplace(); w_padded.fft2_many_inplace(); maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; tmp_result(batch) = h_s_padded(batch) >> w_padded(channel); tmp_result(batch).ifft2_many_inplace(); for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(1) += etl::real(tmp_result(batch)(k)); } activate(batch, channel); } }); } #else template <typename L, typename TP, typename H2, typename HCV, typename W, typename Functor> static void batch_compute_hcv(TP& pool, const H2& h_s, HCV&& h_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_hcv:std"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto K = L::K; static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { for (std::size_t channel = 0; channel < NC; ++channel) { h_cv(batch)(1) = 0.0; for (std::size_t k = 0; k < K; ++k) { h_cv(batch)(0) = etl::fast_conv_2d_full(h_s(batch)(k), w(channel)(k)); h_cv(batch)(1) += h_cv(batch)(0); } activate(batch, channel); } }); } #endif template <typename L, typename TP, typename V1, typename VCV, typename W, typename Functor> static void batch_compute_vcv(TP& pool, const V1& v_a, VCV&& v_cv, W&& w, Functor activate) { dll::auto_timer timer("crbm:batch_compute_vcv"); static constexpr const auto Batch = layer_traits<L>::batch_size(); static constexpr const auto NC = L::NC; maybe_parallel_foreach_n(pool, 0, Batch, [&](std::size_t batch) { etl::conv_2d_valid_multi_flipped(v_a(batch)(0), w(0), v_cv(batch)(1)); for (std::size_t channel = 1; channel < NC; ++channel) { etl::conv_2d_valid_multi_flipped(v_a(batch)(channel), w(channel), v_cv(batch)(0)); v_cv(batch)(1) += v_cv(batch)(0); } activate(batch); }); } private: //Since the sub classes do not have the same fields, it is not possible //to put the fields in standard_rbm, therefore, it is necessary to use template //functions to implement the details template <typename Sample> static void reconstruct(const Sample& items, parent_t& rbm) { cpp_assert(items.size() == parent_t::input_size(), "The size of the training sample must match visible units"); cpp::stop_watch<> watch; //Set the state of the visible units rbm.v1 = items; rbm.activate_hidden(rbm.h1_a, rbm.h1_s, rbm.v1, rbm.v1); rbm.activate_visible(rbm.h1_a, rbm.h1_s, rbm.v2_a, rbm.v2_s); rbm.activate_hidden(rbm.h2_a, rbm.h2_s, rbm.v2_a, rbm.v2_s); std::cout << "Reconstruction took " << watch.elapsed() << "ms" << std::endl; } static void display_visible_unit_activations(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_a(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_visible_unit_samples(const parent_t& rbm) { for (std::size_t channel = 0; channel < parent_t::NC; ++channel) { std::cout << "Channel " << channel << std::endl; for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.v2_s(channel, i, j) << " "; } std::cout << std::endl; } } } static void display_hidden_unit_activations(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_a(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } static void display_hidden_unit_samples(const parent_t& rbm) { for (size_t k = 0; k < parent_t::K; ++k) { for (size_t i = 0; i < parent_t::NV; ++i) { for (size_t j = 0; j < parent_t::NV; ++j) { std::cout << rbm.h2_s(k)(i, j) << " "; } std::cout << std::endl; } std::cout << std::endl << std::endl; } } }; } //end of dll namespace #endif <|endoftext|>
<commit_before>#include <iostream> #include <sstream> #include <vector> #include <stdio.h> class Node { private: std::string value; std::string name; std::vector<Node *> childs; bool isset; bool is_array; bool has_valid_childs; int last_key_id; Node *parent; void setParent(Node *parent) { this->parent = parent; } public: static const int TYPE_NOT_SET = 0; static const int TYPE_VALUE = 1; static const int TYPE_ARRAY = 2; static const int TYPE_LIST = 3; static int string2int(std::string value) { int tmp; std::istringstream(value) >> tmp; return tmp; } /** * Return name o this node */ std::string getName() { return this->name; } /** * Return value of this node as string * If array or list return "ARRAY" * see toString function */ std::string getValue() { return this->toString(); } static std::string int2string(int value, std::string format = "%d") { char buffer[50]; sprintf(buffer, format.c_str(), value); return buffer; } Node() { this->isset = false; this->last_key_id = 0; this->is_array = false; this->parent = NULL; this->has_valid_childs = false; } Node(std::string name) { this->name = name; this->isset = false; this->last_key_id = 0; this->is_array = false; this->parent = NULL; this->has_valid_childs = false; } /** * Destructor */ ~Node() { //delete all chidrens for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end(); ++it) { delete (*it); } } /** * unset one child */ void unset(std::string key) { for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end();) { if ((*it)->getName() == key) { it = childs.erase(it); } else { it++; } } } std::vector<Node *> getChildrens() { return this->childs; } Node *getParent() { return this->parent; } int getType() const { if (this->childs.size() > 0 && this->has_valid_childs) { if (this->is_array) return TYPE_ARRAY; return TYPE_LIST; } if (this->isset) return TYPE_VALUE; return TYPE_NOT_SET; } bool operator!=(Node &b) { return (*this == b) ? false : true; } bool operator==(Node &b) { if (this->getType() != b.getType()) return false; switch (this->getType()) { case TYPE_NOT_SET: return true; break; case TYPE_VALUE: return (this->value == b.value) ? true : false; break; case TYPE_ARRAY: case TYPE_LIST: if (this->childs.size() != b.childs.size()) return false; for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end(); it++) { if (!b[(*it)->getName()]) return false; if (!(b[(*it)->getName()] == (**it))) return false; } return true; break; } return false; } std::string toString() const { switch (this->getType()) { case TYPE_NOT_SET: return "NULL"; break; case TYPE_VALUE: return this->value; break; case TYPE_ARRAY: return "Array"; break; case TYPE_LIST: return "Array"; break; } return ""; } bool hasChildrens() { return this->has_valid_childs; } Node& operator=(std::string value) { this->isset = true; this->childs.clear(); this->is_array = false; this->has_valid_childs = false; this->value = value; Node *tmp = this->parent; while (tmp) { if (tmp->childs.size() > 0) { tmp->has_valid_childs = true; } tmp = tmp->getParent(); } return *this; } Node& append() { Node *tmp = new Node(Node::int2string(last_key_id)); this->childs.push_back(tmp); this->last_key_id++; return *tmp; } Node& operator[](std::string key) { for (std::vector<Node *>::iterator it = this->childs.begin(); it != this->childs.end(); ++it) { if ((*it)->name == key) { return *(*it); } } Node *tmp = NULL; if (key == "" || key == Node::int2string(Node::string2int(key))) { if (key == "") key = Node::int2string(this->last_key_id); tmp = new Node(key); if (Node::string2int(key) >= this->last_key_id) this->last_key_id = Node::string2int(key) + 1; } else { //this is not list, this is map! // this->is_array = true; tmp = new Node(key); } tmp->setParent(this); this->childs.push_back(tmp); return *tmp; } operator std::string() const { return this->toString(); } friend std::ostream& operator<<(std::ostream& os, const Node& dt) { os << dt.toString(); return os; } operator void*() { if (isset == true) return this; //to do cleanup search path Node *tmp = this; while (tmp->parent && tmp->parent->has_valid_childs == false) { tmp = tmp->parent; } //std::cout<<tmp->parent->getName()<<std::endl; tmp->parent->unset(tmp->getName()); return 0; //return isset==true ? this : 0; } void print(); }; void Node::print() { std::cout << "Node::" << this->name << ": " << this->toString() << std::endl; } void node_get_leafs(Node *root, std::vector<Node *> *leafs) { if (root->hasChildrens()) { std::vector<Node *> tmp = root->getChildrens(); for (std::vector<Node *>::iterator it = tmp.begin(); it != tmp.end(); ++it) { node_get_leafs((*it), leafs); } } else { leafs->push_back(root); } } std::string build_http_query(Node *root) { std::vector<Node *> leafs; node_get_leafs(root, &leafs); std::string query = ""; for (std::vector<Node *>::iterator it = leafs.begin(); it != leafs.end(); ++it) { std::string name = ""; std::string last_name = (*it)->getName(); Node *parent = (*it); while (parent->getParent()->getParent()) { name = "[" + parent->getName() + "]" + name; last_name = parent->getName(); parent = parent->getParent(); } query += parent->getName() + name + "=" + (*it)->getValue(); if ((it + 1) != leafs.end()) query += "&"; } return query; } int main(void) { Node test; test["id"] = "1"; test["title"] = "test titile"; test["book"]["1"]["name"] = "1"; test["book"]["1"]["author"] = "John Smith"; //autoinc test["autoinc"][""] = "0"; test["autoinc"][""] = "1"; test["autoinc"][""] = "2"; test["autoinc"][""] = "3"; test["autoinc"]["8"] = "8"; test["autoinc"]["abc"] = "abc"; test["autoinc"][""] = "9"; Node test1, test2; test1["id"] = "test2"; test1["name"] = "test2"; test1["deep"]["bla"] = "test2"; test2["id"] = "test2"; test2["name"] = "test2"; test2["deep"]["bla"] = "test2"; if (test1 == test2) { std::cout << "Test operator == true" << std::endl; } else { std::cout << "Test operator == false" << std::endl; } //testing if exists if (test["check"]["if"]["exists"]) { std::cout << "Check fail\n"; } else { std::cout << "Check ok\n"; } std::vector<Node *> leafs; node_get_leafs(&test, &leafs); for (std::vector<Node *>::iterator it = leafs.begin(); it != leafs.end(); ++it) { Node *parent = (*it); std::string name = ""; while (parent->getParent()) { name = parent->getName() + name; parent = parent->getParent(); if (parent->getParent()) name = "." + name; } std::cout << name << "=" << (*it)->getValue() << std::endl; } } <commit_msg>add comments fix comparation<commit_after>#include <iostream> #include <sstream> #include <vector> #include <stdio.h> class Node { private: std::string value; std::string name; std::vector<Node *> childs; bool isset; bool is_array; bool has_valid_childs; int last_key_id; Node *parent; void setParent(Node *parent) { this->parent = parent; } public: static const int TYPE_NOT_SET = 0; static const int TYPE_VALUE = 1; static const int TYPE_ARRAY = 2; static const int TYPE_LIST = 3; static int string2int(std::string value) { int tmp; std::istringstream(value) >> tmp; return tmp; } /** * Return name o this node */ std::string getName() { return this->name; } /** * Return value of this node as string * If array or list return "ARRAY" * see toString function */ std::string getValue() { return this->toString(); } static std::string int2string(int value, std::string format = "%d") { char buffer[50]; sprintf(buffer, format.c_str(), value); return buffer; } Node() { this->isset = false; this->last_key_id = 0; this->is_array = false; this->parent = NULL; this->has_valid_childs = false; } Node(std::string name) { this->name = name; this->isset = false; this->last_key_id = 0; this->is_array = false; this->parent = NULL; this->has_valid_childs = false; } /** * Destructor */ ~Node() { //delete all chidrens for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end(); ++it) { delete (*it); } } /** * unset one child */ void unset(std::string key) { //find key and delete for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end();) { if ((*it)->getName() == key) { it = childs.erase(it); } else { it++; } } } /** * Retrun all childrens */ std::vector<Node *> getChildrens() { return this->childs; } /** * Get parent node * Return null if root */ Node *getParent() { return this->parent; } /** * Get node type */ int getType() const { if (this->childs.size() > 0 && this->has_valid_childs) { if (this->is_array) return TYPE_ARRAY; return TYPE_LIST; } if (this->isset) return TYPE_VALUE; return TYPE_NOT_SET; } /** * != operator overload */ bool operator!=(Node &b) { return (*this == b) ? false : true; } /** * == operator overload */ bool operator==(Node &b) { //test if type is equal if (this->getType() != b.getType()) return false; switch (this->getType()) { case TYPE_NOT_SET: return true; break; case TYPE_VALUE: //test only the value return (this->value == b.value) ? true : false; break; case TYPE_ARRAY: case TYPE_LIST: // check if size is the same if (this->childs.size() != b.childs.size()) { return false; } //test childs if equal for (std::vector<Node *>::iterator it = childs.begin(); it != childs.end(); it++) { //check if key exists if (!b[(*it)->getName()]) { return false; } //check if nodes are equal, recurency if ((b[(*it)->getName()] != (**it))) return false; } return true; break; } return false; } /** * Return as string * */ std::string toString() const { switch (this->getType()) { case TYPE_NOT_SET: return "NULL"; break; case TYPE_VALUE: return this->value; break; case TYPE_ARRAY: return "Array"; break; case TYPE_LIST: return "Array"; break; } return ""; } /** * check if node has valid childrens */ bool hasChildrens() { return this->has_valid_childs; } /** * Value assign */ Node& operator=(std::string value) { //cleanup some data this->isset = true; this->childs.clear(); this->is_array = false; this->has_valid_childs = false; this->value = value; //update parent nodes Node *tmp = this->parent; while (tmp) { tmp->isset=true; if (tmp->childs.size() > 0) { tmp->has_valid_childs = true; } tmp = tmp->getParent(); } return *this; } /** * Append node */ Node& append() { Node *tmp = new Node(Node::int2string(last_key_id)); this->childs.push_back(tmp); this->last_key_id++; return *tmp; } Node& operator[](std::string key) { for (std::vector<Node *>::iterator it = this->childs.begin(); it != this->childs.end(); ++it) { if ((*it)->name == key) { return *(*it); } } Node *tmp = NULL; if (key == "" || key == Node::int2string(Node::string2int(key))) { if (key == "") key = Node::int2string(this->last_key_id); tmp = new Node(key); if (Node::string2int(key) >= this->last_key_id) this->last_key_id = Node::string2int(key) + 1; } else { //this is not list, this is map! // this->is_array = true; tmp = new Node(key); } tmp->setParent(this); this->childs.push_back(tmp); return *tmp; } operator std::string() const { return this->toString(); } friend std::ostream& operator<<(std::ostream& os, const Node& dt) { os << dt.toString(); return os; } operator void*() { if (isset == true) return this; //to do cleanup search path Node *tmp = this; while (tmp->parent && tmp->parent->has_valid_childs == false) { tmp = tmp->parent; } //std::cout<<tmp->parent->getName()<<std::endl; tmp->parent->unset(tmp->getName()); return 0; //return isset==true ? this : 0; } void print(); }; void Node::print() { std::cout << "Node::" << this->name << ": " << this->toString() <<", Type: " <<this->getType()<<std::endl; } void node_get_leafs(Node *root, std::vector<Node *> *leafs) { if (root->hasChildrens()) { std::vector<Node *> tmp = root->getChildrens(); for (std::vector<Node *>::iterator it = tmp.begin(); it != tmp.end(); ++it) { node_get_leafs((*it), leafs); } } else { leafs->push_back(root); } } std::string build_http_query(Node *root) { std::vector<Node *> leafs; node_get_leafs(root, &leafs); std::string query = ""; for (std::vector<Node *>::iterator it = leafs.begin(); it != leafs.end(); ++it) { std::string name = ""; std::string last_name = (*it)->getName(); Node *parent = (*it); while (parent->getParent()->getParent()) { name = "[" + parent->getName() + "]" + name; last_name = parent->getName(); parent = parent->getParent(); } query += parent->getName() + name + "=" + (*it)->getValue(); if ((it + 1) != leafs.end()) query += "&"; } return query; } int main(void) { Node test; test["id"] = "1"; test["title"] = "test titile"; test["book"]["1"]["name"] = "1"; test["book"]["1"]["author"] = "John Smith"; //autoinc test["autoinc"][""] = "0"; test["autoinc"][""] = "1"; test["autoinc"][""] = "2"; test["autoinc"][""] = "3"; test["autoinc"]["8"] = "8"; test["autoinc"]["abc"] = "abc"; test["autoinc"][""] = "9"; Node test1, test2; test1["id"] = "test2"; test1["name"] = "test2"; test1["name"]["bla"] = "test2"; test2["id"] = "test2"; test2["name"] = "test2"; test2["name"]["bla"] = "test2"; if (test1 == test2) { std::cout << "Test operator == true" << std::endl; } else { std::cout << "Test operator == false" << std::endl; } //testing if exists if (test["check"]["if"]["exists"]) { std::cout << "Check fail\n"; } else { std::cout << "Check ok\n"; } std::vector<Node *> leafs; node_get_leafs(&test, &leafs); for (std::vector<Node *>::iterator it = leafs.begin(); it != leafs.end(); ++it) { Node *parent = (*it); std::string name = ""; while (parent->getParent()) { name = parent->getName() + name; parent = parent->getParent(); if (parent->getParent()) name = "." + name; } std::cout << name << "=" << (*it)->getValue() << std::endl; } } <|endoftext|>
<commit_before>#pragma once #include <mapbox/geojsonvt/types.hpp> namespace mapbox { namespace geojsonvt { struct Tile { mapbox::geometry::feature_collection<int16_t> features; uint32_t num_points = 0; uint32_t num_simplified = 0; }; namespace detail { class InternalTile { public: const uint8_t z; const uint32_t x; const uint32_t y; vt_features source_features; bool is_solid = false; mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } }; Tile tile; InternalTile(const vt_features& source, const uint8_t z_, const uint32_t x_, const uint32_t y_, const uint16_t extent_, const uint16_t buffer, const double tolerance_) : z(z_), x(x_), y(y_), z2(std::pow(2, z)), extent(extent_), tolerance(tolerance_), sq_tolerance(tolerance_ * tolerance_) { for (const auto& feature : source) { const auto& geom = feature.geometry; const auto& props = feature.properties; tile.num_points += feature.num_points; vt_geometry::visit(geom, [&] (const auto& g) { visit(transform(g), props); }); bbox.min.x = std::min(feature.bbox.min.x, bbox.min.x); bbox.min.y = std::min(feature.bbox.min.y, bbox.min.y); bbox.max.x = std::max(feature.bbox.max.x, bbox.max.x); bbox.max.y = std::max(feature.bbox.max.y, bbox.max.y); } is_solid = isSolid(buffer); } private: const double z2; const uint16_t extent; const double tolerance; const double sq_tolerance; bool isSolid(const uint16_t buffer) { if (tile.features.size() != 1) return false; const auto& geom = tile.features.front().geometry; if (!geom.is<mapbox::geometry::polygon<int16_t>>()) return false; const auto& rings = geom.get<mapbox::geometry::polygon<int16_t>>(); if (rings.size() > 1) return false; const auto& ring = rings.front(); if (ring.size() != 5) return false; const int16_t min = -static_cast<int16_t>(buffer); const int16_t max = static_cast<int16_t>(extent + buffer); for (const auto& p : ring) { if ((p.x != min && p.x != max) || (p.y != min && p.y != max)) return false; } return true; } void visit(geometry::point<int16_t>&& point, const property_map& props) { tile.features.push_back({ std::move(point), props }); } void visit(geometry::line_string<int16_t>&& line, const property_map& props) { if (!line.empty()) tile.features.push_back({ std::move(line), props }); } void visit(geometry::polygon<int16_t>&& polygon, const property_map& props) { if (!polygon.empty()) tile.features.push_back({ std::move(polygon), props }); } template <class T> void visit(T&& multi, const property_map& props) { switch (multi.size()) { case 0: break; case 1: tile.features.push_back({ std::move(multi[0]), props }); break; default: tile.features.push_back({ std::move(multi), props }); break; } } mapbox::geometry::point<int16_t> transform(const vt_point& p) { ++tile.num_simplified; return { static_cast<int16_t>(std::round((p.x * z2 - x) * extent)), static_cast<int16_t>(std::round((p.y * z2 - y) * extent)) }; } mapbox::geometry::multi_point<int16_t> transform(const vt_multi_point& points) { mapbox::geometry::multi_point<int16_t> result; result.reserve(points.size()); for (const auto& p : points) { result.push_back(transform(p)); } return result; } mapbox::geometry::line_string<int16_t> transform(const vt_line_string& line) { mapbox::geometry::line_string<int16_t> result; if (line.dist > tolerance) { for (const auto& p : line) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::linear_ring<int16_t> transform(const vt_linear_ring& ring) { mapbox::geometry::linear_ring<int16_t> result; if (ring.area > sq_tolerance) { for (const auto& p : ring) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::multi_line_string<int16_t> transform(const vt_multi_line_string& lines) { mapbox::geometry::multi_line_string<int16_t> result; for (const auto& line : lines) { if (line.dist > tolerance) result.push_back(transform(line)); } return result; } mapbox::geometry::polygon<int16_t> transform(const vt_polygon& rings) { mapbox::geometry::polygon<int16_t> result; for (const auto& ring : rings) { if (ring.area > sq_tolerance) result.push_back(transform(ring)); } return result; } mapbox::geometry::multi_polygon<int16_t> transform(const vt_multi_polygon& polygons) { mapbox::geometry::multi_polygon<int16_t> result; for (const auto& polygon : polygons) { const auto p = transform(polygon); if (!p.empty()) result.push_back(p); } return result; } }; } // namespace detail } // namespace geojsonvt } // namespace mapbox <commit_msg>visit ⇢ addFeature<commit_after>#pragma once #include <mapbox/geojsonvt/types.hpp> namespace mapbox { namespace geojsonvt { struct Tile { mapbox::geometry::feature_collection<int16_t> features; uint32_t num_points = 0; uint32_t num_simplified = 0; }; namespace detail { class InternalTile { public: const uint8_t z; const uint32_t x; const uint32_t y; vt_features source_features; bool is_solid = false; mapbox::geometry::box<double> bbox = { { 2, 1 }, { -1, 0 } }; Tile tile; InternalTile(const vt_features& source, const uint8_t z_, const uint32_t x_, const uint32_t y_, const uint16_t extent_, const uint16_t buffer, const double tolerance_) : z(z_), x(x_), y(y_), z2(std::pow(2, z)), extent(extent_), tolerance(tolerance_), sq_tolerance(tolerance_ * tolerance_) { for (const auto& feature : source) { const auto& geom = feature.geometry; const auto& props = feature.properties; tile.num_points += feature.num_points; vt_geometry::visit(geom, [&] (const auto& g) { addFeature(transform(g), props); }); bbox.min.x = std::min(feature.bbox.min.x, bbox.min.x); bbox.min.y = std::min(feature.bbox.min.y, bbox.min.y); bbox.max.x = std::max(feature.bbox.max.x, bbox.max.x); bbox.max.y = std::max(feature.bbox.max.y, bbox.max.y); } is_solid = isSolid(buffer); } private: const double z2; const uint16_t extent; const double tolerance; const double sq_tolerance; bool isSolid(const uint16_t buffer) { if (tile.features.size() != 1) return false; const auto& geom = tile.features.front().geometry; if (!geom.is<mapbox::geometry::polygon<int16_t>>()) return false; const auto& rings = geom.get<mapbox::geometry::polygon<int16_t>>(); if (rings.size() > 1) return false; const auto& ring = rings.front(); if (ring.size() != 5) return false; const int16_t min = -static_cast<int16_t>(buffer); const int16_t max = static_cast<int16_t>(extent + buffer); for (const auto& p : ring) { if ((p.x != min && p.x != max) || (p.y != min && p.y != max)) return false; } return true; } void addFeature(geometry::point<int16_t>&& point, const property_map& props) { tile.features.push_back({ std::move(point), props }); } void addFeature(geometry::line_string<int16_t>&& line, const property_map& props) { if (!line.empty()) tile.features.push_back({ std::move(line), props }); } void addFeature(geometry::polygon<int16_t>&& polygon, const property_map& props) { if (!polygon.empty()) tile.features.push_back({ std::move(polygon), props }); } template <class T> void addFeature(T&& multi, const property_map& props) { switch (multi.size()) { case 0: break; case 1: tile.features.push_back({ std::move(multi[0]), props }); break; default: tile.features.push_back({ std::move(multi), props }); break; } } mapbox::geometry::point<int16_t> transform(const vt_point& p) { ++tile.num_simplified; return { static_cast<int16_t>(std::round((p.x * z2 - x) * extent)), static_cast<int16_t>(std::round((p.y * z2 - y) * extent)) }; } mapbox::geometry::multi_point<int16_t> transform(const vt_multi_point& points) { mapbox::geometry::multi_point<int16_t> result; result.reserve(points.size()); for (const auto& p : points) { result.push_back(transform(p)); } return result; } mapbox::geometry::line_string<int16_t> transform(const vt_line_string& line) { mapbox::geometry::line_string<int16_t> result; if (line.dist > tolerance) { for (const auto& p : line) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::linear_ring<int16_t> transform(const vt_linear_ring& ring) { mapbox::geometry::linear_ring<int16_t> result; if (ring.area > sq_tolerance) { for (const auto& p : ring) { if (p.z > sq_tolerance) result.push_back(transform(p)); } } return result; } mapbox::geometry::multi_line_string<int16_t> transform(const vt_multi_line_string& lines) { mapbox::geometry::multi_line_string<int16_t> result; for (const auto& line : lines) { if (line.dist > tolerance) result.push_back(transform(line)); } return result; } mapbox::geometry::polygon<int16_t> transform(const vt_polygon& rings) { mapbox::geometry::polygon<int16_t> result; for (const auto& ring : rings) { if (ring.area > sq_tolerance) result.push_back(transform(ring)); } return result; } mapbox::geometry::multi_polygon<int16_t> transform(const vt_multi_polygon& polygons) { mapbox::geometry::multi_polygon<int16_t> result; for (const auto& polygon : polygons) { const auto p = transform(polygon); if (!p.empty()) result.push_back(p); } return result; } }; } // namespace detail } // namespace geojsonvt } // namespace mapbox <|endoftext|>
<commit_before>#include "ray/core_worker/transport/direct_task_transport.h" #include "ray/core_worker/transport/dependency_resolver.h" #include "ray/core_worker/transport/direct_actor_transport.h" namespace ray { Status CoreWorkerDirectTaskSubmitter::SubmitTask(TaskSpecification task_spec) { RAY_LOG(DEBUG) << "Submit task " << task_spec.TaskId(); resolver_.ResolveDependencies(task_spec, [this, task_spec]() { RAY_LOG(DEBUG) << "Task dependencies resolved " << task_spec.TaskId(); absl::MutexLock lock(&mu_); // Note that the dependencies in the task spec are mutated to only contain // plasma dependencies after ResolveDependencies finishes. const SchedulingKey scheduling_key( task_spec.GetSchedulingClass(), task_spec.GetDependencies(), task_spec.IsActorCreationTask() ? task_spec.ActorCreationId() : ActorID::Nil()); auto it = task_queues_.find(scheduling_key); if (it == task_queues_.end()) { it = task_queues_.emplace(scheduling_key, std::deque<TaskSpecification>()).first; } it->second.push_back(task_spec); RequestNewWorkerIfNeeded(scheduling_key); }); return Status::OK(); } void CoreWorkerDirectTaskSubmitter::AddWorkerLeaseClient( const rpc::WorkerAddress &addr, std::shared_ptr<WorkerLeaseInterface> lease_client) { auto it = client_cache_.find(addr); if (it == client_cache_.end()) { client_cache_[addr] = std::shared_ptr<rpc::CoreWorkerClientInterface>(client_factory_(addr.ToProto())); RAY_LOG(INFO) << "Connected to " << addr.ip_address << ":" << addr.port; } int64_t expiration = current_time_ms() + lease_timeout_ms_; worker_to_lease_client_.emplace(addr, std::make_pair(std::move(lease_client), expiration)); } void CoreWorkerDirectTaskSubmitter::OnWorkerIdle( const rpc::WorkerAddress &addr, const SchedulingKey &scheduling_key, bool was_error, const google::protobuf::RepeatedPtrField<rpc::ResourceMapEntry> &assigned_resources) { auto lease_entry = worker_to_lease_client_[addr]; auto queue_entry = task_queues_.find(scheduling_key); // Return the worker if there was an error executing the previous task, // the previous task is an actor creation task, // there are no more applicable queued tasks, or the lease is expired. if (was_error || queue_entry == task_queues_.end() || current_time_ms() > lease_entry.second) { auto status = lease_entry.first->ReturnWorker(addr.port, addr.worker_id, was_error); if (!status.ok()) { RAY_LOG(ERROR) << "Error returning worker to raylet: " << status.ToString(); } worker_to_lease_client_.erase(addr); } else { auto &client = *client_cache_[addr]; PushNormalTask(addr, client, scheduling_key, queue_entry->second.front(), assigned_resources); queue_entry->second.pop_front(); // Delete the queue if it's now empty. Note that the queue cannot already be empty // because this is the only place tasks are removed from it. if (queue_entry->second.empty()) { task_queues_.erase(queue_entry); } } RequestNewWorkerIfNeeded(scheduling_key); } std::shared_ptr<WorkerLeaseInterface> CoreWorkerDirectTaskSubmitter::GetOrConnectLeaseClient( const rpc::Address *raylet_address) { std::shared_ptr<WorkerLeaseInterface> lease_client; if (raylet_address && ClientID::FromBinary(raylet_address->raylet_id()) != local_raylet_id_) { // A remote raylet was specified. Connect to the raylet if needed. ClientID raylet_id = ClientID::FromBinary(raylet_address->raylet_id()); auto it = remote_lease_clients_.find(raylet_id); if (it == remote_lease_clients_.end()) { RAY_LOG(DEBUG) << "Connecting to raylet " << raylet_id; it = remote_lease_clients_ .emplace(raylet_id, lease_client_factory_(raylet_address->ip_address(), raylet_address->port())) .first; } lease_client = it->second; } else { lease_client = local_lease_client_; } return lease_client; } void CoreWorkerDirectTaskSubmitter::RequestNewWorkerIfNeeded( const SchedulingKey &scheduling_key, const rpc::Address *raylet_address) { if (pending_lease_requests_.find(scheduling_key) != pending_lease_requests_.end()) { // There's already an outstanding lease request for this type of task. return; } auto it = task_queues_.find(scheduling_key); if (it == task_queues_.end()) { // We don't have any of this type of task to run. return; } auto lease_client = GetOrConnectLeaseClient(raylet_address); TaskSpecification &resource_spec = it->second.front(); TaskID task_id = resource_spec.TaskId(); auto status = lease_client->RequestWorkerLease( resource_spec, [this, lease_client, task_id, scheduling_key]( const Status &status, const rpc::RequestWorkerLeaseReply &reply) mutable { absl::MutexLock lock(&mu_); pending_lease_requests_.erase(scheduling_key); if (status.ok()) { if (!reply.worker_address().raylet_id().empty()) { // We got a lease for a worker. Add the lease client state and try to // assign work to the worker. RAY_LOG(DEBUG) << "Lease granted " << task_id; rpc::WorkerAddress addr(reply.worker_address()); AddWorkerLeaseClient(addr, std::move(lease_client)); auto resources_copy = reply.resource_mapping(); OnWorkerIdle(addr, scheduling_key, /*error=*/false, resources_copy); } else { // The raylet redirected us to a different raylet to retry at. RequestNewWorkerIfNeeded(scheduling_key, &reply.retry_at_raylet_address()); } } else { RetryLeaseRequest(status, lease_client, scheduling_key); } }); if (!status.ok()) { RetryLeaseRequest(status, lease_client, scheduling_key); } pending_lease_requests_.insert(scheduling_key); } void CoreWorkerDirectTaskSubmitter::RetryLeaseRequest( Status status, std::shared_ptr<WorkerLeaseInterface> lease_client, const SchedulingKey &scheduling_key) { if (lease_client != local_lease_client_) { // A lease request to a remote raylet failed. Retry locally if the lease is // still needed. // TODO(swang): Fail after some number of retries? RAY_LOG(ERROR) << "Retrying attempt to schedule task at remote node. Error: " << status.ToString(); RequestNewWorkerIfNeeded(scheduling_key); } else { // A local request failed. This shouldn't happen if the raylet is still alive // and we don't currently handle raylet failures, so treat it as a fatal // error. RAY_LOG(FATAL) << "Lost connection with local raylet. Error: " << status.ToString(); } } void CoreWorkerDirectTaskSubmitter::PushNormalTask( const rpc::WorkerAddress &addr, rpc::CoreWorkerClientInterface &client, const SchedulingKey &scheduling_key, const TaskSpecification &task_spec, const google::protobuf::RepeatedPtrField<rpc::ResourceMapEntry> &assigned_resources) { auto task_id = task_spec.TaskId(); auto request = std::unique_ptr<rpc::PushTaskRequest>(new rpc::PushTaskRequest); bool is_actor = task_spec.IsActorTask(); bool is_actor_creation = task_spec.IsActorCreationTask(); RAY_LOG(DEBUG) << "Pushing normal task " << task_spec.TaskId(); // NOTE(swang): CopyFrom is needed because if we use Swap here and the task // fails, then the task data will be gone when the TaskManager attempts to // access the task. request->mutable_caller_address()->CopyFrom(rpc_address_); request->mutable_task_spec()->CopyFrom(task_spec.GetMessage()); request->mutable_resource_mapping()->CopyFrom(assigned_resources); request->set_intended_worker_id(addr.worker_id.Binary()); auto status = client.PushNormalTask( std::move(request), [this, task_id, is_actor, is_actor_creation, scheduling_key, addr, assigned_resources](Status status, const rpc::PushTaskReply &reply) { if (reply.worker_exiting()) { // The worker is draining and will shutdown after it is done. Don't return // it to the Raylet since that will kill it early. absl::MutexLock lock(&mu_); worker_to_lease_client_.erase(addr); } else if (!status.ok() || !is_actor_creation) { // Successful actor creation leases the worker indefinitely from the raylet. absl::MutexLock lock(&mu_); OnWorkerIdle(addr, scheduling_key, /*error=*/!status.ok(), assigned_resources); } if (!status.ok()) { // TODO: It'd be nice to differentiate here between process vs node // failure (e.g., by contacting the raylet). If it was a process // failure, it may have been an application-level error and it may // not make sense to retry the task. task_finisher_->PendingTaskFailed( task_id, is_actor ? rpc::ErrorType::ACTOR_DIED : rpc::ErrorType::WORKER_DIED, &status); } else { task_finisher_->CompletePendingTask(task_id, reply, addr.ToProto()); } }); if (!status.ok()) { RAY_LOG(ERROR) << "Error pushing task to worker: " << status.ToString(); { absl::MutexLock lock(&mu_); OnWorkerIdle(addr, scheduling_key, /*error=*/true, assigned_resources); } task_finisher_->PendingTaskFailed( task_id, is_actor ? rpc::ErrorType::ACTOR_DIED : rpc::ErrorType::WORKER_DIED, &status); } } }; // namespace ray <commit_msg>Remove misleading error message (#7265)<commit_after>#include "ray/core_worker/transport/direct_task_transport.h" #include "ray/core_worker/transport/dependency_resolver.h" #include "ray/core_worker/transport/direct_actor_transport.h" namespace ray { Status CoreWorkerDirectTaskSubmitter::SubmitTask(TaskSpecification task_spec) { RAY_LOG(DEBUG) << "Submit task " << task_spec.TaskId(); resolver_.ResolveDependencies(task_spec, [this, task_spec]() { RAY_LOG(DEBUG) << "Task dependencies resolved " << task_spec.TaskId(); absl::MutexLock lock(&mu_); // Note that the dependencies in the task spec are mutated to only contain // plasma dependencies after ResolveDependencies finishes. const SchedulingKey scheduling_key( task_spec.GetSchedulingClass(), task_spec.GetDependencies(), task_spec.IsActorCreationTask() ? task_spec.ActorCreationId() : ActorID::Nil()); auto it = task_queues_.find(scheduling_key); if (it == task_queues_.end()) { it = task_queues_.emplace(scheduling_key, std::deque<TaskSpecification>()).first; } it->second.push_back(task_spec); RequestNewWorkerIfNeeded(scheduling_key); }); return Status::OK(); } void CoreWorkerDirectTaskSubmitter::AddWorkerLeaseClient( const rpc::WorkerAddress &addr, std::shared_ptr<WorkerLeaseInterface> lease_client) { auto it = client_cache_.find(addr); if (it == client_cache_.end()) { client_cache_[addr] = std::shared_ptr<rpc::CoreWorkerClientInterface>(client_factory_(addr.ToProto())); RAY_LOG(INFO) << "Connected to " << addr.ip_address << ":" << addr.port; } int64_t expiration = current_time_ms() + lease_timeout_ms_; worker_to_lease_client_.emplace(addr, std::make_pair(std::move(lease_client), expiration)); } void CoreWorkerDirectTaskSubmitter::OnWorkerIdle( const rpc::WorkerAddress &addr, const SchedulingKey &scheduling_key, bool was_error, const google::protobuf::RepeatedPtrField<rpc::ResourceMapEntry> &assigned_resources) { auto lease_entry = worker_to_lease_client_[addr]; auto queue_entry = task_queues_.find(scheduling_key); // Return the worker if there was an error executing the previous task, // the previous task is an actor creation task, // there are no more applicable queued tasks, or the lease is expired. if (was_error || queue_entry == task_queues_.end() || current_time_ms() > lease_entry.second) { auto status = lease_entry.first->ReturnWorker(addr.port, addr.worker_id, was_error); if (!status.ok()) { RAY_LOG(ERROR) << "Error returning worker to raylet: " << status.ToString(); } worker_to_lease_client_.erase(addr); } else { auto &client = *client_cache_[addr]; PushNormalTask(addr, client, scheduling_key, queue_entry->second.front(), assigned_resources); queue_entry->second.pop_front(); // Delete the queue if it's now empty. Note that the queue cannot already be empty // because this is the only place tasks are removed from it. if (queue_entry->second.empty()) { task_queues_.erase(queue_entry); } } RequestNewWorkerIfNeeded(scheduling_key); } std::shared_ptr<WorkerLeaseInterface> CoreWorkerDirectTaskSubmitter::GetOrConnectLeaseClient( const rpc::Address *raylet_address) { std::shared_ptr<WorkerLeaseInterface> lease_client; if (raylet_address && ClientID::FromBinary(raylet_address->raylet_id()) != local_raylet_id_) { // A remote raylet was specified. Connect to the raylet if needed. ClientID raylet_id = ClientID::FromBinary(raylet_address->raylet_id()); auto it = remote_lease_clients_.find(raylet_id); if (it == remote_lease_clients_.end()) { RAY_LOG(DEBUG) << "Connecting to raylet " << raylet_id; it = remote_lease_clients_ .emplace(raylet_id, lease_client_factory_(raylet_address->ip_address(), raylet_address->port())) .first; } lease_client = it->second; } else { lease_client = local_lease_client_; } return lease_client; } void CoreWorkerDirectTaskSubmitter::RequestNewWorkerIfNeeded( const SchedulingKey &scheduling_key, const rpc::Address *raylet_address) { if (pending_lease_requests_.find(scheduling_key) != pending_lease_requests_.end()) { // There's already an outstanding lease request for this type of task. return; } auto it = task_queues_.find(scheduling_key); if (it == task_queues_.end()) { // We don't have any of this type of task to run. return; } auto lease_client = GetOrConnectLeaseClient(raylet_address); TaskSpecification &resource_spec = it->second.front(); TaskID task_id = resource_spec.TaskId(); auto status = lease_client->RequestWorkerLease( resource_spec, [this, lease_client, task_id, scheduling_key]( const Status &status, const rpc::RequestWorkerLeaseReply &reply) mutable { absl::MutexLock lock(&mu_); pending_lease_requests_.erase(scheduling_key); if (status.ok()) { if (!reply.worker_address().raylet_id().empty()) { // We got a lease for a worker. Add the lease client state and try to // assign work to the worker. RAY_LOG(DEBUG) << "Lease granted " << task_id; rpc::WorkerAddress addr(reply.worker_address()); AddWorkerLeaseClient(addr, std::move(lease_client)); auto resources_copy = reply.resource_mapping(); OnWorkerIdle(addr, scheduling_key, /*error=*/false, resources_copy); } else { // The raylet redirected us to a different raylet to retry at. RequestNewWorkerIfNeeded(scheduling_key, &reply.retry_at_raylet_address()); } } else { RetryLeaseRequest(status, lease_client, scheduling_key); } }); if (!status.ok()) { RetryLeaseRequest(status, lease_client, scheduling_key); } pending_lease_requests_.insert(scheduling_key); } void CoreWorkerDirectTaskSubmitter::RetryLeaseRequest( Status status, std::shared_ptr<WorkerLeaseInterface> lease_client, const SchedulingKey &scheduling_key) { if (lease_client != local_lease_client_) { // A lease request to a remote raylet failed. Retry locally if the lease is // still needed. // TODO(swang): Fail after some number of retries? RAY_LOG(ERROR) << "Retrying attempt to schedule task at remote node. Error: " << status.ToString(); RequestNewWorkerIfNeeded(scheduling_key); } else { // A local request failed. This shouldn't happen if the raylet is still alive // and we don't currently handle raylet failures, so treat it as a fatal // error. RAY_LOG(FATAL) << status.ToString(); } } void CoreWorkerDirectTaskSubmitter::PushNormalTask( const rpc::WorkerAddress &addr, rpc::CoreWorkerClientInterface &client, const SchedulingKey &scheduling_key, const TaskSpecification &task_spec, const google::protobuf::RepeatedPtrField<rpc::ResourceMapEntry> &assigned_resources) { auto task_id = task_spec.TaskId(); auto request = std::unique_ptr<rpc::PushTaskRequest>(new rpc::PushTaskRequest); bool is_actor = task_spec.IsActorTask(); bool is_actor_creation = task_spec.IsActorCreationTask(); RAY_LOG(DEBUG) << "Pushing normal task " << task_spec.TaskId(); // NOTE(swang): CopyFrom is needed because if we use Swap here and the task // fails, then the task data will be gone when the TaskManager attempts to // access the task. request->mutable_caller_address()->CopyFrom(rpc_address_); request->mutable_task_spec()->CopyFrom(task_spec.GetMessage()); request->mutable_resource_mapping()->CopyFrom(assigned_resources); request->set_intended_worker_id(addr.worker_id.Binary()); auto status = client.PushNormalTask( std::move(request), [this, task_id, is_actor, is_actor_creation, scheduling_key, addr, assigned_resources](Status status, const rpc::PushTaskReply &reply) { if (reply.worker_exiting()) { // The worker is draining and will shutdown after it is done. Don't return // it to the Raylet since that will kill it early. absl::MutexLock lock(&mu_); worker_to_lease_client_.erase(addr); } else if (!status.ok() || !is_actor_creation) { // Successful actor creation leases the worker indefinitely from the raylet. absl::MutexLock lock(&mu_); OnWorkerIdle(addr, scheduling_key, /*error=*/!status.ok(), assigned_resources); } if (!status.ok()) { // TODO: It'd be nice to differentiate here between process vs node // failure (e.g., by contacting the raylet). If it was a process // failure, it may have been an application-level error and it may // not make sense to retry the task. task_finisher_->PendingTaskFailed( task_id, is_actor ? rpc::ErrorType::ACTOR_DIED : rpc::ErrorType::WORKER_DIED, &status); } else { task_finisher_->CompletePendingTask(task_id, reply, addr.ToProto()); } }); if (!status.ok()) { RAY_LOG(ERROR) << "Error pushing task to worker: " << status.ToString(); { absl::MutexLock lock(&mu_); OnWorkerIdle(addr, scheduling_key, /*error=*/true, assigned_resources); } task_finisher_->PendingTaskFailed( task_id, is_actor ? rpc::ErrorType::ACTOR_DIED : rpc::ErrorType::WORKER_DIED, &status); } } }; // namespace ray <|endoftext|>
<commit_before>#ifndef MATH_VECTOR_2_HPP #define MATH_VECTOR_2_HPP #include <math.h> // Microsoft compiler doesn't support constexpr #ifdef _WIN32 #define constexpr #endif namespace geometry { template <class T> class Vector2 { public: constexpr Vector2() : Vector2(0, 0) {} constexpr Vector2(const Vector2<T>& vec) : Vector2(vec.x, vec.y) {} constexpr Vector2(const T& x_, const T& y_) : x(x_), y(y_) {} public: constexpr double abs() const { return sqrt(x * x + y * y); } void normalize() { *this /= abs(); } constexpr T scalar(const Vector2<T>& vec) const { return x * vec.x + y * vec.y; } constexpr double dir() const { //angle between 2 vectors: scalar(vec1, vec2) / abs(vec1) * abs(vec2) //-> direction = angle between vec(x, y) and the x-axis vec(1, 0) return acos(x / abs()) / M_PI * 180; } void set(const T& x_, const T& y_) { x = x_; y = y_; } void set(const T& val) { x = y = val; } template <class T2> constexpr Vector2<T> operator+(const Vector2<T2>& p) const { return Vector2<T>(x + p.x, y + p.y); } template <class T2> Vector2<T>& operator+=(const Vector2<T2>& p) { return *this = *this + p; } constexpr Vector2<T> operator-() const { return Vector2<T>(-x, -y); } template <class T2> constexpr Vector2<T> operator-(const Vector2<T2>& p) const { return Vector2<T>(x - p.x, y - p.y); } template <class T2> Vector2<T>& operator-=(const Vector2<T2>& p) { return *this = *this - p; } //This is NOT scalar multiplication, use scalar() instead template <class T2> constexpr Vector2<T> operator*(const Vector2<T2>& p) const { return Vector2<T>(x * p.x, y * p.y); } template <class T2> constexpr Vector2<T> operator*(const T2& val) const { return Vector2<T>(x * val, y * val); } template <class T2> Vector2<T>& operator*=(const Vector2<T2>& p) { return *this = *this * p; } template <class T2> Vector2<T>& operator*=(const T2& val) { return *this = *this * val; } template <class T2> constexpr Vector2<T> operator/(const T2& val) const { return Vector2<T>(x / val, y / val); } template <class T2> constexpr Vector2<T> operator/(const Vector2<T2>& p) const { return Vector2<T>(x / p.x, y / p.y); } template <class T2> Vector2<T>& operator/=(const Vector2<T2>& p) { return *this = *this / p; } template <class T2> Vector2<T>& operator/=(const T2& val) { return *this = *this / val; } constexpr bool operator<(const Vector2<T>& p) const { return x < p.x && y < p.y; } constexpr bool operator>(const Vector2<T>& p) const { return x > p.x && y > p.y; } constexpr bool operator<=(const Vector2<T>& p) const { return x <= p.x && y <= p.y; } constexpr bool operator>=(const Vector2<T>& p) const { return x >= p.x && y >= p.y; } constexpr bool operator!=(const Vector2<T>& p) const { return x != p.x || y != p.y; } constexpr bool operator==(const Vector2<T>& p) const { return x == p.x && y == p.y; } constexpr operator bool() const { return x || y; } template <class T2> constexpr operator Vector2<T2>() const { return Vector2<T2>(static_cast<T2>(x), static_cast<T2>(y)); } public: T x, y; }; } #endif <commit_msg>Add function to create vector from length and direction<commit_after>#ifndef MATH_VECTOR_2_HPP #define MATH_VECTOR_2_HPP #include <math.h> // Microsoft compiler doesn't support constexpr #ifdef _WIN32 #define constexpr #endif namespace geometry { template <class T> class Vector2 { public: constexpr Vector2() : Vector2(0, 0) {} constexpr Vector2(const Vector2<T>& vec) : Vector2(vec.x, vec.y) {} constexpr Vector2(const T& x_, const T& y_) : x(x_), y(y_) {} public: constexpr double abs() const { return sqrt(x * x + y * y); } void normalize() { *this /= abs(); } constexpr T scalar(const Vector2<T>& vec) const { return x * vec.x + y * vec.y; } constexpr double dir() const { //angle between 2 vectors: scalar(vec1, vec2) / abs(vec1) * abs(vec2) //-> direction = angle between vec(x, y) and the x-axis vec(1, 0) return acos(x / abs()) / M_PI * 180; } void set(const T& x_, const T& y_) { x = x_; y = y_; } void set(const T& val) { x = y = val; } template <class T2> constexpr Vector2<T> operator+(const Vector2<T2>& p) const { return Vector2<T>(x + p.x, y + p.y); } template <class T2> Vector2<T>& operator+=(const Vector2<T2>& p) { return *this = *this + p; } constexpr Vector2<T> operator-() const { return Vector2<T>(-x, -y); } template <class T2> constexpr Vector2<T> operator-(const Vector2<T2>& p) const { return Vector2<T>(x - p.x, y - p.y); } template <class T2> Vector2<T>& operator-=(const Vector2<T2>& p) { return *this = *this - p; } //This is NOT scalar multiplication, use scalar() instead template <class T2> constexpr Vector2<T> operator*(const Vector2<T2>& p) const { return Vector2<T>(x * p.x, y * p.y); } template <class T2> constexpr Vector2<T> operator*(const T2& val) const { return Vector2<T>(x * val, y * val); } template <class T2> Vector2<T>& operator*=(const Vector2<T2>& p) { return *this = *this * p; } template <class T2> Vector2<T>& operator*=(const T2& val) { return *this = *this * val; } template <class T2> constexpr Vector2<T> operator/(const T2& val) const { return Vector2<T>(x / val, y / val); } template <class T2> constexpr Vector2<T> operator/(const Vector2<T2>& p) const { return Vector2<T>(x / p.x, y / p.y); } template <class T2> Vector2<T>& operator/=(const Vector2<T2>& p) { return *this = *this / p; } template <class T2> Vector2<T>& operator/=(const T2& val) { return *this = *this / val; } constexpr bool operator<(const Vector2<T>& p) const { return x < p.x && y < p.y; } constexpr bool operator>(const Vector2<T>& p) const { return x > p.x && y > p.y; } constexpr bool operator<=(const Vector2<T>& p) const { return x <= p.x && y <= p.y; } constexpr bool operator>=(const Vector2<T>& p) const { return x >= p.x && y >= p.y; } constexpr bool operator!=(const Vector2<T>& p) const { return x != p.x || y != p.y; } constexpr bool operator==(const Vector2<T>& p) const { return x == p.x && y == p.y; } constexpr operator bool() const { return x || y; } template <class T2> constexpr operator Vector2<T2>() const { return Vector2<T2>(static_cast<T2>(x), static_cast<T2>(y)); } public: T x, y; }; template <class T> Vector2<T> fromDirection(float length, float dir) { return Vector2<T>(length * cos(dir * M_PI / 180), length * sin(dir * M_PI / 180)); } } #endif <|endoftext|>
<commit_before>#ifndef SERENITY_HTTP_REQUEST_HPP_ #define SERENITY_HTTP_REQUEST_HPP_ #include <string> #include <map> #include <iostream> #include "response.hpp" namespace serenity { namespace http { const unsigned int nothing = 0; const unsigned int crlf_01_start = 1; const unsigned int crlf_01_end = 2; const unsigned int crlf_02_start = 3; const unsigned int crlf_02_end = 4; const unsigned int post_end = 5; template <typename Enumeration> auto as_integer(Enumeration const value) -> typename std::underlying_type<Enumeration>::type { return static_cast<typename std::underlying_type<Enumeration>::type>(value); } class request { public: /** \brief Method used for request: GET, PUT, DELETE, etc. */ std::string method; /** \brief The requested URI, including parameters */ std::string uri; // Convert to uri class from cpp-net /** \brief The requested function name */ std::string function; // First token after the service resolution info. /** \brief Extra URI arguments, path elements after the first token. */ std::string extra_path; /** \brief All of the HTTP headers provided by the client. */ std::map<std::string, std::string> headers; /** \brief All of the parameters supplied for the request. */ std::map<std::string, std::string> parameters; /** \brief Major HTTP version (ie 1) */ uint8_t version_major; /** \brief Minor HTTP version (ie 0) */ uint8_t version_minor; /** \brief Raw bytes of the extra data provided by the client in the request */ std::string post_data = "";; /** \brief Add data to the request for parsing. */ void add_data(const char *request_data, std::size_t bytes) { //std::cerr << "Data (" << bytes << "):" << std::endl // << request_data << std::endl; memcpy(data_.data() + data_end_, request_data, bytes); data_end_ += bytes; data_ptr_ = (data_.data() + data_end_) - bytes; if (headers_complete_) { // If we're done with the headers, go straight to parse() parse(); return; } int i = 0; for (; (i < bytes) && (parse_state_ < post_end); ++i) { switch (parse_state_) { case nothing: case crlf_01_end: if (request_data[i] == '\r') ++parse_state_; else parse_state_ = nothing; break; case crlf_01_start: case crlf_02_start: if (request_data[i] == '\n') ++parse_state_; else parse_state_ = nothing; break; case crlf_02_end: ++parse_state_; break; } } headers_complete_ = (parse_state_ >= crlf_02_end); if (headers_complete_) { parse(); } } bool is_complete() { return is_complete_; } bool is_error() { return is_error_; } /** \brief Parses the provided data as an HTTP request, and populates the current object. */ bool parse() { parser_state next_state = parser_state::start; char const *token_start = nullptr; std::string variable; std::string value; for (const char *p = data_ptr_; (p - data_.data()) < data_end_; ++p) { switch (parser_state_) { case parser_state::start: if (!set_error( (*p < 'A' || *p > 'Z') )) { parser_state_ = parser_state::method; token_start = p; } break; case parser_state::method: if (!set_error( (*p < 'A' || *p > 'Z') && *p != ' ' )) { if (*p == ' ') { method = std::string(token_start, p - token_start); parser_state_ = parser_state::uri; token_start = p + 1; // +1 to move past ' '. //std::cerr << "[parse] Method: " << method << std::endl; } } break; case parser_state::uri: if (!set_error( (*p < 32 || *p > 126) )) { // Accept all printables. if (*p == '?') { // End of URI, start of params uri = decode_url(std::string(token_start, p - token_start)); parser_state_ = parser_state::uri_parameters; token_start = p + 1; // Move past '?' //std::cerr << "[parse] URI: " << uri << std::endl; } else if (*p == ' ') { // End of URI, start of version uri = decode_url(std::string(token_start, p - token_start)); parser_state_ = parser_state::http_version_HTTP; //std::cerr << "[parse] URI: " << uri << std::endl; } } break; case parser_state::uri_parameters: if (*p == '=') { variable = decode_url(std::string(token_start, p - token_start)); token_start = p + 1; // Move beyond '=' } else if (*p == '&' || *p == ' ') { value = decode_url(std::string(token_start, p - token_start)); if (variable.size() > 0) parameters[variable] = value; else if (value.size() > 0) parameters[value] = ""; //std::cerr << "[parse] param: " << variable << " = " << value << std::endl; if (*p == ' ') parser_state_ = parser_state::http_version_HTTP; token_start = p + 1; // Move beyond '&' } else if (*p == '\r' || *p == '\n') parser_state_ = parser_state::error; break; case parser_state::http_version_HTTP: //std::cerr << "[parse] parsing HTTP: " << *p << std::endl; // TODO: Proper HTTP sequence should be determined. if (!set_error( (*p != 'H' && *p != 'T' && *p != 'P') && *p != '/')) { if (*p == '/') { parser_state_ = parser_state::http_version_major; token_start = p + 1; // +1 to move past '/' } } break; case parser_state::http_version_major: //std::cerr << "[parse] parsing HTTP major: " << *p << std::endl; if (!set_error( (*p < '0' || *p > '9') && (*p != '.') )) { if ('.' == *p) { version_major = std::stol(std::string(token_start, p - token_start)); parser_state_ = parser_state::http_version_minor; token_start = p + 1; // +1 to move past '.' } } break; case parser_state::http_version_minor: //std::cerr << "[parse] parsing HTTP minor: " << *p << std::endl; if (!set_error( (*p < '0' || *p > '9') && (*p != '\r') )) { if ('\r' == *p) { version_minor = std::stol(std::string(token_start, p - token_start)); token_start = p + 2; // Move past "\r\n" next_state = parser_state::header_name; parser_state_ = parser_state::end_of_line; } } break; case parser_state::header_name: if (*p == '\r') { parser_state_ = parser_state::end_of_line; next_state = parser_state::post_data; post_data_start_ptr_ = p + 2; // move past \r\n } else if (!set_error(!identifier_char(*p))) { if (*p == ':') { variable = std::string(token_start, p - token_start); token_start = p + 2; // Move past ": " parser_state_ = parser_state::header_value; } } break; case parser_state::header_value: if (*p == '\r') { value = std::string(token_start, p - token_start); next_state = parser_state::header_name; parser_state_ = parser_state::end_of_line; token_start = p + 2; // Move past "\r\n" headers[variable] = value; //std::cerr << "[parse] " << variable << " = " << value << std::endl; } break; case parser_state::end_of_line: //std::cerr << "[parser] parsing end of line: " << *p << std::endl; if (!set_error( *p != '\n' )) { //std::cerr << "[parser] EOL parsed" << std::endl; parser_state_ = next_state; token_start = p + 1; // Move past '\n' } break; default: break; } if (is_error_) { //std::cerr << "[parse] ERROR - previous state: " << as_integer(state) << std::endl; parser_state_ = parser_state::error; break; } } if (parser_state_ == parser_state::post_data && headers.find("Content-Length") != headers.end()) { // This variable is for debugging puposes. uint32_t content_length = strtoul(headers["Content-Length"].c_str(), NULL, 0); if (data_end_ >= content_length) { post_data += std::string(post_data_start_ptr_, data_end_); is_complete_ = true; } } else { is_complete_ = true; data_end_ = 0; } return !is_error_; } private: enum class parser_state { start, method, uri, uri_parameters, http_version_HTTP, http_version_major, http_version_minor, header_name, header_value, end_of_request_maybe, post_data, error, end_of_line }; // TODO: Make this dynamic without the potential for uploading // huge files. std::array<char, 65535> data_; char *data_ptr_ = data_.data(); const char *post_data_start_ptr_ = nullptr; std::size_t data_end_ = 0; unsigned int parse_state_ = 0; bool is_complete_ = false; bool headers_complete_ = false; bool is_error_ = false; parser_state parser_state_ = parser_state::start; inline bool set_error(bool is_error) { return (is_error_ = is_error); } bool identifier_char(char c) { std::string valid_chars = "abcdefghijklmnopqrstuvwxyz0123456789-:"; auto p = valid_chars.find_first_of(::tolower(c)); return (p != std::string::npos); } std::string decode_url(const std::string &str) { char hex[3] = { 0, 0, 0 }; bool in_hex = false; std::string decoded = ""; for (int i=0; i < str.size(); ++i) { if (in_hex) { if (hex[0] == '\0') hex[0] = str[i]; else { hex[1] = str[i]; in_hex = false; char c = std::strtol(hex, nullptr, 16); decoded += c; } } else if (str[i] != '%') decoded += str[i]; else in_hex = true; } return decoded; } }; } /* http */ } /* serenity */ #endif /* end of include guard: SERENITY_HTTP_REQUEST_HPP_ */ <commit_msg>Post data was too long sometimes, because data_end_, was too long. Used content_length instead<commit_after>#ifndef SERENITY_HTTP_REQUEST_HPP_ #define SERENITY_HTTP_REQUEST_HPP_ #include <string> #include <map> #include <iostream> #include "response.hpp" namespace serenity { namespace http { const unsigned int nothing = 0; const unsigned int crlf_01_start = 1; const unsigned int crlf_01_end = 2; const unsigned int crlf_02_start = 3; const unsigned int crlf_02_end = 4; const unsigned int post_end = 5; template <typename Enumeration> auto as_integer(Enumeration const value) -> typename std::underlying_type<Enumeration>::type { return static_cast<typename std::underlying_type<Enumeration>::type>(value); } class request { public: /** \brief Method used for request: GET, PUT, DELETE, etc. */ std::string method; /** \brief The requested URI, including parameters */ std::string uri; // Convert to uri class from cpp-net /** \brief The requested function name */ std::string function; // First token after the service resolution info. /** \brief Extra URI arguments, path elements after the first token. */ std::string extra_path; /** \brief All of the HTTP headers provided by the client. */ std::map<std::string, std::string> headers; /** \brief All of the parameters supplied for the request. */ std::map<std::string, std::string> parameters; /** \brief Major HTTP version (ie 1) */ uint8_t version_major; /** \brief Minor HTTP version (ie 0) */ uint8_t version_minor; /** \brief Raw bytes of the extra data provided by the client in the request */ std::string post_data = "";; /** \brief Add data to the request for parsing. */ void add_data(const char *request_data, std::size_t bytes) { //std::cerr << "Data (" << bytes << "):" << std::endl // << request_data << std::endl; memcpy(data_.data() + data_end_, request_data, bytes); data_end_ += bytes; data_ptr_ = (data_.data() + data_end_) - bytes; if (headers_complete_) { // If we're done with the headers, go straight to parse() parse(); return; } int i = 0; for (; (i < bytes) && (parse_state_ < post_end); ++i) { switch (parse_state_) { case nothing: case crlf_01_end: if (request_data[i] == '\r') ++parse_state_; else parse_state_ = nothing; break; case crlf_01_start: case crlf_02_start: if (request_data[i] == '\n') ++parse_state_; else parse_state_ = nothing; break; case crlf_02_end: ++parse_state_; break; } } headers_complete_ = (parse_state_ >= crlf_02_end); if (headers_complete_) { parse(); } } bool is_complete() { return is_complete_; } bool is_error() { return is_error_; } /** \brief Parses the provided data as an HTTP request, and populates the current object. */ bool parse() { parser_state next_state = parser_state::start; char const *token_start = nullptr; std::string variable; std::string value; for (const char *p = data_ptr_; (p - data_.data()) < data_end_; ++p) { switch (parser_state_) { case parser_state::start: if (!set_error( (*p < 'A' || *p > 'Z') )) { parser_state_ = parser_state::method; token_start = p; } break; case parser_state::method: if (!set_error( (*p < 'A' || *p > 'Z') && *p != ' ' )) { if (*p == ' ') { method = std::string(token_start, p - token_start); parser_state_ = parser_state::uri; token_start = p + 1; // +1 to move past ' '. //std::cerr << "[parse] Method: " << method << std::endl; } } break; case parser_state::uri: if (!set_error( (*p < 32 || *p > 126) )) { // Accept all printables. if (*p == '?') { // End of URI, start of params uri = decode_url(std::string(token_start, p - token_start)); parser_state_ = parser_state::uri_parameters; token_start = p + 1; // Move past '?' //std::cerr << "[parse] URI: " << uri << std::endl; } else if (*p == ' ') { // End of URI, start of version uri = decode_url(std::string(token_start, p - token_start)); parser_state_ = parser_state::http_version_HTTP; //std::cerr << "[parse] URI: " << uri << std::endl; } } break; case parser_state::uri_parameters: if (*p == '=') { variable = decode_url(std::string(token_start, p - token_start)); token_start = p + 1; // Move beyond '=' } else if (*p == '&' || *p == ' ') { value = decode_url(std::string(token_start, p - token_start)); if (variable.size() > 0) parameters[variable] = value; else if (value.size() > 0) parameters[value] = ""; //std::cerr << "[parse] param: " << variable << " = " << value << std::endl; if (*p == ' ') parser_state_ = parser_state::http_version_HTTP; token_start = p + 1; // Move beyond '&' } else if (*p == '\r' || *p == '\n') parser_state_ = parser_state::error; break; case parser_state::http_version_HTTP: //std::cerr << "[parse] parsing HTTP: " << *p << std::endl; // TODO: Proper HTTP sequence should be determined. if (!set_error( (*p != 'H' && *p != 'T' && *p != 'P') && *p != '/')) { if (*p == '/') { parser_state_ = parser_state::http_version_major; token_start = p + 1; // +1 to move past '/' } } break; case parser_state::http_version_major: //std::cerr << "[parse] parsing HTTP major: " << *p << std::endl; if (!set_error( (*p < '0' || *p > '9') && (*p != '.') )) { if ('.' == *p) { version_major = std::stol(std::string(token_start, p - token_start)); parser_state_ = parser_state::http_version_minor; token_start = p + 1; // +1 to move past '.' } } break; case parser_state::http_version_minor: //std::cerr << "[parse] parsing HTTP minor: " << *p << std::endl; if (!set_error( (*p < '0' || *p > '9') && (*p != '\r') )) { if ('\r' == *p) { version_minor = std::stol(std::string(token_start, p - token_start)); token_start = p + 2; // Move past "\r\n" next_state = parser_state::header_name; parser_state_ = parser_state::end_of_line; } } break; case parser_state::header_name: if (*p == '\r') { parser_state_ = parser_state::end_of_line; next_state = parser_state::post_data; post_data_start_ptr_ = p + 2; // move past \r\n } else if (!set_error(!identifier_char(*p))) { if (*p == ':') { variable = std::string(token_start, p - token_start); token_start = p + 2; // Move past ": " parser_state_ = parser_state::header_value; } } break; case parser_state::header_value: if (*p == '\r') { value = std::string(token_start, p - token_start); next_state = parser_state::header_name; parser_state_ = parser_state::end_of_line; token_start = p + 2; // Move past "\r\n" headers[variable] = value; //std::cerr << "[parse] " << variable << " = " << value << std::endl; } break; case parser_state::end_of_line: //std::cerr << "[parser] parsing end of line: " << *p << std::endl; if (!set_error( *p != '\n' )) { //std::cerr << "[parser] EOL parsed" << std::endl; parser_state_ = next_state; token_start = p + 1; // Move past '\n' } break; default: break; } if (is_error_) { //std::cerr << "[parse] ERROR - previous state: " << as_integer(state) << std::endl; parser_state_ = parser_state::error; break; } } if (parser_state_ == parser_state::post_data && headers.find("Content-Length") != headers.end()) { // This variable is for debugging puposes. uint32_t content_length = strtoul(headers["Content-Length"].c_str(), NULL, 0); if (data_end_ >= content_length) { post_data += std::string(post_data_start_ptr_, content_length); is_complete_ = true; } } else { is_complete_ = true; data_end_ = 0; } return !is_error_; } private: enum class parser_state { start, method, uri, uri_parameters, http_version_HTTP, http_version_major, http_version_minor, header_name, header_value, end_of_request_maybe, post_data, error, end_of_line }; // TODO: Make this dynamic without the potential for uploading // huge files. std::array<char, 65535> data_; char *data_ptr_ = data_.data(); const char *post_data_start_ptr_ = nullptr; std::size_t data_end_ = 0; unsigned int parse_state_ = 0; bool is_complete_ = false; bool headers_complete_ = false; bool is_error_ = false; parser_state parser_state_ = parser_state::start; inline bool set_error(bool is_error) { return (is_error_ = is_error); } bool identifier_char(char c) { std::string valid_chars = "abcdefghijklmnopqrstuvwxyz0123456789-:"; auto p = valid_chars.find_first_of(::tolower(c)); return (p != std::string::npos); } std::string decode_url(const std::string &str) { char hex[3] = { 0, 0, 0 }; bool in_hex = false; std::string decoded = ""; for (int i=0; i < str.size(); ++i) { if (in_hex) { if (hex[0] == '\0') hex[0] = str[i]; else { hex[1] = str[i]; in_hex = false; char c = std::strtol(hex, nullptr, 16); decoded += c; } } else if (str[i] != '%') decoded += str[i]; else in_hex = true; } return decoded; } }; } /* http */ } /* serenity */ #endif /* end of include guard: SERENITY_HTTP_REQUEST_HPP_ */ <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <tracker-sparql.h> #include <QtTest/QtTest> #include <QtSparql/QtSparql> #include <stdlib.h> #include <sys/time.h> #include <stdio.h> #define START_BENCHMARK \ char tsbuf2[32]; \ struct timeval tv2; \ gettimeofday(&tv2, NULL); \ long start = tv2.tv_sec * 1000 + tv2.tv_usec / 1000; \ #define END_BENCHMARK(TEXT) \ gettimeofday(&tv2, NULL); \ long end = tv2.tv_sec * 1000 + tv2.tv_usec / 1000; \ snprintf(tsbuf2, sizeof(tsbuf2), TEXT " %lu\n", end - start); \ write(8, tsbuf2, strlen(tsbuf2)) class tst_QSparqlBenchmark : public QObject { Q_OBJECT public: tst_QSparqlBenchmark(); virtual ~tst_QSparqlBenchmark(); public slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: // Actual benchmarks void queryBenchmark(); void queryBenchmark_data(); // Reference benchmarks void queryWithLibtrackerSparql(); void queryWithLibtrackerSparql_data(); void queryWithLibtrackerSparqlInThread(); void queryWithLibtrackerSparqlInThread_data(); void dummyThread(); }; tst_QSparqlBenchmark::tst_QSparqlBenchmark() { } tst_QSparqlBenchmark::~tst_QSparqlBenchmark() { } void tst_QSparqlBenchmark::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); } void tst_QSparqlBenchmark::cleanupTestCase() { } void tst_QSparqlBenchmark::init() { } void tst_QSparqlBenchmark::cleanup() { } namespace { class ResultRetriever : public QObject { Q_OBJECT public: ResultRetriever(QSparqlResult* r) : result(r) { connect(r, SIGNAL(finished()), SLOT(onFinished())); } public slots: void onFinished() { // Do something silly with the data int total = 0; while (result->next()) { total += result->value(0).toString().size(); } result->deleteLater(); } private: QSparqlResult* result; }; } void tst_QSparqlBenchmark::queryBenchmark() { QFETCH(QString, connectionName); QFETCH(QString, queryString); QSparqlQuery query(queryString); // Note: connection opening cost is left out from the QBENCHMARK. QSparqlConnection conn(connectionName); QSparqlResult* r = 0; // We run multiple queries here (and don't leave it for QBENCHMARK to // run this multiple times, to be able to measure things like "how much // does adding a QThreadPool help". for (int i = 0; i < 100; ++i) { START_BENCHMARK { r = conn.exec(query); r->waitForFinished(); QVERIFY(!r->hasError()); QVERIFY(r->size() > 0); delete r; } END_BENCHMARK("qsparql"); } } void tst_QSparqlBenchmark::queryBenchmark_data() { QTest::addColumn<QString>("connectionName"); QTest::addColumn<QString>("queryString"); // The query is trivial, these tests cases measure (exaggerates) other costs // than running the query. /* QString trivialQuery = "select ?u {?u a rdfs:Resource .}"; QTest::newRow("TrackerDBusAllResources") << "QTRACKER" << trivialQuery; QTest::newRow("TrackerDirectAllResources") << "QTRACKER_DIRECT" << trivialQuery; */ // A bit more complicated query. Test data for running this can be found in // the tracker project. QString artistsAndAlbums = "SELECT nmm:artistName(?artist) GROUP_CONCAT(nie:title(?album),'|') " "WHERE " "{ " "?song a nmm:MusicPiece . " "?song nmm:performer ?artist . " "?song nmm:musicAlbum ?album . " "} GROUP BY ?artist"; /* QTest::newRow("TrackerDBusArtistsAndAlbums") << "QTRACKER" << artistsAndAlbums; */ QTest::newRow("TrackerDirectArtistsAndAlbums") << "QTRACKER_DIRECT" << artistsAndAlbums; } void tst_QSparqlBenchmark::queryWithLibtrackerSparql() { g_type_init(); QFETCH(QString, queryString); GError* error = 0; TrackerSparqlConnection* connection = tracker_sparql_connection_get(0, &error); QVERIFY(connection); QVERIFY(error == 0); for (int i = 0; i < 100; ++i) { START_BENCHMARK { TrackerSparqlCursor* cursor = tracker_sparql_connection_query(connection, queryString.toUtf8(), NULL, &error); QVERIFY(error == 0); QVERIFY(cursor); QStringList values; QList<TrackerSparqlValueType> types; while (tracker_sparql_cursor_next (cursor, NULL, &error)) { gint n_columns = tracker_sparql_cursor_get_n_columns(cursor); for (int i = 0; i < n_columns; i++) { QString value = QString::fromUtf8( tracker_sparql_cursor_get_string(cursor, i, 0)); TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(cursor, i); values << value; types << type; } } QVERIFY(values.size() > 0); QVERIFY(types.size() > 0); g_object_unref(cursor); } END_BENCHMARK("lts"); } g_object_unref(connection); } void tst_QSparqlBenchmark::queryWithLibtrackerSparql_data() { QTest::addColumn<QString>("queryString"); // The query is trivial, these tests cases measure (exaggerates) other costs // than running the query. /*QString trivialQuery = "select ?u {?u a rdfs:Resource .}"; QTest::newRow("AllResources") << trivialQuery; */ // A bit more complicated query. Test data for running this can be found in // the tracker project. QString artistsAndAlbums = "SELECT nmm:artistName(?artist) GROUP_CONCAT(nie:title(?album),'|') " "WHERE " "{ " "?song a nmm:MusicPiece . " "?song nmm:performer ?artist . " "?song nmm:musicAlbum ?album . " "} GROUP BY ?artist"; QTest::newRow("ArtistsAndAlbums") << artistsAndAlbums; } namespace { class QueryRunner : public QThread { public: QueryRunner(TrackerSparqlConnection* c, const QString& q, bool d = false) : connection(c), queryString(q), isDummy(d), hasRun(false) { } void run() { hasRun = true; if (isDummy) return; GError* error = 0; TrackerSparqlCursor* cursor = tracker_sparql_connection_query(connection, queryString.toUtf8(), NULL, &error); QVERIFY(error == 0); QVERIFY(cursor); QStringList values; QList<TrackerSparqlValueType> types; while (tracker_sparql_cursor_next(cursor, NULL, &error)) { QSparqlResultRow resultRow; gint n_columns = tracker_sparql_cursor_get_n_columns(cursor); for (int i = 0; i < n_columns; i++) { QString value = QString::fromUtf8( tracker_sparql_cursor_get_string(cursor, i, 0)); TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(cursor, i); values << value; types << type; } } QVERIFY(values.size() > 0); QVERIFY(types.size() > 0); g_object_unref(cursor); } TrackerSparqlConnection* connection; QString queryString; bool isDummy; bool hasRun; }; } // unnamed namespace void tst_QSparqlBenchmark::queryWithLibtrackerSparqlInThread() { g_type_init(); QFETCH(QString, queryString); GError* error = 0; TrackerSparqlConnection* connection = tracker_sparql_connection_get(0, &error); QVERIFY(connection); QVERIFY(error == 0); for (int i = 0; i < 100; ++i) { START_BENCHMARK { QueryRunner runner(connection, queryString); runner.start(); runner.wait(); } END_BENCHMARK("lts-thread"); } g_object_unref(connection); } void tst_QSparqlBenchmark::queryWithLibtrackerSparqlInThread_data() { queryWithLibtrackerSparql_data(); } void tst_QSparqlBenchmark::dummyThread() { QBENCHMARK { for (int i = 0; i < 100; ++i) { QueryRunner runner(0, "", true); runner.start(); runner.wait(); QVERIFY(runner.hasRun); } } } QTEST_MAIN(tst_QSparqlBenchmark) #include "tst_qsparql_benchmark.moc" <commit_msg>Cleaning up and updating the benchmarks.<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (ivan.frade@nokia.com) ** ** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit). ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at ivan.frade@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <tracker-sparql.h> #include <QtTest/QtTest> #include <QtSparql/QtSparql> #include <stdlib.h> #include <sys/time.h> #include <stdio.h> #define START_BENCHMARK \ char tsbuf2[32]; \ struct timeval tv2; \ gettimeofday(&tv2, NULL); \ long start = tv2.tv_sec * 1000 + tv2.tv_usec / 1000; \ #define END_BENCHMARK(QSTRINGNAME) \ gettimeofday(&tv2, NULL); \ long end = tv2.tv_sec * 1000 + tv2.tv_usec / 1000; \ snprintf(tsbuf2, sizeof(tsbuf2), "%s %lu\n", qPrintable(QSTRINGNAME), end - start); \ write(8, tsbuf2, strlen(tsbuf2)) class tst_QSparqlBenchmark : public QObject { Q_OBJECT public: tst_QSparqlBenchmark(); virtual ~tst_QSparqlBenchmark(); public slots: void initTestCase(); void cleanupTestCase(); void init(); void cleanup(); private slots: // Actual benchmarks void queryBenchmark(); void queryBenchmark_data(); // Reference benchmarks void queryWithLibtrackerSparql(); void queryWithLibtrackerSparql_data(); void queryWithLibtrackerSparqlInThread(); void queryWithLibtrackerSparqlInThread_data(); void dummyThread(); }; tst_QSparqlBenchmark::tst_QSparqlBenchmark() { } tst_QSparqlBenchmark::~tst_QSparqlBenchmark() { } void tst_QSparqlBenchmark::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); } void tst_QSparqlBenchmark::cleanupTestCase() { } void tst_QSparqlBenchmark::init() { } void tst_QSparqlBenchmark::cleanup() { } namespace { class ResultRetriever : public QObject { Q_OBJECT public: ResultRetriever(QSparqlResult* r) : result(r) { connect(r, SIGNAL(finished()), SLOT(onFinished())); } public slots: void onFinished() { // Do something silly with the data int total = 0; while (result->next()) { total += result->value(0).toString().size(); } result->deleteLater(); } private: QSparqlResult* result; }; } void tst_QSparqlBenchmark::queryBenchmark() { QFETCH(QString, benchmarkName); QFETCH(QString, connectionName); QFETCH(QString, queryString); QSparqlQuery query(queryString); QSparqlConnection conn(connectionName); // Note: connection opening cost is left out of the benchmark. Connection // opening is async, so we need to wait here long enough to know that it has // opened (there is no signal sent or such to know it has opened). QTest::qWait(2000); QSparqlResult* r = 0; // We run multiple queries here (and don't leave it for QBENCHMARK to // run this multiple times, to be able to measure things like "how much // does adding a QThreadPool help". for (int i = 0; i < 100; ++i) { START_BENCHMARK { r = conn.exec(query); r->waitForFinished(); QVERIFY(!r->hasError()); QVERIFY(r->size() > 0); delete r; } END_BENCHMARK(benchmarkName); } } void tst_QSparqlBenchmark::queryBenchmark_data() { QTest::addColumn<QString>("benchmarkName"); QTest::addColumn<QString>("connectionName"); QTest::addColumn<QString>("queryString"); // The query is trivial, these tests cases measure (exaggerates) other costs // than running the query. QString trivialQuery = "select ?u {?u a rdfs:Resource .}"; QTest::newRow("TrackerDBusAllResources") << "dbus-allresources" << "QTRACKER" << trivialQuery; QTest::newRow("TrackerDirectAllResources") << "direct-allresources" << "QTRACKER_DIRECT" << trivialQuery; // A bit more complicated query. Test data for running this can be found in // the tracker project. QString artistsAndAlbums = "SELECT nmm:artistName(?artist) GROUP_CONCAT(nie:title(?album),'|') " "WHERE " "{ " "?song a nmm:MusicPiece . " "?song nmm:performer ?artist . " "?song nmm:musicAlbum ?album . " "} GROUP BY ?artist"; QTest::newRow("TrackerDBusArtistsAndAlbums") << "dbus-artistsandalbums" << "QTRACKER" << artistsAndAlbums; QTest::newRow("TrackerDirectArtistsAndAlbums") << "direct-artistsandalbums" << "QTRACKER_DIRECT" << artistsAndAlbums; } void tst_QSparqlBenchmark::queryWithLibtrackerSparql() { g_type_init(); QFETCH(QString, benchmarkName); QFETCH(QString, queryString); GError* error = 0; TrackerSparqlConnection* connection = tracker_sparql_connection_get(0, &error); QVERIFY(connection); QVERIFY(error == 0); for (int i = 0; i < 100; ++i) { START_BENCHMARK { TrackerSparqlCursor* cursor = tracker_sparql_connection_query(connection, queryString.toUtf8(), NULL, &error); QVERIFY(error == 0); QVERIFY(cursor); QStringList values; QList<TrackerSparqlValueType> types; while (tracker_sparql_cursor_next (cursor, NULL, &error)) { gint n_columns = tracker_sparql_cursor_get_n_columns(cursor); for (int i = 0; i < n_columns; i++) { QString value = QString::fromUtf8( tracker_sparql_cursor_get_string(cursor, i, 0)); TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(cursor, i); values << value; types << type; } } QVERIFY(values.size() > 0); QVERIFY(types.size() > 0); g_object_unref(cursor); } END_BENCHMARK(benchmarkName); } g_object_unref(connection); } void tst_QSparqlBenchmark::queryWithLibtrackerSparql_data() { QTest::addColumn<QString>("benchmarkName"); QTest::addColumn<QString>("queryString"); // The query is trivial, these tests cases measure (exaggerates) other costs // than running the query. QString trivialQuery = "select ?u {?u a rdfs:Resource .}"; QTest::newRow("AllResources") << "lts-allresources" << trivialQuery; // A bit more complicated query. Test data for running this can be found in // the tracker project. QString artistsAndAlbums = "SELECT nmm:artistName(?artist) GROUP_CONCAT(nie:title(?album),'|') " "WHERE " "{ " "?song a nmm:MusicPiece . " "?song nmm:performer ?artist . " "?song nmm:musicAlbum ?album . " "} GROUP BY ?artist"; QTest::newRow("ArtistsAndAlbums") << "lts-artistsandalbums" << artistsAndAlbums; } namespace { class QueryRunner : public QThread { public: QueryRunner(TrackerSparqlConnection* c, const QString& q, bool d = false) : connection(c), queryString(q), isDummy(d), hasRun(false) { } void run() { hasRun = true; if (isDummy) return; GError* error = 0; TrackerSparqlCursor* cursor = tracker_sparql_connection_query(connection, queryString.toUtf8(), NULL, &error); QVERIFY(error == 0); QVERIFY(cursor); QStringList values; QList<TrackerSparqlValueType> types; while (tracker_sparql_cursor_next(cursor, NULL, &error)) { QSparqlResultRow resultRow; gint n_columns = tracker_sparql_cursor_get_n_columns(cursor); for (int i = 0; i < n_columns; i++) { QString value = QString::fromUtf8( tracker_sparql_cursor_get_string(cursor, i, 0)); TrackerSparqlValueType type = tracker_sparql_cursor_get_value_type(cursor, i); values << value; types << type; } } QVERIFY(values.size() > 0); QVERIFY(types.size() > 0); g_object_unref(cursor); } TrackerSparqlConnection* connection; QString queryString; bool isDummy; bool hasRun; }; } // unnamed namespace void tst_QSparqlBenchmark::queryWithLibtrackerSparqlInThread() { g_type_init(); QFETCH(QString, benchmarkName); benchmarkName += QString("-thread"); QFETCH(QString, queryString); GError* error = 0; TrackerSparqlConnection* connection = tracker_sparql_connection_get(0, &error); QVERIFY(connection); QVERIFY(error == 0); for (int i = 0; i < 100; ++i) { START_BENCHMARK { QueryRunner runner(connection, queryString); runner.start(); runner.wait(); } END_BENCHMARK(benchmarkName); } g_object_unref(connection); } void tst_QSparqlBenchmark::queryWithLibtrackerSparqlInThread_data() { queryWithLibtrackerSparql_data(); } void tst_QSparqlBenchmark::dummyThread() { QBENCHMARK { for (int i = 0; i < 100; ++i) { QueryRunner runner(0, "", true); runner.start(); runner.wait(); QVERIFY(runner.hasRun); } } } QTEST_MAIN(tst_QSparqlBenchmark) #include "tst_qsparql_benchmark.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // This test code is based on the qdbusthreading tests in qt #include <QtTest> #include <QtCore/QVarLengthArray> #include <QtCore/QThread> #include <QtCore/QObject> #include <QtCore/QSemaphore> #include <QtCore/QMutex> #include <QtCore/QWaitCondition> #include <QtCore/QMap> #include <QtSparql/QtSparql> // #define TEST_PORT 1111 #define TEST_PORT 1234 class Thread : public QThread { Q_OBJECT static int counter; public: Thread(bool automatic = true); void run(); using QThread::exec; public Q_SLOTS: void queryFinished(); }; int Thread::counter; class tst_QSparqlThreading : public QObject { Q_OBJECT static tst_QSparqlThreading *_self; QAtomicInt threadJoinCount; QSemaphore threadJoin; public: QSemaphore sem1, sem2; volatile bool success; QEventLoop *loop; const char *functionSpy; QThread *threadSpy; int signalSpy; QSparqlResult * r1; QSparqlResult * r2; tst_QSparqlThreading(); static inline tst_QSparqlThreading *self() { return _self; } void joinThreads(); bool waitForSignal(QObject *obj, const char *signal, int delay = 1); public Q_SLOTS: void cleanup(); void signalSpySlot() { ++signalSpy; } void threadStarted() { threadJoinCount.ref(); } void threadFinished() { threadJoin.release(); } void concurrentEndpointQueries_thread(); void concurrentVirtuosoQueries_thread(); private Q_SLOTS: void initTestCase(); void concurrentEndpointQueries(); void concurrentVirtuosoQueries(); }; tst_QSparqlThreading *tst_QSparqlThreading::_self; class Object : public QObject { Q_OBJECT public: Object() { } ~Object() { QMetaObject::invokeMethod(QThread::currentThread(), "quit", Qt::QueuedConnection); } public Q_SLOTS: void method() { tst_QSparqlThreading::self()->functionSpy = Q_FUNC_INFO; tst_QSparqlThreading::self()->threadSpy = QThread::currentThread(); emit signal(); deleteLater(); } Q_SIGNALS: void signal(); }; Thread::Thread(bool automatic) { setObjectName(QString::fromLatin1("Aux thread %1").arg(++counter)); connect(this, SIGNAL(started()), tst_QSparqlThreading::self(), SLOT(threadStarted())); connect(this, SIGNAL(finished()), tst_QSparqlThreading::self(), SLOT(threadFinished()), Qt::DirectConnection); connect(this, SIGNAL(finished()), this, SLOT(deleteLater()), Qt::DirectConnection); if (automatic) start(); } void Thread::run() { QVarLengthArray<char, 56> name; name.append(QTest::currentTestFunction(), qstrlen(QTest::currentTestFunction())); name.append("_thread", sizeof "_thread"); QMetaObject::invokeMethod(tst_QSparqlThreading::self(), name.constData(), Qt::DirectConnection); } void Thread::queryFinished() { qDebug() << "In queryFinished"; quit(); } tst_QSparqlThreading::tst_QSparqlThreading() : loop(0), functionSpy(0), threadSpy(0) { _self = this; QCoreApplication::instance()->thread()->setObjectName("Main thread"); } void tst_QSparqlThreading::joinThreads() { qDebug() << "ENTER joinThreads() threadJoinCount:" << threadJoinCount; threadJoin.acquire(threadJoinCount); threadJoinCount = 0; } bool tst_QSparqlThreading::waitForSignal(QObject *obj, const char *signal, int delay) { qDebug() << "tst_QSparqlThreading::waitForSignal() &QTestEventLoop::instance():" << &QTestEventLoop::instance(); qDebug() << "tst_QSparqlThreading::waitForSignal() QTestEventLoop::instance().timeout():" << QTestEventLoop::instance().timeout(); QObject::connect(obj, signal, &QTestEventLoop::instance(), SLOT(exitLoop())); QPointer<QObject> safe = obj; QTestEventLoop::instance().enterLoop(delay); if (!safe.isNull()) QObject::disconnect(safe, signal, &QTestEventLoop::instance(), SLOT(exitLoop())); return QTestEventLoop::instance().timeout(); } void tst_QSparqlThreading::cleanup() { joinThreads(); if (sem1.available()) sem1.acquire(sem1.available()); if (sem2.available()) sem2.acquire(sem2.available()); delete loop; loop = 0; QTest::qWait(500); } void tst_QSparqlThreading::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); } void tst_QSparqlThreading::concurrentEndpointQueries_thread() { sem1.acquire(); QSparqlConnectionOptions options; options.setHostName("localhost"); options.setPort(8890); QSparqlConnection conn("QSPARQL_ENDPOINT", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r2 = conn.exec(q); connect(r2, SIGNAL(finished()), QThread::currentThread(), SLOT(queryFinished())); sem2.release(); qDebug() << "EXIT tst_QSparqlThreading::concurrentEndpointQueries_thread()"; static_cast<Thread *>(QThread::currentThread())->exec(); } void tst_QSparqlThreading::concurrentEndpointQueries() { Thread *th = new Thread; sem1.release(); QSparqlConnectionOptions options; options.setHostName("localhost"); options.setPort(8890); QSparqlConnection conn("QSPARQL_ENDPOINT", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r1 = conn.exec(q); sem2.acquire(); qDebug() << "About to waitForFinished"; // r1->waitForFinished(); qDebug() << "About to waitForSignal"; waitForSignal(th, SIGNAL(finished())); } void tst_QSparqlThreading::concurrentVirtuosoQueries_thread() { sem1.acquire(); QSparqlConnectionOptions options; options.setDatabaseName("DRIVER=/usr/lib/odbc/virtodbc_r.so"); options.setPort(TEST_PORT); QSparqlConnection conn("QVIRTUOSO", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r2 = conn.exec(q); connect(r2, SIGNAL(finished()), QThread::currentThread(), SLOT(queryFinished())); sem2.release(); static_cast<Thread *>(QThread::currentThread())->exec(); } void tst_QSparqlThreading::concurrentVirtuosoQueries() { Thread *th = new Thread; sem1.release(); QSparqlConnectionOptions options; options.setDatabaseName("DRIVER=/usr/lib/odbc/virtodbc_r.so"); options.setPort(TEST_PORT); QSparqlConnection conn("QVIRTUOSO", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r1 = conn.exec(q); sem2.acquire(); // r1->waitForFinished(); waitForSignal(th, SIGNAL(finished())); } QTEST_MAIN(tst_QSparqlThreading) #include "tst_qsparql_threading.moc" <commit_msg>* The threading test now doesn't crash and runs to end<commit_after>/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // This test code is based on the qdbusthreading tests in qt #include <QtTest> #include <QtCore/QVarLengthArray> #include <QtCore/QThread> #include <QtCore/QObject> #include <QtCore/QSemaphore> #include <QtCore/QMutex> #include <QtCore/QWaitCondition> #include <QtCore/QMap> #include <QtSparql/QtSparql> // #define TEST_PORT 1111 #define TEST_PORT 1234 class Thread : public QThread { Q_OBJECT static int counter; public: Thread(bool automatic = true); void run(); using QThread::exec; public Q_SLOTS: void queryFinished(); }; int Thread::counter; class tst_QSparqlThreading : public QObject { Q_OBJECT static tst_QSparqlThreading *_self; QAtomicInt threadJoinCount; QSemaphore threadJoin; public: QSemaphore sem1, sem2; volatile bool success; QEventLoop *loop; const char *functionSpy; QThread *threadSpy; int signalSpy; QSparqlResult * r1; QSparqlResult * r2; tst_QSparqlThreading(); static inline tst_QSparqlThreading *self() { return _self; } void joinThreads(); bool waitForSignal(QObject *obj, const char *signal, int delay = 1); public Q_SLOTS: void cleanup(); void signalSpySlot() { ++signalSpy; } void threadStarted() { threadJoinCount.ref(); } void threadFinished() { threadJoin.release(); } void concurrentEndpointQueries_thread(); void concurrentVirtuosoQueries_thread(); private Q_SLOTS: void initTestCase(); void concurrentEndpointQueries(); void concurrentVirtuosoQueries(); }; tst_QSparqlThreading *tst_QSparqlThreading::_self; class Object : public QObject { Q_OBJECT public: Object() { } ~Object() { QMetaObject::invokeMethod(QThread::currentThread(), "quit", Qt::QueuedConnection); } public Q_SLOTS: void method() { tst_QSparqlThreading::self()->functionSpy = Q_FUNC_INFO; tst_QSparqlThreading::self()->threadSpy = QThread::currentThread(); emit signal(); deleteLater(); } Q_SIGNALS: void signal(); }; Thread::Thread(bool automatic) { setObjectName(QString::fromLatin1("Aux thread %1").arg(++counter)); connect(this, SIGNAL(started()), tst_QSparqlThreading::self(), SLOT(threadStarted())); connect(this, SIGNAL(finished()), tst_QSparqlThreading::self(), SLOT(threadFinished()), Qt::DirectConnection); connect(this, SIGNAL(finished()), this, SLOT(deleteLater()), Qt::DirectConnection); if (automatic) start(); } void Thread::run() { QVarLengthArray<char, 56> name; name.append(QTest::currentTestFunction(), qstrlen(QTest::currentTestFunction())); name.append("_thread", sizeof "_thread"); QMetaObject::invokeMethod(tst_QSparqlThreading::self(), name.constData(), Qt::DirectConnection); } void Thread::queryFinished() { qDebug() << "In queryFinished"; quit(); } tst_QSparqlThreading::tst_QSparqlThreading() : loop(0), functionSpy(0), threadSpy(0) { _self = this; QCoreApplication::instance()->thread()->setObjectName("Main thread"); } void tst_QSparqlThreading::joinThreads() { qDebug() << "ENTER joinThreads() threadJoinCount:" << threadJoinCount; threadJoin.acquire(threadJoinCount); threadJoinCount = 0; } bool tst_QSparqlThreading::waitForSignal(QObject *obj, const char *signal, int delay) { qDebug() << "tst_QSparqlThreading::waitForSignal() &QTestEventLoop::instance():" << &QTestEventLoop::instance(); qDebug() << "tst_QSparqlThreading::waitForSignal() QTestEventLoop::instance().timeout():" << QTestEventLoop::instance().timeout(); QObject::connect(obj, signal, &QTestEventLoop::instance(), SLOT(exitLoop())); QPointer<QObject> safe = obj; QTestEventLoop::instance().enterLoop(delay); if (!safe.isNull()) QObject::disconnect(safe, signal, &QTestEventLoop::instance(), SLOT(exitLoop())); return QTestEventLoop::instance().timeout(); } void tst_QSparqlThreading::cleanup() { joinThreads(); if (sem1.available()) sem1.acquire(sem1.available()); if (sem2.available()) sem2.acquire(sem2.available()); delete loop; loop = 0; QTest::qWait(500); } void tst_QSparqlThreading::initTestCase() { // For running the test without installing the plugins. Should work in // normal and vpath builds. QCoreApplication::addLibraryPath("../../../plugins"); } void tst_QSparqlThreading::concurrentEndpointQueries_thread() { sem1.acquire(); QSparqlConnectionOptions options; options.setHostName("localhost"); options.setPort(8890); QSparqlConnection conn("QSPARQL_ENDPOINT", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r2 = conn.exec(q); connect(r2, SIGNAL(finished()), QThread::currentThread(), SLOT(queryFinished())); sem2.release(); qDebug() << "EXIT tst_QSparqlThreading::concurrentEndpointQueries_thread()"; static_cast<Thread *>(QThread::currentThread())->exec(); } void tst_QSparqlThreading::concurrentEndpointQueries() { Thread *th = new Thread; sem1.release(); QSparqlConnectionOptions options; options.setHostName("localhost"); options.setPort(8890); QSparqlConnection conn("QSPARQL_ENDPOINT", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r1 = conn.exec(q); sem2.acquire(); qDebug() << "About to waitForFinished"; r1->waitForFinished(); if (!th->isFinished()) { qDebug() << "About to waitForSignal"; waitForSignal(th, SIGNAL(finished())); } } void tst_QSparqlThreading::concurrentVirtuosoQueries_thread() { sem1.acquire(); QSparqlConnectionOptions options; options.setDatabaseName("DRIVER=/usr/lib/odbc/virtodbc_r.so"); options.setPort(TEST_PORT); QSparqlConnection conn("QVIRTUOSO", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r2 = conn.exec(q); connect(r2, SIGNAL(finished()), QThread::currentThread(), SLOT(queryFinished())); sem2.release(); static_cast<Thread *>(QThread::currentThread())->exec(); } void tst_QSparqlThreading::concurrentVirtuosoQueries() { Thread *th = new Thread; sem1.release(); QSparqlConnectionOptions options; options.setDatabaseName("DRIVER=/usr/lib/odbc/virtodbc_r.so"); options.setPort(TEST_PORT); QSparqlConnection conn("QVIRTUOSO", options); QSparqlQuery q("SELECT ?s ?p ?o WHERE { ?s ?p ?o . }"); r1 = conn.exec(q); sem2.acquire(); r1->waitForFinished(); if (!th->isFinished()) { qDebug() << "About to waitForSignal"; waitForSignal(th, SIGNAL(finished())); } } QTEST_MAIN(tst_QSparqlThreading) #include "tst_qsparql_threading.moc" <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QmlEngine> #include <QmlComponent> #include <QmlMetaType> #include <QDebug> #include <QGraphicsScene> #include <QGraphicsItem> #include <QmlGraphicsItem> #include <private/qobject_p.h> class tst_creation : public QObject { Q_OBJECT public: tst_creation() {} private slots: void qobject_cpp(); void qobject_qml(); void qobject_qmltype(); void qobject_alloc(); void objects_qmltype_data(); void objects_qmltype(); void qgraphicsitem(); void qgraphicsitem_tree(); void itemtree_notree_cpp(); void itemtree_objtree_cpp(); void itemtree_cpp(); void itemtree_data_cpp(); void itemtree_qml(); void itemtree_scene_cpp(); private: QmlEngine engine; }; inline QUrl TEST_FILE(const QString &filename) { return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename); } void tst_creation::qobject_cpp() { QBENCHMARK { QObject *obj = new QObject; delete obj; } } void tst_creation::qobject_qml() { QmlComponent component(&engine, TEST_FILE("qobject.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::qobject_qmltype() { QmlType *t = QmlMetaType::qmlType("Qt/QtObject", 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } struct QObjectFakeData { char data[sizeof(QObjectPrivate)]; }; struct QObjectFake { QObjectFake(); virtual ~QObjectFake(); private: QObjectFakeData *d; }; QObjectFake::QObjectFake() { d = new QObjectFakeData; } QObjectFake::~QObjectFake() { delete d; } void tst_creation::qobject_alloc() { QBENCHMARK { QObjectFake *obj = new QObjectFake; delete obj; } } void tst_creation::objects_qmltype_data() { QTest::addColumn<QByteArray>("type"); QList<QByteArray> types = QmlMetaType::qmlTypeNames(); foreach (QByteArray type, types) QTest::newRow(type.constData()) << type; } void tst_creation::objects_qmltype() { QFETCH(QByteArray, type); QmlType *t = QmlMetaType::qmlType(type, 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } class QGraphicsItemDummy : public QGraphicsItem { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; void tst_creation::qgraphicsitem() { QBENCHMARK { QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); delete i1; delete i2; delete i3; delete i4; delete i5; delete i6; delete i7; delete i8; delete i9; delete i10; delete i11; delete i12; delete i13; delete i14; } } void tst_creation::qgraphicsitem_tree() { QBENCHMARK { // i1 // +-------------------------+ // i2 i3 // +-----------+ +-----+-----+ // i4 i5 i6 i7 // +----+ +--+ +--+--+ +----+ // i8 i9 i10 i11 i12 i13 i14 QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); i14->setParentItem(i7); i13->setParentItem(i7); i12->setParentItem(i6); i11->setParentItem(i6); i10->setParentItem(i5); i9->setParentItem(i4); i8->setParentItem(i4); i7->setParentItem(i3); i6->setParentItem(i3); i5->setParentItem(i2); i4->setParentItem(i2); i3->setParentItem(i1); i2->setParentItem(i1); delete i1; } } struct QmlGraphics_DerivedObject : public QObject { void setParent_noEvent(QObject *parent) { bool sce = d_ptr->sendChildEvents; d_ptr->sendChildEvents = false; setParent(parent); d_ptr->sendChildEvents = sce; } }; inline void QmlGraphics_setParent_noEvent(QObject *object, QObject *parent) { static_cast<QmlGraphics_DerivedObject *>(object)->setParent_noEvent(parent); } void tst_creation::itemtree_notree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; } delete item; } } void tst_creation::itemtree_objtree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); } delete item; } } void tst_creation::itemtree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); child->setParentItem(item); } delete item; } } void tst_creation::itemtree_data_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); item->data()->append(child); } delete item; } } void tst_creation::itemtree_qml() { QmlComponent component(&engine, TEST_FILE("item.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::itemtree_scene_cpp() { QGraphicsScene scene; QmlGraphicsItem *root = new QmlGraphicsItem; scene.addItem(root); QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); child->setParentItem(item); } item->setParentItem(root); delete item; } delete root; } QTEST_MAIN(tst_creation) #include "tst_creation.moc" <commit_msg>benchmark<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the Technology Preview License Agreement accompanying ** this package. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** ** ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <qtest.h> #include <QmlEngine> #include <QmlComponent> #include <QmlMetaType> #include <QDebug> #include <QGraphicsScene> #include <QGraphicsItem> #include <QmlGraphicsItem> #include <private/qobject_p.h> class tst_creation : public QObject { Q_OBJECT public: tst_creation() {} private slots: void qobject_cpp(); void qobject_qml(); void qobject_qmltype(); void qobject_alloc(); void objects_qmltype_data(); void objects_qmltype(); void qgraphicsitem(); void qgraphicsobject(); void qgraphicsitem14(); void qgraphicsitem_tree14(); void itemtree_notree_cpp(); void itemtree_objtree_cpp(); void itemtree_cpp(); void itemtree_data_cpp(); void itemtree_qml(); void itemtree_scene_cpp(); private: QmlEngine engine; }; inline QUrl TEST_FILE(const QString &filename) { return QUrl::fromLocalFile(QLatin1String(SRCDIR) + QLatin1String("/data/") + filename); } void tst_creation::qobject_cpp() { QBENCHMARK { QObject *obj = new QObject; delete obj; } } void tst_creation::qobject_qml() { QmlComponent component(&engine, TEST_FILE("qobject.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::qobject_qmltype() { QmlType *t = QmlMetaType::qmlType("Qt/QtObject", 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } struct QObjectFakeData { char data[sizeof(QObjectPrivate)]; }; struct QObjectFake { QObjectFake(); virtual ~QObjectFake(); private: QObjectFakeData *d; }; QObjectFake::QObjectFake() { d = new QObjectFakeData; } QObjectFake::~QObjectFake() { delete d; } void tst_creation::qobject_alloc() { QBENCHMARK { QObjectFake *obj = new QObjectFake; delete obj; } } void tst_creation::objects_qmltype_data() { QTest::addColumn<QByteArray>("type"); QList<QByteArray> types = QmlMetaType::qmlTypeNames(); foreach (QByteArray type, types) QTest::newRow(type.constData()) << type; } void tst_creation::objects_qmltype() { QFETCH(QByteArray, type); QmlType *t = QmlMetaType::qmlType(type, 4, 6); QBENCHMARK { QObject *obj = t->create(); delete obj; } } class QGraphicsItemDummy : public QGraphicsItem { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; class QGraphicsObjectDummy : public QGraphicsObject { public: virtual QRectF boundingRect() const { return QRectF(); } virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} }; void tst_creation::qgraphicsitem() { QBENCHMARK { QGraphicsItemDummy *i = new QGraphicsItemDummy(); delete i; } } void tst_creation::qgraphicsobject() { QBENCHMARK { QGraphicsObjectDummy *i = new QGraphicsObjectDummy(); delete i; } } void tst_creation::qgraphicsitem14() { QBENCHMARK { QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); delete i1; delete i2; delete i3; delete i4; delete i5; delete i6; delete i7; delete i8; delete i9; delete i10; delete i11; delete i12; delete i13; delete i14; } } void tst_creation::qgraphicsitem_tree14() { QBENCHMARK { // i1 // +-------------------------+ // i2 i3 // +-----------+ +-----+-----+ // i4 i5 i6 i7 // +----+ +--+ +--+--+ +----+ // i8 i9 i10 i11 i12 i13 i14 QGraphicsItemDummy *i1 = new QGraphicsItemDummy(); QGraphicsItemDummy *i2 = new QGraphicsItemDummy(); QGraphicsItemDummy *i3 = new QGraphicsItemDummy(); QGraphicsItemDummy *i4 = new QGraphicsItemDummy(); QGraphicsItemDummy *i5 = new QGraphicsItemDummy(); QGraphicsItemDummy *i6 = new QGraphicsItemDummy(); QGraphicsItemDummy *i7 = new QGraphicsItemDummy(); QGraphicsItemDummy *i8 = new QGraphicsItemDummy(); QGraphicsItemDummy *i9 = new QGraphicsItemDummy(); QGraphicsItemDummy *i10 = new QGraphicsItemDummy(); QGraphicsItemDummy *i11 = new QGraphicsItemDummy(); QGraphicsItemDummy *i12 = new QGraphicsItemDummy(); QGraphicsItemDummy *i13 = new QGraphicsItemDummy(); QGraphicsItemDummy *i14 = new QGraphicsItemDummy(); i14->setParentItem(i7); i13->setParentItem(i7); i12->setParentItem(i6); i11->setParentItem(i6); i10->setParentItem(i5); i9->setParentItem(i4); i8->setParentItem(i4); i7->setParentItem(i3); i6->setParentItem(i3); i5->setParentItem(i2); i4->setParentItem(i2); i3->setParentItem(i1); i2->setParentItem(i1); delete i1; } } struct QmlGraphics_DerivedObject : public QObject { void setParent_noEvent(QObject *parent) { bool sce = d_ptr->sendChildEvents; d_ptr->sendChildEvents = false; setParent(parent); d_ptr->sendChildEvents = sce; } }; inline void QmlGraphics_setParent_noEvent(QObject *object, QObject *parent) { static_cast<QmlGraphics_DerivedObject *>(object)->setParent_noEvent(parent); } void tst_creation::itemtree_notree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; } delete item; } } void tst_creation::itemtree_objtree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); } delete item; } } void tst_creation::itemtree_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); child->setParentItem(item); } delete item; } } void tst_creation::itemtree_data_cpp() { QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); item->data()->append(child); } delete item; } } void tst_creation::itemtree_qml() { QmlComponent component(&engine, TEST_FILE("item.qml")); QObject *obj = component.create(); delete obj; QBENCHMARK { QObject *obj = component.create(); delete obj; } } void tst_creation::itemtree_scene_cpp() { QGraphicsScene scene; QmlGraphicsItem *root = new QmlGraphicsItem; scene.addItem(root); QBENCHMARK { QmlGraphicsItem *item = new QmlGraphicsItem; for (int i = 0; i < 30; ++i) { QmlGraphicsItem *child = new QmlGraphicsItem; QmlGraphics_setParent_noEvent(child,item); child->setParentItem(item); } item->setParentItem(root); delete item; } delete root; } QTEST_MAIN(tst_creation) #include "tst_creation.moc" <|endoftext|>
<commit_before>// Copyright (c) 2006- Facebook // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/ #include <sys/socket.h> #include <sys/poll.h> #include <sys/types.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include "TSocket.h" #include "TServerSocket.h" #include <boost/shared_ptr.hpp> namespace facebook { namespace thrift { namespace transport { using namespace std; using boost::shared_ptr; TServerSocket::TServerSocket(int port) : port_(port), serverSocket_(-1), acceptBacklog_(1024), sendTimeout_(0), recvTimeout_(0), retryLimit_(0), retryDelay_(0), tcpSendBuffer_(0), tcpRecvBuffer_(0), intSock1_(-1), intSock2_(-1) {} TServerSocket::TServerSocket(int port, int sendTimeout, int recvTimeout) : port_(port), serverSocket_(-1), acceptBacklog_(1024), sendTimeout_(sendTimeout), recvTimeout_(recvTimeout), retryLimit_(0), retryDelay_(0), tcpSendBuffer_(0), tcpRecvBuffer_(0), intSock1_(-1), intSock2_(-1) {} TServerSocket::~TServerSocket() { close(); } void TServerSocket::setSendTimeout(int sendTimeout) { sendTimeout_ = sendTimeout; } void TServerSocket::setRecvTimeout(int recvTimeout) { recvTimeout_ = recvTimeout; } void TServerSocket::setRetryLimit(int retryLimit) { retryLimit_ = retryLimit; } void TServerSocket::setRetryDelay(int retryDelay) { retryDelay_ = retryDelay; } void TServerSocket::setTcpSendBuffer(int tcpSendBuffer) { tcpSendBuffer_ = tcpSendBuffer; } void TServerSocket::setTcpRecvBuffer(int tcpRecvBuffer) { tcpRecvBuffer_ = tcpRecvBuffer; } void TServerSocket::listen() { int sv[2]; if (-1 == socketpair(AF_LOCAL, SOCK_STREAM, 0, sv)) { int errno_copy = errno; string errStr = "TServerSocket::listen() socketpair() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); intSock1_ = -1; intSock2_ = -1; } else { intSock1_ = sv[1]; intSock2_ = sv[0]; } struct addrinfo hints, *res, *res0; int error; char port[sizeof("65536") + 1]; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; sprintf(port, "%d", port_); // Wildcard address error = getaddrinfo(NULL, port, &hints, &res0); if (error) { fprintf(stderr, "getaddrinfo %d: %s\n", error, gai_strerror(error)); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for server socket."); } // Pick the ipv6 address first since ipv4 addresses can be mapped // into ipv6 space. for (res = res0; res; res = res->ai_next) { if (res->ai_family == AF_INET6 || res->ai_next == NULL) break; } serverSocket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (serverSocket_ == -1) { int errno_copy = errno; string errStr = "TServerSocket::listen() socket() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not create server socket.", errno_copy); } // Set reusaddress to prevent 2MSL delay on accept int one = 1; if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_REUSEADDR " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_REUSEADDR", errno_copy); } // Set TCP buffer sizes if (tcpSendBuffer_ > 0) { if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_SNDBUF, &tcpSendBuffer_, sizeof(tcpSendBuffer_))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_SNDBUF " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_SNDBUF", errno_copy); } } if (tcpRecvBuffer_ > 0) { if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_RCVBUF, &tcpRecvBuffer_, sizeof(tcpRecvBuffer_))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_RCVBUF " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_RCVBUF", errno_copy); } } // Defer accept #ifdef TCP_DEFER_ACCEPT if (-1 == setsockopt(serverSocket_, SOL_SOCKET, TCP_DEFER_ACCEPT, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() TCP_DEFER_ACCEPT " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_DEFER_ACCEPT", errno_copy); } #endif // #ifdef TCP_DEFER_ACCEPT // Turn linger off, don't want to block on calls to close struct linger ling = {0, 0}; if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_LINGER " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_LINGER", errno_copy); } // TCP Nodelay, speed over bandwidth if (-1 == setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() TCP_NODELAY " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_NODELAY", errno_copy); } // Set NONBLOCK on the accept socket int flags = fcntl(serverSocket_, F_GETFL, 0); if (flags == -1) { int errno_copy = errno; string errStr = "TServerSocket::listen() fcntl() F_GETFL " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy); } if (-1 == fcntl(serverSocket_, F_SETFL, flags | O_NONBLOCK)) { int errno_copy = errno; string errStr = "TServerSocket::listen() fcntl() O_NONBLOCK " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy); } // prepare the port information // we may want to try to bind more than once, since SO_REUSEADDR doesn't // always seem to work. The client can configure the retry variables. int retries = 0; do { if (0 == bind(serverSocket_, res->ai_addr, res->ai_addrlen)) { break; } // use short circuit evaluation here to only sleep if we need to } while ((retries++ < retryLimit_) && (sleep(retryDelay_) == 0)); // free addrinfo freeaddrinfo(res0); // throw an error if we failed to bind properly if (retries > retryLimit_) { char errbuf[1024]; sprintf(errbuf, "TServerSocket::listen() BIND %d", port_); GlobalOutput(errbuf); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not bind"); } // Call listen if (-1 == ::listen(serverSocket_, acceptBacklog_)) { int errno_copy = errno; string errStr = "TServerSocket::listen() listen() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not listen", errno_copy); } // The socket is now listening! } shared_ptr<TTransport> TServerSocket::acceptImpl() { if (serverSocket_ < 0) { throw TTransportException(TTransportException::NOT_OPEN, "TServerSocket not listening"); } struct pollfd fds[2]; int maxEintrs = 5; int numEintrs = 0; while (true) { memset(fds, 0 , sizeof(fds)); fds[0].fd = serverSocket_; fds[0].events = POLLIN; if (intSock2_ >= 0) { fds[1].fd = intSock2_; fds[1].fd = POLLIN; } int ret = poll(fds, 2, -1); if (ret < 0) { // error cases if (errno == EINTR && (numEintrs++ < maxEintrs)) { // EINTR needs to be handled manually and we can tolerate // a certain number continue; } int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() poll() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy); } else if (ret > 0) { // Check for an interrupt signal if (intSock2_ >= 0 && (fds[1].revents & POLLIN)) { int8_t buf; if (-1 == recv(intSock2_, &buf, sizeof(int8_t), 0)) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() recv() interrupt " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); } throw TTransportException(TTransportException::INTERRUPTED); } // Check for the actual server socket being ready if (fds[0].revents & POLLIN) { break; } } else { GlobalOutput("TServerSocket::acceptImpl() poll 0"); throw TTransportException(TTransportException::UNKNOWN); } } struct sockaddr_storage clientAddress; int size = sizeof(clientAddress); int clientSocket = ::accept(serverSocket_, (struct sockaddr *) &clientAddress, (socklen_t *) &size); if (clientSocket < 0) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() ::accept() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "accept()", errno_copy); } // Make sure client socket is blocking int flags = fcntl(clientSocket, F_GETFL, 0); if (flags == -1) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() fcntl() F_GETFL " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "fcntl(F_GETFL)", errno_copy); } if (-1 == fcntl(clientSocket, F_SETFL, flags & ~O_NONBLOCK)) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() fcntl() F_SETFL ~O_NONBLOCK " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "fcntl(F_SETFL)", errno_copy); } shared_ptr<TSocket> client(new TSocket(clientSocket)); if (sendTimeout_ > 0) { client->setSendTimeout(sendTimeout_); } if (recvTimeout_ > 0) { client->setRecvTimeout(recvTimeout_); } return client; } void TServerSocket::interrupt() { if (intSock1_ >= 0) { int8_t byte = 0; if (-1 == send(intSock1_, &byte, sizeof(int8_t), 0)) { int errno_copy = errno; string errStr = "TServerSocket::interrupt() send() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); } } } void TServerSocket::close() { if (serverSocket_ >= 0) { shutdown(serverSocket_, SHUT_RDWR); ::close(serverSocket_); } if (intSock1_ >= 0) { ::close(intSock1_); } if (intSock2_ >= 0) { ::close(intSock2_); } serverSocket_ = -1; intSock1_ = -1; intSock2_ = -1; } }}} // facebook::thrift::transport <commit_msg>Thrift: bug fix for interrupting server socket<commit_after>// Copyright (c) 2006- Facebook // Distributed under the Thrift Software License // // See accompanying file LICENSE or visit the Thrift site at: // http://developers.facebook.com/thrift/ #include <sys/socket.h> #include <sys/poll.h> #include <sys/types.h> #include <netinet/in.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #include <errno.h> #include "TSocket.h" #include "TServerSocket.h" #include <boost/shared_ptr.hpp> namespace facebook { namespace thrift { namespace transport { using namespace std; using boost::shared_ptr; TServerSocket::TServerSocket(int port) : port_(port), serverSocket_(-1), acceptBacklog_(1024), sendTimeout_(0), recvTimeout_(0), retryLimit_(0), retryDelay_(0), tcpSendBuffer_(0), tcpRecvBuffer_(0), intSock1_(-1), intSock2_(-1) {} TServerSocket::TServerSocket(int port, int sendTimeout, int recvTimeout) : port_(port), serverSocket_(-1), acceptBacklog_(1024), sendTimeout_(sendTimeout), recvTimeout_(recvTimeout), retryLimit_(0), retryDelay_(0), tcpSendBuffer_(0), tcpRecvBuffer_(0), intSock1_(-1), intSock2_(-1) {} TServerSocket::~TServerSocket() { close(); } void TServerSocket::setSendTimeout(int sendTimeout) { sendTimeout_ = sendTimeout; } void TServerSocket::setRecvTimeout(int recvTimeout) { recvTimeout_ = recvTimeout; } void TServerSocket::setRetryLimit(int retryLimit) { retryLimit_ = retryLimit; } void TServerSocket::setRetryDelay(int retryDelay) { retryDelay_ = retryDelay; } void TServerSocket::setTcpSendBuffer(int tcpSendBuffer) { tcpSendBuffer_ = tcpSendBuffer; } void TServerSocket::setTcpRecvBuffer(int tcpRecvBuffer) { tcpRecvBuffer_ = tcpRecvBuffer; } void TServerSocket::listen() { int sv[2]; if (-1 == socketpair(AF_LOCAL, SOCK_STREAM, 0, sv)) { int errno_copy = errno; string errStr = "TServerSocket::listen() socketpair() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); intSock1_ = -1; intSock2_ = -1; } else { intSock1_ = sv[1]; intSock2_ = sv[0]; } struct addrinfo hints, *res, *res0; int error; char port[sizeof("65536") + 1]; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_ADDRCONFIG; sprintf(port, "%d", port_); // Wildcard address error = getaddrinfo(NULL, port, &hints, &res0); if (error) { fprintf(stderr, "getaddrinfo %d: %s\n", error, gai_strerror(error)); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not resolve host for server socket."); } // Pick the ipv6 address first since ipv4 addresses can be mapped // into ipv6 space. for (res = res0; res; res = res->ai_next) { if (res->ai_family == AF_INET6 || res->ai_next == NULL) break; } serverSocket_ = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if (serverSocket_ == -1) { int errno_copy = errno; string errStr = "TServerSocket::listen() socket() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not create server socket.", errno_copy); } // Set reusaddress to prevent 2MSL delay on accept int one = 1; if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_REUSEADDR " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_REUSEADDR", errno_copy); } // Set TCP buffer sizes if (tcpSendBuffer_ > 0) { if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_SNDBUF, &tcpSendBuffer_, sizeof(tcpSendBuffer_))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_SNDBUF " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_SNDBUF", errno_copy); } } if (tcpRecvBuffer_ > 0) { if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_RCVBUF, &tcpRecvBuffer_, sizeof(tcpRecvBuffer_))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_RCVBUF " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_RCVBUF", errno_copy); } } // Defer accept #ifdef TCP_DEFER_ACCEPT if (-1 == setsockopt(serverSocket_, SOL_SOCKET, TCP_DEFER_ACCEPT, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() TCP_DEFER_ACCEPT " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_DEFER_ACCEPT", errno_copy); } #endif // #ifdef TCP_DEFER_ACCEPT // Turn linger off, don't want to block on calls to close struct linger ling = {0, 0}; if (-1 == setsockopt(serverSocket_, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() SO_LINGER " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set SO_LINGER", errno_copy); } // TCP Nodelay, speed over bandwidth if (-1 == setsockopt(serverSocket_, IPPROTO_TCP, TCP_NODELAY, &one, sizeof(one))) { int errno_copy = errno; string errStr = "TServerSocket::listen() setsockopt() TCP_NODELAY " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not set TCP_NODELAY", errno_copy); } // Set NONBLOCK on the accept socket int flags = fcntl(serverSocket_, F_GETFL, 0); if (flags == -1) { int errno_copy = errno; string errStr = "TServerSocket::listen() fcntl() F_GETFL " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy); } if (-1 == fcntl(serverSocket_, F_SETFL, flags | O_NONBLOCK)) { int errno_copy = errno; string errStr = "TServerSocket::listen() fcntl() O_NONBLOCK " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::NOT_OPEN, "fcntl() failed", errno_copy); } // prepare the port information // we may want to try to bind more than once, since SO_REUSEADDR doesn't // always seem to work. The client can configure the retry variables. int retries = 0; do { if (0 == bind(serverSocket_, res->ai_addr, res->ai_addrlen)) { break; } // use short circuit evaluation here to only sleep if we need to } while ((retries++ < retryLimit_) && (sleep(retryDelay_) == 0)); // free addrinfo freeaddrinfo(res0); // throw an error if we failed to bind properly if (retries > retryLimit_) { char errbuf[1024]; sprintf(errbuf, "TServerSocket::listen() BIND %d", port_); GlobalOutput(errbuf); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not bind"); } // Call listen if (-1 == ::listen(serverSocket_, acceptBacklog_)) { int errno_copy = errno; string errStr = "TServerSocket::listen() listen() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); close(); throw TTransportException(TTransportException::NOT_OPEN, "Could not listen", errno_copy); } // The socket is now listening! } shared_ptr<TTransport> TServerSocket::acceptImpl() { if (serverSocket_ < 0) { throw TTransportException(TTransportException::NOT_OPEN, "TServerSocket not listening"); } struct pollfd fds[2]; int maxEintrs = 5; int numEintrs = 0; while (true) { memset(fds, 0 , sizeof(fds)); fds[0].fd = serverSocket_; fds[0].events = POLLIN; if (intSock2_ >= 0) { fds[1].fd = intSock2_; fds[1].events = POLLIN; } int ret = poll(fds, 2, -1); if (ret < 0) { // error cases if (errno == EINTR && (numEintrs++ < maxEintrs)) { // EINTR needs to be handled manually and we can tolerate // a certain number continue; } int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() poll() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "Unknown", errno_copy); } else if (ret > 0) { // Check for an interrupt signal if (intSock2_ >= 0 && (fds[1].revents & POLLIN)) { int8_t buf; if (-1 == recv(intSock2_, &buf, sizeof(int8_t), 0)) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() recv() interrupt " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); } throw TTransportException(TTransportException::INTERRUPTED); } // Check for the actual server socket being ready if (fds[0].revents & POLLIN) { break; } } else { GlobalOutput("TServerSocket::acceptImpl() poll 0"); throw TTransportException(TTransportException::UNKNOWN); } } struct sockaddr_storage clientAddress; int size = sizeof(clientAddress); int clientSocket = ::accept(serverSocket_, (struct sockaddr *) &clientAddress, (socklen_t *) &size); if (clientSocket < 0) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() ::accept() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "accept()", errno_copy); } // Make sure client socket is blocking int flags = fcntl(clientSocket, F_GETFL, 0); if (flags == -1) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() fcntl() F_GETFL " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "fcntl(F_GETFL)", errno_copy); } if (-1 == fcntl(clientSocket, F_SETFL, flags & ~O_NONBLOCK)) { int errno_copy = errno; string errStr = "TServerSocket::acceptImpl() fcntl() F_SETFL ~O_NONBLOCK " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); throw TTransportException(TTransportException::UNKNOWN, "fcntl(F_SETFL)", errno_copy); } shared_ptr<TSocket> client(new TSocket(clientSocket)); if (sendTimeout_ > 0) { client->setSendTimeout(sendTimeout_); } if (recvTimeout_ > 0) { client->setRecvTimeout(recvTimeout_); } return client; } void TServerSocket::interrupt() { if (intSock1_ >= 0) { int8_t byte = 0; if (-1 == send(intSock1_, &byte, sizeof(int8_t), 0)) { int errno_copy = errno; string errStr = "TServerSocket::interrupt() send() " + TOutput::strerror_s(errno_copy); GlobalOutput(errStr.c_str()); } } } void TServerSocket::close() { if (serverSocket_ >= 0) { shutdown(serverSocket_, SHUT_RDWR); ::close(serverSocket_); } if (intSock1_ >= 0) { ::close(intSock1_); } if (intSock2_ >= 0) { ::close(intSock2_); } serverSocket_ = -1; intSock1_ = -1; intSock2_ = -1; } }}} // facebook::thrift::transport <|endoftext|>
<commit_before>#include "MatrixUtils.h" #include <numeric> #include <set> #include <vector> #include <iterator> #include <unsupported/Eigen/SparseExtra> #include <SmurffCpp/Utils/Error.h> Eigen::MatrixXd smurff::matrix_utils::dense_to_eigen(const smurff::MatrixConfig& matrixConfig) { if(!matrixConfig.isDense()) { THROWERROR("matrix config should be dense"); } return Eigen::Map<const Eigen::MatrixXd>(matrixConfig.getValues().data(), matrixConfig.getNRow(), matrixConfig.getNCol()); } std::shared_ptr<smurff::MatrixConfig> smurff::matrix_utils::eigen_to_dense(const Eigen::MatrixXd &eigenMatrix, NoiseConfig n) { std::vector<double> values(eigenMatrix.data(), eigenMatrix.data() + eigenMatrix.size()); return std::make_shared<smurff::MatrixConfig>(eigenMatrix.rows(), eigenMatrix.cols(), values, n); } struct sparse_vec_iterator { sparse_vec_iterator(const smurff::MatrixConfig& matrixConfig, int pos) : config(matrixConfig), pos(pos) {} const smurff::MatrixConfig& config; int pos; bool operator!=(const sparse_vec_iterator &other) const { THROWERROR_ASSERT(&config == &other.config); return pos != other.pos; } sparse_vec_iterator &operator++() { pos++; return *this; } typedef Eigen::Triplet<double> T; T v; T* operator->() { // also convert from 1-base to 0-base uint32_t row = config.getRows()[pos]; uint32_t col = config.getCols()[pos]; double val = config.getValues()[pos]; v = T(row, col, val); return &v; } }; Eigen::SparseMatrix<double> smurff::matrix_utils::sparse_to_eigen(const smurff::MatrixConfig& matrixConfig) { if(matrixConfig.isDense()) { THROWERROR("matrix config should be sparse"); } Eigen::SparseMatrix<double> out(matrixConfig.getNRow(), matrixConfig.getNCol()); sparse_vec_iterator begin(matrixConfig, 0); sparse_vec_iterator end(matrixConfig, matrixConfig.getNNZ()); out.setFromTriplets(begin, end); THROWERROR_ASSERT_MSG(out.nonZeros() == (int)matrixConfig.getNNZ(), "probable presence of duplicate records in " + matrixConfig.getFilename()); return out; } std::shared_ptr<smurff::MatrixConfig> smurff::matrix_utils::eigen_to_sparse(const Eigen::SparseMatrix<double> &X, NoiseConfig n, bool isScarce) { std::uint64_t nrow = X.rows(); std::uint64_t ncol = X.cols(); std::vector<uint32_t> rows; std::vector<uint32_t> cols; std::vector<double> values; for (int k = 0; k < X.outerSize(); ++k) { for (Eigen::SparseMatrix<double>::InnerIterator it(X,k); it; ++it) { rows.push_back(it.row()); cols.push_back(it.col()); values.push_back(it.value()); } } std::uint64_t nnz = values.size(); return std::make_shared<smurff::MatrixConfig>(nrow, ncol, rows, cols, values, n, isScarce); } std::ostream& smurff::matrix_utils::operator << (std::ostream& os, const MatrixConfig& mc) { const std::vector<std::uint32_t>& rows = mc.getRows(); const std::vector<std::uint32_t>& cols = mc.getCols(); const std::vector<double>& values = mc.getValues(); const std::vector<std::uint32_t>& columns = mc.getColumns(); if(rows.size() != cols.size() || rows.size() != values.size()) { THROWERROR("Invalid sizes"); } os << "rows: " << std::endl; for(std::uint64_t i = 0; i < rows.size(); i++) os << rows[i] << ", "; os << std::endl; os << "cols: " << std::endl; for(std::uint64_t i = 0; i < cols.size(); i++) os << cols[i] << ", "; os << std::endl; os << "columns: " << std::endl; for(std::uint64_t i = 0; i < columns.size(); i++) os << columns[i] << ", "; os << std::endl; os << "values: " << std::endl; for(std::uint64_t i = 0; i < values.size(); i++) os << values[i] << ", "; os << std::endl; os << "NRow: " << mc.getNRow() << " NCol: " << mc.getNCol() << std::endl; Eigen::SparseMatrix<double> X(mc.getNRow(), mc.getNCol()); std::vector<Eigen::Triplet<double> > triplets; for(std::uint64_t i = 0; i < mc.getNNZ(); i++) triplets.push_back(Eigen::Triplet<double>(rows[i], cols[i], values[i])); os << "NTriplets: " << triplets.size() << std::endl; X.setFromTriplets(triplets.begin(), triplets.end()); os << X << std::endl; return os; } bool smurff::matrix_utils::equals(const Eigen::MatrixXd& m1, const Eigen::MatrixXd& m2, double precision) { if (m1.rows() != m2.rows() || m1.cols() != m2.cols()) return false; for (Eigen::Index i = 0; i < m1.rows(); i++) { for (Eigen::Index j = 0; j < m1.cols(); j++) { Eigen::MatrixXd::Scalar m1_v = m1(i, j); Eigen::MatrixXd::Scalar m2_v = m2(i, j); if (std::abs(m1_v - m2_v) > precision) return false; } } return true; } bool smurff::matrix_utils::equals_vector(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2, double precision) { if (v1.size() != v2.size()) return false; for (auto i = 0; i < v1.size(); i++) { if (std::abs(v1(i) - v2(i)) > precision) return false; } return true; } <commit_msg>FIX: unused variable warning<commit_after>#include "MatrixUtils.h" #include <numeric> #include <set> #include <vector> #include <iterator> #include <unsupported/Eigen/SparseExtra> #include <SmurffCpp/Utils/Error.h> Eigen::MatrixXd smurff::matrix_utils::dense_to_eigen(const smurff::MatrixConfig& matrixConfig) { if(!matrixConfig.isDense()) { THROWERROR("matrix config should be dense"); } return Eigen::Map<const Eigen::MatrixXd>(matrixConfig.getValues().data(), matrixConfig.getNRow(), matrixConfig.getNCol()); } std::shared_ptr<smurff::MatrixConfig> smurff::matrix_utils::eigen_to_dense(const Eigen::MatrixXd &eigenMatrix, NoiseConfig n) { std::vector<double> values(eigenMatrix.data(), eigenMatrix.data() + eigenMatrix.size()); return std::make_shared<smurff::MatrixConfig>(eigenMatrix.rows(), eigenMatrix.cols(), values, n); } struct sparse_vec_iterator { sparse_vec_iterator(const smurff::MatrixConfig& matrixConfig, int pos) : config(matrixConfig), pos(pos) {} const smurff::MatrixConfig& config; int pos; bool operator!=(const sparse_vec_iterator &other) const { THROWERROR_ASSERT(&config == &other.config); return pos != other.pos; } sparse_vec_iterator &operator++() { pos++; return *this; } typedef Eigen::Triplet<double> T; T v; T* operator->() { // also convert from 1-base to 0-base uint32_t row = config.getRows()[pos]; uint32_t col = config.getCols()[pos]; double val = config.getValues()[pos]; v = T(row, col, val); return &v; } }; Eigen::SparseMatrix<double> smurff::matrix_utils::sparse_to_eigen(const smurff::MatrixConfig& matrixConfig) { if(matrixConfig.isDense()) { THROWERROR("matrix config should be sparse"); } Eigen::SparseMatrix<double> out(matrixConfig.getNRow(), matrixConfig.getNCol()); sparse_vec_iterator begin(matrixConfig, 0); sparse_vec_iterator end(matrixConfig, matrixConfig.getNNZ()); out.setFromTriplets(begin, end); THROWERROR_ASSERT_MSG(out.nonZeros() == (int)matrixConfig.getNNZ(), "probable presence of duplicate records in " + matrixConfig.getFilename()); return out; } std::shared_ptr<smurff::MatrixConfig> smurff::matrix_utils::eigen_to_sparse(const Eigen::SparseMatrix<double> &X, NoiseConfig n, bool isScarce) { std::uint64_t nrow = X.rows(); std::uint64_t ncol = X.cols(); std::vector<uint32_t> rows; std::vector<uint32_t> cols; std::vector<double> values; for (int k = 0; k < X.outerSize(); ++k) { for (Eigen::SparseMatrix<double>::InnerIterator it(X,k); it; ++it) { rows.push_back(it.row()); cols.push_back(it.col()); values.push_back(it.value()); } } return std::make_shared<smurff::MatrixConfig>(nrow, ncol, rows, cols, values, n, isScarce); } std::ostream& smurff::matrix_utils::operator << (std::ostream& os, const MatrixConfig& mc) { const std::vector<std::uint32_t>& rows = mc.getRows(); const std::vector<std::uint32_t>& cols = mc.getCols(); const std::vector<double>& values = mc.getValues(); const std::vector<std::uint32_t>& columns = mc.getColumns(); if(rows.size() != cols.size() || rows.size() != values.size()) { THROWERROR("Invalid sizes"); } os << "rows: " << std::endl; for(std::uint64_t i = 0; i < rows.size(); i++) os << rows[i] << ", "; os << std::endl; os << "cols: " << std::endl; for(std::uint64_t i = 0; i < cols.size(); i++) os << cols[i] << ", "; os << std::endl; os << "columns: " << std::endl; for(std::uint64_t i = 0; i < columns.size(); i++) os << columns[i] << ", "; os << std::endl; os << "values: " << std::endl; for(std::uint64_t i = 0; i < values.size(); i++) os << values[i] << ", "; os << std::endl; os << "NRow: " << mc.getNRow() << " NCol: " << mc.getNCol() << std::endl; Eigen::SparseMatrix<double> X(mc.getNRow(), mc.getNCol()); std::vector<Eigen::Triplet<double> > triplets; for(std::uint64_t i = 0; i < mc.getNNZ(); i++) triplets.push_back(Eigen::Triplet<double>(rows[i], cols[i], values[i])); os << "NTriplets: " << triplets.size() << std::endl; X.setFromTriplets(triplets.begin(), triplets.end()); os << X << std::endl; return os; } bool smurff::matrix_utils::equals(const Eigen::MatrixXd& m1, const Eigen::MatrixXd& m2, double precision) { if (m1.rows() != m2.rows() || m1.cols() != m2.cols()) return false; for (Eigen::Index i = 0; i < m1.rows(); i++) { for (Eigen::Index j = 0; j < m1.cols(); j++) { Eigen::MatrixXd::Scalar m1_v = m1(i, j); Eigen::MatrixXd::Scalar m2_v = m2(i, j); if (std::abs(m1_v - m2_v) > precision) return false; } } return true; } bool smurff::matrix_utils::equals_vector(const Eigen::VectorXd& v1, const Eigen::VectorXd& v2, double precision) { if (v1.size() != v2.size()) return false; for (auto i = 0; i < v1.size(); i++) { if (std::abs(v1(i) - v2(i)) > precision) return false; } return true; } <|endoftext|>
<commit_before>#include "GlobalResources.h" #include "../ResourceManager.h" #ifdef WIN32 #include "Dx11UmbralEffectProvider.h" #include "athena/win32/Dx11GraphicDevice.h" #elif defined(__APPLE__) #include "IosUmbralEffectProvider.h" #endif CGlobalResources::CGlobalResources() { } CGlobalResources::~CGlobalResources() { } void CGlobalResources::Initialize() { { auto diffuseMapTexture = Athena::CGraphicDevice::GetInstance().CreateCubeTexture(Athena::TEXTURE_FORMAT_RGB888, 32); for(unsigned int i = 0; i < 6; i++) { std::vector<uint8> pixels(32 * 32 * 3, 0xCC + i); diffuseMapTexture->UpdateCubeFace(static_cast<Athena::TEXTURE_CUBE_FACE>(i), pixels.data()); } m_diffuseMapTexture = diffuseMapTexture; } m_skyTexture = Athena::CGraphicDevice::GetInstance().CreateCubeTextureFromFile("./data/global/skybox.dds"); m_proxyShadowTexture = Athena::CGraphicDevice::GetInstance().CreateTexture(Athena::TEXTURE_FORMAT_RGBA8888, 32, 32, 1); #ifdef WIN32 auto& graphicDevice = static_cast<Athena::CDx11GraphicDevice&>(Athena::CGraphicDevice::GetInstance()); m_effectProvider = std::make_shared<CDx11UmbralEffectProvider>(graphicDevice.GetDevice(), graphicDevice.GetDeviceContext()); #elif defined(__APPLE__) m_effectProvider = std::make_shared<CIosUmbralEffectProvider>(); #endif } void CGlobalResources::Release() { m_textures.clear(); m_diffuseMapTexture.reset(); m_skyTexture.reset(); m_proxyShadowTexture.reset(); m_effectProvider.reset(); } Athena::TexturePtr CGlobalResources::GetTexture(const std::string& textureName) { auto textureIterator = m_textures.find(textureName); if(textureIterator != std::end(m_textures)) return textureIterator->second; auto textureResource = CResourceManager::GetInstance().GetResource(textureName); if(!textureResource) return Athena::TexturePtr(); auto textureDataInfo = textureResource->SelectNode<CGtexData>(); assert(textureDataInfo); auto texture = CreateTextureFromGtex(textureDataInfo); m_textures.insert(std::make_pair(textureName, texture)); return texture; } Athena::TexturePtr CGlobalResources::CreateTextureFromGtex(const GtexDataPtr& textureDataInfo) { auto textureFormat = textureDataInfo->GetTextureFormat(); auto textureWidth = textureDataInfo->GetTextureWidth(); auto textureHeight = textureDataInfo->GetTextureHeight(); Athena::TEXTURE_FORMAT specTextureFormat = Athena::TEXTURE_FORMAT_UNKNOWN; switch(textureFormat) { case CGtexData::TEXTURE_FORMAT_DXT1: specTextureFormat = Athena::TEXTURE_FORMAT_DXT1; break; case CGtexData::TEXTURE_FORMAT_DXT3: specTextureFormat = Athena::TEXTURE_FORMAT_DXT3; break; case CGtexData::TEXTURE_FORMAT_DXT5: specTextureFormat = Athena::TEXTURE_FORMAT_DXT5; break; case CGtexData::TEXTURE_FORMAT_A8R8G8B8: case CGtexData::TEXTURE_FORMAT_X8R8G8B8: specTextureFormat = Athena::TEXTURE_FORMAT_RGBA8888; break; default: assert(0); break; } unsigned int mipCount = textureDataInfo->GetMipMapInfos().size(); auto texture = Athena::CGraphicDevice::GetInstance().CreateTexture(specTextureFormat, textureWidth, textureHeight, mipCount); for(unsigned int i = 0; i < mipCount; i++) { const auto mipData = textureDataInfo->GetMipMapData(i); texture->Update(i, mipData); } return texture; } Athena::TexturePtr CGlobalResources::GetDiffuseMapTexture() const { return m_diffuseMapTexture; } Athena::TexturePtr CGlobalResources::GetSkyTexture() const { return m_skyTexture; } Athena::TexturePtr CGlobalResources::GetProxyShadowTexture() const { return m_proxyShadowTexture; } Athena::EffectProviderPtr CGlobalResources::GetEffectProvider() const { return m_effectProvider; } <commit_msg>Load sky cube texture properly in WorldEditor.<commit_after>#include "GlobalResources.h" #include "../ResourceManager.h" #ifdef WIN32 #include "Dx11UmbralEffectProvider.h" #include "athena/win32/Dx11GraphicDevice.h" #elif defined(__APPLE__) #include "IosUmbralEffectProvider.h" #endif CGlobalResources::CGlobalResources() { } CGlobalResources::~CGlobalResources() { } void CGlobalResources::Initialize() { { auto diffuseMapTexture = Athena::CGraphicDevice::GetInstance().CreateCubeTexture(Athena::TEXTURE_FORMAT_RGB888, 32); for(unsigned int i = 0; i < 6; i++) { std::vector<uint8> pixels(32 * 32 * 3, 0xCC + i); diffuseMapTexture->UpdateCubeFace(static_cast<Athena::TEXTURE_CUBE_FACE>(i), pixels.data()); } m_diffuseMapTexture = diffuseMapTexture; } auto skyTexturePath = Athena::CResourceManager::GetInstance().MakeResourcePath("global/skybox.dds"); m_skyTexture = Athena::CTextureLoader::CreateCubeTextureFromFile(skyTexturePath); m_proxyShadowTexture = Athena::CGraphicDevice::GetInstance().CreateTexture(Athena::TEXTURE_FORMAT_RGBA8888, 32, 32, 1); #ifdef WIN32 auto& graphicDevice = static_cast<Athena::CDx11GraphicDevice&>(Athena::CGraphicDevice::GetInstance()); m_effectProvider = std::make_shared<CDx11UmbralEffectProvider>(graphicDevice.GetDevice(), graphicDevice.GetDeviceContext()); #elif defined(__APPLE__) m_effectProvider = std::make_shared<CIosUmbralEffectProvider>(); #endif } void CGlobalResources::Release() { m_textures.clear(); m_diffuseMapTexture.reset(); m_skyTexture.reset(); m_proxyShadowTexture.reset(); m_effectProvider.reset(); } Athena::TexturePtr CGlobalResources::GetTexture(const std::string& textureName) { auto textureIterator = m_textures.find(textureName); if(textureIterator != std::end(m_textures)) return textureIterator->second; auto textureResource = CResourceManager::GetInstance().GetResource(textureName); if(!textureResource) return Athena::TexturePtr(); auto textureDataInfo = textureResource->SelectNode<CGtexData>(); assert(textureDataInfo); auto texture = CreateTextureFromGtex(textureDataInfo); m_textures.insert(std::make_pair(textureName, texture)); return texture; } Athena::TexturePtr CGlobalResources::CreateTextureFromGtex(const GtexDataPtr& textureDataInfo) { auto textureFormat = textureDataInfo->GetTextureFormat(); auto textureWidth = textureDataInfo->GetTextureWidth(); auto textureHeight = textureDataInfo->GetTextureHeight(); Athena::TEXTURE_FORMAT specTextureFormat = Athena::TEXTURE_FORMAT_UNKNOWN; switch(textureFormat) { case CGtexData::TEXTURE_FORMAT_DXT1: specTextureFormat = Athena::TEXTURE_FORMAT_DXT1; break; case CGtexData::TEXTURE_FORMAT_DXT3: specTextureFormat = Athena::TEXTURE_FORMAT_DXT3; break; case CGtexData::TEXTURE_FORMAT_DXT5: specTextureFormat = Athena::TEXTURE_FORMAT_DXT5; break; case CGtexData::TEXTURE_FORMAT_A8R8G8B8: case CGtexData::TEXTURE_FORMAT_X8R8G8B8: specTextureFormat = Athena::TEXTURE_FORMAT_RGBA8888; break; default: assert(0); break; } unsigned int mipCount = textureDataInfo->GetMipMapInfos().size(); auto texture = Athena::CGraphicDevice::GetInstance().CreateTexture(specTextureFormat, textureWidth, textureHeight, mipCount); for(unsigned int i = 0; i < mipCount; i++) { const auto mipData = textureDataInfo->GetMipMapData(i); texture->Update(i, mipData); } return texture; } Athena::TexturePtr CGlobalResources::GetDiffuseMapTexture() const { return m_diffuseMapTexture; } Athena::TexturePtr CGlobalResources::GetSkyTexture() const { return m_skyTexture; } Athena::TexturePtr CGlobalResources::GetProxyShadowTexture() const { return m_proxyShadowTexture; } Athena::EffectProviderPtr CGlobalResources::GetEffectProvider() const { return m_effectProvider; } <|endoftext|>
<commit_before> /* * Copyright 1999-2000,2004-2005 The Apache Software Foundation. * * 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. */ /* * $Id$ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/AtomicOpManagers/MacOSAtomicOpMgr.hpp> #include <Carbon/Carbon.h> XERCES_CPP_NAMESPACE_BEGIN MacOSAtomicOpMgr::MacOSAtomicOpMgr() { } MacOSAtomicOpMgr::~MacOSAtomicOpMgr() { } // Atomic operations void* MacOSAtomicOpMgr::compareAndSwap(void** toFill , const void* const newValue , const void* const toCompare) { // Replace *toFill with newValue iff *toFill == toCompare, // returning previous value of *toFill Boolean success = CompareAndSwap( reinterpret_cast<UInt32>(toCompare), reinterpret_cast<UInt32>(newValue), reinterpret_cast<UInt32*>(toFill)); return (success) ? const_cast<void*>(toCompare) : *toFill; } // // Atomic Increment and Decrement // // Apple's routines return the value as it was before the // operation, while these routines want to return it as it // is after. So we perform the translation before returning // the value. // int MacOSAtomicOpMgr::increment(int &location) { return IncrementAtomic(reinterpret_cast<long*>(&location)) + 1; } int MacOSAtomicOpMgr::decrement(int &location) { return DecrementAtomic(reinterpret_cast<long*>(&location)) - 1; } XERCES_CPP_NAMESPACE_END <commit_msg>Include CoreServices framework, not Carbon framework<commit_after> /* * Copyright 1999-2000,2004-2005 The Apache Software Foundation. * * 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. */ /* * $Id$ */ #include <xercesc/util/XercesDefs.hpp> #include <xercesc/util/AtomicOpManagers/MacOSAtomicOpMgr.hpp> #include <CoreServices/CoreServices.h> XERCES_CPP_NAMESPACE_BEGIN MacOSAtomicOpMgr::MacOSAtomicOpMgr() { } MacOSAtomicOpMgr::~MacOSAtomicOpMgr() { } // Atomic operations void* MacOSAtomicOpMgr::compareAndSwap(void** toFill , const void* const newValue , const void* const toCompare) { // Replace *toFill with newValue iff *toFill == toCompare, // returning previous value of *toFill Boolean success = CompareAndSwap( reinterpret_cast<UInt32>(toCompare), reinterpret_cast<UInt32>(newValue), reinterpret_cast<UInt32*>(toFill)); return (success) ? const_cast<void*>(toCompare) : *toFill; } // // Atomic Increment and Decrement // // Apple's routines return the value as it was before the // operation, while these routines want to return it as it // is after. So we perform the translation before returning // the value. // int MacOSAtomicOpMgr::increment(int &location) { return IncrementAtomic(reinterpret_cast<long*>(&location)) + 1; } int MacOSAtomicOpMgr::decrement(int &location) { return DecrementAtomic(reinterpret_cast<long*>(&location)) - 1; } XERCES_CPP_NAMESPACE_END <|endoftext|>
<commit_before>#include "connections/LineConnector.h" #include <QBrush> #include <QGraphicsWidget> #include <QPainter> #include <QPen> namespace i6engine { namespace particleEditor { namespace connections { LineConnector::LineConnector(QGraphicsWidget * first, QGraphicsWidget * second, QColor colour, Qt::PenStyle lineStyle) : _first(first), _second(second), _colour(colour), _lineStyle(lineStyle) { } void LineConnector::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { static int xOffsetMin = 24; QPen pen(QBrush(_colour), _lineStyle); pen.setWidth(2); painter->setPen(pen); QPoint points[4]; int x1 = _first->pos().x(); int y1 = _first->pos().y(); int x2 = _second->pos().x(); int y2 = _second->pos().y(); int width1 = _first->size().width(); int height1 = _first->size().height(); int width2 = _second->size().width(); int height2 = _second->size().height(); int x3, y3; int x4, y4; y1 = y1 + 0.5 * height1; y2 = y2 + 0.5 * height2; y3 = y1; y4 = y2; // Determine widest rectangle if (width2 > width1) { // Swap x1 += x2; // = x1 + x2 x2 = x1 - x2; // = x1 + x2 - x2 = x1 x1 -= x2; // = x1 + x2 - x1 = x2 y1 += y2; y2 = y1 - y2; y1 -= y2; y3 += y4; y4 = y3 - y4; y3 -= y4; width1 += width2; width2 = width1 - width2; width1 -= width2; height1 += height2; height2 = height1 - height2; height1 -= height2; } // Calculate the 4 control points int xOffset = 0.25 * std::abs(x1 - x2); xOffset = std::max(xOffset, xOffsetMin); if (x1 + width1 > x2 + width2) { x3 = x1 - xOffset; x4 = x2 - xOffset; if (x1 > x2 + width2) { x2 += width2; x4 = x2 + xOffset; } } else { x1 += width1; x3 = x1 + xOffset; x4 = x2 - xOffset; if (x1 > x2) { x2 += width2; x4 = x2 + xOffset; } } points[0] = QPoint(x1, y1); points[1] = QPoint(x3, y3); points[2] = QPoint(x4, y4); points[3] = QPoint(x2, y2); painter->drawPolyline(points, 4); } QRectF LineConnector::boundingRect() const { return QRectF(); } } /* namespace connections */ } /* namespace particleEditor */ } /* namespace i6engine */ <commit_msg>ISIXE-1728 fixed lines of LineConnector sometimes not visible and changed them to bezier curves instead of simple lines<commit_after>#include "connections/LineConnector.h" #include <QBrush> #include <QGraphicsWidget> #include <QPainter> #include <QPen> namespace i6engine { namespace particleEditor { namespace connections { LineConnector::LineConnector(QGraphicsWidget * first, QGraphicsWidget * second, QColor colour, Qt::PenStyle lineStyle) : _first(first), _second(second), _colour(colour), _lineStyle(lineStyle) { } void LineConnector::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) { static int xOffsetMin = 24; QPen pen(QBrush(_colour), _lineStyle); pen.setWidth(2); painter->setPen(pen); QPoint points[4]; int x1 = _first->pos().x(); int y1 = _first->pos().y(); int x2 = _second->pos().x(); int y2 = _second->pos().y(); int width1 = _first->size().width(); int height1 = _first->size().height(); int width2 = _second->size().width(); int height2 = _second->size().height(); int x3, y3; int x4, y4; y1 = y1 + 0.5 * height1; y2 = y2 + 0.5 * height2; y3 = y1; y4 = y2; // Determine widest rectangle if (width2 > width1) { // Swap x1 += x2; // = x1 + x2 x2 = x1 - x2; // = x1 + x2 - x2 = x1 x1 -= x2; // = x1 + x2 - x1 = x2 y1 += y2; y2 = y1 - y2; y1 -= y2; y3 += y4; y4 = y3 - y4; y3 -= y4; width1 += width2; width2 = width1 - width2; width1 -= width2; height1 += height2; height2 = height1 - height2; height1 -= height2; } // Calculate the 4 control points int xOffset = 0.25 * std::abs(x1 - x2); xOffset = std::max(xOffset, xOffsetMin); if (x1 + width1 > x2 + width2) { x3 = x1 - xOffset; x4 = x2 - xOffset; if (x1 > x2 + width2) { x2 += width2; x4 = x2 + xOffset; } } else { x1 += width1; x3 = x1 + xOffset; x4 = x2 - xOffset; if (x1 > x2) { x2 += width2; x4 = x2 + xOffset; } } QPainterPath path(QPoint(x1, y1)); path.cubicTo(QPoint(x3, y3), QPoint(x4, y4), QPoint(x2, y2)); painter->drawPath(path); } QRectF LineConnector::boundingRect() const { return QRectF(); } } /* namespace connections */ } /* namespace particleEditor */ } /* namespace i6engine */ <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: FilterConfigCache.hxx,v $ * * $Revision: 1.14 $ * * last change: $Author: obo $ $Date: 2005-04-13 10:59:40 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _FILTER_CONFIG_CACHE_HXX_ #define _FILTER_CONFIG_CACHE_HXX_ #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef INCLUDED_VECTOR #include <vector> #define INCLUDED_VECTOR #endif class SVT_DLLPUBLIC FilterConfigCache { struct FilterConfigCacheEntry { ::rtl::OUString sInternalFilterName; ::rtl::OUString sType; ::com::sun::star::uno::Sequence< ::rtl::OUString > lExtensionList; ::rtl::OUString sUIName; ::rtl::OUString sDocumentService; ::rtl::OUString sFilterService; ::rtl::OUString sTemplateName; ::rtl::OUString sMediaType; ::rtl::OUString sFilterType; sal_Int32 nFlags; sal_Int32 nFileFormatVersion; // user data String sFilterName; sal_Bool bHasDialog : 1; sal_Bool bIsInternalFilter : 1; sal_Bool bIsPixelFormat : 1; sal_Bool IsValid(); sal_Bool CreateFilterName( const ::rtl::OUString& rUserDataEntry ); String GetShortName( ); static const char* InternalPixelFilterNameList[]; static const char* InternalVectorFilterNameList[]; static const char* ExternalPixelFilterNameList[]; }; typedef std::vector< FilterConfigCacheEntry > CacheVector; CacheVector aImport; CacheVector aExport; sal_Bool bUseConfig; SVT_DLLPRIVATE sal_Bool ImplIsOwnFilter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rFilterProperties ); SVT_DLLPRIVATE sal_Bool ImplAddFilterEntry( sal_Int32& nFlags, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rFilterProperties, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& xTypeAccess, const ::rtl::OUString& rInternalFilterName ); static sal_Bool bInitialized; static sal_Int32 nIndType; static sal_Int32 nIndUIName; static sal_Int32 nIndDocumentService; static sal_Int32 nIndFilterService; static sal_Int32 nIndFlags; static sal_Int32 nIndUserData; static sal_Int32 nIndFileFormatVersion; static sal_Int32 nIndTemplateName; static const char* InternalFilterListForSvxLight[]; SVT_DLLPRIVATE void ImplInit(); SVT_DLLPRIVATE void ImplInitSmart(); public : sal_uInt16 GetImportFormatCount() const { return aImport.size(); }; sal_uInt16 GetImportFormatNumber( const String& rFormatName ); sal_uInt16 GetImportFormatNumberForMediaType( const String& rMediaType ); sal_uInt16 GetImportFormatNumberForShortName( const String& rShortName ); sal_uInt16 GetImportFormatNumberForTypeName( const String& rType ); String GetImportFilterName( sal_uInt16 nFormat ); String GetImportFormatName( sal_uInt16 nFormat ); String GetImportFormatExtension( sal_uInt16 nFormat, sal_Int32 nEntry = 0); String GetImportFormatMediaType( sal_uInt16 nFormat ); String GetImportFormatShortName( sal_uInt16 nFormat ); String GetImportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry ); String GetImportFilterType( sal_uInt16 nFormat ); String GetImportFilterTypeName( sal_uInt16 nFormat ); sal_Bool IsImportInternalFilter( sal_uInt16 nFormat ); sal_Bool IsImportPixelFormat( sal_uInt16 nFormat ); sal_Bool IsImportDialog( sal_uInt16 nFormat ); sal_uInt16 GetExportFormatCount() const { return aExport.size(); }; sal_uInt16 GetExportFormatNumber( const String& rFormatName ); sal_uInt16 GetExportFormatNumberForMediaType( const String& rMediaType ); sal_uInt16 GetExportFormatNumberForShortName( const String& rShortName ); sal_uInt16 GetExportFormatNumberForTypeName( const String& rType ); String GetExportFilterName( sal_uInt16 nFormat ); String GetExportFormatName( sal_uInt16 nFormat ); String GetExportFormatExtension( sal_uInt16 nFormat, sal_Int32 nEntry = 0 ); String GetExportFormatMediaType( sal_uInt16 nFormat ); String GetExportFormatShortName( sal_uInt16 nFormat ); String GetExportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry ); String GetExportFilterTypeName( sal_uInt16 nFormat ); String GetExportInternalFilterName( sal_uInt16 nFormat ); sal_Bool IsExportInternalFilter( sal_uInt16 nFormat ); sal_Bool IsExportPixelFormat( sal_uInt16 nFormat ); sal_Bool IsExportDialog( sal_uInt16 nFormat ); FilterConfigCache( sal_Bool bUseConfig ); ~FilterConfigCache(); }; #endif // _FILTER_CONFIG_CACHE_HXX_ <commit_msg>INTEGRATION: CWS ooo19126 (1.14.140); FILE MERGED 2005/09/05 14:52:53 rt 1.14.140.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: FilterConfigCache.hxx,v $ * * $Revision: 1.15 $ * * last change: $Author: rt $ $Date: 2005-09-08 15:32:42 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _FILTER_CONFIG_CACHE_HXX_ #define _FILTER_CONFIG_CACHE_HXX_ #ifndef INCLUDED_SVTDLLAPI_H #include "svtools/svtdllapi.h" #endif #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_ #include <com/sun/star/uno/Sequence.h> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_H_ #include <com/sun/star/uno/Reference.h> #endif #ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_ #include <com/sun/star/beans/PropertyValue.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_ #include <com/sun/star/container/XNameAccess.hpp> #endif #ifndef INCLUDED_VECTOR #include <vector> #define INCLUDED_VECTOR #endif class SVT_DLLPUBLIC FilterConfigCache { struct FilterConfigCacheEntry { ::rtl::OUString sInternalFilterName; ::rtl::OUString sType; ::com::sun::star::uno::Sequence< ::rtl::OUString > lExtensionList; ::rtl::OUString sUIName; ::rtl::OUString sDocumentService; ::rtl::OUString sFilterService; ::rtl::OUString sTemplateName; ::rtl::OUString sMediaType; ::rtl::OUString sFilterType; sal_Int32 nFlags; sal_Int32 nFileFormatVersion; // user data String sFilterName; sal_Bool bHasDialog : 1; sal_Bool bIsInternalFilter : 1; sal_Bool bIsPixelFormat : 1; sal_Bool IsValid(); sal_Bool CreateFilterName( const ::rtl::OUString& rUserDataEntry ); String GetShortName( ); static const char* InternalPixelFilterNameList[]; static const char* InternalVectorFilterNameList[]; static const char* ExternalPixelFilterNameList[]; }; typedef std::vector< FilterConfigCacheEntry > CacheVector; CacheVector aImport; CacheVector aExport; sal_Bool bUseConfig; SVT_DLLPRIVATE sal_Bool ImplIsOwnFilter( const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rFilterProperties ); SVT_DLLPRIVATE sal_Bool ImplAddFilterEntry( sal_Int32& nFlags, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rFilterProperties, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& xTypeAccess, const ::rtl::OUString& rInternalFilterName ); static sal_Bool bInitialized; static sal_Int32 nIndType; static sal_Int32 nIndUIName; static sal_Int32 nIndDocumentService; static sal_Int32 nIndFilterService; static sal_Int32 nIndFlags; static sal_Int32 nIndUserData; static sal_Int32 nIndFileFormatVersion; static sal_Int32 nIndTemplateName; static const char* InternalFilterListForSvxLight[]; SVT_DLLPRIVATE void ImplInit(); SVT_DLLPRIVATE void ImplInitSmart(); public : sal_uInt16 GetImportFormatCount() const { return aImport.size(); }; sal_uInt16 GetImportFormatNumber( const String& rFormatName ); sal_uInt16 GetImportFormatNumberForMediaType( const String& rMediaType ); sal_uInt16 GetImportFormatNumberForShortName( const String& rShortName ); sal_uInt16 GetImportFormatNumberForTypeName( const String& rType ); String GetImportFilterName( sal_uInt16 nFormat ); String GetImportFormatName( sal_uInt16 nFormat ); String GetImportFormatExtension( sal_uInt16 nFormat, sal_Int32 nEntry = 0); String GetImportFormatMediaType( sal_uInt16 nFormat ); String GetImportFormatShortName( sal_uInt16 nFormat ); String GetImportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry ); String GetImportFilterType( sal_uInt16 nFormat ); String GetImportFilterTypeName( sal_uInt16 nFormat ); sal_Bool IsImportInternalFilter( sal_uInt16 nFormat ); sal_Bool IsImportPixelFormat( sal_uInt16 nFormat ); sal_Bool IsImportDialog( sal_uInt16 nFormat ); sal_uInt16 GetExportFormatCount() const { return aExport.size(); }; sal_uInt16 GetExportFormatNumber( const String& rFormatName ); sal_uInt16 GetExportFormatNumberForMediaType( const String& rMediaType ); sal_uInt16 GetExportFormatNumberForShortName( const String& rShortName ); sal_uInt16 GetExportFormatNumberForTypeName( const String& rType ); String GetExportFilterName( sal_uInt16 nFormat ); String GetExportFormatName( sal_uInt16 nFormat ); String GetExportFormatExtension( sal_uInt16 nFormat, sal_Int32 nEntry = 0 ); String GetExportFormatMediaType( sal_uInt16 nFormat ); String GetExportFormatShortName( sal_uInt16 nFormat ); String GetExportWildcard( sal_uInt16 nFormat, sal_Int32 nEntry ); String GetExportFilterTypeName( sal_uInt16 nFormat ); String GetExportInternalFilterName( sal_uInt16 nFormat ); sal_Bool IsExportInternalFilter( sal_uInt16 nFormat ); sal_Bool IsExportPixelFormat( sal_uInt16 nFormat ); sal_Bool IsExportDialog( sal_uInt16 nFormat ); FilterConfigCache( sal_Bool bUseConfig ); ~FilterConfigCache(); }; #endif // _FILTER_CONFIG_CACHE_HXX_ <|endoftext|>
<commit_before>/* This tutorial shows how to write a simple matrix multiplication for gpu. To run this tutorial cd build/ make run_developers_tutorial_04gpu */ #include <tiramisu/tiramisu.h> #define SIZE0 1000 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("matmul"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- constant p0("N", expr((int32_t) SIZE0)); // Declare loop iterators var i("i", 0, p0), j("j", 0, p0), k("k", 0, p0); // Declare cpu buffers. buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input); buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input); buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output); // Declare gpu buffers. buffer b_A_gpu("b_A_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); buffer b_B_gpu("b_B_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); buffer b_C_gpu("b_C_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); // Tag the GPU buffers to be stored in global memory. b_A_gpu.tag_gpu_global(); b_B_gpu.tag_gpu_global(); b_C_gpu.tag_gpu_global(); // Declare inputs (b_A and b_B) input c_A({i,j}, p_uint8); input c_B({i,j}, p_uint8); // Declare a computation to initialize the reduction c[i,j] computation C_init({i,j}, expr((uint8_t) 0)); // Declare the reduction operation. computation c_C({i,j,k}, p_uint8); // Note that the previous computation has an empty expression (because we can only use c_C in an expression after its declaration) c_C.set_expression(c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j)); // Declare host-gpu transfer computations. computation copy_A_to_device({}, memcpy(b_A, b_A_gpu)); computation copy_B_to_device({}, memcpy(b_B, b_B_gpu)); computation copy_C_to_host({}, memcpy(b_C_gpu, b_C)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Scheduling commands copy_B_to_device.after(copy_A_to_device, computation::root); C_init.after(copy_B_to_device, computation::root); c_C.after(C_init, computation::root); copy_C_to_host.after(c_C, computation::root); // A simple tiling. C_init.gpu_tile(i, j, 16, 16); c_C.gpu_tile(i, j, 16, 16); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Map the computations to a buffer. c_A.store_in(&b_A_gpu); c_B.store_in(&b_B_gpu); // Store C_init[i,j,k] in b_C[i,j] C_init.store_in(&b_C_gpu, {i,j}); // Store c_C[i,j,k] in b_C[i,j] c_C.store_in(&b_C_gpu, {i,j}); // Note that both of the computations C_init and c_C store their // results in the buffer b_C. // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Generate object files. Last argument triggers cuda compilation. tiramisu::codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_04gpu.o", true); return 0; } <commit_msg>Change 04gpu to use the new API<commit_after>/* This tutorial shows how to write a simple matrix multiplication for gpu. To run this tutorial cd build/ make run_developers_tutorial_04gpu */ #include <tiramisu/tiramisu.h> #define SIZE0 1000 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("matmul"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- constant N("N", SIZE0); // Declare loop iterators var i("i", 0, N), j("j", 0, N), k("k", 0, N); // Declare cpu buffers. buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input); buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input); buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output); // Declare gpu buffers. buffer b_A_gpu("b_A_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); buffer b_B_gpu("b_B_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); buffer b_C_gpu("b_C_gpu", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_temporary); // Tag the GPU buffers to be stored in global memory. b_A_gpu.tag_gpu_global(); b_B_gpu.tag_gpu_global(); b_C_gpu.tag_gpu_global(); // Declare inputs. input A("A", {i,j}, p_uint8); input B("B", {i,j}, p_uint8); // Declare a computation to initialize the reduction. computation C_init("C_init", {i,j}, expr((uint8_t) 0)); // Declare the reduction operation. computation C("C", {i,j,k}, p_uint8); // Note that the previous computation has an empty expression (because we can only use C in an expression after its declaration) C.set_expression(C(i, j, k - 1) + A(i, k) * B(k, j)); // Declare host-gpu transfer computations. computation copy_A_to_device({}, memcpy(b_A, b_A_gpu)); computation copy_B_to_device({}, memcpy(b_B, b_B_gpu)); computation copy_C_to_host({}, memcpy(b_C_gpu, b_C)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Scheduling commands copy_B_to_device.after(copy_A_to_device, computation::root); C_init.after(copy_B_to_device, computation::root); C.after(C_init, computation::root); copy_C_to_host.after(C, computation::root); // A simple tiling. C_init.gpu_tile(i, j, 16, 16); C.gpu_tile(i, j, 16, 16); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Map the computations to a buffer. A.store_in(&b_A_gpu); B.store_in(&b_B_gpu); // Store C_init[i,j,k] in b_C[i,j] C_init.store_in(&b_C_gpu, {i,j}); // Store C[i,j,k] in b_C[i,j] C.store_in(&b_C_gpu, {i,j}); // Note that both of the computations C_init and C store their // results in the buffer b_C. // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Generate object files. Last argument triggers cuda compilation. tiramisu::codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_04gpu.o", true); return 0; } <|endoftext|>
<commit_before>#include<unordered_map> #include "reductions.h" using namespace std; namespace MARGINAL { typedef pair<float,float> marginal; struct data { float initial_numerator; float initial_denominator; bool id_features[256]; feature temp[256];//temporary storage when reducing. audit_strings_ptr asp[256]; unordered_map<uint64_t, marginal > marginals; }; template <bool is_learn> void predict_or_learn(data& sm, LEARNER::base_learner& base, example& ec) { for (example::iterator i = ec.begin(); i!= ec.end(); ++i) { namespace_index n = i.index(); if (sm.id_features[n]) { features& f = *i; if (f.size() != 2) { cout << "warning: id feature namespace has " << f.size() << " features. Should have a constant then the id" << endl; continue; } features::iterator i = f.begin(); float first_value = i.value(); float second_value = (++i).value(); uint64_t second_index = i.index(); if (first_value != 1. || second_value != 1.) { cout << "warning: bad id features, must have value 1." << endl; continue; } if (sm.marginals.find(second_index) == sm.marginals.end())//need to initialize things. sm.marginals.insert(make_pair(second_index,make_pair(sm.initial_numerator, sm.initial_denominator))); f.begin().value() = sm.marginals[second_index].first / sm.marginals[second_index].second; sm.temp[n]={second_value,second_index}; if (!f.space_names.empty()) sm.asp[n]=f.space_names[1]; f.truncate_to(1); } } if (is_learn) base.learn(ec); else base.predict(ec); for (example::iterator i = ec.begin(); i!= ec.end(); ++i) { namespace_index n = i.index(); if (sm.id_features[n]) { features& f = *i; if (f.size() != 1) cout << "warning: id feature namespace has " << f.size() << " features. Should have a constant then the id" << endl; else //do unsubstitution dance { f.begin().value() = 1.; f.push_back(sm.temp[n].x, sm.temp[n].weight_index); if (!f.space_names.empty()) f.space_names.push_back(sm.asp[n]); if (is_learn) { uint64_t second_index = (++(f.begin())).index(); sm.marginals[second_index].first += ec.l.simple.label * ec.weight; sm.marginals[second_index].second += ec.weight; } } } } } void finish(data& sm) { sm.marginals.~unordered_map(); } } using namespace MARGINAL; LEARNER::base_learner* marginal_setup(vw& all) { if (missing_option<string, true>(all, "marginal", "substitute marginal label estimates for ids")) return nullptr; new_options(all) ("initial_denominator", po::value<float>()->default_value(1.f), "initial default value") ("initial_numerator", po::value<float>()->default_value(0.f), "initial default value"); add_options(all); data& d = calloc_or_throw<data>(); d.initial_numerator = all.vm["initial_numerator"].as<float>(); d.initial_denominator = all.vm["initial_denominator"].as<float>(); string s = (string)all.vm["marginal"].as<string>(); for (size_t u = 0; u < 256; u++) if (s.find((char)u) != string::npos) d.id_features[u] = true; new(&d.marginals)unordered_map<uint64_t,marginal>(); LEARNER::learner<data>& ret = init_learner(&d, setup_base(all), predict_or_learn<true>, predict_or_learn<false>); ret.set_finish(finish); return make_base(ret); } <commit_msg>changed marginal to used doubles<commit_after>#include<unordered_map> #include "reductions.h" using namespace std; namespace MARGINAL { typedef pair<double,double> marginal; struct data { float initial_numerator; float initial_denominator; bool id_features[256]; feature temp[256];//temporary storage when reducing. audit_strings_ptr asp[256]; unordered_map<uint64_t, marginal > marginals; }; template <bool is_learn> void predict_or_learn(data& sm, LEARNER::base_learner& base, example& ec) { for (example::iterator i = ec.begin(); i!= ec.end(); ++i) { namespace_index n = i.index(); if (sm.id_features[n]) { features& f = *i; if (f.size() != 2) { cout << "warning: id feature namespace has " << f.size() << " features. Should have a constant then the id" << endl; continue; } features::iterator i = f.begin(); float first_value = i.value(); float second_value = (++i).value(); uint64_t second_index = i.index(); if (first_value != 1. || second_value != 1.) { cout << "warning: bad id features, must have value 1." << endl; continue; } if (sm.marginals.find(second_index) == sm.marginals.end())//need to initialize things. sm.marginals.insert(make_pair(second_index,make_pair(sm.initial_numerator, sm.initial_denominator))); f.begin().value() = sm.marginals[second_index].first / sm.marginals[second_index].second; sm.temp[n]={second_value,second_index}; if (!f.space_names.empty()) sm.asp[n]=f.space_names[1]; f.truncate_to(1); } } if (is_learn) base.learn(ec); else base.predict(ec); for (example::iterator i = ec.begin(); i!= ec.end(); ++i) { namespace_index n = i.index(); if (sm.id_features[n]) { features& f = *i; if (f.size() != 1) cout << "warning: id feature namespace has " << f.size() << " features. Should have a constant then the id" << endl; else //do unsubstitution dance { f.begin().value() = 1.; f.push_back(sm.temp[n].x, sm.temp[n].weight_index); if (!f.space_names.empty()) f.space_names.push_back(sm.asp[n]); if (is_learn) { uint64_t second_index = (++(f.begin())).index(); sm.marginals[second_index].first += ec.l.simple.label * ec.weight; sm.marginals[second_index].second += ec.weight; } } } } } void finish(data& sm) { sm.marginals.~unordered_map(); } } using namespace MARGINAL; LEARNER::base_learner* marginal_setup(vw& all) { if (missing_option<string, true>(all, "marginal", "substitute marginal label estimates for ids")) return nullptr; new_options(all) ("initial_denominator", po::value<float>()->default_value(1.f), "initial default value") ("initial_numerator", po::value<float>()->default_value(0.f), "initial default value"); add_options(all); data& d = calloc_or_throw<data>(); d.initial_numerator = all.vm["initial_numerator"].as<float>(); d.initial_denominator = all.vm["initial_denominator"].as<float>(); string s = (string)all.vm["marginal"].as<string>(); for (size_t u = 0; u < 256; u++) if (s.find((char)u) != string::npos) d.id_features[u] = true; new(&d.marginals)unordered_map<uint64_t,marginal>(); LEARNER::learner<data>& ret = init_learner(&d, setup_base(all), predict_or_learn<true>, predict_or_learn<false>); ret.set_finish(finish); return make_base(ret); } <|endoftext|>
<commit_before>/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : Id */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* clarke@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*******************************************************************/ #include <vtkXdmfDataArray.h> #include <vtkObjectFactory.h> #include <vtkCommand.h> #include <vtkUnsignedCharArray.h> #include <vtkCharArray.h> #include <vtkIntArray.h> #include <vtkLongArray.h> #include <vtkFloatArray.h> #include <vtkDoubleArray.h> #include <vtkUnsignedIntArray.h> #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include <XdmfArray.h> //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkXdmfDataArray); //---------------------------------------------------------------------------- vtkXdmfDataArray::vtkXdmfDataArray() { this->Array = NULL; this->vtkArray = NULL; } //---------------------------------------------------------------------------- vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, int rank, int Components, int MakeCopy ){ XdmfArray *array = this->Array; XdmfInt64 components = 1; XdmfInt64 tuples = 0; if ( ArrayName != NULL ) { array = TagNameToArray( ArrayName ); } if( array == NULL ){ XdmfErrorMessage("Array is NULL"); return(NULL); } if ( this->vtkArray ) { this->vtkArray->Delete(); this->vtkArray = 0; } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkCharArray::New(); } break; case XDMF_UINT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedCharArray::New(); } break; case XDMF_INT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkShortArray::New(); } break; case XDMF_UINT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedShortArray::New(); } break; case XDMF_UINT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedIntArray::New(); } break; case XDMF_INT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkIntArray::New(); } break; case XDMF_INT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkLongArray::New(); } break; case XDMF_FLOAT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkFloatArray::New(); } break; case XDMF_FLOAT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkDoubleArray::New(); } break; default: vtkErrorMacro("Cannot create VTK data array: " << array->GetNumberType()); return 0; } if ( CopyShape ) { if ( array->GetRank() > rank + 1 ) { this->vtkArray->Delete(); this->vtkArray = 0; vtkErrorMacro("Rank of Xdmf array is more than 1 + rank of dataset"); return 0; } if ( array->GetRank() > rank ) { components = array->GetDimension( rank ); } tuples = array->GetNumberOfElements() / components; /// this breaks components = Components; tuples = array->GetNumberOfElements() / components; // cout << "Tuples: " << tuples << " components: " << components << endl; // cout << "Rank: " << rank << endl; this->vtkArray->SetNumberOfComponents( components ); if(MakeCopy) this->vtkArray->SetNumberOfTuples( tuples ); } else { this->vtkArray->SetNumberOfComponents( 1 ); if(MakeCopy) this->vtkArray->SetNumberOfTuples( array->GetNumberOfElements() ); } //cout << "Number type: " << array->GetNumberType() << endl; if(MakeCopy){ switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->GetValues( 0, ( XDMF_8_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT8_TYPE : array->GetValues( 0, ( XDMF_8_U_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT16_TYPE : array->GetValues( 0, ( XDMF_16_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT16_TYPE : array->GetValues( 0, ( XDMF_16_U_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : array->GetValues( 0, (XDMF_32_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT32_TYPE : array->GetValues( 0, (XDMF_32_U_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT64_TYPE : array->GetValues( 0, (XDMF_64_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->GetValues( 0, ( float *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT64_TYPE : array->GetValues( 0, ( double *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : if ( array->GetNumberOfElements() > 0 ) { //cout << "Manual idx" << endl; //cout << "Tuples: " << vtkArray->GetNumberOfTuples() << endl; //cout << "Components: " << vtkArray->GetNumberOfComponents() << endl; //cout << "Elements: " << array->GetNumberOfElements() << endl; vtkIdType jj, kk; vtkIdType idx = 0; for ( jj = 0; jj < vtkArray->GetNumberOfTuples(); jj ++ ) { for ( kk = 0; kk < vtkArray->GetNumberOfComponents(); kk ++ ) { double val = array->GetValueAsFloat64(idx); //cout << "Value: " << val << endl; vtkArray->SetComponent(jj, kk, val); idx ++; } } } break; } }else{ switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : { vtkCharArray *chara = vtkCharArray::SafeDownCast(this->vtkArray); if(!chara){ XdmfErrorMessage("Cannot downcast data array"); return(0); } chara->SetArray((char *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_UINT8_TYPE : { vtkUnsignedCharArray *uchara = vtkUnsignedCharArray::SafeDownCast(this->vtkArray); if(!uchara){ XdmfErrorMessage("Cannot downcast ucharata array"); return(0); } uchara->SetArray((unsigned char *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_INT16_TYPE : { vtkShortArray *shorta = vtkShortArray::SafeDownCast(this->vtkArray); if(!shorta){ XdmfErrorMessage("Cannot downcast data array"); return(0); } shorta->SetArray((short *)array->GetDataPointer(), tuples, 0); } break; case XDMF_UINT16_TYPE : { vtkUnsignedShortArray *ushorta = vtkUnsignedShortArray::SafeDownCast(this->vtkArray); if(!ushorta){ XdmfErrorMessage("Cannot downcast ushortata array"); return(0); } ushorta->SetArray((unsigned short *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_INT32_TYPE : { vtkIntArray *inta = vtkIntArray::SafeDownCast(this->vtkArray); if(!inta){ XdmfErrorMessage("Cannot downcast intata array"); return(0); } inta->SetArray((int *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_UINT32_TYPE : { vtkUnsignedIntArray *uinta = vtkUnsignedIntArray::SafeDownCast(this->vtkArray); if(!uinta){ XdmfErrorMessage("Cannot downcast uintata array"); return(0); } uinta->SetArray((unsigned int *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_FLOAT32_TYPE : { vtkFloatArray *floata = vtkFloatArray::SafeDownCast(this->vtkArray); if(!floata){ XdmfErrorMessage("Cannot downcast floatata array"); return(0); } floata->SetArray((float *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_FLOAT64_TYPE : { vtkDoubleArray *doublea = vtkDoubleArray::SafeDownCast(this->vtkArray); if(!doublea){ XdmfErrorMessage("Cannot downcast doubleata array"); return(0); } doublea->SetArray((double *)array->GetDataPointer(), components * tuples, 0); } break; default : XdmfErrorMessage("Can't handle number type"); return(0); break; } array->Reset(); } return( this->vtkArray ); } //---------------------------------------------------------------------------- char *vtkXdmfDataArray::ToXdmfArray( vtkDataArray *DataArray, int CopyShape ){ XdmfArray *array; if ( DataArray == NULL ) { DataArray = this->vtkArray; } if ( DataArray == NULL ) { vtkDebugMacro(<< "Array is NULL"); return(NULL); } if ( this->Array == NULL ){ this->Array = new XdmfArray(); switch( DataArray->GetDataType() ){ case VTK_CHAR : case VTK_UNSIGNED_CHAR : this->Array->SetNumberType( XDMF_INT8_TYPE ); break; case VTK_SHORT : case VTK_UNSIGNED_SHORT : case VTK_INT : case VTK_UNSIGNED_INT : case VTK_LONG : case VTK_UNSIGNED_LONG : this->Array->SetNumberType( XDMF_INT32_TYPE ); break; case VTK_FLOAT : this->Array->SetNumberType( XDMF_FLOAT32_TYPE ); break; case VTK_DOUBLE : this->Array->SetNumberType( XDMF_FLOAT64_TYPE ); break; default : XdmfErrorMessage("Can't handle Data Type"); return( NULL ); } } array = this->Array; if( CopyShape ) { XdmfInt64 Shape[3]; Shape[0] = DataArray->GetNumberOfTuples(); Shape[1] = DataArray->GetNumberOfComponents(); if( Shape[1] == 1 ) { array->SetShape( 1, Shape ); } else { array->SetShape( 2, Shape ); } } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->SetValues( 0, ( unsigned char *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : case XDMF_INT64_TYPE : array->SetValues( 0, ( int *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->SetValues( 0, ( float *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : array->SetValues( 0, ( double *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; } return( array->GetTagName() ); } <commit_msg>add support for XDMF_INT64_TYPE<commit_after>/*******************************************************************/ /* XDMF */ /* eXtensible Data Model and Format */ /* */ /* Id : Id */ /* Date : $Date$ */ /* Version : $Revision$ */ /* */ /* Author: */ /* Jerry A. Clarke */ /* clarke@arl.army.mil */ /* US Army Research Laboratory */ /* Aberdeen Proving Ground, MD */ /* */ /* Copyright @ 2002 US Army Research Laboratory */ /* All Rights Reserved */ /* See Copyright.txt or http://www.arl.hpc.mil/ice for details */ /* */ /* This software is distributed WITHOUT ANY WARRANTY; without */ /* even the implied warranty of MERCHANTABILITY or FITNESS */ /* FOR A PARTICULAR PURPOSE. See the above copyright notice */ /* for more information. */ /* */ /*******************************************************************/ #include <vtkXdmfDataArray.h> #include <vtkObjectFactory.h> #include <vtkCommand.h> #include <vtkUnsignedCharArray.h> #include <vtkCharArray.h> #include <vtkIntArray.h> #include <vtkLongArray.h> #include <vtkFloatArray.h> #include <vtkDoubleArray.h> #include <vtkUnsignedIntArray.h> #include "vtkShortArray.h" #include "vtkUnsignedShortArray.h" #include <XdmfArray.h> //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkXdmfDataArray); //---------------------------------------------------------------------------- vtkXdmfDataArray::vtkXdmfDataArray() { this->Array = NULL; this->vtkArray = NULL; } //---------------------------------------------------------------------------- vtkDataArray *vtkXdmfDataArray::FromXdmfArray( char *ArrayName, int CopyShape, int rank, int Components, int MakeCopy ){ XdmfArray *array = this->Array; XdmfInt64 components = 1; XdmfInt64 tuples = 0; if ( ArrayName != NULL ) { array = TagNameToArray( ArrayName ); } if( array == NULL ){ XdmfErrorMessage("Array is NULL"); return(NULL); } if ( this->vtkArray ) { this->vtkArray->Delete(); this->vtkArray = 0; } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkCharArray::New(); } break; case XDMF_UINT8_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedCharArray::New(); } break; case XDMF_INT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkShortArray::New(); } break; case XDMF_UINT16_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedShortArray::New(); } break; case XDMF_UINT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkUnsignedIntArray::New(); } break; case XDMF_INT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkIntArray::New(); } break; case XDMF_INT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkLongArray::New(); } break; case XDMF_FLOAT32_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkFloatArray::New(); } break; case XDMF_FLOAT64_TYPE : if( this->vtkArray == NULL ) { this->vtkArray = vtkDoubleArray::New(); } break; default: vtkErrorMacro("Cannot create VTK data array: " << array->GetNumberType()); return 0; } if ( CopyShape ) { if ( array->GetRank() > rank + 1 ) { this->vtkArray->Delete(); this->vtkArray = 0; vtkErrorMacro("Rank of Xdmf array is more than 1 + rank of dataset"); return 0; } if ( array->GetRank() > rank ) { components = array->GetDimension( rank ); } tuples = array->GetNumberOfElements() / components; /// this breaks components = Components; tuples = array->GetNumberOfElements() / components; // cout << "Tuples: " << tuples << " components: " << components << endl; // cout << "Rank: " << rank << endl; this->vtkArray->SetNumberOfComponents( components ); if(MakeCopy) this->vtkArray->SetNumberOfTuples( tuples ); } else { this->vtkArray->SetNumberOfComponents( 1 ); if(MakeCopy) this->vtkArray->SetNumberOfTuples( array->GetNumberOfElements() ); } //cout << "Number type: " << array->GetNumberType() << endl; if(MakeCopy){ switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->GetValues( 0, ( XDMF_8_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT8_TYPE : array->GetValues( 0, ( XDMF_8_U_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT16_TYPE : array->GetValues( 0, ( XDMF_16_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT16_TYPE : array->GetValues( 0, ( XDMF_16_U_INT*)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : array->GetValues( 0, (XDMF_32_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_UINT32_TYPE : array->GetValues( 0, (XDMF_32_U_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT64_TYPE : array->GetValues( 0, (XDMF_64_INT *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->GetValues( 0, ( float *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT64_TYPE : array->GetValues( 0, ( double *)this->vtkArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : if ( array->GetNumberOfElements() > 0 ) { //cout << "Manual idx" << endl; //cout << "Tuples: " << vtkArray->GetNumberOfTuples() << endl; //cout << "Components: " << vtkArray->GetNumberOfComponents() << endl; //cout << "Elements: " << array->GetNumberOfElements() << endl; vtkIdType jj, kk; vtkIdType idx = 0; for ( jj = 0; jj < vtkArray->GetNumberOfTuples(); jj ++ ) { for ( kk = 0; kk < vtkArray->GetNumberOfComponents(); kk ++ ) { double val = array->GetValueAsFloat64(idx); //cout << "Value: " << val << endl; vtkArray->SetComponent(jj, kk, val); idx ++; } } } break; } }else{ switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : { vtkCharArray *chara = vtkCharArray::SafeDownCast(this->vtkArray); if(!chara){ XdmfErrorMessage("Cannot downcast data array"); return(0); } chara->SetArray((char *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_UINT8_TYPE : { vtkUnsignedCharArray *uchara = vtkUnsignedCharArray::SafeDownCast(this->vtkArray); if(!uchara){ XdmfErrorMessage("Cannot downcast ucharata array"); return(0); } uchara->SetArray((unsigned char *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_INT16_TYPE : { vtkShortArray *shorta = vtkShortArray::SafeDownCast(this->vtkArray); if(!shorta){ XdmfErrorMessage("Cannot downcast data array"); return(0); } shorta->SetArray((short *)array->GetDataPointer(), tuples, 0); } break; case XDMF_UINT16_TYPE : { vtkUnsignedShortArray *ushorta = vtkUnsignedShortArray::SafeDownCast(this->vtkArray); if(!ushorta){ XdmfErrorMessage("Cannot downcast ushortata array"); return(0); } ushorta->SetArray((unsigned short *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_INT32_TYPE : { vtkIntArray *inta = vtkIntArray::SafeDownCast(this->vtkArray); if(!inta){ XdmfErrorMessage("Cannot downcast intata array"); return(0); } inta->SetArray((int *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_UINT32_TYPE : { vtkUnsignedIntArray *uinta = vtkUnsignedIntArray::SafeDownCast(this->vtkArray); if(!uinta){ XdmfErrorMessage("Cannot downcast uintata array"); return(0); } uinta->SetArray((unsigned int *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_INT64_TYPE : { vtkLongArray *longa = vtkLongArray::SafeDownCast(this->vtkArray); if(!longa){ XdmfErrorMessage("Cannot downcast longa array"); return(0); } longa->SetArray((long *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_FLOAT32_TYPE : { vtkFloatArray *floata = vtkFloatArray::SafeDownCast(this->vtkArray); if(!floata){ XdmfErrorMessage("Cannot downcast floatata array"); return(0); } floata->SetArray((float *)array->GetDataPointer(), components * tuples, 0); } break; case XDMF_FLOAT64_TYPE : { vtkDoubleArray *doublea = vtkDoubleArray::SafeDownCast(this->vtkArray); if(!doublea){ XdmfErrorMessage("Cannot downcast doubleata array"); return(0); } doublea->SetArray((double *)array->GetDataPointer(), components * tuples, 0); } break; default : XdmfErrorMessage("Can't handle number type"); return(0); break; } array->Reset(); } return( this->vtkArray ); } //---------------------------------------------------------------------------- char *vtkXdmfDataArray::ToXdmfArray( vtkDataArray *DataArray, int CopyShape ){ XdmfArray *array; if ( DataArray == NULL ) { DataArray = this->vtkArray; } if ( DataArray == NULL ) { vtkDebugMacro(<< "Array is NULL"); return(NULL); } if ( this->Array == NULL ){ this->Array = new XdmfArray(); switch( DataArray->GetDataType() ){ case VTK_CHAR : case VTK_UNSIGNED_CHAR : this->Array->SetNumberType( XDMF_INT8_TYPE ); break; case VTK_SHORT : case VTK_UNSIGNED_SHORT : case VTK_INT : case VTK_UNSIGNED_INT : case VTK_LONG : case VTK_UNSIGNED_LONG : this->Array->SetNumberType( XDMF_INT32_TYPE ); break; case VTK_FLOAT : this->Array->SetNumberType( XDMF_FLOAT32_TYPE ); break; case VTK_DOUBLE : this->Array->SetNumberType( XDMF_FLOAT64_TYPE ); break; default : XdmfErrorMessage("Can't handle Data Type"); return( NULL ); } } array = this->Array; if( CopyShape ) { XdmfInt64 Shape[3]; Shape[0] = DataArray->GetNumberOfTuples(); Shape[1] = DataArray->GetNumberOfComponents(); if( Shape[1] == 1 ) { array->SetShape( 1, Shape ); } else { array->SetShape( 2, Shape ); } } switch( array->GetNumberType() ){ case XDMF_INT8_TYPE : array->SetValues( 0, ( unsigned char *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_INT32_TYPE : case XDMF_INT64_TYPE : array->SetValues( 0, ( int *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; case XDMF_FLOAT32_TYPE : array->SetValues( 0, ( float *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; default : array->SetValues( 0, ( double *)DataArray->GetVoidPointer( 0 ), array->GetNumberOfElements() ); break; } return( array->GetTagName() ); } <|endoftext|>
<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdlib.h> #include <string> #include "../qsim/lib/circuit.h" #include "../qsim/lib/gate_appl.h" #include "../qsim/lib/gates_cirq.h" #include "../qsim/lib/seqfor.h" #include "../qsim/lib/simmux.h" #include "cirq/google/api/v2/program.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow_quantum/core/ops/parse_context.h" #include "tensorflow_quantum/core/src/circuit_parser_qsim.h" #include "tensorflow_quantum/core/src/util_qsim.h" namespace tfq { using ::cirq::google::api::v2::Program; using ::tensorflow::Status; typedef qsim::Cirq::GateCirq<float> QsimGate; typedef qsim::Circuit<QsimGate> QsimCircuit; class TfqSimulateSamplesOp : public tensorflow::OpKernel { public: explicit TfqSimulateSamplesOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) {} void Compute(tensorflow::OpKernelContext* context) override { // TODO (mbbrough): add more dimension checks for other inputs here. DCHECK_EQ(4, context->num_inputs()); // Parse to Program Proto and num_qubits. std::vector<Program> programs; std::vector<int> num_qubits; OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs, &num_qubits)); // Parse symbol maps for parameter resolution in the circuits. std::vector<SymbolMap> maps; OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); OP_REQUIRES( context, maps.size() == programs.size(), tensorflow::errors::InvalidArgument(absl::StrCat( "Number of circuits and values do not match. Got ", programs.size(), " circuits and ", maps.size(), " values."))); int num_samples = 0; OP_REQUIRES_OK(context, GetIndividualSample(context, &num_samples)); // Construct qsim circuits. std::vector<QsimCircuit> qsim_circuits(programs.size(), QsimCircuit()); std::vector<std::vector<qsim::GateFused<QsimGate>>> fused_circuits( programs.size(), std::vector<qsim::GateFused<QsimGate>>({})); auto construct_f = [&](int start, int end) { for (int i = start; i < end; i++) { OP_REQUIRES_OK(context, QsimCircuitFromProgram( programs[i], maps[i], num_qubits[i], &qsim_circuits[i], &fused_circuits[i])); } }; const int num_cycles = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( programs.size(), num_cycles, construct_f); // Find largest circuit for tensor size padding and allocate // the output tensor. int max_num_qubits = 0; for (const int num : num_qubits) { max_num_qubits = std::max(max_num_qubits, num); } const int output_dim_size = maps.size(); tensorflow::TensorShape output_shape; output_shape.AddDim(output_dim_size); output_shape.AddDim(num_samples); output_shape.AddDim(max_num_qubits); tensorflow::Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output)); auto output_tensor = output->tensor<int8_t, 3>(); // Cross reference with standard google cloud compute instances // Memory ~= 2 * num_threads * (2 * 64 * 2 ** num_qubits in circuits) // e2s2 = 2 CPU, 8GB -> Can safely do 25 since Memory = 4GB // e2s4 = 4 CPU, 16GB -> Can safely do 25 since Memory = 8GB // ... if (max_num_qubits < 26) { ComputeSmall(num_qubits, max_num_qubits, num_samples, fused_circuits, context, &output_tensor); } else { ComputeLarge(num_qubits, max_num_qubits, num_samples, fused_circuits, context, &output_tensor); } programs.clear(); num_qubits.clear(); maps.clear(); qsim_circuits.clear(); fused_circuits.clear(); } private: void ComputeLarge( const std::vector<int>& num_qubits, const int max_num_qubits, const int num_samples, const std::vector<std::vector<qsim::GateFused<QsimGate>>>& fused_circuits, tensorflow::OpKernelContext* context, tensorflow::TTypes<int8_t, 3>::Tensor* output_tensor) { // Instantiate qsim objects. const auto tfq_for = tfq::QsimFor(context); using Simulator = qsim::Simulator<const tfq::QsimFor&>; using StateSpace = Simulator::StateSpace; using State = StateSpace::State; // Begin simulation. int largest_nq = 1; State sv = StateSpace(largest_nq, tfq_for).CreateState(); // Simulate programs one by one. Parallelizing over wavefunctions // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as nescessary. for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; Simulator sim = Simulator(nq, tfq_for); StateSpace ss = StateSpace(nq, tfq_for); if (nq > largest_nq) { // need to switch to larger statespace. largest_nq = nq; sv = ss.CreateState(); } ss.SetStateZero(sv); for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } auto samples = ss.Sample(sv, num_samples, rand() % 123456); for (int j = 0; j < num_samples; j++) { uint64_t q_ind = 0; uint64_t mask = 1; bool val = 0; while (q_ind < nq) { val = samples[j] & mask; (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = val; q_ind++; mask <<= 1; } while (q_ind < max_num_qubits) { (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = -2; q_ind++; } } } sv.release(); } void ComputeSmall( const std::vector<int>& num_qubits, const int max_num_qubits, const int num_samples, const std::vector<std::vector<qsim::GateFused<QsimGate>>>& fused_circuits, tensorflow::OpKernelContext* context, tensorflow::TTypes<int8_t, 3>::Tensor* output_tensor) { const auto tfq_for = qsim::SequentialFor(1); using Simulator = qsim::Simulator<const qsim::SequentialFor&>; using StateSpace = Simulator::StateSpace; using State = StateSpace::State; auto DoWork = [&](int start, int end) { int largest_nq = 1; State sv = StateSpace(largest_nq, tfq_for).CreateState(); for (int i = start; i < end; i++) { int nq = num_qubits[i]; Simulator sim = Simulator(nq, tfq_for); StateSpace ss = StateSpace(nq, tfq_for); if (nq > largest_nq) { // need to switch to larger statespace. largest_nq = nq; sv = ss.CreateState(); } ss.SetStateZero(sv); for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } auto samples = ss.Sample(sv, num_samples, rand() % 123456); for (int j = 0; j < num_samples; j++) { uint64_t q_ind = 0; uint64_t mask = 1; bool val = 0; while (q_ind < nq) { val = samples[j] & mask; (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = val; q_ind++; mask <<= 1; } while (q_ind < max_num_qubits) { (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = -2; q_ind++; } } } sv.release(); }; const int64_t num_cycles = 200 * (int64_t(1) << static_cast<int64_t>(max_num_qubits)); context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( fused_circuits.size(), num_cycles, DoWork); } }; REGISTER_KERNEL_BUILDER( Name("TfqSimulateSamples").Device(tensorflow::DEVICE_CPU), TfqSimulateSamplesOp); REGISTER_OP("TfqSimulateSamples") .Input("programs: string") .Input("symbol_names: string") .Input("symbol_values: float") .Input("num_samples: int32") .Output("samples: int8") .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) { tensorflow::shape_inference::ShapeHandle programs_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape)); tensorflow::shape_inference::ShapeHandle symbol_names_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape)); tensorflow::shape_inference::ShapeHandle symbol_values_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape)); tensorflow::shape_inference::ShapeHandle num_samples_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &num_samples_shape)); // [batch_size, n_samples, largest_n_qubits] c->set_output( 0, c->MakeShape( {c->Dim(programs_shape, 0), tensorflow::shape_inference::InferenceContext::kUnknownDim, tensorflow::shape_inference::InferenceContext::kUnknownDim})); return tensorflow::Status::OK(); }); } // namespace tfq <commit_msg>More windows fix attempts.<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <stdlib.h> #include <string> #include "../qsim/lib/circuit.h" #include "../qsim/lib/gate_appl.h" #include "../qsim/lib/gates_cirq.h" #include "../qsim/lib/seqfor.h" #include "../qsim/lib/simmux.h" #include "cirq/google/api/v2/program.pb.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/shape_inference.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/lib/core/error_codes.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/core/threadpool.h" #include "tensorflow_quantum/core/ops/parse_context.h" #include "tensorflow_quantum/core/src/circuit_parser_qsim.h" #include "tensorflow_quantum/core/src/util_qsim.h" namespace tfq { using ::cirq::google::api::v2::Program; using ::tensorflow::Status; typedef qsim::Cirq::GateCirq<float> QsimGate; typedef qsim::Circuit<QsimGate> QsimCircuit; class TfqSimulateSamplesOp : public tensorflow::OpKernel { public: explicit TfqSimulateSamplesOp(tensorflow::OpKernelConstruction* context) : OpKernel(context) {} void Compute(tensorflow::OpKernelContext* context) override { // TODO (mbbrough): add more dimension checks for other inputs here. DCHECK_EQ(4, context->num_inputs()); // Parse to Program Proto and num_qubits. std::vector<Program> programs; std::vector<int> num_qubits; OP_REQUIRES_OK(context, GetProgramsAndNumQubits(context, &programs, &num_qubits)); // Parse symbol maps for parameter resolution in the circuits. std::vector<SymbolMap> maps; OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps)); OP_REQUIRES( context, maps.size() == programs.size(), tensorflow::errors::InvalidArgument(absl::StrCat( "Number of circuits and values do not match. Got ", programs.size(), " circuits and ", maps.size(), " values."))); int num_samples = 0; OP_REQUIRES_OK(context, GetIndividualSample(context, &num_samples)); // Construct qsim circuits. std::vector<QsimCircuit> qsim_circuits(programs.size(), QsimCircuit()); std::vector<std::vector<qsim::GateFused<QsimGate>>> fused_circuits( programs.size(), std::vector<qsim::GateFused<QsimGate>>({})); auto construct_f = [&](int start, int end) { for (int i = start; i < end; i++) { OP_REQUIRES_OK(context, QsimCircuitFromProgram( programs[i], maps[i], num_qubits[i], &qsim_circuits[i], &fused_circuits[i])); } }; const int num_cycles = 1000; context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( programs.size(), num_cycles, construct_f); // Find largest circuit for tensor size padding and allocate // the output tensor. int max_num_qubits = 0; for (const int num : num_qubits) { max_num_qubits = std::max(max_num_qubits, num); } const int output_dim_size = maps.size(); tensorflow::TensorShape output_shape; output_shape.AddDim(output_dim_size); output_shape.AddDim(num_samples); output_shape.AddDim(max_num_qubits); tensorflow::Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output)); auto output_tensor = output->tensor<int8_t, 3>(); // Cross reference with standard google cloud compute instances // Memory ~= 2 * num_threads * (2 * 64 * 2 ** num_qubits in circuits) // e2s2 = 2 CPU, 8GB -> Can safely do 25 since Memory = 4GB // e2s4 = 4 CPU, 16GB -> Can safely do 25 since Memory = 8GB // ... if (max_num_qubits < 26) { ComputeSmall(num_qubits, max_num_qubits, num_samples, fused_circuits, context, &output_tensor); } else { ComputeLarge(num_qubits, max_num_qubits, num_samples, fused_circuits, context, &output_tensor); } programs.clear(); num_qubits.clear(); maps.clear(); qsim_circuits.clear(); fused_circuits.clear(); } private: void ComputeLarge( const std::vector<int>& num_qubits, const int max_num_qubits, const int num_samples, const std::vector<std::vector<qsim::GateFused<QsimGate>>>& fused_circuits, tensorflow::OpKernelContext* context, tensorflow::TTypes<int8_t, 3>::Tensor* output_tensor) { // Instantiate qsim objects. const auto tfq_for = tfq::QsimFor(context); using Simulator = qsim::Simulator<const tfq::QsimFor&>; using StateSpace = Simulator::StateSpace; using State = StateSpace::State; // Begin simulation. int largest_nq = 1; State sv = StateSpace(largest_nq, tfq_for).CreateState(); // Simulate programs one by one. Parallelizing over wavefunctions // we no longer parallelize over circuits. Each time we encounter a // a larger circuit we will grow the Statevector as nescessary. for (int i = 0; i < fused_circuits.size(); i++) { int nq = num_qubits[i]; Simulator sim = Simulator(nq, tfq_for); StateSpace ss = StateSpace(nq, tfq_for); if (nq > largest_nq) { // need to switch to larger statespace. largest_nq = nq; sv = ss.CreateState(); } ss.SetStateZero(sv); for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } auto samples = ss.Sample(sv, num_samples, rand() % 123456); for (int j = 0; j < num_samples; j++) { uint64_t q_ind = 0; uint64_t mask = 1; bool val = 0; while (q_ind < nq) { val = samples[j] & mask; (*output_tensor)( i, j, static_cast<ptrdiff_t>(max_num_qubits - q_ind - 1)) = val; q_ind++; mask <<= 1; } while (q_ind < max_num_qubits) { (*output_tensor)( i, j, static_cast<ptrdiff_t>(max_num_qubits - q_ind - 1)) = -2; q_ind++; } } } sv.release(); } void ComputeSmall( const std::vector<int>& num_qubits, const int max_num_qubits, const int num_samples, const std::vector<std::vector<qsim::GateFused<QsimGate>>>& fused_circuits, tensorflow::OpKernelContext* context, tensorflow::TTypes<int8_t, 3>::Tensor* output_tensor) { const auto tfq_for = qsim::SequentialFor(1); using Simulator = qsim::Simulator<const qsim::SequentialFor&>; using StateSpace = Simulator::StateSpace; using State = StateSpace::State; auto DoWork = [&](int start, int end) { int largest_nq = 1; State sv = StateSpace(largest_nq, tfq_for).CreateState(); for (int i = start; i < end; i++) { int nq = num_qubits[i]; Simulator sim = Simulator(nq, tfq_for); StateSpace ss = StateSpace(nq, tfq_for); if (nq > largest_nq) { // need to switch to larger statespace. largest_nq = nq; sv = ss.CreateState(); } ss.SetStateZero(sv); for (int j = 0; j < fused_circuits[i].size(); j++) { qsim::ApplyFusedGate(sim, fused_circuits[i][j], sv); } auto samples = ss.Sample(sv, num_samples, rand() % 123456); for (int j = 0; j < num_samples; j++) { uint64_t q_ind = 0; uint64_t mask = 1; bool val = 0; while (q_ind < nq) { val = samples[j] & mask; (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = val; q_ind++; mask <<= 1; } while (q_ind < max_num_qubits) { (*output_tensor)(i, j, max_num_qubits - q_ind - 1) = -2; q_ind++; } } } sv.release(); }; const int64_t num_cycles = 200 * (int64_t(1) << static_cast<int64_t>(max_num_qubits)); context->device()->tensorflow_cpu_worker_threads()->workers->ParallelFor( fused_circuits.size(), num_cycles, DoWork); } }; REGISTER_KERNEL_BUILDER( Name("TfqSimulateSamples").Device(tensorflow::DEVICE_CPU), TfqSimulateSamplesOp); REGISTER_OP("TfqSimulateSamples") .Input("programs: string") .Input("symbol_names: string") .Input("symbol_values: float") .Input("num_samples: int32") .Output("samples: int8") .SetShapeFn([](tensorflow::shape_inference::InferenceContext* c) { tensorflow::shape_inference::ShapeHandle programs_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape)); tensorflow::shape_inference::ShapeHandle symbol_names_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape)); tensorflow::shape_inference::ShapeHandle symbol_values_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape)); tensorflow::shape_inference::ShapeHandle num_samples_shape; TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 1, &num_samples_shape)); // [batch_size, n_samples, largest_n_qubits] c->set_output( 0, c->MakeShape( {c->Dim(programs_shape, 0), tensorflow::shape_inference::InferenceContext::kUnknownDim, tensorflow::shape_inference::InferenceContext::kUnknownDim})); return tensorflow::Status::OK(); }); } // namespace tfq <|endoftext|>
<commit_before>/** * \file * \brief SoftwareTimerOperationsTestCase class implementation * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "SoftwareTimerOperationsTestCase.hpp" #include "waitForNextTick.hpp" #include "distortos/StaticSoftwareTimer.hpp" #include "distortos/ThisThread.hpp" namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool SoftwareTimerOperationsTestCase::run_() const { volatile uint32_t value {}; auto softwareTimer = makeStaticSoftwareTimer( [&value]() { ++value; }); { constexpr auto duration = TickClock::duration{11}; if (softwareTimer.isRunning() != false || value != 0) // initially must be stopped and must not execute return false; waitForNextTick(); if (softwareTimer.start(duration) != 0) return false; if (softwareTimer.isRunning() != true || value != 0) // must be started, but may not execute yet return false; if (softwareTimer.stop() != 0) return false; if (softwareTimer.isRunning() != false || value != 0) // must be stopped, must not execute return false; ThisThread::sleepFor(duration * 2); if (softwareTimer.isRunning() != false || value != 0) // make sure it did not execute return false; } { constexpr auto duration = TickClock::duration{9}; waitForNextTick(); if (softwareTimer.start(duration) != 0) return false; if (softwareTimer.isRunning() != true || value != 0) // must be started, but may not execute yet return false; const auto start = TickClock::now(); while (softwareTimer.isRunning() == true); // must be stopped, function must be executed, real duration must equal what is expected if (softwareTimer.isRunning() != false || value != 1 || TickClock::now() - start != duration + decltype(duration){1}) return false; } { waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{13}; if (softwareTimer.start(wakeUpTimePoint) != 0) return false; if (softwareTimer.isRunning() != true || value != 1) // must be started, but may not execute yet return false; while (softwareTimer.isRunning() == true); // must be stopped, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != false || value != 2 || TickClock::now() != wakeUpTimePoint) return false; } { constexpr auto period = TickClock::duration{6}; waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{17}; if (softwareTimer.start(wakeUpTimePoint, period) != 0) return false; if (softwareTimer.isRunning() != true || value != 2) // must be started, but may not execute yet return false; for (size_t iteration {}; iteration < 4; ++iteration) { while (softwareTimer.isRunning() == true && value == 2 + iteration); // must be still running, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != true || value != 3 + iteration || TickClock::now() != wakeUpTimePoint + period * iteration) return false; } if (softwareTimer.stop() != 0) return false; if (softwareTimer.isRunning() != false || value != 6) // must be stopped return false; ThisThread::sleepFor(period * 2); if (softwareTimer.isRunning() != false || value != 6) // make sure it did not execute again return false; } return true; } } // namespace test } // namespace distortos <commit_msg>Add restart test to SoftwareTimerOperationsTestCase<commit_after>/** * \file * \brief SoftwareTimerOperationsTestCase class implementation * * \author Copyright (C) 2014-2016 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "SoftwareTimerOperationsTestCase.hpp" #include "waitForNextTick.hpp" #include "distortos/StaticSoftwareTimer.hpp" #include "distortos/ThisThread.hpp" namespace distortos { namespace test { /*---------------------------------------------------------------------------------------------------------------------+ | private functions +---------------------------------------------------------------------------------------------------------------------*/ bool SoftwareTimerOperationsTestCase::run_() const { volatile uint32_t value {}; auto softwareTimer = makeStaticSoftwareTimer( [&value]() { ++value; }); { constexpr auto duration = TickClock::duration{11}; if (softwareTimer.isRunning() != false || value != 0) // initially must be stopped and must not execute return false; waitForNextTick(); if (softwareTimer.start(duration) != 0) return false; if (softwareTimer.isRunning() != true || value != 0) // must be started, but may not execute yet return false; if (softwareTimer.stop() != 0) return false; if (softwareTimer.isRunning() != false || value != 0) // must be stopped, must not execute return false; ThisThread::sleepFor(duration * 2); if (softwareTimer.isRunning() != false || value != 0) // make sure it did not execute return false; } { constexpr auto duration = TickClock::duration{9}; waitForNextTick(); if (softwareTimer.start(duration) != 0) return false; if (softwareTimer.isRunning() != true || value != 0) // must be started, but may not execute yet return false; const auto start = TickClock::now(); while (softwareTimer.isRunning() == true); // must be stopped, function must be executed, real duration must equal what is expected if (softwareTimer.isRunning() != false || value != 1 || TickClock::now() - start != duration + decltype(duration){1}) return false; } { waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{13}; if (softwareTimer.start(wakeUpTimePoint) != 0) return false; if (softwareTimer.isRunning() != true || value != 1) // must be started, but may not execute yet return false; while (softwareTimer.isRunning() == true); // must be stopped, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != false || value != 2 || TickClock::now() != wakeUpTimePoint) return false; } { constexpr auto period = TickClock::duration{6}; waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{17}; if (softwareTimer.start(wakeUpTimePoint, period) != 0) return false; if (softwareTimer.isRunning() != true || value != 2) // must be started, but may not execute yet return false; for (size_t iteration {}; iteration < 4; ++iteration) { while (softwareTimer.isRunning() == true && value == 2 + iteration); // must be still running, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != true || value != 3 + iteration || TickClock::now() != wakeUpTimePoint + period * iteration) return false; } if (softwareTimer.stop() != 0) return false; if (softwareTimer.isRunning() != false || value != 6) // must be stopped return false; ThisThread::sleepFor(period * 2); if (softwareTimer.isRunning() != false || value != 6) // make sure it did not execute again return false; } { // restart one-shot into one-shot for (size_t iteration {}; iteration < 4; ++iteration) { constexpr auto duration = TickClock::duration{15}; const auto wakeUpTimePoint = TickClock::now() + duration; if (softwareTimer.start(wakeUpTimePoint) != 0) return false; if (softwareTimer.isRunning() != true || value != 6) // must be started, but may not execute yet return false; ThisThread::sleepUntil(wakeUpTimePoint - duration / 2); if (softwareTimer.isRunning() != true || value != 6) // must be started, but may not execute yet return false; } // restart one-shot into periodic, then periodic into periodic for (size_t iteration {}; iteration < 4; ++iteration) { constexpr auto delay = TickClock::duration{12}; const auto wakeUpTimePoint = TickClock::now() + delay; if (softwareTimer.start(wakeUpTimePoint, TickClock::duration{10}) != 0) return false; if (softwareTimer.isRunning() != true || value != 6) // must be started, but may not execute yet return false; ThisThread::sleepUntil(wakeUpTimePoint - delay / 2); if (softwareTimer.isRunning() != true || value != 6) // must be started, but may not execute yet return false; } // restart periodic into periodic { constexpr auto period = TickClock::duration{19}; waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{14}; if (softwareTimer.start(wakeUpTimePoint, period) != 0) return false; if (softwareTimer.isRunning() != true || value != 6) // must be started, but may not execute yet return false; for (size_t iteration {}; iteration < 4; ++iteration) { while (softwareTimer.isRunning() == true && value == 6 + iteration); // must be still running, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != true || value != 7 + iteration || TickClock::now() != wakeUpTimePoint + period * iteration) return false; } } // restart periodic into periodic with different settings { constexpr auto period = TickClock::duration{7}; waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{5}; if (softwareTimer.start(wakeUpTimePoint, period) != 0) return false; if (softwareTimer.isRunning() != true || value != 10) // must be started, but may not execute yet return false; for (size_t iteration {}; iteration < 4; ++iteration) { while (softwareTimer.isRunning() == true && value == 10 + iteration); // must be still running, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != true || value != 11 + iteration || TickClock::now() != wakeUpTimePoint + period * iteration) return false; } } // restart periodic into one-shot waitForNextTick(); const auto wakeUpTimePoint = TickClock::now() + TickClock::duration{16}; if (softwareTimer.start(wakeUpTimePoint) != 0) return false; if (softwareTimer.isRunning() != true || value != 14) // must be started, but may not execute yet return false; while (softwareTimer.isRunning() == true); // must be stopped, function must be executed, wake up time point must equal what is expected if (softwareTimer.isRunning() != false || value != 15 || TickClock::now() != wakeUpTimePoint) return false; } return true; } } // namespace test } // namespace distortos <|endoftext|>
<commit_before>#include <jni.h> #include "AppDelegate.hpp" namespace { std::unique_ptr<eetest::AppDelegate> appDelegate; } // namespace void cocos_android_app_init(JNIEnv* env) { appDelegate.reset(new eetest::AppDelegate()); } <commit_msg>Use std::make_unique.<commit_after>#include <jni.h> #include "AppDelegate.hpp" namespace { std::unique_ptr<eetest::AppDelegate> appDelegate; } // namespace void cocos_android_app_init(JNIEnv* env) { appDelegate = std::make_unique<eetest::AppDelegate>(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkVeloViewQuaternionInterpolator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkVeloViewQuaternion.h" #include "vtkVeloViewQuaternionInterpolator.h" #include <vector> vtkStandardNewMacro(vtkVeloViewQuaternionInterpolator); //---------------------------------------------------------------------------- // PIMPL STL encapsulation for list of quaternions. The list is sorted on // the spline parameter T (or Time) using a STL list. // Here we define a quaternion class that includes extra information including // a unit quaternion representation. struct TimedQuaternion { double Time; vtkVeloViewQuaterniond Q; //VTK's quaternion: unit rotation axis with angles in degrees TimedQuaternion() : Q(0.0) { this->Time = 0.0; } TimedQuaternion(double t, vtkVeloViewQuaterniond q) { this->Time = t; this->Q = q; } }; // The list is arranged in increasing order in T class vtkVeloViewQuaternionList : public std::vector<TimedQuaternion> {}; typedef vtkVeloViewQuaternionList::iterator QuaternionListIterator; //---------------------------------------------------------------------------- vtkVeloViewQuaternionInterpolator::vtkVeloViewQuaternionInterpolator() { // Set up the interpolation this->QuaternionList = new vtkVeloViewQuaternionList; this->InterpolationType = INTERPOLATION_TYPE_SPLINE; } //---------------------------------------------------------------------------- vtkVeloViewQuaternionInterpolator::~vtkVeloViewQuaternionInterpolator() { this->Initialize(); delete this->QuaternionList; } //---------------------------------------------------------------------------- int vtkVeloViewQuaternionInterpolator::GetNumberOfQuaternions() { return static_cast<int>(this->QuaternionList->size()); } //---------------------------------------------------------------------------- double vtkVeloViewQuaternionInterpolator::GetMinimumT() { if (this->QuaternionList->size() > 0) { return this->QuaternionList->front().Time; } else { return 0.0; } } //---------------------------------------------------------------------------- double vtkVeloViewQuaternionInterpolator::GetMaximumT() { if (this->QuaternionList->size() > 0) { return this->QuaternionList->back().Time; } else { return 0.0; } } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::Initialize() { // Wipe out old data this->QuaternionList->clear(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::AddQuaternion(double t, double q[4]) { vtkVeloViewQuaterniond quat(q); this->AddQuaternion(t, quat); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::AddQuaternion(double t, const vtkVeloViewQuaterniond& q) { int size = static_cast<int>(this->QuaternionList->size()); // Check special cases: t at beginning or end of list if ( size <= 0 || t < this->QuaternionList->front().Time ) { this->QuaternionList->insert(this->QuaternionList->begin(),TimedQuaternion(t,q)); return; } else if ( t > this->QuaternionList->back().Time ) { this->QuaternionList->push_back(TimedQuaternion(t,q)); return; } else if ( size == 1 && t == this->QuaternionList->front().Time ) { this->QuaternionList->front() = TimedQuaternion(t,q); return; } // Okay, insert in sorted order QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; for (int i=0; i < (size-1); i++, ++iter, ++nextIter) { if ( t == iter->Time ) { (*iter) = TimedQuaternion(t,q); //overwrite break; } else if ( t > iter->Time && t < nextIter->Time ) { this->QuaternionList->insert(nextIter, TimedQuaternion(t,q)); break; } }//for not in the right spot this->Modified(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::RemoveQuaternion(double t) { if ( t < this->QuaternionList->front().Time || t > this->QuaternionList->back().Time ) { return; } QuaternionListIterator iter = this->QuaternionList->begin(); for ( ; iter->Time != t && iter != this->QuaternionList->end(); ++iter ) { } if ( iter != this->QuaternionList->end() ) { this->QuaternionList->erase(iter); } this->Modified(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::InterpolateQuaternion(double t, double q[4]) { vtkVeloViewQuaterniond quat(q); this->InterpolateQuaternion(t, quat); for (int i = 0; i < 4; ++i) { q[i] = quat[i]; } } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::InterpolateQuaternion(double t, vtkVeloViewQuaterniond& q) { // The quaternion may be clamped if it is outside the range specified if ( t <= this->QuaternionList->front().Time ) { TimedQuaternion &Q = this->QuaternionList->front(); q = Q.Q; return; } else if ( t >= this->QuaternionList->back().Time ) { TimedQuaternion &Q = this->QuaternionList->front(); q = Q.Q; return; } // Depending on the interpolation type we do the right thing. // The code above guarantees that there are at least two quaternions defined. int numQuats = this->GetNumberOfQuaternions(); if ( this->InterpolationType == INTERPOLATION_TYPE_LINEAR || numQuats < 3 ) { QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; for ( ; nextIter != this->QuaternionList->end(); ++iter, ++nextIter) { if ( iter->Time <= t && t <= nextIter->Time ) { double T = (t - iter->Time) / (nextIter->Time - iter->Time); q = iter->Q.Slerp(T,nextIter->Q); break; } } }//if linear quaternion interpolation else // this->InterpolationType == INTERPOLATION_TYPE_SPLINE { QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; QuaternionListIterator iter0, iter1, iter2, iter3; //find the interval double T=0.0; int i; for (i=0; nextIter != this->QuaternionList->end(); ++iter, ++nextIter, ++i) { if ( iter->Time <= t && t <= nextIter->Time ) { T = (t - iter->Time) / (nextIter->Time - iter->Time); break; } } vtkVeloViewQuaterniond ai, bi, qc, qd; if ( i == 0 ) //initial interval { iter1 = iter; iter2 = nextIter; iter3 = nextIter + 1; ai = iter1->Q.Normalized(); //just duplicate first quaternion vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); bi = q1.InnerPoint(iter2->Q.Normalized(), iter3->Q.Normalized()); } else if ( i == (numQuats-2) ) //final interval { iter0 = iter - 1; iter1 = iter; iter2 = nextIter; vtkVeloViewQuaterniond q0 = iter0->Q.Normalized(); ai = q0.InnerPoint(iter1->Q.Normalized(), iter2->Q.Normalized()); bi = iter2->Q.Normalized(); //just duplicate last quaternion } else //in a middle interval somewhere { iter0 = iter - 1; iter1 = iter; iter2 = nextIter; iter3 = nextIter + 1; vtkVeloViewQuaterniond q0 = iter0->Q.Normalized(); ai = q0.InnerPoint(iter1->Q.Normalized(), iter2->Q.Normalized()); vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); bi = q1.InnerPoint(iter2->Q.Normalized(), iter3->Q.Normalized()); } // These three Slerp operations implement a Squad interpolation vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); qc = q1.Slerp(T,iter2->Q.Normalized()); qd = ai.Slerp(T,bi); q = qc.Slerp(2.0*T*(1.0-T),qd); q.NormalizeWithAngleInDegrees(); } return; } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "QuaternionList: " << this->QuaternionList->size() << " quaternions to interpolate\n"; os << indent << "InterpolationType: " << (this->InterpolationType == INTERPOLATION_TYPE_LINEAR ? "Linear\n" : "Spline\n"); } <commit_msg>Bug fix: wrong clamping in quaternion interpolator<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkVeloViewQuaternionInterpolator.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkMath.h" #include "vtkObjectFactory.h" #include "vtkVeloViewQuaternion.h" #include "vtkVeloViewQuaternionInterpolator.h" #include <vector> vtkStandardNewMacro(vtkVeloViewQuaternionInterpolator); //---------------------------------------------------------------------------- // PIMPL STL encapsulation for list of quaternions. The list is sorted on // the spline parameter T (or Time) using a STL list. // Here we define a quaternion class that includes extra information including // a unit quaternion representation. struct TimedQuaternion { double Time; vtkVeloViewQuaterniond Q; //VTK's quaternion: unit rotation axis with angles in degrees TimedQuaternion() : Q(0.0) { this->Time = 0.0; } TimedQuaternion(double t, vtkVeloViewQuaterniond q) { this->Time = t; this->Q = q; } }; // The list is arranged in increasing order in T class vtkVeloViewQuaternionList : public std::vector<TimedQuaternion> {}; typedef vtkVeloViewQuaternionList::iterator QuaternionListIterator; //---------------------------------------------------------------------------- vtkVeloViewQuaternionInterpolator::vtkVeloViewQuaternionInterpolator() { // Set up the interpolation this->QuaternionList = new vtkVeloViewQuaternionList; this->InterpolationType = INTERPOLATION_TYPE_SPLINE; } //---------------------------------------------------------------------------- vtkVeloViewQuaternionInterpolator::~vtkVeloViewQuaternionInterpolator() { this->Initialize(); delete this->QuaternionList; } //---------------------------------------------------------------------------- int vtkVeloViewQuaternionInterpolator::GetNumberOfQuaternions() { return static_cast<int>(this->QuaternionList->size()); } //---------------------------------------------------------------------------- double vtkVeloViewQuaternionInterpolator::GetMinimumT() { if (this->QuaternionList->size() > 0) { return this->QuaternionList->front().Time; } else { return 0.0; } } //---------------------------------------------------------------------------- double vtkVeloViewQuaternionInterpolator::GetMaximumT() { if (this->QuaternionList->size() > 0) { return this->QuaternionList->back().Time; } else { return 0.0; } } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::Initialize() { // Wipe out old data this->QuaternionList->clear(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::AddQuaternion(double t, double q[4]) { vtkVeloViewQuaterniond quat(q); this->AddQuaternion(t, quat); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::AddQuaternion(double t, const vtkVeloViewQuaterniond& q) { int size = static_cast<int>(this->QuaternionList->size()); // Check special cases: t at beginning or end of list if ( size <= 0 || t < this->QuaternionList->front().Time ) { this->QuaternionList->insert(this->QuaternionList->begin(),TimedQuaternion(t,q)); return; } else if ( t > this->QuaternionList->back().Time ) { this->QuaternionList->push_back(TimedQuaternion(t,q)); return; } else if ( size == 1 && t == this->QuaternionList->front().Time ) { this->QuaternionList->front() = TimedQuaternion(t,q); return; } // Okay, insert in sorted order QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; for (int i=0; i < (size-1); i++, ++iter, ++nextIter) { if ( t == iter->Time ) { (*iter) = TimedQuaternion(t,q); //overwrite break; } else if ( t > iter->Time && t < nextIter->Time ) { this->QuaternionList->insert(nextIter, TimedQuaternion(t,q)); break; } }//for not in the right spot this->Modified(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::RemoveQuaternion(double t) { if ( t < this->QuaternionList->front().Time || t > this->QuaternionList->back().Time ) { return; } QuaternionListIterator iter = this->QuaternionList->begin(); for ( ; iter->Time != t && iter != this->QuaternionList->end(); ++iter ) { } if ( iter != this->QuaternionList->end() ) { this->QuaternionList->erase(iter); } this->Modified(); } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::InterpolateQuaternion(double t, double q[4]) { vtkVeloViewQuaterniond quat(q); this->InterpolateQuaternion(t, quat); for (int i = 0; i < 4; ++i) { q[i] = quat[i]; } } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::InterpolateQuaternion(double t, vtkVeloViewQuaterniond& q) { // The quaternion may be clamped if it is outside the range specified if ( t <= this->QuaternionList->front().Time ) { TimedQuaternion &Q = this->QuaternionList->front(); q = Q.Q; return; } else if ( t >= this->QuaternionList->back().Time ) { TimedQuaternion &Q = this->QuaternionList->back(); q = Q.Q; return; } // Depending on the interpolation type we do the right thing. // The code above guarantees that there are at least two quaternions defined. int numQuats = this->GetNumberOfQuaternions(); if ( this->InterpolationType == INTERPOLATION_TYPE_LINEAR || numQuats < 3 ) { QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; for ( ; nextIter != this->QuaternionList->end(); ++iter, ++nextIter) { if ( iter->Time <= t && t <= nextIter->Time ) { double T = (t - iter->Time) / (nextIter->Time - iter->Time); q = iter->Q.Slerp(T,nextIter->Q); break; } } }//if linear quaternion interpolation else // this->InterpolationType == INTERPOLATION_TYPE_SPLINE { QuaternionListIterator iter = this->QuaternionList->begin(); QuaternionListIterator nextIter = iter + 1; QuaternionListIterator iter0, iter1, iter2, iter3; //find the interval double T=0.0; int i; for (i=0; nextIter != this->QuaternionList->end(); ++iter, ++nextIter, ++i) { if ( iter->Time <= t && t <= nextIter->Time ) { T = (t - iter->Time) / (nextIter->Time - iter->Time); break; } } vtkVeloViewQuaterniond ai, bi, qc, qd; if ( i == 0 ) //initial interval { iter1 = iter; iter2 = nextIter; iter3 = nextIter + 1; ai = iter1->Q.Normalized(); //just duplicate first quaternion vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); bi = q1.InnerPoint(iter2->Q.Normalized(), iter3->Q.Normalized()); } else if ( i == (numQuats-2) ) //final interval { iter0 = iter - 1; iter1 = iter; iter2 = nextIter; vtkVeloViewQuaterniond q0 = iter0->Q.Normalized(); ai = q0.InnerPoint(iter1->Q.Normalized(), iter2->Q.Normalized()); bi = iter2->Q.Normalized(); //just duplicate last quaternion } else //in a middle interval somewhere { iter0 = iter - 1; iter1 = iter; iter2 = nextIter; iter3 = nextIter + 1; vtkVeloViewQuaterniond q0 = iter0->Q.Normalized(); ai = q0.InnerPoint(iter1->Q.Normalized(), iter2->Q.Normalized()); vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); bi = q1.InnerPoint(iter2->Q.Normalized(), iter3->Q.Normalized()); } // These three Slerp operations implement a Squad interpolation vtkVeloViewQuaterniond q1 = iter1->Q.Normalized(); qc = q1.Slerp(T,iter2->Q.Normalized()); qd = ai.Slerp(T,bi); q = qc.Slerp(2.0*T*(1.0-T),qd); q.NormalizeWithAngleInDegrees(); } return; } //---------------------------------------------------------------------------- void vtkVeloViewQuaternionInterpolator::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "QuaternionList: " << this->QuaternionList->size() << " quaternions to interpolate\n"; os << indent << "InterpolationType: " << (this->InterpolationType == INTERPOLATION_TYPE_LINEAR ? "Linear\n" : "Spline\n"); } <|endoftext|>
<commit_before>/* Sirikata Utilities -- Math Library * Vector4.hpp * * Copyright (c) 2009, Daniel Reiter Horn * 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 Sirikata 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. */ #ifndef _SIRIKATA_VECTOR4_HPP_ #define _SIRIKATA_VECTOR4_HPP_ #include <string> #include <cassert> #include <sstream> namespace Sirikata { template <typename scalar> class Vector3; template <typename scalar> class Vector4 { public: static const unsigned char size = 4; typedef scalar real; union { struct { scalar x; scalar y; scalar z; scalar w; }; scalar v[4]; }; Vector4(scalar x, scalar y, scalar z, scalar w) { this->x=x; this->y=y; this->z=z; this->w=w; } Vector4(){} Vector4(const Vector3<scalar>& xyz, scalar w) { this->x = xyz.x; this->y = xyz.y; this->z = xyz.z; this->w = w; } template<class T>T convert(const T*ptr=NULL) const{ return T(x,y,z,w); } template<class T> Vector4<T> downCast() const{ return Vector4<T>((T)x,(T)y,(T)z,(T)w); } template <class V> static Vector4 fromArray(const V&other){ return Vector4(other[0],other[1],other[2],other[3]); } template <class V> static Vector4 fromSSE(const V&other){ return Vector4(other.x(),other.y(),other.z(),other.w()); } scalar&operator[](const unsigned int i) { assert(i<4); return v[i]; } scalar operator[](const unsigned int i) const{ assert(i<4); return v[i]; } Vector4&operator=(scalar other) { x=other; y=other; z=other; w=other; return *this; } static Vector4 zero() { return Vector4(0,0,0,0); } static Vector4 unitX() { return Vector4(1,0,0,0); } static Vector4 unitY() { return Vector4(0,1,0,0); } static Vector4 unitZ() { return Vector4(0,0,1,0); } static Vector4 unitNegX() { return Vector4(-1,0,0,0); } static Vector4 unitNegY() { return Vector4(0,-1,0,0); } static Vector4 unitNegZ() { return Vector4(0,0,-1,0); } Vector4 operator*(scalar scale) const { return Vector4(x*scale,y*scale,z*scale,w*scale); } Vector4 operator/(scalar scale) const { return Vector4(x/scale,y/scale,z/scale,w/scale); } Vector4 operator+(const Vector4&other) const { return Vector4(x+other.x,y+other.y,z+other.z,w+other.w); } Vector4 operator-(const Vector4&other) const { return Vector4(x-other.x,y-other.y,z-other.z,w-other.w); } Vector4 operator-() const { return Vector4(-x,-y,-z,-w); } Vector4& operator*=(scalar scale) { x*=scale; y*=scale; z*=scale; w*=scale; return *this; } Vector4& operator/=(scalar scale) { x/=scale; y/=scale; z/=scale; w/=scale; return *this; } Vector4& operator+=(const Vector4& other) { x+=other.x; y+=other.y; z+=other.z; w+=other.w; return *this; } Vector4& operator-=(const Vector4& other) { x-=other.x; y-=other.y; z-=other.z; w-=other.w; return *this; } Vector4 componentMultiply(const Vector4&other) const { return Vector4(x*other.x,y*other.y,z*other.z,w*other.w); } scalar dot(const Vector4 &other) const{ return x*other.x+y*other.y+z*other.z+w*other.w; } Vector4 min(const Vector4&other)const { return Vector4(other.x<x?other.x:x, other.y<y?other.y:y, other.z<z?other.z:z, other.w<w?other.w:w); } Vector4 max(const Vector4&other)const { return Vector4(other.x>x?other.x:x, other.y>y?other.y:y, other.z>z?other.z:z, other.w>w?other.w:w); } scalar lengthSquared()const { return dot(*this); } scalar length()const { return (scalar)sqrt(dot(*this)); } bool operator==(const Vector4&other)const { return x==other.x&&y==other.y&&z==other.z&&w==other.w; } bool operator!=(const Vector4&other)const { return x!=other.x||y!=other.y||z!=other.z||w!=other.w; } Vector4 normal()const { scalar len=length(); if (len>1e-08) return *this/len; return *this; } scalar normalizeThis() { scalar len=length(); if (len>1e-08) *this/=len; return len; } std::string toString()const { std::ostringstream os; os<<'<'<<x<<","<<y<<","<<z<<","<<w<<'>'; return os.str(); } }; template<typename scalar> inline Vector4<scalar> operator *(scalar lhs, const Vector4<scalar> &rhs) { return Vector4<scalar>(lhs*rhs.x,lhs*rhs.y,lhs*rhs.z,lhs*rhs.w); } template<typename scalar> inline Vector4<scalar> operator /(scalar lhs, const Vector4<scalar> &rhs) { return Vector4<scalar>(lhs/rhs.x,lhs/rhs.y,lhs/rhs.z,lhs/rhs.w); } template<typename scalar> inline std::ostream& operator <<(std::ostream& os, const Vector4<scalar> &rhs) { os<<'<'<<rhs.x<<","<<rhs.y<<","<<rhs.z<<","<<rhs.w<<'>'; return os; } template<typename scalar> inline std::istream& operator >>(std::istream& is, Vector4<scalar> &rhs) { // FIXME this should be more robust. It currently relies on the exact format provided by operator << char dummy; is >> dummy >> rhs.x >> dummy >> rhs.y >> dummy >> rhs.z >> dummy >> rhs.w >> dummy; return is; } } #endif //_SIRIKATA_VECTOR4_HPP_ <commit_msg>hash function for vector4's<commit_after>/* Sirikata Utilities -- Math Library * Vector4.hpp * * Copyright (c) 2009, Daniel Reiter Horn * 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 Sirikata 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. */ #ifndef _SIRIKATA_VECTOR4_HPP_ #define _SIRIKATA_VECTOR4_HPP_ #include <string> #include <cassert> #include <sstream> namespace Sirikata { template <typename scalar> class Vector3; template <typename scalar> class Vector4 { public: static const unsigned char size = 4; typedef scalar real; union { struct { scalar x; scalar y; scalar z; scalar w; }; scalar v[4]; }; Vector4(scalar x, scalar y, scalar z, scalar w) { this->x=x; this->y=y; this->z=z; this->w=w; } Vector4(){} Vector4(const Vector3<scalar>& xyz, scalar w) { this->x = xyz.x; this->y = xyz.y; this->z = xyz.z; this->w = w; } template<class T>T convert(const T*ptr=NULL) const{ return T(x,y,z,w); } template<class T> Vector4<T> downCast() const{ return Vector4<T>((T)x,(T)y,(T)z,(T)w); } template <class V> static Vector4 fromArray(const V&other){ return Vector4(other[0],other[1],other[2],other[3]); } template <class V> static Vector4 fromSSE(const V&other){ return Vector4(other.x(),other.y(),other.z(),other.w()); } scalar&operator[](const unsigned int i) { assert(i<4); return v[i]; } scalar operator[](const unsigned int i) const{ assert(i<4); return v[i]; } Vector4&operator=(scalar other) { x=other; y=other; z=other; w=other; return *this; } static Vector4 zero() { return Vector4(0,0,0,0); } static Vector4 unitX() { return Vector4(1,0,0,0); } static Vector4 unitY() { return Vector4(0,1,0,0); } static Vector4 unitZ() { return Vector4(0,0,1,0); } static Vector4 unitNegX() { return Vector4(-1,0,0,0); } static Vector4 unitNegY() { return Vector4(0,-1,0,0); } static Vector4 unitNegZ() { return Vector4(0,0,-1,0); } Vector4 operator*(scalar scale) const { return Vector4(x*scale,y*scale,z*scale,w*scale); } Vector4 operator/(scalar scale) const { return Vector4(x/scale,y/scale,z/scale,w/scale); } Vector4 operator+(const Vector4&other) const { return Vector4(x+other.x,y+other.y,z+other.z,w+other.w); } Vector4 operator-(const Vector4&other) const { return Vector4(x-other.x,y-other.y,z-other.z,w-other.w); } Vector4 operator-() const { return Vector4(-x,-y,-z,-w); } Vector4& operator*=(scalar scale) { x*=scale; y*=scale; z*=scale; w*=scale; return *this; } Vector4& operator/=(scalar scale) { x/=scale; y/=scale; z/=scale; w/=scale; return *this; } Vector4& operator+=(const Vector4& other) { x+=other.x; y+=other.y; z+=other.z; w+=other.w; return *this; } Vector4& operator-=(const Vector4& other) { x-=other.x; y-=other.y; z-=other.z; w-=other.w; return *this; } Vector4 componentMultiply(const Vector4&other) const { return Vector4(x*other.x,y*other.y,z*other.z,w*other.w); } scalar dot(const Vector4 &other) const{ return x*other.x+y*other.y+z*other.z+w*other.w; } Vector4 min(const Vector4&other)const { return Vector4(other.x<x?other.x:x, other.y<y?other.y:y, other.z<z?other.z:z, other.w<w?other.w:w); } Vector4 max(const Vector4&other)const { return Vector4(other.x>x?other.x:x, other.y>y?other.y:y, other.z>z?other.z:z, other.w>w?other.w:w); } scalar lengthSquared()const { return dot(*this); } scalar length()const { return (scalar)sqrt(dot(*this)); } bool operator==(const Vector4&other)const { return x==other.x&&y==other.y&&z==other.z&&w==other.w; } bool operator!=(const Vector4&other)const { return x!=other.x||y!=other.y||z!=other.z||w!=other.w; } Vector4 normal()const { scalar len=length(); if (len>1e-08) return *this/len; return *this; } scalar normalizeThis() { scalar len=length(); if (len>1e-08) *this/=len; return len; } std::string toString()const { std::ostringstream os; os<<'<'<<x<<","<<y<<","<<z<<","<<w<<'>'; return os.str(); } size_t hash() const { size_t seed = 0; boost::hash_combine(seed, x); boost::hash_combine(seed, y); boost::hash_combine(seed, z); boost::hash_combine(seed, w); return seed; } class Hasher{public: size_t operator() (const Vector4 &v) const { return v.hash(); } }; }; template<typename scalar> inline Vector4<scalar> operator *(scalar lhs, const Vector4<scalar> &rhs) { return Vector4<scalar>(lhs*rhs.x,lhs*rhs.y,lhs*rhs.z,lhs*rhs.w); } template<typename scalar> inline Vector4<scalar> operator /(scalar lhs, const Vector4<scalar> &rhs) { return Vector4<scalar>(lhs/rhs.x,lhs/rhs.y,lhs/rhs.z,lhs/rhs.w); } template<typename scalar> inline std::ostream& operator <<(std::ostream& os, const Vector4<scalar> &rhs) { os<<'<'<<rhs.x<<","<<rhs.y<<","<<rhs.z<<","<<rhs.w<<'>'; return os; } template<typename scalar> inline std::istream& operator >>(std::istream& is, Vector4<scalar> &rhs) { // FIXME this should be more robust. It currently relies on the exact format provided by operator << char dummy; is >> dummy >> rhs.x >> dummy >> rhs.y >> dummy >> rhs.z >> dummy >> rhs.w >> dummy; return is; } } #endif //_SIRIKATA_VECTOR4_HPP_ <|endoftext|>
<commit_before>#include "htool/cluster.hpp" using namespace std; using namespace htool; int main(int argc, char const *argv[]) { SetMinClusterSize(1); bool test =0; int n1 = 5; int n2 = 5; int nr = n1+n2; double z = 1; vector<R3> p(nr); vector<int> tab(nr); for(int j=0; j<n1; j++){ double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division! double theta = ((double) rand() / (double)(RAND_MAX)); p[j][0] = sqrt(rho)*cos(2*M_PI*theta); p[j][1] = sqrt(rho)*sin(2*M_PI*theta); p[j][2] = z; // sqrt(rho) otherwise the points would be concentrated in the center of the disk tab[j]=j; } double dist = 5; for(int j=n1; j<nr; j++){ double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division! double theta = ((double) rand() / (double)(RAND_MAX)); p[j][0] = sqrt(rho)*cos(2*M_PI*theta); p[j][1] = sqrt(rho)*sin(2*M_PI*theta); p[j][2] = z + dist; // sqrt(rho) otherwise the points would be concentrated in the center of the disk tab[j]=j; } Cluster t(p,tab); t.build(); // Test Cluster* s = &t; int depth =0; while (s!=NULL){ // test depth test = test || !((*s).get_depth()==depth); depth+=1; if ((*s).IsLeaf()){ s=NULL; } else{ // test num inclusion if (!((*s).get_son(0).IsLeaf()) && !((*s).get_son(1).IsLeaf())){ std::vector<int> root = (*s).get_num(); std::vector<int> son0 = (*s).get_son(0).get_num(); std::vector<int> son1 = (*s).get_son(1).get_num(); for (int i=0;i<root.size();i++){ int count0 = count(son0.begin(),son0.end(),root[i]); int count1 = count(son1.begin(),son1.end(),root[i]); test = test || !((count0==0 && count1==1) || (count0==1 && count1==0) ); } } s=&((*s).get_son(0)); } } cout<<"max depth : "<<t.get_max_depth()<<endl; cout<<"min depth : "<<t.get_min_depth()<<endl; test = test || !(t.get_max_depth()==4 && t.get_min_depth()==3); t.print(); return test; } <commit_msg>offsets added<commit_after>#include "htool/cluster.hpp" using namespace std; using namespace htool; int main(int argc, char const *argv[]) { SetMinClusterSize(1); bool test =0; int n1 = 5; int n2 = 5; int nr = n1+n2; double z = 1; vector<R3> p(nr); vector<int> tab(nr); for(int j=0; j<n1; j++){ double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division! double theta = ((double) rand() / (double)(RAND_MAX)); p[j][0] = sqrt(rho)*cos(2*M_PI*theta); p[j][1] = sqrt(rho)*sin(2*M_PI*theta); p[j][2] = z; // sqrt(rho) otherwise the points would be concentrated in the center of the disk tab[j]=j; } double dist = 5; for(int j=n1; j<nr; j++){ double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division! double theta = ((double) rand() / (double)(RAND_MAX)); p[j][0] = sqrt(rho)*cos(2*M_PI*theta); p[j][1] = sqrt(rho)*sin(2*M_PI*theta); p[j][2] = z + dist; // sqrt(rho) otherwise the points would be concentrated in the center of the disk tab[j]=j; } Cluster t(p,tab); t.build(); // Test Cluster* s = &t; int depth =0; while (s!=NULL){ // test depth test = test || !((*s).get_depth()==depth); depth+=1; if ((*s).IsLeaf()){ s=NULL; } else{ // test num inclusion if (!((*s).get_son(0).IsLeaf()) && !((*s).get_son(1).IsLeaf())){ std::vector<int> root = (*s).get_num(); std::vector<int> son0 = (*s).get_son(0).get_num(); std::vector<int> son1 = (*s).get_son(1).get_num(); for (int i=0;i<root.size();i++){ int count0 = count(son0.begin(),son0.end(),root[i]); int count1 = count(son1.begin(),son1.end(),root[i]); test = test || !((count0==0 && count1==1) || (count0==1 && count1==0) ); } } s=&((*s).get_son(0)); } } cout<<"max depth : "<<t.get_max_depth()<<endl; cout<<"min depth : "<<t.get_min_depth()<<endl; test = test || !(t.get_max_depth()==4 && t.get_min_depth()==3); t.print_offset(); return test; } <|endoftext|>
<commit_before>#include "downloader/image-downloader.h" #include <QImageReader> #include <QSettings> #include <QSize> #include <QUuid> #include "extension-rotator.h" #include "file-downloader.h" #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/filename.h" #include "models/image.h" #include "models/profile.h" #include "models/site.h" #include "models/source.h" static void addMd5(Profile *profile, const QString &path) { QCryptographicHash hash(QCryptographicHash::Md5); QFile f(path); f.open(QFile::ReadOnly); hash.addData(&f); f.close(); profile->addMd5(hash.result().toHex(), path); } ImageDownloader::ImageDownloader(Profile *profile, QSharedPointer<Image> img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate, bool force, Image::Size size) : QObject(parent), m_profile(profile), m_image(std::move(img)), m_fileDownloader(false, this), m_filename(std::move(filename)), m_path(std::move(path)), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) { setSize(size); } ImageDownloader::ImageDownloader(Profile *profile, QSharedPointer<Image> img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate, bool force, Image::Size size) : QObject(parent), m_profile(profile), m_image(std::move(img)), m_fileDownloader(false, this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) { setSize(size); } ImageDownloader::~ImageDownloader() { if (m_reply != nullptr) { m_reply->deleteLater(); } } bool ImageDownloader::isRunning() const { return m_reply != nullptr && m_reply->isRunning(); } void ImageDownloader::setSize(Image::Size size) { if (size == Image::Size::Unknown) { const bool getOriginals = m_profile->getSettings()->value("Save/downloadoriginals", true).toBool(); const bool hasSample = m_image->url(Image::Size::Sample).isEmpty(); if (getOriginals || !hasSample) { m_size = Image::Size::Full; } else { m_size = Image::Size::Sample; } } else { m_size = size; } } void ImageDownloader::setBlacklist(Blacklist *blacklist) { m_blacklist = blacklist; } void ImageDownloader::save() { // Always load details if the API doesn't provide the file URL in the listing page const QStringList forcedTokens = m_image->parentSite()->getApis().first()->forcedTokens(); const bool needFileUrl = forcedTokens.contains("*") || forcedTokens.contains("file_url"); // If we use direct saving or don't want to load tags, we directly save the image const int globalNeedTags = needExactTags(m_profile->getSettings()); const int localNeedTags = m_filename.needExactTags(m_image->parentSite()); const int needTags = qMax(globalNeedTags, localNeedTags); const bool filenameNeedTags = needTags == 2 || (needTags == 1 && m_image->hasUnknownTag()); const bool blacklistNeedTags = m_blacklist != nullptr && m_image->tags().isEmpty(); if (!blacklistNeedTags && !needFileUrl && (!m_loadTags || !m_paths.isEmpty() || !filenameNeedTags)) { loadedSave(); return; } connect(m_image.data(), &Image::finishedLoadingTags, this, &ImageDownloader::loadedSave); m_image->loadDetails(); } int ImageDownloader::needExactTags(QSettings *settings) const { int need = 0; const auto logFiles = getExternalLogFiles(settings); for (auto it = logFiles.constBegin(); it != logFiles.constEnd(); ++it) { need = qMax(need, Filename(it.value().value("content").toString()).needExactTags()); if (need == 2) { return need; } } QStringList settingNames = QStringList() << "Exec/tag_before" << "Exec/image" << "Exec/tag_after" << "Exec/SQL/before" << "Exec/SQL/tag_before" << "Exec/SQL/image" << "Exec/SQL/tag_after" << "Exec/SQL/after"; for (const QString &setting : settingNames) { const QString value = settings->value(setting, "").toString(); if (value.isEmpty()) { continue; } need = qMax(need, Filename(value).needExactTags()); if (need == 2) { return need; } } return need; } void ImageDownloader::abort() { m_image->abortTags(); if (m_reply != nullptr && m_reply->isRunning()) { m_reply->abort(); } } void ImageDownloader::loadedSave() { // Get the download path from the image if possible if (m_paths.isEmpty()) { m_paths = m_image->paths(m_filename, m_path, m_count); // Use a random temporary file if we need the MD5 or equivalent if (m_filename.needTemporaryFile(m_image->tokens(m_profile))) { const QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); m_temporaryPath = tmpDir + "/" + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } } // Directly use the image path as temporary file if possible if (m_temporaryPath.isEmpty()) { m_temporaryPath = m_paths.first() + ".tmp"; } // Check if the image is blacklisted if (m_blacklist != nullptr) { const QStringList &detected = m_blacklist->match(m_image->tokens(m_profile)); if (!detected.isEmpty()) { log(QStringLiteral("Image contains blacklisted tags: '%1'").arg(detected.join("', '")), Logger::Info); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Blacklisted)); return; } } // Try to save the image if it's already loaded or exists somewhere else on disk if (!m_force) { // Check if the destination files already exist bool allExists = true; for (const QString &path : qAsConst(m_paths)) { if (!QFile::exists(path)) { allExists = false; break; } } if (allExists) { log(QStringLiteral("File already exists: `%1`").arg(m_paths.first()), Logger::Info); for (const QString &path : qAsConst(m_paths)) { addMd5(m_profile, path); } emit saved(m_image, makeResult(m_paths, Image::SaveResult::AlreadyExistsDisk)); return; } // If we don't need any loading, we can return already Image::SaveResult res = m_image->preSave(m_temporaryPath, m_size); if (res != Image::SaveResult::NotLoaded) { QList<ImageSaveResult> result {{ m_temporaryPath, m_size, res }}; if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved || res == Image::SaveResult::Linked) { result = postSaving(res); } emit saved(m_image, result); return; } } m_url = m_image->url(m_size); log(QStringLiteral("Loading and saving image from `%1` in `%2`").arg(m_url.toString(), m_paths.first())); loadImage(); } void ImageDownloader::loadImage() { connect(&m_fileDownloader, &FileDownloader::success, this, &ImageDownloader::success, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::networkError, this, &ImageDownloader::networkError, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::writeError, this, &ImageDownloader::writeError, Qt::UniqueConnection); // Delete previous replies for retries if (m_reply != nullptr) { m_reply->deleteLater(); } // Load the image directly on the disk Site *site = m_image->parentSite(); m_reply = site->get(site->fixUrl(m_url.toString()), m_image->page(), QStringLiteral("image"), m_image.data()); m_reply->setParent(this); connect(m_reply, &QNetworkReply::downloadProgress, this, &ImageDownloader::downloadProgressImage); // Create download root directory const QString rootDir = m_temporaryPath.section(QDir::separator(), 0, -2); if (!QDir(rootDir).exists() && !QDir().mkpath(rootDir)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(rootDir), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); return; } // If we can't start writing for some reason, return an error if (!m_fileDownloader.start(m_reply, QStringList() << m_temporaryPath)) { log(QStringLiteral("Unable to open file"), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); return; } } void ImageDownloader::downloadProgressImage(qint64 v1, qint64 v2) { if (m_image->fileSize() == 0 || m_image->fileSize() < v2 / 2) { m_image->setFileSize(v2, currentSize()); } emit downloadProgress(m_image, v1, v2); } Image::Size ImageDownloader::currentSize() const { return m_tryingSample ? Image::Size::Sample : m_size; } QList<ImageSaveResult> ImageDownloader::makeResult(const QStringList &paths, Image::SaveResult result) const { const Image::Size size = currentSize(); QList<ImageSaveResult> res; for (const QString &path : paths) { res.append({ path, size, result }); } return res; } void ImageDownloader::writeError() { emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); } void ImageDownloader::networkError(QNetworkReply::NetworkError error, const QString &msg) { if (error == QNetworkReply::ContentNotFoundError) { QSettings *settings = m_profile->getSettings(); ExtensionRotator *extensionRotator = m_image->extensionRotator(); const bool sampleFallback = settings->value("Save/samplefallback", true).toBool(); const bool shouldFallback = m_size == Image::Size::Full && sampleFallback && !m_image->url(Image::Size::Sample).isEmpty(); QString newext = extensionRotator != nullptr ? extensionRotator->next() : QString(); if (m_rotate && !newext.isEmpty()) { m_url = setExtension(m_image->url(m_size), newext); log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url.toString())); m_image->setUrl(m_url); loadImage(); } else if (shouldFallback && !m_tryingSample) { m_url = m_image->url(Image::Size::Sample); m_tryingSample = true; log(QStringLiteral("Image not found. New try with its sample (%1)...").arg(m_url.toString())); m_image->setUrl(m_url); loadImage(); } else { m_tryingSample = false; log(QStringLiteral("Image not found.")); emit saved(m_image, makeResult(m_paths, Image::SaveResult::NotFound)); } } else if (error != QNetworkReply::OperationCanceledError) { log(QStringLiteral("Network error for the image: `%1`: %2 (%3)").arg(m_image->url().toString().toHtmlEscaped()).arg(error).arg(msg), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::NetworkError)); } } void ImageDownloader::success() { // Handle network redirects QUrl redir = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { m_url = redir; loadImage(); return; } emit saved(m_image, postSaving()); } QList<ImageSaveResult> ImageDownloader::postSaving(Image::SaveResult saveResult) { const QString multipleFiles = m_profile->getSettings()->value("Save/multiple_files", "copy").toString(); const Image::Size size = currentSize(); m_image->setSavePath(m_temporaryPath, size); if (m_image->size(size).isEmpty()) { QImageReader reader(m_temporaryPath); QSize imgSize = reader.size(); if (imgSize.isValid()) { m_image->setSize(imgSize, size); } } if (!m_filename.format().isEmpty()) { m_paths = m_image->paths(m_filename, m_path, m_count); } QString suffix; #ifdef Q_OS_WIN if (saveResult == Image::SaveResult::Linked) { suffix = ".lnk"; } #endif QFile tmp(m_temporaryPath + suffix); bool moved = false; QList<ImageSaveResult> result; for (const QString &file : qAsConst(m_paths)) { const QString path = file + suffix; // Don't overwrite already existing files if (QFile::exists(file) || (!suffix.isEmpty() && QFile::exists(path))) { log(QStringLiteral("File already exists: `%1`").arg(file), Logger::Info); if (suffix.isEmpty()) { addMd5(m_profile, file); } result.append({ path, size, Image::SaveResult::AlreadyExistsDisk }); continue; } if (!moved) { const QString dir = path.section(QDir::separator(), 0, -2); if (!QDir(dir).exists() && !QDir().mkpath(dir)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(dir), Logger::Error); result.append({ path, size, Image::SaveResult::Error }); continue; } tmp.rename(path); moved = true; } else if (multipleFiles == "link") { #ifdef Q_OS_WIN tmp.link(path + ".lnk"); #else tmp.link(path); #endif } else { tmp.copy(path); } result.append({ path, size, saveResult }); m_image->postSave(path, size, saveResult, m_addMd5, m_startCommands, m_count); } if (!moved) { tmp.remove(); } return result; } <commit_msg>Prevent infinite event loops in image downloader (fix #1611)<commit_after>#include "downloader/image-downloader.h" #include <QImageReader> #include <QSettings> #include <QSize> #include <QUuid> #include "extension-rotator.h" #include "file-downloader.h" #include "functions.h" #include "logger.h" #include "models/api/api.h" #include "models/filename.h" #include "models/image.h" #include "models/profile.h" #include "models/site.h" #include "models/source.h" static void addMd5(Profile *profile, const QString &path) { QCryptographicHash hash(QCryptographicHash::Md5); QFile f(path); f.open(QFile::ReadOnly); hash.addData(&f); f.close(); profile->addMd5(hash.result().toHex(), path); } ImageDownloader::ImageDownloader(Profile *profile, QSharedPointer<Image> img, QString filename, QString path, int count, bool addMd5, bool startCommands, QObject *parent, bool loadTags, bool rotate, bool force, Image::Size size) : QObject(parent), m_profile(profile), m_image(std::move(img)), m_fileDownloader(false, this), m_filename(std::move(filename)), m_path(std::move(path)), m_loadTags(loadTags), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) { setSize(size); } ImageDownloader::ImageDownloader(Profile *profile, QSharedPointer<Image> img, QStringList paths, int count, bool addMd5, bool startCommands, QObject *parent, bool rotate, bool force, Image::Size size) : QObject(parent), m_profile(profile), m_image(std::move(img)), m_fileDownloader(false, this), m_loadTags(false), m_paths(std::move(paths)), m_count(count), m_addMd5(addMd5), m_startCommands(startCommands), m_writeError(false), m_rotate(rotate), m_force(force) { setSize(size); } ImageDownloader::~ImageDownloader() { if (m_reply != nullptr) { m_reply->deleteLater(); } } bool ImageDownloader::isRunning() const { return m_reply != nullptr && m_reply->isRunning(); } void ImageDownloader::setSize(Image::Size size) { if (size == Image::Size::Unknown) { const bool getOriginals = m_profile->getSettings()->value("Save/downloadoriginals", true).toBool(); const bool hasSample = m_image->url(Image::Size::Sample).isEmpty(); if (getOriginals || !hasSample) { m_size = Image::Size::Full; } else { m_size = Image::Size::Sample; } } else { m_size = size; } } void ImageDownloader::setBlacklist(Blacklist *blacklist) { m_blacklist = blacklist; } void ImageDownloader::save() { // Always load details if the API doesn't provide the file URL in the listing page const QStringList forcedTokens = m_image->parentSite()->getApis().first()->forcedTokens(); const bool needFileUrl = forcedTokens.contains("*") || forcedTokens.contains("file_url"); // If we use direct saving or don't want to load tags, we directly save the image const int globalNeedTags = needExactTags(m_profile->getSettings()); const int localNeedTags = m_filename.needExactTags(m_image->parentSite()); const int needTags = qMax(globalNeedTags, localNeedTags); const bool filenameNeedTags = needTags == 2 || (needTags == 1 && m_image->hasUnknownTag()); const bool blacklistNeedTags = m_blacklist != nullptr && m_image->tags().isEmpty(); if (!blacklistNeedTags && !needFileUrl && (!m_loadTags || !m_paths.isEmpty() || !filenameNeedTags)) { loadedSave(); return; } connect(m_image.data(), &Image::finishedLoadingTags, this, &ImageDownloader::loadedSave); m_image->loadDetails(); } int ImageDownloader::needExactTags(QSettings *settings) const { int need = 0; const auto logFiles = getExternalLogFiles(settings); for (auto it = logFiles.constBegin(); it != logFiles.constEnd(); ++it) { need = qMax(need, Filename(it.value().value("content").toString()).needExactTags()); if (need == 2) { return need; } } QStringList settingNames = QStringList() << "Exec/tag_before" << "Exec/image" << "Exec/tag_after" << "Exec/SQL/before" << "Exec/SQL/tag_before" << "Exec/SQL/image" << "Exec/SQL/tag_after" << "Exec/SQL/after"; for (const QString &setting : settingNames) { const QString value = settings->value(setting, "").toString(); if (value.isEmpty()) { continue; } need = qMax(need, Filename(value).needExactTags()); if (need == 2) { return need; } } return need; } void ImageDownloader::abort() { m_image->abortTags(); if (m_reply != nullptr && m_reply->isRunning()) { m_reply->abort(); } } void ImageDownloader::loadedSave() { disconnect(m_image.data(), &Image::finishedLoadingTags, this, &ImageDownloader::loadedSave); // Get the download path from the image if possible if (m_paths.isEmpty()) { m_paths = m_image->paths(m_filename, m_path, m_count); // Use a random temporary file if we need the MD5 or equivalent if (m_filename.needTemporaryFile(m_image->tokens(m_profile))) { const QString tmpDir = !m_path.isEmpty() ? m_path : QDir::tempPath(); m_temporaryPath = tmpDir + "/" + QUuid::createUuid().toString().mid(1, 36) + ".tmp"; } } // Directly use the image path as temporary file if possible if (m_temporaryPath.isEmpty()) { m_temporaryPath = m_paths.first() + ".tmp"; } // Check if the image is blacklisted if (m_blacklist != nullptr) { const QStringList &detected = m_blacklist->match(m_image->tokens(m_profile)); if (!detected.isEmpty()) { log(QStringLiteral("Image contains blacklisted tags: '%1'").arg(detected.join("', '")), Logger::Info); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Blacklisted)); return; } } // Try to save the image if it's already loaded or exists somewhere else on disk if (!m_force) { // Check if the destination files already exist bool allExists = true; for (const QString &path : qAsConst(m_paths)) { if (!QFile::exists(path)) { allExists = false; break; } } if (allExists) { log(QStringLiteral("File already exists: `%1`").arg(m_paths.first()), Logger::Info); for (const QString &path : qAsConst(m_paths)) { addMd5(m_profile, path); } emit saved(m_image, makeResult(m_paths, Image::SaveResult::AlreadyExistsDisk)); return; } // If we don't need any loading, we can return already Image::SaveResult res = m_image->preSave(m_temporaryPath, m_size); if (res != Image::SaveResult::NotLoaded) { QList<ImageSaveResult> result {{ m_temporaryPath, m_size, res }}; if (res == Image::SaveResult::Saved || res == Image::SaveResult::Copied || res == Image::SaveResult::Moved || res == Image::SaveResult::Linked) { result = postSaving(res); } emit saved(m_image, result); return; } } m_url = m_image->url(m_size); log(QStringLiteral("Loading and saving image from `%1` in `%2`").arg(m_url.toString(), m_paths.first())); loadImage(); } void ImageDownloader::loadImage() { connect(&m_fileDownloader, &FileDownloader::success, this, &ImageDownloader::success, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::networkError, this, &ImageDownloader::networkError, Qt::UniqueConnection); connect(&m_fileDownloader, &FileDownloader::writeError, this, &ImageDownloader::writeError, Qt::UniqueConnection); // Delete previous replies for retries if (m_reply != nullptr) { m_reply->deleteLater(); } // Load the image directly on the disk Site *site = m_image->parentSite(); m_reply = site->get(site->fixUrl(m_url.toString()), m_image->page(), QStringLiteral("image"), m_image.data()); m_reply->setParent(this); connect(m_reply, &QNetworkReply::downloadProgress, this, &ImageDownloader::downloadProgressImage); // Create download root directory const QString rootDir = m_temporaryPath.section(QDir::separator(), 0, -2); if (!QDir(rootDir).exists() && !QDir().mkpath(rootDir)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(rootDir), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); return; } // If we can't start writing for some reason, return an error if (!m_fileDownloader.start(m_reply, QStringList() << m_temporaryPath)) { log(QStringLiteral("Unable to open file"), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); return; } } void ImageDownloader::downloadProgressImage(qint64 v1, qint64 v2) { if (m_image->fileSize() == 0 || m_image->fileSize() < v2 / 2) { m_image->setFileSize(v2, currentSize()); } emit downloadProgress(m_image, v1, v2); } Image::Size ImageDownloader::currentSize() const { return m_tryingSample ? Image::Size::Sample : m_size; } QList<ImageSaveResult> ImageDownloader::makeResult(const QStringList &paths, Image::SaveResult result) const { const Image::Size size = currentSize(); QList<ImageSaveResult> res; for (const QString &path : paths) { res.append({ path, size, result }); } return res; } void ImageDownloader::writeError() { emit saved(m_image, makeResult(m_paths, Image::SaveResult::Error)); } void ImageDownloader::networkError(QNetworkReply::NetworkError error, const QString &msg) { if (error == QNetworkReply::ContentNotFoundError) { QSettings *settings = m_profile->getSettings(); ExtensionRotator *extensionRotator = m_image->extensionRotator(); const bool sampleFallback = settings->value("Save/samplefallback", true).toBool(); const bool shouldFallback = m_size == Image::Size::Full && sampleFallback && !m_image->url(Image::Size::Sample).isEmpty(); QString newext = extensionRotator != nullptr ? extensionRotator->next() : QString(); if (m_rotate && !newext.isEmpty()) { m_url = setExtension(m_image->url(m_size), newext); log(QStringLiteral("Image not found. New try with extension %1 (%2)...").arg(newext, m_url.toString())); m_image->setUrl(m_url); loadImage(); } else if (shouldFallback && !m_tryingSample) { m_url = m_image->url(Image::Size::Sample); m_tryingSample = true; log(QStringLiteral("Image not found. New try with its sample (%1)...").arg(m_url.toString())); m_image->setUrl(m_url); loadImage(); } else { m_tryingSample = false; log(QStringLiteral("Image not found.")); emit saved(m_image, makeResult(m_paths, Image::SaveResult::NotFound)); } } else if (error != QNetworkReply::OperationCanceledError) { log(QStringLiteral("Network error for the image: `%1`: %2 (%3)").arg(m_image->url().toString().toHtmlEscaped()).arg(error).arg(msg), Logger::Error); emit saved(m_image, makeResult(m_paths, Image::SaveResult::NetworkError)); } } void ImageDownloader::success() { // Handle network redirects QUrl redir = m_reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl(); if (!redir.isEmpty()) { m_url = redir; loadImage(); return; } emit saved(m_image, postSaving()); } QList<ImageSaveResult> ImageDownloader::postSaving(Image::SaveResult saveResult) { const QString multipleFiles = m_profile->getSettings()->value("Save/multiple_files", "copy").toString(); const Image::Size size = currentSize(); m_image->setSavePath(m_temporaryPath, size); if (m_image->size(size).isEmpty()) { QImageReader reader(m_temporaryPath); QSize imgSize = reader.size(); if (imgSize.isValid()) { m_image->setSize(imgSize, size); } } if (!m_filename.format().isEmpty()) { m_paths = m_image->paths(m_filename, m_path, m_count); } QString suffix; #ifdef Q_OS_WIN if (saveResult == Image::SaveResult::Linked) { suffix = ".lnk"; } #endif QFile tmp(m_temporaryPath + suffix); bool moved = false; QList<ImageSaveResult> result; for (const QString &file : qAsConst(m_paths)) { const QString path = file + suffix; // Don't overwrite already existing files if (QFile::exists(file) || (!suffix.isEmpty() && QFile::exists(path))) { log(QStringLiteral("File already exists: `%1`").arg(file), Logger::Info); if (suffix.isEmpty()) { addMd5(m_profile, file); } result.append({ path, size, Image::SaveResult::AlreadyExistsDisk }); continue; } if (!moved) { const QString dir = path.section(QDir::separator(), 0, -2); if (!QDir(dir).exists() && !QDir().mkpath(dir)) { log(QStringLiteral("Impossible to create the destination folder: %1.").arg(dir), Logger::Error); result.append({ path, size, Image::SaveResult::Error }); continue; } tmp.rename(path); moved = true; } else if (multipleFiles == "link") { #ifdef Q_OS_WIN tmp.link(path + ".lnk"); #else tmp.link(path); #endif } else { tmp.copy(path); } result.append({ path, size, saveResult }); m_image->postSave(path, size, saveResult, m_addMd5, m_startCommands, m_count); } if (!moved) { tmp.remove(); } return result; } <|endoftext|>
<commit_before>// BESXDTransmit.cc // This file is part of bes, A C++ back-end server implementation framework // for the OPeNDAP Data Access Protocol. // Copyright (c) 2004,2005 University Corporation for Atmospheric Research // Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu> // // 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 // // You can contact University Corporation for Atmospheric Research at // 3080 Center Green Drive, Boulder, CO 80301 // Authors: // pwest Patrick West <pwest@ucar.edu> // jgarcia Jose Garcia <jgarcia@ucar.edu> #include <BaseType.h> #include <Sequence.h> #include <ConstraintEvaluator.h> #include <XMLWriter.h> #include <DODSFilter.h> #include <escaping.h> #include <InternalErr.h> #include <util.h> #include <mime_util.h> #include <XMLWriter.h> #include <BESDapTransmit.h> #include <BESContainer.h> #include <BESDataNames.h> #include <BESDataDDSResponse.h> #include <BESDapError.h> #include <BESInternalFatalError.h> #include <BESDebug.h> #include <DapFunctionUtils.h> #include "BESXDTransmit.h" #include "get_xml_data.h" using namespace xml_data; void BESXDTransmit::send_basic_ascii(BESResponseObject * obj, BESDataHandlerInterface & dhi) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - BEGIN" << endl); BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj); if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance.", __FILE__, __LINE__); DataDDS *dds = bdds->get_dds(); ConstraintEvaluator & ce = bdds->get_ce(); dhi.first_container(); string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26"); try { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "parsing constraint: " << constraint << endl); ce.parse_constraint(constraint, *dds); } catch (InternalErr &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (...) { string err = (string) "Failed to parse the constraint expression: " + "Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "tagging sequences" << endl); dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node. BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "accessing container" << endl); string dataset_name = dhi.container->access(); BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - dataset_name = " << dataset_name << endl); bool functional_constraint = false; try { // Handle *functional* constraint expressions specially if (ce.function_clauses()) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() Processing functional constraint clause(s)." << endl); DataDDS *tmp_dds = ce.eval_function_clauses(*dds); delete dds; dds = tmp_dds; bdds->set_dds(dds); // This next step utilizes a well known function, promote_function_output_structures() // to look for one or more top level Structures whose name indicates (by way of ending // with "_uwrap") that their contents should be promoted (aka moved) to the top level. // This is in support of a hack around the current API where server side functions // may only return a single DAP object and not a collection of objects. The name suffix // "_unwrap" is used as a signal from the function to the the various response // builders and transmitters that the representation needs to be altered before // transmission, and that in fact is what happens in our friend // promote_function_output_structures() promote_function_output_structures(dds); } else { // Iterate through the variables in the DataDDS and read // in the data if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { if ((*i)->send_p()) { (*i)->intern_data(ce, *dds); } } } #if 0 //################################################################### // OLD WAY //################################################################### // Handle *functional* constraint expressions specially if (ce.functional_expression()) { BESDEBUG("xd", "processing a functional constraint." << endl); // This returns a new BaseType, not a pointer to one in the DataDDS // So once the data has been read using this var create a new // DataDDS and add this new var to the it. BaseType *var = ce.eval_function(*dds, dataset_name); if (!var) throw Error(unknown_error, "Error calling the CE function."); var->read(); dds = new DataDDS(NULL, "virtual"); functional_constraint = true; dds->add_var(var); } else { // Iterate through the variables in the DataDDS and read in the data // if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { BESDEBUG("xd", "processing var: " << (*i)->name() << endl); if ((*i)->send_p()) { BESDEBUG("xd", "reading some data for: " << (*i)->name() << endl); (**i).intern_data(ce, *dds); } } } #endif } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error & e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to read data: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } try { // Now that we have constrained the DataDDS and read in the data, // send it as ascii BESDEBUG("xd", "converting to xd datadds" << endl); DataDDS *xd_dds = datadds_to_xd_datadds(dds); BESDEBUG("xd", "getting xd values" << endl); XMLWriter writer; get_data_values_as_xml(xd_dds, &writer); dhi.get_output_stream() << writer.get_doc(); BESDEBUG("xd", "got the ascii values" << endl); dhi.get_output_stream() << flush; delete xd_dds; BESDEBUG("xd", "done transmitting ascii" << endl); } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } if (functional_constraint) delete dds; } <commit_msg>Cleaning up code for merge.<commit_after>// BESXDTransmit.cc // This file is part of bes, A C++ back-end server implementation framework // for the OPeNDAP Data Access Protocol. // Copyright (c) 2004,2005 University Corporation for Atmospheric Research // Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu> // // 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 // // You can contact University Corporation for Atmospheric Research at // 3080 Center Green Drive, Boulder, CO 80301 // Authors: // pwest Patrick West <pwest@ucar.edu> // jgarcia Jose Garcia <jgarcia@ucar.edu> #include <BaseType.h> #include <Sequence.h> #include <ConstraintEvaluator.h> #include <XMLWriter.h> #include <DODSFilter.h> #include <escaping.h> #include <InternalErr.h> #include <util.h> #include <mime_util.h> #include <XMLWriter.h> #include <BESDapTransmit.h> #include <BESContainer.h> #include <BESDataNames.h> #include <BESDataDDSResponse.h> #include <BESDapError.h> #include <BESInternalFatalError.h> #include <BESDebug.h> #include <DapFunctionUtils.h> #include "BESXDTransmit.h" #include "get_xml_data.h" using namespace xml_data; void BESXDTransmit::send_basic_ascii(BESResponseObject * obj, BESDataHandlerInterface & dhi) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - BEGIN" << endl); BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj); if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance.", __FILE__, __LINE__); DataDDS *dds = bdds->get_dds(); ConstraintEvaluator & ce = bdds->get_ce(); dhi.first_container(); string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26"); try { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "parsing constraint: " << constraint << endl); ce.parse_constraint(constraint, *dds); } catch (InternalErr &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (...) { string err = (string) "Failed to parse the constraint expression: " + "Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "tagging sequences" << endl); dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node. BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "accessing container" << endl); string dataset_name = dhi.container->access(); BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - dataset_name = " << dataset_name << endl); bool functional_constraint = false; try { // Handle *functional* constraint expressions specially if (ce.function_clauses()) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() Processing functional constraint clause(s)." << endl); DataDDS *tmp_dds = ce.eval_function_clauses(*dds); delete dds; dds = tmp_dds; bdds->set_dds(dds); // This next step utilizes a well known function, promote_function_output_structures() // to look for one or more top level Structures whose name indicates (by way of ending // with "_uwrap") that their contents should be promoted (aka moved) to the top level. // This is in support of a hack around the current API where server side functions // may only return a single DAP object and not a collection of objects. The name suffix // "_unwrap" is used as a signal from the function to the the various response // builders and transmitters that the representation needs to be altered before // transmission, and that in fact is what happens in our friend // promote_function_output_structures() promote_function_output_structures(dds); } else { // Iterate through the variables in the DataDDS and read // in the data if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { if ((*i)->send_p()) { (*i)->intern_data(ce, *dds); } } } } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error & e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to read data: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } try { // Now that we have constrained the DataDDS and read in the data, // send it as ascii BESDEBUG("xd", "converting to xd datadds" << endl); DataDDS *xd_dds = datadds_to_xd_datadds(dds); BESDEBUG("xd", "getting xd values" << endl); XMLWriter writer; get_data_values_as_xml(xd_dds, &writer); dhi.get_output_stream() << writer.get_doc(); BESDEBUG("xd", "got the ascii values" << endl); dhi.get_output_stream() << flush; delete xd_dds; BESDEBUG("xd", "done transmitting ascii" << endl); } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } if (functional_constraint) delete dds; } <|endoftext|>
<commit_before>// BESXDTransmit.cc // This file is part of bes, A C++ back-end server implementation framework // for the OPeNDAP Data Access Protocol. // Copyright (c) 2004,2005 University Corporation for Atmospheric Research // Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu> // // 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 // // You can contact University Corporation for Atmospheric Research at // 3080 Center Green Drive, Boulder, CO 80301 // Authors: // pwest Patrick West <pwest@ucar.edu> // jgarcia Jose Garcia <jgarcia@ucar.edu> #include <BaseType.h> #include <Sequence.h> #include <ConstraintEvaluator.h> #include <XMLWriter.h> #include <DODSFilter.h> #include <escaping.h> #include <InternalErr.h> #include <util.h> #include <mime_util.h> #include <XMLWriter.h> #include <BESDapTransmit.h> #include <BESContainer.h> #include <BESDataNames.h> #include <BESDataDDSResponse.h> #include <BESDapError.h> #include <BESInternalFatalError.h> #include <BESDebug.h> #include "BESXDTransmit.h" #include "get_xml_data.h" using namespace xml_data; void BESXDTransmit::send_basic_ascii(BESResponseObject * obj, BESDataHandlerInterface & dhi) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii" << endl); BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj); if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance.", __FILE__, __LINE__); DataDDS *dds = bdds->get_dds(); ConstraintEvaluator & ce = bdds->get_ce(); dhi.first_container(); string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26"); try { BESDEBUG("xd", "BESXDTransmit::send_base_ascii - " "parsing constraint: " << constraint << endl); ce.parse_constraint(constraint, *dds); } catch (InternalErr &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (...) { string err = (string) "Failed to parse the constraint expression: " + "Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } BESDEBUG("xd", "BESXDTransmit::send_base_ascii - " "tagging sequences" << endl); dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node. BESDEBUG("xd", "BESXDTransmit::send_base_ascii - " "accessing container" << endl); string dataset_name = dhi.container->access(); BESDEBUG("xd", "BESXDTransmit::send_base_ascii - dataset_name = " << dataset_name << endl); bool functional_constraint = false; try { // Handle *functional* constraint expressions specially if (ce.functional_expression()) { BESDEBUG("xd", "processing a functional constraint." << endl); // This returns a new BaseType, not a pointer to one in the DataDDS // So once the data has been read using this var create a new // DataDDS and add this new var to the it. BaseType *var = ce.eval_function(*dds, dataset_name); if (!var) throw Error(unknown_error, "Error calling the CE function."); var->read(); dds = new DataDDS(NULL, "virtual"); functional_constraint = true; dds->add_var(var); } else { // Iterate through the variables in the DataDDS and read in the data // if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { BESDEBUG("xd", "processing var: " << (*i)->name() << endl); if ((*i)->send_p()) { BESDEBUG("xd", "reading some data for: " << (*i)->name() << endl); (**i).intern_data(ce, *dds); } } } } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error & e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to read data: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } try { // Now that we have constrained the DataDDS and read in the data, // send it as ascii BESDEBUG("xd", "converting to xd datadds" << endl); DataDDS *xd_dds = datadds_to_xd_datadds(dds); BESDEBUG("xd", "getting xd values" << endl); XMLWriter writer; get_data_values_as_xml(xd_dds, &writer); dhi.get_output_stream() << writer.get_doc(); BESDEBUG("xd", "got the ascii values" << endl); dhi.get_output_stream() << flush; delete xd_dds; BESDEBUG("xd", "done transmitting ascii" << endl); } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } if (functional_constraint) delete dds; } <commit_msg>Added call to function output promoter to xml_data_handler<commit_after>// BESXDTransmit.cc // This file is part of bes, A C++ back-end server implementation framework // for the OPeNDAP Data Access Protocol. // Copyright (c) 2004,2005 University Corporation for Atmospheric Research // Author: Patrick West <pwest@ucar.edu> and Jose Garcia <jgarcia@ucar.edu> // // 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 // // You can contact University Corporation for Atmospheric Research at // 3080 Center Green Drive, Boulder, CO 80301 // Authors: // pwest Patrick West <pwest@ucar.edu> // jgarcia Jose Garcia <jgarcia@ucar.edu> #include <BaseType.h> #include <Sequence.h> #include <ConstraintEvaluator.h> #include <XMLWriter.h> #include <DODSFilter.h> #include <escaping.h> #include <InternalErr.h> #include <util.h> #include <mime_util.h> #include <XMLWriter.h> #include <BESDapTransmit.h> #include <BESContainer.h> #include <BESDataNames.h> #include <BESDataDDSResponse.h> #include <BESDapError.h> #include <BESInternalFatalError.h> #include <BESDebug.h> #include "BESXDTransmit.h" #include "get_xml_data.h" using namespace xml_data; void BESXDTransmit::send_basic_ascii(BESResponseObject * obj, BESDataHandlerInterface & dhi) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - BEGIN" << endl); BESDataDDSResponse *bdds = dynamic_cast<BESDataDDSResponse *>(obj); if (!bdds) throw BESInternalFatalError("Expected a BESDataDDSResponse instance.", __FILE__, __LINE__); DataDDS *dds = bdds->get_dds(); ConstraintEvaluator & ce = bdds->get_ce(); dhi.first_container(); string constraint = www2id(dhi.data[POST_CONSTRAINT], "%", "%20%26"); try { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "parsing constraint: " << constraint << endl); ce.parse_constraint(constraint, *dds); } catch (InternalErr &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { string err = "Failed to parse the constraint expression: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (...) { string err = (string) "Failed to parse the constraint expression: " + "Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "tagging sequences" << endl); dds->tag_nested_sequences(); // Tag Sequences as Parent or Leaf node. BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - " "accessing container" << endl); string dataset_name = dhi.container->access(); BESDEBUG("xd", "BESXDTransmit::send_base_ascii() - dataset_name = " << dataset_name << endl); bool functional_constraint = false; try { // Handle *functional* constraint expressions specially if (ce.function_clauses()) { BESDEBUG("xd", "BESXDTransmit::send_base_ascii() Processing functional constraint clause(s)." << endl); DataDDS *tmp_dds = ce.eval_function_clauses(*dds); // This next step utilizes a well known function, promote_function_output_structures() // to look for one or more top level Structures whose name indicates (by way of ending // with "_uwrap") that their contents should be promoted (aka moved) to the top level. // This is in support of a hack around the current API where server side functions // may only return a single DAP object and not a collection of objects. The name suffix // "_unwrap" is used as a signal from the function to the the various response // builders and transmitters that the representation needs to be altered before // transmission, and that in fact is what happens in our friend // promote_function_output_structures() tmp_dds = promote_function_output_structures(tmp_dds); delete dds; dds = tmp_dds; bdds->set_dds(dds); } else { // Iterate through the variables in the DataDDS and read // in the data if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { if ((*i)->send_p()) { (*i)->intern_data(ce, *dds); } } } #if 0 //################################################################### // OLD WAY //################################################################### // Handle *functional* constraint expressions specially if (ce.functional_expression()) { BESDEBUG("xd", "processing a functional constraint." << endl); // This returns a new BaseType, not a pointer to one in the DataDDS // So once the data has been read using this var create a new // DataDDS and add this new var to the it. BaseType *var = ce.eval_function(*dds, dataset_name); if (!var) throw Error(unknown_error, "Error calling the CE function."); var->read(); dds = new DataDDS(NULL, "virtual"); functional_constraint = true; dds->add_var(var); } else { // Iterate through the variables in the DataDDS and read in the data // if the variable has the send flag set. for (DDS::Vars_iter i = dds->var_begin(); i != dds->var_end(); i++) { BESDEBUG("xd", "processing var: " << (*i)->name() << endl); if ((*i)->send_p()) { BESDEBUG("xd", "reading some data for: " << (*i)->name() << endl); (**i).intern_data(ce, *dds); } } } #endif } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error & e) { if (functional_constraint) delete dds; string err = "Failed to read data: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to read data: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } try { // Now that we have constrained the DataDDS and read in the data, // send it as ascii BESDEBUG("xd", "converting to xd datadds" << endl); DataDDS *xd_dds = datadds_to_xd_datadds(dds); BESDEBUG("xd", "getting xd values" << endl); XMLWriter writer; get_data_values_as_xml(xd_dds, &writer); dhi.get_output_stream() << writer.get_doc(); BESDEBUG("xd", "got the ascii values" << endl); dhi.get_output_stream() << flush; delete xd_dds; BESDEBUG("xd", "done transmitting ascii" << endl); } catch (InternalErr &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, true, e.get_error_code(), __FILE__, __LINE__); } catch (Error &e) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: " + e.get_error_message(); throw BESDapError(err, false, e.get_error_code(), __FILE__, __LINE__); } catch (BESError &e) { throw; } catch (...) { if (functional_constraint) delete dds; string err = "Failed to get values as ascii: Unknown exception caught"; throw BESInternalFatalError(err, __FILE__, __LINE__); } if (functional_constraint) delete dds; } <|endoftext|>
<commit_before>#include "cma_es.h" #include "objective_function.h" using revolution::CmaEs; using revolution::ObjectiveFunction; /*---------------------------------------------------------------------------*/ class CmaEs::CmaEsPriv { public: CmaEsPriv(unsigned int l, struct RVObjectiveFunction *fun) : lambda(l), objFun(fun), wrapper(0) { } void setWrapperObject(RVCmaEvolutionStrategy *w) { wrapper = w; } unsigned int lambda; struct RVObjectiveFunction *objFun; RVCmaEvolutionStrategy *wrapper; }; /*---------------------------------------------------------------------------*/ CmaEs::CmaEs(unsigned int lambda, struct RVObjectiveFunction *fun) : impl(new CmaEsPriv(lambda, fun)) { } /*---------------------------------------------------------------------------*/ CmaEs::~CmaEs() { delete impl; } /*---------------------------------------------------------------------------*/ void CmaEs::setWrapperObject(RVCmaEvolutionStrategy *w) { impl->setWrapperObject(w); } /*---------------------------------------------------------------------------*/ CmaEs* CmaEs::create(unsigned int lambda, RVObjectiveFunction *fun) { return new CmaEs(lambda, fun); } <commit_msg>missing 'struct' from member declaration<commit_after>#include "cma_es.h" #include "objective_function.h" using revolution::CmaEs; using revolution::ObjectiveFunction; /*---------------------------------------------------------------------------*/ class CmaEs::CmaEsPriv { public: CmaEsPriv(unsigned int l, struct RVObjectiveFunction *fun) : lambda(l), objFun(fun), wrapper(0) { } void setWrapperObject(RVCmaEvolutionStrategy *w) { wrapper = w; } unsigned int lambda; struct RVObjectiveFunction *objFun; struct RVCmaEvolutionStrategy *wrapper; }; /*---------------------------------------------------------------------------*/ CmaEs::CmaEs(unsigned int lambda, struct RVObjectiveFunction *fun) : impl(new CmaEsPriv(lambda, fun)) { } /*---------------------------------------------------------------------------*/ CmaEs::~CmaEs() { delete impl; } /*---------------------------------------------------------------------------*/ void CmaEs::setWrapperObject(RVCmaEvolutionStrategy *w) { impl->setWrapperObject(w); } /*---------------------------------------------------------------------------*/ CmaEs* CmaEs::create(unsigned int lambda, RVObjectiveFunction *fun) { return new CmaEs(lambda, fun); } <|endoftext|>
<commit_before>/* Sirikata * PrintFilter.cpp * * Copyright (c) 2010, Jeff Terrace * 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 Sirikata 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 "PrintFilter.hpp" namespace Sirikata { namespace Mesh { PrintFilter::PrintFilter(const String& args) { } FilterDataPtr PrintFilter::apply(FilterDataPtr input) { assert(input->single()); MeshdataPtr md = input->get(); printf("URI: %s\n", md->uri.c_str()); printf("ID: %ld\n", md->id); printf("Hash: %s\n", md->hash.toString().c_str()); printf("Texture List:\n"); for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) { printf(" %s\n", it->c_str()); } printf("Submesh Geometry List:\n"); for(SubMeshGeometryList::const_iterator it = md->geometry.begin(); it != md->geometry.end(); it++) { printf(" Name: %s, Positions: %d Normals: %d Primitives: %d\n", it->name.c_str(), (int)it->positions.size(), (int)it->normals.size(), (int)it->primitives.size()); for(std::vector<SubMeshGeometry::Primitive>::const_iterator p = it->primitives.begin(); p != it->primitives.end(); p++) { printf(" Primitive id: %d, indices: %d\n", (int)p->materialId, (int)p->indices.size()); } } printf("Lights:\n"); for(LightInfoList::const_iterator it = md->lights.begin(); it != md->lights.end(); it++) { printf(" Type: %d Power: %f\n", it->mType, it->mPower); } printf("Material Effects:\n"); for(MaterialEffectInfoList::const_iterator it = md->materials.begin(); it != md->materials.end(); it++) { printf(" Textures: %d Shininess: %f Reflectivity: %f\n", (int)it->textures.size(), it->shininess, it->reflectivity); for(MaterialEffectInfo::TextureList::const_iterator t_it = it->textures.begin(); t_it != it->textures.end(); t_it++) printf(" Texture: %s\n", t_it->uri.c_str()); } printf("Geometry Instances:\n"); for(GeometryInstanceList::const_iterator it = md->instances.begin(); it != md->instances.end(); it++) { printf(" Index: %d Radius: %f MapSize: %d\n", it->geometryIndex, it->radius, it->materialBindingMap.size()); for(GeometryInstance::MaterialBindingMap::const_iterator m = it->materialBindingMap.begin(); m != it->materialBindingMap.end(); m++) { printf(" map from: %d to: %d\n", (int)m->first, (int)m->second); } } printf("Light Instances:\n"); for(LightInstanceList::const_iterator it = md->lightInstances.begin(); it != md->lightInstances.end(); it++) { printf(" Index: %d Matrix: %s\n", it->lightIndex, md->getTransform(it->parentNode).toString().c_str()); } printf("Material Effect size: %d\n", (int)md->materials.size()); return input; } } } <commit_msg>Have PrintFilter print out node structure.<commit_after>/* Sirikata * PrintFilter.cpp * * Copyright (c) 2010, Jeff Terrace * 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 Sirikata 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 "PrintFilter.hpp" #include <stack> namespace Sirikata { namespace Mesh { PrintFilter::PrintFilter(const String& args) { } namespace { struct NodeState { NodeState(NodeIndex idx) : node(idx), curChild(-1) {} NodeIndex node; int32 curChild; }; } FilterDataPtr PrintFilter::apply(FilterDataPtr input) { assert(input->single()); MeshdataPtr md = input->get(); printf("URI: %s\n", md->uri.c_str()); printf("ID: %ld\n", md->id); printf("Hash: %s\n", md->hash.toString().c_str()); printf("Texture List:\n"); for(TextureList::const_iterator it = md->textures.begin(); it != md->textures.end(); it++) { printf(" %s\n", it->c_str()); } printf("Submesh Geometry List:\n"); for(SubMeshGeometryList::const_iterator it = md->geometry.begin(); it != md->geometry.end(); it++) { printf(" Name: %s, Positions: %d Normals: %d Primitives: %d\n", it->name.c_str(), (int)it->positions.size(), (int)it->normals.size(), (int)it->primitives.size()); for(std::vector<SubMeshGeometry::Primitive>::const_iterator p = it->primitives.begin(); p != it->primitives.end(); p++) { printf(" Primitive id: %d, indices: %d\n", (int)p->materialId, (int)p->indices.size()); } } printf("Lights:\n"); for(LightInfoList::const_iterator it = md->lights.begin(); it != md->lights.end(); it++) { printf(" Type: %d Power: %f\n", it->mType, it->mPower); } printf("Material Effects:\n"); for(MaterialEffectInfoList::const_iterator it = md->materials.begin(); it != md->materials.end(); it++) { printf(" Textures: %d Shininess: %f Reflectivity: %f\n", (int)it->textures.size(), it->shininess, it->reflectivity); for(MaterialEffectInfo::TextureList::const_iterator t_it = it->textures.begin(); t_it != it->textures.end(); t_it++) printf(" Texture: %s\n", t_it->uri.c_str()); } printf("Geometry Instances:\n"); for(GeometryInstanceList::const_iterator it = md->instances.begin(); it != md->instances.end(); it++) { printf(" Index: %d Radius: %f MapSize: %d\n", it->geometryIndex, it->radius, (int)it->materialBindingMap.size()); for(GeometryInstance::MaterialBindingMap::const_iterator m = it->materialBindingMap.begin(); m != it->materialBindingMap.end(); m++) { printf(" map from: %d to: %d\n", (int)m->first, (int)m->second); } } printf("Light Instances:\n"); for(LightInstanceList::const_iterator it = md->lightInstances.begin(); it != md->lightInstances.end(); it++) { printf(" Index: %d Matrix: %s\n", it->lightIndex, md->getTransform(it->parentNode).toString().c_str()); } printf("Material Effect size: %d\n", (int)md->materials.size()); printf("Nodes size: %d (%d roots)\n", (int)md->nodes.size(), (int)md->rootNodes.size()); for(uint32 ri = 0; ri < md->rootNodes.size(); ri++) { std::stack<NodeState> node_stack; node_stack.push( NodeState(md->rootNodes[ri]) ); String indent = ""; while(!node_stack.empty()) { NodeState& curnode = node_stack.top(); if (curnode.curChild == -1) { // First time we've seen this node, print info and move it // forward to start procesing children printf("%s %d\n", indent.c_str(), curnode.node); curnode.curChild++; indent += " "; } else if (curnode.curChild >= (int)md->nodes[curnode.node].children.size()) { // We finished with this node node_stack.pop(); indent = indent.substr(1); // reduce indent } else { // Normal iteration, process next child int32 childindex = curnode.curChild; curnode.curChild++; node_stack.push( NodeState(md->nodes[curnode.node].children[childindex]) ); } } } return input; } } } <|endoftext|>
<commit_before>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <string> #include <memory> #include <typeindex> #include <functional> #include <type_traits> #include <unordered_map> #include "caf/actor_factory.hpp" #include "caf/config_option.hpp" #include "caf/config_option_adder.hpp" #include "caf/config_option_set.hpp" #include "caf/config_value.hpp" #include "caf/dictionary.hpp" #include "caf/fwd.hpp" #include "caf/is_typed_actor.hpp" #include "caf/named_actor_config.hpp" #include "caf/settings.hpp" #include "caf/stream.hpp" #include "caf/thread_hook.hpp" #include "caf/type_erased_value.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// Configures an `actor_system` on startup. class actor_system_config { public: // -- member types ----------------------------------------------------------- using hook_factory = std::function<io::hook* (actor_system&)>; using hook_factory_vector = std::vector<hook_factory>; using thread_hooks = std::vector<std::unique_ptr<thread_hook>>; template <class K, class V> using hash_map = std::unordered_map<K, V>; using module_factory = std::function<actor_system::module* (actor_system&)>; using module_factory_vector = std::vector<module_factory>; using value_factory = std::function<type_erased_value_ptr ()>; using value_factory_string_map = hash_map<std::string, value_factory>; using value_factory_rtti_map = hash_map<std::type_index, value_factory>; using actor_factory_map = hash_map<std::string, actor_factory>; using portable_name_map = hash_map<std::type_index, std::string>; using error_renderer = std::function<std::string (uint8_t, atom_value, const message&)>; using error_renderer_map = hash_map<atom_value, error_renderer>; using group_module_factory = std::function<group_module* ()>; using group_module_factory_vector = std::vector<group_module_factory>; using config_map = dictionary<config_value::dictionary>; using string_list = std::vector<std::string>; using named_actor_config_map = hash_map<std::string, named_actor_config>; using opt_group = config_option_adder; // -- constructors, destructors, and assignment operators -------------------- virtual ~actor_system_config(); actor_system_config(); actor_system_config(actor_system_config&&) = default; actor_system_config(const actor_system_config&) = delete; actor_system_config& operator=(const actor_system_config&) = delete; // -- properties ------------------------------------------------------------- /// @private settings content; /// Sets a config by using its INI name `config_name` to `config_value`. template <class T> actor_system_config& set(string_view name, T&& value) { return set_impl(name, config_value{std::forward<T>(value)}); } // -- modifiers -------------------------------------------------------------- /// Parses `args` as tuple of strings containing CLI options and `ini_stream` /// as INI formatted input stream. error parse(string_list args, std::istream& ini); /// Parses `args` as tuple of strings containing CLI options and tries to /// open `ini_file_cstr` as INI formatted config file. The parsers tries to /// open `caf-application.ini` if `ini_file_cstr` is `nullptr`. error parse(string_list args, const char* ini_file_cstr = nullptr); /// Parses the CLI options `{argc, argv}` and `ini_stream` as INI formatted /// input stream. error parse(int argc, char** argv, std::istream& ini); /// Parses the CLI options `{argc, argv}` and tries to open `ini_file_cstr` /// as INI formatted config file. The parsers tries to open /// `caf-application.ini` if `ini_file_cstr` is `nullptr`. error parse(int argc, char** argv, const char* ini_file_cstr = nullptr); /// Allows other nodes to spawn actors created by `fun` /// dynamically by using `name` as identifier. /// @experimental actor_system_config& add_actor_factory(std::string name, actor_factory fun); /// Allows other nodes to spawn actors of type `T` /// dynamically by using `name` as identifier. /// @experimental template <class T, class... Ts> actor_system_config& add_actor_type(std::string name) { using handle = typename infer_handle_from_class<T>::type; if (!std::is_same<handle, actor>::value) add_message_type<handle>(name); return add_actor_factory(std::move(name), make_actor_factory<T, Ts...>()); } /// Allows other nodes to spawn actors implemented by function `f` /// dynamically by using `name` as identifier. /// @experimental template <class F> actor_system_config& add_actor_type(std::string name, F f) { using handle = typename infer_handle_from_fun<F>::type; if (!std::is_same<handle, actor>::value) add_message_type<handle>(name); return add_actor_factory(std::move(name), make_actor_factory(std::move(f))); } /// Adds message type `T` with runtime type info `name`. template <class T> actor_system_config& add_message_type(std::string name) { static_assert(std::is_empty<T>::value || std::is_same<T, actor>::value // silence add_actor_type err || is_typed_actor<T>::value || (std::is_default_constructible<T>::value && std::is_copy_constructible<T>::value), "T must provide default and copy constructors"); std::string stream_name = "stream<"; stream_name += name; stream_name += ">"; add_message_type_impl<stream<T>>(std::move(stream_name)); std::string vec_name = "std::vector<"; vec_name += name; vec_name += ">"; add_message_type_impl<std::vector<T>>(std::move(vec_name)); add_message_type_impl<T>(std::move(name)); return *this; } /// Enables the actor system to convert errors of this error category /// to human-readable strings via `renderer`. actor_system_config& add_error_category(atom_value x, error_renderer y); /// Enables the actor system to convert errors of this error category /// to human-readable strings via `to_string(T)`. template <class T> actor_system_config& add_error_category(atom_value category) { auto f = [=](uint8_t val, const std::string& ctx) -> std::string { std::string result; result = to_string(category); result += ": "; result += to_string(static_cast<T>(val)); if (!ctx.empty()) { result += " ("; result += ctx; result += ")"; } return result; }; return add_error_category(category, f); } /// Loads module `T` with optional template parameters `Ts...`. template <class T, class... Ts> actor_system_config& load() { module_factories.push_back([](actor_system& sys) -> actor_system::module* { return T::make(sys, detail::type_list<Ts...>{}); }); return *this; } /// Adds a factory for a new hook type to the middleman (if loaded). template <class Factory> actor_system_config& add_hook_factory(Factory f) { hook_factories.push_back(f); return *this; } /// Adds a hook type to the middleman (if loaded). template <class Hook> actor_system_config& add_hook_type() { return add_hook_factory([](actor_system& sys) -> Hook* { return new Hook(sys); }); } /// Adds a hook type to the scheduler. template <class Hook, class... Ts> actor_system_config& add_thread_hook(Ts&&... ts) { thread_hooks_.emplace_back(new Hook(std::forward<Ts>(ts)...)); return *this; } // -- parser and CLI state --------------------------------------------------- /// Stores whether the help text was printed. If set to `true`, the /// application should not use this config to initialize an `actor_system` /// and instead return from `main` immediately. bool cli_helptext_printed; /// Stores CLI arguments that were not consumed by CAF. string_list remainder; // -- caf-run parameters ----------------------------------------------------- /// Stores whether this node was started in slave mode. bool slave_mode; /// Name of this node when started in slave mode. std::string slave_name; /// Credentials for connecting to the bootstrap node. std::string bootstrap_node; // -- stream parameters ------------------------------------------------------ /// @private timespan stream_desired_batch_complexity; /// @private timespan stream_max_batch_delay; /// @private timespan stream_credit_round_interval; /// @private timespan stream_tick_duration() const noexcept; // -- OpenCL parameters ------------------------------------------------------ std::string opencl_device_ids; // -- OpenSSL parameters ----------------------------------------------------- std::string openssl_certificate; std::string openssl_key; std::string openssl_passphrase; std::string openssl_capath; std::string openssl_cafile; // -- factories -------------------------------------------------------------- value_factory_string_map value_factories_by_name; value_factory_rtti_map value_factories_by_rtti; actor_factory_map actor_factories; module_factory_vector module_factories; hook_factory_vector hook_factories; group_module_factory_vector group_module_factories; // -- hooks ------------------------------------------------------------------ thread_hooks thread_hooks_; // -- run-time type information ---------------------------------------------- portable_name_map type_names_by_rtti; // -- rendering of user-defined types ---------------------------------------- error_renderer_map error_renderers; // -- parsing parameters ----------------------------------------------------- /// Configures the file path for the INI file, `caf-application.ini` per /// default. std::string config_file_path; // -- utility for caf-run ---------------------------------------------------- // Config parameter for individual actor types. named_actor_config_map named_actor_configs; int (*slave_mode_fun)(actor_system&, const actor_system_config&); protected: virtual std::string make_help_text(const std::vector<message::cli_arg>&); config_option_set custom_options_; private: template <class T> void add_message_type_impl(std::string name) { type_names_by_rtti.emplace(std::type_index(typeid(T)), name); value_factories_by_name.emplace(std::move(name), &make_type_erased_value<T>); value_factories_by_rtti.emplace(std::type_index(typeid(T)), &make_type_erased_value<T>); } actor_system_config& set_impl(string_view name, config_value value); static std::string render_sec(uint8_t, atom_value, const message&); static std::string render_exit_reason(uint8_t, atom_value, const message&); static std::string render_pec(uint8_t, atom_value, const message&); void extract_config_file_path(string_list& args); }; /// @private const settings& content(const actor_system_config& cfg); /// Tries to retrieve the value associated to `name` from `cfg`. /// @relates config_value template <class T> optional<T> get_if(const actor_system_config* cfg, string_view name) { return get_if<T>(&content(*cfg), name); } /// Retrieves the value associated to `name` from `cfg`. /// @relates config_value template <class T> T get(const actor_system_config& cfg, string_view name) { return get<T>(content(cfg), name); } /// Retrieves the value associated to `name` from `cfg` or returns /// `default_value`. /// @relates config_value template <class K, class V> auto get_or(const actor_system_config& cfg, K&& name, V&& default_value) -> decltype(get_or(content(cfg), std::forward<K>(name), std::forward<V>(default_value))) { return get_or(content(cfg), std::forward<K>(name), std::forward<V>(default_value)); } } // namespace caf <commit_msg>Fix build on Clang 3.6<commit_after>/****************************************************************************** * ____ _ _____ * * / ___| / \ | ___| C++ * * | | / _ \ | |_ Actor * * | |___ / ___ \| _| Framework * * \____/_/ \_|_| * * * * Copyright 2011-2018 Dominik Charousset * * * * Distributed under the terms and conditions of the BSD 3-Clause License or * * (at your option) under the terms and conditions of the Boost Software * * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * * * * If you did not receive a copy of the license files, see * * http://opensource.org/licenses/BSD-3-Clause and * * http://www.boost.org/LICENSE_1_0.txt. * ******************************************************************************/ #pragma once #include <atomic> #include <string> #include <memory> #include <typeindex> #include <functional> #include <type_traits> #include <unordered_map> #include "caf/actor_factory.hpp" #include "caf/config_option.hpp" #include "caf/config_option_adder.hpp" #include "caf/config_option_set.hpp" #include "caf/config_value.hpp" #include "caf/dictionary.hpp" #include "caf/fwd.hpp" #include "caf/is_typed_actor.hpp" #include "caf/named_actor_config.hpp" #include "caf/settings.hpp" #include "caf/stream.hpp" #include "caf/thread_hook.hpp" #include "caf/type_erased_value.hpp" #include "caf/detail/safe_equal.hpp" #include "caf/detail/type_traits.hpp" namespace caf { /// Configures an `actor_system` on startup. class actor_system_config { public: // -- member types ----------------------------------------------------------- using hook_factory = std::function<io::hook* (actor_system&)>; using hook_factory_vector = std::vector<hook_factory>; using thread_hooks = std::vector<std::unique_ptr<thread_hook>>; template <class K, class V> using hash_map = std::unordered_map<K, V>; using module_factory = std::function<actor_system::module* (actor_system&)>; using module_factory_vector = std::vector<module_factory>; using value_factory = std::function<type_erased_value_ptr ()>; using value_factory_string_map = hash_map<std::string, value_factory>; using value_factory_rtti_map = hash_map<std::type_index, value_factory>; using actor_factory_map = hash_map<std::string, actor_factory>; using portable_name_map = hash_map<std::type_index, std::string>; using error_renderer = std::function<std::string (uint8_t, atom_value, const message&)>; using error_renderer_map = hash_map<atom_value, error_renderer>; using group_module_factory = std::function<group_module* ()>; using group_module_factory_vector = std::vector<group_module_factory>; using config_map = dictionary<config_value::dictionary>; using string_list = std::vector<std::string>; using named_actor_config_map = hash_map<std::string, named_actor_config>; using opt_group = config_option_adder; // -- constructors, destructors, and assignment operators -------------------- virtual ~actor_system_config(); actor_system_config(); actor_system_config(actor_system_config&&) = default; actor_system_config(const actor_system_config&) = delete; actor_system_config& operator=(const actor_system_config&) = delete; // -- properties ------------------------------------------------------------- /// @private settings content; /// Sets a config by using its INI name `config_name` to `config_value`. template <class T> actor_system_config& set(string_view name, T&& value) { return set_impl(name, config_value{std::forward<T>(value)}); } // -- modifiers -------------------------------------------------------------- /// Parses `args` as tuple of strings containing CLI options and `ini_stream` /// as INI formatted input stream. error parse(string_list args, std::istream& ini); /// Parses `args` as tuple of strings containing CLI options and tries to /// open `ini_file_cstr` as INI formatted config file. The parsers tries to /// open `caf-application.ini` if `ini_file_cstr` is `nullptr`. error parse(string_list args, const char* ini_file_cstr = nullptr); /// Parses the CLI options `{argc, argv}` and `ini_stream` as INI formatted /// input stream. error parse(int argc, char** argv, std::istream& ini); /// Parses the CLI options `{argc, argv}` and tries to open `ini_file_cstr` /// as INI formatted config file. The parsers tries to open /// `caf-application.ini` if `ini_file_cstr` is `nullptr`. error parse(int argc, char** argv, const char* ini_file_cstr = nullptr); /// Allows other nodes to spawn actors created by `fun` /// dynamically by using `name` as identifier. /// @experimental actor_system_config& add_actor_factory(std::string name, actor_factory fun); /// Allows other nodes to spawn actors of type `T` /// dynamically by using `name` as identifier. /// @experimental template <class T, class... Ts> actor_system_config& add_actor_type(std::string name) { using handle = typename infer_handle_from_class<T>::type; if (!std::is_same<handle, actor>::value) add_message_type<handle>(name); return add_actor_factory(std::move(name), make_actor_factory<T, Ts...>()); } /// Allows other nodes to spawn actors implemented by function `f` /// dynamically by using `name` as identifier. /// @experimental template <class F> actor_system_config& add_actor_type(std::string name, F f) { using handle = typename infer_handle_from_fun<F>::type; if (!std::is_same<handle, actor>::value) add_message_type<handle>(name); return add_actor_factory(std::move(name), make_actor_factory(std::move(f))); } /// Adds message type `T` with runtime type info `name`. template <class T> actor_system_config& add_message_type(std::string name) { static_assert(std::is_empty<T>::value || std::is_same<T, actor>::value // silence add_actor_type err || is_typed_actor<T>::value || (std::is_default_constructible<T>::value && std::is_copy_constructible<T>::value), "T must provide default and copy constructors"); std::string stream_name = "stream<"; stream_name += name; stream_name += ">"; add_message_type_impl<stream<T>>(std::move(stream_name)); std::string vec_name = "std::vector<"; vec_name += name; vec_name += ">"; add_message_type_impl<std::vector<T>>(std::move(vec_name)); add_message_type_impl<T>(std::move(name)); return *this; } /// Enables the actor system to convert errors of this error category /// to human-readable strings via `renderer`. actor_system_config& add_error_category(atom_value x, error_renderer y); /// Enables the actor system to convert errors of this error category /// to human-readable strings via `to_string(T)`. template <class T> actor_system_config& add_error_category(atom_value category) { auto f = [=](uint8_t val, const std::string& ctx) -> std::string { std::string result; result = to_string(category); result += ": "; result += to_string(static_cast<T>(val)); if (!ctx.empty()) { result += " ("; result += ctx; result += ")"; } return result; }; return add_error_category(category, f); } /// Loads module `T` with optional template parameters `Ts...`. template <class T, class... Ts> actor_system_config& load() { module_factories.push_back([](actor_system& sys) -> actor_system::module* { return T::make(sys, detail::type_list<Ts...>{}); }); return *this; } /// Adds a factory for a new hook type to the middleman (if loaded). template <class Factory> actor_system_config& add_hook_factory(Factory f) { hook_factories.push_back(f); return *this; } /// Adds a hook type to the middleman (if loaded). template <class Hook> actor_system_config& add_hook_type() { return add_hook_factory([](actor_system& sys) -> Hook* { return new Hook(sys); }); } /// Adds a hook type to the scheduler. template <class Hook, class... Ts> actor_system_config& add_thread_hook(Ts&&... ts) { thread_hooks_.emplace_back(new Hook(std::forward<Ts>(ts)...)); return *this; } // -- parser and CLI state --------------------------------------------------- /// Stores whether the help text was printed. If set to `true`, the /// application should not use this config to initialize an `actor_system` /// and instead return from `main` immediately. bool cli_helptext_printed; /// Stores CLI arguments that were not consumed by CAF. string_list remainder; // -- caf-run parameters ----------------------------------------------------- /// Stores whether this node was started in slave mode. bool slave_mode; /// Name of this node when started in slave mode. std::string slave_name; /// Credentials for connecting to the bootstrap node. std::string bootstrap_node; // -- stream parameters ------------------------------------------------------ /// @private timespan stream_desired_batch_complexity; /// @private timespan stream_max_batch_delay; /// @private timespan stream_credit_round_interval; /// @private timespan stream_tick_duration() const noexcept; // -- OpenCL parameters ------------------------------------------------------ std::string opencl_device_ids; // -- OpenSSL parameters ----------------------------------------------------- std::string openssl_certificate; std::string openssl_key; std::string openssl_passphrase; std::string openssl_capath; std::string openssl_cafile; // -- factories -------------------------------------------------------------- value_factory_string_map value_factories_by_name; value_factory_rtti_map value_factories_by_rtti; actor_factory_map actor_factories; module_factory_vector module_factories; hook_factory_vector hook_factories; group_module_factory_vector group_module_factories; // -- hooks ------------------------------------------------------------------ thread_hooks thread_hooks_; // -- run-time type information ---------------------------------------------- portable_name_map type_names_by_rtti; // -- rendering of user-defined types ---------------------------------------- error_renderer_map error_renderers; // -- parsing parameters ----------------------------------------------------- /// Configures the file path for the INI file, `caf-application.ini` per /// default. std::string config_file_path; // -- utility for caf-run ---------------------------------------------------- // Config parameter for individual actor types. named_actor_config_map named_actor_configs; int (*slave_mode_fun)(actor_system&, const actor_system_config&); protected: virtual std::string make_help_text(const std::vector<message::cli_arg>&); config_option_set custom_options_; private: template <class T> void add_message_type_impl(std::string name) { type_names_by_rtti.emplace(std::type_index(typeid(T)), name); value_factories_by_name.emplace(std::move(name), &make_type_erased_value<T>); value_factories_by_rtti.emplace(std::type_index(typeid(T)), &make_type_erased_value<T>); } actor_system_config& set_impl(string_view name, config_value value); static std::string render_sec(uint8_t, atom_value, const message&); static std::string render_exit_reason(uint8_t, atom_value, const message&); static std::string render_pec(uint8_t, atom_value, const message&); void extract_config_file_path(string_list& args); }; /// @private const settings& content(const actor_system_config& cfg); /// Tries to retrieve the value associated to `name` from `cfg`. /// @relates config_value template <class T> optional<T> get_if(const actor_system_config* cfg, string_view name) { return get_if<T>(&content(*cfg), name); } /// Retrieves the value associated to `name` from `cfg`. /// @relates config_value template <class T> T get(const actor_system_config& cfg, string_view name) { return get<T>(content(cfg), name); } /// Retrieves the value associated to `name` from `cfg` or returns /// `default_value`. /// @relates config_value template <class T, class = typename std::enable_if< !std::is_pointer<T>::value && !std::is_convertible<T, string_view>::value>::type> T get_or(const actor_system_config& cfg, string_view name, T default_value) { return get_or(content(cfg), name, std::move(default_value)); } /// Retrieves the value associated to `name` from `cfg` or returns /// `default_value`. /// @relates config_value inline std::string get_or(const actor_system_config& cfg, string_view name, string_view default_value) { return get_or(content(cfg), name, default_value); } } // namespace caf <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbVectorImage.h" #include "otbImage.h" #include "itkEuclideanDistance.h" #include "otbStreamingTraits.h" #include "itkImageRegionConstIterator.h" #include "itkListSample.h" #include "itkWeightedCentroidKdTreeGenerator.h" #include "itkKdTreeBasedKmeansEstimator.h" #include "otbStreamingShrinkImageFilter.h" #include "itkUnaryFunctorImageFilter.h" #include "otbChangeLabelImageFilter.h" #include "otbRAMDrivenTiledStreamingManager.h" #include "otbRAMDrivenStrippedStreamingManager.h" namespace otb { namespace Wrapper { namespace Functor { template <class TSample, class TLabel> class KMeansFunctor { public: /** operator */ TLabel operator ()(const TSample& sample) const { typename CentroidMapType::const_iterator it = m_CentroidsMap.begin(); if (it == m_CentroidsMap.end()) { return 0; } TLabel resp = it->first; double minDist = m_Distance->Evaluate(sample, it->second); ++it; while (it != m_CentroidsMap.end()) { double dist = m_Distance->Evaluate(sample, it->second); if (dist < minDist) { resp = it->first; minDist = dist; } ++it; } return resp; } /** Add a new centroid */ void AddCentroid(const TLabel& label, const TSample& centroid) { m_CentroidsMap[label] = centroid; } /** Constructor */ KMeansFunctor() : m_CentroidsMap(), m_Distance() { m_Distance = DistanceType::New(); } bool operator !=(const KMeansFunctor& other) const { return m_CentroidsMap != other.m_CentroidsMap; } private: typedef std::map<TLabel, TSample> CentroidMapType; typedef itk::Statistics::EuclideanDistance<TSample> DistanceType; CentroidMapType m_CentroidsMap; typename DistanceType::Pointer m_Distance; }; } typedef FloatImageType::PixelType PixelType; typedef UInt8ImageType LabeledImageType; typedef LabeledImageType::PixelType LabelType; typedef FloatVectorImageType::PixelType SampleType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType; typedef TreeGeneratorType::KdTreeType TreeType; typedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType; typedef RAMDrivenStrippedStreamingManager<FloatVectorImageType> RAMDrivenStrippedStreamingManagerType; typedef itk::ImageRegionConstIterator<FloatVectorImageType> IteratorType; typedef itk::ImageRegionConstIterator<LabeledImageType> LabeledIteratorType; typedef otb::StreamingShrinkImageFilter<FloatVectorImageType, FloatVectorImageType> ImageSamplingFilterType; typedef otb::StreamingShrinkImageFilter<LabeledImageType, UInt8ImageType> MaskSamplingFilterType; typedef Functor::KMeansFunctor<SampleType, LabelType> KMeansFunctorType; typedef itk::UnaryFunctorImageFilter<FloatVectorImageType, LabeledImageType, KMeansFunctorType> KMeansFilterType; class KMeansClassification: public Application { public: /** Standard class typedefs. */ typedef KMeansClassification Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(KMeansClassification, otb::Application); private: KMeansClassification() { SetName("KMeansClassification"); SetDescription("Unsupervised KMeans image classification"); SetDocName("Unsupervised KMeans image classification Application"); SetDocLongDescription("Performs Unsupervised KMeans image classification."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Segmentation); AddDocTag(Tags::Learning); } virtual ~KMeansClassification() { } void DoCreateParameters() { AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in","Input image filename."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image filename."); AddParameter(ParameterType_RAM, "ram", "Available RAM"); SetDefaultParameterInt("ram", 256); MandatoryOff("ram"); AddParameter(ParameterType_InputImage, "vm", "Validity Mask"); SetParameterDescription("vm","Validity mask. Only non-zero pixels will be used to estimate KMeans modes."); AddParameter(ParameterType_Int, "ts", "Training set size"); SetParameterDescription("ts", "Size of the training set."); SetDefaultParameterInt("ts", 100); MandatoryOff("ts"); AddParameter(ParameterType_Int, "nc", "Number of classes"); SetParameterDescription("nc","number of modes, which will be used to generate class membership."); SetDefaultParameterInt("nc", 3); AddParameter(ParameterType_Int, "maxit", "Maximum number of iterations"); SetParameterDescription("maxit", "Maximum number of iterations."); SetDefaultParameterFloat("maxit", 1000); AddParameter(ParameterType_Float, "ct", "Convergence threshold"); SetParameterDescription("ct", "Convergence threshold for class centroid (L2 distance, by default 0.01)."); SetDefaultParameterFloat("ct", 0.01); // Doc example parameter settings SetDocExampleParameterValue("in", "qb_RoadExtract.img"); SetDocExampleParameterValue("vm", "qb_RoadExtract_mask.png"); SetDocExampleParameterValue("ts", "1000"); SetDocExampleParameterValue("nc", "5"); SetDocExampleParameterValue("maxit", "1000"); SetDocExampleParameterValue("ct", "0.01"); SetDocExampleParameterValue("out", "ClassificationFilterOuptut.tif"); } void DoUpdateParameters() { // test of input image // if (HasValue("in")) { // input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); RAMDrivenStrippedStreamingManagerType::Pointer streamingManager = RAMDrivenStrippedStreamingManagerType::New(); int availableRAM = GetParameterInt("ram"); streamingManager->SetAvailableRAMInMB(availableRAM); float bias = 1.5; // empric value; streamingManager->SetBias(bias); FloatVectorImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion(); FloatVectorImageType::SizeType largestRegionSize = largestRegion.GetSize(); streamingManager->PrepareStreaming(inImage, largestRegion); unsigned long nbDivisions = streamingManager->GetNumberOfSplits(); unsigned long largestPixNb = largestRegionSize[0] * largestRegionSize[1]; unsigned long maxPixNb = largestPixNb / nbDivisions; if (GetParameterInt("ts") > static_cast<int> (maxPixNb)) { otbAppLogWARNING(" available RAM is too small to process this sample size is.Sample size will be reduced to "<<maxPixNb<<std::endl); this->SetParameterInt("ts", maxPixNb); } this->SetMaximumParameterIntValue("ts", maxPixNb); } } void DoExecute() { GetLogger()->Debug("Entering DoExecute\n"); m_InImage = GetParameterImage("in"); m_InImage->UpdateOutputInformation(); UInt8ImageType::Pointer maskImage = GetParameterUInt8Image("vm"); maskImage->UpdateOutputInformation(); std::ostringstream message(""); int nbsamples = GetParameterInt("ts"); const unsigned int nbClasses = GetParameterInt("nc"); /*******************************************/ /* Sampling data */ /*******************************************/otbAppLogINFO("-- SAMPLING DATA --"<<std::endl); // Update input images information m_InImage->UpdateOutputInformation(); maskImage->UpdateOutputInformation(); if (m_InImage->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion()) { GetLogger()->Error("Mask image and input image have different sizes."); } // Training sample lists ListSampleType::Pointer sampleList = ListSampleType::New(); unsigned int init_means_index = 0; // Sample dimension and max dimension const unsigned int nbComp = m_InImage->GetNumberOfComponentsPerPixel(); unsigned int sampleSize = nbComp; unsigned int totalSamples = 0; // sampleSize = std::min(nbComp, maxDim); EstimatorType::ParametersType initialMeans(nbComp * nbClasses); initialMeans.Fill(0); // use image and mask shrink ImageSamplingFilterType::Pointer imageSampler = ImageSamplingFilterType::New(); imageSampler->SetInput(m_InImage); MaskSamplingFilterType::Pointer maskSampler = MaskSamplingFilterType::New(); maskSampler->SetInput(maskImage); double theoricNBSamplesForKMeans = nbsamples; const double upperThresholdNBSamplesForKMeans = 1000 * 1000; const double actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans, upperThresholdNBSamplesForKMeans); otbAppLogINFO(<<actualNBSamplesForKMeans<<" is the maximum sample size that will be used."<<std::endl); const double shrinkFactor = vcl_floor( vcl_sqrt( m_InImage->GetLargestPossibleRegion().GetNumberOfPixels() / actualNBSamplesForKMeans)); imageSampler->SetShrinkFactor(shrinkFactor); imageSampler->Update(); maskSampler->SetShrinkFactor(shrinkFactor); maskSampler->Update(); // Then, build the sample list IteratorType it(imageSampler->GetOutput(), imageSampler->GetOutput()->GetLargestPossibleRegion()); LabeledIteratorType m_MaskIt(maskSampler->GetOutput(), maskSampler->GetOutput()->GetLargestPossibleRegion()); it.GoToBegin(); m_MaskIt.GoToBegin(); SampleType min; SampleType max; SampleType sample; //first sample while (!it.IsAtEnd() && !m_MaskIt .IsAtEnd() && (m_MaskIt.Get() <= 0)) { ++it; ++m_MaskIt; } min = it.Get(); max = it.Get(); sample = it.Get(); sampleList->PushBack(sample); ++it; ++m_MaskIt; totalSamples = 1; while (!it.IsAtEnd() && !m_MaskIt .IsAtEnd()) { if (m_MaskIt.Get() > 0) { totalSamples++; sample = it.Get(); sampleList->PushBack(sample); for (unsigned int i = 0; i < nbComp; ++i) { if (min[i] > sample[i]) { min[i] = sample[i]; } if (max[i] < sample[i]) { max[i] = sample[i]; } } } ++it; ++m_MaskIt; } // Next, initialize centroids for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex) { for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex) { initialMeans[compIndex + classIndex * sampleSize] = min[compIndex] + (max[compIndex] - min[compIndex]) * rand() / (RAND_MAX + 1.0); } } otbAppLogINFO(<<totalSamples <<" samples will be used as estimator input."<<std::endl); /*******************************************/ /* Learning */ /*******************************************/ otbAppLogINFO("-- LEARNING --" << std::endl); otbAppLogINFO("Initial centroids are: " << std::endl); message.clear(); message << std::endl; for (unsigned int i = 0; i < nbClasses; ++i) { message << "Class " << i << ": "; for (unsigned int j = 0; j < sampleSize; ++j) { message << std::setw(8) << initialMeans[i * sampleSize + j] << " "; } message << std::endl; } message << std::endl; GetLogger()->Info(message.str()); message.clear(); otbAppLogINFO("Starting optimization." << std::endl); EstimatorType::Pointer estimator = EstimatorType::New(); TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New(); treeGenerator->SetSample(sampleList); treeGenerator->SetBucketSize(10000); treeGenerator->Update(); estimator->SetParameters(initialMeans); estimator->SetKdTree(treeGenerator->GetOutput()); int maxIt = GetParameterInt("maxit"); estimator->SetMaximumIteration(maxIt); estimator->SetCentroidPositionChangesThreshold(GetParameterFloat("ct")); estimator->StartOptimization(); EstimatorType::ParametersType estimatedMeans = estimator->GetParameters(); otbAppLogINFO("Optimization completed." ); if (estimator->GetCurrentIteration() == maxIt) { otbAppLogWARNING("estimator reached maximum iteration number."<<std::endl); } message.clear(); message << "Estimated centroids are: " << std::endl; message << std::endl; for (unsigned int i = 0; i < nbClasses; ++i) { message << "Class " << i << ": "; for (unsigned int j = 0; j < sampleSize; ++j) { message << std::setw(8) << estimatedMeans[i * sampleSize + j] << " "; } message << std::endl; } message << std::endl; message << "Learning completed." << std::endl; message << std::endl; GetLogger()->Info(message.str()); /*******************************************/ /* Classification */ /*******************************************/ otbAppLogINFO("-- CLASSIFICATION --" << std::endl); // Finally, update the KMeans filter KMeansFunctorType functor; for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex) { SampleType centroid(sampleSize); for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex) { centroid[compIndex] = estimatedMeans[compIndex + classIndex * sampleSize]; } functor.AddCentroid(classIndex, centroid); } m_KMeansFilter = KMeansFilterType::New(); m_KMeansFilter->SetFunctor(functor); m_KMeansFilter->SetInput(m_InImage); SetParameterOutputImage<LabeledImageType> ("out", m_KMeansFilter->GetOutput()); } // KMeans filter KMeansFilterType::Pointer m_KMeansFilter; FloatVectorImageType::Pointer m_InImage; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification) <commit_msg>ENH: KMeans application code change.<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbVectorImage.h" #include "otbImage.h" #include "itkEuclideanDistance.h" #include "otbStreamingTraits.h" #include "itkImageRegionConstIterator.h" #include "itkListSample.h" #include "itkWeightedCentroidKdTreeGenerator.h" #include "itkKdTreeBasedKmeansEstimator.h" #include "otbStreamingShrinkImageFilter.h" #include "itkUnaryFunctorImageFilter.h" #include "otbChangeLabelImageFilter.h" #include "otbRAMDrivenTiledStreamingManager.h" #include "otbRAMDrivenStrippedStreamingManager.h" namespace otb { namespace Wrapper { namespace Functor { template <class TSample, class TLabel> class KMeansFunctor { public: /** operator */ TLabel operator ()(const TSample& sample) const { typename CentroidMapType::const_iterator it = m_CentroidsMap.begin(); if (it == m_CentroidsMap.end()) { return 0; } TLabel resp = it->first; double minDist = m_Distance->Evaluate(sample, it->second); ++it; while (it != m_CentroidsMap.end()) { double dist = m_Distance->Evaluate(sample, it->second); if (dist < minDist) { resp = it->first; minDist = dist; } ++it; } return resp; } /** Add a new centroid */ void AddCentroid(const TLabel& label, const TSample& centroid) { m_CentroidsMap[label] = centroid; } /** Constructor */ KMeansFunctor() : m_CentroidsMap(), m_Distance() { m_Distance = DistanceType::New(); } bool operator !=(const KMeansFunctor& other) const { return m_CentroidsMap != other.m_CentroidsMap; } private: typedef std::map<TLabel, TSample> CentroidMapType; typedef itk::Statistics::EuclideanDistance<TSample> DistanceType; CentroidMapType m_CentroidsMap; typename DistanceType::Pointer m_Distance; }; } typedef FloatImageType::PixelType PixelType; typedef UInt8ImageType LabeledImageType; typedef LabeledImageType::PixelType LabelType; typedef FloatVectorImageType::PixelType SampleType; typedef itk::Statistics::ListSample<SampleType> ListSampleType; typedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType; typedef TreeGeneratorType::KdTreeType TreeType; typedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType; typedef RAMDrivenStrippedStreamingManager<FloatVectorImageType> RAMDrivenStrippedStreamingManagerType; typedef itk::ImageRegionConstIterator<FloatVectorImageType> IteratorType; typedef itk::ImageRegionConstIterator<LabeledImageType> LabeledIteratorType; typedef otb::StreamingShrinkImageFilter<FloatVectorImageType, FloatVectorImageType> ImageSamplingFilterType; typedef otb::StreamingShrinkImageFilter<LabeledImageType, UInt8ImageType> MaskSamplingFilterType; typedef Functor::KMeansFunctor<SampleType, LabelType> KMeansFunctorType; typedef itk::UnaryFunctorImageFilter<FloatVectorImageType, LabeledImageType, KMeansFunctorType> KMeansFilterType; class KMeansClassification: public Application { public: /** Standard class typedefs. */ typedef KMeansClassification Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(KMeansClassification, otb::Application); private: KMeansClassification() { SetName("KMeansClassification"); SetDescription("Unsupervised KMeans image classification"); SetDocName("Unsupervised KMeans image classification Application"); SetDocLongDescription("Performs Unsupervised KMeans image classification."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Segmentation); AddDocTag(Tags::Learning); } virtual ~KMeansClassification() { } void DoCreateParameters() { AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in","Input image filename."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out","Output image filename."); AddParameter(ParameterType_RAM, "ram", "Available RAM"); SetDefaultParameterInt("ram", 256); MandatoryOff("ram"); AddParameter(ParameterType_InputImage, "vm", "Validity Mask"); SetParameterDescription("vm","Validity mask. Only non-zero pixels will be used to estimate KMeans modes."); AddParameter(ParameterType_Int, "ts", "Training set size"); SetParameterDescription("ts", "Size of the training set."); SetDefaultParameterInt("ts", 100); MandatoryOff("ts"); AddParameter(ParameterType_Int, "nc", "Number of classes"); SetParameterDescription("nc","number of modes, which will be used to generate class membership."); SetDefaultParameterInt("nc", 3); AddParameter(ParameterType_Int, "maxit", "Maximum number of iterations"); SetParameterDescription("maxit", "Maximum number of iterations."); SetDefaultParameterFloat("maxit", 1000); AddParameter(ParameterType_Float, "ct", "Convergence threshold"); SetParameterDescription("ct", "Convergence threshold for class centroid (L2 distance, by default 0.01)."); SetDefaultParameterFloat("ct", 0.01); // Doc example parameter settings SetDocExampleParameterValue("in", "qb_RoadExtract.img"); SetDocExampleParameterValue("vm", "qb_RoadExtract_mask.png"); SetDocExampleParameterValue("ts", "1000"); SetDocExampleParameterValue("nc", "5"); SetDocExampleParameterValue("maxit", "1000"); SetDocExampleParameterValue("ct", "0.01"); SetDocExampleParameterValue("out", "ClassificationFilterOuptut.tif"); } void DoUpdateParameters() { // test of input image // if (HasValue("in")) { // input image FloatVectorImageType::Pointer inImage = GetParameterImage("in"); RAMDrivenStrippedStreamingManagerType::Pointer streamingManager = RAMDrivenStrippedStreamingManagerType::New(); int availableRAM = GetParameterInt("ram"); streamingManager->SetAvailableRAMInMB(availableRAM); float bias = 1.5; // empric value; streamingManager->SetBias(bias); FloatVectorImageType::RegionType largestRegion = inImage->GetLargestPossibleRegion(); FloatVectorImageType::SizeType largestRegionSize = largestRegion.GetSize(); streamingManager->PrepareStreaming(inImage, largestRegion); unsigned long nbDivisions = streamingManager->GetNumberOfSplits(); unsigned long largestPixNb = largestRegionSize[0] * largestRegionSize[1]; unsigned long maxPixNb = largestPixNb / nbDivisions; if (GetParameterInt("ts") > static_cast<int> (maxPixNb)) { otbAppLogWARNING(" available RAM is too small to process this sample size is.Sample size will be reduced to "<<maxPixNb<<std::endl); this->SetParameterInt("ts", maxPixNb); } this->SetMaximumParameterIntValue("ts", maxPixNb); } } void DoExecute() { GetLogger()->Debug("Entering DoExecute\n"); m_InImage = GetParameterImage("in"); m_InImage->UpdateOutputInformation(); UInt8ImageType::Pointer maskImage = GetParameterUInt8Image("vm"); maskImage->UpdateOutputInformation(); std::ostringstream message(""); int nbsamples = GetParameterInt("ts"); const unsigned int nbClasses = GetParameterInt("nc"); /*******************************************/ /* Sampling data */ /*******************************************/otbAppLogINFO("-- SAMPLING DATA --"<<std::endl); // Update input images information m_InImage->UpdateOutputInformation(); maskImage->UpdateOutputInformation(); if (m_InImage->GetLargestPossibleRegion() != maskImage->GetLargestPossibleRegion()) { GetLogger()->Error("Mask image and input image have different sizes."); } // Training sample lists ListSampleType::Pointer sampleList = ListSampleType::New(); unsigned int init_means_index = 0; // Sample dimension and max dimension const unsigned int nbComp = m_InImage->GetNumberOfComponentsPerPixel(); unsigned int sampleSize = nbComp; unsigned int totalSamples = 0; // sampleSize = std::min(nbComp, maxDim); EstimatorType::ParametersType initialMeans(nbComp * nbClasses); initialMeans.Fill(0); // use image and mask shrink ImageSamplingFilterType::Pointer imageSampler = ImageSamplingFilterType::New(); imageSampler->SetInput(m_InImage); MaskSamplingFilterType::Pointer maskSampler = MaskSamplingFilterType::New(); maskSampler->SetInput(maskImage); double theoricNBSamplesForKMeans = nbsamples; const double upperThresholdNBSamplesForKMeans = 1000 * 1000; const double actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans, upperThresholdNBSamplesForKMeans); otbAppLogINFO(<<actualNBSamplesForKMeans<<" is the maximum sample size that will be used."<<std::endl); const double shrinkFactor = vcl_floor( vcl_sqrt( m_InImage->GetLargestPossibleRegion().GetNumberOfPixels() / actualNBSamplesForKMeans)); imageSampler->SetShrinkFactor(shrinkFactor); imageSampler->Update(); maskSampler->SetShrinkFactor(shrinkFactor); maskSampler->Update(); // Then, build the sample list IteratorType it(imageSampler->GetOutput(), imageSampler->GetOutput()->GetLargestPossibleRegion()); LabeledIteratorType m_MaskIt(maskSampler->GetOutput(), maskSampler->GetOutput()->GetLargestPossibleRegion()); it.GoToBegin(); m_MaskIt.GoToBegin(); SampleType min; SampleType max; SampleType sample; //first sample while (!it.IsAtEnd() && !m_MaskIt .IsAtEnd() && (m_MaskIt.Get() <= 0)) { ++it; ++m_MaskIt; } min = it.Get(); max = it.Get(); sample = it.Get(); sampleList->PushBack(sample); ++it; ++m_MaskIt; totalSamples = 1; while (!it.IsAtEnd() && !m_MaskIt .IsAtEnd()) { if (m_MaskIt.Get() > 0) { totalSamples++; sample = it.Get(); sampleList->PushBack(sample); for (unsigned int i = 0; i < nbComp; ++i) { if (min[i] > sample[i]) { min[i] = sample[i]; } if (max[i] < sample[i]) { max[i] = sample[i]; } } } ++it; ++m_MaskIt; } // Next, initialize centroids for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex) { for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex) { initialMeans[compIndex + classIndex * sampleSize] = min[compIndex] + (max[compIndex] - min[compIndex]) * rand() / (RAND_MAX + 1.0); } } otbAppLogINFO(<<totalSamples <<" samples will be used as estimator input."<<std::endl); /*******************************************/ /* Learning */ /*******************************************/ otbAppLogINFO("-- LEARNING --" << std::endl); otbAppLogINFO("Initial centroids are: " << std::endl); message.clear(); message << std::endl; for (unsigned int i = 0; i < nbClasses; ++i) { message << "Class " << i << ": "; for (unsigned int j = 0; j < sampleSize; ++j) { message << std::setw(8) << initialMeans[i * sampleSize + j] << " "; } message << std::endl; } message << std::endl; GetLogger()->Info(message.str()); message.clear(); otbAppLogINFO("Starting optimization." << std::endl); EstimatorType::Pointer estimator = EstimatorType::New(); TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New(); treeGenerator->SetSample(sampleList); treeGenerator->SetBucketSize(10000); treeGenerator->Update(); estimator->SetParameters(initialMeans); estimator->SetKdTree(treeGenerator->GetOutput()); int maxIt = GetParameterInt("maxit"); estimator->SetMaximumIteration(maxIt); estimator->SetCentroidPositionChangesThreshold(GetParameterFloat("ct")); estimator->StartOptimization(); EstimatorType::ParametersType estimatedMeans = estimator->GetParameters(); otbAppLogINFO("Optimization completed." ); if (estimator->GetCurrentIteration() == maxIt) { otbAppLogWARNING("estimator reached maximum iteration number."<<std::endl); } message.clear(); message << "Estimated centroids are: " << std::endl; message << std::endl; for (unsigned int i = 0; i < nbClasses; ++i) { message << "Class " << i << ": "; for (unsigned int j = 0; j < sampleSize; ++j) { message << std::setw(8) << estimatedMeans[i * sampleSize + j] << " "; } message << std::endl; } message << std::endl; message << "Learning completed." << std::endl; message << std::endl; GetLogger()->Info(message.str()); /*******************************************/ /* Classification */ /*******************************************/ otbAppLogINFO("-- CLASSIFICATION --" << std::endl); // Finally, update the KMeans filter KMeansFunctorType functor; for (unsigned int classIndex = 0; classIndex < nbClasses; ++classIndex) { SampleType centroid(sampleSize); for (unsigned int compIndex = 0; compIndex < sampleSize; ++compIndex) { centroid[compIndex] = estimatedMeans[compIndex + classIndex * sampleSize]; } functor.AddCentroid(classIndex, centroid); } m_KMeansFilter = KMeansFilterType::New(); m_KMeansFilter->SetFunctor(functor); m_KMeansFilter->SetInput(m_InImage); SetParameterOutputImage("out", m_KMeansFilter->GetOutput()); } // KMeans filter KMeansFilterType::Pointer m_KMeansFilter; FloatVectorImageType::Pointer m_InImage; }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification) <|endoftext|>
<commit_before>#include "precompiled.hpp" #include "util/MetaTypeConverters.hpp" #include "util/TypeInfo.hpp" #include <QString> #include <QtTest> #include <QList> #include <QCoreApplication> #include "ui/Uniforms.hpp" #include "util/Logging.hpp" using namespace glm; using balls::Uniforms; using balls::UniformCollection; using balls::UniformInfo; class TestUniformsTest : public QObject { Q_OBJECT private slots: void initTestCase(); void elapsedTimeIncreases(); void elapsedTimeIsUInt(); void filtersEvents(); void mouseCoordinates(); void mouseCoordinates_data(); void receiveUniforms(); void receiveUniforms_data(); void rejectInvalidTypes(); void rejectInvalidTypes_data(); void handleUnsupportedTypes(); void handleUnsupportedTypes_data(); void uniformsRemoved(); void uniformsRemoved_data(); void uniformsAdded(); void uniformsAdded_data(); void uniformsRetyped(); void uniformsRetyped_data(); }; void TestUniformsTest::initTestCase() { QLoggingCategory::setFilterRules("uniform*=false"); balls::registerMetaTypeConverters(); balls::util::types::init(); QVERIFY(balls::util::types::info.size() > 0); QVERIFY(QMetaType::type("vec2") != QMetaType::UnknownType); } void TestUniformsTest::uniformsRetyped() { } void TestUniformsTest::uniformsRetyped_data() { } void TestUniformsTest::uniformsAdded() { } void TestUniformsTest::uniformsAdded_data() { } void TestUniformsTest::uniformsRemoved() { } void TestUniformsTest::uniformsRemoved_data() { } void TestUniformsTest::handleUnsupportedTypes() { } void TestUniformsTest::handleUnsupportedTypes_data() { } void TestUniformsTest::rejectInvalidTypes() { } void TestUniformsTest::rejectInvalidTypes_data() { } void TestUniformsTest::receiveUniforms_data() { QTest::addColumn<UniformCollection>("beforeCompile"); QTest::addColumn<UniformCollection>("result"); QTest::newRow("empty -> empty") << UniformCollection {} << UniformCollection {}; QTest::newRow("empty -> one matrix") << UniformCollection { } << UniformCollection { { "matrix", GL_FLOAT_MAT4, 1 } }; QTest::newRow("one matrix -> empty") << UniformCollection { { "matrix", GL_FLOAT_MAT4, 1 } } << UniformCollection { }; QTest::newRow("matrix -> vector") << UniformCollection { { "matrix", GL_FLOAT_MAT4, 1 } } << UniformCollection { { "matrix", GL_FLOAT_VEC4, 1 } }; QTest::newRow("rearrange") << UniformCollection { { "matrix", GL_DOUBLE_MAT4, 1}, { "scale", GL_FLOAT, 1}, { "available", GL_BOOL, 1}, } << UniformCollection { { "available", GL_BOOL, 1}, { "matrix", GL_DOUBLE_MAT4, 1}, { "scale", GL_FLOAT, 1}, }; QTest::newRow("rearrange and change types") << UniformCollection { { "mvp", GL_FLOAT_MAT3, 1 }, { "color", GL_FLOAT_VEC4, 1 }, { "repetitions", GL_INT, 1 }, { "seed", GL_INT_VEC2, 1 }, } << UniformCollection { { "color", GL_DOUBLE_VEC4, 1 }, { "seed", GL_UNSIGNED_INT, 1 }, { "mvp", GL_FLOAT_MAT3x4, 1 }, { "repetitions", GL_UNSIGNED_INT, 1 }, }; QTest::newRow("unsupported types") << UniformCollection { { "coords", GL_FLOAT_VEC2, 1 }, { "threshold", GL_FLOAT, 1 }, } << UniformCollection { { "threshold", GL_FLOAT, 1 }, { "texture", GL_SAMPLER_2D, 1 }, { "coords", GL_FLOAT_VEC2, 1 }, { "palette", GL_INT_SAMPLER_1D, 1 }, }; } void TestUniformsTest::receiveUniforms() { QFETCH(UniformCollection, beforeCompile); QFETCH(UniformCollection, result); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); uniforms.receiveUniforms(beforeCompile); QCOMPARE(uniforms.uniformInfo(), beforeCompile); uniforms.receiveUniforms(result); QCOMPARE(uniforms.uniformInfo(), result); } void TestUniformsTest::mouseCoordinates_data() { QTest::addColumn<QList<QPoint>>("points"); using QPointList = QList<QPoint>; QTest::newRow("basic") << QPointList {{1, 1}, {42, 43}, {100, 99}}; QTest::newRow("one motion") << QPointList {{0, 0}, {77, 74}}; QTest::newRow("not moving") << QPointList {{0, 0}, {0, 0}, {0, 0}}; QTest::newRow("negative") << QPointList {{ -1, -43}, { -119, -32}, { -55, -22}}; QTest::newRow("change signs") << QPointList {{0, 0}, {34, -66}, { -22, 78}, { -99, -101}, {0, 0}, {1, 0}}; } void TestUniformsTest::mouseCoordinates() { QFETCH(QList<QPoint>, points); Q_ASSERT(points.length() >= 2); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); for (const QPoint& p : points) { QMouseEvent event(QEvent::MouseMove, p, Qt::NoButton, Qt::NoButton, Qt::NoModifier); QCoreApplication::sendEvent(&object, &event); // WORKAROUND: QTest::mouseMove doesn't actually fire a QMouseEvent (it just sets the mouse cursor) } ivec2 mousePos = uniforms.property("mousePos").value<ivec2>(); ivec2 lastMousePos = uniforms.property("lastMousePos").value<ivec2>(); const QPoint& pos = points.last(); const QPoint& lastPos = points[points.length() - 2]; QCOMPARE(mousePos.x, pos.x()); QCOMPARE(mousePos.y, pos.y()); QCOMPARE(lastMousePos.x, lastPos.x()); QCOMPARE(lastMousePos.y, lastPos.y()); } void TestUniformsTest::filtersEvents() { QObject object; Uniforms uniforms; QSize size {100, 100}; QResizeEvent resize {size, {2, 2}}; object.installEventFilter(&uniforms); QCoreApplication::sendEvent(&object, &resize); ivec2 canvasSize = uniforms.property("canvasSize").value<ivec2>(); QCOMPARE(canvasSize.x, size.width()); QCOMPARE(canvasSize.y, size.height()); } void TestUniformsTest::elapsedTimeIsUInt() { Uniforms uniforms; QVariant a = uniforms.property("elapsedTime"); QCOMPARE(a.type(), QVariant::UInt); } void TestUniformsTest::elapsedTimeIncreases() { Uniforms uniforms; QTest::qSleep(50); uint a = uniforms.property("elapsedTime").toUInt(); QTest::qSleep(50); uint b = uniforms.property("elapsedTime").toUInt(); QTest::qSleep(50); uint c = uniforms.property("elapsedTime").toUInt(); QVERIFY(a != 0); QVERIFY(b != 0); QVERIFY(c != 0); QVERIFY(b > a); QVERIFY(c > b); } QTEST_MAIN(TestUniformsTest) #include "tst_TestUniformsTest.moc" <commit_msg>Lots of tests for Uniforms<commit_after>#include "precompiled.hpp" #include "util/MetaTypeConverters.hpp" #include "util/TypeInfo.hpp" #include <initializer_list> #include <utility> #include <QString> #include <QtTest> #include <QList> #include <QCoreApplication> #include "ui/Uniforms.hpp" #include "util/Logging.hpp" using std::tuple; using std::get; using std::initializer_list; using namespace glm; using balls::Uniforms; using balls::UniformCollection; using balls::UniformInfo; struct UniformTestDatum { template<class T> UniformTestDatum(const UniformInfo& u, const T& v) : uniform(u), value(QVariant::fromValue(v)) {} UniformInfo uniform; QVariant value; }; struct UniformTestData { UniformTestData() = default; UniformTestData(const initializer_list<UniformTestDatum>& init) { for (const UniformTestDatum& i : init) { uniforms.push_back(i.uniform); values[i.uniform.name] = i.value; } } UniformCollection uniforms; QVariantMap values; }; Q_DECLARE_METATYPE(UniformTestData) // TODO: Add values to the uniform test cases (to properly test conversions and // retyped values) class TestUniformsTest : public QObject { Q_OBJECT private slots /* general testing */: void initTestCase(); private slots /* general functionality */: void receiveUniforms(); void receiveUniforms_data(); void filterInvalidTypes(); void filterInvalidTypes_data(); void filtersEvents(); void designableIsUpdated(); private slots /* static properties (aka built-in uniforms) */: void elapsedTimeIncreases(); void elapsedTimeIsUInt(); void mouseCoordinates(); void mouseCoordinates_data(); void canvasSize(); void canvasSize_data(); }; void TestUniformsTest::initTestCase() { QLoggingCategory::setFilterRules("uniform*=false"); balls::registerMetaTypeConverters(); balls::util::types::init(); QVERIFY(balls::util::types::info.size() > 0); QVERIFY(QMetaType::type("vec2") != QMetaType::UnknownType); } void TestUniformsTest::filterInvalidTypes_data() { QTest::addColumn<UniformTestData>("invalid"); QTest::addColumn<UniformTestData>("expected"); QTest::newRow("one invalid") << UniformTestData { { {"france", 0, 1}, 0}, } << UniformTestData { }; QTest::newRow("multiple invalid") << UniformTestData { { {"france", 0, 1}, 0}, { {"spain", 12, 16}, 32}, } << UniformTestData { }; QTest::newRow("valid at beginning") << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, { { "bad", 17, 17 }, 32 }, { { "nah", 21, 16 }, 12 }, } << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, }; QTest::newRow("valid in middle") << UniformTestData { { { "bad", 17, 17 }, 32 }, { { "wow", GL_INT, 1 }, 42 }, { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "nah", 21, 16 }, 12 }, } << UniformTestData { { { "wow", GL_INT, 1 }, 42 }, { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, }; QTest::newRow("valid at end") << UniformTestData { { { "bad", 17, 17 }, 32 }, { { "nah", 21, 16 }, 12 }, { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, } << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, }; QTest::newRow("valid interleaved") << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "bad", 17, 17 }, 32 }, { { "wow", GL_INT, 1 }, 42 }, { { "nah", 21, 16 }, 12 }, } << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, }; QTest::newRow("valid at edges") << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "bad", 17, 17 }, 32 }, { { "nah", 21, 16 }, 12 }, { { "wow", GL_INT, 1 }, 42 }, } << UniformTestData { { { "mat", GL_FLOAT_MAT4, 1 }, mat4() }, { { "wow", GL_INT, 1 }, 42 }, }; } void TestUniformsTest::filterInvalidTypes() { QFETCH(UniformTestData, invalid); QFETCH(UniformTestData, expected); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); uniforms.receiveUniforms(invalid.uniforms); QCOMPARE(uniforms.uniformInfo(), expected.uniforms); } void TestUniformsTest::designableIsUpdated() { Uniforms uniforms; QObject object; object.installEventFilter(&uniforms); const QMetaObject* meta = uniforms.metaObject(); QMetaProperty matrix = meta->property(meta->indexOfProperty("matrix")); QMetaProperty mousePos = meta->property(meta->indexOfProperty("mousePos")); Q_ASSERT(matrix.isValid()); Q_ASSERT(mousePos.isValid()); uniforms.receiveUniforms({ UniformInfo {"matrix", GL_FLOAT_MAT4, 1} }); QVERIFY(matrix.isDesignable(&uniforms)); QVERIFY(!mousePos.isDesignable(&uniforms)); uniforms.receiveUniforms({ UniformInfo {"mousePos", GL_INT_VEC2, 1} }); QVERIFY(!matrix.isDesignable(&uniforms)); QVERIFY(mousePos.isDesignable(&uniforms)); uniforms.receiveUniforms({ UniformInfo {"matrix", GL_FLOAT_MAT4, 1}, UniformInfo {"mousePos", GL_INT_VEC2, 1}, }); QVERIFY(matrix.isDesignable(&uniforms)); QVERIFY(mousePos.isDesignable(&uniforms)); uniforms.receiveUniforms({}); QVERIFY(!matrix.isDesignable(&uniforms)); QVERIFY(!mousePos.isDesignable(&uniforms)); } void TestUniformsTest::receiveUniforms_data() { QTest::addColumn<UniformTestData>("before"); QTest::addColumn<UniformTestData>("after"); QTest::newRow("empty -> empty") << UniformTestData {} << UniformTestData {}; QTest::newRow("empty -> one") << UniformTestData { } << UniformTestData {{ { {"mat", GL_FLOAT_MAT4, 1}, mat4() } } }; QTest::newRow("one -> empty") << UniformTestData {{ { {"mat", GL_FLOAT_MAT4, 1}, mat4() } } } << UniformTestData { }; QTest::newRow("matrix -> vector") << UniformTestData {{ { {"mat", GL_FLOAT_MAT4, 1}, mat4(4) } } } << UniformTestData {{ { {"mat", GL_FLOAT_VEC4, 1}, vec4(4, 0, 0, 0) } } }; QTest::newRow("rearrange") << UniformTestData {{ { {"mat", GL_DOUBLE_MAT4, 1}, dmat4()}, { {"scale", GL_FLOAT, 1}, 1.0f}, { {"available", GL_BOOL, 1}, true}, } } << UniformTestData {{ { {"available", GL_BOOL, 1}, true}, { {"mat", GL_DOUBLE_MAT4, 1}, dmat4()}, { {"scale", GL_FLOAT, 1}, 1.0f}, } }; QTest::newRow("rearrange and change types") << UniformTestData {{ { {"mvp", GL_FLOAT_MAT3, 1}, mat3() }, { {"color", GL_FLOAT_VEC4, 1}, vec4(0.5, 0.0, 0.0, 0.0) }, { {"repetitions", GL_INT, 1}, 74 }, { {"seed", GL_INT_VEC2, 1}, ivec2(16, 14)}, } } << UniformTestData {{ { {"color", GL_DOUBLE_VEC4, 1}, dvec4(0.5, 0.0, 0.0, 0.0) }, { {"seed", GL_UNSIGNED_INT, 1}, 16u }, { {"mvp", GL_FLOAT_MAT3x4, 1}, mat3x4() }, { {"repetitions", GL_UNSIGNED_INT, 1}, 74u }, } }; QTest::newRow("unsupported types") << UniformTestData {{ { {"coords", GL_FLOAT_VEC2, 1}, vec2() }, { {"threshold", GL_FLOAT, 1}, 1.0f }, } } << UniformTestData {{ { {"threshold", GL_FLOAT, 1}, 1.0f }, { {"texture", GL_SAMPLER_2D, 1}, 0 }, { {"coords", GL_FLOAT_VEC2, 1}, vec2() }, { {"palette", GL_INT_SAMPLER_1D, 1}, 1 }, } }; } void TestUniformsTest::receiveUniforms() { QFETCH(UniformTestData, before); QFETCH(UniformTestData, after); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); uniforms.receiveUniforms(before.uniforms); QCOMPARE(uniforms.uniformInfo(), before.uniforms); uniforms.receiveUniforms(after.uniforms); QCOMPARE(uniforms.uniformInfo(), after.uniforms); for (const UniformInfo& u : uniforms.uniformInfo()) { QCOMPARE(uniforms.property(qPrintable(u.name)), after.values[u.name]); } } void TestUniformsTest::mouseCoordinates_data() { QTest::addColumn<QList<QPoint>>("points"); using QPointList = QList<QPoint>; QTest::newRow("basic") << QPointList {{1, 1}, {42, 43}, {100, 99}}; QTest::newRow("one motion") << QPointList {{0, 0}, {77, 74}}; QTest::newRow("not moving") << QPointList {{0, 0}, {0, 0}, {0, 0}}; QTest::newRow("negative") << QPointList {{ -1, -43}, { -119, -32}, { -55, -22}}; QTest::newRow("change signs") << QPointList {{0, 0}, {34, -66}, { -22, 78}, { -99, -101}, {0, 0}, {1, 0}}; } void TestUniformsTest::mouseCoordinates() { QFETCH(QList<QPoint>, points); Q_ASSERT(points.length() >= 2); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); for (const QPoint& p : points) { QMouseEvent event(QEvent::MouseMove, p, Qt::NoButton, Qt::NoButton, Qt::NoModifier); QCoreApplication::sendEvent(&object, &event); // WORKAROUND: QTest::mouseMove doesn't actually fire a QMouseEvent (it just sets the mouse cursor) } ivec2 mousePos = uniforms.property("mousePos").value<ivec2>(); ivec2 lastMousePos = uniforms.property("lastMousePos").value<ivec2>(); const QPoint& pos = points.last(); const QPoint& lastPos = points[points.length() - 2]; QCOMPARE(mousePos.x, pos.x()); QCOMPARE(mousePos.y, pos.y()); QCOMPARE(lastMousePos.x, lastPos.x()); QCOMPARE(lastMousePos.y, lastPos.y()); } void TestUniformsTest::canvasSize_data() { QTest::addColumn<QList<QSize>>("sizes"); using QSizeList = QList<QSize>; QTest::newRow("basic") << QSizeList {{1, 1}, {42, 43}, {100, 99}}; QTest::newRow("one resize") << QSizeList {{1, 1}, {77, 74}}; QTest::newRow("grow then shrink") << QSizeList {{1, 1}, {45, 76}, {12, 100}, {34, 99}}; } void TestUniformsTest::canvasSize() { QFETCH(QList<QSize>, sizes); Q_ASSERT(sizes.length() >= 2); QObject object; Uniforms uniforms; object.installEventFilter(&uniforms); for (int i = 1; i < sizes.length(); ++i) { QResizeEvent event(sizes[i], sizes[i - 1]); QCoreApplication::sendEvent(&object, &event); } uvec2 canvasSize = uniforms.property("canvasSize").value<uvec2>(); uvec2 lastCanvasSize = uniforms.property("lastCanvasSize").value<uvec2>(); uint canvasWidth = uniforms.property("canvasWidth").value<uint>(); uint canvasHeight = uniforms.property("canvasHeight").value<uint>(); const QSize& size = sizes.last(); const QSize& lastSize = sizes[sizes.length() - 2]; QCOMPARE(canvasWidth, canvasSize.x); QCOMPARE(canvasHeight, canvasSize.y); QCOMPARE(int(canvasSize.x), size.width()); QCOMPARE(int(canvasSize.y), size.height()); QCOMPARE(int(lastCanvasSize.x), lastSize.width()); QCOMPARE(int(lastCanvasSize.y), lastSize.height()); } void TestUniformsTest::filtersEvents() { QObject object; Uniforms uniforms; QSize size {100, 100}; QResizeEvent resize {size, {2, 2}}; object.installEventFilter(&uniforms); QCoreApplication::sendEvent(&object, &resize); ivec2 canvasSize = uniforms.property("canvasSize").value<ivec2>(); QCOMPARE(canvasSize.x, size.width()); QCOMPARE(canvasSize.y, size.height()); } void TestUniformsTest::elapsedTimeIsUInt() { Uniforms uniforms; QVariant a = uniforms.property("elapsedTime"); QCOMPARE(a.type(), QVariant::UInt); } void TestUniformsTest::elapsedTimeIncreases() { Uniforms uniforms; QTest::qSleep(50); uint a = uniforms.property("elapsedTime").toUInt(); QTest::qSleep(50); uint b = uniforms.property("elapsedTime").toUInt(); QTest::qSleep(50); uint c = uniforms.property("elapsedTime").toUInt(); QVERIFY(a != 0); QVERIFY(b != 0); QVERIFY(c != 0); QVERIFY(b > a); QVERIFY(c > b); } QTEST_MAIN(TestUniformsTest) #include "tst_TestUniformsTest.moc" <|endoftext|>
<commit_before>#ifndef TCL_CONTROLLER_HPP #define TCL_CONTROLLER_HPP #include <string> #include "CLDeviceInformation.hpp" #include "CLInformation.hpp" #include "CLSource.hpp" #include "CLSourceArray.hpp" #include "CLWorkGroupSettings.hpp" #include "CLExecuteProperty.hpp" #include "CLExecute.hpp" #include "CLBuffer.hpp" #include "CLReadBuffer.hpp" #include "CLReadWriteBuffer.hpp" #include "CLWriteBuffer.hpp" namespace tcl { /** * @brief foCX̎ */ enum class DeviceType { GPU, CPU }; /** * @brief TinyCL𐧌䂷邽߂̃Rg[ */ class CLController { CLSource* source; const CLDeviceInformation* device; CLWorkGroupSettings* setting; CLExecute* exec; std::vector<CLBuffer*> argumentBuffer; private: void InitSetting(const cl_uint dimension, const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (setting != nullptr) delete setting; // xĂяo΍ setting = new CLWorkGroupSettings(dimension, offset, workerRange, splitSize); setting->Optimize(*device); } public: /** * @brief TinyCL𐧌䂷邽߂̃Rg[ * \param [in] sourcePath \[XR[h̃pX * \param [in] kernelFunction Gg[|CgɂȂ֐ * \param [in] deviceType foCX̎ * \param [in] sourceType \[XR[h̎ */ CLController(const std::string& sourcePath, const std::string& kernelFunction, const DeviceType& deviceType = DeviceType::GPU, const SourceType& sourceType = SourceType::Text) { switch (deviceType) { case DeviceType::GPU: device = &information.GetGPU(); break; case DeviceType::CPU: device = &information.GetCPU(); break; } if (device == nullptr) throw CLDeviceNotFoundException("Ώۂ̃foCX‚܂ł"); source = new CLSource(sourcePath, kernelFunction, sourceType); exec = new CLExecute(*source, *device); } /** * @brief [J[̐ݒׂw肷 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ * @param [in] splitSize [J[̋؂ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (offset.size() != workerRange.size() || offset.size() != splitSize.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, splitSize); return *this; } /** * @brief ɉoffset, workerRange𑵂Ă * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange) { if (offset.size() != workerRange.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief Ƃ肠C[J[𑽎œĂ݂ƂɎg * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& workerRange) { std::vector<size_t> offset(workerRange.size(), 0); std::vector<size_t> splitSize(workerRange.size()); for (int i = 0; i < workerRange.size(); ++i) splitSize[i] = workerRange[i]; InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief 1ƂāCoffsetX^[gCworkerRange̐[J[𓮂 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& offset, const size_t& workerRange) { InitSetting(1, { offset }, { workerRange } , { workerRange }); return *this; } /** * @brief 1ƂāCwokerRange̐[J[𓮂 * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& workerRange) { InitSetting(1, { 0 }, { workerRange }, { workerRange }); return *this; } /** * R[hs * @param [in] current J[lR[ḧ */ template <typename T> CLController& Run(T& current) { argumentBuffer.push_back(&current); exec->SetArg(current); exec->Run(*setting); return *this; } /** * R[hs * @param [in] current J[lR[ḧ * @param [in] others •ϒ */ template <typename T, typename... Args> CLController& Run(T& current, Args& ...others) { exec->SetArg(current); return Run(others...); } /** * J[lR[h̎s҂ */ CLController& Wait() { exec->Wait(); return *this; } virtual ~CLController() { delete exec; delete setting; delete source; } }; } #endif<commit_msg>Run関数を用意する<commit_after>#ifndef TCL_CONTROLLER_HPP #define TCL_CONTROLLER_HPP #include <string> #include "CLDeviceInformation.hpp" #include "CLInformation.hpp" #include "CLSource.hpp" #include "CLSourceArray.hpp" #include "CLWorkGroupSettings.hpp" #include "CLExecuteProperty.hpp" #include "CLExecute.hpp" #include "CLBuffer.hpp" #include "CLReadBuffer.hpp" #include "CLReadWriteBuffer.hpp" #include "CLWriteBuffer.hpp" namespace tcl { /** * @brief foCX̎ */ enum class DeviceType { GPU, CPU }; /** * @brief TinyCL𐧌䂷邽߂̃Rg[ */ class CLController { CLSource* source; const CLDeviceInformation* device; CLWorkGroupSettings* setting; CLExecute* exec; std::vector<CLBuffer*> argWrite; std::vector<CLBuffer*> argRead; private: void InitSetting(const cl_uint dimension, const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (setting != nullptr) delete setting; // xĂяo΍ setting = new CLWorkGroupSettings(dimension, offset, workerRange, splitSize); setting->Optimize(*device); } public: /** * @brief TinyCL𐧌䂷邽߂̃Rg[ * \param [in] sourcePath \[XR[h̃pX * \param [in] kernelFunction Gg[|CgɂȂ֐ * \param [in] deviceType foCX̎ * \param [in] sourceType \[XR[h̎ */ CLController(const std::string& sourcePath, const std::string& kernelFunction, const DeviceType& deviceType = DeviceType::GPU, const SourceType& sourceType = SourceType::Text) { switch (deviceType) { case DeviceType::GPU: device = &information.GetGPU(); break; case DeviceType::CPU: device = &information.GetCPU(); break; } if (device == nullptr) throw CLDeviceNotFoundException("Ώۂ̃foCX‚܂ł"); source = new CLSource(sourcePath, kernelFunction, sourceType); exec = new CLExecute(*source, *device); } /** * @brief [J[̐ݒׂw肷 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ * @param [in] splitSize [J[̋؂ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange, const std::vector<size_t>& splitSize) { if (offset.size() != workerRange.size() || offset.size() != splitSize.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, splitSize); return *this; } /** * @brief ɉoffset, workerRange𑵂Ă * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& offset, const std::vector<size_t>& workerRange) { if (offset.size() != workerRange.size()) throw CLException("[J[̎eňvĂ܂"); InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief Ƃ肠C[J[𑽎œĂ݂ƂɎg * @param [in] workerRange [J[̐ */ CLController& Setting(const std::vector<size_t>& workerRange) { std::vector<size_t> offset(workerRange.size(), 0); std::vector<size_t> splitSize(workerRange.size()); for (int i = 0; i < workerRange.size(); ++i) splitSize[i] = workerRange[i]; InitSetting(offset.size(), offset, workerRange, workerRange); return *this; } /** * @brief 1ƂāCoffsetX^[gCworkerRange̐[J[𓮂 * @param [in] offset [J[̏ʒu * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& offset, const size_t& workerRange) { InitSetting(1, { offset }, { workerRange } , { workerRange }); return *this; } /** * @brief 1ƂāCwokerRange̐[J[𓮂 * @param [in] workerRange [J[̐ */ CLController& Setting(const size_t& workerRange) { InitSetting(1, { 0 }, { workerRange }, { workerRange }); return *this; } template <typename T> CLController& Run(CLReadBuffer<T>& buffer) { } template <typename T> CLController& Run(CLWriteBuffer<T>& buffer) { } template <typename T> CLController& Run(CLReadWriteBuffer<T>& buffer) { } /** * J[ls */ template <typename BUFFER, typename... Args> CLController& Run(BUFFER& buffer, Args&... args) { Run(args); return *this; } /** * J[lR[h̎s҂ */ CLController& Wait() { exec->Wait(); return *this; } virtual ~CLController() { delete exec; delete setting; delete source; } }; } #endif<|endoftext|>
<commit_before>#include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <cstdio> #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include <memory> #include <iostream> #include <map> #include <array> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #ifdef __APPLE__ #if TARGET_IOS #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #else #import <OpenGL/OpenGL.h> #import <OpenGL/gl3.h> #endif #else #include <GLES2/gl2.h> #endif #include "NativeBitmap.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GameNativeAPI.h" #include "WindowOperations.h" #include "Common.h" const int winWidth = 640, winHeight = 480; SDL_Window *window; SDL_GLContext glContext; bool done = false; SDL_Event event; bool windowed = false; void handleKeyPress(SDL_Event &event) { auto keysym = &event.key.keysym; switch (keysym->sym) { case SDLK_ESCAPE: SDL_Quit(); break; case SDLK_F1: SDL_SetWindowFullscreen(window, windowed ? SDL_WINDOW_FULLSCREEN : 0); windowed = !windowed; break; case SDLK_LEFT: rotateCameraLeft(); break; case SDLK_RIGHT: rotateCameraRight(); break; case SDLK_UP: moveUp(); break; case SDLK_DOWN: moveDown(); break; case SDLK_SPACE: interact(); break; case SDLK_z: moveLeft(); break; case SDLK_x: moveRight(); break; case SDLK_MINUS: cyclePrevItem(); break; case SDLK_EQUALS: cycleNextItem(); break; case SDLK_LEFTBRACKET: pickupItem(); break; case SDLK_RIGHTBRACKET: dropItem(); break; default: break; } } void initWindow() { SDL_Init(SDL_INIT_EVERYTHING); window = SDL_CreateWindow("The Dungeons of Noudar", 0, 0, winWidth, winHeight, SDL_WINDOW_OPENGL); glContext = SDL_GL_CreateContext(window); auto gVertexShader = ""; auto gFragmentShader = ""; setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, std::make_shared<Knights::CPlainFileLoader>()); auto soundListener = std::make_shared<odb::SoundListener>(); std::vector<std::shared_ptr<odb::SoundEmitter>> sounds; std::string filenames[]{ "res/grasssteps.wav", "res/stepsstones.wav", "res/bgnoise.wav", "res/monsterdamage.wav", "res/monsterdead.wav", "res/playerdamage.wav", "res/playerdead.wav", "res/swing.wav" }; for (auto filename : filenames) { FILE *file = fopen(filename.c_str(), "r"); auto soundClip = odb::makeSoundClipFrom(file); sounds.push_back(std::make_shared<odb::SoundEmitter>(soundClip)); } setSoundEmitters(sounds, soundListener); } void tick() { gameLoopTick(20); renderFrame(20); SDL_GL_SwapWindow(window); } void setMainLoop() { while (!done) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKeyPress(event); break; case SDL_QUIT: done = true; break; default: break; } } tick(); } } void destroyWindow() { shutdown(); SDL_GL_DeleteContext(glContext); } <commit_msg>Add more options of interaction keys on SDL version<commit_after>#include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/matrix_transform.hpp> #include <cstdio> #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <vector> #include <string.h> #include <memory> #include <iostream> #include <map> #include <array> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #ifdef __APPLE__ #if TARGET_IOS #import <OpenGLES/ES2/gl.h> #import <OpenGLES/ES2/glext.h> #else #import <OpenGL/OpenGL.h> #import <OpenGL/gl3.h> #endif #else #include <GLES2/gl2.h> #endif #include "NativeBitmap.h" #include "SoundClip.h" #include "SoundUtils.h" #include "SoundListener.h" #include "SoundEmitter.h" #include "IFileLoaderDelegate.h" #include "CPlainFileLoader.h" #include "Vec2i.h" #include "NativeBitmap.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "CMap.h" #include "IRenderer.h" #include "NoudarDungeonSnapshot.h" #include "GameNativeAPI.h" #include "WindowOperations.h" #include "Common.h" const int winWidth = 640, winHeight = 480; SDL_Window *window; SDL_GLContext glContext; bool done = false; SDL_Event event; bool windowed = false; void handleKeyPress(SDL_Event &event) { auto keysym = &event.key.keysym; switch (keysym->sym) { case SDLK_ESCAPE: SDL_Quit(); break; case SDLK_F1: SDL_SetWindowFullscreen(window, windowed ? SDL_WINDOW_FULLSCREEN : 0); windowed = !windowed; break; case SDLK_LEFT: rotateCameraLeft(); break; case SDLK_RIGHT: rotateCameraRight(); break; case SDLK_UP: moveUp(); break; case SDLK_DOWN: moveDown(); break; case SDLK_SPACE: interact(); break; case SDLK_z: moveLeft(); break; case SDLK_x: moveRight(); break; case SDLK_MINUS: case SDLK_e: cyclePrevItem(); break; case SDLK_EQUALS: case SDLK_d: cycleNextItem(); break; case SDLK_w: case SDLK_LEFTBRACKET: pickupItem(); break; case SDLK_s: case SDLK_RIGHTBRACKET: dropItem(); break; default: break; } } void initWindow() { SDL_Init(SDL_INIT_EVERYTHING); window = SDL_CreateWindow("The Dungeons of Noudar", 0, 0, winWidth, winHeight, SDL_WINDOW_OPENGL); glContext = SDL_GL_CreateContext(window); auto gVertexShader = ""; auto gFragmentShader = ""; setupGraphics(winWidth, winHeight, gVertexShader, gFragmentShader, std::make_shared<Knights::CPlainFileLoader>()); auto soundListener = std::make_shared<odb::SoundListener>(); std::vector<std::shared_ptr<odb::SoundEmitter>> sounds; std::string filenames[]{ "res/grasssteps.wav", "res/stepsstones.wav", "res/bgnoise.wav", "res/monsterdamage.wav", "res/monsterdead.wav", "res/playerdamage.wav", "res/playerdead.wav", "res/swing.wav" }; for (auto filename : filenames) { FILE *file = fopen(filename.c_str(), "r"); auto soundClip = odb::makeSoundClipFrom(file); sounds.push_back(std::make_shared<odb::SoundEmitter>(soundClip)); } setSoundEmitters(sounds, soundListener); } void tick() { gameLoopTick(20); renderFrame(20); SDL_GL_SwapWindow(window); } void setMainLoop() { while (!done) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_KEYDOWN: handleKeyPress(event); break; case SDL_QUIT: done = true; break; default: break; } } tick(); } } void destroyWindow() { shutdown(); SDL_GL_DeleteContext(glContext); } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "commands/Command.h" #include "commands/CommandExecutionEngine.h" #include "commands/CommandResult.h" #include "commands/CommandSuggestion.h" #include "handlers/GenericHandler.h" #include "InteractionBasePlugin.h" #include "VisualizationBase/src/items/Item.h" #include "VisualizationBase/src/items/SceneHandlerItem.h" #include "VisualizationBase/src/Scene.h" namespace Interaction { const char* QUOTE_SYMBOLS = "\"'`"; const char* ESCAPE_SYMBOLS = "\\"; CommandExecutionEngine::~CommandExecutionEngine() {} CommandExecutionEngine* CommandExecutionEngine::instance() { static CommandExecutionEngine engine; return &engine; } void CommandExecutionEngine::execute(Visualization::Item *originator, const QString& command, const std::unique_ptr<Visualization::Cursor>& cursor) { lastCommandResult_.clear(); QString trimmed = command.trimmed(); if ( !doQuotesMatch(command, QUOTE_SYMBOLS, ESCAPE_SYMBOLS) ) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("A quoted string expands past the end of the command."))); lastCommandResult_->errors().first()->addResolutionTip("Try inserting a matching quote."); return; } QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; QStringList tokens = tokenize(trimmed, QUOTE_SYMBOLS, ESCAPE_SYMBOLS); bool processed = false; while (target != nullptr && !processed) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); if (handler) { for (int i = 0; i< handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, target, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, target, tokens, cursor)); if (lastCommandResult_->code() != CommandResult::CanNotInterpret) { processed = true; break; } else lastCommandResult_.clear(); } } } if (!processed) target = target->parent(); } // If no item can process this command dispatch it to the SceneItem if (!processed && originator != originator->scene()->sceneHandlerItem()) { auto sceneHandlerItem = source->scene()->sceneHandlerItem(); auto handler = dynamic_cast<GenericHandler*> (sceneHandlerItem->handler()); if ( handler ) { for (int i = 0; i < handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, sceneHandlerItem, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, sceneHandlerItem, tokens, cursor)); if ( lastCommandResult_->code() != CommandResult::CanNotInterpret ) { processed = true; break; } else lastCommandResult_.clear(); } } } } // If the command is still not processed this is an error if (!processed) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("Unknown command '" + command + "' "))); log.warning("Unknown command: " + command); } } QList<CommandSuggestion*> CommandExecutionEngine::autoComplete(Visualization::Item *originator, const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; QString trimmed = textSoFar.trimmed(); QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; // This set keeps a list of commands that have already contributed some suggestions. If a command contributes // suggestions at a more specific context, then we ignore it in less specific contexts, even if it could // contribute more suggestions. The stored value is the hash code of a type_info structure QSet<std::size_t> alreadySuggested; // Get suggestion from item and parents while (target != nullptr) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor)); target = target->parent(); } // Get suggestions from the scene handler item if (originator != originator->scene()->sceneHandlerItem()) { GenericHandler* handler = dynamic_cast<GenericHandler*> (source->scene()->sceneHandlerItem()->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor) ); } return result; } QList<CommandSuggestion*> CommandExecutionEngine::suggestionsForHandler(GenericHandler* handler, QSet<std::size_t>& alreadySuggested, QString trimmedCommandText, Visualization::Item* source, Visualization::Item* target, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; if (handler) for (auto command : handler->commands()) { if (alreadySuggested.contains(typeid(*command).hash_code())) continue; QList<CommandSuggestion*> suggestions; //If it is a menu command, we must make sure it can be interpreted on the current item in its current state if (!trimmedCommandText.isEmpty() || (command->appearsInMenus() && command->canInterpret(source, target, QStringList(command->name()), cursor))) suggestions = command->suggest(source, target, trimmedCommandText, cursor); result.append( suggestions ); if (!suggestions.isEmpty()) alreadySuggested.insert(typeid(*command).hash_code()); } return result; } QString CommandExecutionEngine::extractNavigationString(QString& command) { // Extract navigation information if any QString trimmed = command.trimmed(); QString simplified = trimmed.simplified(); // Note that this will destroy any spacing within quotations. QString navigation; if ( simplified.startsWith("~ ") || simplified.startsWith(".. ") || simplified.startsWith(". ") || simplified.startsWith("../") || simplified.startsWith("./") || simplified.startsWith("/") ) { navigation = trimmed.left(simplified.indexOf(' ')); command = trimmed.mid(navigation.size()).trimmed(); } return navigation; } Visualization::Item* CommandExecutionEngine::navigate(Visualization::Item *originator, const QString&) { //TODO figure out what navigation we want and implement it. return originator; } QStringList CommandExecutionEngine::tokenize(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QStringList result; QString str; QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) { if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); quote = string[i]; str = quote; } else str.append(string[i]); } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) { result.append(str + quote); quote = QChar(); str = QString(); } } } if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); return result; } QStringList CommandExecutionEngine::tokenizeNonQuoted(const QString& string) { //TODO The concept of tokens here is unclear. Define this better. QStringList result; QString str; QChar last; bool fractionInitiated = false; for (int i = 0; i < string.size(); ++i) { if ( string[i] == ' ' ) { if ( !str.isNull() ) result.append(str); str = QString(); fractionInitiated = false; } else if ( string[i].isDigit() && fractionInitiated && last == '.' ) { str = result.last() + '.' + string[i]; result.removeLast(); fractionInitiated = false; } else if ( string[i].isDigit() && str.isNull() ) { fractionInitiated = true; str += string[i]; } else if ( string[i] == '.' && fractionInitiated ) { result.append(str); str = "."; } else if ( string[i].isDigit() && fractionInitiated ) { str += string[i]; } else if ( (string[i].isLetter() || string[i].isDigit() || string[i] == '_') != (last.isLetter() || last.isDigit() || last == '_') ) { if ( !str.isNull() ) result.append(str); str = string[i]; fractionInitiated = false; } else { str += string[i]; } last = string[i]; } if ( !str.isNull() ) result.append(str); return result; } bool CommandExecutionEngine::doQuotesMatch(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) quote = string[i]; } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) quote = QChar(); } } return quote.isNull(); } bool CommandExecutionEngine::isEscaped(const QString& string, int indexToCheck, const QString& escapeSymbols) { int num = 0; int index = indexToCheck - 1; while ( index >= 0 && escapeSymbols.contains(string.at(index)) ) { --index; ++num; } return num % 2 == 1; } } <commit_msg>Make it possible to enter quoted arguments in commands<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "commands/Command.h" #include "commands/CommandExecutionEngine.h" #include "commands/CommandResult.h" #include "commands/CommandSuggestion.h" #include "handlers/GenericHandler.h" #include "InteractionBasePlugin.h" #include "VisualizationBase/src/items/Item.h" #include "VisualizationBase/src/items/SceneHandlerItem.h" #include "VisualizationBase/src/Scene.h" namespace Interaction { const char* QUOTE_SYMBOLS = "\"'`"; const char* ESCAPE_SYMBOLS = "\\"; CommandExecutionEngine::~CommandExecutionEngine() {} CommandExecutionEngine* CommandExecutionEngine::instance() { static CommandExecutionEngine engine; return &engine; } void CommandExecutionEngine::execute(Visualization::Item *originator, const QString& command, const std::unique_ptr<Visualization::Cursor>& cursor) { lastCommandResult_.clear(); QString trimmed = command.trimmed(); if ( !doQuotesMatch(command, QUOTE_SYMBOLS, ESCAPE_SYMBOLS) ) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("A quoted string expands past the end of the command."))); lastCommandResult_->errors().first()->addResolutionTip("Try inserting a matching quote."); return; } QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; QStringList tokens = tokenize(trimmed, QUOTE_SYMBOLS, ESCAPE_SYMBOLS); bool processed = false; while (target != nullptr && !processed) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); if (handler) { for (int i = 0; i< handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, target, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, target, tokens, cursor)); if (lastCommandResult_->code() != CommandResult::CanNotInterpret) { processed = true; break; } else lastCommandResult_.clear(); } } } if (!processed) target = target->parent(); } // If no item can process this command dispatch it to the SceneItem if (!processed && originator != originator->scene()->sceneHandlerItem()) { auto sceneHandlerItem = source->scene()->sceneHandlerItem(); auto handler = dynamic_cast<GenericHandler*> (sceneHandlerItem->handler()); if ( handler ) { for (int i = 0; i < handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, sceneHandlerItem, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, sceneHandlerItem, tokens, cursor)); if ( lastCommandResult_->code() != CommandResult::CanNotInterpret ) { processed = true; break; } else lastCommandResult_.clear(); } } } } // If the command is still not processed this is an error if (!processed) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("Unknown command '" + command + "' "))); log.warning("Unknown command: " + command); } } QList<CommandSuggestion*> CommandExecutionEngine::autoComplete(Visualization::Item *originator, const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; QString trimmed = textSoFar.trimmed(); QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; // This set keeps a list of commands that have already contributed some suggestions. If a command contributes // suggestions at a more specific context, then we ignore it in less specific contexts, even if it could // contribute more suggestions. The stored value is the hash code of a type_info structure QSet<std::size_t> alreadySuggested; // Get suggestion from item and parents while (target != nullptr) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor)); target = target->parent(); } // Get suggestions from the scene handler item if (originator != originator->scene()->sceneHandlerItem()) { GenericHandler* handler = dynamic_cast<GenericHandler*> (source->scene()->sceneHandlerItem()->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor) ); } return result; } QList<CommandSuggestion*> CommandExecutionEngine::suggestionsForHandler(GenericHandler* handler, QSet<std::size_t>& alreadySuggested, QString trimmedCommandText, Visualization::Item* source, Visualization::Item* target, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; if (handler) for (auto command : handler->commands()) { if (alreadySuggested.contains(typeid(*command).hash_code())) continue; QList<CommandSuggestion*> suggestions; //If it is a menu command, we must make sure it can be interpreted on the current item in its current state if (!trimmedCommandText.isEmpty() || (command->appearsInMenus() && command->canInterpret(source, target, QStringList(command->name()), cursor))) suggestions = command->suggest(source, target, trimmedCommandText, cursor); result.append( suggestions ); if (!suggestions.isEmpty()) alreadySuggested.insert(typeid(*command).hash_code()); } return result; } QString CommandExecutionEngine::extractNavigationString(QString& command) { // Extract navigation information if any QString trimmed = command.trimmed(); QString simplified = trimmed.simplified(); // Note that this will destroy any spacing within quotations. QString navigation; if ( simplified.startsWith("~ ") || simplified.startsWith(".. ") || simplified.startsWith(". ") || simplified.startsWith("../") || simplified.startsWith("./") || simplified.startsWith("/") ) { navigation = trimmed.left(simplified.indexOf(' ')); command = trimmed.mid(navigation.size()).trimmed(); } return navigation; } Visualization::Item* CommandExecutionEngine::navigate(Visualization::Item *originator, const QString&) { //TODO figure out what navigation we want and implement it. return originator; } QStringList CommandExecutionEngine::tokenize(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QStringList result; QString str; QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) { if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); quote = string[i]; str = quote; } else str.append(string[i]); } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) { result.append(str + quote); quote = QChar(); str = QString(); } else str.append(string[i]); } } if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); return result; } QStringList CommandExecutionEngine::tokenizeNonQuoted(const QString& string) { //TODO The concept of tokens here is unclear. Define this better. QStringList result; QString str; QChar last; bool fractionInitiated = false; for (int i = 0; i < string.size(); ++i) { if ( string[i] == ' ' ) { if ( !str.isNull() ) result.append(str); str = QString(); fractionInitiated = false; } else if ( string[i].isDigit() && fractionInitiated && last == '.' ) { str = result.last() + '.' + string[i]; result.removeLast(); fractionInitiated = false; } else if ( string[i].isDigit() && str.isNull() ) { fractionInitiated = true; str += string[i]; } else if ( string[i] == '.' && fractionInitiated ) { result.append(str); str = "."; } else if ( string[i].isDigit() && fractionInitiated ) { str += string[i]; } else if ( (string[i].isLetter() || string[i].isDigit() || string[i] == '_') != (last.isLetter() || last.isDigit() || last == '_') ) { if ( !str.isNull() ) result.append(str); str = string[i]; fractionInitiated = false; } else { str += string[i]; } last = string[i]; } if ( !str.isNull() ) result.append(str); return result; } bool CommandExecutionEngine::doQuotesMatch(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) quote = string[i]; } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) quote = QChar(); } } return quote.isNull(); } bool CommandExecutionEngine::isEscaped(const QString& string, int indexToCheck, const QString& escapeSymbols) { int num = 0; int index = indexToCheck - 1; while ( index >= 0 && escapeSymbols.contains(string.at(index)) ) { --index; ++num; } return num % 2 == 1; } } <|endoftext|>
<commit_before>/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/randperm_op.h" #include <string> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/operator.h" namespace paddle { namespace operators { class RandpermOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true, platform::errors::NotFound( "The output(Out) of randperm op must not be null.")); int n = ctx->Attrs().Get<int>("n"); PADDLE_ENFORCE_GT( n, 0, platform::errors::InvalidArgument( "The input(n) of randperm op must be greater than 0.")); ctx->SetOutputDim("Out", framework::make_ddim({n})); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { auto data_type = static_cast<framework::proto::VarType::Type>(ctx.Attr<int>("dtype")); return framework::OpKernelType(data_type, ctx.GetPlace()); } }; class RandpermOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput("Out", "The output tensor of randperm op."); AddAttr<int>( "n", "The upper bound (exclusive), and it should be greater than 0."); AddAttr<int>("dtype", "The data type of output tensor. " "Default: 3[int64].") .SetDefault(framework::proto::VarType::INT64); AddAttr<int>("seed", "Random seed used for permute samples. " "0 means use a seed generated by the system." "Note that if seed is not 0, this operator will always " "generate the same random permutation every time. " "Default: 0.") .SetDefault(0); AddComment(R"DOC( This operator returns a random permutation of integers from 0 to n-1. )DOC"); } }; class RandpermOpVarTypeInference : public framework::VarTypeInference { public: void operator()(framework::InferVarTypeContext *ctx) const override { auto var_data_type = static_cast<framework::proto::VarType::Type>( BOOST_GET_CONST(int, ctx->GetAttr("dtype"))); ctx->SetOutputDataType("Out", var_data_type); } }; } // namespace operators } // namespace paddle REGISTER_OPERATOR( randperm, paddle::operators::RandpermOp, paddle::operators::RandpermOpMaker, paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>, paddle::operators::RandpermOpVarTypeInference); template <typename T> using kernel = paddle::operators::RandpermKernel<paddle::platform::CPUDeviceContext, T>; REGISTER_OP_CPU_KERNEL(randperm, kernel<int64_t>, kernel<int>, kernel<float>, kernel<double>); <commit_msg>Fix the formate of raising error in randperm op (#30108)<commit_after>/* Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "paddle/fluid/operators/randperm_op.h" #include <string> #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/framework/operator.h" namespace paddle { namespace operators { class RandpermOp : public framework::OperatorWithKernel { public: using framework::OperatorWithKernel::OperatorWithKernel; void InferShape(framework::InferShapeContext *ctx) const override { PADDLE_ENFORCE_EQ(ctx->HasOutput("Out"), true, platform::errors::NotFound( "The output(Out) of randperm op must not be null.")); int n = ctx->Attrs().Get<int>("n"); PADDLE_ENFORCE_GT( n, 0, platform::errors::InvalidArgument( "The input 'n' of randperm op should be greater than 0. " "But received %d.", n)); ctx->SetOutputDim("Out", framework::make_ddim({n})); } protected: framework::OpKernelType GetExpectedKernelType( const framework::ExecutionContext &ctx) const override { auto data_type = static_cast<framework::proto::VarType::Type>(ctx.Attr<int>("dtype")); return framework::OpKernelType(data_type, ctx.GetPlace()); } }; class RandpermOpMaker : public framework::OpProtoAndCheckerMaker { public: void Make() override { AddOutput("Out", "The output tensor of randperm op."); AddAttr<int>( "n", "The upper bound (exclusive), and it should be greater than 0."); AddAttr<int>("dtype", "The data type of output tensor. " "Default: 3[int64].") .SetDefault(framework::proto::VarType::INT64); AddAttr<int>("seed", "Random seed used for permute samples. " "0 means use a seed generated by the system." "Note that if seed is not 0, this operator will always " "generate the same random permutation every time. " "Default: 0.") .SetDefault(0); AddComment(R"DOC( This operator returns a random permutation of integers from 0 to n-1. )DOC"); } }; class RandpermOpVarTypeInference : public framework::VarTypeInference { public: void operator()(framework::InferVarTypeContext *ctx) const override { auto var_data_type = static_cast<framework::proto::VarType::Type>( BOOST_GET_CONST(int, ctx->GetAttr("dtype"))); ctx->SetOutputDataType("Out", var_data_type); } }; } // namespace operators } // namespace paddle REGISTER_OPERATOR( randperm, paddle::operators::RandpermOp, paddle::operators::RandpermOpMaker, paddle::framework::EmptyGradOpMaker<paddle::framework::OpDesc>, paddle::framework::EmptyGradOpMaker<paddle::imperative::OpBase>, paddle::operators::RandpermOpVarTypeInference); template <typename T> using kernel = paddle::operators::RandpermKernel<paddle::platform::CPUDeviceContext, T>; REGISTER_OP_CPU_KERNEL(randperm, kernel<int64_t>, kernel<int>, kernel<float>, kernel<double>); <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkRTPlanReaderService.h" #include "mitkImage.h" #include "mitkDICOMDCMTKTagScanner.h" #include "mitkIOMimeTypes.h" #include <mitkDICOMIOHelper.h> #include "mitkDICOMTagPath.h" #include "mitkDICOMTagsOfInterestService.h" #include "mitkDICOMDatasetAccessingImageFrameInfo.h" #include "mitkDicomRTIOMimeTypes.h" namespace mitk { RTPlanReaderService::RTPlanReaderService() : AbstractFileReader(CustomMimeType(mitk::DicomRTIOMimeTypes::DICOMRT_PLAN_MIMETYPE_NAME()), mitk::DicomRTIOMimeTypes::DICOMRT_PLAN_MIMETYPE_DESCRIPTION()) { m_FileReaderServiceReg = RegisterService(); } RTPlanReaderService::RTPlanReaderService(const RTPlanReaderService& other) : mitk::AbstractFileReader(other) { } RTPlanReaderService::~RTPlanReaderService() {} std::vector<itk::SmartPointer<BaseData> > RTPlanReaderService::Read() { std::vector<itk::SmartPointer<mitk::BaseData> > result; auto DICOMTagsOfInterestService = GetDicomTagsOfInterestService(); auto tagsOfInterest = DICOMTagsOfInterestService->GetTagsOfInterest(); DICOMTagPathList tagsOfInterestList; for (const auto& tag : tagsOfInterest) { tagsOfInterestList.push_back(tag.first); } std::string location = GetInputLocation(); mitk::StringList files = { location }; mitk::DICOMDCMTKTagScanner::Pointer scanner = mitk::DICOMDCMTKTagScanner::New(); scanner->SetInputFiles(files); scanner->AddTagPaths(tagsOfInterestList); scanner->Scan(); mitk::DICOMDatasetAccessingImageFrameList frames = scanner->GetFrameInfoList(); if (frames.empty()) { MITK_ERROR << "Error reading the RTPLAN file" << std::endl; return result; } auto findings = ExtractPathsOfInterest(tagsOfInterestList, frames); //just create empty image. No image information available in RTPLAN. But properties will be attached. Image::Pointer dummyImage = Image::New(); mitk::PixelType pt = mitk::MakeScalarPixelType<int>(); unsigned int dim[] = { 1,1}; dummyImage->Initialize(pt, 2, dim); SetProperties(dummyImage, findings); result.push_back(dummyImage.GetPointer()); return result; } RTPlanReaderService* RTPlanReaderService::Clone() const { return new RTPlanReaderService(*this); } } <commit_msg>Changed wrong include<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkRTPlanReaderService.h" #include "mitkImage.h" #include "mitkDICOMDCMTKTagScanner.h" #include "mitkIOMimeTypes.h" #include <mitkDICOMIOHelper.h> #include "mitkDICOMTagPath.h" #include "mitkIDICOMTagsOfInterest.h" #include "mitkDICOMDatasetAccessingImageFrameInfo.h" #include "mitkDicomRTIOMimeTypes.h" namespace mitk { RTPlanReaderService::RTPlanReaderService() : AbstractFileReader(CustomMimeType(mitk::DicomRTIOMimeTypes::DICOMRT_PLAN_MIMETYPE_NAME()), mitk::DicomRTIOMimeTypes::DICOMRT_PLAN_MIMETYPE_DESCRIPTION()) { m_FileReaderServiceReg = RegisterService(); } RTPlanReaderService::RTPlanReaderService(const RTPlanReaderService& other) : mitk::AbstractFileReader(other) { } RTPlanReaderService::~RTPlanReaderService() {} std::vector<itk::SmartPointer<BaseData> > RTPlanReaderService::Read() { std::vector<itk::SmartPointer<mitk::BaseData> > result; auto DICOMTagsOfInterestService = GetDicomTagsOfInterestService(); auto tagsOfInterest = DICOMTagsOfInterestService->GetTagsOfInterest(); DICOMTagPathList tagsOfInterestList; for (const auto& tag : tagsOfInterest) { tagsOfInterestList.push_back(tag.first); } std::string location = GetInputLocation(); mitk::StringList files = { location }; mitk::DICOMDCMTKTagScanner::Pointer scanner = mitk::DICOMDCMTKTagScanner::New(); scanner->SetInputFiles(files); scanner->AddTagPaths(tagsOfInterestList); scanner->Scan(); mitk::DICOMDatasetAccessingImageFrameList frames = scanner->GetFrameInfoList(); if (frames.empty()) { MITK_ERROR << "Error reading the RTPLAN file" << std::endl; return result; } auto findings = ExtractPathsOfInterest(tagsOfInterestList, frames); //just create empty image. No image information available in RTPLAN. But properties will be attached. Image::Pointer dummyImage = Image::New(); mitk::PixelType pt = mitk::MakeScalarPixelType<int>(); unsigned int dim[] = { 1,1}; dummyImage->Initialize(pt, 2, dim); SetProperties(dummyImage, findings); result.push_back(dummyImage.GetPointer()); return result; } RTPlanReaderService* RTPlanReaderService::Clone() const { return new RTPlanReaderService(*this); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: macrosmenucontroller.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-05-25 12:32:32 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <uielement/macrosmenucontroller.hxx> #include <threadhelp/resetableguard.hxx> #include "services.h" #include <classes/resource.hrc> #include <classes/fwkresid.hxx> #include <helper/imageproducer.hxx> #include <com/sun/star/awt/MenuItemStyle.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XContentEnumerationAccess.hpp> #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <drafts/com/sun/star/frame/XModuleManager.hpp> #include <comphelper/processfactory.hxx> #include <vcl/svapp.hxx> #include <vcl/i18nhelp.hxx> #include <tools/urlobj.hxx> #include <rtl/ustrbuf.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace com::sun::star::style; using namespace com::sun::star::container; using namespace drafts::com::sun::star::frame; namespace framework { class DEFINE_XSERVICEINFO_MULTISERVICE ( MacrosMenuController , OWeakObject , SERVICENAME_POPUPMENUCONTROLLER , IMPLEMENTATIONNAME_MACROSMENUCONTROLLER ) DEFINE_INIT_SERVICE ( MacrosMenuController, {} ) MacrosMenuController::MacrosMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : PopupMenuControllerBase( xServiceManager ), m_xServiceManager( xServiceManager) { } MacrosMenuController::~MacrosMenuController() { OSL_TRACE("calling dtor"); } // private function void MacrosMenuController::fillPopupMenu( Reference< css::awt::XPopupMenu >& rPopupMenu ) { VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXMenu::GetImplementation( rPopupMenu ); PopupMenu* pPopupMenu = 0; vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); resetPopupMenu( rPopupMenu ); if ( pVCLPopupMenu ) pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu(); // insert basic String aCommand = String::CreateFromAscii( ".uno:MacroDialog" ); String aDisplayName = RetrieveLabelFromCommand( aCommand ); pPopupMenu->InsertItem( 2, aDisplayName ); pPopupMenu->SetItemCommand( 2, aCommand ); // insert providers but not basic or java addScriptItems( pPopupMenu, 4); } // XEventListener void SAL_CALL MacrosMenuController::disposing( const EventObject& Source ) throw ( RuntimeException ) { Reference< css::awt::XMenuListener > xHolder(( OWeakObject *)this, UNO_QUERY ); ResetableGuard aLock( m_aLock ); OSL_TRACE("disposing"); m_xFrame.clear(); m_xDispatch.clear(); if ( m_xPopupMenu.is() ) { m_xPopupMenu->removeMenuListener( Reference< css::awt::XMenuListener >(( OWeakObject *)this, UNO_QUERY )); OSL_TRACE("removed listener"); } m_xPopupMenu.clear(); } // XStatusListener void SAL_CALL MacrosMenuController::statusChanged( const FeatureStateEvent& Event ) throw ( RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_xPopupMenu.is() ) { fillPopupMenu( m_xPopupMenu ); } } // XMenuListener void SAL_CALL MacrosMenuController::highlight( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } void SAL_CALL MacrosMenuController::select( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { Reference< css::awt::XPopupMenu > xPopupMenu; Reference< XDispatch > xDispatch; Reference< XMultiServiceFactory > xServiceManager; ResetableGuard aLock( m_aLock ); xPopupMenu = m_xPopupMenu; xDispatch = m_xDispatch; xServiceManager = m_xServiceManager; aLock.unlock(); if ( xPopupMenu.is() && xDispatch.is() ) { VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXPopupMenu::GetImplementation( xPopupMenu ); if ( pVCLPopupMenu ) { css::util::URL aTargetURL; Sequence<PropertyValue> aArgs; Reference< XURLTransformer > xURLTransformer( xServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))), UNO_QUERY ); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); PopupMenu* pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu(); aTargetURL.Complete = pPopupMenu->GetItemCommand( rEvent.MenuId ); } xURLTransformer->parseStrict( aTargetURL ); // need to requery, since we handle more than one type of Command // if we don't do this only .uno:ScriptOrganizer commands are executed xDispatch = m_xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if( xDispatch.is() ) { ExecuteInfo* pExecuteInfo = new ExecuteInfo; pExecuteInfo->xDispatch = xDispatch; pExecuteInfo->aTargetURL = aTargetURL; pExecuteInfo->aArgs = aArgs; // xDispatch->dispatch( aTargetURL, aArgs ); Application::PostUserEvent( STATIC_LINK(0, MacrosMenuController , ExecuteHdl_Impl), pExecuteInfo ); } else { } } } } IMPL_STATIC_LINK( MacrosMenuController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo ) { try { // Asynchronous execution as this can lead to our own destruction! // Framework can recycle our current frame and the layout manager disposes all user interface // elements if a component gets detached from its frame! pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs ); } catch ( Exception& ) { } delete pExecuteInfo; return 0; } void SAL_CALL MacrosMenuController::activate( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } void SAL_CALL MacrosMenuController::deactivate( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } // XPopupMenuController void SAL_CALL MacrosMenuController::setPopupMenu( const Reference< css::awt::XPopupMenu >& xPopupMenu ) throw ( RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_xFrame.is() && !m_xPopupMenu.is() ) { // Create popup menu on demand vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); m_xPopupMenu = xPopupMenu; m_xPopupMenu->addMenuListener( Reference< css::awt::XMenuListener >( (OWeakObject*)this, UNO_QUERY )); Reference< XURLTransformer > xURLTransformer( m_xServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))), UNO_QUERY ); Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); m_xDispatchProvider = xDispatchProvider; com::sun::star::util::URL aTargetURL; aTargetURL.Complete = m_aCommandURL; xURLTransformer->parseStrict( aTargetURL ); m_xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); updatePopupMenu(); } } // XInitialization void SAL_CALL MacrosMenuController::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException ) { const rtl::OUString aFrameName( RTL_CONSTASCII_USTRINGPARAM( "Frame" )); const rtl::OUString aCommandURLName( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )); ResetableGuard aLock( m_aLock ); sal_Bool bInitalized( m_bInitialized ); if ( !bInitalized ) { PropertyValue aPropValue; rtl::OUString aCommandURL; Reference< XFrame > xFrame; for ( int i = 0; i < aArguments.getLength(); i++ ) { if ( aArguments[i] >>= aPropValue ) { if ( aPropValue.Name.equalsAscii( "Frame" )) aPropValue.Value >>= xFrame; else if ( aPropValue.Name.equalsAscii( "CommandURL" )) aPropValue.Value >>= aCommandURL; } } ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandLabels; if ( xFrame.is() && aCommandURL.getLength() ) { ResetableGuard aLock( m_aLock ); m_xFrame = xFrame; m_aCommandURL = aCommandURL; m_bInitialized = sal_True; } } } String MacrosMenuController::RetrieveLabelFromCommand( const String& aCmdURL ) { String aLabel; // Retrieve popup menu labels if ( !m_aModuleIdentifier.getLength() ) { Reference< XModuleManager > xModuleManager( ::comphelper::getProcessServiceFactory()->createInstance( SERVICENAME_MODULEMANAGER ), UNO_QUERY_THROW ); Reference< XInterface > xIfac( m_xFrame, UNO_QUERY ); m_aModuleIdentifier = xModuleManager->identify( xIfac ); if ( m_aModuleIdentifier.getLength() > 0 ) { Reference< XNameAccess > xNameAccess( ::comphelper::getProcessServiceFactory()->createInstance( SERVICENAME_UICOMMANDDESCRIPTION ), UNO_QUERY ); if ( xNameAccess.is() ) { Any a = xNameAccess->getByName( m_aModuleIdentifier ); Reference< XNameAccess > xUICommands; a >>= m_xUICommandLabels; } } } if ( m_xUICommandLabels.is() ) { try { if ( aCmdURL.Len() > 0 ) { rtl::OUString aStr; Sequence< PropertyValue > aPropSeq; Any a( m_xUICommandLabels->getByName( aCmdURL )); if ( a >>= aPropSeq ) { for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ ) { if ( aPropSeq[i].Name.equalsAscii( "Label" )) { aPropSeq[i].Value >>= aStr; break; } } } aLabel = aStr; } } catch ( com::sun::star::uno::Exception& ) { } } return aLabel; } void MacrosMenuController::addScriptItems( PopupMenu* pPopupMenu, USHORT startItemId ) { const String aCmdBase = String::CreateFromAscii( ".uno:ScriptOrganizer?ScriptOrganizer.Language:string=" ); const String ellipsis = String::CreateFromAscii( "..." ); const ::rtl::OUString providerKey = ::rtl::OUString::createFromAscii("drafts.com.sun.star.script.provider.ScriptProviderFor" ); const ::rtl::OUString languageProviderName = ::rtl::OUString::createFromAscii("drafts.com.sun.star.script.provider.LanguageScriptProvider" ); USHORT itemId = startItemId; Reference< XContentEnumerationAccess > xEnumAccess = Reference< XContentEnumerationAccess >( m_xServiceManager, UNO_QUERY_THROW ); Reference< XEnumeration > xEnum = xEnumAccess->createContentEnumeration ( languageProviderName ); while ( xEnum->hasMoreElements() ) { Reference< XServiceInfo > xServiceInfo; if ( sal_False == ( xEnum->nextElement() >>= xServiceInfo ) ) { break; } Sequence< ::rtl::OUString > serviceNames = xServiceInfo->getSupportedServiceNames(); if ( serviceNames.getLength() > 0 ) { for ( sal_Int32 index = 0; index < serviceNames.getLength(); index++ ) { if ( serviceNames[ index ].indexOf( providerKey ) == 0 ) { ::rtl::OUString serviceName = serviceNames[ index ]; String aCommand = aCmdBase; String aDisplayName = String( serviceName.copy( providerKey.getLength() ) ); if( aDisplayName.Equals( String::CreateFromAscii( "Java" ) ) || aDisplayName.Equals( String::CreateFromAscii( "Basic" ) ) ) { // no entries for Java & Basic added elsewhere break; } aCommand.Append( aDisplayName ); aDisplayName.Append( ellipsis ); pPopupMenu->InsertItem( itemId, aDisplayName ); pPopupMenu->SetItemCommand( itemId, aCommand ); itemId++; break; } } } } } } <commit_msg>INTEGRATION: CWS docking2 (1.3.32); FILE MERGED 2004/07/16 14:04:13 dfoster 1.3.32.1: #i29739# Add HIDs for Tools->Macros menu items<commit_after>/************************************************************************* * * $RCSfile: macrosmenucontroller.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-08-02 15:12:42 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2004 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <uielement/macrosmenucontroller.hxx> #include <threadhelp/resetableguard.hxx> #include "services.h" #include <classes/resource.hrc> #include <classes/fwkresid.hxx> #include <helper/imageproducer.hxx> #include <com/sun/star/awt/MenuItemStyle.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> #include <com/sun/star/container/XContentEnumerationAccess.hpp> #include <com/sun/star/style/XStyleFamiliesSupplier.hpp> #include <com/sun/star/util/XURLTransformer.hpp> #include <drafts/com/sun/star/frame/XModuleManager.hpp> #include <comphelper/processfactory.hxx> #include <vcl/svapp.hxx> #include <vcl/i18nhelp.hxx> #include <tools/urlobj.hxx> #include <rtl/ustrbuf.hxx> using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::frame; using namespace com::sun::star::beans; using namespace com::sun::star::util; using namespace com::sun::star::style; using namespace com::sun::star::container; using namespace drafts::com::sun::star::frame; namespace framework { class DEFINE_XSERVICEINFO_MULTISERVICE ( MacrosMenuController , OWeakObject , SERVICENAME_POPUPMENUCONTROLLER , IMPLEMENTATIONNAME_MACROSMENUCONTROLLER ) DEFINE_INIT_SERVICE ( MacrosMenuController, {} ) MacrosMenuController::MacrosMenuController( const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& xServiceManager ) : PopupMenuControllerBase( xServiceManager ), m_xServiceManager( xServiceManager) { } MacrosMenuController::~MacrosMenuController() { OSL_TRACE("calling dtor"); } // private function void MacrosMenuController::fillPopupMenu( Reference< css::awt::XPopupMenu >& rPopupMenu ) { VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXMenu::GetImplementation( rPopupMenu ); PopupMenu* pPopupMenu = 0; vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); resetPopupMenu( rPopupMenu ); if ( pVCLPopupMenu ) pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu(); // insert basic String aCommand = String::CreateFromAscii( ".uno:MacroDialog" ); String aDisplayName = RetrieveLabelFromCommand( aCommand ); pPopupMenu->InsertItem( 2, aDisplayName ); pPopupMenu->SetItemCommand( 2, aCommand ); //pPopupMenu->SetHelpId( 2, HID_SVX_BASIC_MACRO_ORGANIZER ); pPopupMenu->SetHelpId( 2, 40012 ); // insert providers but not basic or java addScriptItems( pPopupMenu, 4); } // XEventListener void SAL_CALL MacrosMenuController::disposing( const EventObject& Source ) throw ( RuntimeException ) { Reference< css::awt::XMenuListener > xHolder(( OWeakObject *)this, UNO_QUERY ); ResetableGuard aLock( m_aLock ); OSL_TRACE("disposing"); m_xFrame.clear(); m_xDispatch.clear(); if ( m_xPopupMenu.is() ) { m_xPopupMenu->removeMenuListener( Reference< css::awt::XMenuListener >(( OWeakObject *)this, UNO_QUERY )); OSL_TRACE("removed listener"); } m_xPopupMenu.clear(); } // XStatusListener void SAL_CALL MacrosMenuController::statusChanged( const FeatureStateEvent& Event ) throw ( RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_xPopupMenu.is() ) { fillPopupMenu( m_xPopupMenu ); } } // XMenuListener void SAL_CALL MacrosMenuController::highlight( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } void SAL_CALL MacrosMenuController::select( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { Reference< css::awt::XPopupMenu > xPopupMenu; Reference< XDispatch > xDispatch; Reference< XMultiServiceFactory > xServiceManager; ResetableGuard aLock( m_aLock ); xPopupMenu = m_xPopupMenu; xDispatch = m_xDispatch; xServiceManager = m_xServiceManager; aLock.unlock(); if ( xPopupMenu.is() && xDispatch.is() ) { VCLXPopupMenu* pVCLPopupMenu = (VCLXPopupMenu *)VCLXPopupMenu::GetImplementation( xPopupMenu ); if ( pVCLPopupMenu ) { css::util::URL aTargetURL; Sequence<PropertyValue> aArgs; Reference< XURLTransformer > xURLTransformer( xServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))), UNO_QUERY ); { vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); PopupMenu* pPopupMenu = (PopupMenu *)pVCLPopupMenu->GetMenu(); aTargetURL.Complete = pPopupMenu->GetItemCommand( rEvent.MenuId ); } xURLTransformer->parseStrict( aTargetURL ); // need to requery, since we handle more than one type of Command // if we don't do this only .uno:ScriptOrganizer commands are executed xDispatch = m_xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); if( xDispatch.is() ) { ExecuteInfo* pExecuteInfo = new ExecuteInfo; pExecuteInfo->xDispatch = xDispatch; pExecuteInfo->aTargetURL = aTargetURL; pExecuteInfo->aArgs = aArgs; // xDispatch->dispatch( aTargetURL, aArgs ); Application::PostUserEvent( STATIC_LINK(0, MacrosMenuController , ExecuteHdl_Impl), pExecuteInfo ); } else { } } } } IMPL_STATIC_LINK( MacrosMenuController, ExecuteHdl_Impl, ExecuteInfo*, pExecuteInfo ) { try { // Asynchronous execution as this can lead to our own destruction! // Framework can recycle our current frame and the layout manager disposes all user interface // elements if a component gets detached from its frame! pExecuteInfo->xDispatch->dispatch( pExecuteInfo->aTargetURL, pExecuteInfo->aArgs ); } catch ( Exception& ) { } delete pExecuteInfo; return 0; } void SAL_CALL MacrosMenuController::activate( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } void SAL_CALL MacrosMenuController::deactivate( const css::awt::MenuEvent& rEvent ) throw (RuntimeException) { } // XPopupMenuController void SAL_CALL MacrosMenuController::setPopupMenu( const Reference< css::awt::XPopupMenu >& xPopupMenu ) throw ( RuntimeException ) { ResetableGuard aLock( m_aLock ); if ( m_xFrame.is() && !m_xPopupMenu.is() ) { // Create popup menu on demand vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() ); m_xPopupMenu = xPopupMenu; m_xPopupMenu->addMenuListener( Reference< css::awt::XMenuListener >( (OWeakObject*)this, UNO_QUERY )); Reference< XURLTransformer > xURLTransformer( m_xServiceManager->createInstance( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.util.URLTransformer" ))), UNO_QUERY ); Reference< XDispatchProvider > xDispatchProvider( m_xFrame, UNO_QUERY ); m_xDispatchProvider = xDispatchProvider; com::sun::star::util::URL aTargetURL; aTargetURL.Complete = m_aCommandURL; xURLTransformer->parseStrict( aTargetURL ); m_xDispatch = xDispatchProvider->queryDispatch( aTargetURL, ::rtl::OUString(), 0 ); updatePopupMenu(); } } // XInitialization void SAL_CALL MacrosMenuController::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException ) { const rtl::OUString aFrameName( RTL_CONSTASCII_USTRINGPARAM( "Frame" )); const rtl::OUString aCommandURLName( RTL_CONSTASCII_USTRINGPARAM( "CommandURL" )); ResetableGuard aLock( m_aLock ); sal_Bool bInitalized( m_bInitialized ); if ( !bInitalized ) { PropertyValue aPropValue; rtl::OUString aCommandURL; Reference< XFrame > xFrame; for ( int i = 0; i < aArguments.getLength(); i++ ) { if ( aArguments[i] >>= aPropValue ) { if ( aPropValue.Name.equalsAscii( "Frame" )) aPropValue.Value >>= xFrame; else if ( aPropValue.Name.equalsAscii( "CommandURL" )) aPropValue.Value >>= aCommandURL; } } ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess > m_xUICommandLabels; if ( xFrame.is() && aCommandURL.getLength() ) { ResetableGuard aLock( m_aLock ); m_xFrame = xFrame; m_aCommandURL = aCommandURL; m_bInitialized = sal_True; } } } String MacrosMenuController::RetrieveLabelFromCommand( const String& aCmdURL ) { String aLabel; // Retrieve popup menu labels if ( !m_aModuleIdentifier.getLength() ) { Reference< XModuleManager > xModuleManager( ::comphelper::getProcessServiceFactory()->createInstance( SERVICENAME_MODULEMANAGER ), UNO_QUERY_THROW ); Reference< XInterface > xIfac( m_xFrame, UNO_QUERY ); m_aModuleIdentifier = xModuleManager->identify( xIfac ); if ( m_aModuleIdentifier.getLength() > 0 ) { Reference< XNameAccess > xNameAccess( ::comphelper::getProcessServiceFactory()->createInstance( SERVICENAME_UICOMMANDDESCRIPTION ), UNO_QUERY ); if ( xNameAccess.is() ) { Any a = xNameAccess->getByName( m_aModuleIdentifier ); Reference< XNameAccess > xUICommands; a >>= m_xUICommandLabels; } } } if ( m_xUICommandLabels.is() ) { try { if ( aCmdURL.Len() > 0 ) { rtl::OUString aStr; Sequence< PropertyValue > aPropSeq; Any a( m_xUICommandLabels->getByName( aCmdURL )); if ( a >>= aPropSeq ) { for ( sal_Int32 i = 0; i < aPropSeq.getLength(); i++ ) { if ( aPropSeq[i].Name.equalsAscii( "Label" )) { aPropSeq[i].Value >>= aStr; break; } } } aLabel = aStr; } } catch ( com::sun::star::uno::Exception& ) { } } return aLabel; } void MacrosMenuController::addScriptItems( PopupMenu* pPopupMenu, USHORT startItemId ) { const String aCmdBase = String::CreateFromAscii( ".uno:ScriptOrganizer?ScriptOrganizer.Language:string=" ); const String ellipsis = String::CreateFromAscii( "..." ); const ::rtl::OUString providerKey = ::rtl::OUString::createFromAscii("drafts.com.sun.star.script.provider.ScriptProviderFor" ); const ::rtl::OUString languageProviderName = ::rtl::OUString::createFromAscii("drafts.com.sun.star.script.provider.LanguageScriptProvider" ); USHORT itemId = startItemId; Reference< XContentEnumerationAccess > xEnumAccess = Reference< XContentEnumerationAccess >( m_xServiceManager, UNO_QUERY_THROW ); Reference< XEnumeration > xEnum = xEnumAccess->createContentEnumeration ( languageProviderName ); while ( xEnum->hasMoreElements() ) { Reference< XServiceInfo > xServiceInfo; if ( sal_False == ( xEnum->nextElement() >>= xServiceInfo ) ) { break; } Sequence< ::rtl::OUString > serviceNames = xServiceInfo->getSupportedServiceNames(); if ( serviceNames.getLength() > 0 ) { for ( sal_Int32 index = 0; index < serviceNames.getLength(); index++ ) { if ( serviceNames[ index ].indexOf( providerKey ) == 0 ) { ::rtl::OUString serviceName = serviceNames[ index ]; String aCommand = aCmdBase; String aDisplayName = String( serviceName.copy( providerKey.getLength() ) ); if( aDisplayName.Equals( String::CreateFromAscii( "Java" ) ) || aDisplayName.Equals( String::CreateFromAscii( "Basic" ) ) ) { // no entries for Java & Basic added elsewhere break; } aCommand.Append( aDisplayName ); aDisplayName.Append( ellipsis ); pPopupMenu->InsertItem( itemId, aDisplayName ); pPopupMenu->SetItemCommand( itemId, aCommand ); //pPopupMenu->SetHelpId( itemId, HID_SVX_COMMON_MACRO_ORGANIZER ); pPopupMenu->SetHelpId( itemId, 40014 ); itemId++; break; } } } } } } <|endoftext|>
<commit_before>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // Copyright (C) 2016, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. /* Implementation of Batch Normalization layer. */ #include "../precomp.hpp" #include "layers_common.hpp" #include "op_halide.hpp" #include <opencv2/dnn/shape_utils.hpp> #include <iostream> namespace cv { namespace dnn { class MaxUnpoolLayerImpl : public MaxUnpoolLayer { public: MaxUnpoolLayerImpl(const LayerParams& params) { setParamsFrom(params); poolKernel = Size(params.get<int>("pool_k_w"), params.get<int>("pool_k_h")); poolPad = Size(params.get<int>("pool_pad_w"), params.get<int>("pool_pad_h")); poolStride = Size(params.get<int>("pool_stride_w"), params.get<int>("pool_stride_h")); } virtual bool supportBackend(int backendId) { return backendId == DNN_BACKEND_DEFAULT || backendId == DNN_BACKEND_HALIDE && haveHalide() && !poolPad.width && !poolPad.height; } bool getMemoryShapes(const std::vector<MatShape> &inputs, const int requiredOutputs, std::vector<MatShape> &outputs, std::vector<MatShape> &internals) const { CV_Assert(inputs.size() == 2); CV_Assert(total(inputs[0]) == total(inputs[1])); MatShape outShape = inputs[0]; outShape[2] = (outShape[2] - 1) * poolStride.height + poolKernel.height - 2 * poolPad.height; outShape[3] = (outShape[3] - 1) * poolStride.width + poolKernel.width - 2 * poolPad.width; outputs.clear(); outputs.push_back(outShape); return false; } void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr); } void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals) { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); CV_Assert(inputs.size() == 2); Mat& input = *inputs[0]; Mat& indices = *inputs[1]; CV_Assert(input.total() == indices.total()); CV_Assert(input.size[0] == 1); CV_Assert(input.isContinuous()); for(int i_n = 0; i_n < outputs.size(); i_n++) { Mat& outBlob = outputs[i_n]; outBlob.setTo(0); CV_Assert(input.size[1] == outBlob.size[1]); int outPlaneTotal = outBlob.size[2]*outBlob.size[3]; for (int i_c = 0; i_c < input.size[1]; i_c++) { Mat outPlane = getPlane(outBlob, 0, i_c); int wh_area = input.size[2]*input.size[3]; const float* inptr = input.ptr<float>(0, i_c); const float* idxptr = indices.ptr<float>(0, i_c); float* outptr = outPlane.ptr<float>(); for(int i_wh = 0; i_wh < wh_area; i_wh++) { int index = idxptr[i_wh]; if (!(0 <= index && index < outPlaneTotal)) { std::cerr << "i_n=" << i_n << std::endl << "i_c=" << i_c << std::endl << "i_wh=" << i_wh << std::endl << "index=" << index << std::endl << "outPlaneTotal=" << outPlaneTotal << std::endl << "input.size=" << input.size << std::endl << "indices.size=" << indices.size << std::endl << "outBlob=" << outBlob.size << std::endl ; CV_Assert(0 <= index && index < outPlaneTotal); } outptr[index] = inptr[i_wh]; } } } } virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &input) { #ifdef HAVE_HALIDE // Meaningless operation if false because if kernel > stride // it is not deterministic and if kernel < stride we just // skip a part of input data (you'd better change your model). if (poolKernel.width != poolStride.width || poolKernel.height != poolStride.height) CV_Error(cv::Error::StsNotImplemented, "Halide backend for maximum unpooling " "is not support cases when kernel != stride"); Halide::Var x("x"), y("y"), c("c"), n("n"); Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name)); Halide::Buffer<float> inputBuffer = halideBuffer(input[0]); Halide::Buffer<float> indices = halideBuffer(input[1]); Halide::Expr pooledX = x / poolKernel.width; Halide::Expr pooledY = y / poolKernel.height; const int outW = inputBuffer.width() * poolKernel.width; top(x, y, c, n) = select(y * outW + x == indices(pooledX, pooledY, c, n), inputBuffer(pooledX, pooledY, c, n), 0.0f); return Ptr<BackendNode>(new HalideBackendNode(top)); #endif // HAVE_HALIDE return Ptr<BackendNode>(); } }; Ptr<MaxUnpoolLayer> MaxUnpoolLayer::create(const LayerParams& params) { return Ptr<MaxUnpoolLayer>(new MaxUnpoolLayerImpl(params)); } } } <commit_msg>dnn: more debug information<commit_after>// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. // Copyright (C) 2016, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. /* Implementation of Batch Normalization layer. */ #include "../precomp.hpp" #include "layers_common.hpp" #include "op_halide.hpp" #include <opencv2/dnn/shape_utils.hpp> #include <iostream> namespace cv { namespace dnn { class MaxUnpoolLayerImpl : public MaxUnpoolLayer { public: MaxUnpoolLayerImpl(const LayerParams& params) { setParamsFrom(params); poolKernel = Size(params.get<int>("pool_k_w"), params.get<int>("pool_k_h")); poolPad = Size(params.get<int>("pool_pad_w"), params.get<int>("pool_pad_h")); poolStride = Size(params.get<int>("pool_stride_w"), params.get<int>("pool_stride_h")); } virtual bool supportBackend(int backendId) { return backendId == DNN_BACKEND_DEFAULT || backendId == DNN_BACKEND_HALIDE && haveHalide() && !poolPad.width && !poolPad.height; } bool getMemoryShapes(const std::vector<MatShape> &inputs, const int requiredOutputs, std::vector<MatShape> &outputs, std::vector<MatShape> &internals) const { CV_Assert(inputs.size() == 2); CV_Assert(total(inputs[0]) == total(inputs[1])); MatShape outShape = inputs[0]; outShape[2] = (outShape[2] - 1) * poolStride.height + poolKernel.height - 2 * poolPad.height; outShape[3] = (outShape[3] - 1) * poolStride.width + poolKernel.width - 2 * poolPad.width; outputs.clear(); outputs.push_back(outShape); return false; } void forward(InputArrayOfArrays inputs_arr, OutputArrayOfArrays outputs_arr, OutputArrayOfArrays internals_arr) { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); Layer::forward_fallback(inputs_arr, outputs_arr, internals_arr); } void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals) { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); CV_Assert(inputs.size() == 2); Mat& input = *inputs[0]; Mat& indices = *inputs[1]; CV_Assert(input.total() == indices.total()); CV_Assert(input.size[0] == 1); CV_Assert(input.isContinuous()); for(int i_n = 0; i_n < outputs.size(); i_n++) { Mat& outBlob = outputs[i_n]; outBlob.setTo(0); CV_Assert(input.size[1] == outBlob.size[1]); int outPlaneTotal = outBlob.size[2]*outBlob.size[3]; for (int i_c = 0; i_c < input.size[1]; i_c++) { Mat outPlane = getPlane(outBlob, 0, i_c); int wh_area = input.size[2]*input.size[3]; const float* inptr = input.ptr<float>(0, i_c); const float* idxptr = indices.ptr<float>(0, i_c); float* outptr = outPlane.ptr<float>(); for(int i_wh = 0; i_wh < wh_area; i_wh++) { int index = idxptr[i_wh]; if (!(0 <= index && index < outPlaneTotal)) { std::cerr << "i_n=" << i_n << std::endl << "i_c=" << i_c << std::endl << "i_wh=" << i_wh << std::endl << "index=" << index << std::endl << "maxval=" << inptr[i_wh] << std::endl << "outPlaneTotal=" << outPlaneTotal << std::endl << "input.size=" << input.size << std::endl << "indices.size=" << indices.size << std::endl << "outBlob=" << outBlob.size << std::endl ; CV_Assert(0 <= index && index < outPlaneTotal); } outptr[index] = inptr[i_wh]; } } } } virtual Ptr<BackendNode> initHalide(const std::vector<Ptr<BackendWrapper> > &input) { #ifdef HAVE_HALIDE // Meaningless operation if false because if kernel > stride // it is not deterministic and if kernel < stride we just // skip a part of input data (you'd better change your model). if (poolKernel.width != poolStride.width || poolKernel.height != poolStride.height) CV_Error(cv::Error::StsNotImplemented, "Halide backend for maximum unpooling " "is not support cases when kernel != stride"); Halide::Var x("x"), y("y"), c("c"), n("n"); Halide::Func top = (name.empty() ? Halide::Func() : Halide::Func(name)); Halide::Buffer<float> inputBuffer = halideBuffer(input[0]); Halide::Buffer<float> indices = halideBuffer(input[1]); Halide::Expr pooledX = x / poolKernel.width; Halide::Expr pooledY = y / poolKernel.height; const int outW = inputBuffer.width() * poolKernel.width; top(x, y, c, n) = select(y * outW + x == indices(pooledX, pooledY, c, n), inputBuffer(pooledX, pooledY, c, n), 0.0f); return Ptr<BackendNode>(new HalideBackendNode(top)); #endif // HAVE_HALIDE return Ptr<BackendNode>(); } }; Ptr<MaxUnpoolLayer> MaxUnpoolLayer::create(const LayerParams& params) { return Ptr<MaxUnpoolLayer>(new MaxUnpoolLayerImpl(params)); } } } <|endoftext|>
<commit_before>#include "SimpleAudioEngine.h" #include "Bird.h" #include "Path.h" USING_NS_CC; bool Bird::init() { if (!Sprite::init()) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); velocity = 0.0f; gravity = 18.0f; state = State::Normal; // setAnchorPoint(Point(0.5f, 1.0f)); auto animation = Animation::create(); int which = rand() % 3; for (int i = 0; i < 3; ++i) { auto imageName = String::createWithFormat(IMAGES_DIR "bird%d_%d.png", which, i); animation->addSpriteFrameWithFile(imageName->getCString()); } animation->setDelayPerUnit(0.2f); animation->setRestoreOriginalFrame(false); animation->setLoops(-1); normalAnimation = Animate::create(animation); runAction(normalAnimation); // fallAnimation = EaseOut::create(RotateTo::create(0.6f, 90.0f), 0.4f); fallAnimation = RotateTo::create(0.6f, 90.0f); fallAnimation->retain(); flyAnimation = Sequence::create( EaseOut::create(RotateTo::create(0.15f, 0), 0.4f), EaseIn::create(RotateTo::create(0.25f, -30), 0.4f), // RotateTo::create(0.15f, 0), // RotateTo::create(0.25f, -30), nullptr ); flyAnimation->retain(); return true; } void Bird::update(float dt) { float y = getPositionY() - velocity * dt; if (y > visibleSize.height) { y = visibleSize.height; } setPositionY(y); if (velocity < 0 && velocity + gravity >= 0) { fall(); } velocity += gravity; } void Bird::flyUp() { velocity = -360.0f; if (state != State::FlyingUp) { if (state == State::Falling) { stopAction(fallAnimation); } runAction(flyAnimation); state = State::FlyingUp; } } void Bird::fall() { if (state == State::FlyingUp) { stopAction(flyAnimation); runAction(fallAnimation); state = State::Falling; } } void Bird::die() { stopAllActions(); } <commit_msg>Remove unused header<commit_after>#include "Bird.h" #include "Path.h" USING_NS_CC; bool Bird::init() { if (!Sprite::init()) { return false; } visibleSize = Director::getInstance()->getVisibleSize(); velocity = 0.0f; gravity = 18.0f; state = State::Normal; // setAnchorPoint(Point(0.5f, 1.0f)); auto animation = Animation::create(); int which = rand() % 3; for (int i = 0; i < 3; ++i) { auto imageName = String::createWithFormat(IMAGES_DIR "bird%d_%d.png", which, i); animation->addSpriteFrameWithFile(imageName->getCString()); } animation->setDelayPerUnit(0.2f); animation->setRestoreOriginalFrame(false); animation->setLoops(-1); normalAnimation = Animate::create(animation); runAction(normalAnimation); // fallAnimation = EaseOut::create(RotateTo::create(0.6f, 90.0f), 0.4f); fallAnimation = RotateTo::create(0.6f, 90.0f); fallAnimation->retain(); flyAnimation = Sequence::create( EaseOut::create(RotateTo::create(0.15f, 0), 0.4f), EaseIn::create(RotateTo::create(0.25f, -30), 0.4f), // RotateTo::create(0.15f, 0), // RotateTo::create(0.25f, -30), nullptr ); flyAnimation->retain(); return true; } void Bird::update(float dt) { float y = getPositionY() - velocity * dt; if (y > visibleSize.height) { y = visibleSize.height; } setPositionY(y); if (velocity < 0 && velocity + gravity >= 0) { fall(); } velocity += gravity; } void Bird::flyUp() { velocity = -360.0f; if (state != State::FlyingUp) { if (state == State::Falling) { stopAction(fallAnimation); } runAction(flyAnimation); state = State::FlyingUp; } } void Bird::fall() { if (state == State::FlyingUp) { stopAction(flyAnimation); runAction(fallAnimation); state = State::Falling; } } void Bird::die() { stopAllActions(); } <|endoftext|>
<commit_before>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ComputeInitialConditionThread.h" #include "FEProblem.h" #include "DisplacedProblem.h" #include "Assembly.h" #include "InitialCondition.h" ComputeInitialConditionThread::ComputeInitialConditionThread(FEProblemBase & fe_problem) : _fe_problem(fe_problem) { } ComputeInitialConditionThread::ComputeInitialConditionThread(ComputeInitialConditionThread & x, Threads::split /*split*/) : _fe_problem(x._fe_problem) { } void ComputeInitialConditionThread::operator()(const ConstElemRange & range) { ParallelUniqueId puid; _tid = puid.id; const InitialConditionWarehouse & warehouse = _fe_problem.getInitialConditionWarehouse(); // Iterate over all the elements in the range for (const auto & elem : range) { const unsigned int n_nodes = elem->n_nodes(); // we need to execute objects that are for all subdomains covered by this // elements' nodes. std::set<SubdomainID> block_ids; for (unsigned int n = 0; n < n_nodes; n++) { auto node = elem->node_ptr(n); const auto & ids = _fe_problem.mesh().getNodeBlockIds(*node); block_ids.insert(ids.begin(), ids.end()); } // collect extra variables that are active due to our extra nodes // (explained in below comment) here so we can update this set with any // extra variables we pick up from multi-block nodes before calling fe // problem prepare. std::set<MooseVariableFEBase *> active_vars = _fe_problem.getActiveElementalMooseVariables(_tid); // we need to remember the order the variables originally are provided in // since the ics dependencies are resolved to handle the inter-variable // dependencies correctly. std::vector<MooseVariableFEBase *> order; // group all initial condition objects by variable. so we can compute all // its dof values at once and copy into solution vector once. This is // necessary because we have to collect extra off-block ic objects from // nodes shared between subdomains for cases where the off-block ic "wins" // on the interface. The grouping is required because we need to have all // the dof values for the element determined together so we can compute // the correct qp values, etc. for the variable. std::map<MooseVariableFEBase *, std::vector<std::shared_ptr<InitialConditionBase>>> groups; for (auto id : block_ids) if (warehouse.hasActiveBlockObjects(id, _tid)) for (auto ic : warehouse.getActiveBlockObjects(id, _tid)) { if ((id != elem->subdomain_id()) && !ic->variable().isNodal()) continue; order.push_back(&(ic->variable())); groups[&(ic->variable())].push_back(ic); active_vars.insert(&(ic->variable())); } _fe_problem.setActiveElementalMooseVariables(active_vars, _tid); _fe_problem.setCurrentSubdomainID(elem, _tid); _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); for (auto var : order) { DenseVector<Real> Ue; auto & vec = groups[var]; // because of all the off-node shenanigans/grouping above, per-variable // objects could possible have their order jumbled - so re-sort just in // case. try { DependencyResolverInterface::sort<std::shared_ptr<InitialConditionBase>>(vec); } catch (CyclicDependencyException<std::shared_ptr<InitialConditionBase>> & e) { DependencyResolverInterface::cyclicDependencyError<std::shared_ptr<InitialConditionBase>>( e, "Cyclic dependency detected in object ordering"); } for (auto ic : vec) ic->compute(); vec.clear(); // Now that all dofs are set for this variable, solemnize the solution. var->insert(var->sys().solution()); } } } void ComputeInitialConditionThread::join(const ComputeInitialConditionThread & /*y*/) { } <commit_msg>remove unnecessary active variable set updating<commit_after>//* This file is part of the MOOSE framework //* https://www.mooseframework.org //* //* All rights reserved, see COPYRIGHT for full restrictions //* https://github.com/idaholab/moose/blob/master/COPYRIGHT //* //* Licensed under LGPL 2.1, please see LICENSE for details //* https://www.gnu.org/licenses/lgpl-2.1.html #include "ComputeInitialConditionThread.h" #include "FEProblem.h" #include "DisplacedProblem.h" #include "Assembly.h" #include "InitialCondition.h" ComputeInitialConditionThread::ComputeInitialConditionThread(FEProblemBase & fe_problem) : _fe_problem(fe_problem) { } ComputeInitialConditionThread::ComputeInitialConditionThread(ComputeInitialConditionThread & x, Threads::split /*split*/) : _fe_problem(x._fe_problem) { } void ComputeInitialConditionThread::operator()(const ConstElemRange & range) { ParallelUniqueId puid; _tid = puid.id; const InitialConditionWarehouse & warehouse = _fe_problem.getInitialConditionWarehouse(); // Iterate over all the elements in the range for (const auto & elem : range) { const unsigned int n_nodes = elem->n_nodes(); // we need to execute objects that are for all subdomains covered by this // elements' nodes. std::set<SubdomainID> block_ids; for (unsigned int n = 0; n < n_nodes; n++) { auto node = elem->node_ptr(n); const auto & ids = _fe_problem.mesh().getNodeBlockIds(*node); block_ids.insert(ids.begin(), ids.end()); } // we need to remember the order the variables originally are provided in // since the ics dependencies are resolved to handle the inter-variable // dependencies correctly. std::vector<MooseVariableFEBase *> order; // group all initial condition objects by variable. so we can compute all // its dof values at once and copy into solution vector once. This is // necessary because we have to collect extra off-block ic objects from // nodes shared between subdomains for cases where the off-block ic "wins" // on the interface. The grouping is required because we need to have all // the dof values for the element determined together so we can compute // the correct qp values, etc. for the variable. std::map<MooseVariableFEBase *, std::vector<std::shared_ptr<InitialConditionBase>>> groups; for (auto id : block_ids) if (warehouse.hasActiveBlockObjects(id, _tid)) for (auto ic : warehouse.getActiveBlockObjects(id, _tid)) { if ((id != elem->subdomain_id()) && !ic->variable().isNodal()) continue; order.push_back(&(ic->variable())); groups[&(ic->variable())].push_back(ic); } _fe_problem.setCurrentSubdomainID(elem, _tid); _fe_problem.prepare(elem, _tid); _fe_problem.reinitElem(elem, _tid); for (auto var : order) { DenseVector<Real> Ue; auto & vec = groups[var]; // because of all the off-node shenanigans/grouping above, per-variable // objects could possible have their order jumbled - so re-sort just in // case. try { DependencyResolverInterface::sort<std::shared_ptr<InitialConditionBase>>(vec); } catch (CyclicDependencyException<std::shared_ptr<InitialConditionBase>> & e) { DependencyResolverInterface::cyclicDependencyError<std::shared_ptr<InitialConditionBase>>( e, "Cyclic dependency detected in object ordering"); } for (auto ic : vec) ic->compute(); vec.clear(); // Now that all dofs are set for this variable, solemnize the solution. var->insert(var->sys().solution()); } } } void ComputeInitialConditionThread::join(const ComputeInitialConditionThread & /*y*/) { } <|endoftext|>
<commit_before><commit_msg>planning: add mission_complete decision when pull over for destination is completed<commit_after><|endoftext|>
<commit_before>#include "VolumeJunctionOld.h" #include "FlowModelSinglePhase.h" #include "SinglePhaseFluidProperties.h" registerMooseObject("THMApp", VolumeJunctionOld); template <> InputParameters validParams<VolumeJunctionOld>() { InputParameters params = validParams<VolumeJunctionOldBase>(); return params; } VolumeJunctionOld::VolumeJunctionOld(const InputParameters & params) : VolumeJunctionOldBase(params), _rho_var_name(genName(name(), "rho")), _rhoe_var_name(genName(name(), "rhoE")), _vel_var_name(genName(name(), "vel")), _pressure_var_name(genName(name(), "p")), _energy_var_name(genName(name(), "energy")), _total_mfr_in_var_name(genName(name(), "total_mfr_in")) { } void VolumeJunctionOld::check() const { VolumeJunctionOldBase::check(); if (_flow_model_id != THM::FM_SINGLE_PHASE) logModelNotImplementedError(_flow_model_id); } void VolumeJunctionOld::addVariables() { // figure out delta H Real H_junction = _center(2); computeDeltaH(H_junction); // setup objects const SinglePhaseFluidProperties & spfp = _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name); Real initial_rho = spfp.rho_from_p_T(_initial_p, _initial_T); Real initial_e = spfp.e_from_p_rho(_initial_p, initial_rho); auto connected_subdomains = getConnectedSubdomainIDs(); _sim.addVariable( true, _rho_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[0]); _sim.addConstantScalarIC(_rho_var_name, initial_rho); _sim.addVariable( true, _rhoe_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[1]); _sim.addConstantScalarIC(_rhoe_var_name, initial_rho * initial_e); _sim.addVariable( true, _vel_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[2]); _sim.addConstantScalarIC(_vel_var_name, _initial_vel); // aux scalar vars _sim.addVariable(false, _pressure_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_pressure_var_name, _initial_p); _sim.addVariable(false, _energy_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_energy_var_name, initial_e); _sim.addVariable(false, _total_mfr_in_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_total_mfr_in_var_name, 0); } void VolumeJunctionOld::addMooseObjects() { std::vector<VariableName> cv_vel(1, FlowModelSinglePhase::VELOCITY); std::vector<VariableName> cv_pressure(1, FlowModelSinglePhase::PRESSURE); std::vector<VariableName> cv_enthalpy(1, FlowModelSinglePhase::SPECIFIC_TOTAL_ENTHALPY); std::vector<VariableName> cv_rhoA(1, FlowModelSinglePhase::RHOA); std::vector<VariableName> cv_rhouA(1, FlowModelSinglePhase::RHOUA); std::vector<VariableName> cv_rhoEA(1, FlowModelSinglePhase::RHOEA); std::vector<VariableName> cv_rho(1, FlowModelSinglePhase::DENSITY); std::vector<VariableName> cv_rhou(1, FlowModelSinglePhase::MOMENTUM_DENSITY); std::vector<VariableName> cv_rhoE(1, FlowModelSinglePhase::TOTAL_ENERGY_DENSITY); std::vector<VariableName> cv_v(1, FlowModelSinglePhase::SPECIFIC_VOLUME); std::vector<VariableName> cv_e(1, FlowModelSinglePhase::SPECIFIC_INTERNAL_ENERGY); std::vector<VariableName> cv_area(1, FlowModel::AREA); std::vector<VariableName> cv_junction_rho(1, _rho_var_name); std::vector<VariableName> cv_junction_rhoe(1, _rhoe_var_name); std::vector<VariableName> cv_junction_vel(1, _vel_var_name); std::vector<VariableName> cv_junction_pressure(1, _pressure_var_name); std::vector<VariableName> cv_junction_energy(1, _energy_var_name); { std::string class_name = "TotalMassFlowRateIntoJunctionAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _total_mfr_in_var_name; params.set<std::vector<dof_id_type>>("nodes") = _nodes; params.set<std::vector<Real>>("normals") = _normals; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; _sim.addAuxScalarKernel(class_name, genName(name(), "total_mfr_in"), params); } for (unsigned int i = 0; i < _boundary_names.size(); ++i) { // BCs { std::string class_name = "OneDMassFreeBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<std::vector<VariableName>>("arhouA") = cv_rhouA; _sim.addBoundaryCondition(class_name, genName("bc", _boundary_names[i], "rho"), params); } { std::string class_name = "VolumeJunctionOldBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<MooseEnum>("eqn_name") = FlowModel::getFlowEquationType("MOMENTUM"); params.set<Real>("K") = _k_coeffs[i]; params.set<Real>("K_reverse") = _kr_coeffs[i]; params.set<Real>("ref_area") = _ref_area; params.set<Real>("deltaH") = _deltaH[i]; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("A") = cv_area; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("rho") = cv_rho; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("rho_junction") = cv_junction_rho; params.set<std::vector<VariableName>>("rhoe_junction") = cv_junction_rhoe; params.set<std::vector<VariableName>>("vel_junction") = cv_junction_vel; params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure; params.set<UserObjectName>("fp") = _fp_name; params.set<Real>("gravity_magnitude") = _gravity_magnitude; std::string nm = genName("bc", _boundary_names[i], "rhou"); _sim.addBoundaryCondition(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } { std::string class_name = "VolumeJunctionOldBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOEA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<MooseEnum>("eqn_name") = FlowModel::getFlowEquationType("ENERGY"); params.set<Real>("K") = _k_coeffs[i]; params.set<Real>("K_reverse") = _kr_coeffs[i]; params.set<Real>("ref_area") = _ref_area; params.set<Real>("deltaH") = _deltaH[i]; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("A") = cv_area; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("rho") = cv_rho; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("rho_junction") = cv_junction_rho; params.set<std::vector<VariableName>>("rhoe_junction") = cv_junction_rhoe; params.set<std::vector<VariableName>>("vel_junction") = cv_junction_vel; params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure; params.set<UserObjectName>("fp") = _fp_name; params.set<Real>("gravity_magnitude") = _gravity_magnitude; std::string nm = genName("bc", _boundary_names[i], "rhoE"); _sim.addBoundaryCondition(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } } // add constraint for non-linear scalar { std::string class_name = "ODECoefTimeDerivative"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rho_var_name; params.set<Real>("coef") = _volume; std::string nm = genName(name(), _rho_var_name, "td"); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "volume", "coef"); } { InputParameters params = _factory.getValidParams("MassBalanceScalarKernel"); params.set<NonlinearVariableName>("variable") = _rho_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; std::string nm = genName(name(), "mass_balance"); _sim.addScalarKernel("MassBalanceScalarKernel", nm, params); } { std::string class_name = "ODECoefTimeDerivative"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rhoe_var_name; params.set<Real>("coef") = _volume; std::string nm = genName(name(), _rhoe_var_name, "td"); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "volume", "coef"); } { std::string class_name = "EnergyBalanceScalarKernel"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rhoe_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<UserObjectName>("fp") = _fp_name; // coupling variables params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("v") = cv_v; params.set<std::vector<VariableName>>("e") = cv_e; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("p") = cv_pressure; params.set<std::vector<VariableName>>("A") = cv_area; std::string nm = genName(name(), _rhoe_var_name, "st"); _sim.addScalarKernel(class_name, nm, params); } { std::string class_name = "MomentumBalanceScalarKernel"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _vel_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<Real>("ref_area") = _ref_area; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("junction_rho") = cv_junction_rho; std::string nm = genName(name(), "energy_balance", _vel_var_name); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } { std::string class_name = "VolumeJunctionPressureAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _pressure_var_name; params.set<UserObjectName>("fp") = _fp_name; // coupling variables params.set<std::vector<VariableName>>("junction_rho") = cv_junction_rho; params.set<std::vector<VariableName>>("junction_rhoe") = cv_junction_rhoe; _sim.addAuxScalarKernel(class_name, genName(name(), "p_aux"), params); } { std::string class_name = "QuotientScalarAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _energy_var_name; // coupling variables params.set<std::vector<VariableName>>("numerator") = cv_junction_rhoe; params.set<std::vector<VariableName>>("denominator") = cv_junction_rho; _sim.addAuxScalarKernel(class_name, genName(name(), "energy_aux"), params); } } <commit_msg>Cleanup in VolumeJunctionOld<commit_after>#include "VolumeJunctionOld.h" #include "FlowModelSinglePhase.h" #include "SinglePhaseFluidProperties.h" registerMooseObject("THMApp", VolumeJunctionOld); template <> InputParameters validParams<VolumeJunctionOld>() { InputParameters params = validParams<VolumeJunctionOldBase>(); return params; } VolumeJunctionOld::VolumeJunctionOld(const InputParameters & params) : VolumeJunctionOldBase(params), _rho_var_name(genName(name(), "rho")), _rhoe_var_name(genName(name(), "rhoE")), _vel_var_name(genName(name(), "vel")), _pressure_var_name(genName(name(), "p")), _energy_var_name(genName(name(), "energy")), _total_mfr_in_var_name(genName(name(), "total_mfr_in")) { } void VolumeJunctionOld::check() const { VolumeJunctionOldBase::check(); if (_flow_model_id != THM::FM_SINGLE_PHASE) logModelNotImplementedError(_flow_model_id); } void VolumeJunctionOld::addVariables() { // figure out delta H Real H_junction = _center(2); computeDeltaH(H_junction); // setup objects const SinglePhaseFluidProperties & spfp = _sim.getUserObject<SinglePhaseFluidProperties>(_fp_name); Real initial_rho = spfp.rho_from_p_T(_initial_p, _initial_T); Real initial_e = spfp.e_from_p_rho(_initial_p, initial_rho); auto connected_subdomains = getConnectedSubdomainIDs(); _sim.addVariable( true, _rho_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[0]); _sim.addConstantScalarIC(_rho_var_name, initial_rho); _sim.addVariable( true, _rhoe_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[1]); _sim.addConstantScalarIC(_rhoe_var_name, initial_rho * initial_e); _sim.addVariable( true, _vel_var_name, FEType(FIRST, SCALAR), connected_subdomains, _scale_factors[2]); _sim.addConstantScalarIC(_vel_var_name, _initial_vel); // aux scalar vars _sim.addVariable(false, _pressure_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_pressure_var_name, _initial_p); _sim.addVariable(false, _energy_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_energy_var_name, initial_e); _sim.addVariable(false, _total_mfr_in_var_name, FEType(FIRST, SCALAR), 0); _sim.addConstantScalarIC(_total_mfr_in_var_name, 0); } void VolumeJunctionOld::addMooseObjects() { std::vector<VariableName> cv_vel(1, FlowModelSinglePhase::VELOCITY); std::vector<VariableName> cv_pressure(1, FlowModelSinglePhase::PRESSURE); std::vector<VariableName> cv_enthalpy(1, FlowModelSinglePhase::SPECIFIC_TOTAL_ENTHALPY); std::vector<VariableName> cv_rhoA(1, FlowModelSinglePhase::RHOA); std::vector<VariableName> cv_rhouA(1, FlowModelSinglePhase::RHOUA); std::vector<VariableName> cv_rhoEA(1, FlowModelSinglePhase::RHOEA); std::vector<VariableName> cv_rho(1, FlowModelSinglePhase::DENSITY); std::vector<VariableName> cv_v(1, FlowModelSinglePhase::SPECIFIC_VOLUME); std::vector<VariableName> cv_e(1, FlowModelSinglePhase::SPECIFIC_INTERNAL_ENERGY); std::vector<VariableName> cv_area(1, FlowModel::AREA); std::vector<VariableName> cv_junction_rho(1, _rho_var_name); std::vector<VariableName> cv_junction_rhoe(1, _rhoe_var_name); std::vector<VariableName> cv_junction_vel(1, _vel_var_name); std::vector<VariableName> cv_junction_pressure(1, _pressure_var_name); std::vector<VariableName> cv_junction_energy(1, _energy_var_name); { std::string class_name = "TotalMassFlowRateIntoJunctionAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _total_mfr_in_var_name; params.set<std::vector<dof_id_type>>("nodes") = _nodes; params.set<std::vector<Real>>("normals") = _normals; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; _sim.addAuxScalarKernel(class_name, genName(name(), "total_mfr_in"), params); } for (unsigned int i = 0; i < _boundary_names.size(); ++i) { // BCs { std::string class_name = "OneDMassFreeBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<std::vector<VariableName>>("arhouA") = cv_rhouA; _sim.addBoundaryCondition(class_name, genName("bc", _boundary_names[i], "rho"), params); } { std::string class_name = "VolumeJunctionOldBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<MooseEnum>("eqn_name") = FlowModel::getFlowEquationType("MOMENTUM"); params.set<Real>("K") = _k_coeffs[i]; params.set<Real>("K_reverse") = _kr_coeffs[i]; params.set<Real>("ref_area") = _ref_area; params.set<Real>("deltaH") = _deltaH[i]; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("A") = cv_area; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("rho") = cv_rho; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("rho_junction") = cv_junction_rho; params.set<std::vector<VariableName>>("rhoe_junction") = cv_junction_rhoe; params.set<std::vector<VariableName>>("vel_junction") = cv_junction_vel; params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure; params.set<UserObjectName>("fp") = _fp_name; params.set<Real>("gravity_magnitude") = _gravity_magnitude; std::string nm = genName("bc", _boundary_names[i], "rhou"); _sim.addBoundaryCondition(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } { std::string class_name = "VolumeJunctionOldBC"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOEA; params.set<std::vector<BoundaryName>>("boundary") = {_boundary_names[i]}; params.set<Real>("normal") = _normals[i]; params.set<MooseEnum>("eqn_name") = FlowModel::getFlowEquationType("ENERGY"); params.set<Real>("K") = _k_coeffs[i]; params.set<Real>("K_reverse") = _kr_coeffs[i]; params.set<Real>("ref_area") = _ref_area; params.set<Real>("deltaH") = _deltaH[i]; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("A") = cv_area; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("rho") = cv_rho; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("rho_junction") = cv_junction_rho; params.set<std::vector<VariableName>>("rhoe_junction") = cv_junction_rhoe; params.set<std::vector<VariableName>>("vel_junction") = cv_junction_vel; params.set<std::vector<VariableName>>("p_junction") = cv_junction_pressure; params.set<UserObjectName>("fp") = _fp_name; params.set<Real>("gravity_magnitude") = _gravity_magnitude; std::string nm = genName("bc", _boundary_names[i], "rhoE"); _sim.addBoundaryCondition(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } } // add constraint for non-linear scalar { std::string class_name = "ODECoefTimeDerivative"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rho_var_name; params.set<Real>("coef") = _volume; std::string nm = genName(name(), _rho_var_name, "td"); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "volume", "coef"); } { InputParameters params = _factory.getValidParams("MassBalanceScalarKernel"); params.set<NonlinearVariableName>("variable") = _rho_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; std::string nm = genName(name(), "mass_balance"); _sim.addScalarKernel("MassBalanceScalarKernel", nm, params); } { std::string class_name = "ODECoefTimeDerivative"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rhoe_var_name; params.set<Real>("coef") = _volume; std::string nm = genName(name(), _rhoe_var_name, "td"); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "volume", "coef"); } { std::string class_name = "EnergyBalanceScalarKernel"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _rhoe_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<UserObjectName>("fp") = _fp_name; // coupling variables params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("v") = cv_v; params.set<std::vector<VariableName>>("e") = cv_e; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("p") = cv_pressure; params.set<std::vector<VariableName>>("A") = cv_area; std::string nm = genName(name(), _rhoe_var_name, "st"); _sim.addScalarKernel(class_name, nm, params); } { std::string class_name = "MomentumBalanceScalarKernel"; InputParameters params = _factory.getValidParams(class_name); params.set<NonlinearVariableName>("variable") = _vel_var_name; params.set<std::vector<BoundaryName>>("boundary") = _boundary_names; params.set<std::vector<Real>>("normals") = _normals; params.set<Real>("ref_area") = _ref_area; params.set<std::vector<VariableName>>("total_mfr_in") = {_total_mfr_in_var_name}; params.set<std::vector<VariableName>>("rhoA") = cv_rhoA; params.set<std::vector<VariableName>>("rhouA") = cv_rhouA; params.set<std::vector<VariableName>>("rhoEA") = cv_rhoEA; params.set<std::vector<VariableName>>("vel") = cv_vel; params.set<std::vector<VariableName>>("junction_rho") = cv_junction_rho; std::string nm = genName(name(), "energy_balance", _vel_var_name); _sim.addScalarKernel(class_name, nm, params); connectObject(params, nm, "A_ref", "ref_area"); } { std::string class_name = "VolumeJunctionPressureAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _pressure_var_name; params.set<UserObjectName>("fp") = _fp_name; // coupling variables params.set<std::vector<VariableName>>("junction_rho") = cv_junction_rho; params.set<std::vector<VariableName>>("junction_rhoe") = cv_junction_rhoe; _sim.addAuxScalarKernel(class_name, genName(name(), "p_aux"), params); } { std::string class_name = "QuotientScalarAux"; InputParameters params = _factory.getValidParams(class_name); params.set<AuxVariableName>("variable") = _energy_var_name; // coupling variables params.set<std::vector<VariableName>>("numerator") = cv_junction_rhoe; params.set<std::vector<VariableName>>("denominator") = cv_junction_rho; _sim.addAuxScalarKernel(class_name, genName(name(), "energy_aux"), params); } } <|endoftext|>
<commit_before>/* * This file is part of meego-im-framework * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mpassthruwindow.h" #include "mplainwindow.h" #include "mimapplication.h" #include <QX11Info> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #ifndef M_IM_DISABLE_TRANSLUCENCY #include <X11/extensions/Xfixes.h> #include <X11/extensions/shape.h> #endif MPassThruWindow::MPassThruWindow(bool bypassWMHint, bool selfComposited, QWidget *p) : QWidget(p), raiseOnShow(bypassWMHint), // if bypassing window hint, also do raise to ensure visibility selfComposited(selfComposited) { setWindowTitle("MInputMethod"); if (!selfComposited) setAttribute(Qt::WA_TranslucentBackground); Display *dpy = QX11Info::display(); Qt::WindowFlags windowFlags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint; if (bypassWMHint) { windowFlags |= Qt::X11BypassWindowManagerHint; } setWindowFlags(windowFlags); // Hint to the window manager that we don't want input focus // for the inputmethod window XWMHints wmhints; wmhints.flags = InputHint; wmhints.input = False; XSetWMHints(dpy, winId(), &wmhints); Atom input = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_INPUT", False); XChangeProperty(dpy, winId(), XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False), XA_ATOM, 32, PropModeReplace, (unsigned char *) &input, 1); connect(MIMApplication::instance(), SIGNAL(remoteWindowGone()), this, SLOT(inputPassthrough())); } MPassThruWindow::~MPassThruWindow() { } void MPassThruWindow::inputPassthrough(const QRegion &region) { #ifndef M_IM_DISABLE_TRANSLUCENCY Display *dpy = QX11Info::display(); #endif qDebug() << __PRETTY_FUNCTION__ << region << "geometry=" << geometry(); QVector<QRect> regionRects(region.rects()); const int size = regionRects.size(); if (size) { #ifdef M_IM_DISABLE_TRANSLUCENCY #ifdef M_IM_USE_SHAPE_WINDOW setMask(region); #else QPoint newPos(0, 0); switch (MPlainWindow::instance()->orientationAngle()) { case M::Angle0: newPos.setY(region.boundingRect().top()); break; case M::Angle90: newPos.setX(region.boundingRect().width() - width()); break; case M::Angle180: newPos.setY(region.boundingRect().height() - height()); break; case M::Angle270: newPos.setX(width() - region.boundingRect().width()); break; default: Q_ASSERT(0); } move(newPos); newPos.setX(-newPos.x()); newPos.setY(-newPos.y()); #endif #else XRectangle * const rects = (XRectangle*)malloc(sizeof(XRectangle)*(size)); if (!rects) { return; } quint32 customRegion[size * 4]; // custom region is pack of x, y, w, h XRectangle *rect = rects; for (int i = 0; i < size; ++i, ++rect) { rect->x = regionRects.at(i).x(); rect->y = regionRects.at(i).y(); rect->width = regionRects.at(i).width(); rect->height = regionRects.at(i).height(); customRegion[i * 4 + 0] = rect->x; customRegion[i * 4 + 1] = rect->y; customRegion[i * 4 + 2] = rect->width; customRegion[i * 4 + 3] = rect->height; } const XserverRegion shapeRegion = XFixesCreateRegion(dpy, rects, size); XFixesSetWindowShapeRegion(dpy, winId(), ShapeBounding, 0, 0, 0); XFixesSetWindowShapeRegion(dpy, winId(), ShapeInput, 0, 0, shapeRegion); XFixesDestroyRegion(dpy, shapeRegion); XChangeProperty(dpy, winId(), XInternAtom(dpy, "_MEEGOTOUCH_CUSTOM_REGION", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) customRegion, size * 4); free(rects); XSync(dpy, False); #endif } // selective compositing if (isVisible() && region.isEmpty()) { if (selfComposited) mApp->unredirectRemoteWindow(); hide(); } else if (!isVisible() && !region.isEmpty()) { if (selfComposited) mApp->redirectRemoteWindow(); show(); if (raiseOnShow) { raise(); } } } <commit_msg>Changes: Do not use winId().<commit_after>/* * This file is part of meego-im-framework * * * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * Contact: Nokia Corporation (directui@nokia.com) * * If you have questions regarding the use of this file, please contact * Nokia at directui@nokia.com. * * 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 * and appearing in the file LICENSE.LGPL included in the packaging * of this file. */ #include "mpassthruwindow.h" #include "mplainwindow.h" #include "mimapplication.h" #include <QX11Info> #include <X11/Xlib.h> #include <X11/Xatom.h> #include <X11/Xutil.h> #ifndef M_IM_DISABLE_TRANSLUCENCY #include <X11/extensions/Xfixes.h> #include <X11/extensions/shape.h> #endif MPassThruWindow::MPassThruWindow(bool bypassWMHint, bool selfComposited, QWidget *p) : QWidget(p), raiseOnShow(bypassWMHint), // if bypassing window hint, also do raise to ensure visibility selfComposited(selfComposited) { setWindowTitle("MInputMethod"); if (!selfComposited) { setAttribute(Qt::WA_TranslucentBackground); } Qt::WindowFlags windowFlags = Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint; if (bypassWMHint) { windowFlags |= Qt::X11BypassWindowManagerHint; } setWindowFlags(windowFlags); // We do not want input focus for that window. setAttribute(Qt::WA_X11DoNotAcceptFocus); connect(MIMApplication::instance(), SIGNAL(remoteWindowGone()), this, SLOT(inputPassthrough())); } MPassThruWindow::~MPassThruWindow() { } void MPassThruWindow::inputPassthrough(const QRegion &region) { #ifndef M_IM_DISABLE_TRANSLUCENCY Display *dpy = QX11Info::display(); #endif qDebug() << __PRETTY_FUNCTION__ << "QWidget::effectiveWinId(): " << effectiveWinId(); // Set _NET_WM_WINDOW_TYPE to _NET_WM_WINDOW_TYPE_INPUT static Atom input = XInternAtom(QX11Info::display(), "_NET_WM_WINDOW_TYPE_INPUT", False); static Atom window_type = XInternAtom(QX11Info::display(), "_NET_WM_WINDOW_TYPE", False); XChangeProperty(QX11Info::display(), effectiveWinId(), window_type, XA_ATOM, 32, PropModeReplace, (unsigned char *) &input, 1); qDebug() << __PRETTY_FUNCTION__ << region << "geometry=" << geometry(); QVector<QRect> regionRects(region.rects()); const int size = regionRects.size(); if (size) { #ifdef M_IM_DISABLE_TRANSLUCENCY #ifdef M_IM_USE_SHAPE_WINDOW setMask(region); #else QPoint newPos(0, 0); switch (MPlainWindow::instance()->orientationAngle()) { case M::Angle0: newPos.setY(region.boundingRect().top()); break; case M::Angle90: newPos.setX(region.boundingRect().width() - width()); break; case M::Angle180: newPos.setY(region.boundingRect().height() - height()); break; case M::Angle270: newPos.setX(width() - region.boundingRect().width()); break; default: Q_ASSERT(0); } move(newPos); newPos.setX(-newPos.x()); newPos.setY(-newPos.y()); #endif #else XRectangle * const rects = (XRectangle*)malloc(sizeof(XRectangle)*(size)); if (!rects) { return; } quint32 customRegion[size * 4]; // custom region is pack of x, y, w, h XRectangle *rect = rects; for (int i = 0; i < size; ++i, ++rect) { rect->x = regionRects.at(i).x(); rect->y = regionRects.at(i).y(); rect->width = regionRects.at(i).width(); rect->height = regionRects.at(i).height(); customRegion[i * 4 + 0] = rect->x; customRegion[i * 4 + 1] = rect->y; customRegion[i * 4 + 2] = rect->width; customRegion[i * 4 + 3] = rect->height; } const XserverRegion shapeRegion = XFixesCreateRegion(dpy, rects, size); XFixesSetWindowShapeRegion(dpy, effectiveWinId(), ShapeBounding, 0, 0, 0); XFixesSetWindowShapeRegion(dpy, effectiveWinId(), ShapeInput, 0, 0, shapeRegion); XFixesDestroyRegion(dpy, shapeRegion); XChangeProperty(dpy, effectiveWinId(), XInternAtom(dpy, "_MEEGOTOUCH_CUSTOM_REGION", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char *) customRegion, size * 4); free(rects); XSync(dpy, False); #endif } // selective compositing if (isVisible() && region.isEmpty()) { if (selfComposited) mApp->unredirectRemoteWindow(); hide(); } else if (!isVisible() && !region.isEmpty()) { if (selfComposited) mApp->redirectRemoteWindow(); show(); if (raiseOnShow) { raise(); } } } <|endoftext|>
<commit_before>#include <Network/cUDPClientManager.h> #include <cinder/app/App.h> #include <limits> #include <Utility/MessageBox.h> #include <Network/cUDPManager.h> #include <Scene/cSceneManager.h> #include <Scene/Member/cTitle.h> #include <Node/action.hpp> #include <Network/IpHost.h> namespace Network { cUDPClientManager::cUDPClientManager( ) : mCloseSecond( std::numeric_limits<float>::max( ) ) , mRoot( Node::node::create( ) ) , mConnectSecond( std::numeric_limits<float>::max( ) ) , mSequenceId( 0U ) , mIsConnected(false) , mServerTime( ) { mRoot->set_schedule_update( ); } void cUDPClientManager::close( ) { mSocket.close( ); mRoot->remove_action_by_name( "ping" ); } void cUDPClientManager::open( ) { mSocket.open( ); } bool cUDPClientManager::isConnected( ) { return mIsConnected; } void cUDPClientManager::connect( std::string const& ipAddress ) { mConnectServerHandle = cNetworkHandle( ipAddress, 25565 ); send( new Packet::Request::cReqConnect( ), false ); mConnectSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; } void cUDPClientManager::connectOfflineServer( ) { connect( Network::getLocalIpAddressHost( ) ); } void cUDPClientManager::update( float delta ) { if ( isConnected( ) ) { mServerTime += delta; } updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } float const & cUDPClientManager::getServerTime( ) { return mServerTime; } void cUDPClientManager::updateSend( ) { if ( !mConnectServerHandle ) { close( ); MES_ERR( "Mnh`łB", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } auto& handle = mConnectServerHandle; auto& buf = mSendDataBuffer; // CAuȃf[^l߂܂B auto reliableData = mReliableManager.update( ); std::copy( reliableData.begin( ), reliableData.end( ), std::back_inserter( buf ) ); // pPbg݂瑗܂B // TODO: 1024𒴉߂”\̂ŕđ邱ƁB if ( !buf.empty( ) ) { mSocket.write( mConnectServerHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } } void cUDPClientManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); mPackets.onReceive( chunk ); } connection( ); ping( ); } void cUDPClientManager::connection( ) { while ( auto p = mPackets.ResConnect.get( ) ) { mIsConnected = true; mCloseSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; mServerTime = p->time; using namespace Node::Action; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ this ] { send( new Packet::Request::cReqPing( ) ); } ) ) ); act->set_name( "ping" ); mRoot->run_action( act ); } if ( !isConnected( ) ) { if ( mConnectSecond < cinder::app::getElapsedSeconds( ) ) { close( ); MES_ERR( "T[o[̉܂B", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } } } void cUDPClientManager::ping( ) { while ( auto p = mPackets.EvePing.get( ) ) { mCloseSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; mServerTime = p->time; } if (mConnectServerHandle.ipAddress != Network::getLocalIpAddressHost()) { if (mCloseSecond < cinder::app::getElapsedSeconds()) { close(); MES_ERR( "T[o[Ƃ̐ڑ؂܂B", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } } } void cUDPClientManager::sendDataBufferAdd( cPacketBuffer const & packetBuffer, bool reliable ) { auto& buf = mSendDataBuffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( mConnectServerHandle, buf.size(), buf.data() ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; if ( reliable ) { std::vector<char> buf; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); mReliableManager.append( std::move( buf ) ); } else { buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } } }<commit_msg>コネクト時にリライアブルにしました。<commit_after>#include <Network/cUDPClientManager.h> #include <cinder/app/App.h> #include <limits> #include <Utility/MessageBox.h> #include <Network/cUDPManager.h> #include <Scene/cSceneManager.h> #include <Scene/Member/cTitle.h> #include <Node/action.hpp> #include <Network/IpHost.h> namespace Network { cUDPClientManager::cUDPClientManager( ) : mCloseSecond( std::numeric_limits<float>::max( ) ) , mRoot( Node::node::create( ) ) , mConnectSecond( std::numeric_limits<float>::max( ) ) , mSequenceId( 0U ) , mIsConnected(false) , mServerTime( ) { mRoot->set_schedule_update( ); } void cUDPClientManager::close( ) { mSocket.close( ); mRoot->remove_action_by_name( "ping" ); } void cUDPClientManager::open( ) { mSocket.open( ); } bool cUDPClientManager::isConnected( ) { return mIsConnected; } void cUDPClientManager::connect( std::string const& ipAddress ) { mConnectServerHandle = cNetworkHandle( ipAddress, 25565 ); send( new Packet::Request::cReqConnect( ), true ); mConnectSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; } void cUDPClientManager::connectOfflineServer( ) { connect( Network::getLocalIpAddressHost( ) ); } void cUDPClientManager::update( float delta ) { if ( isConnected( ) ) { mServerTime += delta; } updateRecv( ); updateSend( ); mRoot->entry_update( delta ); } float const & cUDPClientManager::getServerTime( ) { return mServerTime; } void cUDPClientManager::updateSend( ) { if ( !mConnectServerHandle ) { close( ); MES_ERR( "Mnh`łB", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } auto& handle = mConnectServerHandle; auto& buf = mSendDataBuffer; // CAuȃf[^l߂܂B auto reliableData = mReliableManager.update( ); std::copy( reliableData.begin( ), reliableData.end( ), std::back_inserter( buf ) ); // pPbg݂瑗܂B // TODO: 1024𒴉߂”\̂ŕđ邱ƁB if ( !buf.empty( ) ) { mSocket.write( mConnectServerHandle, buf.size( ), buf.data( ) ); buf.clear( ); buf.shrink_to_fit( ); } } void cUDPClientManager::updateRecv( ) { // M̂΃obt@[oăpPbg̕ʂsB while ( !mSocket.emptyChunk( ) ) { auto chunk = mSocket.popChunk( ); mPackets.onReceive( chunk ); } connection( ); ping( ); } void cUDPClientManager::connection( ) { while ( auto p = mPackets.ResConnect.get( ) ) { mIsConnected = true; mCloseSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; mServerTime = p->time; using namespace Node::Action; auto act = repeat_forever::create( sequence::create( delay::create( 1.5F ), call_func::create( [ this ] { send( new Packet::Request::cReqPing( ) ); } ) ) ); act->set_name( "ping" ); mRoot->run_action( act ); } if ( !isConnected( ) ) { if ( mConnectSecond < cinder::app::getElapsedSeconds( ) ) { close( ); MES_ERR( "T[o[̉܂B", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } } } void cUDPClientManager::ping( ) { while ( auto p = mPackets.EvePing.get( ) ) { mCloseSecond = cinder::app::getElapsedSeconds( ) + PING_HOLD_SECOND; mServerTime = p->time; } if (mConnectServerHandle.ipAddress != Network::getLocalIpAddressHost()) { if (mCloseSecond < cinder::app::getElapsedSeconds()) { close(); MES_ERR( "T[o[Ƃ̐ڑ؂܂B", [ ] { cSceneManager::getInstance( )->change<Scene::Member::cTitle>( ); } ); } } } void cUDPClientManager::sendDataBufferAdd( cPacketBuffer const & packetBuffer, bool reliable ) { auto& buf = mSendDataBuffer; // pPbg傫Ȃ肻ȂɑĂ܂܂B if ( 1024 < buf.size( ) ) { mSocket.write( mConnectServerHandle, buf.size(), buf.data() ); buf.clear( ); buf.shrink_to_fit( ); } ubyte2 const& byte = packetBuffer.transferredBytes; cBuffer const& buffer = packetBuffer.buffer; if ( reliable ) { std::vector<char> buf; buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); mReliableManager.append( std::move( buf ) ); } else { buf.resize( buf.size( ) + byte ); memcpy( buf.data( ) + buf.size( ) - byte, &buffer, byte ); } } }<|endoftext|>
<commit_before>#include "Bar.h" namespace CppChart { BarChart::BarChart(const std::vector<DataElement>& d, bool al, bool dv) : m_gap(10), m_guides(true), m_displayGuides(false), m_displayValues(dv), m_data(d), m_width(0), m_vSize(0.0f) { LogFnStart(); m_max = (*max_element(m_data.begin(), m_data.end())).value; m_legend.m_exists = al; if (m_legend.m_exists) { std::vector<DataFormat> temp; for (auto& element : d) { temp.push_back({ element.name, element.color }); } m_legend.AddData(temp); } LogFnEnd(); } }<commit_msg>Implement BarChart::Render()<commit_after>#include <sstream> #include <iomanip> #include "Bar.h" #include "ChartUtil.h" namespace CppChart { BarChart::BarChart(const std::vector<DataElement>& d, bool al, bool dv) : m_gap(10), m_guides(true), m_displayGuides(false), m_displayValues(dv), m_data(d), m_width(0), m_vSize(0.0f) { LogFnStart(); m_max = (*max_element(m_data.begin(), m_data.end())).value; m_legend.m_exists = al; if (m_legend.m_exists) { std::vector<DataFormat> temp; for (auto& element : d) { temp.push_back({ element.name, element.color }); } m_legend.AddData(temp); } LogFnEnd(); } void BarChart::Render() { LogFnStart(); float x = m_chartOffsets.x / 2.0f + m_gap, y = m_chartOffsets.y / 2.0f; float ratio = (m_chartHeight - 2.0f * m_chartOffsets.y - m_vSize) / m_max; float item; sf::Text text, values; sf::RectangleShape guideLines; m_width = (m_chartWidth - 2.0f * m_chartOffsets.x - m_gap * static_cast<float>(m_data.size())) / static_cast<float>(m_data.size()); m_vSize = m_width / static_cast<float>(CountDigit(m_max) + 3u); if (!m_legend.m_exists) { text.setFont(m_axes.labels.font); text.setColor(m_axes.labels.fontColor); text.setCharacterSize(m_axes.labels.fontSize); } if (m_displayValues) { values.setFont(m_axes.labels.font); values.setCharacterSize(m_vSize); } if (m_guides) { // TODO: Fix code } for (auto& d : m_data) { item = d.value; item *= ratio; m_bar.setPosition(x, m_chartHeight - y - item + m_vSize); m_bar.setSize(sf::Vector2f(m_width, item - m_axes.labels.fontSize - m_vSize)); m_bar.setFillColor(d.color); m_chartTexture.draw(m_bar); if (!m_legend.m_exists) { text.setString(d.name); SetTextAtCenter(text, x, m_chartHeight - y - 1.2f * m_axes.labels.fontSize, m_width + m_gap, m_axes.labels.fontSize); text.move(sf::Vector2f(-m_gap / 2.0f, 0.0f)); m_chartTexture.draw(text); } if (m_displayValues) { values.setColor(d.color); values.setString([&]() { std::ostringstream oss; oss << std::setprecision(2) << d.value; return oss.str(); }()); SetTextAtCenter(values, x, m_chartHeight - y - item - m_vSize / 2.0f, m_width + m_gap, m_vSize); values.move(sf::Vector2f(-m_gap / 2.0f, 0.0f)); m_chartTexture.draw(values); } x += m_width + m_gap; } DrawAxes(); LogFnEnd(); } } <|endoftext|>
<commit_before>/*-------------Lanczos.cpp----------------------------------------------------// * * Purpose: To diagonalize a random matrix using the Lanczos algorithm * * Notes: Compile with (for Arch systems): * g++ -I /usr/include/eigen3/ Lanczos.cpp * 0's along the prime diagonal. I don't know what this means. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <Eigen/Core> #include <random> #include <vector> #include <math.h> using namespace Eigen; // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd d_matrix); // Function for QR decomposition MatrixXd qrdecomp(MatrixXd Tridiag); // Function to return sign of value (signum function) int sign(double value); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ int size = 200; MatrixXd d_matrix(size,size); // set up random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); for (size_t i = 0; i < d_matrix.rows(); ++i){ for (size_t j = 0; j <= i; ++j){ d_matrix(i,j) = dist(gen); d_matrix(j,i) = d_matrix(i,j); } } MatrixXd Tridiag = lanczos(d_matrix); std::cout << '\n' << "Tridiagonal matrix is: \n"; for (size_t i = 0; i < Tridiag.rows(); ++i){ for (size_t j = 0; j < Tridiag.cols(); ++j){ std::cout << Tridiag(i, j) << '\t'; } std::cout << '\n'; } std::cout << '\n'; MatrixXd Q = qrdecomp(Tridiag); std::cout << Q << '\n'; } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd d_matrix){ // Creating random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); // Defining values double threshold = 0.01; int j = 0, j_tot = 5; int size = d_matrix.rows(); // Setting beta arbitrarily large for now double beta = 10; // generating the first rayleigh vector // alpha is actually just a double... sorry about that. MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1), alpha(1, 1); MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols()); // krylov is the krylovian subspace... Note, there might be a dynamic way to // do this. Something like: //std::vector <MatrixXd> krylov; MatrixXd krylov(d_matrix.rows(), j_tot); for (size_t i = 0; i < size; ++i){ rayleigh(i) = dist(gen); } //std::cout << rayleigh << '\n'; //while (beta > threshold){ for (size_t i = 0; i < j_tot; ++i){ beta = rayleigh.norm(); //std::cout << "beta is: \n" << beta << '\n'; q = rayleigh / beta; //std::cout << "q is: \n" << q << '\n'; alpha = q.transpose() * d_matrix * q; //std::cout << "alpha is \n" << alpha << '\n'; if (j == 0){ rayleigh = (d_matrix - alpha(0,0) * identity) * q; } else{ rayleigh = (d_matrix - alpha(0,0) * identity) * q - beta * krylov.col(j - 1); } //std::cout << "rayleigh is: \n" << rayleigh <<'\n'; //std::cout << "i is: " << i << '\n'; //krylov.push_back(q); krylov.col(j) = q; j = j+1; std::cout << j << '\n'; } MatrixXd krylov_id = krylov.transpose() * krylov; std::cout << "The identity matrix from the krylov subspace is: \n" << krylov_id << '\n'; MatrixXd T(j_tot,j_tot); T = krylov.transpose() * d_matrix * krylov; /* // Setting values to 0 if they are close... for (size_t i = 0; i < T.rows(); ++i){ for (size_t j = 0; j < T.cols(); ++j){ if (T(i,j) < 0.00001){ T(i,j) = 0; } } } */ return T; } // Function for QR decomposition // Because we only need Q for the power method, I will retun only Q MatrixXd qrdecomp(MatrixXd Tridiag){ // Q is and orthonormal vector => Q'Q = 1 MatrixXd Q(Tridiag.rows(), Tridiag.cols()); MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols()); // R is the upper triangular matrix MatrixXd R = Tridiag; std::cout << R << '\n'; int row_num = Tridiag.rows(); int countx = 0, county = 0; std::cout << "row_num is: " << row_num << '\n'; // Scale R double sum = 0.0, sigma, tau, fak, max_val = 0; for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ if (R(i,j) > max_val){ max_val = R(i,j); } } } for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ R(i,j) /= max_val; } } bool sing; // Defining vectors for algorithm MatrixXd diag(row_num,1); for (size_t i = 0; i < row_num; ++i){ // determining l_2 norm sum = 0.0; for (size_t j = i; j < row_num; ++j){ sum += R(j,i) * R(j,i); } sum = sqrt(sum); //std::cout << i << '\n'; if (sum == 0.0){ sing = true; diag(i) = 0.0; std::cout << "MATRIX IS SINGULAR!!!" << '\n'; } else{ if (R(i,i) >= 0){ diag(i) = -sum; } else{ diag(i) = sum; } fak = sqrt(sum * (sum + abs(R(i,i)))); std::cout << "fak is: " << fak << '\n'; R(i,i) = R(i,i) - diag(i); for (size_t j = i; j < row_num; ++j){ R(j,i) = R(j,i) / fak; } // Creating blocks to work with MatrixXd block1 = R.block(i, i+1, row_num-i, row_num - i - 1); MatrixXd block2 = R.block(i, i, row_num-i,1); std::cout << "R is: " << '\n' << R << '\n'; std::cout << "checking blocks:" << '\n'; std::cout << block1 << '\n' << '\n' << block2 << '\n'; block1 = block1 - block2 * (block2.transpose() * block1); // setting values back to what they need to be countx = 0; for (int j = i+1; j < row_num; ++j){ county = 0; for (int k = i; k < row_num; ++k){ R(k,j) = block1(county, countx); std::cout << k << '\t' << j << '\t' << countx << '\t' << county << '\t' << R(k,j) << '\n'; ++county; } ++countx; } } } std::cout << "R is: " << '\n'; std::cout << R << '\n'; MatrixXd z(row_num, 1); // Explicitly defining Q // Create column block for multiplication for (size_t i = 0; i < row_num; ++i){ MatrixXd Idblock = Id.block(0, i, row_num, 1); std::cout << "i is: " << i << '\n'; std::cout << "IDblock is: " << '\n' << Idblock << '\n'; for (int j = row_num-1; j >= 0; --j){ z = Idblock; std::cout << "j is: " << j << '\n'; // Creating blocks for multiplication MatrixXd zblock = z.block(j, 0, row_num - j, 1); MatrixXd Rblock = R.block(j, j, row_num - j, 1); // Performing multiplication zblock = zblock - Rblock * (Rblock.transpose() * zblock); // Set xblock up for next iteration of k int count = 0; for (int k = j; k < row_num; ++k){ z(k) = zblock(count); ++count; } } std::cout << "got to here" << '\n'; Q.col(i) = z; std::cout << Q << '\n'; } // Remove lower left from R for (int i = 0; i < row_num; ++i){ R(i,i) = diag(i); for (int j = 0; j < i; ++j){ R(i,j) = 0; } } std::cout << "R is: " << '\n' << R << '\n'; std::cout << "Q^T * Q is: " << '\n' << Q * Q.transpose() << '\n' << '\n'; return Q.transpose(); } // Function to return sign of value (signum function) int sign(double value){ if (value < 0.0){ return -1; } else if (value > 0){ return 1; } else { return 0; } } <commit_msg>Can successfully find largest Eigenvector / Value Now the question is: How do we find all the others?<commit_after>/*-------------Lanczos.cpp----------------------------------------------------// * * Purpose: To diagonalize a random matrix using the Lanczos algorithm * * Notes: Compile with (for Arch systems): * g++ -I /usr/include/eigen3/ Lanczos.cpp * 0's along the prime diagonal. I don't know what this means. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <Eigen/Core> #include <random> #include <vector> #include <math.h> using namespace Eigen; // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix); // Function for QR decomposition MatrixXd qrdecomp(MatrixXd &Tridiag); // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q); // Function to return sign of value (signum function) int sign(double value); // Function to check eigenvectors and values void eigentest(MatrixXd &d_matrix, MatrixXd &Q); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ int size = 200; MatrixXd d_matrix(size,size); // set up random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); for (size_t i = 0; i < d_matrix.rows(); ++i){ for (size_t j = 0; j <= i; ++j){ d_matrix(i,j) = dist(gen); d_matrix(j,i) = d_matrix(i,j); } } MatrixXd Tridiag = lanczos(d_matrix); std::cout << '\n' << "Tridiagonal matrix is: \n"; for (size_t i = 0; i < Tridiag.rows(); ++i){ for (size_t j = 0; j < Tridiag.cols(); ++j){ std::cout << Tridiag(i, j) << '\t'; } std::cout << '\n'; } std::cout << '\n'; MatrixXd Q = qrdecomp(Tridiag); MatrixXd Qtemp = Q; std::cout << Q << '\n'; std::cout << "Finding eigenvalues: " << '\n'; p_method(Tridiag, Q); Qtemp = Qtemp - Q; std::cout << "After the Power Method: " << Qtemp.squaredNorm() << '\n'; eigentest(Tridiag, Q); } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix){ // Creating random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); // Defining values double threshold = 0.01; int j = 0, j_tot = 5; int size = d_matrix.rows(); // Setting beta arbitrarily large for now double beta = 10; // generating the first rayleigh vector // alpha is actually just a double... sorry about that. MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1), alpha(1, 1); MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols()); // krylov is the krylovian subspace... Note, there might be a dynamic way to // do this. Something like: //std::vector <MatrixXd> krylov; MatrixXd krylov(d_matrix.rows(), j_tot); for (size_t i = 0; i < size; ++i){ rayleigh(i) = dist(gen); } //std::cout << rayleigh << '\n'; //while (beta > threshold){ for (size_t i = 0; i < j_tot; ++i){ beta = rayleigh.norm(); //std::cout << "beta is: \n" << beta << '\n'; q = rayleigh / beta; //std::cout << "q is: \n" << q << '\n'; alpha = q.transpose() * d_matrix * q; //std::cout << "alpha is \n" << alpha << '\n'; if (j == 0){ rayleigh = (d_matrix - alpha(0,0) * identity) * q; } else{ rayleigh = (d_matrix - alpha(0,0) * identity) * q - beta * krylov.col(j - 1); } //std::cout << "rayleigh is: \n" << rayleigh <<'\n'; //std::cout << "i is: " << i << '\n'; //krylov.push_back(q); krylov.col(j) = q; j = j+1; // std::cout << j << '\n'; } MatrixXd krylov_id = krylov.transpose() * krylov; std::cout << "The identity matrix from the krylov subspace is: \n" << krylov_id << '\n'; MatrixXd T(j_tot,j_tot); T = krylov.transpose() * d_matrix * krylov; return T; } // Function for QR decomposition // Because we only need Q for the power method, I will retun only Q MatrixXd qrdecomp(MatrixXd &Tridiag){ // Q is and orthonormal vector => Q'Q = 1 MatrixXd Q(Tridiag.rows(), Tridiag.cols()); MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols()); // R is the upper triangular matrix MatrixXd R = Tridiag; int row_num = Tridiag.rows(); int countx = 0, county = 0; // Scale R double sum = 0.0, sigma, tau, fak, max_val = 0; for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ if (R(i,j) > max_val){ max_val = R(i,j); } } } for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ R(i,j) /= max_val; } } bool sing; // Defining vectors for algorithm MatrixXd diag(row_num,1); for (size_t i = 0; i < row_num; ++i){ // determining l_2 norm sum = 0.0; for (size_t j = i; j < row_num; ++j){ sum += R(j,i) * R(j,i); } sum = sqrt(sum); if (sum == 0.0){ sing = true; diag(i) = 0.0; std::cout << "MATRIX IS SINGULAR!!!" << '\n'; } else{ if (R(i,i) >= 0){ diag(i) = -sum; } else{ diag(i) = sum; } fak = sqrt(sum * (sum + abs(R(i,i)))); R(i,i) = R(i,i) - diag(i); for (size_t j = i; j < row_num; ++j){ R(j,i) = R(j,i) / fak; } // Creating blocks to work with MatrixXd block1 = R.block(i, i+1, row_num-i, row_num - i - 1); MatrixXd block2 = R.block(i, i, row_num-i,1); block1 = block1 - block2 * (block2.transpose() * block1); // setting values back to what they need to be countx = 0; for (int j = i+1; j < row_num; ++j){ county = 0; for (int k = i; k < row_num; ++k){ R(k,j) = block1(county, countx); ++county; } ++countx; } } } MatrixXd z(row_num, 1); // Explicitly defining Q // Create column block for multiplication for (size_t i = 0; i < row_num; ++i){ MatrixXd Idblock = Id.block(0, i, row_num, 1); for (int j = row_num-1; j >= 0; --j){ z = Idblock; // Creating blocks for multiplication MatrixXd zblock = z.block(j, 0, row_num - j, 1); MatrixXd Rblock = R.block(j, j, row_num - j, 1); // Performing multiplication zblock = zblock - Rblock * (Rblock.transpose() * zblock); // Set xblock up for next iteration of k int count = 0; for (int k = j; k < row_num; ++k){ z(k) = zblock(count); ++count; } } Q.col(i) = z; //std::cout << Q << '\n'; } // Remove lower left from R for (int i = 0; i < row_num; ++i){ R(i,i) = diag(i); for (int j = 0; j < i; ++j){ R(i,j) = 0; } } //std::cout << "R is: " << '\n' << R << '\n'; MatrixXd temp = Q.transpose() * Q; /* std::cout << "Truncated Q^T * Q is:" << '\n'; for (int i = 0; i < temp.rows(); ++i){ for (int j = 0; j < temp.cols(); ++j){ if (temp(i,j) < 0.00000000001){ std::cout << 0 << '\t'; } else{ std::cout << temp(i,j) <<'\t'; } } std::cout << '\n'; } std::cout << '\n'; */ //std::cout << "Q^T * Q is: " << '\n' << Q * Q.transpose() << '\n' << '\n'; return Q.transpose(); } // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q){ // Find all eigenvectors MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols()); MatrixXd Z(Tridiag.rows(), Tridiag.cols()); MatrixXd Qtemp = Q; // Iteratively defines eigenvectors for (int i = 0; i < Tridiag.rows(); ++i){ Z = Tridiag * Q; Q = qrdecomp(Z); } Qtemp = Qtemp - Q; std::cout << "This should not be 0: " << Qtemp.squaredNorm() << '\n'; } // Function to return sign of value (signum function) int sign(double value){ if (value < 0.0){ return -1; } else if (value > 0){ return 1; } else { return 0; } } // Function to check eigenvectors and values void eigentest(MatrixXd &Tridiag, MatrixXd &Q){ // Calculating the Rayleigh quotient (v^t * A * v) / (v^t * v) // Note, that this should be a representation of eigenvalues std::vector<double> eigenvalues(Tridiag.rows()); MatrixXd eigenvector(Tridiag.rows(),1); double QQ, QAQ; for (size_t i = 0; i < Tridiag.rows(); ++i){ QQ = Q.col(i).transpose() * Q.col(i); QAQ = Q.col(i).transpose() * Tridiag * Q.col(i); eigenvalues[i] = QAQ / QQ; std::cout << "eigenvalue is: " << eigenvalues[i] << '\n'; eigenvector = ((Tridiag * Q.col(i)) / eigenvalues[i]) - Q.col(i); std::cout << "This should be 0: " << '\t' << eigenvector.squaredNorm() << '\n'; } } <|endoftext|>
<commit_before>/* TSIframework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2009 Carles F. Julià <carles.fernandez@upf.edu> 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. */ #ifndef SINGLETON_H #define SINGLETON_H //Inspired by http://cc.byexamples.com/20080609/stl-singleton-template/ class VoidClass{}; template<typename T, class Base=VoidClass> class Singleton : public Base { public: static T& Instance() { static T me; return me; } static T* get() { return &Instance(); } }; #endif //SINGLETON_H <commit_msg>Support for multiple inheritance in Singleton template<commit_after>/* TSIframework . Framework for Taller de Sistemes Interactius I Universitat Pompeu Fabra Copyright (c) 2009 Carles F. Julià <carles.fernandez@upf.edu> 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. */ #ifndef SINGLETON_H #define SINGLETON_H //Inspired by http://cc.byexamples.com/20080609/stl-singleton-template/ class VoidClass{}; class VoidClass2{}; template<typename T, class Base=VoidClass, class Base2=VoidClass2> class Singleton : public Base, public Base2 { public: static T& Instance() { static T me; return me; } static T* get() { return &Instance(); } }; #endif //SINGLETON_H <|endoftext|>
<commit_before>/* * Copyright (c) 2017, 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. */ #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "wifi_tests.h" using namespace utest::v1; void wifi_connect_params_valid_secure(void) { WiFiInterface *wifi = get_interface(); if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA2) == NSAPI_ERROR_OK) { TEST_PASS(); } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2) == NSAPI_ERROR_OK) { TEST_PASS(); } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA) == NSAPI_ERROR_OK) { TEST_PASS(); } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WEP) == NSAPI_ERROR_OK) { TEST_PASS(); } TEST_FAIL(); } <commit_msg>Greentea Wifi testcase fixes<commit_after>/* * Copyright (c) 2017, 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. */ #include "mbed.h" #include "greentea-client/test_env.h" #include "unity.h" #include "utest.h" #include "wifi_tests.h" using namespace utest::v1; void wifi_connect_params_valid_secure(void) { WiFiInterface *wifi = get_interface(); if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA2) == NSAPI_ERROR_OK) { return; } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2) == NSAPI_ERROR_OK) { return; } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA) == NSAPI_ERROR_OK) { return; } if(wifi->connect(MBED_CONF_APP_WIFI_SECURE_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WEP) == NSAPI_ERROR_OK) { return; } TEST_FAIL(); } <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkKmeansModelEstimatorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Insight classes #include "itkImage.h" #include "itkVector.h" #include "vnl/vnl_matrix_fixed.h" #include "vnl/vnl_math.h" #include "itkImageRegionIterator.h" #include "itkLightProcessObject.h" #include "itkImageKmeansModelEstimator.h" #include "itkDistanceToCentroidMembershipFunction.h" //Data definitions #define IMGWIDTH 16 #define IMGHEIGHT 1 #define NFRAMES 1 #define NUMBANDS 2 #define NDIMENSION 3 #define CDBKWIDTH 4 #define CDBKHEIGHT 1 #define NFRAMES 1 #define NCODEWORDS CDBKWIDTH * CDBKHEIGHT * NFRAMES #define NUMBANDS 2 #define NDIMENSION 3 #define STARTFRAME 0 #define NUM_BYTES_PER_PIXEL 1 #define ONEBAND 1 // class to support progress feeback class ShowProgressObject { public: ShowProgressObject(itk::LightProcessObject * o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::LightProcessObject::Pointer m_Process; }; int itkKmeansModelEstimatorTest(int, char* [] ) { //------------------------------------------------------ //Create a simple test vector with 16 entries and 2 bands //------------------------------------------------------ typedef itk::Image<itk::Vector<double,NUMBANDS>,NDIMENSION> VecImageType; typedef VecImageType::PixelType VecImagePixelType; VecImageType::Pointer vecImage = VecImageType::New(); VecImageType::SizeType vecImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }}; VecImageType::IndexType index; index.Fill(0); VecImageType::RegionType region; region.SetSize( vecImgSize ); region.SetIndex( index ); vecImage->SetLargestPossibleRegion( region ); vecImage->SetBufferedRegion( region ); vecImage->Allocate(); // setup the iterators typedef VecImageType::PixelType VecPixelType; enum { VecImageDimension = VecImageType::ImageDimension }; typedef itk::ImageRegionIterator< VecImageType > VecIterator; VecIterator outIt( vecImage, vecImage->GetBufferedRegion() ); //-------------------------------------------------------------------------- //Manually create and store each vector //-------------------------------------------------------------------------- //Vector no. 1 VecPixelType vec; vec[0] = 21; vec[1] = 9; outIt.Set( vec ); ++outIt; //Vector no. 2 vec[0] = 10; vec[1] = 20; outIt.Set( vec ); ++outIt; //Vector no. 3 vec[0] = 8; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 4 vec[0] = 10; vec[1] = 23; outIt.Set( vec ); ++outIt; //Vector no. 5 vec[0] = 12; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 6 vec[0] = 11; vec[1] = 12; outIt.Set( vec ); ++outIt; //Vector no. 7 vec[0] = 15; vec[1] = 22; outIt.Set( vec ); ++outIt; //Vector no. 8 vec[0] = 9; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 9 vec[0] = 19; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 10 vec[0] = 19; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 11 vec[0] = 21; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 12 vec[0] = 11; vec[1] = 20; outIt.Set( vec ); ++outIt; //Vector no. 13 vec[0] = 8; vec[1] = 18; outIt.Set( vec ); ++outIt; //Vector no. 14 vec[0] = 18; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 15 vec[0] = 22; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 16 vec[0] = 24; vec[1] = 23; outIt.Set( vec ); ++outIt; //--------------------------------------------------------------- //Input the codebook //--------------------------------------------------------------- //------------------------------------------------------------------ //Read the codebook into an vnl_matrix //------------------------------------------------------------------ vnl_matrix<double> inCDBK(NCODEWORDS, NUMBANDS); //There are 4 entries to the code book int r,c; r=0; c=0; inCDBK.put(r,c,10); r=0; c=1; inCDBK.put(r,c,10); r=1; c=0; inCDBK.put(r,c,10); r=1; c=1; inCDBK.put(r,c,20); r=2; c=0; inCDBK.put(r,c,20); r=2; c=1; inCDBK.put(r,c,10); r=3; c=0; inCDBK.put(r,c,20); r=3; c=1; inCDBK.put(r,c,20); //---------------------------------------------------------------------- // Test code for the Kmeans model estimator //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Multiband data is now available in the right format //--------------------------------------------------------------------- //---------------------------------------------------------------------- //Set membership function (Using the statistics objects) //---------------------------------------------------------------------- namespace stat = itk::Statistics; typedef stat::DistanceToCentroidMembershipFunction< VecImagePixelType > MembershipFunctionType ; typedef MembershipFunctionType::Pointer MembershipFunctionPointer ; typedef std::vector< MembershipFunctionPointer > MembershipFunctionPointerVector; //---------------------------------------------------------------------- //Set the image model estimator //---------------------------------------------------------------------- typedef itk::ImageKmeansModelEstimator<VecImageType, MembershipFunctionType> ImageKmeansModelEstimatorType; ImageKmeansModelEstimatorType::Pointer applyKmeansEstimator = ImageKmeansModelEstimatorType::New(); //---------------------------------------------------------------------- //Set the parameters of the clusterer //---------------------------------------------------------------------- applyKmeansEstimator->SetInputImage(vecImage); applyKmeansEstimator->SetNumberOfModels(NCODEWORDS); applyKmeansEstimator->SetThreshold(0.01); applyKmeansEstimator->Update(); applyKmeansEstimator->Print(std::cout); MembershipFunctionPointerVector membershipFunctions = applyKmeansEstimator->GetMembershipFunctions(); vnl_vector<double> kmeansResultForClass; vnl_vector<double> referenceCodebookForClass; vnl_vector<double> errorForClass; double error =0; double meanCDBKvalue = 0; for(unsigned int classIndex=0; classIndex < membershipFunctions.size(); classIndex++ ) { kmeansResultForClass = membershipFunctions[classIndex]->GetCentroid(); referenceCodebookForClass = inCDBK.get_row( classIndex); errorForClass = kmeansResultForClass - referenceCodebookForClass; for(int i = 0; i < NUMBANDS; i++) { error += vnl_math_abs(errorForClass[i]/referenceCodebookForClass[i]); meanCDBKvalue += referenceCodebookForClass[i]; } } error /= NCODEWORDS*NUMBANDS; meanCDBKvalue /= NCODEWORDS*NUMBANDS; if( error < 0.1 * meanCDBKvalue) std::cout << "Kmeans algorithm passed (without initial input)"<<std::endl; else std::cout << "Kmeans algorithm failed (without initial input)"<<std::endl; //Validation with no codebook/initial Kmeans estimate vnl_matrix<double> kmeansResult = applyKmeansEstimator->GetKmeansResults(); applyKmeansEstimator->SetCodebook(inCDBK); applyKmeansEstimator->Update(); applyKmeansEstimator->Print(std::cout); membershipFunctions = applyKmeansEstimator->GetMembershipFunctions(); //Validation with initial Kmeans estimate provided as input by the user error =0; meanCDBKvalue = 0; const unsigned int test = membershipFunctions.size(); for(unsigned int classIndex=0; classIndex < test; classIndex++ ) { kmeansResultForClass = membershipFunctions[classIndex]->GetCentroid(); referenceCodebookForClass = inCDBK.get_row( classIndex); errorForClass = kmeansResultForClass - referenceCodebookForClass; for(int i = 0; i < NUMBANDS; i++) { error += vnl_math_abs(errorForClass[i]/referenceCodebookForClass[i]); meanCDBKvalue += referenceCodebookForClass[i]; } } error /= NCODEWORDS*NUMBANDS; meanCDBKvalue /= NCODEWORDS*NUMBANDS; if( error < 0.1 * meanCDBKvalue) std::cout << "Kmeans algorithm passed (with initial input)"<<std::endl; else std::cout << "Kmeans algorithm failed (with initial input)"<<std::endl; return 0; } <commit_msg>ENH: Added more testing to increase coverage.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkKmeansModelEstimatorTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // Insight classes #include "itkImage.h" #include "itkVector.h" #include "vnl/vnl_matrix_fixed.h" #include "vnl/vnl_math.h" #include "itkImageRegionIterator.h" #include "itkLightProcessObject.h" #include "itkImageKmeansModelEstimator.h" #include "itkDistanceToCentroidMembershipFunction.h" //Data definitions #define IMGWIDTH 16 #define IMGHEIGHT 1 #define NFRAMES 1 #define NUMBANDS 2 #define NDIMENSION 3 #define CDBKWIDTH 4 #define CDBKHEIGHT 1 #define NFRAMES 1 #define NCODEWORDS CDBKWIDTH * CDBKHEIGHT * NFRAMES #define NUMBANDS 2 #define NDIMENSION 3 #define STARTFRAME 0 #define NUM_BYTES_PER_PIXEL 1 #define ONEBAND 1 // class to support progress feeback class ShowProgressObject { public: ShowProgressObject(itk::LightProcessObject * o) {m_Process = o;} void ShowProgress() {std::cout << "Progress " << m_Process->GetProgress() << std::endl;} itk::LightProcessObject::Pointer m_Process; }; int itkKmeansModelEstimatorTest(int, char* [] ) { //------------------------------------------------------ //Create a simple test vector with 16 entries and 2 bands //------------------------------------------------------ typedef itk::Image<itk::Vector<double,NUMBANDS>,NDIMENSION> VecImageType; typedef VecImageType::PixelType VecImagePixelType; VecImageType::Pointer vecImage = VecImageType::New(); VecImageType::SizeType vecImgSize = {{ IMGWIDTH , IMGHEIGHT, NFRAMES }}; VecImageType::IndexType index; index.Fill(0); VecImageType::RegionType region; region.SetSize( vecImgSize ); region.SetIndex( index ); vecImage->SetLargestPossibleRegion( region ); vecImage->SetBufferedRegion( region ); vecImage->Allocate(); // setup the iterators typedef VecImageType::PixelType VecPixelType; enum { VecImageDimension = VecImageType::ImageDimension }; typedef itk::ImageRegionIterator< VecImageType > VecIterator; VecIterator outIt( vecImage, vecImage->GetBufferedRegion() ); //-------------------------------------------------------------------------- //Manually create and store each vector //-------------------------------------------------------------------------- //Vector no. 1 VecPixelType vec; vec[0] = 21; vec[1] = 9; outIt.Set( vec ); ++outIt; //Vector no. 2 vec[0] = 10; vec[1] = 20; outIt.Set( vec ); ++outIt; //Vector no. 3 vec[0] = 8; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 4 vec[0] = 10; vec[1] = 23; outIt.Set( vec ); ++outIt; //Vector no. 5 vec[0] = 12; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 6 vec[0] = 11; vec[1] = 12; outIt.Set( vec ); ++outIt; //Vector no. 7 vec[0] = 15; vec[1] = 22; outIt.Set( vec ); ++outIt; //Vector no. 8 vec[0] = 9; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 9 vec[0] = 19; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 10 vec[0] = 19; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 11 vec[0] = 21; vec[1] = 21; outIt.Set( vec ); ++outIt; //Vector no. 12 vec[0] = 11; vec[1] = 20; outIt.Set( vec ); ++outIt; //Vector no. 13 vec[0] = 8; vec[1] = 18; outIt.Set( vec ); ++outIt; //Vector no. 14 vec[0] = 18; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 15 vec[0] = 22; vec[1] = 10; outIt.Set( vec ); ++outIt; //Vector no. 16 vec[0] = 24; vec[1] = 23; outIt.Set( vec ); ++outIt; //--------------------------------------------------------------- //Input the codebook //--------------------------------------------------------------- //------------------------------------------------------------------ //Read the codebook into an vnl_matrix //------------------------------------------------------------------ vnl_matrix<double> inCDBK(NCODEWORDS, NUMBANDS); //There are 4 entries to the code book int r,c; r=0; c=0; inCDBK.put(r,c,10); r=0; c=1; inCDBK.put(r,c,10); r=1; c=0; inCDBK.put(r,c,10); r=1; c=1; inCDBK.put(r,c,20); r=2; c=0; inCDBK.put(r,c,20); r=2; c=1; inCDBK.put(r,c,10); r=3; c=0; inCDBK.put(r,c,20); r=3; c=1; inCDBK.put(r,c,20); //---------------------------------------------------------------------- // Test code for the Kmeans model estimator //---------------------------------------------------------------------- //--------------------------------------------------------------------- // Multiband data is now available in the right format //--------------------------------------------------------------------- //---------------------------------------------------------------------- //Set membership function (Using the statistics objects) //---------------------------------------------------------------------- namespace stat = itk::Statistics; typedef stat::DistanceToCentroidMembershipFunction< VecImagePixelType > MembershipFunctionType ; typedef MembershipFunctionType::Pointer MembershipFunctionPointer ; typedef std::vector< MembershipFunctionPointer > MembershipFunctionPointerVector; //---------------------------------------------------------------------- //Set the image model estimator //---------------------------------------------------------------------- typedef itk::ImageKmeansModelEstimator<VecImageType, MembershipFunctionType> ImageKmeansModelEstimatorType; ImageKmeansModelEstimatorType::Pointer applyKmeansEstimator = ImageKmeansModelEstimatorType::New(); //---------------------------------------------------------------------- //Set the parameters of the clusterer //---------------------------------------------------------------------- applyKmeansEstimator->SetInputImage(vecImage); applyKmeansEstimator->SetNumberOfModels(NCODEWORDS); applyKmeansEstimator->SetThreshold(0.01 ); applyKmeansEstimator->SetOffsetAdd( 0.01 ); applyKmeansEstimator->SetOffsetMultiply( 0.01 ); applyKmeansEstimator->SetMaxSplitAttempts( 10 ); applyKmeansEstimator->Update(); applyKmeansEstimator->Print(std::cout); MembershipFunctionPointerVector membershipFunctions = applyKmeansEstimator->GetMembershipFunctions(); vnl_vector<double> kmeansResultForClass; vnl_vector<double> referenceCodebookForClass; vnl_vector<double> errorForClass; double error =0; double meanCDBKvalue = 0; for(unsigned int classIndex=0; classIndex < membershipFunctions.size(); classIndex++ ) { kmeansResultForClass = membershipFunctions[classIndex]->GetCentroid(); referenceCodebookForClass = inCDBK.get_row( classIndex); errorForClass = kmeansResultForClass - referenceCodebookForClass; for(int i = 0; i < NUMBANDS; i++) { error += vnl_math_abs(errorForClass[i]/referenceCodebookForClass[i]); meanCDBKvalue += referenceCodebookForClass[i]; } } error /= NCODEWORDS*NUMBANDS; meanCDBKvalue /= NCODEWORDS*NUMBANDS; if( error < 0.1 * meanCDBKvalue) std::cout << "Kmeans algorithm passed (without initial input)"<<std::endl; else std::cout << "Kmeans algorithm failed (without initial input)"<<std::endl; //Validation with no codebook/initial Kmeans estimate vnl_matrix<double> kmeansResult = applyKmeansEstimator->GetKmeansResults(); applyKmeansEstimator->SetCodebook(inCDBK); applyKmeansEstimator->Update(); applyKmeansEstimator->Print(std::cout); membershipFunctions = applyKmeansEstimator->GetMembershipFunctions(); //Testing for the various parameter access functions in the test std::cout << "The final codebook (cluster centers are: " << std::endl; std::cout << applyKmeansEstimator->GetCodebook() << std::endl; std::cout << "The threshold parameter used was: " << applyKmeansEstimator->GetThreshold() << std::endl; std::cout << "The additive ofset parameter used was: " << applyKmeansEstimator->GetOffsetAdd() << std::endl; std::cout << "The multiplicative ofset parameter used was: " << applyKmeansEstimator->GetOffsetMultiply() << std::endl; std::cout << "The maximum number of attempted splits in codebook: " << applyKmeansEstimator->GetMaxSplitAttempts() << std::endl; std::cout << " " << std::endl; //Validation with initial Kmeans estimate provided as input by the user error =0; meanCDBKvalue = 0; const unsigned int test = membershipFunctions.size(); for(unsigned int classIndex=0; classIndex < test; classIndex++ ) { kmeansResultForClass = membershipFunctions[classIndex]->GetCentroid(); referenceCodebookForClass = inCDBK.get_row( classIndex); errorForClass = kmeansResultForClass - referenceCodebookForClass; for(int i = 0; i < NUMBANDS; i++) { error += vnl_math_abs(errorForClass[i]/referenceCodebookForClass[i]); meanCDBKvalue += referenceCodebookForClass[i]; } } error /= NCODEWORDS*NUMBANDS; meanCDBKvalue /= NCODEWORDS*NUMBANDS; if( error < 0.1 * meanCDBKvalue) std::cout << "Kmeans algorithm passed (with initial input)"<<std::endl; else std::cout << "Kmeans algorithm failed (with initial input)"<<std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: ZipPackageStream.hxx,v $ * * $Revision: 1.17 $ * * last change: $Author: hr $ $Date: 2004-11-26 20:46:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_PACKAGE_STREAM_HXX #define _ZIP_PACKAGE_STREAM_HXX #ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_ #include <com/sun/star/io/XActiveDataSink.hpp> #endif #ifndef _COM_SUN_STAR_PACKAGES_XDATASINKENCRSUPPORT_HPP_ #include <com/sun/star/packages/XDataSinkEncrSupport.hpp> #endif #ifndef _ZIP_PACKAGE_ENTRY_HXX #include <ZipPackageEntry.hxx> #endif #ifndef _VOS_REF_H_ #include <vos/ref.hxx> #endif #ifndef _ENCRYPTION_DATA_HXX_ #include <EncryptionData.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX #include <cppuhelper/implbase2.hxx> #endif #ifndef __MUTEXHOLDER_HXX_ #include <mutexholder.hxx> #endif #define PACKAGE_STREAM_NOTSET 0 #define PACKAGE_STREAM_PACKAGEMEMBER 1 #define PACKAGE_STREAM_DETECT 2 #define PACKAGE_STREAM_DATA 3 #define PACKAGE_STREAM_RAW 4 class ZipPackage; struct ZipEntry; class ZipPackageStream : public cppu::ImplInheritanceHelper2 < ZipPackageEntry, ::com::sun::star::io::XActiveDataSink, ::com::sun::star::packages::XDataSinkEncrSupport > { static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId; protected: com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream; const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory; ZipPackage &rZipPackage; sal_Bool bToBeCompressed, bToBeEncrypted, bHaveOwnKey, bIsEncrypted; vos::ORef < EncryptionData > xEncryptionData; sal_uInt8 m_nStreamMode; sal_uInt32 m_nMagicalHackPos; sal_uInt32 m_nMagicalHackSize; SotMutexHolderRef m_aSharedMutexRef; public: sal_Bool HasOwnKey () { return bHaveOwnKey;} sal_Bool IsToBeCompressed () { return bToBeCompressed;} sal_Bool IsToBeEncrypted () { return bToBeEncrypted;} sal_Bool IsEncrypted () { return bIsEncrypted;} sal_Bool IsPackageMember () { return m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER;} vos::ORef < EncryptionData > & getEncryptionData () { return xEncryptionData;} const com::sun::star::uno::Sequence < sal_Int8 >& getKey () { return xEncryptionData->aKey;} const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector () { return xEncryptionData->aInitVector;} const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest () { return xEncryptionData->aDigest;} const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt () { return xEncryptionData->aSalt;} const sal_Int32 getIterationCount () { return xEncryptionData->nIterationCount;} const sal_Int32 getSize () { return aEntry.nSize;} sal_uInt8 GetStreamMode() { return m_nStreamMode; } sal_uInt32 GetMagicalHackPos() { return m_nMagicalHackPos; } sal_uInt32 GetMagicalHackSize() { return m_nMagicalHackSize; } void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;} void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;} void SetToBeEncrypted (sal_Bool bNewValue) { bToBeEncrypted = bNewValue; if ( bToBeEncrypted && xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() ) xEncryptionData.unbind(); } void SetPackageMember (sal_Bool bNewValue); void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey ) { xEncryptionData->aKey = rNewKey;} void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector ) { xEncryptionData->aInitVector = rNewVector;} void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt ) { xEncryptionData->aSalt = rNewSalt;} void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest ) { xEncryptionData->aDigest = rNewDigest;} void setIterationCount (const sal_Int32 nNewCount) { xEncryptionData->nIterationCount = nNewCount;} void setSize (const sal_Int32 nNewSize); ZipPackageStream ( ZipPackage & rNewPackage, const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory ); virtual ~ZipPackageStream( void ); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetRawEncrStreamNoHeaderCopy(); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > TryToGetRawFromDataStream( sal_Bool bAddHeaderForEncr ); sal_Bool ParsePackageRawStream(); void setZipEntry( const ZipEntry &rInEntry); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawData() throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId() { return aImplementationId; } // XActiveDataSink virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw(::com::sun::star::uno::RuntimeException); // XDataSinkEncrSupport virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getDataStream() throw ( ::com::sun::star::packages::WrongPasswordException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream() throw ( ::com::sun::star::packages::NoEncryptionException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDataStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setRawStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw ( ::com::sun::star::packages::EncryptionNotAllowedException, ::com::sun::star::packages::NoRawFormatException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getPlainRawStream() throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); // XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); }; #endif <commit_msg>INTEGRATION: CWS mav18 (1.17.28); FILE MERGED 2005/05/27 14:52:25 mav 1.17.28.1: #i49755# fix incoplete commit problem<commit_after>/************************************************************************* * * $RCSfile: ZipPackageStream.hxx,v $ * * $Revision: 1.18 $ * * last change: $Author: kz $ $Date: 2005-07-12 12:32:00 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): Martin Gallwey (gallwey@sun.com) * * ************************************************************************/ #ifndef _ZIP_PACKAGE_STREAM_HXX #define _ZIP_PACKAGE_STREAM_HXX #ifndef _COM_SUN_STAR_IO_XACTIVEDATASINK_HPP_ #include <com/sun/star/io/XActiveDataSink.hpp> #endif #ifndef _COM_SUN_STAR_PACKAGES_XDATASINKENCRSUPPORT_HPP_ #include <com/sun/star/packages/XDataSinkEncrSupport.hpp> #endif #ifndef _ZIP_PACKAGE_ENTRY_HXX #include <ZipPackageEntry.hxx> #endif #ifndef _VOS_REF_H_ #include <vos/ref.hxx> #endif #ifndef _ENCRYPTION_DATA_HXX_ #include <EncryptionData.hxx> #endif #ifndef _CPPUHELPER_IMPLBASE2_HXX #include <cppuhelper/implbase2.hxx> #endif #ifndef __MUTEXHOLDER_HXX_ #include <mutexholder.hxx> #endif #define PACKAGE_STREAM_NOTSET 0 #define PACKAGE_STREAM_PACKAGEMEMBER 1 #define PACKAGE_STREAM_DETECT 2 #define PACKAGE_STREAM_DATA 3 #define PACKAGE_STREAM_RAW 4 class ZipPackage; struct ZipEntry; class ZipPackageStream : public cppu::ImplInheritanceHelper2 < ZipPackageEntry, ::com::sun::star::io::XActiveDataSink, ::com::sun::star::packages::XDataSinkEncrSupport > { static com::sun::star::uno::Sequence < sal_Int8 > aImplementationId; protected: com::sun::star::uno::Reference < com::sun::star::io::XInputStream > xStream; const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory > m_xFactory; ZipPackage &rZipPackage; sal_Bool bToBeCompressed, bToBeEncrypted, bHaveOwnKey, bIsEncrypted; vos::ORef < EncryptionData > xEncryptionData; sal_uInt8 m_nStreamMode; sal_uInt32 m_nMagicalHackPos; sal_uInt32 m_nMagicalHackSize; SotMutexHolderRef m_aSharedMutexRef; public: sal_Bool HasOwnKey () { return bHaveOwnKey;} sal_Bool IsToBeCompressed () { return bToBeCompressed;} sal_Bool IsToBeEncrypted () { return bToBeEncrypted;} sal_Bool IsEncrypted () { return bIsEncrypted;} sal_Bool IsPackageMember () { return m_nStreamMode == PACKAGE_STREAM_PACKAGEMEMBER;} vos::ORef < EncryptionData > & getEncryptionData () { return xEncryptionData;} const com::sun::star::uno::Sequence < sal_Int8 >& getKey () { return xEncryptionData->aKey;} const com::sun::star::uno::Sequence < sal_uInt8 >& getInitialisationVector () { return xEncryptionData->aInitVector;} const com::sun::star::uno::Sequence < sal_uInt8 >& getDigest () { return xEncryptionData->aDigest;} const com::sun::star::uno::Sequence < sal_uInt8 >& getSalt () { return xEncryptionData->aSalt;} const sal_Int32 getIterationCount () { return xEncryptionData->nIterationCount;} const sal_Int32 getSize () { return aEntry.nSize;} sal_uInt8 GetStreamMode() { return m_nStreamMode; } sal_uInt32 GetMagicalHackPos() { return m_nMagicalHackPos; } sal_uInt32 GetMagicalHackSize() { return m_nMagicalHackSize; } void SetToBeCompressed (sal_Bool bNewValue) { bToBeCompressed = bNewValue;} void SetIsEncrypted (sal_Bool bNewValue) { bIsEncrypted = bNewValue;} void SetToBeEncrypted (sal_Bool bNewValue) { bToBeEncrypted = bNewValue; if ( bToBeEncrypted && xEncryptionData.isEmpty()) xEncryptionData = new EncryptionData; else if ( !bToBeEncrypted && !xEncryptionData.isEmpty() ) xEncryptionData.unbind(); } void SetPackageMember (sal_Bool bNewValue); void setKey (const com::sun::star::uno::Sequence < sal_Int8 >& rNewKey ) { xEncryptionData->aKey = rNewKey;} void setInitialisationVector (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewVector ) { xEncryptionData->aInitVector = rNewVector;} void setSalt (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewSalt ) { xEncryptionData->aSalt = rNewSalt;} void setDigest (const com::sun::star::uno::Sequence < sal_uInt8 >& rNewDigest ) { xEncryptionData->aDigest = rNewDigest;} void setIterationCount (const sal_Int32 nNewCount) { xEncryptionData->nIterationCount = nNewCount;} void setSize (const sal_Int32 nNewSize); ZipPackageStream ( ZipPackage & rNewPackage, const ::com::sun::star::uno::Reference < com::sun::star::lang::XMultiServiceFactory >& xFactory, sal_Bool bAllowRemoveOnInsert ); virtual ~ZipPackageStream( void ); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > GetRawEncrStreamNoHeaderCopy(); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > TryToGetRawFromDataStream( sal_Bool bAddHeaderForEncr ); sal_Bool ParsePackageRawStream(); void setZipEntry( const ZipEntry &rInEntry); ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawData() throw(::com::sun::star::uno::RuntimeException); static ::com::sun::star::uno::Sequence < sal_Int8 >& static_getImplementationId() { return aImplementationId; } // XActiveDataSink virtual void SAL_CALL setInputStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw(::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getInputStream( ) throw(::com::sun::star::uno::RuntimeException); // XDataSinkEncrSupport virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getDataStream() throw ( ::com::sun::star::packages::WrongPasswordException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getRawStream() throw ( ::com::sun::star::packages::NoEncryptionException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setDataStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setRawStream( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream >& aStream ) throw ( ::com::sun::star::packages::EncryptionNotAllowedException, ::com::sun::star::packages::NoRawFormatException, ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Reference< ::com::sun::star::io::XInputStream > SAL_CALL getPlainRawStream() throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException ); // XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); // XPropertySet virtual void SAL_CALL setPropertyValue( const ::rtl::OUString& aPropertyName, const ::com::sun::star::uno::Any& aValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Any SAL_CALL getPropertyValue( const ::rtl::OUString& PropertyName ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException, ::com::sun::star::uno::RuntimeException); // XServiceInfo virtual ::rtl::OUString SAL_CALL getImplementationName( ) throw (::com::sun::star::uno::RuntimeException); virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& ServiceName ) throw (::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::rtl::OUString > SAL_CALL getSupportedServiceNames( ) throw (::com::sun::star::uno::RuntimeException); }; #endif <|endoftext|>
<commit_before>//----------------------------------*-C++-*----------------------------------// /*! * \file solvers/test/tstAndersonSolver.cc * \author Steven Hamilton * \date Mon Apr 06 08:50:55 2015 * \brief Test interface to NOX Anderson acceleration solver * \note Copyright (C) 2015 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "gtest/utils_gtest.hh" #include "../AndersonSolver.hh" #include "spn/OperatorAdapter.hh" #include "spn/MatrixTraits.hh" #include "spn/VectorTraits.hh" #include "LinAlgTraits.hh" using profugus::AndersonSolver; //---------------------------------------------------------------------------// // Discretization of Chandrasekhar H-equation, cf. Kelley Eq. 5.22 //---------------------------------------------------------------------------// template <class T> class Chandrasekhar_H : public profugus::OperatorAdapter<T> { public: typedef typename T::MV MV; typedef typename T::MAP MAP; Chandrasekhar_H(double c, int N, Teuchos::RCP<const MAP> map) : profugus::OperatorAdapter<T>(map) , d_c(c) , d_N(N) { REQUIRE( d_c > 0.0 && d_c < 1.0 ); REQUIRE( d_N > 0 ); } private: void ApplyImpl(const MV &x, MV &y) const override { // Get all global values of x (all_gather) auto x_global = linalg_traits::get_global_copy<T>( Teuchos::rcpFromRef(x)); // mu is discretized evaluation points std::vector<double> mu(d_N,0.0); for( int i=0; i<d_N; ++i ) { mu[i] = (static_cast<double>(i+1)-0.5)/static_cast<double>(d_N); } // Evaluate H-equation std::vector<double> y_data(d_N,0.0); for( int i=0; i<d_N; ++i ) { // Integral over mu double rsum=0.0; for( int j=0; j<d_N; ++j ) { rsum += mu[i] * x_global[j] / (mu[i] + mu[j]); } y_data[i] = x_global[i] - 1.0 / (1.0 - (d_c/static_cast<double>(2*d_N)) * rsum); } linalg_traits::fill_vector<T>(Teuchos::rcpFromRef(y),y_data); } double d_c; int d_N; }; //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// template <class T> class AndersonSolverTest : public ::testing::Test { protected: typedef typename T::OP OP; typedef typename T::MV MV; typedef typename T::MAP MAP; // Initialization that are performed for each test void SetUp() { // Build operator d_c = 0.5; d_N = 50; d_num_local = d_N / profugus::nodes(); if( profugus::node() < (d_N % profugus::nodes()) ) d_num_local++; d_map = profugus::MatrixTraits<T>::build_map(d_num_local,d_N); d_op = Teuchos::rcp( new Chandrasekhar_H<T>(d_c,d_N,d_map) ); } double d_c; int d_N, d_num_local; Teuchos::RCP<const MAP> d_map; Teuchos::RCP<OP> d_op; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// using profugus::EpetraTypes; using profugus::TpetraTypes; typedef ::testing::Types<EpetraTypes,TpetraTypes> MyTypes; TYPED_TEST_CASE(AndersonSolverTest, MyTypes); TYPED_TEST(AndersonSolverTest, Heqn) { typedef typename TypeParam::MV MV; Teuchos::RCP<Teuchos::ParameterList> pl( new Teuchos::ParameterList() ); pl->set("tolerance",1e-6); pl->set("max_itr",50); Teuchos::RCP<Teuchos::ParameterList> anderson_pl = Teuchos::sublist(pl,"Anderson Parameters"); anderson_pl->set("Storage Depth",5); // Create and initialize vectors Teuchos::RCP<MV> x = linalg_traits::build_vector<TypeParam>(this->d_N); std::vector<double> x_data(this->d_N,0.0); linalg_traits::fill_vector<TypeParam>(x,x_data); // Build solver profugus::AndersonSolver<TypeParam> solver(this->d_op,pl); // Solve solver.solve(x); // Check solution std::vector<double> expected = {1.012429, 1.030067, 1.044180, 1.056382, 1.067269, 1.077160, 1.086252, 1.094680, 1.102543, 1.109917, 1.116860, 1.123420, 1.129635, 1.135540, 1.141162, 1.146525, 1.151651, 1.156556, 1.161258, 1.165771, 1.170108, 1.174280, 1.178298, 1.182171, 1.185907, 1.189515, 1.193002, 1.196374, 1.199638, 1.202798, 1.205861, 1.208831, 1.211712, 1.214509, 1.217225, 1.219865, 1.222432, 1.224928, 1.227357, 1.229722, 1.232025, 1.234269, 1.236456, 1.238589, 1.240669, 1.242699, 1.244680, 1.246614, 1.248504, 1.250349}; linalg_traits::test_vector<TypeParam>(x,expected); } //---------------------------------------------------------------------------// // end of tstAndersonSolver.cc //---------------------------------------------------------------------------// <commit_msg>Adding checking of residual in Anderson test.<commit_after>//----------------------------------*-C++-*----------------------------------// /*! * \file solvers/test/tstAndersonSolver.cc * \author Steven Hamilton * \date Mon Apr 06 08:50:55 2015 * \brief Test interface to NOX Anderson acceleration solver * \note Copyright (C) 2015 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "gtest/utils_gtest.hh" #include "../AndersonSolver.hh" #include "spn/OperatorAdapter.hh" #include "spn/MatrixTraits.hh" #include "spn/VectorTraits.hh" #include "LinAlgTraits.hh" #include "AnasaziMultiVecTraits.hpp" #include "AnasaziOperatorTraits.hpp" using profugus::AndersonSolver; //---------------------------------------------------------------------------// // Discretization of Chandrasekhar H-equation, cf. Kelley Eq. 5.22 //---------------------------------------------------------------------------// template <class T> class Chandrasekhar_H : public profugus::OperatorAdapter<T> { public: typedef typename T::MV MV; typedef typename T::MAP MAP; Chandrasekhar_H(double c, int N, Teuchos::RCP<const MAP> map) : profugus::OperatorAdapter<T>(map) , d_c(c) , d_N(N) { REQUIRE( d_c > 0.0 && d_c < 1.0 ); REQUIRE( d_N > 0 ); } private: void ApplyImpl(const MV &x, MV &y) const override { // Get all global values of x (all_gather) auto x_global = linalg_traits::get_global_copy<T>( Teuchos::rcpFromRef(x)); // mu is discretized evaluation points std::vector<double> mu(d_N,0.0); for( int i=0; i<d_N; ++i ) { mu[i] = (static_cast<double>(i+1)-0.5)/static_cast<double>(d_N); } // Evaluate H-equation std::vector<double> y_data(d_N,0.0); for( int i=0; i<d_N; ++i ) { // Integral over mu double rsum=0.0; for( int j=0; j<d_N; ++j ) { rsum += mu[i] * x_global[j] / (mu[i] + mu[j]); } y_data[i] = x_global[i] - 1.0 / (1.0 - (d_c/static_cast<double>(2*d_N)) * rsum); } linalg_traits::fill_vector<T>(Teuchos::rcpFromRef(y),y_data); } double d_c; int d_N; }; //---------------------------------------------------------------------------// // Test fixture //---------------------------------------------------------------------------// template <class T> class AndersonSolverTest : public ::testing::Test { protected: typedef typename T::OP OP; typedef typename T::MV MV; typedef typename T::MAP MAP; // Initialization that are performed for each test void SetUp() { // Build operator d_c = 0.5; d_N = 50; d_num_local = d_N / profugus::nodes(); if( profugus::node() < (d_N % profugus::nodes()) ) d_num_local++; d_map = profugus::MatrixTraits<T>::build_map(d_num_local,d_N); d_op = Teuchos::rcp( new Chandrasekhar_H<T>(d_c,d_N,d_map) ); } double d_c; int d_N, d_num_local; Teuchos::RCP<const MAP> d_map; Teuchos::RCP<OP> d_op; }; //---------------------------------------------------------------------------// // TESTS //---------------------------------------------------------------------------// using profugus::EpetraTypes; using profugus::TpetraTypes; typedef ::testing::Types<EpetraTypes,TpetraTypes> MyTypes; TYPED_TEST_CASE(AndersonSolverTest, MyTypes); TYPED_TEST(AndersonSolverTest, Heqn) { typedef typename TypeParam::ST ST; typedef typename TypeParam::MV MV; typedef typename TypeParam::OP OP; typedef Anasazi::MultiVecTraits<ST,MV> MVT; typedef Anasazi::OperatorTraits<ST,MV,OP> OPT; Teuchos::RCP<Teuchos::ParameterList> pl( new Teuchos::ParameterList() ); pl->set("tolerance",1e-6); pl->set("max_itr",50); Teuchos::RCP<Teuchos::ParameterList> anderson_pl = Teuchos::sublist(pl,"Anderson Parameters"); anderson_pl->set("Storage Depth",5); // Create and initialize vectors Teuchos::RCP<MV> x = linalg_traits::build_vector<TypeParam>(this->d_N); std::vector<double> x_data(this->d_N,0.0); linalg_traits::fill_vector<TypeParam>(x,x_data); // Compute initial function value Teuchos::RCP<MV> y = linalg_traits::build_vector<TypeParam>(this->d_N); OPT::Apply(*this->d_op,*x,*y); std::vector<double> tmp_norm(1); MVT::MvNorm(*y,tmp_norm); double norm_init = tmp_norm[0]; // Build solver profugus::AndersonSolver<TypeParam> solver(this->d_op,pl); // Solve solver.solve(x); // Check final function value against tolerance OPT::Apply(*this->d_op,*x,*y); MVT::MvNorm(*y,tmp_norm); double norm_final = tmp_norm[0]; EXPECT_TRUE( norm_final / norm_init < 1e-6 ); // Check solution std::vector<double> expected = {1.012429, 1.030067, 1.044180, 1.056382, 1.067269, 1.077160, 1.086252, 1.094680, 1.102543, 1.109917, 1.116860, 1.123420, 1.129635, 1.135540, 1.141162, 1.146525, 1.151651, 1.156556, 1.161258, 1.165771, 1.170108, 1.174280, 1.178298, 1.182171, 1.185907, 1.189515, 1.193002, 1.196374, 1.199638, 1.202798, 1.205861, 1.208831, 1.211712, 1.214509, 1.217225, 1.219865, 1.222432, 1.224928, 1.227357, 1.229722, 1.232025, 1.234269, 1.236456, 1.238589, 1.240669, 1.242699, 1.244680, 1.246614, 1.248504, 1.250349}; linalg_traits::test_vector<TypeParam>(x,expected); } //---------------------------------------------------------------------------// // end of tstAndersonSolver.cc //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FEMTruss.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEM.h" #include <iostream> using namespace itk::fem; using namespace std; /** * Easy access to the FEMObjectFactory. We create a new class * whose name is shorter and it's not templated... */ class FEMOF : public FEMObjectFactory<FEMLightObject> {}; /** * This example constructs a same problem as described in file truss.fem * by creating the appropriate classes. */ int main( int argc, char *argv[] ) { /** * First we create the FEM solver object. This object stores pointers * to all objects that define the FEM problem. One solver object * effectively defines one FEM problem. */ Solver S; /** * Below we'll define a FEM problem described in the chapter 25.3-4, * from the book, which can also be downloaded from * http://titan.colorado.edu/courses.d/IFEM.d/IFEM.Ch25.d/IFEM.Ch25.pdf */ /** * We start by creating four Node objects. One of them is of * class NodeXY. It has two displacements in two degrees of freedom. * 3 of them are of class NodeXYrotZ, which also includes the rotation * around Z axis. */ /** We'll need these pointers to create and initialize the objects. */ NodeXYrotZ::Pointer n1; NodeXY::Pointer n2; /** * We create the objects through the object factory to make everything * compatible when both smart and dumb pointers are used. Since we * want to cast the pointer to the NodeXYrotZ object, not the SmartPointer * class, we use both reference and de-reference operator (&*). This * has absolutely no effect on a compiled code when smart pointers are * not used. The resulting (dumb) pointer NodeXYrotZ* is then automatically * converted to SmartPointer if necessary and stored in n1. */ n1=static_cast<NodeXYrotZ*>( &*FEMOF::Create(NodeXYrotZ::OFID) ); /** * Additionally we could create the objects in the standard way... */ //n1=new NodeXYrotZ; /** * ... or using SmartPointers... */ //n1=NodeXYrotZ::New(); /** * Initialize the data members inside the node objects. Basically here * we only have to specify the X and Y coordinate of the node in global * coordinate system. */ n1->X=-4.0; n1->Y=3.0; /** * Convert the node pointer into a special pointer (FEMP) and add it to * the nodes array inside the solver class. The special pointer now * owns the object and we don't have to keep track of it anymore. * Here we again have to use both reference and de-reference operator (&*), * because we can't cast SmartPointer<NodeXYrotZ> to SmartPointer<Node>. * If smart pointers are not used, the operators have no effect on the * compiled code. */ S.node.push_back( FEMP<Node>(&*n1) ); /** * Special pointers (class FEMP) create a copy of the objects, * when a pointer object is copied. We can use that feature to quickly * create many similar objects without using the FEMObjectFactory, * New() function, or new operator. * * Operator[] on FEMPArray returns the special pointer (FEMP), while * the function operator () returns the actual pointer. */ S.node.push_back( S.node[0] ); S.node.push_back( S.node[0] ); /** * Now we have to update coordinates inside the newly created nodes. * Since we're getting back the pointers to base class, we need to * cast it to the proper class. dynamic_cast is used in this case. * Note that the Y coordinate of a node remains 3.0, so we don't have * to change it. */ dynamic_cast<NodeXYrotZ*>( &*S.node(1) )->X=0.0; dynamic_cast<NodeXYrotZ*>( &*S.node(2) )->X=4.0; /** * Note that we could also create new objects by always using the * FEMObjectFactory and not copying the objects inside arrays. * This is what we'll do for the final node. */ n2=static_cast<NodeXY*>( &*FEMOF::Create(NodeXY::OFID) ); n2->X=0.0; n2->Y=0.0; S.node.push_back( FEMP<Node>(&*n2) ); /** * Automatically assign the global numbers (IDs) to * all the objects in the array. (first object gets number 0, * second 1, and so on). We could have also specified the GN * member in all the created objects above, but this is easier. */ S.node.Renumber(); /** * Then we have to create the materials that will define * the elements. */ MaterialStandard::Pointer m; m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=0; /** Global number of the material */ m->E=30000.0; /** Young modulus */ m->A=0.02; /** Crossection area */ m->I=0.004; /** Momemt of inertia */ S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=1; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.001; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=2; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.003; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); /** * Next we create the finite elements that use the above * created nodes. We'll have 3 Bar elements ( a simple * spring in 2D space ) and 2 Beam elements that also * accounts for bending. */ Beam2D::Pointer e1; Bar2D::Pointer e2; e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); /** * Initialize the pointers to correct node objects. We use the * Find function of the FEMPArray to search for object (in this * case node) with given GN. Since the Beam2D element requires * nodes of class NodeXYrotZ, we have to make sure that we * have the right node object by using dynamic_cast. */ e1->GN=0; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(0) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); /** same for material */ e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** Create the other elements */ e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); e1->GN=1; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(2) ); e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** * Note that Bar2D requires nodes of class NodeXY. But since the * class NodeXYrotZ is derived from NodeXY, we can cast it * to NodeXY without loosing any information and seemlessly * connect these two elements together. Error checking is * guarantied by compiler either at compile time or by * dynamic_cast operator. */ e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=2; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(0) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=3; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(1) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(2) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=4; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(2) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); /** * Apply the boundary conditions and external forces (loads). */ /** * The first node is completely fixed i.e. both displacements * are fixed to 0. * * This is done by using the LoadBC class. */ LoadBC::Pointer l1; l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); /** * Here we're saying that the first degree of freedom at first node * is fixed to value m_value=0.0. See comments in class LoadBC declaration * for more information. Note that the m_value is a vector. This is useful * when having isotropic elements. This is not the case here, so we only * have a scalar. */ l1->m_element = &*S.el.Find(0); l1->m_dof = 0; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * In a same way we also fix the second DOF in a first node and the * second DOF in a third node (it's only fixed in Y direction). */ l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(0); l1->m_dof = 1; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(1); l1->m_dof = 4; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * Now we apply the external force on the fourth node. The force is specified * by a vector [20,-20] in global coordinate system. This is the second point * of the third element in a system. */ LoadNode::Pointer l2; l2=static_cast<LoadNode*>( &*FEMOF::Create(LoadNode::OFID) ); l2->m_element=S.el.Find(2); l2->m_pt=1; l2->F=vnl_vector<double>(2); l2->F[0]=20; l2->F[1]=-20; S.load.push_back( FEMP<Load>(&*l2) ); /** * The whole problem is now stored inside the Solver class. * Note that in the code above we don't use any of the * constructors that make creation of objects easier and with * less code. See declaration of classes for more info. */ /** * We can now solve for displacements. */ /** * Assign a unique id (global freedom number - GFN) * to every degree of freedom (DOF) in a system. */ S.GenerateGFN(); /** * Assemble the master stiffness matrix. In order to do this * the GFN's should already be assigned to every DOF. */ S.AssembleK(); /** * Invert the master stiffness matrix. */ S.DecomposeK(); /** * Assemble the master force vector (from the applied loads) */ S.AssembleF(); /** * Solve the system of equations for displacements (u=K^-1*F) */ S.Solve(); /** * Copy the displacemenets which are now stored inside * the solver class back to nodes, where they belong. */ S.UpdateDisplacements(); /** * Output displacements of all nodes in a system; */ std::cout<<"\nNodal displacements:\n"; for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++) { std::cout<<"Node#: "<<(*n)->GN<<": "; /** For each DOF in the node... */ for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { std::cout<<S.GetSolution(dof); std::cout<<", "; } std::cout<<"\b\b\b \b\n"; } cout<<"\n"; return 0; } <commit_msg>ENH: FEMTruss example now uses ITPACK numeric library.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: FEMTruss.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 2002 Insight Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ // disable debug warnings in MS compiler #ifdef _MSC_VER #pragma warning(disable: 4786) #endif #include "itkFEM.h" #include "itkFEMItpackLinearSystemWrapper.h" #include <iostream> using namespace itk::fem; using namespace std; /** * Easy access to the FEMObjectFactory. We create a new class * whose name is shorter and it's not templated... */ class FEMOF : public FEMObjectFactory<FEMLightObject> {}; /** * This example constructs a same problem as described in file truss.fem * by creating the appropriate classes. */ int main( int argc, char *argv[] ) { /** * First we create the FEM solver object. This object stores pointers * to all objects that define the FEM problem. One solver object * effectively defines one FEM problem. */ Solver S; /* * Set the linear system wrapper object that we wish to use. */ ItpackLinearSystemWrapper itpack; itpack.SetMaximumNonZeroValuesInMatrix(1000); S.SetLinearSystemWrapper(&itpack); /** * Below we'll define a FEM problem described in the chapter 25.3-4, * from the book, which can also be downloaded from * http://titan.colorado.edu/courses.d/IFEM.d/IFEM.Ch25.d/IFEM.Ch25.pdf */ /** * We start by creating four Node objects. One of them is of * class NodeXY. It has two displacements in two degrees of freedom. * 3 of them are of class NodeXYrotZ, which also includes the rotation * around Z axis. */ /** We'll need these pointers to create and initialize the objects. */ NodeXYrotZ::Pointer n1; NodeXY::Pointer n2; /** * We create the objects through the object factory to make everything * compatible when both smart and dumb pointers are used. Since we * want to cast the pointer to the NodeXYrotZ object, not the SmartPointer * class, we use both reference and de-reference operator (&*). This * has absolutely no effect on a compiled code when smart pointers are * not used. The resulting (dumb) pointer NodeXYrotZ* is then automatically * converted to SmartPointer if necessary and stored in n1. */ n1=static_cast<NodeXYrotZ*>( &*FEMOF::Create(NodeXYrotZ::OFID) ); /** * Additionally we could create the objects in the standard way... */ //n1=new NodeXYrotZ; /** * ... or using SmartPointers... */ //n1=NodeXYrotZ::New(); /** * Initialize the data members inside the node objects. Basically here * we only have to specify the X and Y coordinate of the node in global * coordinate system. */ n1->X=-4.0; n1->Y=3.0; /** * Convert the node pointer into a special pointer (FEMP) and add it to * the nodes array inside the solver class. The special pointer now * owns the object and we don't have to keep track of it anymore. * Here we again have to use both reference and de-reference operator (&*), * because we can't cast SmartPointer<NodeXYrotZ> to SmartPointer<Node>. * If smart pointers are not used, the operators have no effect on the * compiled code. */ S.node.push_back( FEMP<Node>(&*n1) ); /** * Special pointers (class FEMP) create a copy of the objects, * when a pointer object is copied. We can use that feature to quickly * create many similar objects without using the FEMObjectFactory, * New() function, or new operator. * * Operator[] on FEMPArray returns the special pointer (FEMP), while * the function operator () returns the actual pointer. */ S.node.push_back( S.node[0] ); S.node.push_back( S.node[0] ); /** * Now we have to update coordinates inside the newly created nodes. * Since we're getting back the pointers to base class, we need to * cast it to the proper class. dynamic_cast is used in this case. * Note that the Y coordinate of a node remains 3.0, so we don't have * to change it. */ dynamic_cast<NodeXYrotZ*>( &*S.node(1) )->X=0.0; dynamic_cast<NodeXYrotZ*>( &*S.node(2) )->X=4.0; /** * Note that we could also create new objects by always using the * FEMObjectFactory and not copying the objects inside arrays. * This is what we'll do for the final node. */ n2=static_cast<NodeXY*>( &*FEMOF::Create(NodeXY::OFID) ); n2->X=0.0; n2->Y=0.0; S.node.push_back( FEMP<Node>(&*n2) ); /** * Automatically assign the global numbers (IDs) to * all the objects in the array. (first object gets number 0, * second 1, and so on). We could have also specified the GN * member in all the created objects above, but this is easier. */ S.node.Renumber(); /** * Then we have to create the materials that will define * the elements. */ MaterialStandard::Pointer m; m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=0; /** Global number of the material */ m->E=30000.0; /** Young modulus */ m->A=0.02; /** Crossection area */ m->I=0.004; /** Momemt of inertia */ S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=1; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.001; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); m=static_cast<MaterialStandard*>( &*FEMOF::Create(MaterialStandard::OFID) ); m->GN=2; /** Global number of the material */ m->E=200000.0; /** Young modulus */ m->A=0.003; /** Crossection area */ /** * Momemt of inertia. This material will be used in * the Bar element, which doesn't need this constant. */ m->I=0.0; S.mat.push_back( FEMP<Material>(&*m) ); /** * Next we create the finite elements that use the above * created nodes. We'll have 3 Bar elements ( a simple * spring in 2D space ) and 2 Beam elements that also * accounts for bending. */ Beam2D::Pointer e1; Bar2D::Pointer e2; e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); /** * Initialize the pointers to correct node objects. We use the * Find function of the FEMPArray to search for object (in this * case node) with given GN. Since the Beam2D element requires * nodes of class NodeXYrotZ, we have to make sure that we * have the right node object by using dynamic_cast. */ e1->GN=0; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(0) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); /** same for material */ e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** Create the other elements */ e1=static_cast<Beam2D*>( &*FEMOF::Create(Beam2D::OFID) ); e1->GN=1; e1->m_node[0]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(1) ); e1->m_node[1]=dynamic_cast<NodeXYrotZ*>( &*S.node.Find(2) ); e1->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(0) ); S.el.push_back( FEMP<Element>(&*e1) ); /** * Note that Bar2D requires nodes of class NodeXY. But since the * class NodeXYrotZ is derived from NodeXY, we can cast it * to NodeXY without loosing any information and seemlessly * connect these two elements together. Error checking is * guarantied by compiler either at compile time or by * dynamic_cast operator. */ e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=2; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(0) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=3; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(1) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(2) ); S.el.push_back( FEMP<Element>(&*e2) ); e2=static_cast<Bar2D*>( &*FEMOF::Create(Bar2D::OFID) ); e2->GN=4; e2->m_node[0]=dynamic_cast<NodeXY*>( &*S.node.Find(2) ); e2->m_node[1]=dynamic_cast<NodeXY*>( &*S.node.Find(3) ); e2->m_mat=dynamic_cast<MaterialStandard*>( &*S.mat.Find(1) ); S.el.push_back( FEMP<Element>(&*e2) ); /** * Apply the boundary conditions and external forces (loads). */ /** * The first node is completely fixed i.e. both displacements * are fixed to 0. * * This is done by using the LoadBC class. */ LoadBC::Pointer l1; l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); /** * Here we're saying that the first degree of freedom at first node * is fixed to value m_value=0.0. See comments in class LoadBC declaration * for more information. Note that the m_value is a vector. This is useful * when having isotropic elements. This is not the case here, so we only * have a scalar. */ l1->m_element = &*S.el.Find(0); l1->m_dof = 0; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * In a same way we also fix the second DOF in a first node and the * second DOF in a third node (it's only fixed in Y direction). */ l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(0); l1->m_dof = 1; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); l1=static_cast<LoadBC*>( &*FEMOF::Create(LoadBC::OFID) ); l1->m_element = &*S.el.Find(1); l1->m_dof = 4; l1->m_value = vnl_vector<double>(1,0.0); S.load.push_back( FEMP<Load>(&*l1) ); /** * Now we apply the external force on the fourth node. The force is specified * by a vector [20,-20] in global coordinate system. This is the second point * of the third element in a system. */ LoadNode::Pointer l2; l2=static_cast<LoadNode*>( &*FEMOF::Create(LoadNode::OFID) ); l2->m_element=S.el.Find(2); l2->m_pt=1; l2->F=vnl_vector<double>(2); l2->F[0]=20; l2->F[1]=-20; S.load.push_back( FEMP<Load>(&*l2) ); /** * The whole problem is now stored inside the Solver class. * Note that in the code above we don't use any of the * constructors that make creation of objects easier and with * less code. See declaration of classes for more info. */ /** * We can now solve for displacements. */ /** * Assign a unique id (global freedom number - GFN) * to every degree of freedom (DOF) in a system. */ S.GenerateGFN(); /** * Assemble the master stiffness matrix. In order to do this * the GFN's should already be assigned to every DOF. */ S.AssembleK(); /** * Invert the master stiffness matrix. */ S.DecomposeK(); /** * Assemble the master force vector (from the applied loads) */ S.AssembleF(); /** * Solve the system of equations for displacements (u=K^-1*F) */ S.Solve(); /** * Copy the displacemenets which are now stored inside * the solver class back to nodes, where they belong. */ S.UpdateDisplacements(); /** * Output displacements of all nodes in a system; */ std::cout<<"\nNodal displacements:\n"; for( ::itk::fem::Solver::NodeArray::iterator n = S.node.begin(); n!=S.node.end(); n++) { std::cout<<"Node#: "<<(*n)->GN<<": "; /** For each DOF in the node... */ for( unsigned int d=0, dof; (dof=(*n)->GetDegreeOfFreedom(d))!=::itk::fem::Element::InvalidDegreeOfFreedomID; d++ ) { std::cout<<S.GetSolution(dof); std::cout<<", "; } std::cout<<"\b\b\b \b\n"; } cout<<"\n"; return 0; } <|endoftext|>
<commit_before>#include <random> #include <aikido/constraint/IkSampleableConstraint.hpp> #include <aikido/constraint/FiniteSampleConstraint.hpp> #include <aikido/constraint/FiniteCyclicSampleConstraint.hpp> #include <aikido/statespace/StateSpace.hpp> #include <aikido/constraint/TSR.hpp> #include <aikido/util/RNG.hpp> #include <gtest/gtest.h> #include <Eigen/Dense> using aikido::util::RNGWrapper; using aikido::util::RNG; using namespace aikido::constraint; using namespace aikido::statespace; using namespace dart::dynamics; class IkSampleableConstraintTest : public ::testing::Test { protected: void SetUp() override { mTsr.reset(new TSR); mRng.reset(new RNGWrapper<std::default_random_engine>()); // Manipulator with 2 revolute joints. mManipulator1 = Skeleton::create("Manipulator1"); // Root joint RevoluteJoint::Properties properties1; properties1.mAxis = Eigen::Vector3d::UnitY(); properties1.mName = "Joint1"; bn1 = mManipulator1->createJointAndBodyNodePair<RevoluteJoint>( nullptr, properties1, BodyNode::Properties(std::string("root_body"))).second; // joint 2, body 2 RevoluteJoint::Properties properties2; properties2.mAxis = Eigen::Vector3d::UnitY(); properties2.mName = "Joint2"; properties2.mT_ParentBodyToJoint.translation() = Eigen::Vector3d(0,0,1); bn2 = mManipulator1->createJointAndBodyNodePair<RevoluteJoint>( bn1, properties2, BodyNode::Properties(std::string("second_body"))).second; mInverseKinematics1 = InverseKinematics::create(bn2); mStateSpace1 = std::make_shared<MetaSkeletonStateSpace>(mManipulator1); // Manipulator with 1 free joint and 1 revolute joint. mManipulator2 = Skeleton::create("Manipulator2"); // Root joint FreeJoint::Properties properties3; properties3.mName = "Joint1"; bn3 = mManipulator2->createJointAndBodyNodePair<FreeJoint>( nullptr, properties3, BodyNode::Properties(std::string("root_body"))).second; // Joint 2, body 2 RevoluteJoint::Properties properties4; properties4.mAxis = Eigen::Vector3d::UnitY(); properties4.mName = "Joint2"; properties4.mT_ParentBodyToJoint.translation() = Eigen::Vector3d(0,0,1); bn4 = mManipulator2->createJointAndBodyNodePair<RevoluteJoint>( bn3, properties4, BodyNode::Properties(std::string("second_body"))).second; mInverseKinematics2 = InverseKinematics::create(bn4); mStateSpace2 = std::make_shared<MetaSkeletonStateSpace>(mManipulator2); } std::shared_ptr<TSR> mTsr; std::unique_ptr<RNG> mRng; SkeletonPtr mManipulator1; MetaSkeletonStateSpacePtr mStateSpace1; InverseKinematicsPtr mInverseKinematics1; BodyNodePtr bn1, bn2; SkeletonPtr mManipulator2; MetaSkeletonStateSpacePtr mStateSpace2; InverseKinematicsPtr mInverseKinematics2; BodyNodePtr bn3, bn4; }; TEST_F(IkSampleableConstraintTest, Constructor) { // Invalid statespace for seed constraint. Eigen::Vector2d v(1,0); RealVectorStateSpace rvss(2); auto seedStateInvalid = rvss.createState(); seedStateInvalid.setValue(v); std::shared_ptr<FiniteSampleConstraint> invalid_seed_constraint( new FiniteSampleConstraint( std::make_shared<RealVectorStateSpace>(rvss), seedStateInvalid)); EXPECT_THROW(IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, invalid_seed_constraint, mInverseKinematics1, mRng->clone(), 1), std::invalid_argument); // Construct valid seed_constraint. auto seedStateValid = mStateSpace1->createState(); std::shared_ptr<FiniteSampleConstraint> valid_seed_constraint( new FiniteSampleConstraint(mStateSpace1, seedStateValid)); IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, valid_seed_constraint, mInverseKinematics1, mRng->clone(), 1); } TEST_F(IkSampleableConstraintTest, SingleSampleGenerator) { // Set mTSR to be a pointTSR that generates // the only feasible solution for mInverseKinematics1. Eigen::Isometry3d T0_w(Eigen::Isometry3d::Identity()); T0_w.translation() = Eigen::Vector3d(0, 0, 1); mTsr->mT0_w = T0_w; // Set FiniteSampleConstraint to generate pose close to the actual solution. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0.1); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteSampleConstraint> seedConstraint( new FiniteSampleConstraint(mStateSpace1, seedState)); // Construct IkSampleableConstraint IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); // Get IkSampleGenerator auto generator = ikConstraint.createSampleGenerator(); ASSERT_TRUE(generator->canSample()); ASSERT_EQ(generator->getNumSamples(), 1); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator->sample(state)); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(0).getAngle(), 0, 1e-5); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(1).getAngle(), 0, 1e-5); // Cannot sample anymore. ASSERT_FALSE(generator->canSample()); } TEST_F(IkSampleableConstraintTest, CyclicSampleGenerator) { // Set mTSR to be a pointTSR that generates // the only feasible solution for mInverseKinematics1. Eigen::Isometry3d T0_w(Eigen::Isometry3d::Identity()); T0_w.translation() = Eigen::Vector3d(0, 0, 1); mTsr->mT0_w = T0_w; // Set FiniteCyclicSampleConstraint to generate // pose close to the actual solution. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0.1); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(mStateSpace1, seedState)); // Construct IkSampleableConstraint IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); // Get IkSampleGenerator auto generator = ikConstraint.createSampleGenerator(); for(int i = 1; i < 10; ++i) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(generator->getNumSamples(), SampleGenerator::NO_LIMIT); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator->sample(state)); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(0).getAngle(), 0, 1e-5); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(1).getAngle(), 0, 1e-5); } } TEST_F(IkSampleableConstraintTest, MultipleGeneratorsSampleSameSequence) { // TSR constraint will generate sequence of different points. Eigen::MatrixXd Bw = Eigen::Matrix<double, 6, 2>::Zero(); Bw(2, 0) = 1; Bw(2, 1) = 3; mTsr->mBw = Bw; // Set FiniteCyclicSampleConstraint to generate // pose close to the actual solution. auto seedState = mStateSpace2->getScopedStateFromMetaSkeleton(); Eigen::Isometry3d isometry(Eigen::Isometry3d::Identity()); isometry.translation() = Eigen::Vector3d(0.1, 0.1, 0.1); seedState.getSubStateHandle<SE3StateSpace>(0).setIsometry(isometry); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(mStateSpace2, seedState)); IkSampleableConstraint ikConstraint(mStateSpace2, mTsr, seedConstraint, mInverseKinematics2, mRng->clone(), 1); // Get 2 IkSampleGenerator auto generator1 = ikConstraint.createSampleGenerator(); auto generator2 = ikConstraint.createSampleGenerator(); // Test the two generators' samples for equality. for(int i = 0; i < 10; i++) { ASSERT_TRUE(generator1->canSample()); ASSERT_TRUE(generator2->canSample()); auto state1 = mStateSpace2->getScopedStateFromMetaSkeleton(); auto state2 = mStateSpace2->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator1->sample(state1)); ASSERT_TRUE(generator2->sample(state2)); EXPECT_TRUE(state1.getSubStateHandle<SE3StateSpace>(0).getIsometry().isApprox (state2.getSubStateHandle<SE3StateSpace>(0).getIsometry())); EXPECT_DOUBLE_EQ(state1.getSubStateHandle<SO2StateSpace>(1).getAngle(), state2.getSubStateHandle<SO2StateSpace>(1).getAngle()); } } TEST_F(IkSampleableConstraintTest, SampleGeneratorIkInfeasible) { // Tests that generator returns false when IK is infeasible. bn1->getParentJoint()->setPosition(0, M_PI/4); mTsr->mT0_w = bn2->getTransform(); /// Set first joint to be a fixed joint. bn1->getParentJoint()->setPositionLowerLimit(0, 0); bn1->getParentJoint()->setPositionUpperLimit(0, 0); // Set FiniteCyclicSampleConstraint. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(mStateSpace1, seedState)); IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); auto generator = ikConstraint.createSampleGenerator(); ASSERT_TRUE(generator->canSample()); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_FALSE(generator->sample(state)); } <commit_msg>Modified test_IkSampleableConstraint to match updated FiniteCyclicSampleConstraint and FiniteSampleConstraint API.<commit_after>#include <random> #include <aikido/constraint/IkSampleableConstraint.hpp> #include <aikido/constraint/FiniteSampleConstraint.hpp> #include <aikido/constraint/FiniteCyclicSampleConstraint.hpp> #include <aikido/statespace/StateSpace.hpp> #include <aikido/constraint/TSR.hpp> #include <aikido/util/RNG.hpp> #include <gtest/gtest.h> #include <Eigen/Dense> using aikido::util::RNGWrapper; using aikido::util::RNG; using namespace aikido::constraint; using namespace aikido::statespace; using namespace dart::dynamics; class IkSampleableConstraintTest : public ::testing::Test { protected: void SetUp() override { mTsr.reset(new TSR); mRng.reset(new RNGWrapper<std::default_random_engine>()); // Manipulator with 2 revolute joints. mManipulator1 = Skeleton::create("Manipulator1"); // Root joint RevoluteJoint::Properties properties1; properties1.mAxis = Eigen::Vector3d::UnitY(); properties1.mName = "Joint1"; bn1 = mManipulator1->createJointAndBodyNodePair<RevoluteJoint>( nullptr, properties1, BodyNode::Properties(std::string("root_body"))).second; // joint 2, body 2 RevoluteJoint::Properties properties2; properties2.mAxis = Eigen::Vector3d::UnitY(); properties2.mName = "Joint2"; properties2.mT_ParentBodyToJoint.translation() = Eigen::Vector3d(0,0,1); bn2 = mManipulator1->createJointAndBodyNodePair<RevoluteJoint>( bn1, properties2, BodyNode::Properties(std::string("second_body"))).second; mInverseKinematics1 = InverseKinematics::create(bn2); mStateSpace1 = std::make_shared<MetaSkeletonStateSpace>(mManipulator1); // Manipulator with 1 free joint and 1 revolute joint. mManipulator2 = Skeleton::create("Manipulator2"); // Root joint FreeJoint::Properties properties3; properties3.mName = "Joint1"; bn3 = mManipulator2->createJointAndBodyNodePair<FreeJoint>( nullptr, properties3, BodyNode::Properties(std::string("root_body"))).second; // Joint 2, body 2 RevoluteJoint::Properties properties4; properties4.mAxis = Eigen::Vector3d::UnitY(); properties4.mName = "Joint2"; properties4.mT_ParentBodyToJoint.translation() = Eigen::Vector3d(0,0,1); bn4 = mManipulator2->createJointAndBodyNodePair<RevoluteJoint>( bn3, properties4, BodyNode::Properties(std::string("second_body"))).second; mInverseKinematics2 = InverseKinematics::create(bn4); mStateSpace2 = std::make_shared<MetaSkeletonStateSpace>(mManipulator2); } std::shared_ptr<TSR> mTsr; std::unique_ptr<RNG> mRng; SkeletonPtr mManipulator1; MetaSkeletonStateSpacePtr mStateSpace1; InverseKinematicsPtr mInverseKinematics1; BodyNodePtr bn1, bn2; SkeletonPtr mManipulator2; MetaSkeletonStateSpacePtr mStateSpace2; InverseKinematicsPtr mInverseKinematics2; BodyNodePtr bn3, bn4; }; TEST_F(IkSampleableConstraintTest, Constructor) { // Invalid statespace for seed constraint. Eigen::Vector2d v(1,0); RealVectorStateSpace rvss(2); auto seedStateInvalid = rvss.createState(); seedStateInvalid.setValue(v); std::shared_ptr<FiniteSampleConstraint> invalid_seed_constraint( new FiniteSampleConstraint( std::make_shared<RealVectorStateSpace>(rvss), seedStateInvalid)); EXPECT_THROW(IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, invalid_seed_constraint, mInverseKinematics1, mRng->clone(), 1), std::invalid_argument); // Construct valid seed_constraint. auto seedStateValid = mStateSpace1->createState(); std::shared_ptr<FiniteSampleConstraint> valid_seed_constraint( new FiniteSampleConstraint(mStateSpace1, seedStateValid)); IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, valid_seed_constraint, mInverseKinematics1, mRng->clone(), 1); } TEST_F(IkSampleableConstraintTest, SingleSampleGenerator) { // Set mTSR to be a pointTSR that generates // the only feasible solution for mInverseKinematics1. Eigen::Isometry3d T0_w(Eigen::Isometry3d::Identity()); T0_w.translation() = Eigen::Vector3d(0, 0, 1); mTsr->mT0_w = T0_w; // Set FiniteSampleConstraint to generate pose close to the actual solution. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0.1); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteSampleConstraint> seedConstraint( new FiniteSampleConstraint(mStateSpace1, seedState)); // Construct IkSampleableConstraint IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); // Get IkSampleGenerator auto generator = ikConstraint.createSampleGenerator(); ASSERT_TRUE(generator->canSample()); ASSERT_EQ(generator->getNumSamples(), 1); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator->sample(state)); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(0).getAngle(), 0, 1e-5); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(1).getAngle(), 0, 1e-5); // Cannot sample anymore. ASSERT_FALSE(generator->canSample()); } TEST_F(IkSampleableConstraintTest, CyclicSampleGenerator) { // Set mTSR to be a pointTSR that generates // the only feasible solution for mInverseKinematics1. Eigen::Isometry3d T0_w(Eigen::Isometry3d::Identity()); T0_w.translation() = Eigen::Vector3d(0, 0, 1); mTsr->mT0_w = T0_w; // Set FiniteCyclicSampleConstraint to generate // pose close to the actual solution. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0.1); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteSampleConstraint> finiteSampleConstraint = std::make_shared<FiniteSampleConstraint>(mStateSpace1, seedState); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(finiteSampleConstraint)); // Construct IkSampleableConstraint IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); // Get IkSampleGenerator auto generator = ikConstraint.createSampleGenerator(); for(int i = 1; i < 10; ++i) { ASSERT_TRUE(generator->canSample()); ASSERT_EQ(generator->getNumSamples(), SampleGenerator::NO_LIMIT); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator->sample(state)); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(0).getAngle(), 0, 1e-5); ASSERT_NEAR(state.getSubStateHandle<SO2StateSpace>(1).getAngle(), 0, 1e-5); } } TEST_F(IkSampleableConstraintTest, MultipleGeneratorsSampleSameSequence) { // TSR constraint will generate sequence of different points. Eigen::MatrixXd Bw = Eigen::Matrix<double, 6, 2>::Zero(); Bw(2, 0) = 1; Bw(2, 1) = 3; mTsr->mBw = Bw; // Set FiniteCyclicSampleConstraint to generate // pose close to the actual solution. auto seedState = mStateSpace2->getScopedStateFromMetaSkeleton(); Eigen::Isometry3d isometry(Eigen::Isometry3d::Identity()); isometry.translation() = Eigen::Vector3d(0.1, 0.1, 0.1); seedState.getSubStateHandle<SE3StateSpace>(0).setIsometry(isometry); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteSampleConstraint> finiteSampleConstraint = std::make_shared<FiniteSampleConstraint>(mStateSpace2, seedState); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(finiteSampleConstraint)); IkSampleableConstraint ikConstraint(mStateSpace2, mTsr, seedConstraint, mInverseKinematics2, mRng->clone(), 1); // Get 2 IkSampleGenerator auto generator1 = ikConstraint.createSampleGenerator(); auto generator2 = ikConstraint.createSampleGenerator(); // Test the two generators' samples for equality. for(int i = 0; i < 10; i++) { ASSERT_TRUE(generator1->canSample()); ASSERT_TRUE(generator2->canSample()); auto state1 = mStateSpace2->getScopedStateFromMetaSkeleton(); auto state2 = mStateSpace2->getScopedStateFromMetaSkeleton(); ASSERT_TRUE(generator1->sample(state1)); ASSERT_TRUE(generator2->sample(state2)); EXPECT_TRUE(state1.getSubStateHandle<SE3StateSpace>(0).getIsometry().isApprox (state2.getSubStateHandle<SE3StateSpace>(0).getIsometry())); EXPECT_DOUBLE_EQ(state1.getSubStateHandle<SO2StateSpace>(1).getAngle(), state2.getSubStateHandle<SO2StateSpace>(1).getAngle()); } } TEST_F(IkSampleableConstraintTest, SampleGeneratorIkInfeasible) { // Tests that generator returns false when IK is infeasible. bn1->getParentJoint()->setPosition(0, M_PI/4); mTsr->mT0_w = bn2->getTransform(); /// Set first joint to be a fixed joint. bn1->getParentJoint()->setPositionLowerLimit(0, 0); bn1->getParentJoint()->setPositionUpperLimit(0, 0); // Set FiniteCyclicSampleConstraint. auto seedState = mStateSpace1->getScopedStateFromMetaSkeleton(); seedState.getSubStateHandle<SO2StateSpace>(0).setAngle(0); seedState.getSubStateHandle<SO2StateSpace>(1).setAngle(0.1); std::shared_ptr<FiniteSampleConstraint> finiteSampleConstraint = std::make_shared<FiniteSampleConstraint>(mStateSpace1, seedState); std::shared_ptr<FiniteCyclicSampleConstraint> seedConstraint( new FiniteCyclicSampleConstraint(finiteSampleConstraint)); IkSampleableConstraint ikConstraint(mStateSpace1, mTsr, seedConstraint, mInverseKinematics1, mRng->clone(), 1); auto generator = ikConstraint.createSampleGenerator(); ASSERT_TRUE(generator->canSample()); auto state = mStateSpace1->getScopedStateFromMetaSkeleton(); ASSERT_FALSE(generator->sample(state)); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/views/domui_menu_widget.h" #include "chrome/browser/chromeos/views/menu_locator.h" #include "chrome/browser/chromeos/views/native_menu_domui.h" #include "chrome/browser/chromeos/wm_ipc.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/dom_view.h" #include "cros/chromeos_wm_ipc_enums.h" #include "gfx/canvas_skia.h" #include "googleurl/src/gurl.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "views/border.h" #include "views/layout_manager.h" #include "views/widget/root_view.h" namespace { // Colors for menu's graident background. const SkColor kMenuStartColor = SK_ColorWHITE; const SkColor kMenuEndColor = 0xFFEEEEEE; // Rounded border for menu. This draws three types of rounded border, // for context menu, dropdown menu and submenu. Please see // menu_locator.cc for details. class RoundedBorder : public views::Border { public: explicit RoundedBorder(chromeos::MenuLocator* locator) : menu_locator_(locator) { } private: // views::Border implementatios. virtual void Paint(const views::View& view, gfx::Canvas* canvas) const { const SkScalar* corners = menu_locator_->GetCorners(); // The menu is in off screen so no need to draw corners. if (!corners) return; int w = view.width(); int h = view.height(); SkRect rect = {0, 0, w, h}; SkPath path; path.addRoundRect(rect, corners); SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setFlags(SkPaint::kAntiAlias_Flag); SkPoint p[2] = { {0, 0}, {0, h} }; SkColor colors[2] = {kMenuStartColor, kMenuEndColor}; SkShader* s = SkGradientShader::CreateLinear( p, colors, NULL, 2, SkShader::kClamp_TileMode, NULL); paint.setShader(s); // Need to unref shader, otherwise never deleted. s->unref(); canvas->AsCanvasSkia()->drawPath(path, paint); } virtual void GetInsets(gfx::Insets* insets) const { DCHECK(insets); menu_locator_->GetInsets(insets); } chromeos::MenuLocator* menu_locator_; // not owned DISALLOW_COPY_AND_ASSIGN(RoundedBorder); }; class InsetsLayout : public views::LayoutManager { public: InsetsLayout() : views::LayoutManager() {} private: // views::LayoutManager implementatios. virtual void Layout(views::View* host) { if (host->GetChildViewCount() == 0) return; gfx::Insets insets = host->GetInsets(); views::View* view = host->GetChildViewAt(0); view->SetBounds(insets.left(), insets.top(), host->width() - insets.width(), host->height() - insets.height()); } virtual gfx::Size GetPreferredSize(views::View* host) { DCHECK(host->GetChildViewCount() == 1); gfx::Insets insets = host->GetInsets(); gfx::Size size = host->GetChildViewAt(0)->GetPreferredSize(); return gfx::Size(size.width() + insets.width(), size.height() + insets.height()); } DISALLOW_COPY_AND_ASSIGN(InsetsLayout); }; // A gtk widget key used to test if a given WidgetGtk instance is // DOMUIMenuWidgetKey. const char* kDOMUIMenuWidgetKey = "__DOMUI_MENU_WIDGET__"; } // namespace namespace chromeos { // static DOMUIMenuWidget* DOMUIMenuWidget::FindDOMUIMenuWidget(gfx::NativeView native) { DCHECK(native); native = gtk_widget_get_toplevel(native); if (!native) return NULL; return static_cast<chromeos::DOMUIMenuWidget*>( g_object_get_data(G_OBJECT(native), kDOMUIMenuWidgetKey)); } /////////////////////////////////////////////////////////////////////////////// // DOMUIMenuWidget public: DOMUIMenuWidget::DOMUIMenuWidget(chromeos::NativeMenuDOMUI* domui_menu, bool root) : views::WidgetGtk(views::WidgetGtk::TYPE_POPUP), domui_menu_(domui_menu), dom_view_(NULL), did_pointer_grab_(false), is_root_(root) { DCHECK(domui_menu_); MakeTransparent(); } DOMUIMenuWidget::~DOMUIMenuWidget() { } void DOMUIMenuWidget::Init(gfx::NativeView parent, const gfx::Rect& bounds) { WidgetGtk::Init(parent, bounds); gtk_window_set_destroy_with_parent(GTK_WINDOW(GetNativeView()), TRUE); gtk_window_set_type_hint(GTK_WINDOW(GetNativeView()), GDK_WINDOW_TYPE_HINT_MENU); g_object_set_data(G_OBJECT(GetNativeView()), kDOMUIMenuWidgetKey, this); } void DOMUIMenuWidget::Hide() { ReleaseGrab(); WidgetGtk::Hide(); } void DOMUIMenuWidget::Close() { // Detach the domui_menu_ which is being deleted. domui_menu_ = NULL; views::WidgetGtk::Close(); } void DOMUIMenuWidget::ReleaseGrab() { WidgetGtk::ReleaseGrab(); if (did_pointer_grab_) { did_pointer_grab_ = false; gdk_pointer_ungrab(GDK_CURRENT_TIME); ClearGrabWidget(); } } gboolean DOMUIMenuWidget::OnGrabBrokeEvent(GtkWidget* widget, GdkEvent* event) { did_pointer_grab_ = false; Hide(); return WidgetGtk::OnGrabBrokeEvent(widget, event); } void DOMUIMenuWidget::OnSizeAllocate(GtkWidget* widget, GtkAllocation* allocation) { views::WidgetGtk::OnSizeAllocate(widget, allocation); // Adjust location when menu gets resized. gfx::Rect bounds; GetBounds(&bounds, false); // Don't move until the menu gets contents. if (bounds.height() >= 2) menu_locator_->Move(this); } gboolean MapToFocus(GtkWidget* widget, GdkEvent* event, gpointer data) { DOMUIMenuWidget* menu_widget = DOMUIMenuWidget::FindDOMUIMenuWidget(widget); if (menu_widget) menu_widget->EnableInput(false); return true; } void DOMUIMenuWidget::EnableInput(bool select_item) { DCHECK(dom_view_); DCHECK(dom_view_->tab_contents()->render_view_host()); DCHECK(dom_view_->tab_contents()->render_view_host()->view()); GtkWidget* target = dom_view_->tab_contents()->render_view_host()->view()->GetNativeView(); DCHECK(target); // Skip if the widget already own the input. if (gtk_grab_get_current() == target) return; ClearGrabWidget(); if (!GTK_WIDGET_REALIZED(target)) { // Try again if the widget is not yet realized. // This happens only for root which tries to open & grab input. DCHECK(is_root_); DCHECK(!select_item); g_signal_connect(G_OBJECT(target), "map-event", G_CALLBACK(&MapToFocus), NULL); return; } gtk_grab_add(target); dom_view_->tab_contents()->Focus(); if (select_item) { ExecuteJavascript(L"selectItem()"); } } void DOMUIMenuWidget::ExecuteJavascript(const std::wstring& script) { // Don't exeute there is no DOMView associated. This is fine because // 1) selectItem make sense only when DOMView is associated. // 2) updateModel will be called again when a DOMView is created/assigned. if (dom_view_ == NULL) return; DCHECK(dom_view_->tab_contents()->render_view_host()); dom_view_->tab_contents()->render_view_host()-> ExecuteJavascriptInWebFrame(std::wstring(), script); } void DOMUIMenuWidget::ShowAt(chromeos::MenuLocator* locator) { DCHECK(domui_menu_); menu_locator_.reset(locator); if (!dom_view_) { dom_view_ = new DOMView(); dom_view_->Init(domui_menu_->GetProfile(), NULL); // TODO(oshima): remove extra view to draw rounded corner. views::View* container = new views::View(); container->AddChildView(dom_view_); container->set_border(new RoundedBorder(locator)); container->SetLayoutManager(new InsetsLayout()); SetContentsView(container); dom_view_->LoadURL(GURL("chrome://menu")); } else { domui_menu_->UpdateStates(); dom_view_->GetParent()->set_border(new RoundedBorder(locator)); menu_locator_->Move(this); } Show(); // The pointer grab is captured only on the top level menu, // all mouse event events are delivered to submenu using gtk_add_grab. if (is_root_) { CaptureGrab(); } } void DOMUIMenuWidget::SetSize(const gfx::Size& new_size) { DCHECK(domui_menu_); // Ignore the empty new_size request which is called when // menu.html is loaded. if (new_size.IsEmpty()) return; menu_locator_->SetBounds(this, new_size); } /////////////////////////////////////////////////////////////////////////////// // DOMUIMenuWidget private: void DOMUIMenuWidget::CaptureGrab() { // Release the current grab. ClearGrabWidget(); // NOTE: we do this to ensure we get mouse events from other apps, a grab // done with gtk_grab_add doesn't get events from other apps. GdkGrabStatus grab_status = gdk_pointer_grab(window_contents()->window, FALSE, static_cast<GdkEventMask>( GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK), NULL, NULL, GDK_CURRENT_TIME); did_pointer_grab_ = (grab_status == GDK_GRAB_SUCCESS); DCHECK(did_pointer_grab_); EnableInput(false /* no selection */); } void DOMUIMenuWidget::ClearGrabWidget() { GtkWidget* grab_widget; while ((grab_widget = gtk_grab_get_current())) gtk_grab_remove(grab_widget); } } // namespace chromeos <commit_msg>Fix assertion failure which happens when opening submenu using keyboard navigation quickly.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/views/domui_menu_widget.h" #include "chrome/browser/chromeos/views/menu_locator.h" #include "chrome/browser/chromeos/views/native_menu_domui.h" #include "chrome/browser/chromeos/wm_ipc.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/renderer_host/render_widget_host_view.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/views/dom_view.h" #include "cros/chromeos_wm_ipc_enums.h" #include "gfx/canvas_skia.h" #include "googleurl/src/gurl.h" #include "third_party/skia/include/effects/SkGradientShader.h" #include "views/border.h" #include "views/layout_manager.h" #include "views/widget/root_view.h" namespace { // Colors for menu's graident background. const SkColor kMenuStartColor = SK_ColorWHITE; const SkColor kMenuEndColor = 0xFFEEEEEE; // Rounded border for menu. This draws three types of rounded border, // for context menu, dropdown menu and submenu. Please see // menu_locator.cc for details. class RoundedBorder : public views::Border { public: explicit RoundedBorder(chromeos::MenuLocator* locator) : menu_locator_(locator) { } private: // views::Border implementatios. virtual void Paint(const views::View& view, gfx::Canvas* canvas) const { const SkScalar* corners = menu_locator_->GetCorners(); // The menu is in off screen so no need to draw corners. if (!corners) return; int w = view.width(); int h = view.height(); SkRect rect = {0, 0, w, h}; SkPath path; path.addRoundRect(rect, corners); SkPaint paint; paint.setStyle(SkPaint::kFill_Style); paint.setFlags(SkPaint::kAntiAlias_Flag); SkPoint p[2] = { {0, 0}, {0, h} }; SkColor colors[2] = {kMenuStartColor, kMenuEndColor}; SkShader* s = SkGradientShader::CreateLinear( p, colors, NULL, 2, SkShader::kClamp_TileMode, NULL); paint.setShader(s); // Need to unref shader, otherwise never deleted. s->unref(); canvas->AsCanvasSkia()->drawPath(path, paint); } virtual void GetInsets(gfx::Insets* insets) const { DCHECK(insets); menu_locator_->GetInsets(insets); } chromeos::MenuLocator* menu_locator_; // not owned DISALLOW_COPY_AND_ASSIGN(RoundedBorder); }; class InsetsLayout : public views::LayoutManager { public: InsetsLayout() : views::LayoutManager() {} private: // views::LayoutManager implementatios. virtual void Layout(views::View* host) { if (host->GetChildViewCount() == 0) return; gfx::Insets insets = host->GetInsets(); views::View* view = host->GetChildViewAt(0); view->SetBounds(insets.left(), insets.top(), host->width() - insets.width(), host->height() - insets.height()); } virtual gfx::Size GetPreferredSize(views::View* host) { DCHECK(host->GetChildViewCount() == 1); gfx::Insets insets = host->GetInsets(); gfx::Size size = host->GetChildViewAt(0)->GetPreferredSize(); return gfx::Size(size.width() + insets.width(), size.height() + insets.height()); } DISALLOW_COPY_AND_ASSIGN(InsetsLayout); }; // A gtk widget key used to test if a given WidgetGtk instance is // DOMUIMenuWidgetKey. const char* kDOMUIMenuWidgetKey = "__DOMUI_MENU_WIDGET__"; } // namespace namespace chromeos { // static DOMUIMenuWidget* DOMUIMenuWidget::FindDOMUIMenuWidget(gfx::NativeView native) { DCHECK(native); native = gtk_widget_get_toplevel(native); if (!native) return NULL; return static_cast<chromeos::DOMUIMenuWidget*>( g_object_get_data(G_OBJECT(native), kDOMUIMenuWidgetKey)); } /////////////////////////////////////////////////////////////////////////////// // DOMUIMenuWidget public: DOMUIMenuWidget::DOMUIMenuWidget(chromeos::NativeMenuDOMUI* domui_menu, bool root) : views::WidgetGtk(views::WidgetGtk::TYPE_POPUP), domui_menu_(domui_menu), dom_view_(NULL), did_pointer_grab_(false), is_root_(root) { DCHECK(domui_menu_); MakeTransparent(); } DOMUIMenuWidget::~DOMUIMenuWidget() { } void DOMUIMenuWidget::Init(gfx::NativeView parent, const gfx::Rect& bounds) { WidgetGtk::Init(parent, bounds); gtk_window_set_destroy_with_parent(GTK_WINDOW(GetNativeView()), TRUE); gtk_window_set_type_hint(GTK_WINDOW(GetNativeView()), GDK_WINDOW_TYPE_HINT_MENU); g_object_set_data(G_OBJECT(GetNativeView()), kDOMUIMenuWidgetKey, this); } void DOMUIMenuWidget::Hide() { ReleaseGrab(); WidgetGtk::Hide(); } void DOMUIMenuWidget::Close() { // Detach the domui_menu_ which is being deleted. domui_menu_ = NULL; views::WidgetGtk::Close(); } void DOMUIMenuWidget::ReleaseGrab() { WidgetGtk::ReleaseGrab(); if (did_pointer_grab_) { did_pointer_grab_ = false; gdk_pointer_ungrab(GDK_CURRENT_TIME); ClearGrabWidget(); } } gboolean DOMUIMenuWidget::OnGrabBrokeEvent(GtkWidget* widget, GdkEvent* event) { did_pointer_grab_ = false; Hide(); return WidgetGtk::OnGrabBrokeEvent(widget, event); } void DOMUIMenuWidget::OnSizeAllocate(GtkWidget* widget, GtkAllocation* allocation) { views::WidgetGtk::OnSizeAllocate(widget, allocation); // Adjust location when menu gets resized. gfx::Rect bounds; GetBounds(&bounds, false); // Don't move until the menu gets contents. if (bounds.height() >= 2) menu_locator_->Move(this); } gboolean MapToFocus(GtkWidget* widget, GdkEvent* event, gpointer data) { DOMUIMenuWidget* menu_widget = DOMUIMenuWidget::FindDOMUIMenuWidget(widget); if (menu_widget) { // See EnableInput for the meaning of data. bool select_item = data != NULL; menu_widget->EnableInput(select_item); } return true; } void DOMUIMenuWidget::EnableInput(bool select_item) { DCHECK(dom_view_); DCHECK(dom_view_->tab_contents()->render_view_host()); DCHECK(dom_view_->tab_contents()->render_view_host()->view()); GtkWidget* target = dom_view_->tab_contents()->render_view_host()->view()->GetNativeView(); DCHECK(target); // Skip if the widget already own the input. if (gtk_grab_get_current() == target) return; ClearGrabWidget(); if (!GTK_WIDGET_REALIZED(target)) { // Wait grabbing widget if the widget is not yet realized. // Using data as a flag. |select_item| is false if data is NULL, // or true otherwise. g_signal_connect(G_OBJECT(target), "map-event", G_CALLBACK(&MapToFocus), select_item ? this : NULL); return; } gtk_grab_add(target); dom_view_->tab_contents()->Focus(); if (select_item) { ExecuteJavascript(L"selectItem()"); } } void DOMUIMenuWidget::ExecuteJavascript(const std::wstring& script) { // Don't exeute there is no DOMView associated. This is fine because // 1) selectItem make sense only when DOMView is associated. // 2) updateModel will be called again when a DOMView is created/assigned. if (dom_view_ == NULL) return; DCHECK(dom_view_->tab_contents()->render_view_host()); dom_view_->tab_contents()->render_view_host()-> ExecuteJavascriptInWebFrame(std::wstring(), script); } void DOMUIMenuWidget::ShowAt(chromeos::MenuLocator* locator) { DCHECK(domui_menu_); menu_locator_.reset(locator); if (!dom_view_) { dom_view_ = new DOMView(); dom_view_->Init(domui_menu_->GetProfile(), NULL); // TODO(oshima): remove extra view to draw rounded corner. views::View* container = new views::View(); container->AddChildView(dom_view_); container->set_border(new RoundedBorder(locator)); container->SetLayoutManager(new InsetsLayout()); SetContentsView(container); dom_view_->LoadURL(GURL("chrome://menu")); } else { domui_menu_->UpdateStates(); dom_view_->GetParent()->set_border(new RoundedBorder(locator)); menu_locator_->Move(this); } Show(); // The pointer grab is captured only on the top level menu, // all mouse event events are delivered to submenu using gtk_add_grab. if (is_root_) { CaptureGrab(); } } void DOMUIMenuWidget::SetSize(const gfx::Size& new_size) { DCHECK(domui_menu_); // Ignore the empty new_size request which is called when // menu.html is loaded. if (new_size.IsEmpty()) return; menu_locator_->SetBounds(this, new_size); } /////////////////////////////////////////////////////////////////////////////// // DOMUIMenuWidget private: void DOMUIMenuWidget::CaptureGrab() { // Release the current grab. ClearGrabWidget(); // NOTE: we do this to ensure we get mouse events from other apps, a grab // done with gtk_grab_add doesn't get events from other apps. GdkGrabStatus grab_status = gdk_pointer_grab(window_contents()->window, FALSE, static_cast<GdkEventMask>( GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK), NULL, NULL, GDK_CURRENT_TIME); did_pointer_grab_ = (grab_status == GDK_GRAB_SUCCESS); DCHECK(did_pointer_grab_); EnableInput(false /* no selection */); } void DOMUIMenuWidget::ClearGrabWidget() { GtkWidget* grab_widget; while ((grab_widget = gtk_grab_get_current())) gtk_grab_remove(grab_widget); } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/bookmark_menu_controller_gtk.h" #include <gtk/gtk.h> #include "app/gtk_dnd_util.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/gtk/bookmark_utils_gtk.h" #include "chrome/browser/gtk/gtk_chrome_button.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/gtk/menu_gtk.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/page_navigator.h" #include "gfx/gtk_util.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "webkit/glue/window_open_disposition.h" namespace { // TODO(estade): It might be a good idea to vary this by locale. const int kMaxChars = 50; void SetImageMenuItem(GtkWidget* menu_item, const BookmarkNode* node, BookmarkModel* model) { GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model, true); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); } const BookmarkNode* GetNodeFromMenuItem(GtkWidget* menu_item) { return static_cast<const BookmarkNode*>( g_object_get_data(G_OBJECT(menu_item), "bookmark-node")); } const BookmarkNode* GetParentNodeFromEmptyMenu(GtkWidget* menu) { return static_cast<const BookmarkNode*>( g_object_get_data(G_OBJECT(menu), "parent-node")); } void* AsVoid(const BookmarkNode* node) { return const_cast<BookmarkNode*>(node); } // The context menu has been dismissed, restore the X and application grabs // to whichever menu last had them. (Assuming that menu is still showing.) // The event mask in this function is taken from gtkmenu.c. void OnContextMenuHide(GtkWidget* context_menu, GtkWidget* grab_menu) { gtk_util::GrabAllInput(grab_menu); // Match the ref we took when connecting this signal. g_object_unref(grab_menu); } } // namespace BookmarkMenuController::BookmarkMenuController(Browser* browser, Profile* profile, PageNavigator* navigator, GtkWindow* window, const BookmarkNode* node, int start_child_index) : browser_(browser), profile_(profile), page_navigator_(navigator), parent_window_(window), model_(profile->GetBookmarkModel()), node_(node), drag_icon_(NULL), ignore_button_release_(false), triggering_widget_(NULL) { menu_ = gtk_menu_new(); BuildMenu(node, start_child_index, menu_); g_signal_connect(menu_, "hide", G_CALLBACK(OnMenuHiddenThunk), this); gtk_widget_show_all(menu_); } BookmarkMenuController::~BookmarkMenuController() { profile_->GetBookmarkModel()->RemoveObserver(this); gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { profile_->GetBookmarkModel()->AddObserver(this); triggering_widget_ = widget; gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(widget), GTK_STATE_ACTIVE); gtk_menu_popup(GTK_MENU(menu_), NULL, NULL, &MenuGtk::WidgetMenuPositionFunc, widget, button_type, timestamp); } void BookmarkMenuController::BookmarkModelChanged() { gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::BookmarkNodeFavIconLoaded( BookmarkModel* model, const BookmarkNode* node) { std::map<const BookmarkNode*, GtkWidget*>::iterator it = node_to_menu_widget_map_.find(node); if (it != node_to_menu_widget_map_.end()) SetImageMenuItem(it->second, node, model); } void BookmarkMenuController::WillExecuteCommand() { gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::CloseMenu() { context_menu_->Cancel(); } void BookmarkMenuController::NavigateToMenuItem( GtkWidget* menu_item, WindowOpenDisposition disposition) { const BookmarkNode* node = GetNodeFromMenuItem(menu_item); DCHECK(node); DCHECK(page_navigator_); page_navigator_->OpenURL( node->GetURL(), GURL(), disposition, PageTransition::AUTO_BOOKMARK); } void BookmarkMenuController::BuildMenu(const BookmarkNode* parent, int start_child_index, GtkWidget* menu) { DCHECK(!parent->GetChildCount() || start_child_index < parent->GetChildCount()); g_signal_connect(menu, "button-press-event", G_CALLBACK(OnButtonPressedThunk), this); for (int i = start_child_index; i < parent->GetChildCount(); ++i) { const BookmarkNode* node = parent->GetChild(i); // This breaks on word boundaries. Ideally we would break on character // boundaries. std::wstring elided_name = l10n_util::TruncateString(node->GetTitle(), kMaxChars); GtkWidget* menu_item = gtk_image_menu_item_new_with_label(WideToUTF8(elided_name).c_str()); g_object_set_data(G_OBJECT(menu_item), "bookmark-node", AsVoid(node)); SetImageMenuItem(menu_item, node, profile_->GetBookmarkModel()); gtk_util::SetAlwaysShowImage(menu_item); g_signal_connect(menu_item, "button-release-event", G_CALLBACK(OnButtonReleasedThunk), this); if (node->is_url()) { g_signal_connect(menu_item, "activate", G_CALLBACK(OnMenuItemActivatedThunk), this); } else if (node->is_folder()) { GtkWidget* submenu = gtk_menu_new(); BuildMenu(node, 0, submenu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else { NOTREACHED(); } gtk_drag_source_set(menu_item, GDK_BUTTON1_MASK, NULL, 0, static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK)); int target_mask = gtk_dnd_util::CHROME_BOOKMARK_ITEM; if (node->is_url()) target_mask |= gtk_dnd_util::TEXT_URI_LIST | gtk_dnd_util::NETSCAPE_URL; gtk_dnd_util::SetSourceTargetListFromCodeMask(menu_item, target_mask); g_signal_connect(menu_item, "drag-begin", G_CALLBACK(OnMenuItemDragBeginThunk), this); g_signal_connect(menu_item, "drag-end", G_CALLBACK(OnMenuItemDragEndThunk), this); g_signal_connect(menu_item, "drag-data-get", G_CALLBACK(OnMenuItemDragGetThunk), this); // It is important to connect to this signal after setting up the drag // source because we only want to stifle the menu's default handler and // not the handler that the drag source uses. if (node->is_folder()) { g_signal_connect(menu_item, "button-press-event", G_CALLBACK(OnFolderButtonPressedThunk), this); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item); node_to_menu_widget_map_[node] = menu_item; } if (parent->GetChildCount() == 0) { GtkWidget* empty_menu = gtk_menu_item_new_with_label( l10n_util::GetStringUTF8(IDS_MENU_EMPTY_SUBMENU).c_str()); gtk_widget_set_sensitive(empty_menu, FALSE); g_object_set_data(G_OBJECT(menu), "parent-node", AsVoid(parent)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), empty_menu); } } gboolean BookmarkMenuController::OnButtonPressed( GtkWidget* sender, GdkEventButton* event) { ignore_button_release_ = false; GtkMenuShell* menu_shell = GTK_MENU_SHELL(sender); if (event->button == 3) { // If the cursor is outside our bounds, pass this event up to the parent. if (!gtk_util::WidgetContainsCursor(sender)) { if (menu_shell->parent_menu_shell) { return OnButtonPressed(menu_shell->parent_menu_shell, event); } else { // We are the top level menu; we can propagate no further. return FALSE; } } // This will return NULL if we are not an empty menu. const BookmarkNode* parent = GetParentNodeFromEmptyMenu(sender); bool is_empty_menu = !!parent; // If there is no active menu item and we are not an empty menu, then do // nothing. GtkWidget* menu_item = menu_shell->active_menu_item; if (!is_empty_menu && !menu_item) return FALSE; const BookmarkNode* node = menu_item ? GetNodeFromMenuItem(menu_item) : NULL; DCHECK_NE(is_empty_menu, !!node); if (!is_empty_menu) parent = node->GetParent(); // Show the right click menu and stop processing this button event. std::vector<const BookmarkNode*> nodes; if (node) nodes.push_back(node); context_menu_controller_.reset( new BookmarkContextMenuController( parent_window_, this, profile_, page_navigator_, parent, nodes)); context_menu_.reset( new MenuGtk(NULL, context_menu_controller_->menu_model())); // Our bookmark folder menu loses the grab to the context menu. When the // context menu is hidden, re-assert our grab. GtkWidget* grabbing_menu = gtk_grab_get_current(); g_object_ref(grabbing_menu); g_signal_connect(context_menu_->widget(), "hide", G_CALLBACK(OnContextMenuHide), grabbing_menu); context_menu_->PopupAsContext(event->time); return TRUE; } return FALSE; } gboolean BookmarkMenuController::OnButtonReleased( GtkWidget* sender, GdkEventButton* event) { if (ignore_button_release_) { // Don't handle this message; it was a drag. ignore_button_release_ = false; return FALSE; } // Releasing either button 1 or 2 should trigger the bookmark. if (!gtk_menu_item_get_submenu(GTK_MENU_ITEM(sender))) { // The menu item is a link node. if (event->button == 1 || event->button == 2) { WindowOpenDisposition disposition = event_utils::DispositionFromEventFlags(event->state); NavigateToMenuItem(sender, disposition); // We need to manually dismiss the popup menu because we're overriding // button-release-event. gtk_menu_popdown(GTK_MENU(menu_)); return TRUE; } } else { // The menu item is a folder node. if (event->button == 1) { gtk_menu_popup(GTK_MENU(gtk_menu_item_get_submenu(GTK_MENU_ITEM(sender))), sender->parent, sender, NULL, NULL, event->button, event->time); } } return FALSE; } gboolean BookmarkMenuController::OnFolderButtonPressed( GtkWidget* sender, GdkEventButton* event) { // The button press may start a drag; don't let the default handler run. if (event->button == 1) return TRUE; return FALSE; } void BookmarkMenuController::OnMenuHidden(GtkWidget* menu) { if (triggering_widget_) gtk_chrome_button_unset_paint_state(GTK_CHROME_BUTTON(triggering_widget_)); } void BookmarkMenuController::OnMenuItemActivated(GtkWidget* menu_item) { NavigateToMenuItem(menu_item, CURRENT_TAB); } void BookmarkMenuController::OnMenuItemDragBegin(GtkWidget* menu_item, GdkDragContext* drag_context) { // The parent menu item might be removed during the drag. Ref it so |button| // won't get destroyed. g_object_ref(menu_item->parent); // Signal to any future OnButtonReleased calls that we're dragging instead of // pressing. ignore_button_release_ = true; const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(menu_item); drag_icon_ = bookmark_utils::GetDragRepresentationForNode( node, model_, GtkThemeProvider::GetFrom(profile_)); gint x, y; gtk_widget_get_pointer(menu_item, &x, &y); gtk_drag_set_icon_widget(drag_context, drag_icon_, x, y); // Hide our node. gtk_widget_hide(menu_item); } void BookmarkMenuController::OnMenuItemDragEnd(GtkWidget* menu_item, GdkDragContext* drag_context) { gtk_widget_show(menu_item); g_object_unref(menu_item->parent); gtk_widget_destroy(drag_icon_); drag_icon_ = NULL; } void BookmarkMenuController::OnMenuItemDragGet( GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selection_data, guint target_type, guint time) { const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(widget); bookmark_utils::WriteBookmarkToSelection(node, selection_data, target_type, profile_); } <commit_msg>GTK: improve bookmark menu subfolder drag workaround.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/bookmark_menu_controller_gtk.h" #include <gtk/gtk.h> #include "app/gtk_dnd_util.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/string_util.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/gtk/bookmark_utils_gtk.h" #include "chrome/browser/gtk/gtk_chrome_button.h" #include "chrome/browser/gtk/gtk_theme_provider.h" #include "chrome/browser/gtk/gtk_util.h" #include "chrome/browser/gtk/menu_gtk.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/page_navigator.h" #include "gfx/gtk_util.h" #include "grit/app_resources.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "webkit/glue/window_open_disposition.h" namespace { // TODO(estade): It might be a good idea to vary this by locale. const int kMaxChars = 50; void SetImageMenuItem(GtkWidget* menu_item, const BookmarkNode* node, BookmarkModel* model) { GdkPixbuf* pixbuf = bookmark_utils::GetPixbufForNode(node, model, true); gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menu_item), gtk_image_new_from_pixbuf(pixbuf)); g_object_unref(pixbuf); } const BookmarkNode* GetNodeFromMenuItem(GtkWidget* menu_item) { return static_cast<const BookmarkNode*>( g_object_get_data(G_OBJECT(menu_item), "bookmark-node")); } const BookmarkNode* GetParentNodeFromEmptyMenu(GtkWidget* menu) { return static_cast<const BookmarkNode*>( g_object_get_data(G_OBJECT(menu), "parent-node")); } void* AsVoid(const BookmarkNode* node) { return const_cast<BookmarkNode*>(node); } // The context menu has been dismissed, restore the X and application grabs // to whichever menu last had them. (Assuming that menu is still showing.) void OnContextMenuHide(GtkWidget* context_menu, GtkWidget* grab_menu) { gtk_util::GrabAllInput(grab_menu); // Match the ref we took when connecting this signal. g_object_unref(grab_menu); } } // namespace BookmarkMenuController::BookmarkMenuController(Browser* browser, Profile* profile, PageNavigator* navigator, GtkWindow* window, const BookmarkNode* node, int start_child_index) : browser_(browser), profile_(profile), page_navigator_(navigator), parent_window_(window), model_(profile->GetBookmarkModel()), node_(node), drag_icon_(NULL), ignore_button_release_(false), triggering_widget_(NULL) { menu_ = gtk_menu_new(); BuildMenu(node, start_child_index, menu_); g_signal_connect(menu_, "hide", G_CALLBACK(OnMenuHiddenThunk), this); gtk_widget_show_all(menu_); } BookmarkMenuController::~BookmarkMenuController() { profile_->GetBookmarkModel()->RemoveObserver(this); gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::Popup(GtkWidget* widget, gint button_type, guint32 timestamp) { profile_->GetBookmarkModel()->AddObserver(this); triggering_widget_ = widget; gtk_chrome_button_set_paint_state(GTK_CHROME_BUTTON(widget), GTK_STATE_ACTIVE); gtk_menu_popup(GTK_MENU(menu_), NULL, NULL, &MenuGtk::WidgetMenuPositionFunc, widget, button_type, timestamp); } void BookmarkMenuController::BookmarkModelChanged() { gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::BookmarkNodeFavIconLoaded( BookmarkModel* model, const BookmarkNode* node) { std::map<const BookmarkNode*, GtkWidget*>::iterator it = node_to_menu_widget_map_.find(node); if (it != node_to_menu_widget_map_.end()) SetImageMenuItem(it->second, node, model); } void BookmarkMenuController::WillExecuteCommand() { gtk_menu_popdown(GTK_MENU(menu_)); } void BookmarkMenuController::CloseMenu() { context_menu_->Cancel(); } void BookmarkMenuController::NavigateToMenuItem( GtkWidget* menu_item, WindowOpenDisposition disposition) { const BookmarkNode* node = GetNodeFromMenuItem(menu_item); DCHECK(node); DCHECK(page_navigator_); page_navigator_->OpenURL( node->GetURL(), GURL(), disposition, PageTransition::AUTO_BOOKMARK); } void BookmarkMenuController::BuildMenu(const BookmarkNode* parent, int start_child_index, GtkWidget* menu) { DCHECK(!parent->GetChildCount() || start_child_index < parent->GetChildCount()); g_signal_connect(menu, "button-press-event", G_CALLBACK(OnButtonPressedThunk), this); for (int i = start_child_index; i < parent->GetChildCount(); ++i) { const BookmarkNode* node = parent->GetChild(i); // This breaks on word boundaries. Ideally we would break on character // boundaries. std::wstring elided_name = l10n_util::TruncateString(node->GetTitle(), kMaxChars); GtkWidget* menu_item = gtk_image_menu_item_new_with_label(WideToUTF8(elided_name).c_str()); g_object_set_data(G_OBJECT(menu_item), "bookmark-node", AsVoid(node)); SetImageMenuItem(menu_item, node, profile_->GetBookmarkModel()); gtk_util::SetAlwaysShowImage(menu_item); g_signal_connect(menu_item, "button-release-event", G_CALLBACK(OnButtonReleasedThunk), this); if (node->is_url()) { g_signal_connect(menu_item, "activate", G_CALLBACK(OnMenuItemActivatedThunk), this); } else if (node->is_folder()) { GtkWidget* submenu = gtk_menu_new(); BuildMenu(node, 0, submenu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_item), submenu); } else { NOTREACHED(); } gtk_drag_source_set(menu_item, GDK_BUTTON1_MASK, NULL, 0, static_cast<GdkDragAction>(GDK_ACTION_COPY | GDK_ACTION_LINK)); int target_mask = gtk_dnd_util::CHROME_BOOKMARK_ITEM; if (node->is_url()) target_mask |= gtk_dnd_util::TEXT_URI_LIST | gtk_dnd_util::NETSCAPE_URL; gtk_dnd_util::SetSourceTargetListFromCodeMask(menu_item, target_mask); g_signal_connect(menu_item, "drag-begin", G_CALLBACK(OnMenuItemDragBeginThunk), this); g_signal_connect(menu_item, "drag-end", G_CALLBACK(OnMenuItemDragEndThunk), this); g_signal_connect(menu_item, "drag-data-get", G_CALLBACK(OnMenuItemDragGetThunk), this); // It is important to connect to this signal after setting up the drag // source because we only want to stifle the menu's default handler and // not the handler that the drag source uses. if (node->is_folder()) { g_signal_connect(menu_item, "button-press-event", G_CALLBACK(OnFolderButtonPressedThunk), this); } gtk_menu_shell_append(GTK_MENU_SHELL(menu), menu_item); node_to_menu_widget_map_[node] = menu_item; } if (parent->GetChildCount() == 0) { GtkWidget* empty_menu = gtk_menu_item_new_with_label( l10n_util::GetStringUTF8(IDS_MENU_EMPTY_SUBMENU).c_str()); gtk_widget_set_sensitive(empty_menu, FALSE); g_object_set_data(G_OBJECT(menu), "parent-node", AsVoid(parent)); gtk_menu_shell_append(GTK_MENU_SHELL(menu), empty_menu); } } gboolean BookmarkMenuController::OnButtonPressed( GtkWidget* sender, GdkEventButton* event) { ignore_button_release_ = false; GtkMenuShell* menu_shell = GTK_MENU_SHELL(sender); if (event->button == 3) { // If the cursor is outside our bounds, pass this event up to the parent. if (!gtk_util::WidgetContainsCursor(sender)) { if (menu_shell->parent_menu_shell) { return OnButtonPressed(menu_shell->parent_menu_shell, event); } else { // We are the top level menu; we can propagate no further. return FALSE; } } // This will return NULL if we are not an empty menu. const BookmarkNode* parent = GetParentNodeFromEmptyMenu(sender); bool is_empty_menu = !!parent; // If there is no active menu item and we are not an empty menu, then do // nothing. This can happen if the user has canceled a context menu while // the cursor is hovering over a bookmark menu. Doing nothing is not optimal // (the hovered item should be active), but it's a hopefully rare corner // case. GtkWidget* menu_item = menu_shell->active_menu_item; if (!is_empty_menu && !menu_item) return TRUE; const BookmarkNode* node = menu_item ? GetNodeFromMenuItem(menu_item) : NULL; DCHECK_NE(is_empty_menu, !!node); if (!is_empty_menu) parent = node->GetParent(); // Show the right click menu and stop processing this button event. std::vector<const BookmarkNode*> nodes; if (node) nodes.push_back(node); context_menu_controller_.reset( new BookmarkContextMenuController( parent_window_, this, profile_, page_navigator_, parent, nodes)); context_menu_.reset( new MenuGtk(NULL, context_menu_controller_->menu_model())); // Our bookmark folder menu loses the grab to the context menu. When the // context menu is hidden, re-assert our grab. GtkWidget* grabbing_menu = gtk_grab_get_current(); g_object_ref(grabbing_menu); g_signal_connect(context_menu_->widget(), "hide", G_CALLBACK(OnContextMenuHide), grabbing_menu); context_menu_->PopupAsContext(event->time); return TRUE; } return FALSE; } gboolean BookmarkMenuController::OnButtonReleased( GtkWidget* sender, GdkEventButton* event) { if (ignore_button_release_) { // Don't handle this message; it was a drag. ignore_button_release_ = false; return FALSE; } // Releasing either button 1 or 2 should trigger the bookmark. if (!gtk_menu_item_get_submenu(GTK_MENU_ITEM(sender))) { // The menu item is a link node. if (event->button == 1 || event->button == 2) { WindowOpenDisposition disposition = event_utils::DispositionFromEventFlags(event->state); NavigateToMenuItem(sender, disposition); // We need to manually dismiss the popup menu because we're overriding // button-release-event. gtk_menu_popdown(GTK_MENU(menu_)); return TRUE; } } else { // The menu item is a folder node. if (event->button == 1) { gtk_menu_shell_select_item(GTK_MENU_SHELL(sender->parent), sender); g_signal_emit_by_name(sender->parent, "activate-current"); return TRUE; } } return FALSE; } gboolean BookmarkMenuController::OnFolderButtonPressed( GtkWidget* sender, GdkEventButton* event) { // The button press may start a drag; don't let the default handler run. if (event->button == 1) return TRUE; return FALSE; } void BookmarkMenuController::OnMenuHidden(GtkWidget* menu) { if (triggering_widget_) gtk_chrome_button_unset_paint_state(GTK_CHROME_BUTTON(triggering_widget_)); } void BookmarkMenuController::OnMenuItemActivated(GtkWidget* menu_item) { NavigateToMenuItem(menu_item, CURRENT_TAB); } void BookmarkMenuController::OnMenuItemDragBegin(GtkWidget* menu_item, GdkDragContext* drag_context) { // The parent menu item might be removed during the drag. Ref it so |button| // won't get destroyed. g_object_ref(menu_item->parent); // Signal to any future OnButtonReleased calls that we're dragging instead of // pressing. ignore_button_release_ = true; const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(menu_item); drag_icon_ = bookmark_utils::GetDragRepresentationForNode( node, model_, GtkThemeProvider::GetFrom(profile_)); gint x, y; gtk_widget_get_pointer(menu_item, &x, &y); gtk_drag_set_icon_widget(drag_context, drag_icon_, x, y); // Hide our node. gtk_widget_hide(menu_item); } void BookmarkMenuController::OnMenuItemDragEnd(GtkWidget* menu_item, GdkDragContext* drag_context) { gtk_widget_show(menu_item); g_object_unref(menu_item->parent); gtk_widget_destroy(drag_icon_); drag_icon_ = NULL; } void BookmarkMenuController::OnMenuItemDragGet( GtkWidget* widget, GdkDragContext* context, GtkSelectionData* selection_data, guint target_type, guint time) { const BookmarkNode* node = bookmark_utils::BookmarkNodeForWidget(widget); bookmark_utils::WriteBookmarkToSelection(node, selection_data, target_type, profile_); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/browser_thread.h" #include "net/base/cookie_monster.h" #include "net/base/host_resolver.h" #include "net/base/load_flags.h" #include "net/base/ssl_config_service_defaults.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_network_layer.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/net/chrome_net_log.h" #include "chrome/browser/policy/device_management_backend_impl.h" #include "chrome/common/net/url_request_context_getter.h" namespace policy { namespace { // Custom request context implementation that allows to override the user agent, // amongst others. Wraps a baseline request context from which we reuse the // networking components. class DeviceManagementRequestContext : public URLRequestContext { public: explicit DeviceManagementRequestContext(URLRequestContext* base_context); virtual ~DeviceManagementRequestContext(); }; DeviceManagementRequestContext::DeviceManagementRequestContext( URLRequestContext* base_context) { // Share resolver, proxy service and ssl bits with the baseline context. This // is important so we don't make redundant requests (e.g. when resolving proxy // auto configuration). net_log_ = base_context->net_log(); host_resolver_ = base_context->host_resolver(); proxy_service_ = base_context->proxy_service(); ssl_config_service_ = base_context->ssl_config_service(); // Share the http session. http_transaction_factory_ = net::HttpNetworkLayer::CreateFactory( base_context->http_transaction_factory()->GetSession()); // No cookies, please. cookie_store_ = new net::CookieMonster(NULL, NULL); // Initialize these to sane values for our purposes. accept_language_ = "*"; accept_charset_ = "*"; } DeviceManagementRequestContext::~DeviceManagementRequestContext() { delete http_transaction_factory_; delete http_auth_handler_factory_; } // Request context holder. class DeviceManagementRequestContextGetter : public URLRequestContextGetter { public: DeviceManagementRequestContextGetter( URLRequestContextGetter* base_context_getter) : base_context_getter_(base_context_getter) {} // URLRequestContextGetter overrides. virtual URLRequestContext* GetURLRequestContext(); virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const; private: scoped_refptr<URLRequestContext> context_; scoped_refptr<URLRequestContextGetter> base_context_getter_; }; URLRequestContext* DeviceManagementRequestContextGetter::GetURLRequestContext() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!context_) { context_ = new DeviceManagementRequestContext( base_context_getter_->GetURLRequestContext()); } return context_.get(); } scoped_refptr<base::MessageLoopProxy> DeviceManagementRequestContextGetter::GetIOMessageLoopProxy() const { return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); } } // namespace DeviceManagementService::~DeviceManagementService() { // All running jobs should have been canceled by now. If not, there are // backend objects still around, which is an error. DCHECK(pending_jobs_.empty()); DCHECK(queued_jobs_.empty()); } DeviceManagementBackend* DeviceManagementService::CreateBackend() { return new DeviceManagementBackendImpl(this); } void DeviceManagementService::Initialize( URLRequestContextGetter* request_context_getter) { DCHECK(!request_context_getter_); request_context_getter_ = new DeviceManagementRequestContextGetter(request_context_getter); while (!queued_jobs_.empty()) { StartJob(queued_jobs_.front()); queued_jobs_.pop_front(); } } void DeviceManagementService::Shutdown() { for (JobFetcherMap::iterator job(pending_jobs_.begin()); job != pending_jobs_.end(); ++job) { delete job->first; queued_jobs_.push_back(job->second); } } DeviceManagementService::DeviceManagementService( const std::string& server_url) : server_url_(server_url) { } void DeviceManagementService::AddJob(DeviceManagementJob* job) { if (request_context_getter_.get()) StartJob(job); else queued_jobs_.push_back(job); } void DeviceManagementService::RemoveJob(DeviceManagementJob* job) { for (JobFetcherMap::iterator entry(pending_jobs_.begin()); entry != pending_jobs_.end(); ++entry) { if (entry->second == job) { delete entry->first; pending_jobs_.erase(entry); break; } } } void DeviceManagementService::StartJob(DeviceManagementJob* job) { URLFetcher* fetcher = URLFetcher::Create(0, job->GetURL(server_url_), URLFetcher::POST, this); fetcher->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DISABLE_CACHE); fetcher->set_request_context(request_context_getter_.get()); job->ConfigureRequest(fetcher); pending_jobs_[fetcher] = job; fetcher->Start(); } void DeviceManagementService::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { JobFetcherMap::iterator entry(pending_jobs_.find(source)); if (entry != pending_jobs_.end()) { DeviceManagementJob* job = entry->second; job->HandleResponse(status, response_code, cookies, data); pending_jobs_.erase(entry); } else { NOTREACHED() << "Callback from foreign URL fetcher"; } delete source; } } // namespace policy <commit_msg>Make the device management service send a proper user agent.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/device_management_service.h" #include "chrome/browser/browser_thread.h" #include "net/base/cookie_monster.h" #include "net/base/host_resolver.h" #include "net/base/load_flags.h" #include "net/base/ssl_config_service_defaults.h" #include "net/http/http_auth_handler_factory.h" #include "net/http/http_network_layer.h" #include "net/proxy/proxy_service.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/io_thread.h" #include "chrome/browser/net/chrome_net_log.h" #include "chrome/browser/policy/device_management_backend_impl.h" #include "chrome/common/net/url_request_context_getter.h" #include "webkit/glue/webkit_glue.h" namespace policy { namespace { // Custom request context implementation that allows to override the user agent, // amongst others. Wraps a baseline request context from which we reuse the // networking components. class DeviceManagementRequestContext : public URLRequestContext { public: explicit DeviceManagementRequestContext(URLRequestContext* base_context); virtual ~DeviceManagementRequestContext(); private: // Overriden from URLRequestContext. virtual const std::string& GetUserAgent(const GURL& url) const; }; DeviceManagementRequestContext::DeviceManagementRequestContext( URLRequestContext* base_context) { // Share resolver, proxy service and ssl bits with the baseline context. This // is important so we don't make redundant requests (e.g. when resolving proxy // auto configuration). net_log_ = base_context->net_log(); host_resolver_ = base_context->host_resolver(); proxy_service_ = base_context->proxy_service(); ssl_config_service_ = base_context->ssl_config_service(); // Share the http session. http_transaction_factory_ = net::HttpNetworkLayer::CreateFactory( base_context->http_transaction_factory()->GetSession()); // No cookies, please. cookie_store_ = new net::CookieMonster(NULL, NULL); // Initialize these to sane values for our purposes. accept_language_ = "*"; accept_charset_ = "*"; } DeviceManagementRequestContext::~DeviceManagementRequestContext() { delete http_transaction_factory_; delete http_auth_handler_factory_; } const std::string& DeviceManagementRequestContext::GetUserAgent( const GURL& url) const { return webkit_glue::GetUserAgent(url); } // Request context holder. class DeviceManagementRequestContextGetter : public URLRequestContextGetter { public: DeviceManagementRequestContextGetter( URLRequestContextGetter* base_context_getter) : base_context_getter_(base_context_getter) {} // URLRequestContextGetter overrides. virtual URLRequestContext* GetURLRequestContext(); virtual scoped_refptr<base::MessageLoopProxy> GetIOMessageLoopProxy() const; private: scoped_refptr<URLRequestContext> context_; scoped_refptr<URLRequestContextGetter> base_context_getter_; }; URLRequestContext* DeviceManagementRequestContextGetter::GetURLRequestContext() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!context_) { context_ = new DeviceManagementRequestContext( base_context_getter_->GetURLRequestContext()); } return context_.get(); } scoped_refptr<base::MessageLoopProxy> DeviceManagementRequestContextGetter::GetIOMessageLoopProxy() const { return BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO); } } // namespace DeviceManagementService::~DeviceManagementService() { // All running jobs should have been canceled by now. If not, there are // backend objects still around, which is an error. DCHECK(pending_jobs_.empty()); DCHECK(queued_jobs_.empty()); } DeviceManagementBackend* DeviceManagementService::CreateBackend() { return new DeviceManagementBackendImpl(this); } void DeviceManagementService::Initialize( URLRequestContextGetter* request_context_getter) { DCHECK(!request_context_getter_); request_context_getter_ = new DeviceManagementRequestContextGetter(request_context_getter); while (!queued_jobs_.empty()) { StartJob(queued_jobs_.front()); queued_jobs_.pop_front(); } } void DeviceManagementService::Shutdown() { for (JobFetcherMap::iterator job(pending_jobs_.begin()); job != pending_jobs_.end(); ++job) { delete job->first; queued_jobs_.push_back(job->second); } } DeviceManagementService::DeviceManagementService( const std::string& server_url) : server_url_(server_url) { } void DeviceManagementService::AddJob(DeviceManagementJob* job) { if (request_context_getter_.get()) StartJob(job); else queued_jobs_.push_back(job); } void DeviceManagementService::RemoveJob(DeviceManagementJob* job) { for (JobFetcherMap::iterator entry(pending_jobs_.begin()); entry != pending_jobs_.end(); ++entry) { if (entry->second == job) { delete entry->first; pending_jobs_.erase(entry); break; } } } void DeviceManagementService::StartJob(DeviceManagementJob* job) { URLFetcher* fetcher = URLFetcher::Create(0, job->GetURL(server_url_), URLFetcher::POST, this); fetcher->set_load_flags(net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DISABLE_CACHE); fetcher->set_request_context(request_context_getter_.get()); job->ConfigureRequest(fetcher); pending_jobs_[fetcher] = job; fetcher->Start(); } void DeviceManagementService::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { JobFetcherMap::iterator entry(pending_jobs_.find(source)); if (entry != pending_jobs_.end()) { DeviceManagementJob* job = entry->second; job->HandleResponse(status, response_code, cookies, data); pending_jobs_.erase(entry); } else { NOTREACHED() << "Callback from foreign URL fetcher"; } delete source; } } // namespace policy <|endoftext|>
<commit_before> /* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <qi/log/journaldloghandler.hpp> #include <qi/log.hpp> #include <systemd/sd-journal.h> #include <iostream> namespace qi { namespace log { void JournaldLogHandler::log(const qi::LogLevel verb, const char* category, const char* msg, const char* file, const char* fct, const int line) { // systemd uses the log level defined by syslog. // Here is how we mix both. // LOG_EMERG(0) LogLevel_Fatal(1) // LOG_ALERT(1) // LOG_CRIT(2) // LOG_ERR(3) LogLevel_Error(2) // LOG_WARNING(4) LogLevel_Warning(3) // LOG_NOTICE(5) LogLevel_Info(4) // LOG_INFO(6) LogLevel_Verbose(5) // LOG_DEBUG(7) LogLevel_Debug(6) int _verb = static_cast<int>(verb); if (_verb == 1) _verb = 0; else _verb += 1; int i = sd_journal_send("MESSAGE=%s", msg, "QI_CATEGORY=%s", category, "PRIORITY=%i", _verb, "CODE_FILE=%s", file, "CODE_LINE=%i", line, "CODE_FUNC=%s", fct, NULL ); if (i == 0) return; // If it fail try to do a simpler call to journald int j = sd_journal_print(_verb, "%s; %s", category, msg); if (j == 0) return; // If it fail again print an error message std::cerr << "Can't set message to journald." << std::endl; } } } <commit_msg>journaldloghandler: improve error message<commit_after> /* * Copyright (c) 2012 Aldebaran Robotics. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the COPYING file. */ #include <qi/log/journaldloghandler.hpp> #include <qi/log.hpp> #include <systemd/sd-journal.h> #include <iostream> namespace qi { namespace log { void JournaldLogHandler::log(const qi::LogLevel verb, const char* category, const char* msg, const char* file, const char* fct, const int line) { // systemd uses the log level defined by syslog. // Here is how we mix both. // LOG_EMERG(0) LogLevel_Fatal(1) // LOG_ALERT(1) // LOG_CRIT(2) // LOG_ERR(3) LogLevel_Error(2) // LOG_WARNING(4) LogLevel_Warning(3) // LOG_NOTICE(5) LogLevel_Info(4) // LOG_INFO(6) LogLevel_Verbose(5) // LOG_DEBUG(7) LogLevel_Debug(6) int _verb = static_cast<int>(verb); if (_verb == 1) _verb = 0; else _verb += 1; int i = sd_journal_send("MESSAGE=%s", msg, "QI_CATEGORY=%s", category, "PRIORITY=%i", _verb, "CODE_FILE=%s", file, "CODE_LINE=%i", line, "CODE_FUNC=%s", fct, NULL ); if (i == 0) return; // If it fail try to do a simpler call to journald int j = sd_journal_print(_verb, "%s; %s", category, msg); if (j == 0) return; // If it fail again print an error message std::cerr << "Can't send message to journald." << std::endl; } } } <|endoftext|>
<commit_before>/* * tt.filter~ * External object for Max/MSP * Wannabe Max wrapper (external) for all filter units in ttblue * Example project for TTBlue * Copyright © 2008 by Timothy Place & Trond Lossius * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTLowpassButterworth.h" // TTBlue Interfaces... /** Data structure for the filter module. */ typedef struct _filter { ///< Data Structure for this object t_pxobject obj; ///< REQUIRED: Our object void *obex; ///< REQUIRED: Object Extensions used by Jitter/Attribute stuff TTLowpassButterworth *filter; ///< Pointer to the TTBlue filter unit used TTAudioSignal *audioIn; ///< Array of pointers to the audio inlets TTAudioSignal *audioOut; ///< Array of pointers to the audio outlets long attrBypass; ///< ATTRIBUTE: Bypass filtering long maxNumChannels; ///< The maximum number of audio channels permitted TTFloat64 attrFrequency; ///< ATTRIBUTE: Filter cutoff or center frequency, depending on the kind of filter } t_filter; // Prototypes for methods: need a method for each incoming message type /** New object create method. */ void* filter_new(t_symbol *msg, short argc, t_atom *argv); /** Free memory etc. when an object is destroyed. */ void filter_free(t_filter *x); /** Assist strings for object inlets and outlets. */ void filter_assist(t_filter *x, void *b, long msg, long arg, char *dst); /** This method is called on each audio vector. */ t_int* filter_perform(t_int *w); /** This method is called when audio is started in order to compile the audio chain. */ void filter_dsp(t_filter *x, t_signal **sp, short *count); /** Clear the filter in case it has blown up (NaN) */ void filter_clear(t_filter *x); /** Method setting the value of the bypass attribute. */ t_max_err filter_setBypass(t_filter *x, void *attr, long argc, t_atom *argv); /** Method setting the value of the frequency attribute. */ t_max_err filter_setFrequency(t_filter *x, void *attr, long argc, t_atom *argv); // Globals t_class *filter_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int main(void) { long attrflags = 0; t_class *c; t_object *attr; common_symbols_init(); c = class_new("tt.filter~",(method)filter_new, (method)filter_free, (short)sizeof(t_filter), (method)0L, A_GIMME, 0); class_obexoffset_set(c, calcoffset(t_filter, obex)); class_addmethod(c, (method)filter_clear, "clear", 0L); class_addmethod(c, (method)filter_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)filter_assist, "assist", A_CANT, 0L); attr = attr_offset_new("bypass", _sym_long, attrflags, (method)0L,(method)filter_setBypass, calcoffset(t_filter, attrBypass)); class_addattr(c, attr); attr = attr_offset_new("frequency", _sym_float, attrflags, (method)0L,(method)filter_setFrequency, calcoffset(t_filter, attrFrequency)); class_addattr(c, attr); class_dspinit(c); // Setup object's class to work with MSP class_register(CLASS_BOX, c); filter_class = c; return 0; } /************************************************************************************/ // Object Creation Method void* filter_new(t_symbol *msg, short argc, t_atom *argv) { t_filter *x; TTValue sr(sys_getsr()); long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; x = (t_filter *)object_alloc(filter_class); if(x){ x->attrBypass = 0; x->maxNumChannels = 2; // An initial argument to this object will set the maximum number of channels if(attrstart && argv) x->maxNumChannels = atom_getlong(argv); TTAudioObject::setGlobalParameterValue(TT("sr"), sr); x->filter = new TTLowpassButterworth(x->maxNumChannels); x->audioIn = new TTAudioSignal(x->maxNumChannels); x->audioOut = new TTAudioSignal(x->maxNumChannels); // Setting default attribute values x->attrFrequency = 4000; attr_args_process(x,argc,argv); // handle attribute args object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout dsp_setup((t_pxobject *)x, x->maxNumChannels); // inlets for(i=0; i < x->maxNumChannels; i++) outlet_new((t_pxobject *)x, "signal"); // outlets x->obj.z_misc = Z_NO_INPLACE; } return (x); // Return the pointer } // Memory Deallocation void filter_free(t_filter *x) { dsp_free((t_pxobject *)x); delete x->filter; delete x->audioIn; delete x->audioOut; } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void filter_assist(t_filter *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlets strcpy(dst, "(signal) input, control messages"); else if(msg==2) // Outlets strcpy(dst, "(signal) Filtered output"); #pragma unused(x) #pragma unused(b) #pragma unused(arg) } void filter_clear(t_filter *x) { x->filter->sendMessage("clear"); } // Perform (signal) Method t_int *filter_perform(t_int *w) { t_filter *x = (t_filter *)(w[1]); short i, j; for(i=0; i < x->audioIn->numChannels; i++){ j = (i*2) + 1; x->audioIn->setVector(i, (t_float *)(w[j+1])); x->audioOut->setVector(i, (t_float *)(w[j+2])); } if(!x->obj.z_disabled) // if we are not muted... x->filter->process(*x->audioIn, *x->audioOut); // Actual DC-Blocker process return w + ((x->audioIn->numChannels*2)+2); // +2 = +1 for the x pointer and +1 to point to the next object } // DSP Method void filter_dsp(t_filter *x, t_signal **sp, short *count) { short i, j, k=0; void **audioVectors = NULL; audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->maxNumChannels * 2) + 1)); audioVectors[k] = x; k++; x->audioIn->numChannels = 0; x->audioOut->numChannels = 0; for(i=0; i < x->maxNumChannels; i++){ j = x->maxNumChannels + i; if(count[i] && count[j]){ audioVectors[k] = sp[i]->s_vec; x->audioIn->numChannels++; x->audioIn->vs = sp[i]->s_n; k++; audioVectors[k] = sp[j]->s_vec; x->audioOut->numChannels++; x->audioIn->vs = sp[j]->s_n; k++; } } x->filter->setParameterValue(TT("sr"), sp[0]->s_sr); dsp_addv(filter_perform, k, audioVectors); sysmem_freeptr(audioVectors); } t_max_err filter_setBypass(t_filter *x, void *attr, long argc, t_atom *argv) { TTSymbol name("bypass"); TTValue value; if(argc){ value = x->attrBypass = atom_getlong(argv); x->filter->setParameterValue(name, value); } return MAX_ERR_NONE; } t_max_err filter_setFrequency(t_filter *x, void *attr, long argc, t_atom *argv) { TTSymbol name("frequency"); TTValue value; if(argc){ value = x->attrFrequency = atom_getfloat(argv); x->filter->setParameterValue(name, value); } return MAX_ERR_NONE; } <commit_msg>Simplified the attr accessors: you no longer have to actually allocate TTValue and TTSymbol objects when calling the setParameterValue() method.<commit_after>/* * tt.filter~ * External object for Max/MSP * Wannabe Max wrapper (external) for all filter units in ttblue * Example project for TTBlue * Copyright © 2008 by Timothy Place & Trond Lossius * * License: This code is licensed under the terms of the GNU LGPL * http://www.gnu.org/licenses/lgpl.html */ #include "ext.h" // Max Header #include "z_dsp.h" // MSP Header #include "ext_strings.h" // String Functions #include "commonsyms.h" // Common symbols used by the Max 4.5 API #include "ext_obex.h" // Max Object Extensions (attributes) Header #include "TTLowpassButterworth.h" // TTBlue Interfaces... /** Data structure for the filter module. */ typedef struct _filter { ///< Data Structure for this object t_pxobject obj; ///< REQUIRED: Our object void *obex; ///< REQUIRED: Object Extensions used by Jitter/Attribute stuff TTLowpassButterworth *filter; ///< Pointer to the TTBlue filter unit used TTAudioSignal *audioIn; ///< Array of pointers to the audio inlets TTAudioSignal *audioOut; ///< Array of pointers to the audio outlets long attrBypass; ///< ATTRIBUTE: Bypass filtering long maxNumChannels; ///< The maximum number of audio channels permitted TTFloat64 attrFrequency; ///< ATTRIBUTE: Filter cutoff or center frequency, depending on the kind of filter } t_filter; // Prototypes for methods: need a method for each incoming message type /** New object create method. */ void* filter_new(t_symbol *msg, short argc, t_atom *argv); /** Free memory etc. when an object is destroyed. */ void filter_free(t_filter *x); /** Assist strings for object inlets and outlets. */ void filter_assist(t_filter *x, void *b, long msg, long arg, char *dst); /** This method is called on each audio vector. */ t_int* filter_perform(t_int *w); /** This method is called when audio is started in order to compile the audio chain. */ void filter_dsp(t_filter *x, t_signal **sp, short *count); /** Clear the filter in case it has blown up (NaN) */ void filter_clear(t_filter *x); /** Method setting the value of the bypass attribute. */ t_max_err filter_setBypass(t_filter *x, void *attr, long argc, t_atom *argv); /** Method setting the value of the frequency attribute. */ t_max_err filter_setFrequency(t_filter *x, void *attr, long argc, t_atom *argv); // Globals t_class *filter_class; // Required. Global pointing to this class /************************************************************************************/ // Main() Function int main(void) { long attrflags = 0; t_class *c; t_object *attr; common_symbols_init(); c = class_new("tt.filter~",(method)filter_new, (method)filter_free, (short)sizeof(t_filter), (method)0L, A_GIMME, 0); class_obexoffset_set(c, calcoffset(t_filter, obex)); class_addmethod(c, (method)filter_clear, "clear", 0L); class_addmethod(c, (method)filter_dsp, "dsp", A_CANT, 0L); class_addmethod(c, (method)filter_assist, "assist", A_CANT, 0L); attr = attr_offset_new("bypass", _sym_long, attrflags, (method)0L,(method)filter_setBypass, calcoffset(t_filter, attrBypass)); class_addattr(c, attr); attr = attr_offset_new("frequency", _sym_float, attrflags, (method)0L,(method)filter_setFrequency, calcoffset(t_filter, attrFrequency)); class_addattr(c, attr); class_dspinit(c); // Setup object's class to work with MSP class_register(CLASS_BOX, c); filter_class = c; return 0; } /************************************************************************************/ // Object Creation Method void* filter_new(t_symbol *msg, short argc, t_atom *argv) { t_filter *x; TTValue sr(sys_getsr()); long attrstart = attr_args_offset(argc, argv); // support normal arguments short i; x = (t_filter *)object_alloc(filter_class); if(x){ x->attrBypass = 0; x->maxNumChannels = 2; // An initial argument to this object will set the maximum number of channels if(attrstart && argv) x->maxNumChannels = atom_getlong(argv); TTAudioObject::setGlobalParameterValue(TT("sr"), sr); x->filter = new TTLowpassButterworth(x->maxNumChannels); x->audioIn = new TTAudioSignal(x->maxNumChannels); x->audioOut = new TTAudioSignal(x->maxNumChannels); // Setting default attribute values x->attrFrequency = 4000; attr_args_process(x,argc,argv); // handle attribute args object_obex_store((void *)x, _sym_dumpout, (object *)outlet_new(x,NULL)); // dumpout dsp_setup((t_pxobject *)x, x->maxNumChannels); // inlets for(i=0; i < x->maxNumChannels; i++) outlet_new((t_pxobject *)x, "signal"); // outlets x->obj.z_misc = Z_NO_INPLACE; } return (x); // Return the pointer } // Memory Deallocation void filter_free(t_filter *x) { dsp_free((t_pxobject *)x); delete x->filter; delete x->audioIn; delete x->audioOut; } /************************************************************************************/ // Methods bound to input/inlets // Method for Assistance Messages void filter_assist(t_filter *x, void *b, long msg, long arg, char *dst) { if(msg==1) // Inlets strcpy(dst, "(signal) input, control messages"); else if(msg==2) // Outlets strcpy(dst, "(signal) Filtered output"); } void filter_clear(t_filter *x) { x->filter->sendMessage("clear"); } // Perform (signal) Method t_int *filter_perform(t_int *w) { t_filter *x = (t_filter *)(w[1]); short i, j; for(i=0; i < x->audioIn->numChannels; i++){ j = (i*2) + 1; x->audioIn->setVector(i, (t_float *)(w[j+1])); x->audioOut->setVector(i, (t_float *)(w[j+2])); } if(!x->obj.z_disabled) // if we are not muted... x->filter->process(*x->audioIn, *x->audioOut); // Actual Filter process return w + ((x->audioIn->numChannels*2)+2); // +2 = +1 for the x pointer and +1 to point to the next object } // DSP Method void filter_dsp(t_filter *x, t_signal **sp, short *count) { short i, j, k=0; void **audioVectors = NULL; audioVectors = (void**)sysmem_newptr(sizeof(void*) * ((x->maxNumChannels * 2) + 1)); audioVectors[k] = x; k++; x->audioIn->numChannels = 0; x->audioOut->numChannels = 0; for(i=0; i < x->maxNumChannels; i++){ j = x->maxNumChannels + i; if(count[i] && count[j]){ audioVectors[k] = sp[i]->s_vec; x->audioIn->numChannels++; x->audioIn->vs = sp[i]->s_n; k++; audioVectors[k] = sp[j]->s_vec; x->audioOut->numChannels++; x->audioIn->vs = sp[j]->s_n; k++; } } x->filter->setParameterValue(TT("sr"), sp[0]->s_sr); dsp_addv(filter_perform, k, audioVectors); sysmem_freeptr(audioVectors); } t_max_err filter_setBypass(t_filter *x, void *attr, long argc, t_atom *argv) { if(argc){ x->attrBypass = atom_getlong(argv); x->filter->setParameterValue(TT("bypass"), x->attrBypass); } return MAX_ERR_NONE; } t_max_err filter_setFrequency(t_filter *x, void *attr, long argc, t_atom *argv) { if(argc){ x->attrFrequency = atom_getfloat(argv); x->filter->setParameterValue(TT("frequency"), x->attrFrequency); } return MAX_ERR_NONE; } <|endoftext|>
<commit_before>#ifndef BUILDERS_CYLINDERGENERATOR_HPP_DEFINED #define BUILDERS_CYLINDERGENERATOR_HPP_DEFINED #include "builders/generators/AbstractGenerator.hpp" #include "utils/MathUtils.hpp" #include <cmath> namespace utymap { namespace builders { // Generates cylinder. class CylinderGenerator : public AbstractGenerator { public: CylinderGenerator(const utymap::builders::BuilderContext& builderContext, utymap::builders::MeshContext& meshContext, const std::string& gradientKey) : AbstractGenerator(builderContext, meshContext, gradientKey), center_(), radius_(0), height_(0), radialSegments_(0), maxSegmentHeight_(0) { } // Sets center of cylinder. CylinderGenerator& setCenter(const utymap::meshing::Vector3& center) { center_ = center; return *this; } // Sets radius of cylinder. CylinderGenerator& setRadius(double radius) { radius_ = radius; return *this; } // Sets radius of cylinder. CylinderGenerator& setHeight(double height) { height_ = height; return *this; } CylinderGenerator& setRadialSegments(int radialSegments) { radialSegments_ = radialSegments; return *this; } CylinderGenerator& setMaxSegmentHeight(double maxSegmentHeight) { maxSegmentHeight_ = maxSegmentHeight; return *this; } void generate() { int heightSegments = (int) std::ceil(height_ / maxSegmentHeight_); double heightStep = height_ / heightSegments; double angleStep = 2 * pi / radialSegments_; for (int j = 0; j < radialSegments_; j++) { double firstAngle = j * angleStep; double secondAngle = (j == radialSegments_ - 1 ? 0 : j + 1) * angleStep; utymap::meshing::Vector2 first( radius_ * std::cos(firstAngle) + center_.x, radius_ * std::sin(firstAngle) + center_.z); utymap::meshing::Vector2 second( radius_ * std::cos(secondAngle) + center_.x, radius_ * std::sin(secondAngle) + center_.z); // bottom cap addTriangle(center_, utymap::meshing::Vector3(second.x, center_.y, second.y), utymap::meshing::Vector3(first.x, center_.y, first.y)); // top cap addTriangle(utymap::meshing::Vector3(center_.x, center_.y + height_, center_.z), utymap::meshing::Vector3(first.x, center_.y + height_, first.y), utymap::meshing::Vector3(second.x, center_.y + height_, second.y)); for (int i = 0; i < heightSegments; i++) { double bottomHeight = i * heightStep + center_.y; double topHeight = (i + 1) * heightStep + center_.y; utymap::meshing::Vector3 v0(first.x, bottomHeight, first.y); utymap::meshing::Vector3 v1(second.x, bottomHeight, second.y); utymap::meshing::Vector3 v2(second.x, topHeight, second.y); utymap::meshing::Vector3 v3(first.x, topHeight, first.y); addTriangle(v0, v2, v1); addTriangle(v3, v2, v0); } } } private: utymap::meshing::Vector3 center_; int radialSegments_; double radius_, height_, maxSegmentHeight_; }; }} #endif // BUILDERS_CYLINDERGENERATOR_HPP_DEFINED <commit_msg>core: correct cylinder generator to build caps<commit_after>#ifndef BUILDERS_CYLINDERGENERATOR_HPP_DEFINED #define BUILDERS_CYLINDERGENERATOR_HPP_DEFINED #include "builders/generators/AbstractGenerator.hpp" #include "utils/MathUtils.hpp" #include <cmath> namespace utymap { namespace builders { // Generates cylinder. class CylinderGenerator : public AbstractGenerator { public: CylinderGenerator(const utymap::builders::BuilderContext& builderContext, utymap::builders::MeshContext& meshContext, const std::string& gradientKey) : AbstractGenerator(builderContext, meshContext, gradientKey), center_(), radius_(0), height_(0), radialSegments_(0), maxSegmentHeight_(0) { } // Sets center of cylinder. CylinderGenerator& setCenter(const utymap::meshing::Vector3& center) { center_ = center; return *this; } // Sets radius of cylinder. CylinderGenerator& setRadius(double radius) { radius_ = radius; return *this; } // Sets radius of cylinder. CylinderGenerator& setHeight(double height) { height_ = height; return *this; } CylinderGenerator& setRadialSegments(int radialSegments) { radialSegments_ = radialSegments; return *this; } CylinderGenerator& setMaxSegmentHeight(double maxSegmentHeight) { maxSegmentHeight_ = maxSegmentHeight; return *this; } void generate() { int heightSegments = (int) std::ceil(height_ / maxSegmentHeight_); double heightStep = height_ / heightSegments; double angleStep = 2 * pi / radialSegments_; for (int j = 0; j < radialSegments_; j++) { double firstAngle = j * angleStep; double secondAngle = (j == radialSegments_ - 1 ? 0 : j + 1) * angleStep; utymap::meshing::Vector2 first( radius_ * std::cos(firstAngle) + center_.x, radius_ * std::sin(firstAngle) + center_.z); utymap::meshing::Vector2 second( radius_ * std::cos(secondAngle) + center_.x, radius_ * std::sin(secondAngle) + center_.z); // bottom cap addTriangle(center_, utymap::meshing::Vector3(first.x, center_.y, first.y), utymap::meshing::Vector3(second.x, center_.y, second.y)); // top cap addTriangle(utymap::meshing::Vector3(center_.x, center_.y + height_, center_.z), utymap::meshing::Vector3(second.x, center_.y + height_, second.y), utymap::meshing::Vector3(first.x, center_.y + height_, first.y)); for (int i = 0; i < heightSegments; i++) { double bottomHeight = i * heightStep + center_.y; double topHeight = (i + 1) * heightStep + center_.y; utymap::meshing::Vector3 v0(first.x, bottomHeight, first.y); utymap::meshing::Vector3 v1(second.x, bottomHeight, second.y); utymap::meshing::Vector3 v2(second.x, topHeight, second.y); utymap::meshing::Vector3 v3(first.x, topHeight, first.y); addTriangle(v0, v2, v1); addTriangle(v3, v2, v0); } } } private: utymap::meshing::Vector3 center_; int radialSegments_; double radius_, height_, maxSegmentHeight_; }; }} #endif // BUILDERS_CYLINDERGENERATOR_HPP_DEFINED <|endoftext|>
<commit_before>/*********************************************************************** filename: CEGUIOgreTextureTarget.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> #include <OgreRenderTexture.h> #include <OgreRenderSystem.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float OgreTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : OgreRenderTarget(owner, rs), d_CEGUITexture(0) { d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture()); // setup area and cause the initial texture to be generated. declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE)); } //----------------------------------------------------------------------------// OgreTextureTarget::~OgreTextureTarget() { d_owner.destroyTexture(*d_CEGUITexture); } //----------------------------------------------------------------------------// bool OgreTextureTarget::isImageryCache() const { return true; } //----------------------------------------------------------------------------// void OgreTextureTarget::clear() { if (!d_viewportValid) updateViewport(); Ogre::Viewport* old_vp = d_renderSystem._getViewport(); d_renderSystem._setViewport(d_viewport); d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR, Ogre::ColourValue(0, 0, 0, 0)); if (old_vp) d_renderSystem._setViewport(old_vp); } //----------------------------------------------------------------------------// Texture& OgreTextureTarget::getTexture() const { return *d_CEGUITexture; } //----------------------------------------------------------------------------// void OgreTextureTarget::declareRenderSize(const Size& sz) { // exit if current size is enough if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height)) return; Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual( OgreTexture::getUniqueName(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET); d_renderTarget = rttTex->getBuffer()->getRenderTarget(); Rect init_area( Vector2(0, 0), Size(d_renderTarget->getWidth(), d_renderTarget->getHeight()) ); setArea(init_area); // delete viewport and reset ptr so a new one is generated. This is // required because we have changed d_renderTarget so need a new VP also. delete d_viewport; d_viewport = 0; // because Texture takes ownership, the act of setting the new ogre texture // also ensures any previous ogre texture is released. d_CEGUITexture->setOgreTexture(rttTex, true); clear(); } //----------------------------------------------------------------------------// bool OgreTextureTarget::isRenderingInverted() const { return false; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <commit_msg>FIX: Crash in Ogre based texture target, where we may inadvertently restore a deleted viewport to the render system.<commit_after>/*********************************************************************** filename: CEGUIOgreTextureTarget.cpp created: Tue Feb 17 2009 author: Paul D Turner *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team * * 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 BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************/ #include "CEGUIOgreTextureTarget.h" #include "CEGUIOgreTexture.h" #include <OgreTextureManager.h> #include <OgreHardwarePixelBuffer.h> #include <OgreRenderTexture.h> #include <OgreRenderSystem.h> // Start of CEGUI namespace section namespace CEGUI { //----------------------------------------------------------------------------// const float OgreTextureTarget::DEFAULT_SIZE = 128.0f; //----------------------------------------------------------------------------// OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner, Ogre::RenderSystem& rs) : OgreRenderTarget(owner, rs), d_CEGUITexture(0) { d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture()); // setup area and cause the initial texture to be generated. declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE)); } //----------------------------------------------------------------------------// OgreTextureTarget::~OgreTextureTarget() { d_owner.destroyTexture(*d_CEGUITexture); } //----------------------------------------------------------------------------// bool OgreTextureTarget::isImageryCache() const { return true; } //----------------------------------------------------------------------------// void OgreTextureTarget::clear() { if (!d_viewportValid) updateViewport(); d_renderSystem._setViewport(d_viewport); d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR, Ogre::ColourValue(0, 0, 0, 0)); } //----------------------------------------------------------------------------// Texture& OgreTextureTarget::getTexture() const { return *d_CEGUITexture; } //----------------------------------------------------------------------------// void OgreTextureTarget::declareRenderSize(const Size& sz) { // exit if current size is enough if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height)) return; Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual( OgreTexture::getUniqueName(), Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8, Ogre::TU_RENDERTARGET); d_renderTarget = rttTex->getBuffer()->getRenderTarget(); Rect init_area( Vector2(0, 0), Size(d_renderTarget->getWidth(), d_renderTarget->getHeight()) ); setArea(init_area); // delete viewport and reset ptr so a new one is generated. This is // required because we have changed d_renderTarget so need a new VP also. delete d_viewport; d_viewport = 0; // because Texture takes ownership, the act of setting the new ogre texture // also ensures any previous ogre texture is released. d_CEGUITexture->setOgreTexture(rttTex, true); clear(); } //----------------------------------------------------------------------------// bool OgreTextureTarget::isRenderingInverted() const { return false; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section <|endoftext|>
<commit_before>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) #define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680 #include <xalanc/PlatformSupport/ArenaBlockBase.hpp> XALAN_CPP_NAMESPACE_BEGIN template<bool> struct CompileTimeError; template<> struct CompileTimeError<true>{}; #define STATIC_CHECK(expr) \ CompileTimeError<(expr) != 0 >() template <class ObjectType, #if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS) class size_Type> #else class size_Type = unsigned short > #endif class ReusableArenaBlock : public ArenaBlockBase<ObjectType, size_Type> { #define VALID_OBJECT_STAMP 0xffddffdd public: typedef ArenaBlockBase<ObjectType, size_Type> BaseClassType; typedef typename BaseClassType::size_type size_type; struct NextBlock { size_type next; const int verificationStamp; NextBlock( size_type _next): next(_next), verificationStamp(VALID_OBJECT_STAMP) { } bool isValidFor( size_type rightBorder ) const { return ( ( verificationStamp == (int)VALID_OBJECT_STAMP ) && ( next <= rightBorder ) ) ? true : false ; } }; /* * Construct an ArenaBlock of the specified size * of objects. * * @param theBlockSize The size of the block (the number of objects it can contain). */ ReusableArenaBlock(size_type theBlockSize) : BaseClassType(theBlockSize), m_firstFreeBlock(0), m_nextFreeBlock(0) { STATIC_CHECK(sizeof(ObjectType) >= sizeof(NextBlock)); for( size_type i = 0; i < this-> m_blockSize ; ++i ) { new ( reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])) ) NextBlock( (size_type)(i + 1) ); } } ~ReusableArenaBlock() { size_type removedObjects = 0; NextBlock* pStruct = 0; for ( size_type i = 0 ; i < this->m_blockSize && (removedObjects < this->m_objectCount) ; ++i ) { pStruct = reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])); if ( isOccupiedBlock(pStruct) ) { this->m_objectBlock[i].~ObjectType(); ++removedObjects; } } } /* * Allocate a block. Once the object is constructed, you must call * commitAllocation(). * * @return a pointer to the new block. */ ObjectType* allocateBlock() { if ( this->m_objectCount == this->m_blockSize ) { assert ( this->m_firstFreeBlock == (m_blockSize + 1) ); return 0; } else { assert( this->m_objectCount < this->m_blockSize ); ObjectType* theResult = 0; assert ( this->m_firstFreeBlock <= this->m_blockSize ); assert ( this->m_nextFreeBlock <= this->m_blockSize ); // check if any part was allocated but not commited if( this->m_firstFreeBlock != this->m_nextFreeBlock) { // return then againg the previouse allocated block and wait for commitment theResult = this->m_objectBlock + this->m_firstFreeBlock; } else { theResult = this->m_objectBlock + this->m_firstFreeBlock; assert(size_type( theResult - this->m_objectBlock ) < this->m_blockSize); this->m_nextFreeBlock = (reinterpret_cast<NextBlock*>(theResult))->next; assert ( ( reinterpret_cast<NextBlock*>(theResult ))->isValidFor( this->m_blockSize ) ); assert ( this->m_nextFreeBlock <= m_blockSize ); ++this->m_objectCount; } return theResult; } } /* * Commit the previous allocation. * * @param theBlock the address that was returned by allocateBlock() */ void commitAllocation(ObjectType* /* theBlock */) { this->m_firstFreeBlock = this->m_nextFreeBlock; assert ( this->m_objectCount <= this->m_blockSize ); } /* * Destroy the object, and return the block to the free list. * The behavior is undefined if the object pointed to is not * owned by the block. * * @param theObject the address of the object. */ void destroyObject(ObjectType* theObject) { // check if any uncommited block is there, add it to the list if ( this->m_firstFreeBlock != this->m_nextFreeBlock ) { // return it to pull of the free blocks NextBlock* p = reinterpret_cast<NextBlock*>( this->m_objectBlock + this->m_firstFreeBlock ); p = new (p) NextBlock(this->m_nextFreeBlock); this->m_nextFreeBlock = this->m_firstFreeBlock; } assert(ownsObject(theObject) == true); assert(shouldDestroyBlock(theObject)); theObject->~ObjectType(); NextBlock* newFreeBlock = reinterpret_cast<NextBlock*>(theObject); newFreeBlock = new (newFreeBlock) NextBlock(this->m_firstFreeBlock); m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock); assert (this->m_firstFreeBlock <= this->m_blockSize); --this->m_objectCount; } /* * Determine if this block owns the specified object. Note * that even if the object address is within our block, this * call will return false if no object currently occupies the * block. See also ownsBlock(). * * @param theObject the address of the object. * @return true if we own the object, false if not. */ bool ownsObject(const ObjectType* theObject) const { assert ( theObject != 0 ); return isOccupiedBlock( reinterpret_cast<const NextBlock*>(theObject) ); } protected: /* * Determine if the block should be destroyed. Returns true, * unless the object is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block should be destroyed, false if not. */ bool shouldDestroyBlock(const ObjectType* theObject) const { assert( size_type(theObject - this->m_objectBlock) < this->m_blockSize); return !isOnFreeList(theObject); } bool isOccupiedBlock(const NextBlock* block)const { assert( block !=0 ); return !( ownsBlock(reinterpret_cast<const ObjectType*>(block)) && block->isValidFor(this->m_blockSize) ); } private: // Not implemented... ReusableArenaBlock(const ReusableArenaBlock<ObjectType>&); ReusableArenaBlock<ObjectType>& operator=(const ReusableArenaBlock<ObjectType>&); bool operator==(const ReusableArenaBlock<ObjectType>&) const; /* * Determine if the block is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block is on the free list, false if not. */ bool isOnFreeList(const ObjectType* theObject) const { if ( this->m_objectCount == 0 ) { return false; } else { ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock; for ( int i = 0; i < (this->m_blockSize - this->m_objectCount); i++) { assert ( ownsBlock( pRunPtr ) ); if (pRunPtr == theObject) { return true; } else { NextBlock* p = reinterpret_cast<NextBlock*>(pRunPtr); assert( p->isValidFor( this->m_blockSize ) ); pRunPtr = this->m_objectBlock + p->next ; } } return false; } } size_type m_firstFreeBlock; size_type m_nextFreeBlock; }; XALAN_CPP_NAMESPACE_END #endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) <commit_msg>Fix for Bugzilla #29983 Created by : June Ng Reviewed: Dmitry Hayes<commit_after>/* * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) #define REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680 #include <xalanc/PlatformSupport/ArenaBlockBase.hpp> XALAN_CPP_NAMESPACE_BEGIN template<bool> struct CompileTimeError; template<> struct CompileTimeError<true>{}; #define STATIC_CHECK(expr) \ CompileTimeError<(expr) != 0 >() template <class ObjectType, #if defined(XALAN_NO_DEFAULT_TEMPLATE_ARGUMENTS) class size_Type> #else class size_Type = unsigned short > #endif class ReusableArenaBlock : public ArenaBlockBase<ObjectType, size_Type> { #define VALID_OBJECT_STAMP 0xffddffdd public: typedef ArenaBlockBase<ObjectType, size_Type> BaseClassType; typedef typename BaseClassType::size_type size_type; struct NextBlock { size_type next; const int verificationStamp; NextBlock( size_type _next): next(_next), verificationStamp(VALID_OBJECT_STAMP) { } bool isValidFor( size_type rightBorder ) const { return ( ( verificationStamp == (int)VALID_OBJECT_STAMP ) && ( next <= rightBorder ) ) ? true : false ; } }; /* * Construct an ArenaBlock of the specified size * of objects. * * @param theBlockSize The size of the block (the number of objects it can contain). */ ReusableArenaBlock(size_type theBlockSize) : BaseClassType(theBlockSize), m_firstFreeBlock(0), m_nextFreeBlock(0) { STATIC_CHECK(sizeof(ObjectType) >= sizeof(NextBlock)); for( size_type i = 0; i < this-> m_blockSize ; ++i ) { new ( reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])) ) NextBlock( (size_type)(i + 1) ); } } ~ReusableArenaBlock() { size_type removedObjects = 0; NextBlock* pStruct = 0; for ( size_type i = 0 ; i < this->m_blockSize && (removedObjects < this->m_objectCount) ; ++i ) { pStruct = reinterpret_cast<NextBlock*>(&(this->m_objectBlock[i])); if ( isOccupiedBlock(pStruct) ) { this->m_objectBlock[i].~ObjectType(); ++removedObjects; } } } /* * Allocate a block. Once the object is constructed, you must call * commitAllocation(). * * @return a pointer to the new block. */ ObjectType* allocateBlock() { if ( this->m_objectCount == this->m_blockSize ) { assert ( this->m_firstFreeBlock == (this->m_blockSize + 1) ); return 0; } else { assert( this->m_objectCount < this->m_blockSize ); ObjectType* theResult = 0; assert ( this->m_firstFreeBlock <= this->m_blockSize ); assert ( this->m_nextFreeBlock <= this->m_blockSize ); // check if any part was allocated but not commited if( this->m_firstFreeBlock != this->m_nextFreeBlock) { // return then againg the previouse allocated block and wait for commitment theResult = this->m_objectBlock + this->m_firstFreeBlock; } else { theResult = this->m_objectBlock + this->m_firstFreeBlock; assert(size_type( theResult - this->m_objectBlock ) < this->m_blockSize); this->m_nextFreeBlock = (reinterpret_cast<NextBlock*>(theResult))->next; assert ( ( reinterpret_cast<NextBlock*>(theResult ))->isValidFor( this->m_blockSize ) ); assert ( this->m_nextFreeBlock <= this->m_blockSize ); ++this->m_objectCount; } return theResult; } } /* * Commit the previous allocation. * * @param theBlock the address that was returned by allocateBlock() */ void commitAllocation(ObjectType* /* theBlock */) { this->m_firstFreeBlock = this->m_nextFreeBlock; assert ( this->m_objectCount <= this->m_blockSize ); } /* * Destroy the object, and return the block to the free list. * The behavior is undefined if the object pointed to is not * owned by the block. * * @param theObject the address of the object. */ void destroyObject(ObjectType* theObject) { // check if any uncommited block is there, add it to the list if ( this->m_firstFreeBlock != this->m_nextFreeBlock ) { // return it to pull of the free blocks NextBlock* p = reinterpret_cast<NextBlock*>( this->m_objectBlock + this->m_firstFreeBlock ); p = new (p) NextBlock(this->m_nextFreeBlock); this->m_nextFreeBlock = this->m_firstFreeBlock; } assert(ownsObject(theObject) == true); assert(shouldDestroyBlock(theObject)); theObject->~ObjectType(); NextBlock* newFreeBlock = reinterpret_cast<NextBlock*>(theObject); newFreeBlock = new (newFreeBlock) NextBlock(this->m_firstFreeBlock); m_firstFreeBlock = this->m_nextFreeBlock = size_type(theObject - this->m_objectBlock); assert (this->m_firstFreeBlock <= this->m_blockSize); --this->m_objectCount; } /* * Determine if this block owns the specified object. Note * that even if the object address is within our block, this * call will return false if no object currently occupies the * block. See also ownsBlock(). * * @param theObject the address of the object. * @return true if we own the object, false if not. */ bool ownsObject(const ObjectType* theObject) const { assert ( theObject != 0 ); return isOccupiedBlock( reinterpret_cast<const NextBlock*>(theObject) ); } protected: /* * Determine if the block should be destroyed. Returns true, * unless the object is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block should be destroyed, false if not. */ bool shouldDestroyBlock(const ObjectType* theObject) const { assert( size_type(theObject - this->m_objectBlock) < this->m_blockSize); return !isOnFreeList(theObject); } bool isOccupiedBlock(const NextBlock* block)const { assert( block !=0 ); return !( ownsBlock(reinterpret_cast<const ObjectType*>(block)) && block->isValidFor(this->m_blockSize) ); } private: // Not implemented... ReusableArenaBlock(const ReusableArenaBlock<ObjectType>&); ReusableArenaBlock<ObjectType>& operator=(const ReusableArenaBlock<ObjectType>&); bool operator==(const ReusableArenaBlock<ObjectType>&) const; /* * Determine if the block is on the free list. The behavior is * undefined if the object pointed to is not owned by the * block. * * @param theObject the address of the object * @return true if block is on the free list, false if not. */ bool isOnFreeList(const ObjectType* theObject) const { if ( this->m_objectCount == 0 ) { return false; } else { ObjectType* pRunPtr = this->m_objectBlock + this->m_firstFreeBlock; for ( int i = 0; i < (this->m_blockSize - this->m_objectCount); i++) { assert ( ownsBlock( pRunPtr ) ); if (pRunPtr == theObject) { return true; } else { NextBlock* p = reinterpret_cast<NextBlock*>(pRunPtr); assert( p->isValidFor( this->m_blockSize ) ); pRunPtr = this->m_objectBlock + p->next ; } } return false; } } size_type m_firstFreeBlock; size_type m_nextFreeBlock; }; XALAN_CPP_NAMESPACE_END #endif // !defined(REUSABLEARENABLOCK_INCLUDE_GUARD_1357924680) <|endoftext|>
<commit_before>#include "lithium.h" #include <gtkmm/menubar.h> #include <gtkmm/menu.h> #include <gtkmm/textview.h> #include <gtkmm/treestore.h> #include <gtkmm/entry.h> #include <glibmm.h> #include <iostream> #include <fstream> // window namespace lith { namespace ui { // creates a new button with label "Hello World". window::window() {} void window::load_style(std::basic_string<char> path) { css = Gtk::CssProvider::get_default(); // get gtk default CssProvider css->load_from_path(path); auto screen = Gdk::Screen::get_default(); auto ctx = Gtk::StyleContext::create(); ctx->add_provider_for_screen(screen, css, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); } window::~window(){} } } // editor Window namespace lith { namespace ui { namespace editor { // creates a new button with label "Hello World". window::window(std::basic_string<char> str) { set_default_size(600, 800); // set window size set_title("Lithium"); // set up keyboard shortcuts add_events( Gdk::KEY_PRESS_MASK ); signal_key_press_event().connect ( sigc::mem_fun(*this, &window::on_key_press) ); signal_key_release_event().connect ( sigc::mem_fun(*this, &window::on_key_release) ); // vertical packing box auto *vbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 0)); add(*vbox); vbox->show(); // menu bar auto*menubar = Gtk::manage(new Gtk::MenuBar()); vbox->pack_start(*menubar, Gtk::PACK_SHRINK, 0); menubar->show(); // File menu auto *menuitem_file = Gtk::manage(new Gtk::MenuItem("_File", true)); menubar->append(*menuitem_file); menuitem_file->show(); auto *filemenu = Gtk::manage(new Gtk::Menu()); menuitem_file->set_submenu(*filemenu); filemenu->show(); // File -> Open auto *menuitem_open = Gtk::manage(new Gtk::MenuItem("_Open", true)); menuitem_open->signal_activate().connect(sigc::mem_fun(*this, &window::on_open_click)); filemenu->append(*menuitem_open); menuitem_open->show(); // File -> Quit auto *menuitem_quit = Gtk::manage(new Gtk::MenuItem("_Quit", true)); menuitem_quit->signal_activate().connect(sigc::mem_fun(*this, &window::on_quit_click)); filemenu->append(*menuitem_quit); menuitem_quit->show(); // command interface command = Gtk::manage(new commandPalette()); vbox->pack_start(*command, Gtk::PACK_SHRINK, 0); command->register_func("open", sigc::mem_fun(*this, &window::on_open_str)); command->register_func("save", sigc::mem_fun(*this, &window::on_save_str)); // horizontal packing box auto *hbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); vbox->pack_end(*hbox, Gtk::PACK_EXPAND_WIDGET, 0); hbox->show(); // add treeview fview = Gtk::manage(new treeView()); fview->set_size_request(200, 0); hbox->pack_start(*fview, Gtk::PACK_SHRINK, 0); // add editor in scrolledwindow auto *editor_scroll = Gtk::manage(new Gtk::ScrolledWindow()); editor_scroll->set_kinetic_scrolling(true); editor = Gtk::manage(new textView()); editor->set_name("editor_pane"); editor_scroll->add(*editor); hbox->pack_start(*editor_scroll, Gtk::PACK_EXPAND_WIDGET, 0); editor_scroll->show(); editor->show(); show(); } window::~window(){} void window::on_open_click() { std::cout << "Hello World" << std::endl; } void window::on_open_str(std::basic_string<char> str) { editor->from_file(str); } void window::on_save_str(std::basic_string<char> str) { editor->save(str); } // do an action on a key press bool window::on_key_press(GdkEventKey *event) { if (event->keyval == GDK_KEY_Escape) { hide(); } return true; } // do an action on a key release bool window::on_key_release(GdkEventKey *event) { if ((event->state & GDK_CONTROL_MASK) && event->keyval == GDK_KEY_P) { if (!command->is_visible()) { command->show_all(); auto *txt = command->get_children()[0]; txt->grab_focus(); } else { command->hide(); } } else if ((event->state & GDK_CONTROL_MASK) && event->keyval == GDK_KEY_backslash) { if (!fview->is_visible()) { fview->show_all(); } else { fview->hide(); } } return true; } void window::on_quit_click() { hide(); } } } } // editor view namespace lith { namespace ui { namespace editor { textView::textView() { set_wrap_mode(Gtk::WrapMode::WRAP_WORD_CHAR); } void textView::from_file(std::basic_string<char> str) { file_name = str; std::ifstream file(str, std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { auto size = file.tellg(); auto memblock = new char [size]; file.seekg (0, std::ios::beg); file.read(memblock, size); get_buffer()->set_text(memblock); // Glib::convert_with_fallback(memblock, "UTF-8", "ISO-8859-1")); } file.close(); } void textView::save(std::basic_string<char> str) { auto txt = get_buffer()->get_text(); std::ofstream file(file_name); if (file.is_open()) { std::cout << txt.length() << txt.c_str() << file.write(txt.c_str(), txt.length()) << std::endl; file.close(); } } textView::~textView() {} } } } // editor file tree view namespace lith { namespace ui { namespace editor { treeView::treeView() { add(tree); set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); auto treeModel = Gtk::TreeStore::create(columns); tree.set_model(treeModel); tree.set_reorderable(); //Fill the TreeView's model Gtk::TreeModel::Row row = *(treeModel->append()); row[columns.m_col_name] = "Billy Bob"; Gtk::TreeModel::Row childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Billy Bob Junior"; childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Sue Bob"; row = *(treeModel->append()); row[columns.m_col_name] = "Joey Jojo"; row = *(treeModel->append()); row[columns.m_col_name] = "Rob McRoberts"; childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Xavier McRoberts"; //Add the TreeView's view columns: tree.append_column("files", columns.m_col_name); tree.set_name("file_view"); } treeView::~treeView() {} } } } // command palette namespace lith { namespace ui { namespace editor { commandPalette::commandPalette() : Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0) { command = Gtk::manage(new Gtk::Entry()); command->set_name("command"); command->set_placeholder_text("command, eg: 'open file.txt'"); command->signal_activate().connect(sigc::mem_fun(*this, &commandPalette::on_enter)); pack_start(*command, Gtk::PACK_EXPAND_WIDGET, 0); } commandPalette::~commandPalette() {} // registers a function for calling when a string (command) is entered void commandPalette::connect(std::basic_string<char> str, sigc::slot<void, std::basic_string<char>> func) { auto *fun = new command_func; fun->str = str; fun->func = func; commands.push_back(fun); } // use as general use input. void commandPalette::get_input() {} void commandPalette::on_enter() { // get command buffer auto buf = command->get_buffer(); auto txt = buf->get_text(); int pos = txt.find(" "); auto command = txt.substr(0, pos); auto args = txt.substr(pos + 1); for (auto it = commands.begin(); it != commands.end(); ++it) { if (command.compare((*it)->str) == 0) { std::cout << "got: "<< txt << " = " << (*it)->str << std::endl; ((*it)->func)(args); } } // print command std::cout << "got: "<< buf->get_text() << std::endl; // clear buffer buf->set_text(""); } } } } // editor file tree view namespace lith { namespace io { sock::sock() { } sock::~sock() {} } } <commit_msg>rename func registering<commit_after>#include "lithium.h" #include <gtkmm/menubar.h> #include <gtkmm/menu.h> #include <gtkmm/textview.h> #include <gtkmm/treestore.h> #include <gtkmm/entry.h> #include <glibmm.h> #include <iostream> #include <fstream> // window namespace lith { namespace ui { // creates a new button with label "Hello World". window::window() {} void window::load_style(std::basic_string<char> path) { css = Gtk::CssProvider::get_default(); // get gtk default CssProvider css->load_from_path(path); auto screen = Gdk::Screen::get_default(); auto ctx = Gtk::StyleContext::create(); ctx->add_provider_for_screen(screen, css, GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); } window::~window(){} } } // editor Window namespace lith { namespace ui { namespace editor { // creates a new button with label "Hello World". window::window(std::basic_string<char> str) { set_default_size(600, 800); // set window size set_title("Lithium"); // set up keyboard shortcuts add_events( Gdk::KEY_PRESS_MASK ); signal_key_press_event().connect ( sigc::mem_fun(*this, &window::on_key_press) ); signal_key_release_event().connect ( sigc::mem_fun(*this, &window::on_key_release) ); // vertical packing box auto *vbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_VERTICAL, 0)); add(*vbox); vbox->show(); // menu bar auto*menubar = Gtk::manage(new Gtk::MenuBar()); vbox->pack_start(*menubar, Gtk::PACK_SHRINK, 0); menubar->show(); // File menu auto *menuitem_file = Gtk::manage(new Gtk::MenuItem("_File", true)); menubar->append(*menuitem_file); menuitem_file->show(); auto *filemenu = Gtk::manage(new Gtk::Menu()); menuitem_file->set_submenu(*filemenu); filemenu->show(); // File -> Open auto *menuitem_open = Gtk::manage(new Gtk::MenuItem("_Open", true)); menuitem_open->signal_activate().connect(sigc::mem_fun(*this, &window::on_open_click)); filemenu->append(*menuitem_open); menuitem_open->show(); // File -> Quit auto *menuitem_quit = Gtk::manage(new Gtk::MenuItem("_Quit", true)); menuitem_quit->signal_activate().connect(sigc::mem_fun(*this, &window::on_quit_click)); filemenu->append(*menuitem_quit); menuitem_quit->show(); // command interface command = Gtk::manage(new commandPalette()); vbox->pack_start(*command, Gtk::PACK_SHRINK, 0); command->connect("open", sigc::mem_fun(*this, &window::on_open_str)); command->connect("save", sigc::mem_fun(*this, &window::on_save_str)); // horizontal packing box auto *hbox = Gtk::manage(new Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0)); vbox->pack_end(*hbox, Gtk::PACK_EXPAND_WIDGET, 0); hbox->show(); // add treeview fview = Gtk::manage(new treeView()); fview->set_size_request(200, 0); hbox->pack_start(*fview, Gtk::PACK_SHRINK, 0); // add editor in scrolledwindow auto *editor_scroll = Gtk::manage(new Gtk::ScrolledWindow()); editor_scroll->set_kinetic_scrolling(true); editor = Gtk::manage(new textView()); editor->set_name("editor_pane"); editor_scroll->add(*editor); hbox->pack_start(*editor_scroll, Gtk::PACK_EXPAND_WIDGET, 0); editor_scroll->show(); editor->show(); show(); } window::~window(){} void window::on_open_click() { std::cout << "Hello World" << std::endl; } void window::on_open_str(std::basic_string<char> str) { editor->from_file(str); } void window::on_save_str(std::basic_string<char> str) { editor->save(str); } // do an action on a key press bool window::on_key_press(GdkEventKey *event) { if (event->keyval == GDK_KEY_Escape) { hide(); } return true; } // do an action on a key release bool window::on_key_release(GdkEventKey *event) { if ((event->state & GDK_CONTROL_MASK) && event->keyval == GDK_KEY_P) { if (!command->is_visible()) { command->show_all(); auto *txt = command->get_children()[0]; txt->grab_focus(); } else { command->hide(); } } else if ((event->state & GDK_CONTROL_MASK) && event->keyval == GDK_KEY_backslash) { if (!fview->is_visible()) { fview->show_all(); } else { fview->hide(); } } return true; } void window::on_quit_click() { hide(); } } } } // editor view namespace lith { namespace ui { namespace editor { textView::textView() { set_wrap_mode(Gtk::WrapMode::WRAP_WORD_CHAR); } void textView::from_file(std::basic_string<char> str) { file_name = str; std::ifstream file(str, std::ios::in | std::ios::binary | std::ios::ate); if (file.is_open()) { auto size = file.tellg(); auto memblock = new char [size]; file.seekg (0, std::ios::beg); file.read(memblock, size); get_buffer()->set_text(memblock); // Glib::convert_with_fallback(memblock, "UTF-8", "ISO-8859-1")); } file.close(); } void textView::save(std::basic_string<char> str) { auto txt = get_buffer()->get_text(); std::ofstream file(file_name); if (file.is_open()) { std::cout << txt.length() << txt.c_str() << file.write(txt.c_str(), txt.length()) << std::endl; file.close(); } } textView::~textView() {} } } } // editor file tree view namespace lith { namespace ui { namespace editor { treeView::treeView() { add(tree); set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC); auto treeModel = Gtk::TreeStore::create(columns); tree.set_model(treeModel); tree.set_reorderable(); //Fill the TreeView's model Gtk::TreeModel::Row row = *(treeModel->append()); row[columns.m_col_name] = "Billy Bob"; Gtk::TreeModel::Row childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Billy Bob Junior"; childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Sue Bob"; row = *(treeModel->append()); row[columns.m_col_name] = "Joey Jojo"; row = *(treeModel->append()); row[columns.m_col_name] = "Rob McRoberts"; childrow = *(treeModel->append(row.children())); childrow[columns.m_col_name] = "Xavier McRoberts"; //Add the TreeView's view columns: tree.append_column("files", columns.m_col_name); tree.set_name("file_view"); } treeView::~treeView() {} } } } // command palette namespace lith { namespace ui { namespace editor { commandPalette::commandPalette() : Gtk::Box(Gtk::ORIENTATION_HORIZONTAL, 0) { command = Gtk::manage(new Gtk::Entry()); command->set_name("command"); command->set_placeholder_text("command, eg: 'open file.txt'"); command->signal_activate().connect(sigc::mem_fun(*this, &commandPalette::on_enter)); pack_start(*command, Gtk::PACK_EXPAND_WIDGET, 0); } commandPalette::~commandPalette() {} // registers a function for calling when a string (command) is entered void commandPalette::connect(std::basic_string<char> str, sigc::slot<void, std::basic_string<char>> func) { auto *fun = new command_func; fun->str = str; fun->func = func; commands.push_back(fun); } // use as general use input. void commandPalette::get_input() {} void commandPalette::on_enter() { // get command buffer auto buf = command->get_buffer(); auto txt = buf->get_text(); int pos = txt.find(" "); auto command = txt.substr(0, pos); auto args = txt.substr(pos + 1); for (auto it = commands.begin(); it != commands.end(); ++it) { if (command.compare((*it)->str) == 0) { std::cout << "got: "<< txt << " = " << (*it)->str << std::endl; ((*it)->func)(args); } } // print command std::cout << "got: "<< buf->get_text() << std::endl; // clear buffer buf->set_text(""); } } } } // editor file tree view namespace lith { namespace io { sock::sock() { } sock::~sock() {} } } <|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // Copyright 2012-2016 Masanori Morise. All Rights Reserved. // Author: mmorise [at] yamanashi.ac.jp (Masanori Morise) // // common.cpp includes functions used in at least two files. // (1) Common functions // (2) FFT, IFFT and minimum phase analysis. // // In FFT analysis and minimum phase analysis, // Functions "Initialize*()" allocate the mamory. // Functions "Destroy*()" free the accolated memory. // FFT size is used for initialization, and structs are used to keep the memory. // Functions "GetMinimumPhaseSpectrum()" calculate minimum phase spectrum. // Forward and inverse FFT do not have the function "Get*()", // because forward FFT and inverse FFT can run in one step. // //----------------------------------------------------------------------------- #include "./common.h" #include <math.h> #include "./constantnumbers.h" #include "./matlabfunctions.h" namespace { //----------------------------------------------------------------------------- // SetParametersForLinearSmoothing() is used in LinearSmoothing() //----------------------------------------------------------------------------- void SetParametersForLinearSmoothing(int boundary, int fft_size, int fs, double width, const double *power_spectrum, double *mirroring_spectrum, double *mirroring_segment, double *frequency_axis) { for (int i = 0; i < boundary; ++i) mirroring_spectrum[i] = power_spectrum[boundary - i]; for (int i = boundary; i < fft_size / 2 + boundary; ++i) mirroring_spectrum[i] = power_spectrum[i - boundary]; for (int i = fft_size / 2 + boundary; i <= fft_size / 2 + boundary * 2; ++i) mirroring_spectrum[i] = power_spectrum[fft_size / 2 - (i - (fft_size / 2 + boundary))]; mirroring_segment[0] = mirroring_spectrum[0] * fs / fft_size; for (int i = 1; i < fft_size / 2 + boundary * 2 + 1; ++i) mirroring_segment[i] = mirroring_spectrum[i] * fs / fft_size + mirroring_segment[i - 1]; for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] = static_cast<double>(i) / fft_size * fs - width / 2.0; } } //----------------------------------------------------------------------------- // Fundamental functions int GetSuitableFFTSize(int sample) { return static_cast<int>(pow(2.0, static_cast<int>(log(static_cast<double>(sample)) / world::kLog2) + 1.0)); } //----------------------------------------------------------------------------- // DCCorrection() corrects the input spectrum from 0 to f0 Hz because the // general signal does not contain the DC (Direct Current) component. // It is used in CheapTrick() and D4C(). //----------------------------------------------------------------------------- void DCCorrection(const double *input, double current_f0, int fs, int fft_size, double *output) { int upper_limit = 1 + static_cast<int>(1.2 * current_f0 * fft_size / fs); double *low_frequency_replica = new double[upper_limit]; double *low_frequency_axis = new double[upper_limit]; for (int i = 0; i < upper_limit; ++i) low_frequency_axis[i] = static_cast<double>(i) * fs / fft_size; int upper_limit_replica = 1 + static_cast<int>(current_f0 * fft_size / fs); interp1Q(current_f0 - low_frequency_axis[0], -static_cast<double>(fs) / fft_size, input, upper_limit + 1, low_frequency_axis, upper_limit_replica, low_frequency_replica); for (int i = 0; i < upper_limit_replica; ++i) output[i] = input[i] + low_frequency_replica[i]; delete[] low_frequency_replica; delete[] low_frequency_axis; } //----------------------------------------------------------------------------- // LinearSmoothing() carries out the spectral smoothing by rectangular window // whose length is width Hz and is used in CheapTrick() and D4C(). //----------------------------------------------------------------------------- void LinearSmoothing(const double *input, double width, int fs, int fft_size, double *output) { int boundary = static_cast<int>(width * fft_size / fs) + 1; // These parameters are set by the other function. double *mirroring_spectrum = new double[fft_size / 2 + boundary * 2 + 1]; double *mirroring_segment = new double[fft_size / 2 + boundary * 2 + 1]; double *frequency_axis = new double[fft_size / 2 + 1]; SetParametersForLinearSmoothing(boundary, fft_size, fs, width, input, mirroring_spectrum, mirroring_segment, frequency_axis); double *low_levels = new double[fft_size / 2 + 1]; double *high_levels = new double[fft_size / 2 + 1]; double origin_of_mirroring_axis = -(static_cast<double>(boundary) - 0.5) * fs / fft_size; double discrete_frequency_interval = static_cast<double>(fs) / fft_size; interp1Q(origin_of_mirroring_axis, discrete_frequency_interval, mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis, fft_size / 2 + 1, low_levels); for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] += width; interp1Q(origin_of_mirroring_axis, discrete_frequency_interval, mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis, fft_size / 2 + 1, high_levels); for (int i = 0; i <= fft_size / 2; ++i) output[i] = (high_levels[i] - low_levels[i]) / width; delete[] mirroring_spectrum; delete[] mirroring_segment; delete[] frequency_axis; delete[] low_levels; delete[] high_levels; } //----------------------------------------------------------------------------- // NuttallWindow() calculates the coefficients of Nuttall window whose length // is y_length and is used in Dio() and D4C(). //----------------------------------------------------------------------------- void NuttallWindow(int y_length, double *y) { double tmp; for (int i = 0; i < y_length; ++i) { tmp = static_cast<double>(i) / (y_length - 1); y[i] = 0.355768 - 0.487396 * cos(2.0 * world::kPi * tmp) + 0.144232 * cos(4.0 * world::kPi * tmp) - 0.012604 * cos(6.0 * world::kPi * tmp); } } //----------------------------------------------------------------------------- // FFT, IFFT and minimum phase analysis void InitializeForwardRealFFT(int fft_size, ForwardRealFFT *forward_real_fft) { forward_real_fft->fft_size = fft_size; forward_real_fft->waveform = new double[fft_size]; forward_real_fft->spectrum = new fft_complex[fft_size]; forward_real_fft->forward_fft = fft_plan_dft_r2c_1d(fft_size, forward_real_fft->waveform, forward_real_fft->spectrum, FFT_ESTIMATE); } void DestroyForwardRealFFT(ForwardRealFFT *forward_real_fft) { fft_destroy_plan(forward_real_fft->forward_fft); delete[] forward_real_fft->spectrum; delete[] forward_real_fft->waveform; } void InitializeInverseRealFFT(int fft_size, InverseRealFFT *inverse_real_fft) { inverse_real_fft->fft_size = fft_size; inverse_real_fft->waveform = new double[fft_size]; inverse_real_fft->spectrum = new fft_complex[fft_size]; inverse_real_fft->inverse_fft = fft_plan_dft_c2r_1d(fft_size, inverse_real_fft->spectrum, inverse_real_fft->waveform, FFT_ESTIMATE); } void DestroyInverseRealFFT(InverseRealFFT *inverse_real_fft) { fft_destroy_plan(inverse_real_fft->inverse_fft); delete[] inverse_real_fft->spectrum; delete[] inverse_real_fft->waveform; } void InitializeMinimumPhaseAnalysis(int fft_size, MinimumPhaseAnalysis *minimum_phase) { minimum_phase->fft_size = fft_size; minimum_phase->log_spectrum = new double[fft_size]; minimum_phase->minimum_phase_spectrum = new fft_complex[fft_size]; minimum_phase->cepstrum = new fft_complex[fft_size]; minimum_phase->inverse_fft = fft_plan_dft_r2c_1d(fft_size, minimum_phase->log_spectrum, minimum_phase->cepstrum, FFT_ESTIMATE); minimum_phase->forward_fft = fft_plan_dft_1d(fft_size, minimum_phase->cepstrum, minimum_phase->minimum_phase_spectrum, FFT_FORWARD, FFT_ESTIMATE); } void GetMinimumPhaseSpectrum(const MinimumPhaseAnalysis *minimum_phase) { // Mirroring for (int i = minimum_phase->fft_size / 2 + 1; i < minimum_phase->fft_size; ++i) minimum_phase->log_spectrum[i] = minimum_phase->log_spectrum[minimum_phase->fft_size - i]; // This fft_plan carries out "forward" FFT. // To carriy out the Inverse FFT, the sign of imaginary part // is inverted after FFT. fft_execute(minimum_phase->inverse_fft); minimum_phase->cepstrum[0][1] *= -1.0; for (int i = 1; i < minimum_phase->fft_size / 2; ++i) { minimum_phase->cepstrum[i][0] *= 2.0; minimum_phase->cepstrum[i][1] *= -2.0; } minimum_phase->cepstrum[minimum_phase->fft_size / 2][1] *= -1.0; for (int i = minimum_phase->fft_size / 2 + 1; i < minimum_phase->fft_size; ++i) { minimum_phase->cepstrum[i][0] = 0.0; minimum_phase->cepstrum[i][1] = 0.0; } fft_execute(minimum_phase->forward_fft); // Since x is complex number, calculation of exp(x) is as following. // Note: This FFT library does not keep the aliasing. double tmp; for (int i = 0; i <= minimum_phase->fft_size / 2; ++i) { tmp = exp(minimum_phase->minimum_phase_spectrum[i][0] / minimum_phase->fft_size); minimum_phase->minimum_phase_spectrum[i][0] = tmp * cos(minimum_phase->minimum_phase_spectrum[i][1] / minimum_phase->fft_size); minimum_phase->minimum_phase_spectrum[i][1] = tmp * sin(minimum_phase->minimum_phase_spectrum[i][1] / minimum_phase->fft_size); } } void DestroyMinimumPhaseAnalysis(MinimumPhaseAnalysis *minimum_phase) { fft_destroy_plan(minimum_phase->forward_fft); fft_destroy_plan(minimum_phase->inverse_fft); delete[] minimum_phase->cepstrum; delete[] minimum_phase->log_spectrum; delete[] minimum_phase->minimum_phase_spectrum; } <commit_msg>Added a missing comment to common.cpp.<commit_after>//----------------------------------------------------------------------------- // Copyright 2012-2016 Masanori Morise. All Rights Reserved. // Author: mmorise [at] yamanashi.ac.jp (Masanori Morise) // // common.cpp includes functions used in at least two files. // (1) Common functions // (2) FFT, IFFT and minimum phase analysis. // // In FFT analysis and minimum phase analysis, // Functions "Initialize*()" allocate the mamory. // Functions "Destroy*()" free the accolated memory. // FFT size is used for initialization, and structs are used to keep the memory. // Functions "GetMinimumPhaseSpectrum()" calculate minimum phase spectrum. // Forward and inverse FFT do not have the function "Get*()", // because forward FFT and inverse FFT can run in one step. // //----------------------------------------------------------------------------- #include "./common.h" #include <math.h> #include "./constantnumbers.h" #include "./matlabfunctions.h" namespace { //----------------------------------------------------------------------------- // SetParametersForLinearSmoothing() is used in LinearSmoothing() //----------------------------------------------------------------------------- void SetParametersForLinearSmoothing(int boundary, int fft_size, int fs, double width, const double *power_spectrum, double *mirroring_spectrum, double *mirroring_segment, double *frequency_axis) { for (int i = 0; i < boundary; ++i) mirroring_spectrum[i] = power_spectrum[boundary - i]; for (int i = boundary; i < fft_size / 2 + boundary; ++i) mirroring_spectrum[i] = power_spectrum[i - boundary]; for (int i = fft_size / 2 + boundary; i <= fft_size / 2 + boundary * 2; ++i) mirroring_spectrum[i] = power_spectrum[fft_size / 2 - (i - (fft_size / 2 + boundary))]; mirroring_segment[0] = mirroring_spectrum[0] * fs / fft_size; for (int i = 1; i < fft_size / 2 + boundary * 2 + 1; ++i) mirroring_segment[i] = mirroring_spectrum[i] * fs / fft_size + mirroring_segment[i - 1]; for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] = static_cast<double>(i) / fft_size * fs - width / 2.0; } } // namespace //----------------------------------------------------------------------------- // Fundamental functions int GetSuitableFFTSize(int sample) { return static_cast<int>(pow(2.0, static_cast<int>(log(static_cast<double>(sample)) / world::kLog2) + 1.0)); } //----------------------------------------------------------------------------- // DCCorrection() corrects the input spectrum from 0 to f0 Hz because the // general signal does not contain the DC (Direct Current) component. // It is used in CheapTrick() and D4C(). //----------------------------------------------------------------------------- void DCCorrection(const double *input, double current_f0, int fs, int fft_size, double *output) { int upper_limit = 1 + static_cast<int>(1.2 * current_f0 * fft_size / fs); double *low_frequency_replica = new double[upper_limit]; double *low_frequency_axis = new double[upper_limit]; for (int i = 0; i < upper_limit; ++i) low_frequency_axis[i] = static_cast<double>(i) * fs / fft_size; int upper_limit_replica = 1 + static_cast<int>(current_f0 * fft_size / fs); interp1Q(current_f0 - low_frequency_axis[0], -static_cast<double>(fs) / fft_size, input, upper_limit + 1, low_frequency_axis, upper_limit_replica, low_frequency_replica); for (int i = 0; i < upper_limit_replica; ++i) output[i] = input[i] + low_frequency_replica[i]; delete[] low_frequency_replica; delete[] low_frequency_axis; } //----------------------------------------------------------------------------- // LinearSmoothing() carries out the spectral smoothing by rectangular window // whose length is width Hz and is used in CheapTrick() and D4C(). //----------------------------------------------------------------------------- void LinearSmoothing(const double *input, double width, int fs, int fft_size, double *output) { int boundary = static_cast<int>(width * fft_size / fs) + 1; // These parameters are set by the other function. double *mirroring_spectrum = new double[fft_size / 2 + boundary * 2 + 1]; double *mirroring_segment = new double[fft_size / 2 + boundary * 2 + 1]; double *frequency_axis = new double[fft_size / 2 + 1]; SetParametersForLinearSmoothing(boundary, fft_size, fs, width, input, mirroring_spectrum, mirroring_segment, frequency_axis); double *low_levels = new double[fft_size / 2 + 1]; double *high_levels = new double[fft_size / 2 + 1]; double origin_of_mirroring_axis = -(static_cast<double>(boundary) - 0.5) * fs / fft_size; double discrete_frequency_interval = static_cast<double>(fs) / fft_size; interp1Q(origin_of_mirroring_axis, discrete_frequency_interval, mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis, fft_size / 2 + 1, low_levels); for (int i = 0; i <= fft_size / 2; ++i) frequency_axis[i] += width; interp1Q(origin_of_mirroring_axis, discrete_frequency_interval, mirroring_segment, fft_size / 2 + boundary * 2 + 1, frequency_axis, fft_size / 2 + 1, high_levels); for (int i = 0; i <= fft_size / 2; ++i) output[i] = (high_levels[i] - low_levels[i]) / width; delete[] mirroring_spectrum; delete[] mirroring_segment; delete[] frequency_axis; delete[] low_levels; delete[] high_levels; } //----------------------------------------------------------------------------- // NuttallWindow() calculates the coefficients of Nuttall window whose length // is y_length and is used in Dio() and D4C(). //----------------------------------------------------------------------------- void NuttallWindow(int y_length, double *y) { double tmp; for (int i = 0; i < y_length; ++i) { tmp = static_cast<double>(i) / (y_length - 1); y[i] = 0.355768 - 0.487396 * cos(2.0 * world::kPi * tmp) + 0.144232 * cos(4.0 * world::kPi * tmp) - 0.012604 * cos(6.0 * world::kPi * tmp); } } //----------------------------------------------------------------------------- // FFT, IFFT and minimum phase analysis void InitializeForwardRealFFT(int fft_size, ForwardRealFFT *forward_real_fft) { forward_real_fft->fft_size = fft_size; forward_real_fft->waveform = new double[fft_size]; forward_real_fft->spectrum = new fft_complex[fft_size]; forward_real_fft->forward_fft = fft_plan_dft_r2c_1d(fft_size, forward_real_fft->waveform, forward_real_fft->spectrum, FFT_ESTIMATE); } void DestroyForwardRealFFT(ForwardRealFFT *forward_real_fft) { fft_destroy_plan(forward_real_fft->forward_fft); delete[] forward_real_fft->spectrum; delete[] forward_real_fft->waveform; } void InitializeInverseRealFFT(int fft_size, InverseRealFFT *inverse_real_fft) { inverse_real_fft->fft_size = fft_size; inverse_real_fft->waveform = new double[fft_size]; inverse_real_fft->spectrum = new fft_complex[fft_size]; inverse_real_fft->inverse_fft = fft_plan_dft_c2r_1d(fft_size, inverse_real_fft->spectrum, inverse_real_fft->waveform, FFT_ESTIMATE); } void DestroyInverseRealFFT(InverseRealFFT *inverse_real_fft) { fft_destroy_plan(inverse_real_fft->inverse_fft); delete[] inverse_real_fft->spectrum; delete[] inverse_real_fft->waveform; } void InitializeMinimumPhaseAnalysis(int fft_size, MinimumPhaseAnalysis *minimum_phase) { minimum_phase->fft_size = fft_size; minimum_phase->log_spectrum = new double[fft_size]; minimum_phase->minimum_phase_spectrum = new fft_complex[fft_size]; minimum_phase->cepstrum = new fft_complex[fft_size]; minimum_phase->inverse_fft = fft_plan_dft_r2c_1d(fft_size, minimum_phase->log_spectrum, minimum_phase->cepstrum, FFT_ESTIMATE); minimum_phase->forward_fft = fft_plan_dft_1d(fft_size, minimum_phase->cepstrum, minimum_phase->minimum_phase_spectrum, FFT_FORWARD, FFT_ESTIMATE); } void GetMinimumPhaseSpectrum(const MinimumPhaseAnalysis *minimum_phase) { // Mirroring for (int i = minimum_phase->fft_size / 2 + 1; i < minimum_phase->fft_size; ++i) minimum_phase->log_spectrum[i] = minimum_phase->log_spectrum[minimum_phase->fft_size - i]; // This fft_plan carries out "forward" FFT. // To carriy out the Inverse FFT, the sign of imaginary part // is inverted after FFT. fft_execute(minimum_phase->inverse_fft); minimum_phase->cepstrum[0][1] *= -1.0; for (int i = 1; i < minimum_phase->fft_size / 2; ++i) { minimum_phase->cepstrum[i][0] *= 2.0; minimum_phase->cepstrum[i][1] *= -2.0; } minimum_phase->cepstrum[minimum_phase->fft_size / 2][1] *= -1.0; for (int i = minimum_phase->fft_size / 2 + 1; i < minimum_phase->fft_size; ++i) { minimum_phase->cepstrum[i][0] = 0.0; minimum_phase->cepstrum[i][1] = 0.0; } fft_execute(minimum_phase->forward_fft); // Since x is complex number, calculation of exp(x) is as following. // Note: This FFT library does not keep the aliasing. double tmp; for (int i = 0; i <= minimum_phase->fft_size / 2; ++i) { tmp = exp(minimum_phase->minimum_phase_spectrum[i][0] / minimum_phase->fft_size); minimum_phase->minimum_phase_spectrum[i][0] = tmp * cos(minimum_phase->minimum_phase_spectrum[i][1] / minimum_phase->fft_size); minimum_phase->minimum_phase_spectrum[i][1] = tmp * sin(minimum_phase->minimum_phase_spectrum[i][1] / minimum_phase->fft_size); } } void DestroyMinimumPhaseAnalysis(MinimumPhaseAnalysis *minimum_phase) { fft_destroy_plan(minimum_phase->forward_fft); fft_destroy_plan(minimum_phase->inverse_fft); delete[] minimum_phase->cepstrum; delete[] minimum_phase->log_spectrum; delete[] minimum_phase->minimum_phase_spectrum; } <|endoftext|>
<commit_before>/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Provides implementations for the chip entropy sourcing functions * on the Linux platforms. */ #include <crypto/CHIPCryptoPAL.h> #include <lib/support/CodeUtils.h> #include <lib/support/RandUtils.h> // Temporary includes for TemporaryAuditRandomPerformance() // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. #include <lib/support/BytesToHex.h> namespace chip { namespace { // Audit random number generator proper initialization with prints. // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. void TemporaryAuditRandomNumberGenerator() { uint8_t buf1[16] = { 0 }; uint8_t buf2[16] = { 0 }; VerifyOrDie(chip::Crypto::DRBG_get_bytes(&buf1[0], sizeof(buf1)) == CHIP_NO_ERROR); VerifyOrDie(chip::Crypto::DRBG_get_bytes(&buf2[0], sizeof(buf2)) == CHIP_NO_ERROR); char hex_buf[sizeof(buf1) * 2 + 1]; ChipLogProgress(DeviceLayer, "AUDIT: ===== RANDOM NUMBER GENERATOR AUDIT START ===="); ChipLogProgress(DeviceLayer, "AUDIT: * Validate buf1 and buf2 are <<<different every run/boot!>>>"); ChipLogProgress(DeviceLayer, "AUDIT: * Validate r1 and r2 are <<<different every run/boot!>>>"); memset(&hex_buf[0], 0, sizeof(hex_buf)); VerifyOrDie(Encoding::BytesToUppercaseHexString(&buf1[0], sizeof(buf1), &hex_buf[0], sizeof(hex_buf)) == CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "AUDIT: * buf1: %s", &hex_buf[0]); memset(&hex_buf[0], 0, sizeof(hex_buf)); VerifyOrDie(Encoding::BytesToUppercaseHexString(&buf2[0], sizeof(buf2), &hex_buf[0], sizeof(hex_buf)) == CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "AUDIT: * buf2: %s", &hex_buf[0]); VerifyOrDieWithMsg(memcmp(&buf1[0], &buf2[0], sizeof(buf1)) != 0, DeviceLayer, "AUDIT: FAILED: buf1, buf2 are equal: DRBG_get_bytes() does not function!"); uint32_t r1 = GetRandU32(); uint32_t r2 = GetRandU32(); ChipLogProgress(DeviceLayer, "AUDIT: * r1: 0x%08" PRIX32 " r2: 0x%08" PRIX32, r1, r2); VerifyOrDieWithMsg(r1 != r2, DeviceLayer, "AUDIT: FAILED: r1, r2 are equal: random number generator does not function!"); ChipLogProgress(DeviceLayer, "AUDIT: ===== RANDOM NUMBER GENERATOR AUDIT END ===="); } } // namespace namespace DeviceLayer { namespace Internal { CHIP_ERROR InitEntropy() { unsigned int seed; ReturnErrorOnFailure(chip::Crypto::DRBG_get_bytes((uint8_t *) &seed, sizeof(seed))); srand(seed); // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. TemporaryAuditRandomNumberGenerator(); return CHIP_NO_ERROR; } } // namespace Internal } // namespace DeviceLayer } // namespace chip <commit_msg>[Hotfix] Fix merge issue build break (#10529)<commit_after>/* * * Copyright (c) 2020 Project CHIP Authors * Copyright (c) 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * Provides implementations for the chip entropy sourcing functions * on the Linux platforms. */ #include <crypto/CHIPCryptoPAL.h> #include <crypto/RandUtils.h> #include <lib/support/CodeUtils.h> // Temporary includes for TemporaryAuditRandomPerformance() // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. #include <lib/support/BytesToHex.h> namespace chip { namespace { // Audit random number generator proper initialization with prints. // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. void TemporaryAuditRandomNumberGenerator() { uint8_t buf1[16] = { 0 }; uint8_t buf2[16] = { 0 }; VerifyOrDie(chip::Crypto::DRBG_get_bytes(&buf1[0], sizeof(buf1)) == CHIP_NO_ERROR); VerifyOrDie(chip::Crypto::DRBG_get_bytes(&buf2[0], sizeof(buf2)) == CHIP_NO_ERROR); char hex_buf[sizeof(buf1) * 2 + 1]; ChipLogProgress(DeviceLayer, "AUDIT: ===== RANDOM NUMBER GENERATOR AUDIT START ===="); ChipLogProgress(DeviceLayer, "AUDIT: * Validate buf1 and buf2 are <<<different every run/boot!>>>"); ChipLogProgress(DeviceLayer, "AUDIT: * Validate r1 and r2 are <<<different every run/boot!>>>"); memset(&hex_buf[0], 0, sizeof(hex_buf)); VerifyOrDie(Encoding::BytesToUppercaseHexString(&buf1[0], sizeof(buf1), &hex_buf[0], sizeof(hex_buf)) == CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "AUDIT: * buf1: %s", &hex_buf[0]); memset(&hex_buf[0], 0, sizeof(hex_buf)); VerifyOrDie(Encoding::BytesToUppercaseHexString(&buf2[0], sizeof(buf2), &hex_buf[0], sizeof(hex_buf)) == CHIP_NO_ERROR); ChipLogProgress(DeviceLayer, "AUDIT: * buf2: %s", &hex_buf[0]); VerifyOrDieWithMsg(memcmp(&buf1[0], &buf2[0], sizeof(buf1)) != 0, DeviceLayer, "AUDIT: FAILED: buf1, buf2 are equal: DRBG_get_bytes() does not function!"); uint32_t r1 = chip::Crypto::GetRandU32(); uint32_t r2 = chip::Crypto::GetRandU32(); ChipLogProgress(DeviceLayer, "AUDIT: * r1: 0x%08" PRIX32 " r2: 0x%08" PRIX32, r1, r2); VerifyOrDieWithMsg(r1 != r2, DeviceLayer, "AUDIT: FAILED: r1, r2 are equal: random number generator does not function!"); ChipLogProgress(DeviceLayer, "AUDIT: ===== RANDOM NUMBER GENERATOR AUDIT END ===="); } } // namespace namespace DeviceLayer { namespace Internal { CHIP_ERROR InitEntropy() { unsigned int seed; ReturnErrorOnFailure(chip::Crypto::DRBG_get_bytes((uint8_t *) &seed, sizeof(seed))); srand(seed); // TODO: remove once https://github.com/project-chip/connectedhomeip/issues/10454 is done. TemporaryAuditRandomNumberGenerator(); return CHIP_NO_ERROR; } } // namespace Internal } // namespace DeviceLayer } // namespace chip <|endoftext|>
<commit_before> #include <stdlib.h> #include <string> // include the sql parser #include "SQLParser.h" // contains printing utilities #include "sqlhelper.h" int main(int argc, char *argv[]) { if (argc <= 1) { fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n"); return -1; } std::string query = argv[1]; // parse a given query hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query); // check whether the parsing was successful if (result->isValid()) { printf("Parsed successfully!\n"); printf("Number of statements: %lu\n", result->size()); for (uint i = 0; i < result->size(); ++i) { // Print a statement summary. hsql::printStatementInfo(result->getStatement(i)); } delete result; return 0; } else { fprintf(stderr, "Given string is not a valid SQL query.\n"); fprintf(stderr, "%s (L%d:%d)\n", result->errorMsg(), result->errorLine(), result->errorColumn()); delete result; return -1; } } <commit_msg>Check NULL value of result.<commit_after> #include <stdlib.h> #include <string> // include the sql parser #include "SQLParser.h" // contains printing utilities #include "sqlhelper.h" int main(int argc, char *argv[]) { if (argc <= 1) { fprintf(stderr, "Usage: ./example \"SELECT * FROM test;\"\n"); return -1; } std::string query = argv[1]; // parse a given query hsql::SQLParserResult* result = hsql::SQLParser::parseSQLString(query); // check whether the parsing was successful if (!result) { return -1; } if (result->isValid()) { printf("Parsed successfully!\n"); printf("Number of statements: %lu\n", result->size()); for (uint i = 0; i < result->size(); ++i) { // Print a statement summary. hsql::printStatementInfo(result->getStatement(i)); } delete result; return 0; } else { fprintf(stderr, "Given string is not a valid SQL query.\n"); fprintf(stderr, "%s (L%d:%d)\n", result->errorMsg(), result->errorLine(), result->errorColumn()); delete result; return -1; } } <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2015-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "cpp_utils/assert.hpp" #include "config.hpp" void print_usage() { std::cout << "Usage: spotter [options] <command> file [file...]" << std::endl; std::cout << "Supported commands: " << std::endl; std::cout << " * train" << std::endl; std::cout << " * features" << std::endl; std::cout << " * evaluate" << std::endl; std::cout << "Supported options: " << std::endl; std::cout << " -0 : Method 0 [Marti2001]" << std::endl; std::cout << " -1 : Method 1 (holistic)" << std::endl; std::cout << " -2 : Method 2 (patches)" << std::endl; std::cout << " -3 : Method 3 [Rath2007]" << std::endl; std::cout << " -4 : Method 4 [Rath2003]" << std::endl; std::cout << " -5 : Method 5 [Rodriguez2008]" << std::endl; std::cout << " -6 : Method 6 [Vinciarelli2004]" << std::endl; std::cout << " -7 : Method 7 [Terasawa2009]" << std::endl; std::cout << " -half : Takes half resolution images only" << std::endl; std::cout << " -quarter : Takes quarter resolution images only" << std::endl; std::cout << " -third : Takes third resolution images only" << std::endl; std::cout << " -svm : Use a SVM" << std::endl; std::cout << " -view : Load the DBN and visualize its weights" << std::endl; std::cout << " -sub : Takes only a subset of the dataset to train (holistic only)" << std::endl; std::cout << " -notrain : No evaluation on the training set" << std::endl; std::cout << " -novalid : No evaluation on the validation set" << std::endl; std::cout << " -washington : The dataset is Washington [default]" << std::endl; std::cout << " -parzival : The dataset is Parzival" << std::endl; std::cout << " -iam : The dataset is IAM" << std::endl; } config parse_args(int argc, char** argv) { config conf; for (std::size_t i = 1; i < static_cast<size_t>(argc); ++i) { conf.args.emplace_back(argv[i]); } std::size_t i = 0; for (; i < conf.args.size(); ++i) { if (conf.args[i] == "-0") { conf.method = Method::Marti2001; } else if (conf.args[i] == "-1") { conf.method = Method::Holistic; } else if (conf.args[i] == "-2") { conf.method = Method::Patches; } else if (conf.args[i] == "-3") { conf.method = Method::Rath2007; } else if (conf.args[i] == "-4") { conf.method = Method::Rath2003; } else if (conf.args[i] == "-5") { conf.method = Method::Rodriguez2008; } else if (conf.args[i] == "-6") { conf.method = Method::Vinciarelli2004; } else if (conf.args[i] == "-7") { conf.method = Method::Terasawa2009; } else if (conf.args[i] == "-full") { //Simply here for consistency sake } else if (conf.args[i] == "-half") { conf.half = true; } else if (conf.args[i] == "-quarter") { conf.quarter = true; } else if (conf.args[i] == "-third") { conf.third = true; } else if (conf.args[i] == "-svm") { conf.svm = true; } else if (conf.args[i] == "-view") { conf.view = true; } else if (conf.args[i] == "-load") { conf.load = true; } else if (conf.args[i] == "-sub") { conf.sub = true; } else if (conf.args[i] == "-all") { conf.all = true; } else if (conf.args[i] == "-notrain") { conf.notrain = true; } else if (conf.args[i] == "-novalid") { conf.novalid = true; } else if (conf.args[i] == "-washington") { conf.washington = true; conf.parzival = false; conf.iam = false; } else if (conf.args[i] == "-parzival") { conf.washington = false; conf.parzival = true; conf.iam = false; } else if (conf.args[i] == "-iam") { conf.washington = false; conf.parzival = false; conf.iam = true; } else { break; } } conf.command = conf.args[i++]; for (; i < conf.args.size(); ++i) { conf.files.push_back(conf.args[i]); } return conf; } std::string method_to_string(Method method){ switch (method) { case Method::Marti2001: return "Marti2001"; case Method::Holistic: return "Holistic"; case Method::Patches: return "Patches"; case Method::Rath2007: return "Rath2007"; case Method::Rath2003: return "Rath2003"; case Method::Rodriguez2008: return "Rodriguez2008"; case Method::Vinciarelli2004: return "Vinciarelli2004"; case Method::Terasawa2009: return "Terasawa2009"; } cpp_unreachable("Unhandled method"); return "invalid_method"; } <commit_msg>Update usage<commit_after>//======================================================================= // Copyright Baptiste Wicht 2015-2016. // Distributed under the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <iostream> #include "cpp_utils/assert.hpp" #include "config.hpp" void print_usage() { std::cout << "Usage: spotter [options] <command> file [file...]" << std::endl; std::cout << "Supported commands: " << std::endl; std::cout << " * train" << std::endl; std::cout << " * features" << std::endl; std::cout << " * evaluate" << std::endl; std::cout << "Supported options: " << std::endl; std::cout << " -0 : Method 0 [Marti2001]" << std::endl; std::cout << " -1 : Method 1 (holistic)" << std::endl; std::cout << " -2 : Method 2 (patches)" << std::endl; std::cout << " -3 : Method 3 [Rath2007]" << std::endl; std::cout << " -4 : Method 4 [Rath2003]" << std::endl; std::cout << " -5 : Method 5 [Rodriguez2008]" << std::endl; std::cout << " -6 : Method 6 [Vinciarelli2004]" << std::endl; std::cout << " -7 : Method 7 [Terasawa2009]" << std::endl; std::cout << " -half : Takes half resolution images only" << std::endl; std::cout << " -quarter : Takes quarter resolution images only" << std::endl; std::cout << " -third : Takes third resolution images only" << std::endl; std::cout << " -svm : Use a SVM" << std::endl; std::cout << " -view : Load the DBN and visualize its weights" << std::endl; std::cout << " -sub : Takes only a subset of the dataset to train (holistic/patches only)" << std::endl; std::cout << " -notrain : No evaluation on the training set" << std::endl; std::cout << " -novalid : No evaluation on the validation set" << std::endl; std::cout << " -washington : The dataset is Washington [default]" << std::endl; std::cout << " -parzival : The dataset is Parzival" << std::endl; std::cout << " -iam : The dataset is IAM" << std::endl; } config parse_args(int argc, char** argv) { config conf; for (std::size_t i = 1; i < static_cast<size_t>(argc); ++i) { conf.args.emplace_back(argv[i]); } std::size_t i = 0; for (; i < conf.args.size(); ++i) { if (conf.args[i] == "-0") { conf.method = Method::Marti2001; } else if (conf.args[i] == "-1") { conf.method = Method::Holistic; } else if (conf.args[i] == "-2") { conf.method = Method::Patches; } else if (conf.args[i] == "-3") { conf.method = Method::Rath2007; } else if (conf.args[i] == "-4") { conf.method = Method::Rath2003; } else if (conf.args[i] == "-5") { conf.method = Method::Rodriguez2008; } else if (conf.args[i] == "-6") { conf.method = Method::Vinciarelli2004; } else if (conf.args[i] == "-7") { conf.method = Method::Terasawa2009; } else if (conf.args[i] == "-full") { //Simply here for consistency sake } else if (conf.args[i] == "-half") { conf.half = true; } else if (conf.args[i] == "-quarter") { conf.quarter = true; } else if (conf.args[i] == "-third") { conf.third = true; } else if (conf.args[i] == "-svm") { conf.svm = true; } else if (conf.args[i] == "-view") { conf.view = true; } else if (conf.args[i] == "-load") { conf.load = true; } else if (conf.args[i] == "-sub") { conf.sub = true; } else if (conf.args[i] == "-all") { conf.all = true; } else if (conf.args[i] == "-notrain") { conf.notrain = true; } else if (conf.args[i] == "-novalid") { conf.novalid = true; } else if (conf.args[i] == "-washington") { conf.washington = true; conf.parzival = false; conf.iam = false; } else if (conf.args[i] == "-parzival") { conf.washington = false; conf.parzival = true; conf.iam = false; } else if (conf.args[i] == "-iam") { conf.washington = false; conf.parzival = false; conf.iam = true; } else { break; } } conf.command = conf.args[i++]; for (; i < conf.args.size(); ++i) { conf.files.push_back(conf.args[i]); } return conf; } std::string method_to_string(Method method){ switch (method) { case Method::Marti2001: return "Marti2001"; case Method::Holistic: return "Holistic"; case Method::Patches: return "Patches"; case Method::Rath2007: return "Rath2007"; case Method::Rath2003: return "Rath2003"; case Method::Rodriguez2008: return "Rodriguez2008"; case Method::Vinciarelli2004: return "Vinciarelli2004"; case Method::Terasawa2009: return "Terasawa2009"; } cpp_unreachable("Unhandled method"); return "invalid_method"; } <|endoftext|>
<commit_before>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "rhodes/JNIRhodes.h" #include "rhodes/JNIRhoRuby.h" #include <ruby/ext/rho/rhoruby.h> #include <api_generator/js_helpers.h> #include <string> RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_extmanager_RhoExtManagerImpl_nativeRequireRubyFile (JNIEnv * env, jclass, jstring jPath) { std::string path = rho_cast<std::string>(env, jPath); rb_require(path.c_str()); } RHO_GLOBAL jstring JNICALL Java_com_rhomobile_rhodes_extmanager_RhoExtManagerImpl_nativeJSCallEntryPoint (JNIEnv * env, jclass, jstring jQuery) { std::string strQuery = rho_cast<std::string>(env, jQuery); std::string strRes = rho::apiGenerator::js_entry_point(strQuery.c_str()); jhstring jhRes = rho_cast<jstring>(env, strRes); return jhRes.release(); } <commit_msg>fix crash when access to CommonAPI<commit_after>/*------------------------------------------------------------------------ * (The MIT License) * * Copyright (c) 2008-2011 Rhomobile, 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. * * http://rhomobile.com *------------------------------------------------------------------------*/ #include "rhodes/JNIRhodes.h" #include "rhodes/JNIRhoRuby.h" #include <ruby/ext/rho/rhoruby.h> #include <api_generator/js_helpers.h> #include <string> RHO_GLOBAL void JNICALL Java_com_rhomobile_rhodes_extmanager_RhoExtManagerImpl_nativeRequireRubyFile (JNIEnv * env, jclass, jstring jPath) { std::string path = rho_cast<std::string>(env, jPath); rb_require(path.c_str()); } RHO_GLOBAL jstring JNICALL Java_com_rhomobile_rhodes_extmanager_RhoExtManagerImpl_nativeJSCallEntryPoint (JNIEnv * env, jclass, jstring jQuery) { initjnienv(env); std::string strQuery = rho_cast<std::string>(env, jQuery); std::string strRes = rho::apiGenerator::js_entry_point(strQuery.c_str()); jhstring jhRes = rho_cast<jstring>(env, strRes); return jhRes.release(); } <|endoftext|>
<commit_before>#include "IRremote.h" #include "IRremoteInt.h" //+============================================================================= void IRsend::sendRaw (unsigned int buf[], int len, int hz) { // Set IR carrier frequency enableIROut(hz); for (int i = 0; i < len; i++) { if (i & 1) space(buf[i]) ; else mark (buf[i]) ; } space(0); // Always end with the LED off } //+============================================================================= // Sends an IR mark for the specified number of microseconds. // The mark output is modulated at the PWM frequency. // void IRsend::mark (int time) { TIMER_ENABLE_PWM; // Enable pin 3 PWM output if (time > 0) delayMicroseconds(time); } //+============================================================================= // Leave pin off for time (given in microseconds) // Sends an IR space for the specified number of microseconds. // A space is no output, so the PWM output is disabled. // void IRsend::space (int time) { TIMER_DISABLE_PWM; // Disable pin 3 PWM output if (time > 0) delayMicroseconds(time); } //+============================================================================= // Enables IR output. The khz value controls the modulation frequency in kilohertz. // The IR output will be on pin 3 (OC2B). // This routine is designed for 36-40KHz; if you use it for other values, it's up to you // to make sure it gives reasonable results. (Watch out for overflow / underflow / rounding.) // TIMER2 is used in phase-correct PWM mode, with OCR2A controlling the frequency and OCR2B // controlling the duty cycle. // There is no prescaling, so the output frequency is 16MHz / (2 * OCR2A) // To turn the output on and off, we leave the PWM running, but connect and disconnect the output pin. // A few hours staring at the ATmega documentation and this will all make sense. // See my Secrets of Arduino PWM at http://arcfn.com/2009/07/secrets-of-arduino-pwm.html for details. // void IRsend::enableIROut (int khz) { // Disable the Timer2 Interrupt (which is used for receiving IR) TIMER_DISABLE_INTR; //Timer2 Overflow Interrupt pinMode(TIMER_PWM_PIN, OUTPUT); digitalWrite(TIMER_PWM_PIN, LOW); // When not sending PWM, we want it low // COM2A = 00: disconnect OC2A // COM2B = 00: disconnect OC2B; to send signal set to 10: OC2B non-inverted // WGM2 = 101: phase-correct PWM with OCRA as top // CS2 = 000: no prescaling // The top value for the timer. The modulation frequency will be SYSCLOCK / 2 / OCR2A. TIMER_CONFIG_KHZ(khz); } <commit_msg>Working on sendRaw Bug<commit_after>#include "IRremote.h" #include "IRremoteInt.h" //+============================================================================= void IRsend::sendRaw (unsigned int buf[], unsigned char len, unsigned char hz) { // Set IR carrier frequency enableIROut(hz); for (unsigned char i = 0; i < len; i++) { if (i & 1) space(buf[i]) ; else mark (buf[i]) ; } space(0); // Always end with the LED off } //+============================================================================= // Sends an IR mark for the specified number of microseconds. // The mark output is modulated at the PWM frequency. // void IRsend::mark (int time) { TIMER_ENABLE_PWM; // Enable pin 3 PWM output if (time > 0) delayMicroseconds(time); } //+============================================================================= // Leave pin off for time (given in microseconds) // Sends an IR space for the specified number of microseconds. // A space is no output, so the PWM output is disabled. // void IRsend::space (int time) { TIMER_DISABLE_PWM; // Disable pin 3 PWM output if (time > 0) delayMicroseconds(time); } //+============================================================================= // Enables IR output. The khz value controls the modulation frequency in kilohertz. // The IR output will be on pin 3 (OC2B). // This routine is designed for 36-40KHz; if you use it for other values, it's up to you // to make sure it gives reasonable results. (Watch out for overflow / underflow / rounding.) // TIMER2 is used in phase-correct PWM mode, with OCR2A controlling the frequency and OCR2B // controlling the duty cycle. // There is no prescaling, so the output frequency is 16MHz / (2 * OCR2A) // To turn the output on and off, we leave the PWM running, but connect and disconnect the output pin. // A few hours staring at the ATmega documentation and this will all make sense. // See my Secrets of Arduino PWM at http://arcfn.com/2009/07/secrets-of-arduino-pwm.html for details. // void IRsend::enableIROut (int khz) { // Disable the Timer2 Interrupt (which is used for receiving IR) TIMER_DISABLE_INTR; //Timer2 Overflow Interrupt pinMode(TIMER_PWM_PIN, OUTPUT); digitalWrite(TIMER_PWM_PIN, LOW); // When not sending PWM, we want it low // COM2A = 00: disconnect OC2A // COM2B = 00: disconnect OC2B; to send signal set to 10: OC2B non-inverted // WGM2 = 101: phase-correct PWM with OCRA as top // CS2 = 000: no prescaling // The top value for the timer. The modulation frequency will be SYSCLOCK / 2 / OCR2A. TIMER_CONFIG_KHZ(khz); } <|endoftext|>
<commit_before> void Hshuttle(Int_t runTime=1500) {// this macro is to simulate the functionality of SHUTTLE. gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so"); // AliTestShuttle::SetMainCDB(TString("local://$HOME/CDB")); AliTestShuttle::SetMainCDB(TString("local://$HOME")); TMap *pDcsMap = new TMap; pDcsMap->SetOwner(1); //DCS archive map AliTestShuttle* pShuttle = new AliTestShuttle(0,0,1000000); pShuttle->SetInputRunType("PHYSICS"); // pShuttle->SetInputRunType("PEDESTAL_RUN"); SimPed(); for(Int_t ldc=1;ldc<=2;ldc++) pShuttle->AddInputFile(AliTestShuttle::kDAQ,"HMP","pedestals",Form("LDC%i",ldc),Form("HmpidPeds%i.tar",ldc)); SimMap(pDcsMap,runTime); pShuttle->SetDCSInput(pDcsMap); //DCS map AliPreprocessor* pp = new AliHMPIDPreprocessor(pShuttle); pShuttle->Process(); delete pp; //here goes preprocessor DrawInput(pDcsMap); DrawOutput(); gSystem->Exec("rm -rf HmpidPedDdl*.txt"); gSystem->Exec("rm -rf HmpidPeds*.tar"); }//Hshuttle() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimPed() { Int_t iDDLmin=0,iDDLmax=13; Int_t nSigmas = 1; // value stored in the ddl files of pedestals ofstream out; for(Int_t ddl=iDDLmin;ddl<=iDDLmax;ddl++){ out.open(Form("HmpidPedDdl%02i.txt",ddl)); out << nSigmas <<endl; for(Int_t row=1;row<=24;row++) for(Int_t dil=1;dil<=10;dil++) for(Int_t adr=0;adr<=47;adr++){ Float_t mean = 150+200*gRandom->Rndm(); Float_t sigma = 1+0.3*gRandom->Gaus(); Int_t inhard=((Int_t(mean))<<9)+Int_t(mean+nSigmas*sigma); out << Form("%2i %2i %2i %5.2f %5.2f %x\n",row,dil,adr,mean,sigma,inhard); } out.close(); } Printf("HMPID - All %i DDL pedestal files created successfully",iDDLmax-iDDLmin+1); gSystem->Exec("tar cf HmpidPeds1.tar HmpidPedDdl00.txt HmpidPedDdl01.txt HmpidPedDdl02.txt HmpidPedDdl03.txt HmpidPedDdl04.txt HmpidPedDdl05.txt HmpidPedDdl06.txt"); gSystem->Exec("tar cf HmpidPeds2.tar HmpidPedDdl07.txt HmpidPedDdl08.txt HmpidPedDdl09.txt HmpidPedDdl10.txt HmpidPedDdl11.txt HmpidPedDdl12.txt HmpidPedDdl13.txt"); Printf("HMPID - 2 tar files (HmpidPeds1-2) created (size 2273280 bytes)"); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimMap(TMap *pDcsMap,Int_t runTime=1500) { Int_t stepTime=100; //time interval between mesuraments Int_t startTime=0; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop TObjArray *pP=new TObjArray; pP->SetOwner(1); TObjArray *pHV=new TObjArray; pHV->SetOwner(1); TObjArray *pUserCut=new TObjArray; pUserCut->SetOwner(1); TObjArray *pDaqSigCut=new TObjArray; pDaqSigCut->SetOwner(1); for(Int_t time=0;time<runTime;time+=stepTime) { pP->Add(new AliDCSValue((Float_t)1005.0 ,time)); //sample CH4 pressure [mBar] pHV->Add(new AliDCSValue((Float_t)2050.0,time)); //sample chamber HV [V] pUserCut->Add(new AliDCSValue(3,time)); //User Cut in number of sigmas pDaqSigCut->Add(new AliDCSValue(1,time)); //Cut in sigmas applied to electronics } pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_GAS/HMP_MP%i_GAS_PMWC.actual.value" ,iCh,iCh,iCh)),pP); pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_PW/HMP_MP%i_SEC0/HMP_MP%i_SEC0_HV.actual.vMon",iCh,iCh,iCh)),pHV); pDcsMap->Add(new TObjString(Form("HMP_%i.UserCut",iCh)),pUserCut); pDcsMap->Add(new TObjString(Form("HMP_%i.DaqSigCut",iCh)),pDaqSigCut); for(Int_t iRad=0;iRad<3;iRad++){//radiators loop TObjArray *pT1=new TObjArray; pT1->SetOwner(1); TObjArray *pT2=new TObjArray; pT2->SetOwner(1); for (Int_t time=0;time<runTime;time+=stepTime) pT1->Add(new AliDCSValue(13,time)); //sample inlet temperature Nmean=1.292 @ 13 degrees for (Int_t time=0;time<runTime;time+=stepTime) pT2->Add(new AliDCSValue(14,time)); //sample outlet temperature pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iIn_Temp",iCh,iCh,iRad)) ,pT1); pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iOut_Temp",iCh,iCh,iRad)),pT2); }//radiators loop }//chambers loop }//SimMap() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawInput(TMap *pDcsMap) { TCanvas *c=new TCanvas("cc","Input data",600,600); c->Divide(3,3); AliDCSValue *pVal; Int_t cnt; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop if(iCh==6) c->cd(1); if(iCh==5) c->cd(2); if(iCh==4) c->cd(4); if(iCh==3) c->cd(5); if(iCh==2) c->cd(6); if(iCh==1) c->cd(8); if(iCh==0) c->cd(9); TObjArray *pHV=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_PW/HMP_MP%i_SEC0/HMP_MP%i_SEC0_HV.actual.vMon",iCh,iCh,iCh,iCh)); //HV TObjArray *pP =(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_GAS/HMP_MP%i_GAS_PMWC.actual.value",iCh,iCh,iCh)); //P TGraph *pGrHV=new TGraph; pGrHV->SetMarkerStyle(5); TIter nextHV(pHV); TGraph *pGrP =new TGraph; pGrP ->SetMarkerStyle(5); TIter nextP (pP ); for(Int_t iRad=0;iRad<3;iRad++){ TObjArray *pT1=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iIn_Temp",iCh,iCh,iRad)); TIter nextT1(pT1); TObjArray *pT2=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iOut_Temp",iCh,iCh,iRad)); TIter nextT2(pT2); TGraph *pGrT1=new TGraph; pGrT1->SetMarkerStyle(5); TGraph *pGrT2=new TGraph; pGrT2->SetMarkerStyle(5); cnt=0; while((pVal=(AliDCSValue*)nextT1())) pGrT1->SetPoint(cnt++,pVal->GetTimeStamp(),pVal->GetFloat()); cnt=0; while((pVal=(AliDCSValue*)nextT2())) pGrT2->SetPoint(cnt++,pVal->GetTimeStamp(),pVal->GetFloat()); pGrT1->Draw("AP"); pGrT2->Draw("same"); }//radiators loop }//chambers loop }//DrawInput() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawOutput() { // AliCDBManager::Instance()->SetDefaultStorage("local://$HOME/CDB"); AliCDBManager::Instance()->SetRun(0); AliCDBManager::Instance()->SetDefaultStorage("local://$HOME"); AliCDBManager::Instance()->SetRun(0); AliCDBEntry *pQthreEnt =AliCDBManager::Instance()->Get("HMPID/Calib/Qthre"); AliCDBEntry *pNmeanEnt =AliCDBManager::Instance()->Get("HMPID/Calib/Nmean"); AliCDBEntry *pDaqSigEnt=AliCDBManager::Instance()->Get("HMPID/Calib/DaqSig"); if(!pQthreEnt || !pNmeanEnt || !pDaqSigEnt) return; TObjArray *pNmean =(TObjArray*)pNmeanEnt ->GetObject(); TObjArray *pQthre =(TObjArray*)pQthreEnt ->GetObject(); TObjArray *pDaqSig=(TObjArray*)pDaqSigEnt->GetObject(); TF1 *pRad0,*pRad1,*pRad2; TCanvas *c2=new TCanvas("c2","Output"); c2->Divide(3,3); TH1F *pSig[7]; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop TMatrix *pM=(TMatrix*)pDaqSig->At(iCh); pSig[iCh]=new TH1F(Form("sig%i",iCh),"Sigma;[QDC]",100,-5,20); //pSig[iCh]->SetLineColor(iCh+kRed); for(Int_t padx=0;padx<160;padx++) for(Int_t pady=0;pady<144;pady++) pSig[iCh]->Fill((*pM)(padx,pady)); c2->cd(7); if(iCh==0) pSig[iCh]->Draw(); else pSig[iCh]->Draw("same"); if(iCh==6) c2->cd(1); if(iCh==5) c2->cd(2); if(iCh==4) c2->cd(4); if(iCh==3) c2->cd(5); if(iCh==2) c2->cd(6); if(iCh==1) c2->cd(8); if(iCh==0) c2->cd(9); TF1 *pRad0=(TF1*)pNmean->At(iCh*3+0); pRad0->Draw(); pRad0->GetXaxis()->SetTimeDisplay(kTRUE); pRad0->GetYaxis()->SetRangeUser(1.28,1.3); TF1 *pRad1=(TF1*)pNmean->At(iCh*3+1); pRad1->Draw("same"); TF1 *pRad2=(TF1*)pNmean->At(iCh*3+2); pRad2->Draw("same"); }//chambers loop }//DrawOutput() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <commit_msg>Sigmas set to 3.<commit_after> void Hshuttle(Int_t runTime=1500) {// this macro is to simulate the functionality of SHUTTLE. gSystem->Load("$ALICE_ROOT/SHUTTLE/TestShuttle/libTestShuttle.so"); // AliTestShuttle::SetMainCDB(TString("local://$HOME/CDB")); AliTestShuttle::SetMainCDB(TString("local://$HOME")); TMap *pDcsMap = new TMap; pDcsMap->SetOwner(1); //DCS archive map AliTestShuttle* pShuttle = new AliTestShuttle(0,0,1000000); pShuttle->SetInputRunType("PHYSICS"); // pShuttle->SetInputRunType("PEDESTAL_RUN"); SimPed(); for(Int_t ldc=1;ldc<=2;ldc++) pShuttle->AddInputFile(AliTestShuttle::kDAQ,"HMP","pedestals",Form("LDC%i",ldc),Form("HmpidPeds%i.tar",ldc)); SimMap(pDcsMap,runTime); pShuttle->SetDCSInput(pDcsMap); //DCS map AliPreprocessor* pp = new AliHMPIDPreprocessor(pShuttle); pShuttle->Process(); delete pp; //here goes preprocessor DrawInput(pDcsMap); DrawOutput(); gSystem->Exec("rm -rf HmpidPedDdl*.txt"); gSystem->Exec("rm -rf HmpidPeds*.tar"); }//Hshuttle() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimPed() { Int_t iDDLmin=0,iDDLmax=13; Int_t nSigmas = 3; // value stored in the ddl files of pedestals ofstream out; for(Int_t ddl=iDDLmin;ddl<=iDDLmax;ddl++){ out.open(Form("HmpidPedDdl%02i.txt",ddl)); out << nSigmas <<endl; for(Int_t row=1;row<=24;row++) for(Int_t dil=1;dil<=10;dil++) for(Int_t adr=0;adr<=47;adr++){ Float_t mean = 150+200*gRandom->Rndm(); Float_t sigma = 1+0.3*gRandom->Gaus(); Int_t inhard=((Int_t(mean))<<9)+Int_t(mean+nSigmas*sigma); out << Form("%2i %2i %2i %5.2f %5.2f %x\n",row,dil,adr,mean,sigma,inhard); } out.close(); } Printf("HMPID - All %i DDL pedestal files created successfully",iDDLmax-iDDLmin+1); gSystem->Exec("tar cf HmpidPeds1.tar HmpidPedDdl00.txt HmpidPedDdl01.txt HmpidPedDdl02.txt HmpidPedDdl03.txt HmpidPedDdl04.txt HmpidPedDdl05.txt HmpidPedDdl06.txt"); gSystem->Exec("tar cf HmpidPeds2.tar HmpidPedDdl07.txt HmpidPedDdl08.txt HmpidPedDdl09.txt HmpidPedDdl10.txt HmpidPedDdl11.txt HmpidPedDdl12.txt HmpidPedDdl13.txt"); Printf("HMPID - 2 tar files (HmpidPeds1-2) created (size 2273280 bytes)"); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void SimMap(TMap *pDcsMap,Int_t runTime=1500) { Int_t stepTime=100; //time interval between mesuraments Int_t startTime=0; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop TObjArray *pP=new TObjArray; pP->SetOwner(1); TObjArray *pHV=new TObjArray; pHV->SetOwner(1); TObjArray *pUserCut=new TObjArray; pUserCut->SetOwner(1); TObjArray *pDaqSigCut=new TObjArray; pDaqSigCut->SetOwner(1); for(Int_t time=0;time<runTime;time+=stepTime) { pP->Add(new AliDCSValue((Float_t)1005.0 ,time)); //sample CH4 pressure [mBar] pHV->Add(new AliDCSValue((Float_t)2050.0,time)); //sample chamber HV [V] pUserCut->Add(new AliDCSValue(3,time)); //User Cut in number of sigmas pDaqSigCut->Add(new AliDCSValue(1,time)); //Cut in sigmas applied to electronics } pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_GAS/HMP_MP%i_GAS_PMWC.actual.value" ,iCh,iCh,iCh)),pP); pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_PW/HMP_MP%i_SEC0/HMP_MP%i_SEC0_HV.actual.vMon",iCh,iCh,iCh)),pHV); pDcsMap->Add(new TObjString(Form("HMP_%i.UserCut",iCh)),pUserCut); pDcsMap->Add(new TObjString(Form("HMP_%i.DaqSigCut",iCh)),pDaqSigCut); for(Int_t iRad=0;iRad<3;iRad++){//radiators loop TObjArray *pT1=new TObjArray; pT1->SetOwner(1); TObjArray *pT2=new TObjArray; pT2->SetOwner(1); for (Int_t time=0;time<runTime;time+=stepTime) pT1->Add(new AliDCSValue(13,time)); //sample inlet temperature Nmean=1.292 @ 13 degrees for (Int_t time=0;time<runTime;time+=stepTime) pT2->Add(new AliDCSValue(14,time)); //sample outlet temperature pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iIn_Temp",iCh,iCh,iRad)) ,pT1); pDcsMap->Add(new TObjString(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iOut_Temp",iCh,iCh,iRad)),pT2); }//radiators loop }//chambers loop }//SimMap() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawInput(TMap *pDcsMap) { TCanvas *c=new TCanvas("cc","Input data",600,600); c->Divide(3,3); AliDCSValue *pVal; Int_t cnt; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop if(iCh==6) c->cd(1); if(iCh==5) c->cd(2); if(iCh==4) c->cd(4); if(iCh==3) c->cd(5); if(iCh==2) c->cd(6); if(iCh==1) c->cd(8); if(iCh==0) c->cd(9); TObjArray *pHV=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_PW/HMP_MP%i_SEC0/HMP_MP%i_SEC0_HV.actual.vMon",iCh,iCh,iCh,iCh)); //HV TObjArray *pP =(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_GAS/HMP_MP%i_GAS_PMWC.actual.value",iCh,iCh,iCh)); //P TGraph *pGrHV=new TGraph; pGrHV->SetMarkerStyle(5); TIter nextHV(pHV); TGraph *pGrP =new TGraph; pGrP ->SetMarkerStyle(5); TIter nextP (pP ); for(Int_t iRad=0;iRad<3;iRad++){ TObjArray *pT1=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iIn_Temp",iCh,iCh,iRad)); TIter nextT1(pT1); TObjArray *pT2=(TObjArray*)pDcsMap->GetValue(Form("HMP_DET/HMP_MP%i/HMP_MP%i_LIQ_LOOP.actual.sensors.Rad%iOut_Temp",iCh,iCh,iRad)); TIter nextT2(pT2); TGraph *pGrT1=new TGraph; pGrT1->SetMarkerStyle(5); TGraph *pGrT2=new TGraph; pGrT2->SetMarkerStyle(5); cnt=0; while((pVal=(AliDCSValue*)nextT1())) pGrT1->SetPoint(cnt++,pVal->GetTimeStamp(),pVal->GetFloat()); cnt=0; while((pVal=(AliDCSValue*)nextT2())) pGrT2->SetPoint(cnt++,pVal->GetTimeStamp(),pVal->GetFloat()); pGrT1->Draw("AP"); pGrT2->Draw("same"); }//radiators loop }//chambers loop }//DrawInput() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ void DrawOutput() { // AliCDBManager::Instance()->SetDefaultStorage("local://$HOME/CDB"); AliCDBManager::Instance()->SetRun(0); AliCDBManager::Instance()->SetDefaultStorage("local://$HOME"); AliCDBManager::Instance()->SetRun(0); AliCDBEntry *pQthreEnt =AliCDBManager::Instance()->Get("HMPID/Calib/Qthre"); AliCDBEntry *pNmeanEnt =AliCDBManager::Instance()->Get("HMPID/Calib/Nmean"); AliCDBEntry *pDaqSigEnt=AliCDBManager::Instance()->Get("HMPID/Calib/DaqSig"); if(!pQthreEnt || !pNmeanEnt || !pDaqSigEnt) return; TObjArray *pNmean =(TObjArray*)pNmeanEnt ->GetObject(); TObjArray *pQthre =(TObjArray*)pQthreEnt ->GetObject(); TObjArray *pDaqSig=(TObjArray*)pDaqSigEnt->GetObject(); TF1 *pRad0,*pRad1,*pRad2; TCanvas *c2=new TCanvas("c2","Output"); c2->Divide(3,3); TH1F *pSig[7]; for(Int_t iCh=0;iCh<7;iCh++){//chambers loop TMatrix *pM=(TMatrix*)pDaqSig->At(iCh); pSig[iCh]=new TH1F(Form("sig%i",iCh),"Sigma;[QDC]",100,-5,20); //pSig[iCh]->SetLineColor(iCh+kRed); for(Int_t padx=0;padx<160;padx++) for(Int_t pady=0;pady<144;pady++) pSig[iCh]->Fill((*pM)(padx,pady)); c2->cd(7); if(iCh==0) pSig[iCh]->Draw(); else pSig[iCh]->Draw("same"); if(iCh==6) c2->cd(1); if(iCh==5) c2->cd(2); if(iCh==4) c2->cd(4); if(iCh==3) c2->cd(5); if(iCh==2) c2->cd(6); if(iCh==1) c2->cd(8); if(iCh==0) c2->cd(9); TF1 *pRad0=(TF1*)pNmean->At(iCh*3+0); pRad0->Draw(); pRad0->GetXaxis()->SetTimeDisplay(kTRUE); pRad0->GetYaxis()->SetRangeUser(1.28,1.3); TF1 *pRad1=(TF1*)pNmean->At(iCh*3+1); pRad1->Draw("same"); TF1 *pRad2=(TF1*)pNmean->At(iCh*3+2); pRad2->Draw("same"); }//chambers loop }//DrawOutput() //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <|endoftext|>
<commit_before>/****************************************************************************** Configuration file for nomlib library Copyright (c) 2013 Jeffrey Carpenter ******************************************************************************/ #ifndef NOMLIB_CONFIG_HEADERS #define NOMLIB_CONFIG_HEADERS #include <iostream> #include <cassert> // nomlib version #include "version.hpp" #include "types.hpp" #include "sys/Logger.hpp" // Identification the operating system #if defined ( _WIN32) || defined ( __WIN32__ ) #define NOMLIB_SYSTEM_WINDOWS #elif defined ( linux ) || defined ( __linux ) #define NOMLIB_SYSTEM_LINUX #elif defined ( __APPLE__ ) || defined ( MACOSX ) || defined ( macintosh ) || defined ( Macintosh ) #define NOMLIB_SYSTEM_OSX #else #warning This operating system is not officially supported by nomlib #endif // Function names and preferably also its type signature #if defined ( _MSC_VER ) // MSVC++ // TODO: Presumably the same as GNU's __PRETTY_FUNCTION__ ? // // SOURCE: http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx #define __func__ __FUNCSIG__ #else // We assume GNU v2+ // The type signature is nice because this shows if the function calling type // is a virtual or not and even what arguments the function has #define __func__ __PRETTY_FUNCTION__ #endif // nomlib debugging // Standard debug level; logging of info, warnings & errors #define NOMLIB_DEBUG // Internal development; logging of class object construction and destruction #define NOMLIB_DEBUG_ALL // Pretty print C macros #ifdef NOMLIB_DEBUG // If debugging is turned on, we log all warnings, errors & info #define NOMLIB_LOG(message) \ ( nom::Logger::info ( message ) ) #define NOMLIB_LOG_ERR(message) \ ( nom::Logger::err ( __FILE__, __LINE__, message ) ) #define NOMLIB_ASSERT(expression) \ ( assert (expression) ) #else // We do not add any overhead #define NOMLIB_LOG(message) #define NOMLIB_LOG_ERR(message) #define NOMLIB_ASSERT(expression) #endif #ifdef NOMLIB_DEBUG_ALL // If all debugging is turned on, we show class construction and destruction #define NOMLIB_LOG_INFO \ ( nom::Logger::info ( __func__ ) ) #else // We do not add any overhead #define NOMLIB_LOG_INFO #endif #endif // NOMLIB_CONFIG_HEADERS defined <commit_msg>Introduce NOMLIB_DUMP_VAR macro<commit_after>/****************************************************************************** Configuration file for nomlib library Copyright (c) 2013 Jeffrey Carpenter ******************************************************************************/ #ifndef NOMLIB_CONFIG_HEADERS #define NOMLIB_CONFIG_HEADERS #include <iostream> #include <cassert> // nomlib version #include "version.hpp" #include "types.hpp" #include "sys/Logger.hpp" // Identification the operating system #if defined ( _WIN32) || defined ( __WIN32__ ) #define NOMLIB_SYSTEM_WINDOWS #elif defined ( linux ) || defined ( __linux ) #define NOMLIB_SYSTEM_LINUX #elif defined ( __APPLE__ ) || defined ( MACOSX ) || defined ( macintosh ) || defined ( Macintosh ) #define NOMLIB_SYSTEM_OSX #else #warning This operating system is not officially supported by nomlib #endif // Function names and preferably also its type signature #if defined ( _MSC_VER ) // MSVC++ // TODO: Presumably the same as GNU's __PRETTY_FUNCTION__ ? // // SOURCE: http://msdn.microsoft.com/en-us/library/b0084kay(v=vs.80).aspx #define __func__ __FUNCSIG__ #else // We assume GNU v2+ // The type signature is nice because this shows if the function calling type // is a virtual or not and even what arguments the function has #define __func__ __PRETTY_FUNCTION__ #endif // nomlib debugging // Standard debug level; logging of info, warnings & errors #define NOMLIB_DEBUG // Internal development; logging of class object construction and destruction #define NOMLIB_DEBUG_ALL // Pretty print C macros #ifdef NOMLIB_DEBUG // If debugging is turned on, we log all warnings, errors & info #define NOMLIB_LOG(message) \ ( nom::Logger::info ( message ) ) #define NOMLIB_LOG_ERR(message) \ ( nom::Logger::err ( __FILE__, __LINE__, message ) ) #define NOMLIB_ASSERT(expression) \ ( assert (expression) ) #else // We do not add any overhead #define NOMLIB_LOG(message) #define NOMLIB_LOG_ERR(message) #define NOMLIB_ASSERT(expression) #endif #ifdef NOMLIB_DEBUG_ALL // If all debugging is turned on, we show class construction and destruction #define NOMLIB_LOG_INFO \ ( nom::Logger::info ( __func__ ) ) #else // We do not add any overhead #define NOMLIB_LOG_INFO #endif #define NOMLIB_DUMP_VAR(var) \ ( std::cout << std::endl << #var << ": " << var << std::endl << std::endl ) #endif // NOMLIB_CONFIG_HEADERS defined <|endoftext|>
<commit_before>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/LU> using namespace std; template<typename MatrixType> void lu_non_invertible() { typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; /* this test covers the following files: LU.h */ int rows, cols, cols2; if(MatrixType::RowsAtCompileTime==Dynamic) { rows = ei_random<int>(2,200); } else { rows = MatrixType::RowsAtCompileTime; } if(MatrixType::ColsAtCompileTime==Dynamic) { cols = ei_random<int>(2,200); cols2 = ei_random<int>(2,200); } else { cols2 = cols = MatrixType::ColsAtCompileTime; } enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime }; typedef typename ei_kernel_retval_base<FullPivLU<MatrixType> >::ReturnType KernelMatrixType; typedef typename ei_image_retval_base<FullPivLU<MatrixType> >::ReturnType ImageMatrixType; typedef Matrix<typename MatrixType::Scalar, ColsAtCompileTime, ColsAtCompileTime> CMatrixType; typedef Matrix<typename MatrixType::Scalar, RowsAtCompileTime, RowsAtCompileTime> RMatrixType; int rank = ei_random<int>(1, std::min(rows, cols)-1); // The image of the zero matrix should consist of a single (zero) column vector VERIFY((MatrixType::Zero(rows,cols).fullPivLu().image(MatrixType::Zero(rows,cols)).cols() == 1)); MatrixType m1(rows, cols), m3(rows, cols2); CMatrixType m2(cols, cols2); createRandomPIMatrixOfRank(rank, rows, cols, m1); FullPivLU<MatrixType> lu; // The special value 0.01 below works well in tests. Keep in mind that we're only computing the rank // of singular values are either 0 or 1. // So it's not clear at all that the epsilon should play any role there. lu.setThreshold(RealScalar(0.01)); lu.compute(m1); MatrixType u(rows,cols); u = lu.matrixLU().template triangularView<Upper>(); RMatrixType l = RMatrixType::Identity(rows,rows); l.block(0,0,rows,std::min(rows,cols)).template triangularView<StrictlyLower>() = lu.matrixLU().block(0,0,rows,std::min(rows,cols)); VERIFY_IS_APPROX(lu.permutationP() * m1 * lu.permutationQ(), l*u); KernelMatrixType m1kernel = lu.kernel(); ImageMatrixType m1image = lu.image(m1); VERIFY_IS_APPROX(m1, lu.reconstructedMatrix()); VERIFY(rank == lu.rank()); VERIFY(cols - lu.rank() == lu.dimensionOfKernel()); VERIFY(!lu.isInjective()); VERIFY(!lu.isInvertible()); VERIFY(!lu.isSurjective()); VERIFY((m1 * m1kernel).isMuchSmallerThan(m1)); VERIFY(m1image.fullPivLu().rank() == rank); VERIFY_IS_APPROX(m1 * m1.adjoint() * m1image, m1image); m2 = CMatrixType::Random(cols,cols2); m3 = m1*m2; m2 = CMatrixType::Random(cols,cols2); // test that the code, which does resize(), may be applied to an xpr m2.block(0,0,m2.rows(),m2.cols()) = lu.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); } template<typename MatrixType> void lu_invertible() { /* this test covers the following files: LU.h */ typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; int size = ei_random<int>(1,200); MatrixType m1(size, size), m2(size, size), m3(size, size); FullPivLU<MatrixType> lu; lu.setThreshold(0.01); do { m1 = MatrixType::Random(size,size); lu.compute(m1); } while(!lu.isInvertible()); VERIFY_IS_APPROX(m1, lu.reconstructedMatrix()); VERIFY(0 == lu.dimensionOfKernel()); VERIFY(lu.kernel().cols() == 1); // the kernel() should consist of a single (zero) column vector VERIFY(size == lu.rank()); VERIFY(lu.isInjective()); VERIFY(lu.isSurjective()); VERIFY(lu.isInvertible()); VERIFY(lu.image(m1).fullPivLu().isInvertible()); m3 = MatrixType::Random(size,size); m2 = lu.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); VERIFY_IS_APPROX(m2, lu.inverse()*m3); } template<typename MatrixType> void lu_partial_piv() { /* this test covers the following files: PartialPivLU.h */ typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; int rows = ei_random<int>(1,4); int cols = rows; MatrixType m1(cols, rows); m1.setRandom(); PartialPivLU<MatrixType> plu(m1); VERIFY_IS_APPROX(m1, plu.reconstructedMatrix()); } template<typename MatrixType> void lu_verify_assert() { MatrixType tmp; FullPivLU<MatrixType> lu; VERIFY_RAISES_ASSERT(lu.matrixLU()) VERIFY_RAISES_ASSERT(lu.permutationP()) VERIFY_RAISES_ASSERT(lu.permutationQ()) VERIFY_RAISES_ASSERT(lu.kernel()) VERIFY_RAISES_ASSERT(lu.image(tmp)) VERIFY_RAISES_ASSERT(lu.solve(tmp)) VERIFY_RAISES_ASSERT(lu.determinant()) VERIFY_RAISES_ASSERT(lu.rank()) VERIFY_RAISES_ASSERT(lu.dimensionOfKernel()) VERIFY_RAISES_ASSERT(lu.isInjective()) VERIFY_RAISES_ASSERT(lu.isSurjective()) VERIFY_RAISES_ASSERT(lu.isInvertible()) VERIFY_RAISES_ASSERT(lu.inverse()) PartialPivLU<MatrixType> plu; VERIFY_RAISES_ASSERT(plu.matrixLU()) VERIFY_RAISES_ASSERT(plu.permutationP()) VERIFY_RAISES_ASSERT(plu.solve(tmp)) VERIFY_RAISES_ASSERT(plu.determinant()) VERIFY_RAISES_ASSERT(plu.inverse()) } void test_lu() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( lu_non_invertible<Matrix3f>() ); CALL_SUBTEST_1( lu_verify_assert<Matrix3f>() ); CALL_SUBTEST_2( (lu_non_invertible<Matrix<double, 4, 6> >()) ); CALL_SUBTEST_2( (lu_verify_assert<Matrix<double, 4, 6> >()) ); CALL_SUBTEST_3( lu_non_invertible<MatrixXf>() ); CALL_SUBTEST_3( lu_invertible<MatrixXf>() ); CALL_SUBTEST_3( lu_verify_assert<MatrixXf>() ); CALL_SUBTEST_4( lu_non_invertible<MatrixXd>() ); CALL_SUBTEST_4( lu_invertible<MatrixXd>() ); CALL_SUBTEST_4( lu_partial_piv<MatrixXd>() ); CALL_SUBTEST_4( lu_verify_assert<MatrixXd>() ); CALL_SUBTEST_5( lu_non_invertible<MatrixXcf>() ); CALL_SUBTEST_5( lu_invertible<MatrixXcf>() ); CALL_SUBTEST_5( lu_verify_assert<MatrixXcf>() ); CALL_SUBTEST_6( lu_non_invertible<MatrixXcd>() ); CALL_SUBTEST_6( lu_invertible<MatrixXcd>() ); CALL_SUBTEST_6( lu_partial_piv<MatrixXcd>() ); CALL_SUBTEST_6( lu_verify_assert<MatrixXcd>() ); CALL_SUBTEST_7(( lu_non_invertible<Matrix<float,Dynamic,16> >() )); // Test problem size constructors CALL_SUBTEST_9( PartialPivLU<MatrixXf>(10) ); CALL_SUBTEST_9( FullPivLU<MatrixXf>(10, 20); ); } } <commit_msg>Fighting for a green dashboard! Next warning's gone.<commit_after>// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2009 Benoit Jacob <jacob.benoit.1@gmail.com> // // Eigen 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 3 of the License, or (at your option) any later version. // // Alternatively, you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of // the License, or (at your option) any later version. // // Eigen 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 or the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License and a copy of the GNU General Public License along with // Eigen. If not, see <http://www.gnu.org/licenses/>. #include "main.h" #include <Eigen/LU> using namespace std; template<typename MatrixType> void lu_non_invertible() { typedef typename MatrixType::Scalar Scalar; typedef typename MatrixType::RealScalar RealScalar; /* this test covers the following files: LU.h */ int rows, cols, cols2; if(MatrixType::RowsAtCompileTime==Dynamic) { rows = ei_random<int>(2,200); } else { rows = MatrixType::RowsAtCompileTime; } if(MatrixType::ColsAtCompileTime==Dynamic) { cols = ei_random<int>(2,200); cols2 = ei_random<int>(2,200); } else { cols2 = cols = MatrixType::ColsAtCompileTime; } enum { RowsAtCompileTime = MatrixType::RowsAtCompileTime, ColsAtCompileTime = MatrixType::ColsAtCompileTime }; typedef typename ei_kernel_retval_base<FullPivLU<MatrixType> >::ReturnType KernelMatrixType; typedef typename ei_image_retval_base<FullPivLU<MatrixType> >::ReturnType ImageMatrixType; typedef Matrix<typename MatrixType::Scalar, ColsAtCompileTime, ColsAtCompileTime> CMatrixType; typedef Matrix<typename MatrixType::Scalar, RowsAtCompileTime, RowsAtCompileTime> RMatrixType; int rank = ei_random<int>(1, std::min(rows, cols)-1); // The image of the zero matrix should consist of a single (zero) column vector VERIFY((MatrixType::Zero(rows,cols).fullPivLu().image(MatrixType::Zero(rows,cols)).cols() == 1)); MatrixType m1(rows, cols), m3(rows, cols2); CMatrixType m2(cols, cols2); createRandomPIMatrixOfRank(rank, rows, cols, m1); FullPivLU<MatrixType> lu; // The special value 0.01 below works well in tests. Keep in mind that we're only computing the rank // of singular values are either 0 or 1. // So it's not clear at all that the epsilon should play any role there. lu.setThreshold(RealScalar(0.01)); lu.compute(m1); MatrixType u(rows,cols); u = lu.matrixLU().template triangularView<Upper>(); RMatrixType l = RMatrixType::Identity(rows,rows); l.block(0,0,rows,std::min(rows,cols)).template triangularView<StrictlyLower>() = lu.matrixLU().block(0,0,rows,std::min(rows,cols)); VERIFY_IS_APPROX(lu.permutationP() * m1 * lu.permutationQ(), l*u); KernelMatrixType m1kernel = lu.kernel(); ImageMatrixType m1image = lu.image(m1); VERIFY_IS_APPROX(m1, lu.reconstructedMatrix()); VERIFY(rank == lu.rank()); VERIFY(cols - lu.rank() == lu.dimensionOfKernel()); VERIFY(!lu.isInjective()); VERIFY(!lu.isInvertible()); VERIFY(!lu.isSurjective()); VERIFY((m1 * m1kernel).isMuchSmallerThan(m1)); VERIFY(m1image.fullPivLu().rank() == rank); VERIFY_IS_APPROX(m1 * m1.adjoint() * m1image, m1image); m2 = CMatrixType::Random(cols,cols2); m3 = m1*m2; m2 = CMatrixType::Random(cols,cols2); // test that the code, which does resize(), may be applied to an xpr m2.block(0,0,m2.rows(),m2.cols()) = lu.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); } template<typename MatrixType> void lu_invertible() { /* this test covers the following files: LU.h */ typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; int size = ei_random<int>(1,200); MatrixType m1(size, size), m2(size, size), m3(size, size); FullPivLU<MatrixType> lu; lu.setThreshold(RealScalar(0.01)); do { m1 = MatrixType::Random(size,size); lu.compute(m1); } while(!lu.isInvertible()); VERIFY_IS_APPROX(m1, lu.reconstructedMatrix()); VERIFY(0 == lu.dimensionOfKernel()); VERIFY(lu.kernel().cols() == 1); // the kernel() should consist of a single (zero) column vector VERIFY(size == lu.rank()); VERIFY(lu.isInjective()); VERIFY(lu.isSurjective()); VERIFY(lu.isInvertible()); VERIFY(lu.image(m1).fullPivLu().isInvertible()); m3 = MatrixType::Random(size,size); m2 = lu.solve(m3); VERIFY_IS_APPROX(m3, m1*m2); VERIFY_IS_APPROX(m2, lu.inverse()*m3); } template<typename MatrixType> void lu_partial_piv() { /* this test covers the following files: PartialPivLU.h */ typedef typename MatrixType::Scalar Scalar; typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar; int rows = ei_random<int>(1,4); int cols = rows; MatrixType m1(cols, rows); m1.setRandom(); PartialPivLU<MatrixType> plu(m1); VERIFY_IS_APPROX(m1, plu.reconstructedMatrix()); } template<typename MatrixType> void lu_verify_assert() { MatrixType tmp; FullPivLU<MatrixType> lu; VERIFY_RAISES_ASSERT(lu.matrixLU()) VERIFY_RAISES_ASSERT(lu.permutationP()) VERIFY_RAISES_ASSERT(lu.permutationQ()) VERIFY_RAISES_ASSERT(lu.kernel()) VERIFY_RAISES_ASSERT(lu.image(tmp)) VERIFY_RAISES_ASSERT(lu.solve(tmp)) VERIFY_RAISES_ASSERT(lu.determinant()) VERIFY_RAISES_ASSERT(lu.rank()) VERIFY_RAISES_ASSERT(lu.dimensionOfKernel()) VERIFY_RAISES_ASSERT(lu.isInjective()) VERIFY_RAISES_ASSERT(lu.isSurjective()) VERIFY_RAISES_ASSERT(lu.isInvertible()) VERIFY_RAISES_ASSERT(lu.inverse()) PartialPivLU<MatrixType> plu; VERIFY_RAISES_ASSERT(plu.matrixLU()) VERIFY_RAISES_ASSERT(plu.permutationP()) VERIFY_RAISES_ASSERT(plu.solve(tmp)) VERIFY_RAISES_ASSERT(plu.determinant()) VERIFY_RAISES_ASSERT(plu.inverse()) } void test_lu() { for(int i = 0; i < g_repeat; i++) { CALL_SUBTEST_1( lu_non_invertible<Matrix3f>() ); CALL_SUBTEST_1( lu_verify_assert<Matrix3f>() ); CALL_SUBTEST_2( (lu_non_invertible<Matrix<double, 4, 6> >()) ); CALL_SUBTEST_2( (lu_verify_assert<Matrix<double, 4, 6> >()) ); CALL_SUBTEST_3( lu_non_invertible<MatrixXf>() ); CALL_SUBTEST_3( lu_invertible<MatrixXf>() ); CALL_SUBTEST_3( lu_verify_assert<MatrixXf>() ); CALL_SUBTEST_4( lu_non_invertible<MatrixXd>() ); CALL_SUBTEST_4( lu_invertible<MatrixXd>() ); CALL_SUBTEST_4( lu_partial_piv<MatrixXd>() ); CALL_SUBTEST_4( lu_verify_assert<MatrixXd>() ); CALL_SUBTEST_5( lu_non_invertible<MatrixXcf>() ); CALL_SUBTEST_5( lu_invertible<MatrixXcf>() ); CALL_SUBTEST_5( lu_verify_assert<MatrixXcf>() ); CALL_SUBTEST_6( lu_non_invertible<MatrixXcd>() ); CALL_SUBTEST_6( lu_invertible<MatrixXcd>() ); CALL_SUBTEST_6( lu_partial_piv<MatrixXcd>() ); CALL_SUBTEST_6( lu_verify_assert<MatrixXcd>() ); CALL_SUBTEST_7(( lu_non_invertible<Matrix<float,Dynamic,16> >() )); // Test problem size constructors CALL_SUBTEST_9( PartialPivLU<MatrixXf>(10) ); CALL_SUBTEST_9( FullPivLU<MatrixXf>(10, 20); ); } } <|endoftext|>